_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
cbd7faca003b94a041d38c04e31deeda585e2172994450ad0eb7f7d2997923bf
ollef/sixten
PreName.hs
module Syntax.PreName where import Protolude import Data.String import Data.Text(Text) import Pretty import SourceLoc import Util -- | An unresolved name data PreName = PreName { preNameSourceLoc :: Maybe SourceLoc , preNameText :: !Text } deriving Show instance Eq PreName where PreName _ t1 == PreName _ t2 = t1 == t2 instance Ord PreName where compare (PreName _ t1) (PreName _ t2) = compare t1 t2 instance Hashable PreName where hashWithSalt s (PreName _ t) = hashWithSalt s t instance IsString PreName where fromString = PreName Nothing . fromString instance Semigroup PreName where PreName loc1 t1 <> PreName loc2 t2 = PreName (loc1 <|> loc2) (t1 <> t2) instance Monoid PreName where mempty = PreName Nothing mempty mappend = (<>) fromPreName :: IsString a => PreName -> a fromPreName (PreName _ t) = fromText t instance Pretty PreName where pretty (PreName _ n) = pretty n
null
https://raw.githubusercontent.com/ollef/sixten/60d46eee20abd62599badea85774a9365c81af45/src/Syntax/PreName.hs
haskell
| An unresolved name
module Syntax.PreName where import Protolude import Data.String import Data.Text(Text) import Pretty import SourceLoc import Util data PreName = PreName { preNameSourceLoc :: Maybe SourceLoc , preNameText :: !Text } deriving Show instance Eq PreName where PreName _ t1 == PreName _ t2 = t1 == t2 instance Ord PreName where compare (PreName _ t1) (PreName _ t2) = compare t1 t2 instance Hashable PreName where hashWithSalt s (PreName _ t) = hashWithSalt s t instance IsString PreName where fromString = PreName Nothing . fromString instance Semigroup PreName where PreName loc1 t1 <> PreName loc2 t2 = PreName (loc1 <|> loc2) (t1 <> t2) instance Monoid PreName where mempty = PreName Nothing mempty mappend = (<>) fromPreName :: IsString a => PreName -> a fromPreName (PreName _ t) = fromText t instance Pretty PreName where pretty (PreName _ n) = pretty n
26502c3ffb78e9ac4b4b36351e01d18ed685ba798159a560ba440de7154bb1f2
maxhbr/LDBcollector
FOSSLight.hs
# LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # module Collectors.FOSSLight ( loadFOSSLightFacts , fossLightLFC ) where import qualified Prelude as P import MyPrelude import Collectors.Common import qualified Data.Text as T import qualified Data.Text.Encoding.Error as T import qualified Data.Vector as V import qualified Data.ByteString.Lazy as B import qualified Data.Map as Map import Control.Applicative import Control.Exception (handle) import Data.Csv as C import Data.Aeson as A import Data.FileEmbed (embedFile) import qualified Database.SQLite.Simple as S import qualified Database.SQLite.Simple.FromRow as S import qualified Database.SQLite.Simple.FromField as S import qualified Database.SQLite.Simple.Types as S import qualified Database.SQLite.Simple.Internal as S import qualified Database.SQLite.Simple.Ok as S import qualified System.IO as IO import qualified System.IO.Temp as IO import Model.License -- CREATE TABLE `LICENSE_NICKNAME` ( -- `LICENSE_NAME` varchar(200) NOT NULL COMMENT '라이선스 NAME', -- `LICENSE_NICKNAME` varchar(200) NOT NULL COMMENT '라이선스 닉네임', -- PRIMARY KEY (`LICENSE_NAME`,`LICENSE_NICKNAME`) -- ) ENGINE=InnoDB DEFAULT CHARSET=utf8; data FOSSLight_Nick = FOSSLight_Nick LicenseName LicenseName deriving (Show) instance S.FromRow FOSSLight_Nick where fromRow = FOSSLight_Nick <$> S.field <*> S.field ( ' 201 ' , ' CP ' , ' ' , '' , '' , 3 , ' Y ' ) , ( ' 201 ' , ' NA ' , ' Proprietary ' , '' , '' , 4 , ' Y ' ) , ( ' 201 ' , ' PF ' , ' Proprietary Free ' , '' , '' , 5 , ' Y ' ) , ( ' 201 ' , ' PMS ' , ' Permissive ' , '' , '' , 1 , ' Y ' ) , ( ' 201 ' , ' ' , ' Weak ' , '' , '' , 2 , ' Y ' ) , data FOSSLight_License_Type = FOSSLight_License_Type_Copyleft | FOSSLight_License_Type_Proprietary | FOSSLight_License_Type_Proprietary_Free | FOSSLight_License_Type_Permissive | FOSSLight_License_Type_Weak_Copyleft | FOSSLight_License_Type_UNKNOWN deriving (Show) instance S.FromField FOSSLight_License_Type where fromField f@(S.Field (S.SQLText txt) _) = case T.unpack txt of "CP" -> S.Ok FOSSLight_License_Type_Copyleft "NA" -> S.Ok FOSSLight_License_Type_Proprietary "PF" -> S.Ok FOSSLight_License_Type_Proprietary_Free "PMS" -> S.Ok FOSSLight_License_Type_Permissive "WCP" -> S.Ok FOSSLight_License_Type_Weak_Copyleft _ -> S.returnError S.ConversionFailed f "failed to parse FOSSLight_License_Type" -- CREATE TABLE `LICENSE_MASTER` ( 1 ` LICENSE_ID ` int(11 ) NOT NULL AUTO_INCREMENT COMMENT ' 라이선스ID ' , 2 ` LICENSE_NAME ` varchar(200 ) NOT NULL COMMENT ' 라이선스 명 ' , 3 ` LICENSE_TYPE ` varchar(6 ) NOT NULL COMMENT ' 라이선스 종류 ' , 4 ` OBLIGATION_DISCLOSING_SRC_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 소스코드공개여부 ' , 5 ` OBLIGATION_NOTIFICATION_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 고지여부 ' , 6 ` OBLIGATION_NEEDS_CHECK_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 추후확인필요여부 ' , 7 ` SHORT_IDENTIFIER ` varchar(100 ) NULL COMMENT ' 라이선스 약어(SPDX기준인 경우만 설정 ) ' , 8 ` WEBPAGE ` varchar(2000 ) DEFAULT NULL COMMENT ' 라이선스를 만든 WEB PAGE 주소 ' , 9 ` DESCRIPTION ` text NULL COMMENT ' 부가설명 및 collab link등 ' , 10 ` LICENSE_TEXT ` mediumtext NULL COMMENT ' 라이선스 원문 ' , 11 ` ATTRIBUTION ` text NULL COMMENT ' 고지문구 추가 사항 ' , 12 ` USE_YN ` char(1 ) DEFAULT ' Y ' COMMENT ' 사용여부 ' , 13 ` CREATOR ` varchar(50 ) DEFAULT NULL COMMENT ' 등록자 ' , 14 ` CREATED_DATE ` datetime DEFAULT current_timestamp ( ) COMMENT ' 등록일 ' , 15 ` MODIFIER ` varchar(50 ) DEFAULT NULL COMMENT ' 수정자 ' , 16 ` MODIFIED_DATE ` datetime DEFAULT current_timestamp ( ) ON UPDATE current_timestamp ( ) COMMENT ' ' , 17 ` REQ_LICENSE_TEXT_YN ` char(1 ) DEFAULT ' N ' COMMENT ' LICENSE TEXT 필수 입력 여부 , MIT LIKE , BSD LIKE만 적용 ' , 18 ` RESTRICTION ` varchar(100 ) NULL , -- PRIMARY KEY (`LICENSE_ID`), -- KEY `idx_LICENSE_NAME` (`LICENSE_NAME`), KEY ` USE_YN ` ( ` USE_YN ` ) -- ) ENGINE=InnoDB AUTO_INCREMENT=672 DEFAULT CHARSET=utf8; data FOSSLight_License = FOSSLight_License 1 ` LICENSE_ID ` int(11 ) NOT NULL AUTO_INCREMENT COMMENT ' 라이선스ID ' , 2 ` LICENSE_NAME ` varchar(200 ) NOT NULL COMMENT ' 라이선스 명 ' , 3 ` LICENSE_TYPE ` varchar(6 ) NOT NULL COMMENT ' 라이선스 종류 ' , 4 ` OBLIGATION_DISCLOSING_SRC_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 소스코드공개여부 ' , 5 ` OBLIGATION_NOTIFICATION_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 고지여부 ' , 6 ` OBLIGATION_NEEDS_CHECK_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 추후확인필요여부 ' , 7 ` SHORT_IDENTIFIER ` varchar(100 ) NULL COMMENT ' 라이선스 약어(SPDX기준인 경우만 설정 ) ' , 8 ` WEBPAGE ` varchar(2000 ) DEFAULT NULL COMMENT ' 라이선스를 만든 WEB PAGE 주소 ' , 9 ` DESCRIPTION ` text NULL COMMENT ' 부가설명 및 collab link등 ' , 10 ` LICENSE_TEXT ` mediumtext NULL COMMENT ' 라이선스 원문 ' , 11 ` ATTRIBUTION ` text NULL COMMENT ' 고지문구 추가 사항 ' , 12 ` USE_YN ` char(1 ) DEFAULT ' Y ' COMMENT ' 사용여부 ' , 13 ` CREATOR ` varchar(50 ) DEFAULT NULL COMMENT ' 등록자 ' , 14 ` CREATED_DATE ` datetime DEFAULT current_timestamp ( ) COMMENT ' 등록일 ' , 15 ` MODIFIER ` varchar(50 ) DEFAULT NULL COMMENT ' 수정자 ' , 16 ` MODIFIED_DATE ` datetime DEFAULT current_timestamp ( ) ON UPDATE current_timestamp ( ) COMMENT ' ' , 17 ` REQ_LICENSE_TEXT_YN ` char(1 ) DEFAULT ' N ' COMMENT ' LICENSE TEXT 필수 입력 여부 , MIT LIKE , BSD LIKE만 적용 ' , 18 ` RESTRICTION ` varchar(100 ) NULL , } deriving (Show) instance S.FromField () where fromField _ = S.Ok () instance S.FromRow FOSSLight_License where fromRow = let ynToBool :: Maybe String -> Bool ynToBool (Just "Y") = True ynToBool _ = False in FOSSLight_License <$> S.field <*> S.field <*> S.field <*> fmap ynToBool (S.field) <*> fmap ynToBool (S.field) <*> fmap ynToBool (S.field) <*> S.field <*> S.field <*> S.field <*> S.field <*> S.field <*> fmap ynToBool (S.field) <*> S.field <*> S.field <*> S.field <*> S.field <*> fmap ynToBool (S.field) <*> S.field data FOSSLightFact = FOSSLightFact { _FOSSLightFact_License :: FOSSLight_License , _FOSSLightFact_Nicks :: [LicenseName] } deriving (Show) instance ToJSON FOSSLightFact where toJSON (FOSSLightFact license _) = TODO fossLightLFC :: LicenseFactClassifier fossLightLFC = LFCWithLicense (LFLWithURL "" "AGPL-3.0-only") "FOSSLight" instance LicenseFactClassifiable FOSSLightFact where getLicenseFactClassifier _ = fossLightLFC instance LFRaw FOSSLightFact where getImpliedNames (FOSSLightFact lic _) = CLSR (_fossLight_name lic : (maybeToList (_fossLight_SHORT_IDENTIFIER lic))) getImpliedAmbiguousNames (FOSSLightFact _ nicks) = CLSR nicks getImpliedJudgement flf@(FOSSLightFact lic _) = SLSR (getLicenseFactClassifier flf) $ case _fossLight_USE lic of True -> NeutralJudgement "This license is allowed for use at LG" False -> NegativeJudgement "This license is prohibited to use at LG" getImpliedFullName flf@(FOSSLightFact lic _) = mkRLSR flf 20 $ _fossLight_name lic getImpliedURLs flf@(FOSSLightFact lic _) = case _fossLight_WEBPAGE lic of Just webpage -> CLSR [(Just "webpage", T.unpack webpage)] Nothing -> NoCLSR getImpliedText flf@(FOSSLightFact lic _) = case _fossLight_LICENSE_TEXT lic of Just txt -> mkRLSR flf 10 txt Nothing -> NoRLSR getImpliedDescription flf@(FOSSLightFact lic _) = case _fossLight_DESCRIPTION lic of Just desc -> mkRLSR flf 5 (T.unpack desc) Nothing -> NoRLSR getImpliedCopyleft flf@(FOSSLightFact lic _) = case _fossLight_type lic of FOSSLight_License_Type_Copyleft -> mkSLSR flf StrongCopyleft FOSSLight_License_Type_Proprietary -> NoSLSR FOSSLight_License_Type_Proprietary_Free -> NoSLSR FOSSLight_License_Type_Permissive -> mkSLSR flf NoCopyleft FOSSLight_License_Type_Weak_Copyleft -> mkSLSR flf WeakCopyleft FOSSLight_License_Type_UNKNOWN -> NoSLSR {- - ############################################################################################ -} licensesMasterSqlite :: ByteString licensesMasterSqlite = B.fromStrict $(embedFile "data/fosslight/fosslight.sqlite.db") loadFOSSLightFacts :: IO Facts loadFOSSLightFacts = let extractLicensesFromSqlite :: FilePath -> IO.Handle -> IO ([FOSSLight_License],[FOSSLight_Nick]) extractLicensesFromSqlite tmpfile hfile = do B.hPut hfile licensesMasterSqlite IO.hClose hfile conn <- S.open tmpfile license_names <- S.query_ conn "SELECT License_ID,LICENSE_NAME from LICENSE_MASTER" :: IO [(Int,LicenseName)] licenses <- fmap concat $ mapM (\(i, name) -> do putStrLn $ "get License for id=" ++ show i ++ " name=" ++ name let handleUnicodeException :: T.UnicodeException -> IO [FOSSLight_License] handleUnicodeException e = do print e return [] handleResultError :: S.ResultError -> IO [FOSSLight_License] handleResultError e = do print e return [] q = S.query_ conn ((S.Query . T.pack) $ "SELECT * from LICENSE_MASTER where LICENSE_ID=" ++ show i) :: IO [FOSSLight_License] handle handleUnicodeException . handle handleResultError $ q :: IO [FOSSLight_License] ) license_names nicks <- S.query_ conn "SELECT * from LICENSE_NICKNAME" :: IO [FOSSLight_Nick] S.close conn return (licenses, nicks) in do logThatFactsAreLoadedFrom "FOSSLight" (licenses, nicks) <- IO.withSystemTempFile "fosslight.sqlite.db" extractLicensesFromSqlite let rawToFact = LicenseFact (Just "") rawFromLicense (license@FOSSLight_License { _fossLight_name = name } ) = let nicksForLicense = map (\(FOSSLight_Nick _ nick) -> nick) $ filter (\n@(FOSSLight_Nick name' _) -> name == name') nicks in FOSSLightFact license nicksForLicense facts = map (rawToFact . rawFromLicense) licenses logThatOneHasFoundFacts "FOSSLight" facts return (V.fromList facts)
null
https://raw.githubusercontent.com/maxhbr/LDBcollector/758f414dfa4f3f92cb10c2b23498975bc9ac2419/src/Collectors/FOSSLight.hs
haskell
# LANGUAGE OverloadedStrings # CREATE TABLE `LICENSE_NICKNAME` ( `LICENSE_NAME` varchar(200) NOT NULL COMMENT '라이선스 NAME', `LICENSE_NICKNAME` varchar(200) NOT NULL COMMENT '라이선스 닉네임', PRIMARY KEY (`LICENSE_NAME`,`LICENSE_NICKNAME`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `LICENSE_MASTER` ( PRIMARY KEY (`LICENSE_ID`), KEY `idx_LICENSE_NAME` (`LICENSE_NAME`), ) ENGINE=InnoDB AUTO_INCREMENT=672 DEFAULT CHARSET=utf8; - ############################################################################################
# LANGUAGE DeriveGeneric # # LANGUAGE LambdaCase # # LANGUAGE TemplateHaskell # module Collectors.FOSSLight ( loadFOSSLightFacts , fossLightLFC ) where import qualified Prelude as P import MyPrelude import Collectors.Common import qualified Data.Text as T import qualified Data.Text.Encoding.Error as T import qualified Data.Vector as V import qualified Data.ByteString.Lazy as B import qualified Data.Map as Map import Control.Applicative import Control.Exception (handle) import Data.Csv as C import Data.Aeson as A import Data.FileEmbed (embedFile) import qualified Database.SQLite.Simple as S import qualified Database.SQLite.Simple.FromRow as S import qualified Database.SQLite.Simple.FromField as S import qualified Database.SQLite.Simple.Types as S import qualified Database.SQLite.Simple.Internal as S import qualified Database.SQLite.Simple.Ok as S import qualified System.IO as IO import qualified System.IO.Temp as IO import Model.License data FOSSLight_Nick = FOSSLight_Nick LicenseName LicenseName deriving (Show) instance S.FromRow FOSSLight_Nick where fromRow = FOSSLight_Nick <$> S.field <*> S.field ( ' 201 ' , ' CP ' , ' ' , '' , '' , 3 , ' Y ' ) , ( ' 201 ' , ' NA ' , ' Proprietary ' , '' , '' , 4 , ' Y ' ) , ( ' 201 ' , ' PF ' , ' Proprietary Free ' , '' , '' , 5 , ' Y ' ) , ( ' 201 ' , ' PMS ' , ' Permissive ' , '' , '' , 1 , ' Y ' ) , ( ' 201 ' , ' ' , ' Weak ' , '' , '' , 2 , ' Y ' ) , data FOSSLight_License_Type = FOSSLight_License_Type_Copyleft | FOSSLight_License_Type_Proprietary | FOSSLight_License_Type_Proprietary_Free | FOSSLight_License_Type_Permissive | FOSSLight_License_Type_Weak_Copyleft | FOSSLight_License_Type_UNKNOWN deriving (Show) instance S.FromField FOSSLight_License_Type where fromField f@(S.Field (S.SQLText txt) _) = case T.unpack txt of "CP" -> S.Ok FOSSLight_License_Type_Copyleft "NA" -> S.Ok FOSSLight_License_Type_Proprietary "PF" -> S.Ok FOSSLight_License_Type_Proprietary_Free "PMS" -> S.Ok FOSSLight_License_Type_Permissive "WCP" -> S.Ok FOSSLight_License_Type_Weak_Copyleft _ -> S.returnError S.ConversionFailed f "failed to parse FOSSLight_License_Type" 1 ` LICENSE_ID ` int(11 ) NOT NULL AUTO_INCREMENT COMMENT ' 라이선스ID ' , 2 ` LICENSE_NAME ` varchar(200 ) NOT NULL COMMENT ' 라이선스 명 ' , 3 ` LICENSE_TYPE ` varchar(6 ) NOT NULL COMMENT ' 라이선스 종류 ' , 4 ` OBLIGATION_DISCLOSING_SRC_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 소스코드공개여부 ' , 5 ` OBLIGATION_NOTIFICATION_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 고지여부 ' , 6 ` OBLIGATION_NEEDS_CHECK_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 추후확인필요여부 ' , 7 ` SHORT_IDENTIFIER ` varchar(100 ) NULL COMMENT ' 라이선스 약어(SPDX기준인 경우만 설정 ) ' , 8 ` WEBPAGE ` varchar(2000 ) DEFAULT NULL COMMENT ' 라이선스를 만든 WEB PAGE 주소 ' , 9 ` DESCRIPTION ` text NULL COMMENT ' 부가설명 및 collab link등 ' , 10 ` LICENSE_TEXT ` mediumtext NULL COMMENT ' 라이선스 원문 ' , 11 ` ATTRIBUTION ` text NULL COMMENT ' 고지문구 추가 사항 ' , 12 ` USE_YN ` char(1 ) DEFAULT ' Y ' COMMENT ' 사용여부 ' , 13 ` CREATOR ` varchar(50 ) DEFAULT NULL COMMENT ' 등록자 ' , 14 ` CREATED_DATE ` datetime DEFAULT current_timestamp ( ) COMMENT ' 등록일 ' , 15 ` MODIFIER ` varchar(50 ) DEFAULT NULL COMMENT ' 수정자 ' , 16 ` MODIFIED_DATE ` datetime DEFAULT current_timestamp ( ) ON UPDATE current_timestamp ( ) COMMENT ' ' , 17 ` REQ_LICENSE_TEXT_YN ` char(1 ) DEFAULT ' N ' COMMENT ' LICENSE TEXT 필수 입력 여부 , MIT LIKE , BSD LIKE만 적용 ' , 18 ` RESTRICTION ` varchar(100 ) NULL , KEY ` USE_YN ` ( ` USE_YN ` ) data FOSSLight_License = FOSSLight_License 1 ` LICENSE_ID ` int(11 ) NOT NULL AUTO_INCREMENT COMMENT ' 라이선스ID ' , 2 ` LICENSE_NAME ` varchar(200 ) NOT NULL COMMENT ' 라이선스 명 ' , 3 ` LICENSE_TYPE ` varchar(6 ) NOT NULL COMMENT ' 라이선스 종류 ' , 4 ` OBLIGATION_DISCLOSING_SRC_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 소스코드공개여부 ' , 5 ` OBLIGATION_NOTIFICATION_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 고지여부 ' , 6 ` OBLIGATION_NEEDS_CHECK_YN ` char(1 ) DEFAULT ' N ' COMMENT ' 추후확인필요여부 ' , 7 ` SHORT_IDENTIFIER ` varchar(100 ) NULL COMMENT ' 라이선스 약어(SPDX기준인 경우만 설정 ) ' , 8 ` WEBPAGE ` varchar(2000 ) DEFAULT NULL COMMENT ' 라이선스를 만든 WEB PAGE 주소 ' , 9 ` DESCRIPTION ` text NULL COMMENT ' 부가설명 및 collab link등 ' , 10 ` LICENSE_TEXT ` mediumtext NULL COMMENT ' 라이선스 원문 ' , 11 ` ATTRIBUTION ` text NULL COMMENT ' 고지문구 추가 사항 ' , 12 ` USE_YN ` char(1 ) DEFAULT ' Y ' COMMENT ' 사용여부 ' , 13 ` CREATOR ` varchar(50 ) DEFAULT NULL COMMENT ' 등록자 ' , 14 ` CREATED_DATE ` datetime DEFAULT current_timestamp ( ) COMMENT ' 등록일 ' , 15 ` MODIFIER ` varchar(50 ) DEFAULT NULL COMMENT ' 수정자 ' , 16 ` MODIFIED_DATE ` datetime DEFAULT current_timestamp ( ) ON UPDATE current_timestamp ( ) COMMENT ' ' , 17 ` REQ_LICENSE_TEXT_YN ` char(1 ) DEFAULT ' N ' COMMENT ' LICENSE TEXT 필수 입력 여부 , MIT LIKE , BSD LIKE만 적용 ' , 18 ` RESTRICTION ` varchar(100 ) NULL , } deriving (Show) instance S.FromField () where fromField _ = S.Ok () instance S.FromRow FOSSLight_License where fromRow = let ynToBool :: Maybe String -> Bool ynToBool (Just "Y") = True ynToBool _ = False in FOSSLight_License <$> S.field <*> S.field <*> S.field <*> fmap ynToBool (S.field) <*> fmap ynToBool (S.field) <*> fmap ynToBool (S.field) <*> S.field <*> S.field <*> S.field <*> S.field <*> S.field <*> fmap ynToBool (S.field) <*> S.field <*> S.field <*> S.field <*> S.field <*> fmap ynToBool (S.field) <*> S.field data FOSSLightFact = FOSSLightFact { _FOSSLightFact_License :: FOSSLight_License , _FOSSLightFact_Nicks :: [LicenseName] } deriving (Show) instance ToJSON FOSSLightFact where toJSON (FOSSLightFact license _) = TODO fossLightLFC :: LicenseFactClassifier fossLightLFC = LFCWithLicense (LFLWithURL "" "AGPL-3.0-only") "FOSSLight" instance LicenseFactClassifiable FOSSLightFact where getLicenseFactClassifier _ = fossLightLFC instance LFRaw FOSSLightFact where getImpliedNames (FOSSLightFact lic _) = CLSR (_fossLight_name lic : (maybeToList (_fossLight_SHORT_IDENTIFIER lic))) getImpliedAmbiguousNames (FOSSLightFact _ nicks) = CLSR nicks getImpliedJudgement flf@(FOSSLightFact lic _) = SLSR (getLicenseFactClassifier flf) $ case _fossLight_USE lic of True -> NeutralJudgement "This license is allowed for use at LG" False -> NegativeJudgement "This license is prohibited to use at LG" getImpliedFullName flf@(FOSSLightFact lic _) = mkRLSR flf 20 $ _fossLight_name lic getImpliedURLs flf@(FOSSLightFact lic _) = case _fossLight_WEBPAGE lic of Just webpage -> CLSR [(Just "webpage", T.unpack webpage)] Nothing -> NoCLSR getImpliedText flf@(FOSSLightFact lic _) = case _fossLight_LICENSE_TEXT lic of Just txt -> mkRLSR flf 10 txt Nothing -> NoRLSR getImpliedDescription flf@(FOSSLightFact lic _) = case _fossLight_DESCRIPTION lic of Just desc -> mkRLSR flf 5 (T.unpack desc) Nothing -> NoRLSR getImpliedCopyleft flf@(FOSSLightFact lic _) = case _fossLight_type lic of FOSSLight_License_Type_Copyleft -> mkSLSR flf StrongCopyleft FOSSLight_License_Type_Proprietary -> NoSLSR FOSSLight_License_Type_Proprietary_Free -> NoSLSR FOSSLight_License_Type_Permissive -> mkSLSR flf NoCopyleft FOSSLight_License_Type_Weak_Copyleft -> mkSLSR flf WeakCopyleft FOSSLight_License_Type_UNKNOWN -> NoSLSR licensesMasterSqlite :: ByteString licensesMasterSqlite = B.fromStrict $(embedFile "data/fosslight/fosslight.sqlite.db") loadFOSSLightFacts :: IO Facts loadFOSSLightFacts = let extractLicensesFromSqlite :: FilePath -> IO.Handle -> IO ([FOSSLight_License],[FOSSLight_Nick]) extractLicensesFromSqlite tmpfile hfile = do B.hPut hfile licensesMasterSqlite IO.hClose hfile conn <- S.open tmpfile license_names <- S.query_ conn "SELECT License_ID,LICENSE_NAME from LICENSE_MASTER" :: IO [(Int,LicenseName)] licenses <- fmap concat $ mapM (\(i, name) -> do putStrLn $ "get License for id=" ++ show i ++ " name=" ++ name let handleUnicodeException :: T.UnicodeException -> IO [FOSSLight_License] handleUnicodeException e = do print e return [] handleResultError :: S.ResultError -> IO [FOSSLight_License] handleResultError e = do print e return [] q = S.query_ conn ((S.Query . T.pack) $ "SELECT * from LICENSE_MASTER where LICENSE_ID=" ++ show i) :: IO [FOSSLight_License] handle handleUnicodeException . handle handleResultError $ q :: IO [FOSSLight_License] ) license_names nicks <- S.query_ conn "SELECT * from LICENSE_NICKNAME" :: IO [FOSSLight_Nick] S.close conn return (licenses, nicks) in do logThatFactsAreLoadedFrom "FOSSLight" (licenses, nicks) <- IO.withSystemTempFile "fosslight.sqlite.db" extractLicensesFromSqlite let rawToFact = LicenseFact (Just "") rawFromLicense (license@FOSSLight_License { _fossLight_name = name } ) = let nicksForLicense = map (\(FOSSLight_Nick _ nick) -> nick) $ filter (\n@(FOSSLight_Nick name' _) -> name == name') nicks in FOSSLightFact license nicksForLicense facts = map (rawToFact . rawFromLicense) licenses logThatOneHasFoundFacts "FOSSLight" facts return (V.fromList facts)
1357b4b96dfcb67ded58a8325d6d507caa2000cf344329b21deafa09cb883a5d
Drup/functoria-lua
Functoria_lua.ml
open Rresult open Astring module Key = Functoria_key module Name = Functoria_app.Name module Codegen = Functoria_app.Codegen include Functoria let tool_name = "functoria-lua" let src = Logs.Src.create tool_name ~doc:"functoria-lua cli tool" module Log = (val Logs.src_log src : Logs.LOG) (** Devices **) class base = object method packages: package list Key.value = Key.pure [] method keys: Key.t list = [] method connect (_:Info.t) (_:string) (_l: string list) = "()" method configure (_: Info.t): (unit, R.msg) R.t = R.ok () method build (_: Info.t): (unit, R.msg) R.t = R.ok () method clean (_: Info.t): (unit, R.msg) R.t = R.ok () method deps: abstract_impl list = [] end type +'a usertype = USERTYPE let usertype = Type USERTYPE class ['ty] new_type ?(packages=[]) ?(keys=[]) ?(deps=[]) module_name : ['ty usertype] configurable = let name = Name.create module_name ~prefix:"type" in object method ty : 'ty usertype typ = usertype method name = name method module_name = module_name method keys = keys method packages = Key.pure packages method connect (_:Info.t) (_:string) (_l: string list) = "()" method clean _ = R.ok () method configure _ = R.ok () method build _ = R.ok () method deps = deps end let new_type ?packages ?keys ?deps module_name = impl (new new_type ?packages ?keys ?deps module_name) . S type _ luavalue = VALUE let value = Type VALUE let mk_value () = impl @@ object inherit base method ty = usertype @-> value method name = "ast" method module_name = "Luavalue.Make" end (* Luaast.S *) type ast = AST let ast = Type AST let mk_ast () = impl @@ object inherit base method ty = value @-> ast method name = "ast" method module_name = "Luaast.Make" end . S type parser = PARSER let parser = Type PARSER let maker = ast @-> parser let mk_parser = impl @@ object inherit base method ty = maker method name = "parser" method module_name = "Luaparser.MakeStandard" end (* Lualib.BARECODE *) type barecode = BARECODE let barecode = Type BARECODE let bc n mn = impl @@ object inherit base method ty = barecode method name = n method module_name = mn end let mathlib = bc "mathlib" "Luamathlib.M" let strlib = bc "strlib" "Luastrlib.M" (* Lualib.USERCODE *) type +'a usercode = USERCODE let usercode = Type USERCODE let c2 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode method name = "combineC2" method module_name = "Lua.Lib.Combine.C2" end let c3 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode @-> usercode method name = "combineC3" method module_name = "Lua.Lib.Combine.C3" end let c4 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode @-> usercode @-> usercode method name = "combineC4" method module_name = "Lua.Lib.Combine.C4" end let c5 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode @-> usercode @-> usercode @-> usercode method name = "combineC5" method module_name = "Lua.Lib.Combine.C5" end (* Types *) type +'a combined = 'a usertype let combined = usertype let as_type x = x type (+'a, +'b) view = VIEW let view = Type VIEW let withtype () = impl @@ object inherit base method ty = usertype @-> barecode @-> usercode method name = "withtype" method module_name = "Lua.Lib.WithType" end let takeview i = proj (combined @-> view) ("TV"^string_of_int i) let tv1 () : ((< tv1 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 1 let tv2 () : ((< tv2 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 2 let tv3 () : ((< tv3 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 3 let tv4 () : ((< tv4 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 4 let t2 () = impl @@ object inherit base method ty = usertype @-> usertype @-> combined method name = "combine2" method module_name = "Lua.Lib.Combine.T2" end let t3 () = impl @@ object inherit base method ty = usertype @-> usertype @-> usertype @-> combined method name = "combine3" method module_name = "Lua.Lib.Combine.T3" end let t4 () = impl @@ object inherit base method ty = usertype @-> usertype @-> usertype @-> usertype @-> combined method name = "combine4" method module_name = "Lua.Lib.Combine.T4" end (* Luaiolib *) type iolib let iolib_type : iolib usertype impl = new_type "Luaiolib.T" let iolib () = impl @@ object inherit base method ty = view @-> usercode method name = "iolib" method module_name = "Luaiolib.Make" end let camllib () = impl @@ object inherit base method ty = view @-> usercode method name = "camllib" method module_name = "Luacamllib.Make" end Lua . type eval = EVAL let eval = Type EVAL let mk_eval () = impl @@ object inherit base method ty = usertype @-> usercode @-> eval method name = "eval" method module_name = "Lua.MakeEval" end type interp = INTERP let interp = Type INTERP let mk_interp = impl @@ object inherit base method ty = maker @-> eval @-> interp method name = "interp" method module_name = "Lua.MakeInterp" end let runlua = impl @@ object inherit base method ty = interp @-> job method name = "run" method module_name = "Lua.Run" method! connect _ _ _ = "fun () -> ()" end (** Tool-related functions *) let with_output ?mode f k err = match Bos.OS.File.with_oc ?mode f k () with | Ok b -> b | Error _ -> R.error_msg ("couldn't open output channel for " ^ err) (** Makefile **) let configure_makefile ~app_name info = let name = Info.name info in let open Codegen in let file = Fpath.(v "Makefile") in with_output file (fun oc () -> let fmt = Format.formatter_of_out_channel oc in append fmt {| # %s -include Makefile.user"; OPAM = opam BIN = %s DEPEXT ?= opam depext --yes --update %s .PHONY: all depend depends clean build all:: build depend depends:: $(OPAM) pin add --no-action --yes %s . $(DEPEXT) $(OPAM) install --yes --deps-only %s $(OPAM) pin remove --no-action %s build:: $(BIN) build clean:: $(BIN) clean |} (generated_header ()) name app_name app_name app_name app_name; R.ok ()) "Makefile" let clean_makefile () = Bos.OS.File.delete Fpath.(v "Makefile") * let fn = Fpath.(v "myocamlbuild.ml") let configure_myocamlbuild () = Bos.OS.File.exists fn >>= function | true -> R.ok () | false -> Bos.OS.File.write fn "" (* we made it, so we should clean it up *) let clean_myocamlbuild () = match Bos.OS.Path.stat fn with | Ok stat when stat.Unix.st_size = 0 -> Bos.OS.File.delete fn | _ -> R.ok () (** OPAM file *) let configure_opam ~app_name info = let name = Info.name info in let open Codegen in let file = Fpath.(v name + "opam") in with_output file (fun oc () -> let fmt = Format.formatter_of_out_channel oc in append fmt "# %s" (generated_header ()); Info.opam ~name:app_name fmt info; append fmt "build: [ \"%s\" \"build\" ]" tool_name; append fmt "available: [ ocaml-version >= \"4.03.0\" ]"; R.ok ()) "opam file" let clean_opam ~name = Bos.OS.File.delete Fpath.(v name + "opam") let app_name name = String.concat ~sep:"-" ["lua" ; "ml" ; name] let configure i = let name = Info.name i in Log.info (fun m -> m "Configuring."); let app_name = app_name name in configure_myocamlbuild () >>= fun () -> configure_opam ~app_name i >>= fun () -> configure_makefile ~app_name i let clean i = let name = Info.name i in clean_myocamlbuild () >>= fun () -> clean_makefile () >>= fun () -> clean_opam ~name >>= fun () -> Bos.OS.File.delete Fpath.(v "main.native.o") >>= fun () -> Bos.OS.File.delete Fpath.(v "main.native") >>= fun () -> Bos.OS.File.delete Fpath.(v name) (** Compilation *) let terminal () = let dumb = try Sys.getenv "TERM" = "dumb" with Not_found -> true in let isatty = try Unix.(isatty (descr_of_out_channel Pervasives.stdout)) with | Unix.Unix_error _ -> false in not dumb && isatty let compile i = let libs = Info.libraries i in let tags = [ "warn(A-4-41-42-44)"; "debug"; "bin_annot"; "strict_sequence"; "principal"; "safe_string" ] @ (if terminal () then ["color(always)"] else []) in let concat = String.concat ~sep:"," in let cmd = Bos.Cmd.(v "ocamlbuild" % "-use-ocamlfind" % "-classic-display" % "-tags" % concat tags % "-pkgs" % concat libs % "main.native") in Log.info (fun m -> m "executing %a" Bos.Cmd.pp cmd); Bos.OS.Cmd.run cmd let link info = let name = Info.name info in Bos.OS.Cmd.run Bos.Cmd.(v "ln" % "-nfs" % "_build/main.native" % name) >>= fun () -> Ok name let build i = compile i >>= fun () -> link i >>| fun out -> Log.info (fun m -> m "Build succeeded: %s" out) module Project = struct let name = "functoria-lua" let version = "%%VERSION%%" let prelude = {| let (>>=) x f = f x let return x = x let run () = () |} (* The ocamlfind packages to use when compiling config.ml *) let packages = [package "functoria-lua"] (* The directories to ignore when compiling config.ml *) let ignore_dirs = [] let create jobs = impl @@ object inherit base_configurable method ty = job method name = tool_name method module_name = "Functoria_lua_runtime" method! keys = [ ] method! packages = let common = [ package "lua-ml"; package "functoria-runtime"; package ~build:true "ocamlfind" ; package ~build:true "ocamlbuild" ; ] in Key.pure common method! build = build method! configure = configure method! clean = clean method! connect _ _mod _names = "()" method! deps = List.map abstract jobs end end include Functoria_app.Make (Project) let register ?keys ?packages name jobs = let argv = Functoria_app.(keys sys_argv) in let init = [ argv ] in register ?keys ?packages ~init name jobs * Copyright ( c ) 2018 < > * * 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) 2018 Gabriel Radanne <> * * 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. *)
null
https://raw.githubusercontent.com/Drup/functoria-lua/820ca7700482aa610496175d48bb7bfffdb17bd9/lib/Functoria_lua.ml
ocaml
* Devices * Luaast.S Lualib.BARECODE Lualib.USERCODE Types Luaiolib * Tool-related functions * Makefile * we made it, so we should clean it up * OPAM file * Compilation The ocamlfind packages to use when compiling config.ml The directories to ignore when compiling config.ml
open Rresult open Astring module Key = Functoria_key module Name = Functoria_app.Name module Codegen = Functoria_app.Codegen include Functoria let tool_name = "functoria-lua" let src = Logs.Src.create tool_name ~doc:"functoria-lua cli tool" module Log = (val Logs.src_log src : Logs.LOG) class base = object method packages: package list Key.value = Key.pure [] method keys: Key.t list = [] method connect (_:Info.t) (_:string) (_l: string list) = "()" method configure (_: Info.t): (unit, R.msg) R.t = R.ok () method build (_: Info.t): (unit, R.msg) R.t = R.ok () method clean (_: Info.t): (unit, R.msg) R.t = R.ok () method deps: abstract_impl list = [] end type +'a usertype = USERTYPE let usertype = Type USERTYPE class ['ty] new_type ?(packages=[]) ?(keys=[]) ?(deps=[]) module_name : ['ty usertype] configurable = let name = Name.create module_name ~prefix:"type" in object method ty : 'ty usertype typ = usertype method name = name method module_name = module_name method keys = keys method packages = Key.pure packages method connect (_:Info.t) (_:string) (_l: string list) = "()" method clean _ = R.ok () method configure _ = R.ok () method build _ = R.ok () method deps = deps end let new_type ?packages ?keys ?deps module_name = impl (new new_type ?packages ?keys ?deps module_name) . S type _ luavalue = VALUE let value = Type VALUE let mk_value () = impl @@ object inherit base method ty = usertype @-> value method name = "ast" method module_name = "Luavalue.Make" end type ast = AST let ast = Type AST let mk_ast () = impl @@ object inherit base method ty = value @-> ast method name = "ast" method module_name = "Luaast.Make" end . S type parser = PARSER let parser = Type PARSER let maker = ast @-> parser let mk_parser = impl @@ object inherit base method ty = maker method name = "parser" method module_name = "Luaparser.MakeStandard" end type barecode = BARECODE let barecode = Type BARECODE let bc n mn = impl @@ object inherit base method ty = barecode method name = n method module_name = mn end let mathlib = bc "mathlib" "Luamathlib.M" let strlib = bc "strlib" "Luastrlib.M" type +'a usercode = USERCODE let usercode = Type USERCODE let c2 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode method name = "combineC2" method module_name = "Lua.Lib.Combine.C2" end let c3 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode @-> usercode method name = "combineC3" method module_name = "Lua.Lib.Combine.C3" end let c4 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode @-> usercode @-> usercode method name = "combineC4" method module_name = "Lua.Lib.Combine.C4" end let c5 () = impl @@ object inherit base method ty = usercode @-> usercode @-> usercode @-> usercode @-> usercode @-> usercode method name = "combineC5" method module_name = "Lua.Lib.Combine.C5" end type +'a combined = 'a usertype let combined = usertype let as_type x = x type (+'a, +'b) view = VIEW let view = Type VIEW let withtype () = impl @@ object inherit base method ty = usertype @-> barecode @-> usercode method name = "withtype" method module_name = "Lua.Lib.WithType" end let takeview i = proj (combined @-> view) ("TV"^string_of_int i) let tv1 () : ((< tv1 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 1 let tv2 () : ((< tv2 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 2 let tv3 () : ((< tv3 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 3 let tv4 () : ((< tv4 : 'a ; .. > as 'c) combined -> ('a, 'c) view) impl = takeview 4 let t2 () = impl @@ object inherit base method ty = usertype @-> usertype @-> combined method name = "combine2" method module_name = "Lua.Lib.Combine.T2" end let t3 () = impl @@ object inherit base method ty = usertype @-> usertype @-> usertype @-> combined method name = "combine3" method module_name = "Lua.Lib.Combine.T3" end let t4 () = impl @@ object inherit base method ty = usertype @-> usertype @-> usertype @-> usertype @-> combined method name = "combine4" method module_name = "Lua.Lib.Combine.T4" end type iolib let iolib_type : iolib usertype impl = new_type "Luaiolib.T" let iolib () = impl @@ object inherit base method ty = view @-> usercode method name = "iolib" method module_name = "Luaiolib.Make" end let camllib () = impl @@ object inherit base method ty = view @-> usercode method name = "camllib" method module_name = "Luacamllib.Make" end Lua . type eval = EVAL let eval = Type EVAL let mk_eval () = impl @@ object inherit base method ty = usertype @-> usercode @-> eval method name = "eval" method module_name = "Lua.MakeEval" end type interp = INTERP let interp = Type INTERP let mk_interp = impl @@ object inherit base method ty = maker @-> eval @-> interp method name = "interp" method module_name = "Lua.MakeInterp" end let runlua = impl @@ object inherit base method ty = interp @-> job method name = "run" method module_name = "Lua.Run" method! connect _ _ _ = "fun () -> ()" end let with_output ?mode f k err = match Bos.OS.File.with_oc ?mode f k () with | Ok b -> b | Error _ -> R.error_msg ("couldn't open output channel for " ^ err) let configure_makefile ~app_name info = let name = Info.name info in let open Codegen in let file = Fpath.(v "Makefile") in with_output file (fun oc () -> let fmt = Format.formatter_of_out_channel oc in append fmt {| # %s -include Makefile.user"; OPAM = opam BIN = %s DEPEXT ?= opam depext --yes --update %s .PHONY: all depend depends clean build all:: build depend depends:: $(OPAM) pin add --no-action --yes %s . $(DEPEXT) $(OPAM) install --yes --deps-only %s $(OPAM) pin remove --no-action %s build:: $(BIN) build clean:: $(BIN) clean |} (generated_header ()) name app_name app_name app_name app_name; R.ok ()) "Makefile" let clean_makefile () = Bos.OS.File.delete Fpath.(v "Makefile") * let fn = Fpath.(v "myocamlbuild.ml") let configure_myocamlbuild () = Bos.OS.File.exists fn >>= function | true -> R.ok () | false -> Bos.OS.File.write fn "" let clean_myocamlbuild () = match Bos.OS.Path.stat fn with | Ok stat when stat.Unix.st_size = 0 -> Bos.OS.File.delete fn | _ -> R.ok () let configure_opam ~app_name info = let name = Info.name info in let open Codegen in let file = Fpath.(v name + "opam") in with_output file (fun oc () -> let fmt = Format.formatter_of_out_channel oc in append fmt "# %s" (generated_header ()); Info.opam ~name:app_name fmt info; append fmt "build: [ \"%s\" \"build\" ]" tool_name; append fmt "available: [ ocaml-version >= \"4.03.0\" ]"; R.ok ()) "opam file" let clean_opam ~name = Bos.OS.File.delete Fpath.(v name + "opam") let app_name name = String.concat ~sep:"-" ["lua" ; "ml" ; name] let configure i = let name = Info.name i in Log.info (fun m -> m "Configuring."); let app_name = app_name name in configure_myocamlbuild () >>= fun () -> configure_opam ~app_name i >>= fun () -> configure_makefile ~app_name i let clean i = let name = Info.name i in clean_myocamlbuild () >>= fun () -> clean_makefile () >>= fun () -> clean_opam ~name >>= fun () -> Bos.OS.File.delete Fpath.(v "main.native.o") >>= fun () -> Bos.OS.File.delete Fpath.(v "main.native") >>= fun () -> Bos.OS.File.delete Fpath.(v name) let terminal () = let dumb = try Sys.getenv "TERM" = "dumb" with Not_found -> true in let isatty = try Unix.(isatty (descr_of_out_channel Pervasives.stdout)) with | Unix.Unix_error _ -> false in not dumb && isatty let compile i = let libs = Info.libraries i in let tags = [ "warn(A-4-41-42-44)"; "debug"; "bin_annot"; "strict_sequence"; "principal"; "safe_string" ] @ (if terminal () then ["color(always)"] else []) in let concat = String.concat ~sep:"," in let cmd = Bos.Cmd.(v "ocamlbuild" % "-use-ocamlfind" % "-classic-display" % "-tags" % concat tags % "-pkgs" % concat libs % "main.native") in Log.info (fun m -> m "executing %a" Bos.Cmd.pp cmd); Bos.OS.Cmd.run cmd let link info = let name = Info.name info in Bos.OS.Cmd.run Bos.Cmd.(v "ln" % "-nfs" % "_build/main.native" % name) >>= fun () -> Ok name let build i = compile i >>= fun () -> link i >>| fun out -> Log.info (fun m -> m "Build succeeded: %s" out) module Project = struct let name = "functoria-lua" let version = "%%VERSION%%" let prelude = {| let (>>=) x f = f x let return x = x let run () = () |} let packages = [package "functoria-lua"] let ignore_dirs = [] let create jobs = impl @@ object inherit base_configurable method ty = job method name = tool_name method module_name = "Functoria_lua_runtime" method! keys = [ ] method! packages = let common = [ package "lua-ml"; package "functoria-runtime"; package ~build:true "ocamlfind" ; package ~build:true "ocamlbuild" ; ] in Key.pure common method! build = build method! configure = configure method! clean = clean method! connect _ _mod _names = "()" method! deps = List.map abstract jobs end end include Functoria_app.Make (Project) let register ?keys ?packages name jobs = let argv = Functoria_app.(keys sys_argv) in let init = [ argv ] in register ?keys ?packages ~init name jobs * Copyright ( c ) 2018 < > * * 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) 2018 Gabriel Radanne <> * * 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. *)
77f05c8cdc7b9e5612c4e20e8d14b5a8c5ea147250e274e845cd487737127bae
mbutterick/beautiful-racket
parser-tester.rkt
#lang br (require "parser.rkt") (parse-to-datum "++++-+++-++-++[>++++-+++-++-++<-]>.")
null
https://raw.githubusercontent.com/mbutterick/beautiful-racket/f0e2cb5b325733b3f9cbd554cc7d2bb236af9ee9/beautiful-racket-demo/bf-demo/parser-tester.rkt
racket
#lang br (require "parser.rkt") (parse-to-datum "++++-+++-++-++[>++++-+++-++-++<-]>.")
3cc31ad99c3d98de7caee6373c779521135c2510421459119e32a037713c3d68
EveryTian/Haskell-Codewars
youre-a-square.hs
-a-square module Codewars.Kata.Square where isSquare :: Integral n => n -> Bool isSquare n = let sqrtN = floor $ sqrt $ fromIntegral n in sqrtN * sqrtN == n
null
https://raw.githubusercontent.com/EveryTian/Haskell-Codewars/dc48d95c676ce1a59f697d07672acb6d4722893b/7kyu/youre-a-square.hs
haskell
-a-square module Codewars.Kata.Square where isSquare :: Integral n => n -> Bool isSquare n = let sqrtN = floor $ sqrt $ fromIntegral n in sqrtN * sqrtN == n
57511104466eb5f3c1b0007bd533814e4f28388149e4fd20410ae3c0dd89bdd8
notogawa/yesod-websocket-sample
StaticFiles.hs
module Settings.StaticFiles where import Prelude (IO) import Yesod.Static import qualified Yesod.Static as Static import Settings (staticDir) import Settings.Development -- | use this to create your static file serving site staticSite :: IO Static.Static staticSite = if development then Static.staticDevel staticDir else Static.static staticDir -- | This generates easy references to files in the static directory at compile time, -- giving you compile-time verification that referenced files exist. -- Warning: any files added to your static directory during run-time can't be accessed this way . You 'll have to use their FilePath or URL to access them . $(staticFiles Settings.staticDir)
null
https://raw.githubusercontent.com/notogawa/yesod-websocket-sample/aa3eb38339830753a26ec68e130053ea01a80ff2/Settings/StaticFiles.hs
haskell
| use this to create your static file serving site | This generates easy references to files in the static directory at compile time, giving you compile-time verification that referenced files exist. Warning: any files added to your static directory during run-time can't be
module Settings.StaticFiles where import Prelude (IO) import Yesod.Static import qualified Yesod.Static as Static import Settings (staticDir) import Settings.Development staticSite :: IO Static.Static staticSite = if development then Static.staticDevel staticDir else Static.static staticDir accessed this way . You 'll have to use their FilePath or URL to access them . $(staticFiles Settings.staticDir)
464cdd32d1faabdfd96a5a8363ad47d91ed4f6875146edf5feb648dddca0e207
jimpil/clojuima
core.clj
(ns clojuima.core (:import [org.apache.uima UIMAFramework] [org.apache.uima.jcas JCas] [org.apache.uima.jcas.tcas Annotation] [org.apache.uima.resource ResourceSpecifier ResourceManager] [org.apache.uima.util XMLInputSource CasPool] [org.apache.uima.analysis_engine AnalysisEngine] [org.uimafit.component JCasAnnotator_ImplBase] [org.uimafit.util JCasUtil CasUtil] [org.uimafit.component.initialize ConfigurationParameterInitializer] [org.uimafit.factory JCasFactory TypeSystemDescriptionFactory AnalysisEngineFactory AggregateBuilder CollectionReaderFactory] [clojuima.java UIMAProxy] [org.apache.uima.examples.tagger HMMTagger] [org.apache.uima TokenAnnotation SentenceAnnotation] )) (def dynamic-classloader (. (Thread/currentThread) getContextClassLoader)) (definline xml-parser "Get the current XML parser." [] `(UIMAFramework/getXMLParser)) (definline logger "Get the current logger." [] `(UIMAFramework/getLogger)) (defn ^ResourceSpecifier xml-resource "Parses an xml-descriptor file and returns the ResourceSpecifier object." [xml-descriptor-loc] (let [source (XMLInputSource. xml-descriptor-loc)] (.parseResourceSpecifier (xml-parser) source))) (defn ^JCas jcas "Create a JCas, given an Analysis Engine (ae)." [^AnalysisEngine ae] (.newJCas ae)) (defn produce-primitive "Produce UIMA components from your objects without writing any XML descriptors, via uima-fit." [& os] (map #(AnalysisEngineFactory/createPrimitive (class %) (TypeSystemDescriptionFactory/createTypeSystemDescription) (to-array [])) os)) (defn produce "Produce UIMA components according to some ResourceSpecifier objects (which you get from calling (xml-resource some.xml)." [what specifier config-map & {:keys [resource-manager] :or {resource-manager (doto (UIMAFramework/newDefaultResourceManager) (.setExtensionClassPath dynamic-classloader "" true))}}] (let [min-params {"TIMEOUT_PERIOD" 0 ;"NUM_SIMULTANEOUS_REQUESTS" (int par-requests) "RESOURCE_MANAGER" resource-manager} additional-params (merge min-params config-map)] (case what :analysis-engine (UIMAFramework/produceAnalysisEngine specifier additional-params) :cas-consumer (UIMAFramework/produceCasConsumer specifier additional-params) :cas-initializer (UIMAFramework/produceCasInitializer specifier additional-params) :collection-processing-engine (UIMAFramework/produceCollectionProcessingEngine specifier additional-params) :collection-reader (UIMAFramework/produceCollectionReader specifier additional-params) :primitive-ae (produce-primitive specifier)))) ;;'specifier' here really means 'object-instance' and not xml as we're going through uima-fit (defn inject-annotation! [^JCas jc [^Class type begin end]] (let [cas (.getCas jc) type-system (.getTypeSystem jc) type (CasUtil/getAnnotationType cas type)] (.addFsToIndexes cas (.createAnnotation cas type begin end)))) (defn select-annotations [^JCas jc ^Class klass start end] (JCasUtil/selectCovered jc klass start end)) (defn calculate-indices [original matches] (let [matcher (fn ^java.util.regex.Matcher [p] (re-matcher (re-pattern p) original))] (with-local-vars [cpos 0] (reduce #(assoc %1 %2 (let [ma1 (doto (matcher %2) (.find @cpos)) endpos (.end ma1)] (var-set cpos endpos) [(.start ma1) endpos])) {} matches)))) (defn uima-compatible "Given a component and a function to extract the desired input from the JCas, returns a UIMA compatible oblect that wraps the original component. For now the component must be able to act as a function. The fn 'jcas-input-extractor' must accept 2 arguments [JCas, UIMAContext]." ([component jcas-input-extractor jcas-writer config-map] (produce :analysis-engine (AnalysisEngineFactory/createPrimitiveDescription UIMAProxy (to-array [UIMAProxy/PARAM_ANNFN (class component) UIMAProxy/PARAM_EXTFN (class jcas-input-extractor) UIMAProxy/PARAM_POSTFN (class jcas-writer)])) config-map)) ([component jcas-input-extractor jcas-writer] (uima-compatible component jcas-input-extractor jcas-writer {})) ) (defn hmm-postag "A HMM POS-tagger capable of working not only with bigrams(n=2) but also trigrams(n=3). The 3rd overload is the important one. It expects the path to the model you want to use and a map from sentences (String) to tokens (seq of Strings). If you don't have the tokens for the sentences simply pass nil or an empty seq and UIMA's basic WhiteSpaceTokenizer will be used to create the tokens. Theoretically you can mix non-empty token-seqs with empty ones in the same map - however if that is the case, the tokens that were supplied will be ignored only to be re-tokenized by the WhiteSpaceTokenizer. Therefore, it is not suggested that you do that. In fact, it not suggested to use the WhiteSpaceTokenizer for any serious work at all. In addition, you can also pass an extra key :n with value 2 or 3, to specify whether you want bigram or trigram modelling. The other 2 overloads are there to simply deal with a single sentence." ([path-to-model whole-sentence tokens n] (hmm-postag path-to-model {whole-sentence tokens :n n})) ([path-to-model whole-sentence tokens] (hmm-postag path-to-model whole-sentence tokens 3)) ([path-to-model sentence-token-map] (let [config {"NGRAM_SIZE" (int (or (:n sentence-token-map) 3)) "ModelFile" path-to-model} proper-map (dissoc sentence-token-map :n) need-aggregate? (not (every? seq (vals proper-map))) tagger (if need-aggregate? (produce :analysis-engine (-> "HmmTaggerAggregate.xml" clojure.java.io/resource xml-resource) config) (produce :analysis-engine (-> "HmmTagger.xml" clojure.java.io/resource xml-resource) config)) jc (jcas tagger) pos-tag (fn [^String s ^JCas jc] (.setDocumentText jc s) (.process tagger jc) (mapv (fn [^TokenAnnotation ta] (.getPosTag ta)) (select-annotations jc TokenAnnotation 0 (count s))))] (if need-aggregate? (reduce-kv (fn [init sentence tokens] (conj init (pos-tag sentence jc))) [] proper-map) (reduce-kv (fn [init sentence tokens] (conj init (do (inject-annotation! jc [SentenceAnnotation 0 (count sentence)]) (doseq [[_ [b e]] (calculate-indices sentence tokens)] (inject-annotation! jc [TokenAnnotation b e])) (pos-tag sentence jc)))) [] proper-map)))) ) (def postag-brown (partial hmm-postag "/home/sorted/clooJWorkspace/hotel-nlp/resources/pretrained_models/BrownModel.dat")) (comment -----CLOJURE->UIMA--------- (def sample "All plants need light and water to grow!") ;;define a sample sentence (def token-regex "Regular expression capable of identifying word boundaries." #"[\p{L}\d/]+|[\-\,\.\?\!\(\)]") (defn my-tok "A tokenizing fucntion" [^String s] (re-seq token-regex s)) (my-tok sample) 2nd arg is the UIMAContext which we do n't need for our purpose (.getDocumentText c)) (defn post-fn "Given a JCas, some annotation result and the original input, calculate the appropriate indices and inject them into the CAS. " [^JCas jc res original-input] (inject-annotation! jc [Annotation 0 (count original-input)]) ;;the entire sentence annotation (doseq [[_ [b e]] (calculate-indices original-input res)] (inject-annotation! jc [Annotation b e])) );; the token annotations (uima-compatible my-tok extractor post-fn) (def my-ae *1) ;;got our UIMA tokenizer (def jc (JCasFactory/createJCas)) (.setDocumentText jc sample) (.process my-ae jc) clojuima.java.UIMAProxy/resultMap --------UIMA->CLOJURE--------- (postag-brown sample (re-seq token-regex sample) 3) ;;providing the tokens so WhitespaceTokenizer won't be used (postag-brown sample nil 2) ;;not providing the tokens so WhitespaceTokenizer will be used )
null
https://raw.githubusercontent.com/jimpil/clojuima/14e9929891606eb2127bee696be88ca2f0ca78cc/src/clojuima/core.clj
clojure
"NUM_SIMULTANEOUS_REQUESTS" (int par-requests) 'specifier' here really means 'object-instance' and not xml as we're going through uima-fit define a sample sentence the entire sentence annotation the token annotations got our UIMA tokenizer providing the tokens so WhitespaceTokenizer won't be used not providing the tokens so WhitespaceTokenizer will be used
(ns clojuima.core (:import [org.apache.uima UIMAFramework] [org.apache.uima.jcas JCas] [org.apache.uima.jcas.tcas Annotation] [org.apache.uima.resource ResourceSpecifier ResourceManager] [org.apache.uima.util XMLInputSource CasPool] [org.apache.uima.analysis_engine AnalysisEngine] [org.uimafit.component JCasAnnotator_ImplBase] [org.uimafit.util JCasUtil CasUtil] [org.uimafit.component.initialize ConfigurationParameterInitializer] [org.uimafit.factory JCasFactory TypeSystemDescriptionFactory AnalysisEngineFactory AggregateBuilder CollectionReaderFactory] [clojuima.java UIMAProxy] [org.apache.uima.examples.tagger HMMTagger] [org.apache.uima TokenAnnotation SentenceAnnotation] )) (def dynamic-classloader (. (Thread/currentThread) getContextClassLoader)) (definline xml-parser "Get the current XML parser." [] `(UIMAFramework/getXMLParser)) (definline logger "Get the current logger." [] `(UIMAFramework/getLogger)) (defn ^ResourceSpecifier xml-resource "Parses an xml-descriptor file and returns the ResourceSpecifier object." [xml-descriptor-loc] (let [source (XMLInputSource. xml-descriptor-loc)] (.parseResourceSpecifier (xml-parser) source))) (defn ^JCas jcas "Create a JCas, given an Analysis Engine (ae)." [^AnalysisEngine ae] (.newJCas ae)) (defn produce-primitive "Produce UIMA components from your objects without writing any XML descriptors, via uima-fit." [& os] (map #(AnalysisEngineFactory/createPrimitive (class %) (TypeSystemDescriptionFactory/createTypeSystemDescription) (to-array [])) os)) (defn produce "Produce UIMA components according to some ResourceSpecifier objects (which you get from calling (xml-resource some.xml)." [what specifier config-map & {:keys [resource-manager] :or {resource-manager (doto (UIMAFramework/newDefaultResourceManager) (.setExtensionClassPath dynamic-classloader "" true))}}] (let [min-params {"TIMEOUT_PERIOD" 0 "RESOURCE_MANAGER" resource-manager} additional-params (merge min-params config-map)] (case what :analysis-engine (UIMAFramework/produceAnalysisEngine specifier additional-params) :cas-consumer (UIMAFramework/produceCasConsumer specifier additional-params) :cas-initializer (UIMAFramework/produceCasInitializer specifier additional-params) :collection-processing-engine (UIMAFramework/produceCollectionProcessingEngine specifier additional-params) :collection-reader (UIMAFramework/produceCollectionReader specifier additional-params) (defn inject-annotation! [^JCas jc [^Class type begin end]] (let [cas (.getCas jc) type-system (.getTypeSystem jc) type (CasUtil/getAnnotationType cas type)] (.addFsToIndexes cas (.createAnnotation cas type begin end)))) (defn select-annotations [^JCas jc ^Class klass start end] (JCasUtil/selectCovered jc klass start end)) (defn calculate-indices [original matches] (let [matcher (fn ^java.util.regex.Matcher [p] (re-matcher (re-pattern p) original))] (with-local-vars [cpos 0] (reduce #(assoc %1 %2 (let [ma1 (doto (matcher %2) (.find @cpos)) endpos (.end ma1)] (var-set cpos endpos) [(.start ma1) endpos])) {} matches)))) (defn uima-compatible "Given a component and a function to extract the desired input from the JCas, returns a UIMA compatible oblect that wraps the original component. For now the component must be able to act as a function. The fn 'jcas-input-extractor' must accept 2 arguments [JCas, UIMAContext]." ([component jcas-input-extractor jcas-writer config-map] (produce :analysis-engine (AnalysisEngineFactory/createPrimitiveDescription UIMAProxy (to-array [UIMAProxy/PARAM_ANNFN (class component) UIMAProxy/PARAM_EXTFN (class jcas-input-extractor) UIMAProxy/PARAM_POSTFN (class jcas-writer)])) config-map)) ([component jcas-input-extractor jcas-writer] (uima-compatible component jcas-input-extractor jcas-writer {})) ) (defn hmm-postag "A HMM POS-tagger capable of working not only with bigrams(n=2) but also trigrams(n=3). The 3rd overload is the important one. It expects the path to the model you want to use and a map from sentences (String) to tokens (seq of Strings). If you don't have the tokens for the sentences simply pass nil or an empty seq and UIMA's basic WhiteSpaceTokenizer will be used to create the tokens. Theoretically you can mix non-empty token-seqs with empty ones in the same map - however if that is the case, the tokens that were supplied will be ignored only to be re-tokenized by the WhiteSpaceTokenizer. Therefore, it is not suggested that you do that. In fact, it not suggested to use the WhiteSpaceTokenizer for any serious work at all. In addition, you can also pass an extra key :n with value 2 or 3, to specify whether you want bigram or trigram modelling. The other 2 overloads are there to simply deal with a single sentence." ([path-to-model whole-sentence tokens n] (hmm-postag path-to-model {whole-sentence tokens :n n})) ([path-to-model whole-sentence tokens] (hmm-postag path-to-model whole-sentence tokens 3)) ([path-to-model sentence-token-map] (let [config {"NGRAM_SIZE" (int (or (:n sentence-token-map) 3)) "ModelFile" path-to-model} proper-map (dissoc sentence-token-map :n) need-aggregate? (not (every? seq (vals proper-map))) tagger (if need-aggregate? (produce :analysis-engine (-> "HmmTaggerAggregate.xml" clojure.java.io/resource xml-resource) config) (produce :analysis-engine (-> "HmmTagger.xml" clojure.java.io/resource xml-resource) config)) jc (jcas tagger) pos-tag (fn [^String s ^JCas jc] (.setDocumentText jc s) (.process tagger jc) (mapv (fn [^TokenAnnotation ta] (.getPosTag ta)) (select-annotations jc TokenAnnotation 0 (count s))))] (if need-aggregate? (reduce-kv (fn [init sentence tokens] (conj init (pos-tag sentence jc))) [] proper-map) (reduce-kv (fn [init sentence tokens] (conj init (do (inject-annotation! jc [SentenceAnnotation 0 (count sentence)]) (doseq [[_ [b e]] (calculate-indices sentence tokens)] (inject-annotation! jc [TokenAnnotation b e])) (pos-tag sentence jc)))) [] proper-map)))) ) (def postag-brown (partial hmm-postag "/home/sorted/clooJWorkspace/hotel-nlp/resources/pretrained_models/BrownModel.dat")) (comment -----CLOJURE->UIMA--------- (def token-regex "Regular expression capable of identifying word boundaries." #"[\p{L}\d/]+|[\-\,\.\?\!\(\)]") (defn my-tok "A tokenizing fucntion" [^String s] (re-seq token-regex s)) (my-tok sample) 2nd arg is the UIMAContext which we do n't need for our purpose (.getDocumentText c)) (defn post-fn "Given a JCas, some annotation result and the original input, calculate the appropriate indices and inject them into the CAS. " [^JCas jc res original-input] (doseq [[_ [b e]] (calculate-indices original-input res)] (uima-compatible my-tok extractor post-fn) (def jc (JCasFactory/createJCas)) (.setDocumentText jc sample) (.process my-ae jc) clojuima.java.UIMAProxy/resultMap --------UIMA->CLOJURE--------- )
33e6689a0c7d880b2745bef57709c2d647923bd27ed3208b5e47026935ce5e88
ekmett/ekmett.github.com
Dual.hs
------------------------------------------------------------------------------------------- -- | -- Module : Control.Category.Dual Copyright : 2008 -- License : BSD-style (see the LICENSE file in the distribution) -- Maintainer : < > -- Stability : experimental -- Portability : non-portable (class-associated types) -- -- The dual of a category is another category. -- -- This notion appears to be fundamentally flawed because the instances here seem to actively -- get in the way of other instances. TODO: wrap functors ------------------------------------------------------------------------------------------- module Control.Category.Dual where import Prelude hiding (Functor, map, (.), id, fst, snd, Monad, return, (>>=), curry, uncurry) import qualified Prelude import Control.Category.Classes newtype Dual k a b = Dual { runDual :: k b a } instance Category k => Category (Dual k) where id = Dual id f . g = Dual (runDual g . runDual f) instance Bifunctor p k1 k2 k3 => Bifunctor p (Dual k1) (Dual k2) (Dual k3) where bimap f g = Dual $ bimap (runDual f) (runDual g) instance Associative p k => Coassociative p (Dual k) where coassociate = Dual associate instance Coassociative p k => Associative p (Dual k) where associate = Dual coassociate instance Braided p k => Braided p (Dual k) where braid = Dual braid instance Cartesian k => CoCartesian (Dual k) where #ifndef __HADDOCK__ type Sum (Dual k) = Prod k #endif inl = Dual fst inr = Dual snd f ||| g = Dual (runDual f &&& runDual g) codiag = Dual diag instance CoCartesian k => Cartesian (Dual k) where #ifndef __HADDOCK__ type Prod (Dual k) = Sum k #endif fst = Dual inl snd = Dual inr f &&& g = Dual (runDual f ||| runDual g) diag = Dual codiag instance Monoidal p k => Comonoidal p (Dual k) where coidl = Dual idl coidr = Dual idr instance Comonoidal p k => Monoidal p (Dual k) where idl = Dual coidl idr = Dual coidr instance HasIdentity p k => HasIdentity p (Dual k) #ifndef __HADDOCK__ where type Identity (Dual k) p = Identity k p #endif instance Functor f k k => Functor f (Dual k) (Dual k) where map = Dual . map . runDual instance Full f k k => Full f (Dual k) (Dual k) where premap = Dual . premap . runDual instance Faithful f k k => Faithful f (Dual k) (Dual k) instance Pointed f k => Copointed f (Dual k) where extract = Dual return instance Copointed f k => Pointed f (Dual k) where return = Dual extract instance Monad m k => Comonad m (Dual k) where extend = Dual . bind . runDual duplicate = Dual join instance Comonad w k => Monad w (Dual k) where bind = Dual . extend . runDual join = Dual duplicate instance Adjunction f g k k => Adjunction g f (Dual k) (Dual k) where unit = Dual counit counit = Dual unit leftAdjunct = Dual . rightAdjunct . runDual rightAdjunct = Dual . leftAdjunct . runDual instance CCC k => CoCCC (Dual k) where #ifndef __HADDOCK__ type Coexp (Dual k) = Exp k #endif coapply = Dual apply cocurry = Dual . curry . runDual uncocurry = Dual . uncurry . runDual instance CoCCC k => CCC (Dual k) where #ifndef __HADDOCK__ type Exp (Dual k) = Coexp k #endif apply = Dual coapply curry = Dual . cocurry . runDual uncurry = Dual . uncocurry . runDual instance ( Arrow k #ifndef __HADDOCK__ , Prod k ~ (,) #endif ) => DualArrow (Dual k) where dualarr f = Dual (arr f) instance ( DualArrow k #ifndef __HADDOCK__ , Sum k ~ (,) #endif ) => Arrow (Dual k) where arr f = Dual (dualarr f) liftDualDual :: k a b -> Dual (Dual k) a b liftDualDual = Dual . Dual lowerDualDual :: Dual (Dual k) a b -> k a b lowerDualDual = runDual . runDual instance HasFunctorComposition k => HasFunctorComposition (Dual k) where comp = Dual decomp decomp = Dual comp instance HasBitransform p c d e => HasBitransform p (Dual c) (Dual d) (Dual e) where unbitransform = Dual bitransform bitransform = Dual unbitransform
null
https://raw.githubusercontent.com/ekmett/ekmett.github.com/8d3abab5b66db631e148e1d046d18909bece5893/haskell/categories/_darcs/pristine/src/Control/Category/Dual.hs
haskell
----------------------------------------------------------------------------------------- | Module : Control.Category.Dual License : BSD-style (see the LICENSE file in the distribution) Stability : experimental Portability : non-portable (class-associated types) The dual of a category is another category. This notion appears to be fundamentally flawed because the instances here seem to actively get in the way of other instances. TODO: wrap functors -----------------------------------------------------------------------------------------
Copyright : 2008 Maintainer : < > module Control.Category.Dual where import Prelude hiding (Functor, map, (.), id, fst, snd, Monad, return, (>>=), curry, uncurry) import qualified Prelude import Control.Category.Classes newtype Dual k a b = Dual { runDual :: k b a } instance Category k => Category (Dual k) where id = Dual id f . g = Dual (runDual g . runDual f) instance Bifunctor p k1 k2 k3 => Bifunctor p (Dual k1) (Dual k2) (Dual k3) where bimap f g = Dual $ bimap (runDual f) (runDual g) instance Associative p k => Coassociative p (Dual k) where coassociate = Dual associate instance Coassociative p k => Associative p (Dual k) where associate = Dual coassociate instance Braided p k => Braided p (Dual k) where braid = Dual braid instance Cartesian k => CoCartesian (Dual k) where #ifndef __HADDOCK__ type Sum (Dual k) = Prod k #endif inl = Dual fst inr = Dual snd f ||| g = Dual (runDual f &&& runDual g) codiag = Dual diag instance CoCartesian k => Cartesian (Dual k) where #ifndef __HADDOCK__ type Prod (Dual k) = Sum k #endif fst = Dual inl snd = Dual inr f &&& g = Dual (runDual f ||| runDual g) diag = Dual codiag instance Monoidal p k => Comonoidal p (Dual k) where coidl = Dual idl coidr = Dual idr instance Comonoidal p k => Monoidal p (Dual k) where idl = Dual coidl idr = Dual coidr instance HasIdentity p k => HasIdentity p (Dual k) #ifndef __HADDOCK__ where type Identity (Dual k) p = Identity k p #endif instance Functor f k k => Functor f (Dual k) (Dual k) where map = Dual . map . runDual instance Full f k k => Full f (Dual k) (Dual k) where premap = Dual . premap . runDual instance Faithful f k k => Faithful f (Dual k) (Dual k) instance Pointed f k => Copointed f (Dual k) where extract = Dual return instance Copointed f k => Pointed f (Dual k) where return = Dual extract instance Monad m k => Comonad m (Dual k) where extend = Dual . bind . runDual duplicate = Dual join instance Comonad w k => Monad w (Dual k) where bind = Dual . extend . runDual join = Dual duplicate instance Adjunction f g k k => Adjunction g f (Dual k) (Dual k) where unit = Dual counit counit = Dual unit leftAdjunct = Dual . rightAdjunct . runDual rightAdjunct = Dual . leftAdjunct . runDual instance CCC k => CoCCC (Dual k) where #ifndef __HADDOCK__ type Coexp (Dual k) = Exp k #endif coapply = Dual apply cocurry = Dual . curry . runDual uncocurry = Dual . uncurry . runDual instance CoCCC k => CCC (Dual k) where #ifndef __HADDOCK__ type Exp (Dual k) = Coexp k #endif apply = Dual coapply curry = Dual . cocurry . runDual uncurry = Dual . uncocurry . runDual instance ( Arrow k #ifndef __HADDOCK__ , Prod k ~ (,) #endif ) => DualArrow (Dual k) where dualarr f = Dual (arr f) instance ( DualArrow k #ifndef __HADDOCK__ , Sum k ~ (,) #endif ) => Arrow (Dual k) where arr f = Dual (dualarr f) liftDualDual :: k a b -> Dual (Dual k) a b liftDualDual = Dual . Dual lowerDualDual :: Dual (Dual k) a b -> k a b lowerDualDual = runDual . runDual instance HasFunctorComposition k => HasFunctorComposition (Dual k) where comp = Dual decomp decomp = Dual comp instance HasBitransform p c d e => HasBitransform p (Dual c) (Dual d) (Dual e) where unbitransform = Dual bitransform bitransform = Dual unbitransform
182aa2196b0fb1ec143fd5d412f5b0e1ec79f239aba5b4b8ed515a7283b637c7
hvdthong/PatchNetTool
lcommon.ml
* This file is part of PatchNet , licensed under the terms of the GPL v2 . * See copyright.txt in the PatchNet source code for more information . * The PatchNet source code can be obtained at * * This file is part of PatchNet, licensed under the terms of the GPL v2. * See copyright.txt in the PatchNet source code for more information. * The PatchNet source code can be obtained at * *) let linux = ref "/dev/shm/linux" let before_linux = "/dev/shm/linux-before" let after_linux = " /mnt / ramdisk / linux - after " let after_linux = "/dev/shm/linux-after" let stable = ref "/dev/shm/linux-stable" let process_output_to_list2 = fun command -> let chan = Unix.open_process_in command in let res = ref ([] : string list) in let rec process_otl_aux () = let e = input_line chan in res := e::!res; process_otl_aux() in try process_otl_aux () with End_of_file -> let stat = Unix.close_process_in chan in (List.rev !res,stat) let cmd_to_list command = let (l,_) = process_output_to_list2 command in l let process_output_to_list = cmd_to_list let cmd_to_list_and_status = process_output_to_list2 let safe_int_of_string key s = try int_of_string s with x -> failwith (Printf.sprintf "%d: ios failure on %s\n" key s) (* from later ocaml *) let is_space = function | ' ' | '\012' | '\n' | '\r' | '\t' -> true | _ -> false let trim s = let len = String.length s in let i = ref 0 in while !i < len && try is_space (String.get s !i) with _ -> false do incr i done; let j = ref (len - 1) in while !j >= !i && try is_space (String.get s !j) with _ -> false do decr j done; if !i = 0 && !j = len - 1 then s else if !j >= !i then String.sub s !i (!j - !i + 1) else "" let cores = ref 4 let chunksize = 1 let tmpdir = ref "/tmp" let union l1 l2 = List.fold_left (fun prev x -> if List.mem x prev then prev else x::prev) l2 l1 type ('a,'b) either = Left of 'a | Right of 'b let hashadd tbl k v = let cell = try Hashtbl.find tbl k with Not_found -> let cell = ref [] in Hashtbl.add tbl k cell; cell in if not (List.mem v !cell) then cell := v :: !cell
null
https://raw.githubusercontent.com/hvdthong/PatchNetTool/24a47115f89a0aab2c458758a89f129670c5de27/preprocessing/lcommon.ml
ocaml
from later ocaml
* This file is part of PatchNet , licensed under the terms of the GPL v2 . * See copyright.txt in the PatchNet source code for more information . * The PatchNet source code can be obtained at * * This file is part of PatchNet, licensed under the terms of the GPL v2. * See copyright.txt in the PatchNet source code for more information. * The PatchNet source code can be obtained at * *) let linux = ref "/dev/shm/linux" let before_linux = "/dev/shm/linux-before" let after_linux = " /mnt / ramdisk / linux - after " let after_linux = "/dev/shm/linux-after" let stable = ref "/dev/shm/linux-stable" let process_output_to_list2 = fun command -> let chan = Unix.open_process_in command in let res = ref ([] : string list) in let rec process_otl_aux () = let e = input_line chan in res := e::!res; process_otl_aux() in try process_otl_aux () with End_of_file -> let stat = Unix.close_process_in chan in (List.rev !res,stat) let cmd_to_list command = let (l,_) = process_output_to_list2 command in l let process_output_to_list = cmd_to_list let cmd_to_list_and_status = process_output_to_list2 let safe_int_of_string key s = try int_of_string s with x -> failwith (Printf.sprintf "%d: ios failure on %s\n" key s) let is_space = function | ' ' | '\012' | '\n' | '\r' | '\t' -> true | _ -> false let trim s = let len = String.length s in let i = ref 0 in while !i < len && try is_space (String.get s !i) with _ -> false do incr i done; let j = ref (len - 1) in while !j >= !i && try is_space (String.get s !j) with _ -> false do decr j done; if !i = 0 && !j = len - 1 then s else if !j >= !i then String.sub s !i (!j - !i + 1) else "" let cores = ref 4 let chunksize = 1 let tmpdir = ref "/tmp" let union l1 l2 = List.fold_left (fun prev x -> if List.mem x prev then prev else x::prev) l2 l1 type ('a,'b) either = Left of 'a | Right of 'b let hashadd tbl k v = let cell = try Hashtbl.find tbl k with Not_found -> let cell = ref [] in Hashtbl.add tbl k cell; cell in if not (List.mem v !cell) then cell := v :: !cell
0ef30d5aadba02ca670d513a07cb5f9a9910e14ca378cd861af32e607d54737b
privet-kitty/cl-competitive
write-double-float.lisp
(defpackage :cp/write-double-float (:use :cl) (:export #:write-double-float)) (in-package :cp/write-double-float) Based on SBCL 's implementation (defun write-double-float (x &key (max-decimal-places 10) (stream *standard-output*) (allow-trailing-point t)) "Writes a double float X to STREAM using a fixed-point expression. MAX-DECIMAL-PLACES is the maximum number of digits after decimal point. (The actual number of output digits can be less than this number, however.) If ALLOW-TRAILING-POINT is false, an expression like `123.' is modified to `123.0'" (declare (optimize (speed 3)) ((integer 0 #.most-positive-fixnum) max-decimal-places) (double-float x)) (if (minusp x) (progn (write-char #\- stream) (when (> x -1d0) (write-char #\0 stream))) (when (< x 1d0) (write-char #\0 stream))) (multiple-value-bind (e string) (sb-impl::flonum-to-digits x) (declare (fixnum e) (simple-base-string string)) (if (plusp e) (let* ((len (length string)) (len-before-. (min len e)) (len-after-. (- (min (+ len-before-. max-decimal-places) len) len-before-.))) (write-string string stream :end len-before-.) (dotimes (i (- e len)) (write-char #\0 stream)) (write-char #\. stream) (write-string string stream :start len-before-. :end (min (+ len-before-. max-decimal-places) len)) (when (and (not allow-trailing-point) (zerop len-after-.)) (write-char #\0 stream))) (let* ((len-0 (min (- e) max-decimal-places)) (len-after-0 (min (length string) (the fixnum (- max-decimal-places len-0))))) (write-char #\. stream) (dotimes (i len-0) (write-char #\0 stream)) (write-string string stream :end len-after-0) (when (and (not allow-trailing-point) (zerop len-after-0)) (write-char #\0 stream))))))
null
https://raw.githubusercontent.com/privet-kitty/cl-competitive/4d1c601ff42b10773a5d0c5989b1234da5bb98b6/module/write-double-float.lisp
lisp
(defpackage :cp/write-double-float (:use :cl) (:export #:write-double-float)) (in-package :cp/write-double-float) Based on SBCL 's implementation (defun write-double-float (x &key (max-decimal-places 10) (stream *standard-output*) (allow-trailing-point t)) "Writes a double float X to STREAM using a fixed-point expression. MAX-DECIMAL-PLACES is the maximum number of digits after decimal point. (The actual number of output digits can be less than this number, however.) If ALLOW-TRAILING-POINT is false, an expression like `123.' is modified to `123.0'" (declare (optimize (speed 3)) ((integer 0 #.most-positive-fixnum) max-decimal-places) (double-float x)) (if (minusp x) (progn (write-char #\- stream) (when (> x -1d0) (write-char #\0 stream))) (when (< x 1d0) (write-char #\0 stream))) (multiple-value-bind (e string) (sb-impl::flonum-to-digits x) (declare (fixnum e) (simple-base-string string)) (if (plusp e) (let* ((len (length string)) (len-before-. (min len e)) (len-after-. (- (min (+ len-before-. max-decimal-places) len) len-before-.))) (write-string string stream :end len-before-.) (dotimes (i (- e len)) (write-char #\0 stream)) (write-char #\. stream) (write-string string stream :start len-before-. :end (min (+ len-before-. max-decimal-places) len)) (when (and (not allow-trailing-point) (zerop len-after-.)) (write-char #\0 stream))) (let* ((len-0 (min (- e) max-decimal-places)) (len-after-0 (min (length string) (the fixnum (- max-decimal-places len-0))))) (write-char #\. stream) (dotimes (i len-0) (write-char #\0 stream)) (write-string string stream :end len-after-0) (when (and (not allow-trailing-point) (zerop len-after-0)) (write-char #\0 stream))))))
19c20c830214b642f4ff860cdbfa9a3bd65578e72cbff38554b4c30c11aa7a74
fukamachi/qlot
dist.lisp
(defpackage #:qlot/distify/dist (:use #:cl) (:import-from #:qlot/source #:source-dist #:source-distribution #:source-distinfo-url #:source-project-name) (:import-from #:qlot/proxy #:*proxy*) (:import-from #:qlot/utils/distify #:get-distinfo-url) (:import-from #:dexador) (:export #:distify-dist)) (in-package #:qlot/distify/dist) (defun distify-dist (source destination &key distinfo-only) (declare (ignore distinfo-only)) (check-type source source-dist) (unless (source-distinfo-url source) (setf (source-distinfo-url source) (get-distinfo-url (source-distribution source) (slot-value source 'qlot/source/dist::%version)))) (let* ((destination (truename destination)) (relative-path ;; distribution name may include slashes ;; and can't be used directly as a name ;; of a pathname. (uiop:parse-unix-namestring (source-project-name source) :type "txt")) (target-path (merge-pathnames relative-path destination))) (ensure-directories-exist target-path) (dex:fetch (source-distinfo-url source) target-path :if-exists :supersede :proxy *proxy*) destination))
null
https://raw.githubusercontent.com/fukamachi/qlot/f4ba8ad6e925e833b2d74373f8645a53736ddb9a/distify/dist.lisp
lisp
distribution name may include slashes and can't be used directly as a name of a pathname.
(defpackage #:qlot/distify/dist (:use #:cl) (:import-from #:qlot/source #:source-dist #:source-distribution #:source-distinfo-url #:source-project-name) (:import-from #:qlot/proxy #:*proxy*) (:import-from #:qlot/utils/distify #:get-distinfo-url) (:import-from #:dexador) (:export #:distify-dist)) (in-package #:qlot/distify/dist) (defun distify-dist (source destination &key distinfo-only) (declare (ignore distinfo-only)) (check-type source source-dist) (unless (source-distinfo-url source) (setf (source-distinfo-url source) (get-distinfo-url (source-distribution source) (slot-value source 'qlot/source/dist::%version)))) (let* ((destination (truename destination)) (relative-path (uiop:parse-unix-namestring (source-project-name source) :type "txt")) (target-path (merge-pathnames relative-path destination))) (ensure-directories-exist target-path) (dex:fetch (source-distinfo-url source) target-path :if-exists :supersede :proxy *proxy*) destination))
aa73691573bc24adfb2748188f05cb2e6af6d2ffc410a7d49113e0770663afc1
cbaggers/cepl
errors.lisp
(in-package :cepl.errors) (deferror gfun-invalid-arg-format () (gfun-name invalid-pair) "CEPL - defun-g: defun-g expects its parameter args to be typed in the~%format (var-name type), but instead ~s was found in the definition for ~s" invalid-pair gfun-name) (deferror gpu-func-spec-not-found () (name types) "CEPL - gpu-func-spec: Could not find spec for the gpu-function named ~s with the in-arg types ~s" name types) (deferror dispatch-called-outside-of-map-g () (name) "Looks like you tried to call the pipeline ~s without using map-g.~%" name) (deferror invalid-keywords-for-shader-gpipe-args () (pipeline-name keys) "Found some invalid keys in the pipeline called ~a:~%~s" pipeline-name keys) (deferror invalid-context-for-assert-gpipe () (context) "CEPL: ~a is an invalid context for asserting whether gpipe args are valid" context) (deferror invalid-context-for-assert-options () (context) "CEPL: ~a is an invalid context for asserting whether pipeline options are valid" context) (deferror invalid-shader-gpipe-form () (pipeline-name valid-forms invalid-forms) "When using defpipeline-g to compose GPU functions, the valid stage specifiers are function literals~%(optionally with keyword stage names).~%~%In the defpipeline-g for ~a ~athese forms were not valid:~%~{~s~%~}~%" pipeline-name (if valid-forms (format nil "these forms were valid:~%~{~s~%~}~%However" valid-forms) "") invalid-forms) (deferror not-enough-args-for-implicit-gpipe-stages () (pipeline-name clauses) "Tried to compile the pipeline ~a; however, there are not enough functions here for a valid pipeline:~%~s" pipeline-name clauses) (deferror invalid-shader-gpipe-stage-keys () (pipeline-name keys) "In the defpipeline-g form for ~s the gpipe args are incorrect.~%~s" pipeline-name (let ((unknown-keys (remove-if (lambda (x) (member x varjo:*stage-names*)) keys))) (if unknown-keys (format nil "The following stages are not supported, or are incorrectly named: ~a" unknown-keys) (format nil "The order of the following stages is incorrect:~%~s~%Valid order of stages is: ~a" keys varjo:*stage-names*)))) (deferror invalid-compose-gpipe-form () (pipeline-name clauses) "In the defpipeline-g for ~s there are some invalid pass clauses.~% ~{~a~%~} A pass clause's first element is the destination; the last element is the call to another CEPL pipeline. The elements between these are optional Lisp forms to run in the context of the destination. Example valid forms: ~%(f0 (blit stream :tex tx)) -- where f0 is an fbo ~%(nil (blit stream :tex tx)) -- nil stands in for the default fbo ~%(f0 (clear) (blit stream :tex tx)) -- where the #'clear is running inside the implicit with-fbo" pipeline-name clauses) (deferror invalid-defpipeline-options () (pipeline-name invalid-options valid-options) "CEPL - defpipeline-g: The defpipeline-g for ~a contained the following invalid options:~%~a~%The valid options to this form of defpipeline-g are:~s" pipeline-name invalid-options valid-options) (deferror shader-pipeline-non-null-args () (pipeline-name) "CEPL - defpipeline-g: In defpipeline-g for ~a. Args are not needed in pipelines composed of g-functions" pipeline-name) (deferror make-tex-no-content-no-type () () "CEPL - make-texture: Trying to make texture, but have no element-type or initial-contents to infer the type from") (deferror make-tex-array-not-match-type () (element-type pixel-format supposed-type array-type) "CEPL - make-texture: Trying to make texture, but the element-type given was ~s which implies an pixel-format of ~s. That pixel-format would require an array element-type of ~s. This conflicts with the array element-type of ~s" element-type pixel-format supposed-type array-type) (deferror make-tex-array-not-match-type2 () (element-type initial-contents) "CEPL - make-texture: Trying to make texture with an element-type of ~s, however, the initial-contents provided do not seem to be compatible:~%~s" element-type initial-contents) (deferror image-format->lisp-type-failed () (type-name) "CEPL - make-texture: to find a conversion from the image-format ~s to a Lisp type" type-name) (deferror lisp-type->image-format-failed () (type-name) "CEPL - make-texture: to find a suitable conversion from the Lisp type ~s to an internal texture format" type-name) (deferror pixel-format->image-format-failed () (type-name) "CEPL - make-texture: to find a suitable conversion from the pixel format ~s to an internal texture format" type-name) (deferror image-format->pixel-format-failed () (type-name) "CEPL - unable to find a suitable conversion from the internal texture format ~s to a pixel format" type-name) (deferror buffer-backed-texture-invalid-args () () "CEPL - make-texture: Buffer-backed textures cannot have mipmaps, multiple layers, or be cube rectangle or multisample") (deferror buffer-backed-texture-invalid-samplers () () "CEPL - make-texture: We do not currently support setting any texture sampling parameters on buffer-backed textures") (deferror buffer-backed-texture-invalid-image-format () (type-name) "CEPL - make-texture: The internal format ~a is invalid for use with buffer-backed-textures" type-name) (deferror buffer-backed-texture-establish-image-format () (type-name) "CEPL - make-texture: Could not establish the correct texture type for a buffer texture: ~a" type-name) (deferror failed-to-test-compile-gpu-func (:error-type warning) (gfunc-name missing-func-names) "CEPL - defun-g: Failed to test compile the gpu function named '~s, as not all dependent functions having been compiled yet. Missing funcs: ~s To disable this warning for all future compilations: (setf cepl.pipelines:*warn-when-cant-test-compile* nil)" gfunc-name missing-func-names) (deferror dont-define-space-to-self () (space) "with-model-space: please dont try redefining the relationship between ~s and itself." space) (deferror index-on-buffer-stream-with-no-gpu-arrays () () "Cepl: Invalid attempt to make buffer-stream with an index array even though there were no gpu-arrays.") (deferror struct-in-glsl-stage-args () (arg-names) "Found arguments to def-glsl-stage which have struct types. Arg names: ~s This is not currently supported by def-glsl-stage" arg-names) (deferror make-gpu-array-from-c-array-mismatched-dimensions () (c-arr-dimensions provided-dimensions) "CEPL: make-gpu-array mismatched dimensions A call to #'make-gpu-array was made with a c-array as the initial-contents. The dimensions of the c-array are ~s; however, the dimensions given in the call to #'make-gpu-array were ~s" c-arr-dimensions provided-dimensions) (deferror symbol-stage-designator () (designator possible-choices) "CEPL: defpipeline-g found a stage that was incorrectly specified. The problematic defintition was: ~s The problem: because of potential overloading, CEPL stages must be fully qualified. ~a" designator (if (= (length possible-choices) 1) (format nil "Instead of ~s please use: ~s" designator (first possible-choices)) (format nil "Instead of ~s please use one of the following:~%~{~s~^~%~}" designator possible-choices))) (deferror symbol-stage-designators () (designator-choice-pairs) "CEPL: defpipeline-g found a stage that was incorrectly specified. The problematic stage designators were: ~{~s ~} The problem: because of potential overloading, CEPL stages must be fully qualified. ~{~%~%~a~}" (mapcar #'first designator-choice-pairs) (loop :for (designator choices) :in designator-choice-pairs :collect (if (= (length choices) 1) (format nil "Instead of ~s, please use: ~s" designator (first choices)) (format nil "Instead of ~s, please use one of the following:~%~{~s~^~%~}" designator choices)))) (deferror stage-not-found () (designator) "CEPL - defpipeline-g: Could not find a gpu-function called ~s. This most likely means it hasn't been compiled yet or that the name is incorrect" designator) (deferror pixel-format-in-bb-texture () (pixel-format) "CEPL: make-texture was making a buffer-backed texture, however a pixel-format was provided. This is invalid, as pixel conversion is not done when uploading data to a buffer-backed texture. Pixel-format: ~s" pixel-format) (deferror glsl-version-conflict () (issue) "CEPL: When trying to compile the pipeline we found some stages which have conflicting glsl version requirements: ~{~s~%~}" issue) (deferror glsl-version-conflict-in-gpu-func () (name context) "CEPL: When trying to compile ~a we found multiple glsl versions. Context: ~a" name context) (deferror delete-multi-func-error () (name choices) "CEPL: When trying to delete the GPU function ~a we found multiple overloads and didn't know which to delete for you. Please try again using one of the following: ~{~s~%~}" name choices) (deferror multi-func-error () (name choices) "CEPL: When trying find the gpu function ~a we found multiple overloads and didn't know which to return for you. Please try again using one of the following: ~{~s~%~}" name choices) (defwarning pull-g-not-cached () (asset-name) "Either ~s is not a pipeline/gpu-function or the code for this asset has not been cached yet" asset-name) (deferror pull*-g-not-enabled () () "CEPL has been set to not cache the results of pipeline compilation. See the *cache-last-compile-result* var for more details") (defwarning func-keyed-pipeline-not-found () (callee func) "CEPL: ~a was called with ~a. When functions are passed to ~a we assume this is a either pipeline function or a gpu-lambda. After checking that is wasnt a gpu-lambda we looked for the details for a matching pipeline. However we didn't find anything. Please note that you cannot lookup non-lambda gpu-functions in this way as, due to overloading, many gpu-functions map to a single function object." callee func callee) (deferror attachments-with-different-sizes (:print-circle nil) (args sizes) "CEPL: Whilst making an fbo we saw that some of the attachments will end up having different dimensions: ~a Whilst this is not an error according to GL it can trip people up because according to the spec: > If the attachment sizes are not all identical, rendering will > be limited to the largest area that can fit in all of the > attachments (an intersection of rectangles having a lower left > of (0 0) and an upper right of (width height) for each attachment). If you want to make an fbo with differing arguments, please call make-fbo with `:matching-dimensions nil` in the arguments e.g. (MAKE-FBO ~{~% ~a~}) " sizes (labels ((ffa (a) (typecase a ((or null keyword) (format nil "~s" a)) ((or list symbol) (format nil "'~s" a)) (otherwise (format nil "~s" a))))) (append (mapcar #'ffa args) '(":MATCHING-DIMENSIONS NIL")))) (deferror invalid-cube-fbo-args () (args) "CEPL: Invalid args for cube-map bound fbo: args: ~s You have passed a cube-map texture without an attachment number; this means you want the fbo to have 6 color attachments which are bound to the faces of the cube texture. Whilst using this feature, the only other legal argument is depth attachment info. " args) (deferror functions-in-non-uniform-args () (name) " CEPL: We currently only support functions as uniform arguments. Pipeline: ~s" name) (deferror mapping-over-partial-pipeline () (name args) "CEPL: This pipeline named ~s is a partial pipeline. This is because the following uniform arguments take functions: ~{~%~s~} As OpenGL does not itself support passing functions as values you must use bake-uniforms to create set the uniforms above. This will generate a 'complete' pipeline which you can then map-g over. " name args) (deferror fbo-target-not-valid-constant () (target) "CEPL: with-fbo-bound form found with invalid target The target must be constant and must be one of the following: - :framebuffer - :read-framebuffer - :draw-framebuffer In this case the compile-time value of 'target' was: ~a " target) (deferror bake-invalid-pipeling-arg () (invalid-arg) "CEPL: The pipeline argument to #'bake was expected to be a pipeline name or pipeline function object. Instead we found: ~s" invalid-arg) (deferror bake-invalid-uniform-name () (proposed invalid) "CEPL: An attempt to bake some uniforms in a pipeline has failed. The arguments to be baked were: ~{~s ~s~^~%~} However the following uniforms were not found in the pipeline: ~{~s~^ ~}" proposed invalid) (deferror bake-uniform-invalid-values (:print-circle nil) (proposed invalid) "CEPL: An attempt to bake some uniforms in a pipeline has failed. The arguments to be baked were: ~{~s ~s~^~%~} However the following values are ~a, they are not representable in shaders. ~{~s~^ ~} Might you have meant to specify a gpu function?" proposed (cond ((every #'symbolp invalid) "symbols") ((every #'listp invalid) "lists") (t "invalid")) invalid) (deferror partial-lambda-pipeline (:print-circle nil) (partial-stages) "CEPL: pipeline-g was called with at least one stage taking functions as uniform arguments. If this were defpipeline-g we would make a partial pipeline however we don't currently support partial lambda pipelines. Sorry for the inconvenience. It is a feature we are interested in adding so if this is causing you issues please reach out to us on Github. The problem stages were: ~{~%~s~}" partial-stages) (deferror glsl-geom-stage-no-out-layout (:print-circle nil) (glsl-body) "CEPL: def-glsl-stage was asked to make a geometry stage however it could not find a valid 'out' layout declaration. These lines look something like this: layout(<primitive-name>, max_vertices=20) out; Where <primitive-name> is one of points, line_strip or triangle_strip and max_vertices is any integer. Here is the block of glsl we search in: ~a" glsl-body) (deferror invalid-inline-glsl-stage-arg-layout (:print-circle nil) (name arg) "CEPL: Invalid arg layout found in ~a. The correct layout for a argument to a glsl-stage is (\"string-name-of-arg\" arg-type ,@keyword-qualifiers) Problematic arg was: ~a" name arg) (deferror adjust-gpu-array-mismatched-dimensions () (current-dim new-dim) "CEPL: adjust-gpu-array cannot currently change the number of dimensions in a gpu-array. current dimensions: ~a proposed new dimensions: ~a If working around this limitation proves to be too difficult please report it on github so we can re-evaluate this limitation." current-dim new-dim) (deferror adjust-gpu-array-shared-buffer () (array shared-count) "CEPL: adjust-gpu-array cannot currently adjust the size of gpu-array which is sharing a gpu-buffer with other gpu-arrays. Array: ~a is sharing a gpu buffer with ~a other gpu-arrays" array shared-count) (deferror buffer-stream-has-invalid-primitive-for-stream () (name pline-prim stream-prim) "CEPL: The buffer-stream passed to ~a contains ~s, however ~a was expecting ~s. You can either change the type of primitives the pipeline was expecting e.g: (defpipeline-g ~s (~s) ..) Or you can create a stream with containing ~a e.g: (make-buffer-stream gpu-array :draw-mode ~s) It is also worth noting that it is possible to pass triangles to a pipeline declared to take (:patch 3), to pass lines to pipelines declared to take (:patch 2) and points to pipelines taking (:patch 1)" name stream-prim name pline-prim name stream-prim pline-prim pline-prim) (deferror invalid-options-for-texture () (buffer-storage cubes dimensions layer-count mipmap multisample rectangle) "CEPL: We could not establish the correct texture type for the following combination of options: buffer-storage - ~a cubes - ~a dimensions - ~a layer-count - ~a mipmap - ~a multisample - ~a rectangle - ~a If the GL spec says this is valid then we are sorry for the mistake. If you have the time please report the issue here: " buffer-storage cubes dimensions layer-count mipmap multisample rectangle) (deferror gpu-func-symbol-name () (name alternatives env) "CEPL: We were asked to find the gpu function named ~a. Now we did find ~a however as gpu-functions can be overloaded we now require that you specify the types along with the name. This is slightly more annoying when there is only one match, however it eliminates the ambiguity that occurs as soon as someone does overload the gpu-function. Here are the possible names for this function: ~{~a~} ~@[ You may pick a implementation to use this time but, as this will not update your code, you will get this error on the next compile unless it is fixed~]" name (if (> (length alternatives) 1) "matches" "a match") alternatives (not (null env))) (deferror gl-context-initialized-from-incorrect-thread () (ctx-thread init-thread) "CEPL: This CEPL context is tied to thread A (shown below) however something tried to create the gl-context from thread B: A: ~a B: ~a" ctx-thread init-thread) (deferror shared-context-created-from-incorrect-thread () (ctx-thread init-thread) "CEPL: This CEPL context is tied to thread A (shown below) however something tried to create a shared CEPL context using it from thread B: A: ~a B: ~a" ctx-thread init-thread) (deferror tried-to-make-context-on-thread-that-already-has-one () (context thread) "CEPL: An attempt was made to create a context on thread ~a however that thread already has the CEPL context ~a. In CEPL you may only have 1 CEPL context per thread. That context then holds the handles to any GL contexts and any caching related to those gl contexts" thread context) (deferror max-context-count-reached () (max) "CEPL: Currently CEPL has a silly restriction on the number of contexts that can be active at once. The current maximum is max. It's silly in that GL itself doesnt have this restriction and it was only introduced in CEPL to make the implementation of multi-threading simpler. This restriction does need to be removed however so if you are hitting this then please report it at . This lets us know that this is causing real issues for people and we can prioritize it accordingingly.") (deferror nested-with-transform-feedback () () "CEPL: Detected a nested with-transform-feedback form. Currently this is not supported however in future it may be possible to support on GLv4 and up.") (deferror non-consecutive-feedback-groups () (groups) "CEPL: Currently when you specify transform-feedback groups their numbers must be consecutive and there must be at least one value being written to :feedback or (:feedback 0). We hope to be able to relax this in future when we support more recent GL features, however even then if you want maximum compatibility this will remain a good rule to follow. These were the groups in question: ~s" groups) (deferror mixed-pipelines-in-with-tb () () "CEPL: Different pipelines have been called within same tfs block") (deferror incorrect-number-of-arrays-in-tfs () (tfs tfs-count count) "CEPL: The transform feedback stream currently bound has ~a arrays bound, however the current pipeline is expecting to write into ~a ~a. The stream in question was:~%~a" tfs-count count (if (= count 1) "array" "arrays") tfs) (deferror invalid-args-in-make-tfs () (args) "CEPL: make-transform-feedback-stream was called with some arguments that are not buffer-backed gpu-arrays:~{~%~s~}" args) (deferror invalid-sizes-in-make-tfs () (args) "CEPL: Some of the gpu-arrays passed to make tfs have sizes which are not multiples of 4, GL does not allow this:~{~%~s~}" args) (defwarning tfs-setf-arrays-whilst-bound () () "CEPL: There was an attempt to setf the arrays attached to the transform-feedback-stream whilst it is bound inside with-transform-feedback. It is not possible to make these changes whilst in the block so we will apply them at the end of with-transform-feedback's scope") (deferror one-stage-non-explicit () () "CEPL: When defining a pipeline with only 1 stage you need to explicitly mark what stage it is as CEPL is unable to infer this. For example: (defpipeline-g some-pipeline () :vertex (some-stage :vec4))") (deferror invalid-stage-for-single-stage-pipeline () (kind) "CEPL: We found a pipeline where the only stage was of type ~a. Single stage pipelines are valid in CEPL however only if the stage is a vertex, fragment or compute stage" kind) (deferror pipeline-recompile-in-tfb-scope () (name) "CEPL: We were about to recompile the GL program behind ~a however we noticed that this is happening inside the scope of with-transform-feedback which GL does not allow. Sorry about that." name) (deferror compile-g-missing-requested-feature () (form) "CEPL: Sorry currently compile-g can only be used to make gpu lambdas by passing nil as the name and the source for the lambda like this: (lambda-g ((vert :vec4) &uniform (factor :float)) (* vert factor)) We received: ~a " form) (deferror query-is-already-active () (query) "CEPL: An attempt was made to start querying using the query object listed below, however that query object is currently in use. query: ~s" query) (deferror query-is-active-bug () (query) "CEPL BUG: This error should never be hit as it should have been covered by another assert inside #'begin-gpu-query. we are sorry for the mistake. If you have the time please report the issue here: query: ~s" query) (deferror another-query-is-active () (query current) "CEPL: An attempt was made to begin querying with query object 'A' listed below however query object 'B' of the same kind was already active on this context. GL only allows 1 query of this kind to be active at a given time. Query A: ~s Query B: ~s" query current) (deferror query-not-active () (query) "CEPL: A call was made to #'end-gpu-query with the query object listed below. The issue is that the query object is not currently active so it is not valid to try and make it inactive. Query: ~s" query) (deferror compute-pipeline-must-be-single-stage () (name stages) "CEPL: A attempt was made to compile ~a which contains the following stage kinds: ~a However if you include a compute stage it is the only stage allowed in the pipeline. Please either remove the compute stage or remove the other stages." (if name name "a pipeline") stages) (deferror could-not-layout-type () (type) "CEPL BUG: We were unable to work out the layout for the type ~a We are sorry for the mistake. If you have the time please report the issue here: (if you are able to include the definition of the type in the issue report that we be excedingly helpful)" type) (deferror invalid-data-layout-specifier () (specifier valid-specifiers) "CEPL: ~a is not a valid layout data specifier. Please use one of the following: ~{~a~^, ~}" specifier valid-specifiers) (deferror invalid-layout-for-inargs () (name type-name layout) "CEPL: ~a is not a valid type for ~a's input arguments as it has the layout ~a. ~a can only be used for uniforms marked as :ubo or :ssbo." type-name (or name "this lambda pipeline") layout type-name) (deferror invalid-layout-for-uniform () (name type-name layout func-p) "CEPL: ~a is not a valid type for ~a's uniform argument as it has the layout ~a. std-140 & std-430 layouts are only valid for ubo & ssbo uniforms." type-name (or name (if func-p "this gpu-lambda" "this lambda pipeline")) layout) (deferror c-array-total-size-type-error () (size required-type) "CEPL: c-array's total size must be of type c-array-index, also known as ~a. Total size found was ~a" (upgraded-array-element-type required-type) size) (deferror state-restore-limitation-transform-feedback () () "CEPL: State restoring currently cannot be used from within the dynamic scope of a transform feedback") (deferror state-restore-limitation-blending () () "CEPL: State restoring currently cannot be used from within the dynamic scope of with-blending (may have been introduced by with-fbo-bound)") (deferror state-restore-limitation-queries () () "CEPL: State restoring currently cannot be used from within the dynamic scope of with-blending (may have been introduced by with-fbo-bound)") (deferror fbo-binding-missing () (kind current-surface) "CEPL: FBO ~a bindings missing from context. ~a" (string-downcase (string kind)) (if current-surface "" "This is probably due to there being no surface current on this context")) (deferror texture-dimensions-lequal-zero () (dimensions) "CEPL: Found an request to make a texture where at least one of the dimensions were less than or equal to zero. Dimensions: ~a" dimensions) (deferror unknown-symbols-in-pipeline-context () (name full issue for) " CEPL: Found something we didnt recognise in the context of ~a Problematic symbol/s: ~{~s~^, ~} Full context: ~s The pipeline context must contain: The symbol :static at most once and.. ..0 or more of the following glsl versions:~{~%- :~a~} and at most 1 primitive from: - :dynamic - :points - :lines - :iso-lines - :line-loop - :line-strip - :lines-adjacency - :line-strip-adjacency - :triangles - :triangle-fan - :triangle-strip - :triangles-adjacency - :triangle-strip-adjacency - (:patch <patch length>) " (ecase for (:function (if name (format nil "the gpu-function named ~a." name) (format nil "a gpu-lambda."))) (:pipeline (if name (format nil "the pipeline named ~a." name) (format nil "a lambda pipeline."))) (:glsl-stage (if name (format nil "the glsl stage named ~a." name) (format nil "a glsl stage.")))) ;; this one should never happend issue full varjo:*supported-versions*) (deferror stage-in-context-only-valid-for-glsl-stages () (name) " ~a had a stage declaration in it's `compile-context` list this is only valid for gpu-functions & glsl stages. " (if name (format nil "The pipeline named ~a" name) "A lambda pipeline")) (deferror unknown-stage-kind () (stage) " Unknown stage kind '~a' Valid stage kinds are:~{~%- ~s~}" stage varjo:*stage-names*) (deferror stage-not-valid-for-function-restriction () (name stage func-stage) " When compiling ~a we found that the function being used as the ~a stage has a restriction that means it is only valid to be used as a ~a stage. " (or name "a lambda pipeline") stage func-stage) (deferror gl-version-too-low-for-empty-fbos () (version) " We found a valid attempt to create an empty fbo, however these are only supported in GL versions 4.3 and above. Current version: ~a " version) (deferror invalid-attachments-for-empty-fbo () (args) " When defining an empty fbo there can be 0 or 1 attachment declarations. When present it's name must be NIL. For example: - `(make-fbo '(nil :dimensions (1024 1024)))` - `(make-fbo '(nil))` - `(make-fbo)` You may also optionally specify the following parameters as you would in `make-texture`: - :dimensions - :layer-count - :samples - :fixed-sample-locations The empty fbo can be 1 or 2 dimensional In this case we were passed the following declarations:~{~%- ~s~} " args) (deferror invalid-empty-fbo-declaration () (decl) " When defining an empty fbo there can only be 1 attachment declaration, it's name must be NIL, and dimensions must be specified. For example: `(make-fbo '(nil :dimensions (1024 1024))` Dimensions can be 1 or 2 dimensional You may also optionally specify the following parameters as you would in `make-texture`: - :layer-count - :samples - :fixed-sample-locations In this case we were passed the following declaration:~%- ~s " decl) (deferror quote-symbol-found-in-fbo-dimensions () (form) " During creation of an fbo we found the quote symbol in the 'dimensions' portion of the attachment form. As the attachment form was already quoted this is unnecessary. Form: ~s " form) (deferror attachment-viewport-empty-fbo () (fbo attachment) " `T` cannot be used as a attachment-name. It is only allowed in `with-fbo-viewport` & `with-fbo-bound`'s 'attachment-for-size' parameter and only if the fbo being bound is empty. Likewise, when trying to use the above (and only the above) on an empty fbo, the attachment name *must* be 'T'. FBO Found: ~a Attachment: ~a " fbo attachment) (deferror invalid-fbo-args () (args) " ") (deferror invalid-sampler-wrap-value () (sampler value) " CEPL: Invalid value provided for 'wrap' of sampler: Sampler: ~a Value: ~s The value must be one of the following - :repeat - :mirrored-repeat - :clamp-to-edge - :clamp-to-border - :mirror-clamp-to-edge or a vector of 3 of the above keywords. " sampler value) (deferror make-gpu-buffer-from-id-clashing-keys () (args) " CEPL: When calling make-gpu-buffer-from-id you can pass in either initial-contents or layout, but not both. Args: ~s " args) (deferror invalid-gpu-buffer-layout () (layout) " CEPL: When calling make-gpu-buffer-from-id and passing in layouts, each layout must be either: - A positive integer representing a size in bytes - A list contain both :dimensions and :element-type &key arguments. e.g. - 512 - '(:dimensions (10 20) :element-type :uint8) layout: ~s " layout) (deferror invalid-gpu-arrays-layout () (layout) " CEPL: When calling make-gpu-arrays-from-buffer-id each layout must be a list containing both :dimensions and :element-type &key arguments. e.g. - '(:dimensions (10 20) :element-type :uint8) layout: ~s " layout) (deferror gpu-array-from-id-missing-args () (element-type dimensions) " CEPL: When calling make-gpu-array-from-buffer-id element-type and dimensions as mandatory. element-type: ~s dimensions: ~s " element-type dimensions) (deferror gpu-array-from-buffer-missing-args () (element-type dimensions) " CEPL: When calling make-gpu-array-from-buffer element-type and dimensions as mandatory. element-type: ~s dimensions: ~s " element-type dimensions) (deferror quote-in-buffer-layout () (layout) " CEPL: The symbol 'quote' was found in the gpu-buffer layout, making the layout list invalid. This was probably a typo. layout: ~s " layout) (deferror make-arrays-layout-mismatch () (current-sizes requested-sizes) " CEPL: When settting make-gpu-array-from-buffer's :keep-data argument to T you are requesting that the arrays are made using the existing contents of the buffer. However, in this case the byte size of the requested gpu arrays would not fit in the current available sections of the gpu-buffer. Current Section Sizes: ~a Requested gpu-array sizes: ~a " current-sizes requested-sizes) (deferror make-arrays-layout-count-mismatch () (current-count layouts) " CEPL: When settting make-gpu-array-from-buffer's :keep-data argument to T you are requesting that the arrays are made using the existing contents of the buffer. However, in this case the number of layouts provided (~s) does not match the number of sections in the gpu-buffer (~s). Layouts: ~s " (length layouts) current-count layouts) (deferror cannot-keep-data-when-uploading () (data) " CEPL: When calling make-gpu-buffer-from-id with keep-data it is not valid to pass initial-contents. The reason is that we would be required to upload the data in those c-arrays, which means we would not be keeping our promise to 'keep-data'. keep-data can be used when passing layouts instead of initial-contents as there we are just replacing CEPL's understanding of the layout of data in the buffer, without changing what is actually there. initial-contents provided: ~s " data) (deferror invalid-stream-layout () (layout) " CEPL: When calling make-buffer-stream-from-id-and-layouts each layout must be a list containing both :dimensions and :element-type &key arguments. e.g. - '(:dimensions (500) :element-type :vec3) layout: ~s " layout) (deferror index-on-buffer-stream-with-no-gpu-layouts () () " CEPL: Invalid attempt to make buffer-stream with an index layout even though there were no data layouts.") (deferror cannot-extract-stream-length-from-layouts () (layouts) " CEPL: We were unable to compute a suitable length for the buffer-stream as at least one of the data-layouts had an unknown length and there was no index-layout for us to take into account layouts: ~s" layouts) (deferror index-layout-with-unknown-length () (layout) " CEPL: When make-buffer-stream-from-id-and-layouts is called and an index layout is provided, it may not have '?' as the dimensions. layout: ~s" layout) (deferror inconsistent-struct-layout () (name target slots) " CEPL: the attempt to define the gpu-structs named ~a failed as, whilst it was defined to have a ~a layout, the following slots had different layouts: ~{~%- ~a~} " name target slots) (deferror not-a-gpu-lambda () (thing) "CEPL: ~a does not appear to be a gpu-lambda" thing) (deferror bad-c-array-element () (incorrect-type correct-type elem initial-contents extra-info-string) " CEPL: The first element in the initial-contents to the array being created is a ~a, this is not valid for an array of ~a First Value: ~s Initial-Contents: ~s~@[~%~%~a~]" incorrect-type correct-type elem initial-contents extra-info-string) (deferror no-named-stages () (stages) " CEPL: Small issue in a pipeline definition. Only a pipeline with 2 stages can be implicitly named, others must have explicit named stages. In this case we received the following for the stages: ~{~s~%~} Each of these stages will need to be named with one each of the following: ~{~%- ~a~}" stages varjo.api:*stage-names*) (deferror bad-type-for-buffer-stream-data () (type) " CEPL: ~s is not a type we can use for the data passed to the shader in a buffer-stream or vao as glsl does not directly support that type.~@[~%~%~a~]" type (when (find type '(:short :ushort :signed-short :unsigned-short)) "Perhaps this was meant to be used as the index?")) (deferror fbo-missing-outputs () (missing fbo) "CEPL - with-outputs-to-attachment~s: The current fbo does not have the following color attachments: ~{~a~^, ~} Fbo: ~a" (if (= (length missing) 1) "" "s") missing fbo) (deferror pipeline-invalid-null-stage () (name args) "CEPL - An attempt was found to make a pipeline which explicitly used nil as the stage designator. This is only valid for :fragment stages where you still want to write to the depth buffer Pipeline name: ~a Arguments given: ~s" (or name "<lambda pipeline>") args) (deferror invalid-gpu-function-args () (name unknown-key-arguments invalid-syntax constant-names incorrectly-typed-args) " CEPL - Invalid arguments found in lambda list for ~a~@[ ~s~] ~@[~%The following items are not valid lamda-list keywords:~{~%- ~s~}~%The valid keywords are :&uniform, :&context and :&shared~]~@[~%~%Invalid syntax found in the following arguments, each element must be a list of~%the format (name type &rest qualifiers):~{~%- ~s~}~]~@[~%~%The following symbols are already defined as constants and so cannot be~%used as argument names: ~{~s~^, ~}~]~@[~%~%The following args have types we didnt recognise:~%~{> ~s~}~]~@[~%~%Here are some types we think may have been meant: ~{~a~}~] " (if name "the gpu-function named" "a gpu-lambda") name unknown-key-arguments invalid-syntax constant-names incorrectly-typed-args (loop :for (name type) :in incorrectly-typed-args :for suggestion := (varjo.internals::find-alternative-types-for-spec type) :when suggestion :collect (format nil "~%> ~s~{~%~s~}" name suggestion))) Please remember the following 2 things ;; ;; - add your condition's name to the package export ;; - keep this comment at the bottom of the file. ;; ;; Thanks :)
null
https://raw.githubusercontent.com/cbaggers/cepl/d1a10b6c8f4cedc07493bf06aef3a56c7b6f8d5b/core/errors.lisp
lisp
the last element is the call however, the dimensions given in the this this one should never happend - add your condition's name to the package export - keep this comment at the bottom of the file. Thanks :)
(in-package :cepl.errors) (deferror gfun-invalid-arg-format () (gfun-name invalid-pair) "CEPL - defun-g: defun-g expects its parameter args to be typed in the~%format (var-name type), but instead ~s was found in the definition for ~s" invalid-pair gfun-name) (deferror gpu-func-spec-not-found () (name types) "CEPL - gpu-func-spec: Could not find spec for the gpu-function named ~s with the in-arg types ~s" name types) (deferror dispatch-called-outside-of-map-g () (name) "Looks like you tried to call the pipeline ~s without using map-g.~%" name) (deferror invalid-keywords-for-shader-gpipe-args () (pipeline-name keys) "Found some invalid keys in the pipeline called ~a:~%~s" pipeline-name keys) (deferror invalid-context-for-assert-gpipe () (context) "CEPL: ~a is an invalid context for asserting whether gpipe args are valid" context) (deferror invalid-context-for-assert-options () (context) "CEPL: ~a is an invalid context for asserting whether pipeline options are valid" context) (deferror invalid-shader-gpipe-form () (pipeline-name valid-forms invalid-forms) "When using defpipeline-g to compose GPU functions, the valid stage specifiers are function literals~%(optionally with keyword stage names).~%~%In the defpipeline-g for ~a ~athese forms were not valid:~%~{~s~%~}~%" pipeline-name (if valid-forms (format nil "these forms were valid:~%~{~s~%~}~%However" valid-forms) "") invalid-forms) (deferror not-enough-args-for-implicit-gpipe-stages () (pipeline-name clauses) "Tried to compile the pipeline ~a; however, there are not enough functions here for a valid pipeline:~%~s" pipeline-name clauses) (deferror invalid-shader-gpipe-stage-keys () (pipeline-name keys) "In the defpipeline-g form for ~s the gpipe args are incorrect.~%~s" pipeline-name (let ((unknown-keys (remove-if (lambda (x) (member x varjo:*stage-names*)) keys))) (if unknown-keys (format nil "The following stages are not supported, or are incorrectly named: ~a" unknown-keys) (format nil "The order of the following stages is incorrect:~%~s~%Valid order of stages is: ~a" keys varjo:*stage-names*)))) (deferror invalid-compose-gpipe-form () (pipeline-name clauses) "In the defpipeline-g for ~s there are some invalid pass clauses.~% ~{~a~%~} to another CEPL pipeline. The elements between these are optional Lisp forms to run in the context of the destination. Example valid forms: ~%(f0 (blit stream :tex tx)) -- where f0 is an fbo ~%(nil (blit stream :tex tx)) -- nil stands in for the default fbo ~%(f0 (clear) (blit stream :tex tx)) -- where the #'clear is running inside the implicit with-fbo" pipeline-name clauses) (deferror invalid-defpipeline-options () (pipeline-name invalid-options valid-options) "CEPL - defpipeline-g: The defpipeline-g for ~a contained the following invalid options:~%~a~%The valid options to this form of defpipeline-g are:~s" pipeline-name invalid-options valid-options) (deferror shader-pipeline-non-null-args () (pipeline-name) "CEPL - defpipeline-g: In defpipeline-g for ~a. Args are not needed in pipelines composed of g-functions" pipeline-name) (deferror make-tex-no-content-no-type () () "CEPL - make-texture: Trying to make texture, but have no element-type or initial-contents to infer the type from") (deferror make-tex-array-not-match-type () (element-type pixel-format supposed-type array-type) "CEPL - make-texture: Trying to make texture, but the element-type given was ~s which implies an pixel-format of ~s. That pixel-format would require an array element-type of ~s. This conflicts with the array element-type of ~s" element-type pixel-format supposed-type array-type) (deferror make-tex-array-not-match-type2 () (element-type initial-contents) "CEPL - make-texture: Trying to make texture with an element-type of ~s, however, the initial-contents provided do not seem to be compatible:~%~s" element-type initial-contents) (deferror image-format->lisp-type-failed () (type-name) "CEPL - make-texture: to find a conversion from the image-format ~s to a Lisp type" type-name) (deferror lisp-type->image-format-failed () (type-name) "CEPL - make-texture: to find a suitable conversion from the Lisp type ~s to an internal texture format" type-name) (deferror pixel-format->image-format-failed () (type-name) "CEPL - make-texture: to find a suitable conversion from the pixel format ~s to an internal texture format" type-name) (deferror image-format->pixel-format-failed () (type-name) "CEPL - unable to find a suitable conversion from the internal texture format ~s to a pixel format" type-name) (deferror buffer-backed-texture-invalid-args () () "CEPL - make-texture: Buffer-backed textures cannot have mipmaps, multiple layers, or be cube rectangle or multisample") (deferror buffer-backed-texture-invalid-samplers () () "CEPL - make-texture: We do not currently support setting any texture sampling parameters on buffer-backed textures") (deferror buffer-backed-texture-invalid-image-format () (type-name) "CEPL - make-texture: The internal format ~a is invalid for use with buffer-backed-textures" type-name) (deferror buffer-backed-texture-establish-image-format () (type-name) "CEPL - make-texture: Could not establish the correct texture type for a buffer texture: ~a" type-name) (deferror failed-to-test-compile-gpu-func (:error-type warning) (gfunc-name missing-func-names) "CEPL - defun-g: Failed to test compile the gpu function named '~s, as not all dependent functions having been compiled yet. Missing funcs: ~s To disable this warning for all future compilations: (setf cepl.pipelines:*warn-when-cant-test-compile* nil)" gfunc-name missing-func-names) (deferror dont-define-space-to-self () (space) "with-model-space: please dont try redefining the relationship between ~s and itself." space) (deferror index-on-buffer-stream-with-no-gpu-arrays () () "Cepl: Invalid attempt to make buffer-stream with an index array even though there were no gpu-arrays.") (deferror struct-in-glsl-stage-args () (arg-names) "Found arguments to def-glsl-stage which have struct types. Arg names: ~s This is not currently supported by def-glsl-stage" arg-names) (deferror make-gpu-array-from-c-array-mismatched-dimensions () (c-arr-dimensions provided-dimensions) "CEPL: make-gpu-array mismatched dimensions A call to #'make-gpu-array was made with a c-array as the initial-contents. call to #'make-gpu-array were ~s" c-arr-dimensions provided-dimensions) (deferror symbol-stage-designator () (designator possible-choices) "CEPL: defpipeline-g found a stage that was incorrectly specified. The problematic defintition was: ~s The problem: because of potential overloading, CEPL stages must be fully qualified. ~a" designator (if (= (length possible-choices) 1) (format nil "Instead of ~s please use: ~s" designator (first possible-choices)) (format nil "Instead of ~s please use one of the following:~%~{~s~^~%~}" designator possible-choices))) (deferror symbol-stage-designators () (designator-choice-pairs) "CEPL: defpipeline-g found a stage that was incorrectly specified. The problematic stage designators were: ~{~s ~} The problem: because of potential overloading, CEPL stages must be fully qualified. ~{~%~%~a~}" (mapcar #'first designator-choice-pairs) (loop :for (designator choices) :in designator-choice-pairs :collect (if (= (length choices) 1) (format nil "Instead of ~s, please use: ~s" designator (first choices)) (format nil "Instead of ~s, please use one of the following:~%~{~s~^~%~}" designator choices)))) (deferror stage-not-found () (designator) "CEPL - defpipeline-g: Could not find a gpu-function called ~s. This most likely means it hasn't been compiled yet or that the name is incorrect" designator) (deferror pixel-format-in-bb-texture () (pixel-format) "CEPL: make-texture was making a buffer-backed texture, however a pixel-format was provided. This is invalid, as pixel conversion is not done when uploading data to a buffer-backed texture. Pixel-format: ~s" pixel-format) (deferror glsl-version-conflict () (issue) "CEPL: When trying to compile the pipeline we found some stages which have conflicting glsl version requirements: ~{~s~%~}" issue) (deferror glsl-version-conflict-in-gpu-func () (name context) "CEPL: When trying to compile ~a we found multiple glsl versions. Context: ~a" name context) (deferror delete-multi-func-error () (name choices) "CEPL: When trying to delete the GPU function ~a we found multiple overloads and didn't know which to delete for you. Please try again using one of the following: ~{~s~%~}" name choices) (deferror multi-func-error () (name choices) "CEPL: When trying find the gpu function ~a we found multiple overloads and didn't know which to return for you. Please try again using one of the following: ~{~s~%~}" name choices) (defwarning pull-g-not-cached () (asset-name) "Either ~s is not a pipeline/gpu-function or the code for this asset has not been cached yet" asset-name) (deferror pull*-g-not-enabled () () "CEPL has been set to not cache the results of pipeline compilation. See the *cache-last-compile-result* var for more details") (defwarning func-keyed-pipeline-not-found () (callee func) "CEPL: ~a was called with ~a. When functions are passed to ~a we assume this is a either pipeline function or a gpu-lambda. After checking that is wasnt a gpu-lambda we looked for the details for a matching pipeline. However we didn't find anything. Please note that you cannot lookup non-lambda gpu-functions in this way as, due to overloading, many gpu-functions map to a single function object." callee func callee) (deferror attachments-with-different-sizes (:print-circle nil) (args sizes) "CEPL: Whilst making an fbo we saw that some of the attachments will end up having different dimensions: ~a Whilst this is not an error according to GL it can trip people up because according to the spec: > If the attachment sizes are not all identical, rendering will > be limited to the largest area that can fit in all of the > attachments (an intersection of rectangles having a lower left > of (0 0) and an upper right of (width height) for each attachment). If you want to make an fbo with differing arguments, please call make-fbo with `:matching-dimensions nil` in the arguments e.g. (MAKE-FBO ~{~% ~a~}) " sizes (labels ((ffa (a) (typecase a ((or null keyword) (format nil "~s" a)) ((or list symbol) (format nil "'~s" a)) (otherwise (format nil "~s" a))))) (append (mapcar #'ffa args) '(":MATCHING-DIMENSIONS NIL")))) (deferror invalid-cube-fbo-args () (args) "CEPL: Invalid args for cube-map bound fbo: args: ~s means you want the fbo to have 6 color attachments which are bound to the faces of the cube texture. Whilst using this feature, the only other legal argument is depth attachment info. " args) (deferror functions-in-non-uniform-args () (name) " CEPL: We currently only support functions as uniform arguments. Pipeline: ~s" name) (deferror mapping-over-partial-pipeline () (name args) "CEPL: This pipeline named ~s is a partial pipeline. This is because the following uniform arguments take functions: ~{~%~s~} As OpenGL does not itself support passing functions as values you must use bake-uniforms to create set the uniforms above. This will generate a 'complete' pipeline which you can then map-g over. " name args) (deferror fbo-target-not-valid-constant () (target) "CEPL: with-fbo-bound form found with invalid target The target must be constant and must be one of the following: - :framebuffer - :read-framebuffer - :draw-framebuffer In this case the compile-time value of 'target' was: ~a " target) (deferror bake-invalid-pipeling-arg () (invalid-arg) "CEPL: The pipeline argument to #'bake was expected to be a pipeline name or pipeline function object. Instead we found: ~s" invalid-arg) (deferror bake-invalid-uniform-name () (proposed invalid) "CEPL: An attempt to bake some uniforms in a pipeline has failed. The arguments to be baked were: ~{~s ~s~^~%~} However the following uniforms were not found in the pipeline: ~{~s~^ ~}" proposed invalid) (deferror bake-uniform-invalid-values (:print-circle nil) (proposed invalid) "CEPL: An attempt to bake some uniforms in a pipeline has failed. The arguments to be baked were: ~{~s ~s~^~%~} However the following values are ~a, they are not representable in shaders. ~{~s~^ ~} Might you have meant to specify a gpu function?" proposed (cond ((every #'symbolp invalid) "symbols") ((every #'listp invalid) "lists") (t "invalid")) invalid) (deferror partial-lambda-pipeline (:print-circle nil) (partial-stages) "CEPL: pipeline-g was called with at least one stage taking functions as uniform arguments. If this were defpipeline-g we would make a partial pipeline however we don't currently support partial lambda pipelines. Sorry for the inconvenience. It is a feature we are interested in adding so if this is causing you issues please reach out to us on Github. The problem stages were: ~{~%~s~}" partial-stages) (deferror glsl-geom-stage-no-out-layout (:print-circle nil) (glsl-body) "CEPL: def-glsl-stage was asked to make a geometry stage however it could not find a valid 'out' layout declaration. These lines look something like this: Where <primitive-name> is one of points, line_strip or triangle_strip and max_vertices is any integer. Here is the block of glsl we search in: ~a" glsl-body) (deferror invalid-inline-glsl-stage-arg-layout (:print-circle nil) (name arg) "CEPL: Invalid arg layout found in ~a. The correct layout for a argument to a glsl-stage is (\"string-name-of-arg\" arg-type ,@keyword-qualifiers) Problematic arg was: ~a" name arg) (deferror adjust-gpu-array-mismatched-dimensions () (current-dim new-dim) "CEPL: adjust-gpu-array cannot currently change the number of dimensions in a gpu-array. current dimensions: ~a proposed new dimensions: ~a If working around this limitation proves to be too difficult please report it on github so we can re-evaluate this limitation." current-dim new-dim) (deferror adjust-gpu-array-shared-buffer () (array shared-count) "CEPL: adjust-gpu-array cannot currently adjust the size of gpu-array which is sharing a gpu-buffer with other gpu-arrays. Array: ~a is sharing a gpu buffer with ~a other gpu-arrays" array shared-count) (deferror buffer-stream-has-invalid-primitive-for-stream () (name pline-prim stream-prim) "CEPL: The buffer-stream passed to ~a contains ~s, however ~a was expecting ~s. You can either change the type of primitives the pipeline was expecting e.g: (defpipeline-g ~s (~s) ..) Or you can create a stream with containing ~a e.g: (make-buffer-stream gpu-array :draw-mode ~s) It is also worth noting that it is possible to pass triangles to a pipeline declared to take (:patch 3), to pass lines to pipelines declared to take (:patch 2) and points to pipelines taking (:patch 1)" name stream-prim name pline-prim name stream-prim pline-prim pline-prim) (deferror invalid-options-for-texture () (buffer-storage cubes dimensions layer-count mipmap multisample rectangle) "CEPL: We could not establish the correct texture type for the following combination of options: buffer-storage - ~a cubes - ~a dimensions - ~a layer-count - ~a mipmap - ~a multisample - ~a rectangle - ~a If the GL spec says this is valid then we are sorry for the mistake. If you have the time please report the issue here: " buffer-storage cubes dimensions layer-count mipmap multisample rectangle) (deferror gpu-func-symbol-name () (name alternatives env) "CEPL: We were asked to find the gpu function named ~a. Now we did find ~a however as gpu-functions can be overloaded we now require that you specify the types along with the name. This is slightly more annoying when there is only one match, however it eliminates the ambiguity that occurs as soon as someone does overload the gpu-function. Here are the possible names for this function: ~{~a~} ~@[ You may pick a implementation to use this time but, as this will not update your code, you will get this error on the next compile unless it is fixed~]" name (if (> (length alternatives) 1) "matches" "a match") alternatives (not (null env))) (deferror gl-context-initialized-from-incorrect-thread () (ctx-thread init-thread) "CEPL: This CEPL context is tied to thread A (shown below) however something tried to create the gl-context from thread B: A: ~a B: ~a" ctx-thread init-thread) (deferror shared-context-created-from-incorrect-thread () (ctx-thread init-thread) "CEPL: This CEPL context is tied to thread A (shown below) however something tried to create a shared CEPL context using it from thread B: A: ~a B: ~a" ctx-thread init-thread) (deferror tried-to-make-context-on-thread-that-already-has-one () (context thread) "CEPL: An attempt was made to create a context on thread ~a however that thread already has the CEPL context ~a. In CEPL you may only have 1 CEPL context per thread. That context then holds the handles to any GL contexts and any caching related to those gl contexts" thread context) (deferror max-context-count-reached () (max) "CEPL: Currently CEPL has a silly restriction on the number of contexts that can be active at once. The current maximum is max. It's silly in that GL itself doesnt have this restriction and it was only introduced in CEPL to make the implementation of multi-threading simpler. This restriction does need to be removed however so if you are hitting this then please report it at . This lets us know that this is causing real issues for people and we can prioritize it accordingingly.") (deferror nested-with-transform-feedback () () "CEPL: Detected a nested with-transform-feedback form. Currently this is not supported however in future it may be possible to support on GLv4 and up.") (deferror non-consecutive-feedback-groups () (groups) "CEPL: Currently when you specify transform-feedback groups their numbers must be consecutive and there must be at least one value being written to :feedback or (:feedback 0). We hope to be able to relax this in future when we support more recent GL features, however even then if you want maximum compatibility this will remain a good rule to follow. These were the groups in question: ~s" groups) (deferror mixed-pipelines-in-with-tb () () "CEPL: Different pipelines have been called within same tfs block") (deferror incorrect-number-of-arrays-in-tfs () (tfs tfs-count count) "CEPL: The transform feedback stream currently bound has ~a arrays bound, however the current pipeline is expecting to write into ~a ~a. The stream in question was:~%~a" tfs-count count (if (= count 1) "array" "arrays") tfs) (deferror invalid-args-in-make-tfs () (args) "CEPL: make-transform-feedback-stream was called with some arguments that are not buffer-backed gpu-arrays:~{~%~s~}" args) (deferror invalid-sizes-in-make-tfs () (args) "CEPL: Some of the gpu-arrays passed to make tfs have sizes which are not multiples of 4, GL does not allow this:~{~%~s~}" args) (defwarning tfs-setf-arrays-whilst-bound () () "CEPL: There was an attempt to setf the arrays attached to the transform-feedback-stream whilst it is bound inside with-transform-feedback. It is not possible to make these changes whilst in the block so we will apply them at the end of with-transform-feedback's scope") (deferror one-stage-non-explicit () () "CEPL: When defining a pipeline with only 1 stage you need to explicitly mark what stage it is as CEPL is unable to infer this. For example: (defpipeline-g some-pipeline () :vertex (some-stage :vec4))") (deferror invalid-stage-for-single-stage-pipeline () (kind) "CEPL: We found a pipeline where the only stage was of type ~a. Single stage pipelines are valid in CEPL however only if the stage is a vertex, fragment or compute stage" kind) (deferror pipeline-recompile-in-tfb-scope () (name) "CEPL: We were about to recompile the GL program behind ~a however we noticed that this is happening inside the scope of with-transform-feedback which GL does not allow. Sorry about that." name) (deferror compile-g-missing-requested-feature () (form) "CEPL: Sorry currently compile-g can only be used to make gpu lambdas by passing nil as the name and the source for the lambda like this: (lambda-g ((vert :vec4) &uniform (factor :float)) (* vert factor)) We received: ~a " form) (deferror query-is-already-active () (query) "CEPL: An attempt was made to start querying using the query object listed below, however that query object is currently in use. query: ~s" query) (deferror query-is-active-bug () (query) "CEPL BUG: This error should never be hit as it should have been covered by another assert inside #'begin-gpu-query. we are sorry for the mistake. If you have the time please report the issue here: query: ~s" query) (deferror another-query-is-active () (query current) "CEPL: An attempt was made to begin querying with query object 'A' listed below however query object 'B' of the same kind was already active on this context. GL only allows 1 query of this kind to be active at a given time. Query A: ~s Query B: ~s" query current) (deferror query-not-active () (query) "CEPL: A call was made to #'end-gpu-query with the query object listed below. The issue is that the query object is not currently active so it is not valid to try and make it inactive. Query: ~s" query) (deferror compute-pipeline-must-be-single-stage () (name stages) "CEPL: A attempt was made to compile ~a which contains the following stage kinds: ~a However if you include a compute stage it is the only stage allowed in the pipeline. Please either remove the compute stage or remove the other stages." (if name name "a pipeline") stages) (deferror could-not-layout-type () (type) "CEPL BUG: We were unable to work out the layout for the type ~a We are sorry for the mistake. If you have the time please report the issue here: (if you are able to include the definition of the type in the issue report that we be excedingly helpful)" type) (deferror invalid-data-layout-specifier () (specifier valid-specifiers) "CEPL: ~a is not a valid layout data specifier. Please use one of the following: ~{~a~^, ~}" specifier valid-specifiers) (deferror invalid-layout-for-inargs () (name type-name layout) "CEPL: ~a is not a valid type for ~a's input arguments as it has the layout ~a. ~a can only be used for uniforms marked as :ubo or :ssbo." type-name (or name "this lambda pipeline") layout type-name) (deferror invalid-layout-for-uniform () (name type-name layout func-p) "CEPL: ~a is not a valid type for ~a's uniform argument as it has the layout ~a. std-140 & std-430 layouts are only valid for ubo & ssbo uniforms." type-name (or name (if func-p "this gpu-lambda" "this lambda pipeline")) layout) (deferror c-array-total-size-type-error () (size required-type) "CEPL: c-array's total size must be of type c-array-index, also known as ~a. Total size found was ~a" (upgraded-array-element-type required-type) size) (deferror state-restore-limitation-transform-feedback () () "CEPL: State restoring currently cannot be used from within the dynamic scope of a transform feedback") (deferror state-restore-limitation-blending () () "CEPL: State restoring currently cannot be used from within the dynamic scope of with-blending (may have been introduced by with-fbo-bound)") (deferror state-restore-limitation-queries () () "CEPL: State restoring currently cannot be used from within the dynamic scope of with-blending (may have been introduced by with-fbo-bound)") (deferror fbo-binding-missing () (kind current-surface) "CEPL: FBO ~a bindings missing from context. ~a" (string-downcase (string kind)) (if current-surface "" "This is probably due to there being no surface current on this context")) (deferror texture-dimensions-lequal-zero () (dimensions) "CEPL: Found an request to make a texture where at least one of the dimensions were less than or equal to zero. Dimensions: ~a" dimensions) (deferror unknown-symbols-in-pipeline-context () (name full issue for) " CEPL: Found something we didnt recognise in the context of ~a Problematic symbol/s: ~{~s~^, ~} Full context: ~s The pipeline context must contain: The symbol :static at most once and.. ..0 or more of the following glsl versions:~{~%- :~a~} and at most 1 primitive from: - :dynamic - :points - :lines - :iso-lines - :line-loop - :line-strip - :lines-adjacency - :line-strip-adjacency - :triangles - :triangle-fan - :triangle-strip - :triangles-adjacency - :triangle-strip-adjacency - (:patch <patch length>) " (ecase for (:function (if name (format nil "the gpu-function named ~a." name) (format nil "a gpu-lambda."))) (:pipeline (if name (format nil "the pipeline named ~a." name) (format nil "a lambda pipeline."))) (:glsl-stage (if name (format nil "the glsl stage named ~a." name) issue full varjo:*supported-versions*) (deferror stage-in-context-only-valid-for-glsl-stages () (name) " ~a had a stage declaration in it's `compile-context` list this is only valid for gpu-functions & glsl stages. " (if name (format nil "The pipeline named ~a" name) "A lambda pipeline")) (deferror unknown-stage-kind () (stage) " Unknown stage kind '~a' Valid stage kinds are:~{~%- ~s~}" stage varjo:*stage-names*) (deferror stage-not-valid-for-function-restriction () (name stage func-stage) " When compiling ~a we found that the function being used as the ~a stage has a restriction that means it is only valid to be used as a ~a stage. " (or name "a lambda pipeline") stage func-stage) (deferror gl-version-too-low-for-empty-fbos () (version) " We found a valid attempt to create an empty fbo, however these are only supported in GL versions 4.3 and above. Current version: ~a " version) (deferror invalid-attachments-for-empty-fbo () (args) " When defining an empty fbo there can be 0 or 1 attachment declarations. When present it's name must be NIL. For example: - `(make-fbo '(nil :dimensions (1024 1024)))` - `(make-fbo '(nil))` - `(make-fbo)` You may also optionally specify the following parameters as you would in `make-texture`: - :dimensions - :layer-count - :samples - :fixed-sample-locations The empty fbo can be 1 or 2 dimensional In this case we were passed the following declarations:~{~%- ~s~} " args) (deferror invalid-empty-fbo-declaration () (decl) " When defining an empty fbo there can only be 1 attachment declaration, it's name must be NIL, and dimensions must be specified. For example: `(make-fbo '(nil :dimensions (1024 1024))` Dimensions can be 1 or 2 dimensional You may also optionally specify the following parameters as you would in `make-texture`: - :layer-count - :samples - :fixed-sample-locations In this case we were passed the following declaration:~%- ~s " decl) (deferror quote-symbol-found-in-fbo-dimensions () (form) " During creation of an fbo we found the quote symbol in the 'dimensions' portion of the attachment form. As the attachment form was already quoted this is unnecessary. Form: ~s " form) (deferror attachment-viewport-empty-fbo () (fbo attachment) " `T` cannot be used as a attachment-name. It is only allowed in `with-fbo-viewport` & `with-fbo-bound`'s 'attachment-for-size' parameter and only if the fbo being bound is empty. Likewise, when trying to use the above (and only the above) on an empty fbo, the attachment name *must* be 'T'. FBO Found: ~a Attachment: ~a " fbo attachment) (deferror invalid-fbo-args () (args) " ") (deferror invalid-sampler-wrap-value () (sampler value) " CEPL: Invalid value provided for 'wrap' of sampler: Sampler: ~a Value: ~s The value must be one of the following - :repeat - :mirrored-repeat - :clamp-to-edge - :clamp-to-border - :mirror-clamp-to-edge or a vector of 3 of the above keywords. " sampler value) (deferror make-gpu-buffer-from-id-clashing-keys () (args) " CEPL: When calling make-gpu-buffer-from-id you can pass in either initial-contents or layout, but not both. Args: ~s " args) (deferror invalid-gpu-buffer-layout () (layout) " CEPL: When calling make-gpu-buffer-from-id and passing in layouts, each layout must be either: - A positive integer representing a size in bytes - A list contain both :dimensions and :element-type &key arguments. e.g. - 512 - '(:dimensions (10 20) :element-type :uint8) layout: ~s " layout) (deferror invalid-gpu-arrays-layout () (layout) " CEPL: When calling make-gpu-arrays-from-buffer-id each layout must be a list containing both :dimensions and :element-type &key arguments. e.g. - '(:dimensions (10 20) :element-type :uint8) layout: ~s " layout) (deferror gpu-array-from-id-missing-args () (element-type dimensions) " CEPL: When calling make-gpu-array-from-buffer-id element-type and dimensions as mandatory. element-type: ~s dimensions: ~s " element-type dimensions) (deferror gpu-array-from-buffer-missing-args () (element-type dimensions) " CEPL: When calling make-gpu-array-from-buffer element-type and dimensions as mandatory. element-type: ~s dimensions: ~s " element-type dimensions) (deferror quote-in-buffer-layout () (layout) " CEPL: The symbol 'quote' was found in the gpu-buffer layout, making the layout list invalid. This was probably a typo. layout: ~s " layout) (deferror make-arrays-layout-mismatch () (current-sizes requested-sizes) " CEPL: When settting make-gpu-array-from-buffer's :keep-data argument to T you are requesting that the arrays are made using the existing contents of the buffer. However, in this case the byte size of the requested gpu arrays would not fit in the current available sections of the gpu-buffer. Current Section Sizes: ~a Requested gpu-array sizes: ~a " current-sizes requested-sizes) (deferror make-arrays-layout-count-mismatch () (current-count layouts) " CEPL: When settting make-gpu-array-from-buffer's :keep-data argument to T you are requesting that the arrays are made using the existing contents of the buffer. However, in this case the number of layouts provided (~s) does not match the number of sections in the gpu-buffer (~s). Layouts: ~s " (length layouts) current-count layouts) (deferror cannot-keep-data-when-uploading () (data) " CEPL: When calling make-gpu-buffer-from-id with keep-data it is not valid to pass initial-contents. The reason is that we would be required to upload the data in those c-arrays, which means we would not be keeping our promise to 'keep-data'. keep-data can be used when passing layouts instead of initial-contents as there we are just replacing CEPL's understanding of the layout of data in the buffer, without changing what is actually there. initial-contents provided: ~s " data) (deferror invalid-stream-layout () (layout) " CEPL: When calling make-buffer-stream-from-id-and-layouts each layout must be a list containing both :dimensions and :element-type &key arguments. e.g. - '(:dimensions (500) :element-type :vec3) layout: ~s " layout) (deferror index-on-buffer-stream-with-no-gpu-layouts () () " CEPL: Invalid attempt to make buffer-stream with an index layout even though there were no data layouts.") (deferror cannot-extract-stream-length-from-layouts () (layouts) " CEPL: We were unable to compute a suitable length for the buffer-stream as at least one of the data-layouts had an unknown length and there was no index-layout for us to take into account layouts: ~s" layouts) (deferror index-layout-with-unknown-length () (layout) " CEPL: When make-buffer-stream-from-id-and-layouts is called and an index layout is provided, it may not have '?' as the dimensions. layout: ~s" layout) (deferror inconsistent-struct-layout () (name target slots) " CEPL: the attempt to define the gpu-structs named ~a failed as, whilst it was defined to have a ~a layout, the following slots had different layouts: ~{~%- ~a~} " name target slots) (deferror not-a-gpu-lambda () (thing) "CEPL: ~a does not appear to be a gpu-lambda" thing) (deferror bad-c-array-element () (incorrect-type correct-type elem initial-contents extra-info-string) " CEPL: The first element in the initial-contents to the array being created is a ~a, this is not valid for an array of ~a First Value: ~s Initial-Contents: ~s~@[~%~%~a~]" incorrect-type correct-type elem initial-contents extra-info-string) (deferror no-named-stages () (stages) " CEPL: Small issue in a pipeline definition. Only a pipeline with 2 stages can be implicitly named, others must have explicit named stages. In this case we received the following for the stages: ~{~s~%~} Each of these stages will need to be named with one each of the following: ~{~%- ~a~}" stages varjo.api:*stage-names*) (deferror bad-type-for-buffer-stream-data () (type) " CEPL: ~s is not a type we can use for the data passed to the shader in a buffer-stream or vao as glsl does not directly support that type.~@[~%~%~a~]" type (when (find type '(:short :ushort :signed-short :unsigned-short)) "Perhaps this was meant to be used as the index?")) (deferror fbo-missing-outputs () (missing fbo) "CEPL - with-outputs-to-attachment~s: The current fbo does not have the following color attachments: ~{~a~^, ~} Fbo: ~a" (if (= (length missing) 1) "" "s") missing fbo) (deferror pipeline-invalid-null-stage () (name args) "CEPL - An attempt was found to make a pipeline which explicitly used nil as the stage designator. This is only valid for :fragment stages where you still want to write to the depth buffer Pipeline name: ~a Arguments given: ~s" (or name "<lambda pipeline>") args) (deferror invalid-gpu-function-args () (name unknown-key-arguments invalid-syntax constant-names incorrectly-typed-args) " CEPL - Invalid arguments found in lambda list for ~a~@[ ~s~] ~@[~%The following items are not valid lamda-list keywords:~{~%- ~s~}~%The valid keywords are :&uniform, :&context and :&shared~]~@[~%~%Invalid syntax found in the following arguments, each element must be a list of~%the format (name type &rest qualifiers):~{~%- ~s~}~]~@[~%~%The following symbols are already defined as constants and so cannot be~%used as argument names: ~{~s~^, ~}~]~@[~%~%The following args have types we didnt recognise:~%~{> ~s~}~]~@[~%~%Here are some types we think may have been meant: ~{~a~}~] " (if name "the gpu-function named" "a gpu-lambda") name unknown-key-arguments invalid-syntax constant-names incorrectly-typed-args (loop :for (name type) :in incorrectly-typed-args :for suggestion := (varjo.internals::find-alternative-types-for-spec type) :when suggestion :collect (format nil "~%> ~s~{~%~s~}" name suggestion))) Please remember the following 2 things
f08ca3f45c52505b70d96fafe8988ef1eba9e9048aa2fa0a98f1c1f3d767a29c
GaloisInc/daedalus
Util.hs
module Util where -- system: import Data.Char import System.Exit -- shake: import Development.Shake.FilePath ---- utilities --------------------------------------------------------------- triviallyFormat [] = "" triviallyFormat (c:cs) = if c `elem` "{,}" then "\n " ++ [c] ++ triviallyFormat cs else c : triviallyFormat cs timeInMs x = round(x * 1000) sfStripExtension :: String -> FilePath -> FilePath sfStripExtension ext fp = case stripExtension ext fp of Just fp' -> fp' Nothing -> error "sfStripExtension" quit :: String -> IO a quit msg = do putStrLn msg exitFailure cmpFileContents :: (String -> String -> a) -> FilePath -> FilePath -> IO a cmpFileContents eqv fa fb = do ca <- readFile fa cb <- readFile fb return (eqv ca cb) cmpFileContentsIO :: (String -> String -> IO a) -> FilePath -> FilePath -> IO a cmpFileContentsIO eqv fa fb = do ca <- readFile fa cb <- readFile fb eqv ca cb rmTrailingWhitespace :: [Char] -> [Char] rmTrailingWhitespace = reverse . dropWhile isSpace . reverse ---- split,unsplit ----------------------------------------------------------- -- split,unsplit a generalization of words,unwords! split :: Eq a => a -> [a] -> [[a]] split x = splitBy (==x) splitBy :: (a->Bool) -> [a] -> [[a]] splitBy _ [] = [] splitBy p xs = let (l,xs') = break p xs in l : case xs' of [] -> [] (_:xs'') -> splitBy p xs'' unsplit :: a -> [[a]] -> [a] unsplit _ [] = [] unsplit x xs = foldr1 (\x' s -> x' ++ x:s) xs unsplit' x xs = foldr (\x' s -> x' ++ x:s) [] xs
null
https://raw.githubusercontent.com/GaloisInc/daedalus/016da6b2de23747e48642f6ece79c07b436ef5d1/formats/pdf/old/driver/test/src/run-testset/Util.hs
haskell
system: shake: -- utilities --------------------------------------------------------------- -- split,unsplit ----------------------------------------------------------- split,unsplit a generalization of words,unwords!
module Util where import Data.Char import System.Exit import Development.Shake.FilePath triviallyFormat [] = "" triviallyFormat (c:cs) = if c `elem` "{,}" then "\n " ++ [c] ++ triviallyFormat cs else c : triviallyFormat cs timeInMs x = round(x * 1000) sfStripExtension :: String -> FilePath -> FilePath sfStripExtension ext fp = case stripExtension ext fp of Just fp' -> fp' Nothing -> error "sfStripExtension" quit :: String -> IO a quit msg = do putStrLn msg exitFailure cmpFileContents :: (String -> String -> a) -> FilePath -> FilePath -> IO a cmpFileContents eqv fa fb = do ca <- readFile fa cb <- readFile fb return (eqv ca cb) cmpFileContentsIO :: (String -> String -> IO a) -> FilePath -> FilePath -> IO a cmpFileContentsIO eqv fa fb = do ca <- readFile fa cb <- readFile fb eqv ca cb rmTrailingWhitespace :: [Char] -> [Char] rmTrailingWhitespace = reverse . dropWhile isSpace . reverse split :: Eq a => a -> [a] -> [[a]] split x = splitBy (==x) splitBy :: (a->Bool) -> [a] -> [[a]] splitBy _ [] = [] splitBy p xs = let (l,xs') = break p xs in l : case xs' of [] -> [] (_:xs'') -> splitBy p xs'' unsplit :: a -> [[a]] -> [a] unsplit _ [] = [] unsplit x xs = foldr1 (\x' s -> x' ++ x:s) xs unsplit' x xs = foldr (\x' s -> x' ++ x:s) [] xs
f8122b31732425bbd08d5df04b5e9201a93a5547596a3660917e6b36df1d9962
mirage/ocaml-git
traverse_bfs.ml
* Copyright ( c ) 2013 - 2017 < > * and < > * * 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) 2013-2017 Thomas Gazagnaire <> * and Romain Calascibetta <> * * 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. *) let src = Logs.Src.create "git.traverse" ~doc:"logs git's traverse event" module Log = (val Logs.src_log src : Logs.LOG) module type STORE = sig module Hash : S.HASH module Value : Value.S with type hash = Hash.t type t val root : t -> Fpath.t val read_exn : t -> Hash.t -> Value.t Lwt.t val is_shallowed : t -> Hash.t -> bool Lwt.t end module Make (Store : STORE) = struct (* XXX(dinosaure): convenience and common part between the file-system and the mem back-end - to avoid redundant code. *) let fold t (f : 'acc -> ?name:Fpath.t -> length:int64 -> Store.Hash.t -> Store.Value.t -> 'acc Lwt.t) ~path acc hash = let names = Hashtbl.create 0x100 in let open Lwt.Infix in let rec walk close rest queue acc = match rest with | [] -> ( match Queue.pop queue with | rest -> walk close [ rest ] queue acc | exception Queue.Empty -> Lwt.return acc) | hash :: rest -> ( if Store.Hash.Set.mem hash close then walk close rest queue acc else let close' = Store.Hash.Set.add hash close in Store.read_exn t hash >>= function | Value.Commit commit as value -> ( let rest' = Store.Value.Commit.tree commit :: rest in Store.is_shallowed t hash >>= function | true -> f acc ~length:(Store.Value.Commit.length commit) hash value >>= fun acc' -> walk close' rest' queue acc' | false -> List.iter (fun x -> Queue.add x queue) (Store.Value.Commit.parents commit); f acc ~length:(Store.Value.Commit.length commit) hash value >>= fun acc' -> walk close' rest' queue acc') | Value.Tree tree as value -> let path = try Hashtbl.find names hash with Not_found -> path in Lwt_list.iter_s (fun { Tree.name; node; _ } -> Hashtbl.add names node Fpath.(path / name); Lwt.return ()) (Store.Value.Tree.to_list tree) >>= fun () -> let rest' = rest @ List.map (fun { Tree.node; _ } -> node) (Store.Value.Tree.to_list tree) in f acc ~name:path ~length:(Store.Value.Tree.length tree) hash value >>= fun acc' -> walk close' rest' queue acc' | Value.Blob blob as value -> let path = try Hashtbl.find names hash with Not_found -> path in f acc ~name:path ~length:(Store.Value.Blob.length blob) hash value >>= fun acc' -> walk close' rest queue acc' | Value.Tag tag as value -> Queue.add (Store.Value.Tag.obj tag) queue; f acc ~length:(Store.Value.Tag.length tag) hash value >>= fun acc' -> walk close' rest queue acc') in walk Store.Hash.Set.empty [ hash ] (Queue.create ()) acc let iter t f hash = fold t (fun () ?name:_ ~length:_ hash value -> f hash value) ~path:(Store.root t) () hash end
null
https://raw.githubusercontent.com/mirage/ocaml-git/37c9ef41944b5b19117c34eee83ca672bb63f482/src/git/traverse_bfs.ml
ocaml
XXX(dinosaure): convenience and common part between the file-system and the mem back-end - to avoid redundant code.
* Copyright ( c ) 2013 - 2017 < > * and < > * * 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) 2013-2017 Thomas Gazagnaire <> * and Romain Calascibetta <> * * 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. *) let src = Logs.Src.create "git.traverse" ~doc:"logs git's traverse event" module Log = (val Logs.src_log src : Logs.LOG) module type STORE = sig module Hash : S.HASH module Value : Value.S with type hash = Hash.t type t val root : t -> Fpath.t val read_exn : t -> Hash.t -> Value.t Lwt.t val is_shallowed : t -> Hash.t -> bool Lwt.t end module Make (Store : STORE) = struct let fold t (f : 'acc -> ?name:Fpath.t -> length:int64 -> Store.Hash.t -> Store.Value.t -> 'acc Lwt.t) ~path acc hash = let names = Hashtbl.create 0x100 in let open Lwt.Infix in let rec walk close rest queue acc = match rest with | [] -> ( match Queue.pop queue with | rest -> walk close [ rest ] queue acc | exception Queue.Empty -> Lwt.return acc) | hash :: rest -> ( if Store.Hash.Set.mem hash close then walk close rest queue acc else let close' = Store.Hash.Set.add hash close in Store.read_exn t hash >>= function | Value.Commit commit as value -> ( let rest' = Store.Value.Commit.tree commit :: rest in Store.is_shallowed t hash >>= function | true -> f acc ~length:(Store.Value.Commit.length commit) hash value >>= fun acc' -> walk close' rest' queue acc' | false -> List.iter (fun x -> Queue.add x queue) (Store.Value.Commit.parents commit); f acc ~length:(Store.Value.Commit.length commit) hash value >>= fun acc' -> walk close' rest' queue acc') | Value.Tree tree as value -> let path = try Hashtbl.find names hash with Not_found -> path in Lwt_list.iter_s (fun { Tree.name; node; _ } -> Hashtbl.add names node Fpath.(path / name); Lwt.return ()) (Store.Value.Tree.to_list tree) >>= fun () -> let rest' = rest @ List.map (fun { Tree.node; _ } -> node) (Store.Value.Tree.to_list tree) in f acc ~name:path ~length:(Store.Value.Tree.length tree) hash value >>= fun acc' -> walk close' rest' queue acc' | Value.Blob blob as value -> let path = try Hashtbl.find names hash with Not_found -> path in f acc ~name:path ~length:(Store.Value.Blob.length blob) hash value >>= fun acc' -> walk close' rest queue acc' | Value.Tag tag as value -> Queue.add (Store.Value.Tag.obj tag) queue; f acc ~length:(Store.Value.Tag.length tag) hash value >>= fun acc' -> walk close' rest queue acc') in walk Store.Hash.Set.empty [ hash ] (Queue.create ()) acc let iter t f hash = fold t (fun () ?name:_ ~length:_ hash value -> f hash value) ~path:(Store.root t) () hash end
726bf58d6fad7a98ce18667fca533c3a40696fc1809dd540c9f6b5d12bd962ed
MyDataFlow/ttalk-server
proper_print.erl
Copyright 2010 - 2011 < > , < > and < > %%% This file is part of PropEr . %%% %%% PropEr 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. %%% %%% PropEr 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 PropEr. If not, see </>. 2010 - 2011 , and %%% @version {@version} @author %%% @doc This module contains tests to check the information printed by proper %%% on the shell -module(proper_print). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). %% Test that the stacktrace is not empty when something crashes in the property stacktrace_test_() -> [?_assertThrow({stacktrace, [_|_]}, proper:quickcheck(bad_proper_call_property())), ?_assertThrow({stacktrace, [_|_]}, proper:quickcheck(bad_call_property()))]. set_stacktrace_thrower(Prop) -> proper:on_output(fun throw_stacktrace/2, Prop). throw_stacktrace("Stacktrace: ~p.~n", [Stacktrace]) -> throw({stacktrace, Stacktrace}); throw_stacktrace(_, _) -> ok. bad_proper_call_property() -> set_stacktrace_thrower(?FORALL(_X, proper_types:int(), proper:foo())). bad_call_property() -> set_stacktrace_thrower(?FORALL(_X, proper_types:int(), foo:bar())).
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/proper/test/proper_print.erl
erlang
PropEr is free software: you can redistribute it and/or modify (at your option) any later version. PropEr 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 PropEr. If not, see </>. @version {@version} @doc This module contains tests to check the information printed by proper on the shell Test that the stacktrace is not empty when something crashes in the property
Copyright 2010 - 2011 < > , < > and < > This file is part of PropEr . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License 2010 - 2011 , and @author -module(proper_print). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). stacktrace_test_() -> [?_assertThrow({stacktrace, [_|_]}, proper:quickcheck(bad_proper_call_property())), ?_assertThrow({stacktrace, [_|_]}, proper:quickcheck(bad_call_property()))]. set_stacktrace_thrower(Prop) -> proper:on_output(fun throw_stacktrace/2, Prop). throw_stacktrace("Stacktrace: ~p.~n", [Stacktrace]) -> throw({stacktrace, Stacktrace}); throw_stacktrace(_, _) -> ok. bad_proper_call_property() -> set_stacktrace_thrower(?FORALL(_X, proper_types:int(), proper:foo())). bad_call_property() -> set_stacktrace_thrower(?FORALL(_X, proper_types:int(), foo:bar())).
9875530589c0d3b08850714978e9ff4242a2c3588dbd8168b32e9f9089ba2e96
digitallyinduced/ihp
Types.hs
module IHP.DataSync.REST.Types where import IHP.Prelude data ApiController ^ POST /api / books | UpdateRecordAction { table :: Text, id :: UUID } | DeleteRecordAction { table :: Text, id :: UUID } ^ GET /api / books/9ba0ffbc - bfc1 - 4d7d-8152 - 30a6648806f7 ^ GET /api / books | GraphQLQueryAction deriving (Eq, Show, Data)
null
https://raw.githubusercontent.com/digitallyinduced/ihp/620e8508be41a7977b92f2fa117b05b0842322b3/IHP/DataSync/REST/Types.hs
haskell
module IHP.DataSync.REST.Types where import IHP.Prelude data ApiController ^ POST /api / books | UpdateRecordAction { table :: Text, id :: UUID } | DeleteRecordAction { table :: Text, id :: UUID } ^ GET /api / books/9ba0ffbc - bfc1 - 4d7d-8152 - 30a6648806f7 ^ GET /api / books | GraphQLQueryAction deriving (Eq, Show, Data)
d5cb97f579998599524b9df6c7aa2e17d87c2eca7970c736b0a2f6ec0aa82b11
xvw/quasar
index.ml
open Quasar_js open Util let () = Console.log "Hello World" let () = Console.print "Hello World" let () = Console.error "test" let () = Console.warning "foobar" let () = Console.log (Array.make 10 7) let () = Console.timetrack "answer time" [ (fun logger -> logger "foo"; Console.print "Hello"); (fun logger -> logger "bar"; Console.print "World") ] ;; let () = Console.time "foo" let () = Console.time_log "foo" () let () = Console.time_log "foo" () let () = Console.time_end "foo" let () = Console.count () let () = Console.count () let () = Console.count ~label:"foo" () let () = Console.count_reset () let () = Console.count ~label:"foo" () let () = Console.count_reset ~label:"foo" () let () = Console.count ~label:"foo" () let () = Console.count () let () = Console.dir "foo" let () = Console.dir 7 let () = Console.dir Js_of_ocaml.Firebug.console let () = Console.trace () let () = Console.info "foo" let () = Console.table $ Array.from_array Js_of_ocaml.Js.string [| "foo"; "bar"; "baz" |] ;; let () = let () = Console.group ~label:"foo" () in let () = Console.print "foo" in let () = Console.print "bar" in let () = Console.group () in let () = Console.print "baz" in let () = Console.group_end () in let () = Console.print "foobar" in let () = Console.group_end () in Console.print "foobarbaz" ;;
null
https://raw.githubusercontent.com/xvw/quasar/a414d32ded53562802893590e2996bb8daeb0cf3/examples/00-various/index.ml
ocaml
open Quasar_js open Util let () = Console.log "Hello World" let () = Console.print "Hello World" let () = Console.error "test" let () = Console.warning "foobar" let () = Console.log (Array.make 10 7) let () = Console.timetrack "answer time" [ (fun logger -> logger "foo"; Console.print "Hello"); (fun logger -> logger "bar"; Console.print "World") ] ;; let () = Console.time "foo" let () = Console.time_log "foo" () let () = Console.time_log "foo" () let () = Console.time_end "foo" let () = Console.count () let () = Console.count () let () = Console.count ~label:"foo" () let () = Console.count_reset () let () = Console.count ~label:"foo" () let () = Console.count_reset ~label:"foo" () let () = Console.count ~label:"foo" () let () = Console.count () let () = Console.dir "foo" let () = Console.dir 7 let () = Console.dir Js_of_ocaml.Firebug.console let () = Console.trace () let () = Console.info "foo" let () = Console.table $ Array.from_array Js_of_ocaml.Js.string [| "foo"; "bar"; "baz" |] ;; let () = let () = Console.group ~label:"foo" () in let () = Console.print "foo" in let () = Console.print "bar" in let () = Console.group () in let () = Console.print "baz" in let () = Console.group_end () in let () = Console.print "foobar" in let () = Console.group_end () in Console.print "foobarbaz" ;;
d57aad553f735198e387be0aabfc5bcd8dc7b5b10f85091f7bbfef38d4dd91a3
vehicle-lang/vehicle
Libraries.hs
module Vehicle.Libraries ( LibraryName, LibraryInfo (..), Library (..), findLibraryContentFile, ) where import Control.Exception (IOException, catch) import Control.Monad (unless) import Control.Monad.IO.Class (MonadIO (..)) import Data.Aeson (FromJSON, ToJSON, decode) import Data.Aeson.Encode.Pretty (encodePretty) import Data.ByteString.Lazy qualified as BIO import Data.Text (Text) import Data.Text.IO qualified as TIO import Data.Version (Version) import GHC.Generics (Generic) import System.Directory (createDirectoryIfMissing) import System.FilePath ((<.>), (</>)) import Vehicle.Prelude type LibraryName = String data LibraryInfo = LibraryInfo { libraryName :: LibraryName, libraryVersion :: Version } deriving (Generic) instance FromJSON LibraryInfo instance ToJSON LibraryInfo data Library = Library { libraryInfo :: LibraryInfo, libraryContent :: Text } getLibraryPath :: MonadIO m => LibraryName -> m FilePath getLibraryPath name = do vehiclePath <- getVehiclePath return $ vehiclePath </> "libraries" </> name getLibraryInfoFile :: FilePath -> FilePath getLibraryInfoFile libraryFolder = libraryFolder </> vehicleLibraryExtension getLibraryContentFile :: FilePath -> LibraryName -> FilePath getLibraryContentFile libraryFolder fileName = libraryFolder </> fileName <.> vehicleFileExtension installLibrary :: (MonadIO m, MonadLogger m) => Library -> m () installLibrary Library {..} = do let name = libraryName libraryInfo logDebug MaxDetail $ "Installing library" <+> quotePretty name libraryFolder <- getLibraryPath name liftIO $ createDirectoryIfMissing True libraryFolder -- Write the library info file out let libraryInfoFile = getLibraryInfoFile libraryFolder let libraryInfoFileContent = encodePretty libraryInfo liftIO $ BIO.writeFile libraryInfoFile libraryInfoFileContent -- Write the contents of the library out let libraryContentFile = libraryFolder </> name <.> vehicleFileExtension liftIO $ TIO.writeFile libraryContentFile libraryContent -- | Finds the file path to the library content. At the moment -- this is very hacky, as it assumes there's a single file per library -- and that it should install a newer version if out of date. findLibraryContentFile :: (MonadIO m, MonadLogger m) => Library -> m FilePath findLibraryContentFile library = do let name = libraryName $ libraryInfo library libraryFolder <- getLibraryPath name -- Check the library info file and see if it's up to date let libraryInfoFile = getLibraryInfoFile libraryFolder errorOrContents <- liftIO $ catch (Right <$> BIO.readFile libraryInfoFile) (\(e :: IOException) -> return (Left e)) libraryUpToDate <- case errorOrContents of Left _err -> do logDebug MaxDetail $ "Unable to find or read" <+> quotePretty libraryInfoFile return False Right contents -> case decode contents of Nothing -> do logDebug MaxDetail $ "Unable to decode contents of" <+> quotePretty libraryInfoFile return False Just actualInfo -> do let actualVersion = libraryVersion actualInfo let expectedVersion = libraryVersion (libraryInfo library) if actualVersion == expectedVersion then do logDebug MaxDetail $ "Found up-to-date installed version of" <+> quotePretty name <+> "at" <+> quotePretty libraryFolder return True else do logDebug MaxDetail $ "Installed version of" <+> quotePretty name <+> parens (pretty actualVersion) <+> "does not match latest version" <+> parens (pretty expectedVersion) return False -- If not update to date then reinstall unless libraryUpToDate $ do installLibrary library return (getLibraryContentFile libraryFolder name)
null
https://raw.githubusercontent.com/vehicle-lang/vehicle/ca99b8da9e5aabde2c94b758bb4141fbe53ebed5/vehicle/src/Vehicle/Libraries.hs
haskell
Write the library info file out Write the contents of the library out | Finds the file path to the library content. At the moment this is very hacky, as it assumes there's a single file per library and that it should install a newer version if out of date. Check the library info file and see if it's up to date If not update to date then reinstall
module Vehicle.Libraries ( LibraryName, LibraryInfo (..), Library (..), findLibraryContentFile, ) where import Control.Exception (IOException, catch) import Control.Monad (unless) import Control.Monad.IO.Class (MonadIO (..)) import Data.Aeson (FromJSON, ToJSON, decode) import Data.Aeson.Encode.Pretty (encodePretty) import Data.ByteString.Lazy qualified as BIO import Data.Text (Text) import Data.Text.IO qualified as TIO import Data.Version (Version) import GHC.Generics (Generic) import System.Directory (createDirectoryIfMissing) import System.FilePath ((<.>), (</>)) import Vehicle.Prelude type LibraryName = String data LibraryInfo = LibraryInfo { libraryName :: LibraryName, libraryVersion :: Version } deriving (Generic) instance FromJSON LibraryInfo instance ToJSON LibraryInfo data Library = Library { libraryInfo :: LibraryInfo, libraryContent :: Text } getLibraryPath :: MonadIO m => LibraryName -> m FilePath getLibraryPath name = do vehiclePath <- getVehiclePath return $ vehiclePath </> "libraries" </> name getLibraryInfoFile :: FilePath -> FilePath getLibraryInfoFile libraryFolder = libraryFolder </> vehicleLibraryExtension getLibraryContentFile :: FilePath -> LibraryName -> FilePath getLibraryContentFile libraryFolder fileName = libraryFolder </> fileName <.> vehicleFileExtension installLibrary :: (MonadIO m, MonadLogger m) => Library -> m () installLibrary Library {..} = do let name = libraryName libraryInfo logDebug MaxDetail $ "Installing library" <+> quotePretty name libraryFolder <- getLibraryPath name liftIO $ createDirectoryIfMissing True libraryFolder let libraryInfoFile = getLibraryInfoFile libraryFolder let libraryInfoFileContent = encodePretty libraryInfo liftIO $ BIO.writeFile libraryInfoFile libraryInfoFileContent let libraryContentFile = libraryFolder </> name <.> vehicleFileExtension liftIO $ TIO.writeFile libraryContentFile libraryContent findLibraryContentFile :: (MonadIO m, MonadLogger m) => Library -> m FilePath findLibraryContentFile library = do let name = libraryName $ libraryInfo library libraryFolder <- getLibraryPath name let libraryInfoFile = getLibraryInfoFile libraryFolder errorOrContents <- liftIO $ catch (Right <$> BIO.readFile libraryInfoFile) (\(e :: IOException) -> return (Left e)) libraryUpToDate <- case errorOrContents of Left _err -> do logDebug MaxDetail $ "Unable to find or read" <+> quotePretty libraryInfoFile return False Right contents -> case decode contents of Nothing -> do logDebug MaxDetail $ "Unable to decode contents of" <+> quotePretty libraryInfoFile return False Just actualInfo -> do let actualVersion = libraryVersion actualInfo let expectedVersion = libraryVersion (libraryInfo library) if actualVersion == expectedVersion then do logDebug MaxDetail $ "Found up-to-date installed version of" <+> quotePretty name <+> "at" <+> quotePretty libraryFolder return True else do logDebug MaxDetail $ "Installed version of" <+> quotePretty name <+> parens (pretty actualVersion) <+> "does not match latest version" <+> parens (pretty expectedVersion) return False unless libraryUpToDate $ do installLibrary library return (getLibraryContentFile libraryFolder name)
f0bba8c29cf862fca1becb9b05755215f4c5a72f260b6733f91c73927105994b
hyperthunk/annotations
annotation.erl
%% ----------------------------------------------------------------------------- %% Copyright ( c ) 2008 - 2011 ( ) %% %% Permission is hereby granted, free of charge, to any person obtaining a copy %% of this software and associated documentation files (the "Software"), to deal in the Software without restriction , including without limitation the rights %% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is %% furnished to do so, subject to the following conditions: %% %% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR %% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, %% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE %% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , %% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN %% THE SOFTWARE. %% %% ----------------------------------------------------------------------------- -module(annotation). -export([behaviour_info/1]). -export([has_advice/1, has_advice/2, has_codegen/1]). -export([process_annotation/2, call_advised/3, get_scope/0]). -annotation(['application', 'package', 'module']). -include("types.hrl"). behaviour_info(callbacks) -> [{process_annotation, 2}, {get_scope, 0}]; behaviour_info(_) -> undefined. process_annotation(A, _Data) -> A. get_scope() -> 'function'. call_advised(M, F, Inputs) -> erlang:apply(M, annotations:advised_name(F), Inputs). has_codegen(#annotation{name=Module}) -> erlang:function_exported(Module, codegen, 3). has_advice(#annotation{name=Module}) -> lists:member(true, all_advice(Module)). has_advice(after_advice, #annotation{name=Module}) -> erlang:function_exported(Module, after_advice, 5); has_advice(Advice, #annotation{name=Module}) -> erlang:function_exported(Module, Advice, 4). all_advice(Module) -> [ erlang:function_exported(Module, F, 4) || F <- [before_advice, around_advice] ] ++ [ erlang:function_exported(Module, after_advice, 5) ].
null
https://raw.githubusercontent.com/hyperthunk/annotations/ac34bf92a7b369aae3a763dd6ff7c0e463230404/src/annotation.erl
erlang
----------------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal to use, copy, modify, merge, publish, distribute, sublicense, and/or sell furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -----------------------------------------------------------------------------
Copyright ( c ) 2008 - 2011 ( ) in the Software without restriction , including without limitation the rights copies of the Software , and to permit persons to whom the Software is all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , -module(annotation). -export([behaviour_info/1]). -export([has_advice/1, has_advice/2, has_codegen/1]). -export([process_annotation/2, call_advised/3, get_scope/0]). -annotation(['application', 'package', 'module']). -include("types.hrl"). behaviour_info(callbacks) -> [{process_annotation, 2}, {get_scope, 0}]; behaviour_info(_) -> undefined. process_annotation(A, _Data) -> A. get_scope() -> 'function'. call_advised(M, F, Inputs) -> erlang:apply(M, annotations:advised_name(F), Inputs). has_codegen(#annotation{name=Module}) -> erlang:function_exported(Module, codegen, 3). has_advice(#annotation{name=Module}) -> lists:member(true, all_advice(Module)). has_advice(after_advice, #annotation{name=Module}) -> erlang:function_exported(Module, after_advice, 5); has_advice(Advice, #annotation{name=Module}) -> erlang:function_exported(Module, Advice, 4). all_advice(Module) -> [ erlang:function_exported(Module, F, 4) || F <- [before_advice, around_advice] ] ++ [ erlang:function_exported(Module, after_advice, 5) ].
7f6a2fa7e92cf180c808d499fb364c5b7d708ee9b76697d6e5a94724912c2a52
ladderlife/clj-tutorial
project.clj
(defproject clj-tutorial "1.0.0-SNAPSHOT" :resource-paths ["resources"] :dependencies [[org.clojure/clojure "1.9.0-alpha12"]])
null
https://raw.githubusercontent.com/ladderlife/clj-tutorial/9302f94ff0bfdf5aae9801b2b1ee855a8d88bc5d/project.clj
clojure
(defproject clj-tutorial "1.0.0-SNAPSHOT" :resource-paths ["resources"] :dependencies [[org.clojure/clojure "1.9.0-alpha12"]])
b90e0799030100f925e601d9d94fe720e76caed3c0789fc17740ea2ed733d1b5
TaktInc/fake
Fake.hs
module Fake ( module Fake.Class , module Fake.Combinators , module Fake.Cover , module Fake.Types , module Fake.Utils ) where import Fake.Class import Fake.Combinators import Fake.Cover import Fake.Types import Fake.Utils
null
https://raw.githubusercontent.com/TaktInc/fake/02d1d8219c4bf2958ee92c3b9fc9fe3fb5dd1270/src/Fake.hs
haskell
module Fake ( module Fake.Class , module Fake.Combinators , module Fake.Cover , module Fake.Types , module Fake.Utils ) where import Fake.Class import Fake.Combinators import Fake.Cover import Fake.Types import Fake.Utils
a62833f8caae4c37cd70b0ff2be7ef1689f0bf76fdea3afcd63c988dd6d6c3c6
takahisa/featherweight-java
ast_field.ml
* Copyright ( c ) 2014 - 2015 < > All rights reserved . * * Permission is hereby granted , free of charge , to any person obtaining a copy * of this software and associated documentation files ( the " Software " ) , to deal * in the Software without restriction , including without limitation the rights * to use , copy , modify , merge , publish , distribute , sublicense , and/or sell * copies of the Software , and to permit persons to whom the Software is * furnished to do so , subject to the following conditions : * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software . * * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE . * Copyright (c) 2014 - 2015 Takahisa Watanabe <> All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *) type t = { name : Id.t; typ : Ast_type.t; } let make ~name ~typ = { name = name; typ = typ } let name f = f.name let typ f = f.typ
null
https://raw.githubusercontent.com/takahisa/featherweight-java/356e9357fcf915dac71f0063a51a9211c98c677d/ast_field.ml
ocaml
* Copyright ( c ) 2014 - 2015 < > All rights reserved . * * Permission is hereby granted , free of charge , to any person obtaining a copy * of this software and associated documentation files ( the " Software " ) , to deal * in the Software without restriction , including without limitation the rights * to use , copy , modify , merge , publish , distribute , sublicense , and/or sell * copies of the Software , and to permit persons to whom the Software is * furnished to do so , subject to the following conditions : * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software . * * THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR * IMPLIED , INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY , * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER * LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM , * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE . * Copyright (c) 2014 - 2015 Takahisa Watanabe <> All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *) type t = { name : Id.t; typ : Ast_type.t; } let make ~name ~typ = { name = name; typ = typ } let name f = f.name let typ f = f.typ
cec705e8b5924f56d0a47364b7408787f15599a442d78c4abe806162e05c7477
plumatic/grab-bag
cookies.cljs
(ns tubes.cookies (:refer-clojure :exclude [set get remove]) (:require [goog.net.cookies])) (defn set [k v & [{:keys [max-age]}]] (.set goog.net.cookies (name k) (js/JSON.stringify (clj->js v)) (or max-age -1))) (defn get [k] (.get goog.net.cookies (name k))) (defn remove [k & [{:keys [path domain]}]] (.remove goog.net.cookies (name k) path domain))
null
https://raw.githubusercontent.com/plumatic/grab-bag/a15e943322fbbf6f00790ce5614ba6f90de1a9b5/lib/tubes/src/tubes/cookies.cljs
clojure
(ns tubes.cookies (:refer-clojure :exclude [set get remove]) (:require [goog.net.cookies])) (defn set [k v & [{:keys [max-age]}]] (.set goog.net.cookies (name k) (js/JSON.stringify (clj->js v)) (or max-age -1))) (defn get [k] (.get goog.net.cookies (name k))) (defn remove [k & [{:keys [path domain]}]] (.remove goog.net.cookies (name k) path domain))
8de07738119123942eba1db1e75b6baab0c9a0a219e334a4e5653348d52fa8cc
leanprover/tc
Inductive.hs
| Module : . Inductive Description : Inductive type declarations Copyright : ( c ) , 2016 License : GPL-3 Maintainer : API for inductive types Module : Kernel.Inductive Description : Inductive type declarations Copyright : (c) Daniel Selsam, 2016 License : GPL-3 Maintainer : API for inductive types -} module Kernel.Inductive (IndDeclError, addInductive) where import Kernel.Inductive.Internal
null
https://raw.githubusercontent.com/leanprover/tc/250a568346f29ae27190fccee169ba10002c7399/src/Kernel/Inductive.hs
haskell
| Module : . Inductive Description : Inductive type declarations Copyright : ( c ) , 2016 License : GPL-3 Maintainer : API for inductive types Module : Kernel.Inductive Description : Inductive type declarations Copyright : (c) Daniel Selsam, 2016 License : GPL-3 Maintainer : API for inductive types -} module Kernel.Inductive (IndDeclError, addInductive) where import Kernel.Inductive.Internal
44a05bf91f25f65aad61f4bef5fa9b9a247390bca5b693d47b6f016e6658e263
facebook/Haxl
OutgoneFetchesTests.hs
Copyright ( c ) 2014 - present , Facebook , Inc. -- All rights reserved. -- This source code is distributed under the terms of a BSD license , -- found in the LICENSE file. {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ApplicativeDo # module OutgoneFetchesTests (tests) where import Haxl.Prelude as Haxl import Prelude() import Haxl.Core import Haxl.DataSource.ConcurrentIO import Data.IORef import qualified Data.Map as Map import Data.Typeable import Test.HUnit import System.Timeout import ExampleDataSource import SleepDataSource testEnv :: IO (Env () ()) testEnv = do exstate <- ExampleDataSource.initGlobalState sleepState <- mkConcurrentIOState let st = stateSet exstate $ stateSet sleepState stateEmpty e <- initEnv st () return e { flags = (flags e) { report = setReportFlag ReportOutgoneFetches defaultReportFlags } } -- report=1 to enable fetches tracking -- A cheap haxl computation we interleave b/w the @sleep@ fetches. wombats :: GenHaxl () () Int wombats = length <$> listWombats 3 outgoneFetchesTest :: String -> Int -> GenHaxl () () a -> Test outgoneFetchesTest label unfinished haxl = TestLabel label $ TestCase $ do env <- testEnv _ <- timeout (100*1000) $ runHaxl env haxl -- 100ms actual <- getMapFromRCMap <$> readIORef (submittedReqsRef env) assertEqual "fetchesMap" expected actual where expected = if unfinished == 0 then Map.empty else Map.singleton (dataSourceName (Proxy :: Proxy (ConcurrentIOReq Sleep))) $ Map.singleton (typeOf1 (undefined :: ConcurrentIOReq Sleep a)) unfinished tests :: Test tests = TestList [ outgoneFetchesTest "finished" 0 $ do -- test that a completed datasource fetch doesn't show up in Env _ <- sleep 1 -- finished _ <- sleep 1 -- cached/finished _ <- sleep 1 -- cached/finished wombats , outgoneFetchesTest "unfinished" 2 $ do -- test that unfinished datasource fetches shows up in Env _ <- sleep 200 -- unfinished _ <- wombats _ <- sleep 300 -- unfinished _ <- wombats return () , outgoneFetchesTest "mixed" 2 $ do -- test for finished/unfinished fetches from the same datasource _ <- sleep 1 -- finished _ <- sleep 200 -- unfinished _ <- sleep 300 -- unfinished return () , outgoneFetchesTest "cached" 1 $ do test for cached requests not showing up twice in ReqCountMap _ <- sleep 200 -- unfinished _ <- sleep 200 -- cached/unfinished return () , outgoneFetchesTest "unsent" 1 $ test for unsent requests not showing up in ReqCountMap second req should never be sent ]
null
https://raw.githubusercontent.com/facebook/Haxl/8c645b0e20b0eab942111494e042a908ebbe5132/tests/OutgoneFetchesTests.hs
haskell
All rights reserved. found in the LICENSE file. # LANGUAGE OverloadedStrings # report=1 to enable fetches tracking A cheap haxl computation we interleave b/w the @sleep@ fetches. 100ms test that a completed datasource fetch doesn't show up in Env finished cached/finished cached/finished test that unfinished datasource fetches shows up in Env unfinished unfinished test for finished/unfinished fetches from the same datasource finished unfinished unfinished unfinished cached/unfinished
Copyright ( c ) 2014 - present , Facebook , Inc. This source code is distributed under the terms of a BSD license , # LANGUAGE ApplicativeDo # module OutgoneFetchesTests (tests) where import Haxl.Prelude as Haxl import Prelude() import Haxl.Core import Haxl.DataSource.ConcurrentIO import Data.IORef import qualified Data.Map as Map import Data.Typeable import Test.HUnit import System.Timeout import ExampleDataSource import SleepDataSource testEnv :: IO (Env () ()) testEnv = do exstate <- ExampleDataSource.initGlobalState sleepState <- mkConcurrentIOState let st = stateSet exstate $ stateSet sleepState stateEmpty e <- initEnv st () return e { flags = (flags e) { report = setReportFlag ReportOutgoneFetches defaultReportFlags } } wombats :: GenHaxl () () Int wombats = length <$> listWombats 3 outgoneFetchesTest :: String -> Int -> GenHaxl () () a -> Test outgoneFetchesTest label unfinished haxl = TestLabel label $ TestCase $ do env <- testEnv actual <- getMapFromRCMap <$> readIORef (submittedReqsRef env) assertEqual "fetchesMap" expected actual where expected = if unfinished == 0 then Map.empty else Map.singleton (dataSourceName (Proxy :: Proxy (ConcurrentIOReq Sleep))) $ Map.singleton (typeOf1 (undefined :: ConcurrentIOReq Sleep a)) unfinished tests :: Test tests = TestList [ outgoneFetchesTest "finished" 0 $ do wombats , outgoneFetchesTest "unfinished" 2 $ do _ <- wombats _ <- wombats return () , outgoneFetchesTest "mixed" 2 $ do return () , outgoneFetchesTest "cached" 1 $ do test for cached requests not showing up twice in ReqCountMap return () , outgoneFetchesTest "unsent" 1 $ test for unsent requests not showing up in ReqCountMap second req should never be sent ]
7d264c2d3ce7814484d211b454f79174820c51f2bf91df8b7f88ec7c282df041
finnishtransportagency/harja
geometriaaineistot.clj
(ns harja.kyselyt.geometriaaineistot (:require [harja.domain.geometriaaineistot :as ga] [specql.core :refer [fetch update! insert! upsert! delete!]] [specql.op :as op] [jeesql.core :refer [defqueries]] [harja.pvm :as pvm])) (defn tallenna-urakan-tyotunnit [db geometria-aineistot] (upsert! db ::ga/geometria-aineistot #{::ga/nimi ::ga/tiedostonimi ::ga/voimassaolo-alkaa ::ga/voimassaolo-paattyy} geometria-aineistot)) (defn hae-geometria-aineistot [db] (fetch db ::ga/geometria-aineistot ga/kaikki-kentat {})) (defn hae-voimassaoleva-geometria-aineisto [db nimi] (first (fetch db ::ga/geometria-aineistot ga/kaikki-kentat (op/and {::ga/nimi nimi} (op/or {::ga/voimassaolo-alkaa op/null?} {::ga/voimassaolo-alkaa (op/<= (pvm/nyt))}) (op/or {::ga/voimassaolo-paattyy op/null?} {::ga/voimassaolo-paattyy (op/>= (pvm/nyt))}))))) (defn tallenna-geometria-aineisto [db geometria-ainesto] (upsert! db ::ga/geometria-aineistot geometria-ainesto)) (defn poista-geometria-aineisto [db id] (delete! db ::ga/geometria-aineistot {::ga/id id}))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/20ede1b2317b7cf88a8e4d746f4fbd634a9a7b4c/src/clj/harja/kyselyt/geometriaaineistot.clj
clojure
(ns harja.kyselyt.geometriaaineistot (:require [harja.domain.geometriaaineistot :as ga] [specql.core :refer [fetch update! insert! upsert! delete!]] [specql.op :as op] [jeesql.core :refer [defqueries]] [harja.pvm :as pvm])) (defn tallenna-urakan-tyotunnit [db geometria-aineistot] (upsert! db ::ga/geometria-aineistot #{::ga/nimi ::ga/tiedostonimi ::ga/voimassaolo-alkaa ::ga/voimassaolo-paattyy} geometria-aineistot)) (defn hae-geometria-aineistot [db] (fetch db ::ga/geometria-aineistot ga/kaikki-kentat {})) (defn hae-voimassaoleva-geometria-aineisto [db nimi] (first (fetch db ::ga/geometria-aineistot ga/kaikki-kentat (op/and {::ga/nimi nimi} (op/or {::ga/voimassaolo-alkaa op/null?} {::ga/voimassaolo-alkaa (op/<= (pvm/nyt))}) (op/or {::ga/voimassaolo-paattyy op/null?} {::ga/voimassaolo-paattyy (op/>= (pvm/nyt))}))))) (defn tallenna-geometria-aineisto [db geometria-ainesto] (upsert! db ::ga/geometria-aineistot geometria-ainesto)) (defn poista-geometria-aineisto [db id] (delete! db ::ga/geometria-aineistot {::ga/id id}))
4e3ad238c7bd232886c47db3e29d9b113005dee775bc577bcadcea345a4c3b33
markandrus/twilio-haskell
Message.hs
# LANGUAGE MultiParamTypeClasses # {-#LANGUAGE OverloadedStrings #-} # LANGUAGE ViewPatterns # ------------------------------------------------------------------------------- -- | -- Module : Twilio.Message Copyright : ( C ) 2017- -- License : BSD-style (see the file LICENSE) Maintainer : < > -- Stability : provisional ------------------------------------------------------------------------------- module Twilio.Message ( -- * Resource Message(..) , Twilio.Message.get -- * Types , MessageDirection(..) , MessageStatus(..) ) where import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Text (Text) import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types Resource data Message = Message { sid :: !MessageSID , dateCreated :: !UTCTime , dateUpdated :: !UTCTime , dateSent :: !(Maybe UTCTime) ^ This will be Nothing if has n't sent the message yet . , accountSID :: !AccountSID , to :: !Text , from :: !Text , body :: !Text , status :: !MessageStatus , numSegments : : ! Integer , direction :: !MessageDirection -- , price :: !Double , priceUnit :: !PriceUnit , apiVersion :: !APIVersion , uri :: !URI } deriving (Show, Eq) instance FromJSON Message where parseJSON (Object v) = Message <$> v .: "sid" <*> (v .: "date_created" >>= parseDateTime) <*> (v .: "date_updated" >>= parseDateTime) <*> (v .:? "date_sent" >>= parseMaybeDateTime) <*> v .: "account_sid" <*> v .: "to" <*> v .: "from" <*> v .: "body" <*> v .: "status" -- <*> (v .: "num_segments" <&> fmap safeRead > > = ) <*> v .: "direction" -- <*> (v .: "price" <&> fmap safeRead > > = ' ) <*> v .: "price_unit" <*> v .: "api_version" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) parseJSON _ = mzero instance Get1 MessageSID Message where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Messages/" <> sid <> ".json") -- | Get a 'Message' by 'MessageSID'. get :: MonadThrow m => MessageSID -> TwilioT m Message get = Resource.get {- Types -} data MessageDirection = Inbound | OutboundAPI | OutboundCall | OutboundReply deriving Eq instance Show MessageDirection where show Inbound = "inbound" show OutboundAPI = "outbound-api" show OutboundCall = "outbound-call" show OutboundReply = "outbound-reply" instance FromJSON MessageDirection where parseJSON (String "inbound") = return Inbound parseJSON (String "outbound-api") = return OutboundAPI parseJSON (String "outbound-call") = return OutboundCall parseJSON (String "outbound-reply") = return OutboundReply parseJSON _ = mzero data MessageStatus = Queued | Sending | Sent | Failed | Received | Delivered | Undelivered deriving Eq instance Show MessageStatus where show Queued = "queued" show Sending = "sending" show Sent = "sent" show Failed = "failed" show Received = "received" show Delivered = "delivered" show Undelivered = "undelivered" instance FromJSON MessageStatus where parseJSON (String "queued") = return Queued parseJSON (String "sending") = return Sending parseJSON (String "sent") = return Sent parseJSON (String "failed") = return Failed parseJSON (String "received") = return Received parseJSON (String "delivered") = return Delivered parseJSON (String "undelivered") = return Undelivered parseJSON _ = mzero
null
https://raw.githubusercontent.com/markandrus/twilio-haskell/00704dc86dbf2117b855b1e2dcf8b6c0eff5bfbe/src/Twilio/Message.hs
haskell
#LANGUAGE OverloadedStrings # ----------------------------------------------------------------------------- | Module : Twilio.Message License : BSD-style (see the file LICENSE) Stability : provisional ----------------------------------------------------------------------------- * Resource * Types , price :: !Double <*> (v .: "num_segments" <&> fmap safeRead <*> (v .: "price" <&> fmap safeRead | Get a 'Message' by 'MessageSID'. Types
# LANGUAGE MultiParamTypeClasses # # LANGUAGE ViewPatterns # Copyright : ( C ) 2017- Maintainer : < > module Twilio.Message Message(..) , Twilio.Message.get , MessageDirection(..) , MessageStatus(..) ) where import Control.Monad import Control.Monad.Catch import Data.Aeson import Data.Monoid import Data.Text (Text) import Data.Time.Clock import Network.URI import Control.Monad.Twilio import Twilio.Internal.Parser import Twilio.Internal.Request import Twilio.Internal.Resource as Resource import Twilio.Types Resource data Message = Message { sid :: !MessageSID , dateCreated :: !UTCTime , dateUpdated :: !UTCTime , dateSent :: !(Maybe UTCTime) ^ This will be Nothing if has n't sent the message yet . , accountSID :: !AccountSID , to :: !Text , from :: !Text , body :: !Text , status :: !MessageStatus , numSegments : : ! Integer , direction :: !MessageDirection , priceUnit :: !PriceUnit , apiVersion :: !APIVersion , uri :: !URI } deriving (Show, Eq) instance FromJSON Message where parseJSON (Object v) = Message <$> v .: "sid" <*> (v .: "date_created" >>= parseDateTime) <*> (v .: "date_updated" >>= parseDateTime) <*> (v .:? "date_sent" >>= parseMaybeDateTime) <*> v .: "account_sid" <*> v .: "to" <*> v .: "from" <*> v .: "body" <*> v .: "status" > > = ) <*> v .: "direction" > > = ' ) <*> v .: "price_unit" <*> v .: "api_version" <*> (v .: "uri" <&> parseRelativeReference >>= maybeReturn) parseJSON _ = mzero instance Get1 MessageSID Message where get1 (getSID -> sid) = request parseJSONFromResponse =<< makeTwilioRequest ("/Messages/" <> sid <> ".json") get :: MonadThrow m => MessageSID -> TwilioT m Message get = Resource.get data MessageDirection = Inbound | OutboundAPI | OutboundCall | OutboundReply deriving Eq instance Show MessageDirection where show Inbound = "inbound" show OutboundAPI = "outbound-api" show OutboundCall = "outbound-call" show OutboundReply = "outbound-reply" instance FromJSON MessageDirection where parseJSON (String "inbound") = return Inbound parseJSON (String "outbound-api") = return OutboundAPI parseJSON (String "outbound-call") = return OutboundCall parseJSON (String "outbound-reply") = return OutboundReply parseJSON _ = mzero data MessageStatus = Queued | Sending | Sent | Failed | Received | Delivered | Undelivered deriving Eq instance Show MessageStatus where show Queued = "queued" show Sending = "sending" show Sent = "sent" show Failed = "failed" show Received = "received" show Delivered = "delivered" show Undelivered = "undelivered" instance FromJSON MessageStatus where parseJSON (String "queued") = return Queued parseJSON (String "sending") = return Sending parseJSON (String "sent") = return Sent parseJSON (String "failed") = return Failed parseJSON (String "received") = return Received parseJSON (String "delivered") = return Delivered parseJSON (String "undelivered") = return Undelivered parseJSON _ = mzero
45b027b6b9165ca2096d684739c6f5e57d007592c9bd020d230affde22fa521f
geneweb/geneweb
test_mergeInd.ml
open Geneweb open OUnit2 open Def let empty_string = 0 let quest_string = 1 let ascend parents = { Gwdb.no_ascend with Def.parents } let descend children = { Def.children } let union family = { Def.family } let couple a b = Adef.couple a b let person i = { (Mutil.empty_person empty_string quest_string) with occ = i; key_index = i } let family i = { (Mutil.empty_family empty_string) with fam_index = i } let iper (i : int) : Gwdb.iper = Obj.magic i let test_is_ancestor = let child = person 0 in let father = person 1 in let mother = person 2 in let persons = [| child; father; mother |] in let ascends = [| ascend (Some 0); ascend None; ascend None |] in let unions = [| union [||]; union [| 0 |]; union [| 0 |] |] in let families = [| family 0 |] in let couples = [| couple 1 2 |] in let descends = [| descend [| 0 |] |] in let strings = [| ""; "?" |] in let base_notes = { nread = (fun _ _ -> ""); norigin_file = ""; efiles = (fun () -> []) } in let data = ( (persons, ascends, unions), (families, couples, descends), strings, base_notes ) in let base = Gwdb.make "" [] data in let child = Gwdb.poi base (iper 0) in let father = Gwdb.poi base (iper 1) in let mother = Gwdb.poi base (iper 2) in let test exp p1 p2 _ = assert_equal exp (MergeInd.is_ancestor base p1 p2) in [ "is_ancetor child father" >:: test false child father; "is_ancetor father child" >:: test true father child; "is_ancetor mother child" >:: test true mother child; ] let suite = [ "MergeInd.is_ancestor" >::: test_is_ancestor ]
null
https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/test/test_mergeInd.ml
ocaml
open Geneweb open OUnit2 open Def let empty_string = 0 let quest_string = 1 let ascend parents = { Gwdb.no_ascend with Def.parents } let descend children = { Def.children } let union family = { Def.family } let couple a b = Adef.couple a b let person i = { (Mutil.empty_person empty_string quest_string) with occ = i; key_index = i } let family i = { (Mutil.empty_family empty_string) with fam_index = i } let iper (i : int) : Gwdb.iper = Obj.magic i let test_is_ancestor = let child = person 0 in let father = person 1 in let mother = person 2 in let persons = [| child; father; mother |] in let ascends = [| ascend (Some 0); ascend None; ascend None |] in let unions = [| union [||]; union [| 0 |]; union [| 0 |] |] in let families = [| family 0 |] in let couples = [| couple 1 2 |] in let descends = [| descend [| 0 |] |] in let strings = [| ""; "?" |] in let base_notes = { nread = (fun _ _ -> ""); norigin_file = ""; efiles = (fun () -> []) } in let data = ( (persons, ascends, unions), (families, couples, descends), strings, base_notes ) in let base = Gwdb.make "" [] data in let child = Gwdb.poi base (iper 0) in let father = Gwdb.poi base (iper 1) in let mother = Gwdb.poi base (iper 2) in let test exp p1 p2 _ = assert_equal exp (MergeInd.is_ancestor base p1 p2) in [ "is_ancetor child father" >:: test false child father; "is_ancetor father child" >:: test true father child; "is_ancetor mother child" >:: test true mother child; ] let suite = [ "MergeInd.is_ancestor" >::: test_is_ancestor ]
9036dce8e2448a5e5ec5a66d9b099c976dca15b21af997e165650cf4b75a2237
melange-re/melange
build_version.ml
let ( .?() ) = Map_string.find_opt let file_contents ~version = Format.asprintf {| Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * 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 , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU 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 . * * 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, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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. *) let version = %S let header = "// Generated by Melange" |} version let pkg_json = "../../package.json" type json_map = Ext_json_types.t Map_string.t let extract_package_version (map : json_map) = match map.?("version") with | Some (Str { str = version; _ }) -> version | None | Some _ -> failwith "version field expects a string" let build_version () = let version = match Ext_json_parse.parse_json_from_file pkg_json with | Obj { map; _ } -> extract_package_version map | _ -> assert false in let target = Sys.argv.(1) in let content = file_contents ~version in let f = open_out_bin target in output_string f content; close_out f let () = build_version ()
null
https://raw.githubusercontent.com/melange-re/melange/a4f572e5acb261178e6d8aafac77f1b5eaef213b/jscomp/build_version.ml
ocaml
let ( .?() ) = Map_string.find_opt let file_contents ~version = Format.asprintf {| Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * 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 , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU 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 . * * 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, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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. *) let version = %S let header = "// Generated by Melange" |} version let pkg_json = "../../package.json" type json_map = Ext_json_types.t Map_string.t let extract_package_version (map : json_map) = match map.?("version") with | Some (Str { str = version; _ }) -> version | None | Some _ -> failwith "version field expects a string" let build_version () = let version = match Ext_json_parse.parse_json_from_file pkg_json with | Obj { map; _ } -> extract_package_version map | _ -> assert false in let target = Sys.argv.(1) in let content = file_contents ~version in let f = open_out_bin target in output_string f content; close_out f let () = build_version ()
00327de1d0a69dd6f49a613d047ce92f7ba9512216794e2a4d00a10efdf2dd3b
kyleburton/sandbox
project.clj
(defproject gherkin "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :main ^:skip-aot gherkin.core :jvm-opts ["-Xmx512m" "-server" "-Dorg.quartz.scheduler.skipUpdateCheck=true"] :dependencies [ [org.clojure/clojure "1.6.0"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] [org.clojure/tools.logging "1.2.1"] [org.clojure/tools.nrepl "0.2.3"] [cider/cider-nrepl "0.7.0"] [org.clojure/data.json "0.2.5"] [prismatic/schema "0.3.1"] [clj-time "0.8.0"] [org.clojure/core.cache "0.6.4"] [org.clojure/data.csv "0.1.2"] ])
null
https://raw.githubusercontent.com/kyleburton/sandbox/1164c96c1c0de0948e8666e2ad8a06bbc673d37a/examples/clojure/gherkin/project.clj
clojure
(defproject gherkin "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :main ^:skip-aot gherkin.core :jvm-opts ["-Xmx512m" "-server" "-Dorg.quartz.scheduler.skipUpdateCheck=true"] :dependencies [ [org.clojure/clojure "1.6.0"] [org.clojure/core.async "0.1.346.0-17112a-alpha"] [org.clojure/tools.logging "1.2.1"] [org.clojure/tools.nrepl "0.2.3"] [cider/cider-nrepl "0.7.0"] [org.clojure/data.json "0.2.5"] [prismatic/schema "0.3.1"] [clj-time "0.8.0"] [org.clojure/core.cache "0.6.4"] [org.clojure/data.csv "0.1.2"] ])
15472a2436880bef233bdd8f72635ed87cafee6c8db73d590621b15376f4fc8a
jephthai/NTFSx
SectorDump.hs
-- SectorDump.hs: -- -- This is a module that exports block ranges from a disk using the -- Win32 API. It expects to have a handle provided which can be created with the " CreateFile ( ) " Win32 API call . -- -- Author : -- Contact: Created : 2012 -- module SectorDump ( exportSectors, exportRuns ) where import System.Win32.File import System.Win32.Types import Foreign.Marshal.Alloc import Foreign.Storable import Foreign.Ptr import Data.Word import Data.Bits import Unsafe.Coerce import Control.Monad -- System . Win32.File does not import the SetFilePointer ( ) function . -- This is a usable import that will allow me to seek the file HANDLE -- to whatever byte offset I want. -- foreign import stdcall unsafe "windows.h SetFilePointer" c_setFilePointer :: HANDLE -> DWORD -> Ptr a -> DWORD -> IO () -- This is a wrapper for my import above that seeks to a block offset ( 512 - byte blocks ) . -- setFilePointer :: HANDLE -> Integer -> IO () setFilePointer h offset = do p <- mallocBytes 4 poke (castPtr p) high c_setFilePointer h low p 0 free p where block = fromIntegral (offset * 512) :: Word64 low = unsafeCoerce (block .&. 0xffffffff) :: Word32 high = unsafeCoerce (block `shift` (-32)) .&. 0xffffffff :: Word32 -- -- Given a buffer, this function will return a single byte at the req- -- uested offset. -- secReadByte :: Ptr Word8 -> Int -> IO Word8 secReadByte mem addr = peek offset where offset = mem `plusPtr` addr -- -- The primary functionality I need, disk-wise, is to read a single block from one HANDLE and write the same data out to another one . -- readWriteBlock h1 h2 = do buffer <- mallocBytes 512 count <- win32_ReadFile h1 buffer 512 Nothing win32_WriteFile h2 buffer count Nothing free buffer return count secReadBlock :: HANDLE -> IO [Word8] secReadBlock h = do buffer <- mallocBytes 512 win32_ReadFile h buffer 512 Nothing ws <- mapM (secReadByte buffer) [0..511] free buffer return ws exportRuns h outfile runs = do out <- createFile outfile gENERIC_WRITE 3 Nothing cREATE_ALWAYS fILE_ATTRIBUTE_NORMAL Nothing forM_ runs $ \(offset, count) -> do setFilePointer h offset forM [1..count] $ \_ -> readWriteBlock h out return () exportSectors h outfile start count = do out <- createFile outfile gENERIC_WRITE 3 Nothing cREATE_ALWAYS fILE_ATTRIBUTE_NORMAL Nothing setFilePointer h start mapM_ (\_ -> readWriteBlock h out) [1..count] closeHandle out
null
https://raw.githubusercontent.com/jephthai/NTFSx/f4a613262a7da8239b5281ed503d3aaa5378b4f2/SectorDump.hs
haskell
SectorDump.hs: This is a module that exports block ranges from a disk using the Win32 API. It expects to have a handle provided which can be Contact: This is a usable import that will allow me to seek the file HANDLE to whatever byte offset I want. Given a buffer, this function will return a single byte at the req- uested offset. The primary functionality I need, disk-wise, is to read a single
created with the " CreateFile ( ) " Win32 API call . Author : Created : 2012 module SectorDump ( exportSectors, exportRuns ) where import System.Win32.File import System.Win32.Types import Foreign.Marshal.Alloc import Foreign.Storable import Foreign.Ptr import Data.Word import Data.Bits import Unsafe.Coerce import Control.Monad System . Win32.File does not import the SetFilePointer ( ) function . foreign import stdcall unsafe "windows.h SetFilePointer" c_setFilePointer :: HANDLE -> DWORD -> Ptr a -> DWORD -> IO () This is a wrapper for my import above that seeks to a block offset ( 512 - byte blocks ) . setFilePointer :: HANDLE -> Integer -> IO () setFilePointer h offset = do p <- mallocBytes 4 poke (castPtr p) high c_setFilePointer h low p 0 free p where block = fromIntegral (offset * 512) :: Word64 low = unsafeCoerce (block .&. 0xffffffff) :: Word32 high = unsafeCoerce (block `shift` (-32)) .&. 0xffffffff :: Word32 secReadByte :: Ptr Word8 -> Int -> IO Word8 secReadByte mem addr = peek offset where offset = mem `plusPtr` addr block from one HANDLE and write the same data out to another one . readWriteBlock h1 h2 = do buffer <- mallocBytes 512 count <- win32_ReadFile h1 buffer 512 Nothing win32_WriteFile h2 buffer count Nothing free buffer return count secReadBlock :: HANDLE -> IO [Word8] secReadBlock h = do buffer <- mallocBytes 512 win32_ReadFile h buffer 512 Nothing ws <- mapM (secReadByte buffer) [0..511] free buffer return ws exportRuns h outfile runs = do out <- createFile outfile gENERIC_WRITE 3 Nothing cREATE_ALWAYS fILE_ATTRIBUTE_NORMAL Nothing forM_ runs $ \(offset, count) -> do setFilePointer h offset forM [1..count] $ \_ -> readWriteBlock h out return () exportSectors h outfile start count = do out <- createFile outfile gENERIC_WRITE 3 Nothing cREATE_ALWAYS fILE_ATTRIBUTE_NORMAL Nothing setFilePointer h start mapM_ (\_ -> readWriteBlock h out) [1..count] closeHandle out
836024147ef397920aef42d1018a276d33ff0d01690373447500e2fc62d6ef03
huangjs/cl
terminfo.lisp
;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: TERMINFO -*- Copyright © 2001 ( ) ;;; ;;; Permission is hereby granted, free of charge, to any person obtaining a copy of this Software to deal in the Software without restriction , ;;; including without limitation the rights to use, copy, modify, merge, publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , ;;; provided that the above copyright notice and this permission notice are included in all copies or substantial portions of the Software . ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHOR OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT ;;; OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR ;;; BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE ;;; USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;;; DAMAGE. #+CMU (ext:file-comment "$Header: /home/paul/public_html/actrix/RCS/terminfo.lisp,v 1.9 2006/10/21 05:53:59 paul Exp paul $") (in-package "COMMON-LISP-USER") ;; DEFPACKAGE would warn here, since we export things outside the definition (eval-when (:compile-toplevel :load-toplevel) (unless (find-package "TERMINFO") (make-package "TERMINFO" :nicknames '("TI") :use '("CL")))) (in-package "TERMINFO") (export '(*terminfo-directories* *terminfo* capability tparm tputs set-terminal)) (defvar *terminfo-directories* '("/usr/share/terminfo/" "/usr/share/misc/terminfo/")) (defvar *terminfo* nil) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *capabilities* (make-hash-table :size 494))) (flet ((required-argument () (error "A required argument was not supplied."))) (defstruct (terminfo (:print-function (lambda (object stream depth) (declare (ignore depth)) (print-unreadable-object (object stream :type t :identity t) (format stream "~A" (first (terminfo-names object))))))) (names (required-argument) :type list :read-only t) (booleans (required-argument) :type (simple-array (member t nil) (*))) (numbers (required-argument) :type (simple-array (signed-byte 16) (*))) (strings (required-argument) :type (simple-array t (*))))) #+CMU (declaim (ext:start-block capability %capability)) (defun %capability (name terminfo) (let ((whatsit (gethash name *capabilities*))) (when (null whatsit) (error "Terminfo capability ~S doesn't exist." name)) (if (or (null terminfo) (>= (cdr whatsit) (length (funcall (car whatsit) terminfo)))) nil #| default |# (let ((value (aref (funcall (car whatsit) terminfo) (cdr whatsit)))) (if (and (numberp value) (minusp value)) nil value))))) (declaim (inline capability)) (defun capability (name &optional (terminfo *terminfo*)) (%capability name terminfo)) #+CMU (declaim (ext:end-block)) (define-compiler-macro capability (&whole form name &optional (terminfo '*terminfo*)) (if (not (keywordp name)) form (let ((value (gensym)) (tmp (gensym))) (unless (gethash name *capabilities*) (warn "Terminfo capability ~S doesn't exist." name)) `(let ((,value (load-time-value (cons nil nil))) (,tmp ,terminfo)) (if (eq (car ,value) ,tmp) (cdr ,value) (setf (car ,value) ,tmp (cdr ,value) (%capability ,name ,tmp))))))) (defmacro defcap (name type index &optional docstring) (let ((thing (ecase type (boolean 'terminfo-booleans) (integer 'terminfo-numbers) (string 'terminfo-strings))) (symbol (intern (string name) "KEYWORD"))) `(progn (eval-when (:compile-toplevel) ;; Mark capability as valid for the compiler-macro; needed when compiling TPUTS . If there 's already a value present , leave ;; it alone, else just put any non-NIL value there; it'll get ;; fixed up when the file is loaded. (setf (gethash ,symbol *capabilities*) (gethash ,symbol *capabilities* t))) (setf (gethash ,symbol *capabilities*) (cons #',thing ,index)) (define-symbol-macro ,name (capability ,symbol *terminfo*)) ,(when docstring `(setf (documentation ',name 'variable) ,docstring)) (export ',name "TERMINFO")))) (defcap auto-left-margin boolean 0) (defcap auto-right-margin boolean 1) (defcap no-esc-ctlc boolean 2) (defcap ceol-standout-glitch boolean 3) (defcap eat-newline-glitch boolean 4) (defcap erase-overstrike boolean 5) (defcap generic-type boolean 6) (defcap hard-copy boolean 7) (defcap has-meta-key boolean 8) (defcap has-status-line boolean 9) (defcap insert-null-glitch boolean 10) (defcap memory-above boolean 11) (defcap memory-below boolean 12) (defcap move-insert-mode boolean 13) (defcap move-standout-mode boolean 14) (defcap over-strike boolean 15) (defcap status-line-esc-ok boolean 16) (defcap dest-tabs-magic-smso boolean 17) (defcap tilde-glitch boolean 18) (defcap transparent-underline boolean 19) (defcap xon-xoff boolean 20) (defcap needs-xon-xoff boolean 21) (defcap prtr-silent boolean 22) (defcap hard-cursor boolean 23) (defcap non-rev-rmcup boolean 24) (defcap no-pad-char boolean 25) (defcap non-dest-scroll-region boolean 26) (defcap can-change boolean 27) (defcap back-color-erase boolean 28) (defcap hue-lightness-saturation boolean 29) (defcap col-addr-glitch boolean 30) (defcap cr-cancels-micro-mode boolean 31) (defcap has-print-wheel boolean 32) (defcap row-addr-glitch boolean 33) (defcap semi-auto-right-margin boolean 34) (defcap cpi-changes-res boolean 35) (defcap lpi-changes-res boolean 36) (defcap columns integer 0) (defcap init-tabs integer 1) (defcap lines integer 2) (defcap lines-of-memory integer 3) (defcap magic-cookie-glitch integer 4) (defcap padding-baud-rate integer 5) (defcap virtual-terminal integer 6) (defcap width-status-line integer 7) (defcap num-labels integer 8) (defcap label-height integer 9) (defcap label-width integer 10) (defcap max-attributes integer 11) (defcap maximum-windows integer 12) (defcap max-colors integer 13) (defcap max-pairs integer 14) (defcap no-color-video integer 15) (defcap buffer-capacity integer 16) (defcap dot-vert-spacing integer 17) (defcap dot-horz-spacing integer 18) (defcap max-micro-address integer 19) (defcap max-micro-jump integer 20) (defcap micro-col-size integer 21) (defcap micro-line-size integer 22) (defcap number-of-pins integer 23) (defcap output-res-char integer 24) (defcap output-res-line integer 25) (defcap output-res-horz-inch integer 26) (defcap output-res-vert-inch integer 27) (defcap print-rate integer 28) (defcap wide-char-size integer 29) (defcap buttons integer 30) (defcap bit-image-entwining integer 31) (defcap bit-image-type integer 32) (defcap back-tab string 0) (defcap bell string 1) (defcap carriage-return string 2) (defcap change-scroll-region string 3) (defcap clear-all-tabs string 4) (defcap clear-screen string 5) (defcap clr-eol string 6) (defcap clr-eos string 7) (defcap column-address string 8) (defcap command-character string 9) (defcap cursor-address string 10) (defcap cursor-down string 11) (defcap cursor-home string 12) (defcap cursor-invisible string 13) (defcap cursor-left string 14) (defcap cursor-mem-address string 15) (defcap cursor-normal string 16) (defcap cursor-right string 17) (defcap cursor-to-ll string 18) (defcap cursor-up string 19) (defcap cursor-visible string 20) (defcap delete-character string 21) (defcap delete-line string 22) (defcap dis-status-line string 23) (defcap down-half-line string 24) (defcap enter-alt-charset-mode string 25) (defcap enter-blink-mode string 26) (defcap enter-bold-mode string 27) (defcap enter-ca-mode string 28) (defcap enter-delete-mode string 29) (defcap enter-dim-mode string 30) (defcap enter-insert-mode string 31) (defcap enter-secure-mode string 32) (defcap enter-protected-mode string 33) (defcap enter-reverse-mode string 34) (defcap enter-standout-mode string 35) (defcap enter-underline-mode string 36) (defcap erase-chars string 37) (defcap exit-alt-charset-mode string 38) (defcap exit-attribute-mode string 39) (defcap exit-ca-mode string 40) (defcap exit-delete-mode string 41) (defcap exit-insert-mode string 42) (defcap exit-standout-mode string 43) (defcap exit-underline-mode string 44) (defcap flash-screen string 45) (defcap form-feed string 46) (defcap from-status-line string 47) (defcap init-1string string 48) (defcap init-2string string 49) (defcap init-3string string 50) (defcap init-file string 51) (defcap insert-character string 52) (defcap insert-line string 53) (defcap insert-padding string 54) (defcap key-backspace string 55) (defcap key-catab string 56) (defcap key-clear string 57) (defcap key-ctab string 58) (defcap key-dc string 59) (defcap key-dl string 60) (defcap key-down string 61) (defcap key-eic string 62) (defcap key-eol string 63) (defcap key-eos string 64) (defcap key-f0 string 65) (defcap key-f1 string 66) (defcap key-f10 string 67) (defcap key-f2 string 68) (defcap key-f3 string 69) (defcap key-f4 string 70) (defcap key-f5 string 71) (defcap key-f6 string 72) (defcap key-f7 string 73) (defcap key-f8 string 74) (defcap key-f9 string 75) (defcap key-home string 76) (defcap key-ic string 77) (defcap key-il string 78) (defcap key-left string 79) (defcap key-ll string 80) (defcap key-npage string 81) (defcap key-ppage string 82) (defcap key-right string 83) (defcap key-sf string 84) (defcap key-sr string 85) (defcap key-stab string 86) (defcap key-up string 87) (defcap keypad-local string 88) (defcap keypad-xmit string 89) (defcap lab-f0 string 90) (defcap lab-f1 string 91) (defcap lab-f10 string 92) (defcap lab-f2 string 93) (defcap lab-f3 string 94) (defcap lab-f4 string 95) (defcap lab-f5 string 96) (defcap lab-f6 string 97) (defcap lab-f7 string 98) (defcap lab-f8 string 99) (defcap lab-f9 string 100) (defcap meta-off string 101) (defcap meta-on string 102) (defcap newline string 103) (defcap pad-char string 104) (defcap parm-dch string 105) (defcap parm-delete-line string 106) (defcap parm-down-cursor string 107) (defcap parm-ich string 108) (defcap parm-index string 109) (defcap parm-insert-line string 110) (defcap parm-left-cursor string 111) (defcap parm-right-cursor string 112) (defcap parm-rindex string 113) (defcap parm-up-cursor string 114) (defcap pkey-key string 115) (defcap pkey-local string 116) (defcap pkey-xmit string 117) (defcap print-screen string 118) (defcap prtr-off string 119) (defcap prtr-on string 120) (defcap repeat-char string 121) (defcap reset-1string string 122) (defcap reset-2string string 123) (defcap reset-3string string 124) (defcap reset-file string 125) (defcap restore-cursor string 126) (defcap row-address string 127) (defcap save-cursor string 128) (defcap scroll-forward string 129) (defcap scroll-reverse string 130) (defcap set-attributes string 131) (defcap set-tab string 132) (defcap set-window string 133) (defcap tab string 134) (defcap to-status-line string 135) (defcap underline-char string 136) (defcap up-half-line string 137) (defcap init-prog string 138) (defcap key-a1 string 139) (defcap key-a3 string 140) (defcap key-b2 string 141) (defcap key-c1 string 142) (defcap key-c3 string 143) (defcap prtr-non string 144) (defcap char-padding string 145) (defcap acs-chars string 146) (defcap plab-norm string 147) (defcap key-btab string 148) (defcap enter-xon-mode string 149) (defcap exit-xon-mode string 150) (defcap enter-am-mode string 151) (defcap exit-am-mode string 152) (defcap xon-character string 153) (defcap xoff-character string 154) (defcap ena-acs string 155) (defcap label-on string 156) (defcap label-off string 157) (defcap key-beg string 158) (defcap key-cancel string 159) (defcap key-close string 160) (defcap key-command string 161) (defcap key-copy string 162) (defcap key-create string 163) (defcap key-end string 164) (defcap key-enter string 165) (defcap key-exit string 166) (defcap key-find string 167) (defcap key-help string 168) (defcap key-mark string 169) (defcap key-message string 170) (defcap key-move string 171) (defcap key-next string 172) (defcap key-open string 173) (defcap key-options string 174) (defcap key-previous string 175) (defcap key-print string 176) (defcap key-redo string 177) (defcap key-reference string 178) (defcap key-refresh string 179) (defcap key-replace string 180) (defcap key-restart string 181) (defcap key-resume string 182) (defcap key-save string 183) (defcap key-suspend string 184) (defcap key-undo string 185) (defcap key-sbeg string 186) (defcap key-scancel string 187) (defcap key-scommand string 188) (defcap key-scopy string 189) (defcap key-screate string 190) (defcap key-sdc string 191) (defcap key-sdl string 192) (defcap key-select string 193) (defcap key-send string 194) (defcap key-seol string 195) (defcap key-sexit string 196) (defcap key-sfind string 197) (defcap key-shelp string 198) (defcap key-shome string 199) (defcap key-sic string 200) (defcap key-sleft string 201) (defcap key-smessage string 202) (defcap key-smove string 203) (defcap key-snext string 204) (defcap key-soptions string 205) (defcap key-sprevious string 206) (defcap key-sprint string 207) (defcap key-sredo string 208) (defcap key-sreplace string 209) (defcap key-sright string 210) (defcap key-srsume string 211) (defcap key-ssave string 212) (defcap key-ssuspend string 213) (defcap key-sundo string 214) (defcap req-for-input string 215) (defcap key-f11 string 216) (defcap key-f12 string 217) (defcap key-f13 string 218) (defcap key-f14 string 219) (defcap key-f15 string 220) (defcap key-f16 string 221) (defcap key-f17 string 222) (defcap key-f18 string 223) (defcap key-f19 string 224) (defcap key-f20 string 225) (defcap key-f21 string 226) (defcap key-f22 string 227) (defcap key-f23 string 228) (defcap key-f24 string 229) (defcap key-f25 string 230) (defcap key-f26 string 231) (defcap key-f27 string 232) (defcap key-f28 string 233) (defcap key-f29 string 234) (defcap key-f30 string 235) (defcap key-f31 string 236) (defcap key-f32 string 237) (defcap key-f33 string 238) (defcap key-f34 string 239) (defcap key-f35 string 240) (defcap key-f36 string 241) (defcap key-f37 string 242) (defcap key-f38 string 243) (defcap key-f39 string 244) (defcap key-f40 string 245) (defcap key-f41 string 246) (defcap key-f42 string 247) (defcap key-f43 string 248) (defcap key-f44 string 249) (defcap key-f45 string 250) (defcap key-f46 string 251) (defcap key-f47 string 252) (defcap key-f48 string 253) (defcap key-f49 string 254) (defcap key-f50 string 255) (defcap key-f51 string 256) (defcap key-f52 string 257) (defcap key-f53 string 258) (defcap key-f54 string 259) (defcap key-f55 string 260) (defcap key-f56 string 261) (defcap key-f57 string 262) (defcap key-f58 string 263) (defcap key-f59 string 264) (defcap key-f60 string 265) (defcap key-f61 string 266) (defcap key-f62 string 267) (defcap key-f63 string 268) (defcap clr-bol string 269) (defcap clear-margins string 270) (defcap set-left-margin string 271) (defcap set-right-margin string 272) (defcap label-format string 273) (defcap set-clock string 274) (defcap display-clock string 275) (defcap remove-clock string 276) (defcap create-window string 277) (defcap goto-window string 278) (defcap hangup string 279) (defcap dial-phone string 280) (defcap quick-dial string 281) (defcap tone string 282) (defcap pulse string 283) (defcap flash-hook string 284) (defcap fixed-pause string 285) (defcap wait-tone string 286) (defcap user0 string 287) (defcap user1 string 288) (defcap user2 string 289) (defcap user3 string 290) (defcap user4 string 291) (defcap user5 string 292) (defcap user6 string 293) (defcap user7 string 294) (defcap user8 string 295) (defcap user9 string 296) (defcap orig-pair string 297) (defcap orig-colors string 298) (defcap initialize-color string 299) (defcap initialize-pair string 300) (defcap set-color-pair string 301) (defcap set-foreground string 302) (defcap set-background string 303) (defcap change-char-pitch string 304) (defcap change-line-pitch string 305) (defcap change-res-horz string 306) (defcap change-res-vert string 307) (defcap define-char string 308) (defcap enter-doublewide-mode string 309) (defcap enter-draft-quality string 310) (defcap enter-italics-mode string 311) (defcap enter-leftward-mode string 312) (defcap enter-micro-mode string 313) (defcap enter-near-letter-quality string 314) (defcap enter-normal-quality string 315) (defcap enter-shadow-mode string 316) (defcap enter-subscript-mode string 317) (defcap enter-superscript-mode string 318) (defcap enter-upward-mode string 319) (defcap exit-doublewide-mode string 320) (defcap exit-italics-mode string 321) (defcap exit-leftward-mode string 322) (defcap exit-micro-mode string 323) (defcap exit-shadow-mode string 324) (defcap exit-subscript-mode string 325) (defcap exit-superscript-mode string 326) (defcap exit-upward-mode string 327) (defcap micro-column-address string 328) (defcap micro-down string 329) (defcap micro-left string 330) (defcap micro-right string 331) (defcap micro-row-address string 332) (defcap micro-up string 333) (defcap order-of-pins string 334) (defcap parm-down-micro string 335) (defcap parm-left-micro string 336) (defcap parm-right-micro string 337) (defcap parm-up-micro string 338) (defcap select-char-set string 339) (defcap set-bottom-margin string 340) (defcap set-bottom-margin-parm string 341) (defcap set-left-margin-parm string 342) (defcap set-right-margin-parm string 343) (defcap set-top-margin string 344) (defcap set-top-margin-parm string 345) (defcap start-bit-image string 346) (defcap start-char-set-def string 347) (defcap stop-bit-image string 348) (defcap stop-char-set-def string 349) (defcap subscript-characters string 350) (defcap superscript-characters string 351) (defcap these-cause-cr string 352) (defcap zero-motion string 353) (defcap char-set-names string 354) (defcap key-mouse string 355) (defcap mouse-info string 356) (defcap req-mouse-pos string 357) (defcap get-mouse string 358) (defcap set-a-foreground string 359) (defcap set-a-background string 360) (defcap pkey-plab string 361) (defcap device-type string 362) (defcap code-set-init string 363) (defcap set0-des-seq string 364) (defcap set1-des-seq string 365) (defcap set2-des-seq string 366) (defcap set3-des-seq string 367) (defcap set-lr-margin string 368) (defcap set-tb-margin string 369) (defcap bit-image-repeat string 370) (defcap bit-image-newline string 371) (defcap bit-image-carriage-return string 372) (defcap color-names string 373) (defcap define-bit-image-region string 374) (defcap end-bit-image-region string 375) (defcap set-color-band string 376) (defcap set-page-length string 377) (defcap display-pc-char string 378) (defcap enter-pc-charset-mode string 379) (defcap exit-pc-charset-mode string 380) (defcap enter-scancode-mode string 381) (defcap exit-scancode-mode string 382) (defcap pc-term-options string 383) (defcap scancode-escape string 384) (defcap alt-scancode-esc string 385) (defcap enter-horizontal-hl-mode string 386) (defcap enter-left-hl-mode string 387) (defcap enter-low-hl-mode string 388) (defcap enter-right-hl-mode string 389) (defcap enter-top-hl-mode string 390) (defcap enter-vertical-hl-mode string 391) (defcap set-a-attributes string 392) (defcap set-pglen-inch string 393) # + INTERNAL - CAPS - VISIBLE (progn (defcap termcap-init2 string 394) (defcap termcap-reset string 395) (defcap magic-cookie-glitch-ul integer 33) (defcap backspaces-with-bs boolean 37) (defcap crt-no-scrolling boolean 38) (defcap no-correctly-working-cr boolean 39) (defcap carriage-return-delay integer 34) (defcap new-line-delay integer 35) (defcap linefeed-if-not-lf string 396) (defcap backspace-if-not-bs string 397) (defcap gnu-has-meta-key boolean 40) (defcap linefeed-is-newline boolean 41) (defcap backspace-delay integer 36) (defcap horizontal-tab-delay integer 37) (defcap number-of-function-keys integer 38) (defcap other-non-function-keys string 398) (defcap arrow-key-map string 399) (defcap has-hardware-tabs boolean 42) (defcap return-does-clr-eol boolean 43) (defcap acs-ulcorner string 400) (defcap acs-llcorner string 401) (defcap acs-urcorner string 402) (defcap acs-lrcorner string 403) (defcap acs-ltee string 404) (defcap acs-rtee string 405) (defcap acs-btee string 406) (defcap acs-ttee string 407) (defcap acs-hline string 408) (defcap acs-vline string 409) (defcap acs-plus string 410) (defcap memory-lock string 411) (defcap memory-unlock string 412) (defcap box-chars-1 string 413)) (defun load-terminfo (name) (let ((name (concatenate 'string (list (char name 0) #\/) name))) (dolist (path (list* (merge-pathnames (make-pathname :directory '(:relative ".terminfo")) (user-homedir-pathname)) *terminfo-directories*)) (with-open-file (stream (merge-pathnames name path) :direction :input :element-type '(unsigned-byte 8) :if-does-not-exist nil) (when stream (flet ((read-short (stream) (let ((n (+ (read-byte stream) (* 256 (read-byte stream))))) (if (> n 32767) (- n 65536) n))) (read-string (stream) (do ((c (read-byte stream) (read-byte stream)) (s '())) ((zerop c) (coerce (nreverse s) 'string)) (push (code-char c) s)))) (let* ((magic (read-short stream)) (sznames (read-short stream)) (szbooleans (read-short stream)) (sznumbers (read-short stream)) (szstrings (read-short stream)) (szstringtable (read-short stream)) (names (let ((string (read-string stream))) (loop for i = 0 then (1+ j) as j = (position #\| string :start i) collect (subseq string i j) while j))) (booleans (make-array szbooleans :element-type '(or t nil) :initial-element nil)) (numbers (make-array sznumbers :element-type '(signed-byte 16) :initial-element -1)) (strings (make-array szstrings :element-type '(signed-byte 16) :initial-element -1)) (stringtable (make-string szstringtable)) (count 0)) (unless (= magic #o432) (error "Invalid file format")) (dotimes (i szbooleans) (setf (aref booleans i) (not (zerop (read-byte stream))))) (when (oddp (+ sznames szbooleans)) (read-byte stream)) (dotimes (i sznumbers) (setf (aref numbers i) (read-short stream))) (dotimes (i szstrings) (unless (minusp (setf (aref strings i) (read-short stream))) (incf count))) (dotimes (i szstringtable) (setf (char stringtable i) (code-char (read-byte stream)))) (let ((xtrings (make-array szstrings :initial-element nil))) (dotimes (i szstrings) (unless (minusp (aref strings i)) (setf (aref xtrings i) (subseq stringtable (aref strings i) (position #\Null stringtable :start (aref strings i)))))) (setq strings xtrings)) (return (make-terminfo :names names :booleans booleans :numbers numbers :strings strings))))))))) (defun xform (value format flags width precision) (let ((temp (make-array 8 :element-type 'character :fill-pointer 0 :adjustable t))) (flet ((shift (n c sign) (let ((len (length temp)) (s 0)) (when (and sign (> len 0) (char= (char temp 0) #\-)) (setq len (1- len) s 1)) (when (> (+ len n s) (array-dimension temp 0)) (adjust-array temp (+ len n 5))) (incf (fill-pointer temp) n) (replace temp temp :start1 (+ n s) :start2 s :end2 (+ s len)) (fill temp c :start s :end (+ n s))))) (format temp (ecase format (#\d "~D") (#\o "~O") (#\x "~(~X~)") (#\X "~:@(~X~)") (#\s "~A")) value) (when (position format "doxX") (let ((len (length temp))) (when (minusp value) (decf len)) (when (< len precision) (shift (- precision len) #\0 t))) (when (logbitp 0 flags) (case format (#\o (unless (char= (char temp (if (minusp value) 1 0)) #\0) (shift 1 #\0 t))) (#\x (shift 1 #\x t) (shift 1 #\0 t)) (#\X (shift 1 #\X t) (shift 1 #\0 t)))) (unless (minusp value) (cond ((logbitp 1 flags) (shift 1 #\+ nil)) ((logbitp 2 flags) (shift 1 #\Space nil))))) (when (and (eql format #\s) (> precision 0) (> (length temp) precision)) (setf (fill-pointer temp) precision)) (when (< (length temp) width) (if (logbitp 3 flags) (shift (- width (length temp)) #\Space nil) (dotimes (i (- width (length temp))) (vector-push-extend #\Space temp)))) temp))) (defun skip-forward (stream flag) (do ((level 0) (c (read-char stream nil) (read-char stream nil))) ((null c)) (when (char= c #\%) (setq c (read-char stream)) (cond ((char= c #\?) (incf level)) ) ( when ( minusp ( decf level ) ) ( return t ) ) ) ((and flag (char= c #\e) (= level 0)) (return t)))))) (defun tparm (string &rest args) (when (null string) (return-from tparm "")) (with-output-to-string (out) (with-input-from-string (in string) (do ((stack '()) (flags 0) (width 0) (precision 0) (number 0) (dvars (make-array 26 :element-type '(unsigned-byte 8) :initial-element 0)) (svars (load-time-value (make-array 26 :element-type '(unsigned-byte 8) :initial-element 0))) (c (read-char in nil) (read-char in nil))) ((null c)) (cond ((char= c #\%) (setq c (read-char in) flags 0 width 0 precision 0) (tagbody state0 (case c (#\% (princ c out) (go terminal)) (#\: (setq c (read-char in)) (go state2)) (#\+ (go state1)) (#\- (go state1)) (#\# (go state2)) (#\Space (go state2)) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (go state3)) (#\d (go state5)) (#\o (go state6)) ((#\X #\x) (go state7)) (#\s (go state8)) (#\c (princ (code-char (pop stack)) out) (go terminal)) (#\p (go state9)) (#\P (go state10)) (#\g (go state11)) (#\' (go state12)) (#\{ (go state13)) (#\l (push (length (pop stack)) stack) (go terminal)) (#\* (push (* (pop stack) (pop stack)) stack) (go terminal)) (#\/ (push (let ((n (pop stack))) (/ (pop stack) n)) stack) (go terminal)) (#\m (push (let ((n (pop stack))) (mod (pop stack) n)) stack) (go terminal)) (#\& (push (logand (pop stack) (pop stack)) stack) (go terminal)) (#\| (push (logior (pop stack) (pop stack)) stack) (go terminal)) (#\^ (push (logxor (pop stack) (pop stack)) stack) (go terminal)) (#\= (push (if (= (pop stack) (pop stack)) 1 0) stack) (go terminal)) (#\> (push (if (<= (pop stack) (pop stack)) 1 0) stack) (go terminal)) (#\< (push (if (>= (pop stack) (pop stack)) 1 0) stack) (go terminal)) (#\A (push (if (or (zerop (pop stack)) (zerop (pop stack))) 0 1) stack) (go terminal)) (#\O (push (if (and (zerop (pop stack)) (zerop (pop stack))) 0 1) stack) (go terminal)) (#\! (push (if (zerop (pop stack)) 1 0) stack) (go terminal)) (#\~ (push (logand #xFF (lognot (pop stack))) stack) (go terminal)) (#\i (when args (incf (first args)) (when (cdr args) (incf (second args)))) (go terminal)) (#\? (go state14)) (#\t (go state15)) (#\e (go state16)) (#\; (go state17)) (otherwise (error "Unknown %-control character: ~C" c))) state1 (let ((next (peek-char nil in nil))) (when (position next "0123456789# +-doXxs") (go state2))) (if (char= c #\+) (push (+ (pop stack) (pop stack)) stack) (push (let ((n (pop stack))) (- (pop stack) n)) stack)) (go terminal) state2 (case c (#\# (setf flags (logior flags 1))) (#\+ (setf flags (logior flags 2))) (#\Space (setf flags (logior flags 4))) (#\- (setf flags (logior flags 8))) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (go state3)) (t (go blah))) (setf c (read-char in)) (go state2) state3 (setf width (digit-char-p c)) state3-loop (setf c (read-char in)) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf width (+ (* width 10) (digit-char-p c))) (go state3-loop)) (#\. (setf c (read-char in)) (go state4))) (go blah) state4 (setf precision (digit-char-p c)) state4-loop (setf c (read-char in)) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf precision (+ (* precision 10) (digit-char-p c))) (go state4-loop))) (go blah) blah (case c (#\d (go state5)) (#\o (go state6)) ((#\X #\x) (go state7)) (#\s (go state8)) (otherwise (error "Unknown %-control character: ~C" c))) state5 state6 state7 state8 (princ (xform (pop stack) c flags width precision) out) (go terminal) state9 (let* ((i (digit-char-p (read-char in))) (a (nth (1- i) args))) (etypecase a (character (push (char-code a) stack)) (integer (push a stack)) (string (push a stack)))) (go terminal) state10 (let ((var (read-char in))) (cond ((char<= #\a var #\z) (setf (aref dvars (- (char-code var) (char-code #\a))) (pop stack))) ((char<= #\A var #\Z) (setf (aref svars (- (char-code var) (char-code #\A))) (pop stack))) (t (error "Illegal variable name: ~C" var)))) (go terminal) state11 (let ((var (read-char in))) (cond ((char<= #\a var #\z) (push (aref dvars (- (char-code var) (char-code #\a))) stack)) ((char<= #\A var #\Z) (push (aref svars (- (char-code var) (char-code #\A))) stack)) (t (error "Illegal variable name: ~C" var)))) (go terminal) state12 (push (char-code (read-char in)) stack) (unless (char= (read-char in) #\') (error "Invalid character constant")) (go terminal) state13 (setq number 0) state13-loop (setq c (read-char in)) (let ((n (digit-char-p c))) (cond (n (setq number (+ (* 10 number) n)) (go state13-loop)) ((char= c #\}) (push number stack) (go terminal)))) (error "Invalid integer constant") state14 (go terminal) state15 (when (/= (pop stack) 0) (go terminal)) (skip-forward in t) (go terminal) state16 (skip-forward in nil) state17 terminal #| that's all, folks |#)) (t (princ c out))))))) (defgeneric stream-fileno (stream) (:method ((stream stream)) nil) #+CMU (:method ((stream sys:fd-stream)) (sys:fd-stream-fd stream)) (:method ((stream two-way-stream)) (stream-fileno (two-way-stream-output-stream stream))) (:method ((stream synonym-stream)) (stream-fileno (symbol-value (synonym-stream-symbol stream)))) (:method ((stream echo-stream)) (stream-fileno (echo-stream-output-stream stream))) (:method ((stream broadcast-stream)) (stream-fileno (first (broadcast-stream-streams stream)))) #+(and CMU simple-streams) (:method ((stream stream:simple-stream)) (let ((fd (stream:stream-output-handle stream))) (if (or (null fd) (integerp fd)) fd (stream-fileno fd))))) (defun stream-baud-rate (stream) (declare (type stream stream) (values (or null (integer 0 4000000)))) #+CMU (alien:with-alien ((termios (alien:struct unix:termios))) (declare (optimize (ext:inhibit-warnings 3))) (when (unix:unix-tcgetattr (stream-fileno stream) termios) (let ((baud (logand unix:tty-cbaud (alien:slot termios 'unix:c-cflag)))) (if (< baud unix::tty-cbaudex) (aref #(0 50 75 110 134 150 200 300 600 1200 1800 2400 4800 9600 19200 38400) baud) (aref #(57600 115200 230400 460800 500000 576000 921600 1000000 1152000 1500000 2000000 2500000 3000000 3500000 4000000) (logxor baud unix::tty-cbaudex))))))) (defun terminal-size (&optional (stream *terminal-io*)) (declare (type stream stream)) #+CMU (alien:with-alien ((winsz (alien:struct unix:winsize))) (declare (optimize (ext:inhibit-warnings 3))) (if (unix:unix-ioctl (stream-fileno stream) unix:TIOCGWINSZ winsz) (values (alien:slot winsz 'unix:ws-row) (alien:slot winsz 'unix:ws-col)) (values nil nil)))) (defun tputs (string &rest args) (when string (let* ((stream (if (streamp (first args)) (pop args) *terminal-io*)) (terminfo (if (terminfo-p (first args)) (pop args) *terminfo*))) (with-input-from-string (string (apply #'tparm string args)) (do ((c (read-char string nil) (read-char string nil))) ((null c)) (cond ((and (char= c #\$) (eql (peek-char nil string nil) #\<)) (let ((time 0) (force nil) (rate nil) (pad #\Null)) ;; Find out how long to pad for: (read-char string) ; eat the #\< (loop (setq c (read-char string)) (let ((n (digit-char-p c))) (if n (setq time (+ (* time 10) n)) (return)))) (if (char= c #\.) (setq time (+ (* time 10) (digit-char-p (read-char string))) c (read-char string)) (setq time (* time 10))) (when (char= c #\*) ;; multiply time by "number of lines affected" ;; but how do I know that?? (setq c (read-char string))) (when (char= c #\/) (setq force t c (read-char string))) (unless (char= c #\>) (error "Invalid padding specification.")) ;; Decide whether to apply padding: (when (or force (not (capability :xon-xoff terminfo))) (setq rate (stream-baud-rate stream)) (when (let ((pb (capability :padding-baud-rate terminfo))) (and rate (or (null pb) (> rate pb)))) (cond ((capability :no-pad-char terminfo) (finish-output stream) (sleep (/ time 10000.0))) (t (let ((tmp (capability :pad-char terminfo))) (when tmp (setf pad (schar tmp 0)))) (dotimes (i (ceiling (* rate time) 100000)) (write-char pad stream)))))))) (t (write-char c stream)))))) t)) (defun set-terminal (&optional name) (setf *terminfo* (load-terminfo (or name #+CMU (cdr (assoc "TERM" ext:*environment-list* :test #'string=)) #+Allegro (sys:getenv "TERM") #+SBCL (sb-ext:posix-getenv "TERM") #+lispworks (lispworks:environment-variable "TERM") #| if all else fails |# "dumb")))) ;;(if (null *terminfo*) ;; (set-terminal)) (provide :terminfo)
null
https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/utils/terminfo.lisp
lisp
-*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: TERMINFO -*- Permission is hereby granted, free of charge, to any person obtaining including without limitation the rights to use, copy, modify, merge, provided that the above copyright notice and this permission notice OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. DEFPACKAGE would warn here, since we export things outside the definition default Mark capability as valid for the compiler-macro; needed when it alone, else just put any non-NIL value there; it'll get fixed up when the file is loaded. (go state17)) that's all, folks Find out how long to pad for: eat the #\< multiply time by "number of lines affected" but how do I know that?? Decide whether to apply padding: if all else fails (if (null *terminfo*) (set-terminal))
Copyright © 2001 ( ) a copy of this Software to deal in the Software without restriction , publish , distribute , sublicense , and/or sell copies of the Software , and to permit persons to whom the Software is furnished to do so , are included in all copies or substantial portions of the Software . THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS ARE DISCLAIMED . IN NO EVENT SHALL THE AUTHOR OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT #+CMU (ext:file-comment "$Header: /home/paul/public_html/actrix/RCS/terminfo.lisp,v 1.9 2006/10/21 05:53:59 paul Exp paul $") (in-package "COMMON-LISP-USER") (eval-when (:compile-toplevel :load-toplevel) (unless (find-package "TERMINFO") (make-package "TERMINFO" :nicknames '("TI") :use '("CL")))) (in-package "TERMINFO") (export '(*terminfo-directories* *terminfo* capability tparm tputs set-terminal)) (defvar *terminfo-directories* '("/usr/share/terminfo/" "/usr/share/misc/terminfo/")) (defvar *terminfo* nil) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *capabilities* (make-hash-table :size 494))) (flet ((required-argument () (error "A required argument was not supplied."))) (defstruct (terminfo (:print-function (lambda (object stream depth) (declare (ignore depth)) (print-unreadable-object (object stream :type t :identity t) (format stream "~A" (first (terminfo-names object))))))) (names (required-argument) :type list :read-only t) (booleans (required-argument) :type (simple-array (member t nil) (*))) (numbers (required-argument) :type (simple-array (signed-byte 16) (*))) (strings (required-argument) :type (simple-array t (*))))) #+CMU (declaim (ext:start-block capability %capability)) (defun %capability (name terminfo) (let ((whatsit (gethash name *capabilities*))) (when (null whatsit) (error "Terminfo capability ~S doesn't exist." name)) (if (or (null terminfo) (>= (cdr whatsit) (length (funcall (car whatsit) terminfo)))) (let ((value (aref (funcall (car whatsit) terminfo) (cdr whatsit)))) (if (and (numberp value) (minusp value)) nil value))))) (declaim (inline capability)) (defun capability (name &optional (terminfo *terminfo*)) (%capability name terminfo)) #+CMU (declaim (ext:end-block)) (define-compiler-macro capability (&whole form name &optional (terminfo '*terminfo*)) (if (not (keywordp name)) form (let ((value (gensym)) (tmp (gensym))) (unless (gethash name *capabilities*) (warn "Terminfo capability ~S doesn't exist." name)) `(let ((,value (load-time-value (cons nil nil))) (,tmp ,terminfo)) (if (eq (car ,value) ,tmp) (cdr ,value) (setf (car ,value) ,tmp (cdr ,value) (%capability ,name ,tmp))))))) (defmacro defcap (name type index &optional docstring) (let ((thing (ecase type (boolean 'terminfo-booleans) (integer 'terminfo-numbers) (string 'terminfo-strings))) (symbol (intern (string name) "KEYWORD"))) `(progn (eval-when (:compile-toplevel) compiling TPUTS . If there 's already a value present , leave (setf (gethash ,symbol *capabilities*) (gethash ,symbol *capabilities* t))) (setf (gethash ,symbol *capabilities*) (cons #',thing ,index)) (define-symbol-macro ,name (capability ,symbol *terminfo*)) ,(when docstring `(setf (documentation ',name 'variable) ,docstring)) (export ',name "TERMINFO")))) (defcap auto-left-margin boolean 0) (defcap auto-right-margin boolean 1) (defcap no-esc-ctlc boolean 2) (defcap ceol-standout-glitch boolean 3) (defcap eat-newline-glitch boolean 4) (defcap erase-overstrike boolean 5) (defcap generic-type boolean 6) (defcap hard-copy boolean 7) (defcap has-meta-key boolean 8) (defcap has-status-line boolean 9) (defcap insert-null-glitch boolean 10) (defcap memory-above boolean 11) (defcap memory-below boolean 12) (defcap move-insert-mode boolean 13) (defcap move-standout-mode boolean 14) (defcap over-strike boolean 15) (defcap status-line-esc-ok boolean 16) (defcap dest-tabs-magic-smso boolean 17) (defcap tilde-glitch boolean 18) (defcap transparent-underline boolean 19) (defcap xon-xoff boolean 20) (defcap needs-xon-xoff boolean 21) (defcap prtr-silent boolean 22) (defcap hard-cursor boolean 23) (defcap non-rev-rmcup boolean 24) (defcap no-pad-char boolean 25) (defcap non-dest-scroll-region boolean 26) (defcap can-change boolean 27) (defcap back-color-erase boolean 28) (defcap hue-lightness-saturation boolean 29) (defcap col-addr-glitch boolean 30) (defcap cr-cancels-micro-mode boolean 31) (defcap has-print-wheel boolean 32) (defcap row-addr-glitch boolean 33) (defcap semi-auto-right-margin boolean 34) (defcap cpi-changes-res boolean 35) (defcap lpi-changes-res boolean 36) (defcap columns integer 0) (defcap init-tabs integer 1) (defcap lines integer 2) (defcap lines-of-memory integer 3) (defcap magic-cookie-glitch integer 4) (defcap padding-baud-rate integer 5) (defcap virtual-terminal integer 6) (defcap width-status-line integer 7) (defcap num-labels integer 8) (defcap label-height integer 9) (defcap label-width integer 10) (defcap max-attributes integer 11) (defcap maximum-windows integer 12) (defcap max-colors integer 13) (defcap max-pairs integer 14) (defcap no-color-video integer 15) (defcap buffer-capacity integer 16) (defcap dot-vert-spacing integer 17) (defcap dot-horz-spacing integer 18) (defcap max-micro-address integer 19) (defcap max-micro-jump integer 20) (defcap micro-col-size integer 21) (defcap micro-line-size integer 22) (defcap number-of-pins integer 23) (defcap output-res-char integer 24) (defcap output-res-line integer 25) (defcap output-res-horz-inch integer 26) (defcap output-res-vert-inch integer 27) (defcap print-rate integer 28) (defcap wide-char-size integer 29) (defcap buttons integer 30) (defcap bit-image-entwining integer 31) (defcap bit-image-type integer 32) (defcap back-tab string 0) (defcap bell string 1) (defcap carriage-return string 2) (defcap change-scroll-region string 3) (defcap clear-all-tabs string 4) (defcap clear-screen string 5) (defcap clr-eol string 6) (defcap clr-eos string 7) (defcap column-address string 8) (defcap command-character string 9) (defcap cursor-address string 10) (defcap cursor-down string 11) (defcap cursor-home string 12) (defcap cursor-invisible string 13) (defcap cursor-left string 14) (defcap cursor-mem-address string 15) (defcap cursor-normal string 16) (defcap cursor-right string 17) (defcap cursor-to-ll string 18) (defcap cursor-up string 19) (defcap cursor-visible string 20) (defcap delete-character string 21) (defcap delete-line string 22) (defcap dis-status-line string 23) (defcap down-half-line string 24) (defcap enter-alt-charset-mode string 25) (defcap enter-blink-mode string 26) (defcap enter-bold-mode string 27) (defcap enter-ca-mode string 28) (defcap enter-delete-mode string 29) (defcap enter-dim-mode string 30) (defcap enter-insert-mode string 31) (defcap enter-secure-mode string 32) (defcap enter-protected-mode string 33) (defcap enter-reverse-mode string 34) (defcap enter-standout-mode string 35) (defcap enter-underline-mode string 36) (defcap erase-chars string 37) (defcap exit-alt-charset-mode string 38) (defcap exit-attribute-mode string 39) (defcap exit-ca-mode string 40) (defcap exit-delete-mode string 41) (defcap exit-insert-mode string 42) (defcap exit-standout-mode string 43) (defcap exit-underline-mode string 44) (defcap flash-screen string 45) (defcap form-feed string 46) (defcap from-status-line string 47) (defcap init-1string string 48) (defcap init-2string string 49) (defcap init-3string string 50) (defcap init-file string 51) (defcap insert-character string 52) (defcap insert-line string 53) (defcap insert-padding string 54) (defcap key-backspace string 55) (defcap key-catab string 56) (defcap key-clear string 57) (defcap key-ctab string 58) (defcap key-dc string 59) (defcap key-dl string 60) (defcap key-down string 61) (defcap key-eic string 62) (defcap key-eol string 63) (defcap key-eos string 64) (defcap key-f0 string 65) (defcap key-f1 string 66) (defcap key-f10 string 67) (defcap key-f2 string 68) (defcap key-f3 string 69) (defcap key-f4 string 70) (defcap key-f5 string 71) (defcap key-f6 string 72) (defcap key-f7 string 73) (defcap key-f8 string 74) (defcap key-f9 string 75) (defcap key-home string 76) (defcap key-ic string 77) (defcap key-il string 78) (defcap key-left string 79) (defcap key-ll string 80) (defcap key-npage string 81) (defcap key-ppage string 82) (defcap key-right string 83) (defcap key-sf string 84) (defcap key-sr string 85) (defcap key-stab string 86) (defcap key-up string 87) (defcap keypad-local string 88) (defcap keypad-xmit string 89) (defcap lab-f0 string 90) (defcap lab-f1 string 91) (defcap lab-f10 string 92) (defcap lab-f2 string 93) (defcap lab-f3 string 94) (defcap lab-f4 string 95) (defcap lab-f5 string 96) (defcap lab-f6 string 97) (defcap lab-f7 string 98) (defcap lab-f8 string 99) (defcap lab-f9 string 100) (defcap meta-off string 101) (defcap meta-on string 102) (defcap newline string 103) (defcap pad-char string 104) (defcap parm-dch string 105) (defcap parm-delete-line string 106) (defcap parm-down-cursor string 107) (defcap parm-ich string 108) (defcap parm-index string 109) (defcap parm-insert-line string 110) (defcap parm-left-cursor string 111) (defcap parm-right-cursor string 112) (defcap parm-rindex string 113) (defcap parm-up-cursor string 114) (defcap pkey-key string 115) (defcap pkey-local string 116) (defcap pkey-xmit string 117) (defcap print-screen string 118) (defcap prtr-off string 119) (defcap prtr-on string 120) (defcap repeat-char string 121) (defcap reset-1string string 122) (defcap reset-2string string 123) (defcap reset-3string string 124) (defcap reset-file string 125) (defcap restore-cursor string 126) (defcap row-address string 127) (defcap save-cursor string 128) (defcap scroll-forward string 129) (defcap scroll-reverse string 130) (defcap set-attributes string 131) (defcap set-tab string 132) (defcap set-window string 133) (defcap tab string 134) (defcap to-status-line string 135) (defcap underline-char string 136) (defcap up-half-line string 137) (defcap init-prog string 138) (defcap key-a1 string 139) (defcap key-a3 string 140) (defcap key-b2 string 141) (defcap key-c1 string 142) (defcap key-c3 string 143) (defcap prtr-non string 144) (defcap char-padding string 145) (defcap acs-chars string 146) (defcap plab-norm string 147) (defcap key-btab string 148) (defcap enter-xon-mode string 149) (defcap exit-xon-mode string 150) (defcap enter-am-mode string 151) (defcap exit-am-mode string 152) (defcap xon-character string 153) (defcap xoff-character string 154) (defcap ena-acs string 155) (defcap label-on string 156) (defcap label-off string 157) (defcap key-beg string 158) (defcap key-cancel string 159) (defcap key-close string 160) (defcap key-command string 161) (defcap key-copy string 162) (defcap key-create string 163) (defcap key-end string 164) (defcap key-enter string 165) (defcap key-exit string 166) (defcap key-find string 167) (defcap key-help string 168) (defcap key-mark string 169) (defcap key-message string 170) (defcap key-move string 171) (defcap key-next string 172) (defcap key-open string 173) (defcap key-options string 174) (defcap key-previous string 175) (defcap key-print string 176) (defcap key-redo string 177) (defcap key-reference string 178) (defcap key-refresh string 179) (defcap key-replace string 180) (defcap key-restart string 181) (defcap key-resume string 182) (defcap key-save string 183) (defcap key-suspend string 184) (defcap key-undo string 185) (defcap key-sbeg string 186) (defcap key-scancel string 187) (defcap key-scommand string 188) (defcap key-scopy string 189) (defcap key-screate string 190) (defcap key-sdc string 191) (defcap key-sdl string 192) (defcap key-select string 193) (defcap key-send string 194) (defcap key-seol string 195) (defcap key-sexit string 196) (defcap key-sfind string 197) (defcap key-shelp string 198) (defcap key-shome string 199) (defcap key-sic string 200) (defcap key-sleft string 201) (defcap key-smessage string 202) (defcap key-smove string 203) (defcap key-snext string 204) (defcap key-soptions string 205) (defcap key-sprevious string 206) (defcap key-sprint string 207) (defcap key-sredo string 208) (defcap key-sreplace string 209) (defcap key-sright string 210) (defcap key-srsume string 211) (defcap key-ssave string 212) (defcap key-ssuspend string 213) (defcap key-sundo string 214) (defcap req-for-input string 215) (defcap key-f11 string 216) (defcap key-f12 string 217) (defcap key-f13 string 218) (defcap key-f14 string 219) (defcap key-f15 string 220) (defcap key-f16 string 221) (defcap key-f17 string 222) (defcap key-f18 string 223) (defcap key-f19 string 224) (defcap key-f20 string 225) (defcap key-f21 string 226) (defcap key-f22 string 227) (defcap key-f23 string 228) (defcap key-f24 string 229) (defcap key-f25 string 230) (defcap key-f26 string 231) (defcap key-f27 string 232) (defcap key-f28 string 233) (defcap key-f29 string 234) (defcap key-f30 string 235) (defcap key-f31 string 236) (defcap key-f32 string 237) (defcap key-f33 string 238) (defcap key-f34 string 239) (defcap key-f35 string 240) (defcap key-f36 string 241) (defcap key-f37 string 242) (defcap key-f38 string 243) (defcap key-f39 string 244) (defcap key-f40 string 245) (defcap key-f41 string 246) (defcap key-f42 string 247) (defcap key-f43 string 248) (defcap key-f44 string 249) (defcap key-f45 string 250) (defcap key-f46 string 251) (defcap key-f47 string 252) (defcap key-f48 string 253) (defcap key-f49 string 254) (defcap key-f50 string 255) (defcap key-f51 string 256) (defcap key-f52 string 257) (defcap key-f53 string 258) (defcap key-f54 string 259) (defcap key-f55 string 260) (defcap key-f56 string 261) (defcap key-f57 string 262) (defcap key-f58 string 263) (defcap key-f59 string 264) (defcap key-f60 string 265) (defcap key-f61 string 266) (defcap key-f62 string 267) (defcap key-f63 string 268) (defcap clr-bol string 269) (defcap clear-margins string 270) (defcap set-left-margin string 271) (defcap set-right-margin string 272) (defcap label-format string 273) (defcap set-clock string 274) (defcap display-clock string 275) (defcap remove-clock string 276) (defcap create-window string 277) (defcap goto-window string 278) (defcap hangup string 279) (defcap dial-phone string 280) (defcap quick-dial string 281) (defcap tone string 282) (defcap pulse string 283) (defcap flash-hook string 284) (defcap fixed-pause string 285) (defcap wait-tone string 286) (defcap user0 string 287) (defcap user1 string 288) (defcap user2 string 289) (defcap user3 string 290) (defcap user4 string 291) (defcap user5 string 292) (defcap user6 string 293) (defcap user7 string 294) (defcap user8 string 295) (defcap user9 string 296) (defcap orig-pair string 297) (defcap orig-colors string 298) (defcap initialize-color string 299) (defcap initialize-pair string 300) (defcap set-color-pair string 301) (defcap set-foreground string 302) (defcap set-background string 303) (defcap change-char-pitch string 304) (defcap change-line-pitch string 305) (defcap change-res-horz string 306) (defcap change-res-vert string 307) (defcap define-char string 308) (defcap enter-doublewide-mode string 309) (defcap enter-draft-quality string 310) (defcap enter-italics-mode string 311) (defcap enter-leftward-mode string 312) (defcap enter-micro-mode string 313) (defcap enter-near-letter-quality string 314) (defcap enter-normal-quality string 315) (defcap enter-shadow-mode string 316) (defcap enter-subscript-mode string 317) (defcap enter-superscript-mode string 318) (defcap enter-upward-mode string 319) (defcap exit-doublewide-mode string 320) (defcap exit-italics-mode string 321) (defcap exit-leftward-mode string 322) (defcap exit-micro-mode string 323) (defcap exit-shadow-mode string 324) (defcap exit-subscript-mode string 325) (defcap exit-superscript-mode string 326) (defcap exit-upward-mode string 327) (defcap micro-column-address string 328) (defcap micro-down string 329) (defcap micro-left string 330) (defcap micro-right string 331) (defcap micro-row-address string 332) (defcap micro-up string 333) (defcap order-of-pins string 334) (defcap parm-down-micro string 335) (defcap parm-left-micro string 336) (defcap parm-right-micro string 337) (defcap parm-up-micro string 338) (defcap select-char-set string 339) (defcap set-bottom-margin string 340) (defcap set-bottom-margin-parm string 341) (defcap set-left-margin-parm string 342) (defcap set-right-margin-parm string 343) (defcap set-top-margin string 344) (defcap set-top-margin-parm string 345) (defcap start-bit-image string 346) (defcap start-char-set-def string 347) (defcap stop-bit-image string 348) (defcap stop-char-set-def string 349) (defcap subscript-characters string 350) (defcap superscript-characters string 351) (defcap these-cause-cr string 352) (defcap zero-motion string 353) (defcap char-set-names string 354) (defcap key-mouse string 355) (defcap mouse-info string 356) (defcap req-mouse-pos string 357) (defcap get-mouse string 358) (defcap set-a-foreground string 359) (defcap set-a-background string 360) (defcap pkey-plab string 361) (defcap device-type string 362) (defcap code-set-init string 363) (defcap set0-des-seq string 364) (defcap set1-des-seq string 365) (defcap set2-des-seq string 366) (defcap set3-des-seq string 367) (defcap set-lr-margin string 368) (defcap set-tb-margin string 369) (defcap bit-image-repeat string 370) (defcap bit-image-newline string 371) (defcap bit-image-carriage-return string 372) (defcap color-names string 373) (defcap define-bit-image-region string 374) (defcap end-bit-image-region string 375) (defcap set-color-band string 376) (defcap set-page-length string 377) (defcap display-pc-char string 378) (defcap enter-pc-charset-mode string 379) (defcap exit-pc-charset-mode string 380) (defcap enter-scancode-mode string 381) (defcap exit-scancode-mode string 382) (defcap pc-term-options string 383) (defcap scancode-escape string 384) (defcap alt-scancode-esc string 385) (defcap enter-horizontal-hl-mode string 386) (defcap enter-left-hl-mode string 387) (defcap enter-low-hl-mode string 388) (defcap enter-right-hl-mode string 389) (defcap enter-top-hl-mode string 390) (defcap enter-vertical-hl-mode string 391) (defcap set-a-attributes string 392) (defcap set-pglen-inch string 393) # + INTERNAL - CAPS - VISIBLE (progn (defcap termcap-init2 string 394) (defcap termcap-reset string 395) (defcap magic-cookie-glitch-ul integer 33) (defcap backspaces-with-bs boolean 37) (defcap crt-no-scrolling boolean 38) (defcap no-correctly-working-cr boolean 39) (defcap carriage-return-delay integer 34) (defcap new-line-delay integer 35) (defcap linefeed-if-not-lf string 396) (defcap backspace-if-not-bs string 397) (defcap gnu-has-meta-key boolean 40) (defcap linefeed-is-newline boolean 41) (defcap backspace-delay integer 36) (defcap horizontal-tab-delay integer 37) (defcap number-of-function-keys integer 38) (defcap other-non-function-keys string 398) (defcap arrow-key-map string 399) (defcap has-hardware-tabs boolean 42) (defcap return-does-clr-eol boolean 43) (defcap acs-ulcorner string 400) (defcap acs-llcorner string 401) (defcap acs-urcorner string 402) (defcap acs-lrcorner string 403) (defcap acs-ltee string 404) (defcap acs-rtee string 405) (defcap acs-btee string 406) (defcap acs-ttee string 407) (defcap acs-hline string 408) (defcap acs-vline string 409) (defcap acs-plus string 410) (defcap memory-lock string 411) (defcap memory-unlock string 412) (defcap box-chars-1 string 413)) (defun load-terminfo (name) (let ((name (concatenate 'string (list (char name 0) #\/) name))) (dolist (path (list* (merge-pathnames (make-pathname :directory '(:relative ".terminfo")) (user-homedir-pathname)) *terminfo-directories*)) (with-open-file (stream (merge-pathnames name path) :direction :input :element-type '(unsigned-byte 8) :if-does-not-exist nil) (when stream (flet ((read-short (stream) (let ((n (+ (read-byte stream) (* 256 (read-byte stream))))) (if (> n 32767) (- n 65536) n))) (read-string (stream) (do ((c (read-byte stream) (read-byte stream)) (s '())) ((zerop c) (coerce (nreverse s) 'string)) (push (code-char c) s)))) (let* ((magic (read-short stream)) (sznames (read-short stream)) (szbooleans (read-short stream)) (sznumbers (read-short stream)) (szstrings (read-short stream)) (szstringtable (read-short stream)) (names (let ((string (read-string stream))) (loop for i = 0 then (1+ j) as j = (position #\| string :start i) collect (subseq string i j) while j))) (booleans (make-array szbooleans :element-type '(or t nil) :initial-element nil)) (numbers (make-array sznumbers :element-type '(signed-byte 16) :initial-element -1)) (strings (make-array szstrings :element-type '(signed-byte 16) :initial-element -1)) (stringtable (make-string szstringtable)) (count 0)) (unless (= magic #o432) (error "Invalid file format")) (dotimes (i szbooleans) (setf (aref booleans i) (not (zerop (read-byte stream))))) (when (oddp (+ sznames szbooleans)) (read-byte stream)) (dotimes (i sznumbers) (setf (aref numbers i) (read-short stream))) (dotimes (i szstrings) (unless (minusp (setf (aref strings i) (read-short stream))) (incf count))) (dotimes (i szstringtable) (setf (char stringtable i) (code-char (read-byte stream)))) (let ((xtrings (make-array szstrings :initial-element nil))) (dotimes (i szstrings) (unless (minusp (aref strings i)) (setf (aref xtrings i) (subseq stringtable (aref strings i) (position #\Null stringtable :start (aref strings i)))))) (setq strings xtrings)) (return (make-terminfo :names names :booleans booleans :numbers numbers :strings strings))))))))) (defun xform (value format flags width precision) (let ((temp (make-array 8 :element-type 'character :fill-pointer 0 :adjustable t))) (flet ((shift (n c sign) (let ((len (length temp)) (s 0)) (when (and sign (> len 0) (char= (char temp 0) #\-)) (setq len (1- len) s 1)) (when (> (+ len n s) (array-dimension temp 0)) (adjust-array temp (+ len n 5))) (incf (fill-pointer temp) n) (replace temp temp :start1 (+ n s) :start2 s :end2 (+ s len)) (fill temp c :start s :end (+ n s))))) (format temp (ecase format (#\d "~D") (#\o "~O") (#\x "~(~X~)") (#\X "~:@(~X~)") (#\s "~A")) value) (when (position format "doxX") (let ((len (length temp))) (when (minusp value) (decf len)) (when (< len precision) (shift (- precision len) #\0 t))) (when (logbitp 0 flags) (case format (#\o (unless (char= (char temp (if (minusp value) 1 0)) #\0) (shift 1 #\0 t))) (#\x (shift 1 #\x t) (shift 1 #\0 t)) (#\X (shift 1 #\X t) (shift 1 #\0 t)))) (unless (minusp value) (cond ((logbitp 1 flags) (shift 1 #\+ nil)) ((logbitp 2 flags) (shift 1 #\Space nil))))) (when (and (eql format #\s) (> precision 0) (> (length temp) precision)) (setf (fill-pointer temp) precision)) (when (< (length temp) width) (if (logbitp 3 flags) (shift (- width (length temp)) #\Space nil) (dotimes (i (- width (length temp))) (vector-push-extend #\Space temp)))) temp))) (defun skip-forward (stream flag) (do ((level 0) (c (read-char stream nil) (read-char stream nil))) ((null c)) (when (char= c #\%) (setq c (read-char stream)) (cond ((char= c #\?) (incf level)) ) ( when ( minusp ( decf level ) ) ( return t ) ) ) ((and flag (char= c #\e) (= level 0)) (return t)))))) (defun tparm (string &rest args) (when (null string) (return-from tparm "")) (with-output-to-string (out) (with-input-from-string (in string) (do ((stack '()) (flags 0) (width 0) (precision 0) (number 0) (dvars (make-array 26 :element-type '(unsigned-byte 8) :initial-element 0)) (svars (load-time-value (make-array 26 :element-type '(unsigned-byte 8) :initial-element 0))) (c (read-char in nil) (read-char in nil))) ((null c)) (cond ((char= c #\%) (setq c (read-char in) flags 0 width 0 precision 0) (tagbody state0 (case c (#\% (princ c out) (go terminal)) (#\: (setq c (read-char in)) (go state2)) (#\+ (go state1)) (#\- (go state1)) (#\# (go state2)) (#\Space (go state2)) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (go state3)) (#\d (go state5)) (#\o (go state6)) ((#\X #\x) (go state7)) (#\s (go state8)) (#\c (princ (code-char (pop stack)) out) (go terminal)) (#\p (go state9)) (#\P (go state10)) (#\g (go state11)) (#\' (go state12)) (#\{ (go state13)) (#\l (push (length (pop stack)) stack) (go terminal)) (#\* (push (* (pop stack) (pop stack)) stack) (go terminal)) (#\/ (push (let ((n (pop stack))) (/ (pop stack) n)) stack) (go terminal)) (#\m (push (let ((n (pop stack))) (mod (pop stack) n)) stack) (go terminal)) (#\& (push (logand (pop stack) (pop stack)) stack) (go terminal)) (#\| (push (logior (pop stack) (pop stack)) stack) (go terminal)) (#\^ (push (logxor (pop stack) (pop stack)) stack) (go terminal)) (#\= (push (if (= (pop stack) (pop stack)) 1 0) stack) (go terminal)) (#\> (push (if (<= (pop stack) (pop stack)) 1 0) stack) (go terminal)) (#\< (push (if (>= (pop stack) (pop stack)) 1 0) stack) (go terminal)) (#\A (push (if (or (zerop (pop stack)) (zerop (pop stack))) 0 1) stack) (go terminal)) (#\O (push (if (and (zerop (pop stack)) (zerop (pop stack))) 0 1) stack) (go terminal)) (#\! (push (if (zerop (pop stack)) 1 0) stack) (go terminal)) (#\~ (push (logand #xFF (lognot (pop stack))) stack) (go terminal)) (#\i (when args (incf (first args)) (when (cdr args) (incf (second args)))) (go terminal)) (#\? (go state14)) (#\t (go state15)) (#\e (go state16)) (otherwise (error "Unknown %-control character: ~C" c))) state1 (let ((next (peek-char nil in nil))) (when (position next "0123456789# +-doXxs") (go state2))) (if (char= c #\+) (push (+ (pop stack) (pop stack)) stack) (push (let ((n (pop stack))) (- (pop stack) n)) stack)) (go terminal) state2 (case c (#\# (setf flags (logior flags 1))) (#\+ (setf flags (logior flags 2))) (#\Space (setf flags (logior flags 4))) (#\- (setf flags (logior flags 8))) ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (go state3)) (t (go blah))) (setf c (read-char in)) (go state2) state3 (setf width (digit-char-p c)) state3-loop (setf c (read-char in)) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf width (+ (* width 10) (digit-char-p c))) (go state3-loop)) (#\. (setf c (read-char in)) (go state4))) (go blah) state4 (setf precision (digit-char-p c)) state4-loop (setf c (read-char in)) (case c ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (setf precision (+ (* precision 10) (digit-char-p c))) (go state4-loop))) (go blah) blah (case c (#\d (go state5)) (#\o (go state6)) ((#\X #\x) (go state7)) (#\s (go state8)) (otherwise (error "Unknown %-control character: ~C" c))) state5 state6 state7 state8 (princ (xform (pop stack) c flags width precision) out) (go terminal) state9 (let* ((i (digit-char-p (read-char in))) (a (nth (1- i) args))) (etypecase a (character (push (char-code a) stack)) (integer (push a stack)) (string (push a stack)))) (go terminal) state10 (let ((var (read-char in))) (cond ((char<= #\a var #\z) (setf (aref dvars (- (char-code var) (char-code #\a))) (pop stack))) ((char<= #\A var #\Z) (setf (aref svars (- (char-code var) (char-code #\A))) (pop stack))) (t (error "Illegal variable name: ~C" var)))) (go terminal) state11 (let ((var (read-char in))) (cond ((char<= #\a var #\z) (push (aref dvars (- (char-code var) (char-code #\a))) stack)) ((char<= #\A var #\Z) (push (aref svars (- (char-code var) (char-code #\A))) stack)) (t (error "Illegal variable name: ~C" var)))) (go terminal) state12 (push (char-code (read-char in)) stack) (unless (char= (read-char in) #\') (error "Invalid character constant")) (go terminal) state13 (setq number 0) state13-loop (setq c (read-char in)) (let ((n (digit-char-p c))) (cond (n (setq number (+ (* 10 number) n)) (go state13-loop)) ((char= c #\}) (push number stack) (go terminal)))) (error "Invalid integer constant") state14 (go terminal) state15 (when (/= (pop stack) 0) (go terminal)) (skip-forward in t) (go terminal) state16 (skip-forward in nil) state17 terminal (t (princ c out))))))) (defgeneric stream-fileno (stream) (:method ((stream stream)) nil) #+CMU (:method ((stream sys:fd-stream)) (sys:fd-stream-fd stream)) (:method ((stream two-way-stream)) (stream-fileno (two-way-stream-output-stream stream))) (:method ((stream synonym-stream)) (stream-fileno (symbol-value (synonym-stream-symbol stream)))) (:method ((stream echo-stream)) (stream-fileno (echo-stream-output-stream stream))) (:method ((stream broadcast-stream)) (stream-fileno (first (broadcast-stream-streams stream)))) #+(and CMU simple-streams) (:method ((stream stream:simple-stream)) (let ((fd (stream:stream-output-handle stream))) (if (or (null fd) (integerp fd)) fd (stream-fileno fd))))) (defun stream-baud-rate (stream) (declare (type stream stream) (values (or null (integer 0 4000000)))) #+CMU (alien:with-alien ((termios (alien:struct unix:termios))) (declare (optimize (ext:inhibit-warnings 3))) (when (unix:unix-tcgetattr (stream-fileno stream) termios) (let ((baud (logand unix:tty-cbaud (alien:slot termios 'unix:c-cflag)))) (if (< baud unix::tty-cbaudex) (aref #(0 50 75 110 134 150 200 300 600 1200 1800 2400 4800 9600 19200 38400) baud) (aref #(57600 115200 230400 460800 500000 576000 921600 1000000 1152000 1500000 2000000 2500000 3000000 3500000 4000000) (logxor baud unix::tty-cbaudex))))))) (defun terminal-size (&optional (stream *terminal-io*)) (declare (type stream stream)) #+CMU (alien:with-alien ((winsz (alien:struct unix:winsize))) (declare (optimize (ext:inhibit-warnings 3))) (if (unix:unix-ioctl (stream-fileno stream) unix:TIOCGWINSZ winsz) (values (alien:slot winsz 'unix:ws-row) (alien:slot winsz 'unix:ws-col)) (values nil nil)))) (defun tputs (string &rest args) (when string (let* ((stream (if (streamp (first args)) (pop args) *terminal-io*)) (terminfo (if (terminfo-p (first args)) (pop args) *terminfo*))) (with-input-from-string (string (apply #'tparm string args)) (do ((c (read-char string nil) (read-char string nil))) ((null c)) (cond ((and (char= c #\$) (eql (peek-char nil string nil) #\<)) (let ((time 0) (force nil) (rate nil) (pad #\Null)) (loop (setq c (read-char string)) (let ((n (digit-char-p c))) (if n (setq time (+ (* time 10) n)) (return)))) (if (char= c #\.) (setq time (+ (* time 10) (digit-char-p (read-char string))) c (read-char string)) (setq time (* time 10))) (when (char= c #\*) (setq c (read-char string))) (when (char= c #\/) (setq force t c (read-char string))) (unless (char= c #\>) (error "Invalid padding specification.")) (when (or force (not (capability :xon-xoff terminfo))) (setq rate (stream-baud-rate stream)) (when (let ((pb (capability :padding-baud-rate terminfo))) (and rate (or (null pb) (> rate pb)))) (cond ((capability :no-pad-char terminfo) (finish-output stream) (sleep (/ time 10000.0))) (t (let ((tmp (capability :pad-char terminfo))) (when tmp (setf pad (schar tmp 0)))) (dotimes (i (ceiling (* rate time) 100000)) (write-char pad stream)))))))) (t (write-char c stream)))))) t)) (defun set-terminal (&optional name) (setf *terminfo* (load-terminfo (or name #+CMU (cdr (assoc "TERM" ext:*environment-list* :test #'string=)) #+Allegro (sys:getenv "TERM") #+SBCL (sb-ext:posix-getenv "TERM") #+lispworks (lispworks:environment-variable "TERM") "dumb")))) (provide :terminfo)
2f589b56dbc0810e081aab435c0b6bcd3375125a46873439e5640f7b3916e135
realworldocaml/book
test_float_tolerance_dropped_diff.ml
open! Core open! Async open! Import Regression test for a case where we used to drop the first line of this diff . let prev = {| ((foo (1 2)) (bar 0.5%)) |} let next = {| () |} let%expect_test "default" = let%bind () = patdiff ~prev ~next ~extra_flags:[] in [%expect {| (fg:red)------ (+bold)prev/file (fg:green)++++++ (+bold)next/file (fg:black)@|(+bold)-1,3 +1,2(off) ============================================================ (fg:black) | (fg:black bg:yellow)!|(off)((fg:red)(foo (1 2)) (fg:black bg:yellow)!|(fg:red) (bar 0.5%)(off)) ("Unclean exit" (Exit_non_zero 1)) |}]; return () ;; let%expect_test "-float-tolerance 0x" = let%bind () = patdiff ~prev ~next ~extra_flags:[ "-float-tolerance"; "0x" ] in [%expect {| (fg:red)------ (+bold)prev/file (fg:green)++++++ (+bold)next/file (fg:black)@|(+bold)-1,3 +1,2(off) ============================================================ (fg:black) | (fg:black bg:yellow)!|(off)((fg:red)(foo (1 2)) (fg:black bg:yellow)!|(fg:red) (bar 0.5%)(off)) ("Unclean exit" (Exit_non_zero 1)) |}]; return () ;; let%expect_test "-float-tolerance 0x -no-semantic-cleanup" = let%bind () = patdiff ~prev ~next ~extra_flags:[ "-float-tolerance"; "0x"; "-no-semantic-cleanup" ] in [%expect {| (fg:red)------ (+bold)prev/file (fg:green)++++++ (+bold)next/file (fg:black)@|(+bold)-1,3 +1,2(off) ============================================================ (fg:black) | (fg:black bg:yellow)!|(off)((fg:red)(foo (1 2)) (fg:black bg:yellow)!|(fg:red) (bar 0.5%)(off)) ("Unclean exit" (Exit_non_zero 1)) |}]; return () ;;
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/patdiff/test/src/test_float_tolerance_dropped_diff.ml
ocaml
open! Core open! Async open! Import Regression test for a case where we used to drop the first line of this diff . let prev = {| ((foo (1 2)) (bar 0.5%)) |} let next = {| () |} let%expect_test "default" = let%bind () = patdiff ~prev ~next ~extra_flags:[] in [%expect {| (fg:red)------ (+bold)prev/file (fg:green)++++++ (+bold)next/file (fg:black)@|(+bold)-1,3 +1,2(off) ============================================================ (fg:black) | (fg:black bg:yellow)!|(off)((fg:red)(foo (1 2)) (fg:black bg:yellow)!|(fg:red) (bar 0.5%)(off)) ("Unclean exit" (Exit_non_zero 1)) |}]; return () ;; let%expect_test "-float-tolerance 0x" = let%bind () = patdiff ~prev ~next ~extra_flags:[ "-float-tolerance"; "0x" ] in [%expect {| (fg:red)------ (+bold)prev/file (fg:green)++++++ (+bold)next/file (fg:black)@|(+bold)-1,3 +1,2(off) ============================================================ (fg:black) | (fg:black bg:yellow)!|(off)((fg:red)(foo (1 2)) (fg:black bg:yellow)!|(fg:red) (bar 0.5%)(off)) ("Unclean exit" (Exit_non_zero 1)) |}]; return () ;; let%expect_test "-float-tolerance 0x -no-semantic-cleanup" = let%bind () = patdiff ~prev ~next ~extra_flags:[ "-float-tolerance"; "0x"; "-no-semantic-cleanup" ] in [%expect {| (fg:red)------ (+bold)prev/file (fg:green)++++++ (+bold)next/file (fg:black)@|(+bold)-1,3 +1,2(off) ============================================================ (fg:black) | (fg:black bg:yellow)!|(off)((fg:red)(foo (1 2)) (fg:black bg:yellow)!|(fg:red) (bar 0.5%)(off)) ("Unclean exit" (Exit_non_zero 1)) |}]; return () ;;
5af4a3e088348feb75bee8841655ca11672837385f7fbf13060866a1a8ed96e1
trez/LazyNES
Addressing.hs
-- | -- Module: CPU.Addressing Copyright : -- module CPU.Addressing * Zero page zeropage, zeropageX, zeropageY -- * Absolute addressing , absolute, absoluteX, absoluteY -- * Indirect addressing , indirect, indirectX, indirectY , relative , immediate , implicit , accumulator -- * Memory , Addressing (..) , AddressMode (..) , Storage (..) , fetchValue, fetchAddress , storeValue , alterValue ) where import CPU.Types import CPU.Definition import Helpers import Control.Applicative ((<$>)) data Storage = Implicit | Accumulator | Value Operand | Memory !Address data AddressMode = ACC | IMM | IMP | REL | ZPG | ZPX | ZPY | ABS | ABX | ABY | INX | INY | IND deriving (Show,Eq) data Addressing = Addressing { mode :: AddressMode , pageCross :: Bool , storage :: Storage } -- | Default values for Addressing (..) addressing :: Addressing addressing = Addressing { mode = IMP , pageCross = False , storage = Implicit } storeValue :: Addressing -> Operand -> CPU s () storeValue Addressing{storage=Accumulator} = setA storeValue Addressing{storage=Memory addr} = writeMemory addr fetchValue :: Addressing -> CPU s Operand fetchValue Addressing{storage=Accumulator} = getA fetchValue Addressing{storage=Memory addr} = readMemory addr fetchValue Addressing{storage=Value v} = return v alterValue :: Addressing -> (Operand -> Operand) -> CPU s Operand alterValue Addressing{storage=Accumulator} = alterA alterValue Addressing{storage=Memory addr} = alterMemory addr fetchAddress :: Addressing -> CPU s Address fetchAddress Addressing{storage=Memory addr} = return addr | Fetch an 8 bit address operand from the stack -} operand :: CPU s Operand operand = fetch | Fetch two 8 bit address operands from the stack and use them as a low - and high value of a 16 bit address . - and high value of a 16 bit address. -} address :: CPU s Address address = fetch <#> fetch | Zero page addressing uses only an 8 bit address operand to address the - first 256 bytes in memory ( e.g. $ 0000 to $ 00FF ) . - Example : LDA $ 0F ; Load accumulator from $ 000F. - first 256 bytes in memory (e.g. $0000 to $00FF). - Example: LDA $0F ; Load accumulator from $000F. -} zeropage :: CPU s Addressing zeropage = do addr <- zeropageIndex (return 0x00) return Addressing { mode = ZPG , pageCross = False , storage = Memory addr } | Indexed zero page addressing adds the value of register x to the value - of the 8 bit operand to address something in the first page . - Example : STY $ 10,X ; Store the Y register at location $ 00(10+X ) . - of the 8 bit operand to address something in the first page. - Example: STY $10,X ; Store the Y register at location $00(10+X). -} zeropageX :: CPU s Addressing zeropageX = do addr <- zeropageIndex getX return Addressing { mode = ZPX , pageCross = False , storage = Memory addr } | Indexed zero page addressing adds the value of register y to the value - of the 8 bit operand to address somehting in the first page . - of the 8 bit operand to address somehting in the first page. -} zeropageY :: CPU s Addressing zeropageY = do addr <- zeropageIndex getY return Addressing { mode = ZPY , pageCross = False , storage = Memory addr } | Add ' idx ' to a 8 bit operand . -} zeropageIndex :: CPU s Operand -> CPU s Address zeropageIndex idx = fromIntegral <$> (idx <+> operand) | Fetch two bytes from stack and construct a absolute address . -} absolute :: CPU s Addressing absolute = do addr <- address return Addressing { mode = ABS , pageCross = False , storage = Memory addr } {-| Fetches absolute address and adds register x. -} absoluteX :: CPU s Addressing absoluteX = absoluteIndex (addressing{mode=ABX}) getX {-| Fetches absolute address and adds register y. -} absoluteY :: CPU s Addressing absoluteY = absoluteIndex (addressing{mode=ABY}) getY {-| Adds the value of the index register to fetched absolute address. -} absoluteIndex :: Addressing -> CPU s Operand -> CPU s Addressing absoluteIndex a idx = do lsb <- fetch msb <- fetch reg <- idx return $ pageCrossing a lsb msb reg {-| Indirect -} indirect :: CPU s Addressing indirect = do lsbAddr <- absolute >>= fetchAddress addr <- readMemory lsbAddr <#> readMemory (wrapPageBoundary lsbAddr) return Addressing { mode = IND , pageCross = False , storage = Memory $ addr } {-| Indexed Indirect -} indirectX :: CPU s Addressing indirectX = do lsbAddr <- zeropageX >>= fetchAddress addr <- readMemory lsbAddr <#> readMemory (wrapPageBoundary lsbAddr) return Addressing { mode = INX , pageCross = False , storage = Memory addr } {-| Indirect Indexed -} indirectY :: CPU s Addressing indirectY = do lsbAddr <- zeropage >>= fetchAddress lsb <- readMemory lsbAddr msb <- readMemory (wrapPageBoundary lsbAddr) regY <- getY return $ pageCrossing (addressing{mode=INY}) lsb msb regY {-| FIXME: -} relative :: CPU s Addressing relative = do pc <- getPC op <- (fromIntegral . signed) <$> operand let addr = pc + op return Addressing { mode = REL , pageCross = (pc .&. 0xFF00) /= (addr .&. 0xFF00) , storage = Memory $ addr } | Constant 8 bit value . -} immediate :: CPU s Addressing immediate = do opValue <- operand return Addressing { mode = IMM , pageCross = False , storage = Value opValue } {-| -} implicit :: CPU s Addressing implicit = return Addressing { mode = IMP , pageCross = False , storage = Implicit } {-| -} accumulator :: CPU s Addressing accumulator = return Addressing { mode = ACC , pageCross = False , storage = Accumulator } -- | pageCrossing :: Addressing -> Operand -> Operand -> Operand -> Addressing pageCrossing a lsb msb reg = a { pageCross = reg + lsb < lsb , storage = Memory $ lsb `mkAddr` msb + toAddr reg } -- | wrapPageBoundary :: Address -> Address wrapPageBoundary addr | (addr .&. 0x00FF) == 0xFF = addr - 0xFF | otherwise = addr + 1
null
https://raw.githubusercontent.com/trez/LazyNES/8f2572e6bb60d1c0ab2c94c584144220ff9e05d1/src/CPU/Addressing.hs
haskell
| Module: CPU.Addressing * Absolute addressing * Indirect addressing * Memory | Default values for Addressing (..) | Fetches absolute address and adds register x. | Fetches absolute address and adds register y. | Adds the value of the index register to fetched absolute address. | Indirect | Indexed Indirect | Indirect Indexed | FIXME: | | | |
Copyright : module CPU.Addressing * Zero page zeropage, zeropageX, zeropageY , absolute, absoluteX, absoluteY , indirect, indirectX, indirectY , relative , immediate , implicit , accumulator , Addressing (..) , AddressMode (..) , Storage (..) , fetchValue, fetchAddress , storeValue , alterValue ) where import CPU.Types import CPU.Definition import Helpers import Control.Applicative ((<$>)) data Storage = Implicit | Accumulator | Value Operand | Memory !Address data AddressMode = ACC | IMM | IMP | REL | ZPG | ZPX | ZPY | ABS | ABX | ABY | INX | INY | IND deriving (Show,Eq) data Addressing = Addressing { mode :: AddressMode , pageCross :: Bool , storage :: Storage } addressing :: Addressing addressing = Addressing { mode = IMP , pageCross = False , storage = Implicit } storeValue :: Addressing -> Operand -> CPU s () storeValue Addressing{storage=Accumulator} = setA storeValue Addressing{storage=Memory addr} = writeMemory addr fetchValue :: Addressing -> CPU s Operand fetchValue Addressing{storage=Accumulator} = getA fetchValue Addressing{storage=Memory addr} = readMemory addr fetchValue Addressing{storage=Value v} = return v alterValue :: Addressing -> (Operand -> Operand) -> CPU s Operand alterValue Addressing{storage=Accumulator} = alterA alterValue Addressing{storage=Memory addr} = alterMemory addr fetchAddress :: Addressing -> CPU s Address fetchAddress Addressing{storage=Memory addr} = return addr | Fetch an 8 bit address operand from the stack -} operand :: CPU s Operand operand = fetch | Fetch two 8 bit address operands from the stack and use them as a low - and high value of a 16 bit address . - and high value of a 16 bit address. -} address :: CPU s Address address = fetch <#> fetch | Zero page addressing uses only an 8 bit address operand to address the - first 256 bytes in memory ( e.g. $ 0000 to $ 00FF ) . - Example : LDA $ 0F ; Load accumulator from $ 000F. - first 256 bytes in memory (e.g. $0000 to $00FF). - Example: LDA $0F ; Load accumulator from $000F. -} zeropage :: CPU s Addressing zeropage = do addr <- zeropageIndex (return 0x00) return Addressing { mode = ZPG , pageCross = False , storage = Memory addr } | Indexed zero page addressing adds the value of register x to the value - of the 8 bit operand to address something in the first page . - Example : STY $ 10,X ; Store the Y register at location $ 00(10+X ) . - of the 8 bit operand to address something in the first page. - Example: STY $10,X ; Store the Y register at location $00(10+X). -} zeropageX :: CPU s Addressing zeropageX = do addr <- zeropageIndex getX return Addressing { mode = ZPX , pageCross = False , storage = Memory addr } | Indexed zero page addressing adds the value of register y to the value - of the 8 bit operand to address somehting in the first page . - of the 8 bit operand to address somehting in the first page. -} zeropageY :: CPU s Addressing zeropageY = do addr <- zeropageIndex getY return Addressing { mode = ZPY , pageCross = False , storage = Memory addr } | Add ' idx ' to a 8 bit operand . -} zeropageIndex :: CPU s Operand -> CPU s Address zeropageIndex idx = fromIntegral <$> (idx <+> operand) | Fetch two bytes from stack and construct a absolute address . -} absolute :: CPU s Addressing absolute = do addr <- address return Addressing { mode = ABS , pageCross = False , storage = Memory addr } absoluteX :: CPU s Addressing absoluteX = absoluteIndex (addressing{mode=ABX}) getX absoluteY :: CPU s Addressing absoluteY = absoluteIndex (addressing{mode=ABY}) getY absoluteIndex :: Addressing -> CPU s Operand -> CPU s Addressing absoluteIndex a idx = do lsb <- fetch msb <- fetch reg <- idx return $ pageCrossing a lsb msb reg indirect :: CPU s Addressing indirect = do lsbAddr <- absolute >>= fetchAddress addr <- readMemory lsbAddr <#> readMemory (wrapPageBoundary lsbAddr) return Addressing { mode = IND , pageCross = False , storage = Memory $ addr } indirectX :: CPU s Addressing indirectX = do lsbAddr <- zeropageX >>= fetchAddress addr <- readMemory lsbAddr <#> readMemory (wrapPageBoundary lsbAddr) return Addressing { mode = INX , pageCross = False , storage = Memory addr } indirectY :: CPU s Addressing indirectY = do lsbAddr <- zeropage >>= fetchAddress lsb <- readMemory lsbAddr msb <- readMemory (wrapPageBoundary lsbAddr) regY <- getY return $ pageCrossing (addressing{mode=INY}) lsb msb regY relative :: CPU s Addressing relative = do pc <- getPC op <- (fromIntegral . signed) <$> operand let addr = pc + op return Addressing { mode = REL , pageCross = (pc .&. 0xFF00) /= (addr .&. 0xFF00) , storage = Memory $ addr } | Constant 8 bit value . -} immediate :: CPU s Addressing immediate = do opValue <- operand return Addressing { mode = IMM , pageCross = False , storage = Value opValue } implicit :: CPU s Addressing implicit = return Addressing { mode = IMP , pageCross = False , storage = Implicit } accumulator :: CPU s Addressing accumulator = return Addressing { mode = ACC , pageCross = False , storage = Accumulator } pageCrossing :: Addressing -> Operand -> Operand -> Operand -> Addressing pageCrossing a lsb msb reg = a { pageCross = reg + lsb < lsb , storage = Memory $ lsb `mkAddr` msb + toAddr reg } wrapPageBoundary :: Address -> Address wrapPageBoundary addr | (addr .&. 0x00FF) == 0xFF = addr - 0xFF | otherwise = addr + 1
f059cb5d2a573c057f6b9a1f77966ed21e0e27c19679a29130954792f44bf66a
ocaml-multicore/ocaml-tsan
subst.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Substitutions *) open Misc open Path open Types open Btype open Local_store type type_replacement = | Path of Path.t | Type_function of { params : type_expr list; body : type_expr } type t = { types: type_replacement Path.Map.t; modules: Path.t Path.Map.t; modtypes: module_type Path.Map.t; for_saving: bool; loc: Location.t option; } let identity = { types = Path.Map.empty; modules = Path.Map.empty; modtypes = Path.Map.empty; for_saving = false; loc = None; } let add_type_path id p s = { s with types = Path.Map.add id (Path p) s.types } let add_type id p s = add_type_path (Pident id) p s let add_type_function id ~params ~body s = { s with types = Path.Map.add id (Type_function { params; body }) s.types } let add_module_path id p s = { s with modules = Path.Map.add id p s.modules } let add_module id p s = add_module_path (Pident id) p s let add_modtype_path p ty s = { s with modtypes = Path.Map.add p ty s.modtypes } let add_modtype id ty s = add_modtype_path (Pident id) ty s let for_saving s = { s with for_saving = true } let change_locs s loc = { s with loc = Some loc } let loc s x = match s.loc with | Some l -> l | None -> if s.for_saving && not !Clflags.keep_locs then Location.none else x let remove_loc = let open Ast_mapper in {default_mapper with location = (fun _this _loc -> Location.none)} let is_not_doc = function | {Parsetree.attr_name = {Location.txt = "ocaml.doc"}; _} -> false | {Parsetree.attr_name = {Location.txt = "ocaml.text"}; _} -> false | {Parsetree.attr_name = {Location.txt = "doc"}; _} -> false | {Parsetree.attr_name = {Location.txt = "text"}; _} -> false | _ -> true let attrs s x = let x = if s.for_saving && not !Clflags.keep_docs then List.filter is_not_doc x else x in if s.for_saving && not !Clflags.keep_locs then remove_loc.Ast_mapper.attributes remove_loc x else x let rec module_path s path = try Path.Map.find path s.modules with Not_found -> match path with | Pident _ -> path | Pdot(p, n) -> Pdot(module_path s p, n) | Papply(p1, p2) -> Papply(module_path s p1, module_path s p2) | Pextra_ty _ -> fatal_error "Subst.module_path" let modtype_path s path = match Path.Map.find path s.modtypes with | Mty_ident p -> p | Mty_alias _ | Mty_signature _ | Mty_functor _ -> fatal_error "Subst.modtype_path" | exception Not_found -> match path with | Pdot(p, n) -> Pdot(module_path s p, n) | Papply _ | Pextra_ty _ -> fatal_error "Subst.modtype_path" | Pident _ -> path (* For values, extension constructors, classes and class types *) let value_path s path = match path with | Pident _ -> path | Pdot(p, n) -> Pdot(module_path s p, n) | Papply _ | Pextra_ty _ -> fatal_error "Subst.value_path" let rec type_path s path = match Path.Map.find path s.types with | Path p -> p | Type_function _ -> assert false | exception Not_found -> match path with | Pident _ -> path | Pdot(p, n) -> Pdot(module_path s p, n) | Papply _ -> fatal_error "Subst.type_path" | Pextra_ty (p, extra) -> match extra with | Pcstr_ty _ -> Pextra_ty (type_path s p, extra) | Pext_ty -> Pextra_ty (value_path s p, extra) let to_subst_by_type_function s p = match Path.Map.find p s.types with | Path _ -> false | Type_function _ -> true | exception Not_found -> false (* Special type ids for saved signatures *) let new_id = s_ref (-1) let reset_for_saving () = new_id := -1 let newpersty desc = decr new_id; create_expr desc ~level:generic_level ~scope:Btype.lowest_level ~id:!new_id (* ensure that all occurrences of 'Tvar None' are physically shared *) let tvar_none = Tvar None let tunivar_none = Tunivar None let norm = function | Tvar None -> tvar_none | Tunivar None -> tunivar_none | d -> d let ctype_apply_env_empty = ref (fun _ -> assert false) (* Similar to [Ctype.nondep_type_rec]. *) let rec typexp copy_scope s ty = let desc = get_desc ty in match desc with Tvar _ | Tunivar _ -> if s.for_saving || get_id ty < 0 then let ty' = if s.for_saving then newpersty (norm desc) else newty2 ~level:(get_level ty) desc in For_copy.redirect_desc copy_scope ty (Tsubst (ty', None)); ty' else ty | Tsubst (ty, _) -> ty | Tfield (m, k, _t1, _t2) when not s.for_saving && m = dummy_method && field_kind_repr k <> Fabsent && get_level ty < generic_level -> (* do not copy the type of self when it is not generalized *) ty can not do it , since it would omit substitution | Tvariant row when not ( static_row row ) - > ty | Tvariant row when not (static_row row) -> ty *) | _ -> let tm = row_of_type ty in let has_fixed_row = not (is_Tconstr ty) && is_constr_row ~allow_ident:false tm in (* Make a stub *) let ty' = if s.for_saving then newpersty (Tvar None) else newgenstub ~scope:(get_scope ty) in For_copy.redirect_desc copy_scope ty (Tsubst (ty', None)); let desc = if has_fixed_row then match get_desc tm with (* PR#7348 *) Tconstr (Pdot(m,i), tl, _abbrev) -> let i' = String.sub i 0 (String.length i - 4) in Tconstr(type_path s (Pdot(m,i')), tl, ref Mnil) | _ -> assert false else match desc with | Tconstr (p, args, _abbrev) -> let args = List.map (typexp copy_scope s) args in begin match Path.Map.find p s.types with | exception Not_found -> Tconstr(type_path s p, args, ref Mnil) | Path _ -> Tconstr(type_path s p, args, ref Mnil) | Type_function { params; body } -> Tlink (!ctype_apply_env_empty params body args) end | Tpackage(p, fl) -> Tpackage(modtype_path s p, List.map (fun (n, ty) -> (n, typexp copy_scope s ty)) fl) | Tobject (t1, name) -> let t1' = typexp copy_scope s t1 in let name' = match !name with | None -> None | Some (p, tl) -> if to_subst_by_type_function s p then None else Some (type_path s p, List.map (typexp copy_scope s) tl) in Tobject (t1', ref name') | Tvariant row -> let more = row_more row in let mored = get_desc more in (* We must substitute in a subtle way *) (* Tsubst takes a tuple containing the row var and the variant *) begin match mored with Tsubst (_, Some ty2) -> (* This variant type has been already copied *) Change the stub to avoid in the new type For_copy.redirect_desc copy_scope ty (Tsubst (ty2, None)); Tlink ty2 | _ -> let dup = s.for_saving || get_level more = generic_level || static_row row || is_Tconstr more in (* Various cases for the row variable *) let more' = match mored with Tsubst (ty, None) -> ty | Tconstr _ | Tnil -> typexp copy_scope s more | Tunivar _ | Tvar _ -> if s.for_saving then newpersty (norm mored) else if dup && is_Tvar more then newgenty mored else more | _ -> assert false in Register new type first for recursion For_copy.redirect_desc copy_scope more (Tsubst (more', Some ty')); (* TODO: check if more' can be eliminated *) (* Return a new copy *) let row = copy_row (typexp copy_scope s) true row (not dup) more' in match row_name row with | Some (p, tl) -> let name = if to_subst_by_type_function s p then None else Some (type_path s p, tl) in Tvariant (set_row_name row name) | None -> Tvariant row end | Tfield(_label, kind, _t1, t2) when field_kind_repr kind = Fabsent -> Tlink (typexp copy_scope s t2) | _ -> copy_type_desc (typexp copy_scope s) desc in Transient_expr.set_stub_desc ty' desc; ty' (* Always make a copy of the type. If this is not done, type levels might not be correct. *) let type_expr s ty = For_copy.with_scope (fun copy_scope -> typexp copy_scope s ty) let label_declaration copy_scope s l = { ld_id = l.ld_id; ld_mutable = l.ld_mutable; ld_type = typexp copy_scope s l.ld_type; ld_loc = loc s l.ld_loc; ld_attributes = attrs s l.ld_attributes; ld_uid = l.ld_uid; } let constructor_arguments copy_scope s = function | Cstr_tuple l -> Cstr_tuple (List.map (typexp copy_scope s) l) | Cstr_record l -> Cstr_record (List.map (label_declaration copy_scope s) l) let constructor_declaration copy_scope s c = { cd_id = c.cd_id; cd_args = constructor_arguments copy_scope s c.cd_args; cd_res = Option.map (typexp copy_scope s) c.cd_res; cd_loc = loc s c.cd_loc; cd_attributes = attrs s c.cd_attributes; cd_uid = c.cd_uid; } let type_declaration' copy_scope s decl = { type_params = List.map (typexp copy_scope s) decl.type_params; type_arity = decl.type_arity; type_kind = begin match decl.type_kind with Type_abstract -> Type_abstract | Type_variant (cstrs, rep) -> Type_variant (List.map (constructor_declaration copy_scope s) cstrs, rep) | Type_record(lbls, rep) -> Type_record (List.map (label_declaration copy_scope s) lbls, rep) | Type_open -> Type_open end; type_manifest = begin match decl.type_manifest with None -> None | Some ty -> Some(typexp copy_scope s ty) end; type_private = decl.type_private; type_variance = decl.type_variance; type_separability = decl.type_separability; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = loc s decl.type_loc; type_attributes = attrs s decl.type_attributes; type_immediate = decl.type_immediate; type_unboxed_default = decl.type_unboxed_default; type_uid = decl.type_uid; } let type_declaration s decl = For_copy.with_scope (fun copy_scope -> type_declaration' copy_scope s decl) let class_signature copy_scope s sign = { csig_self = typexp copy_scope s sign.csig_self; csig_self_row = typexp copy_scope s sign.csig_self_row; csig_vars = Vars.map (function (m, v, t) -> (m, v, typexp copy_scope s t)) sign.csig_vars; csig_meths = Meths.map (function (p, v, t) -> (p, v, typexp copy_scope s t)) sign.csig_meths; } let rec class_type copy_scope s = function | Cty_constr (p, tyl, cty) -> let p' = type_path s p in let tyl' = List.map (typexp copy_scope s) tyl in let cty' = class_type copy_scope s cty in Cty_constr (p', tyl', cty') | Cty_signature sign -> Cty_signature (class_signature copy_scope s sign) | Cty_arrow (l, ty, cty) -> Cty_arrow (l, typexp copy_scope s ty, class_type copy_scope s cty) let class_declaration' copy_scope s decl = { cty_params = List.map (typexp copy_scope s) decl.cty_params; cty_variance = decl.cty_variance; cty_type = class_type copy_scope s decl.cty_type; cty_path = type_path s decl.cty_path; cty_new = begin match decl.cty_new with | None -> None | Some ty -> Some (typexp copy_scope s ty) end; cty_loc = loc s decl.cty_loc; cty_attributes = attrs s decl.cty_attributes; cty_uid = decl.cty_uid; } let class_declaration s decl = For_copy.with_scope (fun copy_scope -> class_declaration' copy_scope s decl) let cltype_declaration' copy_scope s decl = { clty_params = List.map (typexp copy_scope s) decl.clty_params; clty_variance = decl.clty_variance; clty_type = class_type copy_scope s decl.clty_type; clty_path = type_path s decl.clty_path; clty_hash_type = type_declaration' copy_scope s decl.clty_hash_type ; clty_loc = loc s decl.clty_loc; clty_attributes = attrs s decl.clty_attributes; clty_uid = decl.clty_uid; } let cltype_declaration s decl = For_copy.with_scope (fun copy_scope -> cltype_declaration' copy_scope s decl) let class_type s cty = For_copy.with_scope (fun copy_scope -> class_type copy_scope s cty) let value_description' copy_scope s descr = { val_type = typexp copy_scope s descr.val_type; val_kind = descr.val_kind; val_loc = loc s descr.val_loc; val_attributes = attrs s descr.val_attributes; val_uid = descr.val_uid; } let value_description s descr = For_copy.with_scope (fun copy_scope -> value_description' copy_scope s descr) let extension_constructor' copy_scope s ext = { ext_type_path = type_path s ext.ext_type_path; ext_type_params = List.map (typexp copy_scope s) ext.ext_type_params; ext_args = constructor_arguments copy_scope s ext.ext_args; ext_ret_type = Option.map (typexp copy_scope s) ext.ext_ret_type; ext_private = ext.ext_private; ext_attributes = attrs s ext.ext_attributes; ext_loc = if s.for_saving then Location.none else ext.ext_loc; ext_uid = ext.ext_uid; } let extension_constructor s ext = For_copy.with_scope (fun copy_scope -> extension_constructor' copy_scope s ext) (* For every binding k |-> d of m1, add k |-> f d to m2 and return resulting merged map. *) let merge_path_maps f m1 m2 = Path.Map.fold (fun k d accu -> Path.Map.add k (f d) accu) m1 m2 let keep_latest_loc l1 l2 = match l2 with | None -> l1 | Some _ -> l2 let type_replacement s = function | Path p -> Path (type_path s p) | Type_function { params; body } -> For_copy.with_scope (fun copy_scope -> let params = List.map (typexp copy_scope s) params in let body = typexp copy_scope s body in Type_function { params; body }) type scoping = | Keep | Make_local | Rescope of int module Lazy_types = struct type module_decl = { mdl_type: modtype; mdl_attributes: Parsetree.attributes; mdl_loc: Location.t; mdl_uid: Uid.t; } and modtype = | MtyL_ident of Path.t | MtyL_signature of signature | MtyL_functor of functor_parameter * modtype | MtyL_alias of Path.t and modtype_declaration = { mtdl_type: modtype option; mtdl_attributes: Parsetree.attributes; mtdl_loc: Location.t; mtdl_uid: Uid.t; } and signature' = | S_eager of Types.signature | S_lazy of signature_item list and signature = (scoping * t * signature', signature') Lazy_backtrack.t and signature_item = SigL_value of Ident.t * value_description * visibility | SigL_type of Ident.t * type_declaration * rec_status * visibility | SigL_typext of Ident.t * extension_constructor * ext_status * visibility | SigL_module of Ident.t * module_presence * module_decl * rec_status * visibility | SigL_modtype of Ident.t * modtype_declaration * visibility | SigL_class of Ident.t * class_declaration * rec_status * visibility | SigL_class_type of Ident.t * class_type_declaration * rec_status * visibility and functor_parameter = | Unit | Named of Ident.t option * modtype end open Lazy_types let rename_bound_idents scoping s sg = let rename = let open Ident in match scoping with | Keep -> (fun id -> create_scoped ~scope:(scope id) (name id)) | Make_local -> Ident.rename | Rescope scope -> (fun id -> create_scoped ~scope (name id)) in let rec rename_bound_idents s sg = function | [] -> sg, s | SigL_type(id, td, rs, vis) :: rest -> let id' = rename id in rename_bound_idents (add_type id (Pident id') s) (SigL_type(id', td, rs, vis) :: sg) rest | SigL_module(id, pres, md, rs, vis) :: rest -> let id' = rename id in rename_bound_idents (add_module id (Pident id') s) (SigL_module (id', pres, md, rs, vis) :: sg) rest | SigL_modtype(id, mtd, vis) :: rest -> let id' = rename id in rename_bound_idents (add_modtype id (Mty_ident(Pident id')) s) (SigL_modtype(id', mtd, vis) :: sg) rest | SigL_class(id, cd, rs, vis) :: rest -> (* cheat and pretend they are types cf. PR#6650 *) let id' = rename id in rename_bound_idents (add_type id (Pident id') s) (SigL_class(id', cd, rs, vis) :: sg) rest | SigL_class_type(id, ctd, rs, vis) :: rest -> (* cheat and pretend they are types cf. PR#6650 *) let id' = rename id in rename_bound_idents (add_type id (Pident id') s) (SigL_class_type(id', ctd, rs, vis) :: sg) rest | SigL_value(id, vd, vis) :: rest -> (* scope doesn't matter for value identifiers. *) let id' = Ident.rename id in rename_bound_idents s (SigL_value(id', vd, vis) :: sg) rest | SigL_typext(id, ec, es, vis) :: rest -> let id' = rename id in rename_bound_idents s (SigL_typext(id',ec,es,vis) :: sg) rest in rename_bound_idents s [] sg let rec lazy_module_decl md = { mdl_type = lazy_modtype md.md_type; mdl_attributes = md.md_attributes; mdl_loc = md.md_loc; mdl_uid = md.md_uid } and subst_lazy_module_decl scoping s md = let mdl_type = subst_lazy_modtype scoping s md.mdl_type in { mdl_type; mdl_attributes = attrs s md.mdl_attributes; mdl_loc = loc s md.mdl_loc; mdl_uid = md.mdl_uid } and force_module_decl md = let md_type = force_modtype md.mdl_type in { md_type; md_attributes = md.mdl_attributes; md_loc = md.mdl_loc; md_uid = md.mdl_uid } and lazy_modtype = function | Mty_ident p -> MtyL_ident p | Mty_signature sg -> MtyL_signature (Lazy_backtrack.create_forced (S_eager sg)) | Mty_functor (Unit, mty) -> MtyL_functor (Unit, lazy_modtype mty) | Mty_functor (Named (id, arg), res) -> MtyL_functor (Named (id, lazy_modtype arg), lazy_modtype res) | Mty_alias p -> MtyL_alias p and subst_lazy_modtype scoping s = function | MtyL_ident p -> begin match Path.Map.find p s.modtypes with | mty -> lazy_modtype mty | exception Not_found -> begin match p with | Pident _ -> MtyL_ident p | Pdot(p, n) -> MtyL_ident(Pdot(module_path s p, n)) | Papply _ | Pextra_ty _ -> fatal_error "Subst.modtype" end end | MtyL_signature sg -> MtyL_signature(subst_lazy_signature scoping s sg) | MtyL_functor(Unit, res) -> MtyL_functor(Unit, subst_lazy_modtype scoping s res) | MtyL_functor(Named (None, arg), res) -> MtyL_functor(Named (None, (subst_lazy_modtype scoping s) arg), subst_lazy_modtype scoping s res) | MtyL_functor(Named (Some id, arg), res) -> let id' = Ident.rename id in MtyL_functor(Named (Some id', (subst_lazy_modtype scoping s) arg), subst_lazy_modtype scoping (add_module id (Pident id') s) res) | MtyL_alias p -> MtyL_alias (module_path s p) and force_modtype = function | MtyL_ident p -> Mty_ident p | MtyL_signature sg -> Mty_signature (force_signature sg) | MtyL_functor (param, res) -> let param : Types.functor_parameter = match param with | Unit -> Unit | Named (id, mty) -> Named (id, force_modtype mty) in Mty_functor (param, force_modtype res) | MtyL_alias p -> Mty_alias p and lazy_modtype_decl mtd = let mtdl_type = Option.map lazy_modtype mtd.mtd_type in { mtdl_type; mtdl_attributes = mtd.mtd_attributes; mtdl_loc = mtd.mtd_loc; mtdl_uid = mtd.mtd_uid } and subst_lazy_modtype_decl scoping s mtd = { mtdl_type = Option.map (subst_lazy_modtype scoping s) mtd.mtdl_type; mtdl_attributes = attrs s mtd.mtdl_attributes; mtdl_loc = loc s mtd.mtdl_loc; mtdl_uid = mtd.mtdl_uid } and force_modtype_decl mtd = let mtd_type = Option.map force_modtype mtd.mtdl_type in { mtd_type; mtd_attributes = mtd.mtdl_attributes; mtd_loc = mtd.mtdl_loc; mtd_uid = mtd.mtdl_uid } and subst_lazy_signature scoping s sg = match Lazy_backtrack.get_contents sg with | Left (scoping', s', sg) -> let scoping = match scoping', scoping with | sc, Keep -> sc | _, (Make_local|Rescope _) -> scoping in let s = compose s' s in Lazy_backtrack.create (scoping, s, sg) | Right sg -> Lazy_backtrack.create (scoping, s, sg) and force_signature sg = List.map force_signature_item (force_signature_once sg) and force_signature_once sg = lazy_signature' (Lazy_backtrack.force force_signature_once' sg) and lazy_signature' = function | S_lazy sg -> sg | S_eager sg -> List.map lazy_signature_item sg and force_signature_once' (scoping, s, sg) = let sg = lazy_signature' sg in Components of signature may be mutually recursive ( e.g. type declarations or class and type declarations ) , so first build global renaming substitution ... or class and type declarations), so first build global renaming substitution... *) let (sg', s') = rename_bound_idents scoping s sg in (* ... then apply it to each signature component in turn *) For_copy.with_scope (fun copy_scope -> S_lazy (List.rev_map (subst_lazy_signature_item' copy_scope scoping s') sg') ) and lazy_signature_item = function | Sig_value(id, d, vis) -> SigL_value(id, d, vis) | Sig_type(id, d, rs, vis) -> SigL_type(id, d, rs, vis) | Sig_typext(id, ext, es, vis) -> SigL_typext(id, ext, es, vis) | Sig_module(id, res, d, rs, vis) -> SigL_module(id, res, lazy_module_decl d, rs, vis) | Sig_modtype(id, d, vis) -> SigL_modtype(id, lazy_modtype_decl d, vis) | Sig_class(id, d, rs, vis) -> SigL_class(id, d, rs, vis) | Sig_class_type(id, d, rs, vis) -> SigL_class_type(id, d, rs, vis) and subst_lazy_signature_item' copy_scope scoping s comp = match comp with SigL_value(id, d, vis) -> SigL_value(id, value_description' copy_scope s d, vis) | SigL_type(id, d, rs, vis) -> SigL_type(id, type_declaration' copy_scope s d, rs, vis) | SigL_typext(id, ext, es, vis) -> SigL_typext(id, extension_constructor' copy_scope s ext, es, vis) | SigL_module(id, pres, d, rs, vis) -> SigL_module(id, pres, subst_lazy_module_decl scoping s d, rs, vis) | SigL_modtype(id, d, vis) -> SigL_modtype(id, subst_lazy_modtype_decl scoping s d, vis) | SigL_class(id, d, rs, vis) -> SigL_class(id, class_declaration' copy_scope s d, rs, vis) | SigL_class_type(id, d, rs, vis) -> SigL_class_type(id, cltype_declaration' copy_scope s d, rs, vis) and force_signature_item = function | SigL_value(id, vd, vis) -> Sig_value(id, vd, vis) | SigL_type(id, d, rs, vis) -> Sig_type(id, d, rs, vis) | SigL_typext(id, ext, es, vis) -> Sig_typext(id, ext, es, vis) | SigL_module(id, pres, d, rs, vis) -> Sig_module(id, pres, force_module_decl d, rs, vis) | SigL_modtype(id, d, vis) -> Sig_modtype (id, force_modtype_decl d, vis) | SigL_class(id, d, rs, vis) -> Sig_class(id, d, rs, vis) | SigL_class_type(id, d, rs, vis) -> Sig_class_type(id, d, rs, vis) and modtype scoping s t = t |> lazy_modtype |> subst_lazy_modtype scoping s |> force_modtype (* Composition of substitutions: apply (compose s1 s2) x = apply s2 (apply s1 x) *) and compose s1 s2 = if s1 == identity then s2 else if s2 == identity then s1 else { types = merge_path_maps (type_replacement s2) s1.types s2.types; modules = merge_path_maps (module_path s2) s1.modules s2.modules; modtypes = merge_path_maps (modtype Keep s2) s1.modtypes s2.modtypes; for_saving = s1.for_saving || s2.for_saving; loc = keep_latest_loc s1.loc s2.loc; } let subst_lazy_signature_item scoping s comp = For_copy.with_scope (fun copy_scope -> subst_lazy_signature_item' copy_scope scoping s comp) module Lazy = struct include Lazy_types let of_module_decl = lazy_module_decl let of_modtype = lazy_modtype let of_modtype_decl = lazy_modtype_decl let of_signature sg = Lazy_backtrack.create_forced (S_eager sg) let of_signature_items sg = Lazy_backtrack.create_forced (S_lazy sg) let of_signature_item = lazy_signature_item let module_decl = subst_lazy_module_decl let modtype = subst_lazy_modtype let modtype_decl = subst_lazy_modtype_decl let signature = subst_lazy_signature let signature_item = subst_lazy_signature_item let force_module_decl = force_module_decl let force_modtype = force_modtype let force_modtype_decl = force_modtype_decl let force_signature = force_signature let force_signature_once = force_signature_once let force_signature_item = force_signature_item end let signature sc s sg = Lazy.(sg |> of_signature |> signature sc s |> force_signature) let signature_item sc s comp = Lazy.(comp|> of_signature_item |> signature_item sc s |> force_signature_item) let modtype_declaration sc s decl = Lazy.(decl |> of_modtype_decl |> modtype_decl sc s |> force_modtype_decl) let module_declaration scoping s decl = Lazy.(decl |> of_module_decl |> module_decl scoping s |> force_module_decl)
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/typing/subst.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Substitutions For values, extension constructors, classes and class types Special type ids for saved signatures ensure that all occurrences of 'Tvar None' are physically shared Similar to [Ctype.nondep_type_rec]. do not copy the type of self when it is not generalized Make a stub PR#7348 We must substitute in a subtle way Tsubst takes a tuple containing the row var and the variant This variant type has been already copied Various cases for the row variable TODO: check if more' can be eliminated Return a new copy Always make a copy of the type. If this is not done, type levels might not be correct. For every binding k |-> d of m1, add k |-> f d to m2 and return resulting merged map. cheat and pretend they are types cf. PR#6650 cheat and pretend they are types cf. PR#6650 scope doesn't matter for value identifiers. ... then apply it to each signature component in turn Composition of substitutions: apply (compose s1 s2) x = apply s2 (apply s1 x)
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Misc open Path open Types open Btype open Local_store type type_replacement = | Path of Path.t | Type_function of { params : type_expr list; body : type_expr } type t = { types: type_replacement Path.Map.t; modules: Path.t Path.Map.t; modtypes: module_type Path.Map.t; for_saving: bool; loc: Location.t option; } let identity = { types = Path.Map.empty; modules = Path.Map.empty; modtypes = Path.Map.empty; for_saving = false; loc = None; } let add_type_path id p s = { s with types = Path.Map.add id (Path p) s.types } let add_type id p s = add_type_path (Pident id) p s let add_type_function id ~params ~body s = { s with types = Path.Map.add id (Type_function { params; body }) s.types } let add_module_path id p s = { s with modules = Path.Map.add id p s.modules } let add_module id p s = add_module_path (Pident id) p s let add_modtype_path p ty s = { s with modtypes = Path.Map.add p ty s.modtypes } let add_modtype id ty s = add_modtype_path (Pident id) ty s let for_saving s = { s with for_saving = true } let change_locs s loc = { s with loc = Some loc } let loc s x = match s.loc with | Some l -> l | None -> if s.for_saving && not !Clflags.keep_locs then Location.none else x let remove_loc = let open Ast_mapper in {default_mapper with location = (fun _this _loc -> Location.none)} let is_not_doc = function | {Parsetree.attr_name = {Location.txt = "ocaml.doc"}; _} -> false | {Parsetree.attr_name = {Location.txt = "ocaml.text"}; _} -> false | {Parsetree.attr_name = {Location.txt = "doc"}; _} -> false | {Parsetree.attr_name = {Location.txt = "text"}; _} -> false | _ -> true let attrs s x = let x = if s.for_saving && not !Clflags.keep_docs then List.filter is_not_doc x else x in if s.for_saving && not !Clflags.keep_locs then remove_loc.Ast_mapper.attributes remove_loc x else x let rec module_path s path = try Path.Map.find path s.modules with Not_found -> match path with | Pident _ -> path | Pdot(p, n) -> Pdot(module_path s p, n) | Papply(p1, p2) -> Papply(module_path s p1, module_path s p2) | Pextra_ty _ -> fatal_error "Subst.module_path" let modtype_path s path = match Path.Map.find path s.modtypes with | Mty_ident p -> p | Mty_alias _ | Mty_signature _ | Mty_functor _ -> fatal_error "Subst.modtype_path" | exception Not_found -> match path with | Pdot(p, n) -> Pdot(module_path s p, n) | Papply _ | Pextra_ty _ -> fatal_error "Subst.modtype_path" | Pident _ -> path let value_path s path = match path with | Pident _ -> path | Pdot(p, n) -> Pdot(module_path s p, n) | Papply _ | Pextra_ty _ -> fatal_error "Subst.value_path" let rec type_path s path = match Path.Map.find path s.types with | Path p -> p | Type_function _ -> assert false | exception Not_found -> match path with | Pident _ -> path | Pdot(p, n) -> Pdot(module_path s p, n) | Papply _ -> fatal_error "Subst.type_path" | Pextra_ty (p, extra) -> match extra with | Pcstr_ty _ -> Pextra_ty (type_path s p, extra) | Pext_ty -> Pextra_ty (value_path s p, extra) let to_subst_by_type_function s p = match Path.Map.find p s.types with | Path _ -> false | Type_function _ -> true | exception Not_found -> false let new_id = s_ref (-1) let reset_for_saving () = new_id := -1 let newpersty desc = decr new_id; create_expr desc ~level:generic_level ~scope:Btype.lowest_level ~id:!new_id let tvar_none = Tvar None let tunivar_none = Tunivar None let norm = function | Tvar None -> tvar_none | Tunivar None -> tunivar_none | d -> d let ctype_apply_env_empty = ref (fun _ -> assert false) let rec typexp copy_scope s ty = let desc = get_desc ty in match desc with Tvar _ | Tunivar _ -> if s.for_saving || get_id ty < 0 then let ty' = if s.for_saving then newpersty (norm desc) else newty2 ~level:(get_level ty) desc in For_copy.redirect_desc copy_scope ty (Tsubst (ty', None)); ty' else ty | Tsubst (ty, _) -> ty | Tfield (m, k, _t1, _t2) when not s.for_saving && m = dummy_method && field_kind_repr k <> Fabsent && get_level ty < generic_level -> ty can not do it , since it would omit substitution | Tvariant row when not ( static_row row ) - > ty | Tvariant row when not (static_row row) -> ty *) | _ -> let tm = row_of_type ty in let has_fixed_row = not (is_Tconstr ty) && is_constr_row ~allow_ident:false tm in let ty' = if s.for_saving then newpersty (Tvar None) else newgenstub ~scope:(get_scope ty) in For_copy.redirect_desc copy_scope ty (Tsubst (ty', None)); let desc = if has_fixed_row then Tconstr (Pdot(m,i), tl, _abbrev) -> let i' = String.sub i 0 (String.length i - 4) in Tconstr(type_path s (Pdot(m,i')), tl, ref Mnil) | _ -> assert false else match desc with | Tconstr (p, args, _abbrev) -> let args = List.map (typexp copy_scope s) args in begin match Path.Map.find p s.types with | exception Not_found -> Tconstr(type_path s p, args, ref Mnil) | Path _ -> Tconstr(type_path s p, args, ref Mnil) | Type_function { params; body } -> Tlink (!ctype_apply_env_empty params body args) end | Tpackage(p, fl) -> Tpackage(modtype_path s p, List.map (fun (n, ty) -> (n, typexp copy_scope s ty)) fl) | Tobject (t1, name) -> let t1' = typexp copy_scope s t1 in let name' = match !name with | None -> None | Some (p, tl) -> if to_subst_by_type_function s p then None else Some (type_path s p, List.map (typexp copy_scope s) tl) in Tobject (t1', ref name') | Tvariant row -> let more = row_more row in let mored = get_desc more in begin match mored with Tsubst (_, Some ty2) -> Change the stub to avoid in the new type For_copy.redirect_desc copy_scope ty (Tsubst (ty2, None)); Tlink ty2 | _ -> let dup = s.for_saving || get_level more = generic_level || static_row row || is_Tconstr more in let more' = match mored with Tsubst (ty, None) -> ty | Tconstr _ | Tnil -> typexp copy_scope s more | Tunivar _ | Tvar _ -> if s.for_saving then newpersty (norm mored) else if dup && is_Tvar more then newgenty mored else more | _ -> assert false in Register new type first for recursion For_copy.redirect_desc copy_scope more (Tsubst (more', Some ty')); let row = copy_row (typexp copy_scope s) true row (not dup) more' in match row_name row with | Some (p, tl) -> let name = if to_subst_by_type_function s p then None else Some (type_path s p, tl) in Tvariant (set_row_name row name) | None -> Tvariant row end | Tfield(_label, kind, _t1, t2) when field_kind_repr kind = Fabsent -> Tlink (typexp copy_scope s t2) | _ -> copy_type_desc (typexp copy_scope s) desc in Transient_expr.set_stub_desc ty' desc; ty' let type_expr s ty = For_copy.with_scope (fun copy_scope -> typexp copy_scope s ty) let label_declaration copy_scope s l = { ld_id = l.ld_id; ld_mutable = l.ld_mutable; ld_type = typexp copy_scope s l.ld_type; ld_loc = loc s l.ld_loc; ld_attributes = attrs s l.ld_attributes; ld_uid = l.ld_uid; } let constructor_arguments copy_scope s = function | Cstr_tuple l -> Cstr_tuple (List.map (typexp copy_scope s) l) | Cstr_record l -> Cstr_record (List.map (label_declaration copy_scope s) l) let constructor_declaration copy_scope s c = { cd_id = c.cd_id; cd_args = constructor_arguments copy_scope s c.cd_args; cd_res = Option.map (typexp copy_scope s) c.cd_res; cd_loc = loc s c.cd_loc; cd_attributes = attrs s c.cd_attributes; cd_uid = c.cd_uid; } let type_declaration' copy_scope s decl = { type_params = List.map (typexp copy_scope s) decl.type_params; type_arity = decl.type_arity; type_kind = begin match decl.type_kind with Type_abstract -> Type_abstract | Type_variant (cstrs, rep) -> Type_variant (List.map (constructor_declaration copy_scope s) cstrs, rep) | Type_record(lbls, rep) -> Type_record (List.map (label_declaration copy_scope s) lbls, rep) | Type_open -> Type_open end; type_manifest = begin match decl.type_manifest with None -> None | Some ty -> Some(typexp copy_scope s ty) end; type_private = decl.type_private; type_variance = decl.type_variance; type_separability = decl.type_separability; type_is_newtype = false; type_expansion_scope = Btype.lowest_level; type_loc = loc s decl.type_loc; type_attributes = attrs s decl.type_attributes; type_immediate = decl.type_immediate; type_unboxed_default = decl.type_unboxed_default; type_uid = decl.type_uid; } let type_declaration s decl = For_copy.with_scope (fun copy_scope -> type_declaration' copy_scope s decl) let class_signature copy_scope s sign = { csig_self = typexp copy_scope s sign.csig_self; csig_self_row = typexp copy_scope s sign.csig_self_row; csig_vars = Vars.map (function (m, v, t) -> (m, v, typexp copy_scope s t)) sign.csig_vars; csig_meths = Meths.map (function (p, v, t) -> (p, v, typexp copy_scope s t)) sign.csig_meths; } let rec class_type copy_scope s = function | Cty_constr (p, tyl, cty) -> let p' = type_path s p in let tyl' = List.map (typexp copy_scope s) tyl in let cty' = class_type copy_scope s cty in Cty_constr (p', tyl', cty') | Cty_signature sign -> Cty_signature (class_signature copy_scope s sign) | Cty_arrow (l, ty, cty) -> Cty_arrow (l, typexp copy_scope s ty, class_type copy_scope s cty) let class_declaration' copy_scope s decl = { cty_params = List.map (typexp copy_scope s) decl.cty_params; cty_variance = decl.cty_variance; cty_type = class_type copy_scope s decl.cty_type; cty_path = type_path s decl.cty_path; cty_new = begin match decl.cty_new with | None -> None | Some ty -> Some (typexp copy_scope s ty) end; cty_loc = loc s decl.cty_loc; cty_attributes = attrs s decl.cty_attributes; cty_uid = decl.cty_uid; } let class_declaration s decl = For_copy.with_scope (fun copy_scope -> class_declaration' copy_scope s decl) let cltype_declaration' copy_scope s decl = { clty_params = List.map (typexp copy_scope s) decl.clty_params; clty_variance = decl.clty_variance; clty_type = class_type copy_scope s decl.clty_type; clty_path = type_path s decl.clty_path; clty_hash_type = type_declaration' copy_scope s decl.clty_hash_type ; clty_loc = loc s decl.clty_loc; clty_attributes = attrs s decl.clty_attributes; clty_uid = decl.clty_uid; } let cltype_declaration s decl = For_copy.with_scope (fun copy_scope -> cltype_declaration' copy_scope s decl) let class_type s cty = For_copy.with_scope (fun copy_scope -> class_type copy_scope s cty) let value_description' copy_scope s descr = { val_type = typexp copy_scope s descr.val_type; val_kind = descr.val_kind; val_loc = loc s descr.val_loc; val_attributes = attrs s descr.val_attributes; val_uid = descr.val_uid; } let value_description s descr = For_copy.with_scope (fun copy_scope -> value_description' copy_scope s descr) let extension_constructor' copy_scope s ext = { ext_type_path = type_path s ext.ext_type_path; ext_type_params = List.map (typexp copy_scope s) ext.ext_type_params; ext_args = constructor_arguments copy_scope s ext.ext_args; ext_ret_type = Option.map (typexp copy_scope s) ext.ext_ret_type; ext_private = ext.ext_private; ext_attributes = attrs s ext.ext_attributes; ext_loc = if s.for_saving then Location.none else ext.ext_loc; ext_uid = ext.ext_uid; } let extension_constructor s ext = For_copy.with_scope (fun copy_scope -> extension_constructor' copy_scope s ext) let merge_path_maps f m1 m2 = Path.Map.fold (fun k d accu -> Path.Map.add k (f d) accu) m1 m2 let keep_latest_loc l1 l2 = match l2 with | None -> l1 | Some _ -> l2 let type_replacement s = function | Path p -> Path (type_path s p) | Type_function { params; body } -> For_copy.with_scope (fun copy_scope -> let params = List.map (typexp copy_scope s) params in let body = typexp copy_scope s body in Type_function { params; body }) type scoping = | Keep | Make_local | Rescope of int module Lazy_types = struct type module_decl = { mdl_type: modtype; mdl_attributes: Parsetree.attributes; mdl_loc: Location.t; mdl_uid: Uid.t; } and modtype = | MtyL_ident of Path.t | MtyL_signature of signature | MtyL_functor of functor_parameter * modtype | MtyL_alias of Path.t and modtype_declaration = { mtdl_type: modtype option; mtdl_attributes: Parsetree.attributes; mtdl_loc: Location.t; mtdl_uid: Uid.t; } and signature' = | S_eager of Types.signature | S_lazy of signature_item list and signature = (scoping * t * signature', signature') Lazy_backtrack.t and signature_item = SigL_value of Ident.t * value_description * visibility | SigL_type of Ident.t * type_declaration * rec_status * visibility | SigL_typext of Ident.t * extension_constructor * ext_status * visibility | SigL_module of Ident.t * module_presence * module_decl * rec_status * visibility | SigL_modtype of Ident.t * modtype_declaration * visibility | SigL_class of Ident.t * class_declaration * rec_status * visibility | SigL_class_type of Ident.t * class_type_declaration * rec_status * visibility and functor_parameter = | Unit | Named of Ident.t option * modtype end open Lazy_types let rename_bound_idents scoping s sg = let rename = let open Ident in match scoping with | Keep -> (fun id -> create_scoped ~scope:(scope id) (name id)) | Make_local -> Ident.rename | Rescope scope -> (fun id -> create_scoped ~scope (name id)) in let rec rename_bound_idents s sg = function | [] -> sg, s | SigL_type(id, td, rs, vis) :: rest -> let id' = rename id in rename_bound_idents (add_type id (Pident id') s) (SigL_type(id', td, rs, vis) :: sg) rest | SigL_module(id, pres, md, rs, vis) :: rest -> let id' = rename id in rename_bound_idents (add_module id (Pident id') s) (SigL_module (id', pres, md, rs, vis) :: sg) rest | SigL_modtype(id, mtd, vis) :: rest -> let id' = rename id in rename_bound_idents (add_modtype id (Mty_ident(Pident id')) s) (SigL_modtype(id', mtd, vis) :: sg) rest | SigL_class(id, cd, rs, vis) :: rest -> let id' = rename id in rename_bound_idents (add_type id (Pident id') s) (SigL_class(id', cd, rs, vis) :: sg) rest | SigL_class_type(id, ctd, rs, vis) :: rest -> let id' = rename id in rename_bound_idents (add_type id (Pident id') s) (SigL_class_type(id', ctd, rs, vis) :: sg) rest | SigL_value(id, vd, vis) :: rest -> let id' = Ident.rename id in rename_bound_idents s (SigL_value(id', vd, vis) :: sg) rest | SigL_typext(id, ec, es, vis) :: rest -> let id' = rename id in rename_bound_idents s (SigL_typext(id',ec,es,vis) :: sg) rest in rename_bound_idents s [] sg let rec lazy_module_decl md = { mdl_type = lazy_modtype md.md_type; mdl_attributes = md.md_attributes; mdl_loc = md.md_loc; mdl_uid = md.md_uid } and subst_lazy_module_decl scoping s md = let mdl_type = subst_lazy_modtype scoping s md.mdl_type in { mdl_type; mdl_attributes = attrs s md.mdl_attributes; mdl_loc = loc s md.mdl_loc; mdl_uid = md.mdl_uid } and force_module_decl md = let md_type = force_modtype md.mdl_type in { md_type; md_attributes = md.mdl_attributes; md_loc = md.mdl_loc; md_uid = md.mdl_uid } and lazy_modtype = function | Mty_ident p -> MtyL_ident p | Mty_signature sg -> MtyL_signature (Lazy_backtrack.create_forced (S_eager sg)) | Mty_functor (Unit, mty) -> MtyL_functor (Unit, lazy_modtype mty) | Mty_functor (Named (id, arg), res) -> MtyL_functor (Named (id, lazy_modtype arg), lazy_modtype res) | Mty_alias p -> MtyL_alias p and subst_lazy_modtype scoping s = function | MtyL_ident p -> begin match Path.Map.find p s.modtypes with | mty -> lazy_modtype mty | exception Not_found -> begin match p with | Pident _ -> MtyL_ident p | Pdot(p, n) -> MtyL_ident(Pdot(module_path s p, n)) | Papply _ | Pextra_ty _ -> fatal_error "Subst.modtype" end end | MtyL_signature sg -> MtyL_signature(subst_lazy_signature scoping s sg) | MtyL_functor(Unit, res) -> MtyL_functor(Unit, subst_lazy_modtype scoping s res) | MtyL_functor(Named (None, arg), res) -> MtyL_functor(Named (None, (subst_lazy_modtype scoping s) arg), subst_lazy_modtype scoping s res) | MtyL_functor(Named (Some id, arg), res) -> let id' = Ident.rename id in MtyL_functor(Named (Some id', (subst_lazy_modtype scoping s) arg), subst_lazy_modtype scoping (add_module id (Pident id') s) res) | MtyL_alias p -> MtyL_alias (module_path s p) and force_modtype = function | MtyL_ident p -> Mty_ident p | MtyL_signature sg -> Mty_signature (force_signature sg) | MtyL_functor (param, res) -> let param : Types.functor_parameter = match param with | Unit -> Unit | Named (id, mty) -> Named (id, force_modtype mty) in Mty_functor (param, force_modtype res) | MtyL_alias p -> Mty_alias p and lazy_modtype_decl mtd = let mtdl_type = Option.map lazy_modtype mtd.mtd_type in { mtdl_type; mtdl_attributes = mtd.mtd_attributes; mtdl_loc = mtd.mtd_loc; mtdl_uid = mtd.mtd_uid } and subst_lazy_modtype_decl scoping s mtd = { mtdl_type = Option.map (subst_lazy_modtype scoping s) mtd.mtdl_type; mtdl_attributes = attrs s mtd.mtdl_attributes; mtdl_loc = loc s mtd.mtdl_loc; mtdl_uid = mtd.mtdl_uid } and force_modtype_decl mtd = let mtd_type = Option.map force_modtype mtd.mtdl_type in { mtd_type; mtd_attributes = mtd.mtdl_attributes; mtd_loc = mtd.mtdl_loc; mtd_uid = mtd.mtdl_uid } and subst_lazy_signature scoping s sg = match Lazy_backtrack.get_contents sg with | Left (scoping', s', sg) -> let scoping = match scoping', scoping with | sc, Keep -> sc | _, (Make_local|Rescope _) -> scoping in let s = compose s' s in Lazy_backtrack.create (scoping, s, sg) | Right sg -> Lazy_backtrack.create (scoping, s, sg) and force_signature sg = List.map force_signature_item (force_signature_once sg) and force_signature_once sg = lazy_signature' (Lazy_backtrack.force force_signature_once' sg) and lazy_signature' = function | S_lazy sg -> sg | S_eager sg -> List.map lazy_signature_item sg and force_signature_once' (scoping, s, sg) = let sg = lazy_signature' sg in Components of signature may be mutually recursive ( e.g. type declarations or class and type declarations ) , so first build global renaming substitution ... or class and type declarations), so first build global renaming substitution... *) let (sg', s') = rename_bound_idents scoping s sg in For_copy.with_scope (fun copy_scope -> S_lazy (List.rev_map (subst_lazy_signature_item' copy_scope scoping s') sg') ) and lazy_signature_item = function | Sig_value(id, d, vis) -> SigL_value(id, d, vis) | Sig_type(id, d, rs, vis) -> SigL_type(id, d, rs, vis) | Sig_typext(id, ext, es, vis) -> SigL_typext(id, ext, es, vis) | Sig_module(id, res, d, rs, vis) -> SigL_module(id, res, lazy_module_decl d, rs, vis) | Sig_modtype(id, d, vis) -> SigL_modtype(id, lazy_modtype_decl d, vis) | Sig_class(id, d, rs, vis) -> SigL_class(id, d, rs, vis) | Sig_class_type(id, d, rs, vis) -> SigL_class_type(id, d, rs, vis) and subst_lazy_signature_item' copy_scope scoping s comp = match comp with SigL_value(id, d, vis) -> SigL_value(id, value_description' copy_scope s d, vis) | SigL_type(id, d, rs, vis) -> SigL_type(id, type_declaration' copy_scope s d, rs, vis) | SigL_typext(id, ext, es, vis) -> SigL_typext(id, extension_constructor' copy_scope s ext, es, vis) | SigL_module(id, pres, d, rs, vis) -> SigL_module(id, pres, subst_lazy_module_decl scoping s d, rs, vis) | SigL_modtype(id, d, vis) -> SigL_modtype(id, subst_lazy_modtype_decl scoping s d, vis) | SigL_class(id, d, rs, vis) -> SigL_class(id, class_declaration' copy_scope s d, rs, vis) | SigL_class_type(id, d, rs, vis) -> SigL_class_type(id, cltype_declaration' copy_scope s d, rs, vis) and force_signature_item = function | SigL_value(id, vd, vis) -> Sig_value(id, vd, vis) | SigL_type(id, d, rs, vis) -> Sig_type(id, d, rs, vis) | SigL_typext(id, ext, es, vis) -> Sig_typext(id, ext, es, vis) | SigL_module(id, pres, d, rs, vis) -> Sig_module(id, pres, force_module_decl d, rs, vis) | SigL_modtype(id, d, vis) -> Sig_modtype (id, force_modtype_decl d, vis) | SigL_class(id, d, rs, vis) -> Sig_class(id, d, rs, vis) | SigL_class_type(id, d, rs, vis) -> Sig_class_type(id, d, rs, vis) and modtype scoping s t = t |> lazy_modtype |> subst_lazy_modtype scoping s |> force_modtype and compose s1 s2 = if s1 == identity then s2 else if s2 == identity then s1 else { types = merge_path_maps (type_replacement s2) s1.types s2.types; modules = merge_path_maps (module_path s2) s1.modules s2.modules; modtypes = merge_path_maps (modtype Keep s2) s1.modtypes s2.modtypes; for_saving = s1.for_saving || s2.for_saving; loc = keep_latest_loc s1.loc s2.loc; } let subst_lazy_signature_item scoping s comp = For_copy.with_scope (fun copy_scope -> subst_lazy_signature_item' copy_scope scoping s comp) module Lazy = struct include Lazy_types let of_module_decl = lazy_module_decl let of_modtype = lazy_modtype let of_modtype_decl = lazy_modtype_decl let of_signature sg = Lazy_backtrack.create_forced (S_eager sg) let of_signature_items sg = Lazy_backtrack.create_forced (S_lazy sg) let of_signature_item = lazy_signature_item let module_decl = subst_lazy_module_decl let modtype = subst_lazy_modtype let modtype_decl = subst_lazy_modtype_decl let signature = subst_lazy_signature let signature_item = subst_lazy_signature_item let force_module_decl = force_module_decl let force_modtype = force_modtype let force_modtype_decl = force_modtype_decl let force_signature = force_signature let force_signature_once = force_signature_once let force_signature_item = force_signature_item end let signature sc s sg = Lazy.(sg |> of_signature |> signature sc s |> force_signature) let signature_item sc s comp = Lazy.(comp|> of_signature_item |> signature_item sc s |> force_signature_item) let modtype_declaration sc s decl = Lazy.(decl |> of_modtype_decl |> modtype_decl sc s |> force_modtype_decl) let module_declaration scoping s decl = Lazy.(decl |> of_module_decl |> module_decl scoping s |> force_module_decl)
964f6db214a71e291d9a9f2c2b77d357a56fcdb64f2d976a1e7b5a11ceebe99a
avsm/platform
yojson.cppo.ml
#include "common.ml" #define INT #define INTLIT #define FLOAT #define FLOATLIT #define STRING #define STRINGLIT #define TUPLE #define VARIANT #include "type.ml" type json_max = t #include "write.ml" #include "monomorphic.ml" module Pretty = struct #include "pretty.ml" end #include "write2.ml" #undef INT #undef INTLIT #undef FLOAT #undef FLOATLIT #undef STRING #undef STRINGLIT #undef TUPLE #undef VARIANT module Basic = struct #define INT #define FLOAT #define STRING #include "type.ml" #include "write.ml" #include "monomorphic.ml" #include "write2.ml" #include "read.ml" module Util = struct #include "util.ml" end #undef INT #undef FLOAT #undef STRING end module Safe = struct #define INT #define INTLIT #define FLOAT #define STRING #define TUPLE #define VARIANT #include "type.ml" #include "safe.ml" #include "write.ml" #include "monomorphic.ml" #include "write2.ml" #include "read.ml" module Util = struct #include "util.ml" end #undef INT #undef INTLIT #undef FLOAT #undef STRING #undef TUPLE #undef VARIANT end module Raw = struct #define INTLIT #define FLOATLIT #define STRINGLIT #define TUPLE #define VARIANT #include "type.ml" #include "write.ml" #include "monomorphic.ml" #include "write2.ml" #include "read.ml" #undef INTLIT #undef FLOATLIT #undef STRINGLIT #undef TUPLE #undef VARIANT end
null
https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/yojson.1.7.0/lib/yojson.cppo.ml
ocaml
#include "common.ml" #define INT #define INTLIT #define FLOAT #define FLOATLIT #define STRING #define STRINGLIT #define TUPLE #define VARIANT #include "type.ml" type json_max = t #include "write.ml" #include "monomorphic.ml" module Pretty = struct #include "pretty.ml" end #include "write2.ml" #undef INT #undef INTLIT #undef FLOAT #undef FLOATLIT #undef STRING #undef STRINGLIT #undef TUPLE #undef VARIANT module Basic = struct #define INT #define FLOAT #define STRING #include "type.ml" #include "write.ml" #include "monomorphic.ml" #include "write2.ml" #include "read.ml" module Util = struct #include "util.ml" end #undef INT #undef FLOAT #undef STRING end module Safe = struct #define INT #define INTLIT #define FLOAT #define STRING #define TUPLE #define VARIANT #include "type.ml" #include "safe.ml" #include "write.ml" #include "monomorphic.ml" #include "write2.ml" #include "read.ml" module Util = struct #include "util.ml" end #undef INT #undef INTLIT #undef FLOAT #undef STRING #undef TUPLE #undef VARIANT end module Raw = struct #define INTLIT #define FLOATLIT #define STRINGLIT #define TUPLE #define VARIANT #include "type.ml" #include "write.ml" #include "monomorphic.ml" #include "write2.ml" #include "read.ml" #undef INTLIT #undef FLOATLIT #undef STRINGLIT #undef TUPLE #undef VARIANT end
cadee3aa643032df8868cf1a7101263e5b521925e29c58eb8b93b769dd093c9e
marigold-dev/easier-proofs
easier_proof_test.ml
(*****************************************************************************) (* *) (* Open Source License *) Copyright ( c ) 2021 Marigold < > (* *) (* Permission is hereby granted, free of charge, to any person obtaining a *) (* copy of this software and associated documentation files (the "Software"),*) to deal in the Software without restriction , including without limitation (* the rights to use, copy, modify, merge, publish, distribute, sublicense, *) and/or sell copies of the Software , and to permit persons to whom the (* Software is furnished to do so, subject to the following conditions: *) (* *) (* The above copyright notice and this permission notice shall be included *) (* in all copies or substantial portions of the Software. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR (* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *) (* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *) (* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*) LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *) (* DEALINGS IN THE SOFTWARE. *) (* *) (*****************************************************************************) open Easier_proof.DslProp open Easier_proof.GenerateProofs open Format (** Boolean *) let bool_and_expected = fprintf std_formatter "From Test Require Import CpdtTactics.\n\ \ (* ----PROOFS---- *)\n\ \ (* Proofs for my_and *)\n\ \ Fact andb_true1 : forall (b:boolean) , andb True b = b.\n\ \ crush.\n\ \ Qed.\n\ \ Fact andb_true2 : forall (b:boolean) , andb b True = b.\n\ \ destruct b\n\ \ crush.\n\ \ crush.\n\ \ Qed." let bool_and_properties = to_proofs [ block "andb" [ prop "andb_true1" ~context:(forall [("b", "boolean")]) ( atom "andb b True" =.= atom "b" >> case "b" &^ (atom "andb True b" =.= atom "b" >> straight) ) ] ] let test_bool_and () = Alcotest.(check unit) "have to match" bool_and_expected (generate_proof std_formatter bool_and_properties) (** Natural numbers *) let nat_trivial = to_proofs [block "nat" [prop "diff42_41" (atom "42" =!= atom "41" >> straight)]] let nat_trivial_expected = fprintf std_formatter "From Test Require Import CpdtTactics.\n\ \ (* ----PROOFS---- *)\n\ Proofs for \ Fact diff42_41 : 42 <> 41.\n\ \ crush.\n\ \ Qed." let test_nat_inequal () = Alcotest.(check unit) "have to match" nat_trivial_expected (generate_proof std_formatter nat_trivial) let nat_add_properties = to_proofs [ block "add" [ prop "add_0" ~context:(forall [("m", "nat")]) (atom "add Zero m" =.= atom "m" >> straight) ; prop "add_1" ~context:(forall [("n", "nat")]) (atom "add n Zero" =.= atom "n" >> induction "n") ] ] let nat_add_expected = fprintf std_formatter "From Test Require Import CpdtTactics.\n\ \ (* ----PROOFS---- *)\n\ \ (* Proofs for add *)\n\ \ Fact add_0 : forall (m:nat) , add Zero m = m.\n\ \ crush.\n\ \ Qed.\n\ \ Fact add_1 : forall (n:nat) , add n Zero = n.\n\ \ induction n.\n\ \ crush.\n\ \ crush.\n\ \ Qed." let test_nat_add () = Alcotest.(check unit) "have to match" nat_add_expected (generate_proof std_formatter nat_add_properties) let () = let open Alcotest in run "DSL for express assertions and generate proofs on them" [ ( "Testing suite for bool/nat properties proofs " , [ test_case "Simple straight and case proof on andb" `Quick test_bool_and ; test_case "Simple auto proof of an nat inequality" `Quick test_nat_inequal ; test_case "Simple straight and inductive proofs for add function on nat" `Quick test_nat_add ] ) ]
null
https://raw.githubusercontent.com/marigold-dev/easier-proofs/49aa431be997df8c7363c8a81f7b64c0c70af0a8/src/tests/easier_proof_test.ml
ocaml
*************************************************************************** Open Source License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************************************** * Boolean ----PROOFS---- Proofs for my_and * Natural numbers ----PROOFS---- ----PROOFS---- Proofs for add
Copyright ( c ) 2021 Marigold < > to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING open Easier_proof.DslProp open Easier_proof.GenerateProofs open Format let bool_and_expected = fprintf std_formatter "From Test Require Import CpdtTactics.\n\ \ Fact andb_true1 : forall (b:boolean) , andb True b = b.\n\ \ crush.\n\ \ Qed.\n\ \ Fact andb_true2 : forall (b:boolean) , andb b True = b.\n\ \ destruct b\n\ \ crush.\n\ \ crush.\n\ \ Qed." let bool_and_properties = to_proofs [ block "andb" [ prop "andb_true1" ~context:(forall [("b", "boolean")]) ( atom "andb b True" =.= atom "b" >> case "b" &^ (atom "andb True b" =.= atom "b" >> straight) ) ] ] let test_bool_and () = Alcotest.(check unit) "have to match" bool_and_expected (generate_proof std_formatter bool_and_properties) let nat_trivial = to_proofs [block "nat" [prop "diff42_41" (atom "42" =!= atom "41" >> straight)]] let nat_trivial_expected = fprintf std_formatter "From Test Require Import CpdtTactics.\n\ Proofs for \ Fact diff42_41 : 42 <> 41.\n\ \ crush.\n\ \ Qed." let test_nat_inequal () = Alcotest.(check unit) "have to match" nat_trivial_expected (generate_proof std_formatter nat_trivial) let nat_add_properties = to_proofs [ block "add" [ prop "add_0" ~context:(forall [("m", "nat")]) (atom "add Zero m" =.= atom "m" >> straight) ; prop "add_1" ~context:(forall [("n", "nat")]) (atom "add n Zero" =.= atom "n" >> induction "n") ] ] let nat_add_expected = fprintf std_formatter "From Test Require Import CpdtTactics.\n\ \ Fact add_0 : forall (m:nat) , add Zero m = m.\n\ \ crush.\n\ \ Qed.\n\ \ Fact add_1 : forall (n:nat) , add n Zero = n.\n\ \ induction n.\n\ \ crush.\n\ \ crush.\n\ \ Qed." let test_nat_add () = Alcotest.(check unit) "have to match" nat_add_expected (generate_proof std_formatter nat_add_properties) let () = let open Alcotest in run "DSL for express assertions and generate proofs on them" [ ( "Testing suite for bool/nat properties proofs " , [ test_case "Simple straight and case proof on andb" `Quick test_bool_and ; test_case "Simple auto proof of an nat inequality" `Quick test_nat_inequal ; test_case "Simple straight and inductive proofs for add function on nat" `Quick test_nat_add ] ) ]
cb173979445c4070b5f90aa90cfff73432425b8ebdbb6da4fa32b5675de3b994
pascal-knodel/haskell-craft
C'3.hs
-- Chapter 3 . -- module C'3 where import Prelude hiding ( (&&) , (||) ) import Test.QuickCheck import E'3'27 import E'3'26 import E'3'25 import E'3'24 import E'3'23 import E'3'22 import E'3'21 import E'3'20 import E'3'19 import E'3'18 import E'3'17 import E'3'16 import E'3'15 import E'3'14 import E'3'13 import E'3'12 import E'3'11 import E'3'10 import E'3''9 import E'3''8 import E'3''7 import E'3''6 import E'3''5 import E'3''4 import E'3''3 import E'3''2 import E'3''1
null
https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/Chapter%203/C'3.hs
haskell
Chapter 3 . module C'3 where import Prelude hiding ( (&&) , (||) ) import Test.QuickCheck import E'3'27 import E'3'26 import E'3'25 import E'3'24 import E'3'23 import E'3'22 import E'3'21 import E'3'20 import E'3'19 import E'3'18 import E'3'17 import E'3'16 import E'3'15 import E'3'14 import E'3'13 import E'3'12 import E'3'11 import E'3'10 import E'3''9 import E'3''8 import E'3''7 import E'3''6 import E'3''5 import E'3''4 import E'3''3 import E'3''2 import E'3''1
36bef1058290dfbf798100fa5815c764f6157c209de044486d12a71a27d43cb2
avieth/diplomacy
Subject.hs
| Module : Diplomacy . Subject Description : Definition of Subject Copyright : ( c ) , 2015 Licence : : Stability : experimental Portability : non - portable ( GHC only ) Module : Diplomacy.Subject Description : Definition of Subject Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : Stability : experimental Portability : non-portable (GHC only) -} module Diplomacy.Subject ( Subject , subjectUnit , subjectProvinceTarget ) where import Diplomacy.Unit import Diplomacy.Province -- | Description of a subject in a diplomacy game, like the subject of an order -- for instance: -- -- a. F Bre - Eng b. A Par S A Bre - Pic -- -- have subjects -- a. ( Fleet , Normal Brest ) b. ( Army , Normal Paris ) -- type Subject = (Unit, ProvinceTarget) subjectUnit :: Subject -> Unit subjectUnit (x, _) = x subjectProvinceTarget :: Subject -> ProvinceTarget subjectProvinceTarget (_, x) = x
null
https://raw.githubusercontent.com/avieth/diplomacy/b8868322e59264f8210962dc357c657b86add588/src/Diplomacy/Subject.hs
haskell
| Description of a subject in a diplomacy game, like the subject of an order for instance: a. F Bre - Eng have subjects
| Module : Diplomacy . Subject Description : Definition of Subject Copyright : ( c ) , 2015 Licence : : Stability : experimental Portability : non - portable ( GHC only ) Module : Diplomacy.Subject Description : Definition of Subject Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : Stability : experimental Portability : non-portable (GHC only) -} module Diplomacy.Subject ( Subject , subjectUnit , subjectProvinceTarget ) where import Diplomacy.Unit import Diplomacy.Province b. A Par S A Bre - Pic a. ( Fleet , Normal Brest ) b. ( Army , Normal Paris ) type Subject = (Unit, ProvinceTarget) subjectUnit :: Subject -> Unit subjectUnit (x, _) = x subjectProvinceTarget :: Subject -> ProvinceTarget subjectProvinceTarget (_, x) = x
e1f761a39799dbc39b354a6b0164968ccd3aecc50fecf58290f3ed363bd1dac1
richmit/mjrcalc
tst-vvec.lisp
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; @file tst-vvec.lisp @author < > ;; @brief Unit Tests.@EOL ;; @std Common Lisp ;; @see use-vvec.lisp @parblock Copyright ( c ) 1997,2008,2012,2015 , < > All rights reserved . ;; ;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: ;; 1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer . ;; 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation ;; and/or other materials provided with the distribution. ;; 3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT ;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ;; DAMAGE. ;; @endparblock ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defpackage :MJR_VVEC-TESTS (:USE :COMMON-LISP :LISP-UNIT :MJR_VVEC)) (in-package :MJR_VVEC-TESTS) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_normalize-kw-vvt-aseq 0001 0001 0001 0011 0100 0100 0101 0110 0111 0111 1001 1011 1011 1100 1100 1101 1101 1110 1110 1111 1111 1111 1111 ;; nil vector (assert-equalp (list :vvec-type :VVT-NIL :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :start 4 :end 2 :step 1 ))) ;; NIL Vector (assert-equalp (list :vvec-type :VVT-NIL :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :start 2 :end 4 :step -1 ))) ;; NIL Vector (assert-equalp (list :vvec-type :VVT-NIL :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :start 1 :end 4 :step 1 :len 0 ))) ;; NIL Vector ;; Error Cases (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :start 2 ))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :start 2 :step 1 ))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :step 1 ))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list ))) len should be 2 len should be 2 len should be 2 (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-points :start 4 :end 2 :step -1 :len 3))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-fun :start 4 :end 2 :step -1 :len 3))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-cheb :start 4 :end 2 :step -1 :len 3))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-mitch1 :start 4 :end 2 :step -1 :len 3))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_normalize-kw-vvt-points (assert-equalp '(:vvec-type :vvt-points :points (2) :start 0 :end 0 :len 1 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2)))) (assert-equalp '(:vvec-type :vvt-points :points (2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2 3 4)))) (assert-equalp '(:vvec-type :vvt-points :points #(2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(2 3 4)))) (assert-equalp '(:vvec-type :vvt-points :points #(4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2 3 4) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points #(2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(2 3 4) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points #(4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(4 9 16) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(4 9 16) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points (2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2 3 4) :len 3.0))) (assert-equalp '(:vvec-type :vvt-points :points #(2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(2 3 4) :len 3.0))) (assert-equalp '(:vvec-type :vvt-points :points #(4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(4 9 16) :len 3.0))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(4 9 16) :len 3.0))) ;; Subsets (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 1 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 3.1 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 2.9 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 1 :end 2 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start 1 :end 2 :len 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 1 :end 2 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 2 :len 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 1 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 1 :points '(4 9 16)))) ;; empty vectors (assert-equalp '(:vvec-type :vvt-nil :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 0 :points '()))) (assert-equalp '(:vvec-type :vvt-nil :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '()))) (assert-equalp '(:vvec-type :vvt-nil :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #()))) : len=0 always wins (assert-equalp '(:vvec-type :vvt-nil :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 5 :points '()))) ;; :plen=0 wins ;; Error Cases (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 4 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start -1 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start 3 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end -1 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 3 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start -1 :len 2 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end -1 :len 2 :points '(4 9 16)))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_map-filter-reduce ;; Various combinations of args (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :start 0 :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 ))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :start 0 ))) ;; (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list ))) ;; TODO: FIX (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :start 0 :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 ))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :start 0 ))) ;; (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list ))) ;; TODO: FIX (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :start 0 :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 ))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :start 0 ))) ;; (assert-error 'error (mjr_vvec_map-filter-reduce nil (list ))) ;; TODO: FIX ;; Inconsistent (assert-error 'warning (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :step 1 :len 12))) (assert-error 'warning (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :step 1 :len 12))) (assert-error 'warning (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :step 1 :len 12))) ;; Points (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :points '(0 1 2 3 4 5 6 7 8 9 10)))) ;; Inconsistent (list (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :len 12 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :len 12 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :len 12 :points '(0 1 2 3 4 5 6 7 8 9 10)))) ;; Can't have :step (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :step 1 :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_vvec2fi ;; Note: This function dosen't need test cases -- tested by mjr_vvec_map-filter-reduce 1 ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_map-sum (assert-equalp 29 (mjr_vvec_map-sum (list :start 4 :end 2 :step -1 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :step 1 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 4 :end 2 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 4 :end 2 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :points '(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :points #(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :points #(4 9 16)))) (assert-equalp 29 (mjr_vvec_map-sum (list :points '(4 9 16)))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :step 1) :point-fun (lambda (x i) (declare (ignore i)) (* x x)))) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 9 : step 2 ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 : map - fun ( lambda ( i ) ( if ( oddp i ) i 0 ) ) ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 ) : point - fun ( lambda ( v i ) ( declare ( ignore i ) ) ( and ( oddp v ) v ) ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 ) : point - fun ( lambda ( v i ) ( declare ( ignore i ) ) ( if ( oddp v ) v 0 ) ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 ) : filter - fun ( lambda ( v fv i ) ( declare ( ignore fv i ) ) ( oddp v ) ) ) ) ( assert - equalp 4 ( mjr_vvec_map - sum ( list : points ' ( 4 ) ) ) ) (assert-equalp 4 (mjr_vvec_map-sum (list :start 4 :end 4))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_map-prod (assert-equalp 576 (mjr_vvec_map-prod (list :start 4 :end 2 :step -1 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :step 1 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 4 :end 2 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 4 :end 2 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :points '(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :points #(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :points #(4 9 16)))) (assert-equalp 576 (mjr_vvec_map-prod (list :points '(4 9 16)))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :step 1) :point-fun (lambda (x i) (declare (ignore i)) (* x x)))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 9 :step 2))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10 :map-fun (lambda (i) (if (oddp i) i 1))))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10) :point-fun (lambda (v i) (declare (ignore i)) (and (oddp v) v)))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10) :point-fun (lambda (v i) (declare (ignore i)) (if (oddp v) v 1)))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10) :filter-fun (lambda (v fv i) (declare (ignore fv i)) (oddp v)))) (assert-equalp 4 (mjr_vvec_map-prod (list :points '(4)))) (assert-equalp 4 (mjr_vvec_map-prod (list :start 4 :end 4))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_map-maxi (assert-equalp '(0 100) (multiple-value-list (mjr_vvec_map-maxi (list :map-fun (lambda (x) (* x x)) :start -10 :end 10 :len 21)))) (assert-equalp '(10 0) (multiple-value-list (mjr_vvec_map-maxi (list :map-fun (lambda (x) (- (* x x))) :start -10 :end 10 :len 21)))) (assert-equalp '(2 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(3 2 4 2))))) (assert-equalp '(2 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(3 2 4 1))))) (assert-equalp '(3 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(1 2 3 4))))) (assert-equalp '(0 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(4 3 2 1))))) (assert-equalp '(0 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points '(-1 -2 -3 -4))))) (assert-equalp '(3 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points '(-4 -3 -2 -1))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2 2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2))))) (assert-equalp '(3 4) (multiple-value-list (mjr_vvec_map-maxi (list :points #(1 2 3 4))))) (assert-equalp '(0 4) (multiple-value-list (mjr_vvec_map-maxi (list :points #(4 3 2 1))))) (assert-equalp '(0 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points #(-1 -2 -3 -4))))) (assert-equalp '(3 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points #(-4 -3 -2 -1))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2 2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2))))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-maxi (list :points '())))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-maxi (list :points nil)))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-maxi (list :points #())))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_map-mini (assert-equalp '(10 0) (multiple-value-list (mjr_vvec_map-mini (list :map-fun (lambda (x) (* x x)) :start -10 :end 10 :len 21)))) (assert-equalp '(0 -100) (multiple-value-list (mjr_vvec_map-mini (list :map-fun (lambda (x) (- (* x x))) :start -10 :end 10 :len 21)))) (assert-equalp '(2 1) (multiple-value-list (mjr_vvec_map-mini (list :points '(3 2 1 4))))) (assert-equalp '(0 1) (multiple-value-list (mjr_vvec_map-mini (list :points '(1 2 3 4))))) (assert-equalp '(3 1) (multiple-value-list (mjr_vvec_map-mini (list :points '(4 3 2 1))))) (assert-equalp '(3 -4) (multiple-value-list (mjr_vvec_map-mini (list :points '(-1 -2 -3 -4))))) (assert-equalp '(0 -4) (multiple-value-list (mjr_vvec_map-mini (list :points '(-4 -3 -2 -1))))) Make sure it gets the FIRST instance (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2 2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2))))) ;; Error as empty lists don't have a minimum -- ;; TODO: Think about returning nil instead. (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-mini (list :points '())))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-mini (list :points nil)))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-mini (list :points #())))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_help ;; Note: This function dosen't need test cases.. 1 ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_to-vec ;; ------------------------------------------------------------------------------------------------------------------------------- ;; vvt-rfun A000045 : Fibonacci numbers : F(n ) = F(n-1 ) + F(n-2 ) with F(0 ) = 0 and F(1 ) = 1 (assert-equalp #(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169) (mjr_vvec_to-vec (list :start '(0 1) :len 39 :rfun (lambda (a b) (+ a b))))) A000032 : numbers ( beginning at 2 ): L(n ) = L(n-1 ) + L(n-2 ) (assert-equalp #(2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349 15127 24476 39603 64079 103682 167761 271443 439204 710647 1149851 1860498 3010349 4870847 7881196 12752043 20633239 33385282) (mjr_vvec_to-vec (list :start '(2 1) :len 37 :rfun (lambda (a b) (+ a b))))) A000129 : numbers : a(0 ) = 0 , a(1 ) = 1 ; for n > 1 , a(n ) = 2*a(n-1 ) + a(n-2 ) (assert-equalp #(0 1 2 5 12 29 70 169 408 985 2378 5741 13860 33461 80782 195025 470832 1136689 2744210 6625109 15994428 38613965 93222358 225058681 543339720 1311738121 3166815962 7645370045 18457556052 44560482149 107578520350 259717522849) (mjr_vvec_to-vec (list :start '(0 1) :len 32 :rfun (lambda (a b) (+ (* 2 b) a))))) A000931 : Padovan sequence : a(n ) = a(n-2 ) + a(n-3 ) with a(0)=1 , a(1)=a(2)=0 (assert-equalp #(1 0 0 1 0 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 200 265 351 465 616 816 1081 1432 1897 2513 3329 4410 5842 7739 10252 13581 17991 23833 31572 41824 55405 73396 97229 128801 170625) (mjr_vvec_to-vec (list :start '(1 0 0) :len 50 :rfun (lambda (a b c) (declare (ignore c)) (+ a b))))) ;; A001608: Perrin sequence: a(n) = a(n-2) + a(n-3). (assert-equalp #(3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90 119 158 209 277 367 486 644 853 1130 1497 1983 2627 3480 4610 6107 8090 10717 14197 18807 24914 33004 43721 57918 76725 101639 134643 178364 236282 313007) (mjr_vvec_to-vec (list :start '(3 0 2) :len 46 :rfun (lambda (a b c) (declare (ignore c)) (+ a b))))) ;; ------------------------------------------------------------------------------------------------------------------------------- ;; vvt-rep (loop for n from 1 upto 20 for c = (random 100) for v = (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start c :len n)) do (assert-true (every (lambda (a) (= a c)) v)) do (assert-equalp n (length v))) (assert-equalp #() (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start 1 :len 0 ))) (assert-error 'error (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start 1 :len -1 ))) (assert-error 'error (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start 1 ))) (assert-error 'error (mjr_vvec_to-vec (list :vvec-type :vvt-rep :len 1 ))) ;; ------------------------------------------------------------------------------------------------------------------------------- : vvec - rep = = : vvr - vec (assert-equalp #(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-vec #(3 0 2 3 2 5 5 7 10 12))) (assert-equalp #(3 0 2 3 2) (mjr_vvec_to-vec #(3 0 2 3 2))) (assert-equalp #(3) (mjr_vvec_to-vec #(3))) (assert-equalp #() (mjr_vvec_to-vec #())) ;; ------------------------------------------------------------------------------------------------------------------------------- : vvec - rep = = : vvr - list (assert-equalp #(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-vec '(3 0 2 3 2 5 5 7 10 12))) (assert-equalp #(3 0 2 3 2) (mjr_vvec_to-vec '(3 0 2 3 2))) (assert-equalp #(3) (mjr_vvec_to-vec '(3))) (assert-equalp #() (mjr_vvec_to-vec '())) ;; ------------------------------------------------------------------------------------------------------------------------------- : vvec - rep = = : vvr - int (assert-equalp #(0 1 2 3 4 5 6 7 8 9) (mjr_vvec_to-vec 10)) (assert-equalp #(0 1 2 3) (mjr_vvec_to-vec 4)) (assert-equalp #(0) (mjr_vvec_to-vec 1)) (assert-equalp #() (mjr_vvec_to-vec 0)) (assert-equalp #(1) (mjr_vvec_to-vec -1)) (assert-equalp #(1 2 3 4) (mjr_vvec_to-vec -4)) (assert-equalp #(1 2 3 4 5 6 7 8 9 10) (mjr_vvec_to-vec -10)) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_to-list (assert-equalp '(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-list #(3 0 2 3 2 5 5 7 10 12))) (assert-equalp '(3 0 2 3 2) (mjr_vvec_to-list #(3 0 2 3 2))) (assert-equalp '(3) (mjr_vvec_to-list #(3))) (assert-equalp '() (mjr_vvec_to-list #())) (assert-equalp '(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-list '(3 0 2 3 2 5 5 7 10 12))) (assert-equalp '(3 0 2 3 2) (mjr_vvec_to-list '(3 0 2 3 2))) (assert-equalp '(3) (mjr_vvec_to-list '(3))) (assert-equalp '() (mjr_vvec_to-list '())) (assert-equalp '(0 1 2 3 4 5 6 7 8 9) (mjr_vvec_to-list 10)) (assert-equalp '(0 1 2 3) (mjr_vvec_to-list 4)) (assert-equalp '(0) (mjr_vvec_to-list 1)) (assert-equalp '() (mjr_vvec_to-list 0)) (assert-equalp '(1) (mjr_vvec_to-list -1)) (assert-equalp '(1 2 3 4) (mjr_vvec_to-list -4)) (assert-equalp '(1 2 3 4 5 6 7 8 9 10) (mjr_vvec_to-list -10)) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-test mjr_vvec_check-len (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len nil 't)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len nil nil)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len #() 't)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len 0 't)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len 0.0 't)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len 0.499 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len #(1) 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len '(1) 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len 1 't)) (assert-equalp -1 (mjr_vvec::mjr_vvec_check-len -1 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len 1.0 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len 0.51 't)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len nil nil)) ;; Some of these should be errors -- TODO. (assert-equalp nil (mjr_vvec::mjr_vvec_check-len #() nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0.0 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0.499 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len #(1) nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len '(1) nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 1 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len -1 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 1.0 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0.51 nil)) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (run-tests ; '(mjr_vvec_normalize-kw-vvt-points) ) ;; TODO: mjr_vvec_gen-1sim ;; TODO: mjr_vvec_kw-type TODO : - type - check ;; TODO: mjr_vvec_normalize-kw-vvt-any ;; TODO: mjr_vvec_normalize-kw-vvt-cheb ;; TODO: mjr_vvec_normalize-kw-vvt-mitch1 ;; TODO: mjr_vvec_normalize-kw-vvt-nfun ;; TODO: mjr_vvec_normalize-kw-vvt-nil ;; TODO: mjr_vvec_normalize-kw-vvt-rep ;; TODO: mjr_vvec_normalize-kw-vvt-rfun ;; TODO: mjr_vvec_representation
null
https://raw.githubusercontent.com/richmit/mjrcalc/96f66d030034754e7d3421688ff201f4f1db4833/tst-vvec.lisp
lisp
-*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*- @file tst-vvec.lisp @brief Unit Tests.@EOL @std Common Lisp @see use-vvec.lisp Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: and/or other materials provided with the distribution. without specific prior written permission. LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @endparblock nil vector NIL Vector NIL Vector NIL Vector Error Cases Subsets empty vectors :plen=0 wins Error Cases Various combinations of args (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list ))) ;; TODO: FIX (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list ))) ;; TODO: FIX (assert-error 'error (mjr_vvec_map-filter-reduce nil (list ))) ;; TODO: FIX Inconsistent Points Inconsistent (list Can't have :step Note: This function dosen't need test cases -- tested by mjr_vvec_map-filter-reduce Error as empty lists don't have a minimum -- ;; TODO: Think about returning nil instead. Note: This function dosen't need test cases.. ------------------------------------------------------------------------------------------------------------------------------- vvt-rfun for n > 1 , a(n ) = 2*a(n-1 ) + a(n-2 ) A001608: Perrin sequence: a(n) = a(n-2) + a(n-3). ------------------------------------------------------------------------------------------------------------------------------- vvt-rep ------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------- Some of these should be errors -- TODO. '(mjr_vvec_normalize-kw-vvt-points) TODO: mjr_vvec_gen-1sim TODO: mjr_vvec_kw-type TODO: mjr_vvec_normalize-kw-vvt-any TODO: mjr_vvec_normalize-kw-vvt-cheb TODO: mjr_vvec_normalize-kw-vvt-mitch1 TODO: mjr_vvec_normalize-kw-vvt-nfun TODO: mjr_vvec_normalize-kw-vvt-nil TODO: mjr_vvec_normalize-kw-vvt-rep TODO: mjr_vvec_normalize-kw-vvt-rfun TODO: mjr_vvec_representation
@author < > @parblock Copyright ( c ) 1997,2008,2012,2015 , < > All rights reserved . 1 . Redistributions of source code must retain the above copyright notice , this list of conditions , and the following disclaimer . 2 . Redistributions in binary form must reproduce the above copyright notice , this list of conditions , and the following disclaimer in the documentation 3 . Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS (defpackage :MJR_VVEC-TESTS (:USE :COMMON-LISP :LISP-UNIT :MJR_VVEC)) (in-package :MJR_VVEC-TESTS) (define-test mjr_vvec_normalize-kw-vvt-aseq 0001 0001 0001 0011 0100 0100 0101 0110 0111 0111 1001 1011 1011 1100 1100 1101 1101 1110 1110 1111 1111 1111 1111 (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :start 2 ))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :start 2 :step 1 ))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :step 1 ))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list ))) len should be 2 len should be 2 len should be 2 (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-points :start 4 :end 2 :step -1 :len 3))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-fun :start 4 :end 2 :step -1 :len 3))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-cheb :start 4 :end 2 :step -1 :len 3))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-aseq (list :vvec-type :vvt-mitch1 :start 4 :end 2 :step -1 :len 3))) ) (define-test mjr_vvec_normalize-kw-vvt-points (assert-equalp '(:vvec-type :vvt-points :points (2) :start 0 :end 0 :len 1 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2)))) (assert-equalp '(:vvec-type :vvt-points :points (2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2 3 4)))) (assert-equalp '(:vvec-type :vvt-points :points #(2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(2 3 4)))) (assert-equalp '(:vvec-type :vvt-points :points #(4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2 3 4) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points #(2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(2 3 4) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points #(4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(4 9 16) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(4 9 16) :len 3))) (assert-equalp '(:vvec-type :vvt-points :points (2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(2 3 4) :len 3.0))) (assert-equalp '(:vvec-type :vvt-points :points #(2 3 4) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(2 3 4) :len 3.0))) (assert-equalp '(:vvec-type :vvt-points :points #(4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #(4 9 16) :len 3.0))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '(4 9 16) :len 3.0))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 1 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 3.1 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 2.9 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 1 :end 2 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start 1 :end 2 :len 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 1 :end 2 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 2 :len 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 2 :len 3 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 2 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-points :points (4 9 16) :start 0 :end 1 :len 2 :map-fun nil) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 1 :points '(4 9 16)))) (assert-equalp '(:vvec-type :vvt-nil :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 0 :points '()))) (assert-equalp '(:vvec-type :vvt-nil :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points '()))) (assert-equalp '(:vvec-type :vvt-nil :len 0) (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :points #()))) : len=0 always wins (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :len 4 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start -1 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start 3 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end -1 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end 3 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :start -1 :len 2 :points '(4 9 16)))) (assert-error 'error (mjr_vvec::mjr_vvec_normalize-kw-vvt-points (list :end -1 :len 2 :points '(4 9 16)))) ) (define-test mjr_vvec_map-filter-reduce (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :step 1 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 :len 11))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :start 0 :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :step 1 ))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :end 10 ))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :start 0 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :step 1 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 :len 11))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :start 0 :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :step 1 ))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :end 10 ))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :start 0 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :step 1 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 :len 11))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :start 0 :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :len 11))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :step 1 ))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :end 10 ))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :start 0 ))) (assert-error 'warning (mjr_vvec_map-filter-reduce 'list (list :start 0 :end 10 :step 1 :len 12))) (assert-error 'warning (mjr_vvec_map-filter-reduce 'vector (list :start 0 :end 10 :step 1 :len 12))) (assert-error 'warning (mjr_vvec_map-filter-reduce nil (list :start 0 :end 10 :step 1 :len 12))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp '(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'list (list :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp #(0 1 2 3 4 5 6 7 8 9 10) (mjr_vvec_map-filter-reduce 'vector (list :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-equalp nil (mjr_vvec_map-filter-reduce nil (list :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :len 12 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-error 'error (mjr_vvec_map-filter-reduce 'vector (list :len 12 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-error 'error (mjr_vvec_map-filter-reduce nil (list :len 12 :points '(0 1 2 3 4 5 6 7 8 9 10)))) (assert-error 'error (mjr_vvec_map-filter-reduce 'list (list :step 1 :len 11 :points '(0 1 2 3 4 5 6 7 8 9 10)))) ) (define-test mjr_vvec_vvec2fi 1 ) (define-test mjr_vvec_map-sum (assert-equalp 29 (mjr_vvec_map-sum (list :start 4 :end 2 :step -1 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :step 1 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 4 :end 2 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 4 :end 2 :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :points '(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :points #(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 29 (mjr_vvec_map-sum (list :points #(4 9 16)))) (assert-equalp 29 (mjr_vvec_map-sum (list :points '(4 9 16)))) (assert-equalp 29 (mjr_vvec_map-sum (list :start 2 :end 4 :step 1) :point-fun (lambda (x i) (declare (ignore i)) (* x x)))) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 9 : step 2 ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 : map - fun ( lambda ( i ) ( if ( oddp i ) i 0 ) ) ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 ) : point - fun ( lambda ( v i ) ( declare ( ignore i ) ) ( and ( oddp v ) v ) ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 ) : point - fun ( lambda ( v i ) ( declare ( ignore i ) ) ( if ( oddp v ) v 0 ) ) ) ) ( assert - equalp 25 ( mjr_vvec_map - sum ( list : start 1 : end 10 ) : filter - fun ( lambda ( v fv i ) ( declare ( ignore fv i ) ) ( oddp v ) ) ) ) ( assert - equalp 4 ( mjr_vvec_map - sum ( list : points ' ( 4 ) ) ) ) (assert-equalp 4 (mjr_vvec_map-sum (list :start 4 :end 4))) ) (define-test mjr_vvec_map-prod (assert-equalp 576 (mjr_vvec_map-prod (list :start 4 :end 2 :step -1 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :step 1 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 4 :end 2 :len 3 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 4 :end 2 :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :points '(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :points #(2 3 4) :map-fun (lambda (x) (* x x))))) (assert-equalp 576 (mjr_vvec_map-prod (list :points #(4 9 16)))) (assert-equalp 576 (mjr_vvec_map-prod (list :points '(4 9 16)))) (assert-equalp 576 (mjr_vvec_map-prod (list :start 2 :end 4 :step 1) :point-fun (lambda (x i) (declare (ignore i)) (* x x)))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 9 :step 2))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10 :map-fun (lambda (i) (if (oddp i) i 1))))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10) :point-fun (lambda (v i) (declare (ignore i)) (and (oddp v) v)))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10) :point-fun (lambda (v i) (declare (ignore i)) (if (oddp v) v 1)))) (assert-equalp 945 (mjr_vvec_map-prod (list :start 1 :end 10) :filter-fun (lambda (v fv i) (declare (ignore fv i)) (oddp v)))) (assert-equalp 4 (mjr_vvec_map-prod (list :points '(4)))) (assert-equalp 4 (mjr_vvec_map-prod (list :start 4 :end 4))) ) (define-test mjr_vvec_map-maxi (assert-equalp '(0 100) (multiple-value-list (mjr_vvec_map-maxi (list :map-fun (lambda (x) (* x x)) :start -10 :end 10 :len 21)))) (assert-equalp '(10 0) (multiple-value-list (mjr_vvec_map-maxi (list :map-fun (lambda (x) (- (* x x))) :start -10 :end 10 :len 21)))) (assert-equalp '(2 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(3 2 4 2))))) (assert-equalp '(2 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(3 2 4 1))))) (assert-equalp '(3 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(1 2 3 4))))) (assert-equalp '(0 4) (multiple-value-list (mjr_vvec_map-maxi (list :points '(4 3 2 1))))) (assert-equalp '(0 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points '(-1 -2 -3 -4))))) (assert-equalp '(3 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points '(-4 -3 -2 -1))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2 2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points '(2))))) (assert-equalp '(3 4) (multiple-value-list (mjr_vvec_map-maxi (list :points #(1 2 3 4))))) (assert-equalp '(0 4) (multiple-value-list (mjr_vvec_map-maxi (list :points #(4 3 2 1))))) (assert-equalp '(0 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points #(-1 -2 -3 -4))))) (assert-equalp '(3 -1) (multiple-value-list (mjr_vvec_map-maxi (list :points #(-4 -3 -2 -1))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2 2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-maxi (list :points #(2))))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-maxi (list :points '())))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-maxi (list :points nil)))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-maxi (list :points #())))) ) (define-test mjr_vvec_map-mini (assert-equalp '(10 0) (multiple-value-list (mjr_vvec_map-mini (list :map-fun (lambda (x) (* x x)) :start -10 :end 10 :len 21)))) (assert-equalp '(0 -100) (multiple-value-list (mjr_vvec_map-mini (list :map-fun (lambda (x) (- (* x x))) :start -10 :end 10 :len 21)))) (assert-equalp '(2 1) (multiple-value-list (mjr_vvec_map-mini (list :points '(3 2 1 4))))) (assert-equalp '(0 1) (multiple-value-list (mjr_vvec_map-mini (list :points '(1 2 3 4))))) (assert-equalp '(3 1) (multiple-value-list (mjr_vvec_map-mini (list :points '(4 3 2 1))))) (assert-equalp '(3 -4) (multiple-value-list (mjr_vvec_map-mini (list :points '(-1 -2 -3 -4))))) (assert-equalp '(0 -4) (multiple-value-list (mjr_vvec_map-mini (list :points '(-4 -3 -2 -1))))) Make sure it gets the FIRST instance (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2 2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2 2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2 2))))) (assert-equalp '(0 2) (multiple-value-list (mjr_vvec_map-mini (list :points '(2))))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-mini (list :points '())))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-mini (list :points nil)))) (assert-equalp '(nil nil) (multiple-value-list (mjr_vvec_map-mini (list :points #())))) ) (define-test mjr_vvec_help 1 ) (define-test mjr_vvec_to-vec A000045 : Fibonacci numbers : F(n ) = F(n-1 ) + F(n-2 ) with F(0 ) = 0 and F(1 ) = 1 (assert-equalp #(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169) (mjr_vvec_to-vec (list :start '(0 1) :len 39 :rfun (lambda (a b) (+ a b))))) A000032 : numbers ( beginning at 2 ): L(n ) = L(n-1 ) + L(n-2 ) (assert-equalp #(2 1 3 4 7 11 18 29 47 76 123 199 322 521 843 1364 2207 3571 5778 9349 15127 24476 39603 64079 103682 167761 271443 439204 710647 1149851 1860498 3010349 4870847 7881196 12752043 20633239 33385282) (mjr_vvec_to-vec (list :start '(2 1) :len 37 :rfun (lambda (a b) (+ a b))))) (assert-equalp #(0 1 2 5 12 29 70 169 408 985 2378 5741 13860 33461 80782 195025 470832 1136689 2744210 6625109 15994428 38613965 93222358 225058681 543339720 1311738121 3166815962 7645370045 18457556052 44560482149 107578520350 259717522849) (mjr_vvec_to-vec (list :start '(0 1) :len 32 :rfun (lambda (a b) (+ (* 2 b) a))))) A000931 : Padovan sequence : a(n ) = a(n-2 ) + a(n-3 ) with a(0)=1 , a(1)=a(2)=0 (assert-equalp #(1 0 0 1 0 1 1 1 2 2 3 4 5 7 9 12 16 21 28 37 49 65 86 114 151 200 265 351 465 616 816 1081 1432 1897 2513 3329 4410 5842 7739 10252 13581 17991 23833 31572 41824 55405 73396 97229 128801 170625) (mjr_vvec_to-vec (list :start '(1 0 0) :len 50 :rfun (lambda (a b c) (declare (ignore c)) (+ a b))))) (assert-equalp #(3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90 119 158 209 277 367 486 644 853 1130 1497 1983 2627 3480 4610 6107 8090 10717 14197 18807 24914 33004 43721 57918 76725 101639 134643 178364 236282 313007) (mjr_vvec_to-vec (list :start '(3 0 2) :len 46 :rfun (lambda (a b c) (declare (ignore c)) (+ a b))))) (loop for n from 1 upto 20 for c = (random 100) for v = (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start c :len n)) do (assert-true (every (lambda (a) (= a c)) v)) do (assert-equalp n (length v))) (assert-equalp #() (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start 1 :len 0 ))) (assert-error 'error (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start 1 :len -1 ))) (assert-error 'error (mjr_vvec_to-vec (list :vvec-type :vvt-rep :start 1 ))) (assert-error 'error (mjr_vvec_to-vec (list :vvec-type :vvt-rep :len 1 ))) : vvec - rep = = : vvr - vec (assert-equalp #(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-vec #(3 0 2 3 2 5 5 7 10 12))) (assert-equalp #(3 0 2 3 2) (mjr_vvec_to-vec #(3 0 2 3 2))) (assert-equalp #(3) (mjr_vvec_to-vec #(3))) (assert-equalp #() (mjr_vvec_to-vec #())) : vvec - rep = = : vvr - list (assert-equalp #(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-vec '(3 0 2 3 2 5 5 7 10 12))) (assert-equalp #(3 0 2 3 2) (mjr_vvec_to-vec '(3 0 2 3 2))) (assert-equalp #(3) (mjr_vvec_to-vec '(3))) (assert-equalp #() (mjr_vvec_to-vec '())) : vvec - rep = = : vvr - int (assert-equalp #(0 1 2 3 4 5 6 7 8 9) (mjr_vvec_to-vec 10)) (assert-equalp #(0 1 2 3) (mjr_vvec_to-vec 4)) (assert-equalp #(0) (mjr_vvec_to-vec 1)) (assert-equalp #() (mjr_vvec_to-vec 0)) (assert-equalp #(1) (mjr_vvec_to-vec -1)) (assert-equalp #(1 2 3 4) (mjr_vvec_to-vec -4)) (assert-equalp #(1 2 3 4 5 6 7 8 9 10) (mjr_vvec_to-vec -10)) ) (define-test mjr_vvec_to-list (assert-equalp '(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-list #(3 0 2 3 2 5 5 7 10 12))) (assert-equalp '(3 0 2 3 2) (mjr_vvec_to-list #(3 0 2 3 2))) (assert-equalp '(3) (mjr_vvec_to-list #(3))) (assert-equalp '() (mjr_vvec_to-list #())) (assert-equalp '(3 0 2 3 2 5 5 7 10 12) (mjr_vvec_to-list '(3 0 2 3 2 5 5 7 10 12))) (assert-equalp '(3 0 2 3 2) (mjr_vvec_to-list '(3 0 2 3 2))) (assert-equalp '(3) (mjr_vvec_to-list '(3))) (assert-equalp '() (mjr_vvec_to-list '())) (assert-equalp '(0 1 2 3 4 5 6 7 8 9) (mjr_vvec_to-list 10)) (assert-equalp '(0 1 2 3) (mjr_vvec_to-list 4)) (assert-equalp '(0) (mjr_vvec_to-list 1)) (assert-equalp '() (mjr_vvec_to-list 0)) (assert-equalp '(1) (mjr_vvec_to-list -1)) (assert-equalp '(1 2 3 4) (mjr_vvec_to-list -4)) (assert-equalp '(1 2 3 4 5 6 7 8 9 10) (mjr_vvec_to-list -10)) ) (define-test mjr_vvec_check-len (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len nil 't)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len nil nil)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len #() 't)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len 0 't)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len 0.0 't)) (assert-equalp 0 (mjr_vvec::mjr_vvec_check-len 0.499 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len #(1) 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len '(1) 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len 1 't)) (assert-equalp -1 (mjr_vvec::mjr_vvec_check-len -1 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len 1.0 't)) (assert-equalp 1 (mjr_vvec::mjr_vvec_check-len 0.51 't)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len #() nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0.0 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0.499 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len #(1) nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len '(1) nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 1 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len -1 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 1.0 nil)) (assert-equalp nil (mjr_vvec::mjr_vvec_check-len 0.51 nil)) ) (run-tests ) TODO : - type - check
084bcdcba7c18efbadd39b6d5c3f7323ebe1f4608bf8f50f9e64e7cc25bb2aef
mikebroberts/clojurenote
enml.clj
(ns clojurenote.enml (:use [clojure.walk :only [postwalk]]) (:require [clojure.xml :as xml])) ; ** READ ** (defn plain-span [text] (struct xml/element :span nil [text])) (defn en-media->simple-img-fn "An alternate translation for <en-media> that will produce <img> tags if the type of media starts with 'image/' . This function actually produces the function that should be passed to enml-> html, given a resource-map argument. This would be a map of hash-to-URL. It thus requires knowledge of all the resource hashes contained within the ENML ahead of time, and this would typically be gathered by examining the resources of the original Note, possibly using clojurenote.notes/resource->bean-with-body-hash-hex" [resource-map] (fn [{{:keys [hash type] :as attrs} :attrs :as node}] (if (.startsWith type "image/") (assoc node :tag :img :attrs (assoc attrs :src (get resource-map hash))) (plain-span "[Media in Evernote]") ))) (defn en-note->html-document "An alternate translation for <en-note> that will create a complete HTML document." [node] (struct xml/element :html nil [(assoc node :tag :body)])) (def default-en-tag-fns ^{:doc "Default translation behavior for enml->html. Override some or all of the functions in this map to specify your own translation behavior for each of the en- tags. Each function must take exactly 1 argument, which will be the top level node (as provided by clojure.xml) for a given XML tree of that type. See the en-*->* functions as examples of how your own functions should work"} { :en-note (fn [node] (assoc node :tag :div)) :en-media (fn [_] (plain-span "[Image in Evernote]")) :en-crypt (fn [_] (plain-span "[Encrypted in Evernote]")) :en-todo (fn [_] (plain-span "")) }) (defn remove-headers [enml] (-> enml (clojure.string/replace "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "") (clojure.string/replace "<!DOCTYPE en-note SYSTEM \"\">" ""))) (defn replace-tags [tag-fns node] (if-let [tag-fn (get tag-fns (:tag node))] (tag-fn node) node)) (defn walk-fn [user-supplied-tag-fns] (partial replace-tags (into default-en-tag-fns (apply hash-map user-supplied-tag-fns)))) (defn enml->html "Translates an ENML document to HTML by removing headers and translating <en-*> tags. Default translation is simplist possible, but won't (for example) map <en-media> tags to <img> tags. Specify optional en-tag-fns argument in order to customize the tag translation behavior. See documentation on default-en-tag-fns for more detail." [enml & optional-en-tag-fns] (->> enml (remove-headers) (.getBytes) (java.io.ByteArrayInputStream.) (xml/parse) (postwalk (walk-fn optional-en-tag-fns)) (xml/emit-element) (with-out-str) )) (defn note->html "Same as enml->html (including the same optional argument), but takes a Note instead of ENML document. Note can be the original Java object returned by the Evernote API, or can be the 'beaned' version of the same object." [{content :content :as note} & more] (apply enml->html (if content content (.getContent note)) more)) ; ** WRITE ** (def enml-header (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<!DOCTYPE en-note SYSTEM \"\">" "<en-note>")) (def enml-footer "</en-note>") (defn create-enml-document "Creates an ENML document by adding XML headers and wrapping with a <en-note> tag. Original content must already be valid ENML" [content] (format (str enml-header "%s" enml-footer) (if content content "")))
null
https://raw.githubusercontent.com/mikebroberts/clojurenote/db1f183fcb3766b9fb219484f3d9a17bd1fa4563/clojurenote/src/clojurenote/enml.clj
clojure
** READ ** ** WRITE **
(ns clojurenote.enml (:use [clojure.walk :only [postwalk]]) (:require [clojure.xml :as xml])) (defn plain-span [text] (struct xml/element :span nil [text])) (defn en-media->simple-img-fn "An alternate translation for <en-media> that will produce <img> tags if the type of media starts with 'image/' . This function actually produces the function that should be passed to enml-> html, given a resource-map argument. This would be a map of hash-to-URL. It thus requires knowledge of all the resource hashes contained within the ENML ahead of time, and this would typically be gathered by examining the resources of the original Note, possibly using clojurenote.notes/resource->bean-with-body-hash-hex" [resource-map] (fn [{{:keys [hash type] :as attrs} :attrs :as node}] (if (.startsWith type "image/") (assoc node :tag :img :attrs (assoc attrs :src (get resource-map hash))) (plain-span "[Media in Evernote]") ))) (defn en-note->html-document "An alternate translation for <en-note> that will create a complete HTML document." [node] (struct xml/element :html nil [(assoc node :tag :body)])) (def default-en-tag-fns ^{:doc "Default translation behavior for enml->html. Override some or all of the functions in this map to specify your own translation behavior for each of the en- tags. Each function must take exactly 1 argument, which will be the top level node (as provided by clojure.xml) for a given XML tree of that type. See the en-*->* functions as examples of how your own functions should work"} { :en-note (fn [node] (assoc node :tag :div)) :en-media (fn [_] (plain-span "[Image in Evernote]")) :en-crypt (fn [_] (plain-span "[Encrypted in Evernote]")) :en-todo (fn [_] (plain-span "")) }) (defn remove-headers [enml] (-> enml (clojure.string/replace "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "") (clojure.string/replace "<!DOCTYPE en-note SYSTEM \"\">" ""))) (defn replace-tags [tag-fns node] (if-let [tag-fn (get tag-fns (:tag node))] (tag-fn node) node)) (defn walk-fn [user-supplied-tag-fns] (partial replace-tags (into default-en-tag-fns (apply hash-map user-supplied-tag-fns)))) (defn enml->html "Translates an ENML document to HTML by removing headers and translating <en-*> tags. Default translation is simplist possible, but won't (for example) map <en-media> tags to <img> tags. Specify optional en-tag-fns argument in order to customize the tag translation behavior. See documentation on default-en-tag-fns for more detail." [enml & optional-en-tag-fns] (->> enml (remove-headers) (.getBytes) (java.io.ByteArrayInputStream.) (xml/parse) (postwalk (walk-fn optional-en-tag-fns)) (xml/emit-element) (with-out-str) )) (defn note->html "Same as enml->html (including the same optional argument), but takes a Note instead of ENML document. Note can be the original Java object returned by the Evernote API, or can be the 'beaned' version of the same object." [{content :content :as note} & more] (apply enml->html (if content content (.getContent note)) more)) (def enml-header (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<!DOCTYPE en-note SYSTEM \"\">" "<en-note>")) (def enml-footer "</en-note>") (defn create-enml-document "Creates an ENML document by adding XML headers and wrapping with a <en-note> tag. Original content must already be valid ENML" [content] (format (str enml-header "%s" enml-footer) (if content content "")))
dd91eb3de9a91a1945f5f091cf12c77f8ff7edefcf48343d59a49486a62a385e
tonymorris/geo-gpx
DgpsStation.hs
-- | Simple Type: @dgpsStationType@ </#type_dgpsStationType> module Data.Geo.GPX.Type.DgpsStation( DgpsStation , dgpsStation , runDgpsStation ) where import Data.Ix import Text.XML.HXT.Arrow.Pickle newtype DgpsStation = DgpsStation Int deriving (Eq, Ord) dgpsStation :: ^ The value between 0 and 1023 . -> Maybe DgpsStation dgpsStation n = if inRange (0, 1023) n then Just (DgpsStation n) else Nothing runDgpsStation :: DgpsStation -> Int runDgpsStation (DgpsStation i) = i instance XmlPickler DgpsStation where xpickle = xpWrapMaybe (dgpsStation, \(DgpsStation n) -> n) xpickle
null
https://raw.githubusercontent.com/tonymorris/geo-gpx/526b59ec403293c810c2ba08d2c006dc526e8bf9/src/Data/Geo/GPX/Type/DgpsStation.hs
haskell
| Simple Type: @dgpsStationType@ </#type_dgpsStationType>
module Data.Geo.GPX.Type.DgpsStation( DgpsStation , dgpsStation , runDgpsStation ) where import Data.Ix import Text.XML.HXT.Arrow.Pickle newtype DgpsStation = DgpsStation Int deriving (Eq, Ord) dgpsStation :: ^ The value between 0 and 1023 . -> Maybe DgpsStation dgpsStation n = if inRange (0, 1023) n then Just (DgpsStation n) else Nothing runDgpsStation :: DgpsStation -> Int runDgpsStation (DgpsStation i) = i instance XmlPickler DgpsStation where xpickle = xpWrapMaybe (dgpsStation, \(DgpsStation n) -> n) xpickle
c8ba541eae685315c9951517f6b0e57cdd845ae92aa7a6fcdf38a5afe7e822a5
runtimeverification/haskell-backend
PatternVerifier.hs
module Test.Kore.Validate.DefinitionVerifier.PatternVerifier ( test_patternVerifier, test_verifyBinder, ) where import Data.List qualified as List import Data.Text qualified as Text import Kore.Attribute.Hook qualified as Attribute.Hook import Kore.Attribute.Simplification ( simplificationAttribute, ) import Kore.Attribute.Sort.HasDomainValues qualified as Attribute.HasDomainValues import Kore.Error import Kore.IndexedModule.Error ( noSort, ) import Kore.IndexedModule.IndexedModule ( IndexedModule (..), ) import Kore.Internal.TermLike qualified as Internal import Kore.Syntax import Kore.Syntax.Definition import Kore.Validate.Error ( sortNeedsDomainValueAttributeMessage, ) import Kore.Validate.PatternVerifier as PatternVerifier import Prelude.Kore import Test.Kore import Test.Kore.Builtin.Builtin qualified as Builtin import Test.Kore.Builtin.Definition qualified as Builtin import Test.Kore.Builtin.External import Test.Kore.Validate.DefinitionVerifier as Helpers import Test.Tasty ( TestTree, ) import Test.Tasty.HUnit data PatternRestrict = NeedsInternalDefinitions | NeedsSortedParent data TestPattern = TestPattern { testPatternPattern :: !(PatternF VariableName ParsedPattern) , testPatternSort :: !Sort , testPatternErrorStack :: !ErrorStack } newtype VariableOfDeclaredSort = VariableOfDeclaredSort (ElementVariable VariableName) testPatternErrorStackStrings :: TestPattern -> [String] testPatternErrorStackStrings TestPattern{testPatternErrorStack = ErrorStack strings} = strings testPatternUnverifiedPattern :: TestPattern -> ParsedPattern testPatternUnverifiedPattern TestPattern{testPatternPattern} = embedParsedPattern testPatternPattern test_patternVerifier :: [TestTree] test_patternVerifier = [ expectSuccess "Simplest definition" (simpleDefinitionFromSentences (ModuleName "MODULE") []) , successTestsForObjectPattern "Simple object pattern" (simpleExistsPattern objectVariable' objectSort) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - sort not defined" (ExpectedErrorMessage $ noSort "ObjectSort") ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "\\exists 'ObjectVariable' (<test data>)" , "sort 'ObjectSort' (<test data>)" , "(<test data>)" ] ) ( ExistsF Exists { existsSort = anotherSort , existsVariable = anotherVariable , existsChild = embedParsedPattern $ simpleExistsPattern objectVariable' objectSort } ) (NamePrefix "dummy") (TestedPatternSort anotherSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - different variable sort" (ExpectedErrorMessage "The declared sort is different.") ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "element variable 'ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) ( ExistsF Exists { existsSort = objectSort , existsVariable = objectVariable' , existsChild = externalize $ Internal.mkElemVar anotherVariable } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Object pattern - sort variable defined" ( simpleExistsPattern objectVariableSortVariable objectSortVariableSort ) (NamePrefix "dummy") (TestedPatternSort objectSortVariableSort) (SortVariablesThatMustBeDeclared [objectSortVariable]) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Mu pattern - different variable sort" (ExpectedErrorMessage "The declared sort is different.") ( ErrorStack [ "\\mu (<test data>)" , "set variable '@ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) ( MuF Mu { muVariable = objectSetVariable' , muChild = externalize $ Internal.mkSetVar anotherSetVariable } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Mu pattern - sort variable defined" (simpleMuPattern objectSetVariableSortVariable) (NamePrefix "dummy") (TestedPatternSort objectSortVariableSort) (SortVariablesThatMustBeDeclared [objectSortVariable]) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Nu pattern - different variable sort" (ExpectedErrorMessage "The declared sort is different.") ( ErrorStack [ "\\nu (<test data>)" , "set variable '@ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) ( NuF Nu { nuVariable = objectSetVariable' , nuChild = externalize $ Internal.mkSetVar anotherSetVariable } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Nu pattern - sort variable defined" (simpleNuPattern objectSetVariableSortVariable) (NamePrefix "dummy") (TestedPatternSort objectSortVariableSort) (SortVariablesThatMustBeDeclared [objectSortVariable]) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - sort variable not defined" ( ExpectedErrorMessage "Sort variable ObjectSortVariable not declared." ) ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "\\exists 'ObjectVariable' (<test data>)" , "(<test data>)" ] ) ( ExistsF Exists { existsSort = objectSort , existsVariable = objectVariable' , existsChild = embedParsedPattern $ simpleExistsPattern objectVariableSortVariable objectSortVariableSort } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - sort not matched" ( ExpectedErrorMessage "Expecting sort anotherSort2{} but got ObjectSort{}." ) ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) (simpleExistsPattern objectVariable' anotherObjectSort2) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 ] NeedsInternalDefinitions , successTestsForObjectPattern "Application pattern - symbol" ( applicationPatternWithChildren objectSymbolName [simpleExistsParsedPattern objectVariableName anotherObjectSort2] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectSymbolSentence ] NeedsInternalDefinitions , successTestsForObjectPattern "Application pattern - alias" ( applicationPatternWithChildren objectAliasNameAsSymbol [ variableParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectAliasSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - symbol not declared" (ExpectedErrorMessage "Head 'ObjectSymbol' not defined.") (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( applicationPatternWithChildren objectSymbolName [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 --, objectSymbolSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - not enough arguments" (ExpectedErrorMessage "Expected 1 operands, but got 0.") (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) (applicationPatternWithChildren objectSymbolName []) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectSymbolSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - too many arguments" (ExpectedErrorMessage "Expected 1 operands, but got 2.") (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( applicationPatternWithChildren objectSymbolName [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 , simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectSymbolSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern alias - too many arguments" (ExpectedErrorMessage "Expected 1 operands, but got 2.") (ErrorStack ["symbol or alias 'ObjectAlias' (<test data>)"]) ( applicationPatternWithChildren objectAliasNameAsSymbol [ variableParsedPattern objectVariableName anotherObjectSort2 , variableParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectAliasSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - too few sorts" ( ExpectedErrorMessage "Application uses less sorts than the declaration." ) (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( ApplicationF Application { applicationSymbolOrAlias = SymbolOrAlias { symbolOrAliasConstructor = testId oneSortSymbolRawName , symbolOrAliasParams = [] } , applicationChildren = [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , oneSortSymbolSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - too many sorts" ( ExpectedErrorMessage "Application uses more sorts than the declaration." ) (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( ApplicationF Application { applicationSymbolOrAlias = SymbolOrAlias { symbolOrAliasConstructor = testId oneSortSymbolRawName , symbolOrAliasParams = [objectSort, objectSort] } , applicationChildren = [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , oneSortSymbolSentence ] NeedsInternalDefinitions , successTestsForObjectPattern "Object pattern - unquantified variable" (VariableF $ Const $ inject objectVariable') (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Bottom pattern" (BottomF Bottom{bottomSort = objectSort}) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence ] NeedsInternalDefinitions , successTestsForObjectPattern "Top pattern" (TopF Top{topSort = objectSort}) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Domain value - INT.Int" ( ExpectedErrorMessage "<string literal>:1:1:\n\ \ |\n\ \1 | abcd\n\ \ | ^\n\ \unexpected 'a'\n\ \expecting '+', '-', or integer\n" ) ( ErrorStack [ "\\dv (<test data>)" , "Verifying builtin sort 'INT.Int'" , "While parsing domain value" ] ) ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "abcd" -- Not a decimal integer } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - INT.Int - Negative" ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "-256" } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - INT.Int - Positive (unsigned)" ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "1024" } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - INT.Int - Positive (signed)" ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "+128" } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Domain value - BOOL.Bool" ( ExpectedErrorMessage "<string literal>:1:1:\n\ \ |\n\ \1 | untrue\n\ \ | ^^^^^\n\ \unexpected \"untru\"\n\ \expecting \"false\" or \"true\"\n" ) ( ErrorStack [ "\\dv (<test data>)" , "Verifying builtin sort 'BOOL.Bool'" , "While parsing domain value" ] ) ( DomainValueF DomainValue { domainValueSort = boolSort , domainValueChild = externalize $ Internal.mkStringLiteral "untrue" -- Not a BOOL.Bool } ) (NamePrefix "dummy") (TestedPatternSort boolSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort boolSort) [asSentence boolSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - BOOL.Bool - true" ( DomainValueF DomainValue { domainValueSort = boolSort , domainValueChild = externalize $ Internal.mkStringLiteral "true" } ) (NamePrefix "dummy") (TestedPatternSort boolSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort boolSort) [asSentence boolSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - BOOL.Bool - false" ( DomainValueF DomainValue { domainValueSort = boolSort , domainValueChild = externalize $ Internal.mkStringLiteral "false" } ) (NamePrefix "dummy") (TestedPatternSort boolSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort boolSort) [asSentence boolSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Domain value - sort without DVs" ( ExpectedErrorMessage (Text.unpack sortNeedsDomainValueAttributeMessage) ) ( ErrorStack [ "\\dv (<test data>)" , "(<test data>)" ] ) ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "1" -- Not a decimal integer } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentenceWithoutDv] NeedsInternalDefinitions ] where objectSortName = SortName "ObjectSort" objectSort :: Sort objectSort = simpleSort objectSortName objectVariableName = "ObjectVariable" objectVariable' = variable objectVariableName objectSort objectSetVariable' = setVariable objectVariableName objectSort objectSortSentence = simpleSortSentence objectSortName anotherSortName = SortName "anotherSort" anotherSort :: Sort anotherSort = simpleSort anotherSortName anotherVariable = variable objectVariableName anotherSort anotherSetVariable = setVariable objectVariableName anotherSort anotherSortSentence = simpleSortSentence anotherSortName anotherObjectSortName2 = SortName "anotherSort2" anotherObjectSort2 :: Sort anotherObjectSort2 = simpleSort anotherObjectSortName2 anotherObjectSortSentence2 = simpleSortSentence anotherObjectSortName2 objectSymbolName = SymbolName "ObjectSymbol" objectSymbolSentence = objectSymbolSentenceWithArguments objectSymbolName objectSort [anotherObjectSort2] objectAliasName = AliasName "ObjectAlias" objectAliasNameAsSymbol = SymbolName "ObjectAlias" objectAliasSentence = objectAliasSentenceWithArguments objectAliasName objectSort [inject $ mkElementVariable (testId "x") anotherObjectSort2] objectSortVariable = sortVariable "ObjectSortVariable" objectSortVariableSort :: Sort objectSortVariableSort = sortVariableSort "ObjectSortVariable" objectVariableSortVariable = variable objectVariableName objectSortVariableSort objectSetVariableSortVariable = setVariable objectVariableName objectSortVariableSort oneSortSymbolRawName = "ObjectSymbol" oneSortSymbolSentence :: ParsedSentence oneSortSymbolSentence = asSentence SentenceSymbol { sentenceSymbolSymbol = Symbol { symbolConstructor = testId oneSortSymbolRawName , symbolParams = [objectSortVariable] } , sentenceSymbolSorts = [anotherObjectSort2] , sentenceSymbolResultSort = objectSort , sentenceSymbolAttributes = Attributes [] } intSortName = SortName "Int" intSort :: Sort intSort = simpleSort intSortName intSortSentence :: ParsedSentenceHook intSortSentence = SentenceHookedSort SentenceSort { sentenceSortName = testId name , sentenceSortParameters = [] , sentenceSortAttributes = Attributes [ Attribute.Hook.hookAttribute "INT.Int" , Attribute.HasDomainValues.hasDomainValuesAttribute ] } where SortName name = intSortName intSortSentenceWithoutDv = SentenceHookedSort SentenceSort { sentenceSortName = testId name , sentenceSortParameters = [] , sentenceSortAttributes = Attributes [Attribute.Hook.hookAttribute "INT.Int"] } where SortName name = intSortName boolSortName = SortName "Int" boolSort :: Sort boolSort = simpleSort boolSortName boolSortSentence :: ParsedSentenceHook boolSortSentence = SentenceHookedSort SentenceSort { sentenceSortName = testId name , sentenceSortParameters = [] , sentenceSortAttributes = Attributes [ Attribute.Hook.hookAttribute "BOOL.Bool" , Attribute.HasDomainValues.hasDomainValuesAttribute ] } where SortName name = boolSortName test_verifyBinder :: [TestTree] test_verifyBinder = [ testVerifyExists , testVerifyForall ] where context = PatternVerifier.verifiedModuleContext $ indexedModuleSyntax Builtin.verifiedModule testVerifyBinder name expect = testCase name $ do let original = externalize expect verifier = verifyStandalonePattern Nothing original actual = assertRight $ runPatternVerifier context verifier assertEqual "" expect actual on (assertEqual "") Internal.extractAttributes expect actual testVerifyExists = testVerifyBinder "verifyExists" expect where x = Internal.mkElementVariable "x" Builtin.intSort expect = Internal.mkExists x (Internal.mkElemVar x) testVerifyForall = testVerifyBinder "verifyForall" expect where x = Internal.mkElementVariable "x" Builtin.intSort expect = Internal.mkForall x (Internal.mkElemVar x) dummyVariableAndSentences :: NamePrefix -> (ElementVariable VariableName, [ParsedSentence]) dummyVariableAndSentences (NamePrefix namePrefix) = (dummyVariable, [simpleSortSentence dummySortName]) where dummySortName = SortName (namePrefix <> "_OtherSort") dummySort' = simpleSort dummySortName dummyVariable = variable (namePrefix <> "_OtherVariable") dummySort' successTestsForObjectPattern :: HasCallStack => String -> PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> TestTree successTestsForObjectPattern description testedPattern namePrefix testedSort sortVariables anotherSort sentences patternRestrict = successTestDataGroup description testData where (dummyVariable, dummySortSentences) = dummyVariableAndSentences namePrefix testData = genericPatternInAllContexts testedPattern namePrefix testedSort sortVariables sortVariables anotherSort (VariableOfDeclaredSort dummyVariable) (dummySortSentences ++ sentences) patternRestrict ++ objectPatternInAllContexts testedPattern namePrefix testedSort sortVariables anotherSort (dummySortSentences ++ sentences) patternRestrict failureTestsForObjectPattern :: HasCallStack => String -> ExpectedErrorMessage -> ErrorStack -> PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> TestTree failureTestsForObjectPattern description errorMessage errorStackSuffix testedPattern namePrefix@(NamePrefix rawNamePrefix) testedSort sortVariables anotherSort sentences patternRestrict = failureTestDataGroup description errorMessage errorStackSuffix testData where dummySortName = SortName (rawNamePrefix <> "_OtherSort") dummySort' = simpleSort dummySortName dummyVariable = variable (rawNamePrefix <> "_OtherVariable") dummySort' dummySortSentence = simpleSortSentence dummySortName testData = genericPatternInAllContexts testedPattern namePrefix testedSort sortVariables sortVariables anotherSort (VariableOfDeclaredSort dummyVariable) (dummySortSentence : sentences) patternRestrict ++ objectPatternInAllContexts testedPattern namePrefix testedSort sortVariables anotherSort (dummySortSentence : sentences) patternRestrict genericPatternInAllContexts :: PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> SortVariablesThatMustBeDeclared -> DeclaredSort -> VariableOfDeclaredSort -> [ParsedSentence] -> PatternRestrict -> [TestData] genericPatternInAllContexts testedPattern (NamePrefix namePrefix) (TestedPatternSort testedSort) sortVariables objectSortVariables (DeclaredSort anotherSort) dummyVariable sentences patternRestrict = patternsInAllContexts patternExpansion (NamePrefix namePrefix) sortVariables objectSortVariables (DeclaredSort anotherSort) sentences patternRestrict where patternExpansion = genericPatternInPatterns testedPattern anotherPattern (OperandSort testedSort) (Helpers.ResultSort anotherSort) dummyVariable (symbolFromSort testedSort) (aliasFromSort testedSort) patternRestrict anotherPattern = ExistsF Exists { existsSort = testedSort , existsVariable = anotherVariable , existsChild = externalize $ Internal.mkElemVar anotherVariable } anotherVariable = mkElementVariable (testId (namePrefix <> "_anotherVar")) testedSort rawSymbolName = namePrefix <> "_anotherSymbol" rawAliasName = namePrefix <> "_anotherAlias" symbolFromSort sort = SymbolOrAlias { symbolOrAliasConstructor = testId rawSymbolName , symbolOrAliasParams = [sort] } aliasFromSort sort = SymbolOrAlias { symbolOrAliasConstructor = testId rawAliasName , symbolOrAliasParams = [sort] } objectPatternInAllContexts :: PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> [TestData] objectPatternInAllContexts testedPattern (NamePrefix namePrefix) (TestedPatternSort testedSort) sortVariables (DeclaredSort anotherSort) = patternsInAllContexts patternExpansion (NamePrefix namePrefix) sortVariables sortVariables (DeclaredSort anotherSort) where patternExpansion = objectPatternInPatterns testedPattern anotherPattern (OperandSort testedSort) anotherPattern = ExistsF Exists { existsSort = testedSort , existsVariable = anotherVariable , existsChild = externalize $ Internal.mkElemVar anotherVariable } anotherVariable = mkElementVariable (testId (namePrefix <> "_anotherVar")) testedSort patternsInAllContexts :: [TestPattern] -> NamePrefix -> SortVariablesThatMustBeDeclared -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> [TestData] patternsInAllContexts patterns (NamePrefix namePrefix) sortVariables objectSortVariables (DeclaredSort anotherSort) sentences patternRestrict = map (\context -> context (List.head patterns)) contextExpansion ++ map (List.head contextExpansion) patterns where contextExpansion = testsForUnifiedPatternInTopLevelContext (NamePrefix (namePrefix <> "_piac")) (DeclaredSort anotherSort) sortVariables objectSortVariables ( symbolSentence : aliasSentence : sentences ) patternRestrict rawSymbolName = namePrefix <> "_anotherSymbol" rawAliasName = namePrefix <> "_anotherAlias" rawSortVariableName = namePrefix <> "_sortVariable" symbolAliasSort = sortVariableSort rawSortVariableName symbolSentence = SentenceSymbolSentence SentenceSymbol { sentenceSymbolSymbol = Symbol { symbolConstructor = testId rawSymbolName , symbolParams = [SortVariable (testId rawSortVariableName)] } , sentenceSymbolSorts = [symbolAliasSort] , sentenceSymbolResultSort = anotherSort , sentenceSymbolAttributes = Attributes [] } aliasSentence :: ParsedSentence aliasSentence = let aliasConstructor = testId rawAliasName aliasParams = [SortVariable (testId rawSortVariableName)] in SentenceAliasSentence SentenceAlias { sentenceAliasAlias = Alias{aliasConstructor, aliasParams} , sentenceAliasSorts = [symbolAliasSort] , sentenceAliasResultSort = anotherSort , sentenceAliasLeftPattern = Application { applicationSymbolOrAlias = SymbolOrAlias { symbolOrAliasConstructor = aliasConstructor , symbolOrAliasParams = SortVariableSort <$> aliasParams } , applicationChildren = [inject $ mkSetVariable (testId "x") symbolAliasSort] } , sentenceAliasRightPattern = externalize $ Internal.mkTop anotherSort , sentenceAliasAttributes = Attributes [] } genericPatternInPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> Helpers.ResultSort -> VariableOfDeclaredSort -> SymbolOrAlias -> SymbolOrAlias -> PatternRestrict -> [TestPattern] genericPatternInPatterns testedPattern anotherPattern sort@(OperandSort testedSort) resultSort (VariableOfDeclaredSort dummyVariable) symbol alias patternRestrict = patternInQuantifiedPatterns testedPattern testedSort dummyVariable ++ patternInUnquantifiedGenericPatterns testedPattern anotherPattern sort resultSort ++ case patternRestrict of NeedsSortedParent -> [] _ -> [ TestPattern { testPatternPattern = testedPattern , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [] } ] ++ [ TestPattern { testPatternPattern = ApplicationF Application { applicationSymbolOrAlias = symbol , applicationChildren = [embedParsedPattern testedPattern] } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "symbol or alias '" ++ getIdForError (symbolOrAliasConstructor symbol) ++ "' (<test data>)" ] } , TestPattern { testPatternPattern = ApplicationF Application { applicationSymbolOrAlias = alias , applicationChildren = [embedParsedPattern testedPattern] } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "symbol or alias '" ++ getIdForError (symbolOrAliasConstructor alias) ++ "' (<test data>)" ] } ] objectPatternInPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> [TestPattern] objectPatternInPatterns = patternInUnquantifiedObjectPatterns patternInQuantifiedPatterns :: PatternF VariableName ParsedPattern -> Sort -> ElementVariable VariableName -> [TestPattern] patternInQuantifiedPatterns testedPattern testedSort quantifiedVariable = [ TestPattern { testPatternPattern = ExistsF Exists { existsSort = testedSort , existsVariable = quantifiedVariable , existsChild = testedKorePattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "\\exists '" ++ getIdForError ( base . unElementVariableName . variableName $ quantifiedVariable ) ++ "' (<test data>)" ] } , TestPattern { testPatternPattern = ForallF Forall { forallSort = testedSort , forallVariable = quantifiedVariable , forallChild = testedKorePattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "\\forall '" ++ getIdForError ( base . unElementVariableName . variableName $ quantifiedVariable ) ++ "' (<test data>)" ] } ] where testedKorePattern = embedParsedPattern testedPattern patternInUnquantifiedGenericPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> Helpers.ResultSort -> [TestPattern] patternInUnquantifiedGenericPatterns testedPattern anotherPattern (OperandSort testedSort) (Helpers.ResultSort resultSort) = [ TestPattern { testPatternPattern = AndF And { andSort = testedSort , andFirst = testedUnifiedPattern , andSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\and (<test data>)"] } , TestPattern { testPatternPattern = AndF And { andSort = testedSort , andFirst = anotherUnifiedPattern , andSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\and (<test data>)"] } , TestPattern { testPatternPattern = CeilF Ceil { ceilOperandSort = testedSort , ceilResultSort = resultSort , ceilChild = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\ceil (<test data>)"] } , TestPattern { testPatternPattern = EqualsF Equals { equalsOperandSort = testedSort , equalsResultSort = resultSort , equalsFirst = testedUnifiedPattern , equalsSecond = anotherUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\equals (<test data>)"] } , TestPattern { testPatternPattern = EqualsF Equals { equalsOperandSort = testedSort , equalsResultSort = resultSort , equalsFirst = anotherUnifiedPattern , equalsSecond = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\equals (<test data>)"] } , TestPattern { testPatternPattern = FloorF Floor { floorOperandSort = testedSort , floorResultSort = resultSort , floorChild = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\floor (<test data>)"] } , TestPattern { testPatternPattern = IffF Iff { iffSort = testedSort , iffFirst = testedUnifiedPattern , iffSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\iff (<test data>)"] } , TestPattern { testPatternPattern = IffF Iff { iffSort = testedSort , iffFirst = anotherUnifiedPattern , iffSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\iff (<test data>)"] } , TestPattern { testPatternPattern = ImpliesF Implies { impliesSort = testedSort , impliesFirst = testedUnifiedPattern , impliesSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\implies (<test data>)"] } , TestPattern { testPatternPattern = ImpliesF Implies { impliesSort = testedSort , impliesFirst = anotherUnifiedPattern , impliesSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\implies (<test data>)"] } , TestPattern { testPatternPattern = InF In { inOperandSort = testedSort , inResultSort = resultSort , inContainedChild = testedUnifiedPattern , inContainingChild = anotherUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\in (<test data>)"] } , TestPattern { testPatternPattern = InF In { inOperandSort = testedSort , inResultSort = resultSort , inContainedChild = anotherUnifiedPattern , inContainingChild = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\in (<test data>)"] } , TestPattern { testPatternPattern = NotF Not { notSort = testedSort , notChild = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\not (<test data>)"] } , TestPattern { testPatternPattern = OrF Or { orSort = testedSort , orFirst = testedUnifiedPattern , orSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\or (<test data>)"] } , TestPattern { testPatternPattern = OrF Or { orSort = testedSort , orFirst = anotherUnifiedPattern , orSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\or (<test data>)"] } ] where anotherUnifiedPattern = embedParsedPattern anotherPattern testedUnifiedPattern = embedParsedPattern testedPattern patternInUnquantifiedObjectPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> [TestPattern] patternInUnquantifiedObjectPatterns testedPattern anotherPattern (OperandSort testedSort) = [ TestPattern { testPatternPattern = NextF Next { nextSort = testedSort , nextChild = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\next (<test data>)"] } , TestPattern { testPatternPattern = RewritesF Rewrites { rewritesSort = testedSort , rewritesFirst = testedUnifiedPattern , rewritesSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\rewrites (<test data>)"] } , TestPattern { testPatternPattern = RewritesF Rewrites { rewritesSort = testedSort , rewritesFirst = anotherUnifiedPattern , rewritesSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\rewrites (<test data>)"] } ] where anotherUnifiedPattern = embedParsedPattern anotherPattern testedUnifiedPattern = embedParsedPattern testedPattern testsForUnifiedPatternInTopLevelContext :: NamePrefix -> DeclaredSort -> SortVariablesThatMustBeDeclared -> SortVariablesThatMustBeDeclared -> [ParsedSentence] -> PatternRestrict -> [TestPattern -> TestData] testsForUnifiedPatternInTopLevelContext namePrefix additionalSort sortVariables _ = testsForUnifiedPatternInTopLevelGenericContext namePrefix additionalSort sortVariables testsForUnifiedPatternInTopLevelGenericContext :: NamePrefix -> DeclaredSort -> SortVariablesThatMustBeDeclared -> [ParsedSentence] -> PatternRestrict -> [TestPattern -> TestData] testsForUnifiedPatternInTopLevelGenericContext (NamePrefix _) (DeclaredSort _) (SortVariablesThatMustBeDeclared sortVariables) additionalSentences patternRestrict = let axiomPattern testPattern = TestData { testDataDescription = "Pattern in axiom" , testDataError = Error ( "module 'MODULE'" : "axiom declaration" : testPatternErrorStackStrings testPattern ) defaultErrorMessage , testDataDefinition = simpleDefinitionFromSentences (ModuleName "MODULE") ( axiomSentenceWithParamsAndAttrs (testPatternUnverifiedPattern testPattern) sortVariables [simplificationAttribute Nothing] : additionalSentences ) } in case patternRestrict of NeedsInternalDefinitions -> [axiomPattern] NeedsSortedParent -> [axiomPattern] defaultErrorMessage :: String defaultErrorMessage = "Replace this with a real error message." -- MLPatternType -- Application -- axiom -- attributes -- module and definition
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/7e0d12bef597158073a5d273185096828bd68300/kore/test/Test/Kore/Validate/DefinitionVerifier/PatternVerifier.hs
haskell
, objectSymbolSentence Not a decimal integer Not a BOOL.Bool Not a decimal integer MLPatternType Application axiom attributes -- module and definition
module Test.Kore.Validate.DefinitionVerifier.PatternVerifier ( test_patternVerifier, test_verifyBinder, ) where import Data.List qualified as List import Data.Text qualified as Text import Kore.Attribute.Hook qualified as Attribute.Hook import Kore.Attribute.Simplification ( simplificationAttribute, ) import Kore.Attribute.Sort.HasDomainValues qualified as Attribute.HasDomainValues import Kore.Error import Kore.IndexedModule.Error ( noSort, ) import Kore.IndexedModule.IndexedModule ( IndexedModule (..), ) import Kore.Internal.TermLike qualified as Internal import Kore.Syntax import Kore.Syntax.Definition import Kore.Validate.Error ( sortNeedsDomainValueAttributeMessage, ) import Kore.Validate.PatternVerifier as PatternVerifier import Prelude.Kore import Test.Kore import Test.Kore.Builtin.Builtin qualified as Builtin import Test.Kore.Builtin.Definition qualified as Builtin import Test.Kore.Builtin.External import Test.Kore.Validate.DefinitionVerifier as Helpers import Test.Tasty ( TestTree, ) import Test.Tasty.HUnit data PatternRestrict = NeedsInternalDefinitions | NeedsSortedParent data TestPattern = TestPattern { testPatternPattern :: !(PatternF VariableName ParsedPattern) , testPatternSort :: !Sort , testPatternErrorStack :: !ErrorStack } newtype VariableOfDeclaredSort = VariableOfDeclaredSort (ElementVariable VariableName) testPatternErrorStackStrings :: TestPattern -> [String] testPatternErrorStackStrings TestPattern{testPatternErrorStack = ErrorStack strings} = strings testPatternUnverifiedPattern :: TestPattern -> ParsedPattern testPatternUnverifiedPattern TestPattern{testPatternPattern} = embedParsedPattern testPatternPattern test_patternVerifier :: [TestTree] test_patternVerifier = [ expectSuccess "Simplest definition" (simpleDefinitionFromSentences (ModuleName "MODULE") []) , successTestsForObjectPattern "Simple object pattern" (simpleExistsPattern objectVariable' objectSort) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - sort not defined" (ExpectedErrorMessage $ noSort "ObjectSort") ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "\\exists 'ObjectVariable' (<test data>)" , "sort 'ObjectSort' (<test data>)" , "(<test data>)" ] ) ( ExistsF Exists { existsSort = anotherSort , existsVariable = anotherVariable , existsChild = embedParsedPattern $ simpleExistsPattern objectVariable' objectSort } ) (NamePrefix "dummy") (TestedPatternSort anotherSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - different variable sort" (ExpectedErrorMessage "The declared sort is different.") ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "element variable 'ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) ( ExistsF Exists { existsSort = objectSort , existsVariable = objectVariable' , existsChild = externalize $ Internal.mkElemVar anotherVariable } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Object pattern - sort variable defined" ( simpleExistsPattern objectVariableSortVariable objectSortVariableSort ) (NamePrefix "dummy") (TestedPatternSort objectSortVariableSort) (SortVariablesThatMustBeDeclared [objectSortVariable]) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Mu pattern - different variable sort" (ExpectedErrorMessage "The declared sort is different.") ( ErrorStack [ "\\mu (<test data>)" , "set variable '@ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) ( MuF Mu { muVariable = objectSetVariable' , muChild = externalize $ Internal.mkSetVar anotherSetVariable } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Mu pattern - sort variable defined" (simpleMuPattern objectSetVariableSortVariable) (NamePrefix "dummy") (TestedPatternSort objectSortVariableSort) (SortVariablesThatMustBeDeclared [objectSortVariable]) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Nu pattern - different variable sort" (ExpectedErrorMessage "The declared sort is different.") ( ErrorStack [ "\\nu (<test data>)" , "set variable '@ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) ( NuF Nu { nuVariable = objectSetVariable' , nuChild = externalize $ Internal.mkSetVar anotherSetVariable } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Nu pattern - sort variable defined" (simpleNuPattern objectSetVariableSortVariable) (NamePrefix "dummy") (TestedPatternSort objectSortVariableSort) (SortVariablesThatMustBeDeclared [objectSortVariable]) (DeclaredSort anotherSort) [anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - sort variable not defined" ( ExpectedErrorMessage "Sort variable ObjectSortVariable not declared." ) ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "\\exists 'ObjectVariable' (<test data>)" , "(<test data>)" ] ) ( ExistsF Exists { existsSort = objectSort , existsVariable = objectVariable' , existsChild = embedParsedPattern $ simpleExistsPattern objectVariableSortVariable objectSortVariableSort } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - sort not matched" ( ExpectedErrorMessage "Expecting sort anotherSort2{} but got ObjectSort{}." ) ( ErrorStack [ "\\exists 'ObjectVariable' (<test data>)" , "(<test data>, <test data>)" ] ) (simpleExistsPattern objectVariable' anotherObjectSort2) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 ] NeedsInternalDefinitions , successTestsForObjectPattern "Application pattern - symbol" ( applicationPatternWithChildren objectSymbolName [simpleExistsParsedPattern objectVariableName anotherObjectSort2] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectSymbolSentence ] NeedsInternalDefinitions , successTestsForObjectPattern "Application pattern - alias" ( applicationPatternWithChildren objectAliasNameAsSymbol [ variableParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectAliasSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - symbol not declared" (ExpectedErrorMessage "Head 'ObjectSymbol' not defined.") (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( applicationPatternWithChildren objectSymbolName [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - not enough arguments" (ExpectedErrorMessage "Expected 1 operands, but got 0.") (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) (applicationPatternWithChildren objectSymbolName []) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectSymbolSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern - too many arguments" (ExpectedErrorMessage "Expected 1 operands, but got 2.") (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( applicationPatternWithChildren objectSymbolName [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 , simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectSymbolSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Object pattern alias - too many arguments" (ExpectedErrorMessage "Expected 1 operands, but got 2.") (ErrorStack ["symbol or alias 'ObjectAlias' (<test data>)"]) ( applicationPatternWithChildren objectAliasNameAsSymbol [ variableParsedPattern objectVariableName anotherObjectSort2 , variableParsedPattern objectVariableName anotherObjectSort2 ] ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , objectAliasSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - too few sorts" ( ExpectedErrorMessage "Application uses less sorts than the declaration." ) (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( ApplicationF Application { applicationSymbolOrAlias = SymbolOrAlias { symbolOrAliasConstructor = testId oneSortSymbolRawName , symbolOrAliasParams = [] } , applicationChildren = [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , oneSortSymbolSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Application pattern - too many sorts" ( ExpectedErrorMessage "Application uses more sorts than the declaration." ) (ErrorStack ["symbol or alias 'ObjectSymbol' (<test data>)"]) ( ApplicationF Application { applicationSymbolOrAlias = SymbolOrAlias { symbolOrAliasConstructor = testId oneSortSymbolRawName , symbolOrAliasParams = [objectSort, objectSort] } , applicationChildren = [ simpleExistsParsedPattern objectVariableName anotherObjectSort2 ] } ) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence , anotherObjectSortSentence2 , oneSortSymbolSentence ] NeedsInternalDefinitions , successTestsForObjectPattern "Object pattern - unquantified variable" (VariableF $ Const $ inject objectVariable') (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [objectSortSentence, anotherSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Bottom pattern" (BottomF Bottom{bottomSort = objectSort}) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence ] NeedsInternalDefinitions , successTestsForObjectPattern "Top pattern" (TopF Top{topSort = objectSort}) (NamePrefix "dummy") (TestedPatternSort objectSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort anotherSort) [ objectSortSentence , anotherSortSentence ] NeedsInternalDefinitions , failureTestsForObjectPattern "Domain value - INT.Int" ( ExpectedErrorMessage "<string literal>:1:1:\n\ \ |\n\ \1 | abcd\n\ \ | ^\n\ \unexpected 'a'\n\ \expecting '+', '-', or integer\n" ) ( ErrorStack [ "\\dv (<test data>)" , "Verifying builtin sort 'INT.Int'" , "While parsing domain value" ] ) ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - INT.Int - Negative" ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "-256" } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - INT.Int - Positive (unsigned)" ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "1024" } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - INT.Int - Positive (signed)" ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ Internal.mkStringLiteral "+128" } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Domain value - BOOL.Bool" ( ExpectedErrorMessage "<string literal>:1:1:\n\ \ |\n\ \1 | untrue\n\ \ | ^^^^^\n\ \unexpected \"untru\"\n\ \expecting \"false\" or \"true\"\n" ) ( ErrorStack [ "\\dv (<test data>)" , "Verifying builtin sort 'BOOL.Bool'" , "While parsing domain value" ] ) ( DomainValueF DomainValue { domainValueSort = boolSort , domainValueChild = externalize $ } ) (NamePrefix "dummy") (TestedPatternSort boolSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort boolSort) [asSentence boolSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - BOOL.Bool - true" ( DomainValueF DomainValue { domainValueSort = boolSort , domainValueChild = externalize $ Internal.mkStringLiteral "true" } ) (NamePrefix "dummy") (TestedPatternSort boolSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort boolSort) [asSentence boolSortSentence] NeedsInternalDefinitions , successTestsForObjectPattern "Domain value - BOOL.Bool - false" ( DomainValueF DomainValue { domainValueSort = boolSort , domainValueChild = externalize $ Internal.mkStringLiteral "false" } ) (NamePrefix "dummy") (TestedPatternSort boolSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort boolSort) [asSentence boolSortSentence] NeedsInternalDefinitions , failureTestsForObjectPattern "Domain value - sort without DVs" ( ExpectedErrorMessage (Text.unpack sortNeedsDomainValueAttributeMessage) ) ( ErrorStack [ "\\dv (<test data>)" , "(<test data>)" ] ) ( DomainValueF DomainValue { domainValueSort = intSort , domainValueChild = externalize $ } ) (NamePrefix "dummy") (TestedPatternSort intSort) (SortVariablesThatMustBeDeclared []) (DeclaredSort intSort) [asSentence intSortSentenceWithoutDv] NeedsInternalDefinitions ] where objectSortName = SortName "ObjectSort" objectSort :: Sort objectSort = simpleSort objectSortName objectVariableName = "ObjectVariable" objectVariable' = variable objectVariableName objectSort objectSetVariable' = setVariable objectVariableName objectSort objectSortSentence = simpleSortSentence objectSortName anotherSortName = SortName "anotherSort" anotherSort :: Sort anotherSort = simpleSort anotherSortName anotherVariable = variable objectVariableName anotherSort anotherSetVariable = setVariable objectVariableName anotherSort anotherSortSentence = simpleSortSentence anotherSortName anotherObjectSortName2 = SortName "anotherSort2" anotherObjectSort2 :: Sort anotherObjectSort2 = simpleSort anotherObjectSortName2 anotherObjectSortSentence2 = simpleSortSentence anotherObjectSortName2 objectSymbolName = SymbolName "ObjectSymbol" objectSymbolSentence = objectSymbolSentenceWithArguments objectSymbolName objectSort [anotherObjectSort2] objectAliasName = AliasName "ObjectAlias" objectAliasNameAsSymbol = SymbolName "ObjectAlias" objectAliasSentence = objectAliasSentenceWithArguments objectAliasName objectSort [inject $ mkElementVariable (testId "x") anotherObjectSort2] objectSortVariable = sortVariable "ObjectSortVariable" objectSortVariableSort :: Sort objectSortVariableSort = sortVariableSort "ObjectSortVariable" objectVariableSortVariable = variable objectVariableName objectSortVariableSort objectSetVariableSortVariable = setVariable objectVariableName objectSortVariableSort oneSortSymbolRawName = "ObjectSymbol" oneSortSymbolSentence :: ParsedSentence oneSortSymbolSentence = asSentence SentenceSymbol { sentenceSymbolSymbol = Symbol { symbolConstructor = testId oneSortSymbolRawName , symbolParams = [objectSortVariable] } , sentenceSymbolSorts = [anotherObjectSort2] , sentenceSymbolResultSort = objectSort , sentenceSymbolAttributes = Attributes [] } intSortName = SortName "Int" intSort :: Sort intSort = simpleSort intSortName intSortSentence :: ParsedSentenceHook intSortSentence = SentenceHookedSort SentenceSort { sentenceSortName = testId name , sentenceSortParameters = [] , sentenceSortAttributes = Attributes [ Attribute.Hook.hookAttribute "INT.Int" , Attribute.HasDomainValues.hasDomainValuesAttribute ] } where SortName name = intSortName intSortSentenceWithoutDv = SentenceHookedSort SentenceSort { sentenceSortName = testId name , sentenceSortParameters = [] , sentenceSortAttributes = Attributes [Attribute.Hook.hookAttribute "INT.Int"] } where SortName name = intSortName boolSortName = SortName "Int" boolSort :: Sort boolSort = simpleSort boolSortName boolSortSentence :: ParsedSentenceHook boolSortSentence = SentenceHookedSort SentenceSort { sentenceSortName = testId name , sentenceSortParameters = [] , sentenceSortAttributes = Attributes [ Attribute.Hook.hookAttribute "BOOL.Bool" , Attribute.HasDomainValues.hasDomainValuesAttribute ] } where SortName name = boolSortName test_verifyBinder :: [TestTree] test_verifyBinder = [ testVerifyExists , testVerifyForall ] where context = PatternVerifier.verifiedModuleContext $ indexedModuleSyntax Builtin.verifiedModule testVerifyBinder name expect = testCase name $ do let original = externalize expect verifier = verifyStandalonePattern Nothing original actual = assertRight $ runPatternVerifier context verifier assertEqual "" expect actual on (assertEqual "") Internal.extractAttributes expect actual testVerifyExists = testVerifyBinder "verifyExists" expect where x = Internal.mkElementVariable "x" Builtin.intSort expect = Internal.mkExists x (Internal.mkElemVar x) testVerifyForall = testVerifyBinder "verifyForall" expect where x = Internal.mkElementVariable "x" Builtin.intSort expect = Internal.mkForall x (Internal.mkElemVar x) dummyVariableAndSentences :: NamePrefix -> (ElementVariable VariableName, [ParsedSentence]) dummyVariableAndSentences (NamePrefix namePrefix) = (dummyVariable, [simpleSortSentence dummySortName]) where dummySortName = SortName (namePrefix <> "_OtherSort") dummySort' = simpleSort dummySortName dummyVariable = variable (namePrefix <> "_OtherVariable") dummySort' successTestsForObjectPattern :: HasCallStack => String -> PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> TestTree successTestsForObjectPattern description testedPattern namePrefix testedSort sortVariables anotherSort sentences patternRestrict = successTestDataGroup description testData where (dummyVariable, dummySortSentences) = dummyVariableAndSentences namePrefix testData = genericPatternInAllContexts testedPattern namePrefix testedSort sortVariables sortVariables anotherSort (VariableOfDeclaredSort dummyVariable) (dummySortSentences ++ sentences) patternRestrict ++ objectPatternInAllContexts testedPattern namePrefix testedSort sortVariables anotherSort (dummySortSentences ++ sentences) patternRestrict failureTestsForObjectPattern :: HasCallStack => String -> ExpectedErrorMessage -> ErrorStack -> PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> TestTree failureTestsForObjectPattern description errorMessage errorStackSuffix testedPattern namePrefix@(NamePrefix rawNamePrefix) testedSort sortVariables anotherSort sentences patternRestrict = failureTestDataGroup description errorMessage errorStackSuffix testData where dummySortName = SortName (rawNamePrefix <> "_OtherSort") dummySort' = simpleSort dummySortName dummyVariable = variable (rawNamePrefix <> "_OtherVariable") dummySort' dummySortSentence = simpleSortSentence dummySortName testData = genericPatternInAllContexts testedPattern namePrefix testedSort sortVariables sortVariables anotherSort (VariableOfDeclaredSort dummyVariable) (dummySortSentence : sentences) patternRestrict ++ objectPatternInAllContexts testedPattern namePrefix testedSort sortVariables anotherSort (dummySortSentence : sentences) patternRestrict genericPatternInAllContexts :: PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> SortVariablesThatMustBeDeclared -> DeclaredSort -> VariableOfDeclaredSort -> [ParsedSentence] -> PatternRestrict -> [TestData] genericPatternInAllContexts testedPattern (NamePrefix namePrefix) (TestedPatternSort testedSort) sortVariables objectSortVariables (DeclaredSort anotherSort) dummyVariable sentences patternRestrict = patternsInAllContexts patternExpansion (NamePrefix namePrefix) sortVariables objectSortVariables (DeclaredSort anotherSort) sentences patternRestrict where patternExpansion = genericPatternInPatterns testedPattern anotherPattern (OperandSort testedSort) (Helpers.ResultSort anotherSort) dummyVariable (symbolFromSort testedSort) (aliasFromSort testedSort) patternRestrict anotherPattern = ExistsF Exists { existsSort = testedSort , existsVariable = anotherVariable , existsChild = externalize $ Internal.mkElemVar anotherVariable } anotherVariable = mkElementVariable (testId (namePrefix <> "_anotherVar")) testedSort rawSymbolName = namePrefix <> "_anotherSymbol" rawAliasName = namePrefix <> "_anotherAlias" symbolFromSort sort = SymbolOrAlias { symbolOrAliasConstructor = testId rawSymbolName , symbolOrAliasParams = [sort] } aliasFromSort sort = SymbolOrAlias { symbolOrAliasConstructor = testId rawAliasName , symbolOrAliasParams = [sort] } objectPatternInAllContexts :: PatternF VariableName ParsedPattern -> NamePrefix -> TestedPatternSort -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> [TestData] objectPatternInAllContexts testedPattern (NamePrefix namePrefix) (TestedPatternSort testedSort) sortVariables (DeclaredSort anotherSort) = patternsInAllContexts patternExpansion (NamePrefix namePrefix) sortVariables sortVariables (DeclaredSort anotherSort) where patternExpansion = objectPatternInPatterns testedPattern anotherPattern (OperandSort testedSort) anotherPattern = ExistsF Exists { existsSort = testedSort , existsVariable = anotherVariable , existsChild = externalize $ Internal.mkElemVar anotherVariable } anotherVariable = mkElementVariable (testId (namePrefix <> "_anotherVar")) testedSort patternsInAllContexts :: [TestPattern] -> NamePrefix -> SortVariablesThatMustBeDeclared -> SortVariablesThatMustBeDeclared -> DeclaredSort -> [ParsedSentence] -> PatternRestrict -> [TestData] patternsInAllContexts patterns (NamePrefix namePrefix) sortVariables objectSortVariables (DeclaredSort anotherSort) sentences patternRestrict = map (\context -> context (List.head patterns)) contextExpansion ++ map (List.head contextExpansion) patterns where contextExpansion = testsForUnifiedPatternInTopLevelContext (NamePrefix (namePrefix <> "_piac")) (DeclaredSort anotherSort) sortVariables objectSortVariables ( symbolSentence : aliasSentence : sentences ) patternRestrict rawSymbolName = namePrefix <> "_anotherSymbol" rawAliasName = namePrefix <> "_anotherAlias" rawSortVariableName = namePrefix <> "_sortVariable" symbolAliasSort = sortVariableSort rawSortVariableName symbolSentence = SentenceSymbolSentence SentenceSymbol { sentenceSymbolSymbol = Symbol { symbolConstructor = testId rawSymbolName , symbolParams = [SortVariable (testId rawSortVariableName)] } , sentenceSymbolSorts = [symbolAliasSort] , sentenceSymbolResultSort = anotherSort , sentenceSymbolAttributes = Attributes [] } aliasSentence :: ParsedSentence aliasSentence = let aliasConstructor = testId rawAliasName aliasParams = [SortVariable (testId rawSortVariableName)] in SentenceAliasSentence SentenceAlias { sentenceAliasAlias = Alias{aliasConstructor, aliasParams} , sentenceAliasSorts = [symbolAliasSort] , sentenceAliasResultSort = anotherSort , sentenceAliasLeftPattern = Application { applicationSymbolOrAlias = SymbolOrAlias { symbolOrAliasConstructor = aliasConstructor , symbolOrAliasParams = SortVariableSort <$> aliasParams } , applicationChildren = [inject $ mkSetVariable (testId "x") symbolAliasSort] } , sentenceAliasRightPattern = externalize $ Internal.mkTop anotherSort , sentenceAliasAttributes = Attributes [] } genericPatternInPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> Helpers.ResultSort -> VariableOfDeclaredSort -> SymbolOrAlias -> SymbolOrAlias -> PatternRestrict -> [TestPattern] genericPatternInPatterns testedPattern anotherPattern sort@(OperandSort testedSort) resultSort (VariableOfDeclaredSort dummyVariable) symbol alias patternRestrict = patternInQuantifiedPatterns testedPattern testedSort dummyVariable ++ patternInUnquantifiedGenericPatterns testedPattern anotherPattern sort resultSort ++ case patternRestrict of NeedsSortedParent -> [] _ -> [ TestPattern { testPatternPattern = testedPattern , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [] } ] ++ [ TestPattern { testPatternPattern = ApplicationF Application { applicationSymbolOrAlias = symbol , applicationChildren = [embedParsedPattern testedPattern] } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "symbol or alias '" ++ getIdForError (symbolOrAliasConstructor symbol) ++ "' (<test data>)" ] } , TestPattern { testPatternPattern = ApplicationF Application { applicationSymbolOrAlias = alias , applicationChildren = [embedParsedPattern testedPattern] } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "symbol or alias '" ++ getIdForError (symbolOrAliasConstructor alias) ++ "' (<test data>)" ] } ] objectPatternInPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> [TestPattern] objectPatternInPatterns = patternInUnquantifiedObjectPatterns patternInQuantifiedPatterns :: PatternF VariableName ParsedPattern -> Sort -> ElementVariable VariableName -> [TestPattern] patternInQuantifiedPatterns testedPattern testedSort quantifiedVariable = [ TestPattern { testPatternPattern = ExistsF Exists { existsSort = testedSort , existsVariable = quantifiedVariable , existsChild = testedKorePattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "\\exists '" ++ getIdForError ( base . unElementVariableName . variableName $ quantifiedVariable ) ++ "' (<test data>)" ] } , TestPattern { testPatternPattern = ForallF Forall { forallSort = testedSort , forallVariable = quantifiedVariable , forallChild = testedKorePattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack [ "\\forall '" ++ getIdForError ( base . unElementVariableName . variableName $ quantifiedVariable ) ++ "' (<test data>)" ] } ] where testedKorePattern = embedParsedPattern testedPattern patternInUnquantifiedGenericPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> Helpers.ResultSort -> [TestPattern] patternInUnquantifiedGenericPatterns testedPattern anotherPattern (OperandSort testedSort) (Helpers.ResultSort resultSort) = [ TestPattern { testPatternPattern = AndF And { andSort = testedSort , andFirst = testedUnifiedPattern , andSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\and (<test data>)"] } , TestPattern { testPatternPattern = AndF And { andSort = testedSort , andFirst = anotherUnifiedPattern , andSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\and (<test data>)"] } , TestPattern { testPatternPattern = CeilF Ceil { ceilOperandSort = testedSort , ceilResultSort = resultSort , ceilChild = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\ceil (<test data>)"] } , TestPattern { testPatternPattern = EqualsF Equals { equalsOperandSort = testedSort , equalsResultSort = resultSort , equalsFirst = testedUnifiedPattern , equalsSecond = anotherUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\equals (<test data>)"] } , TestPattern { testPatternPattern = EqualsF Equals { equalsOperandSort = testedSort , equalsResultSort = resultSort , equalsFirst = anotherUnifiedPattern , equalsSecond = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\equals (<test data>)"] } , TestPattern { testPatternPattern = FloorF Floor { floorOperandSort = testedSort , floorResultSort = resultSort , floorChild = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\floor (<test data>)"] } , TestPattern { testPatternPattern = IffF Iff { iffSort = testedSort , iffFirst = testedUnifiedPattern , iffSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\iff (<test data>)"] } , TestPattern { testPatternPattern = IffF Iff { iffSort = testedSort , iffFirst = anotherUnifiedPattern , iffSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\iff (<test data>)"] } , TestPattern { testPatternPattern = ImpliesF Implies { impliesSort = testedSort , impliesFirst = testedUnifiedPattern , impliesSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\implies (<test data>)"] } , TestPattern { testPatternPattern = ImpliesF Implies { impliesSort = testedSort , impliesFirst = anotherUnifiedPattern , impliesSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\implies (<test data>)"] } , TestPattern { testPatternPattern = InF In { inOperandSort = testedSort , inResultSort = resultSort , inContainedChild = testedUnifiedPattern , inContainingChild = anotherUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\in (<test data>)"] } , TestPattern { testPatternPattern = InF In { inOperandSort = testedSort , inResultSort = resultSort , inContainedChild = anotherUnifiedPattern , inContainingChild = testedUnifiedPattern } , testPatternSort = resultSort , testPatternErrorStack = ErrorStack ["\\in (<test data>)"] } , TestPattern { testPatternPattern = NotF Not { notSort = testedSort , notChild = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\not (<test data>)"] } , TestPattern { testPatternPattern = OrF Or { orSort = testedSort , orFirst = testedUnifiedPattern , orSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\or (<test data>)"] } , TestPattern { testPatternPattern = OrF Or { orSort = testedSort , orFirst = anotherUnifiedPattern , orSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\or (<test data>)"] } ] where anotherUnifiedPattern = embedParsedPattern anotherPattern testedUnifiedPattern = embedParsedPattern testedPattern patternInUnquantifiedObjectPatterns :: PatternF VariableName ParsedPattern -> PatternF VariableName ParsedPattern -> OperandSort -> [TestPattern] patternInUnquantifiedObjectPatterns testedPattern anotherPattern (OperandSort testedSort) = [ TestPattern { testPatternPattern = NextF Next { nextSort = testedSort , nextChild = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\next (<test data>)"] } , TestPattern { testPatternPattern = RewritesF Rewrites { rewritesSort = testedSort , rewritesFirst = testedUnifiedPattern , rewritesSecond = anotherUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\rewrites (<test data>)"] } , TestPattern { testPatternPattern = RewritesF Rewrites { rewritesSort = testedSort , rewritesFirst = anotherUnifiedPattern , rewritesSecond = testedUnifiedPattern } , testPatternSort = testedSort , testPatternErrorStack = ErrorStack ["\\rewrites (<test data>)"] } ] where anotherUnifiedPattern = embedParsedPattern anotherPattern testedUnifiedPattern = embedParsedPattern testedPattern testsForUnifiedPatternInTopLevelContext :: NamePrefix -> DeclaredSort -> SortVariablesThatMustBeDeclared -> SortVariablesThatMustBeDeclared -> [ParsedSentence] -> PatternRestrict -> [TestPattern -> TestData] testsForUnifiedPatternInTopLevelContext namePrefix additionalSort sortVariables _ = testsForUnifiedPatternInTopLevelGenericContext namePrefix additionalSort sortVariables testsForUnifiedPatternInTopLevelGenericContext :: NamePrefix -> DeclaredSort -> SortVariablesThatMustBeDeclared -> [ParsedSentence] -> PatternRestrict -> [TestPattern -> TestData] testsForUnifiedPatternInTopLevelGenericContext (NamePrefix _) (DeclaredSort _) (SortVariablesThatMustBeDeclared sortVariables) additionalSentences patternRestrict = let axiomPattern testPattern = TestData { testDataDescription = "Pattern in axiom" , testDataError = Error ( "module 'MODULE'" : "axiom declaration" : testPatternErrorStackStrings testPattern ) defaultErrorMessage , testDataDefinition = simpleDefinitionFromSentences (ModuleName "MODULE") ( axiomSentenceWithParamsAndAttrs (testPatternUnverifiedPattern testPattern) sortVariables [simplificationAttribute Nothing] : additionalSentences ) } in case patternRestrict of NeedsInternalDefinitions -> [axiomPattern] NeedsSortedParent -> [axiomPattern] defaultErrorMessage :: String defaultErrorMessage = "Replace this with a real error message."
4f9b009264d6d3851095a62d38e746329e9c87fd3a721b8eb643350015ea2888
Timothy-G-Griffin/cc_cl_cam_ac_uk
dfc.ml
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge ( ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge Timothy G. Griffin () *****************************************) The " defunctionalisation " ( dfc ) transformation replaces functions with elements in a data structure . It also defines an " apply " function that simulates function application on this representation . Suppose we have a ( fun x - > e ) in our code . Let y1 : t1 , .... yn : tn be the free variables of e , not inluding x. This " lambda " is replaced by C(y1 , y2 , ... , yn ) where C is a constructor of a new datatype type funs = ... | C of t1 * t2 * ... tn ... We have an associated clause in our new apply function let apply funs = functon ... | ( C(y1 , y2 , ... , yn ) , x ) - > e ' ... where e ' is the dfc(e ) . Finally , we replace every f(e1 , e2 , ... , en ) where this lambda could be applied is replaced by apply(f , e1 ' , e2 ' , ... , en ' ) where each ei ' = dfc(ei ) . replaces functions with elements in a data structure. It also defines an "apply" function that simulates function application on this representation. Suppose we have a (fun x -> e) in our code. Let y1 :t1, .... yn : tn be the free variables of e, not inluding x. This "lambda" is replaced by C(y1, y2, ..., yn) where C is a constructor of a new datatype type funs = ... | C of t1 * t2 * ... tn ... We have an associated clause in our new apply function let apply funs = functon ... | (C(y1, y2, ..., yn), x) -> e' ... where e' is the dfc(e). Finally, we replace every f(e1, e2, ..., en) where this lambda could be applied is replaced by apply(f, e1', e2', ..., en') where each ei' = dfc(ei). *) First a very simple example (* sum : 'a * 'a * ('a -> int) -> int *) let sum (a, b, f) = (f a) + (f b) (* test : int * int -> int *) let test (x, y) = (sum (x, y, fun z -> z * y)) * (sum (x, y, fun w -> (w * x) + y)) (* after the dfc transformation : *) type funs = FUN1 of int | FUN2 of int * int (* apply_funs : funs * int -> int *) let apply_funs = function | (FUN1 y, z) -> z * y | (FUN2(x, y), w) -> (w * x) + y (* sum_dfc : int * int * funs -> int *) let sum_dfc (a, b, f) = apply_funs(f, a) + apply_funs(f, b) (* test_dfc : int * int -> int *) let test_dfc (x, y) = (sum_dfc (x, y, FUN1 y)) * (sum_dfc (x, y, FUN2(x,y))) (* Observation. We have specialized sum_dfc to a version that only calls the functions used by test, represented now as elements of the datastructure funs. Thus the type of sum_dfc is not as general as that of sum. *)
null
https://raw.githubusercontent.com/Timothy-G-Griffin/cc_cl_cam_ac_uk/aabaf64c997301ea69060a1b69e915b9d1031573/basic_transformations/dfc.ml
ocaml
sum : 'a * 'a * ('a -> int) -> int test : int * int -> int after the dfc transformation : apply_funs : funs * int -> int sum_dfc : int * int * funs -> int test_dfc : int * int -> int Observation. We have specialized sum_dfc to a version that only calls the functions used by test, represented now as elements of the datastructure funs. Thus the type of sum_dfc is not as general as that of sum.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge ( ) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Compiler Construction 2016 Computer Laboratory University of Cambridge Timothy G. Griffin () *****************************************) The " defunctionalisation " ( dfc ) transformation replaces functions with elements in a data structure . It also defines an " apply " function that simulates function application on this representation . Suppose we have a ( fun x - > e ) in our code . Let y1 : t1 , .... yn : tn be the free variables of e , not inluding x. This " lambda " is replaced by C(y1 , y2 , ... , yn ) where C is a constructor of a new datatype type funs = ... | C of t1 * t2 * ... tn ... We have an associated clause in our new apply function let apply funs = functon ... | ( C(y1 , y2 , ... , yn ) , x ) - > e ' ... where e ' is the dfc(e ) . Finally , we replace every f(e1 , e2 , ... , en ) where this lambda could be applied is replaced by apply(f , e1 ' , e2 ' , ... , en ' ) where each ei ' = dfc(ei ) . replaces functions with elements in a data structure. It also defines an "apply" function that simulates function application on this representation. Suppose we have a (fun x -> e) in our code. Let y1 :t1, .... yn : tn be the free variables of e, not inluding x. This "lambda" is replaced by C(y1, y2, ..., yn) where C is a constructor of a new datatype type funs = ... | C of t1 * t2 * ... tn ... We have an associated clause in our new apply function let apply funs = functon ... | (C(y1, y2, ..., yn), x) -> e' ... where e' is the dfc(e). Finally, we replace every f(e1, e2, ..., en) where this lambda could be applied is replaced by apply(f, e1', e2', ..., en') where each ei' = dfc(ei). *) First a very simple example let sum (a, b, f) = (f a) + (f b) let test (x, y) = (sum (x, y, fun z -> z * y)) * (sum (x, y, fun w -> (w * x) + y)) type funs = FUN1 of int | FUN2 of int * int let apply_funs = function | (FUN1 y, z) -> z * y | (FUN2(x, y), w) -> (w * x) + y let sum_dfc (a, b, f) = apply_funs(f, a) + apply_funs(f, b) let test_dfc (x, y) = (sum_dfc (x, y, FUN1 y)) * (sum_dfc (x, y, FUN2(x,y)))
b688eb872cbbce8f0c827ecc5fae6523f4dbc780e077aa984a2374c539223517
mcorbin/meuse
download_test.clj
(ns meuse.api.crate.download-test (:require [meuse.api.crate.download :refer :all] [meuse.api.crate.http :refer [crates-api!]] [meuse.crate-file :refer [crate-file-store]] [meuse.helpers.fixtures :refer :all] [meuse.helpers.request :refer [add-auth]] [meuse.store.protocol :as store] [clojure.test :refer :all]) (:import clojure.lang.ExceptionInfo)) (use-fixtures :once system-fixture) (use-fixtures :each tmp-fixture) (deftest crate-api-download-test (testing "success" (store/write-file crate-file-store {:name "crate1" :vers "1.1.0"} (.getBytes "file content"))) (is (= (slurp (:body (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "crate1" :crate-version "1.1.0"}})))) "file content")) (testing "error" (is (thrown-with-msg? ExceptionInfo #"the file test/resources/tmp/bar/1.0.0/download does not exist" (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "bar" :crate-version "1.0.0"}}))))) (testing "invalid parameters" (is (thrown-with-msg? ExceptionInfo #"Wrong input parameters:\n - field crate-name: the value should be a non empty string\n" (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "" :crate-version "1.0.0"}})))) (is (thrown-with-msg? ExceptionInfo #"Wrong input parameters:\n - field crate-version: the value should be a valid semver string\n" (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "aaaa" :crate-version "1.1"}}))))))
null
https://raw.githubusercontent.com/mcorbin/meuse/d2b74543fce37c8cde770ae6f6097cabb509a804/test/meuse/api/crate/download_test.clj
clojure
(ns meuse.api.crate.download-test (:require [meuse.api.crate.download :refer :all] [meuse.api.crate.http :refer [crates-api!]] [meuse.crate-file :refer [crate-file-store]] [meuse.helpers.fixtures :refer :all] [meuse.helpers.request :refer [add-auth]] [meuse.store.protocol :as store] [clojure.test :refer :all]) (:import clojure.lang.ExceptionInfo)) (use-fixtures :once system-fixture) (use-fixtures :each tmp-fixture) (deftest crate-api-download-test (testing "success" (store/write-file crate-file-store {:name "crate1" :vers "1.1.0"} (.getBytes "file content"))) (is (= (slurp (:body (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "crate1" :crate-version "1.1.0"}})))) "file content")) (testing "error" (is (thrown-with-msg? ExceptionInfo #"the file test/resources/tmp/bar/1.0.0/download does not exist" (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "bar" :crate-version "1.0.0"}}))))) (testing "invalid parameters" (is (thrown-with-msg? ExceptionInfo #"Wrong input parameters:\n - field crate-name: the value should be a non empty string\n" (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "" :crate-version "1.0.0"}})))) (is (thrown-with-msg? ExceptionInfo #"Wrong input parameters:\n - field crate-version: the value should be a valid semver string\n" (crates-api! (add-auth {:action :download :config {:crate {:path tmp-dir}} :route-params {:crate-name "aaaa" :crate-version "1.1"}}))))))
7458aba182c0fb6a29ee83d64e6284148cef7c8786ad26a70dc5bb0234a49d2f
K1D77A/lunamech-matrix-api
api-helpers.lisp
(in-package #:lunamech-matrix-api) (defparameter *request-type-hash* (make-hash-table)) (defparameter +content-type+ "application/json; charset=utf-8");;I will back to const (defun url-e (url) (do-urlencode:urlencode url)) (defun gen-headers (connection &optional (content-type +content-type+)) "Generates a header list for use with dex" `(("Content-Type" . ,content-type) ("Authorization" . ,(format nil "Bearer ~A" (token (auth connection)))))) (defun gen-url (connection &optional (prefix nil)) "Generates a base uri for CONNECTION. if MEDIA is non nil then uses /_matrix/media/r0/ in place of (api CONNECTION). Returns a list whose first element is the url." (list (concatenate 'string (url connection) (key->url connection prefix)))) (defgeneric key->url (connection key) (:documentation "converts a keyword like :MSC2946 into a URL. If key is a string evaluates to that string, if it is :DEFAULT evaluates to (api connection), if it is anything else evaluates to (api connection)")) (defmethod key->url (connection (key (eql :MSC2946))) "/_matrix/client/unstable/org.matrix.msc2946/") (defmethod key->url (connection (key string)) key) (defmethod key->url (connection (key (eql :DEFAULT))) (api connection)) (defmethod key->url (connection key) (api connection)) (defmethod key->url (connection (key (eql :MEDIA))) "/_matrix/media/r0/") (defun gen-admin-url (connection) (list (url connection))) (defun plist-to-get-params (plist) "Loops over PLIST and creates a single string from the keys and vals. Keys are displayed with the following format string ~A= and vals ~A&. Vals are also url encoded" (apply #'concatenate 'string (loop :for str :in plist :for n :from 0 :to (length plist) :collect (if (evenp n) (format nil "~A=" str) (format nil "~A&" (url-e (if (numberp str) (format nil "~D" str) str))))))) ;;;post requests (psetf dex:*default-read-timeout* 3 dex:*default-connect-timeout* 3) (defmacro with-captured-dex-error (&body body) "Catches any conditions signalled by dex and converts the response into a special condition defined in src/classes.lisp and signals." (alexandria:with-gensyms (condition) `(labels ((try-again-restart (fun) (restart-case (funcall fun) (try-again () :report "Try again?" (sleep 3) (try-again-restart fun))))) (let ((fun (lambda () (handler-case (locally (bt:with-timeout (30) ,@body)) (bt:timeout (,condition) (error 'api-timeout :api-timeout-message "Connection broken" :api-timeout-condition ,condition)) ((or usocket:socket-condition usocket:ns-condition usocket:socket-error usocket:timeout-error usocket:unknown-error usocket:ns-error) (,condition) (error 'api-no-connection :api-timeout-message "No network" :api-timeout-condition ,condition)) (condition (,condition);;total catchall oh well (handler-case (signal-condition-from-response (jojo:parse (dexador.error:response-body ,condition))) (jojo:<jonathan-error> (,condition) (error 'api-no-connection ;;if the server is down then this will end up ;;returning html not json :api-timeout-message "Server probably down" :api-timeout-condition ,condition)))))))) (try-again-restart fun))))) ;;;post requests. theres a few as there are a few ways to post content. (defun post-no-auth (connection url &optional (plist nil)) (declare (ignorable connection)) (with-captured-dex-error (let ((headers `(("Content-Type" . ,+content-type+)))) (if plist (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json plist :from :plist) :use-connection-pool nil) (dex:post (apply #'str:concat url) :headers headers :use-connection-pool nil))))) (defun post-content (connection url content-type content) (with-captured-dex-error (dex:post (apply #'str:concat url) :headers (gen-headers connection content-type) :content content :use-connection-pool nil))) (defclass empty-object () ()) (defmethod jojo:%to-json ((o empty-object)) (jojo:with-object nil)) (defun post-request (connection url &optional (plist nil)) (with-captured-dex-error (let ((headers (gen-headers connection))) (if plist (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json plist :from :plist) :use-connection-pool nil) (dex:post (apply #'str:concat url) :headers headers :use-connection-pool nil))))) (defun post-request-object (connection url object) (with-captured-dex-error (let ((headers (gen-headers connection))) (dex:post (apply #'str:concat url) :headers headers :content object :use-connection-pool nil))));;do not auto convert to json (defun admin-post-request (connection url &optional (plist nil)) (with-captured-dex-error (let ((headers (gen-headers connection))) (if plist (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json plist :from :plist) :use-connection-pool nil) (dex:post (apply #'str:concat url) :headers headers :use-connection-pool nil))))) (defun admin-post-object (connection url object) (with-captured-dex-error (let ((headers (gen-headers connection))) (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json object) :use-connection-pool nil)))) ;;;put requests (defun put-request (connection url plist) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content (jojo:to-json plist :from :plist) :use-connection-pool nil))) (defun put-request-object (connection url object) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content (jojo:to-json object) :use-connection-pool nil))) (defun put-request-from-json (connection url json-string) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content json-string :use-connection-pool nil))) (defun admin-put-request (connection url plist) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content (jojo:to-json plist :from :plist) :use-connection-pool nil))) ;;;get requests (defun get-request (connection url &optional (get-params nil)) (with-captured-dex-error (dex:get (if get-params (apply #'str:concat (append url (list "?") (list (plist-to-get-params get-params)))) (apply #'str:concat url)) :headers (gen-headers connection) :use-connection-pool nil))) (defun admin-get-request (connection url) (let ((url (apply #'str:concat url))) (with-captured-dex-error (dex:get url :headers (gen-headers connection) :use-connection-pool nil)))) ;;;delete requests (defun admin-delete-request (connection url) (let ((url (apply #'str:concat url))) (with-captured-dex-error (dex:delete url :headers (gen-headers connection) :use-connection-pool nil)))) ;;;request macro system (defun new-request-type (key fun) (setf (gethash key *request-type-hash*) fun)) (defmacro new-r-t ((key) &body body) `(new-request-type ,key (lambda (connection url data prefix) (declare (ignorable data)) ,@body))) (new-r-t (:post-no-auth) (jojo:parse (post-no-auth connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:post) (jojo:parse (post-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:post-object) (jojo:parse (post-request-object connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:post-content) (jojo:parse (post-content connection (nconc (gen-url connection prefix) url) (getf data :content-type) (getf data :content)))) (new-r-t (:get) (jojo:parse (get-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:content-get) (get-request connection (nconc (gen-url connection prefix) url) data)) (new-r-t (:put) (jojo:parse (put-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:put-event) (jojo:parse (put-request-object connection (nconc (gen-url connection prefix) url) (getf data :object)))) (new-r-t (:put-content) (jojo:parse (put-request-object connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:put-no-json) (jojo:parse (put-request-from-json connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:admin-post) (declare (ignore prefix)) (jojo:parse (admin-post-request connection (nconc (gen-admin-url connection) url) data))) (new-r-t (:admin-post-object) (declare (ignore prefix)) (jojo:parse (admin-post-request connection (nconc (gen-admin-url connection) url) data))) (new-r-t (:admin-get) (declare (ignore prefix)) (jojo:parse (admin-get-request connection (nconc (gen-admin-url connection) url)))) (new-r-t (:admin-put) (jojo:parse (admin-put-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:admin-delete) (declare (ignore prefix)) (jojo:parse (admin-delete-request connection (nconc (gen-admin-url connection) url)))) ;;;main macro for sending requests (defmacro auth-req ((method connection url data response-var &optional (prefix :DEFAULT)) &body body) (check-type url list) (alexandria:with-gensyms (req) `(let ((,req (funcall (gethash ,method *request-type-hash*) ,connection (list ,@url) ,data ,prefix))) (let ((,response-var ,req)) ,@body))))
null
https://raw.githubusercontent.com/K1D77A/lunamech-matrix-api/cead2f3c7c8f93291067542150fde0c1f2399f20/api/api-helpers.lisp
lisp
I will back to const post requests total catchall oh well if the server is down then this will end up returning html not json post requests. theres a few as there are a few ways to post content. do not auto convert to json put requests get requests delete requests request macro system main macro for sending requests
(in-package #:lunamech-matrix-api) (defparameter *request-type-hash* (make-hash-table)) (defun url-e (url) (do-urlencode:urlencode url)) (defun gen-headers (connection &optional (content-type +content-type+)) "Generates a header list for use with dex" `(("Content-Type" . ,content-type) ("Authorization" . ,(format nil "Bearer ~A" (token (auth connection)))))) (defun gen-url (connection &optional (prefix nil)) "Generates a base uri for CONNECTION. if MEDIA is non nil then uses /_matrix/media/r0/ in place of (api CONNECTION). Returns a list whose first element is the url." (list (concatenate 'string (url connection) (key->url connection prefix)))) (defgeneric key->url (connection key) (:documentation "converts a keyword like :MSC2946 into a URL. If key is a string evaluates to that string, if it is :DEFAULT evaluates to (api connection), if it is anything else evaluates to (api connection)")) (defmethod key->url (connection (key (eql :MSC2946))) "/_matrix/client/unstable/org.matrix.msc2946/") (defmethod key->url (connection (key string)) key) (defmethod key->url (connection (key (eql :DEFAULT))) (api connection)) (defmethod key->url (connection key) (api connection)) (defmethod key->url (connection (key (eql :MEDIA))) "/_matrix/media/r0/") (defun gen-admin-url (connection) (list (url connection))) (defun plist-to-get-params (plist) "Loops over PLIST and creates a single string from the keys and vals. Keys are displayed with the following format string ~A= and vals ~A&. Vals are also url encoded" (apply #'concatenate 'string (loop :for str :in plist :for n :from 0 :to (length plist) :collect (if (evenp n) (format nil "~A=" str) (format nil "~A&" (url-e (if (numberp str) (format nil "~D" str) str))))))) (psetf dex:*default-read-timeout* 3 dex:*default-connect-timeout* 3) (defmacro with-captured-dex-error (&body body) "Catches any conditions signalled by dex and converts the response into a special condition defined in src/classes.lisp and signals." (alexandria:with-gensyms (condition) `(labels ((try-again-restart (fun) (restart-case (funcall fun) (try-again () :report "Try again?" (sleep 3) (try-again-restart fun))))) (let ((fun (lambda () (handler-case (locally (bt:with-timeout (30) ,@body)) (bt:timeout (,condition) (error 'api-timeout :api-timeout-message "Connection broken" :api-timeout-condition ,condition)) ((or usocket:socket-condition usocket:ns-condition usocket:socket-error usocket:timeout-error usocket:unknown-error usocket:ns-error) (,condition) (error 'api-no-connection :api-timeout-message "No network" :api-timeout-condition ,condition)) (handler-case (signal-condition-from-response (jojo:parse (dexador.error:response-body ,condition))) (jojo:<jonathan-error> (,condition) (error 'api-no-connection :api-timeout-message "Server probably down" :api-timeout-condition ,condition)))))))) (try-again-restart fun))))) (defun post-no-auth (connection url &optional (plist nil)) (declare (ignorable connection)) (with-captured-dex-error (let ((headers `(("Content-Type" . ,+content-type+)))) (if plist (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json plist :from :plist) :use-connection-pool nil) (dex:post (apply #'str:concat url) :headers headers :use-connection-pool nil))))) (defun post-content (connection url content-type content) (with-captured-dex-error (dex:post (apply #'str:concat url) :headers (gen-headers connection content-type) :content content :use-connection-pool nil))) (defclass empty-object () ()) (defmethod jojo:%to-json ((o empty-object)) (jojo:with-object nil)) (defun post-request (connection url &optional (plist nil)) (with-captured-dex-error (let ((headers (gen-headers connection))) (if plist (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json plist :from :plist) :use-connection-pool nil) (dex:post (apply #'str:concat url) :headers headers :use-connection-pool nil))))) (defun post-request-object (connection url object) (with-captured-dex-error (let ((headers (gen-headers connection))) (dex:post (apply #'str:concat url) :headers headers :content object (defun admin-post-request (connection url &optional (plist nil)) (with-captured-dex-error (let ((headers (gen-headers connection))) (if plist (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json plist :from :plist) :use-connection-pool nil) (dex:post (apply #'str:concat url) :headers headers :use-connection-pool nil))))) (defun admin-post-object (connection url object) (with-captured-dex-error (let ((headers (gen-headers connection))) (dex:post (apply #'str:concat url) :headers headers :content (jojo:to-json object) :use-connection-pool nil)))) (defun put-request (connection url plist) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content (jojo:to-json plist :from :plist) :use-connection-pool nil))) (defun put-request-object (connection url object) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content (jojo:to-json object) :use-connection-pool nil))) (defun put-request-from-json (connection url json-string) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content json-string :use-connection-pool nil))) (defun admin-put-request (connection url plist) (with-captured-dex-error (dex:put (apply #'str:concat url) :headers (gen-headers connection) :content (jojo:to-json plist :from :plist) :use-connection-pool nil))) (defun get-request (connection url &optional (get-params nil)) (with-captured-dex-error (dex:get (if get-params (apply #'str:concat (append url (list "?") (list (plist-to-get-params get-params)))) (apply #'str:concat url)) :headers (gen-headers connection) :use-connection-pool nil))) (defun admin-get-request (connection url) (let ((url (apply #'str:concat url))) (with-captured-dex-error (dex:get url :headers (gen-headers connection) :use-connection-pool nil)))) (defun admin-delete-request (connection url) (let ((url (apply #'str:concat url))) (with-captured-dex-error (dex:delete url :headers (gen-headers connection) :use-connection-pool nil)))) (defun new-request-type (key fun) (setf (gethash key *request-type-hash*) fun)) (defmacro new-r-t ((key) &body body) `(new-request-type ,key (lambda (connection url data prefix) (declare (ignorable data)) ,@body))) (new-r-t (:post-no-auth) (jojo:parse (post-no-auth connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:post) (jojo:parse (post-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:post-object) (jojo:parse (post-request-object connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:post-content) (jojo:parse (post-content connection (nconc (gen-url connection prefix) url) (getf data :content-type) (getf data :content)))) (new-r-t (:get) (jojo:parse (get-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:content-get) (get-request connection (nconc (gen-url connection prefix) url) data)) (new-r-t (:put) (jojo:parse (put-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:put-event) (jojo:parse (put-request-object connection (nconc (gen-url connection prefix) url) (getf data :object)))) (new-r-t (:put-content) (jojo:parse (put-request-object connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:put-no-json) (jojo:parse (put-request-from-json connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:admin-post) (declare (ignore prefix)) (jojo:parse (admin-post-request connection (nconc (gen-admin-url connection) url) data))) (new-r-t (:admin-post-object) (declare (ignore prefix)) (jojo:parse (admin-post-request connection (nconc (gen-admin-url connection) url) data))) (new-r-t (:admin-get) (declare (ignore prefix)) (jojo:parse (admin-get-request connection (nconc (gen-admin-url connection) url)))) (new-r-t (:admin-put) (jojo:parse (admin-put-request connection (nconc (gen-url connection prefix) url) data))) (new-r-t (:admin-delete) (declare (ignore prefix)) (jojo:parse (admin-delete-request connection (nconc (gen-admin-url connection) url)))) (defmacro auth-req ((method connection url data response-var &optional (prefix :DEFAULT)) &body body) (check-type url list) (alexandria:with-gensyms (req) `(let ((,req (funcall (gethash ,method *request-type-hash*) ,connection (list ,@url) ,data ,prefix))) (let ((,response-var ,req)) ,@body))))
4cfb5b8796e8cb33fef577815607f636d3bc1d1fcd42bdd42c02e4c2665662a6
GrammaticalFramework/gf-core
Idents.hs
module Idents where import PGF cidASimul = mkCId "ASimul" cidAAnter = mkCId "AAnter" cidPositAdvAdj = mkCId "PositAdvAdj" cidPositAdVAdj = mkCId "PositAdVAdj" cidUseCl = mkCId "UseCl" cidUseQCl = mkCId "UseQCl" cidPredVP = mkCId "PredVP" cidAdjCN = mkCId "AdjCN" cidUseN = mkCId "UseN" cidDetQuant = mkCId "DetQuant" cidNumSg = mkCId "NumSg" cidNumPl = mkCId "NumPl" cidDetCN = mkCId "DetCN" cidIndefArt = mkCId "IndefArt" cidDefArt = mkCId "DefArt" cidUsePN = mkCId "UsePN" cidUseQuantPN = mkCId "UseQuantPN" cidSymbPN = mkCId "SymbPN" cidMkSymb = mkCId "MkSymb" cidUsePron = mkCId "UsePron" cidConjNP = mkCId "ConjNP" cidBaseNP = mkCId "BaseNP" cidConsNP = mkCId "ConsNP" cidConjCN = mkCId "ConjCN" cidBaseCN = mkCId "BaseCN" cidConsCN = mkCId "ConsCN" cidMassNP = mkCId "MassNP" cidAdvNP = mkCId "AdvNP" cidTPres = mkCId "TPres" cidTPast = mkCId "TPast" cidTFut = mkCId "TFut" cidTFutKommer = mkCId "TFutKommer" cidTCond = mkCId "TCond" cidTTAnt = mkCId "TTAnt" cidPPos = mkCId "PPos" cidPNeg = mkCId "PNeg" cidComplSlash = mkCId "ComplSlash" cidSlashV2a = mkCId "SlashV2a" cidSlashV2A = mkCId "SlashV2A" cidComplVS = mkCId "ComplVS" cidUseV = mkCId "UseV" cidAdVVP = mkCId "AdVVP" cidAdvVP = mkCId "AdvVP" cidAdvVPSlash = mkCId "AdvVPSlash" cidPrepNP = mkCId "PrepNP" cidto_Prep = mkCId "to_Prep" cidsuch_as_Prep= mkCId "such_as_Prep" cidPastPartAP = mkCId "PastPartAP" cidPassV2 = mkCId "PassV2" cidAdvS = mkCId "AdvS" cidPositA = mkCId "PositA" cidIDig = mkCId "IDig" cidIIDig = mkCId "IIDig" cidNumCard = mkCId "NumCard" cidNumDigits = mkCId "NumDigits" cidNumNumeral = mkCId "NumNumeral" cidnum = mkCId "num" cidpot2as3 = mkCId "pot2as3" cidpot1as2 = mkCId "pot1as2" cidpot0as1 = mkCId "pot0as1" cidpot01 = mkCId "pot01" cidpot0 = mkCId "pot0" cidn7 = mkCId "n7" cidPossPron = mkCId "PossPron" cidCompAP = mkCId "CompAP" cidCompNP = mkCId "CompNP" cidCompAdv = mkCId "CompAdv" cidUseComp = mkCId "UseComp" cidCompoundCN = mkCId "CompoundCN" cidDashCN = mkCId "DashCN" cidProgrVP = mkCId "ProgrVP" cidGerundN = mkCId "GerundN" cidGenNP = mkCId "GenNP" cidPredetNP = mkCId "PredetNP" cidDetNP = mkCId "DetNP" cidAdAP = mkCId "AdAP" cidPositAdAAdj = mkCId "PositAdAAdj" cidBaseAP = mkCId "BaseAP" cidConjAP = mkCId "ConjAP" cidAndConj = mkCId "and_Conj" cidOrConj = mkCId "or_Conj" cidConsAP = mkCId "ConsAP" cidQuestVP = mkCId "QuestVP" cidComplVV = mkCId "ComplVV" cidComplVA = mkCId "ComplVA" cidUseCopula = mkCId "UseCopula" cidPhrUtt = mkCId "PhrUtt" cidNoPConj = mkCId "NoPConj" cidNoVoc = mkCId "NoVoc" cidUttS = mkCId "UttS" cidUttQS = mkCId "UttQS" cidUseComparA = mkCId "UseComparA" cidOrdSuperl = mkCId "OrdSuperl" cidUttImpPol = mkCId "UttImpPol" cidImpVP = mkCId "ImpVP" cidPConjConj = mkCId "PConjConj" cidUttNP = mkCId "UttNP" cidGenericCl = mkCId "GenericCl" cidAdAdv = mkCId "AdAdv" cidConsAdv = mkCId "ConsAdv" cidBaseAdv = mkCId "BaseAdv" cidConjAdv = mkCId "ConjAdv" cidConsVPS = mkCId "ConsVPS" cidBaseVPS = mkCId "BaseVPS" cidConjVPS = mkCId "ConjVPS" cidConsS = mkCId "ConsS" cidBaseS = mkCId "BaseS" cidConjS = mkCId "ConjS" cidSubjS = mkCId "SubjS" cidUttAdv = mkCId "UttAdv" cidApposCN = mkCId "ApposCN" cidUseRCl = mkCId "UseRCl" cidImpersCl = mkCId "ImpersCl" cidReflVP = mkCId "ReflVP" cidExistNP = mkCId "ExistNP" cidUseA2 = mkCId "UseA2" cidComplN2 = mkCId "ComplN2" cidAdvIAdv = mkCId "AdvIAdv" cidQuestIAdv = mkCId "QuestIAdv" cidQuestIComp = mkCId "QuestIComp" cidQuestSlash = mkCId "QuestSlash" cidCompIAdv = mkCId "CompIAdv" cidCompIP = mkCId "CompIP" cidIdetCN = mkCId "IdetCN" cidIdetQuant = mkCId "IdetQuant" cidPrepIP = mkCId "PrepIP" cidFocObj = mkCId "FocObj" cidSlashVP = mkCId "SlashVP" cidAdvSlash = mkCId "AdvSlash" cidSSubjS = mkCId "SSubjS" cidRelVP = mkCId "RelVP" cidIdRP = mkCId "IdRP" cidRelSlash = mkCId "RelSlash" cidTopAdv = mkCId "TopAdv" cidTopAP = mkCId "TopAP" cidTopObj = mkCId "TopObj" cidUseTop = mkCId "UseTop" -- added to Extra cidDropAttVV = mkCId "ComplBareVV" cidRelCN = mkCId "RelCN" cidPassV2' = mkCId "PassV2" cidVPSlashAP = mkCId "PPartAP" cidReflCN = mkCId "ReflIdPron" cidReflIdPron = mkCId "ReflIdPron" cidPredetAdvF = mkCId "PredetAdvF" cidCompPronAQ = mkCId "CompPronAQ" cidQuantPronAQ = mkCId "QuantPronAQ" --not present in grammar cidCNNumNP = mkCId "CNNumNP" -- words cidhow8much_IAdv = mkCId "how8much_IAdv" cidBy8agent_Prep = mkCId "by8agent_Prep" cidD_1 = mkCId "D_1" cidName = mkCId "john_PN" cidCan_VV = mkCId "can_VV" cidMust_VV = mkCId "must_VV" cidWant_VV = mkCId "want_VV" cidHave_V2 = mkCId "have_V2" cidGet_V2 = mkCId "faa_vb_1_1_V2" -- in lexicon, not grammar cidGet_VV = mkCId "faa_vb_1_1_VV" -- in lexicon, not grammar cidDo_V2 = mkCId "do_V2" cidDo_VV = mkCId "do_VV" cidBecome_V2 = mkCId "become_V2" cidBecome_VA = mkCId "become_VA" -- for old translation cidReflSlash = mkCId "ReflSlash" cidSlash3V3 = mkCId "Slash3V3" cidSlash2V3 = mkCId "Slash2V3" cidSlashV2V = mkCId "Slash2V2" cidComplVQ = mkCId "ComplVQ" cidRelNP' = mkCId "RelNP'"
null
https://raw.githubusercontent.com/GrammaticalFramework/gf-core/9b4f2dd18b64b770aaebfa1885085e8e3447f119/treebanks/talbanken/Idents.hs
haskell
added to Extra not present in grammar words in lexicon, not grammar in lexicon, not grammar for old translation
module Idents where import PGF cidASimul = mkCId "ASimul" cidAAnter = mkCId "AAnter" cidPositAdvAdj = mkCId "PositAdvAdj" cidPositAdVAdj = mkCId "PositAdVAdj" cidUseCl = mkCId "UseCl" cidUseQCl = mkCId "UseQCl" cidPredVP = mkCId "PredVP" cidAdjCN = mkCId "AdjCN" cidUseN = mkCId "UseN" cidDetQuant = mkCId "DetQuant" cidNumSg = mkCId "NumSg" cidNumPl = mkCId "NumPl" cidDetCN = mkCId "DetCN" cidIndefArt = mkCId "IndefArt" cidDefArt = mkCId "DefArt" cidUsePN = mkCId "UsePN" cidUseQuantPN = mkCId "UseQuantPN" cidSymbPN = mkCId "SymbPN" cidMkSymb = mkCId "MkSymb" cidUsePron = mkCId "UsePron" cidConjNP = mkCId "ConjNP" cidBaseNP = mkCId "BaseNP" cidConsNP = mkCId "ConsNP" cidConjCN = mkCId "ConjCN" cidBaseCN = mkCId "BaseCN" cidConsCN = mkCId "ConsCN" cidMassNP = mkCId "MassNP" cidAdvNP = mkCId "AdvNP" cidTPres = mkCId "TPres" cidTPast = mkCId "TPast" cidTFut = mkCId "TFut" cidTFutKommer = mkCId "TFutKommer" cidTCond = mkCId "TCond" cidTTAnt = mkCId "TTAnt" cidPPos = mkCId "PPos" cidPNeg = mkCId "PNeg" cidComplSlash = mkCId "ComplSlash" cidSlashV2a = mkCId "SlashV2a" cidSlashV2A = mkCId "SlashV2A" cidComplVS = mkCId "ComplVS" cidUseV = mkCId "UseV" cidAdVVP = mkCId "AdVVP" cidAdvVP = mkCId "AdvVP" cidAdvVPSlash = mkCId "AdvVPSlash" cidPrepNP = mkCId "PrepNP" cidto_Prep = mkCId "to_Prep" cidsuch_as_Prep= mkCId "such_as_Prep" cidPastPartAP = mkCId "PastPartAP" cidPassV2 = mkCId "PassV2" cidAdvS = mkCId "AdvS" cidPositA = mkCId "PositA" cidIDig = mkCId "IDig" cidIIDig = mkCId "IIDig" cidNumCard = mkCId "NumCard" cidNumDigits = mkCId "NumDigits" cidNumNumeral = mkCId "NumNumeral" cidnum = mkCId "num" cidpot2as3 = mkCId "pot2as3" cidpot1as2 = mkCId "pot1as2" cidpot0as1 = mkCId "pot0as1" cidpot01 = mkCId "pot01" cidpot0 = mkCId "pot0" cidn7 = mkCId "n7" cidPossPron = mkCId "PossPron" cidCompAP = mkCId "CompAP" cidCompNP = mkCId "CompNP" cidCompAdv = mkCId "CompAdv" cidUseComp = mkCId "UseComp" cidCompoundCN = mkCId "CompoundCN" cidDashCN = mkCId "DashCN" cidProgrVP = mkCId "ProgrVP" cidGerundN = mkCId "GerundN" cidGenNP = mkCId "GenNP" cidPredetNP = mkCId "PredetNP" cidDetNP = mkCId "DetNP" cidAdAP = mkCId "AdAP" cidPositAdAAdj = mkCId "PositAdAAdj" cidBaseAP = mkCId "BaseAP" cidConjAP = mkCId "ConjAP" cidAndConj = mkCId "and_Conj" cidOrConj = mkCId "or_Conj" cidConsAP = mkCId "ConsAP" cidQuestVP = mkCId "QuestVP" cidComplVV = mkCId "ComplVV" cidComplVA = mkCId "ComplVA" cidUseCopula = mkCId "UseCopula" cidPhrUtt = mkCId "PhrUtt" cidNoPConj = mkCId "NoPConj" cidNoVoc = mkCId "NoVoc" cidUttS = mkCId "UttS" cidUttQS = mkCId "UttQS" cidUseComparA = mkCId "UseComparA" cidOrdSuperl = mkCId "OrdSuperl" cidUttImpPol = mkCId "UttImpPol" cidImpVP = mkCId "ImpVP" cidPConjConj = mkCId "PConjConj" cidUttNP = mkCId "UttNP" cidGenericCl = mkCId "GenericCl" cidAdAdv = mkCId "AdAdv" cidConsAdv = mkCId "ConsAdv" cidBaseAdv = mkCId "BaseAdv" cidConjAdv = mkCId "ConjAdv" cidConsVPS = mkCId "ConsVPS" cidBaseVPS = mkCId "BaseVPS" cidConjVPS = mkCId "ConjVPS" cidConsS = mkCId "ConsS" cidBaseS = mkCId "BaseS" cidConjS = mkCId "ConjS" cidSubjS = mkCId "SubjS" cidUttAdv = mkCId "UttAdv" cidApposCN = mkCId "ApposCN" cidUseRCl = mkCId "UseRCl" cidImpersCl = mkCId "ImpersCl" cidReflVP = mkCId "ReflVP" cidExistNP = mkCId "ExistNP" cidUseA2 = mkCId "UseA2" cidComplN2 = mkCId "ComplN2" cidAdvIAdv = mkCId "AdvIAdv" cidQuestIAdv = mkCId "QuestIAdv" cidQuestIComp = mkCId "QuestIComp" cidQuestSlash = mkCId "QuestSlash" cidCompIAdv = mkCId "CompIAdv" cidCompIP = mkCId "CompIP" cidIdetCN = mkCId "IdetCN" cidIdetQuant = mkCId "IdetQuant" cidPrepIP = mkCId "PrepIP" cidFocObj = mkCId "FocObj" cidSlashVP = mkCId "SlashVP" cidAdvSlash = mkCId "AdvSlash" cidSSubjS = mkCId "SSubjS" cidRelVP = mkCId "RelVP" cidIdRP = mkCId "IdRP" cidRelSlash = mkCId "RelSlash" cidTopAdv = mkCId "TopAdv" cidTopAP = mkCId "TopAP" cidTopObj = mkCId "TopObj" cidUseTop = mkCId "UseTop" cidDropAttVV = mkCId "ComplBareVV" cidRelCN = mkCId "RelCN" cidPassV2' = mkCId "PassV2" cidVPSlashAP = mkCId "PPartAP" cidReflCN = mkCId "ReflIdPron" cidReflIdPron = mkCId "ReflIdPron" cidPredetAdvF = mkCId "PredetAdvF" cidCompPronAQ = mkCId "CompPronAQ" cidQuantPronAQ = mkCId "QuantPronAQ" cidCNNumNP = mkCId "CNNumNP" cidhow8much_IAdv = mkCId "how8much_IAdv" cidBy8agent_Prep = mkCId "by8agent_Prep" cidD_1 = mkCId "D_1" cidName = mkCId "john_PN" cidCan_VV = mkCId "can_VV" cidMust_VV = mkCId "must_VV" cidWant_VV = mkCId "want_VV" cidHave_V2 = mkCId "have_V2" cidDo_V2 = mkCId "do_V2" cidDo_VV = mkCId "do_VV" cidBecome_V2 = mkCId "become_V2" cidBecome_VA = mkCId "become_VA" cidReflSlash = mkCId "ReflSlash" cidSlash3V3 = mkCId "Slash3V3" cidSlash2V3 = mkCId "Slash2V3" cidSlashV2V = mkCId "Slash2V2" cidComplVQ = mkCId "ComplVQ" cidRelNP' = mkCId "RelNP'"
a75f74db10895ef1e49c594fa30e26b7ce991f89c47b2124a056395ce5a5231a
ajhc/ajhc
CType.hs
# OPTIONS_JHC -fno - prelude # module Prelude.CType ( isAscii, isLatin1, isControl, isPrint, isSpace, isUpper, isLower, isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum, digitToInt, intToDigit, toUpper, toLower ) where import Jhc.Inst.Order import Jhc.Basics import Jhc.Order import Jhc.List import Jhc.IO -- Character-testing operations isAscii, isLatin1, isControl, isPrint, isSpace, isUpper, isLower, isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum :: Char -> Bool isAscii c = c < '\x80' isLatin1 c = c <= '\xff' isControl c = c < ' ' || c >= '\DEL' && c <= '\x9f' isPrint c = isLatin1 c && not (isControl c) isSpace c = c `elem` " \t\n\r\f\v\xA0" isUpper c = c >= 'A' && c <= 'Z' isLower c = c >= 'a' && c <= 'z' isAlpha c = isUpper c || isLower c isDigit c = c >= '0' && c <= '9' isOctDigit c = c >= '0' && c <= '7' isHexDigit c = isDigit c || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f' isAlphaNum c = isAlpha c || isDigit c Digit conversion operations digitToInt :: Char -> Int digitToInt c | isDigit c = ord c - ord '0' | c >= 'a' && c <= 'f' = ord c - (ord 'a' + Int 10#) | c >= 'A' && c <= 'F' = ord c - (ord 'A' + Int 10#) | otherwise = error "Char.digitToInt: not a digit" intToDigit :: Int -> Char intToDigit i = f (int2word i) where f w | w < (Word 10#) = chr (ord '0' + i) | w < (Word 16#) = chr ((ord 'a' - Int 10#) + i) | otherwise = error "Char.intToDigit: not a digit" foreign import primitive "U2U" int2word :: Int -> Word foreign import primitive "Add" (+) :: Int -> Int -> Int foreign import primitive "Sub" (-) :: Int -> Int -> Int -- Case-changing operations toUpper :: Char -> Char toUpper c | isLower c = chr $ ord c - (Int 32#) | otherwise = c toLower :: Char -> Char toLower c | isUpper c = chr $ ord c + (Int 32#) | otherwise = c
null
https://raw.githubusercontent.com/ajhc/ajhc/8ef784a6a3b5998cfcd95d0142d627da9576f264/lib/jhc/Prelude/CType.hs
haskell
Character-testing operations Case-changing operations
# OPTIONS_JHC -fno - prelude # module Prelude.CType ( isAscii, isLatin1, isControl, isPrint, isSpace, isUpper, isLower, isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum, digitToInt, intToDigit, toUpper, toLower ) where import Jhc.Inst.Order import Jhc.Basics import Jhc.Order import Jhc.List import Jhc.IO isAscii, isLatin1, isControl, isPrint, isSpace, isUpper, isLower, isAlpha, isDigit, isOctDigit, isHexDigit, isAlphaNum :: Char -> Bool isAscii c = c < '\x80' isLatin1 c = c <= '\xff' isControl c = c < ' ' || c >= '\DEL' && c <= '\x9f' isPrint c = isLatin1 c && not (isControl c) isSpace c = c `elem` " \t\n\r\f\v\xA0" isUpper c = c >= 'A' && c <= 'Z' isLower c = c >= 'a' && c <= 'z' isAlpha c = isUpper c || isLower c isDigit c = c >= '0' && c <= '9' isOctDigit c = c >= '0' && c <= '7' isHexDigit c = isDigit c || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f' isAlphaNum c = isAlpha c || isDigit c Digit conversion operations digitToInt :: Char -> Int digitToInt c | isDigit c = ord c - ord '0' | c >= 'a' && c <= 'f' = ord c - (ord 'a' + Int 10#) | c >= 'A' && c <= 'F' = ord c - (ord 'A' + Int 10#) | otherwise = error "Char.digitToInt: not a digit" intToDigit :: Int -> Char intToDigit i = f (int2word i) where f w | w < (Word 10#) = chr (ord '0' + i) | w < (Word 16#) = chr ((ord 'a' - Int 10#) + i) | otherwise = error "Char.intToDigit: not a digit" foreign import primitive "U2U" int2word :: Int -> Word foreign import primitive "Add" (+) :: Int -> Int -> Int foreign import primitive "Sub" (-) :: Int -> Int -> Int toUpper :: Char -> Char toUpper c | isLower c = chr $ ord c - (Int 32#) | otherwise = c toLower :: Char -> Char toLower c | isUpper c = chr $ ord c + (Int 32#) | otherwise = c
9e1f238e2391c77a7d487c21feeac4d633165e2072c4ba691843f2ad33e51bbd
Apress/beg-haskell
Par.hs
module Chapter8.APriori.Par (apriori) where import Control.Monad.Par -- import Data.Set (Set) import qualified Data.Set as S import Chapter8.APriori.Types -- No parallelism apriori : : Double - > [ Transaction ] - > [ FrequentSet ] apriori transactions = let c1 = noDups $ concatMap ( \(Transaction t ) - > map ( FrequentSet . S.singleton ) $ S.toList t ) transactions l1 = filter ( \fs - > setSupport transactions fs > ) c1 in concat $ l1 : generateMoreCs transactions l1 generateMoreCs : : Double - > [ Transaction ] - > [ FrequentSet ] - > [ [ FrequentSet ] ] generateMoreCs _ _ [ ] = [ ] generateMoreCs transactions lk = let ck1 = noDups $ zipWith ( \(FrequentSet a ) ( FrequentSet b ) - > FrequentSet $ a ` S.union ` b ) lk lk lk1 = filter ( \fs - > setSupport transactions fs > ) ck1 in lk1 : generateMoreCs transactions lk1 -- No parallelism apriori :: Double -> [Transaction] -> [FrequentSet] apriori minSupport transactions = let c1 = noDups $ concatMap (\(Transaction t) -> map (FrequentSet . S.singleton) $ S.toList t) transactions l1 = filter (\fs -> setSupport transactions fs > minSupport) c1 in concat $ l1 : generateMoreCs minSupport transactions l1 generateMoreCs :: Double -> [Transaction] -> [FrequentSet] -> [[FrequentSet]] generateMoreCs _ _ [] = [] generateMoreCs minSupport transactions lk = let ck1 = noDups $ zipWith (\(FrequentSet a) (FrequentSet b) -> FrequentSet $ a `S.union` b) lk lk lk1 = filter (\fs -> setSupport transactions fs > minSupport) ck1 in lk1 : generateMoreCs minSupport transactions lk1 -} noDups :: Ord a => [a] -> [a] noDups = S.toList . S.fromList -- With parMapM apriori :: Double -> [Transaction] -> [FrequentSet] apriori minSupport transactions = runPar $ do let c1 = noDups $ concatMap (\(Transaction t) -> map (FrequentSet . S.singleton) $ S.toList t) transactions l1NotFiltered <- parMap (\fs -> (fs, setSupport transactions fs > minSupport)) c1 let l1 = concatMap (\(fs,b) -> if b then [fs] else []) l1NotFiltered return $ concat (l1 : generateMoreCs minSupport transactions l1) generateMoreCs :: Double -> [Transaction] -> [FrequentSet] -> [[FrequentSet]] generateMoreCs _ _ [] = [] generateMoreCs minSupport transactions lk = let ck1 = noDups $ zipWith (\(FrequentSet a) (FrequentSet b) -> FrequentSet $ a `S.union` b) lk lk lk1 = runPar $ filterLk minSupport transactions ck1 in lk1 : generateMoreCs minSupport transactions lk1 Splitting in halves filterLk :: Double -> [Transaction] -> [FrequentSet] -> Par [FrequentSet] filterLk minSupport transactions ck = let lengthCk = length ck in if lengthCk <= 5 then return $ filter (\fs -> setSupport transactions fs > minSupport) ck else let (l,r) = splitAt (lengthCk `div` 2) ck in do lVar <- spawn $ filterLk minSupport transactions l lFiltered <- get lVar rVar <- spawn $ filterLk minSupport transactions r rFiltered <- get rVar return $ lFiltered ++ rFiltered -- With skeleton filterLk : : Double - > [ Transaction ] - > [ FrequentSet ] - > [ FrequentSet ] filterLk transactions = divConq ( - > length p < = 5 ) ( - > let ( l , r ) = splitAt ( length p ` div ` 2 ) p in [ l , r ] ) ( \[l , r ] - > l + + r ) ( filter ( \fs - > setSupport transactions fs > ) ) -- With skeleton filterLk :: Double -> [Transaction] -> [FrequentSet] -> [FrequentSet] filterLk minSupport transactions = divConq (\p -> length p <= 5) (\p -> let (l, r) = splitAt (length p `div` 2) p in [l, r]) (\[l,r] -> l ++ r) (filter (\fs -> setSupport transactions fs > minSupport)) -} divConq :: NFData sol => (prob -> Bool) -- indivisible? -> (prob -> [prob]) -- split into subproblems -> ([sol] -> sol) -- join solutions -> (prob -> sol) -- solve a subproblem -> (prob -> sol) divConq indiv split join f prob = runPar $ go prob where go prob | indiv prob = return (f prob) | otherwise = do sols <- parMapM go (split prob) return (join sols)
null
https://raw.githubusercontent.com/Apress/beg-haskell/aaacbf047d553e6177c38807e662cc465409dffd/chapter8/src/Chapter8/APriori/Par.hs
haskell
import Data.Set (Set) No parallelism No parallelism With parMapM With skeleton With skeleton indivisible? split into subproblems join solutions solve a subproblem
module Chapter8.APriori.Par (apriori) where import Control.Monad.Par import qualified Data.Set as S import Chapter8.APriori.Types apriori : : Double - > [ Transaction ] - > [ FrequentSet ] apriori transactions = let c1 = noDups $ concatMap ( \(Transaction t ) - > map ( FrequentSet . S.singleton ) $ S.toList t ) transactions l1 = filter ( \fs - > setSupport transactions fs > ) c1 in concat $ l1 : generateMoreCs transactions l1 generateMoreCs : : Double - > [ Transaction ] - > [ FrequentSet ] - > [ [ FrequentSet ] ] generateMoreCs _ _ [ ] = [ ] generateMoreCs transactions lk = let ck1 = noDups $ zipWith ( \(FrequentSet a ) ( FrequentSet b ) - > FrequentSet $ a ` S.union ` b ) lk lk lk1 = filter ( \fs - > setSupport transactions fs > ) ck1 in lk1 : generateMoreCs transactions lk1 apriori :: Double -> [Transaction] -> [FrequentSet] apriori minSupport transactions = let c1 = noDups $ concatMap (\(Transaction t) -> map (FrequentSet . S.singleton) $ S.toList t) transactions l1 = filter (\fs -> setSupport transactions fs > minSupport) c1 in concat $ l1 : generateMoreCs minSupport transactions l1 generateMoreCs :: Double -> [Transaction] -> [FrequentSet] -> [[FrequentSet]] generateMoreCs _ _ [] = [] generateMoreCs minSupport transactions lk = let ck1 = noDups $ zipWith (\(FrequentSet a) (FrequentSet b) -> FrequentSet $ a `S.union` b) lk lk lk1 = filter (\fs -> setSupport transactions fs > minSupport) ck1 in lk1 : generateMoreCs minSupport transactions lk1 -} noDups :: Ord a => [a] -> [a] noDups = S.toList . S.fromList apriori :: Double -> [Transaction] -> [FrequentSet] apriori minSupport transactions = runPar $ do let c1 = noDups $ concatMap (\(Transaction t) -> map (FrequentSet . S.singleton) $ S.toList t) transactions l1NotFiltered <- parMap (\fs -> (fs, setSupport transactions fs > minSupport)) c1 let l1 = concatMap (\(fs,b) -> if b then [fs] else []) l1NotFiltered return $ concat (l1 : generateMoreCs minSupport transactions l1) generateMoreCs :: Double -> [Transaction] -> [FrequentSet] -> [[FrequentSet]] generateMoreCs _ _ [] = [] generateMoreCs minSupport transactions lk = let ck1 = noDups $ zipWith (\(FrequentSet a) (FrequentSet b) -> FrequentSet $ a `S.union` b) lk lk lk1 = runPar $ filterLk minSupport transactions ck1 in lk1 : generateMoreCs minSupport transactions lk1 Splitting in halves filterLk :: Double -> [Transaction] -> [FrequentSet] -> Par [FrequentSet] filterLk minSupport transactions ck = let lengthCk = length ck in if lengthCk <= 5 then return $ filter (\fs -> setSupport transactions fs > minSupport) ck else let (l,r) = splitAt (lengthCk `div` 2) ck in do lVar <- spawn $ filterLk minSupport transactions l lFiltered <- get lVar rVar <- spawn $ filterLk minSupport transactions r rFiltered <- get rVar return $ lFiltered ++ rFiltered filterLk : : Double - > [ Transaction ] - > [ FrequentSet ] - > [ FrequentSet ] filterLk transactions = divConq ( - > length p < = 5 ) ( - > let ( l , r ) = splitAt ( length p ` div ` 2 ) p in [ l , r ] ) ( \[l , r ] - > l + + r ) ( filter ( \fs - > setSupport transactions fs > ) ) filterLk :: Double -> [Transaction] -> [FrequentSet] -> [FrequentSet] filterLk minSupport transactions = divConq (\p -> length p <= 5) (\p -> let (l, r) = splitAt (length p `div` 2) p in [l, r]) (\[l,r] -> l ++ r) (filter (\fs -> setSupport transactions fs > minSupport)) -} divConq :: NFData sol -> (prob -> sol) divConq indiv split join f prob = runPar $ go prob where go prob | indiv prob = return (f prob) | otherwise = do sols <- parMapM go (split prob) return (join sols)
b133874c72ce7c3568b429f8f712a87b8caa519039796ab7f03489b134840a31
RedPRL/yuujinchou
Trie.mli
open Bwd (** {1 Types} *) (** The type of hierarchical names. The name [x.y.z] is represented by the OCaml list [["x"; "y"; "z"]]. *) type path = string list (** The type of hierarchical names, but using backward lists. The name [x.y.z] is represented by the backward list [Emp #< "x" #< "y" #< "z"]. *) type bwd_path = string bwd * The abstract type of a trie . [ ' data ] represents the information surviving retagging , and [ ' tag ] represents the information to be reset during retagging . See { ! : retag } , which could reset all tags in O(1 ) time while keeping data intact . A possible usage when making a proof assistant is to put top - level definitions into [ ' data ] and identities of the import statements into [ ' tag ] for efficient detection of unused imports . ['data] represents the information surviving retagging, and ['tag] represents the information to be reset during retagging. See {!val:retag}, which could reset all tags in O(1) time while keeping data intact. A possible usage when making a proof assistant is to put top-level definitions into ['data] and identities of the import statements into ['tag] for efficient detection of unused imports. *) type (+!'data, +!'tag) t (** {1 Basic Operations} *) (** The empty trie. *) val empty : ('data, 'tag) t (** Check whether the trie is empty. *) val is_empty : ('data, 'tag) t -> bool * [ root ( d , t ) ] makes a trie with the only one binding : the root and its associated data [ d ] and tag [ t ] . It is equivalent to { ! : } [ ( Some ( d , t ) ) ] . val root : 'data * 'tag -> ('data, 'tag) t * [ root_opt v ] is equivalent to [ match v with None - > ] { ! : empty } [ | Some v - > ] { ! : root } [ v ] . In other words , [ root_opt None ] will make an empty trie and [ root_opt ( Some ( d , t ) ) ] will make a trie with only one binding : the root associated with the data [ d ] and the tag [ t ] . If the input is always [ Some v ] , use { ! : root } . val root_opt : ('data * 'tag) option -> ('data, 'tag) t (** [prefix p t] makes a minimum trie with [t] rooted at [p]. *) val prefix : path -> ('data, 'tag) t -> ('data, 'tag) t * [ singleton ( p , ( d , t ) ) ] makes a trie with the only binding : [ p ] and its associated data [ d ] and tag [ t ] . It is equivalent to { ! : prefix } [ p @@ ] { ! : root } [ ( d , t ) ] val singleton : path * ('data * 'tag) -> ('data, 'tag) t * [ equal eq_data eq_tag t1 t2 ] checks whether two tries are equal . val equal : ('data -> 'data -> bool) -> ('tag -> 'tag -> bool) -> ('data, 'tag) t -> ('data, 'tag) t -> bool (** {1 Finding Values} *) (** [find_subtree p t] returns the subtree rooted at [p]. @return The subtree with all the bindings under [p], including the binding at [p] itself (which will be the root). If there are no such bindings with the prefix [p], an empty trie is returned. *) val find_subtree : path -> ('data, 'tag) t -> ('data, 'tag) t (** [find_singleton p t] returns the data and tag at [p]. *) val find_singleton : path -> ('data, 'tag) t -> ('data * 'tag) option * [ find_root t ] returns the data and tag at the root . This is equivalent to { ! : find_singleton } [ [ ] t ] . val find_root : ('data, 'tag) t -> ('data * 'tag) option * { 1 Mapping and Filtering } (** [iter ~prefix f t] applies the function [f] to each data and tag in the trie. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). *) val iter : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> unit) -> ('data, 'tag) t -> unit (** [map ~prefix f trie] applies the function [f] to each data and tag in the trie. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). *) val map : ?prefix:bwd_path -> (bwd_path -> 'data1 * 'tag1 -> 'data2 * 'tag2) -> ('data1, 'tag1) t -> ('data2, 'tag2) t (** [filter ~prefix f trie] removes all data [d] with tag [t] at path [p] such that [f ~prefix:p (d, t)] returns [false]. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). *) val filter : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> bool) -> ('data, 'tag) t -> ('data, 'tag) t (** [filter_map ~prefix f trie] applies the function [f] to each data [d] with tag [t] at [p] in [trie]. If [f ~prefix:p (d, t)] returns [None], then the binding will be removed from the trie. Otherwise, if [f v] returns [Some d'], then the data will be replaced by [d']. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). *) val filter_map : ?prefix:bwd_path -> (bwd_path -> 'data1 * 'tag1 -> ('data2 * 'tag2) option) -> ('data1, 'tag1) t -> ('data2, 'tag2) t (** {1 Updating} *) (** [update_subtree p f t] replaces the subtree [t'] rooted at [p] in [t] with [f t']. *) val update_subtree : path -> (('data, 'tag) t -> ('data, 'tag) t) -> ('data, 'tag) t -> ('data, 'tag) t (** [update_singleton p f trie] replaces the data and tag at [p] in [trie] with the result of [f]. If there was no binding at [p], [f None] is evaluated. Otherwise, [f (Some (d, t))] is used where [d] and [t] are the data and the tag. If the result is [None], the old binding at [p] (if any) is removed. Otherwise, if the result is [Some (d', t')], the data and the tag at [p] are replaced by [d'] and [t']. *) val update_singleton : path -> (('data * 'tag) option -> ('data * 'tag) option) -> ('data, 'tag) t -> ('data, 'tag) t * [ update_root f t ] updates the value at root with [ f ] . It is equivalent to { ! : update_singleton } [ [ ] f t ] . val update_root : (('data * 'tag) option -> ('data * 'tag) option) -> ('data, 'tag) t -> ('data, 'tag) t (** {1 Union} *) * [ union ~prefix merger t1 t2 ] merges two tries [ t1 ] and [ t2 ] . If both tries have a binding at the same path [ p ] , it will call [ merger p x y ] to reconcile the values [ x ] from [ t1 ] and [ y ] from [ t2 ] that are both bound at the [ path ] . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> ('data, 'tag) t -> ('data, 'tag) t * [ union_subtree ~prefix merger t1 ( path , t2 ) ] is equivalent to { ! : union } [ ~prefix merger t1 ( prefix path t2 ) ] , but potentially more efficient . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union_subtree : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> path * ('data, 'tag) t -> ('data, 'tag) t * [ union_singleton ~prefix merger t binding ] is equivalent to { ! : union } [ ~prefix merger t1 ( singleton binding ) ] , but potentially more efficient . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union_singleton : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> path * ('data * 'tag) -> ('data, 'tag) t * [ union_root ~prefix merger t r ] is equivalent to { ! : union_singleton } [ ~prefix merger t ( [ ] , r ) ] , but potentially more efficient . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union_root : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> 'data * 'tag -> ('data, 'tag) t (** {1 Separation} *) * [ detach_subtree p t ] detaches the subtree at [ p ] from the main trie and returns both the subtree and the remaining trie ( in that order ) . If [ detach p t ] returns [ t1 , t2 ] , then { ! : } [ m t2 ( p , t1 ) ] should be equivalent to [ t ] . val detach_subtree : path -> ('data, 'tag) t -> ('data, 'tag) t * ('data, 'tag) t * [ detach_singleton p t ] detaches the binding at [ p ] from the main trie and returns both the binding and the remaining trie . If [ detach p t ] returns [ b , t ' ] , then { ! : } [ m t ' ( p , ] { ! : } [ b ) ] should be equivalent to [ t ] . val detach_singleton : path -> ('data, 'tag) t -> ('data * 'tag) option * ('data, 'tag) t * [ detach_root t ] detaches the binding at the root of and returns both the binding and the remaining trie . It is equivalent to { ! : detach_singleton } [ [ ] t ] . val detach_root : ('data, 'tag) t -> ('data * 'tag) option * ('data, 'tag) t (** {1 Iterators} *) (** [to_seq ~prefix t] traverses through the trie [t] in the lexicographical order. @param prefix The prefix prepended to any path in the output. The default is the empty prefix ([Emp]). *) val to_seq : ?prefix:bwd_path -> ('data, 'tag) t -> (path * ('data * 'tag)) Seq.t * [ to_seq_with_bwd_paths ] is like { ! : to_seq } , but with paths in the backward direction . This is potentially more efficient than { ! : to_seq } because the conversion from backward lists to forward lists is skipped . @param prefix The prefix prepended to any path in the output . The default is the empty prefix ( [ Emp ] ) . This is potentially more efficient than {!val:to_seq} because the conversion from backward lists to forward lists is skipped. @param prefix The prefix prepended to any path in the output. The default is the empty prefix ([Emp]). *) val to_seq_with_bwd_paths : ?prefix:bwd_path -> ('data, 'tag) t -> (bwd_path * ('data * 'tag)) Seq.t * [ to_seq_values t ] traverses through the trie [ t ] in the lexicographical order but only returns the associated data and tags . This is potentially more efficient than { ! : to_seq } because the conversion from backward lists to forward lists is skipped . val to_seq_values : ('data, 'tag) t -> ('data * 'tag) Seq.t * [ of_seq ~prefix s ] inserts bindings [ ( p , d ) ] into an empty trie , one by one , using { ! : union_singleton } . Later bindings will shadow previous ones if the paths of bindings are not unique . val of_seq : (path * ('data * 'tag)) Seq.t -> ('data, 'tag) t * [ of_seq_with_merger ~prefix merger s ] inserts bindings [ ( p , d ) ] into an empty trie , one by one , using { ! : union_singleton } . Bindings with the same path are resolved using [ merger ] instead of silent shadowing . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . Note that [ prefix ] does not directly affect the output trie , only the argument to [ merger ] . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). Note that [prefix] does not directly affect the output trie, only the argument to [merger]. *) val of_seq_with_merger : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> (path * ('data * 'tag)) Seq.t -> ('data, 'tag) t (** {1 Tags} *) (** Untagged tries (where all tags are [()]). *) type 'data untagged = ('data, unit) t (** [retag tag t] changes all tags within [t] to [tag] in O(1) time. The data remain intact. *) val retag : 'tag -> ('data, _) t -> ('data, 'tag) t * [ retag_subtree tag path t ] changes all tags within the subtrie rooted at [ path ] to [ tag ] efficiently . The data remain intact . val retag_subtree : path -> 'tag -> ('data, 'tag) t -> ('data, 'tag) t * [ untag t ] is [ retag ( ) t ] . val untag : ('data, _) t -> 'data untagged * [ set_of_tags t ] returns the set of tags used in a trie , but as a [ Seq.t ] . val set_of_tags : ('tag -> 'tag -> int) -> ('data, 'tag) t -> 'tag Seq.t
null
https://raw.githubusercontent.com/RedPRL/yuujinchou/8b10007d96f165d0c6f9aee8ef66e8f401c75562/src/Trie.mli
ocaml
* {1 Types} * The type of hierarchical names. The name [x.y.z] is represented by the OCaml list [["x"; "y"; "z"]]. * The type of hierarchical names, but using backward lists. The name [x.y.z] is represented by the backward list [Emp #< "x" #< "y" #< "z"]. * {1 Basic Operations} * The empty trie. * Check whether the trie is empty. * [prefix p t] makes a minimum trie with [t] rooted at [p]. * {1 Finding Values} * [find_subtree p t] returns the subtree rooted at [p]. @return The subtree with all the bindings under [p], including the binding at [p] itself (which will be the root). If there are no such bindings with the prefix [p], an empty trie is returned. * [find_singleton p t] returns the data and tag at [p]. * [iter ~prefix f t] applies the function [f] to each data and tag in the trie. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). * [map ~prefix f trie] applies the function [f] to each data and tag in the trie. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). * [filter ~prefix f trie] removes all data [d] with tag [t] at path [p] such that [f ~prefix:p (d, t)] returns [false]. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). * [filter_map ~prefix f trie] applies the function [f] to each data [d] with tag [t] at [p] in [trie]. If [f ~prefix:p (d, t)] returns [None], then the binding will be removed from the trie. Otherwise, if [f v] returns [Some d'], then the data will be replaced by [d']. @param prefix The prefix prepended to any path sent to [f]. The default is the empty prefix ([Emp]). * {1 Updating} * [update_subtree p f t] replaces the subtree [t'] rooted at [p] in [t] with [f t']. * [update_singleton p f trie] replaces the data and tag at [p] in [trie] with the result of [f]. If there was no binding at [p], [f None] is evaluated. Otherwise, [f (Some (d, t))] is used where [d] and [t] are the data and the tag. If the result is [None], the old binding at [p] (if any) is removed. Otherwise, if the result is [Some (d', t')], the data and the tag at [p] are replaced by [d'] and [t']. * {1 Union} * {1 Separation} * {1 Iterators} * [to_seq ~prefix t] traverses through the trie [t] in the lexicographical order. @param prefix The prefix prepended to any path in the output. The default is the empty prefix ([Emp]). * {1 Tags} * Untagged tries (where all tags are [()]). * [retag tag t] changes all tags within [t] to [tag] in O(1) time. The data remain intact.
open Bwd type path = string list type bwd_path = string bwd * The abstract type of a trie . [ ' data ] represents the information surviving retagging , and [ ' tag ] represents the information to be reset during retagging . See { ! : retag } , which could reset all tags in O(1 ) time while keeping data intact . A possible usage when making a proof assistant is to put top - level definitions into [ ' data ] and identities of the import statements into [ ' tag ] for efficient detection of unused imports . ['data] represents the information surviving retagging, and ['tag] represents the information to be reset during retagging. See {!val:retag}, which could reset all tags in O(1) time while keeping data intact. A possible usage when making a proof assistant is to put top-level definitions into ['data] and identities of the import statements into ['tag] for efficient detection of unused imports. *) type (+!'data, +!'tag) t val empty : ('data, 'tag) t val is_empty : ('data, 'tag) t -> bool * [ root ( d , t ) ] makes a trie with the only one binding : the root and its associated data [ d ] and tag [ t ] . It is equivalent to { ! : } [ ( Some ( d , t ) ) ] . val root : 'data * 'tag -> ('data, 'tag) t * [ root_opt v ] is equivalent to [ match v with None - > ] { ! : empty } [ | Some v - > ] { ! : root } [ v ] . In other words , [ root_opt None ] will make an empty trie and [ root_opt ( Some ( d , t ) ) ] will make a trie with only one binding : the root associated with the data [ d ] and the tag [ t ] . If the input is always [ Some v ] , use { ! : root } . val root_opt : ('data * 'tag) option -> ('data, 'tag) t val prefix : path -> ('data, 'tag) t -> ('data, 'tag) t * [ singleton ( p , ( d , t ) ) ] makes a trie with the only binding : [ p ] and its associated data [ d ] and tag [ t ] . It is equivalent to { ! : prefix } [ p @@ ] { ! : root } [ ( d , t ) ] val singleton : path * ('data * 'tag) -> ('data, 'tag) t * [ equal eq_data eq_tag t1 t2 ] checks whether two tries are equal . val equal : ('data -> 'data -> bool) -> ('tag -> 'tag -> bool) -> ('data, 'tag) t -> ('data, 'tag) t -> bool val find_subtree : path -> ('data, 'tag) t -> ('data, 'tag) t val find_singleton : path -> ('data, 'tag) t -> ('data * 'tag) option * [ find_root t ] returns the data and tag at the root . This is equivalent to { ! : find_singleton } [ [ ] t ] . val find_root : ('data, 'tag) t -> ('data * 'tag) option * { 1 Mapping and Filtering } val iter : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> unit) -> ('data, 'tag) t -> unit val map : ?prefix:bwd_path -> (bwd_path -> 'data1 * 'tag1 -> 'data2 * 'tag2) -> ('data1, 'tag1) t -> ('data2, 'tag2) t val filter : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> bool) -> ('data, 'tag) t -> ('data, 'tag) t val filter_map : ?prefix:bwd_path -> (bwd_path -> 'data1 * 'tag1 -> ('data2 * 'tag2) option) -> ('data1, 'tag1) t -> ('data2, 'tag2) t val update_subtree : path -> (('data, 'tag) t -> ('data, 'tag) t) -> ('data, 'tag) t -> ('data, 'tag) t val update_singleton : path -> (('data * 'tag) option -> ('data * 'tag) option) -> ('data, 'tag) t -> ('data, 'tag) t * [ update_root f t ] updates the value at root with [ f ] . It is equivalent to { ! : update_singleton } [ [ ] f t ] . val update_root : (('data * 'tag) option -> ('data * 'tag) option) -> ('data, 'tag) t -> ('data, 'tag) t * [ union ~prefix merger t1 t2 ] merges two tries [ t1 ] and [ t2 ] . If both tries have a binding at the same path [ p ] , it will call [ merger p x y ] to reconcile the values [ x ] from [ t1 ] and [ y ] from [ t2 ] that are both bound at the [ path ] . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> ('data, 'tag) t -> ('data, 'tag) t * [ union_subtree ~prefix merger t1 ( path , t2 ) ] is equivalent to { ! : union } [ ~prefix merger t1 ( prefix path t2 ) ] , but potentially more efficient . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union_subtree : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> path * ('data, 'tag) t -> ('data, 'tag) t * [ union_singleton ~prefix merger t binding ] is equivalent to { ! : union } [ ~prefix merger t1 ( singleton binding ) ] , but potentially more efficient . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union_singleton : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> path * ('data * 'tag) -> ('data, 'tag) t * [ union_root ~prefix merger t r ] is equivalent to { ! : union_singleton } [ ~prefix merger t ( [ ] , r ) ] , but potentially more efficient . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). *) val union_root : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> ('data, 'tag) t -> 'data * 'tag -> ('data, 'tag) t * [ detach_subtree p t ] detaches the subtree at [ p ] from the main trie and returns both the subtree and the remaining trie ( in that order ) . If [ detach p t ] returns [ t1 , t2 ] , then { ! : } [ m t2 ( p , t1 ) ] should be equivalent to [ t ] . val detach_subtree : path -> ('data, 'tag) t -> ('data, 'tag) t * ('data, 'tag) t * [ detach_singleton p t ] detaches the binding at [ p ] from the main trie and returns both the binding and the remaining trie . If [ detach p t ] returns [ b , t ' ] , then { ! : } [ m t ' ( p , ] { ! : } [ b ) ] should be equivalent to [ t ] . val detach_singleton : path -> ('data, 'tag) t -> ('data * 'tag) option * ('data, 'tag) t * [ detach_root t ] detaches the binding at the root of and returns both the binding and the remaining trie . It is equivalent to { ! : detach_singleton } [ [ ] t ] . val detach_root : ('data, 'tag) t -> ('data * 'tag) option * ('data, 'tag) t val to_seq : ?prefix:bwd_path -> ('data, 'tag) t -> (path * ('data * 'tag)) Seq.t * [ to_seq_with_bwd_paths ] is like { ! : to_seq } , but with paths in the backward direction . This is potentially more efficient than { ! : to_seq } because the conversion from backward lists to forward lists is skipped . @param prefix The prefix prepended to any path in the output . The default is the empty prefix ( [ Emp ] ) . This is potentially more efficient than {!val:to_seq} because the conversion from backward lists to forward lists is skipped. @param prefix The prefix prepended to any path in the output. The default is the empty prefix ([Emp]). *) val to_seq_with_bwd_paths : ?prefix:bwd_path -> ('data, 'tag) t -> (bwd_path * ('data * 'tag)) Seq.t * [ to_seq_values t ] traverses through the trie [ t ] in the lexicographical order but only returns the associated data and tags . This is potentially more efficient than { ! : to_seq } because the conversion from backward lists to forward lists is skipped . val to_seq_values : ('data, 'tag) t -> ('data * 'tag) Seq.t * [ of_seq ~prefix s ] inserts bindings [ ( p , d ) ] into an empty trie , one by one , using { ! : union_singleton } . Later bindings will shadow previous ones if the paths of bindings are not unique . val of_seq : (path * ('data * 'tag)) Seq.t -> ('data, 'tag) t * [ of_seq_with_merger ~prefix merger s ] inserts bindings [ ( p , d ) ] into an empty trie , one by one , using { ! : union_singleton } . Bindings with the same path are resolved using [ merger ] instead of silent shadowing . @param prefix The prefix prepended to any path sent to [ merger ] . The default is the empty prefix ( [ Emp ] ) . Note that [ prefix ] does not directly affect the output trie , only the argument to [ merger ] . @param prefix The prefix prepended to any path sent to [merger]. The default is the empty prefix ([Emp]). Note that [prefix] does not directly affect the output trie, only the argument to [merger]. *) val of_seq_with_merger : ?prefix:bwd_path -> (bwd_path -> 'data * 'tag -> 'data * 'tag -> 'data * 'tag) -> (path * ('data * 'tag)) Seq.t -> ('data, 'tag) t type 'data untagged = ('data, unit) t val retag : 'tag -> ('data, _) t -> ('data, 'tag) t * [ retag_subtree tag path t ] changes all tags within the subtrie rooted at [ path ] to [ tag ] efficiently . The data remain intact . val retag_subtree : path -> 'tag -> ('data, 'tag) t -> ('data, 'tag) t * [ untag t ] is [ retag ( ) t ] . val untag : ('data, _) t -> 'data untagged * [ set_of_tags t ] returns the set of tags used in a trie , but as a [ Seq.t ] . val set_of_tags : ('tag -> 'tag -> int) -> ('data, 'tag) t -> 'tag Seq.t
0356135823902c7f367909cf64d44b8599ca1fcaf73de4c2f40d750ed3ce29a4
mirage/mirage-skeleton
config.ml
open Mirage let main = main "Unikernel.Main" (time @-> pclock @-> mclock @-> job) let () = register "speaking_clock" [ main $ default_time $ default_posix_clock $ default_monotonic_clock ]
null
https://raw.githubusercontent.com/mirage/mirage-skeleton/144d68992a284730c383eb3d39c409a061bc452e/device-usage/clock/config.ml
ocaml
open Mirage let main = main "Unikernel.Main" (time @-> pclock @-> mclock @-> job) let () = register "speaking_clock" [ main $ default_time $ default_posix_clock $ default_monotonic_clock ]
14920ae9cdbae3c9453edb4458b89b4916b689193732d503c7ed5302272b8c0e
spurious/snd-mirror
edit-menu.scm
;;; add some useful options to the Edit menu ;;; ;;; these used to be in the effects menu (provide 'snd-edit-menu.scm) (define edit-menu 1) ;;; -------- selection -> new file (define selection->new (let ((+documentation+ "(selection-<new) saves the selection in a new file, then opens that file")) (lambda () (and (selection?) (let ((new-file-name (snd-tempnam))) (save-selection new-file-name) (open-sound new-file-name)))))) pos=8 puts this in the selection section in the Edit menu ;;; -------- cut selection -> new file (define cut-selection->new (let ((+documentation+ "(cut-selection->new) saves the selection, deletes it, then opens the saved file")) (lambda () (and (selection?) (let ((new-file-name (snd-tempnam))) (save-selection new-file-name) (delete-selection) (open-sound new-file-name)))))) (add-to-menu edit-menu "Cut selection->new" cut-selection->new 9) ;;; -------- append selection (define append-selection (let ((+documentation+ "(append-selection) appends the current selection")) (lambda () (if (selection?) (insert-selection (framples)))))) (add-to-menu edit-menu "Append selection" append-selection 10) ;;; -------- make-stereofile (define (make-stereofile) (let* ((ofile-name (file-name)) (old-sound (selected-sound)) (nsnd (new-sound (string-append ofile-name ".stereo") 2 (srate) (sample-type) (header-type)))) (if (not nsnd) (begin (display "Could not make new sound.")(newline)) (begin (insert-sound ofile-name 0 0 nsnd 0) (insert-sound ofile-name 0 (if (> (channels old-sound) 1) 1 0) nsnd 1))))) (add-to-menu edit-menu "Make Stereofile" make-stereofile) ;;; -------- (add-to-menu edit-menu #f #f) -------- trim front and back ( goes by first or last mark ) (define trim-front (let ((+documentation+ "(trim-front) finds the first mark in each of the syncd channels and removes all samples before it") (trim-front-one-channel (lambda (snd chn) (if (null? (marks snd chn)) (status-report "trim-front needs a mark" snd) (delete-samples 0 (mark-sample (car (marks snd chn))) snd chn))))) (lambda () (let ((snc (sync))) (if (> snc 0) (apply map (lambda (snd chn) (if (= (sync snd) snc) (trim-front-one-channel snd chn))) (all-chans)) (trim-front-one-channel (or (selected-sound) (car (sounds))) (or (selected-channel) 0))))))) (add-to-menu edit-menu "Trim front" trim-front) (define trim-back (let ((+documentation+ "(trim-back) finds the last mark in each of the syncd channels and removes all samples after it") (trim-back-one-channel (lambda (snd chn) (if (null? (marks snd chn)) (status-report "trim-back needs a mark" snd) (let ((endpt (let ((ms (marks snd chn))) (mark-sample (list-ref ms (- (length ms) 1)))))) (delete-samples (+ endpt 1) (- (framples snd chn) endpt))))))) (lambda () (let ((snc (sync))) (if (> snc 0) (apply map (lambda (snd chn) (if (= (sync snd) snc) (trim-back-one-channel snd chn))) (all-chans)) (trim-back-one-channel (or (selected-sound) (car (sounds))) (or (selected-channel) 0))))))) (add-to-menu edit-menu "Trim back" trim-back) ;;; -------- crop (trims front and back) (define* (crop-one-channel snd chn) (if (< (length (marks snd chn)) 2) (status-report "crop needs start and end marks" snd) (as-one-edit (lambda () (delete-samples 0 (mark-sample (car (marks snd chn))) snd chn) (let ((endpt (let ((ms (marks snd chn))) (mark-sample (list-ref ms (- (length ms) 1)))))) (delete-samples (+ endpt 1) (- (framples snd chn) endpt)))) "crop-one-channel"))) (define crop (let ((+documentation+ "(crop) finds the first and last marks in each of the syncd channels and removes all samples outside them")) (lambda () (let ((snc (sync))) (if (> snc 0) (apply map (lambda (snd chn) (if (= (sync snd) snc) (crop-one-channel snd chn))) (all-chans)) (crop-one-channel (or (selected-sound) (car (sounds))) (or (selected-channel) 0))))))) (add-to-menu edit-menu "Crop" crop) ;;; -------- add these to the Edit menu, if possible (when (provided? 'xm) (with-let (sublet *motif*) (define (for-each-child w func) ;; (for-each-child w func) applies func to w and its descendents (func w) (if (XtIsComposite w) (for-each (lambda (n) (for-each-child n func)) (cadr (XtGetValues w (list XmNchildren 0) 1))))) (let* ((edit-cascade (list-ref (menu-widgets) 2)) (edit-menu (cadr (XtGetValues edit-cascade (list XmNsubMenuId 0))))) (XtAddCallback edit-cascade XmNcascadingCallback (lambda (w c i) (for-each-child edit-menu (lambda (child) (cond ((member (XtName child) '("Selection->new" "Cut selection->new" "Append selection") string=?) (XtSetSensitive child (selection?))) ((string=? (XtName child) "Crop") (XtSetSensitive child (and (selected-sound) (> (length (marks (selected-sound) (selected-channel))) 1)))) ((member (XtName child) '("Trim front" "Trim back") string=?) (XtSetSensitive child (and (selected-sound) (>= (length (marks (selected-sound) (selected-channel))) 1))))))))))))
null
https://raw.githubusercontent.com/spurious/snd-mirror/8e7a643c840592797c29384ffe07c87ba5c0a3eb/edit-menu.scm
scheme
add some useful options to the Edit menu these used to be in the effects menu -------- selection -> new file -------- cut selection -> new file -------- append selection -------- make-stereofile -------- -------- crop (trims front and back) -------- add these to the Edit menu, if possible (for-each-child w func) applies func to w and its descendents
(provide 'snd-edit-menu.scm) (define edit-menu 1) (define selection->new (let ((+documentation+ "(selection-<new) saves the selection in a new file, then opens that file")) (lambda () (and (selection?) (let ((new-file-name (snd-tempnam))) (save-selection new-file-name) (open-sound new-file-name)))))) pos=8 puts this in the selection section in the Edit menu (define cut-selection->new (let ((+documentation+ "(cut-selection->new) saves the selection, deletes it, then opens the saved file")) (lambda () (and (selection?) (let ((new-file-name (snd-tempnam))) (save-selection new-file-name) (delete-selection) (open-sound new-file-name)))))) (add-to-menu edit-menu "Cut selection->new" cut-selection->new 9) (define append-selection (let ((+documentation+ "(append-selection) appends the current selection")) (lambda () (if (selection?) (insert-selection (framples)))))) (add-to-menu edit-menu "Append selection" append-selection 10) (define (make-stereofile) (let* ((ofile-name (file-name)) (old-sound (selected-sound)) (nsnd (new-sound (string-append ofile-name ".stereo") 2 (srate) (sample-type) (header-type)))) (if (not nsnd) (begin (display "Could not make new sound.")(newline)) (begin (insert-sound ofile-name 0 0 nsnd 0) (insert-sound ofile-name 0 (if (> (channels old-sound) 1) 1 0) nsnd 1))))) (add-to-menu edit-menu "Make Stereofile" make-stereofile) (add-to-menu edit-menu #f #f) -------- trim front and back ( goes by first or last mark ) (define trim-front (let ((+documentation+ "(trim-front) finds the first mark in each of the syncd channels and removes all samples before it") (trim-front-one-channel (lambda (snd chn) (if (null? (marks snd chn)) (status-report "trim-front needs a mark" snd) (delete-samples 0 (mark-sample (car (marks snd chn))) snd chn))))) (lambda () (let ((snc (sync))) (if (> snc 0) (apply map (lambda (snd chn) (if (= (sync snd) snc) (trim-front-one-channel snd chn))) (all-chans)) (trim-front-one-channel (or (selected-sound) (car (sounds))) (or (selected-channel) 0))))))) (add-to-menu edit-menu "Trim front" trim-front) (define trim-back (let ((+documentation+ "(trim-back) finds the last mark in each of the syncd channels and removes all samples after it") (trim-back-one-channel (lambda (snd chn) (if (null? (marks snd chn)) (status-report "trim-back needs a mark" snd) (let ((endpt (let ((ms (marks snd chn))) (mark-sample (list-ref ms (- (length ms) 1)))))) (delete-samples (+ endpt 1) (- (framples snd chn) endpt))))))) (lambda () (let ((snc (sync))) (if (> snc 0) (apply map (lambda (snd chn) (if (= (sync snd) snc) (trim-back-one-channel snd chn))) (all-chans)) (trim-back-one-channel (or (selected-sound) (car (sounds))) (or (selected-channel) 0))))))) (add-to-menu edit-menu "Trim back" trim-back) (define* (crop-one-channel snd chn) (if (< (length (marks snd chn)) 2) (status-report "crop needs start and end marks" snd) (as-one-edit (lambda () (delete-samples 0 (mark-sample (car (marks snd chn))) snd chn) (let ((endpt (let ((ms (marks snd chn))) (mark-sample (list-ref ms (- (length ms) 1)))))) (delete-samples (+ endpt 1) (- (framples snd chn) endpt)))) "crop-one-channel"))) (define crop (let ((+documentation+ "(crop) finds the first and last marks in each of the syncd channels and removes all samples outside them")) (lambda () (let ((snc (sync))) (if (> snc 0) (apply map (lambda (snd chn) (if (= (sync snd) snc) (crop-one-channel snd chn))) (all-chans)) (crop-one-channel (or (selected-sound) (car (sounds))) (or (selected-channel) 0))))))) (add-to-menu edit-menu "Crop" crop) (when (provided? 'xm) (with-let (sublet *motif*) (define (for-each-child w func) (func w) (if (XtIsComposite w) (for-each (lambda (n) (for-each-child n func)) (cadr (XtGetValues w (list XmNchildren 0) 1))))) (let* ((edit-cascade (list-ref (menu-widgets) 2)) (edit-menu (cadr (XtGetValues edit-cascade (list XmNsubMenuId 0))))) (XtAddCallback edit-cascade XmNcascadingCallback (lambda (w c i) (for-each-child edit-menu (lambda (child) (cond ((member (XtName child) '("Selection->new" "Cut selection->new" "Append selection") string=?) (XtSetSensitive child (selection?))) ((string=? (XtName child) "Crop") (XtSetSensitive child (and (selected-sound) (> (length (marks (selected-sound) (selected-channel))) 1)))) ((member (XtName child) '("Trim front" "Trim back") string=?) (XtSetSensitive child (and (selected-sound) (>= (length (marks (selected-sound) (selected-channel))) 1))))))))))))
add20f6da4ac51858cb32329c0dc8a05c4e07754c9666b8c43d13107ff87ab70
lehins/Color
Alternative.hs
-- | Module : Graphics . Color . Space . RGB.Alternative Copyright : ( c ) 2019 - 2020 -- License : BSD3 Maintainer : < > -- Stability : experimental -- Portability : non-portable -- module Graphics.Color.Space.RGB.Alternative ( module X ) where import Graphics.Color.Space.Internal as X import Graphics.Color.Space.RGB.Internal as X import Graphics.Color.Space.RGB.Alternative.HSI as X import Graphics.Color.Space.RGB.Alternative.HSL as X import Graphics.Color.Space.RGB.Alternative.HSV as X import Graphics.Color.Space.RGB.Alternative.CMYK as X import Graphics.Color.Space.RGB.Alternative.YCbCr as X
null
https://raw.githubusercontent.com/lehins/Color/8f17d4d17dc9b899af702f54b69d49f3a5752e7b/Color/src/Graphics/Color/Space/RGB/Alternative.hs
haskell
| License : BSD3 Stability : experimental Portability : non-portable
Module : Graphics . Color . Space . RGB.Alternative Copyright : ( c ) 2019 - 2020 Maintainer : < > module Graphics.Color.Space.RGB.Alternative ( module X ) where import Graphics.Color.Space.Internal as X import Graphics.Color.Space.RGB.Internal as X import Graphics.Color.Space.RGB.Alternative.HSI as X import Graphics.Color.Space.RGB.Alternative.HSL as X import Graphics.Color.Space.RGB.Alternative.HSV as X import Graphics.Color.Space.RGB.Alternative.CMYK as X import Graphics.Color.Space.RGB.Alternative.YCbCr as X
9e6f7ce975c91212acd804846e02e411888527a15eb2cbeb300000adf3e2f50c
justinmeiners/exercises
1_9.scm
9 ; what is (define l '((kiwis mangoes lemons) and (more))) (print (car (cdr (cdr (car l))))) ; (more) ; wrong :( ; lemons (set! l '(() (eggs and (bacon)) (for) (breakfast))) (print (car (cdr (car (cdr l))))) ; and (set! l '(() () () (and (cofee)) please)) (print (car (cdr (cdr (cdr l))))) ; (and (coffee))
null
https://raw.githubusercontent.com/justinmeiners/exercises/9491bc16925eae12e048ccd3f424b870ebdc73aa/the-little-lisper/1/1_9.scm
scheme
what is (more) wrong :( lemons and (and (coffee))
9 (define l '((kiwis mangoes lemons) and (more))) (print (car (cdr (cdr (car l))))) (set! l '(() (eggs and (bacon)) (for) (breakfast))) (print (car (cdr (car (cdr l))))) (set! l '(() () () (and (cofee)) please)) (print (car (cdr (cdr (cdr l)))))
de897d6ced13699dc77bd976e1cee47d939855e1516e71ad2fd1eaac2537fe8a
mhuebert/maria
format.cljc
(ns lark.tree.format (:require [clojure.string :as str] [lark.tree.reader :as rd] [lark.tree.node :as n] [lark.tree.util :as util] [lark.tree.range :as range] [fast-zip.core :as z])) (def SPACES (str/join (take 200 (repeat " ")))) (defn spaces [n] (subs SPACES 0 n)) (def ^:dynamic *pretty* false) (defn emit-space? [loc] (and (some? (z/left loc)) (some? (z/right loc)) (not (n/newline? (some-> (z/left loc) (z/node)))))) (defn indentation-for [x] (case x ("bound-fn" "extend" "extend-protocol" "extend-type" "fn" "ns" "reify") :indent ("cond" "do" "finally" "try" "with-out-str" "go") 0 ("assoc" "apply" "binding" "case" "definterface" "defstruct" "deftype" "doseq" "dotimes" "doto" "for" "if" "if-let" "if-not" "if-some" "let" "letfn" "locking" "loop" "struct-map" "when" "when-first" "when-let" "when-not" "when-some" "while" "with-bindings" "with-local-vars" "with-open" "with-redefs" "with-redefs-fn" "go-loop" "are" "deftest" "testing") 1 ("catch" "condp" "proxy") 2 (cond (str/starts-with? x "def") :indent (re-find #"with|when|if" x) 1 ( str / ends - with ? x " - > " ) 1 :else 0))) (defn threading-node? [node] (when-let [operator (and (= (.-tag node) :list) (some-> node (.-children) (first)))] (and (= :token (.-tag operator)) (str/ends-with? (.-value operator) "->")))) (defn node-length [{:as node :keys [column end-column tag value]}] (case tag :space (if (= node rd/*active-cursor-node*) (count value) 1) :tab 1 (:cursor :selection) 0 (- end-column column))) (defn whitespace-tag? [t] (util/contains-identical-keyword? [:space :cursor :selection :tab :newline] t)) (defn butlast-vec [v] (cond-> v (not (empty? v)) (pop))) (defn body-indent* ([indent-level node] (body-indent* indent-level node nil)) ([indent-level loc child] (assert (number? indent-level)) (let [node (.-node loc) tag (.-tag node) children (.-children node) operator (first children) threading? (and (= tag :list) (some-> (z/up loc) (.-node) (threading-node?)))] (if (and (= :list tag) operator (= :token (.-tag operator))) (let [indent-type (indentation-for (name (.-value operator)))] (case indent-type :indent (+ indent-level 1) (let [indent-offset (-> indent-type (cond-> threading? (dec))) split-after (+ 2 indent-offset) [exact? taken _ num-passed] (->> (cond-> children (n/whitespace? operator) (butlast-vec)) (rd/split-after-n split-after n/sexp? (fn [node] (or (= :newline (.-tag node)) (= node child)))))] (+ indent-level (cond exact? (reduce + 0 (mapv node-length (pop taken))) (and (= num-passed 1) (not threading?)) 0 :else 1))))) (+ indent-level))))) (defn indentation-parent? [node] (util/contains-identical-keyword? [:vector :list :map] (.-tag node))) (defn body-indent-string [pos child-loc] (if-let [coll-loc (->> (iterate z/up child-loc) (sequence (comp (take-while identity) (filter #(range/within-inner? (z/node %) pos)) (filter (comp indentation-parent? z/node)))) (first))] (let [coll-node (z/node coll-loc)] (let [child (z/node child-loc) left-edge-width (count (first (get rd/edges (.-tag coll-node)))) body-indent (+ left-edge-width (body-indent* (:column coll-node) coll-loc child))] (spaces body-indent))) 0)) (defn pad-chars? "Returns true if space should be left inbetween characters c1 and c2." [c1 c2] (if (or (rd/close-bracket? c2) (rd/open-bracket? c1) (rd/prefix-boundary? c1) (= \# c1)) false true))
null
https://raw.githubusercontent.com/mhuebert/maria/15586564796bc9273ace3101b21662d0c66b4d22/editor/vendor/lark/tree/format.cljc
clojure
(ns lark.tree.format (:require [clojure.string :as str] [lark.tree.reader :as rd] [lark.tree.node :as n] [lark.tree.util :as util] [lark.tree.range :as range] [fast-zip.core :as z])) (def SPACES (str/join (take 200 (repeat " ")))) (defn spaces [n] (subs SPACES 0 n)) (def ^:dynamic *pretty* false) (defn emit-space? [loc] (and (some? (z/left loc)) (some? (z/right loc)) (not (n/newline? (some-> (z/left loc) (z/node)))))) (defn indentation-for [x] (case x ("bound-fn" "extend" "extend-protocol" "extend-type" "fn" "ns" "reify") :indent ("cond" "do" "finally" "try" "with-out-str" "go") 0 ("assoc" "apply" "binding" "case" "definterface" "defstruct" "deftype" "doseq" "dotimes" "doto" "for" "if" "if-let" "if-not" "if-some" "let" "letfn" "locking" "loop" "struct-map" "when" "when-first" "when-let" "when-not" "when-some" "while" "with-bindings" "with-local-vars" "with-open" "with-redefs" "with-redefs-fn" "go-loop" "are" "deftest" "testing") 1 ("catch" "condp" "proxy") 2 (cond (str/starts-with? x "def") :indent (re-find #"with|when|if" x) 1 ( str / ends - with ? x " - > " ) 1 :else 0))) (defn threading-node? [node] (when-let [operator (and (= (.-tag node) :list) (some-> node (.-children) (first)))] (and (= :token (.-tag operator)) (str/ends-with? (.-value operator) "->")))) (defn node-length [{:as node :keys [column end-column tag value]}] (case tag :space (if (= node rd/*active-cursor-node*) (count value) 1) :tab 1 (:cursor :selection) 0 (- end-column column))) (defn whitespace-tag? [t] (util/contains-identical-keyword? [:space :cursor :selection :tab :newline] t)) (defn butlast-vec [v] (cond-> v (not (empty? v)) (pop))) (defn body-indent* ([indent-level node] (body-indent* indent-level node nil)) ([indent-level loc child] (assert (number? indent-level)) (let [node (.-node loc) tag (.-tag node) children (.-children node) operator (first children) threading? (and (= tag :list) (some-> (z/up loc) (.-node) (threading-node?)))] (if (and (= :list tag) operator (= :token (.-tag operator))) (let [indent-type (indentation-for (name (.-value operator)))] (case indent-type :indent (+ indent-level 1) (let [indent-offset (-> indent-type (cond-> threading? (dec))) split-after (+ 2 indent-offset) [exact? taken _ num-passed] (->> (cond-> children (n/whitespace? operator) (butlast-vec)) (rd/split-after-n split-after n/sexp? (fn [node] (or (= :newline (.-tag node)) (= node child)))))] (+ indent-level (cond exact? (reduce + 0 (mapv node-length (pop taken))) (and (= num-passed 1) (not threading?)) 0 :else 1))))) (+ indent-level))))) (defn indentation-parent? [node] (util/contains-identical-keyword? [:vector :list :map] (.-tag node))) (defn body-indent-string [pos child-loc] (if-let [coll-loc (->> (iterate z/up child-loc) (sequence (comp (take-while identity) (filter #(range/within-inner? (z/node %) pos)) (filter (comp indentation-parent? z/node)))) (first))] (let [coll-node (z/node coll-loc)] (let [child (z/node child-loc) left-edge-width (count (first (get rd/edges (.-tag coll-node)))) body-indent (+ left-edge-width (body-indent* (:column coll-node) coll-loc child))] (spaces body-indent))) 0)) (defn pad-chars? "Returns true if space should be left inbetween characters c1 and c2." [c1 c2] (if (or (rd/close-bracket? c2) (rd/open-bracket? c1) (rd/prefix-boundary? c1) (= \# c1)) false true))
8bbe9778aa86ae53a97fedc257f7113b396ceebc2c6e04b42225ab5e403faaa0
robert-stuttaford/bridge
schema.clj
(ns bridge.event.schema) (def schema [#:db{:ident :event/id :cardinality :db.cardinality/one :valueType :db.type/uuid :unique :db.unique/value} #:db{:ident :event/title :cardinality :db.cardinality/one :valueType :db.type/string} #:db{:ident :event/slug :cardinality :db.cardinality/one :valueType :db.type/string :unique :db.unique/value} #:db{:ident :event/status :cardinality :db.cardinality/one :valueType :db.type/keyword} #:db{:ident :event/chapter :cardinality :db.cardinality/one :valueType :db.type/ref :doc "ref to :chapter"} #:db{:ident :event/organisers :cardinality :db.cardinality/many :valueType :db.type/ref :doc "ref to :person"} #:db{:ident :event/start-date :cardinality :db.cardinality/one :valueType :db.type/instant} #:db{:ident :event/end-date :cardinality :db.cardinality/one :valueType :db.type/instant} #:db{:ident :event/registration-close-date :cardinality :db.cardinality/one :valueType :db.type/instant} #:db{:ident :event/details-markdown :cardinality :db.cardinality/one :valueType :db.type/string} #:db{:ident :event/notes-markdown :cardinality :db.cardinality/one :valueType :db.type/string}])
null
https://raw.githubusercontent.com/robert-stuttaford/bridge/867d81354457c600cc5c25917de267a8e267c853/src/bridge/event/schema.clj
clojure
(ns bridge.event.schema) (def schema [#:db{:ident :event/id :cardinality :db.cardinality/one :valueType :db.type/uuid :unique :db.unique/value} #:db{:ident :event/title :cardinality :db.cardinality/one :valueType :db.type/string} #:db{:ident :event/slug :cardinality :db.cardinality/one :valueType :db.type/string :unique :db.unique/value} #:db{:ident :event/status :cardinality :db.cardinality/one :valueType :db.type/keyword} #:db{:ident :event/chapter :cardinality :db.cardinality/one :valueType :db.type/ref :doc "ref to :chapter"} #:db{:ident :event/organisers :cardinality :db.cardinality/many :valueType :db.type/ref :doc "ref to :person"} #:db{:ident :event/start-date :cardinality :db.cardinality/one :valueType :db.type/instant} #:db{:ident :event/end-date :cardinality :db.cardinality/one :valueType :db.type/instant} #:db{:ident :event/registration-close-date :cardinality :db.cardinality/one :valueType :db.type/instant} #:db{:ident :event/details-markdown :cardinality :db.cardinality/one :valueType :db.type/string} #:db{:ident :event/notes-markdown :cardinality :db.cardinality/one :valueType :db.type/string}])
f9b5595088765a56f47f1eb9f510d34a20d18c11c2eb86e972965abb816e859d
samrushing/irken-compiler
t_halloc.scm
;; -*- Mode: Irken -*- (include "lib/basis.scm") (include "lib/map.scm") (require-ffi 'posix) (define (get-cstring p) (%cref->string #f p (posix/strlen p))) (let ((utsname0 (halloc (struct utsname))) (utsname1 (malloc (struct utsname)))) (posix/uname utsname0) (posix/uname utsname1) (printf (string (get-cstring (%c-sref utsname.nodename utsname0))) "\n") (printf (string (get-cstring (%c-sref utsname.nodename utsname1))) "\n") (printf (string (get-cstring (%c-sref utsname.sysname utsname0))) "\n") (printf (string (get-cstring (%c-sref utsname.sysname utsname1))) "\n") (free utsname1) )
null
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/ffi/tests/t_halloc.scm
scheme
-*- Mode: Irken -*-
(include "lib/basis.scm") (include "lib/map.scm") (require-ffi 'posix) (define (get-cstring p) (%cref->string #f p (posix/strlen p))) (let ((utsname0 (halloc (struct utsname))) (utsname1 (malloc (struct utsname)))) (posix/uname utsname0) (posix/uname utsname1) (printf (string (get-cstring (%c-sref utsname.nodename utsname0))) "\n") (printf (string (get-cstring (%c-sref utsname.nodename utsname1))) "\n") (printf (string (get-cstring (%c-sref utsname.sysname utsname0))) "\n") (printf (string (get-cstring (%c-sref utsname.sysname utsname1))) "\n") (free utsname1) )
5f7d69b50859883def3f78fb9181d6a9f3bb7e0214e2c8ba8f6487bff9ae392b
gafiatulin/codewars
Person.hs
-- Broken Greetings -- module Person where data Person = Person { name :: String } greet :: Person -> String -> String greet person otherName = "Hi " ++ otherName ++ ", my name is " ++ name person
null
https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/8%20kyu/Person.hs
haskell
Broken Greetings
module Person where data Person = Person { name :: String } greet :: Person -> String -> String greet person otherName = "Hi " ++ otherName ++ ", my name is " ++ name person
a54a1dc8e9a75f35c9d39b61af1ef0fd9494298cd58cc2a50705c502cf109504
logicmoo/logicmoo_nlu
paip-prolog.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- Code from Paradigms of AI Programming Copyright ( c ) 1991 ;;; File auxfns.lisp: Auxiliary functions used by all other programs ;;; Load this file before running any other programs. ;;(in-package "USER") ;;;; Implementation-Specific Details ;; #+:COMMON-LISP (eval-when (eval compile load) ;; Make it ok to place a function definition on a built-in LISP symbol. #+(or Allegro EXCL) (dolist (pkg '(excl common-lisp common-lisp-user)) (setf (excl:package-definition-lock (find-package pkg)) nil)) ;; Don't warn if a function is defined in multiple files -- ;; this happens often since we refine several programs. #+Lispworks (setq *PACKAGES-FOR-WARN-ON-REDEFINITION* nil) #+LCL (compiler-options :warnings nil) ) ;;;; REQUIRES ;;; The function REQUIRES is used in subsequent files to state dependencies ;;; between files. The current definition just loads the required files, ;;; assumming they match the pathname specified in *PAIP-DIRECTORY*. ;;; You should change that to match where you have stored the files. ;;; A more sophisticated REQUIRES would only load it if it has not yet ;;; been loaded, and would search in different directories if needed. (defun requires (&rest files) "The arguments are files that are required to run an application." (mapc #'load-paip-file files)) (defvar *paip-files* `("auxfns" "tutor" "examples" "intro" "simple" "overview" "gps1" "gps" "eliza1" "eliza" "patmatch" "eliza-pm" "search" "gps-srch" "student" "macsyma" "macsymar" "unify" "prolog1" "prolog" "prologc1" "prologc2" "prologc" "prologcp" "clos" "krep1" "krep2" "krep" "cmacsyma" "mycin" "mycin-r" "waltz" "othello" "othello2" "syntax1" "syntax2" "syntax3" "unifgram" "grammar" "lexicon" "interp1" "interp2" "interp3" "compile1" "compile2" "compile3" "compopt")) (defparameter *paip-directory* (make-pathname :name nil :type nil :defaults (or (and (boundp '*load-truename*) *load-truename*) (truename ""))) ;;??? Maybe Change this "The location of the source files for this book. If things don't work, change it to reflect the location of the files on your computer.") (defparameter *paip-source* (make-pathname :name nil :type "lisp" ;;??? Maybe Change this :defaults *paip-directory*)) (defparameter *paip-binary* (make-pathname :name nil :type (first (list #+LCL (first *load-binary-pathname-types*) #+Lispworks system::*binary-file-type* #+MCL "fasl" #+Allegro excl:*fasl-default-type* #+(or AKCL KCL) "o" #+CMU "sparcf" #+CLISP "fas" "bin")) ;;??? Maybe Change this :directory (append (pathname-directory *paip-source*) '("bin")) :defaults *paip-directory*)) (defun paip-pathname (name &optional (type :lisp)) (make-pathname :name name :defaults (ecase type ((:lisp :source) *paip-source*) ((:binary :bin) *paip-binary*)))) (defun compile-all-paip-files () (mapc #'compile-paip-file *paip-files*)) (defun compile-paip-file (name) (let ((path (paip-pathname name :lisp))) (load path) (compile-file path :output-file (paip-pathname name :binary)))) (defun load-paip-file (file) "Load the binary file if it exists and is newer, else load the source." (let* ((src (paip-pathname file :lisp)) (src-date (file-write-date src)) (bin (paip-pathname file :binary)) (bin-date (file-write-date bin))) (load (if (and (probe-file bin) src-date bin-date (>= bin-date src-date)) bin src)))) Macros ( formerly in auxmacs.lisp : that file no longer needed ) ;;(in-package :LISP) (eval-when (load eval compile) (defmacro once-only (variables &rest body) "Returns the code built by BODY. If any of VARIABLES might have side effects, they are evaluated once and stored in temporary variables that are then passed to BODY." (assert (every #'symbolp variables)) (let ((temps nil)) (dotimes (i (length variables)) (push (gensym) temps)) `(if (every #'side-effect-free? (list .,variables)) (progn .,body) (list 'let ,`(list ,@(mapcar #'(lambda (tmp var) `(list ',tmp ,var)) temps variables)) (let ,(mapcar #'(lambda (var tmp) `(,var ',tmp)) variables temps) .,body))))) (defun side-effect-free? (exp) "Is exp a constant, variable, or function, or of the form (THE type x) where x is side-effect-free?" (or (atom exp) (constantp exp) (starts-with exp 'function) (and (starts-with exp 'the) (side-effect-free? (third exp))))) (defmacro funcall-if (fn arg) (once-only (fn) `(if ,fn (funcall ,fn ,arg) ,arg))) (defmacro read-time-case (first-case &rest other-cases) "Do the first case, where normally cases are specified with #+ or possibly #- marks." (declare (ignore other-cases)) first-case) (defun rest2 (x) "The rest of a list after the first TWO elements." (rest (rest x))) (defun find-anywhere (item tree) "Does item occur anywhere in tree?" (if (atom tree) (if (eql item tree) tree) (or (find-anywhere item (first tree)) (find-anywhere item (rest tree))))) (defun starts-with (list x) "Is x a list whose first element is x?" (and (consp list) (eql (first list) x))) ) ;;;; Auxiliary Functions (setf (symbol-function 'find-all-if) #'remove-if-not) (defun find-all (item sequence &rest keyword-args &key (test #'eql) test-not &allow-other-keys) "Find all those elements of sequence that match item, according to the keywords. Doesn't alter sequence." (if test-not (apply #'remove item sequence :test-not (complement test-not) keyword-args) (apply #'remove item sequence :test (complement test) keyword-args))) (defun partition-if (pred list) "Return 2 values: elements of list that satisfy pred, and elements that don't." (let ((yes-list nil) (no-list nil)) (dolist (item list) (if (funcall pred item) (push item yes-list) (push item no-list))) (values (nreverse yes-list) (nreverse no-list)))) (defun maybe-add (op exps &optional if-nil) "For example, (maybe-add 'and exps t) returns t if exps is nil, exps if there is only one, and (and exp1 exp2...) if there are several exps." (cond ((null exps) if-nil) ((length=1 exps) (first exps)) (t (cons op exps)))) ;;; ============================== (defun seq-ref (seq index) "Return code that indexes into a sequence, using the pop-lists/aref-vectors strategy." `(if (listp ,seq) (prog1 (first ,seq) (setq ,seq (the list (rest ,seq)))) (aref ,seq ,index))) (defun maybe-set-fill-pointer (array new-length) "If this is an array with a fill pointer, set it to new-length, if that is longer than the current length." (if (and (arrayp array) (array-has-fill-pointer-p array)) (setf (fill-pointer array) (max (fill-pointer array) new-length)))) ;;; ============================== ;;; NOTE: In ANSI Common Lisp, the effects of adding a definition (or most ;;; anything else) to a symbol in the common-lisp package is undefined. ;;; Therefore, it would be best to rename the function SYMBOL to something ;;; else. This has not been done (for compatibility with the book). (defun symbol (&rest args) "Concatenate symbols or strings to form an interned symbol" (intern (format nil "~{~a~}" args))) (defun new-symbol (&rest args) "Concatenate symbols or strings to form an uninterned symbol" (make-symbol (format nil "~{~a~}" args))) (defun last1 (list) "Return the last element (not last cons cell) of list" (first (last list))) ;;; ============================== (defun mappend (fn list) "Append the results of calling fn on each element of list. Like mapcon, but uses append instead of nconc." (apply #'append (mapcar fn list))) (defun mklist (x) "If x is a list return it, otherwise return the list of x" (if (listp x) x (list x))) (defun flatten (exp) "Get rid of imbedded lists (to one level only)." (mappend #'mklist exp)) (defun random-elt (seq) "Pick a random element out of a sequence." (elt seq (random (length seq)))) ;;; ============================== (defun member-equal (item list) (member item list :test #'equal)) ;;; ============================== (defun compose (&rest functions) #'(lambda (x) (reduce #'funcall functions :from-end t :initial-value x))) The Debugging Output Facility : (defvar *dbg-ids* nil "Identifiers used by dbg") (defun dbg (id format-string &rest args) "Print debugging info if (DEBUG ID) has been specified." (when (member id *dbg-ids*) (fresh-line *debug-io*) (apply #'format *debug-io* format-string args))) (defun debug (&rest ids) "Start dbg output on the given ids." (setf *dbg-ids* (union ids *dbg-ids*))) (defun undebug (&rest ids) "Stop dbg on the ids. With no ids, stop dbg altogether." (setf *dbg-ids* (if (null ids) nil (set-difference *dbg-ids* ids)))) ;;; ============================== (defun dbg-indent (id indent format-string &rest args) "Print indented debugging info if (DEBUG ID) has been specified." (when (member id *dbg-ids*) (fresh-line *debug-io*) (dotimes (i indent) (princ " " *debug-io*)) (apply #'format *debug-io* format-string args))) ;;;; PATTERN MATCHING FACILITY (defconstant fail nil) (defconstant no-bindings '((t . t))) (defun pat-match (pattern input &optional (bindings no-bindings)) "Match pattern against input in the context of the bindings" (cond ((eq bindings fail) fail) ((variable-p pattern) (match-variable pattern input bindings)) ((eql pattern input) bindings) ((and (consp pattern) (consp input)) (pat-match (rest pattern) (rest input) (pat-match (first pattern) (first input) bindings))) (t fail))) (defun match-variable (var input bindings) "Does VAR match input? Uses (or updates) and returns bindings." (let ((binding (get-binding var bindings))) (cond ((not binding) (extend-bindings var input bindings)) ((equal input (binding-val binding)) bindings) (t fail)))) (defun make-binding (var val) (cons var val)) (defun binding-var (binding) "Get the variable part of a single binding." (car binding)) (defun binding-val (binding) "Get the value part of a single binding." (cdr binding)) (defun get-binding (var bindings) "Find a (variable . value) pair in a binding list." (assoc var bindings)) (defun lookup (var bindings) "Get the value part (for var) from a binding list." (binding-val (get-binding var bindings))) (defun extend-bindings (var val bindings) "Add a (var . value) pair to a binding list." (cons (cons var val) ;; Once we add a "real" binding, ;; we can get rid of the dummy no-bindings (if (eq bindings no-bindings) nil bindings))) (defun variable-p (x) "Is x a variable (a symbol beginning with `?')?" (and (symbolp x) (equal (elt (symbol-name x) 0) #\?))) ;;; ============================== The Memoization facility : (defmacro defun-memo (fn args &body body) "Define a memoized function." `(memoize (defun ,fn ,args . ,body))) (defun memo (fn &key (key #'first) (test #'eql) name) "Return a memo-function of fn." (let ((table (make-hash-table :test test))) (setf (get name 'memo) table) #'(lambda (&rest args) (let ((k (funcall key args))) (multiple-value-bind (val found-p) (gethash k table) (if found-p val (setf (gethash k table) (apply fn args)))))))) (defun memoize (fn-name &key (key #'first) (test #'eql)) "Replace fn-name's global definition with a memoized version." (clear-memoize fn-name) (setf (symbol-function fn-name) (memo (symbol-function fn-name) :name fn-name :key key :test test))) (defun clear-memoize (fn-name) "Clear the hash table from a memo function." (let ((table (get fn-name 'memo))) (when table (clrhash table)))) ;;;; Delayed computation: (defstruct delay value (computed? nil)) (defmacro delay (&rest body) "A computation that can be executed later by FORCE." `(make-delay :value #'(lambda () . ,body))) (defun force (delay) "Do a delayed computation, or fetch its previously-computed value." (if (delay-computed? delay) (delay-value delay) (prog1 (setf (delay-value delay) (funcall (delay-value delay))) (setf (delay-computed? delay) t)))) Defresource : (defmacro defresource (name &key constructor (initial-copies 0) (size (max initial-copies 10))) (let ((resource (symbol '* (symbol name '-resource*))) (deallocate (symbol 'deallocate- name)) (allocate (symbol 'allocate- name))) `(progn (defparameter ,resource (make-array ,size :fill-pointer 0)) (defun ,allocate () "Get an element from the resource pool, or make one." (if (= (fill-pointer ,resource) 0) ,constructor (vector-pop ,resource))) (defun ,deallocate (,name) "Place a no-longer-needed element back in the pool." (vector-push-extend ,name ,resource)) ,(if (> initial-copies 0) `(mapc #',deallocate (loop repeat ,initial-copies collect (,allocate)))) ',name))) (defmacro with-resource ((var resource &optional protect) &rest body) "Execute body with VAR bound to an instance of RESOURCE." (let ((allocate (symbol 'allocate- resource)) (deallocate (symbol 'deallocate- resource))) (if protect `(let ((,var nil)) (unwind-protect (progn (setf ,var (,allocate)) ,@body) (unless (null ,var) (,deallocate ,var)))) `(let ((,var (,allocate))) ,@body (,deallocate var))))) Queues : ;;; A queue is a (last . contents) pair (defun queue-contents (q) (cdr q)) (defun make-queue () "Build a new queue, with no elements." (let ((q (cons nil nil))) (setf (car q) q))) (defun enqueue (item q) "Insert item at the end of the queue." (setf (car q) (setf (rest (car q)) (cons item nil))) q) (defun dequeue (q) "Remove an item from the front of the queue." (pop (cdr q)) (if (null (cdr q)) (setf (car q) q)) q) (defun front (q) (first (queue-contents q))) (defun empty-queue-p (q) (null (queue-contents q))) (defun queue-nconc (q list) "Add the elements of LIST to the end of the queue." (setf (car q) (last (setf (rest (car q)) list)))) ;;;; Other: (defun sort* (seq pred &key key) "Sort without altering the sequence" (sort (copy-seq seq) pred :key key)) (defun reuse-cons (x y x-y) "Return (cons x y), or reuse x-y if it is equal to (cons x y)" (if (and (eql x (car x-y)) (eql y (cdr x-y))) x-y (cons x y))) ;;; ============================== (defun length=1 (x) "Is x a list of length 1?" (and (consp x) (null (cdr x)))) (defun rest3 (list) "The rest of a list after the first THREE elements." (cdddr list)) ;;; ============================== (defun unique-find-if-anywhere (predicate tree &optional found-so-far) "Return a list of leaves of tree satisfying predicate, with duplicates removed." (if (atom tree) (if (funcall predicate tree) (adjoin tree found-so-far) found-so-far) (unique-find-if-anywhere predicate (first tree) (unique-find-if-anywhere predicate (rest tree) found-so-far)))) (defun find-if-anywhere (predicate tree) "Does predicate apply to any atom in the tree?" (if (atom tree) (funcall predicate tree) (or (find-if-anywhere predicate (first tree)) (find-if-anywhere predicate (rest tree))))) ;;; ============================== (defmacro define-enumerated-type (type &rest elements) "Represent an enumerated type with integers 0-n." `(progn (deftype ,type () '(integer 0 ,(- (length elements) 1))) (defun ,(symbol type '->symbol) (,type) (elt ',elements ,type)) (defun ,(symbol 'symbol-> type) (symbol) (position symbol ',elements)) ,@(loop for element in elements for i from 0 collect `(defconstant ,element ,i)))) ;;; ============================== (defun not-null (x) (not (null x))) (defun first-or-nil (x) "The first element of x if it is a list; else nil." (if (consp x) (first x) nil)) (defun first-or-self (x) "The first element of x, if it is a list; else x itself." (if (consp x) (first x) x)) ;;; ============================== ;;;; CLtL2 and ANSI CL Compatibility (unless (fboundp 'defmethod) (defmacro defmethod (name args &rest body) `(defun ',name ',args ,@body)) ) (unless (fboundp 'map-into) (defun map-into (result-sequence function &rest sequences) "Destructively set elements of RESULT-SEQUENCE to the results of applying FUNCTION to respective elements of SEQUENCES." (let ((arglist (make-list (length sequences))) (n (if (listp result-sequence) most-positive-fixnum (array-dimension result-sequence 0)))) ;; arglist is made into a list of args for each call ;; n is the length of the longest vector (when sequences (setf n (min n (loop for seq in sequences minimize (length seq))))) ;; Define some shared functions: (flet ((do-one-call (i) (loop for seq on sequences for arg on arglist do (if (listp (first seq)) (setf (first arg) (pop (first seq))) (setf (first arg) (aref (first seq) i)))) (apply function arglist)) (do-result (i) (if (and (vectorp result-sequence) (array-has-fill-pointer-p result-sequence)) (setf (fill-pointer result-sequence) (max i (fill-pointer result-sequence)))))) (declare (inline do-one-call)) ;; Decide if the result is a list or vector, ;; and loop through each element (if (listp result-sequence) (loop for i from 0 to (- n 1) for r on result-sequence do (setf (first r) (do-one-call i)) finally (do-result i)) (loop for i from 0 to (- n 1) do (setf (aref result-sequence i) (do-one-call i)) finally (do-result i)))) result-sequence)) ) (unless (fboundp 'complement) (defun complement (fn) "If FN returns y, then (complement FN) returns (not y)." #'(lambda (&rest args) (not (apply fn args)))) ) (unless (fboundp 'with-compilation-unit) (defmacro with-compilation-unit (options &body body) "Do the body, but delay compiler warnings until the end." ;; That way, undefined function warnings that are really ;; just forward references will not be printed at all. This is defined in Common Lisp the Language , 2nd ed . (declare (ignore options)) `(,(read-time-case #+Lispm 'compiler:compiler-warnings-context-bind #+Lucid 'with-deferred-warnings 'progn) .,body)) ) ;;;; Reduce (when nil ;; Change this to T if you need REDUCE with :key keyword. (defun reduce* (fn seq from-end start end key init init-p) (funcall (if (listp seq) #'reduce-list #'reduce-vect) fn seq from-end (or start 0) end key init init-p)) (defun reduce (function sequence &key from-end start end key (initial-value nil initial-value-p)) (reduce* function sequence from-end start end key initial-value initial-value-p)) (defun reduce-vect (fn seq from-end start end key init init-p) (if (null end) (setf end (length seq))) (assert (<= 0 start end (length seq)) (start end) "Illegal subsequence of ~a --- :start ~d :end ~d" seq start end) (case (- end start) (1 (if init-p (funcall fn init (funcall-if key (aref seq start))) (funcall-if key (aref seq start)))) (0 (if init-p init (funcall fn))) (t (if (not from-end) (let ((result (if init-p (funcall fn init (funcall-if key (aref seq start))) (funcall fn (funcall-if key (aref seq start)) (funcall-if key (aref seq (+ start 1))))))) (loop for i from (+ start (if init-p 1 2)) to (- end 1) do (setf result (funcall fn result (funcall-if key (aref seq i))))) result) (let ((result (if init-p (funcall fn (funcall-if key (aref seq (- end 1))) init) (funcall fn (funcall-if key (aref seq (- end 2))) (funcall-if key (aref seq (- end 1))))))) (loop for i from (- end (if init-p 2 3)) downto start do (setf result (funcall fn (funcall-if key (aref seq i)) result))) result))))) (defun reduce-list (fn seq from-end start end key init init-p) (if (null end) (setf end (length seq))) (cond ((> start 0) (reduce-list fn (nthcdr start seq) from-end 0 (- end start) key init init-p)) ((or (null seq) (eql start end)) (if init-p init (funcall fn))) ((= (- end start) 1) (if init-p (funcall fn init (funcall-if key (first seq))) (funcall-if key (first seq)))) (from-end (reduce-vect fn (coerce seq 'vector) t start end key init init-p)) ((null (rest seq)) (if init-p (funcall fn init (funcall-if key (first seq))) (funcall-if key (first seq)))) (t (let ((result (if init-p (funcall fn init (funcall-if key (pop seq))) (funcall fn (funcall-if key (pop seq)) (funcall-if key (pop seq)))))) (if end (loop repeat (- end (if init-p 1 2)) while seq do (setf result (funcall fn result (funcall-if key (pop seq))))) (loop while seq do (setf result (funcall fn result (funcall-if key (pop seq)))))) result)))) ) (defun do-s (words) (top-level-prove `((S ?sem ,words ())))) (if (boundp 'clear-db) (clear-db)) ;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- Code from Paradigms of AI Programming Copyright ( c ) 1991 ;;;; File pat-match.lisp: Pattern matcher from section 6.2 Two bug fixes By , October 92 . ;;; The basic are in auxfns.lisp; look for "PATTERN MATCHING FACILITY" (defun variable-p (x) "Is x a variable (a symbol beginning with `?')?" (and (symbolp x) (equal (elt (symbol-name x) 0) #\?))) (defun pat-match (pattern input &optional (bindings no-bindings)) "Match pattern against input in the context of the bindings" (cond ((eq bindings fail) fail) ((variable-p pattern) (match-variable pattern input bindings)) ((eql pattern input) bindings) ((segment-pattern-p pattern) (segment-matcher pattern input bindings)) ((single-pattern-p pattern) ; *** (single-matcher pattern input bindings)) ; *** ((and (consp pattern) (consp input)) (pat-match (rest pattern) (rest input) (pat-match (first pattern) (first input) bindings))) (t fail))) (setf (get '?is 'single-match) 'match-is) (setf (get '?or 'single-match) 'match-or) (setf (get '?and 'single-match) 'match-and) (setf (get '?not 'single-match) 'match-not) (setf (get '?* 'segment-match) 'segment-match) (setf (get '?+ 'segment-match) 'segment-match+) (setf (get '?? 'segment-match) 'segment-match?) (setf (get '?if 'segment-match) 'match-if) (defun segment-pattern-p (pattern) "Is this a segment-matching pattern like ((?* var) . pat)?" (and (consp pattern) (consp (first pattern)) (symbolp (first (first pattern))) (segment-match-fn (first (first pattern))))) (defun single-pattern-p (pattern) "Is this a single-matching pattern? E.g. (?is x predicate) (?and . patterns) (?or . patterns)." (and (consp pattern) (single-match-fn (first pattern)))) (defun segment-matcher (pattern input bindings) "Call the right function for this kind of segment pattern." (funcall (segment-match-fn (first (first pattern))) pattern input bindings)) (defun single-matcher (pattern input bindings) "Call the right function for this kind of single pattern." (funcall (single-match-fn (first pattern)) (rest pattern) input bindings)) (defun segment-match-fn (x) "Get the segment-match function for x, if it is a symbol that has one." (when (symbolp x) (get x 'segment-match))) (defun single-match-fn (x) "Get the single-match function for x, if it is a symbol that has one." (when (symbolp x) (get x 'single-match))) (defun match-is (var-and-pred input bindings) "Succeed and bind var if the input satisfies pred, where var-and-pred is the list (var pred)." (let* ((var (first var-and-pred)) (pred (second var-and-pred)) (new-bindings (pat-match var input bindings))) (if (or (eq new-bindings fail) (not (funcall pred input))) fail new-bindings))) (defun match-and (patterns input bindings) "Succeed if all the patterns match the input." (cond ((eq bindings fail) fail) ((null patterns) bindings) (t (match-and (rest patterns) input (pat-match (first patterns) input bindings))))) (defun match-or (patterns input bindings) "Succeed if any one of the patterns match the input." (if (null patterns) fail (let ((new-bindings (pat-match (first patterns) input bindings))) (if (eq new-bindings fail) (match-or (rest patterns) input bindings) new-bindings)))) (defun match-not (patterns input bindings) "Succeed if none of the patterns match the input. This will never bind any variables." (if (match-or patterns input bindings) fail bindings)) (defun segment-match (pattern input bindings &optional (start 0)) "Match the segment pattern ((?* var) . pat) against input." (let ((var (second (first pattern))) (pat (rest pattern))) (if (null pat) (match-variable var input bindings) (let ((pos (first-match-pos (first pat) input start))) (if (null pos) fail (let ((b2 (pat-match pat (subseq input pos) (match-variable var (subseq input 0 pos) bindings)))) If this match failed , try another longer one (if (eq b2 fail) (segment-match pattern input bindings (+ pos 1)) b2))))))) (defun first-match-pos (pat1 input start) "Find the first position that pat1 could possibly match input, starting at position start. If pat1 is non-constant, then just return start." (cond ((and (atom pat1) (not (variable-p pat1))) (position pat1 input :start start :test #'equal)) ((<= start (length input)) start) ;*** fix, rjf 10/1/92 (was <) (t nil))) (defun segment-match+ (pattern input bindings) "Match one or more elements of input." (segment-match pattern input bindings 1)) (defun segment-match? (pattern input bindings) "Match zero or one element of input." (let ((var (second (first pattern))) (pat (rest pattern))) (or (pat-match (cons var pat) input bindings) (pat-match pat input bindings)))) (defun match-if (pattern input bindings) "Test an arbitrary expression involving variables. The pattern looks like ((?if code) . rest)." ;; *** fix, rjf 10/1/92 (used to eval binding values) (and (progv (mapcar #'car bindings) (mapcar #'cdr bindings) (eval (second (first pattern)))) (pat-match (rest pattern) input bindings))) (defun pat-match-abbrev (symbol expansion) "Define symbol as a macro standing for a pat-match pattern." (setf (get symbol 'expand-pat-match-abbrev) (expand-pat-match-abbrev expansion))) (defun expand-pat-match-abbrev (pat) "Expand out all pattern matching abbreviations in pat." (cond ((and (symbolp pat) (get pat 'expand-pat-match-abbrev))) ((atom pat) pat) (t (cons (expand-pat-match-abbrev (first pat)) (expand-pat-match-abbrev (rest pat)))))) (defun rule-based-translator (input rules &key (matcher 'pat-match) (rule-if #'first) (rule-then #'rest) (action #'sublis)) "Find the first rule in rules that matches input, and apply the action to that rule." (some #'(lambda (rule) (let ((result (funcall matcher (funcall rule-if rule) input))) (if (not (eq result fail)) (funcall action result (funcall rule-then rule))))) rules)) ;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- ;;; Code from Paradigms of Artificial Intelligence Programming Copyright ( c ) 1991 ;;;; File unify.lisp: Unification functions ;;(requires "patmatch") (defparameter *occurs-check* t "Should we do the occurs check?") (defun unify (x y &optional (bindings no-bindings)) "See if x and y match with given bindings." (cond ((eq bindings fail) fail) ((eql x y) bindings) ((variable-p x) (unify-variable x y bindings)) ((variable-p y) (unify-variable y x bindings)) ((and (consp x) (consp y)) (unify (rest x) (rest y) (unify (first x) (first y) bindings))) (t fail))) (defun unify-variable (var x bindings) "Unify var with x, using (and maybe extending) bindings." (cond ((get-binding var bindings) (unify (lookup var bindings) x bindings)) ((and (variable-p x) (get-binding x bindings)) (unify var (lookup x bindings) bindings)) ((and *occurs-check* (occurs-check var x bindings)) fail) (t (extend-bindings var x bindings)))) (defun occurs-check (var x bindings) "Does var occur anywhere inside x?" (cond ((eq var x) t) ((and (variable-p x) (get-binding x bindings)) (occurs-check var (lookup x bindings) bindings)) ((consp x) (or (occurs-check var (first x) bindings) (occurs-check var (rest x) bindings))) (t nil))) ;;; ============================== (defun subst-bindings (bindings x) "Substitute the value of variables in bindings into x, taking recursively bound variables into account." (cond ((eq bindings fail) fail) ((eq bindings no-bindings) x) ((and (variable-p x) (get-binding x bindings)) (subst-bindings bindings (lookup x bindings))) ((atom x) x) (t (reuse-cons (subst-bindings bindings (car x)) (subst-bindings bindings (cdr x)) x)))) ;;; ============================== (defun unifier (x y) "Return something that unifies with both x and y (or fail)." (subst-bindings (unify x y) x)) ;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- Code from Paradigms of AI Programming Copyright ( c ) 1991 File prolog.lisp : prolog from ( 11.3 ) , with interactive backtracking . ;;(requires "unify") ; does not require "prolog1" does not include destructive unification ( 11.6 ) ; see prologc.lisp ;; clauses are represented as (head . body) cons cells (defun clause-head (clause) (first clause)) (defun clause-body (clause) (rest clause)) ;; clauses are stored on the predicate's plist (defun get-clauses (pred) (get pred 'clauses)) (defun predicate (relation) (first relation)) (defun args (x) "The arguments of a relation" (rest x)) (defvar *db-predicates* nil "a list of all predicates stored in the database.") (defmacro <- (&rest clause) "add a clause to the data base." `(add-clause ',(replace-?-vars clause))) (defun add-clause (clause) "add a clause to the data base, indexed by head's predicate." ;; the predicate must be a non-variable symbol. (let ((pred (predicate (clause-head clause)))) (assert (and (symbolp pred) (not (variable-p pred)))) (pushnew pred *db-predicates*) (setf (get pred 'clauses) (nconc (get-clauses pred) (list clause))) pred)) (defun clear-db () "remove all clauses (for all predicates) from the data base." (mapc #'clear-predicate *db-predicates*)) (defun clear-predicate (predicate) "remove the clauses for a single predicate." (setf (get predicate 'clauses) nil)) (defun rename-variables (x) "replace all variables in x with new ones." (sublis (mapcar #'(lambda (var) (cons var (gensym (string var)))) (variables-in x)) x)) (defun unique-find-anywhere-if (predicate tree &optional found-so-far) "return a list of leaves of tree satisfying predicate, with duplicates removed." (if (atom tree) (if (funcall predicate tree) (adjoin tree found-so-far) found-so-far) (unique-find-anywhere-if predicate (first tree) (unique-find-anywhere-if predicate (rest tree) found-so-far)))) (defun find-anywhere-if (predicate tree) "does predicate apply to any atom in the tree?" (if (atom tree) (funcall predicate tree) (or (find-anywhere-if predicate (first tree)) (find-anywhere-if predicate (rest tree))))) (defmacro ?- (&rest goals) `(top-level-prove ',(replace-?-vars goals))) (defun prove-all (goals bindings) "Find a solution to the conjunction of goals." (cond ((eq bindings fail) fail) ((null goals) bindings) (t (prove (first goals) bindings (rest goals))))) (defun prove (goal bindings other-goals) "Return a list of possible solutions to goal." (let ((clauses (get-clauses (predicate goal)))) (if (listp clauses) (some #'(lambda (clause) (let ((new-clause (rename-variables clause))) (prove-all (append (clause-body new-clause) other-goals) (unify goal (clause-head new-clause) bindings)))) clauses) ;; The predicate's "clauses" can be an atom: ;; a primitive function to call (funcall clauses (rest goal) bindings other-goals)))) (defun top-level-prove (goals) (prove-all `(,@goals (show-prolog-vars ,@(variables-in goals))) no-bindings) (format t "~&No.") (values)) (defun show-prolog-vars (vars bindings other-goals) "Print each variable with its binding. Then ask the user if more solutions are desired." (if (null vars) (format t "~&Yes") (dolist (var vars) (format t "~&~a = ~a" var (subst-bindings bindings var)))) (if (continue-p) fail (prove-all other-goals bindings))) (setf (get 'show-prolog-vars 'clauses) 'show-prolog-vars) (defun continue-p () "Ask user if we should continue looking for solutions." (case (read-char) (#\; t) (#\. nil) (#\newline (continue-p)) (otherwise (format t " Type ; to see more or . to stop") (continue-p)))) (defun variables-in (exp) "Return a list of all the variables in EXP." (unique-find-anywhere-if #'non-anon-variable-p exp)) (defun non-anon-variable-p (x) (and (variable-p x) (not (eq x '?)))) (defun replace-?-vars (exp) "Replace any ? within exp with a var of the form ?123." (cond ((eq exp '?) (gensym "?")) ((atom exp) exp) (t (reuse-cons (replace-?-vars (first exp)) (replace-?-vars (rest exp)) exp)))) ;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- Code from Paradigms of AI Programming Copyright ( c ) 1991 ;;;; File prologc.lisp: Final version of the compiler, ;;;; including all improvements from the chapter. ;; (requires "prolog") (defconstant unbound "Unbound") (defstruct var name (binding unbound)) (defun bound-p (var) (not (eq (var-binding var) unbound))) (defmacro deref (exp) "Follow pointers for bound variables." `(progn (loop while (and (var-p ,exp) (bound-p ,exp)) do (setf ,exp (var-binding ,exp))) ,exp)) (defun unify! (x y) "Destructively unify two expressions" (cond ((eql (deref x) (deref y)) t) ((var-p x) (set-binding! x y)) ((var-p y) (set-binding! y x)) ((and (consp x) (consp y)) (and (unify! (first x) (first y)) (unify! (rest x) (rest y)))) (t nil))) (defun set-binding! (var value) "Set var's binding to value. Always succeeds (returns t)." (setf (var-binding var) value) t) (defun print-var (var stream depth) (if (or (and *print-level* (>= depth *print-level*)) (var-p (deref var))) (format stream "?~a" (var-name var)) (write var :stream stream))) (defvar *trail* (make-array 200 :fill-pointer 0 :adjustable t)) (defun set-binding! (var value) "Set var's binding to value, after saving the variable in the trail. Always returns t." (unless (eq var value) (vector-push-extend var *trail*) (setf (var-binding var) value)) t) (defun undo-bindings! (old-trail) "Undo all bindings back to a given point in the trail." (loop until (= (fill-pointer *trail*) old-trail) do (setf (var-binding (vector-pop *trail*)) unbound))) (defvar *var-counter* 0) (defstruct (var (:constructor ? ()) (:print-function print-var)) (name (incf *var-counter*)) (binding unbound)) (defun prolog-compile (symbol &optional (clauses (get-clauses symbol))) "Compile a symbol; make a separate function for each arity." (unless (null clauses) (let ((arity (relation-arity (clause-head (first clauses))))) ;; Compile the clauses with this arity (compile-predicate symbol arity (clauses-with-arity clauses #'= arity)) ;; Compile all the clauses with any other arity (prolog-compile symbol (clauses-with-arity clauses #'/= arity))))) (defun clauses-with-arity (clauses test arity) "Return all clauses whose head has given arity." (find-all arity clauses :key #'(lambda (clause) (relation-arity (clause-head clause))) :test test)) (defun relation-arity (relation) "The number of arguments to a relation. Example: (relation-arity '(p a b c)) => 3" (length (args relation))) (defun args (x) "The arguments of a relation" (rest x)) (defun make-parameters (arity) "Return the list (?arg1 ?arg2 ... ?arg-arity)" (loop for i from 1 to arity collect (new-symbol '?arg i))) (defun make-predicate (symbol arity) "Return the symbol: symbol/arity" (symbol symbol '/ arity)) (defun make-= (x y) `(= ,x ,y)) (defun compile-call (predicate args cont) "Compile a call to a prolog predicate." `(,predicate ,@args ,cont)) (defun prolog-compiler-macro (name) "Fetch the compiler macro for a Prolog predicate." ;; Note NAME is the raw name, not the name/arity (get name 'prolog-compiler-macro)) (defmacro def-prolog-compiler-macro (name arglist &body body) "Define a compiler macro for Prolog." `(setf (get ',name 'prolog-compiler-macro) #'(lambda ,arglist .,body))) (defun compile-arg (arg) "Generate code for an argument to a goal in the body." (cond ((variable-p arg) arg) ((not (has-variable-p arg)) `',arg) ((proper-listp arg) `(list .,(mapcar #'compile-arg arg))) (t `(cons ,(compile-arg (first arg)) ,(compile-arg (rest arg)))))) (defun has-variable-p (x) "Is there a variable anywhere in the expression x?" (find-if-anywhere #'variable-p x)) (defun proper-listp (x) "Is x a proper (non-dotted) list?" (or (null x) (and (consp x) (proper-listp (rest x))))) (defun maybe-add-undo-bindings (compiled-exps) "Undo any bindings that need undoing. If there are any, bind the trail before we start." (if (length=1 compiled-exps) compiled-exps `((let ((old-trail (fill-pointer *trail*))) ,(first compiled-exps) ,@(loop for exp in (rest compiled-exps) collect '(undo-bindings! old-trail) collect exp))))) (defun bind-unbound-vars (parameters exp) "If there are any variables in exp (besides the parameters) then bind them to new vars." (let ((exp-vars (set-difference (variables-in exp) parameters))) (if exp-vars `(let ,(mapcar #'(lambda (var) `(,var (?))) exp-vars) ,exp) exp))) (defmacro <- (&rest clause) "Add a clause to the data base." `(add-clause ',(make-anonymous clause))) (defun make-anonymous (exp &optional (anon-vars (anonymous-variables-in exp))) "Replace variables that are only used once with ?." (cond ((consp exp) (reuse-cons (make-anonymous (first exp) anon-vars) (make-anonymous (rest exp) anon-vars) exp)) ((member exp anon-vars) '?) (t exp))) (defun anonymous-variables-in (tree) "Return a list of all variables that occur only once in tree." (values (anon-vars-in tree nil nil))) (defun anon-vars-in (tree seen-once seen-more) "Walk the data structure TREE, returning a list of variabless seen once, and a list of variables seen more than once." (cond ((consp tree) (multiple-value-bind (new-seen-once new-seen-more) (anon-vars-in (first tree) seen-once seen-more) (anon-vars-in (rest tree) new-seen-once new-seen-more))) ((not (variable-p tree)) (values seen-once seen-more)) ((member tree seen-once) (values (delete tree seen-once) (cons tree seen-more))) ((member tree seen-more) (values seen-once seen-more)) (t (values (cons tree seen-once) seen-more)))) (defun compile-unify (x y bindings) "Return 2 values: code to test if x and y unify, and a new binding list." (cond ;; Unify constants and conses: ; Case 1,2 (values (equal x y) bindings)) 3 (multiple-value-bind (code1 bindings1) (compile-unify (first x) (first y) bindings) (multiple-value-bind (code2 bindings2) (compile-unify (rest x) (rest y) bindings1) (values (compile-if code1 code2) bindings2)))) ;; Here x or y is a variable. Pick the right one: ((variable-p x) (compile-unify-variable x y bindings)) (t (compile-unify-variable y x bindings)))) (defun compile-if (pred then-part) "Compile a Lisp IF form. No else-part allowed." (case pred ((t) then-part) ((nil) nil) (otherwise `(if ,pred ,then-part)))) (defun compile-unify-variable (x y bindings) "X is a variable, and Y may be." (let* ((xb (follow-binding x bindings)) (x1 (if xb (cdr xb) x)) (yb (if (variable-p y) (follow-binding y bindings))) (y1 (if yb (cdr yb) y))) (cond ; Case: 12 ((not (and (equal x x1) (equal y y1))) ; deref (compile-unify x1 y1 bindings)) 11 7,10 (values `(unify! ,x1 ,(compile-arg y1 bindings)) (bind-variables-in y1 bindings))) ((not (null xb)) ;; i.e. x is an ?arg variable (if (and (variable-p y1) (null yb)) 4 (values `(unify! ,x1 ,(compile-arg y1 bindings)) 5,6 ((not (null yb)) (compile-unify-variable y1 x1 bindings)) 8,9 (defun bind-variables-in (exp bindings) "Bind all variables in exp to themselves, and add that to bindings (except for variables already bound)." (dolist (var (variables-in exp)) (unless (get-binding var bindings) (setf bindings (extend-bindings var var bindings)))) bindings) (defun follow-binding (var bindings) "Get the ultimate binding of var according to bindings." (let ((b (get-binding var bindings))) (if (eq (car b) (cdr b)) b (or (follow-binding (cdr b) bindings) b)))) (defun compile-arg (arg bindings) "Generate code for an argument to a goal in the body." (cond ((eq arg '?) '(?)) ((variable-p arg) (let ((binding (get-binding arg bindings))) (if (and (not (null binding)) (not (eq arg (binding-val binding)))) (compile-arg (binding-val binding) bindings) arg))) ((not (find-if-anywhere #'variable-p arg)) `',arg) ((proper-listp arg) `(list .,(mapcar #'(lambda (a) (compile-arg a bindings)) arg))) (t `(cons ,(compile-arg (first arg) bindings) ,(compile-arg (rest arg) bindings))))) (defun bind-new-variables (bindings goal) "Extend bindings to include any unbound variables in goal." (let ((variables (remove-if #'(lambda (v) (assoc v bindings)) (variables-in goal)))) (nconc (mapcar #'self-cons variables) bindings))) (defun self-cons (x) (cons x x)) (def-prolog-compiler-macro = (goal body cont bindings) "Compile a goal which is a call to =." (let ((args (args goal))) (if (/= (length args) 2) :pass ;; decline to handle this goal (multiple-value-bind (code1 bindings1) (compile-unify (first args) (second args) bindings) (compile-if code1 (compile-body body cont bindings1)))))) (defun compile-clause (parms clause cont) "Transform away the head, and compile the resulting body." (bind-unbound-vars parms (compile-body (nconc (mapcar #'make-= parms (args (clause-head clause))) (clause-body clause)) cont (mapcar #'self-cons parms)))) ;*** (defvar *uncompiled* nil "Prolog symbols that have not been compiled.") (defun add-clause (clause) "Add a clause to the data base, indexed by head's predicate." ;; The predicate must be a non-variable symbol. (let ((pred (predicate (clause-head clause)))) (assert (and (symbolp pred) (not (variable-p pred)))) (pushnew pred *db-predicates*) (pushnew pred *uncompiled*) ;*** (setf (get pred 'clauses) (nconc (get-clauses pred) (list clause))) pred)) (defun top-level-prove (goals) "Prove the list of goals by compiling and calling it." First redefine top - level - query (clear-predicate 'top-level-query) (let ((vars (delete '? (variables-in goals)))) (add-clause `((top-level-query) ,@goals (show-prolog-vars ,(mapcar #'symbol-name vars) ,vars)))) ;; Now run it (run-prolog 'top-level-query/0 #'ignore) (format t "~&No.") (values)) (defun run-prolog (procedure cont) "Run a 0-ary prolog procedure with a given continuation." First compile anything else that needs it (prolog-compile-symbols) ;; Reset the trail and the new variable counter (setf (fill-pointer *trail*) 0) (setf *var-counter* 0) ;; Finally, call the query (catch 'top-level-prove (funcall procedure cont))) (defun prolog-compile-symbols (&optional (symbols *uncompiled*)) "Compile a list of Prolog symbols. By default, the list is all symbols that need it." (mapc #'prolog-compile symbols) (setf *uncompiled* (set-difference *uncompiled* symbols))) (defun ignore (&rest args) (declare (ignore args)) nil) (defun show-prolog-vars/2 (var-names vars cont) "Display the variables, and prompt the user to see if we should continue. If not, return to the top level." (if (null vars) (format t "~&Yes") (loop for name in var-names for var in vars do (format t "~&~a = ~a" name (deref-exp var)))) (if (continue-p) (funcall cont) (throw 'top-level-prove nil))) (defun deref-exp (exp) "Build something equivalent to EXP with variables dereferenced." (if (atom (deref exp)) exp (reuse-cons (deref-exp (first exp)) (deref-exp (rest exp)) exp))) (defvar *predicate* nil "The Prolog predicate currently being compiled") (defun compile-predicate (symbol arity clauses) "Compile all the clauses for a given symbol/arity into a single LISP function." (let ((*predicate* (make-predicate symbol arity)) ;*** (parameters (make-parameters arity))) (compile (eval `(defun ,*predicate* (,@parameters cont) .,(maybe-add-undo-bindings (mapcar #'(lambda (clause) (compile-clause parameters clause 'cont)) clauses))))))) (defun compile-body (body cont bindings) "Compile the body of a clause." (cond ((null body) `(funcall ,cont)) ((eq (first body) '!) ;*** `(progn ,(compile-body (rest body) cont bindings) ;*** (return-from ,*predicate* nil))) ;*** (t (let* ((goal (first body)) (macro (prolog-compiler-macro (predicate goal))) (macro-val (if macro (funcall macro goal (rest body) cont bindings)))) (if (and macro (not (eq macro-val :pass))) macro-val `(,(make-predicate (predicate goal) (relation-arity goal)) ,@(mapcar #'(lambda (arg) (compile-arg arg bindings)) (args goal)) ,(if (null (rest body)) cont `#'(lambda () ,(compile-body (rest body) cont (bind-new-variables bindings goal)))))))))) ;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*- Code from Paradigms of AI Programming Copyright ( c ) 1991 ;;;; File prologcp.lisp: Primitives for the prolog compiler ;;;; needed to actually run some functions. Bug fix by , . Trivia : Farquhar is 's cousin . ( requires " prologc " ) (defun read/1 (exp cont) (if (unify! exp (read)) (funcall cont))) (defun write/1 (exp cont) (write (deref-exp exp) :pretty t) (funcall cont)) (defun nl/0 (cont) (terpri) (funcall cont)) (defun =/2 (?arg1 ?arg2 cont) (if (unify! ?arg1 ?arg2) (funcall cont))) (defun ==/2 (?arg1 ?arg2 cont) "Are the two arguments EQUAL with no unification, but with dereferencing? If so, succeed." (if (deref-equal ?arg1 ?arg2) (funcall cont))) (defun deref-equal (x y) "Are the two arguments EQUAL with no unification, but with dereferencing?" (or (eql (deref x) (deref y)) (and (consp x) (consp y) (deref-equal (first x) (first y)) (deref-equal (rest x) (rest y))))) (defun call/1 (goal cont) "Try to prove goal by calling it." (deref goal) (apply (make-predicate (first goal) (length (args goal))) (append (args goal) (list cont)))) (<- (or ?a ?b) (call ?a)) (<- (or ?a ?b) (call ?b)) (<- (and ?a ?b) (call ?a) (call ?b)) (defmacro with-undo-bindings (&body body) "Undo bindings after each expression in body except the last." (if (length=1 body) (first body) `(let ((old-trail (fill-pointer *trail*))) ,(first body) ,@(loop for exp in (rest body) collect '(undo-bindings! old-trail) collect exp)))) (defun not/1 (relation cont) "Negation by failure: If you can't prove G, then (not G) true." ;; Either way, undo the bindings. (with-undo-bindings (call/1 relation #'(lambda () (return-from not/1 nil))) (funcall cont))) (defun bagof/3 (exp goal result cont) "Find all solutions to GOAL, and for each solution, collect the value of EXP into the list RESULT." Ex : Assume ( p 1 ) ( p 2 ) ( p 3 ) . Then : ( bagof ? x ( p ? x ) ? l ) = = > ? l = ( 1 2 3 ) (let ((answers nil)) (call/1 goal #'(lambda () Bug fix by mdf0% ( ) on 25 Jan 1996 ; was deref - COPY (push (deref-EXP exp) answers))) (if (and (not (null answers)) (unify! result (nreverse answers))) (funcall cont)))) (defun deref-copy (exp) "Copy the expression, replacing variables with new ones. The part without variables can be returned as is." Bug fix by farquhar and , 12/12/92 . Forgot to deref var . (sublis (mapcar #'(lambda (var) (cons (deref var) (?))) (unique-find-anywhere-if #'var-p exp)) exp)) (defun setof/3 (exp goal result cont) "Find all unique solutions to GOAL, and for each solution, collect the value of EXP into the list RESULT." Ex : Assume ( p 1 ) ( p 2 ) ( p 3 ) . Then : ( setof ? x ( p ? x ) ? l ) = = > ? l = ( 1 2 3 ) (let ((answers nil)) (call/1 goal #'(lambda () (push (deref-copy exp) answers))) (if (and (not (null answers)) (unify! result (delete-duplicates answers :test #'deref-equal))) (funcall cont)))) (defun is/2 (var exp cont) ;; Example: (is ?x (+ 3 (* ?y (+ ?z 4)))) Or even : ( is ( ? x ? y ? x ) ( cons ( first ? z ) ? l ) ) (if (and (not (find-if-anywhere #'unbound-var-p exp)) (unify! var (eval (deref-exp exp)))) (funcall cont))) (defun unbound-var-p (exp) "Is EXP an unbound var?" (and (var-p exp) (not (bound-p exp)))) (defun var/1 (?arg1 cont) "Succeeds if ?arg1 is an uninstantiated variable." (if (unbound-var-p ?arg1) (funcall cont))) (defun lisp/2 (?result exp cont) "Apply (first exp) to (rest exp), and return the result." (if (and (consp (deref exp)) (unify! ?result (apply (first exp) (rest exp)))) (funcall cont))) (defun repeat/0 (cont) (loop (funcall cont))) (<- (if ?test ?then) (if ?then ?else (fail))) (<- (if ?test ?then ?else) (call ?test) ! (call ?then)) (<- (if ?test ?then ?else) (call ?else)) (<- (member ?item (?item . ?rest))) (<- (member ?item (?x . ?rest)) (member ?item ?rest)) (<- (length () 0)) (<- (length (?x . ?y) (1+ ?n)) (length ?y ?n)) (defun numberp/1 (x cont) (when (numberp (deref x)) (funcall cont))) (defun atom/1 (x cont) (when (atom (deref x)) (funcall cont)))
null
https://raw.githubusercontent.com/logicmoo/logicmoo_nlu/c066897f55b3ff45aa9155ebcf799fda9741bf74/ext/e2c/cynd/paip-prolog.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp -*- File auxfns.lisp: Auxiliary functions used by all other programs Load this file before running any other programs. (in-package "USER") Implementation-Specific Details #+:COMMON-LISP Make it ok to place a function definition on a built-in LISP symbol. Don't warn if a function is defined in multiple files -- this happens often since we refine several programs. REQUIRES The function REQUIRES is used in subsequent files to state dependencies between files. The current definition just loads the required files, assumming they match the pathname specified in *PAIP-DIRECTORY*. You should change that to match where you have stored the files. A more sophisticated REQUIRES would only load it if it has not yet been loaded, and would search in different directories if needed. ??? Maybe Change this ??? Maybe Change this ??? Maybe Change this (in-package :LISP) Auxiliary Functions ============================== ============================== NOTE: In ANSI Common Lisp, the effects of adding a definition (or most anything else) to a symbol in the common-lisp package is undefined. Therefore, it would be best to rename the function SYMBOL to something else. This has not been done (for compatibility with the book). ============================== ============================== ============================== ============================== PATTERN MATCHING FACILITY Once we add a "real" binding, we can get rid of the dummy no-bindings ============================== Delayed computation: A queue is a (last . contents) pair Other: ============================== ============================== ============================== ============================== ============================== CLtL2 and ANSI CL Compatibility arglist is made into a list of args for each call n is the length of the longest vector Define some shared functions: Decide if the result is a list or vector, and loop through each element That way, undefined function warnings that are really just forward references will not be printed at all. Reduce Change this to T if you need REDUCE with :key keyword. -*- Mode: Lisp; Syntax: Common-Lisp -*- File pat-match.lisp: Pattern matcher from section 6.2 The basic are in auxfns.lisp; look for "PATTERN MATCHING FACILITY" *** *** *** fix, rjf 10/1/92 (was <) *** fix, rjf 10/1/92 (used to eval binding values) -*- Mode: Lisp; Syntax: Common-Lisp; -*- Code from Paradigms of Artificial Intelligence Programming File unify.lisp: Unification functions (requires "patmatch") ============================== ============================== -*- Mode: Lisp; Syntax: Common-Lisp -*- (requires "unify") ; does not require "prolog1" see prologc.lisp clauses are represented as (head . body) cons cells clauses are stored on the predicate's plist the predicate must be a non-variable symbol. The predicate's "clauses" can be an atom: a primitive function to call t) -*- Mode: Lisp; Syntax: Common-Lisp -*- File prologc.lisp: Final version of the compiler, including all improvements from the chapter. (requires "prolog") Compile the clauses with this arity Compile all the clauses with any other arity Note NAME is the raw name, not the name/arity Unify constants and conses: ; Case Here x or y is a variable. Pick the right one: Case: deref i.e. x is an ?arg variable decline to handle this goal *** The predicate must be a non-variable symbol. *** Now run it Reset the trail and the new variable counter Finally, call the query *** *** *** *** -*- Mode: Lisp; Syntax: Common-Lisp -*- File prologcp.lisp: Primitives for the prolog compiler needed to actually run some functions. Either way, undo the bindings. was deref - COPY Example: (is ?x (+ 3 (* ?y (+ ?z 4))))
Code from Paradigms of AI Programming Copyright ( c ) 1991 (eval-when (eval compile load) #+(or Allegro EXCL) (dolist (pkg '(excl common-lisp common-lisp-user)) (setf (excl:package-definition-lock (find-package pkg)) nil)) #+Lispworks (setq *PACKAGES-FOR-WARN-ON-REDEFINITION* nil) #+LCL (compiler-options :warnings nil) ) (defun requires (&rest files) "The arguments are files that are required to run an application." (mapc #'load-paip-file files)) (defvar *paip-files* `("auxfns" "tutor" "examples" "intro" "simple" "overview" "gps1" "gps" "eliza1" "eliza" "patmatch" "eliza-pm" "search" "gps-srch" "student" "macsyma" "macsymar" "unify" "prolog1" "prolog" "prologc1" "prologc2" "prologc" "prologcp" "clos" "krep1" "krep2" "krep" "cmacsyma" "mycin" "mycin-r" "waltz" "othello" "othello2" "syntax1" "syntax2" "syntax3" "unifgram" "grammar" "lexicon" "interp1" "interp2" "interp3" "compile1" "compile2" "compile3" "compopt")) (defparameter *paip-directory* (make-pathname :name nil :type nil :defaults (or (and (boundp '*load-truename*) *load-truename*) "The location of the source files for this book. If things don't work, change it to reflect the location of the files on your computer.") (defparameter *paip-source* :defaults *paip-directory*)) (defparameter *paip-binary* (make-pathname :name nil :type (first (list #+LCL (first *load-binary-pathname-types*) #+Lispworks system::*binary-file-type* #+MCL "fasl" #+Allegro excl:*fasl-default-type* #+(or AKCL KCL) "o" #+CMU "sparcf" #+CLISP "fas" :directory (append (pathname-directory *paip-source*) '("bin")) :defaults *paip-directory*)) (defun paip-pathname (name &optional (type :lisp)) (make-pathname :name name :defaults (ecase type ((:lisp :source) *paip-source*) ((:binary :bin) *paip-binary*)))) (defun compile-all-paip-files () (mapc #'compile-paip-file *paip-files*)) (defun compile-paip-file (name) (let ((path (paip-pathname name :lisp))) (load path) (compile-file path :output-file (paip-pathname name :binary)))) (defun load-paip-file (file) "Load the binary file if it exists and is newer, else load the source." (let* ((src (paip-pathname file :lisp)) (src-date (file-write-date src)) (bin (paip-pathname file :binary)) (bin-date (file-write-date bin))) (load (if (and (probe-file bin) src-date bin-date (>= bin-date src-date)) bin src)))) Macros ( formerly in auxmacs.lisp : that file no longer needed ) (eval-when (load eval compile) (defmacro once-only (variables &rest body) "Returns the code built by BODY. If any of VARIABLES might have side effects, they are evaluated once and stored in temporary variables that are then passed to BODY." (assert (every #'symbolp variables)) (let ((temps nil)) (dotimes (i (length variables)) (push (gensym) temps)) `(if (every #'side-effect-free? (list .,variables)) (progn .,body) (list 'let ,`(list ,@(mapcar #'(lambda (tmp var) `(list ',tmp ,var)) temps variables)) (let ,(mapcar #'(lambda (var tmp) `(,var ',tmp)) variables temps) .,body))))) (defun side-effect-free? (exp) "Is exp a constant, variable, or function, or of the form (THE type x) where x is side-effect-free?" (or (atom exp) (constantp exp) (starts-with exp 'function) (and (starts-with exp 'the) (side-effect-free? (third exp))))) (defmacro funcall-if (fn arg) (once-only (fn) `(if ,fn (funcall ,fn ,arg) ,arg))) (defmacro read-time-case (first-case &rest other-cases) "Do the first case, where normally cases are specified with #+ or possibly #- marks." (declare (ignore other-cases)) first-case) (defun rest2 (x) "The rest of a list after the first TWO elements." (rest (rest x))) (defun find-anywhere (item tree) "Does item occur anywhere in tree?" (if (atom tree) (if (eql item tree) tree) (or (find-anywhere item (first tree)) (find-anywhere item (rest tree))))) (defun starts-with (list x) "Is x a list whose first element is x?" (and (consp list) (eql (first list) x))) ) (setf (symbol-function 'find-all-if) #'remove-if-not) (defun find-all (item sequence &rest keyword-args &key (test #'eql) test-not &allow-other-keys) "Find all those elements of sequence that match item, according to the keywords. Doesn't alter sequence." (if test-not (apply #'remove item sequence :test-not (complement test-not) keyword-args) (apply #'remove item sequence :test (complement test) keyword-args))) (defun partition-if (pred list) "Return 2 values: elements of list that satisfy pred, and elements that don't." (let ((yes-list nil) (no-list nil)) (dolist (item list) (if (funcall pred item) (push item yes-list) (push item no-list))) (values (nreverse yes-list) (nreverse no-list)))) (defun maybe-add (op exps &optional if-nil) "For example, (maybe-add 'and exps t) returns t if exps is nil, exps if there is only one, and (and exp1 exp2...) if there are several exps." (cond ((null exps) if-nil) ((length=1 exps) (first exps)) (t (cons op exps)))) (defun seq-ref (seq index) "Return code that indexes into a sequence, using the pop-lists/aref-vectors strategy." `(if (listp ,seq) (prog1 (first ,seq) (setq ,seq (the list (rest ,seq)))) (aref ,seq ,index))) (defun maybe-set-fill-pointer (array new-length) "If this is an array with a fill pointer, set it to new-length, if that is longer than the current length." (if (and (arrayp array) (array-has-fill-pointer-p array)) (setf (fill-pointer array) (max (fill-pointer array) new-length)))) (defun symbol (&rest args) "Concatenate symbols or strings to form an interned symbol" (intern (format nil "~{~a~}" args))) (defun new-symbol (&rest args) "Concatenate symbols or strings to form an uninterned symbol" (make-symbol (format nil "~{~a~}" args))) (defun last1 (list) "Return the last element (not last cons cell) of list" (first (last list))) (defun mappend (fn list) "Append the results of calling fn on each element of list. Like mapcon, but uses append instead of nconc." (apply #'append (mapcar fn list))) (defun mklist (x) "If x is a list return it, otherwise return the list of x" (if (listp x) x (list x))) (defun flatten (exp) "Get rid of imbedded lists (to one level only)." (mappend #'mklist exp)) (defun random-elt (seq) "Pick a random element out of a sequence." (elt seq (random (length seq)))) (defun member-equal (item list) (member item list :test #'equal)) (defun compose (&rest functions) #'(lambda (x) (reduce #'funcall functions :from-end t :initial-value x))) The Debugging Output Facility : (defvar *dbg-ids* nil "Identifiers used by dbg") (defun dbg (id format-string &rest args) "Print debugging info if (DEBUG ID) has been specified." (when (member id *dbg-ids*) (fresh-line *debug-io*) (apply #'format *debug-io* format-string args))) (defun debug (&rest ids) "Start dbg output on the given ids." (setf *dbg-ids* (union ids *dbg-ids*))) (defun undebug (&rest ids) "Stop dbg on the ids. With no ids, stop dbg altogether." (setf *dbg-ids* (if (null ids) nil (set-difference *dbg-ids* ids)))) (defun dbg-indent (id indent format-string &rest args) "Print indented debugging info if (DEBUG ID) has been specified." (when (member id *dbg-ids*) (fresh-line *debug-io*) (dotimes (i indent) (princ " " *debug-io*)) (apply #'format *debug-io* format-string args))) (defconstant fail nil) (defconstant no-bindings '((t . t))) (defun pat-match (pattern input &optional (bindings no-bindings)) "Match pattern against input in the context of the bindings" (cond ((eq bindings fail) fail) ((variable-p pattern) (match-variable pattern input bindings)) ((eql pattern input) bindings) ((and (consp pattern) (consp input)) (pat-match (rest pattern) (rest input) (pat-match (first pattern) (first input) bindings))) (t fail))) (defun match-variable (var input bindings) "Does VAR match input? Uses (or updates) and returns bindings." (let ((binding (get-binding var bindings))) (cond ((not binding) (extend-bindings var input bindings)) ((equal input (binding-val binding)) bindings) (t fail)))) (defun make-binding (var val) (cons var val)) (defun binding-var (binding) "Get the variable part of a single binding." (car binding)) (defun binding-val (binding) "Get the value part of a single binding." (cdr binding)) (defun get-binding (var bindings) "Find a (variable . value) pair in a binding list." (assoc var bindings)) (defun lookup (var bindings) "Get the value part (for var) from a binding list." (binding-val (get-binding var bindings))) (defun extend-bindings (var val bindings) "Add a (var . value) pair to a binding list." (cons (cons var val) (if (eq bindings no-bindings) nil bindings))) (defun variable-p (x) "Is x a variable (a symbol beginning with `?')?" (and (symbolp x) (equal (elt (symbol-name x) 0) #\?))) The Memoization facility : (defmacro defun-memo (fn args &body body) "Define a memoized function." `(memoize (defun ,fn ,args . ,body))) (defun memo (fn &key (key #'first) (test #'eql) name) "Return a memo-function of fn." (let ((table (make-hash-table :test test))) (setf (get name 'memo) table) #'(lambda (&rest args) (let ((k (funcall key args))) (multiple-value-bind (val found-p) (gethash k table) (if found-p val (setf (gethash k table) (apply fn args)))))))) (defun memoize (fn-name &key (key #'first) (test #'eql)) "Replace fn-name's global definition with a memoized version." (clear-memoize fn-name) (setf (symbol-function fn-name) (memo (symbol-function fn-name) :name fn-name :key key :test test))) (defun clear-memoize (fn-name) "Clear the hash table from a memo function." (let ((table (get fn-name 'memo))) (when table (clrhash table)))) (defstruct delay value (computed? nil)) (defmacro delay (&rest body) "A computation that can be executed later by FORCE." `(make-delay :value #'(lambda () . ,body))) (defun force (delay) "Do a delayed computation, or fetch its previously-computed value." (if (delay-computed? delay) (delay-value delay) (prog1 (setf (delay-value delay) (funcall (delay-value delay))) (setf (delay-computed? delay) t)))) Defresource : (defmacro defresource (name &key constructor (initial-copies 0) (size (max initial-copies 10))) (let ((resource (symbol '* (symbol name '-resource*))) (deallocate (symbol 'deallocate- name)) (allocate (symbol 'allocate- name))) `(progn (defparameter ,resource (make-array ,size :fill-pointer 0)) (defun ,allocate () "Get an element from the resource pool, or make one." (if (= (fill-pointer ,resource) 0) ,constructor (vector-pop ,resource))) (defun ,deallocate (,name) "Place a no-longer-needed element back in the pool." (vector-push-extend ,name ,resource)) ,(if (> initial-copies 0) `(mapc #',deallocate (loop repeat ,initial-copies collect (,allocate)))) ',name))) (defmacro with-resource ((var resource &optional protect) &rest body) "Execute body with VAR bound to an instance of RESOURCE." (let ((allocate (symbol 'allocate- resource)) (deallocate (symbol 'deallocate- resource))) (if protect `(let ((,var nil)) (unwind-protect (progn (setf ,var (,allocate)) ,@body) (unless (null ,var) (,deallocate ,var)))) `(let ((,var (,allocate))) ,@body (,deallocate var))))) Queues : (defun queue-contents (q) (cdr q)) (defun make-queue () "Build a new queue, with no elements." (let ((q (cons nil nil))) (setf (car q) q))) (defun enqueue (item q) "Insert item at the end of the queue." (setf (car q) (setf (rest (car q)) (cons item nil))) q) (defun dequeue (q) "Remove an item from the front of the queue." (pop (cdr q)) (if (null (cdr q)) (setf (car q) q)) q) (defun front (q) (first (queue-contents q))) (defun empty-queue-p (q) (null (queue-contents q))) (defun queue-nconc (q list) "Add the elements of LIST to the end of the queue." (setf (car q) (last (setf (rest (car q)) list)))) (defun sort* (seq pred &key key) "Sort without altering the sequence" (sort (copy-seq seq) pred :key key)) (defun reuse-cons (x y x-y) "Return (cons x y), or reuse x-y if it is equal to (cons x y)" (if (and (eql x (car x-y)) (eql y (cdr x-y))) x-y (cons x y))) (defun length=1 (x) "Is x a list of length 1?" (and (consp x) (null (cdr x)))) (defun rest3 (list) "The rest of a list after the first THREE elements." (cdddr list)) (defun unique-find-if-anywhere (predicate tree &optional found-so-far) "Return a list of leaves of tree satisfying predicate, with duplicates removed." (if (atom tree) (if (funcall predicate tree) (adjoin tree found-so-far) found-so-far) (unique-find-if-anywhere predicate (first tree) (unique-find-if-anywhere predicate (rest tree) found-so-far)))) (defun find-if-anywhere (predicate tree) "Does predicate apply to any atom in the tree?" (if (atom tree) (funcall predicate tree) (or (find-if-anywhere predicate (first tree)) (find-if-anywhere predicate (rest tree))))) (defmacro define-enumerated-type (type &rest elements) "Represent an enumerated type with integers 0-n." `(progn (deftype ,type () '(integer 0 ,(- (length elements) 1))) (defun ,(symbol type '->symbol) (,type) (elt ',elements ,type)) (defun ,(symbol 'symbol-> type) (symbol) (position symbol ',elements)) ,@(loop for element in elements for i from 0 collect `(defconstant ,element ,i)))) (defun not-null (x) (not (null x))) (defun first-or-nil (x) "The first element of x if it is a list; else nil." (if (consp x) (first x) nil)) (defun first-or-self (x) "The first element of x, if it is a list; else x itself." (if (consp x) (first x) x)) (unless (fboundp 'defmethod) (defmacro defmethod (name args &rest body) `(defun ',name ',args ,@body)) ) (unless (fboundp 'map-into) (defun map-into (result-sequence function &rest sequences) "Destructively set elements of RESULT-SEQUENCE to the results of applying FUNCTION to respective elements of SEQUENCES." (let ((arglist (make-list (length sequences))) (n (if (listp result-sequence) most-positive-fixnum (array-dimension result-sequence 0)))) (when sequences (setf n (min n (loop for seq in sequences minimize (length seq))))) (flet ((do-one-call (i) (loop for seq on sequences for arg on arglist do (if (listp (first seq)) (setf (first arg) (pop (first seq))) (setf (first arg) (aref (first seq) i)))) (apply function arglist)) (do-result (i) (if (and (vectorp result-sequence) (array-has-fill-pointer-p result-sequence)) (setf (fill-pointer result-sequence) (max i (fill-pointer result-sequence)))))) (declare (inline do-one-call)) (if (listp result-sequence) (loop for i from 0 to (- n 1) for r on result-sequence do (setf (first r) (do-one-call i)) finally (do-result i)) (loop for i from 0 to (- n 1) do (setf (aref result-sequence i) (do-one-call i)) finally (do-result i)))) result-sequence)) ) (unless (fboundp 'complement) (defun complement (fn) "If FN returns y, then (complement FN) returns (not y)." #'(lambda (&rest args) (not (apply fn args)))) ) (unless (fboundp 'with-compilation-unit) (defmacro with-compilation-unit (options &body body) "Do the body, but delay compiler warnings until the end." This is defined in Common Lisp the Language , 2nd ed . (declare (ignore options)) `(,(read-time-case #+Lispm 'compiler:compiler-warnings-context-bind #+Lucid 'with-deferred-warnings 'progn) .,body)) ) (defun reduce* (fn seq from-end start end key init init-p) (funcall (if (listp seq) #'reduce-list #'reduce-vect) fn seq from-end (or start 0) end key init init-p)) (defun reduce (function sequence &key from-end start end key (initial-value nil initial-value-p)) (reduce* function sequence from-end start end key initial-value initial-value-p)) (defun reduce-vect (fn seq from-end start end key init init-p) (if (null end) (setf end (length seq))) (assert (<= 0 start end (length seq)) (start end) "Illegal subsequence of ~a --- :start ~d :end ~d" seq start end) (case (- end start) (1 (if init-p (funcall fn init (funcall-if key (aref seq start))) (funcall-if key (aref seq start)))) (0 (if init-p init (funcall fn))) (t (if (not from-end) (let ((result (if init-p (funcall fn init (funcall-if key (aref seq start))) (funcall fn (funcall-if key (aref seq start)) (funcall-if key (aref seq (+ start 1))))))) (loop for i from (+ start (if init-p 1 2)) to (- end 1) do (setf result (funcall fn result (funcall-if key (aref seq i))))) result) (let ((result (if init-p (funcall fn (funcall-if key (aref seq (- end 1))) init) (funcall fn (funcall-if key (aref seq (- end 2))) (funcall-if key (aref seq (- end 1))))))) (loop for i from (- end (if init-p 2 3)) downto start do (setf result (funcall fn (funcall-if key (aref seq i)) result))) result))))) (defun reduce-list (fn seq from-end start end key init init-p) (if (null end) (setf end (length seq))) (cond ((> start 0) (reduce-list fn (nthcdr start seq) from-end 0 (- end start) key init init-p)) ((or (null seq) (eql start end)) (if init-p init (funcall fn))) ((= (- end start) 1) (if init-p (funcall fn init (funcall-if key (first seq))) (funcall-if key (first seq)))) (from-end (reduce-vect fn (coerce seq 'vector) t start end key init init-p)) ((null (rest seq)) (if init-p (funcall fn init (funcall-if key (first seq))) (funcall-if key (first seq)))) (t (let ((result (if init-p (funcall fn init (funcall-if key (pop seq))) (funcall fn (funcall-if key (pop seq)) (funcall-if key (pop seq)))))) (if end (loop repeat (- end (if init-p 1 2)) while seq do (setf result (funcall fn result (funcall-if key (pop seq))))) (loop while seq do (setf result (funcall fn result (funcall-if key (pop seq)))))) result)))) ) (defun do-s (words) (top-level-prove `((S ?sem ,words ())))) (if (boundp 'clear-db) (clear-db)) Code from Paradigms of AI Programming Copyright ( c ) 1991 Two bug fixes By , October 92 . (defun variable-p (x) "Is x a variable (a symbol beginning with `?')?" (and (symbolp x) (equal (elt (symbol-name x) 0) #\?))) (defun pat-match (pattern input &optional (bindings no-bindings)) "Match pattern against input in the context of the bindings" (cond ((eq bindings fail) fail) ((variable-p pattern) (match-variable pattern input bindings)) ((eql pattern input) bindings) ((segment-pattern-p pattern) (segment-matcher pattern input bindings)) ((and (consp pattern) (consp input)) (pat-match (rest pattern) (rest input) (pat-match (first pattern) (first input) bindings))) (t fail))) (setf (get '?is 'single-match) 'match-is) (setf (get '?or 'single-match) 'match-or) (setf (get '?and 'single-match) 'match-and) (setf (get '?not 'single-match) 'match-not) (setf (get '?* 'segment-match) 'segment-match) (setf (get '?+ 'segment-match) 'segment-match+) (setf (get '?? 'segment-match) 'segment-match?) (setf (get '?if 'segment-match) 'match-if) (defun segment-pattern-p (pattern) "Is this a segment-matching pattern like ((?* var) . pat)?" (and (consp pattern) (consp (first pattern)) (symbolp (first (first pattern))) (segment-match-fn (first (first pattern))))) (defun single-pattern-p (pattern) "Is this a single-matching pattern? E.g. (?is x predicate) (?and . patterns) (?or . patterns)." (and (consp pattern) (single-match-fn (first pattern)))) (defun segment-matcher (pattern input bindings) "Call the right function for this kind of segment pattern." (funcall (segment-match-fn (first (first pattern))) pattern input bindings)) (defun single-matcher (pattern input bindings) "Call the right function for this kind of single pattern." (funcall (single-match-fn (first pattern)) (rest pattern) input bindings)) (defun segment-match-fn (x) "Get the segment-match function for x, if it is a symbol that has one." (when (symbolp x) (get x 'segment-match))) (defun single-match-fn (x) "Get the single-match function for x, if it is a symbol that has one." (when (symbolp x) (get x 'single-match))) (defun match-is (var-and-pred input bindings) "Succeed and bind var if the input satisfies pred, where var-and-pred is the list (var pred)." (let* ((var (first var-and-pred)) (pred (second var-and-pred)) (new-bindings (pat-match var input bindings))) (if (or (eq new-bindings fail) (not (funcall pred input))) fail new-bindings))) (defun match-and (patterns input bindings) "Succeed if all the patterns match the input." (cond ((eq bindings fail) fail) ((null patterns) bindings) (t (match-and (rest patterns) input (pat-match (first patterns) input bindings))))) (defun match-or (patterns input bindings) "Succeed if any one of the patterns match the input." (if (null patterns) fail (let ((new-bindings (pat-match (first patterns) input bindings))) (if (eq new-bindings fail) (match-or (rest patterns) input bindings) new-bindings)))) (defun match-not (patterns input bindings) "Succeed if none of the patterns match the input. This will never bind any variables." (if (match-or patterns input bindings) fail bindings)) (defun segment-match (pattern input bindings &optional (start 0)) "Match the segment pattern ((?* var) . pat) against input." (let ((var (second (first pattern))) (pat (rest pattern))) (if (null pat) (match-variable var input bindings) (let ((pos (first-match-pos (first pat) input start))) (if (null pos) fail (let ((b2 (pat-match pat (subseq input pos) (match-variable var (subseq input 0 pos) bindings)))) If this match failed , try another longer one (if (eq b2 fail) (segment-match pattern input bindings (+ pos 1)) b2))))))) (defun first-match-pos (pat1 input start) "Find the first position that pat1 could possibly match input, starting at position start. If pat1 is non-constant, then just return start." (cond ((and (atom pat1) (not (variable-p pat1))) (position pat1 input :start start :test #'equal)) (t nil))) (defun segment-match+ (pattern input bindings) "Match one or more elements of input." (segment-match pattern input bindings 1)) (defun segment-match? (pattern input bindings) "Match zero or one element of input." (let ((var (second (first pattern))) (pat (rest pattern))) (or (pat-match (cons var pat) input bindings) (pat-match pat input bindings)))) (defun match-if (pattern input bindings) "Test an arbitrary expression involving variables. The pattern looks like ((?if code) . rest)." (and (progv (mapcar #'car bindings) (mapcar #'cdr bindings) (eval (second (first pattern)))) (pat-match (rest pattern) input bindings))) (defun pat-match-abbrev (symbol expansion) "Define symbol as a macro standing for a pat-match pattern." (setf (get symbol 'expand-pat-match-abbrev) (expand-pat-match-abbrev expansion))) (defun expand-pat-match-abbrev (pat) "Expand out all pattern matching abbreviations in pat." (cond ((and (symbolp pat) (get pat 'expand-pat-match-abbrev))) ((atom pat) pat) (t (cons (expand-pat-match-abbrev (first pat)) (expand-pat-match-abbrev (rest pat)))))) (defun rule-based-translator (input rules &key (matcher 'pat-match) (rule-if #'first) (rule-then #'rest) (action #'sublis)) "Find the first rule in rules that matches input, and apply the action to that rule." (some #'(lambda (rule) (let ((result (funcall matcher (funcall rule-if rule) input))) (if (not (eq result fail)) (funcall action result (funcall rule-then rule))))) rules)) Copyright ( c ) 1991 (defparameter *occurs-check* t "Should we do the occurs check?") (defun unify (x y &optional (bindings no-bindings)) "See if x and y match with given bindings." (cond ((eq bindings fail) fail) ((eql x y) bindings) ((variable-p x) (unify-variable x y bindings)) ((variable-p y) (unify-variable y x bindings)) ((and (consp x) (consp y)) (unify (rest x) (rest y) (unify (first x) (first y) bindings))) (t fail))) (defun unify-variable (var x bindings) "Unify var with x, using (and maybe extending) bindings." (cond ((get-binding var bindings) (unify (lookup var bindings) x bindings)) ((and (variable-p x) (get-binding x bindings)) (unify var (lookup x bindings) bindings)) ((and *occurs-check* (occurs-check var x bindings)) fail) (t (extend-bindings var x bindings)))) (defun occurs-check (var x bindings) "Does var occur anywhere inside x?" (cond ((eq var x) t) ((and (variable-p x) (get-binding x bindings)) (occurs-check var (lookup x bindings) bindings)) ((consp x) (or (occurs-check var (first x) bindings) (occurs-check var (rest x) bindings))) (t nil))) (defun subst-bindings (bindings x) "Substitute the value of variables in bindings into x, taking recursively bound variables into account." (cond ((eq bindings fail) fail) ((eq bindings no-bindings) x) ((and (variable-p x) (get-binding x bindings)) (subst-bindings bindings (lookup x bindings))) ((atom x) x) (t (reuse-cons (subst-bindings bindings (car x)) (subst-bindings bindings (cdr x)) x)))) (defun unifier (x y) "Return something that unifies with both x and y (or fail)." (subst-bindings (unify x y) x)) Code from Paradigms of AI Programming Copyright ( c ) 1991 File prolog.lisp : prolog from ( 11.3 ) , with interactive backtracking . (defun clause-head (clause) (first clause)) (defun clause-body (clause) (rest clause)) (defun get-clauses (pred) (get pred 'clauses)) (defun predicate (relation) (first relation)) (defun args (x) "The arguments of a relation" (rest x)) (defvar *db-predicates* nil "a list of all predicates stored in the database.") (defmacro <- (&rest clause) "add a clause to the data base." `(add-clause ',(replace-?-vars clause))) (defun add-clause (clause) "add a clause to the data base, indexed by head's predicate." (let ((pred (predicate (clause-head clause)))) (assert (and (symbolp pred) (not (variable-p pred)))) (pushnew pred *db-predicates*) (setf (get pred 'clauses) (nconc (get-clauses pred) (list clause))) pred)) (defun clear-db () "remove all clauses (for all predicates) from the data base." (mapc #'clear-predicate *db-predicates*)) (defun clear-predicate (predicate) "remove the clauses for a single predicate." (setf (get predicate 'clauses) nil)) (defun rename-variables (x) "replace all variables in x with new ones." (sublis (mapcar #'(lambda (var) (cons var (gensym (string var)))) (variables-in x)) x)) (defun unique-find-anywhere-if (predicate tree &optional found-so-far) "return a list of leaves of tree satisfying predicate, with duplicates removed." (if (atom tree) (if (funcall predicate tree) (adjoin tree found-so-far) found-so-far) (unique-find-anywhere-if predicate (first tree) (unique-find-anywhere-if predicate (rest tree) found-so-far)))) (defun find-anywhere-if (predicate tree) "does predicate apply to any atom in the tree?" (if (atom tree) (funcall predicate tree) (or (find-anywhere-if predicate (first tree)) (find-anywhere-if predicate (rest tree))))) (defmacro ?- (&rest goals) `(top-level-prove ',(replace-?-vars goals))) (defun prove-all (goals bindings) "Find a solution to the conjunction of goals." (cond ((eq bindings fail) fail) ((null goals) bindings) (t (prove (first goals) bindings (rest goals))))) (defun prove (goal bindings other-goals) "Return a list of possible solutions to goal." (let ((clauses (get-clauses (predicate goal)))) (if (listp clauses) (some #'(lambda (clause) (let ((new-clause (rename-variables clause))) (prove-all (append (clause-body new-clause) other-goals) (unify goal (clause-head new-clause) bindings)))) clauses) (funcall clauses (rest goal) bindings other-goals)))) (defun top-level-prove (goals) (prove-all `(,@goals (show-prolog-vars ,@(variables-in goals))) no-bindings) (format t "~&No.") (values)) (defun show-prolog-vars (vars bindings other-goals) "Print each variable with its binding. Then ask the user if more solutions are desired." (if (null vars) (format t "~&Yes") (dolist (var vars) (format t "~&~a = ~a" var (subst-bindings bindings var)))) (if (continue-p) fail (prove-all other-goals bindings))) (setf (get 'show-prolog-vars 'clauses) 'show-prolog-vars) (defun continue-p () "Ask user if we should continue looking for solutions." (case (read-char) (#\. nil) (#\newline (continue-p)) (otherwise (format t " Type ; to see more or . to stop") (continue-p)))) (defun variables-in (exp) "Return a list of all the variables in EXP." (unique-find-anywhere-if #'non-anon-variable-p exp)) (defun non-anon-variable-p (x) (and (variable-p x) (not (eq x '?)))) (defun replace-?-vars (exp) "Replace any ? within exp with a var of the form ?123." (cond ((eq exp '?) (gensym "?")) ((atom exp) exp) (t (reuse-cons (replace-?-vars (first exp)) (replace-?-vars (rest exp)) exp)))) Code from Paradigms of AI Programming Copyright ( c ) 1991 (defconstant unbound "Unbound") (defstruct var name (binding unbound)) (defun bound-p (var) (not (eq (var-binding var) unbound))) (defmacro deref (exp) "Follow pointers for bound variables." `(progn (loop while (and (var-p ,exp) (bound-p ,exp)) do (setf ,exp (var-binding ,exp))) ,exp)) (defun unify! (x y) "Destructively unify two expressions" (cond ((eql (deref x) (deref y)) t) ((var-p x) (set-binding! x y)) ((var-p y) (set-binding! y x)) ((and (consp x) (consp y)) (and (unify! (first x) (first y)) (unify! (rest x) (rest y)))) (t nil))) (defun set-binding! (var value) "Set var's binding to value. Always succeeds (returns t)." (setf (var-binding var) value) t) (defun print-var (var stream depth) (if (or (and *print-level* (>= depth *print-level*)) (var-p (deref var))) (format stream "?~a" (var-name var)) (write var :stream stream))) (defvar *trail* (make-array 200 :fill-pointer 0 :adjustable t)) (defun set-binding! (var value) "Set var's binding to value, after saving the variable in the trail. Always returns t." (unless (eq var value) (vector-push-extend var *trail*) (setf (var-binding var) value)) t) (defun undo-bindings! (old-trail) "Undo all bindings back to a given point in the trail." (loop until (= (fill-pointer *trail*) old-trail) do (setf (var-binding (vector-pop *trail*)) unbound))) (defvar *var-counter* 0) (defstruct (var (:constructor ? ()) (:print-function print-var)) (name (incf *var-counter*)) (binding unbound)) (defun prolog-compile (symbol &optional (clauses (get-clauses symbol))) "Compile a symbol; make a separate function for each arity." (unless (null clauses) (let ((arity (relation-arity (clause-head (first clauses))))) (compile-predicate symbol arity (clauses-with-arity clauses #'= arity)) (prolog-compile symbol (clauses-with-arity clauses #'/= arity))))) (defun clauses-with-arity (clauses test arity) "Return all clauses whose head has given arity." (find-all arity clauses :key #'(lambda (clause) (relation-arity (clause-head clause))) :test test)) (defun relation-arity (relation) "The number of arguments to a relation. Example: (relation-arity '(p a b c)) => 3" (length (args relation))) (defun args (x) "The arguments of a relation" (rest x)) (defun make-parameters (arity) "Return the list (?arg1 ?arg2 ... ?arg-arity)" (loop for i from 1 to arity collect (new-symbol '?arg i))) (defun make-predicate (symbol arity) "Return the symbol: symbol/arity" (symbol symbol '/ arity)) (defun make-= (x y) `(= ,x ,y)) (defun compile-call (predicate args cont) "Compile a call to a prolog predicate." `(,predicate ,@args ,cont)) (defun prolog-compiler-macro (name) "Fetch the compiler macro for a Prolog predicate." (get name 'prolog-compiler-macro)) (defmacro def-prolog-compiler-macro (name arglist &body body) "Define a compiler macro for Prolog." `(setf (get ',name 'prolog-compiler-macro) #'(lambda ,arglist .,body))) (defun compile-arg (arg) "Generate code for an argument to a goal in the body." (cond ((variable-p arg) arg) ((not (has-variable-p arg)) `',arg) ((proper-listp arg) `(list .,(mapcar #'compile-arg arg))) (t `(cons ,(compile-arg (first arg)) ,(compile-arg (rest arg)))))) (defun has-variable-p (x) "Is there a variable anywhere in the expression x?" (find-if-anywhere #'variable-p x)) (defun proper-listp (x) "Is x a proper (non-dotted) list?" (or (null x) (and (consp x) (proper-listp (rest x))))) (defun maybe-add-undo-bindings (compiled-exps) "Undo any bindings that need undoing. If there are any, bind the trail before we start." (if (length=1 compiled-exps) compiled-exps `((let ((old-trail (fill-pointer *trail*))) ,(first compiled-exps) ,@(loop for exp in (rest compiled-exps) collect '(undo-bindings! old-trail) collect exp))))) (defun bind-unbound-vars (parameters exp) "If there are any variables in exp (besides the parameters) then bind them to new vars." (let ((exp-vars (set-difference (variables-in exp) parameters))) (if exp-vars `(let ,(mapcar #'(lambda (var) `(,var (?))) exp-vars) ,exp) exp))) (defmacro <- (&rest clause) "Add a clause to the data base." `(add-clause ',(make-anonymous clause))) (defun make-anonymous (exp &optional (anon-vars (anonymous-variables-in exp))) "Replace variables that are only used once with ?." (cond ((consp exp) (reuse-cons (make-anonymous (first exp) anon-vars) (make-anonymous (rest exp) anon-vars) exp)) ((member exp anon-vars) '?) (t exp))) (defun anonymous-variables-in (tree) "Return a list of all variables that occur only once in tree." (values (anon-vars-in tree nil nil))) (defun anon-vars-in (tree seen-once seen-more) "Walk the data structure TREE, returning a list of variabless seen once, and a list of variables seen more than once." (cond ((consp tree) (multiple-value-bind (new-seen-once new-seen-more) (anon-vars-in (first tree) seen-once seen-more) (anon-vars-in (rest tree) new-seen-once new-seen-more))) ((not (variable-p tree)) (values seen-once seen-more)) ((member tree seen-once) (values (delete tree seen-once) (cons tree seen-more))) ((member tree seen-more) (values seen-once seen-more)) (t (values (cons tree seen-once) seen-more)))) (defun compile-unify (x y bindings) "Return 2 values: code to test if x and y unify, and a new binding list." (cond 1,2 (values (equal x y) bindings)) 3 (multiple-value-bind (code1 bindings1) (compile-unify (first x) (first y) bindings) (multiple-value-bind (code2 bindings2) (compile-unify (rest x) (rest y) bindings1) (values (compile-if code1 code2) bindings2)))) ((variable-p x) (compile-unify-variable x y bindings)) (t (compile-unify-variable y x bindings)))) (defun compile-if (pred then-part) "Compile a Lisp IF form. No else-part allowed." (case pred ((t) then-part) ((nil) nil) (otherwise `(if ,pred ,then-part)))) (defun compile-unify-variable (x y bindings) "X is a variable, and Y may be." (let* ((xb (follow-binding x bindings)) (x1 (if xb (cdr xb) x)) (yb (if (variable-p y) (follow-binding y bindings))) (y1 (if yb (cdr yb) y))) 12 (compile-unify x1 y1 bindings)) 11 7,10 (values `(unify! ,x1 ,(compile-arg y1 bindings)) (bind-variables-in y1 bindings))) ((not (null xb)) (if (and (variable-p y1) (null yb)) 4 (values `(unify! ,x1 ,(compile-arg y1 bindings)) 5,6 ((not (null yb)) (compile-unify-variable y1 x1 bindings)) 8,9 (defun bind-variables-in (exp bindings) "Bind all variables in exp to themselves, and add that to bindings (except for variables already bound)." (dolist (var (variables-in exp)) (unless (get-binding var bindings) (setf bindings (extend-bindings var var bindings)))) bindings) (defun follow-binding (var bindings) "Get the ultimate binding of var according to bindings." (let ((b (get-binding var bindings))) (if (eq (car b) (cdr b)) b (or (follow-binding (cdr b) bindings) b)))) (defun compile-arg (arg bindings) "Generate code for an argument to a goal in the body." (cond ((eq arg '?) '(?)) ((variable-p arg) (let ((binding (get-binding arg bindings))) (if (and (not (null binding)) (not (eq arg (binding-val binding)))) (compile-arg (binding-val binding) bindings) arg))) ((not (find-if-anywhere #'variable-p arg)) `',arg) ((proper-listp arg) `(list .,(mapcar #'(lambda (a) (compile-arg a bindings)) arg))) (t `(cons ,(compile-arg (first arg) bindings) ,(compile-arg (rest arg) bindings))))) (defun bind-new-variables (bindings goal) "Extend bindings to include any unbound variables in goal." (let ((variables (remove-if #'(lambda (v) (assoc v bindings)) (variables-in goal)))) (nconc (mapcar #'self-cons variables) bindings))) (defun self-cons (x) (cons x x)) (def-prolog-compiler-macro = (goal body cont bindings) "Compile a goal which is a call to =." (let ((args (args goal))) (if (/= (length args) 2) (multiple-value-bind (code1 bindings1) (compile-unify (first args) (second args) bindings) (compile-if code1 (compile-body body cont bindings1)))))) (defun compile-clause (parms clause cont) "Transform away the head, and compile the resulting body." (bind-unbound-vars parms (compile-body (nconc (mapcar #'make-= parms (args (clause-head clause))) (clause-body clause)) cont (defvar *uncompiled* nil "Prolog symbols that have not been compiled.") (defun add-clause (clause) "Add a clause to the data base, indexed by head's predicate." (let ((pred (predicate (clause-head clause)))) (assert (and (symbolp pred) (not (variable-p pred)))) (pushnew pred *db-predicates*) (setf (get pred 'clauses) (nconc (get-clauses pred) (list clause))) pred)) (defun top-level-prove (goals) "Prove the list of goals by compiling and calling it." First redefine top - level - query (clear-predicate 'top-level-query) (let ((vars (delete '? (variables-in goals)))) (add-clause `((top-level-query) ,@goals (show-prolog-vars ,(mapcar #'symbol-name vars) ,vars)))) (run-prolog 'top-level-query/0 #'ignore) (format t "~&No.") (values)) (defun run-prolog (procedure cont) "Run a 0-ary prolog procedure with a given continuation." First compile anything else that needs it (prolog-compile-symbols) (setf (fill-pointer *trail*) 0) (setf *var-counter* 0) (catch 'top-level-prove (funcall procedure cont))) (defun prolog-compile-symbols (&optional (symbols *uncompiled*)) "Compile a list of Prolog symbols. By default, the list is all symbols that need it." (mapc #'prolog-compile symbols) (setf *uncompiled* (set-difference *uncompiled* symbols))) (defun ignore (&rest args) (declare (ignore args)) nil) (defun show-prolog-vars/2 (var-names vars cont) "Display the variables, and prompt the user to see if we should continue. If not, return to the top level." (if (null vars) (format t "~&Yes") (loop for name in var-names for var in vars do (format t "~&~a = ~a" name (deref-exp var)))) (if (continue-p) (funcall cont) (throw 'top-level-prove nil))) (defun deref-exp (exp) "Build something equivalent to EXP with variables dereferenced." (if (atom (deref exp)) exp (reuse-cons (deref-exp (first exp)) (deref-exp (rest exp)) exp))) (defvar *predicate* nil "The Prolog predicate currently being compiled") (defun compile-predicate (symbol arity clauses) "Compile all the clauses for a given symbol/arity into a single LISP function." (parameters (make-parameters arity))) (compile (eval `(defun ,*predicate* (,@parameters cont) .,(maybe-add-undo-bindings (mapcar #'(lambda (clause) (compile-clause parameters clause 'cont)) clauses))))))) (defun compile-body (body cont bindings) "Compile the body of a clause." (cond ((null body) `(funcall ,cont)) (t (let* ((goal (first body)) (macro (prolog-compiler-macro (predicate goal))) (macro-val (if macro (funcall macro goal (rest body) cont bindings)))) (if (and macro (not (eq macro-val :pass))) macro-val `(,(make-predicate (predicate goal) (relation-arity goal)) ,@(mapcar #'(lambda (arg) (compile-arg arg bindings)) (args goal)) ,(if (null (rest body)) cont `#'(lambda () ,(compile-body (rest body) cont (bind-new-variables bindings goal)))))))))) Code from Paradigms of AI Programming Copyright ( c ) 1991 Bug fix by , . Trivia : Farquhar is 's cousin . ( requires " prologc " ) (defun read/1 (exp cont) (if (unify! exp (read)) (funcall cont))) (defun write/1 (exp cont) (write (deref-exp exp) :pretty t) (funcall cont)) (defun nl/0 (cont) (terpri) (funcall cont)) (defun =/2 (?arg1 ?arg2 cont) (if (unify! ?arg1 ?arg2) (funcall cont))) (defun ==/2 (?arg1 ?arg2 cont) "Are the two arguments EQUAL with no unification, but with dereferencing? If so, succeed." (if (deref-equal ?arg1 ?arg2) (funcall cont))) (defun deref-equal (x y) "Are the two arguments EQUAL with no unification, but with dereferencing?" (or (eql (deref x) (deref y)) (and (consp x) (consp y) (deref-equal (first x) (first y)) (deref-equal (rest x) (rest y))))) (defun call/1 (goal cont) "Try to prove goal by calling it." (deref goal) (apply (make-predicate (first goal) (length (args goal))) (append (args goal) (list cont)))) (<- (or ?a ?b) (call ?a)) (<- (or ?a ?b) (call ?b)) (<- (and ?a ?b) (call ?a) (call ?b)) (defmacro with-undo-bindings (&body body) "Undo bindings after each expression in body except the last." (if (length=1 body) (first body) `(let ((old-trail (fill-pointer *trail*))) ,(first body) ,@(loop for exp in (rest body) collect '(undo-bindings! old-trail) collect exp)))) (defun not/1 (relation cont) "Negation by failure: If you can't prove G, then (not G) true." (with-undo-bindings (call/1 relation #'(lambda () (return-from not/1 nil))) (funcall cont))) (defun bagof/3 (exp goal result cont) "Find all solutions to GOAL, and for each solution, collect the value of EXP into the list RESULT." Ex : Assume ( p 1 ) ( p 2 ) ( p 3 ) . Then : ( bagof ? x ( p ? x ) ? l ) = = > ? l = ( 1 2 3 ) (let ((answers nil)) (call/1 goal #'(lambda () Bug fix by mdf0% ( ) (push (deref-EXP exp) answers))) (if (and (not (null answers)) (unify! result (nreverse answers))) (funcall cont)))) (defun deref-copy (exp) "Copy the expression, replacing variables with new ones. The part without variables can be returned as is." Bug fix by farquhar and , 12/12/92 . Forgot to deref var . (sublis (mapcar #'(lambda (var) (cons (deref var) (?))) (unique-find-anywhere-if #'var-p exp)) exp)) (defun setof/3 (exp goal result cont) "Find all unique solutions to GOAL, and for each solution, collect the value of EXP into the list RESULT." Ex : Assume ( p 1 ) ( p 2 ) ( p 3 ) . Then : ( setof ? x ( p ? x ) ? l ) = = > ? l = ( 1 2 3 ) (let ((answers nil)) (call/1 goal #'(lambda () (push (deref-copy exp) answers))) (if (and (not (null answers)) (unify! result (delete-duplicates answers :test #'deref-equal))) (funcall cont)))) (defun is/2 (var exp cont) Or even : ( is ( ? x ? y ? x ) ( cons ( first ? z ) ? l ) ) (if (and (not (find-if-anywhere #'unbound-var-p exp)) (unify! var (eval (deref-exp exp)))) (funcall cont))) (defun unbound-var-p (exp) "Is EXP an unbound var?" (and (var-p exp) (not (bound-p exp)))) (defun var/1 (?arg1 cont) "Succeeds if ?arg1 is an uninstantiated variable." (if (unbound-var-p ?arg1) (funcall cont))) (defun lisp/2 (?result exp cont) "Apply (first exp) to (rest exp), and return the result." (if (and (consp (deref exp)) (unify! ?result (apply (first exp) (rest exp)))) (funcall cont))) (defun repeat/0 (cont) (loop (funcall cont))) (<- (if ?test ?then) (if ?then ?else (fail))) (<- (if ?test ?then ?else) (call ?test) ! (call ?then)) (<- (if ?test ?then ?else) (call ?else)) (<- (member ?item (?item . ?rest))) (<- (member ?item (?x . ?rest)) (member ?item ?rest)) (<- (length () 0)) (<- (length (?x . ?y) (1+ ?n)) (length ?y ?n)) (defun numberp/1 (x cont) (when (numberp (deref x)) (funcall cont))) (defun atom/1 (x cont) (when (atom (deref x)) (funcall cont)))
39f01797563e0fee57ec31fbed581321892317296837b1e9faa8eb3984e59811
winny-/runomatic
bot.rkt
#lang racket (provide (all-defined-out) (all-from-out "types.rkt")) (require "client.rkt" "types.rkt" gregor) (define (my-player state) (match state [(struct* GameState ([players players])) (for/first ([p players] #:when (Player-id p)) p)])) (define (my-hand state) (Player-hand (my-player state))) (define (admin-player state) (match state [(struct* GameState ([players players])) (for/first ([p players] #:when (Player-admin p)) p)])) (define (my-turn? state) (and (GameState-active state) (let ([me (my-player state)]) (Player-active me)))) (define (playable-card? state card) (and (my-turn? state) (let ([last-discard (GameState-last-discard state)]) (match card [(struct Card (_ _ (or "WILD" "WILD_DRAW_FOUR"))) #t] [(struct Card (_ (? (curry equal? (Card-color last-discard))) _)) #t] [(struct Card (_ _ (? (curry equal? (Card-value last-discard))))) #t] [_ #f])))) (define (playable-cards state) (if (my-turn? state) (filter (curry playable-card? state) (Player-hand (my-player state))) empty)) (define (actions state) (and (my-turn? state) (append (playable-cards state) (list 'draw)))) (define (hand-by-color hand) (for/hash ([color '("RED" "GREEN" "BLUE" "YELLOW")]) (values color (filter (λ (c) (equal? color (Card-color c))) hand)))) (define (select-wildcard-color state) (let ([h (hash->list (hand-by-color (my-hand state)))]) (if (empty? h) "BLUE" (car (argmax (match-lambda [(cons color cards) (length cards)]) h))))) (define (select-action state) (define available (actions state)) (define-values (last-resort colored) (partition (match-lambda [(struct* Card ([value (or "WILD" "WILD_DRAW_FOUR")])) #t] [_ #f]) (filter Card? available))) (cond [(not (empty? colored)) (or (findf (λ (c) (member (Card-value c) '("DRAW_TWO" "SKIP" "REVERSE"))) colored) (car colored))] [(not (empty? last-resort)) (struct-copy Card (car last-resort) [color (select-wildcard-color state)])] [else (car available)])) (define (play-turn g [state (get-state g)]) (and (my-turn? state) (match (select-action state) ['draw (draw-card g)] [(struct* Card ([id id] [color color])) (play-card g id color)]))) (define (bot-loop game-descriptor start-game-at-capacity) (display "." (current-error-port)) (flush-output (current-error-port)) (define st (get-state game-descriptor)) (when st (cond [(and (not (GameState-active st)) start-game-at-capacity (>= (length (GameState-players st)) start-game-at-capacity)) (start-game game-descriptor)] [(my-turn? st) (play-turn game-descriptor st)])) (sleep .5) (bot-loop game-descriptor start-game-at-capacity)) (module+ main (define *bot-name* (make-parameter "racket")) (define *game-id* (make-parameter #f)) (define *game-name* (make-parameter #f)) (define *game-descriptor* (make-parameter #f)) (define *new-game* (make-parameter #f)) (command-line #:once-each [("-n" "--name") n "The bot's name" (*bot-name* n)] [("-l" "--list") "List open games" (displayln "ID Name Players Created") (for ([g (open-games)]) (match-define (struct OpenGame [id name created players]) g) (printf "~a ~a ~a ~a\n" (~a id #:width 48) (~a name #:width 10) (~a players #:width 7 #:align 'right) (~t created "YYYY-MM-dd HH:mm:ss"))) (exit 0)] #:once-any [("--game-id") i "Join by game ID" (*game-id* i)] [("--game-name") n "Join by game Name" (*game-name* n)] [("--game-descriptor") d "Resume an existing game" (match-define (list game-id player-id) (string-split d ":")) (*game-descriptor* (GameDescriptor game-id player-id))] [("--new-game") num-players "Start a new game, and start when num-players join" (define n (string->number num-players)) (unless n (fprintf (current-error-port) "Could not parse --new-game ~a\n" num-players)) (*new-game* n)] #:args () (cond [(*game-name*) (define game (findf (λ (g) (equal? (*game-name*) (OpenGame-name g))) (open-games))) (unless game (fprintf (current-error-port) "Could not find game \"~a\"\n") (exit 1)) (*game-id* (OpenGame-id game))] [(*game-descriptor*) (*game-id* (GameDescriptor-game-id (*game-descriptor*)))] [(*new-game*) (*game-descriptor* (new-game (*bot-name*))) (*game-id* (GameDescriptor-game-id (*game-descriptor*)))]) (unless (*game-id*) (fprintf (current-error-port) "Please specify either --game-id, --game-name, --game-descriptor, --new-game.\n") (exit 1)) (*game-descriptor* (or (*game-descriptor*) (join-game (*game-id*) (*bot-name*)))) (unless (*game-descriptor*) (fprintf (current-error-port) "Could not join game with ID ~a\n" (*game-id*)) (exit 1)) (printf "Game name: ~a Game ID: ~a\n" (GameState-name (get-state (*game-descriptor*))) (GameDescriptor-game-id (*game-descriptor*))) (printf "To resume session, use --game-descriptor ~a:~a\n" (GameDescriptor-game-id (*game-descriptor*)) (GameDescriptor-player-id (*game-descriptor*))) (printf "Open this URL to watch the game: ~a\n" (GameDescriptor->url (*game-descriptor*))) (bot-loop (*game-descriptor*) (*new-game*))))
null
https://raw.githubusercontent.com/winny-/runomatic/1043169259980f6092ba2aa13d370c13953c5955/runomatic/bot.rkt
racket
#lang racket (provide (all-defined-out) (all-from-out "types.rkt")) (require "client.rkt" "types.rkt" gregor) (define (my-player state) (match state [(struct* GameState ([players players])) (for/first ([p players] #:when (Player-id p)) p)])) (define (my-hand state) (Player-hand (my-player state))) (define (admin-player state) (match state [(struct* GameState ([players players])) (for/first ([p players] #:when (Player-admin p)) p)])) (define (my-turn? state) (and (GameState-active state) (let ([me (my-player state)]) (Player-active me)))) (define (playable-card? state card) (and (my-turn? state) (let ([last-discard (GameState-last-discard state)]) (match card [(struct Card (_ _ (or "WILD" "WILD_DRAW_FOUR"))) #t] [(struct Card (_ (? (curry equal? (Card-color last-discard))) _)) #t] [(struct Card (_ _ (? (curry equal? (Card-value last-discard))))) #t] [_ #f])))) (define (playable-cards state) (if (my-turn? state) (filter (curry playable-card? state) (Player-hand (my-player state))) empty)) (define (actions state) (and (my-turn? state) (append (playable-cards state) (list 'draw)))) (define (hand-by-color hand) (for/hash ([color '("RED" "GREEN" "BLUE" "YELLOW")]) (values color (filter (λ (c) (equal? color (Card-color c))) hand)))) (define (select-wildcard-color state) (let ([h (hash->list (hand-by-color (my-hand state)))]) (if (empty? h) "BLUE" (car (argmax (match-lambda [(cons color cards) (length cards)]) h))))) (define (select-action state) (define available (actions state)) (define-values (last-resort colored) (partition (match-lambda [(struct* Card ([value (or "WILD" "WILD_DRAW_FOUR")])) #t] [_ #f]) (filter Card? available))) (cond [(not (empty? colored)) (or (findf (λ (c) (member (Card-value c) '("DRAW_TWO" "SKIP" "REVERSE"))) colored) (car colored))] [(not (empty? last-resort)) (struct-copy Card (car last-resort) [color (select-wildcard-color state)])] [else (car available)])) (define (play-turn g [state (get-state g)]) (and (my-turn? state) (match (select-action state) ['draw (draw-card g)] [(struct* Card ([id id] [color color])) (play-card g id color)]))) (define (bot-loop game-descriptor start-game-at-capacity) (display "." (current-error-port)) (flush-output (current-error-port)) (define st (get-state game-descriptor)) (when st (cond [(and (not (GameState-active st)) start-game-at-capacity (>= (length (GameState-players st)) start-game-at-capacity)) (start-game game-descriptor)] [(my-turn? st) (play-turn game-descriptor st)])) (sleep .5) (bot-loop game-descriptor start-game-at-capacity)) (module+ main (define *bot-name* (make-parameter "racket")) (define *game-id* (make-parameter #f)) (define *game-name* (make-parameter #f)) (define *game-descriptor* (make-parameter #f)) (define *new-game* (make-parameter #f)) (command-line #:once-each [("-n" "--name") n "The bot's name" (*bot-name* n)] [("-l" "--list") "List open games" (displayln "ID Name Players Created") (for ([g (open-games)]) (match-define (struct OpenGame [id name created players]) g) (printf "~a ~a ~a ~a\n" (~a id #:width 48) (~a name #:width 10) (~a players #:width 7 #:align 'right) (~t created "YYYY-MM-dd HH:mm:ss"))) (exit 0)] #:once-any [("--game-id") i "Join by game ID" (*game-id* i)] [("--game-name") n "Join by game Name" (*game-name* n)] [("--game-descriptor") d "Resume an existing game" (match-define (list game-id player-id) (string-split d ":")) (*game-descriptor* (GameDescriptor game-id player-id))] [("--new-game") num-players "Start a new game, and start when num-players join" (define n (string->number num-players)) (unless n (fprintf (current-error-port) "Could not parse --new-game ~a\n" num-players)) (*new-game* n)] #:args () (cond [(*game-name*) (define game (findf (λ (g) (equal? (*game-name*) (OpenGame-name g))) (open-games))) (unless game (fprintf (current-error-port) "Could not find game \"~a\"\n") (exit 1)) (*game-id* (OpenGame-id game))] [(*game-descriptor*) (*game-id* (GameDescriptor-game-id (*game-descriptor*)))] [(*new-game*) (*game-descriptor* (new-game (*bot-name*))) (*game-id* (GameDescriptor-game-id (*game-descriptor*)))]) (unless (*game-id*) (fprintf (current-error-port) "Please specify either --game-id, --game-name, --game-descriptor, --new-game.\n") (exit 1)) (*game-descriptor* (or (*game-descriptor*) (join-game (*game-id*) (*bot-name*)))) (unless (*game-descriptor*) (fprintf (current-error-port) "Could not join game with ID ~a\n" (*game-id*)) (exit 1)) (printf "Game name: ~a Game ID: ~a\n" (GameState-name (get-state (*game-descriptor*))) (GameDescriptor-game-id (*game-descriptor*))) (printf "To resume session, use --game-descriptor ~a:~a\n" (GameDescriptor-game-id (*game-descriptor*)) (GameDescriptor-player-id (*game-descriptor*))) (printf "Open this URL to watch the game: ~a\n" (GameDescriptor->url (*game-descriptor*))) (bot-loop (*game-descriptor*) (*new-game*))))
831ed0aeade1027bf03884921ee775fe9ccfcc99b7ae9fc8e92e00b4c4e516f3
parsonsmatt/annotated-exception
UnliftIO.hs
{-# LANGUAGE ExplicitForAll #-} -- | This module presents the same interface as " Control . Exception . Annotated " , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' or ' Control . . Catch . MonadThrow ' . -- -- @since 0.1.2.0 module Control.Exception.Annotated.UnliftIO ( -- * The Main Type AnnotatedException(..) , exceptionWithCallStack , throwWithCallStack -- * Annotating Exceptions , checkpoint , checkpointMany , checkpointCallStack , checkpointCallStackWith -- * Handling Exceptions , catch , catches , tryAnnotated , try -- * Manipulating Annotated Exceptions , check , hide , annotatedExceptionCallStack , addCallStackToException -- * Re-exports from "Data.Annotation" , Annotation(..) , CallStackAnnotation(..) -- * Re-exports from "Control.Exception.Safe" , Exception(..) , Safe.SomeException(..) , throw , Handler (..) , MonadIO(..) , MonadUnliftIO(..) ) where import Control.Exception.Annotated ( AnnotatedException(..) , Annotation(..) , CallStackAnnotation(..) , Exception(..) , Handler(..) , addCallStackToException , annotatedExceptionCallStack , check , exceptionWithCallStack , hide ) import qualified Control.Exception.Annotated as Catch import qualified Control.Exception.Safe as Safe import Control.Monad.IO.Unlift import GHC.Stack -- | Like 'Catch.throwWithCallStack', but uses 'MonadIO' instead of ' Control . . Catch . MonadThrow ' . -- -- @since 0.1.2.0 throwWithCallStack :: forall e m a. (MonadIO m, Exception e, HasCallStack) => e -> m a throwWithCallStack = liftIO . withFrozenCallStack Catch.throwWithCallStack | Like ' Catch.throw ' , but uses ' MonadIO ' instead of ' Control . . Catch . MonadThrow ' . -- -- @since 0.1.2.0 throw :: forall e m a. (MonadIO m, Exception e, HasCallStack) => e -> m a throw = liftIO . withFrozenCallStack Catch.throw | Like ' Catch.checkpoint ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- -- @since 0.1.2.0 checkpoint :: forall m a. (MonadUnliftIO m, HasCallStack) => Annotation -> m a -> m a checkpoint ann action = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack (Catch.checkpoint ann) (runInIO action) | Like ' Catch.checkpointCallStack ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- -- @since 0.2.0.2 checkpointCallStack :: forall m a. (MonadUnliftIO m, HasCallStack) => m a -> m a checkpointCallStack action = withRunInIO $ \runInIO -> withFrozenCallStack Catch.checkpointCallStack (runInIO action) | Like ' Catch.checkpointMany ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- -- @since 0.1.2.0 checkpointMany :: forall m a. (MonadUnliftIO m, HasCallStack) => [Annotation] -> m a -> m a checkpointMany anns action = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack Catch.checkpointMany anns (runInIO action) | Like ' Catch.checkpointCallStackWith ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- Deprecated in 0.2.0.0 as it is now an alias for ' checkpointMany ' . -- -- @since 0.1.2.0 checkpointCallStackWith :: forall m a. (MonadUnliftIO m, HasCallStack) => [Annotation] -> m a -> m a checkpointCallStackWith anns action = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack Catch.checkpointCallStackWith anns (runInIO action) {-# DEPRECATED checkpointCallStackWith "As of annotated-exception-0.2.0.0, this is an alias for checkpointMany" #-} | Like ' Catch.catch ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- -- @since 0.1.2.0 catch :: forall e m a. (MonadUnliftIO m, Exception e, HasCallStack) => m a -> (e -> m a) -> m a catch action handler = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack Catch.catch (runInIO action) (\e -> runInIO $ handler e) | Like ' Catch.tryAnnotated ' but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- -- @since 0.1.2.0 tryAnnotated :: forall e m a. (MonadUnliftIO m, Exception e) => m a -> m (Either (AnnotatedException e) a) tryAnnotated action = withRunInIO $ \runInIO -> liftIO $ Catch.tryAnnotated (runInIO action) | Like ' Catch.try ' but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- -- @since 0.1.2.0 try :: forall e m a. (MonadUnliftIO m, Exception e) => m a -> m (Either e a) try action = withRunInIO $ \runInIO -> liftIO $ Catch.try (runInIO action) | Like ' Catch.catches ' , uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . -- -- @since 0.1.2.0 catches :: forall m a. (MonadUnliftIO m, HasCallStack) => m a -> [Handler m a] -> m a catches action handlers = withRunInIO $ \runInIO -> do let f (Handler k) = Handler (\e -> runInIO (k e)) liftIO $ withFrozenCallStack Catch.catches (runInIO action) (map f handlers)
null
https://raw.githubusercontent.com/parsonsmatt/annotated-exception/83623c26ef266aca6f077d269cca96cd8fafbace/src/Control/Exception/Annotated/UnliftIO.hs
haskell
# LANGUAGE ExplicitForAll # | This module presents the same interface as @since 0.1.2.0 * The Main Type * Annotating Exceptions * Handling Exceptions * Manipulating Annotated Exceptions * Re-exports from "Data.Annotation" * Re-exports from "Control.Exception.Safe" | Like 'Catch.throwWithCallStack', but uses 'MonadIO' instead of @since 0.1.2.0 @since 0.1.2.0 @since 0.1.2.0 @since 0.2.0.2 @since 0.1.2.0 @since 0.1.2.0 # DEPRECATED checkpointCallStackWith "As of annotated-exception-0.2.0.0, this is an alias for checkpointMany" # @since 0.1.2.0 @since 0.1.2.0 @since 0.1.2.0 @since 0.1.2.0
" Control . Exception . Annotated " , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' or ' Control . . Catch . MonadThrow ' . module Control.Exception.Annotated.UnliftIO AnnotatedException(..) , exceptionWithCallStack , throwWithCallStack , checkpoint , checkpointMany , checkpointCallStack , checkpointCallStackWith , catch , catches , tryAnnotated , try , check , hide , annotatedExceptionCallStack , addCallStackToException , Annotation(..) , CallStackAnnotation(..) , Exception(..) , Safe.SomeException(..) , throw , Handler (..) , MonadIO(..) , MonadUnliftIO(..) ) where import Control.Exception.Annotated ( AnnotatedException(..) , Annotation(..) , CallStackAnnotation(..) , Exception(..) , Handler(..) , addCallStackToException , annotatedExceptionCallStack , check , exceptionWithCallStack , hide ) import qualified Control.Exception.Annotated as Catch import qualified Control.Exception.Safe as Safe import Control.Monad.IO.Unlift import GHC.Stack ' Control . . Catch . MonadThrow ' . throwWithCallStack :: forall e m a. (MonadIO m, Exception e, HasCallStack) => e -> m a throwWithCallStack = liftIO . withFrozenCallStack Catch.throwWithCallStack | Like ' Catch.throw ' , but uses ' MonadIO ' instead of ' Control . . Catch . MonadThrow ' . throw :: forall e m a. (MonadIO m, Exception e, HasCallStack) => e -> m a throw = liftIO . withFrozenCallStack Catch.throw | Like ' Catch.checkpoint ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . checkpoint :: forall m a. (MonadUnliftIO m, HasCallStack) => Annotation -> m a -> m a checkpoint ann action = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack (Catch.checkpoint ann) (runInIO action) | Like ' Catch.checkpointCallStack ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . checkpointCallStack :: forall m a. (MonadUnliftIO m, HasCallStack) => m a -> m a checkpointCallStack action = withRunInIO $ \runInIO -> withFrozenCallStack Catch.checkpointCallStack (runInIO action) | Like ' Catch.checkpointMany ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . checkpointMany :: forall m a. (MonadUnliftIO m, HasCallStack) => [Annotation] -> m a -> m a checkpointMany anns action = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack Catch.checkpointMany anns (runInIO action) | Like ' Catch.checkpointCallStackWith ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . Deprecated in 0.2.0.0 as it is now an alias for ' checkpointMany ' . checkpointCallStackWith :: forall m a. (MonadUnliftIO m, HasCallStack) => [Annotation] -> m a -> m a checkpointCallStackWith anns action = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack Catch.checkpointCallStackWith anns (runInIO action) | Like ' Catch.catch ' , but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . catch :: forall e m a. (MonadUnliftIO m, Exception e, HasCallStack) => m a -> (e -> m a) -> m a catch action handler = withRunInIO $ \runInIO -> liftIO $ withFrozenCallStack Catch.catch (runInIO action) (\e -> runInIO $ handler e) | Like ' Catch.tryAnnotated ' but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . tryAnnotated :: forall e m a. (MonadUnliftIO m, Exception e) => m a -> m (Either (AnnotatedException e) a) tryAnnotated action = withRunInIO $ \runInIO -> liftIO $ Catch.tryAnnotated (runInIO action) | Like ' Catch.try ' but uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . try :: forall e m a. (MonadUnliftIO m, Exception e) => m a -> m (Either e a) try action = withRunInIO $ \runInIO -> liftIO $ Catch.try (runInIO action) | Like ' Catch.catches ' , uses ' MonadUnliftIO ' instead of ' Control . . Catch . MonadCatch ' . catches :: forall m a. (MonadUnliftIO m, HasCallStack) => m a -> [Handler m a] -> m a catches action handlers = withRunInIO $ \runInIO -> do let f (Handler k) = Handler (\e -> runInIO (k e)) liftIO $ withFrozenCallStack Catch.catches (runInIO action) (map f handlers)
2c677b80c96c654a4c89e89c3abd8d6fcb553966a94ca43b3d97fa42ec28cc13
vlstill/hsExprTest
rebind.1.ok.hs
myif :: Bool -> a -> a -> a myif True x _ = x myif False _ y = y
null
https://raw.githubusercontent.com/vlstill/hsExprTest/391fc823c1684ec248ac8f76412fefeffb791865/examples/rebind.1.ok.hs
haskell
myif :: Bool -> a -> a -> a myif True x _ = x myif False _ y = y
18f55285d242828746b2079195cd673f8b1f46181c9a39dca6faed627980ba0e
RefactoringTools/wrangler
dets_eqc.erl
-module(dets_eqc). -include_lib("eqc/include/eqc.hrl"). -include_lib("eqc/include/eqc_fsm.hrl"). -compile(export_all). -ifndef(BUG_OPEN_FILE). -define(BUG_OPEN_FILE,false). -endif. -ifndef(BUG_INSERT_NEW). -define(BUG_INSERT_NEW,true). -endif. -record(state,{name,type,contents=[]}). -behaviour(common). module_name() -> dets. table_name() -> dets_table. init_state(S) -> common:init_state(?MODULE, S). opened(S) -> common:common_5(?MODULE, S). object() -> common:object(?MODULE). pattern() -> common:pattern(?MODULE). %% Identify the initial state initial_state() -> init_state. Initialize the state data initial_state_data() -> #state{}. Next state transformation for state data . %% S is the current state, From and To are state names next_state_data(_From,_To,S,V,{call,_,open_file,[_,[{type,T}]]}) -> common:common_1(S, T, V); next_state_data(_From,_To,S,_V,{call,_,insert,[_,Objs]}) -> common:common_8(?MODULE, Objs, S); next_state_data(_From,_To,S,_V,{call,_,insert_new,[_,Objs]}) -> common:common_3(?MODULE, Objs, S); next_state_data(_From,_To,S,_V,{call,_,delete,[_,K]}) -> common:common_10(?MODULE, K, S); next_state_data(_From,_To,S,_V,{call,_,_,_}) -> S. precondition(From, To, S, X4) -> common:precondition(?MODULE, From, To, S, X4). %% Postcondition, checked after command has been evaluated OBS : S is the state before next_state_data(From , To , S,_,<command > ) postcondition(_From,_To,_S,{call,_,close,_},Res) -> common:common_9(Res); %% not_owner in parallel tests postcondition(_From,_To,_S,{call,_,delete,_},Res) -> Res==ok; postcondition(_From,_To,_S,{call,_,insert,_},Res) -> Res==ok; postcondition(_From,_To,S,{call,_,insert_new,[_,Objs]},Res) -> common:common_7(?MODULE, Objs, Res, S); postcondition(_From,_To,S,{call,_,get_contents,_},Res) -> common:common_2(Res, S); postcondition(_From,_To,_S,{call,_,_,_},_Res) -> true. Model model_insert(T, S, Obj) -> common:model_insert(?MODULE, T, S, Obj). any_exist(Obj, S) -> common:any_exist(?MODULE, Obj, S). model_delete(S, K) -> common:model_delete(S, K). %% Top level property prop_dets() -> common:common_6(?MODULE, Cmds). Parallel testing property prop_parallel() -> common:prop_parallel(?MODULE). weight(From, To, X3) -> common:weight(From, To, X3). open_file(Name,Args) -> {ok,N} = dets:open_file(Name,Args), N. %% Operations for inclusion in test cases get_contents(Name) -> dets:traverse(Name,fun(X)->{continue,X}end). file_delete(Name) -> common:common_4(?MODULE, Name). callback_1() -> insert_new. callback_2() -> close. callback_3(S) -> [{type,S#state.type}]. callback_4() -> [{opened,{call,module_name(),delete,[table_name(),nat()]}}, {opened,{call,?MODULE,get_contents,[table_name()]}} ]. callback_5() -> oneof([object(),list(object())]). callback_6() -> ?MODULE. callback_7() -> open_file. callback_8() -> insert. callback_9(Cmds) -> dets:close(table_name()), file_delete(table_name()), {H,S,Res} = run_commands(?MODULE,Cmds), common:common_11(?MODULE, Cmds, H, Res, S). callback_10() -> ?MODULE. callback_11() -> open_file. callback_12() -> [{type,oneof([set,bag])}]. callback_13(From) -> From == init_state orelse ?BUG_OPEN_FILE. callback_14(Par, Seq) -> %% Make sure the table is not left open by a previous test. [dets:close(table_name()) || _ <- "abcdefghijkl"], %% Make sure the table is initially empty. file_delete(table_name()), %% Run the test case. {H,ParH,Res} = run_parallel_commands(?MODULE,{Seq,Par}), common:common_12(?MODULE, H, Par, ParH, Res).
null
https://raw.githubusercontent.com/RefactoringTools/wrangler/1c33ad0e923bb7bcebb6fd75347638def91e50a8/examples/behaviour_extraction/ets_dets/automatic_output/dets_eqc.erl
erlang
Identify the initial state S is the current state, From and To are state names Postcondition, checked after command has been evaluated not_owner in parallel tests Top level property Operations for inclusion in test cases Make sure the table is not left open by a previous test. Make sure the table is initially empty. Run the test case.
-module(dets_eqc). -include_lib("eqc/include/eqc.hrl"). -include_lib("eqc/include/eqc_fsm.hrl"). -compile(export_all). -ifndef(BUG_OPEN_FILE). -define(BUG_OPEN_FILE,false). -endif. -ifndef(BUG_INSERT_NEW). -define(BUG_INSERT_NEW,true). -endif. -record(state,{name,type,contents=[]}). -behaviour(common). module_name() -> dets. table_name() -> dets_table. init_state(S) -> common:init_state(?MODULE, S). opened(S) -> common:common_5(?MODULE, S). object() -> common:object(?MODULE). pattern() -> common:pattern(?MODULE). initial_state() -> init_state. Initialize the state data initial_state_data() -> #state{}. Next state transformation for state data . next_state_data(_From,_To,S,V,{call,_,open_file,[_,[{type,T}]]}) -> common:common_1(S, T, V); next_state_data(_From,_To,S,_V,{call,_,insert,[_,Objs]}) -> common:common_8(?MODULE, Objs, S); next_state_data(_From,_To,S,_V,{call,_,insert_new,[_,Objs]}) -> common:common_3(?MODULE, Objs, S); next_state_data(_From,_To,S,_V,{call,_,delete,[_,K]}) -> common:common_10(?MODULE, K, S); next_state_data(_From,_To,S,_V,{call,_,_,_}) -> S. precondition(From, To, S, X4) -> common:precondition(?MODULE, From, To, S, X4). OBS : S is the state before next_state_data(From , To , S,_,<command > ) postcondition(_From,_To,_S,{call,_,close,_},Res) -> postcondition(_From,_To,_S,{call,_,delete,_},Res) -> Res==ok; postcondition(_From,_To,_S,{call,_,insert,_},Res) -> Res==ok; postcondition(_From,_To,S,{call,_,insert_new,[_,Objs]},Res) -> common:common_7(?MODULE, Objs, Res, S); postcondition(_From,_To,S,{call,_,get_contents,_},Res) -> common:common_2(Res, S); postcondition(_From,_To,_S,{call,_,_,_},_Res) -> true. Model model_insert(T, S, Obj) -> common:model_insert(?MODULE, T, S, Obj). any_exist(Obj, S) -> common:any_exist(?MODULE, Obj, S). model_delete(S, K) -> common:model_delete(S, K). prop_dets() -> common:common_6(?MODULE, Cmds). Parallel testing property prop_parallel() -> common:prop_parallel(?MODULE). weight(From, To, X3) -> common:weight(From, To, X3). open_file(Name,Args) -> {ok,N} = dets:open_file(Name,Args), N. get_contents(Name) -> dets:traverse(Name,fun(X)->{continue,X}end). file_delete(Name) -> common:common_4(?MODULE, Name). callback_1() -> insert_new. callback_2() -> close. callback_3(S) -> [{type,S#state.type}]. callback_4() -> [{opened,{call,module_name(),delete,[table_name(),nat()]}}, {opened,{call,?MODULE,get_contents,[table_name()]}} ]. callback_5() -> oneof([object(),list(object())]). callback_6() -> ?MODULE. callback_7() -> open_file. callback_8() -> insert. callback_9(Cmds) -> dets:close(table_name()), file_delete(table_name()), {H,S,Res} = run_commands(?MODULE,Cmds), common:common_11(?MODULE, Cmds, H, Res, S). callback_10() -> ?MODULE. callback_11() -> open_file. callback_12() -> [{type,oneof([set,bag])}]. callback_13(From) -> From == init_state orelse ?BUG_OPEN_FILE. callback_14(Par, Seq) -> [dets:close(table_name()) || _ <- "abcdefghijkl"], file_delete(table_name()), {H,ParH,Res} = run_parallel_commands(?MODULE,{Seq,Par}), common:common_12(?MODULE, H, Par, ParH, Res).
bc493e33395b602002577faf99a9f8c63cf5abbf0ef96765930c91ec71db2b4d
parsonsmatt/gear-tracker
Component.hs
module Spec.GT.DB.Component where import Spec.GT.DB.Prelude import Database.Persist.Postgresql import GT.DB.Schema.Component import GT.DB.Schema.Bike import qualified GT.DB.Component as Component spec :: SpecWith TestDb spec = do describe "getForBike" $ do itDb "works" $ do let frame = Component { componentName = "Scrubtrout" , componentPart = "Frame" , componentBrand = "Salsa" , componentModel = "Cutthroat" , componentDescription = "" , componentParent = Nothing } frameId <- insert frame bikeId <- insert $ Bike frameId let wheel = Component { componentName = "Good wheel" , componentPart = "Front wheel" , componentBrand = "WTB" , componentModel = "Asym 29" , componentDescription = "it is p good" , componentParent = Just frameId } let handlebars = Component { componentName = "bars" , componentPart = "handlebars" , componentBrand = "Salsa" , componentModel = "Cowchipper 46" , componentDescription = "" , componentParent = Just frameId } wheelId <- insert wheel let tire = Component { componentName = "knobbss" , componentPart = "Tire" , componentBrand = "WTB" , componentModel = "Riddler 45" , componentDescription = "" , componentParent = Just wheelId } tireId <- insert tire handlebarId <- insert handlebars let frame2 = Component { componentName = "Chonker" , componentPart = "Frame" , componentBrand = "Salsa" , componentModel = "Mukluk" , componentDescription = "" , componentParent = Nothing } frame2Id <- insert frame2 bike2Id <- insert $ Bike frame2Id flatboys <- insert Component { componentName = "" , componentPart = "Handlebars" , componentBrand = "Salsa" , componentModel = "Rustler" , componentDescription = "" , componentParent = Just frame2Id } components <- Component.getForBike bikeId map (componentName . entityVal) components `shouldMatchList` map componentName [ wheel, tire, handlebars, frame ]
null
https://raw.githubusercontent.com/parsonsmatt/gear-tracker/b7a597b32322e8938192a443572e6735219ce8ff/test/Spec/GT/DB/Component.hs
haskell
module Spec.GT.DB.Component where import Spec.GT.DB.Prelude import Database.Persist.Postgresql import GT.DB.Schema.Component import GT.DB.Schema.Bike import qualified GT.DB.Component as Component spec :: SpecWith TestDb spec = do describe "getForBike" $ do itDb "works" $ do let frame = Component { componentName = "Scrubtrout" , componentPart = "Frame" , componentBrand = "Salsa" , componentModel = "Cutthroat" , componentDescription = "" , componentParent = Nothing } frameId <- insert frame bikeId <- insert $ Bike frameId let wheel = Component { componentName = "Good wheel" , componentPart = "Front wheel" , componentBrand = "WTB" , componentModel = "Asym 29" , componentDescription = "it is p good" , componentParent = Just frameId } let handlebars = Component { componentName = "bars" , componentPart = "handlebars" , componentBrand = "Salsa" , componentModel = "Cowchipper 46" , componentDescription = "" , componentParent = Just frameId } wheelId <- insert wheel let tire = Component { componentName = "knobbss" , componentPart = "Tire" , componentBrand = "WTB" , componentModel = "Riddler 45" , componentDescription = "" , componentParent = Just wheelId } tireId <- insert tire handlebarId <- insert handlebars let frame2 = Component { componentName = "Chonker" , componentPart = "Frame" , componentBrand = "Salsa" , componentModel = "Mukluk" , componentDescription = "" , componentParent = Nothing } frame2Id <- insert frame2 bike2Id <- insert $ Bike frame2Id flatboys <- insert Component { componentName = "" , componentPart = "Handlebars" , componentBrand = "Salsa" , componentModel = "Rustler" , componentDescription = "" , componentParent = Just frame2Id } components <- Component.getForBike bikeId map (componentName . entityVal) components `shouldMatchList` map componentName [ wheel, tire, handlebars, frame ]
58fcfd6b10911231aa58cd771c5ac113c2cd099e5fe32a717cc4038fddbcd59f
fare/lisp-interface-library
maybe.lisp
(defpackage :lil/interface/monad/test/monad/transformer/maybe (:use :cl :lil/interface/base :lil/interface/monad :lil/interface/monad/maybe :lil/interface/monad/transformer/maybe :lil/interface/monad/transformer :lil/interface/monad/test/monad)) (in-package :lil/interface/monad/test/monad/transformer/maybe) (defmethod test-for-check-monad-laws ((<mt> <maybe-transformer>) v) (test-for-check-monad-laws <maybe> (test-for-check-monad-laws (inner <mt>) v))) (defmethod check-invariant ((<mt> <maybe-transformer>) monad &key &allow-other-keys) (check-invariant <monad> monad) (check-invariant (inner <mt>) monad))
null
https://raw.githubusercontent.com/fare/lisp-interface-library/ac2e0063dc65feb805f0c57715d52fda28d4dcd8/interface/monad/test/monad/transformer/maybe.lisp
lisp
(defpackage :lil/interface/monad/test/monad/transformer/maybe (:use :cl :lil/interface/base :lil/interface/monad :lil/interface/monad/maybe :lil/interface/monad/transformer/maybe :lil/interface/monad/transformer :lil/interface/monad/test/monad)) (in-package :lil/interface/monad/test/monad/transformer/maybe) (defmethod test-for-check-monad-laws ((<mt> <maybe-transformer>) v) (test-for-check-monad-laws <maybe> (test-for-check-monad-laws (inner <mt>) v))) (defmethod check-invariant ((<mt> <maybe-transformer>) monad &key &allow-other-keys) (check-invariant <monad> monad) (check-invariant (inner <mt>) monad))
defa02c89746128ffd4216b434e5abbf5f88c51986098246be5c45c842d575fb
emqx/emqx
emqx_authz_mongodb_SUITE.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_authz_mongodb_SUITE). -compile(nowarn_export_all). -compile(export_all). -include("emqx_authz.hrl"). -include_lib("emqx_connector/include/emqx_connector.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("emqx/include/emqx_placeholder.hrl"). -define(MONGO_HOST, "mongo"). -define(MONGO_CLIENT, 'emqx_authz_mongo_SUITE_client'). all() -> emqx_common_test_helpers:all(?MODULE). groups() -> []. init_per_suite(Config) -> ok = stop_apps([emqx_resource]), case emqx_common_test_helpers:is_tcp_server_available(?MONGO_HOST, ?MONGO_DEFAULT_PORT) of true -> ok = emqx_common_test_helpers:start_apps( [emqx_conf, emqx_authz], fun set_special_configs/1 ), ok = start_apps([emqx_resource]), Config; false -> {skip, no_mongo} end. end_per_suite(_Config) -> ok = emqx_authz_test_lib:restore_authorizers(), ok = stop_apps([emqx_resource]), ok = emqx_common_test_helpers:stop_apps([emqx_authz]). set_special_configs(emqx_authz) -> ok = emqx_authz_test_lib:reset_authorizers(); set_special_configs(_) -> ok. init_per_testcase(_TestCase, Config) -> {ok, _} = mc_worker_api:connect(mongo_config()), ok = emqx_authz_test_lib:reset_authorizers(), Config. end_per_testcase(_TestCase, _Config) -> ok = reset_samples(), ok = mc_worker_api:disconnect(?MONGO_CLIENT). %%------------------------------------------------------------------------------ %% Testcases %%------------------------------------------------------------------------------ t_topic_rules(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ok = emqx_authz_test_lib:test_no_topic_rules(ClientInfo, fun setup_client_samples/2), ok = emqx_authz_test_lib:test_allow_topic_rules(ClientInfo, fun setup_client_samples/2), ok = emqx_authz_test_lib:test_deny_topic_rules(ClientInfo, fun setup_client_samples/2). t_complex_filter(_) -> %% atom and string values also supported ClientInfo = #{ clientid => clientid, username => "username", peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, Samples = [ #{ <<"x">> => #{ <<"u">> => <<"username">>, <<"c">> => [#{<<"c">> => <<"clientid">>}], <<"y">> => 1 }, <<"permission">> => <<"allow">>, <<"action">> => <<"publish">>, <<"topics">> => [<<"t">>] } ], ok = setup_samples(Samples), ok = setup_config( #{ <<"filter">> => #{ <<"x">> => #{ <<"u">> => <<"${username}">>, <<"c">> => [#{<<"c">> => <<"${clientid}">>}], <<"y">> => 1 } } } ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [{allow, publish, <<"t">>}] ). t_mongo_error(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ok = setup_samples([]), ok = setup_config( #{<<"filter">> => #{<<"$badoperator">> => <<"$badoperator">>}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [{deny, publish, <<"t">>}] ). t_lookups(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, cn => <<"cn">>, dn => <<"dn">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ByClientid = #{ <<"clientid">> => <<"clientid">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByClientid]), ok = setup_config( #{<<"filter">> => #{<<"clientid">> => <<"${clientid}">>}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ), ByPeerhost = #{ <<"peerhost">> => <<"127.0.0.1">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByPeerhost]), ok = setup_config( #{<<"filter">> => #{<<"peerhost">> => <<"${peerhost}">>}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ), ByCN = #{ <<"CN">> => <<"cn">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByCN]), ok = setup_config( #{<<"filter">> => #{<<"CN">> => ?PH_CERT_CN_NAME}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ), ByDN = #{ <<"DN">> => <<"dn">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByDN]), ok = setup_config( #{<<"filter">> => #{<<"DN">> => ?PH_CERT_SUBJECT}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ). t_bad_filter(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, cn => <<"cn">>, dn => <<"dn">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ok = setup_config( #{<<"filter">> => #{<<"$in">> => #{<<"a">> => 1}}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {deny, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ). %%------------------------------------------------------------------------------ %% Helpers %%------------------------------------------------------------------------------ populate_records(AclRecords, AdditionalData) -> [maps:merge(Record, AdditionalData) || Record <- AclRecords]. setup_samples(AclRecords) -> ok = reset_samples(), {{true, _}, _} = mc_worker_api:insert(?MONGO_CLIENT, <<"acl">>, AclRecords), ok. setup_client_samples(ClientInfo, Samples) -> #{username := Username} = ClientInfo, Records = lists:map( fun(Sample) -> #{ topics := Topics, permission := Permission, action := Action } = Sample, #{ <<"topics">> => Topics, <<"permission">> => Permission, <<"action">> => Action, <<"username">> => Username } end, Samples ), setup_samples(Records), setup_config(#{<<"filter">> => #{<<"username">> => <<"${username}">>}}). reset_samples() -> {true, _} = mc_worker_api:delete(?MONGO_CLIENT, <<"acl">>, #{}), ok. setup_config(SpecialParams) -> emqx_authz_test_lib:setup_config( raw_mongo_authz_config(), SpecialParams ). raw_mongo_authz_config() -> #{ <<"type">> => <<"mongodb">>, <<"enable">> => <<"true">>, <<"mongo_type">> => <<"single">>, <<"database">> => <<"mqtt">>, <<"collection">> => <<"acl">>, <<"server">> => mongo_server(), <<"filter">> => #{<<"username">> => <<"${username}">>} }. mongo_server() -> iolist_to_binary(io_lib:format("~s", [?MONGO_HOST])). mongo_config() -> [ {database, <<"mqtt">>}, {host, ?MONGO_HOST}, {port, ?MONGO_DEFAULT_PORT}, {register, ?MONGO_CLIENT} ]. start_apps(Apps) -> lists:foreach(fun application:ensure_all_started/1, Apps). stop_apps(Apps) -> lists:foreach(fun application:stop/1, Apps).
null
https://raw.githubusercontent.com/emqx/emqx/dbc10c2eed3df314586c7b9ac6292083204f1f68/apps/emqx_authz/test/emqx_authz_mongodb_SUITE.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. -------------------------------------------------------------------- ------------------------------------------------------------------------------ Testcases ------------------------------------------------------------------------------ atom and string values also supported ------------------------------------------------------------------------------ Helpers ------------------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_authz_mongodb_SUITE). -compile(nowarn_export_all). -compile(export_all). -include("emqx_authz.hrl"). -include_lib("emqx_connector/include/emqx_connector.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -include_lib("emqx/include/emqx_placeholder.hrl"). -define(MONGO_HOST, "mongo"). -define(MONGO_CLIENT, 'emqx_authz_mongo_SUITE_client'). all() -> emqx_common_test_helpers:all(?MODULE). groups() -> []. init_per_suite(Config) -> ok = stop_apps([emqx_resource]), case emqx_common_test_helpers:is_tcp_server_available(?MONGO_HOST, ?MONGO_DEFAULT_PORT) of true -> ok = emqx_common_test_helpers:start_apps( [emqx_conf, emqx_authz], fun set_special_configs/1 ), ok = start_apps([emqx_resource]), Config; false -> {skip, no_mongo} end. end_per_suite(_Config) -> ok = emqx_authz_test_lib:restore_authorizers(), ok = stop_apps([emqx_resource]), ok = emqx_common_test_helpers:stop_apps([emqx_authz]). set_special_configs(emqx_authz) -> ok = emqx_authz_test_lib:reset_authorizers(); set_special_configs(_) -> ok. init_per_testcase(_TestCase, Config) -> {ok, _} = mc_worker_api:connect(mongo_config()), ok = emqx_authz_test_lib:reset_authorizers(), Config. end_per_testcase(_TestCase, _Config) -> ok = reset_samples(), ok = mc_worker_api:disconnect(?MONGO_CLIENT). t_topic_rules(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ok = emqx_authz_test_lib:test_no_topic_rules(ClientInfo, fun setup_client_samples/2), ok = emqx_authz_test_lib:test_allow_topic_rules(ClientInfo, fun setup_client_samples/2), ok = emqx_authz_test_lib:test_deny_topic_rules(ClientInfo, fun setup_client_samples/2). t_complex_filter(_) -> ClientInfo = #{ clientid => clientid, username => "username", peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, Samples = [ #{ <<"x">> => #{ <<"u">> => <<"username">>, <<"c">> => [#{<<"c">> => <<"clientid">>}], <<"y">> => 1 }, <<"permission">> => <<"allow">>, <<"action">> => <<"publish">>, <<"topics">> => [<<"t">>] } ], ok = setup_samples(Samples), ok = setup_config( #{ <<"filter">> => #{ <<"x">> => #{ <<"u">> => <<"${username}">>, <<"c">> => [#{<<"c">> => <<"${clientid}">>}], <<"y">> => 1 } } } ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [{allow, publish, <<"t">>}] ). t_mongo_error(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ok = setup_samples([]), ok = setup_config( #{<<"filter">> => #{<<"$badoperator">> => <<"$badoperator">>}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [{deny, publish, <<"t">>}] ). t_lookups(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, cn => <<"cn">>, dn => <<"dn">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ByClientid = #{ <<"clientid">> => <<"clientid">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByClientid]), ok = setup_config( #{<<"filter">> => #{<<"clientid">> => <<"${clientid}">>}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ), ByPeerhost = #{ <<"peerhost">> => <<"127.0.0.1">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByPeerhost]), ok = setup_config( #{<<"filter">> => #{<<"peerhost">> => <<"${peerhost}">>}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ), ByCN = #{ <<"CN">> => <<"cn">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByCN]), ok = setup_config( #{<<"filter">> => #{<<"CN">> => ?PH_CERT_CN_NAME}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ), ByDN = #{ <<"DN">> => <<"dn">>, <<"topics">> => [<<"a">>], <<"action">> => <<"all">>, <<"permission">> => <<"allow">> }, ok = setup_samples([ByDN]), ok = setup_config( #{<<"filter">> => #{<<"DN">> => ?PH_CERT_SUBJECT}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {allow, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ). t_bad_filter(_Config) -> ClientInfo = #{ clientid => <<"clientid">>, cn => <<"cn">>, dn => <<"dn">>, username => <<"username">>, peerhost => {127, 0, 0, 1}, zone => default, listener => {tcp, default} }, ok = setup_config( #{<<"filter">> => #{<<"$in">> => #{<<"a">> => 1}}} ), ok = emqx_authz_test_lib:test_samples( ClientInfo, [ {deny, subscribe, <<"a">>}, {deny, subscribe, <<"b">>} ] ). populate_records(AclRecords, AdditionalData) -> [maps:merge(Record, AdditionalData) || Record <- AclRecords]. setup_samples(AclRecords) -> ok = reset_samples(), {{true, _}, _} = mc_worker_api:insert(?MONGO_CLIENT, <<"acl">>, AclRecords), ok. setup_client_samples(ClientInfo, Samples) -> #{username := Username} = ClientInfo, Records = lists:map( fun(Sample) -> #{ topics := Topics, permission := Permission, action := Action } = Sample, #{ <<"topics">> => Topics, <<"permission">> => Permission, <<"action">> => Action, <<"username">> => Username } end, Samples ), setup_samples(Records), setup_config(#{<<"filter">> => #{<<"username">> => <<"${username}">>}}). reset_samples() -> {true, _} = mc_worker_api:delete(?MONGO_CLIENT, <<"acl">>, #{}), ok. setup_config(SpecialParams) -> emqx_authz_test_lib:setup_config( raw_mongo_authz_config(), SpecialParams ). raw_mongo_authz_config() -> #{ <<"type">> => <<"mongodb">>, <<"enable">> => <<"true">>, <<"mongo_type">> => <<"single">>, <<"database">> => <<"mqtt">>, <<"collection">> => <<"acl">>, <<"server">> => mongo_server(), <<"filter">> => #{<<"username">> => <<"${username}">>} }. mongo_server() -> iolist_to_binary(io_lib:format("~s", [?MONGO_HOST])). mongo_config() -> [ {database, <<"mqtt">>}, {host, ?MONGO_HOST}, {port, ?MONGO_DEFAULT_PORT}, {register, ?MONGO_CLIENT} ]. start_apps(Apps) -> lists:foreach(fun application:ensure_all_started/1, Apps). stop_apps(Apps) -> lists:foreach(fun application:stop/1, Apps).
6204dead0338c36ce74a382473486b906fa961c1215033a90942281eeb5aa960
haskell-tools/haskell-tools
BindingElem.hs
# LANGUAGE FlexibleContexts # # LANGUAGE MonoLocalBinds # -- | Utilities for transformations that work on both top-level and local definitions module Language.Haskell.Tools.Refactor.Utils.BindingElem where import Control.Reference import Language.Haskell.Tools.AST import Language.Haskell.Tools.Rewrite import SrcLoc (RealSrcSpan) -- | A type class for handling definitions that can appear as both top-level and local definitions class NamedElement d => BindingElem d where -- | Accesses a type signature definition in a local or top-level definition sigBind :: Simple Partial (Ann d IdDom SrcTemplateStage) TypeSignature -- | Accesses a value or function definition in a local or top-level definition valBind :: Simple Partial (Ann d IdDom SrcTemplateStage) ValueBind -- | Accesses a type signature definition in a local or top-level definition fixitySig :: Simple Partial (Ann d IdDom SrcTemplateStage) FixitySignature -- | Creates a new definition from a type signature createTypeSig :: TypeSignature -> Ann d IdDom SrcTemplateStage -- | Creates a new definition from a value or function definition createBinding :: ValueBind -> Ann d IdDom SrcTemplateStage -- | Creates a new fixity signature createFixitySig :: FixitySignature -> Ann d IdDom SrcTemplateStage -- | Checks if a given definition is a type signature isTypeSig :: Ann d IdDom SrcTemplateStage -> Bool -- | Checks if a given definition is a function or value binding isBinding :: Ann d IdDom SrcTemplateStage -> Bool -- | Checks if a given definition is a fixity signature isFixitySig :: Ann d IdDom SrcTemplateStage -> Bool instance BindingElem UDecl where sigBind = declTypeSig valBind = declValBind fixitySig = declFixity createTypeSig = mkTypeSigDecl createBinding = mkValueBinding createFixitySig = mkFixityDecl isTypeSig TypeSigDecl {} = True isTypeSig _ = False isBinding ValueBinding {} = True isBinding _ = False isFixitySig FixityDecl {} = True isFixitySig _ = False instance BindingElem ULocalBind where sigBind = localSig valBind = localVal fixitySig = localFixity createTypeSig = mkLocalTypeSig createBinding = mkLocalValBind createFixitySig = mkLocalFixity isTypeSig LocalTypeSig {} = True isTypeSig _ = False isBinding LocalValBind {} = True isBinding _ = False isFixitySig LocalFixity {} = True isFixitySig _ = False getValBindInList :: BindingElem d => RealSrcSpan -> AnnList d -> Maybe ValueBind getValBindInList sp ls = case ls ^? valBindsInList & filtered (isInside sp) of [] -> Nothing [n] -> Just n _ -> error "getValBindInList: Multiple nodes" valBindsInList :: BindingElem d => Simple Traversal (AnnList d) ValueBind valBindsInList = annList & valBind
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/refactor/Language/Haskell/Tools/Refactor/Utils/BindingElem.hs
haskell
| Utilities for transformations that work on both top-level and local definitions | A type class for handling definitions that can appear as both top-level and local definitions | Accesses a type signature definition in a local or top-level definition | Accesses a value or function definition in a local or top-level definition | Accesses a type signature definition in a local or top-level definition | Creates a new definition from a type signature | Creates a new definition from a value or function definition | Creates a new fixity signature | Checks if a given definition is a type signature | Checks if a given definition is a function or value binding | Checks if a given definition is a fixity signature
# LANGUAGE FlexibleContexts # # LANGUAGE MonoLocalBinds # module Language.Haskell.Tools.Refactor.Utils.BindingElem where import Control.Reference import Language.Haskell.Tools.AST import Language.Haskell.Tools.Rewrite import SrcLoc (RealSrcSpan) class NamedElement d => BindingElem d where sigBind :: Simple Partial (Ann d IdDom SrcTemplateStage) TypeSignature valBind :: Simple Partial (Ann d IdDom SrcTemplateStage) ValueBind fixitySig :: Simple Partial (Ann d IdDom SrcTemplateStage) FixitySignature createTypeSig :: TypeSignature -> Ann d IdDom SrcTemplateStage createBinding :: ValueBind -> Ann d IdDom SrcTemplateStage createFixitySig :: FixitySignature -> Ann d IdDom SrcTemplateStage isTypeSig :: Ann d IdDom SrcTemplateStage -> Bool isBinding :: Ann d IdDom SrcTemplateStage -> Bool isFixitySig :: Ann d IdDom SrcTemplateStage -> Bool instance BindingElem UDecl where sigBind = declTypeSig valBind = declValBind fixitySig = declFixity createTypeSig = mkTypeSigDecl createBinding = mkValueBinding createFixitySig = mkFixityDecl isTypeSig TypeSigDecl {} = True isTypeSig _ = False isBinding ValueBinding {} = True isBinding _ = False isFixitySig FixityDecl {} = True isFixitySig _ = False instance BindingElem ULocalBind where sigBind = localSig valBind = localVal fixitySig = localFixity createTypeSig = mkLocalTypeSig createBinding = mkLocalValBind createFixitySig = mkLocalFixity isTypeSig LocalTypeSig {} = True isTypeSig _ = False isBinding LocalValBind {} = True isBinding _ = False isFixitySig LocalFixity {} = True isFixitySig _ = False getValBindInList :: BindingElem d => RealSrcSpan -> AnnList d -> Maybe ValueBind getValBindInList sp ls = case ls ^? valBindsInList & filtered (isInside sp) of [] -> Nothing [n] -> Just n _ -> error "getValBindInList: Multiple nodes" valBindsInList :: BindingElem d => Simple Traversal (AnnList d) ValueBind valBindsInList = annList & valBind
29c0d2ea07a52363eeadb0e81841ac72922e670322d60383bd73a8c20c2796ea
yallop/ocaml-ctypes
functions.ml
* This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open Ctypes open Foreign module Stubs (F: Ctypes.FOREIGN) = struct open F let callback_returns_int8_t = foreign "callback_returns_int8_t" (funptr Ctypes.(void @-> returning int8_t) @-> returning int8_t) let callback_returns_int16_t = foreign "callback_returns_int16_t" (funptr Ctypes.(void @-> returning int16_t) @-> returning int16_t) let callback_returns_int32_t = foreign "callback_returns_int32_t" (funptr Ctypes.(void @-> returning int32_t) @-> returning int32_t) let callback_returns_int64_t = foreign "callback_returns_int64_t" (funptr Ctypes.(void @-> returning int64_t) @-> returning int64_t) let callback_returns_uint8_t = foreign "callback_returns_uint8_t" (funptr Ctypes.(void @-> returning uint8_t) @-> returning uint8_t) let callback_returns_uint16_t = foreign "callback_returns_uint16_t" (funptr Ctypes.(void @-> returning uint16_t) @-> returning uint16_t) let callback_returns_uint32_t = foreign "callback_returns_uint32_t" (funptr Ctypes.(void @-> returning uint32_t) @-> returning uint32_t) let callback_returns_uint64_t = foreign "callback_returns_uint64_t" (funptr Ctypes.(void @-> returning uint64_t) @-> returning uint64_t) let callback_returns_float = foreign "callback_returns_float" (funptr Ctypes.(void @-> returning float) @-> returning float) let callback_returns_double = foreign "callback_returns_double" (funptr Ctypes.(void @-> returning double) @-> returning double) let callback_returns_bool = foreign "callback_returns_bool" (funptr Ctypes.(void @-> returning bool) @-> returning bool) end
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/tests/test-closure-type-promotion/stubs/functions.ml
ocaml
* This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open Ctypes open Foreign module Stubs (F: Ctypes.FOREIGN) = struct open F let callback_returns_int8_t = foreign "callback_returns_int8_t" (funptr Ctypes.(void @-> returning int8_t) @-> returning int8_t) let callback_returns_int16_t = foreign "callback_returns_int16_t" (funptr Ctypes.(void @-> returning int16_t) @-> returning int16_t) let callback_returns_int32_t = foreign "callback_returns_int32_t" (funptr Ctypes.(void @-> returning int32_t) @-> returning int32_t) let callback_returns_int64_t = foreign "callback_returns_int64_t" (funptr Ctypes.(void @-> returning int64_t) @-> returning int64_t) let callback_returns_uint8_t = foreign "callback_returns_uint8_t" (funptr Ctypes.(void @-> returning uint8_t) @-> returning uint8_t) let callback_returns_uint16_t = foreign "callback_returns_uint16_t" (funptr Ctypes.(void @-> returning uint16_t) @-> returning uint16_t) let callback_returns_uint32_t = foreign "callback_returns_uint32_t" (funptr Ctypes.(void @-> returning uint32_t) @-> returning uint32_t) let callback_returns_uint64_t = foreign "callback_returns_uint64_t" (funptr Ctypes.(void @-> returning uint64_t) @-> returning uint64_t) let callback_returns_float = foreign "callback_returns_float" (funptr Ctypes.(void @-> returning float) @-> returning float) let callback_returns_double = foreign "callback_returns_double" (funptr Ctypes.(void @-> returning double) @-> returning double) let callback_returns_bool = foreign "callback_returns_bool" (funptr Ctypes.(void @-> returning bool) @-> returning bool) end
4d29087b1d5cbd52745f88c9a8d91922fdedb03749d35aca13c2646598aab63f
anoma/juvix
Prealloc.hs
module Juvix.Compiler.Asm.Transformation.Prealloc where import Data.HashMap.Strict qualified as HashMap import Juvix.Compiler.Asm.Options import Juvix.Compiler.Asm.Transformation.Base computeCodePrealloc :: forall r. (Members '[Error AsmError, Reader Options] r) => InfoTable -> Code -> Sem r Code computeCodePrealloc tab code = prealloc <$> foldS sig code (0, []) where -- returns the maximum memory use and the mapping result (Code with the -- Prealloc instructions inserted) sig :: FoldSig StackInfo r (Int, Code) sig = FoldSig { _foldInfoTable = tab, _foldAdjust = second (const []), _foldInstr = const goInstr, _foldBranch = const goBranch, _foldCase = const goCase } goInstr :: CmdInstr -> (Int, Code) -> Sem r (Int, Code) goInstr instr@CmdInstr {..} acc@(k, c) = case _cmdInstrInstruction of AllocConstr tag -> return (k + size, cmd : c) where ci = getConstrInfo tab tag size = getConstrSize (ci ^. constructorRepresentation) (ci ^. constructorArgsNum) AllocClosure InstrAllocClosure {..} -> do opts <- ask let size = getClosureSize opts _allocClosureArgsNum return (k + size, cmd : c) ExtendClosure {} -> do opts <- ask let size = opts ^. optLimits . limitsMaxClosureSize return (k + size, cmd : c) Call {} -> return (0, cmd : prealloc acc) TailCall {} -> return (0, cmd : prealloc acc) CallClosures {} -> return (0, cmd : prealloc acc) TailCallClosures {} -> return (0, cmd : prealloc acc) _ -> return (k, cmd : c) where cmd = Instr instr goBranch :: CmdBranch -> (Int, Code) -> (Int, Code) -> (Int, Code) -> Sem r (Int, Code) goBranch cmd br1 br2 (_, c) = return (0, cmd' : c) where cmd' = Branch cmd { _cmdBranchTrue = prealloc br1, _cmdBranchFalse = prealloc br2 } goCase :: CmdCase -> [(Int, Code)] -> Maybe (Int, Code) -> (Int, Code) -> Sem r (Int, Code) goCase cmd brs md (_, c) = return (0, cmd' : c) where cmd' = Case cmd { _cmdCaseBranches = zipWith CaseBranch (map (^. caseBranchTag) (cmd ^. cmdCaseBranches)) (map prealloc brs), _cmdCaseDefault = fmap prealloc md } prealloc :: (Int, Code) -> Code prealloc (0, c) = c prealloc (n, c) = mkInstr (Prealloc (InstrPrealloc n)) : c computeFunctionPrealloc :: (Members '[Error AsmError, Reader Options] r) => InfoTable -> FunctionInfo -> Sem r FunctionInfo computeFunctionPrealloc tab = liftCodeTransformation (computeCodePrealloc tab) computePrealloc :: (Members '[Error AsmError, Reader Options] r) => InfoTable -> Sem r InfoTable computePrealloc tab = liftFunctionTransformation (computeFunctionPrealloc tab) tab checkCodePrealloc :: forall r. (Members '[Error AsmError, Reader Options] r) => InfoTable -> Code -> Sem r Bool checkCodePrealloc tab code = do f <- foldS sig code id return $ f 0 >= 0 where sig :: FoldSig StackInfo r (Int -> Int) sig = FoldSig { _foldInfoTable = tab, _foldAdjust = id, _foldInstr = const goInstr, _foldBranch = const goBranch, _foldCase = const goCase } goInstr :: CmdInstr -> (Int -> Int) -> Sem r (Int -> Int) goInstr CmdInstr {..} cont = case _cmdInstrInstruction of Prealloc InstrPrealloc {..} -> return $ \k -> if k < 0 then error "check prealloc" else cont _preallocWordsNum AllocConstr tag -> return $ \k -> cont (k - size) where ci = getConstrInfo tab tag size = getConstrSize (ci ^. constructorRepresentation) (ci ^. constructorArgsNum) AllocClosure InstrAllocClosure {..} -> do opts <- ask let size = getClosureSize opts _allocClosureArgsNum return $ \k -> cont (k - size) ExtendClosure {} -> do opts <- ask let size = opts ^. optLimits . limitsMaxClosureSize return $ \k -> cont (k - size) _ -> return id goBranch :: CmdBranch -> (Int -> Int) -> (Int -> Int) -> (Int -> Int) -> Sem r (Int -> Int) goBranch _ br1 br2 cont = return $ \k -> let k1 = br1 k k2 = br2 k in cont (min k1 k2) goCase :: CmdCase -> [Int -> Int] -> Maybe (Int -> Int) -> (Int -> Int) -> Sem r (Int -> Int) goCase _ brs md cont = return $ \k -> let ks = map (\f -> f k) brs kd = fmap (\f -> f k) md k' = min (minimum ks) (fromMaybe k kd) in cont k' checkPrealloc :: Options -> InfoTable -> Bool checkPrealloc opts tab = case run $ runError $ runReader opts sb of Left err -> error (show err) Right b -> b where sb :: Sem '[Reader Options, Error AsmError] Bool sb = allM (checkCodePrealloc tab . (^. functionCode)) (HashMap.elems (tab ^. infoFunctions))
null
https://raw.githubusercontent.com/anoma/juvix/807b3b1770289b8921304e92e7305c55c2e11f8f/src/Juvix/Compiler/Asm/Transformation/Prealloc.hs
haskell
returns the maximum memory use and the mapping result (Code with the Prealloc instructions inserted)
module Juvix.Compiler.Asm.Transformation.Prealloc where import Data.HashMap.Strict qualified as HashMap import Juvix.Compiler.Asm.Options import Juvix.Compiler.Asm.Transformation.Base computeCodePrealloc :: forall r. (Members '[Error AsmError, Reader Options] r) => InfoTable -> Code -> Sem r Code computeCodePrealloc tab code = prealloc <$> foldS sig code (0, []) where sig :: FoldSig StackInfo r (Int, Code) sig = FoldSig { _foldInfoTable = tab, _foldAdjust = second (const []), _foldInstr = const goInstr, _foldBranch = const goBranch, _foldCase = const goCase } goInstr :: CmdInstr -> (Int, Code) -> Sem r (Int, Code) goInstr instr@CmdInstr {..} acc@(k, c) = case _cmdInstrInstruction of AllocConstr tag -> return (k + size, cmd : c) where ci = getConstrInfo tab tag size = getConstrSize (ci ^. constructorRepresentation) (ci ^. constructorArgsNum) AllocClosure InstrAllocClosure {..} -> do opts <- ask let size = getClosureSize opts _allocClosureArgsNum return (k + size, cmd : c) ExtendClosure {} -> do opts <- ask let size = opts ^. optLimits . limitsMaxClosureSize return (k + size, cmd : c) Call {} -> return (0, cmd : prealloc acc) TailCall {} -> return (0, cmd : prealloc acc) CallClosures {} -> return (0, cmd : prealloc acc) TailCallClosures {} -> return (0, cmd : prealloc acc) _ -> return (k, cmd : c) where cmd = Instr instr goBranch :: CmdBranch -> (Int, Code) -> (Int, Code) -> (Int, Code) -> Sem r (Int, Code) goBranch cmd br1 br2 (_, c) = return (0, cmd' : c) where cmd' = Branch cmd { _cmdBranchTrue = prealloc br1, _cmdBranchFalse = prealloc br2 } goCase :: CmdCase -> [(Int, Code)] -> Maybe (Int, Code) -> (Int, Code) -> Sem r (Int, Code) goCase cmd brs md (_, c) = return (0, cmd' : c) where cmd' = Case cmd { _cmdCaseBranches = zipWith CaseBranch (map (^. caseBranchTag) (cmd ^. cmdCaseBranches)) (map prealloc brs), _cmdCaseDefault = fmap prealloc md } prealloc :: (Int, Code) -> Code prealloc (0, c) = c prealloc (n, c) = mkInstr (Prealloc (InstrPrealloc n)) : c computeFunctionPrealloc :: (Members '[Error AsmError, Reader Options] r) => InfoTable -> FunctionInfo -> Sem r FunctionInfo computeFunctionPrealloc tab = liftCodeTransformation (computeCodePrealloc tab) computePrealloc :: (Members '[Error AsmError, Reader Options] r) => InfoTable -> Sem r InfoTable computePrealloc tab = liftFunctionTransformation (computeFunctionPrealloc tab) tab checkCodePrealloc :: forall r. (Members '[Error AsmError, Reader Options] r) => InfoTable -> Code -> Sem r Bool checkCodePrealloc tab code = do f <- foldS sig code id return $ f 0 >= 0 where sig :: FoldSig StackInfo r (Int -> Int) sig = FoldSig { _foldInfoTable = tab, _foldAdjust = id, _foldInstr = const goInstr, _foldBranch = const goBranch, _foldCase = const goCase } goInstr :: CmdInstr -> (Int -> Int) -> Sem r (Int -> Int) goInstr CmdInstr {..} cont = case _cmdInstrInstruction of Prealloc InstrPrealloc {..} -> return $ \k -> if k < 0 then error "check prealloc" else cont _preallocWordsNum AllocConstr tag -> return $ \k -> cont (k - size) where ci = getConstrInfo tab tag size = getConstrSize (ci ^. constructorRepresentation) (ci ^. constructorArgsNum) AllocClosure InstrAllocClosure {..} -> do opts <- ask let size = getClosureSize opts _allocClosureArgsNum return $ \k -> cont (k - size) ExtendClosure {} -> do opts <- ask let size = opts ^. optLimits . limitsMaxClosureSize return $ \k -> cont (k - size) _ -> return id goBranch :: CmdBranch -> (Int -> Int) -> (Int -> Int) -> (Int -> Int) -> Sem r (Int -> Int) goBranch _ br1 br2 cont = return $ \k -> let k1 = br1 k k2 = br2 k in cont (min k1 k2) goCase :: CmdCase -> [Int -> Int] -> Maybe (Int -> Int) -> (Int -> Int) -> Sem r (Int -> Int) goCase _ brs md cont = return $ \k -> let ks = map (\f -> f k) brs kd = fmap (\f -> f k) md k' = min (minimum ks) (fromMaybe k kd) in cont k' checkPrealloc :: Options -> InfoTable -> Bool checkPrealloc opts tab = case run $ runError $ runReader opts sb of Left err -> error (show err) Right b -> b where sb :: Sem '[Reader Options, Error AsmError] Bool sb = allM (checkCodePrealloc tab . (^. functionCode)) (HashMap.elems (tab ^. infoFunctions))
ff62d1ae75361924ee4c36fc0f804cdfb3040a7330f71235f412ee04e7ec9e2c
ocamllabs/opam-doc
index.ml
(* | Direct_path : package * module | Packed_module : package * imports *) type t_value = | Direct_path of string * string | Packed_module of string * (string * Digest.t) list module CrcMap = Map.Make(struct type t = string * Digest.t let compare (s1, d1) (s2, d2) = let sc = String.compare s1 s2 in if sc = 0 then Digest.compare d1 d2 else sc end) module LocalMap = Map.Make( struct type t = string option * string (* Packer * name *) let compare (s1, d1) (s2,d2) = let sc = compare s1 s2 in if sc = 0 then compare d1 d2 else sc end) type package_list = (string * Cow.Html.t option) list type global = { map: t_value CrcMap.t ; package_list: package_list } type local = t_value LocalMap.t let read_global_file path = if Opam_doc_config.clear_index () then {map= CrcMap.empty; package_list= []} else try let ic = open_in path in let global = input_value ic in close_in ic; global with | Sys_error _ -> {map= CrcMap.empty; package_list= []} let update_global global filenames = let doFile acc fname = let cmio, cmto = Cmt_format.read fname in match cmio, cmto with (* looking up for a packed cmt *) | Some cmi, Some cmt -> let module_name = cmi.Cmi_format.cmi_name in let (name,crc) = match cmi.Cmi_format.cmi_crcs with | e::_ -> e | _ -> assert false in begin match cmt.Cmt_format.cmt_annots with (* If this is a packed module, we need a way to find the path to submodules *) | Cmt_format.Packed _ -> (* The references should be present in the table after the update *) CrcMap.add (module_name, crc) (* Filter the self-references *) (Packed_module (Opam_doc_config.current_package (), (List.filter ((<>) (name,crc)) cmi.Cmi_format.cmi_crcs))) acc | Cmt_format.Implementation _ | Cmt_format.Interface _ -> CrcMap.add (module_name, crc) (Direct_path (Opam_doc_config.current_package (), module_name)) acc | _ -> acc (* shouldn't happen but you never know :l *) end * In case the cmi is not included in the cmt file | None, Some cmt -> let module_name = cmt.Cmt_format.cmt_modname in let (name, crc) = List.find (fun (n,_) -> module_name = n) cmt.Cmt_format.cmt_imports in begin match cmt.Cmt_format.cmt_annots with | Cmt_format.Packed _ -> (* The references should be present in the table after the update *) CrcMap.add (module_name, crc) (* Filter the self-references *) (Packed_module (Opam_doc_config.current_package (), (List.filter ((<>) (name,crc)) cmt.Cmt_format.cmt_imports))) acc | Cmt_format.Implementation _ | Cmt_format.Interface _ -> CrcMap.add (module_name, crc) (Direct_path (Opam_doc_config.current_package (), module_name)) acc | _ -> acc (* shouldn't happen but you never know :l *) end | _ -> Printf.eprintf "Index.update_global: %s -- Wrong cmt file handed\n%!" fname; acc in let newmap = List.fold_left doFile global.map filenames in { global with map = newmap } let write_global_file global path = let oc = open_out path in output_value oc global; close_out oc let create_local global mds = let rec doMod pack acc ((name, _) as md) = try let value = CrcMap.find md global.map in match value with | Packed_module (_,crcs) -> let acc = List.fold_left (doMod (Some name)) acc crcs in LocalMap.add (pack, name) value acc | Direct_path _ -> LocalMap.add (pack, name) value acc with Not_found -> acc in List.fold_left (doMod None) LocalMap.empty mds let local_lookup local elems = let rec loop pack = function | (m, Uris.Module) :: r -> begin match LocalMap.find (pack, m) local with | Direct_path (pkg, str) -> pkg, (str, Uris.Module) :: r | Packed_module _ -> loop (Some m) r end | _ -> raise Not_found in let package, path = loop None elems in Uris.uri ~package path let get_global_packages global = global.package_list let package_exists global package_name = List.exists (fun (n,_) -> n = package_name) global.package_list let add_global_package global package_name info = let info_opt = if info = "" then None else Some (Cow.Html.of_string info) in let rec add_or_replace acc = function | [] -> List.rev ((package_name, info_opt)::acc) | (h,_)::t when h = package_name -> (package_name, info_opt)::acc@t | h::t -> add_or_replace (h::acc) t in {global with package_list = (add_or_replace [] global.package_list)} Internal references part let internal_table = Hashtbl.create 32 let reset_internal_table () = Hashtbl.reset internal_table let add_internal = Hashtbl.add internal_table let lookup_internal kind id elems = let path = (Hashtbl.find internal_table id) @ [id.Ident.name, kind] @ elems in Uris.uri path
null
https://raw.githubusercontent.com/ocamllabs/opam-doc/4f5a332750177e3016b82d5923a681510335af4c/src/opam-doc-index/index.ml
ocaml
| Direct_path : package * module | Packed_module : package * imports Packer * name looking up for a packed cmt If this is a packed module, we need a way to find the path to submodules The references should be present in the table after the update Filter the self-references shouldn't happen but you never know :l The references should be present in the table after the update Filter the self-references shouldn't happen but you never know :l
type t_value = | Direct_path of string * string | Packed_module of string * (string * Digest.t) list module CrcMap = Map.Make(struct type t = string * Digest.t let compare (s1, d1) (s2, d2) = let sc = String.compare s1 s2 in if sc = 0 then Digest.compare d1 d2 else sc end) module LocalMap = Map.Make( struct let compare (s1, d1) (s2,d2) = let sc = compare s1 s2 in if sc = 0 then compare d1 d2 else sc end) type package_list = (string * Cow.Html.t option) list type global = { map: t_value CrcMap.t ; package_list: package_list } type local = t_value LocalMap.t let read_global_file path = if Opam_doc_config.clear_index () then {map= CrcMap.empty; package_list= []} else try let ic = open_in path in let global = input_value ic in close_in ic; global with | Sys_error _ -> {map= CrcMap.empty; package_list= []} let update_global global filenames = let doFile acc fname = let cmio, cmto = Cmt_format.read fname in match cmio, cmto with | Some cmi, Some cmt -> let module_name = cmi.Cmi_format.cmi_name in let (name,crc) = match cmi.Cmi_format.cmi_crcs with | e::_ -> e | _ -> assert false in begin match cmt.Cmt_format.cmt_annots with | Cmt_format.Packed _ -> CrcMap.add (module_name, crc) (Packed_module (Opam_doc_config.current_package (), (List.filter ((<>) (name,crc)) cmi.Cmi_format.cmi_crcs))) acc | Cmt_format.Implementation _ | Cmt_format.Interface _ -> CrcMap.add (module_name, crc) (Direct_path (Opam_doc_config.current_package (), module_name)) acc end * In case the cmi is not included in the cmt file | None, Some cmt -> let module_name = cmt.Cmt_format.cmt_modname in let (name, crc) = List.find (fun (n,_) -> module_name = n) cmt.Cmt_format.cmt_imports in begin match cmt.Cmt_format.cmt_annots with | Cmt_format.Packed _ -> CrcMap.add (module_name, crc) (Packed_module (Opam_doc_config.current_package (), (List.filter ((<>) (name,crc)) cmt.Cmt_format.cmt_imports))) acc | Cmt_format.Implementation _ | Cmt_format.Interface _ -> CrcMap.add (module_name, crc) (Direct_path (Opam_doc_config.current_package (), module_name)) acc end | _ -> Printf.eprintf "Index.update_global: %s -- Wrong cmt file handed\n%!" fname; acc in let newmap = List.fold_left doFile global.map filenames in { global with map = newmap } let write_global_file global path = let oc = open_out path in output_value oc global; close_out oc let create_local global mds = let rec doMod pack acc ((name, _) as md) = try let value = CrcMap.find md global.map in match value with | Packed_module (_,crcs) -> let acc = List.fold_left (doMod (Some name)) acc crcs in LocalMap.add (pack, name) value acc | Direct_path _ -> LocalMap.add (pack, name) value acc with Not_found -> acc in List.fold_left (doMod None) LocalMap.empty mds let local_lookup local elems = let rec loop pack = function | (m, Uris.Module) :: r -> begin match LocalMap.find (pack, m) local with | Direct_path (pkg, str) -> pkg, (str, Uris.Module) :: r | Packed_module _ -> loop (Some m) r end | _ -> raise Not_found in let package, path = loop None elems in Uris.uri ~package path let get_global_packages global = global.package_list let package_exists global package_name = List.exists (fun (n,_) -> n = package_name) global.package_list let add_global_package global package_name info = let info_opt = if info = "" then None else Some (Cow.Html.of_string info) in let rec add_or_replace acc = function | [] -> List.rev ((package_name, info_opt)::acc) | (h,_)::t when h = package_name -> (package_name, info_opt)::acc@t | h::t -> add_or_replace (h::acc) t in {global with package_list = (add_or_replace [] global.package_list)} Internal references part let internal_table = Hashtbl.create 32 let reset_internal_table () = Hashtbl.reset internal_table let add_internal = Hashtbl.add internal_table let lookup_internal kind id elems = let path = (Hashtbl.find internal_table id) @ [id.Ident.name, kind] @ elems in Uris.uri path
383cc087445966e44ccfbb516586f53fa8f0c97dab83212ec21c8b08f7c36568
cr-org/supernova
Producer.hs
# LANGUAGE FlexibleContexts # | Module : Pulsar . Producer Description : Apache Pulsar client License : Apache-2.0 Maintainer : Stability : experimental The basic producer interaction looks as follows : > > > LOOKUP < < < LOOKUP_RESPONSE > > > PRODUCER < < < SUCCESS > > > SEND 1 > > > SEND 2 < < < SEND_RECEIPT 1 < < < SEND_RECEIPT 2 When the program finishes , either succesfully or due to a failure , we close the producer . > > > CLOSE_PRODUCER < < < SUCCESS Module : Pulsar.Producer Description : Apache Pulsar client License : Apache-2.0 Maintainer : Stability : experimental The basic producer interaction looks as follows: -binary-protocol/#producer >>> LOOKUP <<< LOOKUP_RESPONSE >>> PRODUCER <<< SUCCESS >>> SEND 1 >>> SEND 2 <<< SEND_RECEIPT 1 <<< SEND_RECEIPT 2 When the program finishes, either succesfully or due to a failure, we close the producer. >>> CLOSE_PRODUCER <<< SUCCESS -} module Pulsar.Producer where import Control.Concurrent.Async ( async ) import Control.Monad.Catch ( bracket_ ) import Control.Concurrent.MVar import Control.Monad.IO.Class ( MonadIO , liftIO ) import Control.Monad.Managed ( managed_ , runManaged ) import Control.Monad.Reader ( MonadReader , ask ) import Data.IORef import Data.Text ( Text ) import Pulsar.AppState import qualified Pulsar.Core as C import Pulsar.Connection ( PulsarCtx(..) ) import Pulsar.Types | An abstract ' Producer ' able to ' send ' messages of type ' PulsarMessage ' . newtype Producer m = Producer { send :: PulsarMessage -> m () -- ^ Produces a single message. } data ProducerState = ProducerState { stSeqId :: SeqId -- an incremental message sequence counter , stName :: Text -- a unique name } mkSeqId :: MonadIO m => IORef ProducerState -> m SeqId mkSeqId ref = liftIO $ atomicModifyIORef ref (\(ProducerState s n) -> let s' = s + 1 in (ProducerState s' n, s)) | Create a new ' Producer ' by supplying a ' PulsarCtx ' ( returned by ' Pulsar.connect ' ) and a ' Topic ' . newProducer :: (MonadIO m, MonadReader PulsarCtx m, MonadIO f) => Topic -> m (Producer f) newProducer topic = do (Ctx conn app _) <- ask pid <- mkProducerId app pname <- liftIO $ mkProducer conn pid app pst <- liftIO $ newIORef (ProducerState 0 pname) var <- liftIO newEmptyMVar let release = newReq app >>= \(r, v) -> C.closeProducer conn v pid r handler = managed_ (bracket_ (pure ()) release) >> liftIO (readMVar var) worker <- liftIO $ async (runManaged handler) addWorker app (worker, var) return $ Producer (dispatch conn pid app pst) where newReq app = mkRequestId app dispatch conn pid app pst msg = do sid <- mkSeqId pst var <- registerSeqId app pid sid liftIO $ C.send conn var pid sid msg mkProducer conn pid app = do (req1, var1) <- newReq app C.lookup conn var1 req1 topic (req2, var2) <- newReq app C.newProducer conn var2 req2 pid topic
null
https://raw.githubusercontent.com/cr-org/supernova/602409a18f47a38541ba24f5e885199efd383f48/lib/src/Pulsar/Producer.hs
haskell
^ Produces a single message. an incremental message sequence counter a unique name
# LANGUAGE FlexibleContexts # | Module : Pulsar . Producer Description : Apache Pulsar client License : Apache-2.0 Maintainer : Stability : experimental The basic producer interaction looks as follows : > > > LOOKUP < < < LOOKUP_RESPONSE > > > PRODUCER < < < SUCCESS > > > SEND 1 > > > SEND 2 < < < SEND_RECEIPT 1 < < < SEND_RECEIPT 2 When the program finishes , either succesfully or due to a failure , we close the producer . > > > CLOSE_PRODUCER < < < SUCCESS Module : Pulsar.Producer Description : Apache Pulsar client License : Apache-2.0 Maintainer : Stability : experimental The basic producer interaction looks as follows: -binary-protocol/#producer >>> LOOKUP <<< LOOKUP_RESPONSE >>> PRODUCER <<< SUCCESS >>> SEND 1 >>> SEND 2 <<< SEND_RECEIPT 1 <<< SEND_RECEIPT 2 When the program finishes, either succesfully or due to a failure, we close the producer. >>> CLOSE_PRODUCER <<< SUCCESS -} module Pulsar.Producer where import Control.Concurrent.Async ( async ) import Control.Monad.Catch ( bracket_ ) import Control.Concurrent.MVar import Control.Monad.IO.Class ( MonadIO , liftIO ) import Control.Monad.Managed ( managed_ , runManaged ) import Control.Monad.Reader ( MonadReader , ask ) import Data.IORef import Data.Text ( Text ) import Pulsar.AppState import qualified Pulsar.Core as C import Pulsar.Connection ( PulsarCtx(..) ) import Pulsar.Types | An abstract ' Producer ' able to ' send ' messages of type ' PulsarMessage ' . newtype Producer m = Producer } data ProducerState = ProducerState } mkSeqId :: MonadIO m => IORef ProducerState -> m SeqId mkSeqId ref = liftIO $ atomicModifyIORef ref (\(ProducerState s n) -> let s' = s + 1 in (ProducerState s' n, s)) | Create a new ' Producer ' by supplying a ' PulsarCtx ' ( returned by ' Pulsar.connect ' ) and a ' Topic ' . newProducer :: (MonadIO m, MonadReader PulsarCtx m, MonadIO f) => Topic -> m (Producer f) newProducer topic = do (Ctx conn app _) <- ask pid <- mkProducerId app pname <- liftIO $ mkProducer conn pid app pst <- liftIO $ newIORef (ProducerState 0 pname) var <- liftIO newEmptyMVar let release = newReq app >>= \(r, v) -> C.closeProducer conn v pid r handler = managed_ (bracket_ (pure ()) release) >> liftIO (readMVar var) worker <- liftIO $ async (runManaged handler) addWorker app (worker, var) return $ Producer (dispatch conn pid app pst) where newReq app = mkRequestId app dispatch conn pid app pst msg = do sid <- mkSeqId pst var <- registerSeqId app pid sid liftIO $ C.send conn var pid sid msg mkProducer conn pid app = do (req1, var1) <- newReq app C.lookup conn var1 req1 topic (req2, var2) <- newReq app C.newProducer conn var2 req2 pid topic
cd6b3b768b04675e439bcfb696f6aa3420c67a87ceb929691fb303966b8f5029
graninas/Hydra
FTL.hs
{-# LANGUAGE PackageImports #-} # LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE FlexibleContexts #-} # LANGUAGE ScopedTypeVariables # module FTL where import Control.Monad import Hydra.Prelude import qualified Hydra.FTL as FTL import qualified "hydra-base" Hydra.Runtime as R import Hydra.FTLI () flow :: (MonadIO m, FTL.LangL m) => IORef Int -> m () flow ref = do val' <- liftIO $ readIORef ref val <- FTL.getRandomInt (1, 100) liftIO $ writeIORef ref $ val' + val scenario :: Int -> R.CoreRuntime -> IO () scenario ops coreRt = do ref <- newIORef 0 void $ runReaderT (replicateM_ ops $ flow ref) coreRt val <- readIORef ref print val
null
https://raw.githubusercontent.com/graninas/Hydra/60d591b1300528f5ffd93efa205012eebdd0286c/app/PerfTestApp2/src/FTL.hs
haskell
# LANGUAGE PackageImports # # LANGUAGE FlexibleContexts #
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE ScopedTypeVariables # module FTL where import Control.Monad import Hydra.Prelude import qualified Hydra.FTL as FTL import qualified "hydra-base" Hydra.Runtime as R import Hydra.FTLI () flow :: (MonadIO m, FTL.LangL m) => IORef Int -> m () flow ref = do val' <- liftIO $ readIORef ref val <- FTL.getRandomInt (1, 100) liftIO $ writeIORef ref $ val' + val scenario :: Int -> R.CoreRuntime -> IO () scenario ops coreRt = do ref <- newIORef 0 void $ runReaderT (replicateM_ ops $ flow ref) coreRt val <- readIORef ref print val
9b40fed4900748ef4ceefa7731a59da85655ba4fb1b08e62de299ac48ac5bbd7
ekmett/ekmett.github.com
Apo.hs
{-# OPTIONS_GHC -fglasgow-exts #-} ----------------------------------------------------------------------------- -- | Module : Control . Morphism . Apo Copyright : ( C ) 2008 -- License : BSD-style (see the file LICENSE) -- Maintainer : < > -- Stability : experimental -- Portability : non-portable (rank-2 polymorphism) -- -- Traditional operators, shown here to show how to roll your own ---------------------------------------------------------------------------- module Control.Morphism.Apo ( apo , Apo, ApoT , distApoT , g_apo , GApo, GApoT , distGApo, distGApoT ) where import Control.Functor.Algebra import Control.Functor.Extras import Control.Functor.Fix import Control.Monad import Control.Monad.Either import Control.Morphism.Ana import Control.Arrow ((|||)) -- * Unfold Sugar apo :: Functor f => GCoalgebra f (Apo f) a -> a -> FixF f apo = g_apo outF g_apo :: Functor f => Coalgebra f b -> GCoalgebra f (GApo b) a -> a -> FixF f g_apo g = g_ana (distGApo g) type Apo f a = Either (FixF f) a type ApoT f m a = EitherT (FixF f) m a type GApo b a = Either b a type GApoT b m a = EitherT b m a -- * Distributive Law Combinators distGApo :: Functor f => Coalgebra f b -> Dist (Either b) f distGApo f = fmap Left . f ||| fmap Right distGApoT :: (Functor f, Monad m) => GCoalgebra f m b -> Dist m f -> Dist (EitherT b m) f distGApoT g k = fmap (EitherT . join) . k . liftM (fmap (liftM Left) . g ||| fmap (return . Right)) . runEitherT distApoT :: (Functor f, Monad m) => Dist m f -> Dist (ApoT f m) f distApoT = distGApoT (liftCoalgebra outF)
null
https://raw.githubusercontent.com/ekmett/ekmett.github.com/8d3abab5b66db631e148e1d046d18909bece5893/haskell/category-extras-backup/src/Control/Morphism/Apo.hs
haskell
# OPTIONS_GHC -fglasgow-exts # --------------------------------------------------------------------------- | License : BSD-style (see the file LICENSE) Stability : experimental Portability : non-portable (rank-2 polymorphism) Traditional operators, shown here to show how to roll your own -------------------------------------------------------------------------- * Unfold Sugar * Distributive Law Combinators
Module : Control . Morphism . Apo Copyright : ( C ) 2008 Maintainer : < > module Control.Morphism.Apo ( apo , Apo, ApoT , distApoT , g_apo , GApo, GApoT , distGApo, distGApoT ) where import Control.Functor.Algebra import Control.Functor.Extras import Control.Functor.Fix import Control.Monad import Control.Monad.Either import Control.Morphism.Ana import Control.Arrow ((|||)) apo :: Functor f => GCoalgebra f (Apo f) a -> a -> FixF f apo = g_apo outF g_apo :: Functor f => Coalgebra f b -> GCoalgebra f (GApo b) a -> a -> FixF f g_apo g = g_ana (distGApo g) type Apo f a = Either (FixF f) a type ApoT f m a = EitherT (FixF f) m a type GApo b a = Either b a type GApoT b m a = EitherT b m a distGApo :: Functor f => Coalgebra f b -> Dist (Either b) f distGApo f = fmap Left . f ||| fmap Right distGApoT :: (Functor f, Monad m) => GCoalgebra f m b -> Dist m f -> Dist (EitherT b m) f distGApoT g k = fmap (EitherT . join) . k . liftM (fmap (liftM Left) . g ||| fmap (return . Right)) . runEitherT distApoT :: (Functor f, Monad m) => Dist m f -> Dist (ApoT f m) f distApoT = distGApoT (liftCoalgebra outF)
7ed19753443a73e81f1ae6e541e6c1ddcae78daf9fdf06c39fc6463e70524ae3
babashka/nbb
example.cljs
(ns example "From " (:require ["pdfjs-dist/legacy/build/pdf$default" :as pdfjs] [clojure.string :as str] [promesa.core :as p])) (defn get-text [path] (p/let [doc (.-promise (.getDocument pdfjs path)) page1 (.getPage doc 1) content (.getTextContent page1) strings (map #(.-str %) (.-items content))] (str/join "\n" strings))) (p/let [strs (get-text "pdf-test.pdf")] (println strs))
null
https://raw.githubusercontent.com/babashka/nbb/4d06aa142a5fb5baac48a8ad8e611d672f779b5f/examples/pdfjs/example.cljs
clojure
(ns example "From " (:require ["pdfjs-dist/legacy/build/pdf$default" :as pdfjs] [clojure.string :as str] [promesa.core :as p])) (defn get-text [path] (p/let [doc (.-promise (.getDocument pdfjs path)) page1 (.getPage doc 1) content (.getTextContent page1) strings (map #(.-str %) (.-items content))] (str/join "\n" strings))) (p/let [strs (get-text "pdf-test.pdf")] (println strs))
dfe39fefdf9a9a37592eeea0772f94a543f01d4bd9ba9f0de22d620d2edc5ce5
PEZ/rich4clojure
problem_178.clj
(ns rich4clojure.hard.problem-178 (:require [hyperfiddle.rcf :refer [tests]])) ;; = Best Hand = ;; By 4Clojure user: toolkit ;; Difficulty: Hard ;; Tags: [strings game] ;; Following on from Recognize Playing Cards , determine the best poker hand that can be made with five cards . ;; The hand rankings are listed below for your ;; convenience. ;; ;; * Straight flush: All cards in the same suit, and in ;; sequence * Four of a kind : Four of the cards have the same rank * Full House : Three cards of one rank , the other two of ;; another rank ;; * Flush: All cards in the same suit ;; * Straight: All cards in sequence (aces can be high or ;; low, but not both at once) * Three of a kind : Three of the cards have the same ;; rank * Two pair : Two pairs of cards have the same rank * Pair : Two cards have the same rank ;; * High card: None of the above conditions are met (def __ :tests-will-fail) (comment ) (tests :high-card := (__ ["HA" "D2" "H3" "C9" "DJ"]) :pair := (__ ["HA" "HQ" "SJ" "DA" "HT"]) :two-pair := (__ ["HA" "DA" "HQ" "SQ" "HT"]) :three-of-a-kind := (__ ["HA" "DA" "CA" "HJ" "HT"]) :straight := (__ ["HA" "DK" "HQ" "HJ" "HT"]) :straight := (__ ["HA" "H2" "S3" "D4" "C5"]) :flush := (__ ["HA" "HK" "H2" "H4" "HT"]) :full-house := (__ ["HA" "DA" "CA" "HJ" "DJ"]) :four-of-a-kind := (__ ["HA" "DA" "CA" "SA" "DJ"]) :straight-flush := (__ ["HA" "HK" "HQ" "HJ" "HT"])) ;; Share your solution, and/or check how others did it: ;;
null
https://raw.githubusercontent.com/PEZ/rich4clojure/482f98f95408639bf3ac7a96d59b33efb443db27/src/rich4clojure/hard/problem_178.clj
clojure
= Best Hand = By 4Clojure user: toolkit Difficulty: Hard Tags: [strings game] The hand rankings are listed below for your convenience. * Straight flush: All cards in the same suit, and in sequence another rank * Flush: All cards in the same suit * Straight: All cards in sequence (aces can be high or low, but not both at once) rank * High card: None of the above conditions are met Share your solution, and/or check how others did it:
(ns rich4clojure.hard.problem-178 (:require [hyperfiddle.rcf :refer [tests]])) Following on from Recognize Playing Cards , determine the best poker hand that can be made with five cards . * Four of a kind : Four of the cards have the same rank * Full House : Three cards of one rank , the other two of * Three of a kind : Three of the cards have the same * Two pair : Two pairs of cards have the same rank * Pair : Two cards have the same rank (def __ :tests-will-fail) (comment ) (tests :high-card := (__ ["HA" "D2" "H3" "C9" "DJ"]) :pair := (__ ["HA" "HQ" "SJ" "DA" "HT"]) :two-pair := (__ ["HA" "DA" "HQ" "SQ" "HT"]) :three-of-a-kind := (__ ["HA" "DA" "CA" "HJ" "HT"]) :straight := (__ ["HA" "DK" "HQ" "HJ" "HT"]) :straight := (__ ["HA" "H2" "S3" "D4" "C5"]) :flush := (__ ["HA" "HK" "H2" "H4" "HT"]) :full-house := (__ ["HA" "DA" "CA" "HJ" "DJ"]) :four-of-a-kind := (__ ["HA" "DA" "CA" "SA" "DJ"]) :straight-flush := (__ ["HA" "HK" "HQ" "HJ" "HT"]))
ab9e3c90e9a43c27192ecba378e034deb08717af42c2e5099b70ea3e0cdcf407
NorfairKing/cursor
Gen.hs
# OPTIONS_GHC -fno - warn - orphans # module Cursor.Text.Gen ( genSafeChar, genTextCursorChar, textCursorSentenceGen, textCursorWithGen, textCursorWithIndex0, shrinkSentence, ) where import Cursor.List import Cursor.List.Gen import Cursor.Text import Cursor.Types import Data.Char (isSpace) import Data.GenValidity import Data.GenValidity.Text () import Test.QuickCheck instance GenValid TextCursor where genValid = TextCursor <$> listCursorWithGen genTextCursorChar shrinkValid = shrinkValidStructurally genSafeChar :: Gen Char genSafeChar = choose (minBound, maxBound) `suchThat` isSafeChar genSpaceChar :: Gen Char genSpaceChar = elements [' ', '\t', '\v'] genTextCursorChar :: Gen Char genTextCursorChar = genSafeChar `suchThat` (/= '\n') textCursorWithGen :: Gen Char -> Gen TextCursor textCursorWithGen gen = TextCursor <$> listCursorWithGen gen textCursorWithIndex0 :: Gen Char -> Gen TextCursor textCursorWithIndex0 gen = TextCursor <$> listCursorWithIndex0 gen textCursorSentenceGen :: Gen TextCursor textCursorSentenceGen = textCursorWithGen sentenceGen where sentenceGen :: Gen Char sentenceGen = frequency [(1, genSpaceChar), (5, genSafeChar)] shrinkSentence :: TextCursor -> [TextCursor] shrinkSentence tc@(TextCursor (ListCursor before after)) = filter (/= tc) [TextCursor (ListCursor (map f before) (map f after))] where f :: Char -> Char f x | isSpace x = ' ' | otherwise = 'a'
null
https://raw.githubusercontent.com/NorfairKing/cursor/ff27e78281430c298a25a7805c9c61ca1e69f4c5/cursor-gen/src/Cursor/Text/Gen.hs
haskell
# OPTIONS_GHC -fno - warn - orphans # module Cursor.Text.Gen ( genSafeChar, genTextCursorChar, textCursorSentenceGen, textCursorWithGen, textCursorWithIndex0, shrinkSentence, ) where import Cursor.List import Cursor.List.Gen import Cursor.Text import Cursor.Types import Data.Char (isSpace) import Data.GenValidity import Data.GenValidity.Text () import Test.QuickCheck instance GenValid TextCursor where genValid = TextCursor <$> listCursorWithGen genTextCursorChar shrinkValid = shrinkValidStructurally genSafeChar :: Gen Char genSafeChar = choose (minBound, maxBound) `suchThat` isSafeChar genSpaceChar :: Gen Char genSpaceChar = elements [' ', '\t', '\v'] genTextCursorChar :: Gen Char genTextCursorChar = genSafeChar `suchThat` (/= '\n') textCursorWithGen :: Gen Char -> Gen TextCursor textCursorWithGen gen = TextCursor <$> listCursorWithGen gen textCursorWithIndex0 :: Gen Char -> Gen TextCursor textCursorWithIndex0 gen = TextCursor <$> listCursorWithIndex0 gen textCursorSentenceGen :: Gen TextCursor textCursorSentenceGen = textCursorWithGen sentenceGen where sentenceGen :: Gen Char sentenceGen = frequency [(1, genSpaceChar), (5, genSafeChar)] shrinkSentence :: TextCursor -> [TextCursor] shrinkSentence tc@(TextCursor (ListCursor before after)) = filter (/= tc) [TextCursor (ListCursor (map f before) (map f after))] where f :: Char -> Char f x | isSpace x = ' ' | otherwise = 'a'
e602ac74c1be3bd8d90188a953ef4969d668052ba874721f9b0cb7995873c4d1
ondrap/dynamodb-simple
BaseSpec.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # module BaseSpec where import Control.Exception.Safe (SomeException, catchAny, finally, try) import Control.Lens ((.~)) import Control.Monad.IO.Class (liftIO) import Data.Conduit (runConduit, (=$=)) import qualified Data.Conduit.List as CL import Data.Either (isLeft) import Data.Function ((&)) import Data.List (sort) import Data.Proxy import Data.Semigroup ((<>)) import qualified Data.Text as T import Network.AWS import Network.AWS.DynamoDB (dynamoDB) import System.Environment (setEnv) import System.IO (stdout) import Test.Hspec import Data.Maybe (fromJust) import Database.DynamoDB import Database.DynamoDB.Filter import Database.DynamoDB.TH import Database.DynamoDB.Types (RangeOper (..)) import Database.DynamoDB.Update data Test = Test { iHashKey :: T.Text , iRangeKey :: Int , iText :: T.Text , iBool :: Bool , iDouble :: Double , iInt :: Int , iMText :: Maybe T.Text } deriving (Show, Eq, Ord) data TestKeyOnly = TestKeyOnly { d_iText :: T.Text , d_iHashKey :: T.Text } mkTableDefs "migrateTest" (tableConfig "" (''Test, WithRange) [(''TestKeyOnly, NoRange)] []) data TestSecond = TestSecond { tHashKey :: T.Text , tInt :: Int } deriving (Show, Eq) mkTableDefs "migrateTest2" (tableConfig "" (''TestSecond, NoRange) [] []) withDb :: Example (IO b) => String -> AWS b -> SpecWith (Arg (IO b)) withDb msg code = it msg runcode where runcode = do setEnv "AWS_ACCESS_KEY_ID" "XXXXXXXXXXXXXX" setEnv "AWS_SECRET_ACCESS_KEY" "XXXXXXXXXXXXXXfdjdsfjdsfjdskldfs+kl" lgr <- newLogger Debug stdout env <- newEnv Discover let dynamo = setEndpoint False "localhost" 8000 dynamoDB let newenv = env & configure dynamo -- & set envLogger lgr runResourceT $ runAWS newenv $ do deleteTable (Proxy :: Proxy Test) `catchAny` (\_ -> return ()) migrateTest mempty Nothing migrateTest2 mempty Nothing code `finally` deleteTable (Proxy :: Proxy Test) spec :: Spec spec = do describe "Basic operations" $ do withDb "putItem/getItem works" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 Nothing testitem2 = Test "2" 3 "text" False 4.15 3 (Just "text") putItem testitem1 putItem testitem2 it1 <- getItem Strongly tTest ("1", 2) it2 <- getItem Strongly tTest ("2", 3) liftIO $ Just testitem1 `shouldBe` it1 liftIO $ Just testitem2 `shouldBe` it2 withDb "getItemBatch/putItemBatch work" $ do let template i = Test (T.pack $ show i) i "text" False 3.14 i Nothing newItems = map template [1..300] putItemBatch newItems -- let keys = map tableKey newItems items <- getItemBatch Strongly keys liftIO $ sort items `shouldBe` sort newItems withDb "insertItem doesn't overwrite items" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 Nothing testitem1_ = Test "1" 2 "XXXX" True 3.14 3 Nothing insertItem testitem1 (res :: Either SomeException ()) <- try (insertItem testitem1_) liftIO $ res `shouldSatisfy` isLeft withDb "scanSource works correctly with sLimit" $ do let template i = Test (T.pack $ show i) i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems let squery = scanOpts & sFilterCondition .~ Just (iInt' >. 50) & sLimit .~ Just 1 res <- runConduit $ scanSource tTest squery =$= CL.consume liftIO $ sort res `shouldBe` sort (drop 50 newItems) withDb "querySource works correctly with qLimit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems let squery = queryOpts "hashkey" & qFilterCondition .~ Just (iInt' >. 50) & qLimit .~ Just 1 res <- runConduit $ querySource tTest squery =$= CL.consume liftIO $ res `shouldBe` drop 50 newItems withDb "queryCond works correctly with qLimit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems items <- queryCond tTest "hashkey" Nothing (iInt' >. 50) Forward 5 liftIO $ items `shouldBe` drop 50 newItems withDb "scanCond works correctly" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems items <- scanCond tTest (iInt' >. 50) 5 liftIO $ items `shouldBe` drop 50 newItems withDb "scan works correctly with qlimit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (iInt' >. 50)) 5 liftIO $ items `shouldBe` drop 50 newItems withDb "scan works correctly with `valIn`" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (iInt' `valIn` [20..30])) 50 liftIO $ map iInt items `shouldBe` [20..30] withDb "scan works correctly with BETWEEN" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (iInt' `between` (20, 30))) 50 liftIO $ map iInt items `shouldBe` [20..30] withDb "scan works correctly with SIZE" $ do let testitem1 = Test "1" 2 "very very very very very long" False 3.14 2 Nothing testitem2 = Test "1" 3 "short" False 3.14 2 Nothing putItem testitem1 putItem testitem2 (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (size iText' >. 10)) 50 liftIO $ items `shouldBe` [testitem1] withDb "querySimple works correctly with RangeOper" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems items <- querySimple tTest "hashkey" (Just $ RangeLessThan 30) Backward 5 liftIO $ map iRangeKey items `shouldBe` [29,28..25] withDb "queryCond works correctly with -1 limit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items :: [Test]) <- queryCond tTest "hashkey" Nothing (iInt' >. 50) Backward (-1) liftIO $ items `shouldBe` [] withDb "querySourceByKey works/compiles correctly" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems res <- runConduit $ querySourceByKey iTestKeyOnly "text" =$= CL.consume liftIO $ length res `shouldBe` 55 withDb "updateItemByKey works" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 (Just "something") putItem testitem1 new1 <- updateItemByKey tTest (tableKey testitem1) ((iInt' +=. 5) <> (iText' =. "updated") <> (iMText' =. Nothing)) new2 <- fromJust <$> getItem Strongly tTest (tableKey testitem1) liftIO $ do new1 `shouldBe` new2 iInt new1 `shouldBe` 7 iText new1 `shouldBe` "updated" iMText new1 `shouldBe` Nothing withDb "update fails on non-existing item" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 (Just "something") putItem testitem1 updateItemByKey_ tTest ("1", 2) (iBool' =. True) (res :: Either SomeException ()) <- try $ updateItemByKey_ tTest ("2", 3) (iBool' =. True) liftIO $ res `shouldSatisfy` isLeft withDb "scan continuation works" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (it1, next) <- scan tTest (scanOpts & sFilterCondition .~ Just (iInt' >. 20) & sLimit .~ Just 2) 5 (it2, _) <- scan tTest (scanOpts & sFilterCondition .~ Just (iInt' >. 20) & sLimit .~ Just 1 & sStartKey .~ next) 5 liftIO $ map iInt (it1 ++ it2) `shouldBe` [21..30] withDb "searching empty strings" $ do let testitem1 = Test "1" 2 "" False 3.14 2 Nothing let testitem2 = Test "1" 3 "aaa" False 3.14 2 (Just "test") putItem testitem1 putItem testitem2 items1 <- queryCond tTest "1" Nothing (iText' ==. "") Forward 10 items2 <- queryCond tTest "1" Nothing (iMText' ==. Nothing) Forward 10 liftIO $ items1 `shouldBe` [testitem1] liftIO $ items2 `shouldBe` [testitem1] withDb "deleting by key" $ do let testitem1 = Test "1" 2 "" False 3.14 2 Nothing let testitem2 = Test "1" 3 "aaa" False 3.14 2 (Just "test") putItem testitem1 putItem testitem2 (items, _) <- scan tTest scanOpts 10 deleteItemByKey tTest (tableKey testitem1) deleteItemByKey tTest (tableKey testitem2) (items2, _) <- scan tTest scanOpts 10 liftIO $ do length items `shouldBe` 2 length items2 `shouldBe` 0 withDb "test left join" $ do let testitem1 = Test "1" 2 "" False 3.14 2 Nothing let testitem2 = Test "1" 3 "aaa" False 3.14 2 (Just "aaa") let testsecond = TestSecond "aaa" 3 putItem testitem1 putItem testitem2 putItem testsecond res <- runConduit $ querySourceChunks tTest (queryOpts "1") =$= leftJoin Strongly tTestSecond (Just . iText) =$= CL.concat =$= CL.consume liftIO $ res `shouldBe` [(testitem1, Nothing), (testitem2, Just testsecond)] res2 <- runConduit $ querySourceChunks tTest (queryOpts "1") =$= leftJoin Strongly tTestSecond iMText =$= CL.concat =$= CL.consume liftIO $ res2 `shouldBe` [(testitem1, Nothing), (testitem2, Just testsecond)] main :: IO () main = hspec spec
null
https://raw.githubusercontent.com/ondrap/dynamodb-simple/fb7e3fe37d7e534161274cfd812cd11a82cc384b/test/BaseSpec.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # & set envLogger lgr
# LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # module BaseSpec where import Control.Exception.Safe (SomeException, catchAny, finally, try) import Control.Lens ((.~)) import Control.Monad.IO.Class (liftIO) import Data.Conduit (runConduit, (=$=)) import qualified Data.Conduit.List as CL import Data.Either (isLeft) import Data.Function ((&)) import Data.List (sort) import Data.Proxy import Data.Semigroup ((<>)) import qualified Data.Text as T import Network.AWS import Network.AWS.DynamoDB (dynamoDB) import System.Environment (setEnv) import System.IO (stdout) import Test.Hspec import Data.Maybe (fromJust) import Database.DynamoDB import Database.DynamoDB.Filter import Database.DynamoDB.TH import Database.DynamoDB.Types (RangeOper (..)) import Database.DynamoDB.Update data Test = Test { iHashKey :: T.Text , iRangeKey :: Int , iText :: T.Text , iBool :: Bool , iDouble :: Double , iInt :: Int , iMText :: Maybe T.Text } deriving (Show, Eq, Ord) data TestKeyOnly = TestKeyOnly { d_iText :: T.Text , d_iHashKey :: T.Text } mkTableDefs "migrateTest" (tableConfig "" (''Test, WithRange) [(''TestKeyOnly, NoRange)] []) data TestSecond = TestSecond { tHashKey :: T.Text , tInt :: Int } deriving (Show, Eq) mkTableDefs "migrateTest2" (tableConfig "" (''TestSecond, NoRange) [] []) withDb :: Example (IO b) => String -> AWS b -> SpecWith (Arg (IO b)) withDb msg code = it msg runcode where runcode = do setEnv "AWS_ACCESS_KEY_ID" "XXXXXXXXXXXXXX" setEnv "AWS_SECRET_ACCESS_KEY" "XXXXXXXXXXXXXXfdjdsfjdsfjdskldfs+kl" lgr <- newLogger Debug stdout env <- newEnv Discover let dynamo = setEndpoint False "localhost" 8000 dynamoDB let newenv = env & configure dynamo runResourceT $ runAWS newenv $ do deleteTable (Proxy :: Proxy Test) `catchAny` (\_ -> return ()) migrateTest mempty Nothing migrateTest2 mempty Nothing code `finally` deleteTable (Proxy :: Proxy Test) spec :: Spec spec = do describe "Basic operations" $ do withDb "putItem/getItem works" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 Nothing testitem2 = Test "2" 3 "text" False 4.15 3 (Just "text") putItem testitem1 putItem testitem2 it1 <- getItem Strongly tTest ("1", 2) it2 <- getItem Strongly tTest ("2", 3) liftIO $ Just testitem1 `shouldBe` it1 liftIO $ Just testitem2 `shouldBe` it2 withDb "getItemBatch/putItemBatch work" $ do let template i = Test (T.pack $ show i) i "text" False 3.14 i Nothing newItems = map template [1..300] putItemBatch newItems let keys = map tableKey newItems items <- getItemBatch Strongly keys liftIO $ sort items `shouldBe` sort newItems withDb "insertItem doesn't overwrite items" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 Nothing testitem1_ = Test "1" 2 "XXXX" True 3.14 3 Nothing insertItem testitem1 (res :: Either SomeException ()) <- try (insertItem testitem1_) liftIO $ res `shouldSatisfy` isLeft withDb "scanSource works correctly with sLimit" $ do let template i = Test (T.pack $ show i) i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems let squery = scanOpts & sFilterCondition .~ Just (iInt' >. 50) & sLimit .~ Just 1 res <- runConduit $ scanSource tTest squery =$= CL.consume liftIO $ sort res `shouldBe` sort (drop 50 newItems) withDb "querySource works correctly with qLimit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems let squery = queryOpts "hashkey" & qFilterCondition .~ Just (iInt' >. 50) & qLimit .~ Just 1 res <- runConduit $ querySource tTest squery =$= CL.consume liftIO $ res `shouldBe` drop 50 newItems withDb "queryCond works correctly with qLimit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems items <- queryCond tTest "hashkey" Nothing (iInt' >. 50) Forward 5 liftIO $ items `shouldBe` drop 50 newItems withDb "scanCond works correctly" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems items <- scanCond tTest (iInt' >. 50) 5 liftIO $ items `shouldBe` drop 50 newItems withDb "scan works correctly with qlimit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (iInt' >. 50)) 5 liftIO $ items `shouldBe` drop 50 newItems withDb "scan works correctly with `valIn`" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (iInt' `valIn` [20..30])) 50 liftIO $ map iInt items `shouldBe` [20..30] withDb "scan works correctly with BETWEEN" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (iInt' `between` (20, 30))) 50 liftIO $ map iInt items `shouldBe` [20..30] withDb "scan works correctly with SIZE" $ do let testitem1 = Test "1" 2 "very very very very very long" False 3.14 2 Nothing testitem2 = Test "1" 3 "short" False 3.14 2 Nothing putItem testitem1 putItem testitem2 (items, _) <- scan tTest (scanOpts & sLimit .~ Just 1 & sFilterCondition .~ Just (size iText' >. 10)) 50 liftIO $ items `shouldBe` [testitem1] withDb "querySimple works correctly with RangeOper" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems items <- querySimple tTest "hashkey" (Just $ RangeLessThan 30) Backward 5 liftIO $ map iRangeKey items `shouldBe` [29,28..25] withDb "queryCond works correctly with -1 limit" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (items :: [Test]) <- queryCond tTest "hashkey" Nothing (iInt' >. 50) Backward (-1) liftIO $ items `shouldBe` [] withDb "querySourceByKey works/compiles correctly" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems res <- runConduit $ querySourceByKey iTestKeyOnly "text" =$= CL.consume liftIO $ length res `shouldBe` 55 withDb "updateItemByKey works" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 (Just "something") putItem testitem1 new1 <- updateItemByKey tTest (tableKey testitem1) ((iInt' +=. 5) <> (iText' =. "updated") <> (iMText' =. Nothing)) new2 <- fromJust <$> getItem Strongly tTest (tableKey testitem1) liftIO $ do new1 `shouldBe` new2 iInt new1 `shouldBe` 7 iText new1 `shouldBe` "updated" iMText new1 `shouldBe` Nothing withDb "update fails on non-existing item" $ do let testitem1 = Test "1" 2 "text" False 3.14 2 (Just "something") putItem testitem1 updateItemByKey_ tTest ("1", 2) (iBool' =. True) (res :: Either SomeException ()) <- try $ updateItemByKey_ tTest ("2", 3) (iBool' =. True) liftIO $ res `shouldSatisfy` isLeft withDb "scan continuation works" $ do let template i = Test "hashkey" i "text" False 3.14 i Nothing newItems = map template [1..55] putItemBatch newItems (it1, next) <- scan tTest (scanOpts & sFilterCondition .~ Just (iInt' >. 20) & sLimit .~ Just 2) 5 (it2, _) <- scan tTest (scanOpts & sFilterCondition .~ Just (iInt' >. 20) & sLimit .~ Just 1 & sStartKey .~ next) 5 liftIO $ map iInt (it1 ++ it2) `shouldBe` [21..30] withDb "searching empty strings" $ do let testitem1 = Test "1" 2 "" False 3.14 2 Nothing let testitem2 = Test "1" 3 "aaa" False 3.14 2 (Just "test") putItem testitem1 putItem testitem2 items1 <- queryCond tTest "1" Nothing (iText' ==. "") Forward 10 items2 <- queryCond tTest "1" Nothing (iMText' ==. Nothing) Forward 10 liftIO $ items1 `shouldBe` [testitem1] liftIO $ items2 `shouldBe` [testitem1] withDb "deleting by key" $ do let testitem1 = Test "1" 2 "" False 3.14 2 Nothing let testitem2 = Test "1" 3 "aaa" False 3.14 2 (Just "test") putItem testitem1 putItem testitem2 (items, _) <- scan tTest scanOpts 10 deleteItemByKey tTest (tableKey testitem1) deleteItemByKey tTest (tableKey testitem2) (items2, _) <- scan tTest scanOpts 10 liftIO $ do length items `shouldBe` 2 length items2 `shouldBe` 0 withDb "test left join" $ do let testitem1 = Test "1" 2 "" False 3.14 2 Nothing let testitem2 = Test "1" 3 "aaa" False 3.14 2 (Just "aaa") let testsecond = TestSecond "aaa" 3 putItem testitem1 putItem testitem2 putItem testsecond res <- runConduit $ querySourceChunks tTest (queryOpts "1") =$= leftJoin Strongly tTestSecond (Just . iText) =$= CL.concat =$= CL.consume liftIO $ res `shouldBe` [(testitem1, Nothing), (testitem2, Just testsecond)] res2 <- runConduit $ querySourceChunks tTest (queryOpts "1") =$= leftJoin Strongly tTestSecond iMText =$= CL.concat =$= CL.consume liftIO $ res2 `shouldBe` [(testitem1, Nothing), (testitem2, Just testsecond)] main :: IO () main = hspec spec
9749a42e4d3ca6c329fa6c13d7322b6457a6cf95af62736fc0d6febd0a5cca6e
huangz1990/SICP-answers
46-sub-vect.scm
46-sub-vect.scm (load "46-vect-represent.scm") (define (sub-vect vect another-vect) (make-vect (- (xcor-vect vect) (xcor-vect another-vect)) (- (ycor-vect vect) (ycor-vect another-vect))))
null
https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/46-sub-vect.scm
scheme
46-sub-vect.scm (load "46-vect-represent.scm") (define (sub-vect vect another-vect) (make-vect (- (xcor-vect vect) (xcor-vect another-vect)) (- (ycor-vect vect) (ycor-vect another-vect))))
70793ea7196013774bedc003ef98d9d503c243bde5b97365df7d5a7ad4cb8290
slyrus/mcclim-old
transforms.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: CLIM-INTERNALS; -*- ;;; -------------------------------------------------------------------------------------- ;;; Title: The CLIM Transformations Created : 1998 - 09 - 29 Author : < > ;;; License: LGPL (See file COPYING for details). $ I d : transforms.lisp , v 1.33 2006 - 03 - 10 21:58:13 tmoore Exp $ ;;; -------------------------------------------------------------------------------------- ( c ) copyright 1998,1999,2003 by ( c ) copyright 2000 by ( ) ;;; This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . ;;; ;;; This library 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 Library General Public License for more details . ;;; You should have received a copy of the GNU Library General Public ;;; License along with this library; if not, write to the Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 USA . (in-package :clim-internals) ;;;; Changes ;;; When Who What ;;; -------------------------------------------------------------------------------------- 2001 - 07 - 16 GB added a cache for the inverse transformation ;;; nobody bothers to use the log above ;-( The CLIM 2 spec says : ;; "Implementations are encouraged to allow transformations that are not ;; numerically equal due to floating-point roundoff errors to be TRANSFORMATION - EQUAL . An appropriae level of ' fuzziness ' is ;; single-float-epsilon, or some small multiple of single-float-epsilon." ;; Note: All the predicates like RIGID-TRANSFORMATION-P, RECTILINEAR - TRANSFORMATION - P etc . inherit the " fuzziness " defined by ;; COORDINATE-EPSILON. An implementation of a medium probably invoke these ;; predicates to decide, whether the graphics primitives provided by the ;; underlying windowing system could be used; or if they have to use an own ;; implementation, which may be much slower, since individual pixels may have to ;; be transferred. So I trade speed for precision here. ;; Of course it would be better to assume some resomable maximal device coordinate for instance 40 " * 2400dpi . Now two transformations could be said ;; to be practically equal, if the (rounded) images of any point within that ;; range are equal. ;;;; ---------------------------------------------------------------------------------------------------- ;;;; Transformations ;;;; (defclass standard-transformation (transformation) () (:documentation "All CLIM transformations inherit from this. All transformations of this class should provide a method for GET-TRANSFORMATION, as this is our internal transformation protocol.")) (defclass standard-identity-transformation (standard-transformation) ()) (defparameter +identity-transformation+ (make-instance 'standard-identity-transformation)) (defclass standard-translation (standard-transformation) ((dx :type coordinate :initarg :dx) (dy :type coordinate :initarg :dy))) (defclass cached-inverse-transformation-mixin () ((inverse :type (or null standard-transformation) :initform nil :documentation "Cached inverse transformation."))) (defclass standard-hairy-transformation (standard-transformation cached-inverse-transformation-mixin) ((mxx :type coordinate :initarg :mxx) (mxy :type coordinate :initarg :mxy) (myx :type coordinate :initarg :myx) (myy :type coordinate :initarg :myy) (tx :type coordinate :initarg :tx) (ty :type coordinate :initarg :ty)) (:documentation "A transformation class which is neither the identity nor a translation.")) (defmethod print-object ((self standard-transformation) sink) (print-unreadable-object (self sink :identity nil :type t) (apply #'format sink "~S ~S ~S ~S ~S ~S" (multiple-value-list (get-transformation self))))) (defun make-transformation (mxx mxy myx myy tx ty) ;; Make a transformation, which will map a point (x,y) into x ' = mxx*x + mxy*y + tx ;; y' = myx*x + myy*y + ty (let ((mxx (coerce mxx 'coordinate)) (mxy (coerce mxy 'coordinate)) (myx (coerce myx 'coordinate)) (myy (coerce myy 'coordinate)) (tx (coerce tx 'coordinate)) (ty (coerce ty 'coordinate))) (cond ((and (= 1 mxx) (= 0 mxy) (= 0 myx) (= 1 myy)) (cond ((and (= 0 tx) (= 0 ty)) +identity-transformation+) (t (make-translation-transformation tx ty)))) (t (make-instance 'standard-hairy-transformation :mxx mxx :mxy mxy :tx tx :myx myx :myy myy :ty ty))))) (defgeneric get-transformation (transformation) (:documentation "Get the values of the transformation matrix as multiple values. This is not an exported function!")) (defmethod get-transformation ((transformation standard-identity-transformation)) (values 1 0 0 1 0 0)) (defmethod get-transformation ((transformation standard-translation)) (with-slots (dx dy) transformation (values 1 0 0 1 dx dy))) (defmethod get-transformation ((transformation standard-hairy-transformation)) (with-slots (mxx mxy myx myy tx ty) transformation (values mxx mxy myx myy tx ty))) (defun make-translation-transformation (dx dy) (cond ((and (coordinate= dx 0) (coordinate= dy 0)) +identity-transformation+) (t (make-instance 'standard-translation :dx (coordinate dx) :dy (coordinate dy))))) (defun make-rotation-transformation (angle &optional origin) (if origin (make-rotation-transformation* angle (point-x origin) (point-y origin)) (make-rotation-transformation* angle 0 0))) (defun make-rotation-transformation* (angle &optional origin-x origin-y) (let ((origin-x (or origin-x 0)) (origin-y (or origin-y 0))) (let ((s (coerce (sin angle) 'coordinate)) (c (coerce (cos angle) 'coordinate))) ;; This clamping should be done more sensible -- And: is this actually a good thing? (when (coordinate= s 0) (setq s 0)) (when (coordinate= c 0) (setq c 0)) (when (coordinate= s 1) (setq s 1)) (when (coordinate= c 1) (setq c 1)) (when (coordinate= s -1) (setq s -1)) (when (coordinate= c -1) (setq c -1)) Wir stellen uns hier mal ganz dumm : (make-3-point-transformation* origin-x origin-y (+ origin-x 1) origin-y origin-x (+ origin-y 1) origin-x origin-y (+ origin-x c) (+ origin-y s) (- origin-x s) (+ origin-y c)) ))) (defun make-scaling-transformation (scale-x scale-y &optional origin) "MAKE-SCALING-TRANSFORMATION returns a transformation that multiplies the x-coordinate distance of every point from origin by SCALE-X and the y-coordinate distance of every point from origin by SCALE-Y. SCALE-X and SCALE-Y must be real numbers. If ORIGIN is supplied it must be a point; if not supplied it defaults to (0, 0). ORIGIN-X and ORIGIN-Y must be real numbers, and default to 0." (make-scaling-transformation* scale-x scale-y (if origin (point-x origin) 0) (if origin (point-y origin) 0))) (defun make-scaling-transformation* (scale-x scale-y &optional origin-x origin-y) (let ((origin-x (or origin-x 0)) (origin-y (or origin-y 0))) (make-transformation scale-x 0 0 scale-y (- origin-x (* scale-x origin-x)) (- origin-y (* scale-y origin-y)))) ) (defun make-reflection-transformation (point1 point2) (make-reflection-transformation* (point-x point1) (point-y point1) (point-x point2) (point-y point2))) (defun make-reflection-transformation* (x1 y1 x2 y2) (let ((dx (- x2 x1)) (dy (- y2 y1))) (handler-case (make-3-point-transformation* x1 y1 x2 y2 (- x1 dy) (+ y1 dx) x1 y1 x2 y2 (+ x1 dy) (- y1 dx)) (transformation-underspecified (c) (error 'reflection-underspecified :why c :coords (list x1 y1 x2 y2)))))) (defun make-3-point-transformation (point-1 point-2 point-3 point-1-image point-2-image point-3-image) (make-3-point-transformation* (point-x point-1) (point-y point-1) (point-x point-2) (point-y point-2) (point-x point-3) (point-y point-3) (point-x point-1-image) (point-y point-1-image) (point-x point-2-image) (point-y point-2-image) (point-x point-3-image) (point-y point-3-image))) (defun make-3-point-transformation* (x1 y1 x2 y2 x3 y3 x1-image y1-image x2-image y2-image x3-image y3-image) Find a transformation matrix , which transforms each of the three points ( x_i , y_i ) to its image ( , ) ;; Therefore , we have to solve these two linear equations : ;; ;; / x1 y1 1 \ / mxx \ / x1-image \ / myx \ / y1-image \ ;; A:= | x2 y2 1 | ; A | mxy | = | x2-image | and A | myy | = | y2-image | ; ;; \ x3 y3 1 / \ tx / \ x3-image / \ ty / \ y3-image / ;; These matrices are small enough to simply calculate = |A|^-1 ( adj A ) . ;; (let ((det (+ (* x1 y2) (* y1 x3) (* x2 y3) (- (* y2 x3)) (- (* y1 x2)) (- (* x1 y3))))) (if (coordinate/= 0 det) (let* ((/det (/ det)) ;; a thru' i is (adj A) (a (- y2 y3)) (b (- y3 y1)) (c (- y1 y2)) (d (- x3 x2)) (e (- x1 x3)) (f (- x2 x1)) (g (- (* x2 y3) (* x3 y2))) (h (- (* x3 y1) (* x1 y3))) (i (- (* x1 y2) (* x2 y1))) calculate 1/|A| * ( adj A ) * ( x1 - image x2 - image x3 - image)^t (mxx (* /det (+ (* a x1-image) (* b x2-image) (* c x3-image)))) (mxy (* /det (+ (* d x1-image) (* e x2-image) (* f x3-image)))) (tx (* /det (+ (* g x1-image) (* h x2-image) (* i x3-image)))) finally 1/|A| * ( adj A ) * ( y1 - image y2 - image y3 - image)^t (myx (* /det (+ (* a y1-image) (* b y2-image) (* c y3-image)))) (myy (* /det (+ (* d y1-image) (* e y2-image) (* f y3-image)))) (ty (* /det (+ (* g y1-image) (* h y2-image) (* i y3-image))))) ;; we're done (make-transformation mxx mxy myx myy tx ty) ) determinant was zero , so signal error (error 'transformation-underspecified :coords (list x1 y1 x2 y2 x3 y3 x1-image y1-image x2-image y2-image x3-image y3-image)) ))) (define-condition transformation-error (error) ()) (define-condition transformation-underspecified (transformation-error) ((coords :initarg :coords :reader transformation-error-coords)) (:report (lambda (self sink) (apply #'format sink "The three points (~D,~D), (~D,~D), and (~D,~D) are propably collinear." (subseq (transformation-error-coords self) 0 6))))) (define-condition reflection-underspecified (transformation-error) ((coords :initarg :coords :reader transformation-error-coords) (why :initarg :why :initform nil :reader transformation-error-why)) (:report (lambda (self sink) (apply #'format sink "The two points (~D,~D) and (~D,~D) are coincident." (transformation-error-coords self)) (when (transformation-error-why self) (format sink " (That was determined by the following error:~%~A)" (transformation-error-why self)))))) (define-condition singular-transformation (transformation-error) ((transformation :initarg :transformation :reader transformation-error-transformation) (why :initarg :why :initform nil :reader transformation-error-why)) (:report (lambda (self sink) (format sink "Attempt to invert the probably singular transformation ~S." (transformation-error-transformation self)) (when (transformation-error-why self) (format sink "~%Another error occurred while computing the inverse:~% ~A" (transformation-error-why self)))))) (define-condition rectangle-transformation-error (transformation-error) ((transformation :initarg :transformation :reader transformation-error-transformation) (rect :initarg :rect :reader transformation-error-rect)) (:report (lambda (self sink) (format sink "Attempt to transform the rectangle ~S through the non-rectilinear transformation ~S." (transformation-error-rect self) (transformation-error-transformation self))))) (defmethod transformation-equal ((transformation1 standard-transformation) (transformation2 standard-transformation)) (every #'coordinate= (multiple-value-list (get-transformation transformation1)) (multiple-value-list (get-transformation transformation2)))) ;; make-transformation always returns +identity-transformation+, if ;; the transformation to be build would be the identity. So we ;; IDENTITY-TRANSFORMATION-P can just specialize on ;; STANDARD-IDENTITY-TRANSFORMATION. (defmethod identity-transformation-p ((transformation standard-identity-transformation)) t) (defmethod identity-transformation-p ((transformation standard-transformation)) nil) ;; Same for translations, but +identity-transformation+ is a translation too. (defmethod translation-transformation-p ((transformation standard-translation)) t) (defmethod translation-transformation-p ((transformation standard-identity-transformation)) t) (defmethod translation-transformation-p ((transformation standard-transformation)) nil) (defun transformation-determinant (tr) (multiple-value-bind (mxx mxy myx myy) (get-transformation tr) (- (* mxx myy) (* mxy myx)))) (defmethod invertible-transformation-p ((transformation standard-transformation)) (coordinate/= 0 (transformation-determinant transformation))) (defmethod reflection-transformation-p ((transformation standard-transformation)) (< (transformation-determinant transformation) 0)) (defmethod rigid-transformation-p ((transformation standard-transformation)) (multiple-value-bind (a b c d) (get-transformation transformation) |A(1,0)| = 1 |A(0,1)| = 1 ( A(1,0))(A(0,1 ) ) = 0 (defmethod even-scaling-transformation-p ((transformation standard-transformation)) (and (scaling-transformation-p transformation) (multiple-value-bind (mxx myx mxy myy) (get-transformation transformation) (declare (ignore mxy myx)) (coordinate= (abs mxx) (abs myy))))) (defmethod scaling-transformation-p ((transformation standard-transformation)) ;; Q: was ist mit dem translationsanteil? ;; what gives (scaling-transformation-p (make-translation-transformation 17 42)) I think it would be strange if ( s - t - p ( make - s - t * 2 1 1 0 ) ) is not T. -- APD (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (declare (ignore tx ty)) (and (coordinate= 0 mxy) (coordinate= 0 myx) (coordinate/= 0 mxx) (coordinate/= 0 myy)))) ; ? (defmethod rectilinear-transformation-p ((transformation standard-transformation)) Das testen wir einfach ganz brutal ;;; ist das auch richtig? (multiple-value-bind (mxx mxy myx myy) (get-transformation transformation) (or (and (coordinate= mxx 0) (coordinate/= mxy 0) (coordinate/= myx 0) (coordinate= myy 0)) (and (coordinate/= mxx 0) (coordinate= mxy 0) (coordinate= myx 0) (coordinate/= myy 0))))) (defmethod y-inverting-transformation-p ((transformation standard-transformation)) (multiple-value-bind (mxx mxy myx myy) (get-transformation transformation) (and (coordinate= mxx 1) (coordinate= mxy 0) (coordinate= myx 0) (coordinate= myy -1)))) (defmethod compose-transformations ((transformation2 standard-transformation) (transformation1 standard-transformation)) ;; (compose-transformations A B)x = (A o B)x = ABx (multiple-value-bind (a1 b1 d1 e1 c1 f1) (get-transformation transformation1) (multiple-value-bind (a2 b2 d2 e2 c2 f2) (get-transformation transformation2) (make-transformation (+ (* a2 a1) (* b2 d1)) (+ (* a2 b1) (* b2 e1)) (+ (* d2 a1) (* e2 d1)) (+ (* d2 b1) (* e2 e1)) (+ (* a2 c1) (* b2 f1) c2) (+ (* d2 c1) (* e2 f1) f2) )))) (defmethod invert-transformation :around ((transformation cached-inverse-transformation-mixin)) (with-slots (inverse) transformation (or inverse (let ((computed-inverse (call-next-method))) (when (typep computed-inverse 'cached-inverse-transformation-mixin) (setf (slot-value computed-inverse 'inverse) transformation)) (setf inverse computed-inverse) computed-inverse)))) (defmethod invert-transformation ((transformation standard-transformation)) (restart-case (or (handler-case (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (let ((det (- (* mxx myy) (* myx mxy)))) (if (coordinate= 0 det) nil (let ((/det (/ det))) (let ((mxx (* /det myy)) (mxy (* /det (- mxy))) (myx (* /det (- myx))) (myy (* /det mxx))) (make-transformation mxx mxy myx myy (+ (* -1 mxx tx) (* -1 mxy ty)) (+ (* -1 myx tx) (* -1 myy ty)))))))) (error (c) (error 'singular-transformation :why c :transformation transformation))) (error 'singular-transformation :transformation transformation)) (use-value (value) :report (lambda (sink) (format sink "Supply a transformation to use instead of the inverse.")) value))) (defun compose-translation-with-transformation (transformation dx dy) (compose-transformations transformation (make-translation-transformation dx dy))) (defun compose-scaling-with-transformation (transformation sx sy &optional origin) (compose-transformations transformation (make-scaling-transformation sx sy origin))) (defun compose-rotation-with-transformation (transformation angle &optional origin) (compose-transformations transformation (make-rotation-transformation angle origin))) (defun compose-transformation-with-translation (transformation dx dy) (compose-transformations (make-translation-transformation dx dy) transformation)) (defun compose-transformation-with-scaling (transformation sx sy &optional origin) (compose-transformations (make-scaling-transformation sx sy origin) transformation)) (defun compose-transformation-with-rotation (transformation angle &optional origin) (compose-transformations (make-rotation-transformation angle origin) transformation)) (defmacro with-translation ((medium dx dy) &body body) `(with-drawing-options (,medium :transformation (make-translation-transformation ,dx ,dy)) ,@body)) (defmacro with-scaling ((medium sx &optional sy origin) &body body) (if sy `(with-drawing-options (,medium :transformation (make-scaling-transformation ,sx ,sy ,@(if origin (list origin) nil))) ,@body) (let ((sx-var (make-symbol "SX"))) `(let* ((,sx-var ,sx)) (with-drawing-options (,medium :transformation (make-scaling-transformation ,sx-var ,sx-var)) ,@body)) ))) (defmacro with-rotation ((medium angle &optional origin) &body body) `(with-drawing-options (,medium :transformation (make-rotation-transformation ,angle ,@(if origin (list origin) nil))) ,@body)) ( defmacro with - local - coordinates ( ( medium & optional x y ) & body body ) ) -- what are local coordinates ? ( defmacro with - first - quadrant - coordinates ( ( medium & optional x y ) & body body ) ) (defmacro with-identity-transformation ((medium) &body body) ;; I believe this should set the medium transformation to the identity ;; transformation. To use WITH-DRAWING-OPTIONS which concatenates the the ;; transformation given to the existing one we just pass the inverse. ;; ;; "Further we don't use LETF since it is a pretty much broken idea in case ;; of multithreading." -- gilbert ;; ;; "That may be, but all of the transformation functions/macros are ;; going to set the medium state at some point (see ;; with-drawing-options), and that's not thread-safe either. So I ;; say, 'just use LETF.'" -- moore ;; ;; Q: Do we want a invoke-with-identity-transformation? ;; (let ((medium (stream-designator-symbol medium '*standard-output*))) (gen-invoke-trampoline 'invoke-with-identity-transformation (list medium) nil body))) invoke - with - identity - transformation is gone to graphics.lisp ;; invoke-with-identity-transformation and ;; invoke-with-first-quadrant-coordinates ;; likewise because of the with-drawing-options macro, perhaps we should gather macros in a macros.lisp file ? (defmacro with-local-coordinates ((medium &optional x y) &body body) (setf medium (stream-designator-symbol medium '*standard-output*)) (gen-invoke-trampoline 'invoke-with-local-coordinates (list medium) (list x y) body)) (defmacro with-first-quadrant-coordinates ((medium &optional x y) &body body) (setf medium (stream-designator-symbol medium '*standard-output*)) (gen-invoke-trampoline 'invoke-with-first-quadrant-coordinates (list medium) (list x y) body)) (defmethod untransform-region ((transformation transformation) region) (transform-region (invert-transformation transformation) region)) (defmethod transform-position ((transformation standard-transformation) x y) (let ((x (coordinate x)) (y (coordinate y))) (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (declare (type coordinate mxx mxy myx myy tx ty)) (values (+ (* mxx x) (* mxy y) tx) (+ (* myx x) (* myy y) ty))))) (defmethod untransform-position ((transformation transformation) x y) (transform-position (invert-transformation transformation) x y)) (defmethod transform-distance ((transformation standard-transformation) dx dy) (let ((dx (coordinate dx)) (dy (coordinate dy))) (multiple-value-bind (mxx mxy myx myy) (get-transformation transformation) (declare (type coordinate mxx mxy myx myy)) (values (+ (* mxx dx) (* mxy dy)) (+ (* myx dx) (* myy dy)))))) (defmethod untransform-distance ((transformation transformation) dx dy) (transform-distance (invert-transformation transformation) dx dy)) (defun transform-positions (transformation coord-seq) ;; Some appliations (like a function graph plotter) use a large number of ;; coordinates, therefore we bother optimizing this. We do this by testing ;; the individual elements of the transformation matrix for being 0 or +1 or ;; -1 as these are common cases as most transformations are either mere ;; translations or just scalings. ;; ;; Also: For now we always return a vector. ;; (cond ((eql transformation +identity-transformation+) coord-seq) (t (multiple-value-bind (mxx mxy myx myy tx ty) (climi::get-transformation transformation) (declare (type coordinate mxx mxy myx myy tx ty)) (macrolet ((do-transform () `(progn (cond ((zerop mxx)) ((= mxx +1) (for-coord-seq (setf res.x x))) ((= mxx -1) (for-coord-seq (setf res.x (- x)))) (t (for-coord-seq (setf res.x (* mxx x))))) (cond ((zerop myy)) ((= myy +1) (for-coord-seq (setf res.y y))) ((= myy -1) (for-coord-seq (setf res.y (- y)))) (t (for-coord-seq (setf res.y (* myy y))))) (unless (and (zerop mxy) (zerop myx)) (for-coord-seq (incf res.x (* mxy y)) (incf res.y (* myx x)))) (unless (and (zerop tx) (zerop ty)) (for-coord-seq (incf res.x tx) (incf res.y ty)))))) (macrolet ((do-on-vector () `(let* ((n (length coord-seq)) (res (make-array n :initial-element 0))) (declare (type simple-vector res)) (macrolet ((for-coord-seq (&rest body) `(loop for i of-type fixnum below n by 2 do (let ((x (aref coord-seq i)) (y (aref coord-seq (+ i 1)))) (declare (ignorable x y)) (symbol-macrolet ((res.x (aref res i)) (res.y (aref res (+ i 1)))) ,@body))))) (do-transform)) res)) (do-on-list () `(let* ((n (length coord-seq)) (res (make-array n :initial-element 0))) (declare (type simple-vector res)) (macrolet ((for-coord-seq (&rest body) `(loop for i of-type fixnum below n by 2 for q on coord-seq by #'cddr do (let ((x (car q)) (y (cadr q))) (declare (ignorable x y)) (symbol-macrolet ((res.x (aref res i)) (res.y (aref res (+ i 1)))) ,@body))))) (do-transform)) res))) (cond ((typep coord-seq 'simple-vector) (locally (declare (type simple-vector coord-seq)) (do-on-vector))) ((typep coord-seq 'vector) (locally (declare (type vector coord-seq)) (do-on-vector))) ((typep coord-seq 'list) (locally (declare (type list coord-seq)) (do-on-list))) (t (error "~S is not a sequence." coord-seq)) ))))))) (defun transform-position-sequence (seq-type transformation coord-seq) (cond ((subtypep seq-type 'vector) (transform-positions transformation coord-seq)) (t (map-repeated-sequence seq-type 2 (lambda (x y) (transform-position transformation x y)) coord-seq)))) (defmethod transform-rectangle* ((transformation transformation) x1 y1 x2 y2) (if (rectilinear-transformation-p transformation) (multiple-value-bind (x1 y1) (transform-position transformation x1 y1) (multiple-value-bind (x2 y2) (transform-position transformation x2 y2) (values (min x1 x2) (min y1 y2) (max x1 x2) (max y1 y2)))) (error 'rectangle-transformation-error :transformation transformation :rect (list x1 y2 x2 y2)))) (defmethod untransform-rectangle* ((transformation transformation) x1 y1 x2 y2) (transform-rectangle* (invert-transformation transformation) x1 y1 x2 y2)) (defmethod transformation-transformator ((transformation standard-transformation) &optional (input-type 'real)) ;; returns a function, which transforms its arguments (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (labels ((s* (x y) (cond ((coordinate= 0 x) nil) ((coordinate= 1 x) (list y)) ((coordinate= -1 x) (list `(- ,y))) ((list `(* ,x ,y))))) (s+ (args) (cond ((null args) (coerce 0 'coordinate)) ((null (cdr args)) (car args)) (t `(+ .,args))))) (compile nil `(lambda (x y) (declare (ignorable x y) (type ,input-type x y) (optimize (speed 3) (space 0) (safety 0))) (values ,(s+ (nconc (s* mxx 'x) (s* mxy 'y) (if (coordinate/= 0 tx) (list tx) nil))) ,(s+ (nconc (s* myx 'x) (s* myy 'y) (if (coordinate/= 0 ty) (list ty) nil))))) )))) (defmethod transformation-transformator ((transformation transformation) &optional (input-type 'real)) (declare (ignore input-type)) #'(lambda (x y) (transform-position transformation x y))) (defun atan* (x y) atan so , wie wir es brauchen . Bei uns ist phi=0 zwischen 0 und 2pi . (let ((r (atan y x))) (if (< r 0) (+ r (* 2 pi)) r))) (defun correct-angle (a phi) (if (< a phi) (+ a (* 2 pi)) a)) (defun transform-angle (transformation phi) (multiple-value-bind (rotations remainder) (ffloor phi (* 2 pi)) (when (reflection-transformation-p transformation) (setq rotations (ffloor (- phi) (* 2 pi)))) (multiple-value-bind (ix iy) (transform-distance transformation (cos remainder) (sin remainder)) (multiple-value-bind (x0 y0) (transform-distance transformation 1 0) (let ((my-angle (atan* ix iy)) (null-angle (atan* x0 y0))) (+ (* rotations 2 pi) (correct-angle my-angle null-angle))))))) (defun untransform-angle (transformation phi) (multiple-value-bind (rotations remainder) (ffloor phi (* 2 pi)) (when (reflection-transformation-p transformation) (setq rotations (ffloor (- phi) (* 2 pi)))) (multiple-value-bind (ix iy) (untransform-distance transformation (cos remainder) (sin remainder)) (multiple-value-bind (x0 y0) (untransform-distance transformation 1 0) (let ((my-angle (atan* ix iy)) (null-angle (atan* x0 y0))) (+ (* rotations 2 pi) (correct-angle my-angle null-angle))))))) ;;;; Methods on special transformations for performance. (defmethod compose-transformations ((transformation2 standard-translation) (transformation1 standard-translation)) ;; (compose-transformations A B)x = (A o B)x = ABx (with-slots ((dx1 dx) (dy1 dy)) transformation1 (with-slots ((dx2 dx) (dy2 dy)) transformation2 (make-translation-transformation (+ dx1 dx2) (+ dy1 dy2))))) (defmethod compose-transformations (transformation2 (transformation1 standard-identity-transformation)) transformation2) (defmethod compose-transformations ((transformation2 standard-identity-transformation) transformation1) transformation1) (defmethod invert-transformation ((transformation standard-identity-transformation)) transformation) (defmethod invert-transformation ((transformation standard-translation)) (with-slots (dx dy) transformation (make-translation-transformation (- dx) (- dy)))) (defmethod transform-position ((transformation standard-translation) x y) (with-slots (dx dy) transformation (let ((x (coordinate x)) (y (coordinate y))) (declare (type coordinate dx dy x y)) (values (+ x dx) (+ y dy))))) (defmethod transform-position ((transformation standard-identity-transformation) x y) (values x y)) (defmethod transform-region ((transformation standard-identity-transformation) region) region) (defmethod rectilinear-transformation-p ((tr standard-identity-transformation)) t) (defmethod rectilinear-transformation-p ((tr standard-translation)) t) (defmethod scaling-transformation-p ((tr standard-translation)) t) (defmethod scaling-transformation-p ((tr standard-identity-transformation)) t) (defmethod transformation-equal ((t1 standard-identity-transformation) (t2 standard-identity-transformation)) t) (defmethod transformation-equal ((t1 standard-identity-transformation) (t2 t)) nil) (defmethod transformation-equal ((t2 t) (t1 standard-identity-transformation)) nil) (defmethod transformation-equal ((t1 standard-translation) (t2 standard-translation)) (with-slots ((dx1 dx) (dy1 dy)) t1 (with-slots ((dx2 dx) (dy2 dy)) t2 (and (coordinate= dx1 dx2) (coordinate= dy1 dy2))))) (defmethod transformation-equal ((t1 standard-translation) (t2 t)) nil) (defmethod transformation-equal ((t2 t) (t1 standard-translation)) nil)
null
https://raw.githubusercontent.com/slyrus/mcclim-old/354cdf73c1a4c70e619ccd7d390cb2f416b21c1a/transforms.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: CLIM-INTERNALS; -*- -------------------------------------------------------------------------------------- Title: The CLIM Transformations License: LGPL (See file COPYING for details). -------------------------------------------------------------------------------------- This library is free software; you can redistribute it and/or either This library 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 License along with this library; if not, write to the Changes When Who What -------------------------------------------------------------------------------------- nobody bothers to use the log above ;-( "Implementations are encouraged to allow transformations that are not numerically equal due to floating-point roundoff errors to be single-float-epsilon, or some small multiple of single-float-epsilon." Note: All the predicates like RIGID-TRANSFORMATION-P, COORDINATE-EPSILON. An implementation of a medium probably invoke these predicates to decide, whether the graphics primitives provided by the underlying windowing system could be used; or if they have to use an own implementation, which may be much slower, since individual pixels may have to be transferred. So I trade speed for precision here. Of course it would be better to assume some resomable maximal device to be practically equal, if the (rounded) images of any point within that range are equal. ---------------------------------------------------------------------------------------------------- Transformations Make a transformation, which will map a point (x,y) into y' = myx*x + myy*y + ty This clamping should be done more sensible -- And: is this actually a good thing? / x1 y1 1 \ / mxx \ / x1-image \ / myx \ / y1-image \ A:= | x2 y2 1 | ; A | mxy | = | x2-image | and A | myy | = | y2-image | ; \ x3 y3 1 / \ tx / \ x3-image / \ ty / \ y3-image / a thru' i is (adj A) we're done make-transformation always returns +identity-transformation+, if the transformation to be build would be the identity. So we IDENTITY-TRANSFORMATION-P can just specialize on STANDARD-IDENTITY-TRANSFORMATION. Same for translations, but +identity-transformation+ is a translation too. Q: was ist mit dem translationsanteil? what gives (scaling-transformation-p (make-translation-transformation 17 42)) ? ist das auch richtig? (compose-transformations A B)x = (A o B)x = ABx I believe this should set the medium transformation to the identity transformation. To use WITH-DRAWING-OPTIONS which concatenates the the transformation given to the existing one we just pass the inverse. "Further we don't use LETF since it is a pretty much broken idea in case of multithreading." -- gilbert "That may be, but all of the transformation functions/macros are going to set the medium state at some point (see with-drawing-options), and that's not thread-safe either. So I say, 'just use LETF.'" -- moore Q: Do we want a invoke-with-identity-transformation? invoke-with-identity-transformation and invoke-with-first-quadrant-coordinates likewise because of the with-drawing-options macro, Some appliations (like a function graph plotter) use a large number of coordinates, therefore we bother optimizing this. We do this by testing the individual elements of the transformation matrix for being 0 or +1 or -1 as these are common cases as most transformations are either mere translations or just scalings. Also: For now we always return a vector. returns a function, which transforms its arguments Methods on special transformations for performance. (compose-transformations A B)x = (A o B)x = ABx
Created : 1998 - 09 - 29 Author : < > $ I d : transforms.lisp , v 1.33 2006 - 03 - 10 21:58:13 tmoore Exp $ ( c ) copyright 1998,1999,2003 by ( c ) copyright 2000 by ( ) modify it under the terms of the GNU Library General Public version 2 of the License , or ( at your option ) any later version . Library General Public License for more details . You should have received a copy of the GNU Library General Public Free Software Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 USA . (in-package :clim-internals) 2001 - 07 - 16 GB added a cache for the inverse transformation The CLIM 2 spec says : TRANSFORMATION - EQUAL . An appropriae level of ' fuzziness ' is RECTILINEAR - TRANSFORMATION - P etc . inherit the " fuzziness " defined by coordinate for instance 40 " * 2400dpi . Now two transformations could be said (defclass standard-transformation (transformation) () (:documentation "All CLIM transformations inherit from this. All transformations of this class should provide a method for GET-TRANSFORMATION, as this is our internal transformation protocol.")) (defclass standard-identity-transformation (standard-transformation) ()) (defparameter +identity-transformation+ (make-instance 'standard-identity-transformation)) (defclass standard-translation (standard-transformation) ((dx :type coordinate :initarg :dx) (dy :type coordinate :initarg :dy))) (defclass cached-inverse-transformation-mixin () ((inverse :type (or null standard-transformation) :initform nil :documentation "Cached inverse transformation."))) (defclass standard-hairy-transformation (standard-transformation cached-inverse-transformation-mixin) ((mxx :type coordinate :initarg :mxx) (mxy :type coordinate :initarg :mxy) (myx :type coordinate :initarg :myx) (myy :type coordinate :initarg :myy) (tx :type coordinate :initarg :tx) (ty :type coordinate :initarg :ty)) (:documentation "A transformation class which is neither the identity nor a translation.")) (defmethod print-object ((self standard-transformation) sink) (print-unreadable-object (self sink :identity nil :type t) (apply #'format sink "~S ~S ~S ~S ~S ~S" (multiple-value-list (get-transformation self))))) (defun make-transformation (mxx mxy myx myy tx ty) x ' = mxx*x + mxy*y + tx (let ((mxx (coerce mxx 'coordinate)) (mxy (coerce mxy 'coordinate)) (myx (coerce myx 'coordinate)) (myy (coerce myy 'coordinate)) (tx (coerce tx 'coordinate)) (ty (coerce ty 'coordinate))) (cond ((and (= 1 mxx) (= 0 mxy) (= 0 myx) (= 1 myy)) (cond ((and (= 0 tx) (= 0 ty)) +identity-transformation+) (t (make-translation-transformation tx ty)))) (t (make-instance 'standard-hairy-transformation :mxx mxx :mxy mxy :tx tx :myx myx :myy myy :ty ty))))) (defgeneric get-transformation (transformation) (:documentation "Get the values of the transformation matrix as multiple values. This is not an exported function!")) (defmethod get-transformation ((transformation standard-identity-transformation)) (values 1 0 0 1 0 0)) (defmethod get-transformation ((transformation standard-translation)) (with-slots (dx dy) transformation (values 1 0 0 1 dx dy))) (defmethod get-transformation ((transformation standard-hairy-transformation)) (with-slots (mxx mxy myx myy tx ty) transformation (values mxx mxy myx myy tx ty))) (defun make-translation-transformation (dx dy) (cond ((and (coordinate= dx 0) (coordinate= dy 0)) +identity-transformation+) (t (make-instance 'standard-translation :dx (coordinate dx) :dy (coordinate dy))))) (defun make-rotation-transformation (angle &optional origin) (if origin (make-rotation-transformation* angle (point-x origin) (point-y origin)) (make-rotation-transformation* angle 0 0))) (defun make-rotation-transformation* (angle &optional origin-x origin-y) (let ((origin-x (or origin-x 0)) (origin-y (or origin-y 0))) (let ((s (coerce (sin angle) 'coordinate)) (c (coerce (cos angle) 'coordinate))) (when (coordinate= s 0) (setq s 0)) (when (coordinate= c 0) (setq c 0)) (when (coordinate= s 1) (setq s 1)) (when (coordinate= c 1) (setq c 1)) (when (coordinate= s -1) (setq s -1)) (when (coordinate= c -1) (setq c -1)) Wir stellen uns hier mal ganz dumm : (make-3-point-transformation* origin-x origin-y (+ origin-x 1) origin-y origin-x (+ origin-y 1) origin-x origin-y (+ origin-x c) (+ origin-y s) (- origin-x s) (+ origin-y c)) ))) (defun make-scaling-transformation (scale-x scale-y &optional origin) "MAKE-SCALING-TRANSFORMATION returns a transformation that multiplies the x-coordinate distance of every point from origin by SCALE-X and the y-coordinate distance of every point from origin by SCALE-Y. SCALE-X and if not supplied it defaults to (0, 0). ORIGIN-X and ORIGIN-Y must be real numbers, and default to 0." (make-scaling-transformation* scale-x scale-y (if origin (point-x origin) 0) (if origin (point-y origin) 0))) (defun make-scaling-transformation* (scale-x scale-y &optional origin-x origin-y) (let ((origin-x (or origin-x 0)) (origin-y (or origin-y 0))) (make-transformation scale-x 0 0 scale-y (- origin-x (* scale-x origin-x)) (- origin-y (* scale-y origin-y)))) ) (defun make-reflection-transformation (point1 point2) (make-reflection-transformation* (point-x point1) (point-y point1) (point-x point2) (point-y point2))) (defun make-reflection-transformation* (x1 y1 x2 y2) (let ((dx (- x2 x1)) (dy (- y2 y1))) (handler-case (make-3-point-transformation* x1 y1 x2 y2 (- x1 dy) (+ y1 dx) x1 y1 x2 y2 (+ x1 dy) (- y1 dx)) (transformation-underspecified (c) (error 'reflection-underspecified :why c :coords (list x1 y1 x2 y2)))))) (defun make-3-point-transformation (point-1 point-2 point-3 point-1-image point-2-image point-3-image) (make-3-point-transformation* (point-x point-1) (point-y point-1) (point-x point-2) (point-y point-2) (point-x point-3) (point-y point-3) (point-x point-1-image) (point-y point-1-image) (point-x point-2-image) (point-y point-2-image) (point-x point-3-image) (point-y point-3-image))) (defun make-3-point-transformation* (x1 y1 x2 y2 x3 y3 x1-image y1-image x2-image y2-image x3-image y3-image) Find a transformation matrix , which transforms each of the three points ( x_i , y_i ) to its image ( , ) Therefore , we have to solve these two linear equations : These matrices are small enough to simply calculate = |A|^-1 ( adj A ) . (let ((det (+ (* x1 y2) (* y1 x3) (* x2 y3) (- (* y2 x3)) (- (* y1 x2)) (- (* x1 y3))))) (if (coordinate/= 0 det) (let* ((/det (/ det)) (a (- y2 y3)) (b (- y3 y1)) (c (- y1 y2)) (d (- x3 x2)) (e (- x1 x3)) (f (- x2 x1)) (g (- (* x2 y3) (* x3 y2))) (h (- (* x3 y1) (* x1 y3))) (i (- (* x1 y2) (* x2 y1))) calculate 1/|A| * ( adj A ) * ( x1 - image x2 - image x3 - image)^t (mxx (* /det (+ (* a x1-image) (* b x2-image) (* c x3-image)))) (mxy (* /det (+ (* d x1-image) (* e x2-image) (* f x3-image)))) (tx (* /det (+ (* g x1-image) (* h x2-image) (* i x3-image)))) finally 1/|A| * ( adj A ) * ( y1 - image y2 - image y3 - image)^t (myx (* /det (+ (* a y1-image) (* b y2-image) (* c y3-image)))) (myy (* /det (+ (* d y1-image) (* e y2-image) (* f y3-image)))) (ty (* /det (+ (* g y1-image) (* h y2-image) (* i y3-image))))) (make-transformation mxx mxy myx myy tx ty) ) determinant was zero , so signal error (error 'transformation-underspecified :coords (list x1 y1 x2 y2 x3 y3 x1-image y1-image x2-image y2-image x3-image y3-image)) ))) (define-condition transformation-error (error) ()) (define-condition transformation-underspecified (transformation-error) ((coords :initarg :coords :reader transformation-error-coords)) (:report (lambda (self sink) (apply #'format sink "The three points (~D,~D), (~D,~D), and (~D,~D) are propably collinear." (subseq (transformation-error-coords self) 0 6))))) (define-condition reflection-underspecified (transformation-error) ((coords :initarg :coords :reader transformation-error-coords) (why :initarg :why :initform nil :reader transformation-error-why)) (:report (lambda (self sink) (apply #'format sink "The two points (~D,~D) and (~D,~D) are coincident." (transformation-error-coords self)) (when (transformation-error-why self) (format sink " (That was determined by the following error:~%~A)" (transformation-error-why self)))))) (define-condition singular-transformation (transformation-error) ((transformation :initarg :transformation :reader transformation-error-transformation) (why :initarg :why :initform nil :reader transformation-error-why)) (:report (lambda (self sink) (format sink "Attempt to invert the probably singular transformation ~S." (transformation-error-transformation self)) (when (transformation-error-why self) (format sink "~%Another error occurred while computing the inverse:~% ~A" (transformation-error-why self)))))) (define-condition rectangle-transformation-error (transformation-error) ((transformation :initarg :transformation :reader transformation-error-transformation) (rect :initarg :rect :reader transformation-error-rect)) (:report (lambda (self sink) (format sink "Attempt to transform the rectangle ~S through the non-rectilinear transformation ~S." (transformation-error-rect self) (transformation-error-transformation self))))) (defmethod transformation-equal ((transformation1 standard-transformation) (transformation2 standard-transformation)) (every #'coordinate= (multiple-value-list (get-transformation transformation1)) (multiple-value-list (get-transformation transformation2)))) (defmethod identity-transformation-p ((transformation standard-identity-transformation)) t) (defmethod identity-transformation-p ((transformation standard-transformation)) nil) (defmethod translation-transformation-p ((transformation standard-translation)) t) (defmethod translation-transformation-p ((transformation standard-identity-transformation)) t) (defmethod translation-transformation-p ((transformation standard-transformation)) nil) (defun transformation-determinant (tr) (multiple-value-bind (mxx mxy myx myy) (get-transformation tr) (- (* mxx myy) (* mxy myx)))) (defmethod invertible-transformation-p ((transformation standard-transformation)) (coordinate/= 0 (transformation-determinant transformation))) (defmethod reflection-transformation-p ((transformation standard-transformation)) (< (transformation-determinant transformation) 0)) (defmethod rigid-transformation-p ((transformation standard-transformation)) (multiple-value-bind (a b c d) (get-transformation transformation) |A(1,0)| = 1 |A(0,1)| = 1 ( A(1,0))(A(0,1 ) ) = 0 (defmethod even-scaling-transformation-p ((transformation standard-transformation)) (and (scaling-transformation-p transformation) (multiple-value-bind (mxx myx mxy myy) (get-transformation transformation) (declare (ignore mxy myx)) (coordinate= (abs mxx) (abs myy))))) (defmethod scaling-transformation-p ((transformation standard-transformation)) I think it would be strange if ( s - t - p ( make - s - t * 2 1 1 0 ) ) is not T. -- APD (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (declare (ignore tx ty)) (and (coordinate= 0 mxy) (coordinate= 0 myx) (defmethod rectilinear-transformation-p ((transformation standard-transformation)) Das testen wir einfach ganz brutal (multiple-value-bind (mxx mxy myx myy) (get-transformation transformation) (or (and (coordinate= mxx 0) (coordinate/= mxy 0) (coordinate/= myx 0) (coordinate= myy 0)) (and (coordinate/= mxx 0) (coordinate= mxy 0) (coordinate= myx 0) (coordinate/= myy 0))))) (defmethod y-inverting-transformation-p ((transformation standard-transformation)) (multiple-value-bind (mxx mxy myx myy) (get-transformation transformation) (and (coordinate= mxx 1) (coordinate= mxy 0) (coordinate= myx 0) (coordinate= myy -1)))) (defmethod compose-transformations ((transformation2 standard-transformation) (transformation1 standard-transformation)) (multiple-value-bind (a1 b1 d1 e1 c1 f1) (get-transformation transformation1) (multiple-value-bind (a2 b2 d2 e2 c2 f2) (get-transformation transformation2) (make-transformation (+ (* a2 a1) (* b2 d1)) (+ (* a2 b1) (* b2 e1)) (+ (* d2 a1) (* e2 d1)) (+ (* d2 b1) (* e2 e1)) (+ (* a2 c1) (* b2 f1) c2) (+ (* d2 c1) (* e2 f1) f2) )))) (defmethod invert-transformation :around ((transformation cached-inverse-transformation-mixin)) (with-slots (inverse) transformation (or inverse (let ((computed-inverse (call-next-method))) (when (typep computed-inverse 'cached-inverse-transformation-mixin) (setf (slot-value computed-inverse 'inverse) transformation)) (setf inverse computed-inverse) computed-inverse)))) (defmethod invert-transformation ((transformation standard-transformation)) (restart-case (or (handler-case (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (let ((det (- (* mxx myy) (* myx mxy)))) (if (coordinate= 0 det) nil (let ((/det (/ det))) (let ((mxx (* /det myy)) (mxy (* /det (- mxy))) (myx (* /det (- myx))) (myy (* /det mxx))) (make-transformation mxx mxy myx myy (+ (* -1 mxx tx) (* -1 mxy ty)) (+ (* -1 myx tx) (* -1 myy ty)))))))) (error (c) (error 'singular-transformation :why c :transformation transformation))) (error 'singular-transformation :transformation transformation)) (use-value (value) :report (lambda (sink) (format sink "Supply a transformation to use instead of the inverse.")) value))) (defun compose-translation-with-transformation (transformation dx dy) (compose-transformations transformation (make-translation-transformation dx dy))) (defun compose-scaling-with-transformation (transformation sx sy &optional origin) (compose-transformations transformation (make-scaling-transformation sx sy origin))) (defun compose-rotation-with-transformation (transformation angle &optional origin) (compose-transformations transformation (make-rotation-transformation angle origin))) (defun compose-transformation-with-translation (transformation dx dy) (compose-transformations (make-translation-transformation dx dy) transformation)) (defun compose-transformation-with-scaling (transformation sx sy &optional origin) (compose-transformations (make-scaling-transformation sx sy origin) transformation)) (defun compose-transformation-with-rotation (transformation angle &optional origin) (compose-transformations (make-rotation-transformation angle origin) transformation)) (defmacro with-translation ((medium dx dy) &body body) `(with-drawing-options (,medium :transformation (make-translation-transformation ,dx ,dy)) ,@body)) (defmacro with-scaling ((medium sx &optional sy origin) &body body) (if sy `(with-drawing-options (,medium :transformation (make-scaling-transformation ,sx ,sy ,@(if origin (list origin) nil))) ,@body) (let ((sx-var (make-symbol "SX"))) `(let* ((,sx-var ,sx)) (with-drawing-options (,medium :transformation (make-scaling-transformation ,sx-var ,sx-var)) ,@body)) ))) (defmacro with-rotation ((medium angle &optional origin) &body body) `(with-drawing-options (,medium :transformation (make-rotation-transformation ,angle ,@(if origin (list origin) nil))) ,@body)) ( defmacro with - local - coordinates ( ( medium & optional x y ) & body body ) ) -- what are local coordinates ? ( defmacro with - first - quadrant - coordinates ( ( medium & optional x y ) & body body ) ) (defmacro with-identity-transformation ((medium) &body body) (let ((medium (stream-designator-symbol medium '*standard-output*))) (gen-invoke-trampoline 'invoke-with-identity-transformation (list medium) nil body))) invoke - with - identity - transformation is gone to graphics.lisp perhaps we should gather macros in a macros.lisp file ? (defmacro with-local-coordinates ((medium &optional x y) &body body) (setf medium (stream-designator-symbol medium '*standard-output*)) (gen-invoke-trampoline 'invoke-with-local-coordinates (list medium) (list x y) body)) (defmacro with-first-quadrant-coordinates ((medium &optional x y) &body body) (setf medium (stream-designator-symbol medium '*standard-output*)) (gen-invoke-trampoline 'invoke-with-first-quadrant-coordinates (list medium) (list x y) body)) (defmethod untransform-region ((transformation transformation) region) (transform-region (invert-transformation transformation) region)) (defmethod transform-position ((transformation standard-transformation) x y) (let ((x (coordinate x)) (y (coordinate y))) (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (declare (type coordinate mxx mxy myx myy tx ty)) (values (+ (* mxx x) (* mxy y) tx) (+ (* myx x) (* myy y) ty))))) (defmethod untransform-position ((transformation transformation) x y) (transform-position (invert-transformation transformation) x y)) (defmethod transform-distance ((transformation standard-transformation) dx dy) (let ((dx (coordinate dx)) (dy (coordinate dy))) (multiple-value-bind (mxx mxy myx myy) (get-transformation transformation) (declare (type coordinate mxx mxy myx myy)) (values (+ (* mxx dx) (* mxy dy)) (+ (* myx dx) (* myy dy)))))) (defmethod untransform-distance ((transformation transformation) dx dy) (transform-distance (invert-transformation transformation) dx dy)) (defun transform-positions (transformation coord-seq) (cond ((eql transformation +identity-transformation+) coord-seq) (t (multiple-value-bind (mxx mxy myx myy tx ty) (climi::get-transformation transformation) (declare (type coordinate mxx mxy myx myy tx ty)) (macrolet ((do-transform () `(progn (cond ((zerop mxx)) ((= mxx +1) (for-coord-seq (setf res.x x))) ((= mxx -1) (for-coord-seq (setf res.x (- x)))) (t (for-coord-seq (setf res.x (* mxx x))))) (cond ((zerop myy)) ((= myy +1) (for-coord-seq (setf res.y y))) ((= myy -1) (for-coord-seq (setf res.y (- y)))) (t (for-coord-seq (setf res.y (* myy y))))) (unless (and (zerop mxy) (zerop myx)) (for-coord-seq (incf res.x (* mxy y)) (incf res.y (* myx x)))) (unless (and (zerop tx) (zerop ty)) (for-coord-seq (incf res.x tx) (incf res.y ty)))))) (macrolet ((do-on-vector () `(let* ((n (length coord-seq)) (res (make-array n :initial-element 0))) (declare (type simple-vector res)) (macrolet ((for-coord-seq (&rest body) `(loop for i of-type fixnum below n by 2 do (let ((x (aref coord-seq i)) (y (aref coord-seq (+ i 1)))) (declare (ignorable x y)) (symbol-macrolet ((res.x (aref res i)) (res.y (aref res (+ i 1)))) ,@body))))) (do-transform)) res)) (do-on-list () `(let* ((n (length coord-seq)) (res (make-array n :initial-element 0))) (declare (type simple-vector res)) (macrolet ((for-coord-seq (&rest body) `(loop for i of-type fixnum below n by 2 for q on coord-seq by #'cddr do (let ((x (car q)) (y (cadr q))) (declare (ignorable x y)) (symbol-macrolet ((res.x (aref res i)) (res.y (aref res (+ i 1)))) ,@body))))) (do-transform)) res))) (cond ((typep coord-seq 'simple-vector) (locally (declare (type simple-vector coord-seq)) (do-on-vector))) ((typep coord-seq 'vector) (locally (declare (type vector coord-seq)) (do-on-vector))) ((typep coord-seq 'list) (locally (declare (type list coord-seq)) (do-on-list))) (t (error "~S is not a sequence." coord-seq)) ))))))) (defun transform-position-sequence (seq-type transformation coord-seq) (cond ((subtypep seq-type 'vector) (transform-positions transformation coord-seq)) (t (map-repeated-sequence seq-type 2 (lambda (x y) (transform-position transformation x y)) coord-seq)))) (defmethod transform-rectangle* ((transformation transformation) x1 y1 x2 y2) (if (rectilinear-transformation-p transformation) (multiple-value-bind (x1 y1) (transform-position transformation x1 y1) (multiple-value-bind (x2 y2) (transform-position transformation x2 y2) (values (min x1 x2) (min y1 y2) (max x1 x2) (max y1 y2)))) (error 'rectangle-transformation-error :transformation transformation :rect (list x1 y2 x2 y2)))) (defmethod untransform-rectangle* ((transformation transformation) x1 y1 x2 y2) (transform-rectangle* (invert-transformation transformation) x1 y1 x2 y2)) (defmethod transformation-transformator ((transformation standard-transformation) &optional (input-type 'real)) (multiple-value-bind (mxx mxy myx myy tx ty) (get-transformation transformation) (labels ((s* (x y) (cond ((coordinate= 0 x) nil) ((coordinate= 1 x) (list y)) ((coordinate= -1 x) (list `(- ,y))) ((list `(* ,x ,y))))) (s+ (args) (cond ((null args) (coerce 0 'coordinate)) ((null (cdr args)) (car args)) (t `(+ .,args))))) (compile nil `(lambda (x y) (declare (ignorable x y) (type ,input-type x y) (optimize (speed 3) (space 0) (safety 0))) (values ,(s+ (nconc (s* mxx 'x) (s* mxy 'y) (if (coordinate/= 0 tx) (list tx) nil))) ,(s+ (nconc (s* myx 'x) (s* myy 'y) (if (coordinate/= 0 ty) (list ty) nil))))) )))) (defmethod transformation-transformator ((transformation transformation) &optional (input-type 'real)) (declare (ignore input-type)) #'(lambda (x y) (transform-position transformation x y))) (defun atan* (x y) atan so , wie wir es brauchen . Bei uns ist phi=0 zwischen 0 und 2pi . (let ((r (atan y x))) (if (< r 0) (+ r (* 2 pi)) r))) (defun correct-angle (a phi) (if (< a phi) (+ a (* 2 pi)) a)) (defun transform-angle (transformation phi) (multiple-value-bind (rotations remainder) (ffloor phi (* 2 pi)) (when (reflection-transformation-p transformation) (setq rotations (ffloor (- phi) (* 2 pi)))) (multiple-value-bind (ix iy) (transform-distance transformation (cos remainder) (sin remainder)) (multiple-value-bind (x0 y0) (transform-distance transformation 1 0) (let ((my-angle (atan* ix iy)) (null-angle (atan* x0 y0))) (+ (* rotations 2 pi) (correct-angle my-angle null-angle))))))) (defun untransform-angle (transformation phi) (multiple-value-bind (rotations remainder) (ffloor phi (* 2 pi)) (when (reflection-transformation-p transformation) (setq rotations (ffloor (- phi) (* 2 pi)))) (multiple-value-bind (ix iy) (untransform-distance transformation (cos remainder) (sin remainder)) (multiple-value-bind (x0 y0) (untransform-distance transformation 1 0) (let ((my-angle (atan* ix iy)) (null-angle (atan* x0 y0))) (+ (* rotations 2 pi) (correct-angle my-angle null-angle))))))) (defmethod compose-transformations ((transformation2 standard-translation) (transformation1 standard-translation)) (with-slots ((dx1 dx) (dy1 dy)) transformation1 (with-slots ((dx2 dx) (dy2 dy)) transformation2 (make-translation-transformation (+ dx1 dx2) (+ dy1 dy2))))) (defmethod compose-transformations (transformation2 (transformation1 standard-identity-transformation)) transformation2) (defmethod compose-transformations ((transformation2 standard-identity-transformation) transformation1) transformation1) (defmethod invert-transformation ((transformation standard-identity-transformation)) transformation) (defmethod invert-transformation ((transformation standard-translation)) (with-slots (dx dy) transformation (make-translation-transformation (- dx) (- dy)))) (defmethod transform-position ((transformation standard-translation) x y) (with-slots (dx dy) transformation (let ((x (coordinate x)) (y (coordinate y))) (declare (type coordinate dx dy x y)) (values (+ x dx) (+ y dy))))) (defmethod transform-position ((transformation standard-identity-transformation) x y) (values x y)) (defmethod transform-region ((transformation standard-identity-transformation) region) region) (defmethod rectilinear-transformation-p ((tr standard-identity-transformation)) t) (defmethod rectilinear-transformation-p ((tr standard-translation)) t) (defmethod scaling-transformation-p ((tr standard-translation)) t) (defmethod scaling-transformation-p ((tr standard-identity-transformation)) t) (defmethod transformation-equal ((t1 standard-identity-transformation) (t2 standard-identity-transformation)) t) (defmethod transformation-equal ((t1 standard-identity-transformation) (t2 t)) nil) (defmethod transformation-equal ((t2 t) (t1 standard-identity-transformation)) nil) (defmethod transformation-equal ((t1 standard-translation) (t2 standard-translation)) (with-slots ((dx1 dx) (dy1 dy)) t1 (with-slots ((dx2 dx) (dy2 dy)) t2 (and (coordinate= dx1 dx2) (coordinate= dy1 dy2))))) (defmethod transformation-equal ((t1 standard-translation) (t2 t)) nil) (defmethod transformation-equal ((t2 t) (t1 standard-translation)) nil)
7785d44a6c839160522ea49c9427667429091cfee089b536bfc2d05329e1431f
milankinen/cuic
page.clj
(ns ^:no-doc cuic.internal.page (:require [clojure.tools.logging :refer [warn]] [cuic.internal.cdt :refer [invoke on off cdt-promise]]) (:import (java.lang AutoCloseable))) (set! *warn-on-reflection* true) (defrecord Page [cdt state subscription] AutoCloseable (close [_] (reset! state nil) (off subscription))) (defn- main-frame-id [page] (get-in @(:state page) [:main-frame :id])) (defn- loader-id [page] (get-in @(:state page) [:main-frame :loaderId])) (defn- handle-lifecycle-event [state {:keys [name frameId loaderId]}] (letfn [(handle [{:keys [main-frame] :as s}] (if (= (:id main-frame) frameId) (if (= "init" name) (-> (assoc s :events #{}) (assoc-in [:main-frame :loaderId] loaderId)) (update s :events conj name)) s))] (swap! state handle))) (defn- handle-dialog-opening [cdt state {:keys [message type defaultPrompt]}] (if-let [handler (:dialog-handler @state)] (let [args {:message message :type (keyword type) :default-prompt defaultPrompt} result (handler args)] (invoke {:cdt cdt :cmd "Page.handleJavaScriptDialog" :args {:accept (boolean result) :promptText (if (string? result) result "")}})) (do (warn "JavaScript dialog was opened but no handler is defined." "Using default handler accepting all dialogs") (invoke {:cdt cdt :cmd "Page.handleJavaScriptDialog" :args {:accept true :promptText ""}})))) (defn- handle-event [cdt state method params] (case method "Page.lifecycleEvent" (handle-lifecycle-event state params) "Page.javascriptDialogOpening" (handle-dialog-opening cdt state params) nil)) (defn- navigate [{:keys [cdt] :as page} navigation-op timeout] (let [p (cdt-promise cdt timeout) frame-id (main-frame-id page) cb (fn [method {:keys [frameId name]}] (when (or (and (= "Page.lifecycleEvent" method) (= frameId frame-id) (= "load" name)) (and (= "Page.navigatedWithinDocument" method) (= frameId frame-id))) (deliver p ::ok))) subs (on {:cdt cdt :methods #{"Page.lifecycleEvent" "Page.navigatedWithinDocument"} :callback cb})] (try (navigation-op) (when (pos-int? timeout) @p) (finally (off subs))))) ;;;; (defn page? [x] (some? x)) (defn attach [cdt] (let [;; Get initial main frame main-frame (-> (invoke {:cdt cdt :cmd "Page.getFrameTree" :args {}}) (get-in [:frameTree :frame])) Initialize page state state (atom {:main-frame main-frame :events #{}}) ;; Attach listeners for lifecycle events subs (on {:cdt cdt :methods #{"Page.lifecycleEvent" "Page.javascriptDialogOpening" "Page.javascriptDialogClosed"} :callback #(handle-event cdt state %1 %2)})] ;; Enable events (invoke {:cdt cdt :cmd "Page.enable" :args {}}) (invoke {:cdt cdt :cmd "Page.setLifecycleEventsEnabled" :args {:enabled true}}) ;; Return handle to the page (->Page cdt state subs))) (defn set-dialog-handler [page f] {:pre [(page? page) (fn? f)]} (swap! (:state page) #(when % (assoc % :dialog-handler f)))) (defn detach [page] {:pre [(page? page)]} (.close ^Page page)) (defn detached? [page] {:pre [(page? page)]} (nil? @(:state page))) (defn navigate-to [{:keys [cdt] :as page} url timeout] {:pre [(page? page) (string? url) (nat-int? timeout)]} (let [op #(invoke {:cdt cdt :cmd "Page.navigate" :args {:url url}})] (navigate page op timeout))) (defn navigate-back [{:keys [cdt] :as page} timeout] {:pre [(page? page) (nat-int? timeout)]} (let [history (invoke {:cdt cdt :cmd "Page.getNavigationHistory" :args {}}) idx (:currentIndex history) entry (->> (take idx (:entries history)) (last)) op #(invoke {:cdt cdt :cmd "Page.navigateToHistoryEntry" :args {:entryId (:id entry)}})] (when entry (navigate page op timeout)))) (defn navigate-forward [{:keys [cdt] :as page} timeout] {:pre [(page? page) (nat-int? timeout)]} (let [history (invoke {:cdt cdt :cmd "Page.getNavigationHistory" :args {}}) idx (:currentIndex history) entry (->> (drop (inc idx) (:entries history)) (first)) op #(invoke {:cdt cdt :cmd "Page.navigateToHistoryEntry" :args {:entryId (:id entry)}})] (when entry (navigate page op timeout)))) (defn get-page-cdt [page] {:pre [(page? page)]} (:cdt page)) (defn get-page-loader-id [page] {:pre [(page? page)]} (loader-id page))
null
https://raw.githubusercontent.com/milankinen/cuic/94718c0580da2aa127d967207f163c7a546b6fb1/src/clj/cuic/internal/page.clj
clojure
Get initial main frame Attach listeners for lifecycle events Enable events Return handle to the page
(ns ^:no-doc cuic.internal.page (:require [clojure.tools.logging :refer [warn]] [cuic.internal.cdt :refer [invoke on off cdt-promise]]) (:import (java.lang AutoCloseable))) (set! *warn-on-reflection* true) (defrecord Page [cdt state subscription] AutoCloseable (close [_] (reset! state nil) (off subscription))) (defn- main-frame-id [page] (get-in @(:state page) [:main-frame :id])) (defn- loader-id [page] (get-in @(:state page) [:main-frame :loaderId])) (defn- handle-lifecycle-event [state {:keys [name frameId loaderId]}] (letfn [(handle [{:keys [main-frame] :as s}] (if (= (:id main-frame) frameId) (if (= "init" name) (-> (assoc s :events #{}) (assoc-in [:main-frame :loaderId] loaderId)) (update s :events conj name)) s))] (swap! state handle))) (defn- handle-dialog-opening [cdt state {:keys [message type defaultPrompt]}] (if-let [handler (:dialog-handler @state)] (let [args {:message message :type (keyword type) :default-prompt defaultPrompt} result (handler args)] (invoke {:cdt cdt :cmd "Page.handleJavaScriptDialog" :args {:accept (boolean result) :promptText (if (string? result) result "")}})) (do (warn "JavaScript dialog was opened but no handler is defined." "Using default handler accepting all dialogs") (invoke {:cdt cdt :cmd "Page.handleJavaScriptDialog" :args {:accept true :promptText ""}})))) (defn- handle-event [cdt state method params] (case method "Page.lifecycleEvent" (handle-lifecycle-event state params) "Page.javascriptDialogOpening" (handle-dialog-opening cdt state params) nil)) (defn- navigate [{:keys [cdt] :as page} navigation-op timeout] (let [p (cdt-promise cdt timeout) frame-id (main-frame-id page) cb (fn [method {:keys [frameId name]}] (when (or (and (= "Page.lifecycleEvent" method) (= frameId frame-id) (= "load" name)) (and (= "Page.navigatedWithinDocument" method) (= frameId frame-id))) (deliver p ::ok))) subs (on {:cdt cdt :methods #{"Page.lifecycleEvent" "Page.navigatedWithinDocument"} :callback cb})] (try (navigation-op) (when (pos-int? timeout) @p) (finally (off subs))))) (defn page? [x] (some? x)) (defn attach [cdt] main-frame (-> (invoke {:cdt cdt :cmd "Page.getFrameTree" :args {}}) (get-in [:frameTree :frame])) Initialize page state state (atom {:main-frame main-frame :events #{}}) subs (on {:cdt cdt :methods #{"Page.lifecycleEvent" "Page.javascriptDialogOpening" "Page.javascriptDialogClosed"} :callback #(handle-event cdt state %1 %2)})] (invoke {:cdt cdt :cmd "Page.enable" :args {}}) (invoke {:cdt cdt :cmd "Page.setLifecycleEventsEnabled" :args {:enabled true}}) (->Page cdt state subs))) (defn set-dialog-handler [page f] {:pre [(page? page) (fn? f)]} (swap! (:state page) #(when % (assoc % :dialog-handler f)))) (defn detach [page] {:pre [(page? page)]} (.close ^Page page)) (defn detached? [page] {:pre [(page? page)]} (nil? @(:state page))) (defn navigate-to [{:keys [cdt] :as page} url timeout] {:pre [(page? page) (string? url) (nat-int? timeout)]} (let [op #(invoke {:cdt cdt :cmd "Page.navigate" :args {:url url}})] (navigate page op timeout))) (defn navigate-back [{:keys [cdt] :as page} timeout] {:pre [(page? page) (nat-int? timeout)]} (let [history (invoke {:cdt cdt :cmd "Page.getNavigationHistory" :args {}}) idx (:currentIndex history) entry (->> (take idx (:entries history)) (last)) op #(invoke {:cdt cdt :cmd "Page.navigateToHistoryEntry" :args {:entryId (:id entry)}})] (when entry (navigate page op timeout)))) (defn navigate-forward [{:keys [cdt] :as page} timeout] {:pre [(page? page) (nat-int? timeout)]} (let [history (invoke {:cdt cdt :cmd "Page.getNavigationHistory" :args {}}) idx (:currentIndex history) entry (->> (drop (inc idx) (:entries history)) (first)) op #(invoke {:cdt cdt :cmd "Page.navigateToHistoryEntry" :args {:entryId (:id entry)}})] (when entry (navigate page op timeout)))) (defn get-page-cdt [page] {:pre [(page? page)]} (:cdt page)) (defn get-page-loader-id [page] {:pre [(page? page)]} (loader-id page))
59aa77666369ab233447a16605e2f3785d354d1ec8b5d2bb2764ecd7ce7179ec
lexi-lambda/hackett
todo.rkt
#lang hackett/base (require (only-in racket/base define-syntax for-syntax) (for-syntax racket/base syntax/srcloc hackett/private/typecheck) syntax/parse/define hackett/private/deferred-transformer (only-in hackett/private/prim error!)) (provide todo!) (define-syntax todo! (make-expected-type-transformer (syntax-parser [(_ e ...) (let* ([type-str (type->string (get-expected this-syntax))] [message (string-append (source-location->prefix this-syntax) "todo! with type " type-str)]) (syntax-property (quasisyntax/loc this-syntax (error! #,message)) 'todo `#s(todo-item ,type-str ,type-str)))])))
null
https://raw.githubusercontent.com/lexi-lambda/hackett/e90ace9e4a056ec0a2a267f220cb29b756cbefce/hackett-lib/hackett/todo.rkt
racket
#lang hackett/base (require (only-in racket/base define-syntax for-syntax) (for-syntax racket/base syntax/srcloc hackett/private/typecheck) syntax/parse/define hackett/private/deferred-transformer (only-in hackett/private/prim error!)) (provide todo!) (define-syntax todo! (make-expected-type-transformer (syntax-parser [(_ e ...) (let* ([type-str (type->string (get-expected this-syntax))] [message (string-append (source-location->prefix this-syntax) "todo! with type " type-str)]) (syntax-property (quasisyntax/loc this-syntax (error! #,message)) 'todo `#s(todo-item ,type-str ,type-str)))])))
350c971907f25561132d067ce35570734b2daefa04c03f015d1169fd53c66a4b
aryx/xix
ast.ml
Copyright 2016 , see copyright.txt (* for error reporting *) type loc = { file: Common.filename; (* an mkfile *) line: int; } The elements below are not separated by any separator ; they are direct * concatenations of elements ( hence the need for $ { name } below ) . * The list must contain at least one element . * ex : ' % .c ' - > W [ Percent ; String " .c " ] * concatenations of elements (hence the need for ${name} below). * The list must contain at least one element. * ex: '%.c' -> W [Percent; String ".c"] *) type word = W of word_element list and word_element = | String of string (* except the empty string *) | Percent (* evaluated in eval.ml just after parsing *) | Var of var (* stricter: backquotes are allowed only in word context, not at toplevel * so no `echo '<foo.c'` *) (* `...` or `{...} (the string does not include the backquote or braces) *) | Backquoted of string and var = (* $name or ${name} (the string does not contain the $ or {}) *) | SimpleVar of string (* ${name:a%b=c%d} *) | SubstVar of (string * word * word list) (* Words are separated by spaces. See also Env.values *) type words = word list (* (the strings do not contain the leading space nor trailing newline) *) type recipe = R of string list (* See also Rules.rule_exec *) type rule = { targets: words; prereqs: words; attrs: rule_attribute list; recipe: recipe option; } and rule_attribute = | Virtual | Quiet | Delete pad : I added this one | NotHandled of char type instr = { instr: instr_kind; loc: loc; } and instr_kind = (* should resolve to a single filename * less: could enforce of word? *) | Include of words the words can contain variables , ex : < |rc .. /foo.rc $ CONF * less : we could also do PipeInclude of recipe I think * less: we could also do PipeInclude of recipe I think *) | PipeInclude of words | Rule of rule stricter : no dynamic def like X = AVAR $ X=42 ... $ AVAR , * so ' string ' below , not ' word ' * so 'string' below, not 'word' *) | Definition of string * words
null
https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/mk/ast.ml
ocaml
for error reporting an mkfile except the empty string evaluated in eval.ml just after parsing stricter: backquotes are allowed only in word context, not at toplevel * so no `echo '<foo.c'` `...` or `{...} (the string does not include the backquote or braces) $name or ${name} (the string does not contain the $ or {}) ${name:a%b=c%d} Words are separated by spaces. See also Env.values (the strings do not contain the leading space nor trailing newline) See also Rules.rule_exec should resolve to a single filename * less: could enforce of word?
Copyright 2016 , see copyright.txt type loc = { line: int; } The elements below are not separated by any separator ; they are direct * concatenations of elements ( hence the need for $ { name } below ) . * The list must contain at least one element . * ex : ' % .c ' - > W [ Percent ; String " .c " ] * concatenations of elements (hence the need for ${name} below). * The list must contain at least one element. * ex: '%.c' -> W [Percent; String ".c"] *) type word = W of word_element list and word_element = | Percent | Var of var | Backquoted of string and var = | SimpleVar of string | SubstVar of (string * word * word list) type words = word list type recipe = R of string list type rule = { targets: words; prereqs: words; attrs: rule_attribute list; recipe: recipe option; } and rule_attribute = | Virtual | Quiet | Delete pad : I added this one | NotHandled of char type instr = { instr: instr_kind; loc: loc; } and instr_kind = | Include of words the words can contain variables , ex : < |rc .. /foo.rc $ CONF * less : we could also do PipeInclude of recipe I think * less: we could also do PipeInclude of recipe I think *) | PipeInclude of words | Rule of rule stricter : no dynamic def like X = AVAR $ X=42 ... $ AVAR , * so ' string ' below , not ' word ' * so 'string' below, not 'word' *) | Definition of string * words
065aac5ed69794b29f29e63095be9a7ae0f022d0743881ab5fd8934018ff07f6
fission-codes/fission
Types.hs
-- | File types module Network.IPFS.File.Types (Serialized (..)) where import qualified Data.ByteString.Builder as Builder import Data.Swagger import qualified RIO.ByteString.Lazy as Lazy import Servant.API import Network.IPFS.MIME.RawPlainText.Types import Network.IPFS.Prelude -- | A file serialized as a lazy bytestring newtype Serialized = Serialized { unserialize :: Lazy.ByteString } deriving ( Eq , Show ) deriving newtype ( IsString ) instance ToSchema Serialized where declareNamedSchema _ = mempty |> example ?~ "hello world" |> description ?~ "A typical file's contents" |> type_ ?~ SwaggerString |> NamedSchema (Just "SerializedFile") |> pure instance Display Serialized where display = Utf8Builder . Builder.lazyByteString . unserialize ----- instance MimeRender PlainText Serialized where mimeRender _proxy = unserialize instance MimeRender RawPlainText Serialized where mimeRender _proxy = unserialize instance MimeRender OctetStream Serialized where mimeRender _proxy = unserialize ----- instance MimeUnrender PlainText Serialized where mimeUnrender _proxy = Right . Serialized instance MimeUnrender RawPlainText Serialized where mimeUnrender _proxy = Right . Serialized instance MimeUnrender OctetStream Serialized where mimeUnrender _proxy = Right . Serialized
null
https://raw.githubusercontent.com/fission-codes/fission/fb76d255f06ea73187c9b787bd207c3778e1b559/ipfs/library/Network/IPFS/File/Types.hs
haskell
| File types | A file serialized as a lazy bytestring --- ---
module Network.IPFS.File.Types (Serialized (..)) where import qualified Data.ByteString.Builder as Builder import Data.Swagger import qualified RIO.ByteString.Lazy as Lazy import Servant.API import Network.IPFS.MIME.RawPlainText.Types import Network.IPFS.Prelude newtype Serialized = Serialized { unserialize :: Lazy.ByteString } deriving ( Eq , Show ) deriving newtype ( IsString ) instance ToSchema Serialized where declareNamedSchema _ = mempty |> example ?~ "hello world" |> description ?~ "A typical file's contents" |> type_ ?~ SwaggerString |> NamedSchema (Just "SerializedFile") |> pure instance Display Serialized where display = Utf8Builder . Builder.lazyByteString . unserialize instance MimeRender PlainText Serialized where mimeRender _proxy = unserialize instance MimeRender RawPlainText Serialized where mimeRender _proxy = unserialize instance MimeRender OctetStream Serialized where mimeRender _proxy = unserialize instance MimeUnrender PlainText Serialized where mimeUnrender _proxy = Right . Serialized instance MimeUnrender RawPlainText Serialized where mimeUnrender _proxy = Right . Serialized instance MimeUnrender OctetStream Serialized where mimeUnrender _proxy = Right . Serialized
1604a89c6240e17da32018196796029dcf3d83119c2b294a8b0d9a9baef928e1
alexanderwasey/stupid-computer
FormalActualMap.hs
# LANGUAGE PackageImports , LambdaCase , ScopedTypeVariables , TypeApplications # # OPTIONS_GHC -Wno - missing - fields # module FormalActualMap where import "ghc-lib-parser" GHC.Hs import "ghc-lib-parser" SrcLoc import "ghc-lib-parser" RdrName import "ghc-lib-parser" OccName import "ghc-lib-parser" Outputable import "ghc-lib-parser" BasicTypes import "ghc-lib-parser" FastString import Data.Typeable (Typeable) import Data.Either import Data.List import Data.String import Data.Char import Tools import ScTypes import qualified Data.Map.Strict as Map import Data.Maybe matchPatterns :: [HsExpr GhcPs] -> [LPat GhcPs] -> (ScTypes.ModuleInfo) -> IO(Maybe (Map.Map String (HsExpr GhcPs))) matchPatterns exprs patterns modu = do maps <- mapM (\(expr,pattern) -> matchPattern expr pattern modu) (zip exprs patterns) return $ (Just Map.fromList) <*> (conMaybes maps) --Now deal with each of the cases for the patterns --Simple case with just a variable pattern matchPattern :: (HsExpr GhcPs) -> (LPat GhcPs) -> (ScTypes.ModuleInfo) -> IO(Maybe ([(String, (HsExpr GhcPs))])) matchPattern expr (L _ (VarPat _ id)) _ = return $ Just [(showSDocUnsafe $ ppr id, expr)] matchPattern (HsPar _ (L _ expr)) (L _ (ParPat _ pat)) modu = matchPattern expr pat modu matchPattern (HsPar _ (L _ expr)) pat modu = matchPattern expr pat modu matchPattern expr (L _ (ParPat _ pat)) modu = matchPattern expr pat modu --Currently only concatenation matchPattern (ExplicitList xep syn (expr:exprs)) (L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do headmap <- matchPatternL expr l modu let taillist = (ExplicitList xep syn exprs) tailmap <- matchPattern taillist r modu return $ (++) <$> headmap <*> tailmap _ -> do error "Unsupported ConPatIn found" matchPattern (OpApp xop lhs oper rhs) pat@(L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do case (showSDocUnsafe $ ppr $ Tools.removeLPars oper) of "(:)" -> do headmap <- matchPatternL lhs l modu tailmap <- matchPatternL rhs r modu return $ (++) <$> headmap <*> tailmap lhs might be empty , and still have a match . The lhs * should * be an explicit list with one element . case lhs of (L _ (HsPar _ lhs')) -> matchPattern (OpApp xop lhs' oper rhs) pat modu (L _ (ExplicitList _ _ [lhselem])) -> do headmap <- matchPatternL lhselem l modu tailmap <- matchPatternL rhs r modu return $ (++) <$> headmap <*> tailmap (L _ (ExplicitList _ _ [])) -> matchPatternL rhs pat modu --Check in the rhs for non-empty lists _ -> return Nothing _ -> return Nothing _ -> do let opname = "(" ++ (showSDocUnsafe $ ppr op) ++ ")" if (opname == (showSDocUnsafe $ ppr $ Tools.removeLPars oper)) then do headmap <- matchPatternL lhs l modu tailmap <- matchPatternL rhs r modu return $ (++) <$> headmap <*> tailmap else return Nothing When a constructor has just one component matchPattern (HsApp xep lhs rhs ) (L l (ConPatIn op (PrefixCon ([arg])))) modu = do let lhsstring = showSDocUnsafe $ ppr lhs let opstring = showSDocUnsafe $ ppr op if (lhsstring == opstring) then matchPatternL rhs arg modu else return Nothing When it has more than one matchPattern (HsApp xep lhs rhs ) (L l (ConPatIn op (PrefixCon args))) modu = do if (null args) then return Nothing else do innermatch <- matchPatternL lhs (L l (ConPatIn op (PrefixCon (init args)))) modu outermatch <- matchPatternL rhs (last args) modu return $ (++) <$> innermatch <*> outermatch matchPattern (ArithSeq xarith synexp seqInfo) (L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do case seqInfo of (From expr) -> do headmap <- matchPatternL expr l modu tailmap <- case expr of (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do let newseq = (ArithSeq xarith synexp (From (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ val+1)) neg (val+1))) witness))))) matchPattern newseq r modu _ -> return Nothing return $ (++) <$> headmap <*> tailmap (FromTo from to) -> do headmap <- matchPatternL from l modu tailmap <- case from of (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do case to of (L _ (HsOverLit _ (OverLit _ (HsIntegral (IL _ _ toval)) _))) -> do let newval = val+1 let newlit = (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ newval)) neg (newval))) witness))) let newseq = (ArithSeq xarith synexp (From newlit)) if (newval == toval) then matchPattern (ExplicitList NoExtField Nothing [newlit]) r modu else matchPattern (ArithSeq xarith synexp (FromTo newlit to)) r modu _ -> return Nothing _ -> return Nothing return $ (++) <$> headmap <*> tailmap _ -> do return Nothing _ -> do return Nothing matchPattern (HsLit _ str@(HsString _ _ )) (L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do let s = init $ tail $ showSDocUnsafe $ ppr str if (null s) then return Nothing else do let headchar = (HsLit NoExtField (HsChar (SourceText $ "'" ++ [(head s)] ++"'") (head s))) :: HsExpr GhcPs let tailstring = (HsLit NoExtField (HsString (SourceText $ "\"" ++ (tail s) ++ "\"") (mkFastString $ tail s))) :: HsExpr GhcPs headmap <- matchPattern headchar l modu tailmap <- matchPattern tailstring r modu return $ (++) <$> headmap <*> tailmap _ -> return Nothing --Currently only empty list (and constructors) matchPattern expr pat@(L _ (ConPatIn op (PrefixCon _ ))) _ = do case (showSDocUnsafe $ ppr op) of "[]" -> do let exprstring = showSDocUnsafe $ ppr expr if (exprstring == "[]") || (exprstring == "\"\"") then return (Just []) else return Nothing name -> if (name == (showSDocUnsafe $ ppr expr)) then return (Just []) else return Nothing matchPattern (ExplicitTuple _ contents _) (L _ (TuplePat _ pats _)) modu = do let matches = [(con, pat) | ((L _ (Present _ con)), pat) <- zip contents pats ] maps <- mapM (\(expr,pattern) -> matchPatternL expr pattern modu) matches return $ conMaybes maps matchPattern (ExplicitList _ _ exprs) (L _ (ListPat _ pats)) modu = do maps <- mapM (\(expr,pattern) -> matchPatternL expr pattern modu) (zip exprs pats) return $ conMaybes maps matchPattern _ (L _ (WildPat _)) _ = return $ Just [] -- Matches against `_` matchPattern expr (L _ pat@(NPat _ _ _ _)) _ = do let exprstr = showSDocUnsafe $ ppr expr let patstr = showSDocUnsafe $ ppr pat if (exprstr == patstr) then return (Just []) else return Nothing matchPattern expr (L _ (AsPat _ id pat)) modu = do let leftmap = Just [(showSDocUnsafe $ ppr id, expr)] rightmap <- matchPattern expr pat modu return $ (++) <$> leftmap <*> rightmap matchPattern _ _ _ = return Nothing --For when has located expressions matchPatternsL :: [LHsExpr GhcPs] -> [LPat GhcPs] -> (ScTypes.ModuleInfo) -> IO(Maybe (Map.Map String (HsExpr GhcPs))) matchPatternsL exprs patterns modu = do let exprs' = map (\(L _ expr) -> expr) exprs matchPatterns exprs' patterns modu --Single located expression matchPatternL :: (LHsExpr GhcPs) -> (LPat GhcPs) -> (ScTypes.ModuleInfo) -> IO(Maybe ([(String, (HsExpr GhcPs))])) matchPatternL (L _ expr) pattern modu = matchPattern expr pattern modu conMaybes :: [Maybe [a]] -> Maybe [a] conMaybes [] = Just [] conMaybes (Nothing:_) = Nothing conMaybes (x:xs) = (++) <$> x <*> (conMaybes xs) splitList :: (LHsExpr GhcPs) -> (ScTypes.ModuleInfo) -> IO (Maybe (LHsExpr GhcPs, LHsExpr GhcPs)) splitList (L l (ExplicitList xep syn (expr:exprs))) _ = return $ Just (expr, (L l (ExplicitList xep syn exprs))) splitList (L l (ArithSeq xarith synexp seqInfo)) _ = do case seqInfo of (From expr) -> do let head = expr tail <- case expr of (L _ (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do let newseq = (ArithSeq xarith synexp (From (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ val+1)) neg (val+1))) witness))))) return newseq return $ Just (head, (L l tail)) (FromTo from to) -> do let head = from tail <- case from of (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do case to of (L _ (HsOverLit _ (OverLit _ (HsIntegral (IL _ _ toval)) _))) -> do let newval = val+1 let newlit = (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ newval)) neg (newval))) witness))) let newseq = (ArithSeq xarith synexp (From newlit)) if (newval == toval) then return $ Just (ExplicitList NoExtField Nothing [newlit]) else return $ Just (ArithSeq xarith synexp (FromTo newlit to)) _ -> return Nothing case tail of (Just t) -> return $ Just (head , (L l t)) _ -> return Nothing _ -> do return Nothing splitList (L _ (OpApp _ lhs oper rhs)) _ = do case (showSDocUnsafe $ ppr $ Tools.removeLPars oper) of "(:)" -> do return $ Just (lhs, rhs) _ -> return Nothing splitList (L _ (HsPar _ expr)) modu = splitList expr modu splitList _ _ = return Nothing couldAllMatch :: [(HsExpr GhcPs)] -> [(LPat GhcPs)] -> IO(Bool) couldAllMatch exprs pats = and <$> mapM (uncurry couldMatch) (zip exprs pats) couldMatch :: (HsExpr GhcPs) -> (LPat GhcPs) -> IO(Bool) couldMatch expr (L _ (VarPat _ _)) = return True couldMatch (HsPar _ (L _ expr)) (L _ (ParPat _ pat)) = couldMatch expr pat couldMatch (HsPar _ (L _ expr)) pat = couldMatch expr pat couldMatch expr (L _ (ParPat _ pat)) = couldMatch expr pat couldMatch (ExplicitList xep syn (expr:exprs)) (L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> do let headexpr = (\(L _ x) -> x) expr lhs <- couldMatch headexpr l let taillist = (ExplicitList xep syn exprs) rhs <- couldMatch taillist r return $ lhs && rhs _ -> do error "Unsupported ConPatIn found" couldMatch (ExplicitList xep syn []) (L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> return False _ -> do error "Unsupported ConPatIn found" couldMatch (ExplicitList _ _ exprs) (L _ (ListPat _ pats)) = do if ((length exprs) /= (length pats)) then return False else do results <- mapM (\((L _ expr),pattern) -> couldMatch expr pattern) (zip exprs pats) return $ and results couldMatch (ExplicitList _ _ _) _ = return False couldMatch (OpApp xop (L _ lhs) oper (L _ rhs)) pat@(L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> do case (showSDocUnsafe $ ppr $ Tools.removeLPars oper) of "(:)" -> do headresult <- couldMatch lhs l tailresult <- couldMatch rhs r return $ headresult && tailresult lhs might be empty , and still have a match . The lhs * should * be an explicit list with one element . case lhs of (HsPar _ lhs') -> couldMatch (OpApp xop lhs' oper (noLoc rhs)) pat (ExplicitList _ _ [(L _ lhselem)]) -> do headresult <- couldMatch lhselem l tailresult <- couldMatch rhs r return $ headresult && tailresult (ExplicitList _ _ []) -> couldMatch rhs pat --Check in the rhs for non-empty lists _ -> return False _ -> return False _ -> do let opname = "(" ++ (showSDocUnsafe $ ppr op) ++ ")" if (opname == (showSDocUnsafe $ ppr $ Tools.removeLPars oper)) then do headresult <- couldMatch lhs l tailresult <- couldMatch rhs r return $ headresult && tailresult else return False When a constructor has just one component couldMatch (HsApp xep (L _ lhs) (L _ rhs) ) (L l (ConPatIn op (PrefixCon ([arg])))) = do let lhsstring = showSDocUnsafe $ ppr lhs let opstring = showSDocUnsafe $ ppr op if (lhsstring == opstring) then couldMatch rhs arg else return False When it has more than one couldMatch (HsApp xep (L _ lhs) (L _ rhs) ) (L l (ConPatIn op (PrefixCon args))) = do if (null args) then return False else do innermatch <- couldMatch lhs (L l (ConPatIn op (PrefixCon (init args)))) outermatch <- couldMatch rhs (last args) return $ innermatch && outermatch couldMatch (ArithSeq xarith synexp seqInfo) (L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> do case seqInfo of (From (L _ expr)) -> do headmap <- couldMatch expr l tailmap <- case expr of (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness)) -> do let newseq = (ArithSeq xarith synexp (From (noLoc (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ val+1)) neg (val+1))) witness))))) couldMatch newseq r _ -> return False return $ headmap && tailmap (FromTo (L _ from) (L _ to)) -> do headmap <- couldMatch from l tailmap <- case from of (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness)) -> do case to of (HsOverLit _ (OverLit _ (HsIntegral (IL _ _ toval)) _)) -> do let newval = val+1 let newlit = (noLoc (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ newval)) neg (newval))) witness))) :: (LHsExpr GhcPs) let newseq = (ArithSeq xarith synexp (From newlit)) if (newval == toval) then couldMatch (ExplicitList NoExtField Nothing [newlit]) r else couldMatch (ArithSeq xarith synexp (FromTo newlit (noLoc to))) r _ -> return False _ -> return False return $ headmap && tailmap _ -> do return False _ -> do return False couldMatch seq@(ArithSeq _ _ _ ) pattern = return $ (showSDocUnsafe $ ppr pattern) /= "[]" --Currently only empty list couldMatch (HsLit _ str@(HsString _ _)) (L _ (ConPatIn op (PrefixCon _))) = do let s = showSDocUnsafe $ ppr str case (showSDocUnsafe $ ppr op) of "[]" -> return (null s) _ -> return False couldMatch _ (L _ (ConPatIn op (PrefixCon _ ))) = do case (showSDocUnsafe $ ppr op) of "[]" -> return True _ -> return False couldMatch (ExplicitTuple _ contents _) (L _ (TuplePat _ pats _)) = do if ((length contents) /= (length pats)) then return False else do let matches = [(con, pat) | ((L _ (Present _ con)), pat) <- zip contents pats ] maps <- mapM (\((L _ expr),pattern) -> couldMatch expr pattern) matches return $ and maps couldMatch _ (L _ (WildPat _)) = return True --When matching against a literal couldMatch expr@(HsOverLit _ _) (L _ pat@(NPat _ _ _ _)) = do let exprstr = showSDocUnsafe $ ppr expr let patstr = showSDocUnsafe $ ppr pat return (exprstr == patstr) couldMatch expr@(HsLit _ _) (L _ pat@(NPat _ _ _ _)) = do let exprstr = showSDocUnsafe $ ppr expr let patstr = showSDocUnsafe $ ppr pat return (exprstr == patstr) couldMatch (HsLit _ _) _ = return False couldMatch (HsOverLit _ _) _ = return False couldMatch _ (L _ (NPat _ _ _ _)) = return True couldMatch expr (L _ (AsPat _ _ pat)) = couldMatch expr pat couldMatch expr@(HsVar _ _) pat = return ((showSDocUnsafe $ ppr expr) == (showSDocUnsafe $ ppr pat)) couldMatch exp _ = return True --Takes a part of the pattern and returns it's components nameFromPatternComponent :: (LPat GhcPs) -> [String] nameFromPatternComponent (L _ (VarPat _ (L _ name))) = [occNameString $ rdrNameOcc name] -- For single strings? nameFromPatternComponent (L _ (ConPatIn (L _ name) (InfixCon l r))) = (nameFromPatternComponent l) ++ (nameFromPatternComponent r) -- For (x:xs) patterns nameFromPatternComponent (L _ (ConPatIn (L _ name) (PrefixCon members))) = concat $ map nameFromPatternComponent members -- For constructor patterns nameFromPatternComponent (L _ (ConPatIn (L _ name) _)) = [occNameString $ rdrNameOcc name] nameFromPatternComponent (L _ (ParPat _ name)) = nameFromPatternComponent name --Things in parenthesis Tuples nameFromPatternComponent (L _ (WildPat (NoExtField))) = [] -- For '_' patterns nameFromPatternComponent (L _ (LitPat _ _)) = [] -- Literals do not need to be moved in nameFromPatternComponent (L _ (NPat _ _ _ _)) = [] nameFromPatternComponent (L _ (ListPat _ pats)) = concat $ map nameFromPatternComponent pats nameFromPatternComponent e = error $ "Unsupported type in pattern matching :" ++ (showSDocUnsafe $ ppr e)
null
https://raw.githubusercontent.com/alexanderwasey/stupid-computer/a485d2f33a4b8d58128a74b9003b9eadffe42702/src/FormalActualMap.hs
haskell
Now deal with each of the cases for the patterns Simple case with just a variable pattern Currently only concatenation Check in the rhs for non-empty lists Currently only empty list (and constructors) Matches against `_` For when has located expressions Single located expression Check in the rhs for non-empty lists Currently only empty list When matching against a literal Takes a part of the pattern and returns it's components For single strings? For (x:xs) patterns For constructor patterns Things in parenthesis For '_' patterns Literals do not need to be moved in
# LANGUAGE PackageImports , LambdaCase , ScopedTypeVariables , TypeApplications # # OPTIONS_GHC -Wno - missing - fields # module FormalActualMap where import "ghc-lib-parser" GHC.Hs import "ghc-lib-parser" SrcLoc import "ghc-lib-parser" RdrName import "ghc-lib-parser" OccName import "ghc-lib-parser" Outputable import "ghc-lib-parser" BasicTypes import "ghc-lib-parser" FastString import Data.Typeable (Typeable) import Data.Either import Data.List import Data.String import Data.Char import Tools import ScTypes import qualified Data.Map.Strict as Map import Data.Maybe matchPatterns :: [HsExpr GhcPs] -> [LPat GhcPs] -> (ScTypes.ModuleInfo) -> IO(Maybe (Map.Map String (HsExpr GhcPs))) matchPatterns exprs patterns modu = do maps <- mapM (\(expr,pattern) -> matchPattern expr pattern modu) (zip exprs patterns) return $ (Just Map.fromList) <*> (conMaybes maps) matchPattern :: (HsExpr GhcPs) -> (LPat GhcPs) -> (ScTypes.ModuleInfo) -> IO(Maybe ([(String, (HsExpr GhcPs))])) matchPattern expr (L _ (VarPat _ id)) _ = return $ Just [(showSDocUnsafe $ ppr id, expr)] matchPattern (HsPar _ (L _ expr)) (L _ (ParPat _ pat)) modu = matchPattern expr pat modu matchPattern (HsPar _ (L _ expr)) pat modu = matchPattern expr pat modu matchPattern expr (L _ (ParPat _ pat)) modu = matchPattern expr pat modu matchPattern (ExplicitList xep syn (expr:exprs)) (L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do headmap <- matchPatternL expr l modu let taillist = (ExplicitList xep syn exprs) tailmap <- matchPattern taillist r modu return $ (++) <$> headmap <*> tailmap _ -> do error "Unsupported ConPatIn found" matchPattern (OpApp xop lhs oper rhs) pat@(L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do case (showSDocUnsafe $ ppr $ Tools.removeLPars oper) of "(:)" -> do headmap <- matchPatternL lhs l modu tailmap <- matchPatternL rhs r modu return $ (++) <$> headmap <*> tailmap lhs might be empty , and still have a match . The lhs * should * be an explicit list with one element . case lhs of (L _ (HsPar _ lhs')) -> matchPattern (OpApp xop lhs' oper rhs) pat modu (L _ (ExplicitList _ _ [lhselem])) -> do headmap <- matchPatternL lhselem l modu tailmap <- matchPatternL rhs r modu return $ (++) <$> headmap <*> tailmap _ -> return Nothing _ -> return Nothing _ -> do let opname = "(" ++ (showSDocUnsafe $ ppr op) ++ ")" if (opname == (showSDocUnsafe $ ppr $ Tools.removeLPars oper)) then do headmap <- matchPatternL lhs l modu tailmap <- matchPatternL rhs r modu return $ (++) <$> headmap <*> tailmap else return Nothing When a constructor has just one component matchPattern (HsApp xep lhs rhs ) (L l (ConPatIn op (PrefixCon ([arg])))) modu = do let lhsstring = showSDocUnsafe $ ppr lhs let opstring = showSDocUnsafe $ ppr op if (lhsstring == opstring) then matchPatternL rhs arg modu else return Nothing When it has more than one matchPattern (HsApp xep lhs rhs ) (L l (ConPatIn op (PrefixCon args))) modu = do if (null args) then return Nothing else do innermatch <- matchPatternL lhs (L l (ConPatIn op (PrefixCon (init args)))) modu outermatch <- matchPatternL rhs (last args) modu return $ (++) <$> innermatch <*> outermatch matchPattern (ArithSeq xarith synexp seqInfo) (L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do case seqInfo of (From expr) -> do headmap <- matchPatternL expr l modu tailmap <- case expr of (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do let newseq = (ArithSeq xarith synexp (From (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ val+1)) neg (val+1))) witness))))) matchPattern newseq r modu _ -> return Nothing return $ (++) <$> headmap <*> tailmap (FromTo from to) -> do headmap <- matchPatternL from l modu tailmap <- case from of (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do case to of (L _ (HsOverLit _ (OverLit _ (HsIntegral (IL _ _ toval)) _))) -> do let newval = val+1 let newlit = (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ newval)) neg (newval))) witness))) let newseq = (ArithSeq xarith synexp (From newlit)) if (newval == toval) then matchPattern (ExplicitList NoExtField Nothing [newlit]) r modu else matchPattern (ArithSeq xarith synexp (FromTo newlit to)) r modu _ -> return Nothing _ -> return Nothing return $ (++) <$> headmap <*> tailmap _ -> do return Nothing _ -> do return Nothing matchPattern (HsLit _ str@(HsString _ _ )) (L _(ConPatIn op (InfixCon l r))) modu = do case (showSDocUnsafe $ ppr op) of ":" -> do let s = init $ tail $ showSDocUnsafe $ ppr str if (null s) then return Nothing else do let headchar = (HsLit NoExtField (HsChar (SourceText $ "'" ++ [(head s)] ++"'") (head s))) :: HsExpr GhcPs let tailstring = (HsLit NoExtField (HsString (SourceText $ "\"" ++ (tail s) ++ "\"") (mkFastString $ tail s))) :: HsExpr GhcPs headmap <- matchPattern headchar l modu tailmap <- matchPattern tailstring r modu return $ (++) <$> headmap <*> tailmap _ -> return Nothing matchPattern expr pat@(L _ (ConPatIn op (PrefixCon _ ))) _ = do case (showSDocUnsafe $ ppr op) of "[]" -> do let exprstring = showSDocUnsafe $ ppr expr if (exprstring == "[]") || (exprstring == "\"\"") then return (Just []) else return Nothing name -> if (name == (showSDocUnsafe $ ppr expr)) then return (Just []) else return Nothing matchPattern (ExplicitTuple _ contents _) (L _ (TuplePat _ pats _)) modu = do let matches = [(con, pat) | ((L _ (Present _ con)), pat) <- zip contents pats ] maps <- mapM (\(expr,pattern) -> matchPatternL expr pattern modu) matches return $ conMaybes maps matchPattern (ExplicitList _ _ exprs) (L _ (ListPat _ pats)) modu = do maps <- mapM (\(expr,pattern) -> matchPatternL expr pattern modu) (zip exprs pats) return $ conMaybes maps matchPattern expr (L _ pat@(NPat _ _ _ _)) _ = do let exprstr = showSDocUnsafe $ ppr expr let patstr = showSDocUnsafe $ ppr pat if (exprstr == patstr) then return (Just []) else return Nothing matchPattern expr (L _ (AsPat _ id pat)) modu = do let leftmap = Just [(showSDocUnsafe $ ppr id, expr)] rightmap <- matchPattern expr pat modu return $ (++) <$> leftmap <*> rightmap matchPattern _ _ _ = return Nothing matchPatternsL :: [LHsExpr GhcPs] -> [LPat GhcPs] -> (ScTypes.ModuleInfo) -> IO(Maybe (Map.Map String (HsExpr GhcPs))) matchPatternsL exprs patterns modu = do let exprs' = map (\(L _ expr) -> expr) exprs matchPatterns exprs' patterns modu matchPatternL :: (LHsExpr GhcPs) -> (LPat GhcPs) -> (ScTypes.ModuleInfo) -> IO(Maybe ([(String, (HsExpr GhcPs))])) matchPatternL (L _ expr) pattern modu = matchPattern expr pattern modu conMaybes :: [Maybe [a]] -> Maybe [a] conMaybes [] = Just [] conMaybes (Nothing:_) = Nothing conMaybes (x:xs) = (++) <$> x <*> (conMaybes xs) splitList :: (LHsExpr GhcPs) -> (ScTypes.ModuleInfo) -> IO (Maybe (LHsExpr GhcPs, LHsExpr GhcPs)) splitList (L l (ExplicitList xep syn (expr:exprs))) _ = return $ Just (expr, (L l (ExplicitList xep syn exprs))) splitList (L l (ArithSeq xarith synexp seqInfo)) _ = do case seqInfo of (From expr) -> do let head = expr tail <- case expr of (L _ (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do let newseq = (ArithSeq xarith synexp (From (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ val+1)) neg (val+1))) witness))))) return newseq return $ Just (head, (L l tail)) (FromTo from to) -> do let head = from tail <- case from of (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness))) -> do case to of (L _ (HsOverLit _ (OverLit _ (HsIntegral (IL _ _ toval)) _))) -> do let newval = val+1 let newlit = (L l (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ newval)) neg (newval))) witness))) let newseq = (ArithSeq xarith synexp (From newlit)) if (newval == toval) then return $ Just (ExplicitList NoExtField Nothing [newlit]) else return $ Just (ArithSeq xarith synexp (FromTo newlit to)) _ -> return Nothing case tail of (Just t) -> return $ Just (head , (L l t)) _ -> return Nothing _ -> do return Nothing splitList (L _ (OpApp _ lhs oper rhs)) _ = do case (showSDocUnsafe $ ppr $ Tools.removeLPars oper) of "(:)" -> do return $ Just (lhs, rhs) _ -> return Nothing splitList (L _ (HsPar _ expr)) modu = splitList expr modu splitList _ _ = return Nothing couldAllMatch :: [(HsExpr GhcPs)] -> [(LPat GhcPs)] -> IO(Bool) couldAllMatch exprs pats = and <$> mapM (uncurry couldMatch) (zip exprs pats) couldMatch :: (HsExpr GhcPs) -> (LPat GhcPs) -> IO(Bool) couldMatch expr (L _ (VarPat _ _)) = return True couldMatch (HsPar _ (L _ expr)) (L _ (ParPat _ pat)) = couldMatch expr pat couldMatch (HsPar _ (L _ expr)) pat = couldMatch expr pat couldMatch expr (L _ (ParPat _ pat)) = couldMatch expr pat couldMatch (ExplicitList xep syn (expr:exprs)) (L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> do let headexpr = (\(L _ x) -> x) expr lhs <- couldMatch headexpr l let taillist = (ExplicitList xep syn exprs) rhs <- couldMatch taillist r return $ lhs && rhs _ -> do error "Unsupported ConPatIn found" couldMatch (ExplicitList xep syn []) (L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> return False _ -> do error "Unsupported ConPatIn found" couldMatch (ExplicitList _ _ exprs) (L _ (ListPat _ pats)) = do if ((length exprs) /= (length pats)) then return False else do results <- mapM (\((L _ expr),pattern) -> couldMatch expr pattern) (zip exprs pats) return $ and results couldMatch (ExplicitList _ _ _) _ = return False couldMatch (OpApp xop (L _ lhs) oper (L _ rhs)) pat@(L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> do case (showSDocUnsafe $ ppr $ Tools.removeLPars oper) of "(:)" -> do headresult <- couldMatch lhs l tailresult <- couldMatch rhs r return $ headresult && tailresult lhs might be empty , and still have a match . The lhs * should * be an explicit list with one element . case lhs of (HsPar _ lhs') -> couldMatch (OpApp xop lhs' oper (noLoc rhs)) pat (ExplicitList _ _ [(L _ lhselem)]) -> do headresult <- couldMatch lhselem l tailresult <- couldMatch rhs r return $ headresult && tailresult _ -> return False _ -> return False _ -> do let opname = "(" ++ (showSDocUnsafe $ ppr op) ++ ")" if (opname == (showSDocUnsafe $ ppr $ Tools.removeLPars oper)) then do headresult <- couldMatch lhs l tailresult <- couldMatch rhs r return $ headresult && tailresult else return False When a constructor has just one component couldMatch (HsApp xep (L _ lhs) (L _ rhs) ) (L l (ConPatIn op (PrefixCon ([arg])))) = do let lhsstring = showSDocUnsafe $ ppr lhs let opstring = showSDocUnsafe $ ppr op if (lhsstring == opstring) then couldMatch rhs arg else return False When it has more than one couldMatch (HsApp xep (L _ lhs) (L _ rhs) ) (L l (ConPatIn op (PrefixCon args))) = do if (null args) then return False else do innermatch <- couldMatch lhs (L l (ConPatIn op (PrefixCon (init args)))) outermatch <- couldMatch rhs (last args) return $ innermatch && outermatch couldMatch (ArithSeq xarith synexp seqInfo) (L _(ConPatIn op (InfixCon l r))) = do case (showSDocUnsafe $ ppr op) of ":" -> do case seqInfo of (From (L _ expr)) -> do headmap <- couldMatch expr l tailmap <- case expr of (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness)) -> do let newseq = (ArithSeq xarith synexp (From (noLoc (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ val+1)) neg (val+1))) witness))))) couldMatch newseq r _ -> return False return $ headmap && tailmap (FromTo (L _ from) (L _ to)) -> do headmap <- couldMatch from l tailmap <- case from of (HsOverLit ext (OverLit extlit (HsIntegral (IL text neg val)) witness)) -> do case to of (HsOverLit _ (OverLit _ (HsIntegral (IL _ _ toval)) _)) -> do let newval = val+1 let newlit = (noLoc (HsOverLit ext (OverLit extlit (HsIntegral (IL (SourceText (show $ newval)) neg (newval))) witness))) :: (LHsExpr GhcPs) let newseq = (ArithSeq xarith synexp (From newlit)) if (newval == toval) then couldMatch (ExplicitList NoExtField Nothing [newlit]) r else couldMatch (ArithSeq xarith synexp (FromTo newlit (noLoc to))) r _ -> return False _ -> return False return $ headmap && tailmap _ -> do return False _ -> do return False couldMatch seq@(ArithSeq _ _ _ ) pattern = return $ (showSDocUnsafe $ ppr pattern) /= "[]" couldMatch (HsLit _ str@(HsString _ _)) (L _ (ConPatIn op (PrefixCon _))) = do let s = showSDocUnsafe $ ppr str case (showSDocUnsafe $ ppr op) of "[]" -> return (null s) _ -> return False couldMatch _ (L _ (ConPatIn op (PrefixCon _ ))) = do case (showSDocUnsafe $ ppr op) of "[]" -> return True _ -> return False couldMatch (ExplicitTuple _ contents _) (L _ (TuplePat _ pats _)) = do if ((length contents) /= (length pats)) then return False else do let matches = [(con, pat) | ((L _ (Present _ con)), pat) <- zip contents pats ] maps <- mapM (\((L _ expr),pattern) -> couldMatch expr pattern) matches return $ and maps couldMatch _ (L _ (WildPat _)) = return True couldMatch expr@(HsOverLit _ _) (L _ pat@(NPat _ _ _ _)) = do let exprstr = showSDocUnsafe $ ppr expr let patstr = showSDocUnsafe $ ppr pat return (exprstr == patstr) couldMatch expr@(HsLit _ _) (L _ pat@(NPat _ _ _ _)) = do let exprstr = showSDocUnsafe $ ppr expr let patstr = showSDocUnsafe $ ppr pat return (exprstr == patstr) couldMatch (HsLit _ _) _ = return False couldMatch (HsOverLit _ _) _ = return False couldMatch _ (L _ (NPat _ _ _ _)) = return True couldMatch expr (L _ (AsPat _ _ pat)) = couldMatch expr pat couldMatch expr@(HsVar _ _) pat = return ((showSDocUnsafe $ ppr expr) == (showSDocUnsafe $ ppr pat)) couldMatch exp _ = return True nameFromPatternComponent :: (LPat GhcPs) -> [String] nameFromPatternComponent (L _ (ConPatIn (L _ name) _)) = [occNameString $ rdrNameOcc name] Tuples nameFromPatternComponent (L _ (NPat _ _ _ _)) = [] nameFromPatternComponent (L _ (ListPat _ pats)) = concat $ map nameFromPatternComponent pats nameFromPatternComponent e = error $ "Unsupported type in pattern matching :" ++ (showSDocUnsafe $ ppr e)
345e1249d1dd1f298b37e97d1df489d4c6f21004a9ec66fb9f97b133ee29f9f6
bmeurer/ocaml-arm
stack.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ Id$ type 'a t = { mutable c : 'a list } exception Empty let create () = { c = [] } let clear s = s.c <- [] let copy s = { c = s.c } let push x s = s.c <- x :: s.c let pop s = match s.c with hd::tl -> s.c <- tl; hd | [] -> raise Empty let top s = match s.c with hd::_ -> hd | [] -> raise Empty let is_empty s = (s.c = []) let length s = List.length s.c let iter f s = List.iter f s.c
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/stdlib/stack.ml
ocaml
********************************************************************* OCaml the special exception on linking described in file ../LICENSE. *********************************************************************
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ Id$ type 'a t = { mutable c : 'a list } exception Empty let create () = { c = [] } let clear s = s.c <- [] let copy s = { c = s.c } let push x s = s.c <- x :: s.c let pop s = match s.c with hd::tl -> s.c <- tl; hd | [] -> raise Empty let top s = match s.c with hd::_ -> hd | [] -> raise Empty let is_empty s = (s.c = []) let length s = List.length s.c let iter f s = List.iter f s.c
72b8cf5046d7809b93e1286d5c937603ad0eeb0e6aef506cdf4c4268d0f5b2f1
ucsd-progsys/230-wi19-web
Expressions.hs
{-@ LIQUID "--reflection" @-} {-@ LIQUID "--ple" @-} {-@ LIQUID "--diff" @-} TODO : to have to rewrite this annotation ! # LANGUAGE PartialTypeSignatures # module Expressions where import Prelude hiding ((++), const, sum) import ProofCombinators import Lists import qualified State as S -------------------------------------------------------------------------------- -- | Arithmetic Expressions -------------------------------------------------------------------------------- type Vname = String data AExp = N Val | V Vname | Plus AExp AExp deriving (Show) type Val = Int type State = S.GState Vname Val {-@ reflect aval @-} aval :: AExp -> State -> Val aval (N n) _ = n aval (V x) s = S.get s x aval (Plus e1 e2) s = aval e1 s + aval e2 s -------------------------------------------------------------------------------- -- | Example Expressions -------------------------------------------------------------------------------- @ foog : : { v : Int | v = = 30 } @ foog :: Int foog = aval ex2 st1 where st1 :: State st1 = S.GState [] 10 12 ex0 = N 12 -- x + 9 ex1 = Plus (V "x") (N 9) -- x + y + z ex2 = Plus (V "x") (Plus (V "y") (V "z")) {- reflect state1 @-} -- state1 :: State state1 = S.GState [ ] 10 -------------------------------------------------------------------------------- -- | Constant Folding -------------------------------------------------------------------------------- {-@ reflect asimp_const @-} asimp_const :: AExp -> AExp asimp_const (N n) = N n asimp_const (V x) = V x asimp_const (Plus a1 a2) = case (asimp_const a1, asimp_const a2) of (N n1, N n2) -> N (n1 + n2) (b1 , b2) -> Plus b1 b2 {-@ lemma_aval_asimp_const :: a:_ -> s:_ -> { aval (asimp_const a) s = aval a s } @-} lemma_aval_asimp_const :: AExp -> State -> Proof lemma_aval_asimp_const (N _) _ = () lemma_aval_asimp_const (V _) _ = () lemma_aval_asimp_const (Plus a1 a2) s = case (asimp_const a1, asimp_const a2) of (N _, N _) -> lemma_aval_asimp_const a1 s &&& lemma_aval_asimp_const a2 s (_ , _) -> lemma_aval_asimp_const a1 s &&& lemma_aval_asimp_const a2 s -------------------------------------------------------------------------------- -- | Q: Why is the "case-of" important in the proof? -------------------------------------------------------------------------------- {-@ reflect silly @-} silly :: AExp -> Int silly (N _) = 0 silly (V _) = 0 silly (Plus a1 a2) = silly a1 + silly a2 {-@ lem_silly :: a:_ -> { silly a == 0 } @-} lem_silly :: AExp -> Proof lem_silly (N _) = () lem_silly (V _) = () lem_silly (Plus a1 a2) = lem_silly a1 &&& lem_silly a2 -------------------------------------------------------------------------------- -- | "Smart" Constructors -------------------------------------------------------------------------------- {-@ reflect plus @-} plus :: AExp -> AExp -> AExp plus (N i1) (N i2) = N (i1+i2) plus (N 0) a = a plus a (N 0) = a plus a1 a2 = Plus a1 a2 {-@ lemma_aval_plus :: a1:_ -> a2:_ -> s:_ -> { aval (plus a1 a2) s = aval (Plus a1 a2) s } @-} lemma_aval_plus :: AExp -> AExp -> State -> Proof lemma_aval_plus (N _) (N _) _ = () lemma_aval_plus (N 0) a _ = () lemma_aval_plus a (N 0) _ = () lemma_aval_plus a1 a2 _ = () -------------------------------------------------------------------------------- -- | Recursive simplification using "Smart" Constructors -------------------------------------------------------------------------------- @ reflect @ asimp :: AExp -> AExp asimp (Plus a1 a2) = plus (asimp a1) (asimp a2) asimp a = a {-@ lemma_aval_asimp :: a:_ -> s:_ -> { aval (asimp a) s = aval a s } @-} lemma_aval_asimp :: AExp -> State -> Proof lemma_aval_asimp (Plus a1 a2) s = lemma_aval_asimp a1 s &&& lemma_aval_asimp a2 s &&& lemma_aval_plus (asimp a1) (asimp a2) s lemma_aval_asimp _ _ = () -------------------------------------------------------------------------------- -- | Digression: Assignment -------------------------------------------------------------------------------- {- s x := a s' How will you relate value of some expression `e` in `s'` and `s`? -} {-@ reflect subst @-} subst :: Vname -> AExp -> AExp -> AExp subst x e (Plus a1 a2) = Plus (subst x e a1) (subst x e a2) subst x e (V y) | x == y = e subst _ _ a = a -------------------------------------------------------------------------------- -- | Boolean Expressions -------------------------------------------------------------------------------- data BExp = Bc Bool | Not BExp | And BExp BExp | Less AExp AExp deriving (Show) {-@ reflect bOr @-} bOr :: BExp -> BExp -> BExp bOr b1 b2 = Not ((Not b1) `And` (Not b2)) @ reflect @ bImp :: BExp -> BExp -> BExp bImp b1 b2 = bOr (Not b1) b2 {-@ reflect bval @-} bval :: BExp -> State -> Bool bval (Bc b) s = b bval (Not b) s = not (bval b s) bval (And b1 b2) s = bval b1 s && bval b2 s bval (Less a1 a2) s = aval a1 s < aval a2 s {-@ reflect bNot @-} bNot :: BExp -> BExp bNot (Bc True) = Bc False bNot (Bc False) = Bc True bNot b = Not b @ reflect bAnd @ bAnd :: BExp -> BExp -> BExp bAnd (Bc True) b = b bAnd b (Bc True) = b bAnd (Bc False) b = Bc False bAnd b (Bc False) = Bc False bAnd b1 b2 = And b1 b2 @ reflect bLess @ bLess :: AExp -> AExp -> BExp bLess (N n1) (N n2) = Bc (n1 < n2) bLess a1 a2 = Less a1 a2 @ reflect @ bsimp :: BExp -> BExp bsimp (Bc v) = Bc v bsimp (Not b) = bNot (bsimp b) bsimp (And b1 b2) = bAnd (bsimp b1) (bsimp b2) bsimp (Less a1 a2) = bLess (asimp a1) (asimp a2) -------------------------------------------------------------------------------- -- | Stack Machine -------------------------------------------------------------------------------- data Instr = LOADI Val | LOAD Vname | ADD deriving (Show) type Stack = [Val] @ reflect @ exec1 :: Instr -> State -> Stack -> Stack exec1 (LOADI n) _ stk = n : stk exec1 (LOAD x) s stk = (S.get s x) : stk exec1 ADD _ (j:i:stk) = (i+j) : stk exec1 _ _ _ = [] {-@ reflect exec @-} exec :: [Instr] -> State -> Stack -> Stack exec [] _ stk = stk exec (i:is) s stk = exec is s (exec1 i s stk) -------------------------------------------------------------------------------- | Compiling Arithmetic Expressions to a Stack Machine -------------------------------------------------------------------------------- {-@ reflect comp @-} comp :: AExp -> [Instr] comp (N n) = [LOADI n] comp (V x) = [LOAD x] comp (Plus a1 a2) = comp a1 ++ (comp a2 ++ [ADD]) {-@ lemma_comp :: a:_ -> s:_ -> stk:_ -> { exec (comp a) s stk = cons (aval a s) stk } @-} lemma_comp :: AExp -> State -> Stack -> Proof lemma_comp (N n) s stk = () lemma_comp (V x) s stk = () lemma_comp (Plus a1 a2) s stk = lemma_exec_append (comp a1) (comp a2 ++ [ADD]) s stk &&& lemma_exec_append (comp a2) [ADD] s stk1 &&& lemma_comp a1 s stk &&& lemma_comp a2 s stk1 where stk2 = exec (comp a2) s stk1 stk1 = exec (comp a1) s stk @ lemma_exec_append : : is1 : _ - > is2 : _ - > s : _ - > stk : _ - > { exec ( is1 + + is2 ) s stk = exec is2 s ( exec is1 s stk ) } @ { exec (is1 ++ is2) s stk = exec is2 s (exec is1 s stk) } @-} lemma_exec_append :: [Instr] -> [Instr] -> State -> Stack -> Proof lemma_exec_append [] _ _ _ = () lemma_exec_append (i1:is1) is2 s stk = lemma_exec_append is1 is2 s (exec1 i1 s stk)
null
https://raw.githubusercontent.com/ucsd-progsys/230-wi19-web/7f5fc5414886fae4e2382cd5a0e48f638be06f0f/src/Week4/Expressions.hs
haskell
@ LIQUID "--reflection" @ @ LIQUID "--ple" @ @ LIQUID "--diff" @ ------------------------------------------------------------------------------ | Arithmetic Expressions ------------------------------------------------------------------------------ @ reflect aval @ ------------------------------------------------------------------------------ | Example Expressions ------------------------------------------------------------------------------ x + 9 x + y + z reflect state1 @ state1 :: State ------------------------------------------------------------------------------ | Constant Folding ------------------------------------------------------------------------------ @ reflect asimp_const @ @ lemma_aval_asimp_const :: a:_ -> s:_ -> { aval (asimp_const a) s = aval a s } @ ------------------------------------------------------------------------------ | Q: Why is the "case-of" important in the proof? ------------------------------------------------------------------------------ @ reflect silly @ @ lem_silly :: a:_ -> { silly a == 0 } @ ------------------------------------------------------------------------------ | "Smart" Constructors ------------------------------------------------------------------------------ @ reflect plus @ @ lemma_aval_plus :: a1:_ -> a2:_ -> s:_ -> { aval (plus a1 a2) s = aval (Plus a1 a2) s } @ ------------------------------------------------------------------------------ | Recursive simplification using "Smart" Constructors ------------------------------------------------------------------------------ @ lemma_aval_asimp :: a:_ -> s:_ -> { aval (asimp a) s = aval a s } @ ------------------------------------------------------------------------------ | Digression: Assignment ------------------------------------------------------------------------------ s x := a s' How will you relate value of some expression `e` in `s'` and `s`? @ reflect subst @ ------------------------------------------------------------------------------ | Boolean Expressions ------------------------------------------------------------------------------ @ reflect bOr @ @ reflect bval @ @ reflect bNot @ ------------------------------------------------------------------------------ | Stack Machine ------------------------------------------------------------------------------ @ reflect exec @ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ @ reflect comp @ @ lemma_comp :: a:_ -> s:_ -> stk:_ -> { exec (comp a) s stk = cons (aval a s) stk } @
TODO : to have to rewrite this annotation ! # LANGUAGE PartialTypeSignatures # module Expressions where import Prelude hiding ((++), const, sum) import ProofCombinators import Lists import qualified State as S type Vname = String data AExp = N Val | V Vname | Plus AExp AExp deriving (Show) type Val = Int type State = S.GState Vname Val aval :: AExp -> State -> Val aval (N n) _ = n aval (V x) s = S.get s x aval (Plus e1 e2) s = aval e1 s + aval e2 s @ foog : : { v : Int | v = = 30 } @ foog :: Int foog = aval ex2 st1 where st1 :: State st1 = S.GState [] 10 12 ex0 = N 12 ex1 = Plus (V "x") (N 9) ex2 = Plus (V "x") (Plus (V "y") (V "z")) state1 = S.GState [ ] 10 asimp_const :: AExp -> AExp asimp_const (N n) = N n asimp_const (V x) = V x asimp_const (Plus a1 a2) = case (asimp_const a1, asimp_const a2) of (N n1, N n2) -> N (n1 + n2) (b1 , b2) -> Plus b1 b2 lemma_aval_asimp_const :: AExp -> State -> Proof lemma_aval_asimp_const (N _) _ = () lemma_aval_asimp_const (V _) _ = () lemma_aval_asimp_const (Plus a1 a2) s = case (asimp_const a1, asimp_const a2) of (N _, N _) -> lemma_aval_asimp_const a1 s &&& lemma_aval_asimp_const a2 s (_ , _) -> lemma_aval_asimp_const a1 s &&& lemma_aval_asimp_const a2 s silly :: AExp -> Int silly (N _) = 0 silly (V _) = 0 silly (Plus a1 a2) = silly a1 + silly a2 lem_silly :: AExp -> Proof lem_silly (N _) = () lem_silly (V _) = () lem_silly (Plus a1 a2) = lem_silly a1 &&& lem_silly a2 plus :: AExp -> AExp -> AExp plus (N i1) (N i2) = N (i1+i2) plus (N 0) a = a plus a (N 0) = a plus a1 a2 = Plus a1 a2 lemma_aval_plus :: AExp -> AExp -> State -> Proof lemma_aval_plus (N _) (N _) _ = () lemma_aval_plus (N 0) a _ = () lemma_aval_plus a (N 0) _ = () lemma_aval_plus a1 a2 _ = () @ reflect @ asimp :: AExp -> AExp asimp (Plus a1 a2) = plus (asimp a1) (asimp a2) asimp a = a lemma_aval_asimp :: AExp -> State -> Proof lemma_aval_asimp (Plus a1 a2) s = lemma_aval_asimp a1 s &&& lemma_aval_asimp a2 s &&& lemma_aval_plus (asimp a1) (asimp a2) s lemma_aval_asimp _ _ = () subst :: Vname -> AExp -> AExp -> AExp subst x e (Plus a1 a2) = Plus (subst x e a1) (subst x e a2) subst x e (V y) | x == y = e subst _ _ a = a data BExp = Bc Bool | Not BExp | And BExp BExp | Less AExp AExp deriving (Show) bOr :: BExp -> BExp -> BExp bOr b1 b2 = Not ((Not b1) `And` (Not b2)) @ reflect @ bImp :: BExp -> BExp -> BExp bImp b1 b2 = bOr (Not b1) b2 bval :: BExp -> State -> Bool bval (Bc b) s = b bval (Not b) s = not (bval b s) bval (And b1 b2) s = bval b1 s && bval b2 s bval (Less a1 a2) s = aval a1 s < aval a2 s bNot :: BExp -> BExp bNot (Bc True) = Bc False bNot (Bc False) = Bc True bNot b = Not b @ reflect bAnd @ bAnd :: BExp -> BExp -> BExp bAnd (Bc True) b = b bAnd b (Bc True) = b bAnd (Bc False) b = Bc False bAnd b (Bc False) = Bc False bAnd b1 b2 = And b1 b2 @ reflect bLess @ bLess :: AExp -> AExp -> BExp bLess (N n1) (N n2) = Bc (n1 < n2) bLess a1 a2 = Less a1 a2 @ reflect @ bsimp :: BExp -> BExp bsimp (Bc v) = Bc v bsimp (Not b) = bNot (bsimp b) bsimp (And b1 b2) = bAnd (bsimp b1) (bsimp b2) bsimp (Less a1 a2) = bLess (asimp a1) (asimp a2) data Instr = LOADI Val | LOAD Vname | ADD deriving (Show) type Stack = [Val] @ reflect @ exec1 :: Instr -> State -> Stack -> Stack exec1 (LOADI n) _ stk = n : stk exec1 (LOAD x) s stk = (S.get s x) : stk exec1 ADD _ (j:i:stk) = (i+j) : stk exec1 _ _ _ = [] exec :: [Instr] -> State -> Stack -> Stack exec [] _ stk = stk exec (i:is) s stk = exec is s (exec1 i s stk) | Compiling Arithmetic Expressions to a Stack Machine comp :: AExp -> [Instr] comp (N n) = [LOADI n] comp (V x) = [LOAD x] comp (Plus a1 a2) = comp a1 ++ (comp a2 ++ [ADD]) lemma_comp :: AExp -> State -> Stack -> Proof lemma_comp (N n) s stk = () lemma_comp (V x) s stk = () lemma_comp (Plus a1 a2) s stk = lemma_exec_append (comp a1) (comp a2 ++ [ADD]) s stk &&& lemma_exec_append (comp a2) [ADD] s stk1 &&& lemma_comp a1 s stk &&& lemma_comp a2 s stk1 where stk2 = exec (comp a2) s stk1 stk1 = exec (comp a1) s stk @ lemma_exec_append : : is1 : _ - > is2 : _ - > s : _ - > stk : _ - > { exec ( is1 + + is2 ) s stk = exec is2 s ( exec is1 s stk ) } @ { exec (is1 ++ is2) s stk = exec is2 s (exec is1 s stk) } @-} lemma_exec_append :: [Instr] -> [Instr] -> State -> Stack -> Proof lemma_exec_append [] _ _ _ = () lemma_exec_append (i1:is1) is2 s stk = lemma_exec_append is1 is2 s (exec1 i1 s stk)
f8d302f82b0ff57c989182891cb6be900ebe46ae0839b1c0b984433bda5563e6
rizo/streams-bench
Pull_option.ml
type 'a t = unit -> 'a option let singleton x = let first = ref true in fun () -> if !first then ( first := false; Some x) else None let count () = let i = ref 0 in fun () -> let x = !i in incr i; Some x let init n f = let i = ref 0 in fun () -> if !i = n then None else begin let x = !i in incr i; Some (f x) end let unfold seed next = let seed = ref seed in fun () -> match next !seed with | None -> None | Some (a, seed') -> seed := seed'; Some a let of_list l = let l = ref l in fun () -> match !l with | [] -> None | x :: l' -> l := l'; Some x let map f gen = let stop = ref false in fun () -> if !stop then None else match gen () with | None -> stop := true; None | Some x -> Some (f x) let filter p gen = let rec next () = (* wrap exception into option, for next to be tailrec *) match gen () with | None -> None | Some x as res -> if p x then res (* yield element *) else next () (* discard element *) in next let take n gen = let count = ref 0 in fun () -> if !count = n || !count = ~-1 then None else match gen () with | None -> count := ~-1; None (* indicate stop *) | Some _ as x -> incr count; x let rec fold f acc gen = match gen () with | None -> acc | Some x -> fold f (f acc x) gen type 'a state = Start | Cur of 'a | Stop let flat_map f g = let state = ref Start in let rec aux () = match !state with | Start -> next_gen (); aux () | Stop -> None | Cur g' -> ( match g' () with | None -> next_gen (); aux () | Some _ as res -> res) and next_gen () = match g () with | None -> state := Stop | Some x -> state := Cur (f x) | exception e -> state := Stop; raise e in aux let ( -- ) i j = unfold i (fun x -> if x = j then None else Some (x, x + 1))
null
https://raw.githubusercontent.com/rizo/streams-bench/87baf838971c84613b801ab32b6473d397bcc23f/src/Pull_option.ml
ocaml
wrap exception into option, for next to be tailrec yield element discard element indicate stop
type 'a t = unit -> 'a option let singleton x = let first = ref true in fun () -> if !first then ( first := false; Some x) else None let count () = let i = ref 0 in fun () -> let x = !i in incr i; Some x let init n f = let i = ref 0 in fun () -> if !i = n then None else begin let x = !i in incr i; Some (f x) end let unfold seed next = let seed = ref seed in fun () -> match next !seed with | None -> None | Some (a, seed') -> seed := seed'; Some a let of_list l = let l = ref l in fun () -> match !l with | [] -> None | x :: l' -> l := l'; Some x let map f gen = let stop = ref false in fun () -> if !stop then None else match gen () with | None -> stop := true; None | Some x -> Some (f x) let filter p gen = let rec next () = match gen () with | None -> None | Some x as res -> in next let take n gen = let count = ref 0 in fun () -> if !count = n || !count = ~-1 then None else match gen () with | None -> count := ~-1; | Some _ as x -> incr count; x let rec fold f acc gen = match gen () with | None -> acc | Some x -> fold f (f acc x) gen type 'a state = Start | Cur of 'a | Stop let flat_map f g = let state = ref Start in let rec aux () = match !state with | Start -> next_gen (); aux () | Stop -> None | Cur g' -> ( match g' () with | None -> next_gen (); aux () | Some _ as res -> res) and next_gen () = match g () with | None -> state := Stop | Some x -> state := Cur (f x) | exception e -> state := Stop; raise e in aux let ( -- ) i j = unfold i (fun x -> if x = j then None else Some (x, x + 1))
5cbe5b502c90385c63e5ae809bdf2c246db01a7bcfd756ff85a730f128abe894
freetonik/degas
individual.cljs
(ns degas.individual (:require [clojure.string :as str])) (defn rand-ind [length max] "Returns a vector, an individual of given length with random elements up to u-max each." (apply vector (repeatedly length #(rand-int max)))) (defn rand-unique-ind [length] "Returns a vector of ints from 0 to length, shuffled." (shuffle (range length))) (defn decode [decode-fn ind] "Returns a string consistings of decode-fn applied to each element of ind seq." (str/join "" (map decode-fn ind)))
null
https://raw.githubusercontent.com/freetonik/degas/ca98e9557e35487bee4d012518bdcaac14a327ba/src/degas/individual.cljs
clojure
(ns degas.individual (:require [clojure.string :as str])) (defn rand-ind [length max] "Returns a vector, an individual of given length with random elements up to u-max each." (apply vector (repeatedly length #(rand-int max)))) (defn rand-unique-ind [length] "Returns a vector of ints from 0 to length, shuffled." (shuffle (range length))) (defn decode [decode-fn ind] "Returns a string consistings of decode-fn applied to each element of ind seq." (str/join "" (map decode-fn ind)))
14437f597a0289d16e375cf68b1fef27543f083ea462e17996bfc80fc18355f4
RunOrg/RunOrg
logReq.ml
(* © 2014 RunOrg *) open Run let enabled = match Configuration.Log.httpd with | `None -> false | `Trace | `Debug -> true (* Context management ================== *) type t = { id : int ; mutable time : float ; } class type ctx = object ('self) method logreq : t end let id = ref 0 class log_ctx = object val log = { id = (incr id ; !id) ; time = Unix.gettimeofday () } method logreq = log end let start inner = Run.with_context (new log_ctx :> ctx) inner let set_request_ip str = if enabled then let! ctx = Run.context in let log = ctx # logreq in let () = Log.trace "%04x =========== %s" log.id str in return () else return () let set_request_path str = if enabled then let! ctx = Run.context in let log = ctx # logreq in let () = Log.trace "%04x ----------- %s" log.id str in return () else return () (* Printing out ============ *) let trace = if enabled then fun str -> let! ctx = Run.context in let log = ctx # logreq in let time = Unix.gettimeofday () in let () = Log.trace "%04x : %4d ms : %s" log.id (int_of_float (1000. *. (time -. log.time))) str in let () = log.time <- time in return () else fun _ -> return () For let tracef fmt = if enabled then let buffer = Buffer.create 100 in Format.kfprintf (fun _ -> trace (Buffer.contents buffer)) (Format.formatter_of_buffer buffer) fmt else Format.ikfprintf (fun _ -> return ()) formatter fmt
null
https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/logReq.ml
ocaml
© 2014 RunOrg Context management ================== Printing out ============
open Run let enabled = match Configuration.Log.httpd with | `None -> false | `Trace | `Debug -> true type t = { id : int ; mutable time : float ; } class type ctx = object ('self) method logreq : t end let id = ref 0 class log_ctx = object val log = { id = (incr id ; !id) ; time = Unix.gettimeofday () } method logreq = log end let start inner = Run.with_context (new log_ctx :> ctx) inner let set_request_ip str = if enabled then let! ctx = Run.context in let log = ctx # logreq in let () = Log.trace "%04x =========== %s" log.id str in return () else return () let set_request_path str = if enabled then let! ctx = Run.context in let log = ctx # logreq in let () = Log.trace "%04x ----------- %s" log.id str in return () else return () let trace = if enabled then fun str -> let! ctx = Run.context in let log = ctx # logreq in let time = Unix.gettimeofday () in let () = Log.trace "%04x : %4d ms : %s" log.id (int_of_float (1000. *. (time -. log.time))) str in let () = log.time <- time in return () else fun _ -> return () For let tracef fmt = if enabled then let buffer = Buffer.create 100 in Format.kfprintf (fun _ -> trace (Buffer.contents buffer)) (Format.formatter_of_buffer buffer) fmt else Format.ikfprintf (fun _ -> return ()) formatter fmt
3eb555a1ddd878f2c619f7c1fc85d97a213dfd5972e34d945b9c4862cb9c0c23
amuletml/amulet
Uncurry.hs
# LANGUAGE FlexibleContexts , ScopedTypeVariables # | The unboxing pass attempts to convert curried functions which take multiple arguments to uncurried functions taking unboxed tuples . This is performed through a worker / wrapper transformation . We create a worker function which takes its arguments as an unboxed tuple , which contains the original method 's body . We then replace the original function with a wrapper , which takes curried arguments ( and so has the original type signature ) . The idea here is that we do not need to perform complex changes to the rest of the code : we instead allow the inliner to handle the ( relatively ) simple wrappers as appropriate . = = Example = = = Before > let f = ᴧ a. λ x. λ y. λ = = = After > ( * Worker * ) > let f1 = ᴧ a. λ t1 . > match b with ( # x , y , z # ) - > > EXPR > ( * Wrapper * ) > let f = ᴧ a1 . λ x1 . λ y1 . λ z1 . > let t2 = f1 { a1 } > let t3 = ( # x1 , y1 , z1 # ) > t2 t3 multiple arguments to uncurried functions taking unboxed tuples. This is performed through a worker/wrapper transformation. We create a worker function which takes its arguments as an unboxed tuple, which contains the original method's body. We then replace the original function with a wrapper, which takes curried arguments (and so has the original type signature). The idea here is that we do not need to perform complex changes to the rest of the code: we instead allow the inliner to handle the (relatively) simple wrappers as appropriate. == Example === Before > let f = ᴧ a. λ x. λ y. λ z. EXPR === After > (* Worker *) > let f1 = ᴧ a. λ t1. > match b with (# x, y, z #) -> > EXPR > (* Wrapper *) > let f = ᴧ a1. λ x1. λ y1. λ z1. > let t2 = f1 {a1} > let t3 = (# x1, y1, z1 #) > t2 t3 -} module Core.Optimise.Uncurry (uncurryPass) where import Control.Monad.Namey import Control.Lens ((%%~)) import Control.Arrow import qualified Data.VarMap as VarMap import Data.Sequence ((|>), Seq(..)) import qualified Data.Sequence as Seq import Data.Foldable import Data.Triple import Core.Optimise type Bind = (CoVar, Type, Term CoVar) -- | Runs the uncurry pass on the provided statements. -- -- We need a fresh source of variables for workers and temporary variables , hence the ' ' . uncurryPass :: forall m. MonadNamey m => [Stmt CoVar] -> m [Stmt CoVar] uncurryPass = transS where transS [] = pure [] transS (StmtLet (One var):ss) = do var' <- third3A transT var wvar' <- buildBind var' case wvar' of Nothing -> (StmtLet (One var'):) <$> transS ss Just (worker, wrapper) -> do ss' <- transS ss pure (StmtLet (One worker) : StmtLet (One wrapper) : ss') -- Nested lets transS (StmtLet (Many vs):ss) = do vs' <- buildBinds vs ss' <- transS ss pure (StmtLet (Many vs'):ss') transS (s:ss) = (s:) <$> transS ss -- Trivial terms transT t@Atom{} = pure t transT t@App{} = pure t transT t@TyApp{} = pure t transT t@Cast{} = pure t transT t@Extend{} = pure t transT t@Values{} = pure t -- Nested terms transT (Match t bs) = Match t <$> traverse (armBody %%~ transT) bs transT (Lam arg b) = Lam arg <$> transT b -- Trivial lets transT (Let (One var) r) = do var' <- third3A transT var wvar' <- buildBind var' case wvar' of Nothing -> Let (One var') <$> transT r Just (worker, wrapper) -> Let (One worker) . Let (One wrapper) <$> transT r -- Nested lets transT (Let (Many vs) r) = do vs' <- buildBinds vs Let (Many vs') <$> transT r buildBinds :: [Bind] -> m [Bind] buildBinds binds = do (binds', extras) <- unzip <$> traverse go binds pure (mconcat (binds':extras)) where go b = maybe (b, []) (second pure) <$> buildBind b buildBind :: Bind -> m (Maybe (Bind, Bind)) buildBind (wrapVar, wrapTy, workTerm) | isInteresting 0 workTerm = do workVar <- freshFrom wrapVar (workTy, workTerm', wrapTerm) <- buildBoxedWrapper workVar wrapTy workTerm pure (Just ((workVar, workTy, workTerm'), (wrapVar, wrapTy, wrapTerm))) | otherwise = pure Nothing -- ^ Build a boxed wrapper for some worker function. buildBoxedWrapper :: forall m. MonadNamey m => CoVar -- ^ The worker's variable -> Type -- ^ The wrapper's variable -> Term CoVar -- ^ The original worker's definition -> m (Type, Term CoVar, Term CoVar) -- ^ The worker's type and definition, plus the wrapper's definition. buildBoxedWrapper = buildWrapper mempty mempty id mempty mempty mempty id where buildWrapper :: Seq (CoVar, Type) -- ^ The type arguments of the worker function -> Seq (CoVar, Type) -- ^ The value arguments of the worker function -> (Term CoVar -> Term CoVar) -- ^ The builder for the worker's body. Used for packing tuples. -> VarMap.Map Type -- ^ A set of type variable substitutions to make -> Seq (CoVar, Type) -- ^ The type arguments to be applied to the worker function within the wrapper -> Seq (CoVar, Type) -- ^ The value arguments to be applied to the worker function within the wrapper -> (Term CoVar -> Term CoVar) -- ^ The builder for the wrapper's body. Used for unpacking tuples. -> CoVar -> Type -> Term CoVar -- ^ The existing worker var/type/term -> m (Type, Term CoVar, Term CoVar) -- ^ The type and term of the worker, and the wrapper's term buildWrapper wkTAs wkVAs wkBuild wrSub wrTAs wrVAs wrBuild bVar bType bTerm = case (bType, bTerm) of -- Type lambdas are nice and simple: we just add a type application -- and wrap the wrapper in a lambda. (ForallTy (Relevant _) _ rType, Lam (TypeArgument v ty) rTerm) -> do v' <- freshFrom v let ty' = substituteInType wrSub ty (workTy, workTerm, wrapTerm) <- buildWrapper (wkTAs |> (v, ty)) wkVAs wkBuild (VarMap.insert v (VarTy v') wrSub) (wrTAs |> (v',ty')) wrVAs wrBuild bVar rType rTerm pure ( workTy, workTerm , Lam (TypeArgument v' ty') wrapTerm ) -- Term lambdas with unboxed tuples are the complex one: we need to -- flatten the tuples, and then repack them for the original -- function. (ForallTy Irrelevant _ rType, Lam (TermArgument v (ValuesTy tys)) rTerm) -> do v' <- freshFrom v vs <- traverse (const (fresh' ValueVar)) tys vs' <- traverse (const (fresh' ValueVar)) tys let tys' = map (substituteInType wrSub) tys let wkPack = Let (One (v, ValuesTy tys, Values (zipWith Ref vs tys))) let wrUnpack b = Match (Ref v' (ValuesTy tys')) [ Arm { _armPtrn = PatValues (zipWith Capture vs' tys') , _armTy = ValuesTy tys' , _armBody = b , _armVars = zip vs' tys' , _armTyvars = [] } ] (workTy, workTerm, wrapTerm) <- buildWrapper wkTAs (wkVAs <> Seq.fromList (zip vs tys)) (wrUnpack . wkBuild) wrSub wrTAs (wrVAs <> Seq.fromList (zip vs' tys')) (wkPack . wrBuild) bVar rType rTerm pure ( workTy, workTerm , Lam (TermArgument v' (ValuesTy tys')) wrapTerm ) -- Basic term lambdas are also simple: add the variables and wrap -- it up in a lambda. (ForallTy Irrelevant _ rType, Lam (TermArgument v ty) rTerm) -> do v' <- freshFrom v let ty' = substituteInType wrSub ty (workTy, workTerm, wrapTerm) <- buildWrapper wkTAs (wkVAs |> (v, ty)) wkBuild wrSub wrTAs (wrVAs |> (v', ty')) wrBuild bVar rType rTerm pure ( workTy, workTerm , Lam (TermArgument v' ty') wrapTerm ) (_, _) -> do argVar <- fresh ValueVar let wkVAs' = toList wkVAs argTy = ValuesTy (map snd wkVAs') wkBody = Match (Ref argVar argTy) [ Arm { _armPtrn = PatValues (map (uncurry Capture) wkVAs') , _armTy = argTy , _armBody = wrBuild bTerm , _armVars = wkVAs' , _armTyvars = [] } ] wkLam = foldr (Lam . uncurry TypeArgument) (Lam (TermArgument argVar argTy) wkBody) wkTAs generate ((v, ty) :<| vs) ref = do bindVar <- fresh' ValueVar (bod, bindTy) <- generate vs bindVar let refTy = ForallTy (Relevant v) ty bindTy pure ( Let (One (bindVar, bindTy, TyApp (Ref ref refTy) (VarTy v))) bod , refTy ) generate Empty ref = do tupVar <- fresh' ValueVar let tupTy = ValuesTy (map snd (toList wrVAs)) refTy = ForallTy Irrelevant tupTy (substituteInType wrSub bType) pure ( Let (One ( tupVar , argTy , Values (map (uncurry Ref) (toList wrVAs)) )) (App (Ref ref refTy) (Ref tupVar tupTy)) , refTy ) (wrBody, wkTy) <- first wrBuild <$> generate wrTAs bVar pure (wkTy, wkLam, wrBody) | Determine if a term has 2 or more variable lambdas and the body is -- contains something other than a chain of applications. isInteresting :: Int -> Term CoVar -> Bool isInteresting n (Lam TypeArgument{} b) = isInteresting n b isInteresting n (Lam TermArgument{} b) = isInteresting (n + 1) b isInteresting n body = n >= 2 && not (isWorker Nothing Nothing body) -- | A vague heuristic to determine if something is a worker -- function. -- -- Note this is not complete: we'd rather duplicate worker functions -- than skip potential optimisation opportunities. isWorker :: Maybe CoVar -> Maybe CoVar -> Term CoVar -> Bool -- If we're a type application then we must be applying to the previous -- function. isWorker p a (Let (One (v, _, TyApp (Ref f _) _)) body) | maybe True (==f) p = isWorker (Just v) a body -- If we're packing values, ensure it's the only one and mark that as -- the required argument. isWorker p Nothing (Let (One (v, _, Values _)) body) = isWorker p (Just v) body -- Skip unpacking values isWorker p a (Match _ [Arm { _armPtrn = PatValues{}, _armBody = body }]) = isWorker p a body -- The application must be the last expression, applying the previous -- tyapp with and unboxed tuple isWorker p (Just a) (App (Ref f _) (Ref x _)) = maybe True (==f) p && x == a -- If we hit anything else, assume we're not a worker. isWorker _ _ _ = False
null
https://raw.githubusercontent.com/amuletml/amulet/fcba0b7e198b8d354e95722bbe118bccc8483f4e/src/Core/Optimise/Uncurry.hs
haskell
| Runs the uncurry pass on the provided statements. We need a fresh source of variables for workers and temporary Nested lets Trivial terms Nested terms Trivial lets Nested lets ^ Build a boxed wrapper for some worker function. ^ The worker's variable ^ The wrapper's variable ^ The original worker's definition ^ The worker's type and definition, plus the wrapper's definition. ^ The type arguments of the worker function ^ The value arguments of the worker function ^ The builder for the worker's body. Used for packing tuples. ^ A set of type variable substitutions to make ^ The type arguments to be applied to the worker function within the wrapper ^ The value arguments to be applied to the worker function within the wrapper ^ The builder for the wrapper's body. Used for unpacking tuples. ^ The existing worker var/type/term ^ The type and term of the worker, and the wrapper's term Type lambdas are nice and simple: we just add a type application and wrap the wrapper in a lambda. Term lambdas with unboxed tuples are the complex one: we need to flatten the tuples, and then repack them for the original function. Basic term lambdas are also simple: add the variables and wrap it up in a lambda. contains something other than a chain of applications. | A vague heuristic to determine if something is a worker function. Note this is not complete: we'd rather duplicate worker functions than skip potential optimisation opportunities. If we're a type application then we must be applying to the previous function. If we're packing values, ensure it's the only one and mark that as the required argument. Skip unpacking values The application must be the last expression, applying the previous tyapp with and unboxed tuple If we hit anything else, assume we're not a worker.
# LANGUAGE FlexibleContexts , ScopedTypeVariables # | The unboxing pass attempts to convert curried functions which take multiple arguments to uncurried functions taking unboxed tuples . This is performed through a worker / wrapper transformation . We create a worker function which takes its arguments as an unboxed tuple , which contains the original method 's body . We then replace the original function with a wrapper , which takes curried arguments ( and so has the original type signature ) . The idea here is that we do not need to perform complex changes to the rest of the code : we instead allow the inliner to handle the ( relatively ) simple wrappers as appropriate . = = Example = = = Before > let f = ᴧ a. λ x. λ y. λ = = = After > ( * Worker * ) > let f1 = ᴧ a. λ t1 . > match b with ( # x , y , z # ) - > > EXPR > ( * Wrapper * ) > let f = ᴧ a1 . λ x1 . λ y1 . λ z1 . > let t2 = f1 { a1 } > let t3 = ( # x1 , y1 , z1 # ) > t2 t3 multiple arguments to uncurried functions taking unboxed tuples. This is performed through a worker/wrapper transformation. We create a worker function which takes its arguments as an unboxed tuple, which contains the original method's body. We then replace the original function with a wrapper, which takes curried arguments (and so has the original type signature). The idea here is that we do not need to perform complex changes to the rest of the code: we instead allow the inliner to handle the (relatively) simple wrappers as appropriate. == Example === Before > let f = ᴧ a. λ x. λ y. λ z. EXPR === After > (* Worker *) > let f1 = ᴧ a. λ t1. > match b with (# x, y, z #) -> > EXPR > (* Wrapper *) > let f = ᴧ a1. λ x1. λ y1. λ z1. > let t2 = f1 {a1} > let t3 = (# x1, y1, z1 #) > t2 t3 -} module Core.Optimise.Uncurry (uncurryPass) where import Control.Monad.Namey import Control.Lens ((%%~)) import Control.Arrow import qualified Data.VarMap as VarMap import Data.Sequence ((|>), Seq(..)) import qualified Data.Sequence as Seq import Data.Foldable import Data.Triple import Core.Optimise type Bind = (CoVar, Type, Term CoVar) variables , hence the ' ' . uncurryPass :: forall m. MonadNamey m => [Stmt CoVar] -> m [Stmt CoVar] uncurryPass = transS where transS [] = pure [] transS (StmtLet (One var):ss) = do var' <- third3A transT var wvar' <- buildBind var' case wvar' of Nothing -> (StmtLet (One var'):) <$> transS ss Just (worker, wrapper) -> do ss' <- transS ss pure (StmtLet (One worker) : StmtLet (One wrapper) : ss') transS (StmtLet (Many vs):ss) = do vs' <- buildBinds vs ss' <- transS ss pure (StmtLet (Many vs'):ss') transS (s:ss) = (s:) <$> transS ss transT t@Atom{} = pure t transT t@App{} = pure t transT t@TyApp{} = pure t transT t@Cast{} = pure t transT t@Extend{} = pure t transT t@Values{} = pure t transT (Match t bs) = Match t <$> traverse (armBody %%~ transT) bs transT (Lam arg b) = Lam arg <$> transT b transT (Let (One var) r) = do var' <- third3A transT var wvar' <- buildBind var' case wvar' of Nothing -> Let (One var') <$> transT r Just (worker, wrapper) -> Let (One worker) . Let (One wrapper) <$> transT r transT (Let (Many vs) r) = do vs' <- buildBinds vs Let (Many vs') <$> transT r buildBinds :: [Bind] -> m [Bind] buildBinds binds = do (binds', extras) <- unzip <$> traverse go binds pure (mconcat (binds':extras)) where go b = maybe (b, []) (second pure) <$> buildBind b buildBind :: Bind -> m (Maybe (Bind, Bind)) buildBind (wrapVar, wrapTy, workTerm) | isInteresting 0 workTerm = do workVar <- freshFrom wrapVar (workTy, workTerm', wrapTerm) <- buildBoxedWrapper workVar wrapTy workTerm pure (Just ((workVar, workTy, workTerm'), (wrapVar, wrapTy, wrapTerm))) | otherwise = pure Nothing buildBoxedWrapper :: forall m. MonadNamey m -> m (Type, Term CoVar, Term CoVar) buildBoxedWrapper = buildWrapper mempty mempty id mempty mempty mempty id where -> Seq (CoVar, Type) -> Seq (CoVar, Type) buildWrapper wkTAs wkVAs wkBuild wrSub wrTAs wrVAs wrBuild bVar bType bTerm = case (bType, bTerm) of (ForallTy (Relevant _) _ rType, Lam (TypeArgument v ty) rTerm) -> do v' <- freshFrom v let ty' = substituteInType wrSub ty (workTy, workTerm, wrapTerm) <- buildWrapper (wkTAs |> (v, ty)) wkVAs wkBuild (VarMap.insert v (VarTy v') wrSub) (wrTAs |> (v',ty')) wrVAs wrBuild bVar rType rTerm pure ( workTy, workTerm , Lam (TypeArgument v' ty') wrapTerm ) (ForallTy Irrelevant _ rType, Lam (TermArgument v (ValuesTy tys)) rTerm) -> do v' <- freshFrom v vs <- traverse (const (fresh' ValueVar)) tys vs' <- traverse (const (fresh' ValueVar)) tys let tys' = map (substituteInType wrSub) tys let wkPack = Let (One (v, ValuesTy tys, Values (zipWith Ref vs tys))) let wrUnpack b = Match (Ref v' (ValuesTy tys')) [ Arm { _armPtrn = PatValues (zipWith Capture vs' tys') , _armTy = ValuesTy tys' , _armBody = b , _armVars = zip vs' tys' , _armTyvars = [] } ] (workTy, workTerm, wrapTerm) <- buildWrapper wkTAs (wkVAs <> Seq.fromList (zip vs tys)) (wrUnpack . wkBuild) wrSub wrTAs (wrVAs <> Seq.fromList (zip vs' tys')) (wkPack . wrBuild) bVar rType rTerm pure ( workTy, workTerm , Lam (TermArgument v' (ValuesTy tys')) wrapTerm ) (ForallTy Irrelevant _ rType, Lam (TermArgument v ty) rTerm) -> do v' <- freshFrom v let ty' = substituteInType wrSub ty (workTy, workTerm, wrapTerm) <- buildWrapper wkTAs (wkVAs |> (v, ty)) wkBuild wrSub wrTAs (wrVAs |> (v', ty')) wrBuild bVar rType rTerm pure ( workTy, workTerm , Lam (TermArgument v' ty') wrapTerm ) (_, _) -> do argVar <- fresh ValueVar let wkVAs' = toList wkVAs argTy = ValuesTy (map snd wkVAs') wkBody = Match (Ref argVar argTy) [ Arm { _armPtrn = PatValues (map (uncurry Capture) wkVAs') , _armTy = argTy , _armBody = wrBuild bTerm , _armVars = wkVAs' , _armTyvars = [] } ] wkLam = foldr (Lam . uncurry TypeArgument) (Lam (TermArgument argVar argTy) wkBody) wkTAs generate ((v, ty) :<| vs) ref = do bindVar <- fresh' ValueVar (bod, bindTy) <- generate vs bindVar let refTy = ForallTy (Relevant v) ty bindTy pure ( Let (One (bindVar, bindTy, TyApp (Ref ref refTy) (VarTy v))) bod , refTy ) generate Empty ref = do tupVar <- fresh' ValueVar let tupTy = ValuesTy (map snd (toList wrVAs)) refTy = ForallTy Irrelevant tupTy (substituteInType wrSub bType) pure ( Let (One ( tupVar , argTy , Values (map (uncurry Ref) (toList wrVAs)) )) (App (Ref ref refTy) (Ref tupVar tupTy)) , refTy ) (wrBody, wkTy) <- first wrBuild <$> generate wrTAs bVar pure (wkTy, wkLam, wrBody) | Determine if a term has 2 or more variable lambdas and the body is isInteresting :: Int -> Term CoVar -> Bool isInteresting n (Lam TypeArgument{} b) = isInteresting n b isInteresting n (Lam TermArgument{} b) = isInteresting (n + 1) b isInteresting n body = n >= 2 && not (isWorker Nothing Nothing body) isWorker :: Maybe CoVar -> Maybe CoVar -> Term CoVar -> Bool isWorker p a (Let (One (v, _, TyApp (Ref f _) _)) body) | maybe True (==f) p = isWorker (Just v) a body isWorker p Nothing (Let (One (v, _, Values _)) body) = isWorker p (Just v) body isWorker p a (Match _ [Arm { _armPtrn = PatValues{}, _armBody = body }]) = isWorker p a body isWorker p (Just a) (App (Ref f _) (Ref x _)) = maybe True (==f) p && x == a isWorker _ _ _ = False
f723a932535b341834eec8daa7442e7dd7c181ff2a051d015d56748a7124d230
roelvandijk/containers-unicode-symbols
Unicode.hs
# LANGUAGE NoImplicitPrelude , UnicodeSyntax # | Module : Data . Sequence . Unicode Copyright : 2009–2012 : BSD3 ( see the file LICENSE ) Maintainer : < > Module : Data.Sequence.Unicode Copyright : 2009–2012 Roel van Dijk License : BSD3 (see the file LICENSE) Maintainer : Roel van Dijk <> -} module Data.Sequence.Unicode ( (∅) , (⊲), (⊳) , (⋈) ) where ------------------------------------------------------------------------------- -- Imports ------------------------------------------------------------------------------- -- from containers: import Data.Sequence ( Seq , empty , (<|), (|>) , (><) ) ------------------------------------------------------------------------------- -- Fixities ------------------------------------------------------------------------------- infixr 5 ⋈ infixr 5 ⊲ infixl 5 ⊳ ------------------------------------------------------------------------------- -- Symbols ------------------------------------------------------------------------------- {-| (&#x2205;) = 'empty' U+2205, EMPTY SET -} (∅) ∷ Seq α (∅) = empty {-# INLINE (∅) #-} {-| (&#x22B2;) = ('<|') U+22B2, NORMAL SUBGROUP OF -} (⊲) ∷ α → Seq α → Seq α (⊲) = (<|) {-# INLINE (⊲) #-} | ( & # x22B3 ;) = ( ' | > ' ) U+22B3 , CONTAINS AS NORMAL SUBGROUP (&#x22B3;) = ('|>') U+22B3, CONTAINS AS NORMAL SUBGROUP -} (⊳) ∷ Seq α → α → Seq α (⊳) = (|>) {-# INLINE (⊳) #-} | ( & # x22C8 ;) = ( ' > < ' ) U+22C8 , BOWTIE (&#x22C8;) = ('><') U+22C8, BOWTIE -} (⋈) ∷ Seq α → Seq α → Seq α (⋈) = (><) {-# INLINE (⋈) #-}
null
https://raw.githubusercontent.com/roelvandijk/containers-unicode-symbols/f86291a145e013138c9a935b61b063162afc61a8/Data/Sequence/Unicode.hs
haskell
----------------------------------------------------------------------------- Imports ----------------------------------------------------------------------------- from containers: ----------------------------------------------------------------------------- Fixities ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- Symbols ----------------------------------------------------------------------------- | (&#x2205;) = 'empty' U+2205, EMPTY SET # INLINE (∅) # | (&#x22B2;) = ('<|') U+22B2, NORMAL SUBGROUP OF # INLINE (⊲) # # INLINE (⊳) # # INLINE (⋈) #
# LANGUAGE NoImplicitPrelude , UnicodeSyntax # | Module : Data . Sequence . Unicode Copyright : 2009–2012 : BSD3 ( see the file LICENSE ) Maintainer : < > Module : Data.Sequence.Unicode Copyright : 2009–2012 Roel van Dijk License : BSD3 (see the file LICENSE) Maintainer : Roel van Dijk <> -} module Data.Sequence.Unicode ( (∅) , (⊲), (⊳) , (⋈) ) where import Data.Sequence ( Seq , empty , (<|), (|>) , (><) ) infixr 5 ⋈ infixr 5 ⊲ infixl 5 ⊳ (∅) ∷ Seq α (∅) = empty (⊲) ∷ α → Seq α → Seq α (⊲) = (<|) | ( & # x22B3 ;) = ( ' | > ' ) U+22B3 , CONTAINS AS NORMAL SUBGROUP (&#x22B3;) = ('|>') U+22B3, CONTAINS AS NORMAL SUBGROUP -} (⊳) ∷ Seq α → α → Seq α (⊳) = (|>) | ( & # x22C8 ;) = ( ' > < ' ) U+22C8 , BOWTIE (&#x22C8;) = ('><') U+22C8, BOWTIE -} (⋈) ∷ Seq α → Seq α → Seq α (⋈) = (><)
45615977533f26007462ce415f0d71b58ce16f93e950ab6254dc4ab705a9abb9
OCamlPro/freeton_wallet
commandMultisigDebot.ml
(**************************************************************************) (* *) Copyright ( c ) 2021 OCamlPro SAS (* *) (* 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 LICENSE.md file in the root directory. *) (* *) (* *) (**************************************************************************) open Ezcmd.V2 open EZCMD.TYPES open Types let action account = let config = Config.config () in let account = match account with | None -> "debot-multisig" | Some account -> account in let net = Config.current_network config in let address = Utils.address_of_account net account in let address = Misc.raw_address address in CommandClient.action ~exec:false [ "debot" ; "fetch" ; ADDRESS.to_string address ] ; () let cmd = let account = ref None in EZCMD.sub "multisig debot" (fun () -> action !account ) ~args: [ [], Arg.Anon (0, fun s -> account := Some s), EZCMD.info ~docv:"ACCOUNT" "The debot account"; ] ~doc: "Executes the multisig debot" ~man:[ `S "DESCRIPTION"; `P "This command executes the multisig debot, whose address is in the 'debot-multisig' account. "; ]
null
https://raw.githubusercontent.com/OCamlPro/freeton_wallet/b97877379e51d96cb3544141d386d502348cfca9/src/freeton_wallet_lib/commandMultisigDebot.ml
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the GNU Lesser General described in the LICENSE.md file in the root directory. ************************************************************************
Copyright ( c ) 2021 OCamlPro SAS Public License version 2.1 , with the special exception on linking open Ezcmd.V2 open EZCMD.TYPES open Types let action account = let config = Config.config () in let account = match account with | None -> "debot-multisig" | Some account -> account in let net = Config.current_network config in let address = Utils.address_of_account net account in let address = Misc.raw_address address in CommandClient.action ~exec:false [ "debot" ; "fetch" ; ADDRESS.to_string address ] ; () let cmd = let account = ref None in EZCMD.sub "multisig debot" (fun () -> action !account ) ~args: [ [], Arg.Anon (0, fun s -> account := Some s), EZCMD.info ~docv:"ACCOUNT" "The debot account"; ] ~doc: "Executes the multisig debot" ~man:[ `S "DESCRIPTION"; `P "This command executes the multisig debot, whose address is in the 'debot-multisig' account. "; ]
da627662af52536d0d504f70dd78a8b22df210981cc25a955c5b84ca114b2265
hemmi/coq2scala
refl_tauto.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) module Search = Explore.Make(Proof_search) open Util open Term open Names open Evd open Tacmach open Proof_search let force count lazc = incr count;Lazy.force lazc let step_count = ref 0 let node_count = ref 0 let logic_constant = Coqlib.gen_constant "refl_tauto" ["Init";"Logic"] let li_False = lazy (destInd (logic_constant "False")) let li_and = lazy (destInd (logic_constant "and")) let li_or = lazy (destInd (logic_constant "or")) let data_constant = Coqlib.gen_constant "refl_tauto" ["Init";"Datatypes"] let l_true_equals_true = lazy (mkApp(logic_constant "eq_refl", [|data_constant "bool";data_constant "true"|])) let pos_constant = Coqlib.gen_constant "refl_tauto" ["Numbers";"BinNums"] let l_xI = lazy (pos_constant "xI") let l_xO = lazy (pos_constant "xO") let l_xH = lazy (pos_constant "xH") let store_constant = Coqlib.gen_constant "refl_tauto" ["rtauto";"Bintree"] let l_empty = lazy (store_constant "empty") let l_push = lazy (store_constant "push") let constant= Coqlib.gen_constant "refl_tauto" ["rtauto";"Rtauto"] let l_Reflect = lazy (constant "Reflect") let l_Atom = lazy (constant "Atom") let l_Arrow = lazy (constant "Arrow") let l_Bot = lazy (constant "Bot") let l_Conjunct = lazy (constant "Conjunct") let l_Disjunct = lazy (constant "Disjunct") let l_Ax = lazy (constant "Ax") let l_I_Arrow = lazy (constant "I_Arrow") let l_E_Arrow = lazy (constant "E_Arrow") let l_D_Arrow = lazy (constant "D_Arrow") let l_E_False = lazy (constant "E_False") let l_I_And = lazy (constant "I_And") let l_E_And = lazy (constant "E_And") let l_D_And = lazy (constant "D_And") let l_I_Or_l = lazy (constant "I_Or_l") let l_I_Or_r = lazy (constant "I_Or_r") let l_E_Or = lazy (constant "E_Or") let l_D_Or = lazy (constant "D_Or") let special_whd gl= let infos=Closure.create_clos_infos Closure.betadeltaiota (pf_env gl) in (fun t -> Closure.whd_val infos (Closure.inject t)) let special_nf gl= let infos=Closure.create_clos_infos Closure.betaiotazeta (pf_env gl) in (fun t -> Closure.norm_val infos (Closure.inject t)) type atom_env= {mutable next:int; mutable env:(constr*int) list} let make_atom atom_env term= try let (_,i)= List.find (fun (t,_)-> eq_constr term t) atom_env.env in Atom i with Not_found -> let i=atom_env.next in atom_env.env <- (term,i)::atom_env.env; atom_env.next<- i + 1; Atom i let rec make_form atom_env gls term = let normalize=special_nf gls in let cciterm=special_whd gls term in match kind_of_term cciterm with Prod(_,a,b) -> if not (Termops.dependent (mkRel 1) b) && Retyping.get_sort_family_of (pf_env gls) (Tacmach.project gls) a = InProp then let fa=make_form atom_env gls a in let fb=make_form atom_env gls b in Arrow (fa,fb) else make_atom atom_env (normalize term) | Cast(a,_,_) -> make_form atom_env gls a | Ind ind -> if ind = Lazy.force li_False then Bot else make_atom atom_env (normalize term) | App(hd,argv) when Array.length argv = 2 -> begin try let ind = destInd hd in if ind = Lazy.force li_and then let fa=make_form atom_env gls argv.(0) in let fb=make_form atom_env gls argv.(1) in Conjunct (fa,fb) else if ind = Lazy.force li_or then let fa=make_form atom_env gls argv.(0) in let fb=make_form atom_env gls argv.(1) in Disjunct (fa,fb) else make_atom atom_env (normalize term) with Invalid_argument _ -> make_atom atom_env (normalize term) end | _ -> make_atom atom_env (normalize term) let rec make_hyps atom_env gls lenv = function [] -> [] | (_,Some body,typ)::rest -> make_hyps atom_env gls (typ::body::lenv) rest | (id,None,typ)::rest -> let hrec= make_hyps atom_env gls (typ::lenv) rest in if List.exists (Termops.dependent (mkVar id)) lenv || (Retyping.get_sort_family_of (pf_env gls) (Tacmach.project gls) typ <> InProp) then hrec else (id,make_form atom_env gls typ)::hrec let rec build_pos n = if n<=1 then force node_count l_xH else if n land 1 = 0 then mkApp (force node_count l_xO,[|build_pos (n asr 1)|]) else mkApp (force node_count l_xI,[|build_pos (n asr 1)|]) let rec build_form = function Atom n -> mkApp (force node_count l_Atom,[|build_pos n|]) | Arrow (f1,f2) -> mkApp (force node_count l_Arrow,[|build_form f1;build_form f2|]) | Bot -> force node_count l_Bot | Conjunct (f1,f2) -> mkApp (force node_count l_Conjunct,[|build_form f1;build_form f2|]) | Disjunct (f1,f2) -> mkApp (force node_count l_Disjunct,[|build_form f1;build_form f2|]) let rec decal k = function [] -> k | (start,delta)::rest -> if k>start then k - delta else decal k rest let add_pop size d pops= match pops with [] -> [size+d,d] | (_,sum)::_ -> (size+sum,sum+d)::pops let rec build_proof pops size = function Ax i -> mkApp (force step_count l_Ax, [|build_pos (decal i pops)|]) | I_Arrow p -> mkApp (force step_count l_I_Arrow, [|build_proof pops (size + 1) p|]) | E_Arrow(i,j,p) -> mkApp (force step_count l_E_Arrow, [|build_pos (decal i pops); build_pos (decal j pops); build_proof pops (size + 1) p|]) | D_Arrow(i,p1,p2) -> mkApp (force step_count l_D_Arrow, [|build_pos (decal i pops); build_proof pops (size + 2) p1; build_proof pops (size + 1) p2|]) | E_False i -> mkApp (force step_count l_E_False, [|build_pos (decal i pops)|]) | I_And(p1,p2) -> mkApp (force step_count l_I_And, [|build_proof pops size p1; build_proof pops size p2|]) | E_And(i,p) -> mkApp (force step_count l_E_And, [|build_pos (decal i pops); build_proof pops (size + 2) p|]) | D_And(i,p) -> mkApp (force step_count l_D_And, [|build_pos (decal i pops); build_proof pops (size + 1) p|]) | I_Or_l(p) -> mkApp (force step_count l_I_Or_l, [|build_proof pops size p|]) | I_Or_r(p) -> mkApp (force step_count l_I_Or_r, [|build_proof pops size p|]) | E_Or(i,p1,p2) -> mkApp (force step_count l_E_Or, [|build_pos (decal i pops); build_proof pops (size + 1) p1; build_proof pops (size + 1) p2|]) | D_Or(i,p) -> mkApp (force step_count l_D_Or, [|build_pos (decal i pops); build_proof pops (size + 2) p|]) | Pop(d,p) -> build_proof (add_pop size d pops) size p let build_env gamma= List.fold_right (fun (p,_) e -> mkApp(force node_count l_push,[|mkProp;p;e|])) gamma.env (mkApp (force node_count l_empty,[|mkProp|])) open Goptions let verbose = ref false let opt_verbose= {optsync=true; optdepr=false; optname="Rtauto Verbose"; optkey=["Rtauto";"Verbose"]; optread=(fun () -> !verbose); optwrite=(fun b -> verbose:=b)} let _ = declare_bool_option opt_verbose let check = ref false let opt_check= {optsync=true; optdepr=false; optname="Rtauto Check"; optkey=["Rtauto";"Check"]; optread=(fun () -> !check); optwrite=(fun b -> check:=b)} let _ = declare_bool_option opt_check open Pp let rtauto_tac gls= Coqlib.check_required_library ["Coq";"rtauto";"Rtauto"]; let gamma={next=1;env=[]} in let gl=pf_concl gls in let _= if Retyping.get_sort_family_of (pf_env gls) (Tacmach.project gls) gl <> InProp then errorlabstrm "rtauto" (Pp.str "goal should be in Prop") in let glf=make_form gamma gls gl in let hyps=make_hyps gamma gls [gl] (pf_hyps gls) in let formula= List.fold_left (fun gl (_,f)-> Arrow (f,gl)) glf hyps in let search_fun = if Tacinterp.get_debug()=Tactic_debug.DebugOn 0 then Search.debug_depth_first else Search.depth_first in let _ = begin reset_info (); if !verbose then msgnl (str "Starting proof-search ..."); end in let search_start_time = System.get_time () in let prf = try project (search_fun (init_state [] formula)) with Not_found -> errorlabstrm "rtauto" (Pp.str "rtauto couldn't find any proof") in let search_end_time = System.get_time () in let _ = if !verbose then begin msgnl (str "Proof tree found in " ++ System.fmt_time_difference search_start_time search_end_time); pp_info (); msgnl (str "Building proof term ... ") end in let build_start_time=System.get_time () in let _ = step_count := 0; node_count := 0 in let main = mkApp (force node_count l_Reflect, [|build_env gamma; build_form formula; build_proof [] 0 prf|]) in let term= Term.applist (main,List.rev_map (fun (id,_) -> mkVar id) hyps) in let build_end_time=System.get_time () in let _ = if !verbose then begin msgnl (str "Proof term built in " ++ System.fmt_time_difference build_start_time build_end_time ++ fnl () ++ str "Proof size : " ++ int !step_count ++ str " steps" ++ fnl () ++ str "Proof term size : " ++ int (!step_count+ !node_count) ++ str " nodes (constants)" ++ fnl () ++ str "Giving proof term to Coq ... ") end in let tac_start_time = System.get_time () in let result= if !check then Tactics.exact_check term gls else Tactics.exact_no_check term gls in let tac_end_time = System.get_time () in let _ = if !check then msgnl (str "Proof term type-checking is on"); if !verbose then msgnl (str "Internal tactic executed in " ++ System.fmt_time_difference tac_start_time tac_end_time) in result
null
https://raw.githubusercontent.com/hemmi/coq2scala/d10f441c18146933a99bf2088116bd213ac3648d/coq-8.4pl2/plugins/rtauto/refl_tauto.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 **********************************************************************
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * module Search = Explore.Make(Proof_search) open Util open Term open Names open Evd open Tacmach open Proof_search let force count lazc = incr count;Lazy.force lazc let step_count = ref 0 let node_count = ref 0 let logic_constant = Coqlib.gen_constant "refl_tauto" ["Init";"Logic"] let li_False = lazy (destInd (logic_constant "False")) let li_and = lazy (destInd (logic_constant "and")) let li_or = lazy (destInd (logic_constant "or")) let data_constant = Coqlib.gen_constant "refl_tauto" ["Init";"Datatypes"] let l_true_equals_true = lazy (mkApp(logic_constant "eq_refl", [|data_constant "bool";data_constant "true"|])) let pos_constant = Coqlib.gen_constant "refl_tauto" ["Numbers";"BinNums"] let l_xI = lazy (pos_constant "xI") let l_xO = lazy (pos_constant "xO") let l_xH = lazy (pos_constant "xH") let store_constant = Coqlib.gen_constant "refl_tauto" ["rtauto";"Bintree"] let l_empty = lazy (store_constant "empty") let l_push = lazy (store_constant "push") let constant= Coqlib.gen_constant "refl_tauto" ["rtauto";"Rtauto"] let l_Reflect = lazy (constant "Reflect") let l_Atom = lazy (constant "Atom") let l_Arrow = lazy (constant "Arrow") let l_Bot = lazy (constant "Bot") let l_Conjunct = lazy (constant "Conjunct") let l_Disjunct = lazy (constant "Disjunct") let l_Ax = lazy (constant "Ax") let l_I_Arrow = lazy (constant "I_Arrow") let l_E_Arrow = lazy (constant "E_Arrow") let l_D_Arrow = lazy (constant "D_Arrow") let l_E_False = lazy (constant "E_False") let l_I_And = lazy (constant "I_And") let l_E_And = lazy (constant "E_And") let l_D_And = lazy (constant "D_And") let l_I_Or_l = lazy (constant "I_Or_l") let l_I_Or_r = lazy (constant "I_Or_r") let l_E_Or = lazy (constant "E_Or") let l_D_Or = lazy (constant "D_Or") let special_whd gl= let infos=Closure.create_clos_infos Closure.betadeltaiota (pf_env gl) in (fun t -> Closure.whd_val infos (Closure.inject t)) let special_nf gl= let infos=Closure.create_clos_infos Closure.betaiotazeta (pf_env gl) in (fun t -> Closure.norm_val infos (Closure.inject t)) type atom_env= {mutable next:int; mutable env:(constr*int) list} let make_atom atom_env term= try let (_,i)= List.find (fun (t,_)-> eq_constr term t) atom_env.env in Atom i with Not_found -> let i=atom_env.next in atom_env.env <- (term,i)::atom_env.env; atom_env.next<- i + 1; Atom i let rec make_form atom_env gls term = let normalize=special_nf gls in let cciterm=special_whd gls term in match kind_of_term cciterm with Prod(_,a,b) -> if not (Termops.dependent (mkRel 1) b) && Retyping.get_sort_family_of (pf_env gls) (Tacmach.project gls) a = InProp then let fa=make_form atom_env gls a in let fb=make_form atom_env gls b in Arrow (fa,fb) else make_atom atom_env (normalize term) | Cast(a,_,_) -> make_form atom_env gls a | Ind ind -> if ind = Lazy.force li_False then Bot else make_atom atom_env (normalize term) | App(hd,argv) when Array.length argv = 2 -> begin try let ind = destInd hd in if ind = Lazy.force li_and then let fa=make_form atom_env gls argv.(0) in let fb=make_form atom_env gls argv.(1) in Conjunct (fa,fb) else if ind = Lazy.force li_or then let fa=make_form atom_env gls argv.(0) in let fb=make_form atom_env gls argv.(1) in Disjunct (fa,fb) else make_atom atom_env (normalize term) with Invalid_argument _ -> make_atom atom_env (normalize term) end | _ -> make_atom atom_env (normalize term) let rec make_hyps atom_env gls lenv = function [] -> [] | (_,Some body,typ)::rest -> make_hyps atom_env gls (typ::body::lenv) rest | (id,None,typ)::rest -> let hrec= make_hyps atom_env gls (typ::lenv) rest in if List.exists (Termops.dependent (mkVar id)) lenv || (Retyping.get_sort_family_of (pf_env gls) (Tacmach.project gls) typ <> InProp) then hrec else (id,make_form atom_env gls typ)::hrec let rec build_pos n = if n<=1 then force node_count l_xH else if n land 1 = 0 then mkApp (force node_count l_xO,[|build_pos (n asr 1)|]) else mkApp (force node_count l_xI,[|build_pos (n asr 1)|]) let rec build_form = function Atom n -> mkApp (force node_count l_Atom,[|build_pos n|]) | Arrow (f1,f2) -> mkApp (force node_count l_Arrow,[|build_form f1;build_form f2|]) | Bot -> force node_count l_Bot | Conjunct (f1,f2) -> mkApp (force node_count l_Conjunct,[|build_form f1;build_form f2|]) | Disjunct (f1,f2) -> mkApp (force node_count l_Disjunct,[|build_form f1;build_form f2|]) let rec decal k = function [] -> k | (start,delta)::rest -> if k>start then k - delta else decal k rest let add_pop size d pops= match pops with [] -> [size+d,d] | (_,sum)::_ -> (size+sum,sum+d)::pops let rec build_proof pops size = function Ax i -> mkApp (force step_count l_Ax, [|build_pos (decal i pops)|]) | I_Arrow p -> mkApp (force step_count l_I_Arrow, [|build_proof pops (size + 1) p|]) | E_Arrow(i,j,p) -> mkApp (force step_count l_E_Arrow, [|build_pos (decal i pops); build_pos (decal j pops); build_proof pops (size + 1) p|]) | D_Arrow(i,p1,p2) -> mkApp (force step_count l_D_Arrow, [|build_pos (decal i pops); build_proof pops (size + 2) p1; build_proof pops (size + 1) p2|]) | E_False i -> mkApp (force step_count l_E_False, [|build_pos (decal i pops)|]) | I_And(p1,p2) -> mkApp (force step_count l_I_And, [|build_proof pops size p1; build_proof pops size p2|]) | E_And(i,p) -> mkApp (force step_count l_E_And, [|build_pos (decal i pops); build_proof pops (size + 2) p|]) | D_And(i,p) -> mkApp (force step_count l_D_And, [|build_pos (decal i pops); build_proof pops (size + 1) p|]) | I_Or_l(p) -> mkApp (force step_count l_I_Or_l, [|build_proof pops size p|]) | I_Or_r(p) -> mkApp (force step_count l_I_Or_r, [|build_proof pops size p|]) | E_Or(i,p1,p2) -> mkApp (force step_count l_E_Or, [|build_pos (decal i pops); build_proof pops (size + 1) p1; build_proof pops (size + 1) p2|]) | D_Or(i,p) -> mkApp (force step_count l_D_Or, [|build_pos (decal i pops); build_proof pops (size + 2) p|]) | Pop(d,p) -> build_proof (add_pop size d pops) size p let build_env gamma= List.fold_right (fun (p,_) e -> mkApp(force node_count l_push,[|mkProp;p;e|])) gamma.env (mkApp (force node_count l_empty,[|mkProp|])) open Goptions let verbose = ref false let opt_verbose= {optsync=true; optdepr=false; optname="Rtauto Verbose"; optkey=["Rtauto";"Verbose"]; optread=(fun () -> !verbose); optwrite=(fun b -> verbose:=b)} let _ = declare_bool_option opt_verbose let check = ref false let opt_check= {optsync=true; optdepr=false; optname="Rtauto Check"; optkey=["Rtauto";"Check"]; optread=(fun () -> !check); optwrite=(fun b -> check:=b)} let _ = declare_bool_option opt_check open Pp let rtauto_tac gls= Coqlib.check_required_library ["Coq";"rtauto";"Rtauto"]; let gamma={next=1;env=[]} in let gl=pf_concl gls in let _= if Retyping.get_sort_family_of (pf_env gls) (Tacmach.project gls) gl <> InProp then errorlabstrm "rtauto" (Pp.str "goal should be in Prop") in let glf=make_form gamma gls gl in let hyps=make_hyps gamma gls [gl] (pf_hyps gls) in let formula= List.fold_left (fun gl (_,f)-> Arrow (f,gl)) glf hyps in let search_fun = if Tacinterp.get_debug()=Tactic_debug.DebugOn 0 then Search.debug_depth_first else Search.depth_first in let _ = begin reset_info (); if !verbose then msgnl (str "Starting proof-search ..."); end in let search_start_time = System.get_time () in let prf = try project (search_fun (init_state [] formula)) with Not_found -> errorlabstrm "rtauto" (Pp.str "rtauto couldn't find any proof") in let search_end_time = System.get_time () in let _ = if !verbose then begin msgnl (str "Proof tree found in " ++ System.fmt_time_difference search_start_time search_end_time); pp_info (); msgnl (str "Building proof term ... ") end in let build_start_time=System.get_time () in let _ = step_count := 0; node_count := 0 in let main = mkApp (force node_count l_Reflect, [|build_env gamma; build_form formula; build_proof [] 0 prf|]) in let term= Term.applist (main,List.rev_map (fun (id,_) -> mkVar id) hyps) in let build_end_time=System.get_time () in let _ = if !verbose then begin msgnl (str "Proof term built in " ++ System.fmt_time_difference build_start_time build_end_time ++ fnl () ++ str "Proof size : " ++ int !step_count ++ str " steps" ++ fnl () ++ str "Proof term size : " ++ int (!step_count+ !node_count) ++ str " nodes (constants)" ++ fnl () ++ str "Giving proof term to Coq ... ") end in let tac_start_time = System.get_time () in let result= if !check then Tactics.exact_check term gls else Tactics.exact_no_check term gls in let tac_end_time = System.get_time () in let _ = if !check then msgnl (str "Proof term type-checking is on"); if !verbose then msgnl (str "Internal tactic executed in " ++ System.fmt_time_difference tac_start_time tac_end_time) in result
59e3c7a50f875667ecbdbcbc9b18cc4b8db6762d643bc03bf9c9d624b1711bf9
zotonic/zotonic
zotonic_cmd_startsite.erl
%%%------------------------------------------------------------------- %%% @author Blaise %%% @doc 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. %%% %%% @end Created : 18 . Dec 2017 4:07 PM %%%------------------------------------------------------------------- -module(zotonic_cmd_startsite). -author("Blaise"). %% API -export([info/0, run/1]). info() -> "Start a site.". run([ Site ]) -> case zotonic_command:net_start() of ok -> SiteName = list_to_atom(Site), io:format("Starting site ~p .. ", [ SiteName ]), Res = zotonic_command:rpc(z, shell_startsite, [ SiteName ]), io:format("~p~n", [ Res ]); {error, _} = Error -> zotonic_command:format_error(Error) end; run(_) -> io:format(standard_error, "USAGE: startsite <site_name>~n", []), halt().
null
https://raw.githubusercontent.com/zotonic/zotonic/852f627c28adf6e5212e8ad5383d4af3a2f25e3f/apps/zotonic_launcher/src/command/zotonic_cmd_startsite.erl
erlang
------------------------------------------------------------------- @author Blaise @doc 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. @end ------------------------------------------------------------------- API
Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , Created : 18 . Dec 2017 4:07 PM -module(zotonic_cmd_startsite). -author("Blaise"). -export([info/0, run/1]). info() -> "Start a site.". run([ Site ]) -> case zotonic_command:net_start() of ok -> SiteName = list_to_atom(Site), io:format("Starting site ~p .. ", [ SiteName ]), Res = zotonic_command:rpc(z, shell_startsite, [ SiteName ]), io:format("~p~n", [ Res ]); {error, _} = Error -> zotonic_command:format_error(Error) end; run(_) -> io:format(standard_error, "USAGE: startsite <site_name>~n", []), halt().
946bb059cc0db69fc37b44efe91e8364fd8a47620231bbb02053e4284ac22725
walmartlabs/clojure-game-geek
build.clj
(ns build (:refer-clojure :exclude [test]) (:require [org.corfield.build :as bb])) (def lib 'net.clojars.my/clojure-game-geek) (def version "0.1.0-SNAPSHOT") (def main 'my.clojure-game-geek) (defn test "Run the tests." [opts] (bb/run-tests (assoc opts :aliases [:dev]))) (defn ci "Run the CI pipeline of tests (and build the uberjar)." [opts] (-> opts (assoc :lib lib :version version :main main) (bb/run-tests) (bb/clean) (bb/uber)))
null
https://raw.githubusercontent.com/walmartlabs/clojure-game-geek/62b5fcf7b15e348eb7cda878097b40f4934f0f91/build.clj
clojure
(ns build (:refer-clojure :exclude [test]) (:require [org.corfield.build :as bb])) (def lib 'net.clojars.my/clojure-game-geek) (def version "0.1.0-SNAPSHOT") (def main 'my.clojure-game-geek) (defn test "Run the tests." [opts] (bb/run-tests (assoc opts :aliases [:dev]))) (defn ci "Run the CI pipeline of tests (and build the uberjar)." [opts] (-> opts (assoc :lib lib :version version :main main) (bb/run-tests) (bb/clean) (bb/uber)))
9031eb55fb41e0ecd9b06e8e4efc1555cac037c1b1a71bfc4962885ad29f8bac
hongchangwu/ocaml-type-classes
eq.mli
module type S = sig type t val ( == ) : t -> t -> bool val ( /= ) : t -> t -> bool end val bool : (module S with type t = bool) val char : (module S with type t = char) val float : (module S with type t = float) val int : (module S with type t = int) val list : (module S with type t = 'a) -> (module S with type t = 'a list) val string : (module S with type t = string)
null
https://raw.githubusercontent.com/hongchangwu/ocaml-type-classes/17b11af26008f42a88aec85001a94ba18584ea72/lib/eq.mli
ocaml
module type S = sig type t val ( == ) : t -> t -> bool val ( /= ) : t -> t -> bool end val bool : (module S with type t = bool) val char : (module S with type t = char) val float : (module S with type t = float) val int : (module S with type t = int) val list : (module S with type t = 'a) -> (module S with type t = 'a list) val string : (module S with type t = string)
49f126e51dffb561a1192a3af1e4b3ba82a77ec66954424619ba7db60dda0b5b
databrary/databrary
Messages.hs
{-# LANGUAGE OverloadedStrings #-} module Web.Messages ( generateMessagesJS ) where import Control.Monad.IO.Class (liftIO) import qualified Data.Aeson.Encoding as JSON import qualified Data.ByteString.Builder as BSB import System.IO (withBinaryFile, IOMode(WriteMode), hPutStr) import qualified JSON import Service.Messages import Files import Web import Web.Types import Web.Generate generateMessagesJS :: WebGenerator generateMessagesJS = \fo@(f, _) -> do mf <- liftIO messagesFile mfRawFilePath <- liftIO $ rawFilePath mf fp <- liftIO $ unRawFilePath $ webFileAbs f webRegenerate (do msg <- liftIO $ loadMessagesFrom mf withBinaryFile fp WriteMode $ \h -> do hPutStr h "app.constant('messageData'," BSB.hPutBuilder h $ JSON.fromEncoding $ JSON.value $ JSON.toJSON msg hPutStr h ");") [mfRawFilePath] [] fo
null
https://raw.githubusercontent.com/databrary/databrary/685f3c625b960268f5d9b04e3d7c6146bea5afda/src/Web/Messages.hs
haskell
# LANGUAGE OverloadedStrings #
module Web.Messages ( generateMessagesJS ) where import Control.Monad.IO.Class (liftIO) import qualified Data.Aeson.Encoding as JSON import qualified Data.ByteString.Builder as BSB import System.IO (withBinaryFile, IOMode(WriteMode), hPutStr) import qualified JSON import Service.Messages import Files import Web import Web.Types import Web.Generate generateMessagesJS :: WebGenerator generateMessagesJS = \fo@(f, _) -> do mf <- liftIO messagesFile mfRawFilePath <- liftIO $ rawFilePath mf fp <- liftIO $ unRawFilePath $ webFileAbs f webRegenerate (do msg <- liftIO $ loadMessagesFrom mf withBinaryFile fp WriteMode $ \h -> do hPutStr h "app.constant('messageData'," BSB.hPutBuilder h $ JSON.fromEncoding $ JSON.value $ JSON.toJSON msg hPutStr h ");") [mfRawFilePath] [] fo
c64482d1e530b831e7d9e9f24a0ee63c77d278e36b6a98eb982dedd1abbe474a
phantomics/seed
package.lisp
package.lisp (defpackage #:seed.ui-model.keys (:export #:key-ui #:specify-key-ui #:build-key-ui #:portal-action) (:use #:cl #:parenscript #:symbol-munger))
null
https://raw.githubusercontent.com/phantomics/seed/f128969c671c078543574395d6b23a1a5f2723f8/seed.ui-model.keys/package.lisp
lisp
package.lisp (defpackage #:seed.ui-model.keys (:export #:key-ui #:specify-key-ui #:build-key-ui #:portal-action) (:use #:cl #:parenscript #:symbol-munger))
e2d66637c115a52e76ce0fcf8f65e975e8c845a67aa798a1772c75faf07b4969
realworldocaml/book
cst.mli
(** Concrete syntax tree of expectations and actual outputs *) (** These types represent the contents of an [%expect] node or of the actual output. We keep information about the original layout so that we can give an corrected expectation that follows the original formatting. In the following names, blank means ' ' or '\t', while space means blank or newline. *) open! Base open Base.Exported_for_specific_uses (* for [Ppx_compare_lib] *) module Line : sig type 'a not_blank = { trailing_blanks : string (** regexp: "[ \t]*" *) ; orig : string (** Original contents of the line without the trailing blanks or indentation. regexp: "[^\n]*[^ \t\n]" *) ; data : 'a (** Data associated to the line. *) } [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_not_blank : ('a -> Sexplib0.Sexp.t) -> 'a not_blank -> Sexplib0.Sexp.t val compare_not_blank : ('a -> 'a -> int) -> 'a not_blank -> 'a not_blank -> int val equal_not_blank : ('a -> 'a -> bool) -> 'a not_blank -> 'a not_blank -> bool end[@@ocaml.doc "@inline"] [@@@end] type 'a t = | Blank of string (** regexp: "[ \t]*" *) | Conflict_marker of string (** regexp: "^(<{7} |[|]{7} |>{7} |={7})" *) | Not_blank of 'a not_blank [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_t : ('a -> Sexplib0.Sexp.t) -> 'a t -> Sexplib0.Sexp.t include Ppx_compare_lib.Comparable.S1 with type 'a t := 'a t include Ppx_compare_lib.Equal.S1 with type 'a t := 'a t end[@@ocaml.doc "@inline"] [@@@end] val invariant : ('a -> unit) -> 'a t -> unit (** The callback receive the [orig] and [data] fields *) val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t (** Delete trailing blanks (everything for blank lines) *) val strip : 'a t -> 'a t val data : 'a t -> blank:'a -> conflict_marker:(string -> 'a) -> 'a end * Single line represent [ % expect ] nodes with data on the first line but not on the subsequent ones . For instance : { [ [ % expect " blah " ] ; [ % expect { | blah | } ] ] } subsequent ones. For instance: {[ [%expect " blah "]; [%expect {| blah |}] ]} *) type 'a single_line = { leading_blanks : string (** regexp: "[ \t]*" *) ; trailing_spaces : string (** regexp: "[ \t\n]*" *) ; orig : string (** regexp: "[^ \t\n]([^\n]*[^ \t\n])?" *) ; data : 'a } [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_single_line : ('a -> Sexplib0.Sexp.t) -> 'a single_line -> Sexplib0.Sexp.t val compare_single_line : ('a -> 'a -> int) -> 'a single_line -> 'a single_line -> int val equal_single_line : ('a -> 'a -> bool) -> 'a single_line -> 'a single_line -> bool end[@@ocaml.doc "@inline"] [@@@end] * Any [ % expect ] node with one or more newlines and at least one non - blank line . This also include the case with exactly one non - blank line such as : { [ [ % expect { | blah | } ] ] } This is to preserve this formatting in case the correction is multi - line . [ leading_spaces ] contains everything until the first non - blank line , while [ trailing_spaces ] is either : - trailing blanks on the last line if of the form : { [ [ % expect { | abc def | } ] ] } - all trailing spaces from the newline character ( inclusive ) on the last non - blank line to the end if of the form : { [ [ % expect { | abc def | } ] ] } This also include the case with exactly one non-blank line such as: {[ [%expect {| blah |}] ]} This is to preserve this formatting in case the correction is multi-line. [leading_spaces] contains everything until the first non-blank line, while [trailing_spaces] is either: - trailing blanks on the last line if of the form: {[ [%expect {| abc def |}] ]} - all trailing spaces from the newline character (inclusive) on the last non-blank line to the end if of the form: {[ [%expect {| abc def |}] ]} *) type 'a multi_lines = { leading_spaces : string (** regexp: "\([ \t]*\n\)*" *) * regexp : " [ \t ] * " or " \(\n [ \t]*\ ) * " ; indentation : string (** regexp: "[ \t]*" *) ; lines : 'a Line.t list (** regexp: not_blank (.* not_blank)? *) } [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_multi_lines : ('a -> Sexplib0.Sexp.t) -> 'a multi_lines -> Sexplib0.Sexp.t val compare_multi_lines : ('a -> 'a -> int) -> 'a multi_lines -> 'a multi_lines -> int val equal_multi_lines : ('a -> 'a -> bool) -> 'a multi_lines -> 'a multi_lines -> bool end[@@ocaml.doc "@inline"] [@@@end] type 'a t = | Empty of string (** regexp: "[ \t\n]*" *) | Single_line of 'a single_line | Multi_lines of 'a multi_lines [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_t : ('a -> Sexplib0.Sexp.t) -> 'a t -> Sexplib0.Sexp.t include Ppx_compare_lib.Comparable.S1 with type 'a t := 'a t include Ppx_compare_lib.Equal.S1 with type 'a t := 'a t end[@@ocaml.doc "@inline"] [@@@end] val invariant : ('a -> unit) -> 'a t -> unit val empty : 'a t val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t val data : 'a t -> blank:'a -> conflict_marker:(string -> 'a) -> 'a list val strip : 'a t -> 'a t val to_string : _ t -> string (** For single line expectation, leading blanks and trailing spaces are dropped. *) val to_lines : 'a t -> 'a Line.t list (** Remove blank lines at the beginning and end of the list. *) val trim_lines : 'a Line.t list -> 'a Line.t list (** Given a contents [t] and a list of [lines], try to produce a new contents containing [lines] but with the same formatting as [t]. [default_indentation] is the indentation to use in case we ignore [t]'s indentation (for instance if [t] is [Single_line] or [Empty]). *) val reconcile : 'a t -> lines : 'a Line.t list -> default_indentation : int -> pad_single_line : bool -> 'a t (** Compute the longest indentation of a list of lines and trim it from every line. It returns the found indentation and the list of trimmed lines. *) val extract_indentation : 'a Line.t list -> string * 'a Line.t list (** All the [.orig] fields of [Line.t] or [single_line] values, using [""] for blank lines. *) val stripped_original_lines : _ t -> string list
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ppx_expect/matcher/cst.mli
ocaml
* Concrete syntax tree of expectations and actual outputs * These types represent the contents of an [%expect] node or of the actual output. We keep information about the original layout so that we can give an corrected expectation that follows the original formatting. In the following names, blank means ' ' or '\t', while space means blank or newline. for [Ppx_compare_lib] * regexp: "[ \t]*" * Original contents of the line without the trailing blanks or indentation. regexp: "[^\n]*[^ \t\n]" * Data associated to the line. * regexp: "[ \t]*" * regexp: "^(<{7} |[|]{7} |>{7} |={7})" * The callback receive the [orig] and [data] fields * Delete trailing blanks (everything for blank lines) * regexp: "[ \t]*" * regexp: "[ \t\n]*" * regexp: "[^ \t\n]([^\n]*[^ \t\n])?" * regexp: "\([ \t]*\n\)*" * regexp: "[ \t]*" * regexp: not_blank (.* not_blank)? * regexp: "[ \t\n]*" * For single line expectation, leading blanks and trailing spaces are dropped. * Remove blank lines at the beginning and end of the list. * Given a contents [t] and a list of [lines], try to produce a new contents containing [lines] but with the same formatting as [t]. [default_indentation] is the indentation to use in case we ignore [t]'s indentation (for instance if [t] is [Single_line] or [Empty]). * Compute the longest indentation of a list of lines and trim it from every line. It returns the found indentation and the list of trimmed lines. * All the [.orig] fields of [Line.t] or [single_line] values, using [""] for blank lines.
open! Base module Line : sig type 'a not_blank = ; orig : string ; data : 'a } [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_not_blank : ('a -> Sexplib0.Sexp.t) -> 'a not_blank -> Sexplib0.Sexp.t val compare_not_blank : ('a -> 'a -> int) -> 'a not_blank -> 'a not_blank -> int val equal_not_blank : ('a -> 'a -> bool) -> 'a not_blank -> 'a not_blank -> bool end[@@ocaml.doc "@inline"] [@@@end] type 'a t = | Not_blank of 'a not_blank [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_t : ('a -> Sexplib0.Sexp.t) -> 'a t -> Sexplib0.Sexp.t include Ppx_compare_lib.Comparable.S1 with type 'a t := 'a t include Ppx_compare_lib.Equal.S1 with type 'a t := 'a t end[@@ocaml.doc "@inline"] [@@@end] val invariant : ('a -> unit) -> 'a t -> unit val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t val strip : 'a t -> 'a t val data : 'a t -> blank:'a -> conflict_marker:(string -> 'a) -> 'a end * Single line represent [ % expect ] nodes with data on the first line but not on the subsequent ones . For instance : { [ [ % expect " blah " ] ; [ % expect { | blah | } ] ] } subsequent ones. For instance: {[ [%expect " blah "]; [%expect {| blah |}] ]} *) type 'a single_line = ; data : 'a } [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_single_line : ('a -> Sexplib0.Sexp.t) -> 'a single_line -> Sexplib0.Sexp.t val compare_single_line : ('a -> 'a -> int) -> 'a single_line -> 'a single_line -> int val equal_single_line : ('a -> 'a -> bool) -> 'a single_line -> 'a single_line -> bool end[@@ocaml.doc "@inline"] [@@@end] * Any [ % expect ] node with one or more newlines and at least one non - blank line . This also include the case with exactly one non - blank line such as : { [ [ % expect { | blah | } ] ] } This is to preserve this formatting in case the correction is multi - line . [ leading_spaces ] contains everything until the first non - blank line , while [ trailing_spaces ] is either : - trailing blanks on the last line if of the form : { [ [ % expect { | abc def | } ] ] } - all trailing spaces from the newline character ( inclusive ) on the last non - blank line to the end if of the form : { [ [ % expect { | abc def | } ] ] } This also include the case with exactly one non-blank line such as: {[ [%expect {| blah |}] ]} This is to preserve this formatting in case the correction is multi-line. [leading_spaces] contains everything until the first non-blank line, while [trailing_spaces] is either: - trailing blanks on the last line if of the form: {[ [%expect {| abc def |}] ]} - all trailing spaces from the newline character (inclusive) on the last non-blank line to the end if of the form: {[ [%expect {| abc def |}] ]} *) type 'a multi_lines = * regexp : " [ \t ] * " or " \(\n [ \t]*\ ) * " } [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_multi_lines : ('a -> Sexplib0.Sexp.t) -> 'a multi_lines -> Sexplib0.Sexp.t val compare_multi_lines : ('a -> 'a -> int) -> 'a multi_lines -> 'a multi_lines -> int val equal_multi_lines : ('a -> 'a -> bool) -> 'a multi_lines -> 'a multi_lines -> bool end[@@ocaml.doc "@inline"] [@@@end] type 'a t = | Single_line of 'a single_line | Multi_lines of 'a multi_lines [@@deriving_inline sexp_of, compare, equal] include sig [@@@ocaml.warning "-32"] val sexp_of_t : ('a -> Sexplib0.Sexp.t) -> 'a t -> Sexplib0.Sexp.t include Ppx_compare_lib.Comparable.S1 with type 'a t := 'a t include Ppx_compare_lib.Equal.S1 with type 'a t := 'a t end[@@ocaml.doc "@inline"] [@@@end] val invariant : ('a -> unit) -> 'a t -> unit val empty : 'a t val map : 'a t -> f:(string -> 'a -> 'b) -> 'b t val data : 'a t -> blank:'a -> conflict_marker:(string -> 'a) -> 'a list val strip : 'a t -> 'a t val to_string : _ t -> string val to_lines : 'a t -> 'a Line.t list val trim_lines : 'a Line.t list -> 'a Line.t list val reconcile : 'a t -> lines : 'a Line.t list -> default_indentation : int -> pad_single_line : bool -> 'a t val extract_indentation : 'a Line.t list -> string * 'a Line.t list val stripped_original_lines : _ t -> string list
69112cb37fa2f8ac714e90370beafa141e3ea986e989392241acdf000603483a
timbod7/haskell-chart
example3-m.hs
import Graphics.Rendering.Chart.Easy import Graphics.Rendering.Chart.Backend.Cairo import Data.Time.LocalTime import Prices(prices1) fillBetween title vs = liftEC $ do plot_fillbetween_title .= title color <- takeColor plot_fillbetween_style .= solidFillStyle color plot_fillbetween_values .= vs main = toFile def "example3_big.png" $ do layout_title .= "Price History" plot (fillBetween "price 1" [ (d,(0,v2)) | (d,v1,v2) <- prices1]) plot (fillBetween "price 2" [ (d,(0,v1)) | (d,v1,v2) <- prices1])
null
https://raw.githubusercontent.com/timbod7/haskell-chart/8c5a823652ea1b4ec2adbced4a92a8161065ead6/wiki-examples/example3-m.hs
haskell
import Graphics.Rendering.Chart.Easy import Graphics.Rendering.Chart.Backend.Cairo import Data.Time.LocalTime import Prices(prices1) fillBetween title vs = liftEC $ do plot_fillbetween_title .= title color <- takeColor plot_fillbetween_style .= solidFillStyle color plot_fillbetween_values .= vs main = toFile def "example3_big.png" $ do layout_title .= "Price History" plot (fillBetween "price 1" [ (d,(0,v2)) | (d,v1,v2) <- prices1]) plot (fillBetween "price 2" [ (d,(0,v1)) | (d,v1,v2) <- prices1])