_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
0e02b7e9ed1449f5bf8217f4d7fae0b037753bc5bc80c64702a59923e72282a9
DKurilo/battleship
GameService.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ExtendedDefaultRules # # LANGUAGE TemplateHaskell # # LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # module Api.Services.GameService where import Control.Exception import Control.Monad import Control.Monad.IO.Class import Database.MongoDB import Database.MongoDB.Query as MQ import Database.MongoDB.Connection import Data.Bson as BS import Api.Types import qualified Control.Lens as CL import Control.Monad.State.Class import Data.List as DL import Data.Aeson as DA import Data.UUID as UUID import Data.UUID.V4 import Snap.Core import Snap.Snaplet as SN import qualified Data.ByteString.Char8 as B import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Text.Encoding import Data.Time.Clock.POSIX data GameService = GameService { } CL.makeLenses ''GameService gameTimeout :: Int gameTimeout = 3600 * 10000 mapWidth :: Int mapWidth = 10 mapHeight :: Int mapHeight = 10 --------------------- -- Routes gameRoutes :: Host -> Username -> Password -> Database -> FilePath -> FilePath -> [(B.ByteString, SN.Handler b GameService ())] gameRoutes mongoHost mongoUser mongoPass mongoDb rulePath botsPath= [ ("/", method GET $ getPublicGamesList mongoHost mongoUser mongoPass mongoDb), ("/", method POST $ createGame mongoHost mongoUser mongoPass mongoDb rulePath), ("/rules", method GET $ getRules rulePath), ("/bots", method GET $ getBots botsPath), ("/:gameid", method GET $ getGameShortInfo mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/setmap", method POST $ sendMap mongoHost mongoUser mongoPass mongoDb rulePath), ("/:gameid/:session", method GET $ getStatus mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/invitebot", method POST $ inviteBot mongoHost mongoUser mongoPass mongoDb botsPath), ("/:gameid/:session/setpublic", method POST $ setPublic mongoHost mongoUser mongoPass mongoDb), ("/:gameid/connect/player", method POST $ connectGamePlayer mongoHost mongoUser mongoPass mongoDb), ("/:gameid/connect/guest", method POST $ connectGameGuest mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/shoot", method POST $ shoot mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/chat", method POST $ sendMessage mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/chat", method GET $ readMessages mongoHost mongoUser mongoPass mongoDb), ("/bots/:bot/games", method GET $ getBotsGamesList mongoHost mongoUser mongoPass mongoDb) ] ------------------------- -- Actions --------------------------- -- get list of opened -- sends nothing GET /api / games/ -- response list of {game id, messsge} 200 -- [ -- { " game " : { } , -- "owner": {name}, -- "message": {game message} -- }, -- ... -- ] -- 500 -- {message} getPublicGamesList :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getPublicGamesList mongoHost mongoUser mongoPass mongoDb = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" time <- liftIO $ round . (* 10000) <$> getPOSIXTime let action = rest =<< MQ.find (MQ.select ["date" =: ["$gte" =: time - gameTimeout], "public" =: True] "games") {MQ.sort = ["date" =: -1]} games <- a $ action writeLBS . encode $ fmap (\d -> PublicGame (BS.at "game" d) (BS.at "name" (BS.at "owner" d)) (BS.at "message" d) (BS.at "rules" d) (getTurn $ BS.at "turn" d)) games liftIO $ closeConnection pipe modifyResponse . setResponseCode $ 200 -- get list of games for bot -- sends bot id -- GET /api/games/bots/{botid}/games -- response list of {game id, messsge} 200 -- [ { } , -- ... -- ] -- 500 -- {message} getBotsGamesList :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getBotsGamesList mongoHost mongoUser mongoPass mongoDb = do pbotid <- getParam "bot" modifyResponse $ setHeader "Content-Type" "application/json" case pbotid of Just botid -> do let bid = B.unpack botid pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action time <- liftIO $ round . (* 10000) <$> getPOSIXTime let action = rest =<< MQ.find (MQ.select ["date" =: ["$gte" =: time - gameTimeout]] (T.pack $ "botgames_" ++ bid)) games <- a $ action writeLBS . encode $ fmap (\d -> (BS.at "game" d) :: String) games liftIO $ closeConnection pipe Nothing -> writeLBS . encode $ ([] :: [String]) modifyResponse . setResponseCode $ 200 ------------------------ -- get short game info -- send game id and session -- GET /api/games/{gameid} -- response short game info 200 -- { " game " : { } , -- "message": {message}, -- "owner": {name}, -- "rules": {rules} -- } 404 , 500 -- {message} getGameShortInfo :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getGameShortInfo mongoHost mongoUser mongoPass mongoDb = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" let game = case pgame of Just g -> B.unpack g Nothing -> "" rights <- liftIO $ fillRights pipe mongoDb game Nothing case rights of GameRights True _ _ turn _ _ _ rules (Just gameinfo) -> do let owner = BS.at "owner" gameinfo let ownername = BS.at "name" owner let message = (BS.at "message" gameinfo) modifyResponse . setResponseCode $ 200 writeLBS . encode $ PublicGame game ownername message rules turn _ -> do writeLBS . encode $ APIError "Game not found!" modifyResponse $ setResponseCode 404 liftIO $ closeConnection pipe ---------------------------- -- create game -- post username, message -- POST /api/games -- { -- "username": {username}, -- "message": {message}, -- "rules": {rules} -- } -- response new game id and session or error 201 -- { " game " : { } , -- "session": {session} -- } 400 , 500 -- {message} createGame :: Host -> Username -> Password -> Database -> FilePath -> SN.Handler b GameService () createGame mongoHost mongoUser mongoPass mongoDb rulePath = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" user <- fmap (\x -> decode x :: Maybe NewGameUser) $ readRequestBody 4096 case user of Just (NewGameUser name message rules) -> do gameId <- liftIO $ UUID.toString <$> nextRandom sessionId <- liftIO $ UUID.toString <$> nextRandom time <- liftIO $ round . (* 10000) <$> getPOSIXTime crules <- liftIO $ currentRulesId rules rulePath let game = [ "game" =: gameId, "date" =: time, "message" =: "", "owner" =: ["name" =: (take 20 name), "message" =: (take 140 message), "session" =: sessionId], "turn" =: ["notready"], "public" =: False, "rules" =: crules ] a $ MQ.insert "games" game writeLBS $ encode $ NewGame gameId sessionId crules modifyResponse $ setResponseCode 201 Nothing -> do writeLBS . encode $ APIError "Name and rules can't be empty!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe ----------------------- -- send map -- Map: -- 0 - empty 1 - ship 2 - miss - we do n't need it here 3 - hit - we do n't need it here -- post session id (owner and player can send map), json with map. Only empty or ship on map -- POST /api/games/{gameid}/{session}/setmap -- [[0,0,0,1,1,0,0...],[...],[...],...] -- response ok or error (wrong map or other) 202 -- "ok" 406 , 500 -- {message} sendMap :: Host -> Username -> Password -> Database -> FilePath -> SN.Handler b GameService () sendMap mongoHost mongoUser mongoPass mongoDb rulePath = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = B.unpack <$> session mbseamap <- fmap (\x -> decode x :: Maybe [[Int]]) $ readRequestBody 4096 case mbseamap of Just seamap -> do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action rights <- liftIO $ fillRights pipe mongoDb game msess let act user sm t = [( [ "game" =: game ]::Selector, [ "$set" =: [(T.pack $ user ++ ".map") =: sm], "$push" =: ["turn" =: t] ]::Document, [ ]::[UpdateOption] )] let chat n m= [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: m ]::Document let doit n u m t r = do myrules <- liftIO $ currentRules r rulePath case (isGood seamap myrules) of True -> do a $ MQ.updateAll "games" $ act u seamap t a $ MQ.insert "chats" $ chat n m writeLBS "ok" modifyResponse $ setResponseCode 200 _ -> do writeLBS . encode $ APIError "Check your ships!" modifyResponse $ setResponseCode 406 case rights of GameRights True True _ NOTREADY _ name _ rid _ -> do doit name "owner" "I've sent my map." "owner_map" rid GameRights True True _ NOTREADY_WITH_MAP _ name _ rid _ -> do doit name "owner" "I've sent a new map." "owner_map" rid GameRights True True _ CONFIG _ name _ rid _ -> do doit name "owner" "I've sent my map. Waiting for you!" "owner_map" rid GameRights True True _ CONFIG_WAIT_OWNER _ name _ rid _ -> do doit name "owner" "I've sent my map. Let's do this!" "owner_map" rid GameRights True True _ CONFIG_WAIT_PLAYER _ name _ rid _ -> do doit name "owner" "I've sent a new map. Waiting for you!" "owner_map" rid GameRights True _ True CONFIG _ name _ rid _ -> do doit name "player" "I've sent my map. Waiting for you!" "player_map" rid GameRights True _ True CONFIG_WAIT_OWNER _ name _ rid _ -> do doit name "player" "I've sent a new map. Waiting for you!" "player_map" rid GameRights True _ True CONFIG_WAIT_PLAYER _ name _ rid _ -> do doit name "player" "I've sent my map. Let's do this!" "player_map" rid _ -> do writeLBS . encode $ APIError "Can't send the map for this game or the game is not exists!" modifyResponse $ setResponseCode 403 liftIO $ closeConnection pipe Nothing -> do writeLBS . encode $ APIError "Can't find your map!" modifyResponse $ setResponseCode 404 ----------------------- -- get game status -- send game id and session -- GET /api/games/{gameid}/{session}/ -- response status (map contain only unknown or hit if game is not finished and everything if finished) or error 200 -- { " game " : { } , -- "message": {message}, -- "you": {owner|player|guest}, -- "turn": {owner|player|notready}, -- "owner": { -- "name": {name}, -- "message": {message}, -- "map": [[0,0,0,1,1,0,0...],[...],[...],...] -- }, -- "player": { -- "name": {name}, -- "message": {message}, -- "map": [[0,0,0,1,1,0,0...],[...],[...],...] -- }, -- "guests": [ -- { -- "name": {name}, -- "message": {message} -- } -- ] -- } 404 , 500 -- {message} getStatus :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getStatus mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" psession <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let session = case psession of Just s -> B.unpack s Nothing -> "" let msess = (B.unpack <$> psession) rights <- liftIO $ fillRights pipe mongoDb game msess let getGStatus you turn rules gameinfo isPublic = do let owner = BS.at "owner" gameinfo let ownername = BS.at "name" owner let ownermessage = BS.at "message" owner mbownermap <- try (BS.look "map" owner) :: IO (Either SomeException BS.Value) let ownermap = case mbownermap of Right (BS.Array m) -> [(case mbl of BS.Array l -> [(case mbc of BS.Int32 c -> head $ [c | c > 1 || you == "owner" || isGameFinished turn] ++ [0] _ -> 0) | mbc <- l] _ -> []) | mbl <- m] _ -> [] mbplayer <- try (BS.look "player" gameinfo) :: IO (Either SomeException BS.Value) playerobj <- liftIO $ case mbplayer of Right (BS.Doc player) -> do let playername = BS.at "name" player mbplayermap <- try (BS.look "map" player) :: IO (Either SomeException BS.Value) let playermap = case mbplayermap of Right (BS.Array m) -> [(case mbl of BS.Array l -> [(case mbc of BS.Int32 c -> head $ [c | c > 1 || you == "player" || isGameFinished turn] ++ [0] _ -> 0) | mbc <- l] _ -> []) | mbl <- m] _ -> [] let playermessage = BS.at "message" player return $ object [ "name" .= T.pack playername , "message" .= T.pack playermessage , "map" .= playermap ] _ -> return $ object [] mbguests <- try (BS.look "guests" gameinfo) :: IO (Either SomeException BS.Value) let guestsobj = case mbguests of Right (BS.Array guests) -> [(case mbguest of (BS.Doc guest) -> object [ "name" .= T.pack (BS.at "name" guest) , "message" .= T.pack (BS.at "message" guest) ] _ -> object []) | mbguest <- guests] _ -> [] let yourname = case you of "owner" -> ownername "player" -> BS.at "name" (BS.at "player" gameinfo) "guest" -> case mbguests of Right (BS.Array guests) -> head $ [n | [n,s] <- [(case mbguest of (BS.Doc guest) -> [BS.at "name" guest, BS.at "session" guest] _ -> ["",""]) | mbguest <- guests], s==session] _ -> "" let status = object [ "game" .= game , "message" .= T.pack (BS.at "message" gameinfo) , "you" .= you , "yourname" .= yourname , "rules" .= rules , "turn" .= turn , "owner" .= object [ "name" .= T.pack ownername , "message" .= T.pack ownermessage , "map" .= ownermap ] , "player" .= playerobj , "guests" .= guestsobj , "isPublic" .= isPublic ] return status case rights of GameRights True True False turn False _ isPublic rules (Just gameinfo) -> do status <- liftIO $ getGStatus "owner" turn rules gameinfo isPublic writeLBS . encode $ status modifyResponse . setResponseCode $ 200 GameRights True False True turn False _ isPublic rules (Just gameinfo) -> do status <- liftIO $ getGStatus "player" turn rules gameinfo isPublic writeLBS . encode $ status modifyResponse . setResponseCode $ 200 GameRights True False False turn True _ isPublic rules (Just gameinfo) -> do status <- liftIO $ getGStatus "guest" turn rules gameinfo isPublic writeLBS . encode $ status modifyResponse . setResponseCode $ 200 _ -> do writeLBS . encode $ APIError "Can't find the game or you shouldn't see this game's status!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe ---------------------------- -- invite bot -- post game id and session (only owner can invite strangers) and message -- POST /api/games/{gameid}/{session}/invitebot -- { -- "botname": {botname} -- } -- response success if added in list or error 200 -- "ok" 404 , 500 -- {error} inviteBot :: Host -> Username -> Password -> Database -> FilePath -> SN.Handler b GameService () inviteBot mongoHost mongoUser mongoPass mongoDb botsPath = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" botname <- fmap (\x -> decode x :: Maybe BotName) $ readRequestBody 4096 case botname of Just (BotName bn) -> do pgame <- getParam "gameid" psession <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = (B.unpack <$> psession) rights <- liftIO $ fillRights pipe mongoDb game msess let doit g d r = do bot <- liftIO $ botByName bn botsPath case (getBotIdIfCan bot r) of (Just bid) -> do let botgameSelector = MQ.Select (["game" =: game]::Selector) (T.pack $ "botgames_" ++ bid) let botgame = [ "game" =: game , "date" =: d ]::Document a $ MQ.upsert botgameSelector botgame writeLBS $ "ok" modifyResponse . setResponseCode $ 200 _ -> do writeLBS $ "This bot doesn't know these rules!" modifyResponse . setResponseCode $ 406 case rights of GameRights True True False NOTREADY False _ _ rules (Just gameinfo) -> do let gamedate = (BS.at "date" gameinfo) :: Int doit game gamedate rules GameRights True True False NOTREADY_WITH_MAP False _ _ rules (Just gameinfo) -> do let gamedate = (BS.at "date" gameinfo) :: Int doit game gamedate rules _ -> do writeLBS . encode $ APIError "Can't invite bot! Maybe you already invited it?" modifyResponse $ setResponseCode 406 _ -> do writeLBS . encode $ APIError "Can't find bot name!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe ---------------------------- -- invite stranger -- post game id and session (only owner can invite strangers) and message -- POST /api/games/{gameid}/{session}/setpublic -- { -- "message": {message} -- } -- response success if added in list or error 200 -- "ok" 404 , 500 -- {error} setPublic :: Host -> Username -> Password -> Database -> SN.Handler b GameService () setPublic mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" message <- fmap (\x -> decode x :: Maybe Message) $ readRequestBody 4096 case message of Just (Message msg) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = (B.unpack <$> session) rights <- liftIO $ fillRights pipe mongoDb game msess let doit n = do let act = [( [ "game" =: game ]::Selector, [ "$set" =: ["public" =: True, "message" =: (take 140 msg)] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: "Attention! The game is now public!" ]::Document a $ MQ.insert "chats" chat writeLBS "ok" modifyResponse . setResponseCode $ 200 case rights of GameRights True True _ NOTREADY _ name False _ _ -> do doit name GameRights True True _ NOTREADY_WITH_MAP _ name False _ _ -> do doit name _ -> do writeLBS . encode $ APIError "Can't make this game public!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Can't find message!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe --------------------------------- -- connect -- post game id, username, role (guest|player), short message -- POST /api/games/{gameid}/connect/{guest|player} -- { -- "name": "name", -- "message": "message" -- } -- response session, or error. 202 -- { -- "game": {game} -- "session": {session} -- } 404 , 403 , 400 , 500 -- {message} connectGamePlayer :: Host -> Username -> Password -> Database -> SN.Handler b GameService () connectGamePlayer mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" player <- fmap (\x -> decode x :: Maybe GameUser) $ readRequestBody 4096 case player of Just (GameUser name message) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" rights <- liftIO $ fillRights pipe mongoDb game Nothing let doit = do sessionId <- liftIO $ UUID.toString <$> nextRandom let act = [( [ "game" =: game ]::Selector, [ "$set" =: ["player" =: ["name" =: (take 20 name) , "message" =: (take 140 message) , "session" =: sessionId] ], "$push" =: ["turn" =: "player_join"] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: name , "session" =: sessionId , "time" =: time , "message" =: ("joined as a player!") ]::Document a $ MQ.insert "chats" chat writeLBS $ encode $ SessionInfo game sessionId modifyResponse . setResponseCode $ 200 case rights of GameRights True False False NOTREADY _ _ _ _ _ -> do doit GameRights True False False NOTREADY_WITH_MAP _ _ _ _ _ -> do doit _ -> do writeLBS . encode $ APIError "Can't connect as a player!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Name is required!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe connectGameGuest :: Host -> Username -> Password -> Database -> SN.Handler b GameService () connectGameGuest mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" player <- fmap (\x -> decode x :: Maybe GameUser) $ readRequestBody 4096 case player of Just (GameUser name message) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" rights <- liftIO $ fillRights pipe mongoDb game Nothing case rights of GameRights True _ _ _ _ _ _ _ _ -> do sessionId <- liftIO $ UUID.toString <$> nextRandom let act = [( [ "game" =: game ]::Selector, [ "$push" =: ["guests" =: ["name" =: (take 20 name) , "message" =: (take 140 message) , "session" =: sessionId] ] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: name , "session" =: sessionId , "time" =: time , "message" =: "joined as a guest!" ]::Document a $ MQ.insert "chats" chat writeLBS $ encode $ SessionInfo game sessionId modifyResponse . setResponseCode $ 200 _ -> do writeLBS . encode $ APIError "Can't connect as a guest!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Name is required!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe ------------------------------ -- shoot -- Map: -- 0 - empty 1 - ship 2 - miss 3 - hit -- post game id, session (only owner and player can shoot and only in ther turn) and coords -- POST /api/games/{gameid}/{session}/shoot -- { -- "x": {x}, -- "y": {y}, -- } -- response result (hit|miss|sink|win) or error 202 -- {hit|miss|sink|win} 404 , 403 , 400 , 500 -- {message} shoot :: Host -> Username -> Password -> Database -> SN.Handler b GameService () shoot mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" mbshot <- fmap (\x -> decode x :: Maybe Shot) $ readRequestBody 4096 case mbshot of Just shot -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = (B.unpack <$> session) rights <- liftIO $ fillRights pipe mongoDb game msess let doit n (Shot x y) enemy cell response turn = do let act = [( [ "game" =: game ]::Selector, [ "$set" =: [(T.pack . concat $ [enemy, ".map.", show x, ".", show y]) =: cell], "$push" =: ["turn" =: turn] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: (T.pack . concat $ [shotLabel x y, " - ", response]) ]::Document a $ MQ.insert "chats" chat writeLBS . encode $ response modifyResponse . setResponseCode $ 200 case rights of GameRights True True _ OWNER _ name _ _ (Just gameinfo) -> do let enemymap = (BS.at "map" (BS.at "player" gameinfo)) :: [[Int]] case isShotSane enemymap shot of True -> case getCell enemymap shot of 0 -> doit name shot "player" 2 "miss" "player" 1 -> case isSink enemymap shot of True -> case isWin enemymap of True -> doit name shot "player" 3 "WON" "finished" False -> doit name shot "player" 3 "sank" "owner" False -> doit name shot "player" 3 "hit" "owner" 2 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 3 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 otherwise -> do writeLBS . encode $ APIError "Wrong shot!" modifyResponse $ setResponseCode 406 GameRights True _ True PLAYER _ name _ _ (Just gameinfo) -> do let enemymap = (BS.at "map" (BS.at "owner" gameinfo)) :: [[Int]] case isShotSane enemymap shot of True -> case getCell enemymap shot of 0 -> doit name shot "owner" 2 "miss" "owner" 1 -> case isSink enemymap shot of True -> case isWin enemymap of True -> doit name shot "owner" 3 "WON" "finished" False -> doit name shot "owner" 3 "sank" "player" False -> doit name shot "owner" 3 "hit" "player" 2 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 3 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 otherwise -> do writeLBS . encode $ APIError "Wrong shot!" modifyResponse $ setResponseCode 406 _ -> do writeLBS . encode $ APIError "You can't shoot now!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Can't find coordinates!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe shotLabel:: Int -> Int -> String shotLabel x y = concat [take 1 . drop x $ "ABCDEFGHIJKLMNOPQRSTUVWXYZ", show . (+1) $ y] -------------------------- -- write message -- post game id, session, message -- POST /api/games/{gameid}/{session}/chat/ -- {message} -- response success or error 201 -- "ok" 404 , 403 , 400 , 500 -- { -- "error": {message} -- } sendMessage :: Host -> Username -> Password -> Database -> SN.Handler b GameService () sendMessage mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" mmessage <- fmap (\x -> decode x :: Maybe Message) $ readRequestBody 4096 case mmessage of Just (Message message) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = B.unpack <$> session rights <- liftIO $ fillRights pipe mongoDb game msess let chat n = [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: message ]::Document case rights of GameRights True True _ _ _ n _ _ _ -> do a $ MQ.insert "chats" $ chat n writeLBS "ok" modifyResponse . setResponseCode $ 201 GameRights True _ True _ _ n _ _ _ -> do a $ MQ.insert "chats" $ chat n writeLBS "ok" modifyResponse . setResponseCode $ 201 GameRights True _ _ _ True n _ _ _ -> do a $ MQ.insert "chats" $ chat n writeLBS "ok" modifyResponse . setResponseCode $ 201 _ -> do writeLBS . encode $ APIError "Can't write message here!" modifyResponse $ setResponseCode 403 _ -> do writeLBS . encode $ APIError "Can't find message!" modifyResponse $ setResponseCode 404 liftIO $ closeConnection pipe ------------------------------ -- read messages -- send game id, session, last check date(or nothing) -- GET /api/games/{gameid}/{session}/chat?lastcheck={date} -- response list of [{name, message, date}], last check date or error 200 -- [ -- { -- "name": {name}, -- "message": {message}, -- "date": {date} -- }, -- ... -- ] 404 , 500 -- {message} readMessages :: Host -> Username -> Password -> Database -> SN.Handler b GameService () readMessages mongoHost mongoUser mongoPass mongoDb = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" pltime <- getQueryParam "lastcheck" session <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = B.unpack <$> session let ltime = (read (case pltime of Just t -> B.unpack t Nothing -> "0")) :: Integer let action g t = rest =<< MQ.find (MQ.select ["time" =: ["$gt" =: t], "game" =: g] "chats") {MQ.sort = ["time" =: -1]} rights <- liftIO $ fillRights pipe mongoDb game msess case rights of GameRights True True _ _ _ _ _ _ _ -> do messages <- a $ action game ltime writeLBS . encode $ fmap (\m -> ChatMessage (BS.at "game" m) (BS.at "name" m) (BS.at "session" m) (BS.at "time" m) (BS.at "message" m)) messages modifyResponse . setResponseCode $ 200 GameRights True _ True _ _ _ _ _ _ -> do messages <- a $ action game ltime writeLBS . encode $ fmap (\m -> ChatMessage (BS.at "game" m) (BS.at "name" m) (BS.at "session" m) (BS.at "time" m) (BS.at "message" m)) messages modifyResponse . setResponseCode $ 200 GameRights True _ _ _ True _ _ _ _ -> do messages <- a $ action game ltime writeLBS . encode $ fmap (\m -> ChatMessage (BS.at "game" m) (BS.at "name" m) (BS.at "session" m) (BS.at "time" m) (BS.at "message" m)) messages modifyResponse . setResponseCode $ 200 _ -> do writeLBS . encode $ APIError "Can't read messages!" modifyResponse $ setResponseCode 403 liftIO $ closeConnection pipe ------------------------------ -- get rules list -- sends nothing -- GET /api/games/rules -- response rules list or error 200 -- [ -- { -- "id": {id} -- "name": {name}, -- "description": {text}, -- "rules": {ship set} -- } -- ] 404 , 403 , 400 , 500 -- {message} getRules :: FilePath -> SN.Handler b GameService () getRules rulePath = do rules <- liftIO $ (decodeFileStrict rulePath :: IO (Maybe [Rule])) case rules of Just r -> do writeLBS . encode $ r Nothing -> do writeLBS "[]" modifyResponse $ setHeader "Content-Type" "application/json" modifyResponse . setResponseCode $ 200 ------------------------------ -- get bots list -- sends nothing -- GET /api/games/bots -- response bots list or error 200 -- [ -- { -- "name": {name}, -- "rules": {rules list} -- } -- ] 404 , 403 , 400 , 500 -- {message} getBots :: FilePath -> SN.Handler b GameService () getBots botsPath = do bots <- liftIO $ (decodeFileStrict botsPath :: IO (Maybe [Bot])) case bots of Just b -> do writeLBS . encode $ b _ -> do writeLBS "[]" modifyResponse $ setHeader "Content-Type" "application/json" modifyResponse . setResponseCode $ 200 ---------------------- -- Game authentication fillRights :: Pipe -> Database -> String -> Maybe String -> IO GameRights fillRights pipe mongoDb game session = do let a action = liftIO $ performAction pipe mongoDb action time <- liftIO $ round . (* 10000) <$> getPOSIXTime game <- a $ MQ.findOne (MQ.select ["date" =: ["$gte" =: time - gameTimeout], "game" =: game] "games") let turn v = case v of Right (BS.Array l) -> getTurn $ map (\v -> case v of (BS.String s) -> T.unpack s _ -> "noop") l _ -> NOTREADY case game of Just g -> case session of Just sess -> do vturn <- try (BS.look "turn" g) :: IO (Either SomeException BS.Value) public <- try (BS.look "public" g) :: IO (Either SomeException BS.Value) let ispublic = case public of Right (BS.Bool p) -> p _ -> False owner <- try (BS.look "owner" g) :: IO (Either SomeException BS.Value) osess <- case owner of Right (BS.Doc d) -> BS.look "session" d _ -> return $ BS.Bool False let isowner = case osess of (BS.String s) -> (T.unpack s) == sess _ -> False player <- try (BS.look "player" g) :: IO (Either SomeException BS.Value) psess <- case player of Right (BS.Doc d) -> BS.look "session" d _ -> return $ BS.Bool False let isplayer = case psess of (BS.String s) -> (T.unpack s) == sess _ -> False guests <- try (BS.look "guests" g) :: IO (Either SomeException BS.Value) let isguest = case guests of Right (BS.Array ga) -> or $ fmap (\gt -> (case gt of (BS.Doc dg) -> (T.unpack (BS.at "session" dg)) == sess _ -> False)) ga _ -> False let uname = case isowner of True -> T.unpack $ BS.at "name" $ BS.at "owner" g False -> case isplayer of True -> T.unpack $ BS.at "name" $ BS.at "player" g False -> case isguest of True -> T.unpack $ BS.at "name" $ head $ filter (\x -> (BS.at "session" x) == sess) $ BS.at "guests" g False -> "" let rules = BS.at "rules" g return $ GameRights True isowner isplayer (turn vturn) isguest uname ispublic rules game Nothing -> do let rules = BS.at "rules" g vturn <- try (BS.look "turn" g) :: IO (Either SomeException BS.Value) return $ GameRights True False False (turn vturn) False "" False rules game Nothing -> return $ GameRights False False False NOTREADY False "" False "free" Nothing getTurn :: [String] -> Turn getTurn = getTurn' NOTREADY getTurn' :: Turn -> [String] -> Turn getTurn' t [] = t getTurn' t (x:xs) = getTurn' (changeTurn t x) xs changeTurn :: Turn -> String -> Turn changeTurn t s = case t of NOTREADY -> head $ [CONFIG | s == "player_join"] ++ [NOTREADY_WITH_MAP | s == "owner_map"] ++ [t] CONFIG -> head $ [CONFIG_WAIT_PLAYER | s == "owner_map"] ++ [CONFIG_WAIT_OWNER | s == "player_map"] ++ [t] NOTREADY_WITH_MAP -> head $ [CONFIG_WAIT_PLAYER | s == "player_join"] ++ [t] CONFIG_WAIT_PLAYER -> head $ [OWNER | s == "player_map"] ++ [t] CONFIG_WAIT_OWNER -> head $ [OWNER | s == "owner_map"] ++ [t] OWNER -> head $ [PLAYER | s == "player"] ++ [OWNER_WIN | s == "finished"] ++ [t] PLAYER -> head $ [OWNER | s == "owner"] ++ [PLAYER_WIN | s == "finished"] ++ [t] _ -> NOTREADY currentRulesId :: String -> FilePath -> IO String currentRulesId rules rulePath = do allrules <- liftIO $ (decodeFileStrict rulePath :: IO (Maybe [Rule])) case allrules of Just rs -> do return $ case (length $ filter (\(Rule rid _ _ _ _) -> rid == rules) rs) of 0 -> "free" _ -> rules Nothing -> return "free" currentRules :: String -> FilePath -> IO Rule currentRules rules rulePath = do allrules <- liftIO $ (decodeFileStrict rulePath :: IO (Maybe [Rule])) case allrules of Just rs -> do let myrules = filter (\(Rule rid _ _ _ _) -> rid == rules) rs return $ case (length $ myrules) of 0 -> Rule "free" "" "" [] 0 _ -> head myrules Nothing -> return $ Rule "free" "" "" [] 0 botByName :: String -> FilePath -> IO (Maybe Bot) botByName botName botsPath = do allbots <- liftIO $ (decodeFileStrict botsPath :: IO (Maybe [Bot])) case allbots of Just bs -> do return . head $ [Just b | b <- bs, case b of Bot bn _ _ -> bn == botName _ -> False] ++ [Nothing] _ -> do return Nothing getBotIdIfCan :: Maybe Bot -> String -> Maybe String getBotIdIfCan (Just (Bot _ bid rs)) r = head $ [Just bid | elem r rs] ++ [Nothing] getBotIdIfCan _ _ = Nothing ---------------------- -- Map checks -- For each rule: -- rules: text with description -- ships description: [ ( 1,4 ) , ( 2,3 ) , ( 3,2 ) , ( 4,1 ) ] -- in send map I need to check rules. To do it: get list of counts for separated non empty cells : [ 0,0,0,1,1,0,1,1,1,0 ] - > [ 2,3 ] -- get the same from transposed map -- get amount of twos, threes and so on. It should be as it is in the rules set. -- for ones amount should be sum of not-ones from another list plus amount of ones -- For test: -- Rules: [[1,2],[2,2],[3,1]] 1 0 1 0 1 1 1 1 0 1 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 1 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0 0 -- [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,0,1,1,0],[1,0,0,0,0]] [ [ 1,1,1,0,1],[0,0,0,0,0],[1,1,0,1,0],[0,0,0,1,0],[1,0,0,0,0 ] ] isGood :: [[Int]] -> Rule -> Bool isGood sm (Rule rid _ _ ships _) = (isSane sm) && (rid == "free" || (isShipsByRule sm ships) && (noDiagonalShips sm)) isSane :: [[Int]] -> Bool isSane m = (mapWidth == length m) && (and [l==mapHeight | l <- [length ra | ra <- m]]) isShipsByRule :: [[Int]] -> [[Int]] -> Bool isShipsByRule sm r = isProjectionByRule r (getProjection sm) (getProjection . transpose $ sm) ------------------------- -- getProjection [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,0,1,1,0],[1,0,0,0,0]] -- result:[1,1,1,1,1,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0] getProjection [ [ 1,1,1,0,1],[0,0,0,0,0],[1,1,0,1,0],[0,0,0,1,0],[1,0,0,0,0 ] ] -- result [3,1,0,0,0,0,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0] getProjection :: [[Int]] -> [Int] getProjection m = concat $ [foldr (\x (y:ys) -> case x of 0 -> [0] ++ (y:ys) _ -> (y+1:ys)) [0] $ l | l <- m] ---------------------------- -- isProjectionByRule [[1,2],[2,2],[3,1]] [1,1,1,1,1,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0] [3,1,0,0,0,0,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0] -- True isProjectionByRule :: [[Int]] -> [Int] -> [Int] -> Bool isProjectionByRule rs p pt = and [checkRule (head r) (head . tail $ r) | r <- rs] where checkRule d c = (head $ [c * 2 | d==1] ++ [c]) == (((length $ filter (d==) p) + (length $ filter (d==) pt)) - (head $ [(sum $ filter (1/=) p) + (sum $ filter (1/=) pt) | d==1] ++ [0])) ------------------------------ -- noDiagonalShips [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,0,1,1,0],[1,0,0,0,0]] -- True -- noDiagonalShips [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,1,1,0,0],[1,0,0,0,0]] -- False noDiagonalShips :: [[Int]] -> Bool noDiagonalShips sm = not $ isIntersected sm ((shiftUp [0]) . (shiftLeft 0) $ sm) || isIntersected sm ((shiftUp [0]) . (shiftRight 0) $ sm) || isIntersected sm ((shiftDown [0]) . (shiftLeft 0) $ sm) || isIntersected sm ((shiftDown [0]) . (shiftRight 0) $ sm) shiftUp :: a -> [a] -> [a] shiftUp z xs = tail xs ++ [z] shiftDown :: a -> [a] -> [a] shiftDown z xs = [z] ++ take (-1+length xs) xs shiftLeft :: a -> [[a]] -> [[a]] shiftLeft z xss = [shiftUp z xs | xs <- xss] shiftRight :: a -> [[a]] -> [[a]] shiftRight z xss = [shiftDown z xs | xs <- xss] isIntersected :: [[Int]] -> [[Int]] -> Bool isIntersected m1 m2 = or . concat $ [zipWith (\a b -> (a * b) > 0) x y | (x, y) <- zip m1 m2] --------------------------------- -- check shot isShotSane :: [[Int]] -> Shot -> Bool isShotSane sm (Shot x y) = length sm > x && ((drop y) $ sm !! x) /= [] getCell :: [[Int]] -> Shot -> Int getCell sm (Shot x y) = sm !! x !! y isSink :: [[Int]] -> Shot -> Bool isSink m (Shot x y) = (checkLine y $ m !! x) && (checkLine x $ (transpose m) !! y) checkLine :: Int -> [Int] -> Bool checkLine x xs = and $ (checkPartOfLine $ drop (x+1) $ xs) ++ (checkPartOfLine $ drop ((length xs) - x) $ (reverse xs)) checkPartOfLine :: [Int] -> [Bool] checkPartOfLine [] = [True] checkPartOfLine xs = map (3==) $ getWhile (\v -> v==1|| v==3) xs getWhile :: Ord a => (a -> Bool) -> [a] -> [a] getWhile _ [] = [] getWhile t (x:[]) = [x | t x] getWhile t (x:xs) | t x = [x] ++ getWhile t xs | otherwise = [] isWin :: [[Int]] -> Bool isWin sm = sum [sum [head $ [0 | c/=1] ++ [1] | c <- l] | l <- sm] == 1 isGameFinished :: Turn -> Bool isGameFinished PLAYER_WIN = True isGameFinished OWNER_WIN = True isGameFinished _ = False ---------------------- -- MongoDB functions connectAndAuth :: Host -> Username -> Password -> Database -> IO Pipe connectAndAuth mongoHost mongoUser mongoPass mongoDb = do pipe <- connect mongoHost access pipe master mongoDb $ auth mongoUser mongoPass return pipe performAction :: Pipe -> Database -> Action IO a -> IO a performAction pipe mongoDb action = access pipe master mongoDb action closeConnection :: Pipe -> IO () closeConnection pipe = close pipe ---------------------- -- Initialization gameServiceInit :: String -> String -> String -> String -> String -> String -> SnapletInit b GameService gameServiceInit mongoHost mongoUser mongoPass mongoDb rulePath botsPath = makeSnaplet "game" "Battleship Service" Nothing $ do addRoutes $ gameRoutes (readHostPort mongoHost) (T.pack mongoUser) (T.pack mongoPass) (T.pack mongoDb) rulePath botsPath return $ GameService
null
https://raw.githubusercontent.com/DKurilo/battleship/09e30547a209ffc12f9a9668ebdca489a0a3adfc/server/src/Api/Services/GameService.hs
haskell
# LANGUAGE OverloadedStrings # ------------------- Routes ----------------------- Actions ------------------------- get list of opened sends nothing response list of {game id, messsge} [ { "owner": {name}, "message": {game message} }, ... ] 500 {message} get list of games for bot sends bot id GET /api/games/bots/{botid}/games response list of {game id, messsge} [ ... ] 500 {message} ---------------------- get short game info send game id and session GET /api/games/{gameid} response short game info { "message": {message}, "owner": {name}, "rules": {rules} } {message} -------------------------- create game post username, message POST /api/games { "username": {username}, "message": {message}, "rules": {rules} } response new game id and session or error { "session": {session} } {message} --------------------- send map Map: 0 - empty post session id (owner and player can send map), json with map. Only empty or ship on map POST /api/games/{gameid}/{session}/setmap [[0,0,0,1,1,0,0...],[...],[...],...] response ok or error (wrong map or other) "ok" {message} --------------------- get game status send game id and session GET /api/games/{gameid}/{session}/ response status (map contain only unknown or hit if game is not finished and everything if finished) or error { "message": {message}, "you": {owner|player|guest}, "turn": {owner|player|notready}, "owner": { "name": {name}, "message": {message}, "map": [[0,0,0,1,1,0,0...],[...],[...],...] }, "player": { "name": {name}, "message": {message}, "map": [[0,0,0,1,1,0,0...],[...],[...],...] }, "guests": [ { "name": {name}, "message": {message} } ] } {message} -------------------------- invite bot post game id and session (only owner can invite strangers) and message POST /api/games/{gameid}/{session}/invitebot { "botname": {botname} } response success if added in list or error "ok" {error} -------------------------- invite stranger post game id and session (only owner can invite strangers) and message POST /api/games/{gameid}/{session}/setpublic { "message": {message} } response success if added in list or error "ok" {error} ------------------------------- connect post game id, username, role (guest|player), short message POST /api/games/{gameid}/connect/{guest|player} { "name": "name", "message": "message" } response session, or error. { "game": {game} "session": {session} } {message} ---------------------------- shoot Map: 0 - empty post game id, session (only owner and player can shoot and only in ther turn) and coords POST /api/games/{gameid}/{session}/shoot { "x": {x}, "y": {y}, } response result (hit|miss|sink|win) or error {hit|miss|sink|win} {message} ------------------------ write message post game id, session, message POST /api/games/{gameid}/{session}/chat/ {message} response success or error "ok" { "error": {message} } ---------------------------- read messages send game id, session, last check date(or nothing) GET /api/games/{gameid}/{session}/chat?lastcheck={date} response list of [{name, message, date}], last check date or error [ { "name": {name}, "message": {message}, "date": {date} }, ... ] {message} ---------------------------- get rules list sends nothing GET /api/games/rules response rules list or error [ { "id": {id} "name": {name}, "description": {text}, "rules": {ship set} } ] {message} ---------------------------- get bots list sends nothing GET /api/games/bots response bots list or error [ { "name": {name}, "rules": {rules list} } ] {message} -------------------- Game authentication -------------------- Map checks For each rule: rules: text with description ships description: in send map I need to check rules. To do it: get the same from transposed map get amount of twos, threes and so on. It should be as it is in the rules set. for ones amount should be sum of not-ones from another list plus amount of ones For test: Rules: [[1,2],[2,2],[3,1]] [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,0,1,1,0],[1,0,0,0,0]] ----------------------- getProjection [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,0,1,1,0],[1,0,0,0,0]] result:[1,1,1,1,1,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0] result [3,1,0,0,0,0,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0] -------------------------- isProjectionByRule [[1,2],[2,2],[3,1]] [1,1,1,1,1,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0] [3,1,0,0,0,0,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0] True ---------------------------- noDiagonalShips [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,0,1,1,0],[1,0,0,0,0]] True noDiagonalShips [[1,0,1,0,1],[1,0,1,0,0],[1,0,0,0,0],[0,1,1,0,0],[1,0,0,0,0]] False ------------------------------- check shot -------------------- MongoDB functions -------------------- Initialization
# LANGUAGE ExtendedDefaultRules # # LANGUAGE TemplateHaskell # # LANGUAGE FlexibleInstances # # LANGUAGE DeriveGeneric # module Api.Services.GameService where import Control.Exception import Control.Monad import Control.Monad.IO.Class import Database.MongoDB import Database.MongoDB.Query as MQ import Database.MongoDB.Connection import Data.Bson as BS import Api.Types import qualified Control.Lens as CL import Control.Monad.State.Class import Data.List as DL import Data.Aeson as DA import Data.UUID as UUID import Data.UUID.V4 import Snap.Core import Snap.Snaplet as SN import qualified Data.ByteString.Char8 as B import qualified Data.Text as T import qualified Data.Text.IO as TIO import Data.Text.Encoding import Data.Time.Clock.POSIX data GameService = GameService { } CL.makeLenses ''GameService gameTimeout :: Int gameTimeout = 3600 * 10000 mapWidth :: Int mapWidth = 10 mapHeight :: Int mapHeight = 10 gameRoutes :: Host -> Username -> Password -> Database -> FilePath -> FilePath -> [(B.ByteString, SN.Handler b GameService ())] gameRoutes mongoHost mongoUser mongoPass mongoDb rulePath botsPath= [ ("/", method GET $ getPublicGamesList mongoHost mongoUser mongoPass mongoDb), ("/", method POST $ createGame mongoHost mongoUser mongoPass mongoDb rulePath), ("/rules", method GET $ getRules rulePath), ("/bots", method GET $ getBots botsPath), ("/:gameid", method GET $ getGameShortInfo mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/setmap", method POST $ sendMap mongoHost mongoUser mongoPass mongoDb rulePath), ("/:gameid/:session", method GET $ getStatus mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/invitebot", method POST $ inviteBot mongoHost mongoUser mongoPass mongoDb botsPath), ("/:gameid/:session/setpublic", method POST $ setPublic mongoHost mongoUser mongoPass mongoDb), ("/:gameid/connect/player", method POST $ connectGamePlayer mongoHost mongoUser mongoPass mongoDb), ("/:gameid/connect/guest", method POST $ connectGameGuest mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/shoot", method POST $ shoot mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/chat", method POST $ sendMessage mongoHost mongoUser mongoPass mongoDb), ("/:gameid/:session/chat", method GET $ readMessages mongoHost mongoUser mongoPass mongoDb), ("/bots/:bot/games", method GET $ getBotsGamesList mongoHost mongoUser mongoPass mongoDb) ] GET /api / games/ 200 " game " : { } , getPublicGamesList :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getPublicGamesList mongoHost mongoUser mongoPass mongoDb = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" time <- liftIO $ round . (* 10000) <$> getPOSIXTime let action = rest =<< MQ.find (MQ.select ["date" =: ["$gte" =: time - gameTimeout], "public" =: True] "games") {MQ.sort = ["date" =: -1]} games <- a $ action writeLBS . encode $ fmap (\d -> PublicGame (BS.at "game" d) (BS.at "name" (BS.at "owner" d)) (BS.at "message" d) (BS.at "rules" d) (getTurn $ BS.at "turn" d)) games liftIO $ closeConnection pipe modifyResponse . setResponseCode $ 200 200 { } , getBotsGamesList :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getBotsGamesList mongoHost mongoUser mongoPass mongoDb = do pbotid <- getParam "bot" modifyResponse $ setHeader "Content-Type" "application/json" case pbotid of Just botid -> do let bid = B.unpack botid pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action time <- liftIO $ round . (* 10000) <$> getPOSIXTime let action = rest =<< MQ.find (MQ.select ["date" =: ["$gte" =: time - gameTimeout]] (T.pack $ "botgames_" ++ bid)) games <- a $ action writeLBS . encode $ fmap (\d -> (BS.at "game" d) :: String) games liftIO $ closeConnection pipe Nothing -> writeLBS . encode $ ([] :: [String]) modifyResponse . setResponseCode $ 200 200 " game " : { } , 404 , 500 getGameShortInfo :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getGameShortInfo mongoHost mongoUser mongoPass mongoDb = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" let game = case pgame of Just g -> B.unpack g Nothing -> "" rights <- liftIO $ fillRights pipe mongoDb game Nothing case rights of GameRights True _ _ turn _ _ _ rules (Just gameinfo) -> do let owner = BS.at "owner" gameinfo let ownername = BS.at "name" owner let message = (BS.at "message" gameinfo) modifyResponse . setResponseCode $ 200 writeLBS . encode $ PublicGame game ownername message rules turn _ -> do writeLBS . encode $ APIError "Game not found!" modifyResponse $ setResponseCode 404 liftIO $ closeConnection pipe 201 " game " : { } , 400 , 500 createGame :: Host -> Username -> Password -> Database -> FilePath -> SN.Handler b GameService () createGame mongoHost mongoUser mongoPass mongoDb rulePath = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" user <- fmap (\x -> decode x :: Maybe NewGameUser) $ readRequestBody 4096 case user of Just (NewGameUser name message rules) -> do gameId <- liftIO $ UUID.toString <$> nextRandom sessionId <- liftIO $ UUID.toString <$> nextRandom time <- liftIO $ round . (* 10000) <$> getPOSIXTime crules <- liftIO $ currentRulesId rules rulePath let game = [ "game" =: gameId, "date" =: time, "message" =: "", "owner" =: ["name" =: (take 20 name), "message" =: (take 140 message), "session" =: sessionId], "turn" =: ["notready"], "public" =: False, "rules" =: crules ] a $ MQ.insert "games" game writeLBS $ encode $ NewGame gameId sessionId crules modifyResponse $ setResponseCode 201 Nothing -> do writeLBS . encode $ APIError "Name and rules can't be empty!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe 1 - ship 2 - miss - we do n't need it here 3 - hit - we do n't need it here 202 406 , 500 sendMap :: Host -> Username -> Password -> Database -> FilePath -> SN.Handler b GameService () sendMap mongoHost mongoUser mongoPass mongoDb rulePath = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = B.unpack <$> session mbseamap <- fmap (\x -> decode x :: Maybe [[Int]]) $ readRequestBody 4096 case mbseamap of Just seamap -> do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action rights <- liftIO $ fillRights pipe mongoDb game msess let act user sm t = [( [ "game" =: game ]::Selector, [ "$set" =: [(T.pack $ user ++ ".map") =: sm], "$push" =: ["turn" =: t] ]::Document, [ ]::[UpdateOption] )] let chat n m= [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: m ]::Document let doit n u m t r = do myrules <- liftIO $ currentRules r rulePath case (isGood seamap myrules) of True -> do a $ MQ.updateAll "games" $ act u seamap t a $ MQ.insert "chats" $ chat n m writeLBS "ok" modifyResponse $ setResponseCode 200 _ -> do writeLBS . encode $ APIError "Check your ships!" modifyResponse $ setResponseCode 406 case rights of GameRights True True _ NOTREADY _ name _ rid _ -> do doit name "owner" "I've sent my map." "owner_map" rid GameRights True True _ NOTREADY_WITH_MAP _ name _ rid _ -> do doit name "owner" "I've sent a new map." "owner_map" rid GameRights True True _ CONFIG _ name _ rid _ -> do doit name "owner" "I've sent my map. Waiting for you!" "owner_map" rid GameRights True True _ CONFIG_WAIT_OWNER _ name _ rid _ -> do doit name "owner" "I've sent my map. Let's do this!" "owner_map" rid GameRights True True _ CONFIG_WAIT_PLAYER _ name _ rid _ -> do doit name "owner" "I've sent a new map. Waiting for you!" "owner_map" rid GameRights True _ True CONFIG _ name _ rid _ -> do doit name "player" "I've sent my map. Waiting for you!" "player_map" rid GameRights True _ True CONFIG_WAIT_OWNER _ name _ rid _ -> do doit name "player" "I've sent a new map. Waiting for you!" "player_map" rid GameRights True _ True CONFIG_WAIT_PLAYER _ name _ rid _ -> do doit name "player" "I've sent my map. Let's do this!" "player_map" rid _ -> do writeLBS . encode $ APIError "Can't send the map for this game or the game is not exists!" modifyResponse $ setResponseCode 403 liftIO $ closeConnection pipe Nothing -> do writeLBS . encode $ APIError "Can't find your map!" modifyResponse $ setResponseCode 404 200 " game " : { } , 404 , 500 getStatus :: Host -> Username -> Password -> Database -> SN.Handler b GameService () getStatus mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" psession <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let session = case psession of Just s -> B.unpack s Nothing -> "" let msess = (B.unpack <$> psession) rights <- liftIO $ fillRights pipe mongoDb game msess let getGStatus you turn rules gameinfo isPublic = do let owner = BS.at "owner" gameinfo let ownername = BS.at "name" owner let ownermessage = BS.at "message" owner mbownermap <- try (BS.look "map" owner) :: IO (Either SomeException BS.Value) let ownermap = case mbownermap of Right (BS.Array m) -> [(case mbl of BS.Array l -> [(case mbc of BS.Int32 c -> head $ [c | c > 1 || you == "owner" || isGameFinished turn] ++ [0] _ -> 0) | mbc <- l] _ -> []) | mbl <- m] _ -> [] mbplayer <- try (BS.look "player" gameinfo) :: IO (Either SomeException BS.Value) playerobj <- liftIO $ case mbplayer of Right (BS.Doc player) -> do let playername = BS.at "name" player mbplayermap <- try (BS.look "map" player) :: IO (Either SomeException BS.Value) let playermap = case mbplayermap of Right (BS.Array m) -> [(case mbl of BS.Array l -> [(case mbc of BS.Int32 c -> head $ [c | c > 1 || you == "player" || isGameFinished turn] ++ [0] _ -> 0) | mbc <- l] _ -> []) | mbl <- m] _ -> [] let playermessage = BS.at "message" player return $ object [ "name" .= T.pack playername , "message" .= T.pack playermessage , "map" .= playermap ] _ -> return $ object [] mbguests <- try (BS.look "guests" gameinfo) :: IO (Either SomeException BS.Value) let guestsobj = case mbguests of Right (BS.Array guests) -> [(case mbguest of (BS.Doc guest) -> object [ "name" .= T.pack (BS.at "name" guest) , "message" .= T.pack (BS.at "message" guest) ] _ -> object []) | mbguest <- guests] _ -> [] let yourname = case you of "owner" -> ownername "player" -> BS.at "name" (BS.at "player" gameinfo) "guest" -> case mbguests of Right (BS.Array guests) -> head $ [n | [n,s] <- [(case mbguest of (BS.Doc guest) -> [BS.at "name" guest, BS.at "session" guest] _ -> ["",""]) | mbguest <- guests], s==session] _ -> "" let status = object [ "game" .= game , "message" .= T.pack (BS.at "message" gameinfo) , "you" .= you , "yourname" .= yourname , "rules" .= rules , "turn" .= turn , "owner" .= object [ "name" .= T.pack ownername , "message" .= T.pack ownermessage , "map" .= ownermap ] , "player" .= playerobj , "guests" .= guestsobj , "isPublic" .= isPublic ] return status case rights of GameRights True True False turn False _ isPublic rules (Just gameinfo) -> do status <- liftIO $ getGStatus "owner" turn rules gameinfo isPublic writeLBS . encode $ status modifyResponse . setResponseCode $ 200 GameRights True False True turn False _ isPublic rules (Just gameinfo) -> do status <- liftIO $ getGStatus "player" turn rules gameinfo isPublic writeLBS . encode $ status modifyResponse . setResponseCode $ 200 GameRights True False False turn True _ isPublic rules (Just gameinfo) -> do status <- liftIO $ getGStatus "guest" turn rules gameinfo isPublic writeLBS . encode $ status modifyResponse . setResponseCode $ 200 _ -> do writeLBS . encode $ APIError "Can't find the game or you shouldn't see this game's status!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe 200 404 , 500 inviteBot :: Host -> Username -> Password -> Database -> FilePath -> SN.Handler b GameService () inviteBot mongoHost mongoUser mongoPass mongoDb botsPath = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" botname <- fmap (\x -> decode x :: Maybe BotName) $ readRequestBody 4096 case botname of Just (BotName bn) -> do pgame <- getParam "gameid" psession <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = (B.unpack <$> psession) rights <- liftIO $ fillRights pipe mongoDb game msess let doit g d r = do bot <- liftIO $ botByName bn botsPath case (getBotIdIfCan bot r) of (Just bid) -> do let botgameSelector = MQ.Select (["game" =: game]::Selector) (T.pack $ "botgames_" ++ bid) let botgame = [ "game" =: game , "date" =: d ]::Document a $ MQ.upsert botgameSelector botgame writeLBS $ "ok" modifyResponse . setResponseCode $ 200 _ -> do writeLBS $ "This bot doesn't know these rules!" modifyResponse . setResponseCode $ 406 case rights of GameRights True True False NOTREADY False _ _ rules (Just gameinfo) -> do let gamedate = (BS.at "date" gameinfo) :: Int doit game gamedate rules GameRights True True False NOTREADY_WITH_MAP False _ _ rules (Just gameinfo) -> do let gamedate = (BS.at "date" gameinfo) :: Int doit game gamedate rules _ -> do writeLBS . encode $ APIError "Can't invite bot! Maybe you already invited it?" modifyResponse $ setResponseCode 406 _ -> do writeLBS . encode $ APIError "Can't find bot name!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe 200 404 , 500 setPublic :: Host -> Username -> Password -> Database -> SN.Handler b GameService () setPublic mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" message <- fmap (\x -> decode x :: Maybe Message) $ readRequestBody 4096 case message of Just (Message msg) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = (B.unpack <$> session) rights <- liftIO $ fillRights pipe mongoDb game msess let doit n = do let act = [( [ "game" =: game ]::Selector, [ "$set" =: ["public" =: True, "message" =: (take 140 msg)] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: "Attention! The game is now public!" ]::Document a $ MQ.insert "chats" chat writeLBS "ok" modifyResponse . setResponseCode $ 200 case rights of GameRights True True _ NOTREADY _ name False _ _ -> do doit name GameRights True True _ NOTREADY_WITH_MAP _ name False _ _ -> do doit name _ -> do writeLBS . encode $ APIError "Can't make this game public!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Can't find message!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe 202 404 , 403 , 400 , 500 connectGamePlayer :: Host -> Username -> Password -> Database -> SN.Handler b GameService () connectGamePlayer mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" player <- fmap (\x -> decode x :: Maybe GameUser) $ readRequestBody 4096 case player of Just (GameUser name message) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" rights <- liftIO $ fillRights pipe mongoDb game Nothing let doit = do sessionId <- liftIO $ UUID.toString <$> nextRandom let act = [( [ "game" =: game ]::Selector, [ "$set" =: ["player" =: ["name" =: (take 20 name) , "message" =: (take 140 message) , "session" =: sessionId] ], "$push" =: ["turn" =: "player_join"] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: name , "session" =: sessionId , "time" =: time , "message" =: ("joined as a player!") ]::Document a $ MQ.insert "chats" chat writeLBS $ encode $ SessionInfo game sessionId modifyResponse . setResponseCode $ 200 case rights of GameRights True False False NOTREADY _ _ _ _ _ -> do doit GameRights True False False NOTREADY_WITH_MAP _ _ _ _ _ -> do doit _ -> do writeLBS . encode $ APIError "Can't connect as a player!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Name is required!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe connectGameGuest :: Host -> Username -> Password -> Database -> SN.Handler b GameService () connectGameGuest mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" player <- fmap (\x -> decode x :: Maybe GameUser) $ readRequestBody 4096 case player of Just (GameUser name message) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" rights <- liftIO $ fillRights pipe mongoDb game Nothing case rights of GameRights True _ _ _ _ _ _ _ _ -> do sessionId <- liftIO $ UUID.toString <$> nextRandom let act = [( [ "game" =: game ]::Selector, [ "$push" =: ["guests" =: ["name" =: (take 20 name) , "message" =: (take 140 message) , "session" =: sessionId] ] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: name , "session" =: sessionId , "time" =: time , "message" =: "joined as a guest!" ]::Document a $ MQ.insert "chats" chat writeLBS $ encode $ SessionInfo game sessionId modifyResponse . setResponseCode $ 200 _ -> do writeLBS . encode $ APIError "Can't connect as a guest!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Name is required!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe 1 - ship 2 - miss 3 - hit 202 404 , 403 , 400 , 500 shoot :: Host -> Username -> Password -> Database -> SN.Handler b GameService () shoot mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" mbshot <- fmap (\x -> decode x :: Maybe Shot) $ readRequestBody 4096 case mbshot of Just shot -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = (B.unpack <$> session) rights <- liftIO $ fillRights pipe mongoDb game msess let doit n (Shot x y) enemy cell response turn = do let act = [( [ "game" =: game ]::Selector, [ "$set" =: [(T.pack . concat $ [enemy, ".map.", show x, ".", show y]) =: cell], "$push" =: ["turn" =: turn] ]::Document, [ ]::[UpdateOption] )] a $ MQ.updateAll "games" act let chat = [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: (T.pack . concat $ [shotLabel x y, " - ", response]) ]::Document a $ MQ.insert "chats" chat writeLBS . encode $ response modifyResponse . setResponseCode $ 200 case rights of GameRights True True _ OWNER _ name _ _ (Just gameinfo) -> do let enemymap = (BS.at "map" (BS.at "player" gameinfo)) :: [[Int]] case isShotSane enemymap shot of True -> case getCell enemymap shot of 0 -> doit name shot "player" 2 "miss" "player" 1 -> case isSink enemymap shot of True -> case isWin enemymap of True -> doit name shot "player" 3 "WON" "finished" False -> doit name shot "player" 3 "sank" "owner" False -> doit name shot "player" 3 "hit" "owner" 2 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 3 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 otherwise -> do writeLBS . encode $ APIError "Wrong shot!" modifyResponse $ setResponseCode 406 GameRights True _ True PLAYER _ name _ _ (Just gameinfo) -> do let enemymap = (BS.at "map" (BS.at "owner" gameinfo)) :: [[Int]] case isShotSane enemymap shot of True -> case getCell enemymap shot of 0 -> doit name shot "owner" 2 "miss" "owner" 1 -> case isSink enemymap shot of True -> case isWin enemymap of True -> doit name shot "owner" 3 "WON" "finished" False -> doit name shot "owner" 3 "sank" "player" False -> doit name shot "owner" 3 "hit" "player" 2 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 3 -> do writeLBS . encode $ APIError "You already shot here!" modifyResponse $ setResponseCode 406 otherwise -> do writeLBS . encode $ APIError "Wrong shot!" modifyResponse $ setResponseCode 406 _ -> do writeLBS . encode $ APIError "You can't shoot now!" modifyResponse $ setResponseCode 400 _ -> do writeLBS . encode $ APIError "Can't find coordinates!" modifyResponse $ setResponseCode 400 liftIO $ closeConnection pipe shotLabel:: Int -> Int -> String shotLabel x y = concat [take 1 . drop x $ "ABCDEFGHIJKLMNOPQRSTUVWXYZ", show . (+1) $ y] 201 404 , 403 , 400 , 500 sendMessage :: Host -> Username -> Password -> Database -> SN.Handler b GameService () sendMessage mongoHost mongoUser mongoPass mongoDb = do time <- liftIO $ round . (* 10000) <$> getPOSIXTime pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" session <- getParam "session" mmessage <- fmap (\x -> decode x :: Maybe Message) $ readRequestBody 4096 case mmessage of Just (Message message) -> do let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = B.unpack <$> session rights <- liftIO $ fillRights pipe mongoDb game msess let chat n = [ "game" =: game , "name" =: n , "session" =: msess , "time" =: time , "message" =: message ]::Document case rights of GameRights True True _ _ _ n _ _ _ -> do a $ MQ.insert "chats" $ chat n writeLBS "ok" modifyResponse . setResponseCode $ 201 GameRights True _ True _ _ n _ _ _ -> do a $ MQ.insert "chats" $ chat n writeLBS "ok" modifyResponse . setResponseCode $ 201 GameRights True _ _ _ True n _ _ _ -> do a $ MQ.insert "chats" $ chat n writeLBS "ok" modifyResponse . setResponseCode $ 201 _ -> do writeLBS . encode $ APIError "Can't write message here!" modifyResponse $ setResponseCode 403 _ -> do writeLBS . encode $ APIError "Can't find message!" modifyResponse $ setResponseCode 404 liftIO $ closeConnection pipe 200 404 , 500 readMessages :: Host -> Username -> Password -> Database -> SN.Handler b GameService () readMessages mongoHost mongoUser mongoPass mongoDb = do pipe <- liftIO $ connectAndAuth mongoHost mongoUser mongoPass mongoDb let a action = liftIO $ performAction pipe mongoDb action modifyResponse $ setHeader "Content-Type" "application/json" pgame <- getParam "gameid" pltime <- getQueryParam "lastcheck" session <- getParam "session" let game = case pgame of Just g -> B.unpack g Nothing -> "" let msess = B.unpack <$> session let ltime = (read (case pltime of Just t -> B.unpack t Nothing -> "0")) :: Integer let action g t = rest =<< MQ.find (MQ.select ["time" =: ["$gt" =: t], "game" =: g] "chats") {MQ.sort = ["time" =: -1]} rights <- liftIO $ fillRights pipe mongoDb game msess case rights of GameRights True True _ _ _ _ _ _ _ -> do messages <- a $ action game ltime writeLBS . encode $ fmap (\m -> ChatMessage (BS.at "game" m) (BS.at "name" m) (BS.at "session" m) (BS.at "time" m) (BS.at "message" m)) messages modifyResponse . setResponseCode $ 200 GameRights True _ True _ _ _ _ _ _ -> do messages <- a $ action game ltime writeLBS . encode $ fmap (\m -> ChatMessage (BS.at "game" m) (BS.at "name" m) (BS.at "session" m) (BS.at "time" m) (BS.at "message" m)) messages modifyResponse . setResponseCode $ 200 GameRights True _ _ _ True _ _ _ _ -> do messages <- a $ action game ltime writeLBS . encode $ fmap (\m -> ChatMessage (BS.at "game" m) (BS.at "name" m) (BS.at "session" m) (BS.at "time" m) (BS.at "message" m)) messages modifyResponse . setResponseCode $ 200 _ -> do writeLBS . encode $ APIError "Can't read messages!" modifyResponse $ setResponseCode 403 liftIO $ closeConnection pipe 200 404 , 403 , 400 , 500 getRules :: FilePath -> SN.Handler b GameService () getRules rulePath = do rules <- liftIO $ (decodeFileStrict rulePath :: IO (Maybe [Rule])) case rules of Just r -> do writeLBS . encode $ r Nothing -> do writeLBS "[]" modifyResponse $ setHeader "Content-Type" "application/json" modifyResponse . setResponseCode $ 200 200 404 , 403 , 400 , 500 getBots :: FilePath -> SN.Handler b GameService () getBots botsPath = do bots <- liftIO $ (decodeFileStrict botsPath :: IO (Maybe [Bot])) case bots of Just b -> do writeLBS . encode $ b _ -> do writeLBS "[]" modifyResponse $ setHeader "Content-Type" "application/json" modifyResponse . setResponseCode $ 200 fillRights :: Pipe -> Database -> String -> Maybe String -> IO GameRights fillRights pipe mongoDb game session = do let a action = liftIO $ performAction pipe mongoDb action time <- liftIO $ round . (* 10000) <$> getPOSIXTime game <- a $ MQ.findOne (MQ.select ["date" =: ["$gte" =: time - gameTimeout], "game" =: game] "games") let turn v = case v of Right (BS.Array l) -> getTurn $ map (\v -> case v of (BS.String s) -> T.unpack s _ -> "noop") l _ -> NOTREADY case game of Just g -> case session of Just sess -> do vturn <- try (BS.look "turn" g) :: IO (Either SomeException BS.Value) public <- try (BS.look "public" g) :: IO (Either SomeException BS.Value) let ispublic = case public of Right (BS.Bool p) -> p _ -> False owner <- try (BS.look "owner" g) :: IO (Either SomeException BS.Value) osess <- case owner of Right (BS.Doc d) -> BS.look "session" d _ -> return $ BS.Bool False let isowner = case osess of (BS.String s) -> (T.unpack s) == sess _ -> False player <- try (BS.look "player" g) :: IO (Either SomeException BS.Value) psess <- case player of Right (BS.Doc d) -> BS.look "session" d _ -> return $ BS.Bool False let isplayer = case psess of (BS.String s) -> (T.unpack s) == sess _ -> False guests <- try (BS.look "guests" g) :: IO (Either SomeException BS.Value) let isguest = case guests of Right (BS.Array ga) -> or $ fmap (\gt -> (case gt of (BS.Doc dg) -> (T.unpack (BS.at "session" dg)) == sess _ -> False)) ga _ -> False let uname = case isowner of True -> T.unpack $ BS.at "name" $ BS.at "owner" g False -> case isplayer of True -> T.unpack $ BS.at "name" $ BS.at "player" g False -> case isguest of True -> T.unpack $ BS.at "name" $ head $ filter (\x -> (BS.at "session" x) == sess) $ BS.at "guests" g False -> "" let rules = BS.at "rules" g return $ GameRights True isowner isplayer (turn vturn) isguest uname ispublic rules game Nothing -> do let rules = BS.at "rules" g vturn <- try (BS.look "turn" g) :: IO (Either SomeException BS.Value) return $ GameRights True False False (turn vturn) False "" False rules game Nothing -> return $ GameRights False False False NOTREADY False "" False "free" Nothing getTurn :: [String] -> Turn getTurn = getTurn' NOTREADY getTurn' :: Turn -> [String] -> Turn getTurn' t [] = t getTurn' t (x:xs) = getTurn' (changeTurn t x) xs changeTurn :: Turn -> String -> Turn changeTurn t s = case t of NOTREADY -> head $ [CONFIG | s == "player_join"] ++ [NOTREADY_WITH_MAP | s == "owner_map"] ++ [t] CONFIG -> head $ [CONFIG_WAIT_PLAYER | s == "owner_map"] ++ [CONFIG_WAIT_OWNER | s == "player_map"] ++ [t] NOTREADY_WITH_MAP -> head $ [CONFIG_WAIT_PLAYER | s == "player_join"] ++ [t] CONFIG_WAIT_PLAYER -> head $ [OWNER | s == "player_map"] ++ [t] CONFIG_WAIT_OWNER -> head $ [OWNER | s == "owner_map"] ++ [t] OWNER -> head $ [PLAYER | s == "player"] ++ [OWNER_WIN | s == "finished"] ++ [t] PLAYER -> head $ [OWNER | s == "owner"] ++ [PLAYER_WIN | s == "finished"] ++ [t] _ -> NOTREADY currentRulesId :: String -> FilePath -> IO String currentRulesId rules rulePath = do allrules <- liftIO $ (decodeFileStrict rulePath :: IO (Maybe [Rule])) case allrules of Just rs -> do return $ case (length $ filter (\(Rule rid _ _ _ _) -> rid == rules) rs) of 0 -> "free" _ -> rules Nothing -> return "free" currentRules :: String -> FilePath -> IO Rule currentRules rules rulePath = do allrules <- liftIO $ (decodeFileStrict rulePath :: IO (Maybe [Rule])) case allrules of Just rs -> do let myrules = filter (\(Rule rid _ _ _ _) -> rid == rules) rs return $ case (length $ myrules) of 0 -> Rule "free" "" "" [] 0 _ -> head myrules Nothing -> return $ Rule "free" "" "" [] 0 botByName :: String -> FilePath -> IO (Maybe Bot) botByName botName botsPath = do allbots <- liftIO $ (decodeFileStrict botsPath :: IO (Maybe [Bot])) case allbots of Just bs -> do return . head $ [Just b | b <- bs, case b of Bot bn _ _ -> bn == botName _ -> False] ++ [Nothing] _ -> do return Nothing getBotIdIfCan :: Maybe Bot -> String -> Maybe String getBotIdIfCan (Just (Bot _ bid rs)) r = head $ [Just bid | elem r rs] ++ [Nothing] getBotIdIfCan _ _ = Nothing [ ( 1,4 ) , ( 2,3 ) , ( 3,2 ) , ( 4,1 ) ] get list of counts for separated non empty cells : [ 0,0,0,1,1,0,1,1,1,0 ] - > [ 2,3 ] 1 0 1 0 1 1 1 1 0 1 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 1 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0 0 [ [ 1,1,1,0,1],[0,0,0,0,0],[1,1,0,1,0],[0,0,0,1,0],[1,0,0,0,0 ] ] isGood :: [[Int]] -> Rule -> Bool isGood sm (Rule rid _ _ ships _) = (isSane sm) && (rid == "free" || (isShipsByRule sm ships) && (noDiagonalShips sm)) isSane :: [[Int]] -> Bool isSane m = (mapWidth == length m) && (and [l==mapHeight | l <- [length ra | ra <- m]]) isShipsByRule :: [[Int]] -> [[Int]] -> Bool isShipsByRule sm r = isProjectionByRule r (getProjection sm) (getProjection . transpose $ sm) getProjection [ [ 1,1,1,0,1],[0,0,0,0,0],[1,1,0,1,0],[0,0,0,1,0],[1,0,0,0,0 ] ] getProjection :: [[Int]] -> [Int] getProjection m = concat $ [foldr (\x (y:ys) -> case x of 0 -> [0] ++ (y:ys) _ -> (y+1:ys)) [0] $ l | l <- m] isProjectionByRule :: [[Int]] -> [Int] -> [Int] -> Bool isProjectionByRule rs p pt = and [checkRule (head r) (head . tail $ r) | r <- rs] where checkRule d c = (head $ [c * 2 | d==1] ++ [c]) == (((length $ filter (d==) p) + (length $ filter (d==) pt)) - (head $ [(sum $ filter (1/=) p) + (sum $ filter (1/=) pt) | d==1] ++ [0])) noDiagonalShips :: [[Int]] -> Bool noDiagonalShips sm = not $ isIntersected sm ((shiftUp [0]) . (shiftLeft 0) $ sm) || isIntersected sm ((shiftUp [0]) . (shiftRight 0) $ sm) || isIntersected sm ((shiftDown [0]) . (shiftLeft 0) $ sm) || isIntersected sm ((shiftDown [0]) . (shiftRight 0) $ sm) shiftUp :: a -> [a] -> [a] shiftUp z xs = tail xs ++ [z] shiftDown :: a -> [a] -> [a] shiftDown z xs = [z] ++ take (-1+length xs) xs shiftLeft :: a -> [[a]] -> [[a]] shiftLeft z xss = [shiftUp z xs | xs <- xss] shiftRight :: a -> [[a]] -> [[a]] shiftRight z xss = [shiftDown z xs | xs <- xss] isIntersected :: [[Int]] -> [[Int]] -> Bool isIntersected m1 m2 = or . concat $ [zipWith (\a b -> (a * b) > 0) x y | (x, y) <- zip m1 m2] isShotSane :: [[Int]] -> Shot -> Bool isShotSane sm (Shot x y) = length sm > x && ((drop y) $ sm !! x) /= [] getCell :: [[Int]] -> Shot -> Int getCell sm (Shot x y) = sm !! x !! y isSink :: [[Int]] -> Shot -> Bool isSink m (Shot x y) = (checkLine y $ m !! x) && (checkLine x $ (transpose m) !! y) checkLine :: Int -> [Int] -> Bool checkLine x xs = and $ (checkPartOfLine $ drop (x+1) $ xs) ++ (checkPartOfLine $ drop ((length xs) - x) $ (reverse xs)) checkPartOfLine :: [Int] -> [Bool] checkPartOfLine [] = [True] checkPartOfLine xs = map (3==) $ getWhile (\v -> v==1|| v==3) xs getWhile :: Ord a => (a -> Bool) -> [a] -> [a] getWhile _ [] = [] getWhile t (x:[]) = [x | t x] getWhile t (x:xs) | t x = [x] ++ getWhile t xs | otherwise = [] isWin :: [[Int]] -> Bool isWin sm = sum [sum [head $ [0 | c/=1] ++ [1] | c <- l] | l <- sm] == 1 isGameFinished :: Turn -> Bool isGameFinished PLAYER_WIN = True isGameFinished OWNER_WIN = True isGameFinished _ = False connectAndAuth :: Host -> Username -> Password -> Database -> IO Pipe connectAndAuth mongoHost mongoUser mongoPass mongoDb = do pipe <- connect mongoHost access pipe master mongoDb $ auth mongoUser mongoPass return pipe performAction :: Pipe -> Database -> Action IO a -> IO a performAction pipe mongoDb action = access pipe master mongoDb action closeConnection :: Pipe -> IO () closeConnection pipe = close pipe gameServiceInit :: String -> String -> String -> String -> String -> String -> SnapletInit b GameService gameServiceInit mongoHost mongoUser mongoPass mongoDb rulePath botsPath = makeSnaplet "game" "Battleship Service" Nothing $ do addRoutes $ gameRoutes (readHostPort mongoHost) (T.pack mongoUser) (T.pack mongoPass) (T.pack mongoDb) rulePath botsPath return $ GameService
cbfb288342d698256df59f88b7dd769edf408277219487d23e5e06882d502d8f
janestreet/merlin-jst
printtyp.mli
(**************************************************************************) (* *) (* 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. *) (* *) (**************************************************************************) (* Printing functions *) open Format open Types open Outcometree val longident: formatter -> Longident.t -> unit val ident: formatter -> Ident.t -> unit val tree_of_path: Path.t -> out_ident val path: formatter -> Path.t -> unit val string_of_path: Path.t -> string val type_path: formatter -> Path.t -> unit * Print a type path taking account of [ -short - paths ] . Calls should be within [ wrap_printing_env ] . Calls should be within [wrap_printing_env]. *) module Out_name: sig val create: string -> out_name val print: out_name -> string end type namespace = | Type | Module | Module_type | Class | Class_type | Other (** Other bypasses the unique name for identifier mechanism *) val strings_of_paths: namespace -> Path.t list -> string list (** Print a list of paths, using the same naming context to avoid name collisions *) val raw_type_expr: formatter -> type_expr -> unit val raw_field : formatter -> row_field -> unit val string_of_label: Asttypes.arg_label -> string val wrap_printing_env: ?error:bool -> Env.t -> (unit -> 'a) -> 'a (* Call the function using the environment for type path shortening *) (* This affects all the printing functions below *) Also , if [ ~error : true ] , then disable the loading of cmis val shorten_type_path: Env.t -> Path.t -> Path.t val shorten_module_type_path: Env.t -> Path.t -> Path.t val shorten_module_path: Env.t -> Path.t -> Path.t val shorten_class_type_path: Env.t -> Path.t -> Path.t module Naming_context: sig val enable: bool -> unit * When contextual names are enabled , the mapping between identifiers and names is ensured to be one - to - one . and names is ensured to be one-to-one. *) val reset: unit -> unit (** Reset the naming context *) end (** The [Conflicts] module keeps track of conflicts arising when attributing names to identifiers and provides functions that can print explanations for these conflict in error messages *) module Conflicts: sig val exists: unit -> bool (** [exists()] returns true if the current naming context renamed an identifier to avoid a name collision *) type explanation = { kind: namespace; name:string; root_name:string; location:Location.t } val list_explanations: unit -> explanation list (** [list_explanations()] return the list of conflict explanations collected up to this point, and reset the list of collected explanations *) val print_located_explanations: Format.formatter -> explanation list -> unit val print_explanations: Format.formatter -> unit (** Print all conflict explanations collected up to this point *) val reset: unit -> unit end val reset: unit -> unit (** Print out a type. This will pick names for type variables, and will not reuse names for common type variables shared across multiple type expressions. (It will also reset the printing state, which matters for other type formatters such as [prepared_type_expr].) If you want multiple types to use common names for type variables, see [prepare_for_printing] and [prepared_type_expr]. *) val type_expr: formatter -> type_expr -> unit (** [prepare_for_printing] resets the global printing environment, a la [reset], and prepares the types for printing by reserving names and marking loops. Any type variables that are shared between multiple types in the input list will be given the same name when printed with [prepared_type_expr]. *) val prepare_for_printing: type_expr list -> unit (** [add_type_to_preparation ty] extend a previous type expression preparation to the type expression [ty] *) val add_type_to_preparation: type_expr -> unit val prepared_type_expr: formatter -> type_expr -> unit * The function [ prepared_type_expr ] is a less - safe but more - flexible version of [ type_expr ] that should only be called on [ type_expr]s that have been passed to [ prepare_for_printing ] . Unlike [ type_expr ] , this function does no extra work before printing a type ; in particular , this means that any loops in the type expression may cause a stack overflow ( see # 8860 ) since this function does not mark any loops . The benefit of this is that if multiple type expressions are prepared simultaneously and then printed with [ prepared_type_expr ] , they will use the same names for the same type variables . of [type_expr] that should only be called on [type_expr]s that have been passed to [prepare_for_printing]. Unlike [type_expr], this function does no extra work before printing a type; in particular, this means that any loops in the type expression may cause a stack overflow (see #8860) since this function does not mark any loops. The benefit of this is that if multiple type expressions are prepared simultaneously and then printed with [prepared_type_expr], they will use the same names for the same type variables. *) val constructor_arguments: formatter -> constructor_arguments -> unit val tree_of_type_scheme: type_expr -> out_type val type_scheme: formatter -> type_expr -> unit val shared_type_scheme: formatter -> type_expr -> unit * [ shared_type_scheme ] is very similar to [ type_scheme ] , but does not reset the printing context first . This is intended to be used in cases where the printing should have a particularly wide context , such as documentation generators ; most use cases , such as error messages , have narrower contexts for which [ type_scheme ] is better suited . the printing context first. This is intended to be used in cases where the printing should have a particularly wide context, such as documentation generators; most use cases, such as error messages, have narrower contexts for which [type_scheme] is better suited. *) val tree_of_value_description: Ident.t -> value_description -> out_sig_item val value_description: Ident.t -> formatter -> value_description -> unit val label : formatter -> label_declaration -> unit val constructor : formatter -> constructor_declaration -> unit val tree_of_type_declaration: Ident.t -> type_declaration -> rec_status -> out_sig_item val type_declaration: Ident.t -> formatter -> type_declaration -> unit val tree_of_extension_constructor: Ident.t -> extension_constructor -> ext_status -> out_sig_item val extension_constructor: Ident.t -> formatter -> extension_constructor -> unit (* Prints extension constructor with the type signature: type ('a, 'b) bar += A of float *) val extension_only_constructor: Ident.t -> formatter -> extension_constructor -> unit (* Prints only extension constructor without type signature: A of float *) val tree_of_module: Ident.t -> ?ellipsis:bool -> module_type -> rec_status -> out_sig_item val modtype: formatter -> module_type -> unit val signature: formatter -> signature -> unit val tree_of_modtype: module_type -> out_module_type val tree_of_modtype_declaration: Ident.t -> modtype_declaration -> out_sig_item * Print a list of functor parameters while adjusting the printing environment for each functor argument . Currently , we are disabling disambiguation for functor argument name to avoid the need to track the moving association between identifiers and syntactic names in situation like : got : ( X : sig module type T end ) ( Y : X.T ) ( X : sig module type T end ) ( Z : X.T ) expect : ( _ : sig end ) ( Y : X.T ) ( _ : sig end ) ( Z : X.T ) for each functor argument. Currently, we are disabling disambiguation for functor argument name to avoid the need to track the moving association between identifiers and syntactic names in situation like: got: (X: sig module type T end) (Y:X.T) (X:sig module type T end) (Z:X.T) expect: (_: sig end) (Y:X.T) (_:sig end) (Z:X.T) *) val functor_parameters: sep:(Format.formatter -> unit -> unit) -> ('b -> Format.formatter -> unit) -> (Ident.t option * 'b) list -> Format.formatter -> unit type type_or_scheme = Type | Type_scheme val tree_of_signature: Types.signature -> out_sig_item list val tree_of_typexp: type_or_scheme -> type_expr -> out_type val modtype_declaration: Ident.t -> formatter -> modtype_declaration -> unit val class_type: formatter -> class_type -> unit val tree_of_class_declaration: Ident.t -> class_declaration -> rec_status -> out_sig_item val class_declaration: Ident.t -> formatter -> class_declaration -> unit val tree_of_cltype_declaration: Ident.t -> class_type_declaration -> rec_status -> out_sig_item val cltype_declaration: Ident.t -> formatter -> class_type_declaration -> unit val type_expansion : type_or_scheme -> Format.formatter -> Errortrace.expanded_type -> unit val prepare_expansion: Errortrace.expanded_type -> Errortrace.expanded_type val report_ambiguous_type_error: formatter -> Env.t -> (Path.t * Path.t) -> (Path.t * Path.t) list -> (formatter -> unit) -> (formatter -> unit) -> (formatter -> unit) -> unit val report_unification_error : formatter -> Env.t -> Errortrace.unification_error -> ?type_expected_explanation:(formatter -> unit) -> (formatter -> unit) -> (formatter -> unit) -> unit val report_equality_error : formatter -> type_or_scheme -> Env.t -> Errortrace.equality_error -> (formatter -> unit) -> (formatter -> unit) -> unit val report_moregen_error : formatter -> type_or_scheme -> Env.t -> Errortrace.moregen_error -> (formatter -> unit) -> (formatter -> unit) -> unit val report_comparison_error : formatter -> type_or_scheme -> Env.t -> Errortrace.comparison_error -> (formatter -> unit) -> (formatter -> unit) -> unit module Subtype : sig val report_error : formatter -> Env.t -> Errortrace.Subtype.error -> string -> unit end (* for toploop *) val print_items: (Env.t -> signature_item -> 'a option) -> Env.t -> signature_item list -> (out_sig_item * 'a option) list Simple heuristic to rewrite . * as . Bar . * when . Bar is an alias for . This pattern is used by the stdlib . for Foo__bar. This pattern is used by the stdlib. *) val rewrite_double_underscore_paths: Env.t -> Path.t -> Path.t val rewrite_double_underscore_longidents: Env.t -> Longident.t -> Longident.t (** [printed_signature sourcefile ppf sg] print the signature [sg] of [sourcefile] with potential warnings for name collisions *) val printed_signature: string -> formatter -> signature -> unit
null
https://raw.githubusercontent.com/janestreet/merlin-jst/00f0a2c961fbf5a968125b33612d60224a573f40/src/ocaml/typing/printtyp.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Printing functions * Other bypasses the unique name for identifier mechanism * Print a list of paths, using the same naming context to avoid name collisions Call the function using the environment for type path shortening This affects all the printing functions below * Reset the naming context * The [Conflicts] module keeps track of conflicts arising when attributing names to identifiers and provides functions that can print explanations for these conflict in error messages * [exists()] returns true if the current naming context renamed an identifier to avoid a name collision * [list_explanations()] return the list of conflict explanations collected up to this point, and reset the list of collected explanations * Print all conflict explanations collected up to this point * Print out a type. This will pick names for type variables, and will not reuse names for common type variables shared across multiple type expressions. (It will also reset the printing state, which matters for other type formatters such as [prepared_type_expr].) If you want multiple types to use common names for type variables, see [prepare_for_printing] and [prepared_type_expr]. * [prepare_for_printing] resets the global printing environment, a la [reset], and prepares the types for printing by reserving names and marking loops. Any type variables that are shared between multiple types in the input list will be given the same name when printed with [prepared_type_expr]. * [add_type_to_preparation ty] extend a previous type expression preparation to the type expression [ty] Prints extension constructor with the type signature: type ('a, 'b) bar += A of float Prints only extension constructor without type signature: A of float for toploop * [printed_signature sourcefile ppf sg] print the signature [sg] of [sourcefile] with potential warnings for name collisions
, 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 Format open Types open Outcometree val longident: formatter -> Longident.t -> unit val ident: formatter -> Ident.t -> unit val tree_of_path: Path.t -> out_ident val path: formatter -> Path.t -> unit val string_of_path: Path.t -> string val type_path: formatter -> Path.t -> unit * Print a type path taking account of [ -short - paths ] . Calls should be within [ wrap_printing_env ] . Calls should be within [wrap_printing_env]. *) module Out_name: sig val create: string -> out_name val print: out_name -> string end type namespace = | Type | Module | Module_type | Class | Class_type val strings_of_paths: namespace -> Path.t list -> string list val raw_type_expr: formatter -> type_expr -> unit val raw_field : formatter -> row_field -> unit val string_of_label: Asttypes.arg_label -> string val wrap_printing_env: ?error:bool -> Env.t -> (unit -> 'a) -> 'a Also , if [ ~error : true ] , then disable the loading of cmis val shorten_type_path: Env.t -> Path.t -> Path.t val shorten_module_type_path: Env.t -> Path.t -> Path.t val shorten_module_path: Env.t -> Path.t -> Path.t val shorten_class_type_path: Env.t -> Path.t -> Path.t module Naming_context: sig val enable: bool -> unit * When contextual names are enabled , the mapping between identifiers and names is ensured to be one - to - one . and names is ensured to be one-to-one. *) val reset: unit -> unit end module Conflicts: sig val exists: unit -> bool type explanation = { kind: namespace; name:string; root_name:string; location:Location.t } val list_explanations: unit -> explanation list val print_located_explanations: Format.formatter -> explanation list -> unit val print_explanations: Format.formatter -> unit val reset: unit -> unit end val reset: unit -> unit val type_expr: formatter -> type_expr -> unit val prepare_for_printing: type_expr list -> unit val add_type_to_preparation: type_expr -> unit val prepared_type_expr: formatter -> type_expr -> unit * The function [ prepared_type_expr ] is a less - safe but more - flexible version of [ type_expr ] that should only be called on [ type_expr]s that have been passed to [ prepare_for_printing ] . Unlike [ type_expr ] , this function does no extra work before printing a type ; in particular , this means that any loops in the type expression may cause a stack overflow ( see # 8860 ) since this function does not mark any loops . The benefit of this is that if multiple type expressions are prepared simultaneously and then printed with [ prepared_type_expr ] , they will use the same names for the same type variables . of [type_expr] that should only be called on [type_expr]s that have been passed to [prepare_for_printing]. Unlike [type_expr], this function does no extra work before printing a type; in particular, this means that any loops in the type expression may cause a stack overflow (see #8860) since this function does not mark any loops. The benefit of this is that if multiple type expressions are prepared simultaneously and then printed with [prepared_type_expr], they will use the same names for the same type variables. *) val constructor_arguments: formatter -> constructor_arguments -> unit val tree_of_type_scheme: type_expr -> out_type val type_scheme: formatter -> type_expr -> unit val shared_type_scheme: formatter -> type_expr -> unit * [ shared_type_scheme ] is very similar to [ type_scheme ] , but does not reset the printing context first . This is intended to be used in cases where the printing should have a particularly wide context , such as documentation generators ; most use cases , such as error messages , have narrower contexts for which [ type_scheme ] is better suited . the printing context first. This is intended to be used in cases where the printing should have a particularly wide context, such as documentation generators; most use cases, such as error messages, have narrower contexts for which [type_scheme] is better suited. *) val tree_of_value_description: Ident.t -> value_description -> out_sig_item val value_description: Ident.t -> formatter -> value_description -> unit val label : formatter -> label_declaration -> unit val constructor : formatter -> constructor_declaration -> unit val tree_of_type_declaration: Ident.t -> type_declaration -> rec_status -> out_sig_item val type_declaration: Ident.t -> formatter -> type_declaration -> unit val tree_of_extension_constructor: Ident.t -> extension_constructor -> ext_status -> out_sig_item val extension_constructor: Ident.t -> formatter -> extension_constructor -> unit val extension_only_constructor: Ident.t -> formatter -> extension_constructor -> unit val tree_of_module: Ident.t -> ?ellipsis:bool -> module_type -> rec_status -> out_sig_item val modtype: formatter -> module_type -> unit val signature: formatter -> signature -> unit val tree_of_modtype: module_type -> out_module_type val tree_of_modtype_declaration: Ident.t -> modtype_declaration -> out_sig_item * Print a list of functor parameters while adjusting the printing environment for each functor argument . Currently , we are disabling disambiguation for functor argument name to avoid the need to track the moving association between identifiers and syntactic names in situation like : got : ( X : sig module type T end ) ( Y : X.T ) ( X : sig module type T end ) ( Z : X.T ) expect : ( _ : sig end ) ( Y : X.T ) ( _ : sig end ) ( Z : X.T ) for each functor argument. Currently, we are disabling disambiguation for functor argument name to avoid the need to track the moving association between identifiers and syntactic names in situation like: got: (X: sig module type T end) (Y:X.T) (X:sig module type T end) (Z:X.T) expect: (_: sig end) (Y:X.T) (_:sig end) (Z:X.T) *) val functor_parameters: sep:(Format.formatter -> unit -> unit) -> ('b -> Format.formatter -> unit) -> (Ident.t option * 'b) list -> Format.formatter -> unit type type_or_scheme = Type | Type_scheme val tree_of_signature: Types.signature -> out_sig_item list val tree_of_typexp: type_or_scheme -> type_expr -> out_type val modtype_declaration: Ident.t -> formatter -> modtype_declaration -> unit val class_type: formatter -> class_type -> unit val tree_of_class_declaration: Ident.t -> class_declaration -> rec_status -> out_sig_item val class_declaration: Ident.t -> formatter -> class_declaration -> unit val tree_of_cltype_declaration: Ident.t -> class_type_declaration -> rec_status -> out_sig_item val cltype_declaration: Ident.t -> formatter -> class_type_declaration -> unit val type_expansion : type_or_scheme -> Format.formatter -> Errortrace.expanded_type -> unit val prepare_expansion: Errortrace.expanded_type -> Errortrace.expanded_type val report_ambiguous_type_error: formatter -> Env.t -> (Path.t * Path.t) -> (Path.t * Path.t) list -> (formatter -> unit) -> (formatter -> unit) -> (formatter -> unit) -> unit val report_unification_error : formatter -> Env.t -> Errortrace.unification_error -> ?type_expected_explanation:(formatter -> unit) -> (formatter -> unit) -> (formatter -> unit) -> unit val report_equality_error : formatter -> type_or_scheme -> Env.t -> Errortrace.equality_error -> (formatter -> unit) -> (formatter -> unit) -> unit val report_moregen_error : formatter -> type_or_scheme -> Env.t -> Errortrace.moregen_error -> (formatter -> unit) -> (formatter -> unit) -> unit val report_comparison_error : formatter -> type_or_scheme -> Env.t -> Errortrace.comparison_error -> (formatter -> unit) -> (formatter -> unit) -> unit module Subtype : sig val report_error : formatter -> Env.t -> Errortrace.Subtype.error -> string -> unit end val print_items: (Env.t -> signature_item -> 'a option) -> Env.t -> signature_item list -> (out_sig_item * 'a option) list Simple heuristic to rewrite . * as . Bar . * when . Bar is an alias for . This pattern is used by the stdlib . for Foo__bar. This pattern is used by the stdlib. *) val rewrite_double_underscore_paths: Env.t -> Path.t -> Path.t val rewrite_double_underscore_longidents: Env.t -> Longident.t -> Longident.t val printed_signature: string -> formatter -> signature -> unit
ef3d9ffdb890b34707655f8a10df3cf1836015145be0b286083c128e4eb6c561
yallop/ocaml-ctypes
lDouble.ml
* Copyright ( c ) 2016 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2016 Andy Ray. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) external init : unit -> unit = "ldouble_init" let () = init () type t external to_float : t -> float = "ctypes_ldouble_to_float" external of_float : float -> t = "ctypes_ldouble_of_float" external to_int : t -> int = "ctypes_ldouble_to_int" external of_int : int -> t = "ctypes_ldouble_of_int" external format : int -> int -> t -> string = "ctypes_ldouble_format" let to_string ?(width=0) ?(prec=6) d = format width prec d external of_string : string -> t = "ctypes_ldouble_of_string" (* debug *) external to_hex_string : t - > string = " ctypes_ldouble_to_hex " external add : t -> t -> t = "ctypes_ldouble_add" external sub : t -> t -> t = "ctypes_ldouble_sub" external mul : t -> t -> t = "ctypes_ldouble_mul" external div : t -> t -> t = "ctypes_ldouble_div" external neg : t -> t = "ctypes_ldouble_neg" external pow : t -> t -> t = "ctypes_ldouble_powl" external sqrt : t -> t = "ctypes_ldouble_sqrtl" external exp : t -> t = "ctypes_ldouble_expl" external log : t -> t = "ctypes_ldouble_logl" external log10 : t -> t = "ctypes_ldouble_log10l" external expm1 : t -> t = "ctypes_ldouble_expm1l" external log1p : t -> t = "ctypes_ldouble_log1pl" external cos : t -> t = "ctypes_ldouble_cosl" external sin : t -> t = "ctypes_ldouble_sinl" external tan : t -> t = "ctypes_ldouble_tanl" external acos : t -> t = "ctypes_ldouble_acosl" external asin : t -> t = "ctypes_ldouble_asinl" external atan : t -> t = "ctypes_ldouble_atanl" external atan2 : t -> t -> t = "ctypes_ldouble_atan2l" external hypot : t -> t -> t = "ctypes_ldouble_hypotl" external cosh : t -> t = "ctypes_ldouble_coshl" external sinh : t -> t = "ctypes_ldouble_sinhl" external tanh : t -> t = "ctypes_ldouble_tanhl" external acosh : t -> t = "ctypes_ldouble_acoshl" external asinh : t -> t = "ctypes_ldouble_asinhl" external atanh : t -> t = "ctypes_ldouble_atanhl" external ceil : t -> t = "ctypes_ldouble_ceill" external floor : t -> t = "ctypes_ldouble_floorl" external abs : t -> t = "ctypes_ldouble_fabsl" external rem : t -> t -> t = "ctypes_ldouble_remainderl" external copysign : t -> t -> t = "ctypes_ldouble_copysignl" external frexp : t -> t * int = "ctypes_ldouble_frexp" external ldexp : t -> int -> t = "ctypes_ldouble_ldexp" external modf : t -> t * t = "ctypes_ldouble_modf" external classify : t -> fpclass = "ctypes_ldouble_classify" external min_ : unit -> t = "ctypes_ldouble_min" let min_float = min_ () external max_ : unit -> t = "ctypes_ldouble_max" let max_float = max_ () external epsilon_ : unit -> t = "ctypes_ldouble_epsilon" let epsilon = epsilon_ () external nan_ : unit -> t = "ctypes_ldouble_nan" let nan = nan_ () external inf_ : unit -> t = "ctypes_ldouble_inf" let infinity = inf_ () external ninf_ : unit -> t = "ctypes_ldouble_ninf" let neg_infinity = ninf_ () let zero = of_int 0 let one = of_int 1 external size_ : unit -> (int * int) = "ctypes_ldouble_size" let byte_sizes = size_ () external mant_dig_ : unit -> int = "ctypes_ldouble_mant_dig" [@@noalloc] let mant_dig = mant_dig_ ()
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/src/ctypes/lDouble.ml
ocaml
debug
* Copyright ( c ) 2016 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2016 Andy Ray. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) external init : unit -> unit = "ldouble_init" let () = init () type t external to_float : t -> float = "ctypes_ldouble_to_float" external of_float : float -> t = "ctypes_ldouble_of_float" external to_int : t -> int = "ctypes_ldouble_to_int" external of_int : int -> t = "ctypes_ldouble_of_int" external format : int -> int -> t -> string = "ctypes_ldouble_format" let to_string ?(width=0) ?(prec=6) d = format width prec d external of_string : string -> t = "ctypes_ldouble_of_string" external to_hex_string : t - > string = " ctypes_ldouble_to_hex " external add : t -> t -> t = "ctypes_ldouble_add" external sub : t -> t -> t = "ctypes_ldouble_sub" external mul : t -> t -> t = "ctypes_ldouble_mul" external div : t -> t -> t = "ctypes_ldouble_div" external neg : t -> t = "ctypes_ldouble_neg" external pow : t -> t -> t = "ctypes_ldouble_powl" external sqrt : t -> t = "ctypes_ldouble_sqrtl" external exp : t -> t = "ctypes_ldouble_expl" external log : t -> t = "ctypes_ldouble_logl" external log10 : t -> t = "ctypes_ldouble_log10l" external expm1 : t -> t = "ctypes_ldouble_expm1l" external log1p : t -> t = "ctypes_ldouble_log1pl" external cos : t -> t = "ctypes_ldouble_cosl" external sin : t -> t = "ctypes_ldouble_sinl" external tan : t -> t = "ctypes_ldouble_tanl" external acos : t -> t = "ctypes_ldouble_acosl" external asin : t -> t = "ctypes_ldouble_asinl" external atan : t -> t = "ctypes_ldouble_atanl" external atan2 : t -> t -> t = "ctypes_ldouble_atan2l" external hypot : t -> t -> t = "ctypes_ldouble_hypotl" external cosh : t -> t = "ctypes_ldouble_coshl" external sinh : t -> t = "ctypes_ldouble_sinhl" external tanh : t -> t = "ctypes_ldouble_tanhl" external acosh : t -> t = "ctypes_ldouble_acoshl" external asinh : t -> t = "ctypes_ldouble_asinhl" external atanh : t -> t = "ctypes_ldouble_atanhl" external ceil : t -> t = "ctypes_ldouble_ceill" external floor : t -> t = "ctypes_ldouble_floorl" external abs : t -> t = "ctypes_ldouble_fabsl" external rem : t -> t -> t = "ctypes_ldouble_remainderl" external copysign : t -> t -> t = "ctypes_ldouble_copysignl" external frexp : t -> t * int = "ctypes_ldouble_frexp" external ldexp : t -> int -> t = "ctypes_ldouble_ldexp" external modf : t -> t * t = "ctypes_ldouble_modf" external classify : t -> fpclass = "ctypes_ldouble_classify" external min_ : unit -> t = "ctypes_ldouble_min" let min_float = min_ () external max_ : unit -> t = "ctypes_ldouble_max" let max_float = max_ () external epsilon_ : unit -> t = "ctypes_ldouble_epsilon" let epsilon = epsilon_ () external nan_ : unit -> t = "ctypes_ldouble_nan" let nan = nan_ () external inf_ : unit -> t = "ctypes_ldouble_inf" let infinity = inf_ () external ninf_ : unit -> t = "ctypes_ldouble_ninf" let neg_infinity = ninf_ () let zero = of_int 0 let one = of_int 1 external size_ : unit -> (int * int) = "ctypes_ldouble_size" let byte_sizes = size_ () external mant_dig_ : unit -> int = "ctypes_ldouble_mant_dig" [@@noalloc] let mant_dig = mant_dig_ ()
d8639567615c58ced2557087d6ff270cfb0fe4725d43e8b46112c52a33b09fff
ates/netflow
ipfix_v10_codec.erl
-module(ipfix_v10_codec). %% API -export([init/0]). -export([decode/2]). -export([encode/5]). -include("ipfix_v10.hrl"). -define(TEMPLATES_TABLE, ipfix_v10_templates). -define(TEMPLATES_TABLE_OPTS, [named_table, public, {read_concurrency, true}]). %% @doc Creates the ETS table for storing templates. -spec init() -> ok. init() -> case ets:info(?TEMPLATES_TABLE) of undefined -> ?TEMPLATES_TABLE = ets:new(?TEMPLATES_TABLE, ?TEMPLATES_TABLE_OPTS), ok; _ -> ok end. @doc Decodes the binary NetFlow packet . -spec decode(binary(), inet:ip_address()) -> {ok, {#ipfh_v10{}, [proplists:property()]}} | {error, term()}. decode(Binary, IP) -> %% try %% decode_packet(Binary, IP) %% catch %% _:Reason -> %% {error, Reason} %% end. decode_packet(Binary, IP). encode(ExportTime, FlowSeq, DomainId, TemplateId, Records) -> TemplateFields = encode_template_fields(Records, []), Count = length(Records), Template = << FlowSet ID , 0 for template (byte_size(TemplateFields) + 8):16, % Length Template ID , should be > 255 Count:16, % Count TemplateFields/binary % Fields >>, Fields0 = encode_fields(Records), Fields = pad_to(4, Fields0), DataFlowset = <<TemplateId:16, (byte_size(Fields) + 4):16, Fields/binary>>, Length = byte_size(Template) + byte_size(DataFlowset), Header = <<10:16, (Length + 16):16, ExportTime:32, FlowSeq:32, DomainId:32>>, list_to_binary([Header, Template, DataFlowset]). Internal functions encode_fields(Fields) -> Encoded = [Data || {Data, _, _} <- [encode_field(F, V) || {F, V} <- Fields]], list_to_binary(Encoded). encode_template_fields([], Acc) -> list_to_binary(lists:reverse(Acc)); encode_template_fields([{Field, Value} | Rest], Acc) -> {_Data, Type, Length} = encode_field(Field, Value), encode_template_fields(Rest, [<<Type:16, Length:16>> | Acc]). decode_packet(<<Version:16, Length:16, ExportTime:32, SequenceNum:32, DomainId:32, Data/binary>>, IP) -> BinLen = Length - 16, <<Rest:BinLen/bytes, _Next/binary>> = Data, Header = #ipfh_v10{ version = Version, export_time = ExportTime, flow_seq = SequenceNum, domain_id = DomainId }, case decode_flowsets(Rest, {DomainId, IP}, []) of {ok, Records} -> {ok, {Header, Records}}; {error, Reason} -> {error, Reason} end. decode_flowsets(<<>>, _, Acc0) -> {ok, lists:reverse(Acc0)}; %% Template flowset decode_flowsets(<<SetId:16, Length:16, Rest/binary>>, Domain, Acc0) -> BinLen = Length - 4, <<Data:BinLen/bytes, Next/binary>> = Rest, Acc = decode_flowset(SetId, Domain, Data, Acc0), decode_flowsets(Next, Domain, Acc). %% Template flowset decode_flowset(2, Domain, Data, Acc) -> decode_templates(Data, Domain), Acc; Options template flowset decode_flowset(3, Domain, Data, Acc) -> decode_options_templates(Data, Domain), Acc; %% Data flowset decode_flowset(Id, Domain, Data, Acc) when Id > 255 -> case lookup_template(Domain, Id) of false -> {error, missing_template}; Template -> decode_set_data_fields(Data, Template, Acc) end. decode_templates(<<Id:16, Count:16, Rest/binary>>, Domain) -> Template = decode_template_fields(Rest, Count, []), store_template(Domain, Id, Template). decode_set_data_fields(Bin, {Size, _Map}, Acc) when byte_size(Bin) < Size -> lists:reverse(Acc); decode_set_data_fields(Data, {_Size, Map} = Template, Acc) -> {Set, Rest} = decode_data_fields(Data, Map, []), decode_set_data_fields(Rest, Template, [Set | Acc]). Decode template flowset fields decode_template_fields(Bin, Count, Acc) when Bin =:= <<>>; Count =:= 0 -> lists:reverse(Acc); decode_template_fields(Data, Count, Acc) -> {IE, Rest} = decode_ie(Data), decode_template_fields(Rest, Count - 1, [IE | Acc]). Decode data flowset fields decode_data_fields(Bin, Map, Acc) when Bin =:= <<>>; Map =:= [] -> {lists:reverse(Acc), Bin}; decode_data_fields(Bin, [{scope, {Type, Len}} | T], Acc) -> {Scope, Rest} = decode_data_field(Bin, Len, scope, Type), decode_data_fields(Rest, T, [Scope | Acc]); decode_data_fields(Bin, [{Type, Len} | T], Acc) when Len == 65535 orelse byte_size(Bin) >= Len -> {Field, Rest} = decode_data_field(Bin, Len, field, Type), decode_data_fields(Rest, T, [Field | Acc]). decode_data_field(<<255, Len:16, Value:Len/binary, Rest/binary>>, 65535, Scope, Type) -> {typecast(Value, Scope, Type, Len), Rest}; decode_data_field(<<Len:8, Value:Len/binary, Rest/binary>>, 65535, Scope, Type) -> {typecast(Value, Scope, Type, Len), Rest}; decode_data_field(Bin, Len, Scope, Type) -> <<Value:Len/binary, Rest/binary>> = Bin, {typecast(Value, Scope, Type, Len), Rest}. decode_options_templates(<<Id:16, Count:16, ScopeCount:16, Rest/binary>>, Domain) -> Template = decode_options_template_fields(Rest, Count, ScopeCount, []), store_template(Domain, Id, Template). decode_options_template_fields(Bin, Count, _ScopeCount, Acc) when Bin =:= <<>>; Count =:= 0 -> lists:reverse(Acc); decode_options_template_fields(Data, Count, ScopeCount, Acc) -> {IE, Rest} = decode_ie(Data), Entry = if ScopeCount > 0 -> {scope, IE}; true -> IE end, decode_options_template_fields(Rest, Count - 1, ScopeCount - 1, [Entry | Acc]). decode_ie(<<0:1, Type:15, Len:16, Rest/binary>>) -> {{Type, Len}, Rest}; decode_ie(<<1:1, Type:15, Len:16, Vendor:32, Rest/binary>>) -> {{{Vendor, Type}, Len}, Rest}. lookup_template(Domain, ID) -> case ets:lookup(?TEMPLATES_TABLE, {Domain, ID}) of [] -> false; [{_, Map}] -> Map end. store_template(Domain, ID, Map) -> Size = lists:foldl(fun record_size/2, 0, Map), ets:insert(?TEMPLATES_TABLE, {{Domain, ID}, {Size, Map}}). record_size({scope, {_, 65535}}, Total) -> Total + 1; record_size({scope, {_, Size}}, Total) -> Size + Total; record_size({_, 65535}, Total) -> Total + 1; record_size({_, Size}, Total) -> Size + Total. typecast(Bin, field, Type, Length) -> typecast_field(Bin, Type, Length); typecast(Bin, scope, Type, Length) -> {scope, typecast_field(Bin, Type, Length)}. encode_variable_field(Value) when byte_size(Value) < 255 -> <<(byte_size(Value)):8, Value/binary>>; encode_variable_field(Value) -> <<255, (byte_size(Value)):16, Value/binary>>. -include("ipfix_v10_codec_gen.hrl"). %%%=================================================================== Internal functions %%%=================================================================== pad_length(Width, Length) -> (Width - Length rem Width) rem Width. %% %% pad binary to specific length %% -> -questions/2008-December/040709.html %% pad_to(Width, Binary) -> case pad_length(Width, size(Binary)) of 0 -> Binary; N -> <<Binary/binary, 0:(N*8)>> end.
null
https://raw.githubusercontent.com/ates/netflow/fb00d02d9e5ff742dd7c8b562912308c42e5bffd/src/ipfix_v10_codec.erl
erlang
API @doc Creates the ETS table for storing templates. try decode_packet(Binary, IP) catch _:Reason -> {error, Reason} end. Length Count Fields Template flowset Template flowset Data flowset =================================================================== =================================================================== pad binary to specific length -> -questions/2008-December/040709.html
-module(ipfix_v10_codec). -export([init/0]). -export([decode/2]). -export([encode/5]). -include("ipfix_v10.hrl"). -define(TEMPLATES_TABLE, ipfix_v10_templates). -define(TEMPLATES_TABLE_OPTS, [named_table, public, {read_concurrency, true}]). -spec init() -> ok. init() -> case ets:info(?TEMPLATES_TABLE) of undefined -> ?TEMPLATES_TABLE = ets:new(?TEMPLATES_TABLE, ?TEMPLATES_TABLE_OPTS), ok; _ -> ok end. @doc Decodes the binary NetFlow packet . -spec decode(binary(), inet:ip_address()) -> {ok, {#ipfh_v10{}, [proplists:property()]}} | {error, term()}. decode(Binary, IP) -> decode_packet(Binary, IP). encode(ExportTime, FlowSeq, DomainId, TemplateId, Records) -> TemplateFields = encode_template_fields(Records, []), Count = length(Records), Template = << FlowSet ID , 0 for template Template ID , should be > 255 >>, Fields0 = encode_fields(Records), Fields = pad_to(4, Fields0), DataFlowset = <<TemplateId:16, (byte_size(Fields) + 4):16, Fields/binary>>, Length = byte_size(Template) + byte_size(DataFlowset), Header = <<10:16, (Length + 16):16, ExportTime:32, FlowSeq:32, DomainId:32>>, list_to_binary([Header, Template, DataFlowset]). Internal functions encode_fields(Fields) -> Encoded = [Data || {Data, _, _} <- [encode_field(F, V) || {F, V} <- Fields]], list_to_binary(Encoded). encode_template_fields([], Acc) -> list_to_binary(lists:reverse(Acc)); encode_template_fields([{Field, Value} | Rest], Acc) -> {_Data, Type, Length} = encode_field(Field, Value), encode_template_fields(Rest, [<<Type:16, Length:16>> | Acc]). decode_packet(<<Version:16, Length:16, ExportTime:32, SequenceNum:32, DomainId:32, Data/binary>>, IP) -> BinLen = Length - 16, <<Rest:BinLen/bytes, _Next/binary>> = Data, Header = #ipfh_v10{ version = Version, export_time = ExportTime, flow_seq = SequenceNum, domain_id = DomainId }, case decode_flowsets(Rest, {DomainId, IP}, []) of {ok, Records} -> {ok, {Header, Records}}; {error, Reason} -> {error, Reason} end. decode_flowsets(<<>>, _, Acc0) -> {ok, lists:reverse(Acc0)}; decode_flowsets(<<SetId:16, Length:16, Rest/binary>>, Domain, Acc0) -> BinLen = Length - 4, <<Data:BinLen/bytes, Next/binary>> = Rest, Acc = decode_flowset(SetId, Domain, Data, Acc0), decode_flowsets(Next, Domain, Acc). decode_flowset(2, Domain, Data, Acc) -> decode_templates(Data, Domain), Acc; Options template flowset decode_flowset(3, Domain, Data, Acc) -> decode_options_templates(Data, Domain), Acc; decode_flowset(Id, Domain, Data, Acc) when Id > 255 -> case lookup_template(Domain, Id) of false -> {error, missing_template}; Template -> decode_set_data_fields(Data, Template, Acc) end. decode_templates(<<Id:16, Count:16, Rest/binary>>, Domain) -> Template = decode_template_fields(Rest, Count, []), store_template(Domain, Id, Template). decode_set_data_fields(Bin, {Size, _Map}, Acc) when byte_size(Bin) < Size -> lists:reverse(Acc); decode_set_data_fields(Data, {_Size, Map} = Template, Acc) -> {Set, Rest} = decode_data_fields(Data, Map, []), decode_set_data_fields(Rest, Template, [Set | Acc]). Decode template flowset fields decode_template_fields(Bin, Count, Acc) when Bin =:= <<>>; Count =:= 0 -> lists:reverse(Acc); decode_template_fields(Data, Count, Acc) -> {IE, Rest} = decode_ie(Data), decode_template_fields(Rest, Count - 1, [IE | Acc]). Decode data flowset fields decode_data_fields(Bin, Map, Acc) when Bin =:= <<>>; Map =:= [] -> {lists:reverse(Acc), Bin}; decode_data_fields(Bin, [{scope, {Type, Len}} | T], Acc) -> {Scope, Rest} = decode_data_field(Bin, Len, scope, Type), decode_data_fields(Rest, T, [Scope | Acc]); decode_data_fields(Bin, [{Type, Len} | T], Acc) when Len == 65535 orelse byte_size(Bin) >= Len -> {Field, Rest} = decode_data_field(Bin, Len, field, Type), decode_data_fields(Rest, T, [Field | Acc]). decode_data_field(<<255, Len:16, Value:Len/binary, Rest/binary>>, 65535, Scope, Type) -> {typecast(Value, Scope, Type, Len), Rest}; decode_data_field(<<Len:8, Value:Len/binary, Rest/binary>>, 65535, Scope, Type) -> {typecast(Value, Scope, Type, Len), Rest}; decode_data_field(Bin, Len, Scope, Type) -> <<Value:Len/binary, Rest/binary>> = Bin, {typecast(Value, Scope, Type, Len), Rest}. decode_options_templates(<<Id:16, Count:16, ScopeCount:16, Rest/binary>>, Domain) -> Template = decode_options_template_fields(Rest, Count, ScopeCount, []), store_template(Domain, Id, Template). decode_options_template_fields(Bin, Count, _ScopeCount, Acc) when Bin =:= <<>>; Count =:= 0 -> lists:reverse(Acc); decode_options_template_fields(Data, Count, ScopeCount, Acc) -> {IE, Rest} = decode_ie(Data), Entry = if ScopeCount > 0 -> {scope, IE}; true -> IE end, decode_options_template_fields(Rest, Count - 1, ScopeCount - 1, [Entry | Acc]). decode_ie(<<0:1, Type:15, Len:16, Rest/binary>>) -> {{Type, Len}, Rest}; decode_ie(<<1:1, Type:15, Len:16, Vendor:32, Rest/binary>>) -> {{{Vendor, Type}, Len}, Rest}. lookup_template(Domain, ID) -> case ets:lookup(?TEMPLATES_TABLE, {Domain, ID}) of [] -> false; [{_, Map}] -> Map end. store_template(Domain, ID, Map) -> Size = lists:foldl(fun record_size/2, 0, Map), ets:insert(?TEMPLATES_TABLE, {{Domain, ID}, {Size, Map}}). record_size({scope, {_, 65535}}, Total) -> Total + 1; record_size({scope, {_, Size}}, Total) -> Size + Total; record_size({_, 65535}, Total) -> Total + 1; record_size({_, Size}, Total) -> Size + Total. typecast(Bin, field, Type, Length) -> typecast_field(Bin, Type, Length); typecast(Bin, scope, Type, Length) -> {scope, typecast_field(Bin, Type, Length)}. encode_variable_field(Value) when byte_size(Value) < 255 -> <<(byte_size(Value)):8, Value/binary>>; encode_variable_field(Value) -> <<255, (byte_size(Value)):16, Value/binary>>. -include("ipfix_v10_codec_gen.hrl"). Internal functions pad_length(Width, Length) -> (Width - Length rem Width) rem Width. pad_to(Width, Binary) -> case pad_length(Width, size(Binary)) of 0 -> Binary; N -> <<Binary/binary, 0:(N*8)>> end.
38adcef38c18f003802f8f809e24a98f8a637ee40f19a77ce6eb8d9cfede03e4
spawnfest/eep49ers
oc_statem.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2017 - 2020 . 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. %% %% %CopyrightEnd% %% -module(oc_statem). -behaviour(gen_statem). %% API -export([start/1]). %% gen_statem callbacks -export([init/1, callback_mode/0, handle_event/4]). start(Opts) -> gen_statem:start({local, ?MODULE}, ?MODULE, [], Opts). init([]) -> %% Supervise state machine parent i.e the test case, and if it dies %% (fails due to some reason), kill the state machine, %% just to not leak resources (process, name, ETS table, etc...) %% Parent = gen:get_parent(), Statem = self(), _Supervisor = spawn( fun () -> StatemRef = monitor(process, Statem), ParentRef = monitor(process, Parent), receive {'DOWN', StatemRef, _, _, Reason} -> exit(Reason); {'DOWN', ParentRef, _, _, _} -> exit(Statem, kill) end end), {ok, start, #{}}. callback_mode() -> [handle_event_function, state_enter]. handle_event(enter, start, start, _Data) -> keep_state_and_data; handle_event( {call,From}, {push_callback_module,NewModule} = Action, start, _Data) -> {keep_state_and_data, [Action, {reply,From,ok}]}; handle_event( {call,From}, pop_callback_module = Action, start, _Data) -> {keep_state_and_data, [Action, {reply,From,ok}]}.
null
https://raw.githubusercontent.com/spawnfest/eep49ers/d1020fd625a0bbda8ab01caf0e1738eb1cf74886/lib/stdlib/test/gen_statem_SUITE_data/oc_statem.erl
erlang
%CopyrightBegin% 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. %CopyrightEnd% API gen_statem callbacks Supervise state machine parent i.e the test case, and if it dies (fails due to some reason), kill the state machine, just to not leak resources (process, name, ETS table, etc...)
Copyright Ericsson AB 2017 - 2020 . 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(oc_statem). -behaviour(gen_statem). -export([start/1]). -export([init/1, callback_mode/0, handle_event/4]). start(Opts) -> gen_statem:start({local, ?MODULE}, ?MODULE, [], Opts). init([]) -> Parent = gen:get_parent(), Statem = self(), _Supervisor = spawn( fun () -> StatemRef = monitor(process, Statem), ParentRef = monitor(process, Parent), receive {'DOWN', StatemRef, _, _, Reason} -> exit(Reason); {'DOWN', ParentRef, _, _, _} -> exit(Statem, kill) end end), {ok, start, #{}}. callback_mode() -> [handle_event_function, state_enter]. handle_event(enter, start, start, _Data) -> keep_state_and_data; handle_event( {call,From}, {push_callback_module,NewModule} = Action, start, _Data) -> {keep_state_and_data, [Action, {reply,From,ok}]}; handle_event( {call,From}, pop_callback_module = Action, start, _Data) -> {keep_state_and_data, [Action, {reply,From,ok}]}.
20d88be5798dd1db329e33478575861867ccf9b13e30da68c84a41b3c9933f39
Ericson2314/lighthouse
Console.hs
module Kernel.Types.Console where import H.Concurrency(Chan) import Data.Word ( Word8 ) import Control.Concurrent.Lock type VideoAttributes = Word8 type Row = Int type Col = Int data ConsoleCommand = NewLine | CarriageReturn | ClearEOL | PutChar VideoAttributes Char | MoveCursorBackward Int | ClearScreen data ConsoleData = ConsoleData { consoleChan :: Chan ConsoleCommand , consoleHeight :: Int , consoleWidth :: Int } data Console = Console Lock ConsoleData
null
https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/kernel/Kernel/Types/Console.hs
haskell
module Kernel.Types.Console where import H.Concurrency(Chan) import Data.Word ( Word8 ) import Control.Concurrent.Lock type VideoAttributes = Word8 type Row = Int type Col = Int data ConsoleCommand = NewLine | CarriageReturn | ClearEOL | PutChar VideoAttributes Char | MoveCursorBackward Int | ClearScreen data ConsoleData = ConsoleData { consoleChan :: Chan ConsoleCommand , consoleHeight :: Int , consoleWidth :: Int } data Console = Console Lock ConsoleData
3457da47eb5b763dcb63befc574251a88bba3f8b29e270dd540f9814dab9063f
karamellpelle/grid
SoundMemory.hs
grid is a game written in Haskell Copyright ( C ) 2018 -- -- This file is part of grid. -- -- grid 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. -- -- grid 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 grid. If not, see </>. -- module Game.Memory.MemoryData.Fancy.SoundMemory ( SoundMemory (..), loadSoundMemory, unloadSoundMemory, ) where import MyPrelude import Game.Values import File import OpenAL import OpenAL.Helpers data SoundMemory = SoundMemory { soundMemoryIterationFailureBuf :: !ALuint, soundMemorySrc :: !ALuint } loadSoundMemory :: IO SoundMemory loadSoundMemory = do -- buffer buf <- genBuf path <- fileStaticData "Memory/Output/iteration_failure.mp3" loadBuf buf path -- src src <- genSrc -- make source non-3D alSourcei src al_SOURCE_RELATIVE $ fI al_TRUE alSource3f src al_POSITION 0.0 0.0 0.0 alSource3f src al_VELOCITY 0.0 0.0 0.0 -- set default buffer alSourcei src al_BUFFER (fI buf) return SoundMemory { soundMemoryIterationFailureBuf = buf, soundMemorySrc = src } unloadSoundMemory :: SoundMemory -> IO () unloadSoundMemory sound = do alStopSource ? delSrc $ soundMemorySrc sound delBuf $ soundMemoryIterationFailureBuf sound
null
https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/source/Game/Memory/MemoryData/Fancy/SoundMemory.hs
haskell
This file is part of grid. grid is free software: you can redistribute it and/or modify (at your option) any later version. grid 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 grid. If not, see </>. buffer src make source non-3D set default buffer
grid is a game written in Haskell Copyright ( C ) 2018 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 module Game.Memory.MemoryData.Fancy.SoundMemory ( SoundMemory (..), loadSoundMemory, unloadSoundMemory, ) where import MyPrelude import Game.Values import File import OpenAL import OpenAL.Helpers data SoundMemory = SoundMemory { soundMemoryIterationFailureBuf :: !ALuint, soundMemorySrc :: !ALuint } loadSoundMemory :: IO SoundMemory loadSoundMemory = do buf <- genBuf path <- fileStaticData "Memory/Output/iteration_failure.mp3" loadBuf buf path src <- genSrc alSourcei src al_SOURCE_RELATIVE $ fI al_TRUE alSource3f src al_POSITION 0.0 0.0 0.0 alSource3f src al_VELOCITY 0.0 0.0 0.0 alSourcei src al_BUFFER (fI buf) return SoundMemory { soundMemoryIterationFailureBuf = buf, soundMemorySrc = src } unloadSoundMemory :: SoundMemory -> IO () unloadSoundMemory sound = do alStopSource ? delSrc $ soundMemorySrc sound delBuf $ soundMemoryIterationFailureBuf sound
5615c31a200fd6735be13d65577b7724809f70c4d91838461431cb06221647a8
bmeurer/ocaml-arm
outputbis.mli
(***********************************************************************) (* *) (* OCaml *) (* *) projet (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ Id$ val output_lexdef : string -> in_channel -> out_channel -> Common.line_tracker -> Syntax.location -> (string list, Syntax.location) Lexgen.automata_entry list -> Lexgen.automata array -> Syntax.location -> unit
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/lex/outputbis.mli
ocaml
********************************************************************* OCaml *********************************************************************
projet Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ Id$ val output_lexdef : string -> in_channel -> out_channel -> Common.line_tracker -> Syntax.location -> (string list, Syntax.location) Lexgen.automata_entry list -> Lexgen.automata array -> Syntax.location -> unit
5e91a0c1b934787b9e4def0cef85e006a2ebc07192dd8be7224d440c5e69802e
BinaryAnalysisPlatform/bap
mips_utils.ml
open Core_kernel[@@warning "-D"] open Bap.Std let mips_fail format = let fail str = failwith (sprintf "MIPS lifter fail: %s" str) in Printf.ksprintf fail format
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/plugins/mips/mips_utils.ml
ocaml
open Core_kernel[@@warning "-D"] open Bap.Std let mips_fail format = let fail str = failwith (sprintf "MIPS lifter fail: %s" str) in Printf.ksprintf fail format
84e3971c2e8fd6648faf2af9b97bea3d7b6d5792ff1218ed76eb6b04972f810e
imrehg/ypsilon
sorting.scm
#!core Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (core sorting) (export list-sort vector-sort vector-sort!) (import (core primitives)) (define list-sort (lambda (proc lst) (define merge (lambda (lst1 lst2) (cond ((null? lst1) lst2) ((null? lst2) lst1) (else (if (proc (car lst2) (car lst1)) (cons (car lst2) (merge lst1 (cdr lst2))) (cons (car lst1) (merge (cdr lst1) lst2))))))) (define sort (lambda (lst n) (cond ((= n 1) (list (car lst))) ((= n 2) (if (proc (cadr lst) (car lst)) (list (cadr lst) (car lst)) (list (car lst) (cadr lst)))) (else (let ((n/2 (div n 2))) (merge (sort lst n/2) (sort (list-tail lst n/2) (- n n/2)))))))) (define divide (lambda (lst) (let loop ((acc 1) (lst lst)) (cond ((null? (cdr lst)) (values acc '())) (else (if (proc (car lst) (cadr lst)) (loop (+ acc 1) (cdr lst)) (values acc (cdr lst)))))))) (cond ((null? lst) '()) (else (let ((len (length lst))) (let-values (((n rest) (divide lst))) (cond ((null? rest) lst) (else (merge (list-head lst n) (sort rest (- len n))))))))))) (define vector-sort (lambda (proc vect) (let ((lst (vector->list vect))) (let ((lst2 (list-sort proc lst))) (cond ((eq? lst lst2) vect) (else (list->vector lst2))))))) (define vector-sort! (lambda (proc vect) (let* ((n (vector-length vect)) (work (make-vector (+ (div n 2) 1)))) (define simple-sort! (lambda (first last) (let loop1 ((i first)) (cond ((< i last) (let ((m (vector-ref vect i)) (k i)) (let loop2 ((j (+ i 1))) (cond ((<= j last) (if (proc (vector-ref vect j) m) (begin (set! m (vector-ref vect j)) (set! k j))) (loop2 (+ j 1))) (else (vector-set! vect k (vector-ref vect i)) (vector-set! vect i m) (loop1 (+ i 1))))))))))) (define sort! (lambda (first last) (cond ((> (- last first) 10) (let ((middle (div (+ first last) 2))) (sort! first middle) (sort! (+ middle 1) last) (let loop ((i first) (p2size 0)) (cond ((> i middle) (let loop ((p1 (+ middle 1)) (p2 0) (p3 first)) (cond ((and (<= p1 last) (< p2 p2size)) (cond ((proc (vector-ref work p2) (vector-ref vect p1)) (vector-set! vect p3 (vector-ref work p2)) (loop p1 (+ p2 1) (+ p3 1))) (else (vector-set! vect p3 (vector-ref vect p1)) (loop (+ p1 1) p2 (+ p3 1))))) (else (let loop ((s2 p2)(d3 p3)) (cond ((< s2 p2size) (vector-set! vect d3 (vector-ref work s2)) (loop (+ s2 1) (+ d3 1))))))))) (else (vector-set! work p2size (vector-ref vect i)) (loop (+ i 1) (+ p2size 1))))))) (else (simple-sort! first last))))) (sort! 0 (- n 1))))) ) ;[end]
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/stdlib/core/sorting.scm
scheme
[end]
#!core Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (core sorting) (export list-sort vector-sort vector-sort!) (import (core primitives)) (define list-sort (lambda (proc lst) (define merge (lambda (lst1 lst2) (cond ((null? lst1) lst2) ((null? lst2) lst1) (else (if (proc (car lst2) (car lst1)) (cons (car lst2) (merge lst1 (cdr lst2))) (cons (car lst1) (merge (cdr lst1) lst2))))))) (define sort (lambda (lst n) (cond ((= n 1) (list (car lst))) ((= n 2) (if (proc (cadr lst) (car lst)) (list (cadr lst) (car lst)) (list (car lst) (cadr lst)))) (else (let ((n/2 (div n 2))) (merge (sort lst n/2) (sort (list-tail lst n/2) (- n n/2)))))))) (define divide (lambda (lst) (let loop ((acc 1) (lst lst)) (cond ((null? (cdr lst)) (values acc '())) (else (if (proc (car lst) (cadr lst)) (loop (+ acc 1) (cdr lst)) (values acc (cdr lst)))))))) (cond ((null? lst) '()) (else (let ((len (length lst))) (let-values (((n rest) (divide lst))) (cond ((null? rest) lst) (else (merge (list-head lst n) (sort rest (- len n))))))))))) (define vector-sort (lambda (proc vect) (let ((lst (vector->list vect))) (let ((lst2 (list-sort proc lst))) (cond ((eq? lst lst2) vect) (else (list->vector lst2))))))) (define vector-sort! (lambda (proc vect) (let* ((n (vector-length vect)) (work (make-vector (+ (div n 2) 1)))) (define simple-sort! (lambda (first last) (let loop1 ((i first)) (cond ((< i last) (let ((m (vector-ref vect i)) (k i)) (let loop2 ((j (+ i 1))) (cond ((<= j last) (if (proc (vector-ref vect j) m) (begin (set! m (vector-ref vect j)) (set! k j))) (loop2 (+ j 1))) (else (vector-set! vect k (vector-ref vect i)) (vector-set! vect i m) (loop1 (+ i 1))))))))))) (define sort! (lambda (first last) (cond ((> (- last first) 10) (let ((middle (div (+ first last) 2))) (sort! first middle) (sort! (+ middle 1) last) (let loop ((i first) (p2size 0)) (cond ((> i middle) (let loop ((p1 (+ middle 1)) (p2 0) (p3 first)) (cond ((and (<= p1 last) (< p2 p2size)) (cond ((proc (vector-ref work p2) (vector-ref vect p1)) (vector-set! vect p3 (vector-ref work p2)) (loop p1 (+ p2 1) (+ p3 1))) (else (vector-set! vect p3 (vector-ref vect p1)) (loop (+ p1 1) p2 (+ p3 1))))) (else (let loop ((s2 p2)(d3 p3)) (cond ((< s2 p2size) (vector-set! vect d3 (vector-ref work s2)) (loop (+ s2 1) (+ d3 1))))))))) (else (vector-set! work p2size (vector-ref vect i)) (loop (+ i 1) (+ p2size 1))))))) (else (simple-sort! first last))))) (sort! 0 (- n 1)))))
86f9486216d7f083542095c86b6971c0a3d862d32c8342afaefb19d6e42adff0
haskell/parsec
Perm.hs
{-# LANGUAGE Safe #-} ----------------------------------------------------------------------------- -- | Module : Text . ParserCombinators . Parsec . Perm Copyright : ( c ) 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : -- Stability : provisional -- Portability : portable -- Parsec compatibility module -- ----------------------------------------------------------------------------- module Text.ParserCombinators.Parsec.Perm ( PermParser, permute, (<||>), (<$$>), (<|?>), (<$?>) ) where import Text.Parsec.Perm
null
https://raw.githubusercontent.com/haskell/parsec/38dfc545874dd44c26382d8dd692eb533396c6f5/src/Text/ParserCombinators/Parsec/Perm.hs
haskell
# LANGUAGE Safe # --------------------------------------------------------------------------- | License : BSD-style (see the LICENSE file) Maintainer : Stability : provisional Portability : portable ---------------------------------------------------------------------------
Module : Text . ParserCombinators . Parsec . Perm Copyright : ( c ) 2007 Parsec compatibility module module Text.ParserCombinators.Parsec.Perm ( PermParser, permute, (<||>), (<$$>), (<|?>), (<$?>) ) where import Text.Parsec.Perm
2166d9e2cd58b6f838486b8283362fdaf112d3daa028fba5d65ccc687c4034a6
chiroptical/thinking-with-types
Main.hs
module Main where import Lib main :: IO () main = print "Hello"
null
https://raw.githubusercontent.com/chiroptical/thinking-with-types/781f90f1b08eb94ef3600c5b7da92dfaf9ea4285/Chapter9/app/Main.hs
haskell
module Main where import Lib main :: IO () main = print "Hello"
c8dc8375108959a87740a8af06502d26123590e2fc00e24d2f81174876802a7a
himura/twitter-conduit
Status.hs
module Web.Twitter.Conduit.Status ( -- * Notice -- $notice -- * Timelines mentionsTimeline, userTimeline, homeTimeline, retweetsOfMe, -- * Tweets retweetsId, showId, destroyId, update, retweetId, updateWithMedia, lookup, ) where import Data.Text (Text) import Web.Twitter.Conduit.Api import Web.Twitter.Conduit.Parameters import Web.Twitter.Conduit.Request import Web.Twitter.Types import Prelude hiding (lookup) -- $notice -- -- This module provides aliases of statuses API, for backward compatibility. mentionsTimeline :: APIRequest StatusesMentionsTimeline [Status] mentionsTimeline = statusesMentionsTimeline # DEPRECATED mentionsTimeline " Please use Web . Twitter . Conduit . API.statusesMentionsTimeline " # userTimeline :: UserParam -> APIRequest StatusesUserTimeline [Status] userTimeline = statusesUserTimeline # DEPRECATED userTimeline " Please use Web . Twitter . Conduit . API.statusesUserTimeline " # homeTimeline :: APIRequest StatusesHomeTimeline [Status] homeTimeline = statusesHomeTimeline # DEPRECATED homeTimeline " Please use Web . Twitter . Conduit . API.statusesHomeTimeline " # retweetsOfMe :: APIRequest StatusesRetweetsOfMe [Status] retweetsOfMe = statusesRetweetsOfMe # DEPRECATED retweetsOfMe " Please use Web . Twitter . Conduit . API.statusesRetweetsOfMe " # retweetsId :: StatusId -> APIRequest StatusesRetweetsId [RetweetedStatus] retweetsId = statusesRetweetsId # DEPRECATED retweetsId " Please use Web . Twitter . . API.statusesRetweetsId " # showId :: StatusId -> APIRequest StatusesShowId Status showId = statusesShowId # DEPRECATED showId " Please use Web . Twitter . Conduit . API.statusesShowId " # destroyId :: StatusId -> APIRequest StatusesDestroyId Status destroyId = statusesDestroyId # DEPRECATED destroyId " Please use Web . Twitter . . API.statusesDestroyId " # update :: Text -> APIRequest StatusesUpdate Status update = statusesUpdate # DEPRECATED update " Please use Web . Twitter . . API.statusesUpdate " # retweetId :: StatusId -> APIRequest StatusesRetweetId RetweetedStatus retweetId = statusesRetweetId # DEPRECATED retweetId " Please use Web . Twitter . Conduit . API.statusesRetweetId " # updateWithMedia :: Text -> MediaData -> APIRequest StatusesUpdateWithMedia Status updateWithMedia = statusesUpdateWithMedia # DEPRECATED updateWithMedia " Please use Web . Twitter . Conduit . API.statusesUpdateWithMedia " # lookup :: [StatusId] -> APIRequest StatusesLookup [Status] lookup = statusesLookup # DEPRECATED lookup " Please use Web . Twitter . Conduit . API.statusesLookup " #
null
https://raw.githubusercontent.com/himura/twitter-conduit/a327d7727faf2fb38f54f48ef0a61cbc5537b5d2/src/Web/Twitter/Conduit/Status.hs
haskell
* Notice $notice * Timelines * Tweets $notice This module provides aliases of statuses API, for backward compatibility.
module Web.Twitter.Conduit.Status ( mentionsTimeline, userTimeline, homeTimeline, retweetsOfMe, retweetsId, showId, destroyId, update, retweetId, updateWithMedia, lookup, ) where import Data.Text (Text) import Web.Twitter.Conduit.Api import Web.Twitter.Conduit.Parameters import Web.Twitter.Conduit.Request import Web.Twitter.Types import Prelude hiding (lookup) mentionsTimeline :: APIRequest StatusesMentionsTimeline [Status] mentionsTimeline = statusesMentionsTimeline # DEPRECATED mentionsTimeline " Please use Web . Twitter . Conduit . API.statusesMentionsTimeline " # userTimeline :: UserParam -> APIRequest StatusesUserTimeline [Status] userTimeline = statusesUserTimeline # DEPRECATED userTimeline " Please use Web . Twitter . Conduit . API.statusesUserTimeline " # homeTimeline :: APIRequest StatusesHomeTimeline [Status] homeTimeline = statusesHomeTimeline # DEPRECATED homeTimeline " Please use Web . Twitter . Conduit . API.statusesHomeTimeline " # retweetsOfMe :: APIRequest StatusesRetweetsOfMe [Status] retweetsOfMe = statusesRetweetsOfMe # DEPRECATED retweetsOfMe " Please use Web . Twitter . Conduit . API.statusesRetweetsOfMe " # retweetsId :: StatusId -> APIRequest StatusesRetweetsId [RetweetedStatus] retweetsId = statusesRetweetsId # DEPRECATED retweetsId " Please use Web . Twitter . . API.statusesRetweetsId " # showId :: StatusId -> APIRequest StatusesShowId Status showId = statusesShowId # DEPRECATED showId " Please use Web . Twitter . Conduit . API.statusesShowId " # destroyId :: StatusId -> APIRequest StatusesDestroyId Status destroyId = statusesDestroyId # DEPRECATED destroyId " Please use Web . Twitter . . API.statusesDestroyId " # update :: Text -> APIRequest StatusesUpdate Status update = statusesUpdate # DEPRECATED update " Please use Web . Twitter . . API.statusesUpdate " # retweetId :: StatusId -> APIRequest StatusesRetweetId RetweetedStatus retweetId = statusesRetweetId # DEPRECATED retweetId " Please use Web . Twitter . Conduit . API.statusesRetweetId " # updateWithMedia :: Text -> MediaData -> APIRequest StatusesUpdateWithMedia Status updateWithMedia = statusesUpdateWithMedia # DEPRECATED updateWithMedia " Please use Web . Twitter . Conduit . API.statusesUpdateWithMedia " # lookup :: [StatusId] -> APIRequest StatusesLookup [Status] lookup = statusesLookup # DEPRECATED lookup " Please use Web . Twitter . Conduit . API.statusesLookup " #
f5b90f019bf0ffebd5faeec97b8ae53cd6c4542740158ae48f45b87fd8a659a7
carl-eastlund/mischief
reader.rkt
#lang s-exp syntax/module-reader debug/racket/base
null
https://raw.githubusercontent.com/carl-eastlund/mischief/ce58c3170240f12297e2f98475f53c9514225825/debug/racket/base/lang/reader.rkt
racket
#lang s-exp syntax/module-reader debug/racket/base
87fbe71d6782256d9f1b9cc31079449f7678b6ac0c1116383ccb7a9f0962ca9a
zen-lang/zen
env_test.clj
(ns zen.env-test (:require [matcho.core :as matcho] [clojure.test :refer [deftest is testing]] [zen.core])) (deftest test-envs (def ztx (zen.core/new-context {:paths ["test"] :env {:ESTR "extr" :EINT "99" :ESYM "schema" :ENUM "0.02" :EKEY "some/key"}})) (zen.core/read-ns ztx 'test-env) TODO check why error is returned (zen.core/errors ztx) (matcho/match (zen.core/get-symbol ztx 'test-env/model) {:zen/tags #{'test-env/schema} :home string? :string "extr" :int 99 :key :some/key :num 0.02 :sym 'test-env/schema}))
null
https://raw.githubusercontent.com/zen-lang/zen/d3edf2b79828dd406e3bd4b2bc642a811557b510/test/zen/env_test.clj
clojure
(ns zen.env-test (:require [matcho.core :as matcho] [clojure.test :refer [deftest is testing]] [zen.core])) (deftest test-envs (def ztx (zen.core/new-context {:paths ["test"] :env {:ESTR "extr" :EINT "99" :ESYM "schema" :ENUM "0.02" :EKEY "some/key"}})) (zen.core/read-ns ztx 'test-env) TODO check why error is returned (zen.core/errors ztx) (matcho/match (zen.core/get-symbol ztx 'test-env/model) {:zen/tags #{'test-env/schema} :home string? :string "extr" :int 99 :key :some/key :num 0.02 :sym 'test-env/schema}))
05a28b0cf8c7f9cdcad19195c5d00322030ade86c51e4115e1413533536677eb
cedlemo/OCaml-GI-ctypes-bindings-generator
Tree_view.ml
open Ctypes open Foreign type t = unit ptr let t_typ : t typ = ptr void let create = foreign "gtk_tree_view_new" (void @-> returning (ptr Widget.t_typ)) (*Not implemented gtk_tree_view_new_with_model type interface not implemented*) let append_column = foreign "gtk_tree_view_append_column" (t_typ @-> ptr Tree_view_column.t_typ @-> returning (int32_t)) let collapse_all = foreign "gtk_tree_view_collapse_all" (t_typ @-> returning (void)) let collapse_row = foreign "gtk_tree_view_collapse_row" (t_typ @-> ptr Tree_path.t_typ @-> returning (bool)) let columns_autosize = foreign "gtk_tree_view_columns_autosize" (t_typ @-> returning (void)) let convert_bin_window_to_tree_coords self bx by = let convert_bin_window_to_tree_coords_raw = foreign "gtk_tree_view_convert_bin_window_to_tree_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let tx_ptr = allocate int32_t Int32.zero in let ty_ptr = allocate int32_t Int32.zero in let ret = convert_bin_window_to_tree_coords_raw self bx by tx_ptr ty_ptr in let tx = !@ tx_ptr in let ty = !@ ty_ptr in (tx, ty) let convert_bin_window_to_widget_coords self bx by = let convert_bin_window_to_widget_coords_raw = foreign "gtk_tree_view_convert_bin_window_to_widget_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let wx_ptr = allocate int32_t Int32.zero in let wy_ptr = allocate int32_t Int32.zero in let ret = convert_bin_window_to_widget_coords_raw self bx by wx_ptr wy_ptr in let wx = !@ wx_ptr in let wy = !@ wy_ptr in (wx, wy) let convert_tree_to_bin_window_coords self tx ty = let convert_tree_to_bin_window_coords_raw = foreign "gtk_tree_view_convert_tree_to_bin_window_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let bx_ptr = allocate int32_t Int32.zero in let by_ptr = allocate int32_t Int32.zero in let ret = convert_tree_to_bin_window_coords_raw self tx ty bx_ptr by_ptr in let bx = !@ bx_ptr in let by = !@ by_ptr in (bx, by) let convert_tree_to_widget_coords self tx ty = let convert_tree_to_widget_coords_raw = foreign "gtk_tree_view_convert_tree_to_widget_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let wx_ptr = allocate int32_t Int32.zero in let wy_ptr = allocate int32_t Int32.zero in let ret = convert_tree_to_widget_coords_raw self tx ty wx_ptr wy_ptr in let wx = !@ wx_ptr in let wy = !@ wy_ptr in (wx, wy) let convert_widget_to_bin_window_coords self wx wy = let convert_widget_to_bin_window_coords_raw = foreign "gtk_tree_view_convert_widget_to_bin_window_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let bx_ptr = allocate int32_t Int32.zero in let by_ptr = allocate int32_t Int32.zero in let ret = convert_widget_to_bin_window_coords_raw self wx wy bx_ptr by_ptr in let bx = !@ bx_ptr in let by = !@ by_ptr in (bx, by) let convert_widget_to_tree_coords self wx wy = let convert_widget_to_tree_coords_raw = foreign "gtk_tree_view_convert_widget_to_tree_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let tx_ptr = allocate int32_t Int32.zero in let ty_ptr = allocate int32_t Int32.zero in let ret = convert_widget_to_tree_coords_raw self wx wy tx_ptr ty_ptr in let tx = !@ tx_ptr in let ty = !@ ty_ptr in (tx, ty) let create_row_drag_icon = foreign "gtk_tree_view_create_row_drag_icon" (t_typ @-> ptr Tree_path.t_typ @-> returning (ptr Surface.t_typ)) (*Not implemented gtk_tree_view_enable_model_drag_dest type C Array type for Types.Array tag not implemented*) (*Not implemented gtk_tree_view_enable_model_drag_source type C Array type for Types.Array tag not implemented*) let expand_all = foreign "gtk_tree_view_expand_all" (t_typ @-> returning (void)) let expand_row = foreign "gtk_tree_view_expand_row" (t_typ @-> ptr Tree_path.t_typ @-> bool @-> returning (bool)) let expand_to_path = foreign "gtk_tree_view_expand_to_path" (t_typ @-> ptr Tree_path.t_typ @-> returning (void)) let get_activate_on_single_click = foreign "gtk_tree_view_get_activate_on_single_click" (t_typ @-> returning (bool)) let get_background_area self path column = let get_background_area_raw = foreign "gtk_tree_view_get_background_area" (t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr (Rectangle.t_typ) @-> returning (void)) in let rect_ptr = allocate Rectangle.t_typ (make Rectangle.t_typ) in let ret = get_background_area_raw self path column rect_ptr in let rect = !@ rect_ptr in (rect) let get_bin_window = foreign "gtk_tree_view_get_bin_window" (t_typ @-> returning (ptr_opt Window.t_typ)) let get_cell_area self path column = let get_cell_area_raw = foreign "gtk_tree_view_get_cell_area" (t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr (Rectangle.t_typ) @-> returning (void)) in let rect_ptr = allocate Rectangle.t_typ (make Rectangle.t_typ) in let ret = get_cell_area_raw self path column rect_ptr in let rect = !@ rect_ptr in (rect) let get_column = foreign "gtk_tree_view_get_column" (t_typ @-> int32_t @-> returning (ptr_opt Tree_view_column.t_typ)) let get_columns = foreign "gtk_tree_view_get_columns" (t_typ @-> returning (ptr List.t_typ)) let get_cursor self = let get_cursor_raw = foreign "gtk_tree_view_get_cursor" (t_typ @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (ptr_opt Tree_view_column.t_typ) @-> returning (void)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let focus_column_ptr = allocate (ptr_opt Tree_view_column.t_typ) None in let ret = get_cursor_raw self path_ptr focus_column_ptr in let path = !@ path_ptr in let focus_column = !@ focus_column_ptr in (path, focus_column) let get_dest_row_at_pos self drag_x drag_y = let get_dest_row_at_pos_raw = foreign "gtk_tree_view_get_dest_row_at_pos" (t_typ @-> int32_t @-> int32_t @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (Tree_view_drop_position.t_view) @-> returning (bool)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let pos_ptr = allocate Tree_view_drop_position.t_view (Tree_view_drop_position.t_view.of_value (Unsigned.UInt32.zero)) in let ret = get_dest_row_at_pos_raw self drag_x drag_y path_ptr pos_ptr in let path = !@ path_ptr in let pos = (!@ pos_ptr) in (ret, path, pos) let get_drag_dest_row self = let get_drag_dest_row_raw = foreign "gtk_tree_view_get_drag_dest_row" (t_typ @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (Tree_view_drop_position.t_view) @-> returning (void)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let pos_ptr = allocate Tree_view_drop_position.t_view (Tree_view_drop_position.t_view.of_value (Unsigned.UInt32.zero)) in let ret = get_drag_dest_row_raw self path_ptr pos_ptr in let path = !@ path_ptr in let pos = (!@ pos_ptr) in (path, pos) let get_enable_search = foreign "gtk_tree_view_get_enable_search" (t_typ @-> returning (bool)) let get_enable_tree_lines = foreign "gtk_tree_view_get_enable_tree_lines" (t_typ @-> returning (bool)) let get_expander_column = foreign "gtk_tree_view_get_expander_column" (t_typ @-> returning (ptr Tree_view_column.t_typ)) let get_fixed_height_mode = foreign "gtk_tree_view_get_fixed_height_mode" (t_typ @-> returning (bool)) let get_grid_lines = foreign "gtk_tree_view_get_grid_lines" (t_typ @-> returning (Tree_view_grid_lines.t_view)) let get_hadjustment = foreign "gtk_tree_view_get_hadjustment" (t_typ @-> returning (ptr Adjustment.t_typ)) let get_headers_clickable = foreign "gtk_tree_view_get_headers_clickable" (t_typ @-> returning (bool)) let get_headers_visible = foreign "gtk_tree_view_get_headers_visible" (t_typ @-> returning (bool)) let get_hover_expand = foreign "gtk_tree_view_get_hover_expand" (t_typ @-> returning (bool)) let get_hover_selection = foreign "gtk_tree_view_get_hover_selection" (t_typ @-> returning (bool)) let get_level_indentation = foreign "gtk_tree_view_get_level_indentation" (t_typ @-> returning (int32_t)) (*Not implemented gtk_tree_view_get_model return type interface not handled*) let get_n_columns = foreign "gtk_tree_view_get_n_columns" (t_typ @-> returning (uint32_t)) let get_path_at_pos self x y = let get_path_at_pos_raw = foreign "gtk_tree_view_get_path_at_pos" (t_typ @-> int32_t @-> int32_t @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (ptr_opt Tree_view_column.t_typ) @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (bool)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let column_ptr = allocate (ptr_opt Tree_view_column.t_typ) None in let cell_x_ptr = allocate int32_t Int32.zero in let cell_y_ptr = allocate int32_t Int32.zero in let ret = get_path_at_pos_raw self x y path_ptr column_ptr cell_x_ptr cell_y_ptr in let path = !@ path_ptr in let column = !@ column_ptr in let cell_x = !@ cell_x_ptr in let cell_y = !@ cell_y_ptr in (ret, path, column, cell_x, cell_y) let get_reorderable = foreign "gtk_tree_view_get_reorderable" (t_typ @-> returning (bool)) let get_rubber_banding = foreign "gtk_tree_view_get_rubber_banding" (t_typ @-> returning (bool)) let get_rules_hint = foreign "gtk_tree_view_get_rules_hint" (t_typ @-> returning (bool)) let get_search_column = foreign "gtk_tree_view_get_search_column" (t_typ @-> returning (int32_t)) let get_search_entry = foreign "gtk_tree_view_get_search_entry" (t_typ @-> returning (ptr Entry.t_typ)) let get_selection = foreign "gtk_tree_view_get_selection" (t_typ @-> returning (ptr Tree_selection.t_typ)) let get_show_expanders = foreign "gtk_tree_view_get_show_expanders" (t_typ @-> returning (bool)) let get_tooltip_column = foreign "gtk_tree_view_get_tooltip_column" (t_typ @-> returning (int32_t)) (*Not implemented gtk_tree_view_get_tooltip_context type interface not implemented*) let get_vadjustment = foreign "gtk_tree_view_get_vadjustment" (t_typ @-> returning (ptr Adjustment.t_typ)) let get_visible_range self = let get_visible_range_raw = foreign "gtk_tree_view_get_visible_range" (t_typ @-> ptr (ptr Tree_path.t_typ) @-> ptr (ptr Tree_path.t_typ) @-> returning (bool)) in let start_path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let end_path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let ret = get_visible_range_raw self start_path_ptr end_path_ptr in let start_path = !@ start_path_ptr in let end_path = !@ end_path_ptr in (ret, start_path, end_path) let get_visible_rect self = let get_visible_rect_raw = foreign "gtk_tree_view_get_visible_rect" (t_typ @-> ptr (Rectangle.t_typ) @-> returning (void)) in let visible_rect_ptr = allocate Rectangle.t_typ (make Rectangle.t_typ) in let ret = get_visible_rect_raw self visible_rect_ptr in let visible_rect = !@ visible_rect_ptr in (visible_rect) let insert_column = foreign "gtk_tree_view_insert_column" (t_typ @-> ptr Tree_view_column.t_typ @-> int32_t @-> returning (int32_t)) (*Not implemented gtk_tree_view_insert_column_with_data_func type callback not implemented*) let is_blank_at_pos self x y = let is_blank_at_pos_raw = foreign "gtk_tree_view_is_blank_at_pos" (t_typ @-> int32_t @-> int32_t @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (ptr_opt Tree_view_column.t_typ) @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (bool)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let column_ptr = allocate (ptr_opt Tree_view_column.t_typ) None in let cell_x_ptr = allocate int32_t Int32.zero in let cell_y_ptr = allocate int32_t Int32.zero in let ret = is_blank_at_pos_raw self x y path_ptr column_ptr cell_x_ptr cell_y_ptr in let path = !@ path_ptr in let column = !@ column_ptr in let cell_x = !@ cell_x_ptr in let cell_y = !@ cell_y_ptr in (ret, path, column, cell_x, cell_y) let is_rubber_banding_active = foreign "gtk_tree_view_is_rubber_banding_active" (t_typ @-> returning (bool)) (*Not implemented gtk_tree_view_map_expanded_rows type callback not implemented*) let move_column_after = foreign "gtk_tree_view_move_column_after" (t_typ @-> ptr Tree_view_column.t_typ @-> ptr_opt Tree_view_column.t_typ @-> returning (void)) let remove_column = foreign "gtk_tree_view_remove_column" (t_typ @-> ptr Tree_view_column.t_typ @-> returning (int32_t)) let row_activated = foreign "gtk_tree_view_row_activated" (t_typ @-> ptr Tree_path.t_typ @-> ptr Tree_view_column.t_typ @-> returning (void)) let row_expanded = foreign "gtk_tree_view_row_expanded" (t_typ @-> ptr Tree_path.t_typ @-> returning (bool)) let scroll_to_cell = foreign "gtk_tree_view_scroll_to_cell" (t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> bool @-> float @-> float @-> returning (void)) let scroll_to_point = foreign "gtk_tree_view_scroll_to_point" (t_typ @-> int32_t @-> int32_t @-> returning (void)) let set_activate_on_single_click = foreign "gtk_tree_view_set_activate_on_single_click" (t_typ @-> bool @-> returning (void)) (*Not implemented gtk_tree_view_set_column_drag_function type callback not implemented*) let set_cursor = foreign "gtk_tree_view_set_cursor" (t_typ @-> ptr Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> bool @-> returning (void)) let set_cursor_on_cell = foreign "gtk_tree_view_set_cursor_on_cell" (t_typ @-> ptr Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr_opt Cell_renderer.t_typ @-> bool @-> returning (void)) (*Not implemented gtk_tree_view_set_destroy_count_func type callback not implemented*) let set_drag_dest_row = foreign "gtk_tree_view_set_drag_dest_row" (t_typ @-> ptr_opt Tree_path.t_typ @-> Tree_view_drop_position.t_view @-> returning (void)) let set_enable_search = foreign "gtk_tree_view_set_enable_search" (t_typ @-> bool @-> returning (void)) let set_enable_tree_lines = foreign "gtk_tree_view_set_enable_tree_lines" (t_typ @-> bool @-> returning (void)) let set_expander_column = foreign "gtk_tree_view_set_expander_column" (t_typ @-> ptr Tree_view_column.t_typ @-> returning (void)) let set_fixed_height_mode = foreign "gtk_tree_view_set_fixed_height_mode" (t_typ @-> bool @-> returning (void)) let set_grid_lines = foreign "gtk_tree_view_set_grid_lines" (t_typ @-> Tree_view_grid_lines.t_view @-> returning (void)) let set_hadjustment = foreign "gtk_tree_view_set_hadjustment" (t_typ @-> ptr_opt Adjustment.t_typ @-> returning (void)) let set_headers_clickable = foreign "gtk_tree_view_set_headers_clickable" (t_typ @-> bool @-> returning (void)) let set_headers_visible = foreign "gtk_tree_view_set_headers_visible" (t_typ @-> bool @-> returning (void)) let set_hover_expand = foreign "gtk_tree_view_set_hover_expand" (t_typ @-> bool @-> returning (void)) let set_hover_selection = foreign "gtk_tree_view_set_hover_selection" (t_typ @-> bool @-> returning (void)) let set_level_indentation = foreign "gtk_tree_view_set_level_indentation" (t_typ @-> int32_t @-> returning (void)) (*Not implemented gtk_tree_view_set_model type interface not implemented*) let set_reorderable = foreign "gtk_tree_view_set_reorderable" (t_typ @-> bool @-> returning (void)) (*Not implemented gtk_tree_view_set_row_separator_func type callback not implemented*) let set_rubber_banding = foreign "gtk_tree_view_set_rubber_banding" (t_typ @-> bool @-> returning (void)) let set_rules_hint = foreign "gtk_tree_view_set_rules_hint" (t_typ @-> bool @-> returning (void)) let set_search_column = foreign "gtk_tree_view_set_search_column" (t_typ @-> int32_t @-> returning (void)) let set_search_entry = foreign "gtk_tree_view_set_search_entry" (t_typ @-> ptr_opt Entry.t_typ @-> returning (void)) (*Not implemented gtk_tree_view_set_search_equal_func type callback not implemented*) (*Not implemented gtk_tree_view_set_search_position_func type callback not implemented*) let set_show_expanders = foreign "gtk_tree_view_set_show_expanders" (t_typ @-> bool @-> returning (void)) let set_tooltip_cell = foreign "gtk_tree_view_set_tooltip_cell" (t_typ @-> ptr Tooltip.t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr_opt Cell_renderer.t_typ @-> returning (void)) let set_tooltip_column = foreign "gtk_tree_view_set_tooltip_column" (t_typ @-> int32_t @-> returning (void)) let set_tooltip_row = foreign "gtk_tree_view_set_tooltip_row" (t_typ @-> ptr Tooltip.t_typ @-> ptr Tree_path.t_typ @-> returning (void)) let set_vadjustment = foreign "gtk_tree_view_set_vadjustment" (t_typ @-> ptr_opt Adjustment.t_typ @-> returning (void)) let unset_rows_drag_dest = foreign "gtk_tree_view_unset_rows_drag_dest" (t_typ @-> returning (void)) let unset_rows_drag_source = foreign "gtk_tree_view_unset_rows_drag_source" (t_typ @-> returning (void))
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Tree_view.ml
ocaml
Not implemented gtk_tree_view_new_with_model type interface not implemented Not implemented gtk_tree_view_enable_model_drag_dest type C Array type for Types.Array tag not implemented Not implemented gtk_tree_view_enable_model_drag_source type C Array type for Types.Array tag not implemented Not implemented gtk_tree_view_get_model return type interface not handled Not implemented gtk_tree_view_get_tooltip_context type interface not implemented Not implemented gtk_tree_view_insert_column_with_data_func type callback not implemented Not implemented gtk_tree_view_map_expanded_rows type callback not implemented Not implemented gtk_tree_view_set_column_drag_function type callback not implemented Not implemented gtk_tree_view_set_destroy_count_func type callback not implemented Not implemented gtk_tree_view_set_model type interface not implemented Not implemented gtk_tree_view_set_row_separator_func type callback not implemented Not implemented gtk_tree_view_set_search_equal_func type callback not implemented Not implemented gtk_tree_view_set_search_position_func type callback not implemented
open Ctypes open Foreign type t = unit ptr let t_typ : t typ = ptr void let create = foreign "gtk_tree_view_new" (void @-> returning (ptr Widget.t_typ)) let append_column = foreign "gtk_tree_view_append_column" (t_typ @-> ptr Tree_view_column.t_typ @-> returning (int32_t)) let collapse_all = foreign "gtk_tree_view_collapse_all" (t_typ @-> returning (void)) let collapse_row = foreign "gtk_tree_view_collapse_row" (t_typ @-> ptr Tree_path.t_typ @-> returning (bool)) let columns_autosize = foreign "gtk_tree_view_columns_autosize" (t_typ @-> returning (void)) let convert_bin_window_to_tree_coords self bx by = let convert_bin_window_to_tree_coords_raw = foreign "gtk_tree_view_convert_bin_window_to_tree_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let tx_ptr = allocate int32_t Int32.zero in let ty_ptr = allocate int32_t Int32.zero in let ret = convert_bin_window_to_tree_coords_raw self bx by tx_ptr ty_ptr in let tx = !@ tx_ptr in let ty = !@ ty_ptr in (tx, ty) let convert_bin_window_to_widget_coords self bx by = let convert_bin_window_to_widget_coords_raw = foreign "gtk_tree_view_convert_bin_window_to_widget_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let wx_ptr = allocate int32_t Int32.zero in let wy_ptr = allocate int32_t Int32.zero in let ret = convert_bin_window_to_widget_coords_raw self bx by wx_ptr wy_ptr in let wx = !@ wx_ptr in let wy = !@ wy_ptr in (wx, wy) let convert_tree_to_bin_window_coords self tx ty = let convert_tree_to_bin_window_coords_raw = foreign "gtk_tree_view_convert_tree_to_bin_window_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let bx_ptr = allocate int32_t Int32.zero in let by_ptr = allocate int32_t Int32.zero in let ret = convert_tree_to_bin_window_coords_raw self tx ty bx_ptr by_ptr in let bx = !@ bx_ptr in let by = !@ by_ptr in (bx, by) let convert_tree_to_widget_coords self tx ty = let convert_tree_to_widget_coords_raw = foreign "gtk_tree_view_convert_tree_to_widget_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let wx_ptr = allocate int32_t Int32.zero in let wy_ptr = allocate int32_t Int32.zero in let ret = convert_tree_to_widget_coords_raw self tx ty wx_ptr wy_ptr in let wx = !@ wx_ptr in let wy = !@ wy_ptr in (wx, wy) let convert_widget_to_bin_window_coords self wx wy = let convert_widget_to_bin_window_coords_raw = foreign "gtk_tree_view_convert_widget_to_bin_window_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let bx_ptr = allocate int32_t Int32.zero in let by_ptr = allocate int32_t Int32.zero in let ret = convert_widget_to_bin_window_coords_raw self wx wy bx_ptr by_ptr in let bx = !@ bx_ptr in let by = !@ by_ptr in (bx, by) let convert_widget_to_tree_coords self wx wy = let convert_widget_to_tree_coords_raw = foreign "gtk_tree_view_convert_widget_to_tree_coords" (t_typ @-> int32_t @-> int32_t @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (void)) in let tx_ptr = allocate int32_t Int32.zero in let ty_ptr = allocate int32_t Int32.zero in let ret = convert_widget_to_tree_coords_raw self wx wy tx_ptr ty_ptr in let tx = !@ tx_ptr in let ty = !@ ty_ptr in (tx, ty) let create_row_drag_icon = foreign "gtk_tree_view_create_row_drag_icon" (t_typ @-> ptr Tree_path.t_typ @-> returning (ptr Surface.t_typ)) let expand_all = foreign "gtk_tree_view_expand_all" (t_typ @-> returning (void)) let expand_row = foreign "gtk_tree_view_expand_row" (t_typ @-> ptr Tree_path.t_typ @-> bool @-> returning (bool)) let expand_to_path = foreign "gtk_tree_view_expand_to_path" (t_typ @-> ptr Tree_path.t_typ @-> returning (void)) let get_activate_on_single_click = foreign "gtk_tree_view_get_activate_on_single_click" (t_typ @-> returning (bool)) let get_background_area self path column = let get_background_area_raw = foreign "gtk_tree_view_get_background_area" (t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr (Rectangle.t_typ) @-> returning (void)) in let rect_ptr = allocate Rectangle.t_typ (make Rectangle.t_typ) in let ret = get_background_area_raw self path column rect_ptr in let rect = !@ rect_ptr in (rect) let get_bin_window = foreign "gtk_tree_view_get_bin_window" (t_typ @-> returning (ptr_opt Window.t_typ)) let get_cell_area self path column = let get_cell_area_raw = foreign "gtk_tree_view_get_cell_area" (t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr (Rectangle.t_typ) @-> returning (void)) in let rect_ptr = allocate Rectangle.t_typ (make Rectangle.t_typ) in let ret = get_cell_area_raw self path column rect_ptr in let rect = !@ rect_ptr in (rect) let get_column = foreign "gtk_tree_view_get_column" (t_typ @-> int32_t @-> returning (ptr_opt Tree_view_column.t_typ)) let get_columns = foreign "gtk_tree_view_get_columns" (t_typ @-> returning (ptr List.t_typ)) let get_cursor self = let get_cursor_raw = foreign "gtk_tree_view_get_cursor" (t_typ @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (ptr_opt Tree_view_column.t_typ) @-> returning (void)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let focus_column_ptr = allocate (ptr_opt Tree_view_column.t_typ) None in let ret = get_cursor_raw self path_ptr focus_column_ptr in let path = !@ path_ptr in let focus_column = !@ focus_column_ptr in (path, focus_column) let get_dest_row_at_pos self drag_x drag_y = let get_dest_row_at_pos_raw = foreign "gtk_tree_view_get_dest_row_at_pos" (t_typ @-> int32_t @-> int32_t @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (Tree_view_drop_position.t_view) @-> returning (bool)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let pos_ptr = allocate Tree_view_drop_position.t_view (Tree_view_drop_position.t_view.of_value (Unsigned.UInt32.zero)) in let ret = get_dest_row_at_pos_raw self drag_x drag_y path_ptr pos_ptr in let path = !@ path_ptr in let pos = (!@ pos_ptr) in (ret, path, pos) let get_drag_dest_row self = let get_drag_dest_row_raw = foreign "gtk_tree_view_get_drag_dest_row" (t_typ @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (Tree_view_drop_position.t_view) @-> returning (void)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let pos_ptr = allocate Tree_view_drop_position.t_view (Tree_view_drop_position.t_view.of_value (Unsigned.UInt32.zero)) in let ret = get_drag_dest_row_raw self path_ptr pos_ptr in let path = !@ path_ptr in let pos = (!@ pos_ptr) in (path, pos) let get_enable_search = foreign "gtk_tree_view_get_enable_search" (t_typ @-> returning (bool)) let get_enable_tree_lines = foreign "gtk_tree_view_get_enable_tree_lines" (t_typ @-> returning (bool)) let get_expander_column = foreign "gtk_tree_view_get_expander_column" (t_typ @-> returning (ptr Tree_view_column.t_typ)) let get_fixed_height_mode = foreign "gtk_tree_view_get_fixed_height_mode" (t_typ @-> returning (bool)) let get_grid_lines = foreign "gtk_tree_view_get_grid_lines" (t_typ @-> returning (Tree_view_grid_lines.t_view)) let get_hadjustment = foreign "gtk_tree_view_get_hadjustment" (t_typ @-> returning (ptr Adjustment.t_typ)) let get_headers_clickable = foreign "gtk_tree_view_get_headers_clickable" (t_typ @-> returning (bool)) let get_headers_visible = foreign "gtk_tree_view_get_headers_visible" (t_typ @-> returning (bool)) let get_hover_expand = foreign "gtk_tree_view_get_hover_expand" (t_typ @-> returning (bool)) let get_hover_selection = foreign "gtk_tree_view_get_hover_selection" (t_typ @-> returning (bool)) let get_level_indentation = foreign "gtk_tree_view_get_level_indentation" (t_typ @-> returning (int32_t)) let get_n_columns = foreign "gtk_tree_view_get_n_columns" (t_typ @-> returning (uint32_t)) let get_path_at_pos self x y = let get_path_at_pos_raw = foreign "gtk_tree_view_get_path_at_pos" (t_typ @-> int32_t @-> int32_t @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (ptr_opt Tree_view_column.t_typ) @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (bool)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let column_ptr = allocate (ptr_opt Tree_view_column.t_typ) None in let cell_x_ptr = allocate int32_t Int32.zero in let cell_y_ptr = allocate int32_t Int32.zero in let ret = get_path_at_pos_raw self x y path_ptr column_ptr cell_x_ptr cell_y_ptr in let path = !@ path_ptr in let column = !@ column_ptr in let cell_x = !@ cell_x_ptr in let cell_y = !@ cell_y_ptr in (ret, path, column, cell_x, cell_y) let get_reorderable = foreign "gtk_tree_view_get_reorderable" (t_typ @-> returning (bool)) let get_rubber_banding = foreign "gtk_tree_view_get_rubber_banding" (t_typ @-> returning (bool)) let get_rules_hint = foreign "gtk_tree_view_get_rules_hint" (t_typ @-> returning (bool)) let get_search_column = foreign "gtk_tree_view_get_search_column" (t_typ @-> returning (int32_t)) let get_search_entry = foreign "gtk_tree_view_get_search_entry" (t_typ @-> returning (ptr Entry.t_typ)) let get_selection = foreign "gtk_tree_view_get_selection" (t_typ @-> returning (ptr Tree_selection.t_typ)) let get_show_expanders = foreign "gtk_tree_view_get_show_expanders" (t_typ @-> returning (bool)) let get_tooltip_column = foreign "gtk_tree_view_get_tooltip_column" (t_typ @-> returning (int32_t)) let get_vadjustment = foreign "gtk_tree_view_get_vadjustment" (t_typ @-> returning (ptr Adjustment.t_typ)) let get_visible_range self = let get_visible_range_raw = foreign "gtk_tree_view_get_visible_range" (t_typ @-> ptr (ptr Tree_path.t_typ) @-> ptr (ptr Tree_path.t_typ) @-> returning (bool)) in let start_path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let end_path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let ret = get_visible_range_raw self start_path_ptr end_path_ptr in let start_path = !@ start_path_ptr in let end_path = !@ end_path_ptr in (ret, start_path, end_path) let get_visible_rect self = let get_visible_rect_raw = foreign "gtk_tree_view_get_visible_rect" (t_typ @-> ptr (Rectangle.t_typ) @-> returning (void)) in let visible_rect_ptr = allocate Rectangle.t_typ (make Rectangle.t_typ) in let ret = get_visible_rect_raw self visible_rect_ptr in let visible_rect = !@ visible_rect_ptr in (visible_rect) let insert_column = foreign "gtk_tree_view_insert_column" (t_typ @-> ptr Tree_view_column.t_typ @-> int32_t @-> returning (int32_t)) let is_blank_at_pos self x y = let is_blank_at_pos_raw = foreign "gtk_tree_view_is_blank_at_pos" (t_typ @-> int32_t @-> int32_t @-> ptr (ptr_opt Tree_path.t_typ) @-> ptr (ptr_opt Tree_view_column.t_typ) @-> ptr (int32_t) @-> ptr (int32_t) @-> returning (bool)) in let path_ptr = allocate (ptr_opt Tree_path.t_typ) None in let column_ptr = allocate (ptr_opt Tree_view_column.t_typ) None in let cell_x_ptr = allocate int32_t Int32.zero in let cell_y_ptr = allocate int32_t Int32.zero in let ret = is_blank_at_pos_raw self x y path_ptr column_ptr cell_x_ptr cell_y_ptr in let path = !@ path_ptr in let column = !@ column_ptr in let cell_x = !@ cell_x_ptr in let cell_y = !@ cell_y_ptr in (ret, path, column, cell_x, cell_y) let is_rubber_banding_active = foreign "gtk_tree_view_is_rubber_banding_active" (t_typ @-> returning (bool)) let move_column_after = foreign "gtk_tree_view_move_column_after" (t_typ @-> ptr Tree_view_column.t_typ @-> ptr_opt Tree_view_column.t_typ @-> returning (void)) let remove_column = foreign "gtk_tree_view_remove_column" (t_typ @-> ptr Tree_view_column.t_typ @-> returning (int32_t)) let row_activated = foreign "gtk_tree_view_row_activated" (t_typ @-> ptr Tree_path.t_typ @-> ptr Tree_view_column.t_typ @-> returning (void)) let row_expanded = foreign "gtk_tree_view_row_expanded" (t_typ @-> ptr Tree_path.t_typ @-> returning (bool)) let scroll_to_cell = foreign "gtk_tree_view_scroll_to_cell" (t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> bool @-> float @-> float @-> returning (void)) let scroll_to_point = foreign "gtk_tree_view_scroll_to_point" (t_typ @-> int32_t @-> int32_t @-> returning (void)) let set_activate_on_single_click = foreign "gtk_tree_view_set_activate_on_single_click" (t_typ @-> bool @-> returning (void)) let set_cursor = foreign "gtk_tree_view_set_cursor" (t_typ @-> ptr Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> bool @-> returning (void)) let set_cursor_on_cell = foreign "gtk_tree_view_set_cursor_on_cell" (t_typ @-> ptr Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr_opt Cell_renderer.t_typ @-> bool @-> returning (void)) let set_drag_dest_row = foreign "gtk_tree_view_set_drag_dest_row" (t_typ @-> ptr_opt Tree_path.t_typ @-> Tree_view_drop_position.t_view @-> returning (void)) let set_enable_search = foreign "gtk_tree_view_set_enable_search" (t_typ @-> bool @-> returning (void)) let set_enable_tree_lines = foreign "gtk_tree_view_set_enable_tree_lines" (t_typ @-> bool @-> returning (void)) let set_expander_column = foreign "gtk_tree_view_set_expander_column" (t_typ @-> ptr Tree_view_column.t_typ @-> returning (void)) let set_fixed_height_mode = foreign "gtk_tree_view_set_fixed_height_mode" (t_typ @-> bool @-> returning (void)) let set_grid_lines = foreign "gtk_tree_view_set_grid_lines" (t_typ @-> Tree_view_grid_lines.t_view @-> returning (void)) let set_hadjustment = foreign "gtk_tree_view_set_hadjustment" (t_typ @-> ptr_opt Adjustment.t_typ @-> returning (void)) let set_headers_clickable = foreign "gtk_tree_view_set_headers_clickable" (t_typ @-> bool @-> returning (void)) let set_headers_visible = foreign "gtk_tree_view_set_headers_visible" (t_typ @-> bool @-> returning (void)) let set_hover_expand = foreign "gtk_tree_view_set_hover_expand" (t_typ @-> bool @-> returning (void)) let set_hover_selection = foreign "gtk_tree_view_set_hover_selection" (t_typ @-> bool @-> returning (void)) let set_level_indentation = foreign "gtk_tree_view_set_level_indentation" (t_typ @-> int32_t @-> returning (void)) let set_reorderable = foreign "gtk_tree_view_set_reorderable" (t_typ @-> bool @-> returning (void)) let set_rubber_banding = foreign "gtk_tree_view_set_rubber_banding" (t_typ @-> bool @-> returning (void)) let set_rules_hint = foreign "gtk_tree_view_set_rules_hint" (t_typ @-> bool @-> returning (void)) let set_search_column = foreign "gtk_tree_view_set_search_column" (t_typ @-> int32_t @-> returning (void)) let set_search_entry = foreign "gtk_tree_view_set_search_entry" (t_typ @-> ptr_opt Entry.t_typ @-> returning (void)) let set_show_expanders = foreign "gtk_tree_view_set_show_expanders" (t_typ @-> bool @-> returning (void)) let set_tooltip_cell = foreign "gtk_tree_view_set_tooltip_cell" (t_typ @-> ptr Tooltip.t_typ @-> ptr_opt Tree_path.t_typ @-> ptr_opt Tree_view_column.t_typ @-> ptr_opt Cell_renderer.t_typ @-> returning (void)) let set_tooltip_column = foreign "gtk_tree_view_set_tooltip_column" (t_typ @-> int32_t @-> returning (void)) let set_tooltip_row = foreign "gtk_tree_view_set_tooltip_row" (t_typ @-> ptr Tooltip.t_typ @-> ptr Tree_path.t_typ @-> returning (void)) let set_vadjustment = foreign "gtk_tree_view_set_vadjustment" (t_typ @-> ptr_opt Adjustment.t_typ @-> returning (void)) let unset_rows_drag_dest = foreign "gtk_tree_view_unset_rows_drag_dest" (t_typ @-> returning (void)) let unset_rows_drag_source = foreign "gtk_tree_view_unset_rows_drag_source" (t_typ @-> returning (void))
c425dd31fd2afeec11381cf174ee1503e15ffa6454f264297b14dca616e3ec11
cljdoc/cljdoc-analyzer
main_test.clj
(ns cljdoc-analyzer.metagetta.main-test "Load all `test-sources/*` namespaces and test various things about them." (:require [clojure.test :as t] [cljdoc-analyzer.metagetta.main :as main])) (defn- in? [coll elem] (some #(= elem %) coll)) (defn- concat-res [& args] (remove nil? (apply concat args))) (defn- expected-result [& opts] (concat-res (when (in? opts :clj) (list {:name 'metagetta-test.cljs-macro-functions.foo.core, :publics [{:arglists '([a b]), :file "metagetta_test/cljs_macro_functions/foo/core.clj", :line 6, :name 'add, :type :macro}]})) (when (in? opts :cljs) (list {:name 'metagetta-test.cljs-macro-functions.foo.core :publics [{:arglists '([a b]) :file "metagetta_test/cljs_macro_functions/foo/core.cljs" :line 6 :name 'add :type :var}]} {:name 'metagetta-test.cljs-macro-functions.usage :publics [{:arglists '([]) :file "metagetta_test/cljs_macro_functions/usage.cljs" :line 19 :name 'example :type :var}]})) (list {:name 'metagetta-test.test-ns1.altered :publics [{:name 'altered-def-with-absolute-file :type :var :file "metagetta_test/test_ns1/record.cljc" :line 7} {:name 'altered-fn-with-source-relative-file :arglists '([]) :type :var :file "metagetta_test/test_ns1/multimethod.cljc" :line 14} {:name 'altered-macro-with-root-relative-file :arglists '([]) :type :macro :doc "added doc\n" :file "metagetta_test/test_ns1/multimethod.cljc" :line 3} {:arglists '([x]), :doc "Operation 1 docs\n", :file "metagetta_test/test_ns1/protocols.cljc", :line 6, :name 'fn-pointing-to-protocol-fn, :type :var}]} {:name 'metagetta-test.test-ns1.macro :publics [{:name 'macdoc :arglists '([a b c d]) :type :macro :doc "Macro docs\n" :file "metagetta_test/test_ns1/macro.cljc" :line 23} {:name 'simple :arglists '([a b]) :type :macro :file "metagetta_test/test_ns1/macro.cljc" :line 11} {:name 'varargs :arglists '([a & xs]) :type :macro :file "metagetta_test/test_ns1/macro.cljc" :line 17}]}) (when (not (in? opts :mranderson/inlined)) (list {:name 'metagetta-test.test-ns1.mranderson-inlined-ns, :publics [{:arglists '([a]), :file "metagetta_test/test_ns1/mranderson_inlined_ns.cljc", :line 6 :name 'an-inlined-var :type :var}] :mranderson/inlined true})) (list {:name 'metagetta-test.test-ns1.multiarity :publics [{:name 'multiarity :arglists '([] [a] [a b] [a b c d]) :type :var :doc "Multiarity comment\n" :file "metagetta_test/test_ns1/multiarity.cljc" :line 7}]} {:name 'metagetta-test.test-ns1.multimethod :publics [{:name 'start :type :multimethod :file "metagetta_test/test_ns1/multimethod.cljc" :line 6}]}) (when (not (in? opts :no-doc)) (list {:doc "This namespace will be marked with no-doc at load-time\n" :name 'metagetta-test.test-ns1.no-doc-me-later :no-doc true :publics [{:name 'some-var :arglists '([x]) :file "metagetta_test/test_ns1/no_doc_me_later.cljc", :line 9 :type :var}]} {:name 'metagetta-test.test-ns1.no-doc-ns :no-doc true :publics [{:name 'not-documented :arglists '([a]) :type :var :file "metagetta_test/test_ns1/no_doc_ns.cljc" :line 6}]})) (list {:name 'metagetta-test.test-ns1.protocols :publics [{:name 'ProtoTest :type :protocol :doc "Protocol comment.\n" :members '({:arglists ([a]) :name alpha :type :var} {:arglists ([z]) :name beta :type :var} {:arglists ([m]) :name matilda :type :var} {:arglists ([x] [x y]) :doc "Multi args docs\n" :name multi-args :type :var} {:arglists ([x]) :doc "Operation 1 docs\n" :name operation-one, :type :var} {:arglists ([y]) :name zoolander :type :var}) :file "metagetta_test/test_ns1/protocols.cljc" :line 6}]} {:name 'metagetta-test.test-ns1.record :publics [{:arglists '([]) :file "metagetta_test/test_ns1/record.cljc" :line 13 :name '->NopeNotGenerated :type :var} {:arglists '([]) :doc "not a generated positional factory fn, should be included\n" :file "metagetta_test/test_ns1/record.cljc" :line 11 :name '->NopeNotGeneratedDoc :type :var} {:arglists '([]) :file "metagetta_test/test_ns1/record.cljc", :line 17, :name 'map->NopeNotGenerated, :type :var} {:arglists '([]) :doc "not a generated map factory fn, should be included\n", :file "metagetta_test/test_ns1/record.cljc", :line 15, :name 'map->NopeNotGeneratedDoc, :type :var} {:name 'record-test :type :var :file "metagetta_test/test_ns1/record.cljc" :line 8}]}) (when (not (in? opts :skip-wiki)) (list {:name 'metagetta-test.test-ns1.skip-wiki-ns :doc "skip-wiki is legacy for autodoc\n" :skip-wiki true :publics [{:name 'not-wikied :arglists '([b]) :type :var :file "metagetta_test/test_ns1/skip_wiki_ns.cljc" :line 6}]})) (list {:name 'metagetta-test.test-ns1.special-tags :doc "document the special tags namespace\n" :author "Respect my authoritah" :added "0.1.1" :deprecated "0.5.2" :publics (concat-res [{:name 'added-fn :arglists '([a b]) :type :var :added "10.2.2" :file "metagetta_test/test_ns1/special_tags.cljc" :line 26} {:name 'deprecated-fn :arglists '([x]) :type :var :deprecated "0.4.0" :file "metagetta_test/test_ns1/special_tags.cljc" :line 10}] (when (not (in? opts :no-doc)) [{:name 'dont-doc-me, :arglists '([x]), :doc "no docs please\n", :file "metagetta_test/test_ns1/special_tags.cljc", :line 16, :no-doc true, :type :var}]) (when (not (in? opts :skip-wiki)) [{:name 'dont-wiki-me, :arglists '([y]), :doc "no docs also please\n", :file "metagetta_test/test_ns1/special_tags.cljc", :line 30, :skip-wiki true, :type :var}]) [{:name 'dynamic-def :type :var :doc "dynamic def docs\n" :dynamic true :file "metagetta_test/test_ns1/special_tags.cljc" :line 21}])}) (list {:name 'metagetta-test.test-ns1.type, :publics '({:arglists ([]) :file "metagetta_test/test_ns1/type.cljc" :line 13 :name ->NotGenerated :type :var} {:arglists ([]) :doc "not generated and should be included\n" :file "metagetta_test/test_ns1/type.cljc" :line 11 :name ->NotGeneratedDoc :type :var} {:file "metagetta_test/test_ns1/type.cljc" :line 8 :name type-test :type :var})}))) (defn- analyze-sources "Analyze (by default all) sources from `test-sources`" [opts] (main/get-metadata (merge {:root-path "test-sources"} opts))) (t/deftest analyze-cljs-code-test (let [actual (analyze-sources {:languages #{"cljs"}}) expected {"cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest analyze-clj-code-test (let [actual (analyze-sources {:languages #{"clj"}}) expected {"clj" (expected-result :clj)}] (t/is (= expected actual)))) (t/deftest analyze-clj-and-cljs-code-test (let [actual (analyze-sources {:languages #{"clj" "cljs"}}) expected {"clj" (expected-result :clj) "cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest analyze-clj-and-cljs-via-auto-detect-code-test (let [actual (analyze-sources {:languages :auto-detect}) expected {"clj" (expected-result :clj) "cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest ^:no-doc-test analyze-no-doc-test ;; this test is special in that it includes ;; namespaces marked with no-doc would fail if an attempt was made to load them ;; requires special setup, see test task in bb.edn (let [actual (analyze-sources {:root-path "target/no-doc-sources-test" :languages #{"clj" "cljs"} :exclude-with [:no-doc :skip-wiki :mranderson/inlined]}) expected {"clj" (expected-result :clj :no-doc :skip-wiki :mranderson/inlined) "cljs" (expected-result :cljs :no-doc :skip-wiki :mranderson/inlined)}] (t/is (= expected actual)))) (t/deftest analyze-select-namespace-no-matches-test (let [actual (analyze-sources {:languages #{"clj" "cljs"} :namespaces ["wont.find.me"]}) expected {"clj" [] "cljs" []}] (t/is (= expected actual)))) (t/deftest analyze-specify-namespaces-wildcard-test (let [actual (analyze-sources {:languages #{"clj" "cljs"} :namespaces ["metagetta-test.*"]}) expected {"clj" (expected-result :clj) "cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest analyze-specify-namespaces-subset-test (let [namespaces ['metagetta-test.cljs-macro-functions.usage 'metagetta-test.test-ns1.protocols] actual (analyze-sources {:languages #{"clj" "cljs"} :namespaces namespaces}) expected {"clj" (filter #(in? namespaces (:name %)) (expected-result :clj)) "cljs" (filter #(in? namespaces (:name %)) (expected-result :cljs))}] (t/is (= expected actual))))
null
https://raw.githubusercontent.com/cljdoc/cljdoc-analyzer/5489e7de9542038a57a09abe583fc187d6a360e1/modules/metagetta/test/cljdoc_analyzer/metagetta/main_test.clj
clojure
this test is special in that it includes namespaces marked with no-doc would fail if an attempt was made to load them requires special setup, see test task in bb.edn
(ns cljdoc-analyzer.metagetta.main-test "Load all `test-sources/*` namespaces and test various things about them." (:require [clojure.test :as t] [cljdoc-analyzer.metagetta.main :as main])) (defn- in? [coll elem] (some #(= elem %) coll)) (defn- concat-res [& args] (remove nil? (apply concat args))) (defn- expected-result [& opts] (concat-res (when (in? opts :clj) (list {:name 'metagetta-test.cljs-macro-functions.foo.core, :publics [{:arglists '([a b]), :file "metagetta_test/cljs_macro_functions/foo/core.clj", :line 6, :name 'add, :type :macro}]})) (when (in? opts :cljs) (list {:name 'metagetta-test.cljs-macro-functions.foo.core :publics [{:arglists '([a b]) :file "metagetta_test/cljs_macro_functions/foo/core.cljs" :line 6 :name 'add :type :var}]} {:name 'metagetta-test.cljs-macro-functions.usage :publics [{:arglists '([]) :file "metagetta_test/cljs_macro_functions/usage.cljs" :line 19 :name 'example :type :var}]})) (list {:name 'metagetta-test.test-ns1.altered :publics [{:name 'altered-def-with-absolute-file :type :var :file "metagetta_test/test_ns1/record.cljc" :line 7} {:name 'altered-fn-with-source-relative-file :arglists '([]) :type :var :file "metagetta_test/test_ns1/multimethod.cljc" :line 14} {:name 'altered-macro-with-root-relative-file :arglists '([]) :type :macro :doc "added doc\n" :file "metagetta_test/test_ns1/multimethod.cljc" :line 3} {:arglists '([x]), :doc "Operation 1 docs\n", :file "metagetta_test/test_ns1/protocols.cljc", :line 6, :name 'fn-pointing-to-protocol-fn, :type :var}]} {:name 'metagetta-test.test-ns1.macro :publics [{:name 'macdoc :arglists '([a b c d]) :type :macro :doc "Macro docs\n" :file "metagetta_test/test_ns1/macro.cljc" :line 23} {:name 'simple :arglists '([a b]) :type :macro :file "metagetta_test/test_ns1/macro.cljc" :line 11} {:name 'varargs :arglists '([a & xs]) :type :macro :file "metagetta_test/test_ns1/macro.cljc" :line 17}]}) (when (not (in? opts :mranderson/inlined)) (list {:name 'metagetta-test.test-ns1.mranderson-inlined-ns, :publics [{:arglists '([a]), :file "metagetta_test/test_ns1/mranderson_inlined_ns.cljc", :line 6 :name 'an-inlined-var :type :var}] :mranderson/inlined true})) (list {:name 'metagetta-test.test-ns1.multiarity :publics [{:name 'multiarity :arglists '([] [a] [a b] [a b c d]) :type :var :doc "Multiarity comment\n" :file "metagetta_test/test_ns1/multiarity.cljc" :line 7}]} {:name 'metagetta-test.test-ns1.multimethod :publics [{:name 'start :type :multimethod :file "metagetta_test/test_ns1/multimethod.cljc" :line 6}]}) (when (not (in? opts :no-doc)) (list {:doc "This namespace will be marked with no-doc at load-time\n" :name 'metagetta-test.test-ns1.no-doc-me-later :no-doc true :publics [{:name 'some-var :arglists '([x]) :file "metagetta_test/test_ns1/no_doc_me_later.cljc", :line 9 :type :var}]} {:name 'metagetta-test.test-ns1.no-doc-ns :no-doc true :publics [{:name 'not-documented :arglists '([a]) :type :var :file "metagetta_test/test_ns1/no_doc_ns.cljc" :line 6}]})) (list {:name 'metagetta-test.test-ns1.protocols :publics [{:name 'ProtoTest :type :protocol :doc "Protocol comment.\n" :members '({:arglists ([a]) :name alpha :type :var} {:arglists ([z]) :name beta :type :var} {:arglists ([m]) :name matilda :type :var} {:arglists ([x] [x y]) :doc "Multi args docs\n" :name multi-args :type :var} {:arglists ([x]) :doc "Operation 1 docs\n" :name operation-one, :type :var} {:arglists ([y]) :name zoolander :type :var}) :file "metagetta_test/test_ns1/protocols.cljc" :line 6}]} {:name 'metagetta-test.test-ns1.record :publics [{:arglists '([]) :file "metagetta_test/test_ns1/record.cljc" :line 13 :name '->NopeNotGenerated :type :var} {:arglists '([]) :doc "not a generated positional factory fn, should be included\n" :file "metagetta_test/test_ns1/record.cljc" :line 11 :name '->NopeNotGeneratedDoc :type :var} {:arglists '([]) :file "metagetta_test/test_ns1/record.cljc", :line 17, :name 'map->NopeNotGenerated, :type :var} {:arglists '([]) :doc "not a generated map factory fn, should be included\n", :file "metagetta_test/test_ns1/record.cljc", :line 15, :name 'map->NopeNotGeneratedDoc, :type :var} {:name 'record-test :type :var :file "metagetta_test/test_ns1/record.cljc" :line 8}]}) (when (not (in? opts :skip-wiki)) (list {:name 'metagetta-test.test-ns1.skip-wiki-ns :doc "skip-wiki is legacy for autodoc\n" :skip-wiki true :publics [{:name 'not-wikied :arglists '([b]) :type :var :file "metagetta_test/test_ns1/skip_wiki_ns.cljc" :line 6}]})) (list {:name 'metagetta-test.test-ns1.special-tags :doc "document the special tags namespace\n" :author "Respect my authoritah" :added "0.1.1" :deprecated "0.5.2" :publics (concat-res [{:name 'added-fn :arglists '([a b]) :type :var :added "10.2.2" :file "metagetta_test/test_ns1/special_tags.cljc" :line 26} {:name 'deprecated-fn :arglists '([x]) :type :var :deprecated "0.4.0" :file "metagetta_test/test_ns1/special_tags.cljc" :line 10}] (when (not (in? opts :no-doc)) [{:name 'dont-doc-me, :arglists '([x]), :doc "no docs please\n", :file "metagetta_test/test_ns1/special_tags.cljc", :line 16, :no-doc true, :type :var}]) (when (not (in? opts :skip-wiki)) [{:name 'dont-wiki-me, :arglists '([y]), :doc "no docs also please\n", :file "metagetta_test/test_ns1/special_tags.cljc", :line 30, :skip-wiki true, :type :var}]) [{:name 'dynamic-def :type :var :doc "dynamic def docs\n" :dynamic true :file "metagetta_test/test_ns1/special_tags.cljc" :line 21}])}) (list {:name 'metagetta-test.test-ns1.type, :publics '({:arglists ([]) :file "metagetta_test/test_ns1/type.cljc" :line 13 :name ->NotGenerated :type :var} {:arglists ([]) :doc "not generated and should be included\n" :file "metagetta_test/test_ns1/type.cljc" :line 11 :name ->NotGeneratedDoc :type :var} {:file "metagetta_test/test_ns1/type.cljc" :line 8 :name type-test :type :var})}))) (defn- analyze-sources "Analyze (by default all) sources from `test-sources`" [opts] (main/get-metadata (merge {:root-path "test-sources"} opts))) (t/deftest analyze-cljs-code-test (let [actual (analyze-sources {:languages #{"cljs"}}) expected {"cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest analyze-clj-code-test (let [actual (analyze-sources {:languages #{"clj"}}) expected {"clj" (expected-result :clj)}] (t/is (= expected actual)))) (t/deftest analyze-clj-and-cljs-code-test (let [actual (analyze-sources {:languages #{"clj" "cljs"}}) expected {"clj" (expected-result :clj) "cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest analyze-clj-and-cljs-via-auto-detect-code-test (let [actual (analyze-sources {:languages :auto-detect}) expected {"clj" (expected-result :clj) "cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest ^:no-doc-test analyze-no-doc-test (let [actual (analyze-sources {:root-path "target/no-doc-sources-test" :languages #{"clj" "cljs"} :exclude-with [:no-doc :skip-wiki :mranderson/inlined]}) expected {"clj" (expected-result :clj :no-doc :skip-wiki :mranderson/inlined) "cljs" (expected-result :cljs :no-doc :skip-wiki :mranderson/inlined)}] (t/is (= expected actual)))) (t/deftest analyze-select-namespace-no-matches-test (let [actual (analyze-sources {:languages #{"clj" "cljs"} :namespaces ["wont.find.me"]}) expected {"clj" [] "cljs" []}] (t/is (= expected actual)))) (t/deftest analyze-specify-namespaces-wildcard-test (let [actual (analyze-sources {:languages #{"clj" "cljs"} :namespaces ["metagetta-test.*"]}) expected {"clj" (expected-result :clj) "cljs" (expected-result :cljs)}] (t/is (= expected actual)))) (t/deftest analyze-specify-namespaces-subset-test (let [namespaces ['metagetta-test.cljs-macro-functions.usage 'metagetta-test.test-ns1.protocols] actual (analyze-sources {:languages #{"clj" "cljs"} :namespaces namespaces}) expected {"clj" (filter #(in? namespaces (:name %)) (expected-result :clj)) "cljs" (filter #(in? namespaces (:name %)) (expected-result :cljs))}] (t/is (= expected actual))))
fd4a4478e1eeaea945ce54215f358daeedd3ed90529904e046e6b02062d54240
buntine/Simply-Scheme-Exercises
22-3.scm
; Write a procedure to count the number of words in a file. It should take the ; filename as argument and return the number. (define (numwords file) (let ((inport (open-input-file file))) (define words (count-words inport)) (close-input-port inport) words)) note : This words because ' read ' will ; store the data as a list. (define (count-words inport) (let ((line (read-line inport))) (if (eof-object? line) 0 (+ (length line) (count-words inport)))))
null
https://raw.githubusercontent.com/buntine/Simply-Scheme-Exercises/c6cbf0bd60d6385b506b8df94c348ac5edc7f646/22-files/22-3.scm
scheme
Write a procedure to count the number of words in a file. It should take the filename as argument and return the number. store the data as a list.
(define (numwords file) (let ((inport (open-input-file file))) (define words (count-words inport)) (close-input-port inport) words)) note : This words because ' read ' will (define (count-words inport) (let ((line (read-line inport))) (if (eof-object? line) 0 (+ (length line) (count-words inport)))))
622f6ea76394f32bf8ddee9e4c72f1b9247f3c29759e5679f8ce90a003e059f4
jellelicht/guix
profiles.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (guix build profiles) #:use-module (guix build union) #:use-module (guix build utils) #:use-module (guix search-paths) #:use-module (srfi srfi-26) #:use-module (ice-9 ftw) #:use-module (ice-9 match) #:use-module (ice-9 pretty-print) #:export (ensure-writable-directory build-profile)) ;;; Commentary: ;;; ;;; Build a user profile (essentially the union of all the installed packages) ;;; with its associated meta-data. ;;; ;;; Code: (define (abstract-profile profile) "Return a procedure that replaces PROFILE in VALUE with a reference to the 'GUIX_PROFILE' environment variable. This allows users to specify what the user-friendly name of the profile is, for instance ~/.guix-profile rather than /gnu/store/...-profile." (let ((replacement (string-append "${GUIX_PROFILE:-" profile "}"))) (match-lambda ((search-path . value) (let* ((separator (search-path-specification-separator search-path)) (items (string-tokenize* value separator)) (crop (cute string-drop <> (string-length profile)))) (cons search-path (string-join (map (lambda (str) (string-append replacement (crop str))) items) separator))))))) (define (write-environment-variable-definition port) "Write the given environment variable definition to PORT." (match-lambda ((search-path . value) (display (search-path-definition search-path value #:kind 'prefix) port) (newline port)))) (define (build-etc/profile output search-paths) "Build the 'OUTPUT/etc/profile' shell file containing environment variable definitions for all the SEARCH-PATHS." (mkdir-p (string-append output "/etc")) (call-with-output-file (string-append output "/etc/profile") (lambda (port) ;; The use of $GUIX_PROFILE described below is not great. Another option would have been to use " $ 1 " and have users run : ;; ;; source ~/.guix-profile/etc/profile ~/.guix-profile ;; However , when ' source ' is used with no arguments , $ 1 refers to the ;; first positional parameter of the calling scripts, so we can rely on ;; it. (display "\ # Source this file to define all the relevant environment variables in Bash # for this profile. You may want to define the 'GUIX_PROFILE' environment # variable to point to the \"visible\" name of the profile, like this: # # GUIX_PROFILE=/path/to/profile # source /path/to/profile/etc/profile # # When GUIX_PROFILE is undefined, the various environment variables refer # to this specific profile generation. \n" port) (let ((variables (evaluate-search-paths (cons $PATH search-paths) (list output)))) (for-each (write-environment-variable-definition port) (map (abstract-profile output) variables)))))) (define (ensure-writable-directory directory) "Ensure DIRECTORY exists and is writable. If DIRECTORY is currently a symlink (to a read-only directory in the store), then delete the symlink and instead make DIRECTORY a \"real\" directory containing symlinks." (define (unsymlink link) (let* ((target (readlink link)) ;; TARGET might itself be a symlink, so append "/" to make sure ' scandir ' enters it . (files (scandir (string-append target "/") (negate (cut member <> '("." "..")))))) (delete-file link) (mkdir link) (for-each (lambda (file) (symlink (string-append target "/" file) (string-append link "/" file))) files))) (catch 'system-error (lambda () (mkdir directory)) (lambda args (let ((errno (system-error-errno args))) (if (= errno EEXIST) (let ((stat (lstat directory))) (case (stat:type stat) ((symlink) " Unsymlink " DIRECTORY so that it is writable . (unsymlink directory)) ((directory) #t) (else (error "cannot mkdir because a same-named file exists" directory)))) (apply throw args)))))) (define* (build-profile output inputs #:key manifest search-paths) "Build a user profile from INPUTS in directory OUTPUT. Write MANIFEST, an sexp, to OUTPUT/manifest. Create OUTPUT/etc/profile with Bash definitions for -all the variables listed in SEARCH-PATHS." ;; Make the symlinks. (union-build output inputs #:log-port (%make-void-port "w")) ;; Store meta-data. (call-with-output-file (string-append output "/manifest") (lambda (p) (pretty-print manifest p))) ;; Make sure we can write to 'OUTPUT/etc'. 'union-build' above could have ;; made 'etc' a symlink to a read-only sub-directory in the store so we need ;; to work around that. (ensure-writable-directory (string-append output "/etc")) ;; Write 'OUTPUT/etc/profile'. (build-etc/profile output search-paths)) ;;; profile.scm ends here
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/guix/build/profiles.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. Commentary: Build a user profile (essentially the union of all the installed packages) with its associated meta-data. Code: The use of $GUIX_PROFILE described below is not great. Another source ~/.guix-profile/etc/profile ~/.guix-profile first positional parameter of the calling scripts, so we can rely on it. TARGET might itself be a symlink, so append "/" to make sure Make the symlinks. Store meta-data. Make sure we can write to 'OUTPUT/etc'. 'union-build' above could have made 'etc' a symlink to a read-only sub-directory in the store so we need to work around that. Write 'OUTPUT/etc/profile'. profile.scm ends here
Copyright © 2015 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix build profiles) #:use-module (guix build union) #:use-module (guix build utils) #:use-module (guix search-paths) #:use-module (srfi srfi-26) #:use-module (ice-9 ftw) #:use-module (ice-9 match) #:use-module (ice-9 pretty-print) #:export (ensure-writable-directory build-profile)) (define (abstract-profile profile) "Return a procedure that replaces PROFILE in VALUE with a reference to the 'GUIX_PROFILE' environment variable. This allows users to specify what the user-friendly name of the profile is, for instance ~/.guix-profile rather than /gnu/store/...-profile." (let ((replacement (string-append "${GUIX_PROFILE:-" profile "}"))) (match-lambda ((search-path . value) (let* ((separator (search-path-specification-separator search-path)) (items (string-tokenize* value separator)) (crop (cute string-drop <> (string-length profile)))) (cons search-path (string-join (map (lambda (str) (string-append replacement (crop str))) items) separator))))))) (define (write-environment-variable-definition port) "Write the given environment variable definition to PORT." (match-lambda ((search-path . value) (display (search-path-definition search-path value #:kind 'prefix) port) (newline port)))) (define (build-etc/profile output search-paths) "Build the 'OUTPUT/etc/profile' shell file containing environment variable definitions for all the SEARCH-PATHS." (mkdir-p (string-append output "/etc")) (call-with-output-file (string-append output "/etc/profile") (lambda (port) option would have been to use " $ 1 " and have users run : However , when ' source ' is used with no arguments , $ 1 refers to the (display "\ # Source this file to define all the relevant environment variables in Bash # for this profile. You may want to define the 'GUIX_PROFILE' environment # variable to point to the \"visible\" name of the profile, like this: # # GUIX_PROFILE=/path/to/profile # source /path/to/profile/etc/profile # # When GUIX_PROFILE is undefined, the various environment variables refer # to this specific profile generation. \n" port) (let ((variables (evaluate-search-paths (cons $PATH search-paths) (list output)))) (for-each (write-environment-variable-definition port) (map (abstract-profile output) variables)))))) (define (ensure-writable-directory directory) "Ensure DIRECTORY exists and is writable. If DIRECTORY is currently a symlink (to a read-only directory in the store), then delete the symlink and instead make DIRECTORY a \"real\" directory containing symlinks." (define (unsymlink link) (let* ((target (readlink link)) ' scandir ' enters it . (files (scandir (string-append target "/") (negate (cut member <> '("." "..")))))) (delete-file link) (mkdir link) (for-each (lambda (file) (symlink (string-append target "/" file) (string-append link "/" file))) files))) (catch 'system-error (lambda () (mkdir directory)) (lambda args (let ((errno (system-error-errno args))) (if (= errno EEXIST) (let ((stat (lstat directory))) (case (stat:type stat) ((symlink) " Unsymlink " DIRECTORY so that it is writable . (unsymlink directory)) ((directory) #t) (else (error "cannot mkdir because a same-named file exists" directory)))) (apply throw args)))))) (define* (build-profile output inputs #:key manifest search-paths) "Build a user profile from INPUTS in directory OUTPUT. Write MANIFEST, an sexp, to OUTPUT/manifest. Create OUTPUT/etc/profile with Bash definitions for -all the variables listed in SEARCH-PATHS." (union-build output inputs #:log-port (%make-void-port "w")) (call-with-output-file (string-append output "/manifest") (lambda (p) (pretty-print manifest p))) (ensure-writable-directory (string-append output "/etc")) (build-etc/profile output search-paths))
62ce0acdd4a35706e942d819a28666db37857de517690666b452b47e7ee81ed0
scmlab/gcl
WP.hs
{-# LANGUAGE OverloadedStrings #-} module GCL.WP.WP where import Control.Arrow ( first, second ) import Control.Monad.Except ( MonadError(throwError) , forM ) import Data.Text ( Text ) import Data.Loc ( Loc(..), locOf ) import Data.Set ( member ) import Data.Map ( fromList ) import GCL.Predicate ( Pred(..) ) import GCL.Predicate.Util ( conjunct , toExpr ) import GCL.Common ( Fresh(..) , freshName , freshName' , freeVars ) import Pretty ( toText ) import GCL.WP.Type import GCL.WP.Util import qualified Syntax.Abstract as A import qualified Syntax.Abstract.Operator as A import qualified Syntax.Abstract.Util as A import Syntax.Common.Types ( Name(..) , nameToText ) import Syntax.Substitution -- import Debug.Trace import import . Render . String wpFunctions :: TstructSegs -> (TwpSegs, TwpSStmts, Twp) wpFunctions structSegs = (wpSegs, wpSStmts, wp) where wpStmts :: [A.Stmt] -> Pred -> WP Pred wpStmts = wpSegs . groupStmts -- handels segments without a precondition. -- switches back to structSegs when seeing an assertion wpSegs :: [SegElm] -> Pred -> WP Pred wpSegs [] post = return post wpSegs (SStmts ss : segs) post = do post' <- wpSegs segs post wpSStmts ss post' wpSegs (SSpec (A.Spec _ range) : segs) post = do post' <- wpSegs segs post tellSpec post' post' range return post' wpSegs (SAsrt (A.Assert p l) : segs) post = do structSegs (Assertion p l, Nothing) segs post return (Assertion p l) wpSegs (SAsrt (A.LoopInvariant p bd l) : segs) post = do structSegs (LoopInvariant p bd l, Just bd) segs post SCM : erasing bound information ? wpSegs _ _ = error "Missing case in wpSegs" " simple " version of wpStmts . -- no assertions and specs (in the outer level), -- but may contain invariants in secondary run wpSStmts :: [A.Stmt] -> Pred -> WP Pred wpSStmts [] post = return post wpSStmts (A.LoopInvariant inv _ _ : A.Do gcmds _ : stmts) post = do -- this happens only in secondary run post' <- wpSStmts stmts post let guards = A.getGuards gcmds return . Constant $ inv `A.conj` ( (inv `A.conj` A.conjunct (map A.neg guards)) `A.implies` toExpr post' ) wpSStmts (stmt : stmts) post = do post' <- wpSStmts stmts post wp stmt post' wp :: A.Stmt -> Pred -> WP Pred wp (A.Abort _ ) _ = return (Constant A.false) wp (A.Skip _ ) post = return post wp (A.Assign xs es _) post = substitute xs es post wp (A.AAssign (A.Var x _) i e _) post = substitute [x] [A.ArrUpd (A.nameVar x) i e NoLoc] post wp (A.AAssign _ _ _ l) _ = throwError (MultiDimArrayAsgnNotImp l) wp (A.Do _ l ) _ = throwError $ MissingAssertion l -- shouldn't happen wp (A.If gcmds _ ) post = do pres <- forM gcmds $ \(A.GdCmd guard body _) -> Constant . (guard `A.imply`) . toExpr <$> wpStmts body post return (conjunct (disjunctGuards gcmds : pres)) wp (A.Proof _ _ _ ) post = return post wp (A.Alloc x (e : es) _) post = do -- non-empty {- wp (x := es) P = (forall x', (x' -> es) -* P[x'/x])-} x' <- freshName' (toText x) -- generate fresh name using the exisiting "x" post' <- substitute [x] [A.nameVar x'] (toExpr post) return $ Constant (A.forAll [x'] A.true (newallocs x' `A.sImp` post')) where newallocs x' = A.sconjunct ( (A.nameVar x' `A.pointsTo` e) : zipWith (\i -> A.pointsTo (A.nameVar x' `A.add` A.number i)) [1 ..] es ) wp (A.HLookup x e _) post = do {- wp (x := *e) P = (exists v . (e->v) * ((e->v) -* P[v/x])) -} v <- freshName' (toText x) -- generate fresh name using the exisiting "x" post' <- substitute [x] [A.nameVar v] (toExpr post) return $ Constant (A.exists [v] A.true (entry v `A.sConj` (entry v `A.sImp` post'))) where entry v = e `A.pointsTo` A.nameVar v wp (A.HMutate e1 e2 _) post = do {- wp (e1* := e2) P = (e1->_) * ((e1->e2) -* P) -} e1_allocated <- allocated e1 return $ Constant (e1_allocated `A.sConj` ((e1 `A.pointsTo` e2) `A.sImp` toExpr post)) wp (A.Dispose e _) post = do {- wp (dispose e) P = (e -> _) * P -} e_allocated <- allocated e return $ Constant (e_allocated `A.sConj` toExpr post) -- TODO: wp (A.Block prog _) post = wpBlock prog post wp _ _ = error "missing case in wp" wpBlock :: A.Program -> Pred -> WP Pred wpBlock (A.Program _ decls _props stmts _) post = do let localNames = declaredNames decls (xs, ys) <- withLocalScopes (\scopes -> withScopeExtension (map nameToText localNames) (calcLocalRenaming (concat scopes) localNames)) stmts' <- subst (toSubst ys) stmts withScopeExtension (xs ++ (map (nameToText . snd) ys)) (wpStmts stmts' post) if any ( ` member ` ( fv pre ) ) ( declaredNames decls ) then throwError ( LocalVarExceedScope l ) -- else return pre where toSubst = fromList . map (\(n, n') -> (n, A.Var n' (locOf n'))) calcLocalRenaming :: [Text] -> [Name] -> WP ([Text], [(Text, Name)]) calcLocalRenaming _ [] = return ([], []) calcLocalRenaming scope (x:xs) | t `elem` scope = do x' <- freshName t (locOf x) second ((t,x') :) <$> calcLocalRenaming scope xs | otherwise = first (t:) <$> calcLocalRenaming scope xs where t = nameToText x toMapping :: [(Text, Name)] -> A.Mapping toMapping = fromList . map cvt where cvt (x, y) = (x, A.Var y (locOf y)) allocated :: Fresh m => A.Expr -> m A.Expr allocated e = do v <- freshName' "new" return (A.exists [v] A.true (e `A.pointsTo` A.nameVar v)) -- allocated e = e -> _ -- debugging -- pp :: Pretty a => a -> String pp = renderString . defaultLayoutOptions . pretty
null
https://raw.githubusercontent.com/scmlab/gcl/cadeff706b678e558100f3c3b172055486e6043a/src/GCL/WP/WP.hs
haskell
# LANGUAGE OverloadedStrings # import Debug.Trace handels segments without a precondition. switches back to structSegs when seeing an assertion no assertions and specs (in the outer level), but may contain invariants in secondary run this happens only in secondary run shouldn't happen non-empty wp (x := es) P = (forall x', (x' -> es) -* P[x'/x]) generate fresh name using the exisiting "x" wp (x := *e) P = (exists v . (e->v) * ((e->v) -* P[v/x])) generate fresh name using the exisiting "x" wp (e1* := e2) P = (e1->_) * ((e1->e2) -* P) wp (dispose e) P = (e -> _) * P TODO: else return pre allocated e = e -> _ debugging pp :: Pretty a => a -> String
module GCL.WP.WP where import Control.Arrow ( first, second ) import Control.Monad.Except ( MonadError(throwError) , forM ) import Data.Text ( Text ) import Data.Loc ( Loc(..), locOf ) import Data.Set ( member ) import Data.Map ( fromList ) import GCL.Predicate ( Pred(..) ) import GCL.Predicate.Util ( conjunct , toExpr ) import GCL.Common ( Fresh(..) , freshName , freshName' , freeVars ) import Pretty ( toText ) import GCL.WP.Type import GCL.WP.Util import qualified Syntax.Abstract as A import qualified Syntax.Abstract.Operator as A import qualified Syntax.Abstract.Util as A import Syntax.Common.Types ( Name(..) , nameToText ) import Syntax.Substitution import import . Render . String wpFunctions :: TstructSegs -> (TwpSegs, TwpSStmts, Twp) wpFunctions structSegs = (wpSegs, wpSStmts, wp) where wpStmts :: [A.Stmt] -> Pred -> WP Pred wpStmts = wpSegs . groupStmts wpSegs :: [SegElm] -> Pred -> WP Pred wpSegs [] post = return post wpSegs (SStmts ss : segs) post = do post' <- wpSegs segs post wpSStmts ss post' wpSegs (SSpec (A.Spec _ range) : segs) post = do post' <- wpSegs segs post tellSpec post' post' range return post' wpSegs (SAsrt (A.Assert p l) : segs) post = do structSegs (Assertion p l, Nothing) segs post return (Assertion p l) wpSegs (SAsrt (A.LoopInvariant p bd l) : segs) post = do structSegs (LoopInvariant p bd l, Just bd) segs post SCM : erasing bound information ? wpSegs _ _ = error "Missing case in wpSegs" " simple " version of wpStmts . wpSStmts :: [A.Stmt] -> Pred -> WP Pred wpSStmts [] post = return post post' <- wpSStmts stmts post let guards = A.getGuards gcmds return . Constant $ inv `A.conj` ( (inv `A.conj` A.conjunct (map A.neg guards)) `A.implies` toExpr post' ) wpSStmts (stmt : stmts) post = do post' <- wpSStmts stmts post wp stmt post' wp :: A.Stmt -> Pred -> WP Pred wp (A.Abort _ ) _ = return (Constant A.false) wp (A.Skip _ ) post = return post wp (A.Assign xs es _) post = substitute xs es post wp (A.AAssign (A.Var x _) i e _) post = substitute [x] [A.ArrUpd (A.nameVar x) i e NoLoc] post wp (A.AAssign _ _ _ l) _ = throwError (MultiDimArrayAsgnNotImp l) wp (A.If gcmds _ ) post = do pres <- forM gcmds $ \(A.GdCmd guard body _) -> Constant . (guard `A.imply`) . toExpr <$> wpStmts body post return (conjunct (disjunctGuards gcmds : pres)) wp (A.Proof _ _ _ ) post = return post post' <- substitute [x] [A.nameVar x'] (toExpr post) return $ Constant (A.forAll [x'] A.true (newallocs x' `A.sImp` post')) where newallocs x' = A.sconjunct ( (A.nameVar x' `A.pointsTo` e) : zipWith (\i -> A.pointsTo (A.nameVar x' `A.add` A.number i)) [1 ..] es ) wp (A.HLookup x e _) post = do post' <- substitute [x] [A.nameVar v] (toExpr post) return $ Constant (A.exists [v] A.true (entry v `A.sConj` (entry v `A.sImp` post'))) where entry v = e `A.pointsTo` A.nameVar v wp (A.HMutate e1 e2 _) post = do e1_allocated <- allocated e1 return $ Constant (e1_allocated `A.sConj` ((e1 `A.pointsTo` e2) `A.sImp` toExpr post)) wp (A.Dispose e _) post = do e_allocated <- allocated e return $ Constant (e_allocated `A.sConj` toExpr post) wp (A.Block prog _) post = wpBlock prog post wp _ _ = error "missing case in wp" wpBlock :: A.Program -> Pred -> WP Pred wpBlock (A.Program _ decls _props stmts _) post = do let localNames = declaredNames decls (xs, ys) <- withLocalScopes (\scopes -> withScopeExtension (map nameToText localNames) (calcLocalRenaming (concat scopes) localNames)) stmts' <- subst (toSubst ys) stmts withScopeExtension (xs ++ (map (nameToText . snd) ys)) (wpStmts stmts' post) if any ( ` member ` ( fv pre ) ) ( declaredNames decls ) then throwError ( LocalVarExceedScope l ) where toSubst = fromList . map (\(n, n') -> (n, A.Var n' (locOf n'))) calcLocalRenaming :: [Text] -> [Name] -> WP ([Text], [(Text, Name)]) calcLocalRenaming _ [] = return ([], []) calcLocalRenaming scope (x:xs) | t `elem` scope = do x' <- freshName t (locOf x) second ((t,x') :) <$> calcLocalRenaming scope xs | otherwise = first (t:) <$> calcLocalRenaming scope xs where t = nameToText x toMapping :: [(Text, Name)] -> A.Mapping toMapping = fromList . map cvt where cvt (x, y) = (x, A.Var y (locOf y)) allocated :: Fresh m => A.Expr -> m A.Expr allocated e = do v <- freshName' "new" return (A.exists [v] A.true (e `A.pointsTo` A.nameVar v)) pp = renderString . defaultLayoutOptions . pretty
c58b981e252a3a8012db2d73a9ea1da2a5beb8584b1f9f145551c59364cc1bb9
digitallyinduced/ihp
BuildGeneratedCode.hs
| Module : IHP.CLI.BuildGeneratedCode Description : Provides the @build - generated - code@ command which generates the Generated . Types module Copyright : ( c ) digitally induced GmbH , 2020 Module: IHP.CLI.BuildGeneratedCode Description: Provides the @build-generated-code@ command which generates the Generated.Types module Copyright: (c) digitally induced GmbH, 2020 -} module Main where import IHP.Prelude import IHP.SchemaCompiler import Main.Utf8 (withUtf8) main :: IO () main = withUtf8 do compile
null
https://raw.githubusercontent.com/digitallyinduced/ihp/5a53eff25ed3d765dc0cd5ec7425d4fcaaa25f97/exe/IHP/CLI/BuildGeneratedCode.hs
haskell
| Module : IHP.CLI.BuildGeneratedCode Description : Provides the @build - generated - code@ command which generates the Generated . Types module Copyright : ( c ) digitally induced GmbH , 2020 Module: IHP.CLI.BuildGeneratedCode Description: Provides the @build-generated-code@ command which generates the Generated.Types module Copyright: (c) digitally induced GmbH, 2020 -} module Main where import IHP.Prelude import IHP.SchemaCompiler import Main.Utf8 (withUtf8) main :: IO () main = withUtf8 do compile
d929089ad0c15f95172a1759c2c8e5f39303c7fa960fca971007a177232558fe
vernemq/vernemq
vmq_server_app.erl
Copyright 2018 Erlio GmbH Basel Switzerland ( ) %% 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(vmq_server_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %% =================================================================== %% Application callbacks %% =================================================================== -spec start(_, _) -> {'error', _} | {'ok', pid()} | {'ok', pid(), _}. start(_StartType, _StartArgs) -> ok = vmq_metadata:start(), ok = vmq_message_store:start(), case vmq_server_sup:start_link() of {error, _} = E -> E; R -> %% we'll wait for some millis, this %% enables the vmq_plugin mechanism to be prepared... %% vmq_plugin_mgr waits for the 'vmq_server_sup' process %% to be registered. timer:sleep(500), vmq_server_cli:init_registry(), start_user_plugins(), vmq_config:configure_node(), R end. start_user_plugins() -> Plugins = application:get_env(vmq_server, user_plugins, []), [start_user_plugin(P) || P <- Plugins]. start_user_plugin( {_Order, #{ path := Path, name := PluginName }} ) -> Res = case Path of undefined -> vmq_plugin_mgr:enable_plugin(PluginName); _ -> vmq_plugin_mgr:enable_plugin(PluginName, [{path, Path}]) end, case Res of ok -> ok; {error, Reason} -> lager:warning("could not start plugin ~p due to ~p", [PluginName, Reason]) end. -spec stop(_) -> 'ok'. stop(_State) -> _ = vmq_message_store:stop(), _ = vmq_metadata:stop(), ok.
null
https://raw.githubusercontent.com/vernemq/vernemq/234d253250cb5371b97ebb588622076fdabc6a5f/apps/vmq_server/src/vmq_server_app.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. Application callbacks =================================================================== Application callbacks =================================================================== we'll wait for some millis, this enables the vmq_plugin mechanism to be prepared... vmq_plugin_mgr waits for the 'vmq_server_sup' process to be registered.
Copyright 2018 Erlio GmbH Basel Switzerland ( ) Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(vmq_server_app). -behaviour(application). -export([start/2, stop/1]). -spec start(_, _) -> {'error', _} | {'ok', pid()} | {'ok', pid(), _}. start(_StartType, _StartArgs) -> ok = vmq_metadata:start(), ok = vmq_message_store:start(), case vmq_server_sup:start_link() of {error, _} = E -> E; R -> timer:sleep(500), vmq_server_cli:init_registry(), start_user_plugins(), vmq_config:configure_node(), R end. start_user_plugins() -> Plugins = application:get_env(vmq_server, user_plugins, []), [start_user_plugin(P) || P <- Plugins]. start_user_plugin( {_Order, #{ path := Path, name := PluginName }} ) -> Res = case Path of undefined -> vmq_plugin_mgr:enable_plugin(PluginName); _ -> vmq_plugin_mgr:enable_plugin(PluginName, [{path, Path}]) end, case Res of ok -> ok; {error, Reason} -> lager:warning("could not start plugin ~p due to ~p", [PluginName, Reason]) end. -spec stop(_) -> 'ok'. stop(_State) -> _ = vmq_message_store:stop(), _ = vmq_metadata:stop(), ok.
95c9fc5711e02d8cc7f77982db3ded274ae4a64194052e6b433b8d13bbdb8a72
rtoy/ansi-cl-tests
array-element-type.lsp
;-*- Mode: Lisp -*- Author : ;;;; Contains: Tests of the function ARRAY-ELEMENT-TYPE (in-package :cl-test) Mosts tests are in other files , incidental to testing of ;;; other things (deftest array-element-type.1 (macrolet ((%m (z) z)) (notnot (array-element-type (expand-in-current-env (%m #(a b c)))))) t) (deftest array-element-type.order.1 (let ((i 0)) (array-element-type (progn (incf i) #(a b c))) i) 1) ;;; Error tests (deftest array-element-type.error.1 (signals-error (array-element-type) program-error) t) (deftest array-element-type.error.2 (signals-error (array-element-type #(a b c) nil) program-error) t) (deftest array-element-type.error.3 (check-type-error #'array-element-type #'arrayp) nil) (deftest array-element-type.error.4 (signals-type-error x nil (array-element-type x)) t)
null
https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/array-element-type.lsp
lisp
-*- Mode: Lisp -*- Contains: Tests of the function ARRAY-ELEMENT-TYPE other things Error tests
Author : (in-package :cl-test) Mosts tests are in other files , incidental to testing of (deftest array-element-type.1 (macrolet ((%m (z) z)) (notnot (array-element-type (expand-in-current-env (%m #(a b c)))))) t) (deftest array-element-type.order.1 (let ((i 0)) (array-element-type (progn (incf i) #(a b c))) i) 1) (deftest array-element-type.error.1 (signals-error (array-element-type) program-error) t) (deftest array-element-type.error.2 (signals-error (array-element-type #(a b c) nil) program-error) t) (deftest array-element-type.error.3 (check-type-error #'array-element-type #'arrayp) nil) (deftest array-element-type.error.4 (signals-type-error x nil (array-element-type x)) t)
be1335d44e3f7bd40a2f5330e3953ac662a43949421ce51807321295d9217763
lisp/de.setf.xml
schema.lisp
20100512T225721Z00 from # < doc - node # x224C9D16 > (common-lisp:in-package "urn/") (de.setf.resource.schema:defclass |/|:|Abstention| (|/|:|Option|) nil (:documentation "An 'abstain'-type choice, to be used when a voter cast a ballot with none of the customary options chosen.")) (de.setf.resource.schema:defclass |/|:|ApprovalVote| (|/|:|Vote|) nil (:documentation "A type of Vote in which voters vote for as many options as they want, and the winner is the single option with the most number of votes.")) (de.setf.resource.schema:defclass |/|:|Aye| (|/|:|Option|) nil (:documentation "An Aye vote.")) (de.setf.resource.schema:defclass |/|:|Ballot| nil ((|/|:|voter| :type |/|:|Agent| :documentation "Indicates the agent that cast the ballot.") (|/|:|option| :type |-schema#|:|Literal| :documentation "Indicates the option chosen on a Ballot.")) (:documentation "A choice made by a voter in a Vote.")) (de.setf.resource.schema:defclass |/|:|Nay| (|/|:|Option|) nil (:documentation "A Nay vote.")) (de.setf.resource.schema:defclass |/|:|NoVote| (|/|:|Option|) nil (:documentation "An 'absent'-type option, to be used when a voter did not cast a Ballot but a positive record of the voter's inaction needs to be recorded.")) (de.setf.resource.schema:defclass |/|:|Option| nil nil (:documentation "The parent class of all of the ballot options defined in this specification, although any resource can be used as an option.")) (de.setf.resource.schema:defclass |/|:|PluralityVote| (|/|:|Vote|) nil (:documentation "A type of Vote in which the winner is the single option with the most number of votes.")) (de.setf.resource.schema:defclass |/|:|TwoThirdsVote| (|/|:|Vote|) nil (:documentation "A type of Vote in which the default option wins unless two-thirds or more voters choose the alternative.")) (de.setf.resource.schema:defclass |/|:|Vote| nil ((|/|:|heldBy| :type |/|:|Organization| :documentation "Indicates the organization that held the vote.") (|/|:|procedure| :type ||:|string| :documentation "Indicates the voting procedures, in natural language.") (|/|:|threshold| :type ||:|string| :documentation "For a plurality vote, the threshold of votes needed for the plurality choice to be deemed a winner. Valid values are any fraction expressed as an integer numerator, a slash, and an integer denominator.") (|/|:|hasOption| :type |-schema#|:|Literal| :documentation "Specifies that an option is available for voters in a Vote.") (|/|:|default| :type |-schema#|:|Literal| :documentation "Specifies the default option in Votes that have such an option.") (|/|:|winner| :type |-schema#|:|Literal| :documentation "Indicates the winning option(s) in a vote, if the winner is known.") (|/|:|hasBallot| :type |/|:|Ballot| :documentation "Specifies that a Ballot was cast in a Vote.")) (:documentation "A vote in which agents cast choices."))
null
https://raw.githubusercontent.com/lisp/de.setf.xml/827681c969342096c3b95735d84b447befa69fa6/namespaces/urn-/govshare-info/rdf/vote/schema.lisp
lisp
20100512T225721Z00 from # < doc - node # x224C9D16 > (common-lisp:in-package "urn/") (de.setf.resource.schema:defclass |/|:|Abstention| (|/|:|Option|) nil (:documentation "An 'abstain'-type choice, to be used when a voter cast a ballot with none of the customary options chosen.")) (de.setf.resource.schema:defclass |/|:|ApprovalVote| (|/|:|Vote|) nil (:documentation "A type of Vote in which voters vote for as many options as they want, and the winner is the single option with the most number of votes.")) (de.setf.resource.schema:defclass |/|:|Aye| (|/|:|Option|) nil (:documentation "An Aye vote.")) (de.setf.resource.schema:defclass |/|:|Ballot| nil ((|/|:|voter| :type |/|:|Agent| :documentation "Indicates the agent that cast the ballot.") (|/|:|option| :type |-schema#|:|Literal| :documentation "Indicates the option chosen on a Ballot.")) (:documentation "A choice made by a voter in a Vote.")) (de.setf.resource.schema:defclass |/|:|Nay| (|/|:|Option|) nil (:documentation "A Nay vote.")) (de.setf.resource.schema:defclass |/|:|NoVote| (|/|:|Option|) nil (:documentation "An 'absent'-type option, to be used when a voter did not cast a Ballot but a positive record of the voter's inaction needs to be recorded.")) (de.setf.resource.schema:defclass |/|:|Option| nil nil (:documentation "The parent class of all of the ballot options defined in this specification, although any resource can be used as an option.")) (de.setf.resource.schema:defclass |/|:|PluralityVote| (|/|:|Vote|) nil (:documentation "A type of Vote in which the winner is the single option with the most number of votes.")) (de.setf.resource.schema:defclass |/|:|TwoThirdsVote| (|/|:|Vote|) nil (:documentation "A type of Vote in which the default option wins unless two-thirds or more voters choose the alternative.")) (de.setf.resource.schema:defclass |/|:|Vote| nil ((|/|:|heldBy| :type |/|:|Organization| :documentation "Indicates the organization that held the vote.") (|/|:|procedure| :type ||:|string| :documentation "Indicates the voting procedures, in natural language.") (|/|:|threshold| :type ||:|string| :documentation "For a plurality vote, the threshold of votes needed for the plurality choice to be deemed a winner. Valid values are any fraction expressed as an integer numerator, a slash, and an integer denominator.") (|/|:|hasOption| :type |-schema#|:|Literal| :documentation "Specifies that an option is available for voters in a Vote.") (|/|:|default| :type |-schema#|:|Literal| :documentation "Specifies the default option in Votes that have such an option.") (|/|:|winner| :type |-schema#|:|Literal| :documentation "Indicates the winning option(s) in a vote, if the winner is known.") (|/|:|hasBallot| :type |/|:|Ballot| :documentation "Specifies that a Ballot was cast in a Vote.")) (:documentation "A vote in which agents cast choices."))
0c7f25cffe4c1fde5dffae15f8ec9e4310aeb2e8f5f715fa3da44de4977bc364
dpapavas/lagrange-keyboard
core.clj
-*- coding : utf-8 -*- Copyright 2020 ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see </>. (ns lagrange-keyboard.core (:gen-class) (:refer-clojure :exclude [use import]) (:require [clojure.pprint :refer [pprint]] [clojure.string :refer [starts-with?]] [scad-clj.scad :refer :all] [scad-clj.model :refer :all])) (def π Math/PI) (defn degrees [& θ] (let [f (partial * π 1/180)] (if (> (count θ) 1) (mapv f θ) (f (first θ))))) ;; General parameters. (def place-keycaps? false) (def keys-depressed? false) (def place-keyswitches? false) (def place-pcb? false) (def draft? true) (def mock-threads? true) (def case-test-build? false) (def case-test-locations [0]) (def case-test-volume [50 50 150, 0 0 0]) (def case-color [0.70588 0.69804 0.67059]) (def interference-test-build? false) (def thumb-test-build? false) (def key-test-build? false) (def key-test-range [1 2, 4 4]) ;; Main section parameters. (def row-count 5) (def column-count 6) The radius , in , for each column , or for each row . (def row-radius 235) (def column-radius #(case % (0 1) 65 2 69 3 66 55)) The spacing between rows , in , for each column and between ;; successive columns. (def row-spacing #(case % (0 1) 7/2 2 13/4 3 13/4 9/2)) (def column-spacing #(case % 0 2 1 0 2 9/2 3 5 3)) ;; Column and row rotations in units of keys. (def row-phase (constantly -8)) (def column-phase (fn [i] (+ -57/25 (cond (= i 2) -1/4 (= i 3) -1/8 (> i 3) -1/4 :else 0)))) Column offsets , in , in the Y and Z axes . (def column-offset #(case % (0 1) 0 2 8 3 0 -14)) (def column-height #(case % (0 1) 0 2 -5 3 0 7)) ;; The key scale of the outer columns. (def last-column-scale 3/2) Palm key location tuning offsets , in mm . (def palm-key-offset [0 -1 -3]) ;; Key plate (i.e. switch mount) parameters. This is essentially 1u in mm . (def plate-size keycap-length) (def plate-thickness 3) ; Units of mm. (def plate-hole-size 14) ;; Place nubs at the switch mount hole edges, meant to engage the tabs ;; on the switches. (def place-nub? not) ; Which side to place a nub on. Try even?, odd?, or identity. (def nub-width 1/3) ; How much the nub sticks out into the hole. (def nub-height 1.5) ; The thickness of the edge of the nub that engages the switch. ;; Thumb section parameters. Tuning offsets for the whole thumb section , in mm . (def thumb-radius 68) (def thumb-slant 0.85) ; The degree of downward slant. (def thumb-key-scale 5/4) ; The scale of the top-inner key of the thumb cluster. ;; Per-key phase along the baseline arc, in units of keys, as a pair ;; of numbers: initial phase and per-key phase increment. (defn thumb-key-phase [column row] (case row (1 2) (degrees -37/2 111/2) (degrees (if (zero? column) 12 10) 55/2))) Per - key offset from the baseline arc , in . (defn thumb-key-offset [column row] (case row 1 [0 -20 -8] 2 [0 -42 -16] (case column 0 [0 (* keycap-length 1/2 (- 3/2 thumb-key-scale)) 0] 3 [0 -4 0] [0 0 0]))) ;; Per-key vertical slope. (defn thumb-key-slope [column row] (case row 1 (degrees 33) 2 (degrees 6) 0)) ;; Height offset for the whole keyboard. (def global-z-offset 0) ;; Case-related parameters. (def ^:dynamic wall-thickness 3.2) ; Should probably be a multiple of ; nozzle/line size, if printed with ; walls only. ;; Screw bosses Each boss is a sequence of two key coordinates and , optionally , a ;; pair of parameters. The key coordinates are ultimately passed to ;; key-place; see comments there for their meaning. The boss is placed at a point on the sidewall , between the two key locations . By ;; default it's placed halfway between the given points and inset just ;; enough to clear the outer wall, but this can be tuned via the ;; optional parameters. (def screw-bosses [[[:key, 5 3, 1 -1] ; Right side [:key, 5 3, 1 1] [5/8 1]] [[:key, 5 0, 1 1] [:key, 5 0, 1 -1]] [[:key, 4 0, 0 1] ; Top side [:key, 4 0, 1/2 1]] [[:key, 2 0, 0 1] [:key, 2 0, 1/2 1]] [[:key, 0 0, 0 1] [:key, 0 0, -1/2 1]] [[:key, 0 1, -1 -1] ; Left side [:key, 0 2, -1 1]] [[:key, 0 3, -1 -1] [:thumb, 1 0, -1 1]] Front side [:thumb, 2 1, -1 -1]] [[:thumb, 0 1, 1 1] [:thumb, 0 1, 1 -1]] [[:key, 4 3, 0 -1] [:key, 4 3, -1 -1]]]) (def ^:dynamic screw-boss-radius 11/2) (def screw-boss-height 8) ;; Bottom cover parameters. (def cover-thickness 4) (def cover-countersink-diameter 9/2) ; Inner diameter of countersunk hole. (def cover-countersink-height 2.4) ; Head height. (def cover-countersink-angle (degrees 90)) ; Head angle. Cover mount thread diameter , pitch and length in . ;; Stand parameters. ;; The stand is essentially formed by a rotational extrusion of the ;; bottom cover polygon. To save on material, the inner portion is ;; removed, leaving a strip along the outside, parts of which (the ;; inner, taller tented sections) are also removed in turn, leaving ;; arm-like protrusions which are enough to stabilize the keyboard. ;; These arms can optionally be shortened to save on desktop ;; real estate, although this should be avoided, unless a bridge is ;; installed. (def stand-tenting-angle (degrees 35)) ; The angle of extrusion. 0 is radial extrusion , 1 is projection . (def stand-width 25/2) ; The width of the strip forming the stand cross-section. (def stand-minimum-thickness [6 4 4/10]) ; Thickness at inner bottom, inner top and outer bottom. (def stand-boss-indexes [0 3, 1 8]) ; The screw bosses shared by the stand. (def stand-split-points [15 51]) ; The locations where the arms begin. (def stand-arm-lengths [3 11, 2 6]) ; Hom much to shorten the arms. (def stand-arm-slope (degrees 13)) ;; Stand boot parameters. ;; The wall thickness is given as a pair of offsets from the stand walls . The total wall thickness is thus the difference of the two and the second number can be used to inset the inner boot wall , to ;; account for material removed from the stand during sanding, ;; printing tolerances, etc. (def boot-wall-thickness [11/20 -5/20]) (def boot-wall-height 2) ; The height of the sidewalls. (def boot-bottom-thickness 1) ; The thickness of the boot floor. ;; Bridge parameters. (def bridge-arch-radius 6) (def bridge-boss-indexes [4 5 6]) ; The mating boss indexes for the mount link. (def bridge-bore-expansion 1/5) ; How much to expand the diameter of bearing and link bores. (def bridge-bearing-separation -10) ; Shortens the separation of the bridge bearings. ;; The thread diameter of the bridge links also determines the geometry of the rod ends . The first value below determines the ;; nominal diameter, on which the rod end geometry is based, while the second value allows increasing the actual thread diameter above the ;; nominal, to adjust the thread fit (loose or tight), while keeping the rest of the geometry constant . The third value is the thread ;; pitch. (def bridge-link-thread [6 1/2 1]) (def bridge-link-diameter 11) ; Outer diameter of the linkage bars. ;; Link rod end specification as (type, thread length, range). The ;; type can be :fixed or :rotating. The latter type allows adjustment ;; in place, but backlash in the rotational joint makes the linkage less rigid , allowing some motion between the two halves , which can ;; be annoying. The range adjusts the spacing of the pin holes and with it the approximate range of rotation ( past the 90 ° point ) ;; before interference with the mating part prohibits further motion. (def bridge-separation-fork [:fixed 55 (degrees 10)]) (def bridge-toe-fork [:fixed 17 (degrees 10)]) (def bridge-toe-eye [:fixed 7 (degrees 20)]) (def bridge-bracket-size [18 23]) ; Cable bracket aperture size. ;; Controller PCB parameters. (def pcb-position [-108 32.5 11]) ; PCB mount location. PCB mount thread diameter , pitch and length in . ;; Printable keycap parameters. (def keycap-family-common [:fn-value (if draft? nil 500) shell width [ base top ] Mount cross arm length Mount cross arm width Mount stem radius SA family row 3 keycap . See : ;; (def keycap-family-sa (into keycap-family-common [:height (* 0.462 25.4) :radius 33.35])) (def keycap-family-sa-concave (into keycap-family-sa [:top :spherical-concave :corner-rounding 0.179])) (def keycap-family-sa-saddle (into keycap-family-sa [:top :saddle :corner-rounding 0.145 :extra-height 3/2 :saddle-aspect 2 :saddle-skew [-6/10 -8/10]])) DSA family keycap . See : ;; (def keycap-family-dsa (into keycap-family-common [:height (* 0.291 25.4) :extra-height 1/2 :base-height 1 :radius 36.5 :mount-recess 6/5])) (def keycap-family-dsa-concave (into keycap-family-dsa [:top :spherical-concave :corner-rounding 0.446])) (def keycap-family-dsa-convex (into keycap-family-dsa [:top :spherical-convex :corner-rounding 0.536])) (def keycap-family-dsa-fanged (into keycap-family-dsa-convex [:mount-offset [-0.025 0] :fang-corner-rounding 0.61 :fang-skew 3/2 :fang-angle (degrees 54)])) ;; An OEM-like keycap, at least functionally (meaning ;; cylindrical top of typical OEM radius and height somewhere between OEM R3 and R4 ) (def keycap-family-oem (into keycap-family-common [:top :cylindrical :height 15/2 :radius 26 :thickness [6/5 9/5]])) (def keycap-family-oem-flush (into keycap-family-oem [:corner-rounding 0.343])) (def keycap-family-oem-recessed (into keycap-family-oem [:corner-rounding 0.2 :mount-recess 5/2 :extra-height 5/2])) ;; Route out a keycap legend on the top of the keycap. Must be set to a [ character font - family font - size ] triplet . The official Lagrange logo keycap was created with [ " \\U01D4DB " " Latin Modern Math " 11 ] . (def keycap-legend nil) ;; Define some utility functions. (defn one-over-norm [v] (Math/pow (reduce + (map * v v)) -1/2)) (defn line-normal [a b] (let [[x y] (map - a b)] [(- y) x])) ;; Derive some utility variables and set global settings. (def columns (lazy-seq (apply range (cond (or thumb-test-build? key-test-build?) [(max 0 (key-test-range 0)) (min column-count (inc (key-test-range 2)))] :else [0 column-count])))) (def rows (lazy-seq (apply range (cond (or thumb-test-build? key-test-build?) [(max 0 (key-test-range 1)) (min row-count (inc (key-test-range 3)))] :else [0 row-count])))) (defn row [i] (if (neg? i) (+ row-count i) i)) (defn column [i] (if (neg? i) (+ column-count i) i)) (defn place-key-at? [[i j]] (and ((set columns) i) ((set rows) j) (or (#{2 3 (column -1)} i) (< j (row -1))))) (defn key-scale-at [where, i j] (if (= where :thumb) [1 (case [i j] [0 0] thumb-key-scale ([1 0] [2 0]) 3/2 1)] [(if (= i (column -1)) last-column-scale 1) 1])) (defn key-options-at [where, i j] (let [WAN [0.90980 0.90588 0.89020] VAT [0.57647 0.76078 0.27843] GQC [0.63137 0.61569 0.56863] GAH [0.50588 0.50588 0.49412] BFV [0.36471 0.80392 0.89020] BBJ [0.00000 0.56078 0.69020] BBQ [0.00000 0.65098 0.70588] BO [0.00000 0.29804 0.49804] RBD [0.82745 0.09804 0.16078] RAR [0.79608 0.18431 0.16471]] [(cond ; keycap-family (= [where, i j] [:thumb 0 1]) keycap-family-dsa-fanged (= [where, j] [:thumb, 0]) keycap-family-dsa-convex (= where :thumb) keycap-family-dsa-concave (= [where, i j] [:main, (column -1) (row -1)]) keycap-family-sa-saddle :else keycap-family-oem-flush) (if (= where :thumb) ; color (case j 0 WAN WAN) (cond (= [i j] [(column -1) (row -1)]) RAR (= i 5) GQC :else WAN))])) (defn scale-to-key [where, i j, x y z] ;; Scale normalized plate coordinates (i.e. in [-1 1]) to world ;; space. We stretch recessed (w.r.t their neighbors) columns in ;; the main section, as well as certain keys in the thumb section, ;; to allow more room for keycaps. (let [stretch (if (not= where :thumb) (cond (or (and (= i 2) (not= j (row -1))) (and (= i 3) (pos? x))) [6/5 1 1] :else [1 1 1]) (cond (and (= [i j] [0 0]) (neg? x) (pos? y)) [1 1.1 1] (and (= [i j] [1 0]) (pos? y)) [1 1.02 1] (and (= [i j] [3 0]) (neg? y)) [1 17/16 1] :else [1 1 1]))] (map * [x y z] stretch (conj (mapv (partial * 1/2) (key-scale-at where, i j)) 1/2) [plate-size plate-size plate-thickness]))) (defn thread [D_maj P L & [L_extra]] (if (or draft? mock-threads?) (let [r (/ D_maj 2)] (union (cylinder r L :center false) (translate [0 0 L] (cylinder [r 0] (or L_extra r) :center false)))) ;; Match the *fs* setting, which is, by definition: ;; * fs * = δθ * r = δθ * D_Maj / 2 = π * D_Maj / ( 2 * a ) ;; Therefore : a = π * D_Maj / ( 2 * * fs * ) (let [a (int (/ (* π D_maj) 2 scad-clj.model/*fs*)) δθ (/ π a) N (int (/ (* 2 a L) P)) H (* 1/2 (Math/sqrt 3) P) D_min (- D_maj (* 10/8 H))] (polyhedron (concat [[0 0 0]] ;; Vertices (apply concat (for [i (range N) :let [r (+ D_maj (/ H 4)) [x_1 x_2] (map (partial * 1/2 (Math/cos (* i δθ))) [D_min r]) [y_1 y_2] (map (partial * 1/2 (Math/sin (* i δθ))) [D_min r]) z #(* (+ % (/ (* i δθ) 2 π)) P)]] [[x_1 y_1 (z -1/2)] [x_1 y_1 (z -3/8)] [x_2 y_2 (z 0)] [x_1 y_1 (z 3/8)] [x_1 y_1 (z 1/2)]])) ;; Make the top of the thread conical, to ensure no support is ;; needed above it (for female threads). [[0 0 (+ L (or L_extra (/ D_maj 2)))]]) ;; Indices (concat [(conj (range 5 0 -1) 5 0)] (for [i (range (* 2 a))] [0 (inc (* i 5)) (inc (* (inc i) 5))]) (for [i (range (dec N)) j (range 4)] (map (partial + 1 (* i 5)) [j (inc j) (+ 6 j) (+ 5 j)])) (for [i (range (* 2 a))] (map (partial - (* 5 N)) [-1 (* i 5) (* (inc i) 5)])) [(map (partial - (* 5 N)) (conj (range 4 -1 -1) -1 0))]))))) ;;;;;;;;;;;;;;;;;;;;;; Controller board ; ; ;;;;;;;;;;;;;;;;;;;;;; (def pcb-size [30 65]) (def pcb-thickness 1.6) ;; The radius and position of the board screw hole, measured from the ;; corner of the board. (def pcb-mount-hole [3/2 4 4]) ;; The size and position of the connectors, measured from the ;; upper-left corner of the board to the upper-left corner of the ;; connector. (def pcb-button-position [4.6 52.7]) (def pcb-button-diameter 2.5) (def pcb-6p6c-size [16.64 13.59 16.51]) (def pcb-6p6c-position [2.9 17.4]) (def pcb-usb-size [11.46 12.03 15.62]) (def pcb-usb-position [7.8 2.2]) (defn pcb-place [flip? shape] (cond->> shape flip? (translate (map * [0 -1] pcb-size)) (not flip?) (mirror [0 1 0]) true (rotate [0 π 0]) true (translate pcb-position))) (def pcb-button-hole-cutout (delay (->> (cylinder (/ pcb-button-diameter 2) 50) (translate pcb-button-position)))) (def pcb-connector-cutout (apply union (for [[size position] [[pcb-usb-size pcb-usb-position] [pcb-6p6c-size pcb-6p6c-position]] :let [δ 0.8 [a b c] (map + [δ δ 0] size) [x y] (map (partial + (/ δ -2)) position)]] (union ;; Main cutout (->> (cube a b c :center false) (translate [x y pcb-thickness])) ;; Chamfer cutout (->> (square a b) (extrude-linear {:height 1/2 :scale [(+ 1 (/ 1 a)) (+ 1 (/ 1 b))] :center false}) (union (translate [0 0 (+ 50/2 1/2)] (cube (+ a 1) (+ b 1) 50))) (translate [(+ x (/ a 2)) (+ y (/ b 2)) (+ (last pcb-position) cover-thickness -3/2)])))))) (def pcb-bosses (for [s [-1 1] t [-1 1] :let [[w h] pcb-size [_ δx δy] pcb-mount-hole [D P L] pcb-fastener-thread d 6.8 ;; Make the boss a little higher than the thread (here 0.8 mm ) to allow for a couple of solid layers at the ;; bottom of the boss and a better attachment to the ;; base. h_b (+ L (/ D 2) 4/5) z (partial + (last pcb-position))]] (->> (difference (->> (cube d d h_b) (intersection (cylinder 4 h_b)) (translate [0 0 (z (/ h_b -2))])) (->> (apply thread (update pcb-fastener-thread 2 + P)) (translate [0 0 (z (- (+ h_b P)))]))) (translate [(- (* 1/2 (inc s) w) (* s δx)) (- (* 1/2 (inc t) h) (* t δy)) 0])))) (def pcb (let [corner-radius 4] (with-fs 1/2 ;; The PCB. (color [0 0.55 0.29] (difference (hull ;; The basic PCB... (for [s [-1 1] t [-1 1] :let [[w h] pcb-size]] (->> (cylinder corner-radius pcb-thickness) (translate [(- (* 1/2 (inc s) w) (* s corner-radius)) (- (* 1/2 (inc t) h) (* t corner-radius)) (/ pcb-thickness 2)])))) ;; minus the mount holes... (for [s [-1 1] t [-1 1] :let [[w h] pcb-size [r δx δy] pcb-mount-hole]] (->> (cylinder r (* 3 pcb-thickness)) (translate [(- (* 1/2 (inc s) w) (* s δx)) (- (* 1/2 (inc t) h) (* t δy)) 0]))) ;; minus the center cutout. (->> (cylinder 6 (* 3 pcb-thickness)) (union (translate [6 0 0] (cube 12 12 (* 3 pcb-thickness)))) (translate [29 32.5 0])))) ;; The USB/6P6C connectors. (color (repeat 3 0.75) (->> (apply cube (conj pcb-usb-size :center false)) (translate (conj pcb-usb-position pcb-thickness))) (->> (apply cube (conj pcb-6p6c-size :center false)) (translate (conj pcb-6p6c-position pcb-thickness)))) ;; The USB cable (translate (conj (mapv #(+ %1 (/ %2 2)) pcb-usb-position pcb-usb-size) (+ pcb-thickness 7)) (->> (cube 7 8 12) ; The plug (color (repeat 3 0.85)) (translate [0 0 6])) (->> (cube 22 13 16) ; The housing (color (repeat 3 0.2)) (translate [9/2 0 20])) (->> (cylinder 4 10) ; The strain relief (color (repeat 3 0.2)) (rotate [0 (/ π 2) 0]) (translate [41/2 0 21])) (->> (cylinder 2 30) ; The cable (color (repeat 3 0.2)) (rotate [0 (/ π 2) 0]) (translate [71/2 0 21]))) ;; The board-to-wire connectors. (color [1 1 1] (for [y [8 39]] (translate [25 y -8] (cube 4.5 18 8 :center false))) (translate [9 60 -8] (cube 14 4.5 8 :center false)))))) (def pcb-harness-bracket (let [δ -5/2 r (first pcb-mount-hole) h (second pcb-size)] (difference (union (hull (translate [δ 0 7/2] (cube 2 h 6)) (translate [δ 0 7] (cube 2 (- h 2) 1))) (for [s [-1 1] :let [y (* s (- (* 1/2 h) 4))]] (translate [0 y -1] (map hull (partition 2 1 [(translate [δ (* 3/2 s) 1] (cube 2 5 2)) (translate [(+ δ 1) (* 3/2 s) 0] (cube 2 5 2)) (translate [1/2 (* 3/2 s) 0] (cube 2 5 2))])) (hull (translate [1/2 (* 3/2 s) 0] (cube 2 5 2)) (translate [4 0 0] (cylinder 4 2)))))) (hull (translate [δ 0 -1/2] (cube 3 (- h 10) 6)) (translate [δ 0 3] (cube 3 (- h 12) 1))) (for [s [-1 1] :let [y (* s (- (* 1/2 h) 4))]] (translate [4 y 0] (cylinder (+ r 1/3) 10)))))) ;;;;;;;;;; ;; Keys ;; ;;;;;;;;;; (defn key-plate [where, i j] (let [key-scale (key-scale-at where, i j)] (difference (union (translate [0 0 (/ plate-thickness -2)] (difference (apply hull (for [s [-1 1] t [-1 1] u [1 -1] :let [[x y z] (scale-to-key where, i j, s t u)]] (->> (sphere (/ plate-thickness 4 (Math/cos (/ π 8)))) (with-fn 8) (rotate [0 0 (/ π 8)]) (translate [x y 0]) (translate (map (partial * (/ plate-thickness -4)) [s t])) (translate [0 0 (/ z 2)])))) (cube plate-hole-size plate-hole-size (* 2 plate-thickness)))) (for [i (range 4) :let [nub-length 5 [a b] ((if (even? i) identity reverse) (mapv * (repeat plate-size) key-scale))]] (rotate [0 0 (* i π 1/2)] (union (when (place-nub? i) (->> (cube (* nub-width 11/10) nub-length nub-height :center false) (mirror [0 0 1]) (translate [(- (+ (/ plate-hole-size 2) (* nub-width 1/10))) (/ nub-length -2) 0]))))))) ;; Enlarge the hole below the nubs, to provide some space for ;; the tabs on the switch to extend into. (let [d 5 ; The depth of the keyswitch below the top of the plate. l 3/4 ; Extend the hole by this much on each side. m (+ nub-height l) c (+ plate-hole-size (* 2 l)) h (- plate-thickness m)] (translate [0 0 (- m)] (->> (square c c) (extrude-linear {:height (+ l nub-width) :scale (repeat 2 (/ (- plate-hole-size (* 2 nub-width)) c)) :center false})) (translate [0 0 (/ (- m d) 2)] (cube c c (- d m)))))))) (def keyswitch-socket Kaihua PG1511 keyswitch socket . (+ -1.675 -5.08) (+ -5 -3.05)] (with-fn 30 (color (repeat 3 0.2) (difference (cube 10.9 5.89 1.80 :center false) ; Main body (translate [10.9 0 0] ; Bottom-right fillet cutout (difference (cube 4 4 10) (translate [-2 2 0] (cylinder 2 10)))) (translate [0 5.89 0] ; Top cutout (union (cube 10.8 4 10) (translate [5.4 0 0] (cylinder 2 10))))) Switch pin contacts (for [r [[2.275 1.675 0] [8.625 4.215 0]]] (translate r (cylinder (/ 2.9 2) 3.05 :center false))))) (color (repeat 3 0.75) ; Board contacts (apply union (for [r [[-1.8 (- 1.675 (/ 1.68 2)) 0] [10.9 (- 4.215 (/ 1.68 2)) 0]]] (translate r (cube 1.8 1.68 1.85 :center false)))))))) (defn orient-keyswitch [where, i j, shape] (cond->> shape (or (and (not= where :thumb) (not= i 2) (not= i 5) (not= j 0)) (and (= where :thumb) (not= j 0))) (rotate [0 0 π]))) (defn keyswitch [where, i j] (orient-keyswitch where, i j (union (color (repeat 3 0.2) (hull ; Casing, below the plate. (translate [0 0 -5/4] (cube 13.95 13.95 5/2)) (translate [0 0 -15/4] (cube 12.5 13.95 5/2))) (translate [0 0 -5.4] ; Center locating pin. (cylinder (/ 3.85 2) 2)) (->> (square 13.95 15.6) ; Casing, above the plate. (translate [0 2 0]) (extrude-linear {:height 6.2 :scale [2/3 2/3] :center false}) (translate [0 -2 0]))) (color [0.1 0.5 1] (translate [0 0 8] ; Stem (cube 6 6 4))) (color [0.8 0.5 0.2] ; Electrical terminals. (translate [-2.54 -5.08 -6.30] (cube 1.5 0.2 3)) (translate [3.81 -2.54 -5.85] (cube 1.5 0.2 4)))))) ;; A basic keycap shape. Cylindrical sides, spherical top, rounded corners . Can be configured to yield SA and DSA style keycaps . ;; Additionally supports a couple more exotic shapes. ;; ;; Where: ;; h is the height of keycap (at top center), h_0 is the height of vertical ( i.e. not curved ) section at bottom , ;; ρ is the shared radius of sides, top and corner rounding, ;; φ determines how deeply to round the corners. (defn base-keycap-shape [size h h_0 ρ & {:keys [fn-value shape top corner-rounding saddle-aspect saddle-skew fang-angle fang-skew fang-corner-rounding]}] (let [[minus-or-plus intersection-or-difference] (case top (:spherical-convex :saddle) [- intersection] [+ difference]) Half - length at base Half - length at top ;; h_1 is height at center of each crest h_1 (case top :saddle h :cylindrical (minus-or-plus h (- ρ (Math/sqrt (- (* ρ ρ) (* d_1 d_1))))) (minus-or-plus h (* ρ (- 1 (Math/cos (Math/asin (/ d_1 ρ))))))) Consider two points on the center of the base and top of a ;; side of the key. O is the center of a circle of the given ;; radius passing through them. This will be used to form the ;; sides. p [d_0 h_0] q [d_1 h_1] v (map (partial * 1/2) (map - q p)) a (one-over-norm v) b (Math/pow (- (* ρ ρ) (/ 1 a a)) 1/2) O (map + p v [(* -1 b a (second v)) (* b a (first v))])] ;; We need to set *fn* explicitly, since extrude-rotate below ;; doesn't seem to respect the *fa*/*fs* settings. (union (with-fn (or fn-value (and draft? 80) 160) (cond-> (intersection-or-difference (intersection ;; Initial block. (or shape (union (translate [0 0 h] (apply cube (conj size (* 2 h)))) (when fang-angle ; Extend the side circularly. (->> (square (size 1) (* 2 h)) (translate [0 h]) (intersection (translate O (circle ρ))) (translate [(/ (size 1) 2) 0]) (intersection ; Errors from the previous intersection can extend ; the shape to span the Y axis, so we clip it. (translate [50 0] (square 100 100))) (extrude-rotate {:angle (/ fang-angle π 1/180)}) (rotate (/ π 2) [0 0 1]) (translate (map * (repeat -1/2) size)))))) ;; Cylindrical sides. (for [s [-1 1] t [0 1] :let [fang (and fang-angle (= [s t] [-1 0]))]] (cond->> (cylinder ρ (+ (apply max size) 100)) true (rotate (/ π 2) [1 0 0]) true (translate [(* s (+ (first O) (/ (- (size t) keycap-length) 2))) 0 (second O)]) true (rotate (* t π 1/2) [0 0 1]) fang (translate (map * (repeat 1/2) size)) fang (rotate fang-angle [0 0 1]) fang (translate (map * (repeat -1/2) size))))) ;; Plus or minus the top. (case top top . :saddle (->> (circle ρ) (translate [(* saddle-aspect ρ) 0]) (extrude-rotate {:angle 360}) (rotate [(/ π 2) (/ π 2) 0]) (translate [0 0 (* (- saddle-aspect 1) ρ)]) (translate (map * (concat saddle-skew [1]) (repeat h)))) :cylindrical (->> (cylinder ρ 100) (scale [(/ (first size) keycap-length) 1 1]) (rotate [(/ π 2) 0 0]) (translate [0 0 (+ ρ h)])) ;; Spherical top (rotated to avoid poles). (apply hull (for [s [-1/2 1/2] t [-1/2 1/2] :let [δ (map - (if (and fang-angle (neg? s)) (map * [fang-skew 1] size) size) (repeat keycap-length))]] (->> (sphere ρ) (rotate [(/ π 2) 0 0]) (translate (conj (mapv * [s t] δ) (minus-or-plus h ρ)))))))) ;; Rounded corner. corner-rounding (difference (for [s [0 1] t [0 1] :when (or (not fang-angle) (not= [s t] [0 0])) :let [fang (and fang-angle (zero? s)) ρ_0 2 ρ_1 ρ]] (cond->> (difference (circle 10) (circle ρ_0) (union (translate [-50 0] (square 100 100 :center false)) (translate [0 -50] (square 100 100 :center false)))) true (rotate [0 0 (/ π -4)]) true (translate [(- ρ_1) 0]) true (extrude-rotate {:angle 90}) true (translate [(+ ρ_0 ρ_1) 0]) true (rotate [(/ π -2) (if fang fang-corner-rounding corner-rounding) (/ π 4)]) true (translate (conj (mapv (partial * -1/2) size) h_0)) true (mirror [s 0]) true (mirror [0 t]) fang (translate (map * (repeat 1/2) size)) fang (rotate fang-angle [0 0 1]) fang (translate (map * (repeat -1/2) size)))))))))) (defn keycap-shape [size & rest] Keycap height ( measured at top - center ) . h_add :extra-height ; Additional (wrt profile) height. h_0 :base-height ; Height of vertical part of base. Radius of sides and top . :or {h_add 0 h_0 0}} rest] (apply base-keycap-shape size (+ h h_add) h_0 ρ rest))) (defn keycap [where, i j] For distance from key plate to released keycap ( for Cherry MX ;; switches, and assuming stem flush with keycap bottom), see: ;; ;; (let [[family-options color-triplet] (key-options-at where, i j)] (->> (apply keycap-shape (mapv (partial * keycap-length) (key-scale-at where, i j)) family-options) (translate [0 0 (if keys-depressed? 3 6.6)]) (color color-triplet)))) (defn printable-keycap [scale & rest] (let [size (mapv (partial * keycap-length) scale) {w :thickness a :mount-cross-length b :mount-cross-width r :mount-radius δ :mount-offset h :height h_add :extra-height h_0 :mount-recess h_1 :homing-bar-height :or {δ [0 0] h_add 0 h_0 0 h_1 0} } rest δ_1 3/2 δ_2 0.4 δ_3 (mapv (partial * keycap-length) δ)] (difference (union ;; The shell (difference (union (apply keycap-shape size rest) (when (pos? h_1) (->> (apply keycap-shape size rest) (intersection (hull (for [x [-2 2]] (translate [x 0 0] (with-fn 50 (cylinder 1/2 100)))))) (translate [0 0 h_1])))) (union (apply keycap-shape (mapv (partial + (* -2 (first w))) size) (apply concat (-> (apply hash-map rest) (dissoc :corner-rounding) (update :extra-height #(- (or % 0) (second w))) seq))) (translate [0 0 -4.99] (apply cube (conj (mapv (partial + (* -2 (first w))) size) 10))))) ;; The stem (apply keycap-shape size :shape (translate (conj δ_3 h_0) (cylinder r 100 :center false)) rest)) (translate (conj δ_3 (+ 2 h_0)) (for [θ [0 (/ π 2)]] (rotate [0 0 θ] (translate [0 0 -1/2] (cube a b 5)) (->> (square a b) (extrude-linear {:height (/ b 2) :scale [1 0] :center false}) (translate [0 0 2])))) (->> (cube 15/8 15/8 4) (rotate [0 0 (/ π 4)]))) ;; The legend (when-let [[c font size] keycap-legend] (->> (text c :font font :size size :halign "center" :valign "center") (extrude-linear {:height 1 :center false}) (translate [0 0 (+ h h_add -1/2)])))))) ;; Set up bindings that either generate SCAD code to place a part, or ;; calculate its position. (declare ^:dynamic rotate-x ^:dynamic rotate-z ^:dynamic translate-xyz) (defn transform-or-calculate [transform?] (if transform? {#'rotate-x #(rotate %1 [1 0 0] %2) #'rotate-z #(rotate %1 [0 0 1] %2) #'translate-xyz translate} {#'rotate-x #(identity [(first %2) (reduce + (map * %2 [0 (Math/cos %1) (- (Math/sin %1))])) (reduce + (map * %2 [0 (Math/sin %1) (Math/cos %1)]))]) #'rotate-z #(identity [(reduce + (map * %2 [(Math/cos %1) (- (Math/sin %1)) 0])) (reduce + (map * %2 [(Math/sin %1) (Math/cos %1) 0])) (nth %2 2)]) #'translate-xyz (partial mapv +)})) ;; Either place a shape at [x y z] in the local frame of key [i j] in ;; section where (either :thumb or :key), or calculate and return the ;; coordinates of a point relative to that location. For convenience, ;; the scale of the local frame depends on the key size in question, so that [ x y z ] = [ 1 1 0 ] is at the top right corner of the upper face of the plate ( z starts at zero at the top of the face , as ;; opposed to the center as is the case for x and y, to ensure that ;; the key geometry doesn't change with plate thickness). (defn key-place [where, i j, x y z & [shape-or-point]] (if (not= where :thumb) ;; Place on/at a main section key. (let [offset (scale-to-key where, i j, x y z)] ;; The key plates are spread out along the surface of a torus and are always tangent to it . The angle subtended by a 1u key plate ( of dimensions plate - size ) is 2 * atan(l / 2r ) , ;; where l and r the respective edge length and radius. (let [central-angle (fn [l r] (* 2 (Math/atan (/ l 2 r)))) location (fn [s t phase scale spacing radius] (reduce + (* (+ (phase s) (* scale 1/2)) (central-angle plate-size radius)) (for [k (range t)] (central-angle (+ plate-size (spacing k)) radius)))) θ (location i j column-phase 1 (constantly (row-spacing i)) (column-radius i)) φ (location j i row-phase (first (key-scale-at where, i j)) column-spacing row-radius) maybe-flip #(if (= [i j] [(column -1) (row -1)]) (->> % (translate-xyz palm-key-offset) (translate-xyz [0 (* -1/2 plate-size) 0]) (rotate-x (/ π 2)) (translate-xyz [0 (* 1/2 plate-size) 0])) %)] (with-bindings (transform-or-calculate (fn? shape-or-point)) (->> (if (fn? shape-or-point) (shape-or-point where, i j) (or shape-or-point [0 0 0])) (translate-xyz offset) maybe-flip (translate-xyz [0 0 (- (column-radius i))]) (rotate-x (- θ)) (translate-xyz [0 0 (column-radius i)]) (translate-xyz [0 0 (- row-radius)]) (rotate-x (/ π 2)) (rotate-z (- φ)) (rotate-x (/ π -2)) (translate-xyz [0 0 row-radius]) (translate-xyz [0 (column-offset i) 0]) (translate-xyz [0 0 (column-height i)]) (translate-xyz [0 0 global-z-offset]))))) ;; Same as above, but for the thumb section. (with-bindings (transform-or-calculate (fn? shape-or-point)) (->> (if (fn? shape-or-point) (shape-or-point where, i j) (or shape-or-point [0 0 0])) (translate-xyz (scale-to-key where, i j, x y z)) (rotate-x (thumb-key-slope i j)) (translate-xyz (thumb-key-offset i j)) (translate-xyz [0 thumb-radius 0]) (rotate-x (- thumb-slant)) (rotate-z (reduce + (map * (thumb-key-phase i j) [1 i]))) (rotate-x thumb-slant) (translate-xyz [0 (- thumb-radius) 0]) (translate-xyz (map + (key-place :main, 1 (row -2), 1 -1 0) thumb-offset)))))) (defn key-placed-shapes [shape] (for [i columns j rows :when (place-key-at? [i j])] (key-place :main, i j, 0 0 0, shape))) (defn thumb-placed-shapes [shape] (for [j (range 3) i (case j 0 (range 4) 1 (range 3) [1])] (key-place :thumb, i j, 0 0 0, shape))) ;;;;;;;;;;;;;;;;;;;;;;; ;; Connecting tissue ;; ;;;;;;;;;;;;;;;;;;;;;;; (defn web-kernel [place, i j, x y & [z]] ;; These are small shapes, placed at the edges of the key plates. ;; Hulling kernels placed on neighboring key plates yields ;; connectors between the plates, which preserve the plate's chamfer ;; and are of consistent width. (We make the ;; kernels "infinitesimally" larger than the key plates, to avoid ;; non-manifold results). (key-place place, i j, x y (or z 0) (fn [& _] (let [[δx δy] (map #(* (compare %1 0) -1/4 plate-thickness) [x y]) ε (+ (* x 0.003) (* y 0.002))] (->> (sphere (/ (+ plate-thickness ε) 4 (Math/cos (/ π 8)))) (with-fn 8) (rotate [0 0 (/ π 8)]) (translate [δx δy (/ plate-thickness s 4)]) (for [s [-1 1]]) (apply hull) (translate [0 0 (/ plate-thickness -2)])))))) (def key-web (partial web-kernel :main)) (def thumb-web (partial web-kernel :thumb)) (defn triangle-hulls [& shapes] (->> shapes (partition 3 1) (map (partial apply hull)) (apply union))) (def connectors (delay (list* ;; Odds and ends, which aren't regular enough to handle in a loop. (when (every? place-key-at? [[1 (row -2)] [2 (row -2)]]) (triangle-hulls (key-web 1 (row -2) 1 -1) (key-web 1 (row -2) 1 1) (key-web 2 (row -2) -1 -1) (key-web 1 (row -3) 1 -1))) (when (every? place-key-at? [[2 0] [1 0] [2 0]]) (triangle-hulls (key-web 2 1 -1 1) (key-web 1 0 1 1) (key-web 2 0 -1 -1) (key-web 2 0 -1 1))) (when (every? place-key-at? [[3 (row -1)] [3 (row -2)] [4 (row -2)]]) (triangle-hulls (key-web 3 (row -2) 1 -1) (key-web 4 (row -2) -1 -1) (key-web 3 (row -1) 1 1) (key-web 3 (row -1) 1 -1))) ;; Palm key connectors. (when (every? place-key-at? [[(column -1) (row -2)] [(column -2) (row -2)]]) (triangle-hulls (key-web (column -1) (row -2) -1 -1) (key-web (column -1) (row -1) -1 1) (key-web (column -2) (row -2) 1 -1))) ;; Regular connectors. (concat (for [i (butlast columns) ; Row connections j rows :let [maybe-inc (if (= i 1) inc identity)] :when (and (not= [i j] [1 (row -2)]) (every? place-key-at? [[i j] [(inc i) j]]))] (apply triangle-hulls (cond-> [(key-web i j 1 1) (key-web i j 1 -1) (key-web (inc i) (maybe-inc j) -1 1)] This bit is irregular for the ( row -1 ) of the first ;; column. It's taken care of by the thumb connectors. (not= [i j] [1 (row -2)]) (into [(key-web (inc i) (maybe-inc j) -1 -1)])))) (for [i columns ; Column connections j (butlast rows) :when (every? place-key-at? [[i j] [i (inc j)]])] (triangle-hulls (key-web i j -1 -1) (key-web i j 1 -1) (key-web i (inc j) -1 1) (key-web i (inc j) 1 1))) Diagonal connections j (butlast rows) :let [maybe-inc (if (= i 1) inc identity)] :when (and (not= [i j] [1 (row -3)]) (every? place-key-at? (for [s [0 1] t [0 1]] [(+ i s) (+ j t)])))] (triangle-hulls (key-web i j 1 -1) (key-web i (inc j) 1 1) (key-web (inc i) (maybe-inc j) -1 -1) (key-web (inc i) (maybe-inc (inc j)) -1 1))))))) (def thumb-connectors (delay (let [z (/ ((thumb-key-offset 0 1) 2) plate-thickness) y -5/16] (list (triangle-hulls (thumb-web 0 0 1 -1) (thumb-web 1 0 1 -1) (thumb-web 0 0 -1 -1) (thumb-web 1 0 1 1) (thumb-web 0 0 -1 1) (thumb-web 0 0 -1 1) (thumb-web 0 0 1 1)) (triangle-hulls (thumb-web 2 0 1 1) (thumb-web 1 0 -1 1) (thumb-web 2 0 1 -1) (thumb-web 1 0 -1 -1) (thumb-web 1 1 -1 1) (thumb-web 1 0 1 -1) (thumb-web 1 1 1 1)) (triangle-hulls (thumb-web 0 0 1 -1 z) (thumb-web 1 1 1 1) (thumb-web 0 1 -1 1) (thumb-web 1 1 1 -1) (thumb-web 0 1 -1 -1) (thumb-web 1 2 1 1) (thumb-web 0 1 1 -1) (thumb-web 1 2 1 -1)) (triangle-hulls (thumb-web 2 1 -1 1) (thumb-web 3 0 -1 -1) (thumb-web 2 1 1 1) (thumb-web 3 0 1 -1) (thumb-web 2 0 -1 -1) (thumb-web 3 0 1 1) (thumb-web 2 0 -1 1)) (triangle-hulls (thumb-web 2 0 1 -1) (thumb-web 2 0 -1 -1) (thumb-web 1 1 -1 1) (thumb-web 2 1 1 1) (thumb-web 1 1 -1 -1) (thumb-web 2 1 1 -1) (thumb-web 1 2 -1 1) (thumb-web 2 1 -1 -1) (thumb-web 1 2 -1 -1)) (triangle-hulls (thumb-web 1 1 -1 -1) (thumb-web 1 2 -1 1) (thumb-web 1 1 1 -1) (thumb-web 1 2 1 1)) (when (place-key-at? [0 (row -2)]) (triangle-hulls (key-web 1 (row -2) -1 -1) (key-web 0 (row -2) 1 -1) (thumb-web 0 0 -1 1) (key-web 0 (row -2) -1 -1) (thumb-web 1 0 1 1) (thumb-web 1 0 -1 1))) (triangle-hulls (thumb-web 0 1 -1 1) (thumb-web 0 1 1 1) (thumb-web 0 0 1 -1 z) (key-web 3 (row -1) -1 -1) (key-web 2 (row -1) -1 -1) (key-web 2 (row -1) 1 -1)) (triangle-hulls (thumb-web 1 1 1 1) (thumb-web 1 0 1 -1) (thumb-web 0 0 1 -1 z) (thumb-web 0 0 1 -1) (key-web 2 (row -1) -1 -1) (thumb-web 0 0 1 1) (key-web 2 (row -1) -1 y) (thumb-web 0 0 -1 1) (key-web 1 (row -2) 1 -1) (key-web 1 (row -2) -1 -1)) (triangle-hulls (key-web 2 (row -1) -1 y) (key-web 2 (row -1) -1 1) (key-web 1 (row -2) 1 -1) (key-web 2 (row -2) -1 -1)))))) ;;;;;;;;;; ;; Case ;; ;;;;;;;;;; (defn case-placed-shapes [brace] (let [place #(apply brace %&) strip (fn [where & rest] (for [ab (partition 2 1 rest)] (apply place (map (partial cons where ) (if (:reverse (meta (first ab))) (reverse ab) ab)))))] (concat ;; Back wall (list* (place [:left, 0 0, -1 1] [:back, 0 0, -1 1]) (apply strip :back (for [i columns x (conj (vec (range -1 1 (/ 1/2 (first (key-scale-at :main, i 0))))) 1)] [i 0, x 1]))) (list (place [:back, (column -1) 0, 1 1] [:right, (column -1) 0, 1 1])) ;; Right wall (apply strip :right (for [j rows y [1 -1]] [(column -1) j, 1 y])) Front wall (list* (place [:right, (column -1) (row -1), 1 -1] [:front, (column -1) (row -1), 1 -1, -1/4 1/4]) (strip :front [(column -1) (row -1), 1 -1, -1/4 1/4] [(column -1) (row -1), -1 -1, 1/4 1/4] [(column -1) (row -1), -1 1, -5 -8 0] [(column -2) (row -2), 1 -1, -9 -4] [(column -2) (row -2), 0 -1, 0 -4] [(column -2) (row -2), -1 -1, 3 -4] [3 (row -1), 1 -1, 0 -3 -9/2] [3 (row -1), 0 -1, 4 -3 -9/2] [3 (row -1), -1 -1])) ;; Thumb walls (list* (place [:front, 3 (row -1), -1 -1] [:thumb, 0 1, 1 1]) (strip :thumb [0 1, 1 1] [0 1, 1 -1, 1/2 0 -2] [1 2, 1 -1, 1 -1] [1 2, -1 -1, -1 -1] [2 1, -1 -1, -1/2 0 -2] [2 1, -1 1, -1/2 -1 -2] [3 0, -1 -1, -1/2 17/8 -5] [3 0, -1 1, 1/2 -7/4 -3] [3 0, -1 1, 7/4 -1/2 -3] [3 0, 1 1, -3 1/2 -5] [2 0, -1 1, 0 1] [2 0, 1 1, 0 1] [1 0, -1 1])) (list (place [:thumb, 1 0, -1 1] [:left, 0 (row -2), -1 -1])) ;; Left wall. Stripping in reverse order is necessary for ;; consistent winding, which boss placement relies on. (apply strip :left (for [j (rest (reverse rows)) y [-1 1]] [0 j, -1 y]))))) (defn lagrange [i j, x y z, dy] ;; They curve of the back side is specified via a set of points measured from the keys of the first row . It passes through those points and is smoothly interpolated in - between , using a Lagrange polynomial . We introduce a discontinuity between the second and third column , purely for aesthetic reasons . (let [discontinuous? true [xx yy zz] (if (and discontinuous? (< i 2)) [-23/4 0 -65/4] [0 23/4 -13]) u (first (key-place :main, i j, x y 0)) uu [(first (key-place :main, 0 0, -1 y 0)) (first (key-place :main, 3 0, 1 y 0)) (first (key-place :main, (column -1) 0, 1 y 0))] vv [(key-place :main, 0 0, -1 y z, [(if (neg? z) 10 0) (+ (* 1/2 (- 1 y) plate-size) dy) -15]) (key-place :main, 3 0, 1 y (* 5/13 z), [xx (+ (* 5/13 dy) yy) zz]) (key-place :main, (column -1) 0, 1 y 0, [-1 -5/4 -13/4])] l (fn [k] (reduce * (for [m (range (count uu)) :when (not= m k)] (/ (- u (uu m)) (- (uu k) (uu m))))))] (apply (partial map +) (for [k (range (count vv))] (map (partial * (l k)) (vv k)))))) (defn wall-place [where, i j, x y z, dx dy dz & [shape]] (let [offsets (map (fn [a b] (or a b)) [dx dy dz] (case where :back [0 0 -15] :right (case [j y] [0 1] [-1/4 -5/2 -5/2] [3 -1] [-3/8 3/2 -19/8] [4 1] [-3/8 -3/2 -19/8] [4 -1] [-1/4 1/4 -5/2] [-1/4 0 -5/2]) :left [0 (case [j y] [3 -1] 2 0) -15] :front (if (= [i j, x y] [3 (row -1), -1 -1]) [7 -5 -6] [0 1/2 (if (= i 4) -5 -5/2)]) :thumb (cond (= [i j, x] [1 0, -1]) [1 0 -3/2] (= [i j, x y] [0 1, 1 1]) [0 -3/8 -2] :else [0 0 -6])))] (if (= where :back) (cond-> (lagrange i j, x y z, (second offsets)) shape (translate shape)) (key-place where, i j, x y z (cond-> offsets shape (-> (translate shape) constantly)))))) (defn wall-place-a [where i j x y dx dy dz & [shape]] (wall-place where i j x y 0 dx dy dz shape)) (defn wall-place-b [where i j x y dx dy dz & [shape]] (cond (= where :left) (wall-place where i j x y -4 8 (case [j y] [0 1] -10 [3 -1] 6 0) dz shape) (= where :back) (wall-place where i j x y -4 dx -8 dz shape) (and (= where :thumb) (not= [i j] [3 0]) (not= [i j] [0 1]) (not= [i j] [2 1]) (not= [i j x] [1 0, -1]) (not= [i j x] [2 0, 1])) (wall-place where i j x y -5 (- dx) (- dy) dz shape) (and (= [i j] [(column -1) (row -1)]) (not= y 1)) (wall-place where i j x y -3 dx dy dz shape) :else (wall-place-a where i j x y dx dy dz shape))) (defn wall-sections [endpoints] (apply map vector (for [[where i j x y dx dy dz] endpoints :let [r (/ wall-thickness 2) shape-a (wall-place-a where i j x y dx dy dz (sphere r)) shape-b (wall-place-b where i j x y dx dy dz (sphere r))]] [(web-kernel where, i j, x y) shape-a shape-b (->> shape-b project (extrude-linear {:height 1/10 :center false}))]))) (defn wall-brace [sections & endpoints] consecutive sections to form the walls . Filter out ;; degenerate segments (where the parts are colinear, instead of ;; forming a triangle, for instance because shape-a and shape-b ;; above coincide), to avoid wasting cycles to generate non-manifold ;; results. (->> (sections (reverse endpoints)) (apply concat) (partition 3 1) (filter #(= (count (set %)) 3)) (map (partial apply hull)) (apply union))) ;; Decide when to place a screw boss in a segment and what parameters ;; to use. Note that we also use this to create a cutout for case ;; test builds. (defn place-boss? ([endpoints] (place-boss? (if case-test-build? (set case-test-locations) (constantly true)) endpoints)) ([boss-filter endpoints] (let [boss-map (apply hash-map (apply concat (keep-indexed #(when (boss-filter %1) [(set (take 2 %2)) (nth %2 2 [1/2 1])]) screw-bosses)))] (boss-map (set (map (comp (partial take 5) #(cons (if (= (first %) :thumb) :thumb :key) (rest %))) endpoints)))))) (defn boss-place [x d endpoints & shape] (let [ab (for [[where i j x y dx dy dz] endpoints] (wall-place-b where i j x y dx dy dz)) n (apply line-normal ab)] Place the boss at some point x ( in [ 0 , 1 ] ) along the wall ;; segment , displaced d radii inwards along the normal ;; direction. (cond-> (->> ab (take 2) (apply map #(+ %1 (* (- %2 %1) x))) (mapv + (map (partial * d screw-boss-radius (one-over-norm n)) n))) shape (translate shape)))) (defn screw-boss [& endpoints] (when-let [[x d] (place-boss? endpoints)] ;; Hull the boss itself with a part of the final, straight wall ;; segment, to create a gusset of sorts, for added strength. (We ;; don't use the exact wall thickness, to avoid non-manifold ;; results.) (hull (intersection (binding [wall-thickness (- wall-thickness 0.005)] (apply wall-brace (comp (partial take-last 2) wall-sections) endpoints)) The height is calculated to yield a 45 deg gusset . (boss-place x 0 endpoints (cylinder screw-boss-radius (+ screw-boss-height (- (* 2 screw-boss-radius) (/ wall-thickness 2))) :center false))) (boss-place x d endpoints (cylinder screw-boss-radius screw-boss-height :center false))))) (defn countersink [r h t b] (let [r_1 (+ r (* h (Math/tan (/ cover-countersink-angle 2))))] (union (cylinder [r_1 r] h :center false) (when (pos? t) (translate [0 0 -1] (cylinder r (+ t 1) :center false))) (when (pos? b) (translate [0 0 (- b)] (cylinder r_1 b :center false)))))) (defn screw-countersink [& endpoints] (when-let [[x d] (place-boss? endpoints)] (let [r (/ cover-countersink-diameter 2) h cover-countersink-height] (boss-place x d endpoints (translate [0 0 (- h)] (countersink r h 50 50)))))) (defn screw-thread [& endpoints] (when-let [[x d] (place-boss? endpoints)] (let [[D P L] cover-fastener-thread] ;; Add another turn to the bottom of the thread, to ensure proper CSG results at the bottom face of the boss . (boss-place x d endpoints (translate [0 0 (- P)] (apply thread (update cover-fastener-thread 2 + P))))))) (defn case-test-cutout [& endpoints] (when-let [[x d] (place-boss? endpoints)] (let [[c t] (partition 3 3 case-test-volume)] (boss-place x d endpoints (translate (or t [0 0 0]) (apply cube c)))))) ;; Form a pie-shaped shard of the bottom cover, by hulling a section ;; of the lower part of the wall with a shape at some point towards ;; the center of the cover (affectionately called the "navel"). (def ^:dynamic cover-navel (-> (key-place :main, 3 1 0 0 0) vec (assoc 2 0) (translate (cube 1 1 cover-thickness :center false)))) (defn cover-shard [& endpoints] (->> (wall-sections endpoints) last (map (partial scale [1 1 (* cover-thickness 10)])) (cons cover-navel) hull)) ;;;;;;;;;;;;;;;;;;; ;; Tenting stand ;; ;;;;;;;;;;;;;;;;;;; ;; We form the stand as a rotational extrusion of a strip running ;; along the periphery of the bottom cover, but we scale each section ;; appropriately, so as to end up with a straight projection, or some ;; in-between shape, selectable via stand-shape-factor. The center of ;; rotation is chosen so that a specified minimum thickness is ;; maintained at the edge of the resulting wedge. (defn flattened-endpoints [& endpoints] (for [[where i j x y dx dy dz] endpoints] (assoc (vec (wall-place-b where i j x y dx dy dz)) 2 0))) (def stand-baseline-points (delay (let [points (case-placed-shapes flattened-endpoints) n (count points)] (->> points (cycle) (drop n) (take 60))))) (def stand-baseline-origin (delay (+ (->> @stand-baseline-points (apply concat) (map first) (apply max)) (/ wall-thickness 2)))) (defn stand-xform [θ shape] (let [t (+ @stand-baseline-origin (/ (last stand-minimum-thickness) (Math/sin stand-tenting-angle)))] (->> shape (translate [(- t) 0 0]) (rotate [0 θ 0]) (translate [t 0 0])))) (defn stand-section ([s kernel] (stand-section s [[0 0 0] [stand-width 0 0]] kernel)) ([s offsets kernel] (let [θ (* -1 s stand-tenting-angle) x_max @stand-baseline-origin] ;; Form the strip by displacing each point of the periphery along the mean of the normals of the two edges that share it . This ;; doesn't even result in a simple polygon for the inner periphery ;; of the strip, but it works well enough, as long as we're ;; careful when taking hulls. (for [[[a b] [_b c]] (partition 2 1 @stand-baseline-points) :let [_ (assert (= b _b)) u (map + (line-normal a b) (line-normal b c)) n (map (partial * (one-over-norm u)) u) t [(- (second n)) (first n)] Scale with 1 / cos θ , to get a straight projection . p (update b 0 #(+ (* (- 1 stand-shape-factor) %) (* stand-shape-factor (+ (* (- % x_max) (/ 1 (Math/cos θ))) x_max))))]] (stand-xform θ (for [u offsets :let [[c_n c_t c_b] u q (conj (mapv + p (map (partial * c_n) n) (map (partial * c_t) t)) c_b)]] (translate q kernel))))))) (def countersink-boss (delay (difference (countersink (- (/ cover-countersink-diameter 2) 1/4) cover-countersink-height 0 0) (translate [0 0 (+ 5 cover-countersink-height -1/2)] (cube 10 10 10))))) (defn stand-boss [& endpoints] (when-let [[x d] (place-boss? (set stand-boss-indexes) endpoints)] (boss-place x d endpoints @countersink-boss))) (defn stand-boss-cutout [& endpoints] (when-let [[x d] (place-boss? (set stand-boss-indexes) endpoints)] (boss-place x d endpoints (translate [0 0 -3/2] (countersink (/ cover-countersink-diameter 2) cover-countersink-height 50 20))))) ;;;;;;;;;;;; ;; Bridge ;; ;;;;;;;;;;;; Rebind these for brevity . (let [D_ext bridge-link-diameter [D D_add P] bridge-link-thread] (defn bridge-bearing [indexes] (let [[a b] (map #(conj % 0) (remove nil? (case-placed-shapes (fn [& endpoints] (when-let [[x d] (place-boss? (set indexes) endpoints)] (boss-place x d endpoints)))))) t cover-thickness ; Mount plate thickness ε 3/5 ; Chamfer length R 6 ; Fillet radius N (if draft? 10 20) ; The resolution of the arch extrusion. ;; Flip a vector to point the right way, regardless of the ;; relative poisition of a and b. y (fn [v] (update v 1 (if (> (second b) (second a)) - +))) R' (* (Math/sqrt 2) R) R'' (- R' R) ;; Points a and b are the mount hole locations. We go at 45 ° for a bit to c ( to bring the bearings closer ;; together), then straight up to c', then to b. δ (* -1/2 bridge-bearing-separation) c (mapv - a (y [δ δ 0])) c' (assoc c 0 (first b)) ;; The offset of the arch (with respect to a), needed to ;; get proper fillets. O (y [(- (first b) (first a) R') (- R'' ε δ D) 0]) ;; Points where additional needs to be placed and routed ;; out to create nice fillets. d (map + c' [0 (second O) 0] (y [(- R') (- δ D R'' ε) 0])) e (map + a (y [(+ (- (first b) (first a) R'') R) (+ (- (first b) (first a) R'') R) 0])) ;; A chamfered rectangular slice; the hulling kernel for ;; the arch. section (for [x [0 (+ ε ε)]] (cube 1/10 (+ D D ε ε x) (- t x))) ;; A pre-chamfered disk; the hulling kernel for the mount. chamfered-disk #(union (cylinder % t) (cylinder (+ % ε) (- t ε ε))) ;; The reverse of the above in a way; to cut out fillets. fillet-cutout (fn [r & parts] (->> (list* (translate p (cylinder (- r ε) h)) (->> (cylinder [(- r ε) (+ r ε)] (+ ε ε) :center false) (rotate [(* 1/2 π (dec s)) 0 0]) (translate (map + p [0 0 (* 1/2 s h)])) (for [s [-1 1]]))) ;; The above parts are not convex and need to be ;; hulled separately. (for [p parts :let [h (- t ε ε)]]) (apply map vector) (map hull))) ;; Transform into place along the arch. xform #(->> %2 (translate [0 0 bridge-arch-radius]) (rotate [0 (* -1 %1 stand-tenting-angle) 0]) (translate (map + [0 0 (- bridge-arch-radius)] O)) (translate a))] (translate [0 0 (- cover-thickness)] (difference (union (for [p [a b]] (translate p @countersink-boss)) (translate [0 0 (- 1 (/ t 2))] (let [h (- D t) D' (+ D ε ε) A bent plate mounted on the bottom cover on one ;; end and providing a bearing for the clevis on ;; the other. plate (union ;; Most of the plate. (->> (apply union (list* (when (zero? i) (translate [R'' 0 0] section)) (when (= i N) (->> (chamfered-disk (+ D ε)) (translate [(- D') 0 0]))) section)) (xform (/ i N)) ; Transform into place. (for [i (range (inc N))]) (partition 2 1) ; Take pairs and hull. (mapv hull) union) ;; Bottom cover mount parts. (difference (->> (chamfered-disk R) (translate p) (for [p [a c c' b]]) (partition 2 1) (mapv hull) ;; Some additional material, to be formed into ;; fillets below. (cons (->> (cube R' R' t) (translate c') (translate (y [(/ R' -2) (/ R' 2) 0])))) (cons (->> (cube R'' R'' t) (translate d) (translate (y [(/ R'' 2) (/ R'' 2) 0])))) (cons (->> (cube R' (* 3 R') t) (translate a) (translate (y [0 (* -2 R') 0])))) (apply union)) (apply fillet-cutout R (for [Δ [[-50 0 0] [0 0 0] [50 50 0]]] (map + c (y [(- R') R' 0]) (y Δ)))) (apply fillet-cutout R (for [Δ [[50 50 0] [0 0 0] [0 -50 0]]] (map + e (y [R' (- R') 0]) (y Δ)))) (fillet-cutout R'' d))) ;; The parts that make up the bearing, to be hulled separately. parts (let [ε_2 (/ ε 2)] [(translate [0 0 (- h ε_2)] (cylinder [D (+ D ε_2)] ε_2 :center false)) (translate [0 0 ε_2] (cylinder D (- h ε) :center false)) (cylinder [(- D ε_2) D] ε_2 :center false)])] (difference (->> (cond->> p ; Take each bearing part. Maybe extend along X. (translate [u 0 0]) (for [u [0 50]]) (apply hull))) true (#(->> % ; Transform into place. (translate [(- D') 0 (- (/ t -2) h)]) (xform 1))) intersect? (intersection plate)) ; Maybe intersect with the plate. (for [intersect? [true false]]) ; Bearing + intersection with plate (apply hull) ; Hull together to form ribs. (for [p parts]) ; For all parts. (apply union plate)) ;; Pin bore cutouts (->> (countersink (/ (+ D bridge-bore-expansion) 2) (* 1/8 D) 50 50) (rotate [(* π (dec u)) 0 0]) (translate [(- D') 0 (- (/ t 2) (* u D))]) (xform 1) (for [u [0 1]])))))) ;; Mount screw countersinks (for [p [a b]] (->> (countersink (/ cover-countersink-diameter 2) cover-countersink-height 50 50) (translate p) (translate [0 0 (- 1 t)]))))))) ;; A clevis fork/eye head, in the style of DIN 71751. Can have more ;; than one holes. The angle φ determines the distance from ;; base (or previous hole) to hole, in such a way that the maximum range of the joint is 180 ° + 2φ . In other words you can move it , up to φ degrees past the 90 ° mark . ;; +--+ +--+--------- ;; |//| |//| . ;; +--+ +--+--- . ;; | | | | . . ;; ---------| | | | D . ;; . . | | | | . . ;; . . +--+ +--+--- . ;; . . |//| |//| . . l_1 |//| |//| . ;; . . |//| |//| l_3 ;; . . |//| |//| . ;; l_2 -----+--+----------+--+ . ;; . |////////////////| . ;; . +--+//////////+--+----- . ;; . |//////////| . . . |//////////| . ;; . |//////////| . . ;; ------------+----------+------------ ;; |...D_ext..| (defn clevis [style φ & [n]] (let [ε 0.8 ; Chamfer legnth / fillet radius n' (or n 1) δ (* D (+ 1 (Math/tan φ))) δ' (* (dec n') (+ δ D)) l_1 (+ ε δ) l_4 (* 4/3 D) l_2 (+ l_4 (/ D 2) l_1) l_3 (+ l_2 D 1) l_3' (+ l_3 δ') l_34' (/ (- l_3' l_4) 2) ;; Mirrored countersinks to form the bore. bore #(->> (countersink (+ (/ (+ D bridge-bore-expansion) 2)) (* 1/8 D) 50 50) (rotate [(* π 1/2 (dec s)) 0 0]) (translate [0 0 (* % s D)]) (for [s [-1 1]]) (apply rotate [(/ π 2) 0 0]) (translate [0 0 l_2])) Corner rounding geometry rounding #(->> (sphere (/ l_3 2)) (scale [1.05 1.05 1]) (translate [0 0 (* s %)]) (for [s [-1/2 1/2]]))] (if (= style :eye) ;; A clevis eye rod end. (-> (cylinder (/ D_ext 2) l_3 :center false) ; The body Minus the edges and bore . (->> (sphere ε) (translate [(* u 50) (* v (+ 1 t) (+ (/ D 2) ε)) (- l_2 (* s (- l_1 ε)) (* t (+ (/ D 2) ε)))]) (for [s [-1 1] t [0 1] u [-1 1]]) (apply hull) (for [v [-1 1]])) (bore -1/2)) Corner rounding ;; A clevis fork rod end. (apply difference (->> (intersection (apply cube (map (partial * 2) [D D l_34'])) ; The body (->> (apply cube ; Edge chamfering (map #(- (* 2 % (Math/sqrt 2)) ε) [D D 100])) (rotate [0 0 (/ π 4)])) Corner rounding (apply intersection (rounding (- l_4 δ'))) (apply hull (rounding (- l_4 δ'))))) (translate [0 0 l_34']) (hull (cylinder (/ D_ext 2) 1 :center false)) (translate [0 0 l_4]) (union ; The neck (cylinder (/ D_ext 2) l_4 :center false))) ;; Slot (->> (sphere ε) (translate [(* u 50) (* t (- (/ D 2) ε)) (+ l_2 (- l_1) (* s 100) ε)]) (for [s [0 1] t [-1 1] u [-1 1]]) (apply hull)) ;; Bore(s) (for [i (range n')] (translate [0 0 (* i (+ δ D))] (bore -1))))))) (defn rod-end [style L & rest] (let [φ (degrees 45) ; Essentially the "overhang" angle. Chamfer legnth Journal length n 1 ; Neck length D_eff (+ D D_add) ;; h(d): height of a cone of base diameter d and opening angle 2φ . h (fn [d] (/ d 2 (Math/tan φ))) ): extended base diameter of a cone with a ( lateral ) gap of w relative to a cone of base diameter d. x (fn [d w] (+ d (/ w 1/2 (Math/cos φ)))) Gap Journal diameter D_2 (- D 1) ; Neck diameter Journal bottom Journal top L_2 (+ L_1' (+ (h (- (+ D_1 D_ext) (* 2 D_2))) n)) Create two versions of the joint geometry . One , suitably extended by g , will serve as a cut - out . [M F] (for [δ [0 g] :let [D' (x D_1 δ) D_ext' (x D_ext δ) r (/ D' 2)]] (union (->> (cylinder [0 r] (h D') :center false) ; Lower journal taper (translate [0 0 (- L_1 (h D'))])) Journal (translate [0 0 L_1])) (->> (cylinder [r 0] (h D') :center false) ; Upper journal taper (translate [0 0 L_1'])) (->> (cylinder (/ (x D_2 δ) 2) (- L_2 L_1') :center false) ; Neck (translate [0 0 L_1'])) (->> (cylinder [0 (/ D_ext' 2)] (h D_ext') :center false) (translate [0 0 (- L_2 (h D_ext'))]))))] (difference (if (= style :fixed) (->> (apply clevis rest) (translate [0 0 (- L 7)]) (union (cylinder (/ D_ext 2) L :center false)) (intersection (cylinder (mapv (partial + (/ D_ext 2) ε) [0 500]) 500 :center false))) (union (difference (union (let [H (- L_2 (/ g (Math/sin φ)) (h 2.4)) H_c (+ (/ D_ext 2) H ε)] ;; The rod, up to the joint, with some chamfering. (when (or true) (intersection (cylinder (/ D_ext 2) H :center false) (for [s [0 1]] (->> (cylinder [H_c 0] H_c :center false) (rotate [(* π s) 0 0]) (translate [0 0 (* H s)])))))) (->> (apply clevis rest) (translate [0 0 (- 4 (* 3/2 D))]) (intersection (->> (apply cube (repeat 3 (* 10 D))) (translate [0 0 (* 5 D)]))) (translate [0 0 L_2]))) F) ;; The joint geometry. (difference M Hollow out the center with a suitably expanded cone , to ;; ensure that the joint axis is fully supported by the ;; conical end of the threaded section below it. (->> (cylinder [(/ (x D_eff g) 2) 0] (h (x D_eff g)) :center false) (translate [0 0 L]))))) ;; The thread. We make sure the tip is perfectly conical past ;; the specified height, so that it doesn't intefere with the ;; bearing geometry. (let [H (h D_eff) H' (+ L H)] (->> (thread D_eff P (+ L H P)) (translate [0 0 (- P)]) (intersection (cylinder [(* D_eff 1/2 H' (/ 1 H)) 0] H' :center false)))) ;; Lead-in chamfer (cylinder [(+ (/ D_eff 2) 3/2) (- (/ D_eff 2) 3/2)] 3)))) (def bridge-cable-bracket (delay (let [ε 2/5 ε' (+ ε ε) D' (+ D D) w 3 φ (degrees 10) δ (* D (+ 2 (Math/tan φ))) y_0 (/ (+ (second bridge-bracket-size) w) 2) kernel (hull (cube w (+ 1/10 ε') (- D' ε')) (cube (- w ε') 1/10 D')) loop (->> kernel (translate (apply #(vector (/ (+ %1 w) 2) (/ (- %2 1) 2 s) 0) (if (even? t) bridge-bracket-size (rseq bridge-bracket-size)))) (rotate [0 0 (* 1/2 t π)]) (for [t (range 4) s [-1 1]]) cycle)] (-> (->> loop (partition 2 1) (take 8) (map (partial apply hull)) (apply union)) (union (->> (union (cylinder (- D ε) w) (cylinder D (- w ε ε))) (rotate [(/ π 2) 0 0]) (translate [0 y_0 (* s δ)]) (for [s [0 2]]) hull)) (union (->> kernel (rotate [0 0 (/ π 2)]) (translate [(* s (- D t -2 ε ε)) y_0 t]) (for [s [-1 1] t [0 2]]) hull)) (difference (->> (countersink (/ (+ D bridge-bore-expansion) 2) (/ D 16) 50 50) (rotate [(/ π s 2) 0 0]) (translate [0 (+ y_0 (* 1/2 s w)) (* t δ)]) (for [s [-1 1] t [1 2]])))))))) ;;;;;;;;;;;;;;;;;;;; ;; Final assembly ;; ;;;;;;;;;;;;;;;;;;;; (defn assembly [side & parts] ;; Take either the union or the difference of the keycaps with the ;; rest of the model. (let [left? (= side :left) place-part? (set parts) build-thumb-section? (or thumb-test-build? (not key-test-build?)) difference-or-union (if interference-test-build? difference union) maybe-cut-out (if case-test-build? (partial intersection (apply hull (case-placed-shapes case-test-cutout))) identity) pcb-place-properly (partial pcb-place left?)] (mirror [(if left? 1 0) 0 0] (maybe-cut-out (difference-or-union (apply union (concat (when place-keyswitches? (concat (key-placed-shapes keyswitch) (when build-thumb-section? (thumb-placed-shapes keyswitch)))) (when place-keycaps? (concat (key-placed-shapes keycap) (when build-thumb-section? (thumb-placed-shapes keycap)))))) (when (place-part? :top) (apply (if case-color (partial color case-color) union) (concat ;; Main section @connectors (key-placed-shapes key-plate) ;; Thumb section (when build-thumb-section? (concat @thumb-connectors (thumb-placed-shapes key-plate))) ;; Case walls (when-not (or thumb-test-build? key-test-build?) (list* (apply difference (apply union (case-placed-shapes screw-boss)) (case-placed-shapes screw-thread)) (case-placed-shapes (partial wall-brace wall-sections))))))) (when (place-part? :bottom) (intersection (when case-test-build? (hull (case-placed-shapes case-test-cutout))) (let [δ 1/2] ;; Start with the bottom plate, formed by pie-like pieces ;; projected from a central point and remove slightly inflated ;; versions of the walls and screw bosses. (difference (union (translate [0 0 (- 1 cover-thickness)] (case-placed-shapes cover-shard)) (pcb-place-properly pcb-bosses)) (pcb-place-properly pcb-connector-cutout) (pcb-place-properly @pcb-button-hole-cutout) (binding [wall-thickness (+ wall-thickness δ) screw-boss-radius (+ screw-boss-radius (/ δ 2)) cover-navel nil] (doall (concat (case-placed-shapes cover-shard) (case-placed-shapes screw-boss)))) (translate [0 0 (- cover-countersink-height cover-thickness -1)] (case-placed-shapes screw-countersink)))))) (when place-pcb? (union (pcb-place-properly pcb) (pcb-place-properly (translate [0 (/ (second pcb-size) 2) 0] pcb-harness-bracket)))) (when (or (place-part? :stand) (place-part? :boot)) (let [n (Math/ceil (/ stand-tenting-angle π (if draft? 2/180 1/180))) ;; Extrude the stand section polygon rotationally ;; through stand-tenting-angle, forming a "column" ;; of each section edge. columns (apply map vector (for [i (range (inc n))] (partition 2 1 (stand-section (/ i n) (translate [0 0 -1/20] (cylinder (/ wall-thickness 2) 1/10)))))) ;; Split it into the parts that will be cut out and the ;; part that will be left whole. [part-a rest] (split-at (first stand-split-points) columns) [part-b part-c] (split-at (- (second stand-split-points) (first stand-split-points)) rest) ;; Optionally shorten the upper and/or lower portion of ;; the to be cut out parts and hull. shorten (fn [part & limits] [(map-indexed #(if (>= %1 (first limits)) (drop (quot n 2) %2) []) part) (map-indexed #(if (>= %1 (second limits)) (take (quot n 2) %2) []) part)]) hulled-parts (for [part (concat [part-b] (apply shorten part-a (take 2 stand-arm-lengths)) (apply shorten (reverse part-c) (drop 2 stand-arm-lengths)))] (for [column part [[a b] [c d]] (partition 2 1 column)] (union (hull a b c) (hull b c d))))] (translate [0 0 (- 1 cover-thickness)] (when (place-part? :stand) ;; Assemble the parts of the stand, cut out the arms, ;; then subtract the countersinks from the upper parts ;; only. (let [parts (list* (case-placed-shapes stand-boss) (first hulled-parts) (for [i [1 3 0 2] :let [q (quot i 2) r (rem i 2) qq (- 1 q q) rr (- 1 r r) [take-this take-that] (cond->> [take take-last] (pos? q) reverse)]] (difference (apply union (nth hulled-parts (inc i))) (->> (sphere 1/2) (translate [0 0 (* rr (+ 1/2 (stand-minimum-thickness r)))]) (stand-section (- 1 r) (for [n [-100 100] [t z] [[(/ wall-thickness -2) 0] [100 (* (Math/tan stand-arm-slope) 100)]] z_add [0 100]] [n (* qq t) (* rr (+ z z_add))])) (take-this (inc (stand-arm-lengths i))) (take-that 1) (apply hull))))) [upper-parts lower-parts] (split-at 4 parts)] (apply union (difference (apply union upper-parts) (case-placed-shapes stand-boss-cutout)) lower-parts))) (when (place-part? :boot) (difference Take the difference of lower 10 ° or so of the ;; extruded arm, with the hulling kernel inflated or ;; deflated, so as to arrive at a shell of width (apply ;; min boot-wall-thickness). Also extend the height of ;; the kernel by boot-bottom-thickness at the bottom ;; section, to form the boot floor. (apply difference (for [δ boot-wall-thickness :let [n (Math/ceil (/ stand-tenting-angle π 1/180)) columns (->> (cylinder (+ (/ wall-thickness 2) δ) h) (translate [0 0 (/ h -2)]) (stand-section (/ (- n i) n)) (drop (stand-arm-lengths 0)) (drop-last (stand-arm-lengths 2)) (partition 2 1) (for [i ((if draft? identity (partial apply range)) [0 (if (pos? δ) (quot n 2) n)]) :let [h (if (and (zero? i) (pos? δ)) boot-bottom-thickness 1/10)]]) (apply map vector))]] (union (for [column columns [[a b] [c d]] (partition 2 1 column)] (union (hull a b c) (hull b c d)))))) (->> (cube 1000 1000 1000) (translate [0 0 (+ 500 1/10 boot-wall-height)]) (stand-xform (- stand-tenting-angle))) (case-placed-shapes stand-boss-cutout)))))) (when (place-part? :bridge) ;; Bridge mount (->> bridge-boss-indexes (partition 2 1) (map bridge-bearing) (apply union)))))))) (def prototype (delay)) (defn -main [& args] ;; Process switch arguments and interpret the rest as parts to ;; build. (let [parts (doall (filter (fn [arg] (let [groups (re-find #"--(no-)?(.*?)(=.*)?$" arg)] (if-let [[_ no k v] groups] (if-let [p (find-var (symbol "lagrange-keyboard.core" (cond-> k (not v) (str \?))))] (and (alter-var-root p (constantly (cond v (eval (read-string (subs v 1))) no false :else true))) false) (println (format "No parameter `%s'; ignoring `%s'." k arg))) true))) args)) xform #(->> %1 (translate [0 0 (- cover-thickness)]) (rotate [0 (%2 stand-tenting-angle) 0]) (translate [(- (%2 @stand-baseline-origin)) 0 0]))] (alter-var-root #'scad-clj.model/*fa* (constantly (if draft? 12 3))) (alter-var-root #'scad-clj.model/*fs* (constantly (if draft? 2 2/10))) (doseq [part parts] (case part "right" (spit "things/right.scad" (write-scad (assembly :right :top))) "right-cover" (spit "things/right-cover.scad" (write-scad (assembly :right :bottom))) "right-stand" (spit "things/right-stand.scad" (write-scad (xform (assembly :right :stand) +))) "right-boot" (spit "things/right-boot.scad" (write-scad (xform (assembly :right :boot) +))) "right-subassembly" (spit "things/right-subassembly.scad" (write-scad (assembly :right :top :bottom))) "right-assembly" (spit "things/right-assembly.scad" (write-scad (xform (assembly :right :top :bottom :stand) +))) "left" (spit "things/left.scad" (write-scad (assembly :left :top))) "left-cover" (spit "things/left-cover.scad" (write-scad (assembly :left :bottom))) "left-stand" (spit "things/left-stand.scad" (write-scad (xform (assembly :left :stand) -))) "left-boot" (spit "things/left-boot.scad" (write-scad (xform (assembly :left :boot) -))) "left-subassembly" (spit "things/left-subassembly.scad" (write-scad (assembly :left :top :bottom))) "left-assembly" (spit "things/left-assembly.scad" (write-scad (xform (assembly :left :top :bottom :stand) -))) ;; For other mixes of parts that may be useful during development, but not ;; provided by the above. "custom-assembly" (spit "things/custom-assembly.scad" (write-scad (assembly :right :bottom :stand))) ;; For arbitrary experimentation. "prototype" (spit "things/prototype.scad" (write-scad @prototype)) (cond ;; Bridge (clojure.string/starts-with? part "bridge/") (let [subpart (subs part 7) scad (case subpart "bracket" @bridge-cable-bracket "left-mount" (assembly :left :bridge) "right-mount" (assembly :right :bridge) "toe-fork" (let [[x l φ] bridge-toe-fork] (rod-end x l, :fork φ)) "toe-eye" (let [[x l φ] bridge-toe-eye] (rod-end :fixed l, :eye φ)) "separation-fork" (let [[x l φ] bridge-separation-fork] (rod-end x l, :fork φ 2)) (println (format "No part `%s'." subpart)))] (when scad (spit "things/bridge.scad" (write-scad scad)))) ;; Miscellaneous parts (mostly keycaps). (clojure.string/starts-with? part "misc/") (let [ subpart (subs part 5) scad (case subpart ;; This is used as a convenient location to tie ;; the harness, in order to provide strain relief ;; for the wiring exiting the PCB. "bracket" pcb-harness-bracket ;; Printable keycaps. "oem-1u-recessed" (apply printable-keycap [1 1] keycap-family-oem-recessed) "oem-1u" (apply printable-keycap [1 1] keycap-family-oem-flush) "oem-1.5u" (apply printable-keycap [3/2 1] keycap-family-oem-flush) "oem-1.5u-recessed" (apply printable-keycap [3/2 1] keycap-family-oem-recessed) "dsa-1u-convex" (apply printable-keycap [1 1] keycap-family-dsa-convex) "dsa-1u-concave" (apply printable-keycap [1 1] keycap-family-dsa-concave) "dsa-1.25u-convex" (apply printable-keycap [1 5/4] keycap-family-dsa-convex) "dsa-1.5u-convex" (apply printable-keycap [1 3/2] keycap-family-dsa-convex) "dsa-1.5u-convex-homing" (apply printable-keycap [1 3/2] :homing-bar-height 1/4 keycap-family-dsa-convex) "sa-1.5u-concave" (apply printable-keycap [3/2 1] keycap-family-sa-concave) "sa-1.5u-saddle" (apply printable-keycap [3/2 1] keycap-family-sa-saddle) "dsa-1u-fanged" (apply printable-keycap [0.95 1] keycap-family-dsa-fanged) (println (format "No part `%s'." subpart)))] (when scad (spit "things/misc.scad" (write-scad scad)))) :else (println (format "No part `%s'." part)))))))
null
https://raw.githubusercontent.com/dpapavas/lagrange-keyboard/1eacbe7962e6a221bbb8072e9869c23df4c41580/src/lagrange_keyboard/core.clj
clojure
This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. along with this program. If not, see </>. General parameters. Main section parameters. successive columns. Column and row rotations in units of keys. The key scale of the outer columns. Key plate (i.e. switch mount) parameters. Units of mm. Place nubs at the switch mount hole edges, meant to engage the tabs on the switches. Which side to place a nub on. Try even?, odd?, or identity. How much the nub sticks out into the hole. The thickness of the edge of the nub that engages the switch. Thumb section parameters. The degree of downward slant. The scale of the top-inner key of the thumb cluster. Per-key phase along the baseline arc, in units of keys, as a pair of numbers: initial phase and per-key phase increment. Per-key vertical slope. Height offset for the whole keyboard. Case-related parameters. Should probably be a multiple of nozzle/line size, if printed with walls only. Screw bosses pair of parameters. The key coordinates are ultimately passed to key-place; see comments there for their meaning. The boss is placed default it's placed halfway between the given points and inset just enough to clear the outer wall, but this can be tuned via the optional parameters. Right side Top side Left side Bottom cover parameters. Inner diameter of countersunk hole. Head height. Head angle. Stand parameters. The stand is essentially formed by a rotational extrusion of the bottom cover polygon. To save on material, the inner portion is removed, leaving a strip along the outside, parts of which (the inner, taller tented sections) are also removed in turn, leaving arm-like protrusions which are enough to stabilize the keyboard. These arms can optionally be shortened to save on desktop real estate, although this should be avoided, unless a bridge is installed. The angle of extrusion. The width of the strip forming the stand cross-section. Thickness at inner bottom, inner top and outer bottom. The screw bosses shared by the stand. The locations where the arms begin. Hom much to shorten the arms. Stand boot parameters. The wall thickness is given as a pair of offsets from the stand account for material removed from the stand during sanding, printing tolerances, etc. The height of the sidewalls. The thickness of the boot floor. Bridge parameters. The mating boss indexes for the mount link. How much to expand the diameter of bearing and link bores. Shortens the separation of the bridge bearings. The thread diameter of the bridge links also determines the nominal diameter, on which the rod end geometry is based, while the nominal, to adjust the thread fit (loose or tight), while keeping pitch. Outer diameter of the linkage bars. Link rod end specification as (type, thread length, range). The type can be :fixed or :rotating. The latter type allows adjustment in place, but backlash in the rotational joint makes the linkage be annoying. The range adjusts the spacing of the pin holes and before interference with the mating part prohibits further motion. Cable bracket aperture size. Controller PCB parameters. PCB mount location. Printable keycap parameters. An OEM-like keycap, at least functionally (meaning cylindrical top of typical OEM radius and height Route out a keycap legend on the top of the keycap. Must be set to Define some utility functions. Derive some utility variables and set global settings. keycap-family color Scale normalized plate coordinates (i.e. in [-1 1]) to world space. We stretch recessed (w.r.t their neighbors) columns in the main section, as well as certain keys in the thumb section, to allow more room for keycaps. Match the *fs* setting, which is, by definition: Vertices Make the top of the thread conical, to ensure no support is needed above it (for female threads). Indices ; The radius and position of the board screw hole, measured from the corner of the board. The size and position of the connectors, measured from the upper-left corner of the board to the upper-left corner of the connector. Main cutout Chamfer cutout Make the boss a little higher than the thread (here bottom of the boss and a better attachment to the base. The PCB. The basic PCB... minus the mount holes... minus the center cutout. The USB/6P6C connectors. The USB cable The plug The housing The strain relief The cable The board-to-wire connectors. Keys ;; Enlarge the hole below the nubs, to provide some space for the tabs on the switch to extend into. The depth of the keyswitch below the top of the plate. Extend the hole by this much on each side. Main body Bottom-right fillet cutout Top cutout Board contacts Casing, below the plate. Center locating pin. Casing, above the plate. Stem Electrical terminals. A basic keycap shape. Cylindrical sides, spherical top, rounded Additionally supports a couple more exotic shapes. Where: h is the height of keycap (at top center), ρ is the shared radius of sides, top and corner rounding, φ determines how deeply to round the corners. h_1 is height at center of each crest side of the key. O is the center of a circle of the given radius passing through them. This will be used to form the sides. We need to set *fn* explicitly, since extrude-rotate below doesn't seem to respect the *fa*/*fs* settings. Initial block. Extend the side circularly. Errors from the previous intersection can extend the shape to span the Y axis, so we clip it. Cylindrical sides. Plus or minus the top. Spherical top (rotated to avoid poles). Rounded corner. Additional (wrt profile) height. Height of vertical part of base. switches, and assuming stem flush with keycap bottom), see: The shell The stem The legend Set up bindings that either generate SCAD code to place a part, or calculate its position. Either place a shape at [x y z] in the local frame of key [i j] in section where (either :thumb or :key), or calculate and return the coordinates of a point relative to that location. For convenience, the scale of the local frame depends on the key size in question, opposed to the center as is the case for x and y, to ensure that the key geometry doesn't change with plate thickness). Place on/at a main section key. The key plates are spread out along the surface of a torus where l and r the respective edge length and radius. Same as above, but for the thumb section. Connecting tissue ;; These are small shapes, placed at the edges of the key plates. Hulling kernels placed on neighboring key plates yields connectors between the plates, which preserve the plate's chamfer and are of consistent width. (We make the kernels "infinitesimally" larger than the key plates, to avoid non-manifold results). Odds and ends, which aren't regular enough to handle in a loop. Palm key connectors. Regular connectors. Row connections column. It's taken care of by the thumb connectors. Column connections Case ;; Back wall Right wall Thumb walls Left wall. Stripping in reverse order is necessary for consistent winding, which boss placement relies on. They curve of the back side is specified via a set of points degenerate segments (where the parts are colinear, instead of forming a triangle, for instance because shape-a and shape-b above coincide), to avoid wasting cycles to generate non-manifold results. Decide when to place a screw boss in a segment and what parameters to use. Note that we also use this to create a cutout for case test builds. segment , displaced d radii inwards along the normal direction. Hull the boss itself with a part of the final, straight wall segment, to create a gusset of sorts, for added strength. (We don't use the exact wall thickness, to avoid non-manifold results.) Add another turn to the bottom of the thread, to ensure Form a pie-shaped shard of the bottom cover, by hulling a section of the lower part of the wall with a shape at some point towards the center of the cover (affectionately called the "navel"). Tenting stand ;; We form the stand as a rotational extrusion of a strip running along the periphery of the bottom cover, but we scale each section appropriately, so as to end up with a straight projection, or some in-between shape, selectable via stand-shape-factor. The center of rotation is chosen so that a specified minimum thickness is maintained at the edge of the resulting wedge. Form the strip by displacing each point of the periphery along doesn't even result in a simple polygon for the inner periphery of the strip, but it works well enough, as long as we're careful when taking hulls. Bridge ;; Mount plate thickness Chamfer length Fillet radius The resolution of the arch extrusion. Flip a vector to point the right way, regardless of the relative poisition of a and b. Points a and b are the mount hole locations. We go at together), then straight up to c', then to b. The offset of the arch (with respect to a), needed to get proper fillets. Points where additional needs to be placed and routed out to create nice fillets. A chamfered rectangular slice; the hulling kernel for the arch. A pre-chamfered disk; the hulling kernel for the mount. The reverse of the above in a way; to cut out fillets. The above parts are not convex and need to be hulled separately. Transform into place along the arch. end and providing a bearing for the clevis on the other. Most of the plate. Transform into place. Take pairs and hull. Bottom cover mount parts. Some additional material, to be formed into fillets below. The parts that make up the bearing, to be hulled separately. Take each bearing part. Transform into place. Maybe intersect with the plate. Bearing + intersection with plate Hull together to form ribs. For all parts. Pin bore cutouts Mount screw countersinks A clevis fork/eye head, in the style of DIN 71751. Can have more than one holes. The angle φ determines the distance from base (or previous hole) to hole, in such a way that the maximum +--+ +--+--------- |//| |//| . +--+ +--+--- . | | | | . . ---------| | | | D . . . | | | | . . . . +--+ +--+--- . . . |//| |//| . . . |//| |//| l_3 . . |//| |//| . l_2 -----+--+----------+--+ . . |////////////////| . . +--+//////////+--+----- . . |//////////| . . . |//////////| . . ------------+----------+------------ |...D_ext..| Chamfer legnth / fillet radius Mirrored countersinks to form the bore. A clevis eye rod end. The body A clevis fork rod end. The body Edge chamfering The neck Slot Bore(s) Essentially the "overhang" angle. Neck length h(d): height of a cone of base diameter d and opening Neck diameter Lower journal taper Upper journal taper Neck The rod, up to the joint, with some chamfering. The joint geometry. ensure that the joint axis is fully supported by the conical end of the threaded section below it. The thread. We make sure the tip is perfectly conical past the specified height, so that it doesn't intefere with the bearing geometry. Lead-in chamfer Final assembly ;; Take either the union or the difference of the keycaps with the rest of the model. Main section Thumb section Case walls Start with the bottom plate, formed by pie-like pieces projected from a central point and remove slightly inflated versions of the walls and screw bosses. Extrude the stand section polygon rotationally through stand-tenting-angle, forming a "column" of each section edge. Split it into the parts that will be cut out and the part that will be left whole. Optionally shorten the upper and/or lower portion of the to be cut out parts and hull. Assemble the parts of the stand, cut out the arms, then subtract the countersinks from the upper parts only. extruded arm, with the hulling kernel inflated or deflated, so as to arrive at a shell of width (apply min boot-wall-thickness). Also extend the height of the kernel by boot-bottom-thickness at the bottom section, to form the boot floor. Bridge mount Process switch arguments and interpret the rest as parts to build. For other mixes of parts that may be useful during development, but not provided by the above. For arbitrary experimentation. Bridge Miscellaneous parts (mostly keycaps). This is used as a convenient location to tie the harness, in order to provide strain relief for the wiring exiting the PCB. Printable keycaps.
-*- coding : utf-8 -*- Copyright 2020 it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU Affero General Public License (ns lagrange-keyboard.core (:gen-class) (:refer-clojure :exclude [use import]) (:require [clojure.pprint :refer [pprint]] [clojure.string :refer [starts-with?]] [scad-clj.scad :refer :all] [scad-clj.model :refer :all])) (def π Math/PI) (defn degrees [& θ] (let [f (partial * π 1/180)] (if (> (count θ) 1) (mapv f θ) (f (first θ))))) (def place-keycaps? false) (def keys-depressed? false) (def place-keyswitches? false) (def place-pcb? false) (def draft? true) (def mock-threads? true) (def case-test-build? false) (def case-test-locations [0]) (def case-test-volume [50 50 150, 0 0 0]) (def case-color [0.70588 0.69804 0.67059]) (def interference-test-build? false) (def thumb-test-build? false) (def key-test-build? false) (def key-test-range [1 2, 4 4]) (def row-count 5) (def column-count 6) The radius , in , for each column , or for each row . (def row-radius 235) (def column-radius #(case % (0 1) 65 2 69 3 66 55)) The spacing between rows , in , for each column and between (def row-spacing #(case % (0 1) 7/2 2 13/4 3 13/4 9/2)) (def column-spacing #(case % 0 2 1 0 2 9/2 3 5 3)) (def row-phase (constantly -8)) (def column-phase (fn [i] (+ -57/25 (cond (= i 2) -1/4 (= i 3) -1/8 (> i 3) -1/4 :else 0)))) Column offsets , in , in the Y and Z axes . (def column-offset #(case % (0 1) 0 2 8 3 0 -14)) (def column-height #(case % (0 1) 0 2 -5 3 0 7)) (def last-column-scale 3/2) Palm key location tuning offsets , in mm . (def palm-key-offset [0 -1 -3]) This is essentially 1u in mm . (def plate-size keycap-length) (def plate-hole-size 14) Tuning offsets for the whole thumb section , in mm . (def thumb-radius 68) (defn thumb-key-phase [column row] (case row (1 2) (degrees -37/2 111/2) (degrees (if (zero? column) 12 10) 55/2))) Per - key offset from the baseline arc , in . (defn thumb-key-offset [column row] (case row 1 [0 -20 -8] 2 [0 -42 -16] (case column 0 [0 (* keycap-length 1/2 (- 3/2 thumb-key-scale)) 0] 3 [0 -4 0] [0 0 0]))) (defn thumb-key-slope [column row] (case row 1 (degrees 33) 2 (degrees 6) 0)) (def global-z-offset 0) Each boss is a sequence of two key coordinates and , optionally , a at a point on the sidewall , between the two key locations . By [:key, 5 3, 1 1] [5/8 1]] [[:key, 5 0, 1 1] [:key, 5 0, 1 -1]] [:key, 4 0, 1/2 1]] [[:key, 2 0, 0 1] [:key, 2 0, 1/2 1]] [[:key, 0 0, 0 1] [:key, 0 0, -1/2 1]] [:key, 0 2, -1 1]] [[:key, 0 3, -1 -1] [:thumb, 1 0, -1 1]] Front side [:thumb, 2 1, -1 -1]] [[:thumb, 0 1, 1 1] [:thumb, 0 1, 1 -1]] [[:key, 4 3, 0 -1] [:key, 4 3, -1 -1]]]) (def ^:dynamic screw-boss-radius 11/2) (def screw-boss-height 8) (def cover-thickness 4) Cover mount thread diameter , pitch and length in . 0 is radial extrusion , 1 is projection . (def stand-arm-slope (degrees 13)) walls . The total wall thickness is thus the difference of the two and the second number can be used to inset the inner boot wall , to (def boot-wall-thickness [11/20 -5/20]) (def bridge-arch-radius 6) geometry of the rod ends . The first value below determines the second value allows increasing the actual thread diameter above the the rest of the geometry constant . The third value is the thread (def bridge-link-thread [6 1/2 1]) less rigid , allowing some motion between the two halves , which can with it the approximate range of rotation ( past the 90 ° point ) (def bridge-separation-fork [:fixed 55 (degrees 10)]) (def bridge-toe-fork [:fixed 17 (degrees 10)]) (def bridge-toe-eye [:fixed 7 (degrees 20)]) PCB mount thread diameter , pitch and length in . (def keycap-family-common [:fn-value (if draft? nil 500) shell width [ base top ] Mount cross arm length Mount cross arm width Mount stem radius SA family row 3 keycap . See : (def keycap-family-sa (into keycap-family-common [:height (* 0.462 25.4) :radius 33.35])) (def keycap-family-sa-concave (into keycap-family-sa [:top :spherical-concave :corner-rounding 0.179])) (def keycap-family-sa-saddle (into keycap-family-sa [:top :saddle :corner-rounding 0.145 :extra-height 3/2 :saddle-aspect 2 :saddle-skew [-6/10 -8/10]])) DSA family keycap . See : (def keycap-family-dsa (into keycap-family-common [:height (* 0.291 25.4) :extra-height 1/2 :base-height 1 :radius 36.5 :mount-recess 6/5])) (def keycap-family-dsa-concave (into keycap-family-dsa [:top :spherical-concave :corner-rounding 0.446])) (def keycap-family-dsa-convex (into keycap-family-dsa [:top :spherical-convex :corner-rounding 0.536])) (def keycap-family-dsa-fanged (into keycap-family-dsa-convex [:mount-offset [-0.025 0] :fang-corner-rounding 0.61 :fang-skew 3/2 :fang-angle (degrees 54)])) somewhere between OEM R3 and R4 ) (def keycap-family-oem (into keycap-family-common [:top :cylindrical :height 15/2 :radius 26 :thickness [6/5 9/5]])) (def keycap-family-oem-flush (into keycap-family-oem [:corner-rounding 0.343])) (def keycap-family-oem-recessed (into keycap-family-oem [:corner-rounding 0.2 :mount-recess 5/2 :extra-height 5/2])) a [ character font - family font - size ] triplet . The official Lagrange logo keycap was created with [ " \\U01D4DB " " Latin Modern Math " 11 ] . (def keycap-legend nil) (defn one-over-norm [v] (Math/pow (reduce + (map * v v)) -1/2)) (defn line-normal [a b] (let [[x y] (map - a b)] [(- y) x])) (def columns (lazy-seq (apply range (cond (or thumb-test-build? key-test-build?) [(max 0 (key-test-range 0)) (min column-count (inc (key-test-range 2)))] :else [0 column-count])))) (def rows (lazy-seq (apply range (cond (or thumb-test-build? key-test-build?) [(max 0 (key-test-range 1)) (min row-count (inc (key-test-range 3)))] :else [0 row-count])))) (defn row [i] (if (neg? i) (+ row-count i) i)) (defn column [i] (if (neg? i) (+ column-count i) i)) (defn place-key-at? [[i j]] (and ((set columns) i) ((set rows) j) (or (#{2 3 (column -1)} i) (< j (row -1))))) (defn key-scale-at [where, i j] (if (= where :thumb) [1 (case [i j] [0 0] thumb-key-scale ([1 0] [2 0]) 3/2 1)] [(if (= i (column -1)) last-column-scale 1) 1])) (defn key-options-at [where, i j] (let [WAN [0.90980 0.90588 0.89020] VAT [0.57647 0.76078 0.27843] GQC [0.63137 0.61569 0.56863] GAH [0.50588 0.50588 0.49412] BFV [0.36471 0.80392 0.89020] BBJ [0.00000 0.56078 0.69020] BBQ [0.00000 0.65098 0.70588] BO [0.00000 0.29804 0.49804] RBD [0.82745 0.09804 0.16078] RAR [0.79608 0.18431 0.16471]] (= [where, i j] [:thumb 0 1]) keycap-family-dsa-fanged (= [where, j] [:thumb, 0]) keycap-family-dsa-convex (= where :thumb) keycap-family-dsa-concave (= [where, i j] [:main, (column -1) (row -1)]) keycap-family-sa-saddle :else keycap-family-oem-flush) (case j 0 WAN WAN) (cond (= [i j] [(column -1) (row -1)]) RAR (= i 5) GQC :else WAN))])) (defn scale-to-key [where, i j, x y z] (let [stretch (if (not= where :thumb) (cond (or (and (= i 2) (not= j (row -1))) (and (= i 3) (pos? x))) [6/5 1 1] :else [1 1 1]) (cond (and (= [i j] [0 0]) (neg? x) (pos? y)) [1 1.1 1] (and (= [i j] [1 0]) (pos? y)) [1 1.02 1] (and (= [i j] [3 0]) (neg? y)) [1 17/16 1] :else [1 1 1]))] (map * [x y z] stretch (conj (mapv (partial * 1/2) (key-scale-at where, i j)) 1/2) [plate-size plate-size plate-thickness]))) (defn thread [D_maj P L & [L_extra]] (if (or draft? mock-threads?) (let [r (/ D_maj 2)] (union (cylinder r L :center false) (translate [0 0 L] (cylinder [r 0] (or L_extra r) :center false)))) * fs * = δθ * r = δθ * D_Maj / 2 = π * D_Maj / ( 2 * a ) Therefore : a = π * D_Maj / ( 2 * * fs * ) (let [a (int (/ (* π D_maj) 2 scad-clj.model/*fs*)) δθ (/ π a) N (int (/ (* 2 a L) P)) H (* 1/2 (Math/sqrt 3) P) D_min (- D_maj (* 10/8 H))] (polyhedron (concat [[0 0 0]] (apply concat (for [i (range N) :let [r (+ D_maj (/ H 4)) [x_1 x_2] (map (partial * 1/2 (Math/cos (* i δθ))) [D_min r]) [y_1 y_2] (map (partial * 1/2 (Math/sin (* i δθ))) [D_min r]) z #(* (+ % (/ (* i δθ) 2 π)) P)]] [[x_1 y_1 (z -1/2)] [x_1 y_1 (z -3/8)] [x_2 y_2 (z 0)] [x_1 y_1 (z 3/8)] [x_1 y_1 (z 1/2)]])) [[0 0 (+ L (or L_extra (/ D_maj 2)))]]) (concat [(conj (range 5 0 -1) 5 0)] (for [i (range (* 2 a))] [0 (inc (* i 5)) (inc (* (inc i) 5))]) (for [i (range (dec N)) j (range 4)] (map (partial + 1 (* i 5)) [j (inc j) (+ 6 j) (+ 5 j)])) (for [i (range (* 2 a))] (map (partial - (* 5 N)) [-1 (* i 5) (* (inc i) 5)])) [(map (partial - (* 5 N)) (conj (range 4 -1 -1) -1 0))]))))) (def pcb-size [30 65]) (def pcb-thickness 1.6) (def pcb-mount-hole [3/2 4 4]) (def pcb-button-position [4.6 52.7]) (def pcb-button-diameter 2.5) (def pcb-6p6c-size [16.64 13.59 16.51]) (def pcb-6p6c-position [2.9 17.4]) (def pcb-usb-size [11.46 12.03 15.62]) (def pcb-usb-position [7.8 2.2]) (defn pcb-place [flip? shape] (cond->> shape flip? (translate (map * [0 -1] pcb-size)) (not flip?) (mirror [0 1 0]) true (rotate [0 π 0]) true (translate pcb-position))) (def pcb-button-hole-cutout (delay (->> (cylinder (/ pcb-button-diameter 2) 50) (translate pcb-button-position)))) (def pcb-connector-cutout (apply union (for [[size position] [[pcb-usb-size pcb-usb-position] [pcb-6p6c-size pcb-6p6c-position]] :let [δ 0.8 [a b c] (map + [δ δ 0] size) [x y] (map (partial + (/ δ -2)) position)]] (union (->> (cube a b c :center false) (translate [x y pcb-thickness])) (->> (square a b) (extrude-linear {:height 1/2 :scale [(+ 1 (/ 1 a)) (+ 1 (/ 1 b))] :center false}) (union (translate [0 0 (+ 50/2 1/2)] (cube (+ a 1) (+ b 1) 50))) (translate [(+ x (/ a 2)) (+ y (/ b 2)) (+ (last pcb-position) cover-thickness -3/2)])))))) (def pcb-bosses (for [s [-1 1] t [-1 1] :let [[w h] pcb-size [_ δx δy] pcb-mount-hole [D P L] pcb-fastener-thread d 6.8 0.8 mm ) to allow for a couple of solid layers at the h_b (+ L (/ D 2) 4/5) z (partial + (last pcb-position))]] (->> (difference (->> (cube d d h_b) (intersection (cylinder 4 h_b)) (translate [0 0 (z (/ h_b -2))])) (->> (apply thread (update pcb-fastener-thread 2 + P)) (translate [0 0 (z (- (+ h_b P)))]))) (translate [(- (* 1/2 (inc s) w) (* s δx)) (- (* 1/2 (inc t) h) (* t δy)) 0])))) (def pcb (let [corner-radius 4] (with-fs 1/2 (color [0 0.55 0.29] (difference (hull (for [s [-1 1] t [-1 1] :let [[w h] pcb-size]] (->> (cylinder corner-radius pcb-thickness) (translate [(- (* 1/2 (inc s) w) (* s corner-radius)) (- (* 1/2 (inc t) h) (* t corner-radius)) (/ pcb-thickness 2)])))) (for [s [-1 1] t [-1 1] :let [[w h] pcb-size [r δx δy] pcb-mount-hole]] (->> (cylinder r (* 3 pcb-thickness)) (translate [(- (* 1/2 (inc s) w) (* s δx)) (- (* 1/2 (inc t) h) (* t δy)) 0]))) (->> (cylinder 6 (* 3 pcb-thickness)) (union (translate [6 0 0] (cube 12 12 (* 3 pcb-thickness)))) (translate [29 32.5 0])))) (color (repeat 3 0.75) (->> (apply cube (conj pcb-usb-size :center false)) (translate (conj pcb-usb-position pcb-thickness))) (->> (apply cube (conj pcb-6p6c-size :center false)) (translate (conj pcb-6p6c-position pcb-thickness)))) (translate (conj (mapv #(+ %1 (/ %2 2)) pcb-usb-position pcb-usb-size) (+ pcb-thickness 7)) (color (repeat 3 0.85)) (translate [0 0 6])) (color (repeat 3 0.2)) (translate [9/2 0 20])) (color (repeat 3 0.2)) (rotate [0 (/ π 2) 0]) (translate [41/2 0 21])) (color (repeat 3 0.2)) (rotate [0 (/ π 2) 0]) (translate [71/2 0 21]))) (color [1 1 1] (for [y [8 39]] (translate [25 y -8] (cube 4.5 18 8 :center false))) (translate [9 60 -8] (cube 14 4.5 8 :center false)))))) (def pcb-harness-bracket (let [δ -5/2 r (first pcb-mount-hole) h (second pcb-size)] (difference (union (hull (translate [δ 0 7/2] (cube 2 h 6)) (translate [δ 0 7] (cube 2 (- h 2) 1))) (for [s [-1 1] :let [y (* s (- (* 1/2 h) 4))]] (translate [0 y -1] (map hull (partition 2 1 [(translate [δ (* 3/2 s) 1] (cube 2 5 2)) (translate [(+ δ 1) (* 3/2 s) 0] (cube 2 5 2)) (translate [1/2 (* 3/2 s) 0] (cube 2 5 2))])) (hull (translate [1/2 (* 3/2 s) 0] (cube 2 5 2)) (translate [4 0 0] (cylinder 4 2)))))) (hull (translate [δ 0 -1/2] (cube 3 (- h 10) 6)) (translate [δ 0 3] (cube 3 (- h 12) 1))) (for [s [-1 1] :let [y (* s (- (* 1/2 h) 4))]] (translate [4 y 0] (cylinder (+ r 1/3) 10)))))) (defn key-plate [where, i j] (let [key-scale (key-scale-at where, i j)] (difference (union (translate [0 0 (/ plate-thickness -2)] (difference (apply hull (for [s [-1 1] t [-1 1] u [1 -1] :let [[x y z] (scale-to-key where, i j, s t u)]] (->> (sphere (/ plate-thickness 4 (Math/cos (/ π 8)))) (with-fn 8) (rotate [0 0 (/ π 8)]) (translate [x y 0]) (translate (map (partial * (/ plate-thickness -4)) [s t])) (translate [0 0 (/ z 2)])))) (cube plate-hole-size plate-hole-size (* 2 plate-thickness)))) (for [i (range 4) :let [nub-length 5 [a b] ((if (even? i) identity reverse) (mapv * (repeat plate-size) key-scale))]] (rotate [0 0 (* i π 1/2)] (union (when (place-nub? i) (->> (cube (* nub-width 11/10) nub-length nub-height :center false) (mirror [0 0 1]) (translate [(- (+ (/ plate-hole-size 2) (* nub-width 1/10))) (/ nub-length -2) 0]))))))) m (+ nub-height l) c (+ plate-hole-size (* 2 l)) h (- plate-thickness m)] (translate [0 0 (- m)] (->> (square c c) (extrude-linear {:height (+ l nub-width) :scale (repeat 2 (/ (- plate-hole-size (* 2 nub-width)) c)) :center false})) (translate [0 0 (/ (- m d) 2)] (cube c c (- d m)))))))) (def keyswitch-socket Kaihua PG1511 keyswitch socket . (+ -1.675 -5.08) (+ -5 -3.05)] (with-fn 30 (color (repeat 3 0.2) (difference (difference (cube 4 4 10) (translate [-2 2 0] (cylinder 2 10)))) (union (cube 10.8 4 10) (translate [5.4 0 0] (cylinder 2 10))))) Switch pin contacts (for [r [[2.275 1.675 0] [8.625 4.215 0]]] (translate r (cylinder (/ 2.9 2) 3.05 :center false))))) (apply union (for [r [[-1.8 (- 1.675 (/ 1.68 2)) 0] [10.9 (- 4.215 (/ 1.68 2)) 0]]] (translate r (cube 1.8 1.68 1.85 :center false)))))))) (defn orient-keyswitch [where, i j, shape] (cond->> shape (or (and (not= where :thumb) (not= i 2) (not= i 5) (not= j 0)) (and (= where :thumb) (not= j 0))) (rotate [0 0 π]))) (defn keyswitch [where, i j] (orient-keyswitch where, i j (union (color (repeat 3 0.2) (translate [0 0 -5/4] (cube 13.95 13.95 5/2)) (translate [0 0 -15/4] (cube 12.5 13.95 5/2))) (cylinder (/ 3.85 2) 2)) (translate [0 2 0]) (extrude-linear {:height 6.2 :scale [2/3 2/3] :center false}) (translate [0 -2 0]))) (color [0.1 0.5 1] (cube 6 6 4))) (translate [-2.54 -5.08 -6.30] (cube 1.5 0.2 3)) (translate [3.81 -2.54 -5.85] (cube 1.5 0.2 4)))))) corners . Can be configured to yield SA and DSA style keycaps . h_0 is the height of vertical ( i.e. not curved ) section at bottom , (defn base-keycap-shape [size h h_0 ρ & {:keys [fn-value shape top corner-rounding saddle-aspect saddle-skew fang-angle fang-skew fang-corner-rounding]}] (let [[minus-or-plus intersection-or-difference] (case top (:spherical-convex :saddle) [- intersection] [+ difference]) Half - length at base Half - length at top h_1 (case top :saddle h :cylindrical (minus-or-plus h (- ρ (Math/sqrt (- (* ρ ρ) (* d_1 d_1))))) (minus-or-plus h (* ρ (- 1 (Math/cos (Math/asin (/ d_1 ρ))))))) Consider two points on the center of the base and top of a p [d_0 h_0] q [d_1 h_1] v (map (partial * 1/2) (map - q p)) a (one-over-norm v) b (Math/pow (- (* ρ ρ) (/ 1 a a)) 1/2) O (map + p v [(* -1 b a (second v)) (* b a (first v))])] (union (with-fn (or fn-value (and draft? 80) 160) (cond-> (intersection-or-difference (intersection (or shape (union (translate [0 0 h] (apply cube (conj size (* 2 h)))) (->> (square (size 1) (* 2 h)) (translate [0 h]) (intersection (translate O (circle ρ))) (translate [(/ (size 1) 2) 0]) (translate [50 0] (square 100 100))) (extrude-rotate {:angle (/ fang-angle π 1/180)}) (rotate (/ π 2) [0 0 1]) (translate (map * (repeat -1/2) size)))))) (for [s [-1 1] t [0 1] :let [fang (and fang-angle (= [s t] [-1 0]))]] (cond->> (cylinder ρ (+ (apply max size) 100)) true (rotate (/ π 2) [1 0 0]) true (translate [(* s (+ (first O) (/ (- (size t) keycap-length) 2))) 0 (second O)]) true (rotate (* t π 1/2) [0 0 1]) fang (translate (map * (repeat 1/2) size)) fang (rotate fang-angle [0 0 1]) fang (translate (map * (repeat -1/2) size))))) (case top top . :saddle (->> (circle ρ) (translate [(* saddle-aspect ρ) 0]) (extrude-rotate {:angle 360}) (rotate [(/ π 2) (/ π 2) 0]) (translate [0 0 (* (- saddle-aspect 1) ρ)]) (translate (map * (concat saddle-skew [1]) (repeat h)))) :cylindrical (->> (cylinder ρ 100) (scale [(/ (first size) keycap-length) 1 1]) (rotate [(/ π 2) 0 0]) (translate [0 0 (+ ρ h)])) (apply hull (for [s [-1/2 1/2] t [-1/2 1/2] :let [δ (map - (if (and fang-angle (neg? s)) (map * [fang-skew 1] size) size) (repeat keycap-length))]] (->> (sphere ρ) (rotate [(/ π 2) 0 0]) (translate (conj (mapv * [s t] δ) (minus-or-plus h ρ)))))))) corner-rounding (difference (for [s [0 1] t [0 1] :when (or (not fang-angle) (not= [s t] [0 0])) :let [fang (and fang-angle (zero? s)) ρ_0 2 ρ_1 ρ]] (cond->> (difference (circle 10) (circle ρ_0) (union (translate [-50 0] (square 100 100 :center false)) (translate [0 -50] (square 100 100 :center false)))) true (rotate [0 0 (/ π -4)]) true (translate [(- ρ_1) 0]) true (extrude-rotate {:angle 90}) true (translate [(+ ρ_0 ρ_1) 0]) true (rotate [(/ π -2) (if fang fang-corner-rounding corner-rounding) (/ π 4)]) true (translate (conj (mapv (partial * -1/2) size) h_0)) true (mirror [s 0]) true (mirror [0 t]) fang (translate (map * (repeat 1/2) size)) fang (rotate fang-angle [0 0 1]) fang (translate (map * (repeat -1/2) size)))))))))) (defn keycap-shape [size & rest] Keycap height ( measured at top - center ) . Radius of sides and top . :or {h_add 0 h_0 0}} rest] (apply base-keycap-shape size (+ h h_add) h_0 ρ rest))) (defn keycap [where, i j] For distance from key plate to released keycap ( for Cherry MX (let [[family-options color-triplet] (key-options-at where, i j)] (->> (apply keycap-shape (mapv (partial * keycap-length) (key-scale-at where, i j)) family-options) (translate [0 0 (if keys-depressed? 3 6.6)]) (color color-triplet)))) (defn printable-keycap [scale & rest] (let [size (mapv (partial * keycap-length) scale) {w :thickness a :mount-cross-length b :mount-cross-width r :mount-radius δ :mount-offset h :height h_add :extra-height h_0 :mount-recess h_1 :homing-bar-height :or {δ [0 0] h_add 0 h_0 0 h_1 0} } rest δ_1 3/2 δ_2 0.4 δ_3 (mapv (partial * keycap-length) δ)] (difference (union (difference (union (apply keycap-shape size rest) (when (pos? h_1) (->> (apply keycap-shape size rest) (intersection (hull (for [x [-2 2]] (translate [x 0 0] (with-fn 50 (cylinder 1/2 100)))))) (translate [0 0 h_1])))) (union (apply keycap-shape (mapv (partial + (* -2 (first w))) size) (apply concat (-> (apply hash-map rest) (dissoc :corner-rounding) (update :extra-height #(- (or % 0) (second w))) seq))) (translate [0 0 -4.99] (apply cube (conj (mapv (partial + (* -2 (first w))) size) 10))))) (apply keycap-shape size :shape (translate (conj δ_3 h_0) (cylinder r 100 :center false)) rest)) (translate (conj δ_3 (+ 2 h_0)) (for [θ [0 (/ π 2)]] (rotate [0 0 θ] (translate [0 0 -1/2] (cube a b 5)) (->> (square a b) (extrude-linear {:height (/ b 2) :scale [1 0] :center false}) (translate [0 0 2])))) (->> (cube 15/8 15/8 4) (rotate [0 0 (/ π 4)]))) (when-let [[c font size] keycap-legend] (->> (text c :font font :size size :halign "center" :valign "center") (extrude-linear {:height 1 :center false}) (translate [0 0 (+ h h_add -1/2)])))))) (declare ^:dynamic rotate-x ^:dynamic rotate-z ^:dynamic translate-xyz) (defn transform-or-calculate [transform?] (if transform? {#'rotate-x #(rotate %1 [1 0 0] %2) #'rotate-z #(rotate %1 [0 0 1] %2) #'translate-xyz translate} {#'rotate-x #(identity [(first %2) (reduce + (map * %2 [0 (Math/cos %1) (- (Math/sin %1))])) (reduce + (map * %2 [0 (Math/sin %1) (Math/cos %1)]))]) #'rotate-z #(identity [(reduce + (map * %2 [(Math/cos %1) (- (Math/sin %1)) 0])) (reduce + (map * %2 [(Math/sin %1) (Math/cos %1) 0])) (nth %2 2)]) #'translate-xyz (partial mapv +)})) so that [ x y z ] = [ 1 1 0 ] is at the top right corner of the upper face of the plate ( z starts at zero at the top of the face , as (defn key-place [where, i j, x y z & [shape-or-point]] (if (not= where :thumb) (let [offset (scale-to-key where, i j, x y z)] and are always tangent to it . The angle subtended by a 1u key plate ( of dimensions plate - size ) is 2 * atan(l / 2r ) , (let [central-angle (fn [l r] (* 2 (Math/atan (/ l 2 r)))) location (fn [s t phase scale spacing radius] (reduce + (* (+ (phase s) (* scale 1/2)) (central-angle plate-size radius)) (for [k (range t)] (central-angle (+ plate-size (spacing k)) radius)))) θ (location i j column-phase 1 (constantly (row-spacing i)) (column-radius i)) φ (location j i row-phase (first (key-scale-at where, i j)) column-spacing row-radius) maybe-flip #(if (= [i j] [(column -1) (row -1)]) (->> % (translate-xyz palm-key-offset) (translate-xyz [0 (* -1/2 plate-size) 0]) (rotate-x (/ π 2)) (translate-xyz [0 (* 1/2 plate-size) 0])) %)] (with-bindings (transform-or-calculate (fn? shape-or-point)) (->> (if (fn? shape-or-point) (shape-or-point where, i j) (or shape-or-point [0 0 0])) (translate-xyz offset) maybe-flip (translate-xyz [0 0 (- (column-radius i))]) (rotate-x (- θ)) (translate-xyz [0 0 (column-radius i)]) (translate-xyz [0 0 (- row-radius)]) (rotate-x (/ π 2)) (rotate-z (- φ)) (rotate-x (/ π -2)) (translate-xyz [0 0 row-radius]) (translate-xyz [0 (column-offset i) 0]) (translate-xyz [0 0 (column-height i)]) (translate-xyz [0 0 global-z-offset]))))) (with-bindings (transform-or-calculate (fn? shape-or-point)) (->> (if (fn? shape-or-point) (shape-or-point where, i j) (or shape-or-point [0 0 0])) (translate-xyz (scale-to-key where, i j, x y z)) (rotate-x (thumb-key-slope i j)) (translate-xyz (thumb-key-offset i j)) (translate-xyz [0 thumb-radius 0]) (rotate-x (- thumb-slant)) (rotate-z (reduce + (map * (thumb-key-phase i j) [1 i]))) (rotate-x thumb-slant) (translate-xyz [0 (- thumb-radius) 0]) (translate-xyz (map + (key-place :main, 1 (row -2), 1 -1 0) thumb-offset)))))) (defn key-placed-shapes [shape] (for [i columns j rows :when (place-key-at? [i j])] (key-place :main, i j, 0 0 0, shape))) (defn thumb-placed-shapes [shape] (for [j (range 3) i (case j 0 (range 4) 1 (range 3) [1])] (key-place :thumb, i j, 0 0 0, shape))) (defn web-kernel [place, i j, x y & [z]] (key-place place, i j, x y (or z 0) (fn [& _] (let [[δx δy] (map #(* (compare %1 0) -1/4 plate-thickness) [x y]) ε (+ (* x 0.003) (* y 0.002))] (->> (sphere (/ (+ plate-thickness ε) 4 (Math/cos (/ π 8)))) (with-fn 8) (rotate [0 0 (/ π 8)]) (translate [δx δy (/ plate-thickness s 4)]) (for [s [-1 1]]) (apply hull) (translate [0 0 (/ plate-thickness -2)])))))) (def key-web (partial web-kernel :main)) (def thumb-web (partial web-kernel :thumb)) (defn triangle-hulls [& shapes] (->> shapes (partition 3 1) (map (partial apply hull)) (apply union))) (def connectors (delay (list* (when (every? place-key-at? [[1 (row -2)] [2 (row -2)]]) (triangle-hulls (key-web 1 (row -2) 1 -1) (key-web 1 (row -2) 1 1) (key-web 2 (row -2) -1 -1) (key-web 1 (row -3) 1 -1))) (when (every? place-key-at? [[2 0] [1 0] [2 0]]) (triangle-hulls (key-web 2 1 -1 1) (key-web 1 0 1 1) (key-web 2 0 -1 -1) (key-web 2 0 -1 1))) (when (every? place-key-at? [[3 (row -1)] [3 (row -2)] [4 (row -2)]]) (triangle-hulls (key-web 3 (row -2) 1 -1) (key-web 4 (row -2) -1 -1) (key-web 3 (row -1) 1 1) (key-web 3 (row -1) 1 -1))) (when (every? place-key-at? [[(column -1) (row -2)] [(column -2) (row -2)]]) (triangle-hulls (key-web (column -1) (row -2) -1 -1) (key-web (column -1) (row -1) -1 1) (key-web (column -2) (row -2) 1 -1))) (concat j rows :let [maybe-inc (if (= i 1) inc identity)] :when (and (not= [i j] [1 (row -2)]) (every? place-key-at? [[i j] [(inc i) j]]))] (apply triangle-hulls (cond-> [(key-web i j 1 1) (key-web i j 1 -1) (key-web (inc i) (maybe-inc j) -1 1)] This bit is irregular for the ( row -1 ) of the first (not= [i j] [1 (row -2)]) (into [(key-web (inc i) (maybe-inc j) -1 -1)])))) j (butlast rows) :when (every? place-key-at? [[i j] [i (inc j)]])] (triangle-hulls (key-web i j -1 -1) (key-web i j 1 -1) (key-web i (inc j) -1 1) (key-web i (inc j) 1 1))) Diagonal connections j (butlast rows) :let [maybe-inc (if (= i 1) inc identity)] :when (and (not= [i j] [1 (row -3)]) (every? place-key-at? (for [s [0 1] t [0 1]] [(+ i s) (+ j t)])))] (triangle-hulls (key-web i j 1 -1) (key-web i (inc j) 1 1) (key-web (inc i) (maybe-inc j) -1 -1) (key-web (inc i) (maybe-inc (inc j)) -1 1))))))) (def thumb-connectors (delay (let [z (/ ((thumb-key-offset 0 1) 2) plate-thickness) y -5/16] (list (triangle-hulls (thumb-web 0 0 1 -1) (thumb-web 1 0 1 -1) (thumb-web 0 0 -1 -1) (thumb-web 1 0 1 1) (thumb-web 0 0 -1 1) (thumb-web 0 0 -1 1) (thumb-web 0 0 1 1)) (triangle-hulls (thumb-web 2 0 1 1) (thumb-web 1 0 -1 1) (thumb-web 2 0 1 -1) (thumb-web 1 0 -1 -1) (thumb-web 1 1 -1 1) (thumb-web 1 0 1 -1) (thumb-web 1 1 1 1)) (triangle-hulls (thumb-web 0 0 1 -1 z) (thumb-web 1 1 1 1) (thumb-web 0 1 -1 1) (thumb-web 1 1 1 -1) (thumb-web 0 1 -1 -1) (thumb-web 1 2 1 1) (thumb-web 0 1 1 -1) (thumb-web 1 2 1 -1)) (triangle-hulls (thumb-web 2 1 -1 1) (thumb-web 3 0 -1 -1) (thumb-web 2 1 1 1) (thumb-web 3 0 1 -1) (thumb-web 2 0 -1 -1) (thumb-web 3 0 1 1) (thumb-web 2 0 -1 1)) (triangle-hulls (thumb-web 2 0 1 -1) (thumb-web 2 0 -1 -1) (thumb-web 1 1 -1 1) (thumb-web 2 1 1 1) (thumb-web 1 1 -1 -1) (thumb-web 2 1 1 -1) (thumb-web 1 2 -1 1) (thumb-web 2 1 -1 -1) (thumb-web 1 2 -1 -1)) (triangle-hulls (thumb-web 1 1 -1 -1) (thumb-web 1 2 -1 1) (thumb-web 1 1 1 -1) (thumb-web 1 2 1 1)) (when (place-key-at? [0 (row -2)]) (triangle-hulls (key-web 1 (row -2) -1 -1) (key-web 0 (row -2) 1 -1) (thumb-web 0 0 -1 1) (key-web 0 (row -2) -1 -1) (thumb-web 1 0 1 1) (thumb-web 1 0 -1 1))) (triangle-hulls (thumb-web 0 1 -1 1) (thumb-web 0 1 1 1) (thumb-web 0 0 1 -1 z) (key-web 3 (row -1) -1 -1) (key-web 2 (row -1) -1 -1) (key-web 2 (row -1) 1 -1)) (triangle-hulls (thumb-web 1 1 1 1) (thumb-web 1 0 1 -1) (thumb-web 0 0 1 -1 z) (thumb-web 0 0 1 -1) (key-web 2 (row -1) -1 -1) (thumb-web 0 0 1 1) (key-web 2 (row -1) -1 y) (thumb-web 0 0 -1 1) (key-web 1 (row -2) 1 -1) (key-web 1 (row -2) -1 -1)) (triangle-hulls (key-web 2 (row -1) -1 y) (key-web 2 (row -1) -1 1) (key-web 1 (row -2) 1 -1) (key-web 2 (row -2) -1 -1)))))) (defn case-placed-shapes [brace] (let [place #(apply brace %&) strip (fn [where & rest] (for [ab (partition 2 1 rest)] (apply place (map (partial cons where ) (if (:reverse (meta (first ab))) (reverse ab) ab)))))] (concat (list* (place [:left, 0 0, -1 1] [:back, 0 0, -1 1]) (apply strip :back (for [i columns x (conj (vec (range -1 1 (/ 1/2 (first (key-scale-at :main, i 0))))) 1)] [i 0, x 1]))) (list (place [:back, (column -1) 0, 1 1] [:right, (column -1) 0, 1 1])) (apply strip :right (for [j rows y [1 -1]] [(column -1) j, 1 y])) Front wall (list* (place [:right, (column -1) (row -1), 1 -1] [:front, (column -1) (row -1), 1 -1, -1/4 1/4]) (strip :front [(column -1) (row -1), 1 -1, -1/4 1/4] [(column -1) (row -1), -1 -1, 1/4 1/4] [(column -1) (row -1), -1 1, -5 -8 0] [(column -2) (row -2), 1 -1, -9 -4] [(column -2) (row -2), 0 -1, 0 -4] [(column -2) (row -2), -1 -1, 3 -4] [3 (row -1), 1 -1, 0 -3 -9/2] [3 (row -1), 0 -1, 4 -3 -9/2] [3 (row -1), -1 -1])) (list* (place [:front, 3 (row -1), -1 -1] [:thumb, 0 1, 1 1]) (strip :thumb [0 1, 1 1] [0 1, 1 -1, 1/2 0 -2] [1 2, 1 -1, 1 -1] [1 2, -1 -1, -1 -1] [2 1, -1 -1, -1/2 0 -2] [2 1, -1 1, -1/2 -1 -2] [3 0, -1 -1, -1/2 17/8 -5] [3 0, -1 1, 1/2 -7/4 -3] [3 0, -1 1, 7/4 -1/2 -3] [3 0, 1 1, -3 1/2 -5] [2 0, -1 1, 0 1] [2 0, 1 1, 0 1] [1 0, -1 1])) (list (place [:thumb, 1 0, -1 1] [:left, 0 (row -2), -1 -1])) (apply strip :left (for [j (rest (reverse rows)) y [-1 1]] [0 j, -1 y]))))) (defn lagrange [i j, x y z, dy] measured from the keys of the first row . It passes through those points and is smoothly interpolated in - between , using a Lagrange polynomial . We introduce a discontinuity between the second and third column , purely for aesthetic reasons . (let [discontinuous? true [xx yy zz] (if (and discontinuous? (< i 2)) [-23/4 0 -65/4] [0 23/4 -13]) u (first (key-place :main, i j, x y 0)) uu [(first (key-place :main, 0 0, -1 y 0)) (first (key-place :main, 3 0, 1 y 0)) (first (key-place :main, (column -1) 0, 1 y 0))] vv [(key-place :main, 0 0, -1 y z, [(if (neg? z) 10 0) (+ (* 1/2 (- 1 y) plate-size) dy) -15]) (key-place :main, 3 0, 1 y (* 5/13 z), [xx (+ (* 5/13 dy) yy) zz]) (key-place :main, (column -1) 0, 1 y 0, [-1 -5/4 -13/4])] l (fn [k] (reduce * (for [m (range (count uu)) :when (not= m k)] (/ (- u (uu m)) (- (uu k) (uu m))))))] (apply (partial map +) (for [k (range (count vv))] (map (partial * (l k)) (vv k)))))) (defn wall-place [where, i j, x y z, dx dy dz & [shape]] (let [offsets (map (fn [a b] (or a b)) [dx dy dz] (case where :back [0 0 -15] :right (case [j y] [0 1] [-1/4 -5/2 -5/2] [3 -1] [-3/8 3/2 -19/8] [4 1] [-3/8 -3/2 -19/8] [4 -1] [-1/4 1/4 -5/2] [-1/4 0 -5/2]) :left [0 (case [j y] [3 -1] 2 0) -15] :front (if (= [i j, x y] [3 (row -1), -1 -1]) [7 -5 -6] [0 1/2 (if (= i 4) -5 -5/2)]) :thumb (cond (= [i j, x] [1 0, -1]) [1 0 -3/2] (= [i j, x y] [0 1, 1 1]) [0 -3/8 -2] :else [0 0 -6])))] (if (= where :back) (cond-> (lagrange i j, x y z, (second offsets)) shape (translate shape)) (key-place where, i j, x y z (cond-> offsets shape (-> (translate shape) constantly)))))) (defn wall-place-a [where i j x y dx dy dz & [shape]] (wall-place where i j x y 0 dx dy dz shape)) (defn wall-place-b [where i j x y dx dy dz & [shape]] (cond (= where :left) (wall-place where i j x y -4 8 (case [j y] [0 1] -10 [3 -1] 6 0) dz shape) (= where :back) (wall-place where i j x y -4 dx -8 dz shape) (and (= where :thumb) (not= [i j] [3 0]) (not= [i j] [0 1]) (not= [i j] [2 1]) (not= [i j x] [1 0, -1]) (not= [i j x] [2 0, 1])) (wall-place where i j x y -5 (- dx) (- dy) dz shape) (and (= [i j] [(column -1) (row -1)]) (not= y 1)) (wall-place where i j x y -3 dx dy dz shape) :else (wall-place-a where i j x y dx dy dz shape))) (defn wall-sections [endpoints] (apply map vector (for [[where i j x y dx dy dz] endpoints :let [r (/ wall-thickness 2) shape-a (wall-place-a where i j x y dx dy dz (sphere r)) shape-b (wall-place-b where i j x y dx dy dz (sphere r))]] [(web-kernel where, i j, x y) shape-a shape-b (->> shape-b project (extrude-linear {:height 1/10 :center false}))]))) (defn wall-brace [sections & endpoints] consecutive sections to form the walls . Filter out (->> (sections (reverse endpoints)) (apply concat) (partition 3 1) (filter #(= (count (set %)) 3)) (map (partial apply hull)) (apply union))) (defn place-boss? ([endpoints] (place-boss? (if case-test-build? (set case-test-locations) (constantly true)) endpoints)) ([boss-filter endpoints] (let [boss-map (apply hash-map (apply concat (keep-indexed #(when (boss-filter %1) [(set (take 2 %2)) (nth %2 2 [1/2 1])]) screw-bosses)))] (boss-map (set (map (comp (partial take 5) #(cons (if (= (first %) :thumb) :thumb :key) (rest %))) endpoints)))))) (defn boss-place [x d endpoints & shape] (let [ab (for [[where i j x y dx dy dz] endpoints] (wall-place-b where i j x y dx dy dz)) n (apply line-normal ab)] Place the boss at some point x ( in [ 0 , 1 ] ) along the wall (cond-> (->> ab (take 2) (apply map #(+ %1 (* (- %2 %1) x))) (mapv + (map (partial * d screw-boss-radius (one-over-norm n)) n))) shape (translate shape)))) (defn screw-boss [& endpoints] (when-let [[x d] (place-boss? endpoints)] (hull (intersection (binding [wall-thickness (- wall-thickness 0.005)] (apply wall-brace (comp (partial take-last 2) wall-sections) endpoints)) The height is calculated to yield a 45 deg gusset . (boss-place x 0 endpoints (cylinder screw-boss-radius (+ screw-boss-height (- (* 2 screw-boss-radius) (/ wall-thickness 2))) :center false))) (boss-place x d endpoints (cylinder screw-boss-radius screw-boss-height :center false))))) (defn countersink [r h t b] (let [r_1 (+ r (* h (Math/tan (/ cover-countersink-angle 2))))] (union (cylinder [r_1 r] h :center false) (when (pos? t) (translate [0 0 -1] (cylinder r (+ t 1) :center false))) (when (pos? b) (translate [0 0 (- b)] (cylinder r_1 b :center false)))))) (defn screw-countersink [& endpoints] (when-let [[x d] (place-boss? endpoints)] (let [r (/ cover-countersink-diameter 2) h cover-countersink-height] (boss-place x d endpoints (translate [0 0 (- h)] (countersink r h 50 50)))))) (defn screw-thread [& endpoints] (when-let [[x d] (place-boss? endpoints)] (let [[D P L] cover-fastener-thread] proper CSG results at the bottom face of the boss . (boss-place x d endpoints (translate [0 0 (- P)] (apply thread (update cover-fastener-thread 2 + P))))))) (defn case-test-cutout [& endpoints] (when-let [[x d] (place-boss? endpoints)] (let [[c t] (partition 3 3 case-test-volume)] (boss-place x d endpoints (translate (or t [0 0 0]) (apply cube c)))))) (def ^:dynamic cover-navel (-> (key-place :main, 3 1 0 0 0) vec (assoc 2 0) (translate (cube 1 1 cover-thickness :center false)))) (defn cover-shard [& endpoints] (->> (wall-sections endpoints) last (map (partial scale [1 1 (* cover-thickness 10)])) (cons cover-navel) hull)) (defn flattened-endpoints [& endpoints] (for [[where i j x y dx dy dz] endpoints] (assoc (vec (wall-place-b where i j x y dx dy dz)) 2 0))) (def stand-baseline-points (delay (let [points (case-placed-shapes flattened-endpoints) n (count points)] (->> points (cycle) (drop n) (take 60))))) (def stand-baseline-origin (delay (+ (->> @stand-baseline-points (apply concat) (map first) (apply max)) (/ wall-thickness 2)))) (defn stand-xform [θ shape] (let [t (+ @stand-baseline-origin (/ (last stand-minimum-thickness) (Math/sin stand-tenting-angle)))] (->> shape (translate [(- t) 0 0]) (rotate [0 θ 0]) (translate [t 0 0])))) (defn stand-section ([s kernel] (stand-section s [[0 0 0] [stand-width 0 0]] kernel)) ([s offsets kernel] (let [θ (* -1 s stand-tenting-angle) x_max @stand-baseline-origin] the mean of the normals of the two edges that share it . This (for [[[a b] [_b c]] (partition 2 1 @stand-baseline-points) :let [_ (assert (= b _b)) u (map + (line-normal a b) (line-normal b c)) n (map (partial * (one-over-norm u)) u) t [(- (second n)) (first n)] Scale with 1 / cos θ , to get a straight projection . p (update b 0 #(+ (* (- 1 stand-shape-factor) %) (* stand-shape-factor (+ (* (- % x_max) (/ 1 (Math/cos θ))) x_max))))]] (stand-xform θ (for [u offsets :let [[c_n c_t c_b] u q (conj (mapv + p (map (partial * c_n) n) (map (partial * c_t) t)) c_b)]] (translate q kernel))))))) (def countersink-boss (delay (difference (countersink (- (/ cover-countersink-diameter 2) 1/4) cover-countersink-height 0 0) (translate [0 0 (+ 5 cover-countersink-height -1/2)] (cube 10 10 10))))) (defn stand-boss [& endpoints] (when-let [[x d] (place-boss? (set stand-boss-indexes) endpoints)] (boss-place x d endpoints @countersink-boss))) (defn stand-boss-cutout [& endpoints] (when-let [[x d] (place-boss? (set stand-boss-indexes) endpoints)] (boss-place x d endpoints (translate [0 0 -3/2] (countersink (/ cover-countersink-diameter 2) cover-countersink-height 50 20))))) Rebind these for brevity . (let [D_ext bridge-link-diameter [D D_add P] bridge-link-thread] (defn bridge-bearing [indexes] (let [[a b] (map #(conj % 0) (remove nil? (case-placed-shapes (fn [& endpoints] (when-let [[x d] (place-boss? (set indexes) endpoints)] (boss-place x d endpoints)))))) y (fn [v] (update v 1 (if (> (second b) (second a)) - +))) R' (* (Math/sqrt 2) R) R'' (- R' R) 45 ° for a bit to c ( to bring the bearings closer δ (* -1/2 bridge-bearing-separation) c (mapv - a (y [δ δ 0])) c' (assoc c 0 (first b)) O (y [(- (first b) (first a) R') (- R'' ε δ D) 0]) d (map + c' [0 (second O) 0] (y [(- R') (- δ D R'' ε) 0])) e (map + a (y [(+ (- (first b) (first a) R'') R) (+ (- (first b) (first a) R'') R) 0])) section (for [x [0 (+ ε ε)]] (cube 1/10 (+ D D ε ε x) (- t x))) chamfered-disk #(union (cylinder % t) (cylinder (+ % ε) (- t ε ε))) fillet-cutout (fn [r & parts] (->> (list* (translate p (cylinder (- r ε) h)) (->> (cylinder [(- r ε) (+ r ε)] (+ ε ε) :center false) (rotate [(* 1/2 π (dec s)) 0 0]) (translate (map + p [0 0 (* 1/2 s h)])) (for [s [-1 1]]))) (for [p parts :let [h (- t ε ε)]]) (apply map vector) (map hull))) xform #(->> %2 (translate [0 0 bridge-arch-radius]) (rotate [0 (* -1 %1 stand-tenting-angle) 0]) (translate (map + [0 0 (- bridge-arch-radius)] O)) (translate a))] (translate [0 0 (- cover-thickness)] (difference (union (for [p [a b]] (translate p @countersink-boss)) (translate [0 0 (- 1 (/ t 2))] (let [h (- D t) D' (+ D ε ε) A bent plate mounted on the bottom cover on one plate (union (->> (apply union (list* (when (zero? i) (translate [R'' 0 0] section)) (when (= i N) (->> (chamfered-disk (+ D ε)) (translate [(- D') 0 0]))) section)) (for [i (range (inc N))]) (mapv hull) union) (difference (->> (chamfered-disk R) (translate p) (for [p [a c c' b]]) (partition 2 1) (mapv hull) (cons (->> (cube R' R' t) (translate c') (translate (y [(/ R' -2) (/ R' 2) 0])))) (cons (->> (cube R'' R'' t) (translate d) (translate (y [(/ R'' 2) (/ R'' 2) 0])))) (cons (->> (cube R' (* 3 R') t) (translate a) (translate (y [0 (* -2 R') 0])))) (apply union)) (apply fillet-cutout R (for [Δ [[-50 0 0] [0 0 0] [50 50 0]]] (map + c (y [(- R') R' 0]) (y Δ)))) (apply fillet-cutout R (for [Δ [[50 50 0] [0 0 0] [0 -50 0]]] (map + e (y [R' (- R') 0]) (y Δ)))) (fillet-cutout R'' d))) parts (let [ε_2 (/ ε 2)] [(translate [0 0 (- h ε_2)] (cylinder [D (+ D ε_2)] ε_2 :center false)) (translate [0 0 ε_2] (cylinder D (- h ε) :center false)) (cylinder [(- D ε_2) D] ε_2 :center false)])] (difference Maybe extend along X. (translate [u 0 0]) (for [u [0 50]]) (apply hull))) (translate [(- D') 0 (- (/ t -2) h)]) (xform 1))) (apply union plate)) (->> (countersink (/ (+ D bridge-bore-expansion) 2) (* 1/8 D) 50 50) (rotate [(* π (dec u)) 0 0]) (translate [(- D') 0 (- (/ t 2) (* u D))]) (xform 1) (for [u [0 1]])))))) (for [p [a b]] (->> (countersink (/ cover-countersink-diameter 2) cover-countersink-height 50 50) (translate p) (translate [0 0 (- 1 t)]))))))) range of the joint is 180 ° + 2φ . In other words you can move it , up to φ degrees past the 90 ° mark . . l_1 |//| |//| . . |//////////| . (defn clevis [style φ & [n]] n' (or n 1) δ (* D (+ 1 (Math/tan φ))) δ' (* (dec n') (+ δ D)) l_1 (+ ε δ) l_4 (* 4/3 D) l_2 (+ l_4 (/ D 2) l_1) l_3 (+ l_2 D 1) l_3' (+ l_3 δ') l_34' (/ (- l_3' l_4) 2) bore #(->> (countersink (+ (/ (+ D bridge-bore-expansion) 2)) (* 1/8 D) 50 50) (rotate [(* π 1/2 (dec s)) 0 0]) (translate [0 0 (* % s D)]) (for [s [-1 1]]) (apply rotate [(/ π 2) 0 0]) (translate [0 0 l_2])) Corner rounding geometry rounding #(->> (sphere (/ l_3 2)) (scale [1.05 1.05 1]) (translate [0 0 (* s %)]) (for [s [-1/2 1/2]]))] (if (= style :eye) Minus the edges and bore . (->> (sphere ε) (translate [(* u 50) (* v (+ 1 t) (+ (/ D 2) ε)) (- l_2 (* s (- l_1 ε)) (* t (+ (/ D 2) ε)))]) (for [s [-1 1] t [0 1] u [-1 1]]) (apply hull) (for [v [-1 1]])) (bore -1/2)) Corner rounding (apply difference (->> (intersection (map #(- (* 2 % (Math/sqrt 2)) ε) [D D 100])) (rotate [0 0 (/ π 4)])) Corner rounding (apply intersection (rounding (- l_4 δ'))) (apply hull (rounding (- l_4 δ'))))) (translate [0 0 l_34']) (hull (cylinder (/ D_ext 2) 1 :center false)) (translate [0 0 l_4]) (cylinder (/ D_ext 2) l_4 :center false))) (->> (sphere ε) (translate [(* u 50) (* t (- (/ D 2) ε)) (+ l_2 (- l_1) (* s 100) ε)]) (for [s [0 1] t [-1 1] u [-1 1]]) (apply hull)) (for [i (range n')] (translate [0 0 (* i (+ δ D))] (bore -1))))))) (defn rod-end [style L & rest] Chamfer legnth Journal length D_eff (+ D D_add) angle 2φ . h (fn [d] (/ d 2 (Math/tan φ))) ): extended base diameter of a cone with a ( lateral ) gap of w relative to a cone of base diameter d. x (fn [d w] (+ d (/ w 1/2 (Math/cos φ)))) Gap Journal diameter Journal bottom Journal top L_2 (+ L_1' (+ (h (- (+ D_1 D_ext) (* 2 D_2))) n)) Create two versions of the joint geometry . One , suitably extended by g , will serve as a cut - out . [M F] (for [δ [0 g] :let [D' (x D_1 δ) D_ext' (x D_ext δ) r (/ D' 2)]] (union (translate [0 0 (- L_1 (h D'))])) Journal (translate [0 0 L_1])) (translate [0 0 L_1'])) (translate [0 0 L_1'])) (->> (cylinder [0 (/ D_ext' 2)] (h D_ext') :center false) (translate [0 0 (- L_2 (h D_ext'))]))))] (difference (if (= style :fixed) (->> (apply clevis rest) (translate [0 0 (- L 7)]) (union (cylinder (/ D_ext 2) L :center false)) (intersection (cylinder (mapv (partial + (/ D_ext 2) ε) [0 500]) 500 :center false))) (union (difference (union (let [H (- L_2 (/ g (Math/sin φ)) (h 2.4)) H_c (+ (/ D_ext 2) H ε)] (when (or true) (intersection (cylinder (/ D_ext 2) H :center false) (for [s [0 1]] (->> (cylinder [H_c 0] H_c :center false) (rotate [(* π s) 0 0]) (translate [0 0 (* H s)])))))) (->> (apply clevis rest) (translate [0 0 (- 4 (* 3/2 D))]) (intersection (->> (apply cube (repeat 3 (* 10 D))) (translate [0 0 (* 5 D)]))) (translate [0 0 L_2]))) F) (difference M Hollow out the center with a suitably expanded cone , to (->> (cylinder [(/ (x D_eff g) 2) 0] (h (x D_eff g)) :center false) (translate [0 0 L]))))) (let [H (h D_eff) H' (+ L H)] (->> (thread D_eff P (+ L H P)) (translate [0 0 (- P)]) (intersection (cylinder [(* D_eff 1/2 H' (/ 1 H)) 0] H' :center false)))) (cylinder [(+ (/ D_eff 2) 3/2) (- (/ D_eff 2) 3/2)] 3)))) (def bridge-cable-bracket (delay (let [ε 2/5 ε' (+ ε ε) D' (+ D D) w 3 φ (degrees 10) δ (* D (+ 2 (Math/tan φ))) y_0 (/ (+ (second bridge-bracket-size) w) 2) kernel (hull (cube w (+ 1/10 ε') (- D' ε')) (cube (- w ε') 1/10 D')) loop (->> kernel (translate (apply #(vector (/ (+ %1 w) 2) (/ (- %2 1) 2 s) 0) (if (even? t) bridge-bracket-size (rseq bridge-bracket-size)))) (rotate [0 0 (* 1/2 t π)]) (for [t (range 4) s [-1 1]]) cycle)] (-> (->> loop (partition 2 1) (take 8) (map (partial apply hull)) (apply union)) (union (->> (union (cylinder (- D ε) w) (cylinder D (- w ε ε))) (rotate [(/ π 2) 0 0]) (translate [0 y_0 (* s δ)]) (for [s [0 2]]) hull)) (union (->> kernel (rotate [0 0 (/ π 2)]) (translate [(* s (- D t -2 ε ε)) y_0 t]) (for [s [-1 1] t [0 2]]) hull)) (difference (->> (countersink (/ (+ D bridge-bore-expansion) 2) (/ D 16) 50 50) (rotate [(/ π s 2) 0 0]) (translate [0 (+ y_0 (* 1/2 s w)) (* t δ)]) (for [s [-1 1] t [1 2]])))))))) (defn assembly [side & parts] (let [left? (= side :left) place-part? (set parts) build-thumb-section? (or thumb-test-build? (not key-test-build?)) difference-or-union (if interference-test-build? difference union) maybe-cut-out (if case-test-build? (partial intersection (apply hull (case-placed-shapes case-test-cutout))) identity) pcb-place-properly (partial pcb-place left?)] (mirror [(if left? 1 0) 0 0] (maybe-cut-out (difference-or-union (apply union (concat (when place-keyswitches? (concat (key-placed-shapes keyswitch) (when build-thumb-section? (thumb-placed-shapes keyswitch)))) (when place-keycaps? (concat (key-placed-shapes keycap) (when build-thumb-section? (thumb-placed-shapes keycap)))))) (when (place-part? :top) (apply (if case-color (partial color case-color) union) (concat @connectors (key-placed-shapes key-plate) (when build-thumb-section? (concat @thumb-connectors (thumb-placed-shapes key-plate))) (when-not (or thumb-test-build? key-test-build?) (list* (apply difference (apply union (case-placed-shapes screw-boss)) (case-placed-shapes screw-thread)) (case-placed-shapes (partial wall-brace wall-sections))))))) (when (place-part? :bottom) (intersection (when case-test-build? (hull (case-placed-shapes case-test-cutout))) (let [δ 1/2] (difference (union (translate [0 0 (- 1 cover-thickness)] (case-placed-shapes cover-shard)) (pcb-place-properly pcb-bosses)) (pcb-place-properly pcb-connector-cutout) (pcb-place-properly @pcb-button-hole-cutout) (binding [wall-thickness (+ wall-thickness δ) screw-boss-radius (+ screw-boss-radius (/ δ 2)) cover-navel nil] (doall (concat (case-placed-shapes cover-shard) (case-placed-shapes screw-boss)))) (translate [0 0 (- cover-countersink-height cover-thickness -1)] (case-placed-shapes screw-countersink)))))) (when place-pcb? (union (pcb-place-properly pcb) (pcb-place-properly (translate [0 (/ (second pcb-size) 2) 0] pcb-harness-bracket)))) (when (or (place-part? :stand) (place-part? :boot)) (let [n (Math/ceil (/ stand-tenting-angle π (if draft? 2/180 1/180))) columns (apply map vector (for [i (range (inc n))] (partition 2 1 (stand-section (/ i n) (translate [0 0 -1/20] (cylinder (/ wall-thickness 2) 1/10)))))) [part-a rest] (split-at (first stand-split-points) columns) [part-b part-c] (split-at (- (second stand-split-points) (first stand-split-points)) rest) shorten (fn [part & limits] [(map-indexed #(if (>= %1 (first limits)) (drop (quot n 2) %2) []) part) (map-indexed #(if (>= %1 (second limits)) (take (quot n 2) %2) []) part)]) hulled-parts (for [part (concat [part-b] (apply shorten part-a (take 2 stand-arm-lengths)) (apply shorten (reverse part-c) (drop 2 stand-arm-lengths)))] (for [column part [[a b] [c d]] (partition 2 1 column)] (union (hull a b c) (hull b c d))))] (translate [0 0 (- 1 cover-thickness)] (when (place-part? :stand) (let [parts (list* (case-placed-shapes stand-boss) (first hulled-parts) (for [i [1 3 0 2] :let [q (quot i 2) r (rem i 2) qq (- 1 q q) rr (- 1 r r) [take-this take-that] (cond->> [take take-last] (pos? q) reverse)]] (difference (apply union (nth hulled-parts (inc i))) (->> (sphere 1/2) (translate [0 0 (* rr (+ 1/2 (stand-minimum-thickness r)))]) (stand-section (- 1 r) (for [n [-100 100] [t z] [[(/ wall-thickness -2) 0] [100 (* (Math/tan stand-arm-slope) 100)]] z_add [0 100]] [n (* qq t) (* rr (+ z z_add))])) (take-this (inc (stand-arm-lengths i))) (take-that 1) (apply hull))))) [upper-parts lower-parts] (split-at 4 parts)] (apply union (difference (apply union upper-parts) (case-placed-shapes stand-boss-cutout)) lower-parts))) (when (place-part? :boot) (difference Take the difference of lower 10 ° or so of the (apply difference (for [δ boot-wall-thickness :let [n (Math/ceil (/ stand-tenting-angle π 1/180)) columns (->> (cylinder (+ (/ wall-thickness 2) δ) h) (translate [0 0 (/ h -2)]) (stand-section (/ (- n i) n)) (drop (stand-arm-lengths 0)) (drop-last (stand-arm-lengths 2)) (partition 2 1) (for [i ((if draft? identity (partial apply range)) [0 (if (pos? δ) (quot n 2) n)]) :let [h (if (and (zero? i) (pos? δ)) boot-bottom-thickness 1/10)]]) (apply map vector))]] (union (for [column columns [[a b] [c d]] (partition 2 1 column)] (union (hull a b c) (hull b c d)))))) (->> (cube 1000 1000 1000) (translate [0 0 (+ 500 1/10 boot-wall-height)]) (stand-xform (- stand-tenting-angle))) (case-placed-shapes stand-boss-cutout)))))) (when (place-part? :bridge) (->> bridge-boss-indexes (partition 2 1) (map bridge-bearing) (apply union)))))))) (def prototype (delay)) (defn -main [& args] (let [parts (doall (filter (fn [arg] (let [groups (re-find #"--(no-)?(.*?)(=.*)?$" arg)] (if-let [[_ no k v] groups] (if-let [p (find-var (symbol "lagrange-keyboard.core" (cond-> k (not v) (str \?))))] (and (alter-var-root p (constantly (cond v (eval (read-string (subs v 1))) no false :else true))) false) (println (format "No parameter `%s'; ignoring `%s'." k arg))) true))) args)) xform #(->> %1 (translate [0 0 (- cover-thickness)]) (rotate [0 (%2 stand-tenting-angle) 0]) (translate [(- (%2 @stand-baseline-origin)) 0 0]))] (alter-var-root #'scad-clj.model/*fa* (constantly (if draft? 12 3))) (alter-var-root #'scad-clj.model/*fs* (constantly (if draft? 2 2/10))) (doseq [part parts] (case part "right" (spit "things/right.scad" (write-scad (assembly :right :top))) "right-cover" (spit "things/right-cover.scad" (write-scad (assembly :right :bottom))) "right-stand" (spit "things/right-stand.scad" (write-scad (xform (assembly :right :stand) +))) "right-boot" (spit "things/right-boot.scad" (write-scad (xform (assembly :right :boot) +))) "right-subassembly" (spit "things/right-subassembly.scad" (write-scad (assembly :right :top :bottom))) "right-assembly" (spit "things/right-assembly.scad" (write-scad (xform (assembly :right :top :bottom :stand) +))) "left" (spit "things/left.scad" (write-scad (assembly :left :top))) "left-cover" (spit "things/left-cover.scad" (write-scad (assembly :left :bottom))) "left-stand" (spit "things/left-stand.scad" (write-scad (xform (assembly :left :stand) -))) "left-boot" (spit "things/left-boot.scad" (write-scad (xform (assembly :left :boot) -))) "left-subassembly" (spit "things/left-subassembly.scad" (write-scad (assembly :left :top :bottom))) "left-assembly" (spit "things/left-assembly.scad" (write-scad (xform (assembly :left :top :bottom :stand) -))) "custom-assembly" (spit "things/custom-assembly.scad" (write-scad (assembly :right :bottom :stand))) "prototype" (spit "things/prototype.scad" (write-scad @prototype)) (cond (clojure.string/starts-with? part "bridge/") (let [subpart (subs part 7) scad (case subpart "bracket" @bridge-cable-bracket "left-mount" (assembly :left :bridge) "right-mount" (assembly :right :bridge) "toe-fork" (let [[x l φ] bridge-toe-fork] (rod-end x l, :fork φ)) "toe-eye" (let [[x l φ] bridge-toe-eye] (rod-end :fixed l, :eye φ)) "separation-fork" (let [[x l φ] bridge-separation-fork] (rod-end x l, :fork φ 2)) (println (format "No part `%s'." subpart)))] (when scad (spit "things/bridge.scad" (write-scad scad)))) (clojure.string/starts-with? part "misc/") (let [ subpart (subs part 5) scad (case subpart "bracket" pcb-harness-bracket "oem-1u-recessed" (apply printable-keycap [1 1] keycap-family-oem-recessed) "oem-1u" (apply printable-keycap [1 1] keycap-family-oem-flush) "oem-1.5u" (apply printable-keycap [3/2 1] keycap-family-oem-flush) "oem-1.5u-recessed" (apply printable-keycap [3/2 1] keycap-family-oem-recessed) "dsa-1u-convex" (apply printable-keycap [1 1] keycap-family-dsa-convex) "dsa-1u-concave" (apply printable-keycap [1 1] keycap-family-dsa-concave) "dsa-1.25u-convex" (apply printable-keycap [1 5/4] keycap-family-dsa-convex) "dsa-1.5u-convex" (apply printable-keycap [1 3/2] keycap-family-dsa-convex) "dsa-1.5u-convex-homing" (apply printable-keycap [1 3/2] :homing-bar-height 1/4 keycap-family-dsa-convex) "sa-1.5u-concave" (apply printable-keycap [3/2 1] keycap-family-sa-concave) "sa-1.5u-saddle" (apply printable-keycap [3/2 1] keycap-family-sa-saddle) "dsa-1u-fanged" (apply printable-keycap [0.95 1] keycap-family-dsa-fanged) (println (format "No part `%s'." subpart)))] (when scad (spit "things/misc.scad" (write-scad scad)))) :else (println (format "No part `%s'." part)))))))
880f0ef7025dcc24e05052f6207c2126683f924acd4a90f0b3633de1ebb37cba
baig/pandoc-csv2table
Definition.hs
The MIT License ( MIT ) Copyright ( c ) 2015 < > 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 . The MIT License (MIT) Copyright (c) 2015 Wasif Hasan Baig <> 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 : Text . Table . Definition Copyright : Copyright ( C ) 2015 License : MIT Maintainer : < > Stability : alpha Definition of ' Table ' data structure for internal representation . Module : Text.Table.Definition Copyright : Copyright (C) 2015 Wasif Hasan Baig License : MIT Maintainer : Venkateswara Rao Mandela <> Stability : alpha Definition of 'Table' data structure for internal representation. -} module Text.Table.Definition ( TableType (..) , CaptionPos (..) , Align (..) , Cell (..) , Row (..) , Column (..) , Header (..) , Table (..) , Span , Width , Gutter , Lines , Caption , AtrName , AtrValue , Atrs ) where -- Type synonyms type Span = Int type Width = Int type Gutter = Int type Lines = [String] type Caption = String type AtrName = String type AtrValue = String type Atrs = [(AtrName, AtrValue)] -- Data Definitions -- | Type of the 'Table'. data TableType = Simple -- Simple Table | Multiline -- Multiline Table | Grid -- Grid Table | Pipe -- Pipe Table deriving (Eq, Show) -- | Position of the caption. data CaptionPos = BeforeTable -- Insert caption before table markdown. | AfterTable -- Insert caption after table markdown. deriving (Show) -- | Alignment of a Column in the Table. -- Not all TableTypes support column alignments. Left Align Right Align | CenterAlign -- Center Align | DefaultAlign -- Default Align deriving (Show) -- | A cell in a table has column span, cell width, cell alignment and the -- number of lines. -- -- * __Span:__ Number of lines spanned by the cell. * _ _ : _ _ of the column this cell is contained inside -- * __Align:__ Alignment of the content inside the cells -- * __Lines:__ A list of strings where each string represents a line data Cell = Cell Span Width Align Lines deriving (Show) -- | A Row contains a list of Cells. data Row = Row [Cell] deriving (Show) -- | A Column contain information about its width and alignment. -- * _ _ : _ _ Character length of the widest ' Cell ' in a ' Column ' . -- * __Align:__ Alignment of the cells inside this column data Column = Column Width Align deriving (Show) | A Header contains a Row if present , otherwise NoHeader . data Header = Header Row | NoHeader deriving (Show) -- | A Table has a caption, information about each column's width and -- alignment, either a header with a row or no header, and a series of rows. data Table = Table Caption [Column] Header [Row] deriving (Show)
null
https://raw.githubusercontent.com/baig/pandoc-csv2table/297a466035191fc966edbade5044530d087a9632/src/Text/Table/Definition.hs
haskell
Type synonyms Data Definitions | Type of the 'Table'. Simple Table Multiline Table Grid Table Pipe Table | Position of the caption. Insert caption before table markdown. Insert caption after table markdown. | Alignment of a Column in the Table. Not all TableTypes support column alignments. Center Align Default Align | A cell in a table has column span, cell width, cell alignment and the number of lines. * __Span:__ Number of lines spanned by the cell. * __Align:__ Alignment of the content inside the cells * __Lines:__ A list of strings where each string represents a line | A Row contains a list of Cells. | A Column contain information about its width and alignment. * __Align:__ Alignment of the cells inside this column | A Table has a caption, information about each column's width and alignment, either a header with a row or no header, and a series of rows.
The MIT License ( MIT ) Copyright ( c ) 2015 < > 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 . The MIT License (MIT) Copyright (c) 2015 Wasif Hasan Baig <> 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 : Text . Table . Definition Copyright : Copyright ( C ) 2015 License : MIT Maintainer : < > Stability : alpha Definition of ' Table ' data structure for internal representation . Module : Text.Table.Definition Copyright : Copyright (C) 2015 Wasif Hasan Baig License : MIT Maintainer : Venkateswara Rao Mandela <> Stability : alpha Definition of 'Table' data structure for internal representation. -} module Text.Table.Definition ( TableType (..) , CaptionPos (..) , Align (..) , Cell (..) , Row (..) , Column (..) , Header (..) , Table (..) , Span , Width , Gutter , Lines , Caption , AtrName , AtrValue , Atrs ) where type Span = Int type Width = Int type Gutter = Int type Lines = [String] type Caption = String type AtrName = String type AtrValue = String type Atrs = [(AtrName, AtrValue)] deriving (Eq, Show) deriving (Show) Left Align Right Align deriving (Show) * _ _ : _ _ of the column this cell is contained inside data Cell = Cell Span Width Align Lines deriving (Show) data Row = Row [Cell] deriving (Show) * _ _ : _ _ Character length of the widest ' Cell ' in a ' Column ' . data Column = Column Width Align deriving (Show) | A Header contains a Row if present , otherwise NoHeader . data Header = Header Row | NoHeader deriving (Show) data Table = Table Caption [Column] Header [Row] deriving (Show)
f604a74b41dc15e0f0716cd20bc3dfa6c0de1e938691403cabed4be3a7fcb705
rjnw/sham
type.rkt
#lang racket (require "private/utils.rkt") (provide (all-defined-out))
null
https://raw.githubusercontent.com/rjnw/sham/6e0524b1eb01bcda83ae7a5be6339da4257c6781/sham-sam/sham/sam/syntax/type.rkt
racket
#lang racket (require "private/utils.rkt") (provide (all-defined-out))
440702d738c6274b13bcf3361a0ca52a37bc140c2f1ef6119440e3ef92ab6b7c
open-company/open-company-web
jwt.cljs
(ns oc.web.stores.jwt (:require [taoensso.timbre :as timbre] [oc.web.lib.jwt :as j] [oc.web.lib.cookies :as cook] [oc.web.dispatcher :as dispatcher])) JWT handling Store JWT in App DB so it can be easily accessed in actions etc . (defmethod dispatcher/action :jwt [db [_]] (let [jwt-data (j/get-contents)] (timbre/debug jwt-data) (as-> db tdb (if (cook/get-cookie :show-login-overlay) (assoc tdb dispatcher/show-login-overlay-key (keyword (cook/get-cookie :show-login-overlay))) tdb) (assoc tdb :jwt jwt-data)))) (defmethod dispatcher/action :id-token [db [_]] (let [jwt-data (j/get-id-token-contents) next-db (if (cook/get-cookie :show-login-overlay) (assoc db dispatcher/show-login-overlay-key (keyword (cook/get-cookie :show-login-overlay))) db)] (timbre/debug jwt-data) (assoc next-db :id-token jwt-data)))
null
https://raw.githubusercontent.com/open-company/open-company-web/dfce3dd9bc115df91003179bceb87cca1f84b6cf/src/main/oc/web/stores/jwt.cljs
clojure
(ns oc.web.stores.jwt (:require [taoensso.timbre :as timbre] [oc.web.lib.jwt :as j] [oc.web.lib.cookies :as cook] [oc.web.dispatcher :as dispatcher])) JWT handling Store JWT in App DB so it can be easily accessed in actions etc . (defmethod dispatcher/action :jwt [db [_]] (let [jwt-data (j/get-contents)] (timbre/debug jwt-data) (as-> db tdb (if (cook/get-cookie :show-login-overlay) (assoc tdb dispatcher/show-login-overlay-key (keyword (cook/get-cookie :show-login-overlay))) tdb) (assoc tdb :jwt jwt-data)))) (defmethod dispatcher/action :id-token [db [_]] (let [jwt-data (j/get-id-token-contents) next-db (if (cook/get-cookie :show-login-overlay) (assoc db dispatcher/show-login-overlay-key (keyword (cook/get-cookie :show-login-overlay))) db)] (timbre/debug jwt-data) (assoc next-db :id-token jwt-data)))
e3b3d0eec0f65877129c186ef74ecda33778fb15c0d521e23d28a63e6fc8f245
diku-dk/futhark
LSP.hs
# LANGUAGE ExplicitNamespaces # -- | @futhark lsp@ module Futhark.CLI.LSP (main) where import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.IORef (newIORef) import Futhark.LSP.Handlers (handlers) import Futhark.LSP.State (emptyState) import Language.LSP.Server import Language.LSP.Types ( SaveOptions (SaveOptions), TextDocumentSyncKind (TdSyncIncremental), TextDocumentSyncOptions (..), type (|?) (InR), ) -- | Run @futhark lsp@ main :: String -> [String] -> IO () main _prog _args = do state_mvar <- newIORef emptyState _ <- runServer $ ServerDefinition { onConfigurationChange = const $ const $ Right (), defaultConfig = (), doInitialize = \env _req -> pure $ Right env, staticHandlers = handlers state_mvar, interpretHandler = \env -> Iso (runLspT env) liftIO, options = defaultOptions { textDocumentSync = Just syncOptions } } pure () syncOptions :: TextDocumentSyncOptions syncOptions = TextDocumentSyncOptions { _openClose = Just True, _change = Just TdSyncIncremental, _willSave = Just False, _willSaveWaitUntil = Just False, _save = Just $ InR $ SaveOptions $ Just False }
null
https://raw.githubusercontent.com/diku-dk/futhark/98e4a75e4de7042afe030837084764bbf3c6c66e/src/Futhark/CLI/LSP.hs
haskell
| @futhark lsp@ | Run @futhark lsp@
# LANGUAGE ExplicitNamespaces # module Futhark.CLI.LSP (main) where import Control.Monad.IO.Class (MonadIO (liftIO)) import Data.IORef (newIORef) import Futhark.LSP.Handlers (handlers) import Futhark.LSP.State (emptyState) import Language.LSP.Server import Language.LSP.Types ( SaveOptions (SaveOptions), TextDocumentSyncKind (TdSyncIncremental), TextDocumentSyncOptions (..), type (|?) (InR), ) main :: String -> [String] -> IO () main _prog _args = do state_mvar <- newIORef emptyState _ <- runServer $ ServerDefinition { onConfigurationChange = const $ const $ Right (), defaultConfig = (), doInitialize = \env _req -> pure $ Right env, staticHandlers = handlers state_mvar, interpretHandler = \env -> Iso (runLspT env) liftIO, options = defaultOptions { textDocumentSync = Just syncOptions } } pure () syncOptions :: TextDocumentSyncOptions syncOptions = TextDocumentSyncOptions { _openClose = Just True, _change = Just TdSyncIncremental, _willSave = Just False, _willSaveWaitUntil = Just False, _save = Just $ InR $ SaveOptions $ Just False }
ee5ea78bb7c216b98eaf2563ebe35f445945f6bb048f10cb126785432283a0a7
cojna/iota
AffineSpec.hs
# LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -Wno - orphans # module Data.Monoid.AffineSpec (main, spec) where import Data.Monoid.Affine import Data.Proxy import Test.Prelude import Test.Prop.Monoid main :: IO () main = hspec spec spec :: Spec spec = do describe "Affine Int" $ monoidSpec (Proxy :: Proxy (Affine Int)) instance Arbitrary a => Arbitrary (Affine a) where arbitrary = Affine <$> arbitrary <*> arbitrary
null
https://raw.githubusercontent.com/cojna/iota/a64e8c5e4dd4f92e5ed3fcd0413be94ef1108f9e/test/Data/Monoid/AffineSpec.hs
haskell
# LANGUAGE ScopedTypeVariables # # OPTIONS_GHC -Wno - orphans # module Data.Monoid.AffineSpec (main, spec) where import Data.Monoid.Affine import Data.Proxy import Test.Prelude import Test.Prop.Monoid main :: IO () main = hspec spec spec :: Spec spec = do describe "Affine Int" $ monoidSpec (Proxy :: Proxy (Affine Int)) instance Arbitrary a => Arbitrary (Affine a) where arbitrary = Affine <$> arbitrary <*> arbitrary
ceeb4e215dfa8f0fa60d795be23859f0c01a811da7eff067a05e487e4473e541
christiaanb/clash
HardwareTypes.hs
# LANGUAGE TemplateHaskell , DeriveDataTypeable , RecordWildCards # module CLasH.HardwareTypes ( module Types , module Data.Param.Integer , module Data.Param.Vector , module Data.Param.Index , module Data.Param.Signed , module Data.Param.Unsigned , module Data.Bits , module Language.Haskell.TH.Lift , module Control.Arrow , module Control.Monad.Fix , module CLasH.Translator.Annotations , Bit(..) , State(..) , hwand , hwor , hwxor , hwnot , RAM , MemState , blockRAM , Clock(..) , pulseLength , Comp , simulate , (^^^) , comp , bv2u , u2bv , s2bv , bv2s , SimulatorSession , SimulationState , simulateM , run , runWithClock , setInput , setAndRun , getOutput , showOutput , assert , report ) where import Types import Data.Param.Integer (HWBits(..)) import Data.Param.Vector import Data.Param.Index import Data.Param.Signed import Data.Param.Unsigned import Data.Bits hiding (shiftL,shiftR) import qualified Data.Bits as B import Language.Haskell.TH.Lift import Data.Typeable import Control.Category (Category,(.),id) import Control.Arrow (Arrow,arr,first,ArrowLoop,loop,(>>>),returnA) import Control.Monad.Fix (mfix) import qualified Prelude as P import Prelude hiding (id, (.)) import qualified Data.Set as Set import qualified Data.List as L import qualified Control.Monad.Trans.State.Strict as State import qualified Data.Accessor.Template import qualified Data.Accessor.Monad.Trans.StrictState as MonadState import qualified Control.Monad.Trans.Class as Trans import CLasH.Translator.Annotations newtype State s = State s deriving (P.Show) -- The plain Bit type data Bit = High | Low deriving (P.Show, Eq, P.Read, Typeable) deriveLift ''Bit hwand :: Bit -> Bit -> Bit hwor :: Bit -> Bit -> Bit hwxor :: Bit -> Bit -> Bit hwnot :: Bit -> Bit High `hwand` High = High _ `hwand` _ = Low Low `hwor` Low = Low _ `hwor` _ = High High `hwxor` Low = High Low `hwxor` High = High _ `hwxor` _ = Low hwnot High = Low hwnot Low = High type RAM s a = Vector s a type MemState s a = State (RAM s a) blockRAM :: PositiveT s => MemState s a -> a -> Index s -> Index s -> Bool -> (MemState s a, a ) blockRAM (State mem) data_in rdaddr wraddr wrenable = ((State mem'), data_out) where data_out = mem!rdaddr -- Only write data_in to memory if write is enabled mem' = if wrenable then vreplace mem wraddr data_in else mem -- ============================== = Integer / Vector Conversions = -- ============================== -- =============== -- = Conversions = -- =============== bv2u :: NaturalT nT => Vector nT Bit -> Unsigned nT bv2u bv = vfoldl (\a b -> let a' = B.shiftL a 1 in if b == High then a' + 1 else a' ) 0 bv bv2s :: NaturalT nT => Vector nT Bit -> Signed nT bv2s bv = vfoldl (\a b -> let a' = B.shiftL a 1 in if b == High then a' + 1 else a' ) 0 bv u2bv :: NaturalT nT => Unsigned nT -> Vector nT Bit u2bv u = vreverse . (vmap fst) . (vgenerate f) $ (Low,(0,u)) where f (_,(n,u)) = if testBit u n then (High,(n+1,u)) else (Low,(n+1,u)) s2bv :: NaturalT nT => Signed nT -> Vector nT Bit s2bv u = vreverse . (vmap fst) . (vgenerate f) $ (Low,(0,u)) where f (_,(n,u)) = if testBit u n then (High,(n+1,u)) else (Low,(n+1,u)) -- ========== -- = Clocks = -- ========== data Clock = ClockUp Int | ClockDown Int deriving (Eq,Ord,Show) pulseLength (ClockUp i) = i pulseLength (ClockDown i) = i -- ================== = Automata Arrow = -- ================== data Comp i o = C { domain :: Set.Set Clock , exec :: Clock -> i -> (o, Comp i o) } instance Category Comp where k@(C { domain = cdA, exec = g}) . (C {domain = cdB, exec = f}) = C { domain = Set.union cdA cdB , exec = \clk b -> let (c,f') = f clk b (d,g') = g clk c in (d, g'.f') } id = arr id instance Arrow Comp where arr f = C { domain = Set.empty , exec = \clk b -> (f b, arr f) } first af = af { exec = \clk (b,d) -> let (c,f') = (exec af) clk b in ((c,d), first f') } instance ArrowLoop Comp where loop af = af { exec = (\clk i -> let ((c,d), f') = (exec af) clk (i, d) in (c, loop f')) } comp :: (State s -> i -> (State s,o)) -> s -> Clock -> Comp i o comp f initS clk = C { domain = Set.singleton clk , exec = \clk' i -> let (State s,o) = f (State initS) i s' | clk == clk' = s | otherwise = initS in (o, comp f s' clk) } liftS :: s -> (State s -> i -> (State s,o)) -> Comp i o liftS init f = C {domain = Set.singleton (ClockUp 1), exec = applyS} where applyS = \clk i -> let (State s,o) = f (State init) i in (o, liftS s f) (^^^) :: (State s -> i -> (State s,o)) -> s -> Comp i o (^^^) f init = liftS init f simulate :: Comp b c -> [b] -> [c] simulate af inps = if (Set.size $ domain af) < 2 then simulate' af (Set.findMin $ domain af) inps else error "Use simulateM for components with more than 1 clock" simulate' :: Comp b c -> Clock -> [b] -> [c] simulate' af _ [] = [] simulate' (C {exec = f}) clk (i:is) = let (o,f') = f clk i in (o : simulate' f' clk is) data SimulationState i o = SimulationState { clockTicks_ :: ([Clock],[Int]) , input_ :: i , hw_ :: Comp i o } Data.Accessor.Template.deriveAccessors ''SimulationState type SimulatorSession i o a = State.StateT (SimulationState i o) IO a simulateM :: Comp i o -> SimulatorSession i o () -> IO () simulateM hw testbench = State.evalStateT testbench initSession where initSession = SimulationState ((Set.toList $ domain hw), (replicate (Set.size $ domain hw) 1)) (error "CLasH.simulateM: initial simulation input not set") hw run :: Int -> SimulatorSession i o () run n = do (clocks,ticks) <- MonadState.get clockTicks let (pulses,newTicks) = runClocks (clocks,ticks) n MonadState.modify clockTicks (\(a,b) -> (a,newTicks)) curInp <- MonadState.get input MonadState.modify hw (snd . (run' pulses curInp)) runWithClock :: Clock -> Int -> SimulatorSession i o () runWithClock clk n = do curInp <- MonadState.get input MonadState.modify hw (snd . (run' (replicate n clk) curInp)) run' [] _ arch = ([],arch) run' (clk:clks) i (C {..}) = let (c,f') = clk `seq` exec clk i (cs,f'') = f' `seq` run' clks i f' in f'' `seq` (c:cs,f'') setInput :: i -> SimulatorSession i o () setInput i = MonadState.set input i setAndRun :: i -> Int -> SimulatorSession i o () setAndRun inp n = (setInput inp) >> (run n) getOutput :: SimulatorSession i o o getOutput = do curInp <- MonadState.get input arch <- MonadState.get hw return $ head $ fst $ run' [ClockUp (-1)] curInp arch showOutput :: (Show o) => SimulatorSession i o () showOutput = do outp <- getOutput Trans.lift $ putStrLn $ show outp assert :: (o -> Bool) -> String -> SimulatorSession i o () assert test msg = do outp <- getOutput if (test outp) then return () else Trans.lift $ putStrLn msg report :: String -> SimulatorSession i o () report msg = Trans.lift $ putStrLn msg runClocks :: ([Clock], [Int]) -> Int -> ([Clock],[Int]) runClocks (clocks, ticks) 0 = ([],ticks) runClocks (clocks, ticks) delta = ((concat curClocks) ++ nextClocks,nextTicks) where (curClocks,curTicks) = unzip $ zipWith clockTick clocks ticks (nextClocks,nextTicks) = runClocks (clocks,curTicks) (delta-1) clockTick (ClockUp i) i' = if i == i' then ([ClockUp i] ,1) else ([],i'+1) clockTick (ClockDown i) i' = if i == i' then ([ClockDown i],1) else ([],i'+1)
null
https://raw.githubusercontent.com/christiaanb/clash/18247975e8bbd3f903abc667285e11228a640457/clash/CLasH/HardwareTypes.hs
haskell
The plain Bit type Only write data_in to memory if write is enabled ============================== ============================== =============== = Conversions = =============== ========== = Clocks = ========== ================== ==================
# LANGUAGE TemplateHaskell , DeriveDataTypeable , RecordWildCards # module CLasH.HardwareTypes ( module Types , module Data.Param.Integer , module Data.Param.Vector , module Data.Param.Index , module Data.Param.Signed , module Data.Param.Unsigned , module Data.Bits , module Language.Haskell.TH.Lift , module Control.Arrow , module Control.Monad.Fix , module CLasH.Translator.Annotations , Bit(..) , State(..) , hwand , hwor , hwxor , hwnot , RAM , MemState , blockRAM , Clock(..) , pulseLength , Comp , simulate , (^^^) , comp , bv2u , u2bv , s2bv , bv2s , SimulatorSession , SimulationState , simulateM , run , runWithClock , setInput , setAndRun , getOutput , showOutput , assert , report ) where import Types import Data.Param.Integer (HWBits(..)) import Data.Param.Vector import Data.Param.Index import Data.Param.Signed import Data.Param.Unsigned import Data.Bits hiding (shiftL,shiftR) import qualified Data.Bits as B import Language.Haskell.TH.Lift import Data.Typeable import Control.Category (Category,(.),id) import Control.Arrow (Arrow,arr,first,ArrowLoop,loop,(>>>),returnA) import Control.Monad.Fix (mfix) import qualified Prelude as P import Prelude hiding (id, (.)) import qualified Data.Set as Set import qualified Data.List as L import qualified Control.Monad.Trans.State.Strict as State import qualified Data.Accessor.Template import qualified Data.Accessor.Monad.Trans.StrictState as MonadState import qualified Control.Monad.Trans.Class as Trans import CLasH.Translator.Annotations newtype State s = State s deriving (P.Show) data Bit = High | Low deriving (P.Show, Eq, P.Read, Typeable) deriveLift ''Bit hwand :: Bit -> Bit -> Bit hwor :: Bit -> Bit -> Bit hwxor :: Bit -> Bit -> Bit hwnot :: Bit -> Bit High `hwand` High = High _ `hwand` _ = Low Low `hwor` Low = Low _ `hwor` _ = High High `hwxor` Low = High Low `hwxor` High = High _ `hwxor` _ = Low hwnot High = Low hwnot Low = High type RAM s a = Vector s a type MemState s a = State (RAM s a) blockRAM :: PositiveT s => MemState s a -> a -> Index s -> Index s -> Bool -> (MemState s a, a ) blockRAM (State mem) data_in rdaddr wraddr wrenable = ((State mem'), data_out) where data_out = mem!rdaddr mem' = if wrenable then vreplace mem wraddr data_in else mem = Integer / Vector Conversions = bv2u :: NaturalT nT => Vector nT Bit -> Unsigned nT bv2u bv = vfoldl (\a b -> let a' = B.shiftL a 1 in if b == High then a' + 1 else a' ) 0 bv bv2s :: NaturalT nT => Vector nT Bit -> Signed nT bv2s bv = vfoldl (\a b -> let a' = B.shiftL a 1 in if b == High then a' + 1 else a' ) 0 bv u2bv :: NaturalT nT => Unsigned nT -> Vector nT Bit u2bv u = vreverse . (vmap fst) . (vgenerate f) $ (Low,(0,u)) where f (_,(n,u)) = if testBit u n then (High,(n+1,u)) else (Low,(n+1,u)) s2bv :: NaturalT nT => Signed nT -> Vector nT Bit s2bv u = vreverse . (vmap fst) . (vgenerate f) $ (Low,(0,u)) where f (_,(n,u)) = if testBit u n then (High,(n+1,u)) else (Low,(n+1,u)) data Clock = ClockUp Int | ClockDown Int deriving (Eq,Ord,Show) pulseLength (ClockUp i) = i pulseLength (ClockDown i) = i = Automata Arrow = data Comp i o = C { domain :: Set.Set Clock , exec :: Clock -> i -> (o, Comp i o) } instance Category Comp where k@(C { domain = cdA, exec = g}) . (C {domain = cdB, exec = f}) = C { domain = Set.union cdA cdB , exec = \clk b -> let (c,f') = f clk b (d,g') = g clk c in (d, g'.f') } id = arr id instance Arrow Comp where arr f = C { domain = Set.empty , exec = \clk b -> (f b, arr f) } first af = af { exec = \clk (b,d) -> let (c,f') = (exec af) clk b in ((c,d), first f') } instance ArrowLoop Comp where loop af = af { exec = (\clk i -> let ((c,d), f') = (exec af) clk (i, d) in (c, loop f')) } comp :: (State s -> i -> (State s,o)) -> s -> Clock -> Comp i o comp f initS clk = C { domain = Set.singleton clk , exec = \clk' i -> let (State s,o) = f (State initS) i s' | clk == clk' = s | otherwise = initS in (o, comp f s' clk) } liftS :: s -> (State s -> i -> (State s,o)) -> Comp i o liftS init f = C {domain = Set.singleton (ClockUp 1), exec = applyS} where applyS = \clk i -> let (State s,o) = f (State init) i in (o, liftS s f) (^^^) :: (State s -> i -> (State s,o)) -> s -> Comp i o (^^^) f init = liftS init f simulate :: Comp b c -> [b] -> [c] simulate af inps = if (Set.size $ domain af) < 2 then simulate' af (Set.findMin $ domain af) inps else error "Use simulateM for components with more than 1 clock" simulate' :: Comp b c -> Clock -> [b] -> [c] simulate' af _ [] = [] simulate' (C {exec = f}) clk (i:is) = let (o,f') = f clk i in (o : simulate' f' clk is) data SimulationState i o = SimulationState { clockTicks_ :: ([Clock],[Int]) , input_ :: i , hw_ :: Comp i o } Data.Accessor.Template.deriveAccessors ''SimulationState type SimulatorSession i o a = State.StateT (SimulationState i o) IO a simulateM :: Comp i o -> SimulatorSession i o () -> IO () simulateM hw testbench = State.evalStateT testbench initSession where initSession = SimulationState ((Set.toList $ domain hw), (replicate (Set.size $ domain hw) 1)) (error "CLasH.simulateM: initial simulation input not set") hw run :: Int -> SimulatorSession i o () run n = do (clocks,ticks) <- MonadState.get clockTicks let (pulses,newTicks) = runClocks (clocks,ticks) n MonadState.modify clockTicks (\(a,b) -> (a,newTicks)) curInp <- MonadState.get input MonadState.modify hw (snd . (run' pulses curInp)) runWithClock :: Clock -> Int -> SimulatorSession i o () runWithClock clk n = do curInp <- MonadState.get input MonadState.modify hw (snd . (run' (replicate n clk) curInp)) run' [] _ arch = ([],arch) run' (clk:clks) i (C {..}) = let (c,f') = clk `seq` exec clk i (cs,f'') = f' `seq` run' clks i f' in f'' `seq` (c:cs,f'') setInput :: i -> SimulatorSession i o () setInput i = MonadState.set input i setAndRun :: i -> Int -> SimulatorSession i o () setAndRun inp n = (setInput inp) >> (run n) getOutput :: SimulatorSession i o o getOutput = do curInp <- MonadState.get input arch <- MonadState.get hw return $ head $ fst $ run' [ClockUp (-1)] curInp arch showOutput :: (Show o) => SimulatorSession i o () showOutput = do outp <- getOutput Trans.lift $ putStrLn $ show outp assert :: (o -> Bool) -> String -> SimulatorSession i o () assert test msg = do outp <- getOutput if (test outp) then return () else Trans.lift $ putStrLn msg report :: String -> SimulatorSession i o () report msg = Trans.lift $ putStrLn msg runClocks :: ([Clock], [Int]) -> Int -> ([Clock],[Int]) runClocks (clocks, ticks) 0 = ([],ticks) runClocks (clocks, ticks) delta = ((concat curClocks) ++ nextClocks,nextTicks) where (curClocks,curTicks) = unzip $ zipWith clockTick clocks ticks (nextClocks,nextTicks) = runClocks (clocks,curTicks) (delta-1) clockTick (ClockUp i) i' = if i == i' then ([ClockUp i] ,1) else ([],i'+1) clockTick (ClockDown i) i' = if i == i' then ([ClockDown i],1) else ([],i'+1)
afa53327d85d6b9d410c5abceb449e687b6313ec19665fb8a4e70a2b6cf9322c
tweag/ormolu
main-and-foo-v2.hs
module Main (main) where main :: IO () main = pure () foo :: Int foo = 5
null
https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/diff-tests/inputs/main-and-foo-v2.hs
haskell
module Main (main) where main :: IO () main = pure () foo :: Int foo = 5
37c4c01673d2773b6f059fd1eb539df4afe2d29e60eb581eb145bb3827566047
racketscript/racketscript
lambda-flist.rkt
#lang racket/base (require "lib.rkt") (define add (λ vs (foldl + 0 vs))) (define add2 (λ (a b . c) (* (foldl + 0 c) a b))) (displayln (add 1 2 3 4 5)) (displayln (add2 1 2 3 4 5))
null
https://raw.githubusercontent.com/racketscript/racketscript/f94006d11338a674ae10f6bd83fc53e6806d07d8/tests/basic/lambda-flist.rkt
racket
#lang racket/base (require "lib.rkt") (define add (λ vs (foldl + 0 vs))) (define add2 (λ (a b . c) (* (foldl + 0 c) a b))) (displayln (add 1 2 3 4 5)) (displayln (add2 1 2 3 4 5))
5fb63cdd80f0e63caef1d26862db06524284597b4220530090964741584d7dac
libguestfs/virt-v2v
config.mli
virt - v2v * Copyright ( C ) 2019 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA * Copyright (C) 2019 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) val package_name : string (** The configure value [@PACKAGE_NAME@] *) val package_version : string (** The configure value [@PACKAGE_VERSION@] *) val package_version_full : string (** The configure value [@PACKAGE_VERSION_FULL@] *) val prefix : string * The configure value [ @prefix@ ] val datadir : string (** The configure value [@datadir@] *) val host_cpu : string * The configure value [ ] val nbdkit_python_plugin : string * Return the name of the nbdkit python plugin used by [ virt - v2v -o rhv - upload ] . As above this must also be the Python 3 version of the plugin , unless you change it . The configure command to change this is : [ ./configure --with - virt - v2v - nbdkit - python - plugin= ... ] [virt-v2v -o rhv-upload]. As above this must also be the Python 3 version of the plugin, unless you change it. The configure command to change this is: [./configure --with-virt-v2v-nbdkit-python-plugin=...] *)
null
https://raw.githubusercontent.com/libguestfs/virt-v2v/cff4514927b3e12a30619377149789c5bd2daebb/lib/config.mli
ocaml
* The configure value [@PACKAGE_NAME@] * The configure value [@PACKAGE_VERSION@] * The configure value [@PACKAGE_VERSION_FULL@] * The configure value [@datadir@]
virt - v2v * Copyright ( C ) 2019 Red Hat Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation ; either version 2 of the License , or * ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU General Public License for more details . * * You should have received a copy of the GNU General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA * Copyright (C) 2019 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) val package_name : string val package_version : string val package_version_full : string val prefix : string * The configure value [ @prefix@ ] val datadir : string val host_cpu : string * The configure value [ ] val nbdkit_python_plugin : string * Return the name of the nbdkit python plugin used by [ virt - v2v -o rhv - upload ] . As above this must also be the Python 3 version of the plugin , unless you change it . The configure command to change this is : [ ./configure --with - virt - v2v - nbdkit - python - plugin= ... ] [virt-v2v -o rhv-upload]. As above this must also be the Python 3 version of the plugin, unless you change it. The configure command to change this is: [./configure --with-virt-v2v-nbdkit-python-plugin=...] *)
d992c0334dab40a78a605a955262efd8037a7f43641cfda0a074ed54e43524a8
ZHaskell/z-http
Server.hs
module Z.HTTP.Server where import Z.Data.HTTP.Request import Z.IO.Network import Z.IO type ServerLoop = (UVStream -> IO ()) -> IO () data HTTPServerConfig = HTTPServerConfig { httpSendBufSiz :: Int , httpRecvBufSiz :: Int } defaultHTTPServerConfig :: HTTPServerConfig defaultHTTPServerConfig = HTTPServerConfig defaultChunkSize defaultChunkSize runHTTPServer' :: ServerLoop -> HTTPServerConfig -> (Request -> IO ()) -> IO () runHTTPServer' loop conf@HTTPServerConfig{..} worker = loop $ \ uvs -> do remoteAddr <- getTCPPeerName uvs bi <- newBufferedInput' httpSendBufSiz uvs bo <- newBufferedOutput' httpSendBufSiz uvs req <- readRequest remoteAddr False bi return ()
null
https://raw.githubusercontent.com/ZHaskell/z-http/db37c69d3632bf0730640362604f4015556fd14c/Z/HTTP/Server.hs
haskell
module Z.HTTP.Server where import Z.Data.HTTP.Request import Z.IO.Network import Z.IO type ServerLoop = (UVStream -> IO ()) -> IO () data HTTPServerConfig = HTTPServerConfig { httpSendBufSiz :: Int , httpRecvBufSiz :: Int } defaultHTTPServerConfig :: HTTPServerConfig defaultHTTPServerConfig = HTTPServerConfig defaultChunkSize defaultChunkSize runHTTPServer' :: ServerLoop -> HTTPServerConfig -> (Request -> IO ()) -> IO () runHTTPServer' loop conf@HTTPServerConfig{..} worker = loop $ \ uvs -> do remoteAddr <- getTCPPeerName uvs bi <- newBufferedInput' httpSendBufSiz uvs bo <- newBufferedOutput' httpSendBufSiz uvs req <- readRequest remoteAddr False bi return ()
3aba0f8198fb420b5ed67c9d41e2d27cc8b45fe3a4b9045639840115a229f443
kmi/irs
new.lisp
Mode : Lisp ; Package : File created in WebOnto (in-package "OCML") (in-ontology luisa-wsmo-descriptions) (def-class actor () ((has-actor-id :type integer) (has-actor-name :type string)) ) (def-class learner (actor) ((has-learner-history :type learning-object-list) (has-competency-demand :type competency-list) (has-language :type language) (has-competencies :type competency-list) (has-max-cost :type cost)) ) (def-class cost () ((has-amount :type float) (has-currency :type currency)) ) (def-class currency () ((has-currency-code :type string) (has-currency-title :type string)) ) (def-class learning-object () ((has-related-learning-objects :type learning-object-list) (has-approximate-learning-time :type integer) (has-language :type language) (has-required-competencies :type competency-list) (has-competency :type competency) (has-cost :type cost) (has-relation-partof :type learning-object) (has-relation-haspart :type learning-object) (has-title :type string) (has-id :type integer) (has-lom-set :type lom-learning-object)) ) (def-class competency () ((has-required-competencies :type competency-list) (has-related-competencies :type competency-list) (has-competency-id :type integer) (has-competency-title :type string)) ) (def-class competency-list () ((has-competencies :type competency :min-cardinality 1)) ) (def-class get-lo-list-response () ((has-retrieved-learning-object-list :type learning-object-list)) ) (def-class learning-object-list () ((has-learning-objects :type learning-object :min-cardinality 1)) ) (def-class get-lo-by-competency-request () ((has-competency-request :type string)) ) (def-class get-lo-by-competency-response () ((has-learning-object :type string)) ) (def-class get-lo-results-by-competency-request () ((has-competency-request :type competency) (has-learner :type learner)) ) (def-class processed-lo-results () ((has-learner :type learner) (has-missing-competencies :type competency-list) (has-user-ability :type boolean) (has-lo-list :type learning-object-list)) ) (def-class get-lo-results-by-competency-response () ((has-processed-lo-results :type processed-lo-results)) ) (def-class language () ((has-language-id :type integer) (has-language-title :type string)) ) (def-class get-lo-by-requester-request () ((has-requester :type learner)) ) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-GOAL-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-GOAL (GOAL) ?GOAL ((HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-GOAL-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR (WG-MEDIATOR) ?MEDIATOR ((HAS-SOURCE-COMPONENT :VALUE LUISA-GET-L-O-BY-COMPETENCY-GOAL) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE (WEB-SERVICE) ?WEB-SERVICE ((HAS-CAPABILITY :VALUE LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY) (HAS-INTERFACE :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE) (USED-MEDIATOR :VALUE LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY (CAPABILITY) ?CAPABILITY ((USED-MEDIATOR :VALUE LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-CHOREOGRAPHY (CHOREOGRAPHY) ((HAS-GROUNDING :VALUE ((GROUNDED-TO-LISP (NORMAL DUMMY-METHOD)))))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION-PROBLEM-SOLVING-PATTERN (PROBLEM-SOLVING-PATTERN) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION (ORCHESTRATION) ((HAS-PROBLEM-SOLVING-PATTERN :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION-PROBLEM-SOLVING-PATTERN))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE (INTERFACE) ?INTERFACE ((HAS-CHOREOGRAPHY :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-CHOREOGRAPHY) (HAS-ORCHESTRATION :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-PUBLISHER-INFORMATION (PUBLISHER-INFORMATION) ((HAS-ASSOCIATED-WEB-SERVICE-INTERFACE :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE) (HAS-WEB-SERVICE-HOST :VALUE "137.108.25.167") (HAS-WEB-SERVICE-PORT :VALUE 3001) (HAS-WEB-SERVICE-LOCATION :VALUE "/soap")))
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/luisa-wsmo-descriptions/new.lisp
lisp
Package :
File created in WebOnto (in-package "OCML") (in-ontology luisa-wsmo-descriptions) (def-class actor () ((has-actor-id :type integer) (has-actor-name :type string)) ) (def-class learner (actor) ((has-learner-history :type learning-object-list) (has-competency-demand :type competency-list) (has-language :type language) (has-competencies :type competency-list) (has-max-cost :type cost)) ) (def-class cost () ((has-amount :type float) (has-currency :type currency)) ) (def-class currency () ((has-currency-code :type string) (has-currency-title :type string)) ) (def-class learning-object () ((has-related-learning-objects :type learning-object-list) (has-approximate-learning-time :type integer) (has-language :type language) (has-required-competencies :type competency-list) (has-competency :type competency) (has-cost :type cost) (has-relation-partof :type learning-object) (has-relation-haspart :type learning-object) (has-title :type string) (has-id :type integer) (has-lom-set :type lom-learning-object)) ) (def-class competency () ((has-required-competencies :type competency-list) (has-related-competencies :type competency-list) (has-competency-id :type integer) (has-competency-title :type string)) ) (def-class competency-list () ((has-competencies :type competency :min-cardinality 1)) ) (def-class get-lo-list-response () ((has-retrieved-learning-object-list :type learning-object-list)) ) (def-class learning-object-list () ((has-learning-objects :type learning-object :min-cardinality 1)) ) (def-class get-lo-by-competency-request () ((has-competency-request :type string)) ) (def-class get-lo-by-competency-response () ((has-learning-object :type string)) ) (def-class get-lo-results-by-competency-request () ((has-competency-request :type competency) (has-learner :type learner)) ) (def-class processed-lo-results () ((has-learner :type learner) (has-missing-competencies :type competency-list) (has-user-ability :type boolean) (has-lo-list :type learning-object-list)) ) (def-class get-lo-results-by-competency-response () ((has-processed-lo-results :type processed-lo-results)) ) (def-class language () ((has-language-id :type integer) (has-language-title :type string)) ) (def-class get-lo-by-requester-request () ((has-requester :type learner)) ) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-GOAL-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-GOAL (GOAL) ?GOAL ((HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-GOAL-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR (WG-MEDIATOR) ?MEDIATOR ((HAS-SOURCE-COMPONENT :VALUE LUISA-GET-L-O-BY-COMPETENCY-GOAL) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE (WEB-SERVICE) ?WEB-SERVICE ((HAS-CAPABILITY :VALUE LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY) (HAS-INTERFACE :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE) (USED-MEDIATOR :VALUE LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY (CAPABILITY) ?CAPABILITY ((USED-MEDIATOR :VALUE LUISA-GET-L-O-BY-COMPETENCY-MEDIATOR) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-W-S-CAPABILITY-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-NON-FUNCTIONAL-PROPERTIES (NON-FUNCTIONAL-PROPERTIES) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-CHOREOGRAPHY (CHOREOGRAPHY) ((HAS-GROUNDING :VALUE ((GROUNDED-TO-LISP (NORMAL DUMMY-METHOD)))))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION-PROBLEM-SOLVING-PATTERN (PROBLEM-SOLVING-PATTERN) NIL) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION (ORCHESTRATION) ((HAS-PROBLEM-SOLVING-PATTERN :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION-PROBLEM-SOLVING-PATTERN))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE (INTERFACE) ?INTERFACE ((HAS-CHOREOGRAPHY :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-CHOREOGRAPHY) (HAS-ORCHESTRATION :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-ORCHESTRATION) (HAS-NON-FUNCTIONAL-PROPERTIES :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE-NON-FUNCTIONAL-PROPERTIES))) (DEF-CLASS LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-PUBLISHER-INFORMATION (PUBLISHER-INFORMATION) ((HAS-ASSOCIATED-WEB-SERVICE-INTERFACE :VALUE LUISA-GET-L-O-BY-COMPETENCY-WEB-SERVICE-INTERFACE) (HAS-WEB-SERVICE-HOST :VALUE "137.108.25.167") (HAS-WEB-SERVICE-PORT :VALUE 3001) (HAS-WEB-SERVICE-LOCATION :VALUE "/soap")))
43d1478a837ce3c6584170f233e63425286b67ad561a6502f00a43deda55d56d
rtrusso/scp
sasm-nasmx86.scm
;; sasm-nasmx86.scm SASM Machine Description - x86 on the NASM assembler (need sasm/sasm-tx) (need sasm/nasmx86/util) (need sasm/nasmx86/binop) (need sasm/nasmx86/interp) (need sasm/nasmx86/labels) (need sasm/nasmx86/control) (need sasm/nasmx86/compare) (need sasm/nasmx86/stack) (need sasm/nasmx86/store-array) (need sasm/nasmx86/load-array) (need sasm/nasmx86/call) (need sasm/nasmx86/return) (need sasm/nasmx86/arithmetic) (need sasm/nasmx86/mul) (need sasm/nasmx86/bitwise-const) (need sasm/nasmx86/shift) (need sasm/nasmx86/data) (need sasm/nasmx86/preamble) (need sasm/nasmx86/debug) (need sasm/nasmx86/base) (need sasm/nasmx86/machine) (define (sasm-set-target-x86!) (sasm-set-target! 'nasm-x86 nasm-x86-registers nasm-x86-sys-registers (nasm-x86-machine))) (define (sasm-set-x86-hw-params!) (sasm-symconst-alist-append '((cells-per-word 4) (shift-cells-per-word 2) (mask-cells-per-word 3) (bits-per-word 32) (shift-bits-per-word 5) (mask-bits-per-word 31))))
null
https://raw.githubusercontent.com/rtrusso/scp/2051e76df14bd36aef81aba519ffafa62b260f5c/src/sasm/sasm-nasmx86.scm
scheme
sasm-nasmx86.scm
SASM Machine Description - x86 on the NASM assembler (need sasm/sasm-tx) (need sasm/nasmx86/util) (need sasm/nasmx86/binop) (need sasm/nasmx86/interp) (need sasm/nasmx86/labels) (need sasm/nasmx86/control) (need sasm/nasmx86/compare) (need sasm/nasmx86/stack) (need sasm/nasmx86/store-array) (need sasm/nasmx86/load-array) (need sasm/nasmx86/call) (need sasm/nasmx86/return) (need sasm/nasmx86/arithmetic) (need sasm/nasmx86/mul) (need sasm/nasmx86/bitwise-const) (need sasm/nasmx86/shift) (need sasm/nasmx86/data) (need sasm/nasmx86/preamble) (need sasm/nasmx86/debug) (need sasm/nasmx86/base) (need sasm/nasmx86/machine) (define (sasm-set-target-x86!) (sasm-set-target! 'nasm-x86 nasm-x86-registers nasm-x86-sys-registers (nasm-x86-machine))) (define (sasm-set-x86-hw-params!) (sasm-symconst-alist-append '((cells-per-word 4) (shift-cells-per-word 2) (mask-cells-per-word 3) (bits-per-word 32) (shift-bits-per-word 5) (mask-bits-per-word 31))))
ad1d60af8b8353397b728e69335114ce776fd74a2767baf1dfa30e23f021c8b6
andrejbauer/plzoo
syntax.ml
(** Abstract syntax *) (** The type of identifiers *) type name = string (** Arithmetical operations *) type arithop = Plus | Minus | Times | Divide | Remainder (** Comparisons *) type cmpop = Less | Equal | Unequal (** Logical operators *) type boolop = And | Or (** Expressions *) type expr = | Var of name (** variable *) | Bool of bool (** boolean constant [true] or [false] *) | Int of int (** integer constant *) * arithmetical operation [ e1 op e2 ] | Not of expr (** logical negation [not e] *) | CmpOp of cmpop * expr * expr (** comparison [e1 cmp e2] *) * logical operator [ e1 op e2 ] | If of expr * expr * expr (** conditional statement [if e1 then e2 else e3] *) | Skip (** command [skip], does nothing *) | Seq of expr * expr (** sequencing of expressions [e1; e2] *) | Let of name * expr * expr (** local definition [let x = e1 in e2] *) | App of expr * expr (** application [e1 e2] *) | Fun of name * expr (** function [fun x -> e] *) | This (** the object [this] *) | Object of (name * expr) list (** object with given attributes [{a1=e1, ..., an=en}] *) | Copy of expr (** (shallow) copy of an object [copy e] *) | With of expr * expr (** object extension [e1 with e2] *) | Project of expr * name (** attribute projection [e.x] *) | Assign of expr * name * expr (** set the value of an attribute [e1.x := e2] *) * Toplevel commands type toplevel_cmd = | Expr of expr (** Expression to be evaluated *) | Def of name * expr (** Global definition [let x = e] *)
null
https://raw.githubusercontent.com/andrejbauer/plzoo/ae6041c65baf1eebf65a60617819efeb8dcd3420/src/boa/syntax.ml
ocaml
* Abstract syntax * The type of identifiers * Arithmetical operations * Comparisons * Logical operators * Expressions * variable * boolean constant [true] or [false] * integer constant * logical negation [not e] * comparison [e1 cmp e2] * conditional statement [if e1 then e2 else e3] * command [skip], does nothing * sequencing of expressions [e1; e2] * local definition [let x = e1 in e2] * application [e1 e2] * function [fun x -> e] * the object [this] * object with given attributes [{a1=e1, ..., an=en}] * (shallow) copy of an object [copy e] * object extension [e1 with e2] * attribute projection [e.x] * set the value of an attribute [e1.x := e2] * Expression to be evaluated * Global definition [let x = e]
type name = string type arithop = Plus | Minus | Times | Divide | Remainder type cmpop = Less | Equal | Unequal type boolop = And | Or type expr = * arithmetical operation [ e1 op e2 ] * logical operator [ e1 op e2 ] * Toplevel commands type toplevel_cmd =
5efc1d477f6f87de0100353d4cb39d3d75dc7fe3c93a41b7efdc440c8dcb7ee4
Clozure/ccl
group.lisp
;;; -*- Log: hemlock.log; Package: Hemlock -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; #+CMU (ext:file-comment "$Header$") ;;; ;;; ********************************************************************** ;;; File group stuff for Hemlock . Written by and . ;;; The " Compile Group " and " List Compile Group " commands in lispeval ;;; also know about groups. ;;; This file provides Hemlock commands for manipulating groups of files ;;; that make up a larger system. A file group is a set of files whose names are listed in some other file . At any given time one group of files is the Active group . The Select Group command makes a group the ;;; Active group, prompting for the name of a definition file if the group ;;; has not been selected before. Once a group has been selected once, the ;;; name of the definition file associated with that group is retained. If ;;; one wishes to change the name of the definition file after a group has been selected , one should call Select Group with a prefix argument . (in-package :hemlock) (defvar *file-groups* (make-string-table) "A string table of file groups.") (defvar *active-file-group* () "The list of files in the currently active group.") (defvar *active-file-group-name* () "The name of the currently active group.") ;;;; Selecting the active group. (defcommand "Select Group" (p) "Makes a group the active group. With a prefix argument, changes the definition file associated with the group." "Makes a group the active group." (let* ((group-name (prompt-for-keyword (list *file-groups*) :must-exist nil :prompt "Select Group: " :help "Type the name of the file group you wish to become the active group.")) (old (getstring group-name *file-groups*)) (pathname (if (and old (not p)) old (prompt-for-file :must-exist t :prompt "From File: " :default (merge-pathnames (make-pathname :name group-name :type "upd") (value pathname-defaults)))))) (setq *active-file-group-name* group-name) (setq *active-file-group* (nreverse (read-file-group pathname nil))) (setf (getstring group-name *file-groups*) pathname))) READ - FILE - GROUP reads an Update format file and returns a list of pathnames ;;; of the files named in that file. This guy knows about @@ indirection and ;;; ignores empty lines and lines that begin with @ but not @@. A simpler ;;; scheme could be used for non-Spice implementations, but all this hair is ;;; probably useful, so Update format may as well be a standard for this sort ;;; of thing. ;;; (defun read-file-group (pathname tail) (with-open-file (file pathname) (do* ((name (read-line file nil nil) (read-line file nil nil)) (length (if name (length name)) (if name (length name)))) ((null name) tail) (declare (type (or simple-string null) name)) (cond ((zerop length)) ((char= (char name 0) #\@) (when (and (> length 1) (char= (char name 1) #\@)) (setq tail (read-file-group (merge-pathnames (subseq name 2) pathname) tail)))) (t (push (merge-pathnames (pathname name) pathname) tail)))))) ;;;; DO-ACTIVE-GROUP. (defhvar "Group Find File" "If true, group commands use \"Find File\" to read files, otherwise non-resident files are read into the \"Group Search\" buffer." :value nil) (defhvar "Group Save File Confirm" "If true, then the group commands will ask for confirmation before saving a modified file." :value t) (defmacro do-active-group (&rest forms) "This iterates over the active file group executing forms once for each file. When forms are executed, the file will be in the current buffer, and the point will be at the start of the file." (let ((n-buf (gensym)) (n-start-buf (gensym)) (n-save (gensym))) `(progn (unless *active-file-group* (editor-error "There is no active file group.")) (let ((,n-start-buf (current-buffer)) (,n-buf nil)) (unwind-protect (dolist (file *active-file-group*) (catch 'file-not-found (setq ,n-buf (group-read-file file ,n-buf)) (with-mark ((,n-save (current-point) :right-inserting)) (unwind-protect (progn (buffer-start (current-point)) ,@forms) (move-mark (current-point) ,n-save))) (group-save-file))) (if (member ,n-start-buf *buffer-list*) (setf (current-buffer) ,n-start-buf (window-buffer (current-window)) ,n-start-buf) (editor-error "Original buffer deleted!"))))))) ;;; GROUP-READ-FILE reads in files for the group commands via DO-ACTIVE-GROUP. ;;; We use FIND-FILE-BUFFER, which creates a new buffer when the file hasn't ;;; already been read, to get files in, and then we delete the buffer if it is newly created and " Group Find File " is false . This lets FIND - FILE - BUFFER do all the work . We do n't actually use the " Find File " command , so the ;;; buffer history isn't affected. ;;; Search - Buffer is any temporary search buffer left over from the last file ;;; that we want deleted. We don't do the deletion if the buffer is modified. ;;; (defun group-read-file (name search-buffer) (unless (probe-file name) (message "File ~A not found." name) (throw 'file-not-found nil)) (multiple-value-bind (buffer created-p) (find-file-buffer name) (setf (current-buffer) buffer) (setf (window-buffer (current-window)) buffer) (when (and search-buffer (not (buffer-modified search-buffer))) (dolist (w (buffer-windows search-buffer)) (setf (window-buffer w) (current-buffer))) (delete-buffer search-buffer)) (if (and created-p (not (value group-find-file))) (current-buffer) nil))) ;;; GROUP-SAVE-FILE is used by DO-ACTIVE-GROUP. ;;; (defun group-save-file () (let* ((buffer (current-buffer)) (pn (buffer-pathname buffer)) (name (namestring pn))) (when (and (buffer-modified buffer) (or (not (value group-save-file-confirm)) (prompt-for-y-or-n :prompt (list "Save changes in ~A? " name) :default t))) (save-file-command ())))) ;;;; Searching and Replacing commands. (defcommand "Group Search" (p) "Searches the active group for a specified string, which is prompted for." "Searches the active group for a specified string." (declare (ignore p)) (let ((string (prompt-for-string :prompt "Group Search: " :help "String to search for in active file group" :default *last-search-string*))) (get-search-pattern string :forward) (do-active-group (do ((won (find-pattern (current-point) *last-search-pattern*) (find-pattern (current-point) *last-search-pattern*))) ((not won)) (character-offset (current-point) won) (command-case (:prompt "Group Search: " :help "Type a character indicating the action to perform." :change-window nil) (:no "Search for the next occurrence.") (:do-all "Go on to the next file in the group." (return nil)) ((:exit :yes) "Exit the search." (return-from group-search-command)) (:recursive-edit "Enter a recursive edit." (do-recursive-edit) (get-search-pattern string :forward))))) (message "All files in group ~S searched." *active-file-group-name*))) (defcommand "Group Replace" (p) "Replaces one string with another in the active file group." "Replaces one string with another in the active file group." (declare (ignore p)) (let* ((target (prompt-for-string :prompt "Group Replace: " :help "Target string" :default *last-search-string*)) (replacement (prompt-for-string :prompt "With: " :help "Replacement string"))) (do-active-group (query-replace-function nil target replacement "Group Replace on previous file" t)) (message "Replacement done in all files in group ~S." *active-file-group-name*))) (defcommand "Group Query Replace" (p) "Query Replace for the active file group." "Query Replace for the active file group." (declare (ignore p)) (let ((target (prompt-for-string :prompt "Group Query Replace: " :help "Target string" :default *last-search-string*))) (let ((replacement (prompt-for-string :prompt "With: " :help "Replacement string"))) (do-active-group (unless (query-replace-function nil target replacement "Group Query Replace on previous file") (return nil))) (message "Replacement done in all files in group ~S." *active-file-group-name*))))
null
https://raw.githubusercontent.com/Clozure/ccl/6c1a9458f7a5437b73ec227e989aa5b825f32fd3/cocoa-ide/hemlock/unused/archive/group.lisp
lisp
-*- Log: hemlock.log; Package: Hemlock -*- ********************************************************************** ********************************************************************** also know about groups. that make up a larger system. A file group is a set of files whose Active group, prompting for the name of a definition file if the group has not been selected before. Once a group has been selected once, the name of the definition file associated with that group is retained. If one wishes to change the name of the definition file after a group has Selecting the active group. of the files named in that file. This guy knows about @@ indirection and ignores empty lines and lines that begin with @ but not @@. A simpler scheme could be used for non-Spice implementations, but all this hair is probably useful, so Update format may as well be a standard for this sort of thing. DO-ACTIVE-GROUP. GROUP-READ-FILE reads in files for the group commands via DO-ACTIVE-GROUP. We use FIND-FILE-BUFFER, which creates a new buffer when the file hasn't already been read, to get files in, and then we delete the buffer if it is buffer history isn't affected. that we want deleted. We don't do the deletion if the buffer is modified. GROUP-SAVE-FILE is used by DO-ACTIVE-GROUP. Searching and Replacing commands.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . #+CMU (ext:file-comment "$Header$") File group stuff for Hemlock . Written by and . The " Compile Group " and " List Compile Group " commands in lispeval This file provides Hemlock commands for manipulating groups of files names are listed in some other file . At any given time one group of files is the Active group . The Select Group command makes a group the been selected , one should call Select Group with a prefix argument . (in-package :hemlock) (defvar *file-groups* (make-string-table) "A string table of file groups.") (defvar *active-file-group* () "The list of files in the currently active group.") (defvar *active-file-group-name* () "The name of the currently active group.") (defcommand "Select Group" (p) "Makes a group the active group. With a prefix argument, changes the definition file associated with the group." "Makes a group the active group." (let* ((group-name (prompt-for-keyword (list *file-groups*) :must-exist nil :prompt "Select Group: " :help "Type the name of the file group you wish to become the active group.")) (old (getstring group-name *file-groups*)) (pathname (if (and old (not p)) old (prompt-for-file :must-exist t :prompt "From File: " :default (merge-pathnames (make-pathname :name group-name :type "upd") (value pathname-defaults)))))) (setq *active-file-group-name* group-name) (setq *active-file-group* (nreverse (read-file-group pathname nil))) (setf (getstring group-name *file-groups*) pathname))) READ - FILE - GROUP reads an Update format file and returns a list of pathnames (defun read-file-group (pathname tail) (with-open-file (file pathname) (do* ((name (read-line file nil nil) (read-line file nil nil)) (length (if name (length name)) (if name (length name)))) ((null name) tail) (declare (type (or simple-string null) name)) (cond ((zerop length)) ((char= (char name 0) #\@) (when (and (> length 1) (char= (char name 1) #\@)) (setq tail (read-file-group (merge-pathnames (subseq name 2) pathname) tail)))) (t (push (merge-pathnames (pathname name) pathname) tail)))))) (defhvar "Group Find File" "If true, group commands use \"Find File\" to read files, otherwise non-resident files are read into the \"Group Search\" buffer." :value nil) (defhvar "Group Save File Confirm" "If true, then the group commands will ask for confirmation before saving a modified file." :value t) (defmacro do-active-group (&rest forms) "This iterates over the active file group executing forms once for each file. When forms are executed, the file will be in the current buffer, and the point will be at the start of the file." (let ((n-buf (gensym)) (n-start-buf (gensym)) (n-save (gensym))) `(progn (unless *active-file-group* (editor-error "There is no active file group.")) (let ((,n-start-buf (current-buffer)) (,n-buf nil)) (unwind-protect (dolist (file *active-file-group*) (catch 'file-not-found (setq ,n-buf (group-read-file file ,n-buf)) (with-mark ((,n-save (current-point) :right-inserting)) (unwind-protect (progn (buffer-start (current-point)) ,@forms) (move-mark (current-point) ,n-save))) (group-save-file))) (if (member ,n-start-buf *buffer-list*) (setf (current-buffer) ,n-start-buf (window-buffer (current-window)) ,n-start-buf) (editor-error "Original buffer deleted!"))))))) newly created and " Group Find File " is false . This lets FIND - FILE - BUFFER do all the work . We do n't actually use the " Find File " command , so the Search - Buffer is any temporary search buffer left over from the last file (defun group-read-file (name search-buffer) (unless (probe-file name) (message "File ~A not found." name) (throw 'file-not-found nil)) (multiple-value-bind (buffer created-p) (find-file-buffer name) (setf (current-buffer) buffer) (setf (window-buffer (current-window)) buffer) (when (and search-buffer (not (buffer-modified search-buffer))) (dolist (w (buffer-windows search-buffer)) (setf (window-buffer w) (current-buffer))) (delete-buffer search-buffer)) (if (and created-p (not (value group-find-file))) (current-buffer) nil))) (defun group-save-file () (let* ((buffer (current-buffer)) (pn (buffer-pathname buffer)) (name (namestring pn))) (when (and (buffer-modified buffer) (or (not (value group-save-file-confirm)) (prompt-for-y-or-n :prompt (list "Save changes in ~A? " name) :default t))) (save-file-command ())))) (defcommand "Group Search" (p) "Searches the active group for a specified string, which is prompted for." "Searches the active group for a specified string." (declare (ignore p)) (let ((string (prompt-for-string :prompt "Group Search: " :help "String to search for in active file group" :default *last-search-string*))) (get-search-pattern string :forward) (do-active-group (do ((won (find-pattern (current-point) *last-search-pattern*) (find-pattern (current-point) *last-search-pattern*))) ((not won)) (character-offset (current-point) won) (command-case (:prompt "Group Search: " :help "Type a character indicating the action to perform." :change-window nil) (:no "Search for the next occurrence.") (:do-all "Go on to the next file in the group." (return nil)) ((:exit :yes) "Exit the search." (return-from group-search-command)) (:recursive-edit "Enter a recursive edit." (do-recursive-edit) (get-search-pattern string :forward))))) (message "All files in group ~S searched." *active-file-group-name*))) (defcommand "Group Replace" (p) "Replaces one string with another in the active file group." "Replaces one string with another in the active file group." (declare (ignore p)) (let* ((target (prompt-for-string :prompt "Group Replace: " :help "Target string" :default *last-search-string*)) (replacement (prompt-for-string :prompt "With: " :help "Replacement string"))) (do-active-group (query-replace-function nil target replacement "Group Replace on previous file" t)) (message "Replacement done in all files in group ~S." *active-file-group-name*))) (defcommand "Group Query Replace" (p) "Query Replace for the active file group." "Query Replace for the active file group." (declare (ignore p)) (let ((target (prompt-for-string :prompt "Group Query Replace: " :help "Target string" :default *last-search-string*))) (let ((replacement (prompt-for-string :prompt "With: " :help "Replacement string"))) (do-active-group (unless (query-replace-function nil target replacement "Group Query Replace on previous file") (return nil))) (message "Replacement done in all files in group ~S." *active-file-group-name*))))
f59bc2a4c70e7f39d9f1be767cd4c23181c57271a29e81cdcf538c49482b77af
rmloveland/scheme48-0.53
pseudoscheme-record.scm
Copyright ( c ) 1993 - 1999 by and . See file COPYING . (define make-record-type #'scheme-translator::make-record-type) (define record-constructor #'scheme-translator::record-constructor) (define record-accessor #'scheme-translator::record-accessor) (define record-modifier #'scheme-translator::record-modifier) (define record-predicate #'scheme-translator::record-predicate) (define define-record-discloser #'scheme-translator::define-record-discloser) (define (record-type? x) (lisp:if (scheme-translator::record-type-descriptor-p x) #t #f)) (define record-type-field-names #'scheme-translator::rtd-field-names) (define record-type-name #'scheme-translator::rtd-identification) Internal record things , for inspector or whatever (define disclose-record #'scheme-translator::disclose-record) (define record-type #'scheme-translator::record-type) (define (record? x) (lisp:if (scheme-translator::record-type x) #t #f))
null
https://raw.githubusercontent.com/rmloveland/scheme48-0.53/1ae4531fac7150bd2af42d124da9b50dd1b89ec1/scheme/alt/pseudoscheme-record.scm
scheme
Copyright ( c ) 1993 - 1999 by and . See file COPYING . (define make-record-type #'scheme-translator::make-record-type) (define record-constructor #'scheme-translator::record-constructor) (define record-accessor #'scheme-translator::record-accessor) (define record-modifier #'scheme-translator::record-modifier) (define record-predicate #'scheme-translator::record-predicate) (define define-record-discloser #'scheme-translator::define-record-discloser) (define (record-type? x) (lisp:if (scheme-translator::record-type-descriptor-p x) #t #f)) (define record-type-field-names #'scheme-translator::rtd-field-names) (define record-type-name #'scheme-translator::rtd-identification) Internal record things , for inspector or whatever (define disclose-record #'scheme-translator::disclose-record) (define record-type #'scheme-translator::record-type) (define (record? x) (lisp:if (scheme-translator::record-type x) #t #f))
733ee4d2d52be67bf1cccda7b26961ea3b6fef2e319b36653aea038a512f63ad
tokenmill/timewords
lt_relative_test.clj
(ns timewords.lt-relative-test (:require [clojure.test :refer :all] [clj-time.core :as joda :refer [date-time]] [timewords.core :refer [parse]]) (:import (java.util Date) (org.joda.time DateTime))) (defn date [& xs] (.toDate (apply date-time xs))) (deftest lt-relative-timewords (testing "today variations" (let [document-time (date 2018 4 7 12 3)] (is (= (date 2018 4 6) (parse "prieš 1 d." document-time "lt"))) (is (= (date 2018 4 6) (parse "prieš 1 d" document-time "lt"))) (is (= (date 2018 4 5) (parse "prieš 2 d. " document-time "lt"))) (is (= (date 2018 3 28) (parse "prieš 10 d." document-time "lt")))) (let [document-time (date 2018 4 7 12 3)] (is (= (date 2018 4 7 13 16) (parse "šiandien 13:16" document-time "lt"))) (is (= (date 2018 4 7 4 47) (parse "šiandien 04:47" document-time "lt"))) (is (= (date 2018 4 7 22 00) (parse "šiandien 22:00" document-time "lt"))) (is (= (date 2018 4 6 22 00) (parse "vakar 22:00" document-time "lt")))) (let [document-time (date 2018 4 7 12 3)] (is (= (date 2018 4 6) (parse "1 d. prieš" document-time "lt"))) (is (= (date 2018 4 6) (parse "1 d prieš" document-time "lt"))) (is (= (date 2018 3 31) (parse "1 sav. prieš" document-time "lt"))) (is (= (date 2018 3 31) (parse "1 sav prieš" document-time "lt"))) ; use a timezone for document time setup #_(is (= (date 2018 4 7 11) (parse "1 val prieš" document-time "lt"))) #_(is (= (date 2018 4 7 11) (parse "7 val prieš" document-time "lt")))) ;(is (= nil (parse "Publikuota: 21:05" (Date.) "lt"))) ))
null
https://raw.githubusercontent.com/tokenmill/timewords/431ef3aa9eb899f2abd47cebc20a232f8c226b4a/test/timewords/lt_relative_test.clj
clojure
use a timezone for document time setup (is (= nil (parse "Publikuota: 21:05" (Date.) "lt")))
(ns timewords.lt-relative-test (:require [clojure.test :refer :all] [clj-time.core :as joda :refer [date-time]] [timewords.core :refer [parse]]) (:import (java.util Date) (org.joda.time DateTime))) (defn date [& xs] (.toDate (apply date-time xs))) (deftest lt-relative-timewords (testing "today variations" (let [document-time (date 2018 4 7 12 3)] (is (= (date 2018 4 6) (parse "prieš 1 d." document-time "lt"))) (is (= (date 2018 4 6) (parse "prieš 1 d" document-time "lt"))) (is (= (date 2018 4 5) (parse "prieš 2 d. " document-time "lt"))) (is (= (date 2018 3 28) (parse "prieš 10 d." document-time "lt")))) (let [document-time (date 2018 4 7 12 3)] (is (= (date 2018 4 7 13 16) (parse "šiandien 13:16" document-time "lt"))) (is (= (date 2018 4 7 4 47) (parse "šiandien 04:47" document-time "lt"))) (is (= (date 2018 4 7 22 00) (parse "šiandien 22:00" document-time "lt"))) (is (= (date 2018 4 6 22 00) (parse "vakar 22:00" document-time "lt")))) (let [document-time (date 2018 4 7 12 3)] (is (= (date 2018 4 6) (parse "1 d. prieš" document-time "lt"))) (is (= (date 2018 4 6) (parse "1 d prieš" document-time "lt"))) (is (= (date 2018 3 31) (parse "1 sav. prieš" document-time "lt"))) (is (= (date 2018 3 31) (parse "1 sav prieš" document-time "lt"))) #_(is (= (date 2018 4 7 11) (parse "1 val prieš" document-time "lt"))) #_(is (= (date 2018 4 7 11) (parse "7 val prieš" document-time "lt")))) ))
77bd126910cde972873f5140a2f8df1c84276aa8d470feefee60044010b6fd9e
jepsen-io/etcd
support.clj
(ns jepsen.etcd.client.support "Basic functions for working with clients.") (defprotocol Client (txn! [client pred t-branch false-branch] "Takes a predicate test, an optional true branch, and an optional false branch. See jepsen.etcd.client.txn for how to construct these arguments."))
null
https://raw.githubusercontent.com/jepsen-io/etcd/127de3e52f72e368a3866487c97f6c8293cc3b8b/src/jepsen/etcd/client/support.clj
clojure
(ns jepsen.etcd.client.support "Basic functions for working with clients.") (defprotocol Client (txn! [client pred t-branch false-branch] "Takes a predicate test, an optional true branch, and an optional false branch. See jepsen.etcd.client.txn for how to construct these arguments."))
b9579f9631b9177c1ae9869f1c10d93ed6472dcc7d5056e7ccbeffd0fa0ef61d
jgm/unicode-collation
Collator.hs
# LANGUAGE CPP # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TemplateHaskell # module Text.Collate.Collator ( Collator(..) , SortKey(..) , renderSortKey , VariableWeighting(..) , rootCollator , collatorLang , CollatorOptions(..) , setVariableWeighting , setFrenchAccents , setUpperBeforeLower , setNormalization , collator , defaultCollatorOptions , collatorFor , mkCollator ) where import Text.Collate.Lang import Text.Collate.Tailorings import Text.Collate.Collation (getCollationElements, Collation(..), CollationElement(..)) import Text.Collate.Normalize (toNFD) import Data.Word (Word16) import Data.String import qualified Data.Text as T import Data.Text (Text) import Data.Ord (comparing) import Data.Char (ord) import Data.List (intercalate) import Text.Printf (printf) import Language.Haskell.TH.Quote (QuasiQuoter(..)) #if MIN_VERSION_base(4,11,0) #else import Data.Semigroup (Semigroup(..)) #endif -- | 'VariableWeighting' affects how punctuation is treated. -- See </#Variable_Weighting>. data VariableWeighting = ^ Do n't ignore punctuation ( < deluge- ) ^ Completely ignore punctuation ( = deluge- ) | Shifted -- ^ Consider punctuation at lower priority ( de - luge < delu - ge < deluge < deluge- < Deluge ) ^ Variant of Shifted ( deluge < de - luge < delu - ge ) deriving (Show, Eq, Ord) data CollatorOptions = CollatorOptions ^ ' ' used for tailoring . -- Note that because of fallback rules, this may be somewhat different from the ' ' passed to ' collatorFor ' . This ' ' -- won't contain unicode extensions used to set options, but -- it will specify the collation if a non-default collation is being used. , optVariableWeighting :: VariableWeighting -- ^ Method for handling -- variable elements (see </>, Tables 11 and 12 ) . , optFrenchAccents :: Bool -- ^ If True, secondary weights are scanned -- in reverse order, so we get the sorting " cote côte coté côté " instead of " cote côté " , optUpperBeforeLower :: Bool -- ^ Sort uppercase letters before lower , optNormalize :: Bool -- ^ If True, strings are normalized to NFD before collation elements are constructed . If the input -- is already normalized, this option can be set to False for -- better performance. } deriving (Show, Eq, Ord) showWordList :: [Word16] -> String showWordList ws = "[" ++ intercalate "," (map (printf "0x%04X" . (fromIntegral :: Word16 -> Int)) ws) ++ "]" newtype SortKey = SortKey [Word16] deriving (Eq, Ord) instance Show SortKey where show (SortKey ws) = "SortKey " ++ showWordList ws -- | Render sort key in the manner used in the CLDR collation test data: -- the character '|' is used to separate the levels of the key and -- corresponds to a 0 in the actual sort key. renderSortKey :: SortKey -> String renderSortKey (SortKey ws) = "[" ++ tohexes ws ++ "]" where tohexes = unwords . map tohex tohex 0 = "|" tohex x = printf "%04X" x -- Note that & b < q <<< Q is the same as & b < q, & q <<< Q -- Another syntactic shortcut is: & a < * bcd - gp - s = > & a < b < c < d < e < f < g < p < q < r < s & a = * bB = > & a = b = B ( without that , we have a contraction ) & [ before 2 ] a < < b = > sorts sorts b before a data Collator = Collator | Compare two ' Text 's collate :: Text -> Text -> Ordering | Compare two strings of any type that can be unpacked lazily into a list of ' 's . , collateWithUnpacker :: forall a. Eq a => (a -> [Char]) -> a -> a -> Ordering -- | The sort key used to compare a 'Text' , sortKey :: Text -> SortKey -- | The options used for this 'Collator' , collatorOptions :: CollatorOptions -- | The collation table used for this 'Collator' , collatorCollation :: Collation } instance IsString Collator where fromString = collatorFor . fromString | Default collator based on table ( @allkeys.txt@ ) . rootCollator :: Collator rootCollator = mkCollator defaultCollatorOptions ducetCollation # DEPRECATED collatorLang " Use ( optLang . collatorOptions ) " # | ' ' used for tailoring . Because of fallback rules , this may be somewhat different from the ' ' passed to ' collatorFor ' . This ' ' -- won't contain unicode extensions used to set options, but -- it will specify the collation if a non-default collation is being used. collatorLang :: Collator -> Maybe Lang collatorLang = optLang . collatorOptions modifyCollatorOptions :: (CollatorOptions -> CollatorOptions) -> Collator -> Collator modifyCollatorOptions f coll = mkCollator (f $ collatorOptions coll) (collatorCollation coll) -- | Set method for handling variable elements (punctuation -- and spaces): see </>, Tables 11 and 12 . setVariableWeighting :: VariableWeighting -> Collator -> Collator setVariableWeighting w = modifyCollatorOptions (\o -> o{ optVariableWeighting = w }) | The Unicode Collation Algorithm expects input to be normalized into its canonical decomposition ( NFD ) . By default , collators perform -- this normalization. If your input is already normalized, you can increase performance by disabling this step : @setNormalization False@. setNormalization :: Bool -> Collator -> Collator setNormalization normalize = modifyCollatorOptions (\o -> o{ optNormalize = normalize }) -- | @setFrenchAccents True@ causes secondary weights to be scanned -- in reverse order, so we get the sorting @cote côte coté côté@ instead of @cote côté@. -- The default is usually @False@, except for @fr-CA@ where it is @True@. setFrenchAccents :: Bool -> Collator -> Collator setFrenchAccents frAccents = modifyCollatorOptions (\o -> o{ optFrenchAccents = frAccents }) -- | Most collations default to sorting lowercase letters before uppercase ( exceptions : @mt@ , @da@ , @cu@ ) . To select the opposite behavior , use @setUpperBeforeLower True@. setUpperBeforeLower :: Bool -> Collator -> Collator setUpperBeforeLower upperBefore = modifyCollatorOptions (\o -> o{ optUpperBeforeLower = upperBefore }) | Create a collator at compile time based on a BCP 47 language -- tag: e.g., @[collator|es-u-co-trad|]@. Requires the @QuasiQuotes@ extension. collator :: QuasiQuoter collator = QuasiQuoter { quoteExp = \langtag -> do case parseLang (T.pack langtag) of Left e -> do fail $ "Could not parse BCP47 tag " <> langtag <> e Right lang -> case lookupLang lang tailorings of Nothing -> [| rootCollator |] Just (_, _) -> [| collatorFor lang |] , quotePat = undefined , quoteType = undefined , quoteDec = undefined } | Default ' CollatorOptions ' . defaultCollatorOptions :: CollatorOptions defaultCollatorOptions = CollatorOptions { optLang = Nothing , optVariableWeighting = NonIgnorable , optFrenchAccents = False , optUpperBeforeLower = False , optNormalize = True } | Returns a collator based on a BCP 47 language tag . -- If no exact match is found, we try to find the best match -- (falling back to the root collation if nothing else succeeds). -- If something other than the default collation for a language -- is desired, the @co@ keyword of the unicode extensions can be used ( e.g. @es - u - co - trad@ for traditional Spanish ) . -- Other unicode extensions affect the collator options: -- - The @kb@ keyword has the same effect as -- 'setFrenchAccents' (e.g. @fr-FR-u-kb-true@). -- - The @ka@ keyword has the same effect as 'setVariableWeight' ( e.g. @fr - FR - u - kb - ka - shifted@ or @en - u - ka - noignore@ ) . - The @kf@ keyword has the same effect as ' setUpperBeforeLower ' -- (e.g. @fr-u-kf-upper@ or @fr-u-kf-lower@). - The @kk@ keyword has the same effect as ' setNormalization ' -- (e.g. @fr-u-kk-false@). collatorFor :: Lang -> Collator collatorFor lang = mkCollator opts collation where opts = defaultCollatorOptions{ optLang = langUsed, optFrenchAccents = case lookup "u" exts >>= lookup "kb" of Just "" -> True -- true is default attribute value Just "true" -> True Just _ -> False Nothing -> langLanguage lang == "cu" || (langLanguage lang == "fr" && langRegion lang == Just "CA"), optVariableWeighting = case lookup "u" exts >>= lookup "ka" of Just "" -> NonIgnorable Just "noignore" -> NonIgnorable Just "shifted" -> Shifted Nothing | langLanguage lang == "th" -> Shifted _ -> NonIgnorable, optUpperBeforeLower = case lookup "u" exts >>= lookup "kf" of Just "" -> True Just "upper" -> True Just _ -> False Nothing -> langLanguage lang == "mt" || langLanguage lang == "da" || langLanguage lang == "cu", optNormalize = case lookup "u" exts >>= lookup "kk" of Just "" -> True Just "true" -> True Just "false" -> False _ -> True } (langUsed, collation) = case lookupLang lang tailorings of Nothing -> (Nothing, ducetCollation) Just (l,tailoring) -> (Just l, ducetCollation <> tailoring) exts = langExtensions lang -- | Returns a collator constructed using the collation and -- variable weighting specified in the options. mkCollator :: CollatorOptions -> Collation -> Collator mkCollator opts collation = Collator { collate = \x y -> if x == y -- optimization then EQ else comparing sortKey' x y , collateWithUnpacker = \unpack x y -> if x == y then EQ else comparing (sortKeyFromCodePoints' . map ord . unpack) x y , sortKey = sortKey' , collatorOptions = opts , collatorCollation = collation } where sortKey' = sortKeyFromCodePoints' . T.foldr ((:) . ord) [] sortKeyFromCodePoints' = mkSortKey opts . handleVariable (optVariableWeighting opts) . getCollationElements collation . if optNormalize opts then toNFD else id handleVariable :: VariableWeighting -> [CollationElement] -> [CollationElement] handleVariable NonIgnorable = id handleVariable Blanked = doVariable False False handleVariable Shifted = doVariable True False handleVariable ShiftTrimmed = handleVariable Shifted doVariable :: Bool -> Bool -> [CollationElement] -> [CollationElement] doVariable _useL4 _afterVariable [] = [] doVariable useL4 afterVariable (e:es) | collationVariable e = e{ collationL1 = 0, collationL2 = 0, collationL3 = 0, Table 11 case useL4 of True | collationL1 e == 0 , collationL2 e == 0 , collationL3 e == 0 -> 0 | collationL1 e == 0 , collationL3 e /= 0 , afterVariable -> 0 | collationL1 e /= 0 -> collationL1 e | collationL1 e == 0 , collationL3 e /= 0 , not afterVariable -> 0xFFFF _ -> 0 } : doVariable useL4 True es | collationL1 e == 0 -- "ignorable" , afterVariable = e{ collationL1 = 0, collationL2 = 0, collationL3 = 0, collationL4 = 0 } : doVariable useL4 afterVariable es | collationL1 e /= 0 , not (collationVariable e) , useL4 = e{ collationL4 = 0xFFFF } : doVariable useL4 False es | otherwise = e : doVariable useL4 False es mkSortKey :: CollatorOptions -> [CollationElement] -> SortKey mkSortKey opts elts = SortKey $ l1s ++ (0:l2s) ++ (0:l3s) ++ if null l4s then [] else 0:l4s where l1s = filter (/=0) $ map collationL1 elts l2s = (if optFrenchAccents opts then reverse else id) $ filter (/=0) $ map collationL2 elts l3s = filter (/=0) $ map ((if optUpperBeforeLower opts then switchUpperAndLower else id) . collationL3) elts l4s = case optVariableWeighting opts of NonIgnorable -> [] Blanked -> [] ShiftTrimmed -> trimTrailingFFFFs l4s' Shifted -> l4s' l4s' = filter (/=0) $ map collationL4 elts switchUpperAndLower 0x0002 = 0x0008 switchUpperAndLower 0x0008 = 0x0002 switchUpperAndLower x = x trimTrailingFFFFs :: [Word16] -> [Word16] trimTrailingFFFFs = reverse . dropWhile (== 0xFFFF) . reverse
null
https://raw.githubusercontent.com/jgm/unicode-collation/b499a94ec58071ca0d95ece6a5341640e4bc5468/src/Text/Collate/Collator.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE OverloadedStrings # | 'VariableWeighting' affects how punctuation is treated. See </#Variable_Weighting>. ^ Consider punctuation at lower priority Note that because of fallback rules, this may be somewhat won't contain unicode extensions used to set options, but it will specify the collation if a non-default collation is being used. ^ Method for handling variable elements (see </>, ^ If True, secondary weights are scanned in reverse order, so we get the sorting ^ Sort uppercase letters before lower ^ If True, strings are normalized is already normalized, this option can be set to False for better performance. | Render sort key in the manner used in the CLDR collation test data: the character '|' is used to separate the levels of the key and corresponds to a 0 in the actual sort key. Note that & b < q <<< Q is the same as & b < q, & q <<< Q Another syntactic shortcut is: | The sort key used to compare a 'Text' | The options used for this 'Collator' | The collation table used for this 'Collator' won't contain unicode extensions used to set options, but it will specify the collation if a non-default collation is being used. | Set method for handling variable elements (punctuation and spaces): see </>, this normalization. If your input is already normalized, you can increase | @setFrenchAccents True@ causes secondary weights to be scanned in reverse order, so we get the sorting The default is usually @False@, except for @fr-CA@ where it is @True@. | Most collations default to sorting lowercase letters before tag: e.g., @[collator|es-u-co-trad|]@. Requires the @QuasiQuotes@ extension. If no exact match is found, we try to find the best match (falling back to the root collation if nothing else succeeds). If something other than the default collation for a language is desired, the @co@ keyword of the unicode extensions can be Other unicode extensions affect the collator options: 'setFrenchAccents' (e.g. @fr-FR-u-kb-true@). - The @ka@ keyword has the same effect as 'setVariableWeight' (e.g. @fr-u-kf-upper@ or @fr-u-kf-lower@). (e.g. @fr-u-kk-false@). true is default attribute value | Returns a collator constructed using the collation and variable weighting specified in the options. optimization "ignorable"
# LANGUAGE CPP # # LANGUAGE TemplateHaskell # module Text.Collate.Collator ( Collator(..) , SortKey(..) , renderSortKey , VariableWeighting(..) , rootCollator , collatorLang , CollatorOptions(..) , setVariableWeighting , setFrenchAccents , setUpperBeforeLower , setNormalization , collator , defaultCollatorOptions , collatorFor , mkCollator ) where import Text.Collate.Lang import Text.Collate.Tailorings import Text.Collate.Collation (getCollationElements, Collation(..), CollationElement(..)) import Text.Collate.Normalize (toNFD) import Data.Word (Word16) import Data.String import qualified Data.Text as T import Data.Text (Text) import Data.Ord (comparing) import Data.Char (ord) import Data.List (intercalate) import Text.Printf (printf) import Language.Haskell.TH.Quote (QuasiQuoter(..)) #if MIN_VERSION_base(4,11,0) #else import Data.Semigroup (Semigroup(..)) #endif data VariableWeighting = ^ Do n't ignore punctuation ( < deluge- ) ^ Completely ignore punctuation ( = deluge- ) ( de - luge < delu - ge < deluge < deluge- < Deluge ) ^ Variant of Shifted ( deluge < de - luge < delu - ge ) deriving (Show, Eq, Ord) data CollatorOptions = CollatorOptions ^ ' ' used for tailoring . different from the ' ' passed to ' collatorFor ' . This ' ' Tables 11 and 12 ) . " cote côte coté côté " instead of " cote côté " to NFD before collation elements are constructed . If the input } deriving (Show, Eq, Ord) showWordList :: [Word16] -> String showWordList ws = "[" ++ intercalate "," (map (printf "0x%04X" . (fromIntegral :: Word16 -> Int)) ws) ++ "]" newtype SortKey = SortKey [Word16] deriving (Eq, Ord) instance Show SortKey where show (SortKey ws) = "SortKey " ++ showWordList ws renderSortKey :: SortKey -> String renderSortKey (SortKey ws) = "[" ++ tohexes ws ++ "]" where tohexes = unwords . map tohex tohex 0 = "|" tohex x = printf "%04X" x & a < * bcd - gp - s = > & a < b < c < d < e < f < g < p < q < r < s & a = * bB = > & a = b = B ( without that , we have a contraction ) & [ before 2 ] a < < b = > sorts sorts b before a data Collator = Collator | Compare two ' Text 's collate :: Text -> Text -> Ordering | Compare two strings of any type that can be unpacked lazily into a list of ' 's . , collateWithUnpacker :: forall a. Eq a => (a -> [Char]) -> a -> a -> Ordering , sortKey :: Text -> SortKey , collatorOptions :: CollatorOptions , collatorCollation :: Collation } instance IsString Collator where fromString = collatorFor . fromString | Default collator based on table ( @allkeys.txt@ ) . rootCollator :: Collator rootCollator = mkCollator defaultCollatorOptions ducetCollation # DEPRECATED collatorLang " Use ( optLang . collatorOptions ) " # | ' ' used for tailoring . Because of fallback rules , this may be somewhat different from the ' ' passed to ' collatorFor ' . This ' ' collatorLang :: Collator -> Maybe Lang collatorLang = optLang . collatorOptions modifyCollatorOptions :: (CollatorOptions -> CollatorOptions) -> Collator -> Collator modifyCollatorOptions f coll = mkCollator (f $ collatorOptions coll) (collatorCollation coll) Tables 11 and 12 . setVariableWeighting :: VariableWeighting -> Collator -> Collator setVariableWeighting w = modifyCollatorOptions (\o -> o{ optVariableWeighting = w }) | The Unicode Collation Algorithm expects input to be normalized into its canonical decomposition ( NFD ) . By default , collators perform performance by disabling this step : @setNormalization False@. setNormalization :: Bool -> Collator -> Collator setNormalization normalize = modifyCollatorOptions (\o -> o{ optNormalize = normalize }) @cote côte coté côté@ instead of @cote côté@. setFrenchAccents :: Bool -> Collator -> Collator setFrenchAccents frAccents = modifyCollatorOptions (\o -> o{ optFrenchAccents = frAccents }) uppercase ( exceptions : @mt@ , @da@ , @cu@ ) . To select the opposite behavior , use @setUpperBeforeLower True@. setUpperBeforeLower :: Bool -> Collator -> Collator setUpperBeforeLower upperBefore = modifyCollatorOptions (\o -> o{ optUpperBeforeLower = upperBefore }) | Create a collator at compile time based on a BCP 47 language collator :: QuasiQuoter collator = QuasiQuoter { quoteExp = \langtag -> do case parseLang (T.pack langtag) of Left e -> do fail $ "Could not parse BCP47 tag " <> langtag <> e Right lang -> case lookupLang lang tailorings of Nothing -> [| rootCollator |] Just (_, _) -> [| collatorFor lang |] , quotePat = undefined , quoteType = undefined , quoteDec = undefined } | Default ' CollatorOptions ' . defaultCollatorOptions :: CollatorOptions defaultCollatorOptions = CollatorOptions { optLang = Nothing , optVariableWeighting = NonIgnorable , optFrenchAccents = False , optUpperBeforeLower = False , optNormalize = True } | Returns a collator based on a BCP 47 language tag . used ( e.g. @es - u - co - trad@ for traditional Spanish ) . - The @kb@ keyword has the same effect as ( e.g. @fr - FR - u - kb - ka - shifted@ or @en - u - ka - noignore@ ) . - The @kf@ keyword has the same effect as ' setUpperBeforeLower ' - The @kk@ keyword has the same effect as ' setNormalization ' collatorFor :: Lang -> Collator collatorFor lang = mkCollator opts collation where opts = defaultCollatorOptions{ optLang = langUsed, optFrenchAccents = case lookup "u" exts >>= lookup "kb" of Just "" -> True Just "true" -> True Just _ -> False Nothing -> langLanguage lang == "cu" || (langLanguage lang == "fr" && langRegion lang == Just "CA"), optVariableWeighting = case lookup "u" exts >>= lookup "ka" of Just "" -> NonIgnorable Just "noignore" -> NonIgnorable Just "shifted" -> Shifted Nothing | langLanguage lang == "th" -> Shifted _ -> NonIgnorable, optUpperBeforeLower = case lookup "u" exts >>= lookup "kf" of Just "" -> True Just "upper" -> True Just _ -> False Nothing -> langLanguage lang == "mt" || langLanguage lang == "da" || langLanguage lang == "cu", optNormalize = case lookup "u" exts >>= lookup "kk" of Just "" -> True Just "true" -> True Just "false" -> False _ -> True } (langUsed, collation) = case lookupLang lang tailorings of Nothing -> (Nothing, ducetCollation) Just (l,tailoring) -> (Just l, ducetCollation <> tailoring) exts = langExtensions lang mkCollator :: CollatorOptions -> Collation -> Collator mkCollator opts collation = then EQ else comparing sortKey' x y , collateWithUnpacker = \unpack x y -> if x == y then EQ else comparing (sortKeyFromCodePoints' . map ord . unpack) x y , sortKey = sortKey' , collatorOptions = opts , collatorCollation = collation } where sortKey' = sortKeyFromCodePoints' . T.foldr ((:) . ord) [] sortKeyFromCodePoints' = mkSortKey opts . handleVariable (optVariableWeighting opts) . getCollationElements collation . if optNormalize opts then toNFD else id handleVariable :: VariableWeighting -> [CollationElement] -> [CollationElement] handleVariable NonIgnorable = id handleVariable Blanked = doVariable False False handleVariable Shifted = doVariable True False handleVariable ShiftTrimmed = handleVariable Shifted doVariable :: Bool -> Bool -> [CollationElement] -> [CollationElement] doVariable _useL4 _afterVariable [] = [] doVariable useL4 afterVariable (e:es) | collationVariable e = e{ collationL1 = 0, collationL2 = 0, collationL3 = 0, Table 11 case useL4 of True | collationL1 e == 0 , collationL2 e == 0 , collationL3 e == 0 -> 0 | collationL1 e == 0 , collationL3 e /= 0 , afterVariable -> 0 | collationL1 e /= 0 -> collationL1 e | collationL1 e == 0 , collationL3 e /= 0 , not afterVariable -> 0xFFFF _ -> 0 } : doVariable useL4 True es , afterVariable = e{ collationL1 = 0, collationL2 = 0, collationL3 = 0, collationL4 = 0 } : doVariable useL4 afterVariable es | collationL1 e /= 0 , not (collationVariable e) , useL4 = e{ collationL4 = 0xFFFF } : doVariable useL4 False es | otherwise = e : doVariable useL4 False es mkSortKey :: CollatorOptions -> [CollationElement] -> SortKey mkSortKey opts elts = SortKey $ l1s ++ (0:l2s) ++ (0:l3s) ++ if null l4s then [] else 0:l4s where l1s = filter (/=0) $ map collationL1 elts l2s = (if optFrenchAccents opts then reverse else id) $ filter (/=0) $ map collationL2 elts l3s = filter (/=0) $ map ((if optUpperBeforeLower opts then switchUpperAndLower else id) . collationL3) elts l4s = case optVariableWeighting opts of NonIgnorable -> [] Blanked -> [] ShiftTrimmed -> trimTrailingFFFFs l4s' Shifted -> l4s' l4s' = filter (/=0) $ map collationL4 elts switchUpperAndLower 0x0002 = 0x0008 switchUpperAndLower 0x0008 = 0x0002 switchUpperAndLower x = x trimTrailingFFFFs :: [Word16] -> [Word16] trimTrailingFFFFs = reverse . dropWhile (== 0xFFFF) . reverse
aee81c7da4450ae3340179f0e03506e60f48bec55e6a8c5f6d18305896971453
nomeata/incredible
ConvertJS.hs
module ConvertJS (toContext, toProof, fromAnalysis, fromRule) where import GHCJS.Types import GHCJS.Marshal import Data.Aeson.Types import qualified ConvertAeson as A import Types -- Conversion from/to JSRef toContext :: JSVal -> IO (Either String Context) toContext val = do valMB <- fromJSVal val case valMB of Just v -> return $ A.toContext v Nothing -> return $ Left $ "Context: Could not turn JSRef into a Value" toProof :: JSVal -> IO (Either String Proof) toProof val = do valMB <- fromJSVal val case valMB of Just v -> return $ A.toProof v Nothing -> return $ Left $ "Proof: Could not turn JSRef into a Value" fromAnalysis :: Analysis -> IO JSVal fromAnalysis = toJSVal . A.fromAnalysis fromRule :: Rule -> IO JSVal fromRule = toJSVal . A.fromRule
null
https://raw.githubusercontent.com/nomeata/incredible/d18ada4ae7ce1c7ca268c050ee688b633a307c2e/logic/js/ConvertJS.hs
haskell
Conversion from/to JSRef
module ConvertJS (toContext, toProof, fromAnalysis, fromRule) where import GHCJS.Types import GHCJS.Marshal import Data.Aeson.Types import qualified ConvertAeson as A import Types toContext :: JSVal -> IO (Either String Context) toContext val = do valMB <- fromJSVal val case valMB of Just v -> return $ A.toContext v Nothing -> return $ Left $ "Context: Could not turn JSRef into a Value" toProof :: JSVal -> IO (Either String Proof) toProof val = do valMB <- fromJSVal val case valMB of Just v -> return $ A.toProof v Nothing -> return $ Left $ "Proof: Could not turn JSRef into a Value" fromAnalysis :: Analysis -> IO JSVal fromAnalysis = toJSVal . A.fromAnalysis fromRule :: Rule -> IO JSVal fromRule = toJSVal . A.fromRule
a1fce625b9cbb30f979b9d6c5da648ba335aee168aa557e41d931a25ab6d87a8
facebook/pyre-check
myMap.mli
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) module type S = MyMap_sig.S module Make (Ord : Map.OrderedType) : S with type key = Ord.t
null
https://raw.githubusercontent.com/facebook/pyre-check/10c375bea52db5d10b71cb5206fac7da9549eb0c/source/hack_parallel/hack_parallel/utils/collections/myMap.mli
ocaml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) module type S = MyMap_sig.S module Make (Ord : Map.OrderedType) : S with type key = Ord.t
3fffadf95be63fd508a26a50b4fba9d9e04a0813f357865122c75a89b09e433f
afronski/bferl
programming_language_logic_SUITE.erl
-module(programming_language_logic_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include("../include/interpreter_definitions.hrl"). -define(TO_STRING(Code), string:join(Code, "")). -export([ all/0 ]). -export([ empty_state_should_have_fixed_memory_size/1, other_parameters_should_be_set_to_proper_value/1, after_registering_io_process_state_should_update_that_field/1, pointers_should_be_set_at_the_beginning_after_new/1, after_loading_program_it_should_be_available_in_state/1, you_should_be_able_run_program/1, you_should_be_able_step_through_program/1, stepping_out_of_the_program_should_not_be_a_problem/1, running_partially_stepped_program_should_finish_program_execution/1 ]). all() -> [ empty_state_should_have_fixed_memory_size, other_parameters_should_be_set_to_proper_value, after_registering_io_process_state_should_update_that_field, pointers_should_be_set_at_the_beginning_after_new, after_loading_program_it_should_be_available_in_state, you_should_be_able_run_program, you_should_be_able_step_through_program, stepping_out_of_the_program_should_not_be_a_problem, running_partially_stepped_program_should_finish_program_execution ]. empty_state_should_have_fixed_memory_size(_Context) -> State = bferl_programming_language_logic:new(), ?assertEqual(?MEMORY_SIZE, array:size(State#interpreter.memory)). other_parameters_should_be_set_to_proper_value(_Context) -> State = bferl_programming_language_logic:new(), ?assertEqual([], State#interpreter.stack), ?assertEqual(undefined, State#interpreter.instructions), ?assertEqual({undefined, undefined, undefined}, State#interpreter.io). after_registering_io_process_state_should_update_that_field(_Context) -> State = bferl_programming_language_logic:new(), StateWithTape = bferl_programming_language_logic:register_tape(State), ?assertEqual({fun bferl_io:get_character_from_tape/0, fun bferl_io:put_character_to_tape/1, fun bferl_io:new_line_on_tape/0}, StateWithTape#interpreter.io), StateWithConsole = bferl_programming_language_logic:register_console(State), ?assertEqual({fun bferl_io:get_character_from_console/0, fun bferl_io:put_character_to_console/1, fun bferl_io:new_line_on_console/0}, StateWithConsole#interpreter.io). pointers_should_be_set_at_the_beginning_after_new(_Context) -> State = bferl_programming_language_logic:new(), ?assertEqual(0, State#interpreter.instructions_counter), ?assertEqual(1, State#interpreter.instructions_pointer), ?assertEqual(0, State#interpreter.memory_pointer). after_loading_program_it_should_be_available_in_state(_Context) -> State = bferl_programming_language_logic:load(["+"], bferl_programming_language_logic:new()), ?assertEqual("+", ?TO_STRING(State#interpreter.instructions)), DifferentState = bferl_programming_language_logic:new(["-"]), ?assertEqual("-", ?TO_STRING(DifferentState#interpreter.instructions)). you_should_be_able_run_program(_Context) -> State = bferl_programming_language_logic:new(["+", "+", "+"]), Output = bferl_programming_language_logic:run(State), ?assertEqual(length(Output#interpreter.instructions) + 1, Output#interpreter.instructions_pointer), ?assertEqual(length(Output#interpreter.instructions), Output#interpreter.instructions_counter), ?assertEqual("+", bferl_programming_language_logic:get_opcode(1, Output)), ?assertEqual("+", bferl_programming_language_logic:get_opcode(2, Output)), ?assertEqual("+", bferl_programming_language_logic:get_opcode(3, Output)), ?assertEqual(3, bferl_programming_language_logic:get_memory_cell(0, Output)). you_should_be_able_step_through_program(_Context) -> State = bferl_programming_language_logic:new(["+", "+", "+"]), OutputAfterFirstStep = bferl_programming_language_logic:step(State), ?assertEqual(2, OutputAfterFirstStep#interpreter.instructions_pointer), ?assertEqual(1, OutputAfterFirstStep#interpreter.instructions_counter), ?assertEqual(1, bferl_programming_language_logic:get_memory_cell(0, OutputAfterFirstStep)). stepping_out_of_the_program_should_not_be_a_problem(_Context) -> EmptyState = bferl_programming_language_logic:new(), no_program_loaded = bferl_programming_language_logic:step(EmptyState), State = bferl_programming_language_logic:new([]), end_of_program = bferl_programming_language_logic:step(State), StateWithZeroedPointer = State#interpreter{instructions_pointer = 0}, end_of_program = bferl_programming_language_logic:step(StateWithZeroedPointer), StateWithNegativeInstructionsPointer = State#interpreter{instructions_pointer = -1}, end_of_program = bferl_programming_language_logic:step(StateWithNegativeInstructionsPointer). running_partially_stepped_program_should_finish_program_execution(_Context) -> State = bferl_programming_language_logic:new(["+", "+", "+"]), StateAfterFirstStep = bferl_programming_language_logic:step(State), ?assertEqual(2, StateAfterFirstStep#interpreter.instructions_pointer), Output = bferl_programming_language_logic:run(StateAfterFirstStep), ?assertEqual(length(Output#interpreter.instructions) + 1, Output#interpreter.instructions_pointer), ?assertEqual(length(Output#interpreter.instructions), Output#interpreter.instructions_counter).
null
https://raw.githubusercontent.com/afronski/bferl/18d3482c71cdb0e39bde090d436245a2a9531f49/test/programming_language_logic_SUITE.erl
erlang
-module(programming_language_logic_SUITE). -include_lib("common_test/include/ct.hrl"). -include_lib("eunit/include/eunit.hrl"). -include("../include/interpreter_definitions.hrl"). -define(TO_STRING(Code), string:join(Code, "")). -export([ all/0 ]). -export([ empty_state_should_have_fixed_memory_size/1, other_parameters_should_be_set_to_proper_value/1, after_registering_io_process_state_should_update_that_field/1, pointers_should_be_set_at_the_beginning_after_new/1, after_loading_program_it_should_be_available_in_state/1, you_should_be_able_run_program/1, you_should_be_able_step_through_program/1, stepping_out_of_the_program_should_not_be_a_problem/1, running_partially_stepped_program_should_finish_program_execution/1 ]). all() -> [ empty_state_should_have_fixed_memory_size, other_parameters_should_be_set_to_proper_value, after_registering_io_process_state_should_update_that_field, pointers_should_be_set_at_the_beginning_after_new, after_loading_program_it_should_be_available_in_state, you_should_be_able_run_program, you_should_be_able_step_through_program, stepping_out_of_the_program_should_not_be_a_problem, running_partially_stepped_program_should_finish_program_execution ]. empty_state_should_have_fixed_memory_size(_Context) -> State = bferl_programming_language_logic:new(), ?assertEqual(?MEMORY_SIZE, array:size(State#interpreter.memory)). other_parameters_should_be_set_to_proper_value(_Context) -> State = bferl_programming_language_logic:new(), ?assertEqual([], State#interpreter.stack), ?assertEqual(undefined, State#interpreter.instructions), ?assertEqual({undefined, undefined, undefined}, State#interpreter.io). after_registering_io_process_state_should_update_that_field(_Context) -> State = bferl_programming_language_logic:new(), StateWithTape = bferl_programming_language_logic:register_tape(State), ?assertEqual({fun bferl_io:get_character_from_tape/0, fun bferl_io:put_character_to_tape/1, fun bferl_io:new_line_on_tape/0}, StateWithTape#interpreter.io), StateWithConsole = bferl_programming_language_logic:register_console(State), ?assertEqual({fun bferl_io:get_character_from_console/0, fun bferl_io:put_character_to_console/1, fun bferl_io:new_line_on_console/0}, StateWithConsole#interpreter.io). pointers_should_be_set_at_the_beginning_after_new(_Context) -> State = bferl_programming_language_logic:new(), ?assertEqual(0, State#interpreter.instructions_counter), ?assertEqual(1, State#interpreter.instructions_pointer), ?assertEqual(0, State#interpreter.memory_pointer). after_loading_program_it_should_be_available_in_state(_Context) -> State = bferl_programming_language_logic:load(["+"], bferl_programming_language_logic:new()), ?assertEqual("+", ?TO_STRING(State#interpreter.instructions)), DifferentState = bferl_programming_language_logic:new(["-"]), ?assertEqual("-", ?TO_STRING(DifferentState#interpreter.instructions)). you_should_be_able_run_program(_Context) -> State = bferl_programming_language_logic:new(["+", "+", "+"]), Output = bferl_programming_language_logic:run(State), ?assertEqual(length(Output#interpreter.instructions) + 1, Output#interpreter.instructions_pointer), ?assertEqual(length(Output#interpreter.instructions), Output#interpreter.instructions_counter), ?assertEqual("+", bferl_programming_language_logic:get_opcode(1, Output)), ?assertEqual("+", bferl_programming_language_logic:get_opcode(2, Output)), ?assertEqual("+", bferl_programming_language_logic:get_opcode(3, Output)), ?assertEqual(3, bferl_programming_language_logic:get_memory_cell(0, Output)). you_should_be_able_step_through_program(_Context) -> State = bferl_programming_language_logic:new(["+", "+", "+"]), OutputAfterFirstStep = bferl_programming_language_logic:step(State), ?assertEqual(2, OutputAfterFirstStep#interpreter.instructions_pointer), ?assertEqual(1, OutputAfterFirstStep#interpreter.instructions_counter), ?assertEqual(1, bferl_programming_language_logic:get_memory_cell(0, OutputAfterFirstStep)). stepping_out_of_the_program_should_not_be_a_problem(_Context) -> EmptyState = bferl_programming_language_logic:new(), no_program_loaded = bferl_programming_language_logic:step(EmptyState), State = bferl_programming_language_logic:new([]), end_of_program = bferl_programming_language_logic:step(State), StateWithZeroedPointer = State#interpreter{instructions_pointer = 0}, end_of_program = bferl_programming_language_logic:step(StateWithZeroedPointer), StateWithNegativeInstructionsPointer = State#interpreter{instructions_pointer = -1}, end_of_program = bferl_programming_language_logic:step(StateWithNegativeInstructionsPointer). running_partially_stepped_program_should_finish_program_execution(_Context) -> State = bferl_programming_language_logic:new(["+", "+", "+"]), StateAfterFirstStep = bferl_programming_language_logic:step(State), ?assertEqual(2, StateAfterFirstStep#interpreter.instructions_pointer), Output = bferl_programming_language_logic:run(StateAfterFirstStep), ?assertEqual(length(Output#interpreter.instructions) + 1, Output#interpreter.instructions_pointer), ?assertEqual(length(Output#interpreter.instructions), Output#interpreter.instructions_counter).
28c5d1e5287d4c689ac0415bf3b2237887af6bdbc2da9e4973b93319449b1d99
IvanIvanov/fp2013
lab7-examples.scm
A function that computes the dot product of two vectors ;;; represented as lists. (define (dot-product a b) (if (null? a) 0 (+ (* (car a) (car b)) (dot-product (cdr a) (cdr b))))) 14 ;;; A matrix can be modeled as a list of it's row vectors ;;; which are lists of numbers. ;;; Finds the number of rows of the matrix m. (define (matrix-rows m) (length m)) ;;; Finds the number of columns of the matrix m. (define (matrix-cols m) (if (= (matrix-rows m) 0) 0 (length (car m)))) ;;; Computes the product of a matrix with a column vector. (define (matrix-*-vector m v) (map (lambda (row) (dot-product row v)) m)) ( 11 25 ) Finds the first column vector of a matrix . (define (first-col m) (if (null? m) '() (cons (caar m) (first-col (cdr m))))) ( 1 3 ) Computes a new matrix with the first column removed . (define (rest-cols m) (if (null? m) '() (cons (cdar m) (rest-cols (cdr m))))) ( ( 2 ) ( 4 ) ) ;;; Transposes a matrix m. To transpose a matrix convert its columns into rows. (define (transpose m) (if (= 0 (matrix-cols m)) '() (cons (first-col m) (transpose (rest-cols m))))) ( ( 1 3 ) ( 2 4 ) ) Computes the product of two matrices . (define (matrix-*-matrix m1 m2) (map (lambda (row) (map (lambda (col) (dot-product row col)) (transpose m2))) m1)) ( ( -1 18 ) ( -3 40 ) ) ;;; A system that does symbolic differentiation. ;;; A function that takes an expression and a variable and returns an ;;; expression that is the result of taking the derivative of the input ;;; expression with respect to the variable. For the purposes of this ;;; function an expression is defined as: ;;; 1 . All Scheme numbers are valid expressions . 2 . All variables ( Scheme symbols ) are valid expressions . 3 . If a and b are valid expressions then ( + a b ) is a valid expression . 4 . If a and b are valid expressions then ( * a b ) is a valid expression . ;;; ;;; To find the derivative the following rules are used: ;;; dc / dx = 0 dx / dx = 1 ;;; d(a+b)/dx = da/dx + db/dx ;;; d(a*b)/dx = a * db/dx + b * da/dx ;;; (define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum (deriv (sum-a exp) var) (deriv (sum-b exp) var))) ((product? exp) (make-sum (make-product (product-a exp) (deriv (product-b exp) var)) (make-product (product-b exp) (deriv (product-a exp) var)))) (else "Error"))) (define (variable? exp) (symbol? exp)) (define (same-variable? a b) (and (variable? a) (variable? b) (eq? a b))) ;;; Simple make-sum without simplifications: ;;; ;;;(define (make-sum a b) ;;; (list '+ a b)) ;;; Make-sum with simplifications: (define (make-sum a b) (cond ((and (number? a) (= a 0)) b) ((and (number? b) (= b 0)) a) ((and (number? a) (number? b)) (+ a b)) (else (list '+ a b)))) (define (sum-a exp) (cadr exp)) (define (sum-b exp) (caddr exp)) (define (sum? exp) (and (pair? exp) (eq? '+ (car exp)))) ;;; Simple make-product without simplifications: ;;; ;;;(define (make-product a b) ;;; (list '* a b)) ;;; Make-product with simplifications: (define (make-product a b) (cond ((and (number? a) (= a 0)) 0) ((and (number? a) (= a 1)) b) ((and (number? b) (= b 0)) 0) ((and (number? b) (= b 1)) a) ((and (number? a) (number? b)) (* a b)) (else (list '* a b)))) (define (product-a exp) (cadr exp)) (define (product-b exp) (caddr exp)) (define (product? exp) (and (pair? exp) (eq? '* (car exp)))) 3 1 (deriv '(* x y) 'x) ; y (deriv '(+ (* a x) b) 'x) ; a ( + ( * x y ) ( * ( + x 3 ) y ) )
null
https://raw.githubusercontent.com/IvanIvanov/fp2013/2ac1bb1102cb65e0ecbfa8d2fb3ca69953ae4ecf/lab1/lab7-examples.scm
scheme
represented as lists. A matrix can be modeled as a list of it's row vectors which are lists of numbers. Finds the number of rows of the matrix m. Finds the number of columns of the matrix m. Computes the product of a matrix with a column vector. Transposes a matrix m. To transpose a matrix convert its columns into rows. A system that does symbolic differentiation. A function that takes an expression and a variable and returns an expression that is the result of taking the derivative of the input expression with respect to the variable. For the purposes of this function an expression is defined as: To find the derivative the following rules are used: d(a+b)/dx = da/dx + db/dx d(a*b)/dx = a * db/dx + b * da/dx Simple make-sum without simplifications: (define (make-sum a b) (list '+ a b)) Make-sum with simplifications: Simple make-product without simplifications: (define (make-product a b) (list '* a b)) Make-product with simplifications: y a
A function that computes the dot product of two vectors (define (dot-product a b) (if (null? a) 0 (+ (* (car a) (car b)) (dot-product (cdr a) (cdr b))))) 14 (define (matrix-rows m) (length m)) (define (matrix-cols m) (if (= (matrix-rows m) 0) 0 (length (car m)))) (define (matrix-*-vector m v) (map (lambda (row) (dot-product row v)) m)) ( 11 25 ) Finds the first column vector of a matrix . (define (first-col m) (if (null? m) '() (cons (caar m) (first-col (cdr m))))) ( 1 3 ) Computes a new matrix with the first column removed . (define (rest-cols m) (if (null? m) '() (cons (cdar m) (rest-cols (cdr m))))) ( ( 2 ) ( 4 ) ) (define (transpose m) (if (= 0 (matrix-cols m)) '() (cons (first-col m) (transpose (rest-cols m))))) ( ( 1 3 ) ( 2 4 ) ) Computes the product of two matrices . (define (matrix-*-matrix m1 m2) (map (lambda (row) (map (lambda (col) (dot-product row col)) (transpose m2))) m1)) ( ( -1 18 ) ( -3 40 ) ) 1 . All Scheme numbers are valid expressions . 2 . All variables ( Scheme symbols ) are valid expressions . 3 . If a and b are valid expressions then ( + a b ) is a valid expression . 4 . If a and b are valid expressions then ( * a b ) is a valid expression . dc / dx = 0 dx / dx = 1 (define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum (deriv (sum-a exp) var) (deriv (sum-b exp) var))) ((product? exp) (make-sum (make-product (product-a exp) (deriv (product-b exp) var)) (make-product (product-b exp) (deriv (product-a exp) var)))) (else "Error"))) (define (variable? exp) (symbol? exp)) (define (same-variable? a b) (and (variable? a) (variable? b) (eq? a b))) (define (make-sum a b) (cond ((and (number? a) (= a 0)) b) ((and (number? b) (= b 0)) a) ((and (number? a) (number? b)) (+ a b)) (else (list '+ a b)))) (define (sum-a exp) (cadr exp)) (define (sum-b exp) (caddr exp)) (define (sum? exp) (and (pair? exp) (eq? '+ (car exp)))) (define (make-product a b) (cond ((and (number? a) (= a 0)) 0) ((and (number? a) (= a 1)) b) ((and (number? b) (= b 0)) 0) ((and (number? b) (= b 1)) a) ((and (number? a) (number? b)) (* a b)) (else (list '* a b)))) (define (product-a exp) (cadr exp)) (define (product-b exp) (caddr exp)) (define (product? exp) (and (pair? exp) (eq? '* (car exp)))) 3 1 ( + ( * x y ) ( * ( + x 3 ) y ) )
bb222ca8527f3ae0c9f6857a20f6843cd90e464441779b757fb3f0c612814929
myme/nixon
TestLib.hs
module Test.Nixon.TestLib where import Control.Monad.Trans.State (get, StateT, evalStateT) import Nixon.Prelude import Nixon.Process (HasProc (..)) import System.Exit (ExitCode) newtype MockProc a = MockProc (StateT (ExitCode, Text) IO a) deriving (Functor, Applicative, Monad) runProc :: (ExitCode, Text) -> MockProc a -> IO a runProc state (MockProc computation) = evalStateT computation state instance HasProc MockProc where proc' _ _ _ = MockProc get instance MonadIO MockProc where liftIO = MockProc . liftIO
null
https://raw.githubusercontent.com/myme/nixon/30a1ff6c1e902c2fb06ddfb003ab4124c447cc81/test/Test/Nixon/TestLib.hs
haskell
module Test.Nixon.TestLib where import Control.Monad.Trans.State (get, StateT, evalStateT) import Nixon.Prelude import Nixon.Process (HasProc (..)) import System.Exit (ExitCode) newtype MockProc a = MockProc (StateT (ExitCode, Text) IO a) deriving (Functor, Applicative, Monad) runProc :: (ExitCode, Text) -> MockProc a -> IO a runProc state (MockProc computation) = evalStateT computation state instance HasProc MockProc where proc' _ _ _ = MockProc get instance MonadIO MockProc where liftIO = MockProc . liftIO
f6087cf16df7bf70635e9d5ffd92e03f32275a06c809194bc4b1f7fe8d7c1fcc
erlang/corba
orber_web_server.erl
%%---------------------------------------------------------------------- %% %% %CopyrightBegin% %% Copyright Ericsson AB 2001 - 2015 . 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. %% %% %CopyrightEnd% %% %% %%---------------------------------------------------------------------- %% File : orber_web_server.erl %% Purpose : %%---------------------------------------------------------------------- -module(orber_web_server). -behaviour(gen_server). -export([init/1,handle_call/3,handle_cast/2,handle_info/2]). -export([terminate/2,code_change/3]). -export([start/0,stop/0,start_link/0]). -export([config_data/0, menu/2, configure/2, info/2, nameservice/2, default_selection/2, ifr_select/2, ifr_data/2, create/2, delete_ctx/2, add_ctx/2, delete_obj/2, flash_msg/2]). %%---------------------------------------------------------------------- %%-------------- Defines & Includes ------------------------------------ %%---------------------------------------------------------------------- -define(HTML_HEADER, "Cache-Control:no-cache\r\nPragma:no-cache\r\nExpires:Thu, 01 Dec 1994 16:00:00 GMT\r\nContent-type: text/html\r\n\r\n<HTML BGCOLOR=\"#FFFFFF\">\n<HEAD>\n<TITLE>Orber O&D</TITLE>\n</HEAD>\n"). -define(HTML_END, "</BODY></HTML>"). -define(DEBUG_LEVEL, 5). -record(state, {}). -include("ifr_objects.hrl"). %%---------------------------------------------------------------------- %%-------------- External API ------------------------------------------ %%---------------------------------------------------------------------- %% Function : start/start_link/stop %% Returns : %% Description: %%---------------------------------------------------------------------- start_link()-> gen_server:start_link({local,?MODULE},?MODULE,[],[]). start()-> gen_server:start({local,?MODULE},?MODULE,[],[]). stop()-> gen_server:call(?MODULE,stop,1000). %%---------------------------------------------------------------------- %% Function : config_data %% Returns : %% Description: %%---------------------------------------------------------------------- config_data()-> {orber,[{web_data,{"OrberWeb","/orber/main_frame.html"}}, {alias,{"/orber", code:priv_dir(orber)}}, {start,{child,{{local,?MODULE},{?MODULE,start_link,[]}, permanent,100,worker,[?MODULE]}}}, {alias,{erl_alias,"/orber_erl",[orber_web_server]}} ]}. menu(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {menu, Env, Args}), ?HTML_END]. configure(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {configure, Env, Args}), ?HTML_END]. nameservice(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {nameservice, Env, Args}), ?HTML_END]. info(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {info, Env, Args}), ?HTML_END]. default_selection(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {default_selection, Env, Args}), ?HTML_END]. flash_msg(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {nameservice, Env, Args}), ?HTML_END]. ifr_select(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {ifr_select, Env, Args}), ?HTML_END]. ifr_data(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {ifr_data, Env, Args}), ?HTML_END]. create(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {create, Env, Args}), ?HTML_END]. delete_ctx(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {delete_ctx, Env, Args}), ?HTML_END]. add_ctx(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {add_ctx, Env, Args}), ?HTML_END]. delete_obj(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {delete_obj, Env, Args}), ?HTML_END]. %%---------------------------------------------------------------------- %%-------------- Callback Functions ------------------------------------ %%---------------------------------------------------------------------- %% Function : MISC gen_server specific callback functions %% Returns : %% Description: %%---------------------------------------------------------------------- init(_Arg)-> {ok, #state{}}. terminate(_,_State)-> ok. handle_cast(_,State)-> {noreply,State}. handle_info(_,State)-> {noreply,State}. code_change(_Old_vsn,State,_Extra)-> {ok,State}. %%---------------------------------------------------------------------- %% Function : handle_call %% Returns : %% Description: %%---------------------------------------------------------------------- handle_call({Function, Env, Args}, _From, State)-> case catch orber_web:Function(Env, Args) of {'EXIT', R} -> orber:dbg("[~p] orber_web:~p(~p);~nEXIT: ~p", [?LINE, Function, Args, R], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {'EXIT', R1, R2} -> orber:dbg("[~p] orber_web:~p(~p);~nEXIT: ~p~n~p", [?LINE, Function, Args, R1, R2], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {badrpc, Why} -> orber:dbg("[~p] orber_web:~p(~p);~nbadrpc: ~p", [?LINE, Function, Args, Why], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {'EXCEPTION', E} -> orber:dbg("[~p] orber_web:~p(~p);~nEXCEPTION: ~p", [?LINE, Function, Args, E], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {error, Data} -> orber:dbg("[~p] orber_web:~p(~p); ~nReason: ~p", [?LINE, Function, Args, Data], ?DEBUG_LEVEL), {reply, Data, State}; Reply -> {reply, Reply, State} end; handle_call(stop, _From, State)-> {stop, normal, ok, State}; handle_call(What, _From, State)-> orber:dbg("[~p] orber_web_server:handle_call(~p);", [?LINE, What], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\"><FONT SIZE=6>Unknown Request</FONT>", State}. %%---------------------------------------------------------------------- %% END OF MODULE %%----------------------------------------------------------------------
null
https://raw.githubusercontent.com/erlang/corba/396df81473a386d0315bbba830db6f9d4b12a04f/lib/orber/src/orber_web_server.erl
erlang
---------------------------------------------------------------------- %CopyrightBegin% 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. %CopyrightEnd% ---------------------------------------------------------------------- File : orber_web_server.erl Purpose : ---------------------------------------------------------------------- ---------------------------------------------------------------------- -------------- Defines & Includes ------------------------------------ ---------------------------------------------------------------------- ---------------------------------------------------------------------- -------------- External API ------------------------------------------ ---------------------------------------------------------------------- Function : start/start_link/stop Returns : Description: ---------------------------------------------------------------------- ---------------------------------------------------------------------- Function : config_data Returns : Description: ---------------------------------------------------------------------- ---------------------------------------------------------------------- -------------- Callback Functions ------------------------------------ ---------------------------------------------------------------------- Function : MISC gen_server specific callback functions Returns : Description: ---------------------------------------------------------------------- ---------------------------------------------------------------------- Function : handle_call Returns : Description: ---------------------------------------------------------------------- ---------------------------------------------------------------------- END OF MODULE ----------------------------------------------------------------------
Copyright Ericsson AB 2001 - 2015 . 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(orber_web_server). -behaviour(gen_server). -export([init/1,handle_call/3,handle_cast/2,handle_info/2]). -export([terminate/2,code_change/3]). -export([start/0,stop/0,start_link/0]). -export([config_data/0, menu/2, configure/2, info/2, nameservice/2, default_selection/2, ifr_select/2, ifr_data/2, create/2, delete_ctx/2, add_ctx/2, delete_obj/2, flash_msg/2]). -define(HTML_HEADER, "Cache-Control:no-cache\r\nPragma:no-cache\r\nExpires:Thu, 01 Dec 1994 16:00:00 GMT\r\nContent-type: text/html\r\n\r\n<HTML BGCOLOR=\"#FFFFFF\">\n<HEAD>\n<TITLE>Orber O&D</TITLE>\n</HEAD>\n"). -define(HTML_END, "</BODY></HTML>"). -define(DEBUG_LEVEL, 5). -record(state, {}). -include("ifr_objects.hrl"). start_link()-> gen_server:start_link({local,?MODULE},?MODULE,[],[]). start()-> gen_server:start({local,?MODULE},?MODULE,[],[]). stop()-> gen_server:call(?MODULE,stop,1000). config_data()-> {orber,[{web_data,{"OrberWeb","/orber/main_frame.html"}}, {alias,{"/orber", code:priv_dir(orber)}}, {start,{child,{{local,?MODULE},{?MODULE,start_link,[]}, permanent,100,worker,[?MODULE]}}}, {alias,{erl_alias,"/orber_erl",[orber_web_server]}} ]}. menu(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {menu, Env, Args}), ?HTML_END]. configure(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {configure, Env, Args}), ?HTML_END]. nameservice(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {nameservice, Env, Args}), ?HTML_END]. info(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {info, Env, Args}), ?HTML_END]. default_selection(Env,Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {default_selection, Env, Args}), ?HTML_END]. flash_msg(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {nameservice, Env, Args}), ?HTML_END]. ifr_select(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {ifr_select, Env, Args}), ?HTML_END]. ifr_data(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {ifr_data, Env, Args}), ?HTML_END]. create(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {create, Env, Args}), ?HTML_END]. delete_ctx(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {delete_ctx, Env, Args}), ?HTML_END]. add_ctx(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {add_ctx, Env, Args}), ?HTML_END]. delete_obj(Env, Input) -> Args = uri_string:dissect_query(Input), [?HTML_HEADER, gen_server:call(?MODULE, {delete_obj, Env, Args}), ?HTML_END]. init(_Arg)-> {ok, #state{}}. terminate(_,_State)-> ok. handle_cast(_,State)-> {noreply,State}. handle_info(_,State)-> {noreply,State}. code_change(_Old_vsn,State,_Extra)-> {ok,State}. handle_call({Function, Env, Args}, _From, State)-> case catch orber_web:Function(Env, Args) of {'EXIT', R} -> orber:dbg("[~p] orber_web:~p(~p);~nEXIT: ~p", [?LINE, Function, Args, R], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {'EXIT', R1, R2} -> orber:dbg("[~p] orber_web:~p(~p);~nEXIT: ~p~n~p", [?LINE, Function, Args, R1, R2], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {badrpc, Why} -> orber:dbg("[~p] orber_web:~p(~p);~nbadrpc: ~p", [?LINE, Function, Args, Why], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {'EXCEPTION', E} -> orber:dbg("[~p] orber_web:~p(~p);~nEXCEPTION: ~p", [?LINE, Function, Args, E], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\">Internal Error", State}; {error, Data} -> orber:dbg("[~p] orber_web:~p(~p); ~nReason: ~p", [?LINE, Function, Args, Data], ?DEBUG_LEVEL), {reply, Data, State}; Reply -> {reply, Reply, State} end; handle_call(stop, _From, State)-> {stop, normal, ok, State}; handle_call(What, _From, State)-> orber:dbg("[~p] orber_web_server:handle_call(~p);", [?LINE, What], ?DEBUG_LEVEL), {reply, "<BODY BGCOLOR=\"#FFFFFF\"><FONT SIZE=6>Unknown Request</FONT>", State}.
b45c31610c3eaf18fe4487a42f2680a66cc6de63d46149824eb96c5e109aa511
kxcteam/kxclib-ocaml
kxclib.ml
[%%define re (os_type = "re")] let refset r x = r := x (** [refset r x] sets [x] to ref [r]. *) let refget r = !r (** [refget r] returns [!r]. *) let refupdate r f = r := f !r (** [refupdate r f] updates referent of [r] by [f]. *) let refappend r x = r := x :: !r (** [refappend r x] appends [x] to referent of [r]. *) let refupdate' f r = r := f !r (** [refupdate' f r] is equivalent to [refupdate r f]. *) let refappend' x r = r := x :: !r (** [refappend' x r] is equivalent to [refappend r x]. *) let refpop r = match !r with h::t -> r:=t; h | [] -> raise Not_found * [ refpop r ] pop first item of the list referred to by [ r ] . { b Raises } [ Not_found ] if the list is empty . {b Raises} [Not_found] if the list is empty. *) let incr = refupdate' succ (** [incr r] increases the referent of [r] by one. *) let decr = refupdate' pred (** [decr r] decreases the referent of [r] by one. *) let refupdate'_and_get f r = r := f !r; !r let get_and_refupdate' f r = let x = !r in r := f !r; x let incr_and_get = refupdate'_and_get succ let decr_and_get = refupdate'_and_get pred let get_and_incr = get_and_refupdate' succ let get_and_decr = get_and_refupdate' pred let constant c = fun _ -> c (** constant function *) let identity x = x (** identity function *) let failwith' fmt = Format.kasprintf (failwith) fmt let invalid_arg' fmt = Format.kasprintf (invalid_arg) fmt let iotaf func n = let rec loop acc = function | m when m = n -> acc | m -> loop (func m :: acc) (succ m) in loop [] 0 |> List.rev let iotaf' func n = let rec loop = function | m when m = n -> () | m -> func m; loop (succ m) in loop 0 let iotafl binop acc0 n = let rec loop acc = function | m when m = n -> acc | m -> loop (binop acc m) (succ m) in loop acc0 0 let iotafl' binop acc0 g n = let rec loop acc = function | m when m = n -> acc | m -> loop (binop acc (g m)) (succ m) in loop acc0 0 let min_by f x y = if f y > f x then x else y let max_by f x y = if f y < f x then x else y module Functionals = struct let negate pred x = not (pred x) (** negate a predicate *) let both p g x = p x && g x let either p g x = p x || g x let dig2nd f a b = f b a * [ f ] dig the second argument of [ f ] to be the first . aka [ flip ] let dig3rd f c a b = f a b c * [ f ] dig the third argument of [ f ] to be the first let flip = dig2nd * [ f ] flip the first arguments of [ f ] . aka [ dig2nd ] let fix1st x f = f x * [ x f ] fix the first argument to [ f ] as [ x ] let fix2nd y f x = f x y * [ y f ] fix the second argument to [ f ] as [ y ] let fix3rd z f x y = f x y z * [ z f ] fix the third argument to [ f ] as [ z ] let fix1st' x f = fun _ -> f x * [ x f ] fix the first argument to [ f ] as [ x ] , but still accept ( and ignore ) the fixed argument let tap f x = f x; x let reptill judge f x = let rec loop y = if judge y then y else loop (f y) in loop (f x) (** [reptill judge f x] evaluates [f x] repeatedly till [judge (f x)] holds. *) let ntimes n f x = let rec loop acc = function | 0 -> acc | n -> loop (f acc) (n-1) in loop x n (** [ntimes n f x] applies [f] ntimes to [x]. *) let dotill judge f x = let rec loop y = if judge y then y else loop (f y) in loop (f x) (** [dotill judge f x] applies [f] to [x] repeatedly till [judge x] holds. *) let fixpoint ?maxn = match maxn with | None -> fun f x -> let rec loop (x,x') = if x = x' then x else loop (x', f x') in loop (x, f x) | Some 0 -> failwith "fixpoint not reached after 0 tries" | Some maxn -> fun f x -> let rec loop n (x,x') = if x = x' then x else if n = 0 then failwith' "fixpoint not reached after %d tries" maxn else loop (pred n) (x', f x') in loop (pred maxn) (x, f x) * [ fixpoint f ] try to resolve the fixpoint of f. [ ] , an optional argument , limits the number of iterations to find the fix point . [maxn], an optional argument, limits the number of iterations to find the fix point. *) let converge' judge f = let rec loop n (x, x') = match judge n x x' with | true -> Ok x' | false -> loop (succ n) (x', f x') in fun x -> loop 1 (x, f x) let converge judge f x = converge' (fun _ x x' -> judge x x') f x module BasicInfix = struct * function composition 1 let (%) : ('y -> 'z) -> ('x -> 'y) -> ('x -> 'z) = fun f g x -> x |> g |> f * function composition 1 , on second argument let (%%) : ('a -> 'y -> 'z) -> ('x -> 'y) -> ('a -> 'x -> 'z) = fun f g x y -> f x (g y) * function composition 2 let (&>) : ('x -> 'y) -> ('y -> 'z) -> ('x -> 'z) = fun g f x -> x |> g |> f let (?.) : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c = dig2nd let (?..) : ('a -> 'b -> 'c -> 'd) -> 'c -> 'a -> 'b -> 'd = dig3rd let (!.) : 'b -> ('a -> 'b -> 'c) -> 'b -> 'c = fix2nd let (!..) : 'c -> ('a -> 'b -> 'c -> 'd) -> 'a -> 'b -> 'd = fix3rd * function composition 2 , arity=2 let (&&>) : ('x -> 'y -> 'z) -> ('z -> 'r) -> ('x -> 'y -> 'r) = fun g f x y -> g x y |> f (** piping with tapping *) let (|->) : 'x -> ('x -> unit) -> 'x = fun x f -> (f x); x let (//) : ('a -> 'x) -> ('b -> 'y) -> ('a*'b -> 'x*'y) = fun fa fb (a, b) -> fa a, fb b let (/>) : 'a*'b -> ('b -> 'c) -> 'a*'c = fun (a, b) f -> a, f b let (/<) : 'a*'b -> ('a -> 'c) -> 'c*'b = fun (a, b) f -> f a, b * lift to snd let (?>) : ('b -> 'c) -> ('a*'b -> 'a*'c) = fun f -> fun (a, b) -> a, f b (** lift to fst *) let (?<) : ('a -> 'c) -> ('a*'b -> 'c*'b) = fun f -> fun (a, b) -> f a, b * lift to map snd let (?&>) : ('y2 -> 'x2) -> ('x1 * 'x2 -> 'r) -> 'x1 * 'y2 -> 'r = fun g f -> fun (x, y) -> f (x, g y) (** lift to map fst *) let (?&<) : ('y1 -> 'x1) -> ('x1 * 'x2 -> 'r) -> 'y1 * 'x2 -> 'r = fun g f -> fun (x, y) -> f (g x, y) (** uncurry *) let (!!) : ('a -> 'b -> 'x) -> ('a*'b -> 'x) = fun f -> fun (a, b) -> f a b (** curry *) let (!?) : ('a*'b -> 'x) -> ('a -> 'b -> 'x) = fun f -> fun a b -> f (a, b) end module CommonTypes = struct type 'x endo = 'x -> 'x end module Infix = BasicInfix end module Fn = Functionals include Functionals.BasicInfix include Functionals.CommonTypes module PipeOps(S : sig type _ t val map : ('x -> 'y) -> 'x t -> 'y t val iter : ('x -> unit) -> 'x t -> unit val fold_left : ('acc -> 'x -> 'acc) -> 'acc -> 'x t -> 'acc val filter : ('x -> bool) -> 'x t -> 'x t val filter_map : ('x -> 'y option) -> 'x t -> 'y t end) = struct open S (** piping map *) let (|&>) : 'x t -> ('x -> 'y) -> 'y t = fun xs f -> map f xs * piping map to snd let (|+&>) : 'x t -> ('x -> 'y) -> ('x*'y) t = fun xs f -> map (fun x -> x, f x) xs (** piping iter *) let (|!>) : 'x t -> ('x -> unit) -> unit = fun xs f -> iter f xs (** piping and iter-tapping *) let (|-!>) : 'x t -> ('x -> unit) -> 'x t = fun xs f -> iter f xs; xs (** piping fold_left *) let (|@>) : 'x t -> ('acc*('acc*'x -> 'acc)) -> 'acc = fun xs (z, f) -> fold_left (fun acc x -> f (acc, x)) z xs (** piping filter *) let (|?>) : 'x t -> ('x -> bool) -> 'x t = fun xs f -> filter f xs (** piping filter map *) let (|&?>) : 'x t -> ('x -> 'y option) -> 'y t = fun xs f -> filter_map f xs * piping filter map to snd let (|+&?>) : 'x t -> ('x -> 'y option) -> ('x*'y) t = fun xs f -> filter_map (fun x -> match f x with Some y -> Some (x, y) | None -> None) xs end module type Monadic = sig type _ t val return : 'x -> 'x t val bind : 'x t -> ('x -> 'y t) -> 'y t end module MonadOps(M : sig type _ t val return : 'x -> 'x t val bind : 'x t -> ('x -> 'y t) -> 'y t end) = struct let return x = M.return x let (>>=) = M.bind let (>>) : 'x M.t -> 'y M.t -> 'y M.t = fun ma mb -> ma >>= fun _ -> mb let (>|=) : 'x M.t -> ('x -> 'y) -> 'y M.t = fun ma f -> ma >>= fun x -> return (f x) let sequence_list ms = List.fold_left (fun acc m -> acc >>= fun acc -> m >>= fun x -> x :: acc |> return ) (return []) ms >>= fun xs -> List.rev xs |> return let (>>=*) : 'x M.t list -> ('x list -> 'y M.t) -> 'y M.t = fun ms af -> sequence_list ms >>= af end let foldl = List.fold_left * { ! } let foldr f z l = List.fold_right f l z (** {!List.fold_left} but arg pos exchanged *) let projected_compare proj a b = compare (proj a) (proj b) let neg = Int.neg let mul = Int.mul let div = Int.div let rem = Int.rem module Either = struct type ('a, 'b) t = Left of 'a | Right of 'b let left x = Left x let right x = Right x end type ('a, 'b) either = ('a, 'b) Either.t module Result = struct include Result * NB - returning only the first error let concat : ('x, 'e) result list -> ('x list, 'e) result = fun rs -> let rec loop acc = function | [] -> Ok acc | Ok x :: rest -> loop (x :: acc) rest | Error e :: _ -> Error e in loop [] (List.rev rs) end module ResultOf(E : sig type err end) = struct type err = E.err type 'x t = ('x, err) result let bind : 'x t -> ('x -> 'y t) -> 'y t = Result.bind let return : 'x -> 'x t = Result.ok end module ResultWithErrmsg0 = struct include ResultOf(struct type err = string end) let protect' : handler:(exn -> string) -> ('x -> 'y) -> ('x -> 'y t) = fun ~handler f x -> try Ok (f x) with exn -> Error (handler exn) let protect : ('x -> 'y) -> ('x -> 'y t) = fun f -> protect' ~handler:Printexc.to_string f end module Queue : sig type 'x t val empty : 'x t val is_empty : 'x t -> bool val push : 'x -> 'x t -> 'x t val push_front : 'x -> 'x t -> 'x t val pop : 'x t -> ('x * 'x t) option val peek : 'x t -> ('x * 'x t) option end = struct type 'x t = 'x list*'x list let empty = [], [] let is_empty = function | [], [] -> true | _ -> false let push x (r,u) = (x :: r, u) let push_front x (r,u) = (r, x :: u) let rec pop (r,u) = match u, r with | hd :: rest, _ -> Some (hd, (r, rest)) | [], (_ :: _) -> pop ([], List.rev r) | [], [] -> None let rec peek (r,u as q) = match u, r with | hd :: _, _ -> Some (hd, q) | [], (_ :: _) -> peek ([], List.rev r) | [], [] -> None end type 'x queue = 'x Queue.t module Option0 = struct include Option let return = some let get = function | Some x -> x | None -> raise Not_found let v default = function | Some x -> x | None -> default let v' gen_default = function | Some x -> x | None -> gen_default() let otherwise otherwise = function | Some x -> Some x | None -> otherwise let otherwise' otherwise_f = function | Some x -> Some x | None -> otherwise_f() let pp vpp ppf = Format.(function | Some x -> fprintf ppf "Some(%a)" vpp x | None -> fprintf ppf "None") let filter pred = function | Some x when pred x -> Some x | _ -> None let fmap f = function | None -> None | Some v -> ( match f v with | None -> None | Some v -> v) let of_bool = function | true -> Some () | false -> None let some_if cond x = if cond then Some x else None (** [try_make ~capture f] returns [Some (f())] except when - [f()] throws an [exn] s.t. [capture exn = true], it returns [None] - [f()] throws an [exn] s.t. [capture exn = false], it rethrows [exn] [~capture] defaults to [fun _exn -> true] *) let try_make : ?capture:(exn -> bool) -> (unit -> 'x) -> 'x option = fun ?(capture = constant true) f -> try f() |> some with exn -> if capture exn then none else raise exn (** a specialized version of [try_make] where [~capture] is fixed to [function Not_found -> true | _ -> false] *) let if_found : (unit -> 'x) -> 'x option = fun f -> try_make f ~capture:(function Not_found -> true | _ -> false) end module Option = struct include Option0 module Ops_monad = MonadOps(Option0) module Ops = struct include Ops_monad end end let some = Option.some let none = Option.none let (>?) o f = Option.map f o let (>>?) o f = Option.bind o f let (|?) o v = Option.v v o let (|?!) o v = Option.v' v o let (||?) o1 o2 = Option.otherwise o2 o1 let (||?!) o1 o2 = Option.otherwise' o2 o1 let (&>?) : ('x -> 'y option) -> ('y -> 'z) -> ('x -> 'z option) = fun af f -> af &> (Option.map f) module Seq0 = struct include Seq include PipeOps(Seq) let from : (unit -> 'x option) -> 'x t = fun f -> let rec next() = match f() with | None -> Nil | Some x -> Cons (x, next) in next let iota until_exclusive = let counter = ref 0 in from (fun() -> let x = !counter in if x = until_exclusive then None else ( incr counter; Some x ) ) let length s = fold_left (fun c _ -> succ c) 0 s let range ?include_endpoint:(ie=false) start end_ = let end_exclusive = if ie then succ end_ else end_ in iota (end_exclusive - start) |&> (+) start let enum start = let counter = ref start in from (fun () -> get_and_incr counter |> Option.some ) let rec limited quota orig() = if quota > 0 then ( let open Seq in match orig() with | Nil -> Nil | Cons (x, next) -> Cons (x, limited (pred quota) next) ) else Nil let iteri f s = let rec h i = function | Nil -> () | Cons(x, rest) -> f i x; h (i + 1) (rest()) in s() |> h 0 let hd s = match s() with | Nil -> raise Not_found | Cons(x, _) -> x let tl s = match s() with | Nil -> raise Not_found | Cons(_, t) -> t let take n s = match n with | _ when n < 0 -> failwith "panic" | _ -> let rec h n t () = match n, (t()) with | 0, _ -> Nil | _, Nil -> failwith "panic" | _, Cons(x, u) -> Cons(x, h (n - 1) u) in h n s let drop n s = Fn.ntimes n tl s let make n x = match n with | _ when n < 0 -> failwith "panic" | _ -> let rec h i () = match i with | 0 -> Nil | _ -> Cons(x, h (i - 1)) in h n end module Seq = struct include Seq0 module Ops_piping = PipeOps(Seq0) module Ops = struct include Ops_piping end end type 'x seq = 'x Seq.t module Array0 = struct include Array let filter f arr = arr |> to_seq |> Seq.filter f |> of_seq let filter_map f arr = arr |> to_seq |> Seq.filter_map f |> of_seq include PipeOps(struct include Array let filter = filter let filter_map = filter_map end) let of_list_of_length len list = let cell = ref list in init len (fun _ -> match !cell with | hd :: tl -> cell := tl; hd | [] -> raise Not_found) TODO optimization - specialized version when [ ? f ] not given let mean : ?f:('x -> float) -> float t -> float = fun ?f:(f=identity) arr -> let len = Array.length arr in if len = 0 then raise Not_found else let rec labor left right = match right - left with | 0 -> f arr.(left), 1 | 1 -> (f arr.(left) +. f arr.(right) ) /. 2., 2 | rlen -> if rlen < 0 then 0., 0 else let mid = left + (rlen / 2) in let lv, lw = labor left mid and rv, rw = labor (succ mid) right in let (!) = float_of_int in (lv *. !lw +.rv*. !rw) /. !(lw+rw), lw+rw in labor 0 (len-1) |> fst let min cmp arr = match length arr with | 0 -> raise Not_found | _ -> let cand = ref arr.(0) in iter (fun x -> if cmp x !cand < 0 then cand := x) arr; !cand let max cmp arr = match length arr with | 0 -> raise Not_found | _ -> let cand = ref arr.(0) in iter (fun x -> if cmp x !cand > 0 then cand := x) arr; !cand let first arr = match length arr with | 0 -> raise Not_found | _ -> arr.(0) let last arr = match length arr with | 0 -> raise Not_found | n -> arr.(n-1) let sorted cmp arr = sort cmp arr; arr let update : ('a -> 'a) -> 'a array -> int -> unit = fun f arr idx -> arr.(idx) <- f arr.(idx) let update_each : (int -> 'a -> 'a) -> 'a array -> unit = fun f arr -> arr |> Array.iteri (fun i x -> arr.(i) <- f i x) let blastsati : ('a -> bool) -> 'a array -> int = fun pred arr -> let pred i = pred arr.(i) in let rec loop pred l r = if l > r then raise Not_found else if l+1 = r then begin if pred r then r else l end else if l = r then begin if l = 0 && not (pred l) then raise Not_found else l end else let m = (l+r) / 2 in if pred m then loop pred m r else loop pred l (m-1) in loop pred 0 ((length arr) - 1) let blastsat : ('a -> bool) -> 'a array -> 'a = fun pred arr -> blastsati pred arr |> Array.get arr (** [blastsat] find the last element [e] such that [pred e] being [true] using binary search. more specifically, - when [pred] yields [false] for every element, [Not_found] is raised - when there exists [i >= 0] such that {v forall k <= i. (pred arr.(k)) = true /\ forall k > i, (pred arr.(k)) = false v} , the [i]-th element will be returned - otherwise, the behavior is undefined *) let swap arr idx1 idx2 = let tmp = arr.(idx2) in arr.(idx2) <- arr.(idx1); arr.(idx1) <- tmp let shuffle : ?rng:(int (* bound_exclusive *) -> int) -> 'x array -> unit = fun ?rng:(rng=Random.int) arr -> let len = Array.length arr in for i = len-1 downto 1 do swap arr i (rng (succ i)) done let to_function : 'a array -> (int -> 'a) = fun arr idx -> arr.(idx) end module Array = struct include Array0 module Ops_piping = PipeOps(Array0) module Ops_monad = PipeOps(Array0) module Ops = struct include Ops_piping include Ops_monad end end [%%if ocaml_version < (4, 14, 0)] module Stream = struct include Stream let to_list_rev stream = let result = ref [] in Stream.iter (fun value -> result := value :: !result) stream; !result let to_list stream = to_list_rev stream |> List.rev let hd stream = let open Stream in try next stream with | Failure -> raise Not_found let drop1 stream = let open Stream in let _ = try next stream with | Failure -> raise Not_found in stream let take n stream = let open Stream in let m_lst = try npeek n stream with | Failure -> raise Not_found | Error msg -> failwith msg in match List.length m_lst with | m when m = n -> m_lst | _ -> raise Not_found let drop n s = Fn.ntimes n drop1 s end [%%endif] module List0 = struct include PipeOps(List) include List let iota = function | 0 -> [] | k -> 0 :: (List.init (pred k) succ) let iota1 = function | 0 -> [] | k -> List.init k succ let range = let helper start end_ = iota (end_ - start) |&> (+) start in fun ?include_endpoint:(ie=false) -> if ie then (fun start end_ -> helper start (succ end_)) else (fun start end_ -> helper start end_) let dedup' ~by l = let set = Hashtbl.create (List.length l) in l |?> (fun x -> if Hashtbl.mem set (by x) then false else (Hashtbl.add set (by x) true; true)) let dedup l = dedup' ~by:identity l let update_assoc : 'k -> ('v option -> 'v option) -> ('k*'v) list -> ('k*'v) list = fun k func l -> let l', updated = l |> fold_left (fun (acc, updated) (key, v as ent) -> match updated, k = key with | false, true -> ( match func (some v) with | Some v' -> (key, v') :: acc, true | None -> acc, true) | _ -> ent :: acc, updated ) ([], false) in if not updated then ( match func none with | None -> l | Some v -> (k, v) :: l ) else rev l' let update_assq : 'k -> ('v option -> 'v option) -> ('k*'v) list -> ('k*'v) list = fun k func l -> let l', updated = l |> fold_left (fun (acc, updated) (key, v as ent) -> match updated, k == key with | false, true -> ( match func (some v) with | Some v' -> (key, v') :: acc, true | None -> acc, true) | _ -> ent :: acc, updated ) ([], false) in if not updated then ( match func none with | None -> l | Some v -> (k, v) :: l ) else rev l' let deassoc_opt : 'k -> ('k*'v) list -> 'v option*('k*'v) list = fun k es -> let rec loop (ret, es) = function | [] -> ret, es | (k', v) :: rest when k' = k -> we are not shortcutting here since appending two lists is still O(n ) .. loop (some v, es) rest | e :: rest -> loop (ret, e :: es) rest in loop (none, []) es (** [deassoc_opt k l] removes entry keyed [k] from [l], interpreted as an association list, and return [v, l'] where [v] is the value of the entry being removed or [None], and [l'] is the list after the removal, or semantically unchanged if the key does not exist. note that entries in [l'] may differ in order wrt. [l]. if there are multiple entries keyed [k], [v] will be [Some _] and [l'] will differ from the original, but otherwise the behavior is unspecified *) let deassq_opt : 'k -> ('k*'v) list -> 'v option*('k*'v) list = fun k es -> let rec loop (ret, es) = function | [] -> ret, es | (k', v) :: rest when k' == k -> we are not shortcutting here since appending two lists is still O(n ) .. loop (some v, es) rest | e :: rest -> loop (ret, e :: es) rest in loop (none, []) es (** same as [deassoc_opt] except using [(==)] when comparing keys *) let deassoc_opt' : 'k -> ('k*'v) list -> ('v*('k*'v) list) option = fun k es -> match deassoc_opt k es with | Some v, es -> Some (v, es) | None, _ -> None (** same as [deassoc_opt] but different return type *) let deassq_opt' : 'k -> ('k*'v) list -> ('v*('k*'v) list) option = fun k es -> match deassq_opt k es with | Some v, es -> Some (v, es) | None, _ -> None (** same as [deassq_opt] but different return type *) let deassoc : 'k -> ('k*'v) list -> 'v*('k*'v) list = fun k es -> let ov, es = deassoc_opt k es in Option.v' (fun() -> raise Not_found) ov, es (** same as [deassoc_opt] but throws [Not_found] when the requested key does not exist *) let deassq : 'k -> ('k*'v) list -> 'v*('k*'v) list = fun k es -> let ov, es = deassq_opt k es in Option.v' (fun() -> raise Not_found) ov, es (** same as [deassq_opt] but throws [Not_found] when the requested key does not exist *) let group_by : ('x -> 'k) -> 'x t -> ('k*'x t) t = fun kf l -> l |> fold_left (fun acc x -> let k = kf x in update_assoc k (function | Some xs -> x :: xs |> some | None -> some [x]) acc) [] let unzip l = List.fold_left (fun (l,s) (x,y) -> (x::l,y::s)) ([],[]) (List.rev l) let unzip3 l = List.fold_left (fun (l1,l2,l3) (x1,x2,x3) -> (x1::l1,x2::l2,x3::l3)) ([],[],[]) (List.rev l) let reduce f = function | [] -> raise Not_found | hd::tl -> foldl f hd tl let reduce_opt f = function | [] -> none | hd::tl -> foldl f hd tl |> some let min_opt cmp = function | [] -> none | hd::l -> let f acc x = if cmp acc x > 0 then x else acc in fold_left f hd l |> some let max_opt cmp = function | [] -> none | hd::l -> let f acc x = if cmp acc x < 0 then x else acc in fold_left f hd l |> some let min cmp = min_opt cmp &> Option.get let max cmp = min_opt cmp &> Option.get let foldl = foldl let foldr = foldr let hd = function | [] -> raise Not_found | h :: _ -> h let tl = function | [] -> raise Not_found | _ :: tail -> tail let take n l = let rec loop acc = function | 0, _ -> rev acc | n, hd::tl -> loop (hd::acc) (n-1, tl) | _ -> raise Not_found in loop [] (n, l) let drop n l = Fn.ntimes n tl l let make copies x = List.init copies (constant x) let count pred list = foldl (fun count x -> if pred x then succ count else count) 0 list (** [pred list] returns the number of elements [e] in [list] that satisfies [pred] *) let last list = foldl (fun _ x -> x) (List.hd list) list (** last element of list *) let and_last : 'x. 'x list -> 'x list*'x = fun xs -> match rev xs with | [] -> raise Not_found | l :: r -> rev r, l (** last element and rest of a list *) let iter' f f_last xs = let rec go = function | [x] -> f_last x | x :: rest -> f x; go rest | [] -> () in go xs let fmap : ('x -> 'y list) -> 'x list -> 'y list = fun f l -> let rec loop acc = function | [] -> acc | x :: r -> loop ((f x |> List.rev) :: acc) r in let rec collect acc = function | [] -> acc | [] :: r' -> collect acc r' | (h :: r) :: r' -> collect (h :: acc) (r :: r') in loop [] l |> collect [] let interpolate y xs = let rec loop acc = function | x :: [] -> x :: acc | [] -> acc | x :: xs -> loop (y :: x :: acc) xs in loop [] xs |> rev let filteri p l = let rec aux i acc = function | [] -> rev acc | x::l -> aux (i + 1) (if p i x then x::acc else acc) l in aux 0 [] l let empty = function [] -> true | _ -> false let to_function : 'a list -> (int -> 'a) = fun xs -> Array.(xs |> of_list |> to_function) let to_hashtbl : ('k*'v) list -> ('k, 'v) Hashtbl.t = fun xs -> Hashtbl.of_seq (to_seq xs) let pp ?sep ?parens vpp ppf xs = let open Format in let popen, pclose = match parens with | Some parens -> parens | None -> "[", "]" in let sep = match sep with | Some s -> s | None -> ";" in fprintf ppf "%s @[" popen; iter (fprintf ppf "%a%s@;" vpp |> Fn.fix2nd sep) xs; fprintf ppf "%s@]" pclose let bind ma af = fmap af ma let return x = [x] end module List = struct include List0 module Ops_piping = PipeOps(List0) module Ops_monad = PipeOps(List0) module Ops = struct include Ops_piping include Ops_monad end end include List.Ops_piping let iota = List.iota let iota1 = List.iota1 module Hashtbl = struct include Hashtbl let rev : ('a, 'b) t -> ('b, 'a) t = fun orig -> to_seq orig |> Seq.map (fun (k,v) -> (v,k)) |> of_seq (** swap the key and value *) let to_function : ('a, 'b) t -> 'a -> 'b = Hashtbl.find * [ make n genfunc ] creates a hashtable of [ n ] elements with entries [ { ( fst ( genfunc 0 ) ) |- > ( snd ( genfunc 0 ) ) , ( fst ( genfunc 1 ) ) |- > ( snd ( genfunc 1 ) ) ... , ( fst ( ( n-1 ) ) ) |- > ( snd ( ( n-1 ) ) ) } ] [{ (fst (genfunc 0)) |-> (snd (genfunc 0)) , (fst (genfunc 1)) |-> (snd (genfunc 1)) ... , (fst (genfunc (n-1))) |-> (snd (genfunc (n-1))) }] *) let make ?random : int -> (int -> 'a * 'b) -> ('a, 'b) Hashtbl.t = fun n genfunc -> let table = Hashtbl.create ?random n in Seq.iota n |> Seq.map genfunc |> Hashtbl.add_seq table; table end module String = struct include String * [ empty str ] returns true when is of zero length let empty str = length str = 0 * [ empty_trimmed str ] returns true when is of zero length after being trimmed let empty_trimmed str = length (trim str) = 0 * [ chop_prefix p s ] returns [ s ] minus the prefix [ p ] wrapped in [ Some ] , or [ None ] if [ s ] does not start with [ p ] or [None] if [s] does not start with [p] *) let chop_prefix prefix = let plen = length prefix in fun str -> let slen = length str in if slen < plen then None else if (sub str 0 plen) = prefix then Some (sub str plen (slen-plen)) else None (** [starts_with p s] returns whether [s] starts with a substring of [p] *) let starts_with prefix str = chop_prefix prefix str |> Option.is_some (** [ends_with p s] returns whether [s] ends with a substring of [p] *) let ends_with postfix str = let plen, slen = length postfix, length str in if slen < plen then false else (sub str (slen-plen) plen) = postfix * [ chop_prefix p s ] returns [ s ] minus the suffix [ p ] wrapped in [ Some ] , or [ None ] if [ s ] does not end with [ p ] or [None] if [s] does not end with [p] *) let chop_suffix suffix = let plen = length suffix in fun str -> let slen = length str in if slen < plen then None else if (sub str (slen-plen) plen) = suffix then ( Some (sub str 0 (slen-plen)) ) else None let to_bytes = Bytes.of_string let to_list str = to_seq str |> List.of_seq let of_list = List.to_seq &> of_seq let of_array = Array.to_seq &> of_seq let pp_json_escaped : Format.formatter -> string -> unit = fun ppf str -> let len = length str in let getc = unsafe_get str in let addc = Format.pp_print_char ppf in let adds = Format.pp_print_string ppf in let addu x = adds "\\u"; adds (Format.sprintf "%04x" x) in let addb n k = iotaf' (fun i -> addc (getc (n + i))) k in let flush = Format.pp_print_flush ppf in let raise' pos = invalid_arg' "json_escaped: invalid/incomplete utf-8 string at pos %d" pos in let rec loop n = if (n-1) mod 64 = 0 then flush(); let adv k = loop (n + k) in let check k = if not (n + k <= len) then raise' (n+k-1) in if succ n > len then () else ( match getc n with | '"' -> adds "\\\""; adv 1 | '\\' -> adds "\\\\"; adv 1 | '\b' -> adds "\\b"; adv 1 | '\012' -> adds "\\f"; adv 1 | '\n' -> adds "\\n"; adv 1 | '\r' -> adds "\\r"; adv 1 | '\t' -> adds "\\t"; adv 1 | '\127' -> addu 127; adv 1 | c -> let x1 = int_of_char c in if x1 < 32 then (addu x1; adv 1) else if x1 < 127 then (addc c; adv 1) else ( check 2; let spit k = check k; addb n k; adv k in if x1 land 0xe0 = 0xc0 then ( 2byte utf8 ) else if (x1 land 0xf0 = 0xe0) then ( 3byte ) else if (x1 land 0xf8 = 0xf0) then ( spit 4 (* 4byte utf8 *) ) else raise' n ) ) in loop 0 let json_escaped : string -> string = Format.asprintf "%a" pp_json_escaped end module MapPlus (M : Map.S) = struct let pp' kpp vpp ppf m = let open Format in fprintf ppf "{ "; pp_open_hovbox ppf 0; M.bindings m |> List.iter' (fun (key, value) -> fprintf ppf "@[<hov 0>%a=@,@[<hov 0>%a@];@]@;<1 2>@?" kpp key vpp value) (fun (key, value) -> fprintf ppf "@[<hov 0>%a=@,@[<hov 0>%a@];@] }@?" kpp key vpp value); pp_close_box ppf () [%%if not(re)] let of_list : (M.key * 'v) list -> 'v M.t = fun kvs -> kvs |> M.of_seq % List.to_seq [%%endif] end module StringMap = struct include Map.Make(String) include MapPlus(Map.Make(String)) let pp vpp ppf m = pp' Format.pp_print_string vpp ppf m end module IntMap = struct include Map.Make(Int) include MapPlus(Map.Make(Int)) let pp vpp ppf m = pp' Format.pp_print_int vpp ppf m end module IoPervasives = struct let with_input_file path f = let ch = open_in path in let r = try f ch with e -> close_in ch; raise e in close_in ch; r let with_output_file path f = let ch = open_out path in let r = try f ch with e -> close_out ch; raise e in close_out ch; r let slurp_input ?buf ic = let buf = match buf with | None -> Bytes.make 4096 '\000' | Some buf -> buf in let result = ref "" in let rec loop len = match input ic buf 0 len with | 0 -> result | rlen -> result := !result^(Bytes.sub_string buf 0 rlen); loop len in !(loop (Bytes.length buf)) let slurp_stdin ?buf () = slurp_input ?buf stdin (* optimization *) let slurp_file path = with_input_file path slurp_input [@@warning "-48"] let spit_file path str = with_output_file path (Fn.flip output_string str) end include IoPervasives module Timing = struct (** time the execution of [f], returning the result of [f] and store the measured time in [output] *) let timefunc' output f = let t = Sys.time() in let r = f () in output := Sys.time()-.t; r (** time the execution of [f], discarding the result of [f] *) let timefunc f = let time = ref 0. in timefunc' time f |> ignore; !time end module Int53p = struct type int53p_impl_flavor = [ | `int_impl | `int64_impl | `float_impl | `custom_impl of string ] let pp_int53p_impl_flavor : Format.formatter -> int53p_impl_flavor -> unit = fun ppf -> let open Format in function | `int_impl -> pp_print_string ppf "int_impl" | `int64_impl -> pp_print_string ppf "int64_impl" | `float_impl -> pp_print_string ppf "float_impl" | `custom_impl s -> fprintf ppf "custom_impl(%s)" s let show_int53p_impl_flavor : int53p_impl_flavor -> string = Format.asprintf "%a" pp_int53p_impl_flavor module type Ops = sig type int53p val ( ~-% ) : int53p -> int53p val ( ~+% ) : int53p -> int53p val ( +% ) : int53p -> int53p -> int53p val ( -% ) : int53p -> int53p -> int53p val ( *% ) : int53p -> int53p -> int53p val ( /% ) : int53p -> int53p -> int53p val ( /%% ) : int53p -> int53p -> int53p (* rem *) end module type S = sig val impl_flavor : int53p_impl_flavor module Ops : Ops include Ops with type int53p = Ops.int53p val zero : int53p val one : int53p val minus_one : int53p val neg : int53p -> int53p val add : int53p -> int53p -> int53p val succ : int53p -> int53p val pred : int53p -> int53p val sub : int53p -> int53p -> int53p val mul : int53p -> int53p -> int53p val div : int53p -> int53p -> int53p val rem : int53p -> int53p -> int53p val abs : int53p -> int53p val equal : int53p -> int53p -> bool val compare : int53p -> int53p -> int val min : int53p -> int53p -> int53p val max : int53p -> int53p -> int53p val to_float : int53p -> float val of_float : float -> int53p val to_int : int53p -> int val of_int : int -> int53p val to_int64 : int53p -> int64 val of_int64 : int64 -> int53p [%%if not(re)] val to_nativeint : int53p -> nativeint val of_nativeint : nativeint -> int53p [%%endif] val to_string : int53p -> string val of_string : string -> int53p end module Internals = struct module MakeOps(M : sig type int53p val neg : int53p -> int53p val add : int53p -> int53p -> int53p val sub : int53p -> int53p -> int53p val mul : int53p -> int53p -> int53p val div : int53p -> int53p -> int53p val rem : int53p -> int53p -> int53p end) : Ops with type int53p = M.int53p = struct type int53p = M.int53p let ( ~-% ) : int53p -> int53p = M.neg let ( ~+% ) : int53p -> int53p = identity let ( +% ) : int53p -> int53p -> int53p = M.add let ( -% ) : int53p -> int53p -> int53p = M.sub let ( *% ) : int53p -> int53p -> int53p = M.mul let ( /% ) : int53p -> int53p -> int53p = M.div let ( /%% ) : int53p -> int53p -> int53p = M.rem end module IntImpl : S = struct let impl_flavor = `int_impl include Int [%%if ocaml_version < (4, 13, 0)] let min (a: int) (b: int) = min a b let max (a: int) (b: int) = max a b [%%endif] module Ops = MakeOps(struct type int53p = int include Int end) include Ops let to_int = identity let of_int = identity let to_int64 = Int64.of_int let of_int64 = Int64.to_int let to_float = float_of_int let of_float = int_of_float [%%if not(re)] let to_nativeint = Nativeint.of_int let of_nativeint = Nativeint.to_int [%%endif] let of_string = int_of_string end module Int64Impl : S = struct let impl_flavor = `int64_impl include Int64 [%%if ocaml_version < (4, 13, 0)] let min (a: int64) (b: int64) = min a b let max (a: int64) (b: int64) = max a b [%%endif] module Ops = MakeOps(struct type int53p = int64 include Int64 end) include Ops let of_int64 = identity let to_int64 = identity end module FloatImpl : S = struct let impl_flavor = `float_impl there is a problem with int_of_float in at least JSOO , and type int = float in both JSOO and BuckleScript runtime and type int = float in both JSOO and BuckleScript runtime *) let to_int, of_int = match Sys.backend_type with | Other "js_of_ocaml" | Other "BS" -> Obj.magic, Obj.magic | _ -> Float.(to_int, of_int) let round_towards_zero x = let open Float in if x < 0. then x |> neg % floor % neg else floor x module Float' = struct let zero = Float.zero let one = Float.one let minus_one = Float.minus_one let succ = Float.succ let pred = Float.pred let neg = Float.neg let add = Float.add let sub = Float.sub let mul = Float.mul let rem = Float.rem let abs = Float.abs let equal = Float.equal let compare = Float.compare let min = Float.min let max = Float.max let div a b = Float.div a b |> round_towards_zero let to_int = to_int let of_int = of_int let to_string = Float.to_string end include Float' module Ops = MakeOps(struct type int53p = float include Float' end) include Ops let of_float = identity let to_float = identity let to_int64 = Int64.of_float let of_int64 = Int64.to_float [%%if not(re)] let to_nativeint = Nativeint.of_float let of_nativeint = Nativeint.to_float [%%endif] let of_string = float_of_string end let current_impl_flavor = if Sys.int_size >= 53 then `int_impl else match Sys.backend_type with | Other "js_of_ocaml" | Other "BS" -> `float_impl | _ -> `int64_impl let impl_of_builtin_flavor : int53p_impl_flavor -> (module S) = function | `int_impl -> (module IntImpl) | `int64_impl -> (module Int64Impl) | `float_impl -> (module FloatImpl) | flavor -> failwith' "non-builtin int53p_impl_flavor: %a" pp_int53p_impl_flavor flavor module CurrentFlavorImpl = (val (impl_of_builtin_flavor current_impl_flavor)) end include Internals.CurrentFlavorImpl end include Int53p.Ops module Datetime0 : sig (** all according to proleptic Gregorian Calender *) val leap_year : int -> bool val daycount_of_month : leap:bool -> int -> int val day_of_year : int -> int -> int -> int module type NormalizedTimestamp = sig (** timezone not taking into consideration *) module Conf : sig val epoch_year : int * the epoch would be at January 1st 00:00:00.0 in [ epoch_year ] val subsecond_resolution : int * e.g. sec - resolution use [ 1 ] and millisec - resolution use [ 1000 ] val min_year : int (** min-year supported *) val max_year : int (** max-year supported *) end val normalize : ?subsec:int -> ?tzoffset:(int*int) -> int*int*int -> int*int*int -> int * [ normalize ? tzoffset:(tzhour , tzmin ) ? subsec ( yy , , dd ) ( hour , min , sec ) ] calculates the normalized timestamp ?tzoffset:(tzhour, tzmin) ?subsec (yy, mm, dd) (hour, min, sec)] calculates the normalized timestamp *) end module EpochNormalizedTimestamp (Conf : sig * see NormalizedTimestamp val epoch_year : int val subsecond_resolution : int end) : NormalizedTimestamp module UnixTimestmapSecRes : NormalizedTimestamp module UnixTimestmapMilliRes : NormalizedTimestamp module UnixTimestmapNanoRes : NormalizedTimestamp end = struct let sum = List.foldl (+) 0 let days_of_months_nonleap = List.to_function @@ [ 0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31; ] let days_of_months_leap = List.to_function @@ [ 0; 31; 29; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31; ] let days_of_months_subsum_nonleap = List.( iota 13 |&> (fun x -> iota x |&> days_of_months_nonleap |> sum) |> to_function) let days_of_months_subsum_leap = let sum = List.foldl (+) 0 in List.( iota 13 |&> (fun x -> iota x |&> days_of_months_leap |> sum) |> to_function) let daycount_of_month ~leap = let table = if leap then days_of_months_leap else days_of_months_nonleap in fun mm -> table mm let leap_year yy = let div x = yy mod x = 0 in if not (div 4) then false else if not (div 100) then true else if div 400 then true else false let day_of_year yy = let table = match leap_year yy with | false -> days_of_months_subsum_nonleap | true -> days_of_months_subsum_leap in fun mm dd -> table mm + dd module type NormalizedTimestamp = sig module Conf : sig val epoch_year : int val subsecond_resolution : int val min_year : int val max_year : int end val normalize : ?subsec:int -> ?tzoffset:(int*int) -> int*int*int -> int*int*int -> int * [ normalize yy mm dd ? subsec hour min sec ] calculates the normalized timestamp end (* XXX tests *) module EpochNormalizedTimestamp (Conf : sig val epoch_year : int val subsecond_resolution : int end) = struct module Conf = struct include Conf let min_year = Conf.epoch_year let max_year = let span = (pred Int.max_int) / (366*24*60*60*subsecond_resolution) in span-1+min_year end open Conf let yearcount_leaping ymin ymax = let roundup div = fun x -> if x mod div = 0 then x else div*(succ (x/div)) in let ncat div = let span = ymax - (roundup div ymin) in if span < 0 then 0 else succ (span/div) in let ncat4 = ncat 4 in let ncat100 = ncat 100 in let ncat400 = ncat 400 in ncat4 - ncat100 + ncat400 let normalize ?subsec ?tzoffset (yy, mm, dd) (hour, min, sec) = let subsec = Option.(value ~default:0 subsec) in if yy < min_year || yy > max_year then invalid_arg Format.(asprintf "%s.normalize - timestamp cannot be handled: \ %d-%d-%d %02d:%02d:%02d (subsec: %d/%d) - \ year out of range (%d-%d)" "/kxclib.ml/.Datetime0.EpochNormalizedTimestamp" yy mm dd hour min sec subsec subsecond_resolution min_year max_year); if subsec >= subsecond_resolution then invalid_arg Format.(sprintf "%s.normalize - subsec out of range (%d-%d)" "/kxclib.ml/.Datetime0.EpochNormalizedTimestamp" 0 (pred subsecond_resolution)); let days_past_years = let ymin, ymax = epoch_year, pred yy in let leaping = yearcount_leaping ymin ymax in let nonleaping = ymax-ymin+1-leaping in leaping*366+nonleaping*365 in let doy = day_of_year yy mm dd in let hour, min = match tzoffset with | None -> hour, min | Some (tzhour, tzmin) -> hour+tzhour, min+tzmin in let nts = sec + min*60 + hour*60*60 + (days_past_years + doy)*24*60*60 in let nts = nts * subsecond_resolution + subsec in nts end module UnixTimestmapSecRes = EpochNormalizedTimestamp(struct let epoch_year = 1970 let subsecond_resolution = 1 end) module UnixTimestmapMilliRes = EpochNormalizedTimestamp(struct let epoch_year = 1970 let subsecond_resolution = 1000 end) module UnixTimestmapNanoRes = EpochNormalizedTimestamp(struct let epoch_year = 1970 let subsecond_resolution = 1000*1000*1000 end) end module ParseArgs = struct type optparser = string -> [`Process_next of bool] let prefset r x = r := x let prefsetv r v _ = r := v let scanfparser fmt fn : optparser = fun str -> Scanf.ksscanf str (fun _ _ -> `Process_next true) fmt fn; `Process_next false let exactparser fmt (fn : unit -> unit) : optparser = function | str when str = fmt -> fn (); `Process_next false | _ -> `Process_next true let parse_opts (optparsers : optparser list) ?argsource:(argsource=Sys.argv, 1) () = let rec tryparse str = function | [] -> raise (Invalid_argument ("unparsed option: "^str)) | p::ps -> match (p : optparser) str with | `Process_next true -> tryparse str ps | `Process_next false -> () in Array.to_list (fst argsource) |> List.drop (snd argsource) |!> Fn.fix2nd optparsers tryparse let parse_opts_args ?optprefix:(optprefix="-") ?optsep:(optsep="--") (optparsers : optparser list) ?argsource:(argsource=Sys.argv, 1) () = let source, startidx = argsource in let optprefixlen = String.length optprefix in let prefixed str = if String.length str < optprefixlen then false else (String.sub str 0 optprefixlen) = optprefix in let argc = Array.length source in let args = ref [] in let rec tryparse str = function | [] -> raise (Invalid_argument ("unparsed option: "^str)) | p::ps -> match p str with | `Process_next true -> tryparse str ps | `Process_next false -> () in let tryparse = Fn.fix2nd optparsers tryparse in let rec loop n parseopt = if n >= argc then List.rev !args else begin let arg = source.(n) in if not parseopt then (refappend args arg; loop (succ n) parseopt) else if arg = optsep then loop (succ n) false else if prefixed arg then (tryparse arg; loop (succ n) parseopt) else (refappend args arg; loop (succ n) parseopt) end in loop startidx true end module ArgOptions = struct type _ named_option = | IntOption : string -> int named_option | FloatOption : string -> float named_option | StringOption : string -> string named_option | InChannelOption : string -> in_channel named_option | OutChannelOption : string -> out_channel named_option | InChannelOption' : string -> (in_channel*channel_desc) named_option | OutChannelOption' : string -> (out_channel*channel_desc) named_option and channel_desc = [ `StandardChannel | `FileChannel of string ] let opt_of_named_option (type x) (opt : x named_option) = match opt with | IntOption opt -> opt | FloatOption opt -> opt | StringOption opt -> opt | InChannelOption opt -> opt | OutChannelOption opt -> opt | InChannelOption' opt -> opt | OutChannelOption' opt -> opt module type FeatureRequests = sig val has_flag : ?argsource:(string array*int) -> ?prefix:string -> string (** flag *) -> bool val get_option : ?argsource:(string array*int) -> ?optprefix:string -> ?optsep:string -> 'x named_option -> 'x val get_option_d : ?argsource:(string array*int) -> ?optprefix:string -> ?optsep:string -> 'x named_option -> 'x (** default value *) -> 'x val get_option_d' : ?argsource:(string array*int) -> ?optprefix:string -> ?optsep:string -> 'x named_option -> (unit -> 'x) (** default value producer *) -> 'x val get_args : ?argsource:(string array*int) -> ?optsep:string -> unit -> string list end let has_flag ?argsource ?prefix:(prefix="") flag = let store = ref false in ParseArgs.( parse_opts [ exactparser (prefix^flag) (fun () -> store := true); (constant (`Process_next false)) ]) ?argsource (); !store let get_option ?argsource ?prefix:(prefix="") ?optsep (type x) : x named_option -> x option = let open ParseArgs in let labor opt f = let state = ref `Init in let result = ref None in let marker_raw = prefix^opt in let marker_eq = marker_raw^"=" in let par arg = match !state with | `Init when arg = marker_raw -> state := `CaptureNext; `Process_next true | `Init -> (match String.chop_prefix marker_eq arg with | Some arg -> result := Some (f arg); `Process_next false | None -> `Process_next true) | `CaptureNext -> (state := `Init; result := Some (f arg)); `Process_next false in parse_opts_args ?argsource ~optprefix:"" ?optsep [par; constant (`Process_next false)] () |> ignore; match !state with | `Init -> !result | `CaptureNext -> invalid_arg ("no argument supplied to option "^opt) in function | IntOption opt -> labor opt (fun arg -> Scanf.sscanf arg "%i%!" identity) | FloatOption opt -> labor opt (fun arg -> Scanf.sscanf arg "%g%!" identity) | StringOption opt -> labor opt identity | InChannelOption opt -> labor opt (function | "-" -> stdin | path -> open_in path) | OutChannelOption opt -> labor opt (function | "-" -> stdout | path -> open_out path) | InChannelOption' opt -> labor opt (function | "-" -> stdin, `StandardChannel | path -> open_in path, `FileChannel path) | OutChannelOption' opt -> labor opt (function | "-" -> stdout, `StandardChannel | path -> open_out path, `FileChannel path) let get_option_exn ?argsource ?prefix ?optsep (type x) : x named_option -> x = fun opt -> match get_option ?argsource ?prefix ?optsep opt with | None -> invalid_arg ("you have to provide option "^(opt_of_named_option opt)) | Some x -> x let get_option_d' ?argsource ?prefix ?optsep (type x) : x named_option -> (unit -> x) -> x = fun opt vp -> match get_option ?argsource ?prefix ?optsep opt with | None -> vp() | Some x -> x let get_option_d ?argsource ?prefix ?optsep (type x) : x named_option -> x -> x = fun opt v -> match get_option ?argsource ?prefix ?optsep opt with | None -> v | Some x -> x let get_absolute_args ?optsep:(optsep="--") ?argsource:(argsource=Sys.argv, 1) () = let source, startidx = argsource in let argc = Array.length source in let args = ref [] in let rec loop n record_arg = if n >= argc then List.rev !args else begin let arg = source.(n) in if record_arg then (refappend args arg; loop (succ n) record_arg) else if arg = optsep then loop (succ n) true else loop (succ n) record_arg end in loop startidx false end module FmtPervasives = struct type ppf = Format.formatter let color_enabled = ref true let fprintf ppf fmt = Format.fprintf ppf fmt let printf fmt = Format.printf fmt let sprintf fmt = Format.asprintf fmt let eprintf fmt = Format.eprintf fmt module Fmt = struct let stdout_ppf = Format.std_formatter let stderr_ppf = Format.err_formatter let null_ppf = Format.formatter_of_out_functions { out_string = (fun _ _ _ -> ()); out_flush = (fun _ -> ()); out_newline = (fun _ -> ()); out_spaces = (fun _ -> ()); out_indent = (fun _ -> ()); } let colored ?style ?color_mode:(m=`Fg) color ppf fmt = if !color_enabled then ( let code_table = function (* `Color -> (fg_code, bg_code) *) | `Black -> 30, 40 | `Red -> 31, 41 | `Green -> 32, 42 | `Yellow -> 33, 43 | `Blue -> 34, 44 | `Magenta -> 35, 45 | `Cyan -> 36, 46 | `White -> 37, 47 | `Bright_black -> 90, 100 | `Bright_red -> 91, 101 | `Bright_green -> 92, 102 | `Bright_yellow -> 93, 103 | `Bright_blue -> 94, 104 | `Bright_magenta -> 95, 105 | `Bright_cyan -> 96, 106 in let style_table = function | `Bold -> 1 | `Thin -> 2 | `Italic -> 3 | `Underline -> 4 in let esc x = "\027"^x in let reset = "[0m" in let color_code = code_table color |> (match m with `Fg -> fst | `Bg -> snd) |> sprintf "[%dm" in let style_code = style |> function | None -> None | Some s -> style_table s |> sprintf "[%dm" |> Option.some in (* start *) Format.fprintf ppf "@<0>%s" ((esc color_code)^(style_code |> Option.map esc |? "")); (* contents *) Format.kfprintf (fun ppf -> (* end *) Format.fprintf ppf "@<0>%s" (esc reset)) ppf (* contents *) fmt ) else Format.fprintf ppf fmt end let condformat cond fmtfunc fmt = if cond then fmtfunc fmt else Format.ifprintf Fmt.null_ppf fmt let pp_of_to_string to_string ppf x = Format.pp_print_string ppf (to_string x) let to_string_of_pp pp = sprintf "%a" pp let pps to_string = pp_of_to_string to_string let spp pp = to_string_of_pp pp let pp_int = Format.pp_print_int let pp_float = Format.pp_print_float let pp_string = Format.pp_print_string let pp_char = Format.pp_print_char let pp_bool = Format.pp_print_bool let pp_unit ppf () = pp_string ppf "unit" let pp_ref_address ppf (r : 'x ref) = fprintf ppf "%#x" (2*(Obj.magic r)) let pp_int32 ppf x = Int32.to_string x |> pp_string ppf let pp_int64 ppf x = Int64.to_string x |> pp_string ppf * print integer with thousand separator let pp_integer_sep' ~padding ppf x = let rec loop acc x = if x > 0 then loop ((x mod 1000) :: acc) (x / 1000) else acc in let chunks = loop [] (abs x) in let chunks = match chunks with | [x] -> [string_of_int x] | h :: r -> string_of_int h :: (r |&> sprintf "%03d") | [] -> ["0"] in if x < 0 then pp_char ppf '-'; let str = String.concat "," chunks in (match padding with | None -> () | Some (0, _) -> () | Some (d, pad) -> let d = d + (Float.ceil (float_of_int d /. 3.) |> int_of_float) - 1 in let slen = String.length str in if d > slen then Fn.ntimes (d-slen) (fun() -> pp_char ppf pad) ()); pp_string ppf str let pp_integer_sep ppf = pp_integer_sep' ~padding:None ppf let pp_multiline ppf str = let open Format in let rec loop = function | [line] -> pp_string ppf line | line :: rest -> pp_string ppf line; pp_force_newline ppf (); loop rest | [] -> () in String.split_on_char '\n' str |> loop let pp_exn ppf exn = Printexc.to_string exn |> Format.pp_print_string ppf let pp_full_exn' ppf (exn, bt) = Format.fprintf ppf "@<2>%s@[<hov>@\n%a@]" (Printexc.to_string exn) pp_multiline Printexc.(bt |> raw_backtrace_to_string) let pp_full_exn ppf exn = pp_full_exn' ppf (exn, Printexc.(get_raw_backtrace())) let string_of_symbolic_output_items : Format.symbolic_output_item list -> string = fun items -> let buf = Buffer.create 0 in items |!> (function | Output_flush -> () | Output_newline -> Buffer.add_char buf '\n' | Output_string str -> Buffer.add_string buf str | Output_spaces n | Output_indent n -> Buffer.add_string buf (String.make n ' ')); Buffer.contents buf end include FmtPervasives module Log0 = struct open Format module Internals = struct let timestamp_func = ref (constant None) let logging_formatter = ref err_formatter end open Internals module LoggingConfig = struct let install_timestamp_function func = timestamp_func := func let set_logging_formatter ppf = logging_formatter := ppf let get_logging_formatter() = !logging_formatter end let logr fmt = fprintf !logging_formatter fmt let log ~label ?modul ?header_style:(style=None) ?header_color:(color=`Magenta) fmt = let header = match modul with | None -> label | Some m -> label^":"^m in let header = match !timestamp_func() with | None -> sprintf "[%s]" header | Some ts -> sprintf "[%s :%.3f]" header ts in let pp_header ppf = Fmt.colored ?style color ppf "%s" in logr "@<1>%s @[<hov>" (asprintf "%a" pp_header header); kfprintf (fun ppf -> fprintf ppf "@]@.") !logging_formatter fmt let verbose ?modul fmt = log ?modul fmt ~label:"VERBOSE" ~header_style:(Some `Thin) ~header_color:`Bright_cyan let info ?modul fmt = log ?modul fmt ~label:"INFO" ~header_style:(Some `Bold) ~header_color:`Bright_cyan let warn ?modul fmt = log ?modul fmt ~label:"WARN" ~header_style:(Some `Bold) ~header_color:`Yellow let debug ?modul fmt = log ?modul fmt ~label:"DEBUG" ~header_style:(Some `Bold) ~header_color:`Magenta let error ?modul fmt = log ?modul fmt ~label:"ERROR" ~header_style:(Some `Bold) ~header_color:`Red module Pervasives = struct let debug ?modul fmt = debug ?modul fmt let info ?modul fmt = info ?modul fmt end end include Log0.Pervasives module Json : sig type jv = [ | `null | `bool of bool | `num of float | `str of string | `arr of jv list | `obj of (string*jv) list ] type jv_field = string*jv type jv_fields = jv_field list val normalize : jv -> jv val normalize_fields : jv_fields -> jv_fields val eqv : jv -> jv -> bool * whether two json value are equivalent , i.e. equal while ignoring ordering of object fields val pp_unparse : ppf -> jv -> unit * [ pp_unparse ppf j ] output [ j ] as a JSON string . NB : this function does not check if [ j ] contains any [ ` str s ] where [ s ] is an invalid UTF-8 string . it just assumes so . NB: this function does not check if [j] contains any [`str s] where [s] is an invalid UTF-8 string. it just assumes so. *) val unparse : jv -> string (** [unparse j] convert [j] to a JSON string using [pp_unparse]. see [pp_unparse] for caveats. *) val pp_lit : ppf -> jv -> unit * [ pp_lit j ] output [ j ] in a format that can be used as an OCaml literal . val show : jv -> string (** [show j] convert [j] to a string using [pp_lit], which is a string that can be used as an OCaml literal. *) type jvpath = ([ | `f of string (** field within an object *) | `i of int (** index within an array *) ] as 'path_component) list (** an empty path designate the root element *) type legacy = [ | `arr of jv list | `obj of (string*jv) list ] val of_legacy : legacy -> jv val to_legacy : jv -> legacy option (** Yojson.Safe.t *) type yojson = ([ | `Null | `Bool of bool | `Int of int | `Intlit of string | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list | `Tuple of 't list | `Variant of string * 't option ] as 't) val of_yojson : yojson -> jv val to_yojson : jv -> yojson (** Yojson.Basic.t *) type yojson' = ([ | `Null | `Bool of bool | `Int of int | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list ] as 't) val yojson_basic_of_safe : yojson -> yojson' val yojson_safe_of_basic : yojson' -> yojson type jsonm = jsonm_token seq and jsonm_token = [ | `Null | `Bool of bool | `String of string | `Float of float | `Name of string | `As | `Ae | `Os | `Oe ] type 'loc jsonm' = ('loc*jsonm_token) seq type 'loc jsonm_pe (* pe = parsing_error *) = [ | `empty_document | `premature_end of 'loc (** with loc of the starting token of the inner-most structure (viz. array/object) *) | `expecting_value_at of 'loc | `unexpected_token_at of 'loc*jsonm_token ] val of_jsonm' : 'loc jsonm' -> (jv * 'loc jsonm', 'loc jsonm_pe) result val of_jsonm : jsonm -> (jv * jsonm) option val to_jsonm : jv -> jsonm end = struct type jv = [ | `null | `bool of bool | `num of float | `str of string | `arr of jv list | `obj of (string*jv) list ] let sort_by_key fs = fs |> List.sort_uniq (fun (k1, _) (k2, _) -> String.compare k1 k2) let rec eqv a b = match a, b with | `null, `null -> true | `bool a, `bool b -> a = b | `num a, `num b -> a = b | `str a, `str b -> a = b | `arr xs, `arr ys -> let rec loop = function | [], [] -> true | x :: xs, y :: ys when eqv x y -> loop (xs, ys) | _ -> false in loop (xs, ys) | `obj fs1, `obj fs2 -> let sort = sort_by_key in let fs1, fs2 = sort fs1, sort fs2 in let rec loop = function | [], [] -> true | (k1, x) :: xs, (k2, y) :: ys when k1 = k2 && eqv x y -> loop (xs, ys) | _ -> false in loop (fs1, fs2) | _ -> false type jv_field = string*jv type jv_fields = jv_field list let rec normalize : jv -> jv = function | (`null | `bool _ | `num _ | `str _) as x -> x | `arr xs -> `arr (xs |&> normalize) | `obj fs -> `obj (normalize_fields fs) and normalize_fields : jv_fields -> jv_fields = fun fs -> sort_by_key fs |&> (fun (k, v) -> k, normalize v) let rec pp_unparse = fun ppf -> let self = pp_unparse in let outs = Format.pp_print_string ppf in let outf fmt = Format.fprintf ppf fmt in function | `null -> outs "null" | `bool true -> outs "true" | `bool false -> outs "false" | `num n -> outf "%g" n | `str s -> outf "\"%a\"" String.pp_json_escaped s | `arr [] -> outs "[]" | `arr xs -> outs "["; xs |> List.iter' (fun j -> outf "%a,%!" self j) (fun j -> outf "%a]%!" self j) | `obj [] -> outs "{}" | `obj fs -> outs "{"; fs |> List.iter' (fun (f,j) -> outf "\"%a\":%!%a,%!" String.pp_json_escaped f self j) (fun (f,j) -> outf "\"%a\":%!%a}%!" String.pp_json_escaped f self j) let unparse = sprintf "%a" pp_unparse let rec pp_lit = fun ppf -> let self = pp_lit in let outs = Format.pp_print_string ppf in let outf fmt = Format.fprintf ppf fmt in function | `null -> outs "`null" | `bool true -> outs "`bool true" | `bool false -> outs "`bool false" | `num n -> if n = 0. then outs "`num 0." else if n < 0. then outf "`num (%F)" n else outf "`num %F" n | `str s -> outf "`str %S" s | `arr [] -> outs "`arr []" | `arr xs -> outf "`arr ["; xs |> List.iter' (fun value -> fprintf ppf "@[<hov 0>%a@];@;<1 2>@?" self value) (fun value -> fprintf ppf "@[<hov 0>%a@]]@?" self value); | `obj [] -> outs "`obj []" | `obj fs -> outf "`obj ["; fs |> List.iter' (fun (key, value) -> fprintf ppf "@[<hov 0>%S, @,@[<hov 0>%a@];@]@;<1 2>@?" key self value) (fun (key, value) -> fprintf ppf "@[<hov 0>%S, @,@[<hov 0>%a@]@]]@?" key self value) let show = sprintf "%a" pp_lit type jvpath = ([ | `f of string | `i of int ] as 'path_component) list type legacy = [ | `arr of jv list | `obj of (string*jv) list ] type yojson = ([ | `Null | `Bool of bool | `Int of int | `Intlit of string | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list | `Tuple of 't list | `Variant of string * 't option ] as 't) let of_legacy x = (x :> jv) let to_legacy : jv -> legacy option = function | #legacy as x -> Some x | _ -> None let rec of_yojson : yojson -> jv = function | `Null -> `null | `Bool x -> `bool x | `Int x -> `num (float_of_int x) | `Intlit x -> `num (float_of_string x) | `Float x -> `num x | `String x -> `str x | `Assoc x -> `obj (x |&> ?>of_yojson) | `List x -> `arr (x |&> of_yojson) | `Tuple x -> `arr (x |&> of_yojson) | `Variant (t, Some x) -> `arr [`str t; of_yojson x] | `Variant (t, None) -> `str t let rec to_yojson : jv -> yojson = function | `null -> `Null | `bool x -> `Bool x | `num x -> ( if Float.is_integer x && (x <= (Int.max_int |> float_of_int)) && (x >= (Int.min_int |> float_of_int)) then (`Int (Float.to_int x)) else `Float x) | `str x -> `String x | `arr x -> `List (x |&> to_yojson) | `obj x -> `Assoc (x |&> ?>to_yojson) type yojson' = ([ | `Null | `Bool of bool | `Int of int | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list ] as 't) let rec yojson_basic_of_safe : yojson -> yojson' = fun yojson -> match yojson with | `Null -> `Null | `Bool x -> `Bool x | `Int x -> `Int x | `Intlit x -> `Int (int_of_string x) | `Float x -> `Float x | `String x -> `String x | `Assoc xs -> `Assoc (xs |&> fun (n, x) -> (n, yojson_basic_of_safe x)) | `List xs -> `List (xs |&> yojson_basic_of_safe) | `Tuple xs -> `List (xs |&> yojson_basic_of_safe) | `Variant (c, x_opt) -> begin match Option.map yojson_basic_of_safe x_opt with | None -> `List [`String c] | Some x -> `List [`String c; x] end let yojson_safe_of_basic : yojson' -> yojson = fun x -> (x :> yojson) type jsonm = jsonm_token seq and jsonm_token = [ | `Null | `Bool of bool | `String of string | `Float of float | `Name of string | `As | `Ae | `Os | `Oe ] type atomic_jsonm_token = [ | `Null | `Bool of bool | `String of string | `Float of float ] type value_starting_jsonm_token = [ | atomic_jsonm_token | `As | `Os ] type 'loc jsonm' = ('loc*jsonm_token) seq type 'loc jsonm_pe (* pe = parsing_error *) = [ | `empty_document | `premature_end of 'loc (** with loc of the starting token of the inner-most structure (viz. array/object) *) | `expecting_value_at of 'loc | `unexpected_token_at of 'loc*jsonm_token ] let of_jsonm' : 'loc jsonm' -> (jv*'loc jsonm', 'loc jsonm_pe) result = fun input -> let (>>=) m f = Result.bind m f in let jv_of_atom : atomic_jsonm_token -> jv = function | `Null -> `null | `Bool x -> `bool x | `String x -> `str x | `Float x -> `num x | _ -> . in let with_next (sloc : 'loc) (next : 'loc jsonm') (kont : 'loc -> 'loc jsonm' -> jsonm_token -> 'r) : 'r = match next() with | Seq.Nil -> Error (`premature_end sloc) | Seq.Cons ((nloc, ntok), next') -> kont nloc next' ntok in let ok next x : (jv*'loc jsonm', 'loc jsonm_pe) result = Ok (x, next) in let rec value loc next = function | #atomic_jsonm_token as tok -> jv_of_atom tok |> ok next | `As -> with_next loc next (collect_array []) | `Os -> with_next loc next (collect_object []) | #value_starting_jsonm_token -> . (* assert that all value starting tokens are handled *) | (`Name _ | `Ae | `Oe) as tok -> Error (`unexpected_token_at (loc, tok)) | _ -> . and collect_array acc sloc next = function | `Ae -> ok next (`arr (List.rev acc)) | #value_starting_jsonm_token as head -> with_next sloc Seq.(cons (sloc, head) next) value >>= (fun (v, next) -> with_next sloc next (fun _nloc -> collect_array (v :: acc) sloc)) | (`Name _ | `Oe) as tok -> Error (`unexpected_token_at (sloc, tok)) | _ -> . and collect_object acc sloc next = function | `Oe -> ok next (`obj (List.rev acc)) | `Name key -> ( with_next sloc next value >>= (fun (v, next) -> with_next sloc next (fun _nloc -> collect_object ((key, v) :: acc) sloc))) | (#value_starting_jsonm_token | `Ae) as tok -> Error (`unexpected_token_at (sloc, tok)) | _ -> . in match input () with | Seq.Nil -> Error (`empty_document) | Seq.Cons ((loc, tok), next) -> ( value loc next tok) let of_jsonm : jsonm -> (jv * jsonm) option = fun jsonm -> Seq.map (fun tok -> ((), tok)) jsonm |> of_jsonm' |> Result.to_option |> Option.map (fun (out, rest) -> (out, Seq.map snd rest)) let rec to_jsonm : jv -> jsonm = function (* XXX - optimize *) | `null -> Seq.return `Null | `bool x -> Seq.return (`Bool x) | `num x -> Seq.return (`Float x) | `str x -> Seq.return (`String x) | `arr xs -> Seq.cons `As (List.fold_right (fun x seq -> Seq.append (to_jsonm x) seq) xs (Seq.return `Ae)) | `obj xs -> Seq.cons `Os (List.fold_right (fun (name, x) seq -> Seq.append (Seq.cons (`Name name) (to_jsonm x)) seq) xs (Seq.return `Oe)) end module Jv : sig open Json val pump_field : string -> jv -> jv val access : jvpath -> jv -> jv option val access_null : jvpath -> jv -> unit option val access_bool : jvpath -> jv -> bool option val access_num : jvpath -> jv -> float option val access_int : jvpath -> jv -> int option val access_int53p : jvpath -> jv -> int53p option val access_str : jvpath -> jv -> string option val access_arr : jvpath -> jv -> jv list option val access_obj : jvpath -> jv -> jv_fields option val access' : (jv -> 'a option) -> jvpath -> jv -> 'a option val access_arr' : (jv -> 'a option) -> jvpath -> jv -> 'a list option end = struct open Json let pump_field fname : jv -> jv = function | `obj [(_, _)] as jv -> jv | `obj fs as jv -> ( match List.deassoc_opt fname fs with | Some fval, fs' -> `obj ((fname, fval) :: fs') | None, _ -> jv) | jv -> jv let access : jvpath -> jv -> jv option = fun path jv -> let rec go = function | [], x -> some x | `f fname :: path', `obj fs -> fs |> List.find_map (fun (k, v) -> if k = fname then go (path', v) else none ) | `i idx :: path', `arr xs -> List.nth_opt xs idx >>? (fun x -> go (path', x)) | _ -> none in go (path, jv) let access' : (jv -> 'a option) -> jvpath -> jv -> 'a option = fun f path jv -> access path jv >>? f let access_null : jvpath -> jv -> unit option = access' (function | `null -> some () | _ -> none) let access_bool : jvpath -> jv -> bool option = access' (function | `bool x -> some x | _ -> none) let access_num : jvpath -> jv -> float option = access' (function | `num x -> some x | _ -> none) let access_int : jvpath -> jv -> int option = access' (function | `num x when (float_of_int % int_of_float) x = x -> some (x |> int_of_float) | _ -> none) let access_int53p : jvpath -> jv -> int53p option = fun path jv -> access_num path jv >? Int53p.of_float let access_str : jvpath -> jv -> string option = access' (function | `str x -> some x | _ -> none) let access_arr : jvpath -> jv -> jv list option = access' (function | `arr xs -> some xs | _ -> none) let access_obj : jvpath -> jv -> jv_fields option = access' (function | `obj fs -> some fs | _ -> none) let access_arr' : (jv -> 'a option) -> jvpath -> jv -> 'a list option = fun f path jv -> let open Option.Ops_monad in access_arr path jv >? (List.map f &> sequence_list) |> Option.join end module Base64 = struct module type Config = sig * the 62nd character . [ ' + ' ] in rfc4648 , [ ' - ' ] in rfc4648_url . val c62 : char (** the 63rd character. ['/'] in rfc4648, ['_'] in rfc4648_url. *) val c63 : char (** the pad character. if [None], padding is disabled. [Some '='] in rfc4648. [None] in rfc4648_url. *) val pad : char option (** if set to true, validate padding length on decoding. *) val validate_padding: bool (** if set to true, newline characters are ignored on decoding. *) val ignore_newline : bool (** if set to true, unknown characters are ignored on decoding. [ignore_unknown = true] implies [ignore_newline = true]. *) val ignore_unknown : bool end module type T = sig (** Takes an input [bytes], and writes the encoded string to [Buffer.t]. @param offset the offset of input which the encoder should start reading from. @param len the length of input which the encoder should read. @return the number of bytes written to [Buffer.t]. *) val encode_buf : ?offset:int -> ?len:int -> Buffer.t -> bytes -> int (* written bytes*) (** Takes an input [string], and writes the decoded bytes to [Buffer.t]. @param offset the offset of input which the decoder should start reading from. @param len the length of input which the decoder should read. @return the number of bytes written to [Buffer.t]. *) val decode_buf : ?offset:int -> ?len:int -> Buffer.t -> string -> int (* written bytes *) (** Takes an input [bytes], and returns the encoded [string]. @param offset the offset of input which the encoder should start reading from. @param len the length of input which the encoder should read. *) val encode : ?offset:int -> ?len:int -> bytes -> string (** Takes an input [string], and returns the decoded [bytes]. @param offset the offset of input which the decoder should start reading from. @param len the length of input which the decoder should read. *) val decode : ?offset:int -> ?len:int -> string -> bytes end exception Invalid_base64_padding of [ | `invalid_char_with_position of char * int | `invalid_padding_length of int ] let () = Printexc.register_printer begin function | Invalid_base64_padding (`invalid_char_with_position (c, i)) -> some (sprintf "Invalid_base64_padding - char %c at %d" c i) | Invalid_base64_padding (`invalid_padding_length len) -> some (sprintf "Invalid_base64_padding_len - %d" len) | _ -> none end module Make (C: Config) : T = struct open C let int_A = int_of_char 'A' let int_Z = int_of_char 'Z' let int_a = int_of_char 'a' let int_z = int_of_char 'z' let int_0 = int_of_char '0' let int_9 = int_of_char '9' let c62, c63 = int_of_char c62, int_of_char c63 let sixbit_to_char b = if b < 26 (* A-Z *) then b + int_A else if b < 52 (* a-z *) then b - 26 + int_a 0 - 9 else if b = 62 then c62 else c63 let char_to_sixbit c = if int_A <= c && c <= int_Z then Some (c - int_A) else if int_a <= c && c <= int_z then Some (c - int_a + 26) else if int_0 <= c && c <= int_9 then Some (c - int_0 + 52) else if c = c62 then Some 62 else if c = c63 then Some 63 else None let encode_buf ?(offset=0) ?len (output: Buffer.t) (input: bytes) = let input_offset, input_end, input_length = let orig_len = Bytes.length input in let len = len |? (orig_len - offset) in let end_index = offset + len in if len < 0 || end_index > orig_len then invalid_arg' "Base64.encode: the input range (offset:%d, len:%d) is out of bounds" offset len else offset, end_index, len in let output_buf = let estimated_chars = (input_length / 3) * 4 + 4 (* worst case: (4/3)n + 2 + "==" *) in Buffer.create estimated_chars in let write i o len = let set value o = Buffer.add_uint8 output_buf (sixbit_to_char (value land 0x3f)); o + 1 in let get i = Bytes.get_uint8 input i in let b1 = get i in .. b1[5 ] match len with | `I -> o |> set (b1 lsl 4) (* b1[6] b1[7] 0 0 0 0 *) | `S n -> let b2 = get (i+1) in let o = o |> set ((b1 lsl 4) lor (b2 lsr 4)) in (* b1[6] b1[7] b2[0]..b2[3] *) match n with | `I -> o |> set (b2 lsl 2) (* b2[4]..b2[7] 0 0*) | `S `I -> let b3 = get (i+2) in o |> set ((b2 lsl 2) lor (b3 lsr 6)) (* b2[4]..b2[7] b3[0] b3[1]*) b3[2] .. ] in let rec go i o = match input_end - i with | 0 -> begin match pad with | Some pad -> let pad_chars = match o mod 4 with when len mod 3 = 0 when len mod 3 = 1 when len mod 3 = 2 | _ -> failwith "impossible" in List.range 0 pad_chars |> List.fold_left (fun o _ -> Buffer.add_char output_buf pad; o+1) o | None -> o end | 1 -> `I |> write i o |> go (i+1) | 2 -> `S `I |> write i o |> go (i+2) | _ -> `S (`S `I) |> write i o |> go (i+3) in let total_bytes = go input_offset 0 in Buffer.add_buffer output output_buf; total_bytes let encode ?offset ?len input = let output = Buffer.create 0 in encode_buf ?offset ?len output input |> ignore; Buffer.contents output let count_lenth_ignoring ?(offset=0) ?len (input: Bytes.t): int = let orig_len = Bytes.length input in let len = len |? (orig_len - offset) in let is_sixbit = char_to_sixbit &> Option.is_some in match ignore_unknown, ignore_newline with | true, _ -> let count acc i = let b = Bytes.get_uint8 input (offset + i) in if (is_sixbit b) then acc + 1 else acc in len |> iotafl count 0 | false, true -> let count acc i = let b = Bytes.get_uint8 input (offset + i) in if (is_sixbit b) then acc + 1 else begin match char_of_int b with | '\r' | '\n' -> acc | _ -> acc + 1 end in len |> iotafl count 0 | false, false -> len let decode_buf ?(offset=0) ?len (output: Buffer.t) (input: string) = let input = Bytes.of_string input in let input_offset, input_end, input_length = let orig_len = Bytes.length input in let len = len |? (orig_len - offset) in let end_index = offset + len in if len < 0 || end_index > orig_len then invalid_arg' "Base64.encode: the input range (offset:%d, len:%d) is out of bounds" offset len else if Option.is_some pad then let actual_len = count_lenth_ignoring ~offset ~len input in if actual_len mod 4 <> 0 then invalid_arg "Base64.decode: wrong padding" else offset, end_index, len else offset, end_index, len in let output_buf = let estimated_bytes = (input_length / 4) * 3 + 2 in (* worst case: 3n+2 bytes (= 4n+3 chars) *) Buffer.create estimated_bytes in let read stack o = let set o value = Buffer.add_uint8 output_buf (value land 0xff); o+1 in match List.rev stack with | [] -> o | [_] -> invalid_arg "Base64.decode: unterminated input" | s1 :: s2 :: ss -> let o = set o ((s1 lsl 2) lor (s2 lsr 4)) in (* s1[0]..s1[5] s2[0] s2[1] *) match ss with [ 3n+1 bytes ] 4bits = s2[2] .. s2[5 ] should 've been padded if not ((s2 land 0xf) = 0) then invalid_arg "Base64.decode: unterminated input" else o | s3 :: ss -> s2[2] .. s1[5 ] s3[0] .. [3 ] match ss with [ 3n+2 bytes ] 2bits = s3[4 ] s3[5 ] should 've been padded if not ((s3 land 0x3) = 0) then invalid_arg "Base64.decode: unterminated input" else o [ 3n bytes ] s3[4 ] s3[5 ] s4[0] .. [5 ] | _ -> failwith "impossible" in let rec go stack i o = if i = input_end then read stack o else let c = Bytes.get_uint8 input i in match char_to_sixbit c with | Some s -> let stack = s :: stack in if List.length stack = 4 then let o = read stack o in go [] (i+1) o else go stack (i+1) o | None -> begin match char_of_int c with | _ when ignore_unknown -> go stack (i+1) o | '\r' | '\n' when ignore_newline -> go stack (i+1) o | c when pad = some c && not validate_padding -> read stack o | c when pad = some c && validate_padding -> let pad = c in let validate_pad ignore = let pad_count acc ci = let c = Bytes.get_uint8 input (ci + i + 1) in begin match char_of_int c with | s when s = pad -> acc + 1 | s when ignore s -> acc | s -> raise (Invalid_base64_padding ( `invalid_char_with_position (s, ci + i + 1))) end in let pad_num = (input_end - i - 1) |> iotafl pad_count 0 |> ((+) 1) in let is_valid = 0 < pad_num && pad_num <= 2 in if is_valid then read stack o else raise (Invalid_base64_padding (`invalid_padding_length pad_num)) in begin match ignore_unknown, ignore_newline with | true, _ -> read stack o | false, true -> validate_pad begin function | '\r' | '\n' -> true | _ -> false end | false, false -> validate_pad (fun _ -> false) end | c -> invalid_arg' "Base64.decode: invalid char '%c' at index %d" c i end in let total_bytes = go [] input_offset 0 in Buffer.add_buffer output output_buf; total_bytes let decode ?offset ?len input = let output = Buffer.create 0 in decode_buf ?offset ?len output input |> ignore; Buffer.to_bytes output end module Config_rfc4648 : Config = struct let c62 = '+' let c63 = '/' let pad = Some '=' let validate_padding = true let ignore_newline = false let ignore_unknown = false end module Config_rfc4648_relaxed = struct include Config_rfc4648 let ignore_newline = true end include Make(Config_rfc4648_relaxed) module Config_rfc4648_url : Config = struct let c62 = '-' let c63 = '_' let pad = None let validate_padding = true let ignore_newline = false let ignore_unknown = false end module Config_rfc4648_url_relaxed = struct include Config_rfc4648_url let ignore_newline = true end module Url = Make(Config_rfc4648_url_relaxed) end
null
https://raw.githubusercontent.com/kxcteam/kxclib-ocaml/7d6eae65fcf6edc06d14a10a95c88cd02e11a426/kxclib.ml
ocaml
* [refset r x] sets [x] to ref [r]. * [refget r] returns [!r]. * [refupdate r f] updates referent of [r] by [f]. * [refappend r x] appends [x] to referent of [r]. * [refupdate' f r] is equivalent to [refupdate r f]. * [refappend' x r] is equivalent to [refappend r x]. * [incr r] increases the referent of [r] by one. * [decr r] decreases the referent of [r] by one. * constant function * identity function * negate a predicate * [reptill judge f x] evaluates [f x] repeatedly till [judge (f x)] holds. * [ntimes n f x] applies [f] ntimes to [x]. * [dotill judge f x] applies [f] to [x] repeatedly till [judge x] holds. * piping with tapping * lift to fst * lift to map fst * uncurry * curry * piping map * piping iter * piping and iter-tapping * piping fold_left * piping filter * piping filter map * {!List.fold_left} but arg pos exchanged * [try_make ~capture f] returns [Some (f())] except when - [f()] throws an [exn] s.t. [capture exn = true], it returns [None] - [f()] throws an [exn] s.t. [capture exn = false], it rethrows [exn] [~capture] defaults to [fun _exn -> true] * a specialized version of [try_make] where [~capture] is fixed to [function Not_found -> true | _ -> false] * [blastsat] find the last element [e] such that [pred e] being [true] using binary search. more specifically, - when [pred] yields [false] for every element, [Not_found] is raised - when there exists [i >= 0] such that {v forall k <= i. (pred arr.(k)) = true /\ forall k > i, (pred arr.(k)) = false v} , the [i]-th element will be returned - otherwise, the behavior is undefined bound_exclusive * [deassoc_opt k l] removes entry keyed [k] from [l], interpreted as an association list, and return [v, l'] where [v] is the value of the entry being removed or [None], and [l'] is the list after the removal, or semantically unchanged if the key does not exist. note that entries in [l'] may differ in order wrt. [l]. if there are multiple entries keyed [k], [v] will be [Some _] and [l'] will differ from the original, but otherwise the behavior is unspecified * same as [deassoc_opt] except using [(==)] when comparing keys * same as [deassoc_opt] but different return type * same as [deassq_opt] but different return type * same as [deassoc_opt] but throws [Not_found] when the requested key does not exist * same as [deassq_opt] but throws [Not_found] when the requested key does not exist * [pred list] returns the number of elements [e] in [list] that satisfies [pred] * last element of list * last element and rest of a list * swap the key and value * [starts_with p s] returns whether [s] starts with a substring of [p] * [ends_with p s] returns whether [s] ends with a substring of [p] 4byte utf8 optimization * time the execution of [f], returning the result of [f] and store the measured time in [output] * time the execution of [f], discarding the result of [f] rem * all according to proleptic Gregorian Calender * timezone not taking into consideration * min-year supported * max-year supported XXX tests * flag * default value * default value producer `Color -> (fg_code, bg_code) start contents end contents * [unparse j] convert [j] to a JSON string using [pp_unparse]. see [pp_unparse] for caveats. * [show j] convert [j] to a string using [pp_lit], which is a string that can be used as an OCaml literal. * field within an object * index within an array * an empty path designate the root element * Yojson.Safe.t * Yojson.Basic.t pe = parsing_error * with loc of the starting token of the inner-most structure (viz. array/object) pe = parsing_error * with loc of the starting token of the inner-most structure (viz. array/object) assert that all value starting tokens are handled XXX - optimize * the 63rd character. ['/'] in rfc4648, ['_'] in rfc4648_url. * the pad character. if [None], padding is disabled. [Some '='] in rfc4648. [None] in rfc4648_url. * if set to true, validate padding length on decoding. * if set to true, newline characters are ignored on decoding. * if set to true, unknown characters are ignored on decoding. [ignore_unknown = true] implies [ignore_newline = true]. * Takes an input [bytes], and writes the encoded string to [Buffer.t]. @param offset the offset of input which the encoder should start reading from. @param len the length of input which the encoder should read. @return the number of bytes written to [Buffer.t]. written bytes * Takes an input [string], and writes the decoded bytes to [Buffer.t]. @param offset the offset of input which the decoder should start reading from. @param len the length of input which the decoder should read. @return the number of bytes written to [Buffer.t]. written bytes * Takes an input [bytes], and returns the encoded [string]. @param offset the offset of input which the encoder should start reading from. @param len the length of input which the encoder should read. * Takes an input [string], and returns the decoded [bytes]. @param offset the offset of input which the decoder should start reading from. @param len the length of input which the decoder should read. A-Z a-z worst case: (4/3)n + 2 + "==" b1[6] b1[7] 0 0 0 0 b1[6] b1[7] b2[0]..b2[3] b2[4]..b2[7] 0 0 b2[4]..b2[7] b3[0] b3[1] worst case: 3n+2 bytes (= 4n+3 chars) s1[0]..s1[5] s2[0] s2[1]
[%%define re (os_type = "re")] let refset r x = r := x let refget r = !r let refupdate r f = r := f !r let refappend r x = r := x :: !r let refupdate' f r = r := f !r let refappend' x r = r := x :: !r let refpop r = match !r with h::t -> r:=t; h | [] -> raise Not_found * [ refpop r ] pop first item of the list referred to by [ r ] . { b Raises } [ Not_found ] if the list is empty . {b Raises} [Not_found] if the list is empty. *) let incr = refupdate' succ let decr = refupdate' pred let refupdate'_and_get f r = r := f !r; !r let get_and_refupdate' f r = let x = !r in r := f !r; x let incr_and_get = refupdate'_and_get succ let decr_and_get = refupdate'_and_get pred let get_and_incr = get_and_refupdate' succ let get_and_decr = get_and_refupdate' pred let constant c = fun _ -> c let identity x = x let failwith' fmt = Format.kasprintf (failwith) fmt let invalid_arg' fmt = Format.kasprintf (invalid_arg) fmt let iotaf func n = let rec loop acc = function | m when m = n -> acc | m -> loop (func m :: acc) (succ m) in loop [] 0 |> List.rev let iotaf' func n = let rec loop = function | m when m = n -> () | m -> func m; loop (succ m) in loop 0 let iotafl binop acc0 n = let rec loop acc = function | m when m = n -> acc | m -> loop (binop acc m) (succ m) in loop acc0 0 let iotafl' binop acc0 g n = let rec loop acc = function | m when m = n -> acc | m -> loop (binop acc (g m)) (succ m) in loop acc0 0 let min_by f x y = if f y > f x then x else y let max_by f x y = if f y < f x then x else y module Functionals = struct let negate pred x = not (pred x) let both p g x = p x && g x let either p g x = p x || g x let dig2nd f a b = f b a * [ f ] dig the second argument of [ f ] to be the first . aka [ flip ] let dig3rd f c a b = f a b c * [ f ] dig the third argument of [ f ] to be the first let flip = dig2nd * [ f ] flip the first arguments of [ f ] . aka [ dig2nd ] let fix1st x f = f x * [ x f ] fix the first argument to [ f ] as [ x ] let fix2nd y f x = f x y * [ y f ] fix the second argument to [ f ] as [ y ] let fix3rd z f x y = f x y z * [ z f ] fix the third argument to [ f ] as [ z ] let fix1st' x f = fun _ -> f x * [ x f ] fix the first argument to [ f ] as [ x ] , but still accept ( and ignore ) the fixed argument let tap f x = f x; x let reptill judge f x = let rec loop y = if judge y then y else loop (f y) in loop (f x) let ntimes n f x = let rec loop acc = function | 0 -> acc | n -> loop (f acc) (n-1) in loop x n let dotill judge f x = let rec loop y = if judge y then y else loop (f y) in loop (f x) let fixpoint ?maxn = match maxn with | None -> fun f x -> let rec loop (x,x') = if x = x' then x else loop (x', f x') in loop (x, f x) | Some 0 -> failwith "fixpoint not reached after 0 tries" | Some maxn -> fun f x -> let rec loop n (x,x') = if x = x' then x else if n = 0 then failwith' "fixpoint not reached after %d tries" maxn else loop (pred n) (x', f x') in loop (pred maxn) (x, f x) * [ fixpoint f ] try to resolve the fixpoint of f. [ ] , an optional argument , limits the number of iterations to find the fix point . [maxn], an optional argument, limits the number of iterations to find the fix point. *) let converge' judge f = let rec loop n (x, x') = match judge n x x' with | true -> Ok x' | false -> loop (succ n) (x', f x') in fun x -> loop 1 (x, f x) let converge judge f x = converge' (fun _ x x' -> judge x x') f x module BasicInfix = struct * function composition 1 let (%) : ('y -> 'z) -> ('x -> 'y) -> ('x -> 'z) = fun f g x -> x |> g |> f * function composition 1 , on second argument let (%%) : ('a -> 'y -> 'z) -> ('x -> 'y) -> ('a -> 'x -> 'z) = fun f g x y -> f x (g y) * function composition 2 let (&>) : ('x -> 'y) -> ('y -> 'z) -> ('x -> 'z) = fun g f x -> x |> g |> f let (?.) : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c = dig2nd let (?..) : ('a -> 'b -> 'c -> 'd) -> 'c -> 'a -> 'b -> 'd = dig3rd let (!.) : 'b -> ('a -> 'b -> 'c) -> 'b -> 'c = fix2nd let (!..) : 'c -> ('a -> 'b -> 'c -> 'd) -> 'a -> 'b -> 'd = fix3rd * function composition 2 , arity=2 let (&&>) : ('x -> 'y -> 'z) -> ('z -> 'r) -> ('x -> 'y -> 'r) = fun g f x y -> g x y |> f let (|->) : 'x -> ('x -> unit) -> 'x = fun x f -> (f x); x let (//) : ('a -> 'x) -> ('b -> 'y) -> ('a*'b -> 'x*'y) = fun fa fb (a, b) -> fa a, fb b let (/>) : 'a*'b -> ('b -> 'c) -> 'a*'c = fun (a, b) f -> a, f b let (/<) : 'a*'b -> ('a -> 'c) -> 'c*'b = fun (a, b) f -> f a, b * lift to snd let (?>) : ('b -> 'c) -> ('a*'b -> 'a*'c) = fun f -> fun (a, b) -> a, f b let (?<) : ('a -> 'c) -> ('a*'b -> 'c*'b) = fun f -> fun (a, b) -> f a, b * lift to map snd let (?&>) : ('y2 -> 'x2) -> ('x1 * 'x2 -> 'r) -> 'x1 * 'y2 -> 'r = fun g f -> fun (x, y) -> f (x, g y) let (?&<) : ('y1 -> 'x1) -> ('x1 * 'x2 -> 'r) -> 'y1 * 'x2 -> 'r = fun g f -> fun (x, y) -> f (g x, y) let (!!) : ('a -> 'b -> 'x) -> ('a*'b -> 'x) = fun f -> fun (a, b) -> f a b let (!?) : ('a*'b -> 'x) -> ('a -> 'b -> 'x) = fun f -> fun a b -> f (a, b) end module CommonTypes = struct type 'x endo = 'x -> 'x end module Infix = BasicInfix end module Fn = Functionals include Functionals.BasicInfix include Functionals.CommonTypes module PipeOps(S : sig type _ t val map : ('x -> 'y) -> 'x t -> 'y t val iter : ('x -> unit) -> 'x t -> unit val fold_left : ('acc -> 'x -> 'acc) -> 'acc -> 'x t -> 'acc val filter : ('x -> bool) -> 'x t -> 'x t val filter_map : ('x -> 'y option) -> 'x t -> 'y t end) = struct open S let (|&>) : 'x t -> ('x -> 'y) -> 'y t = fun xs f -> map f xs * piping map to snd let (|+&>) : 'x t -> ('x -> 'y) -> ('x*'y) t = fun xs f -> map (fun x -> x, f x) xs let (|!>) : 'x t -> ('x -> unit) -> unit = fun xs f -> iter f xs let (|-!>) : 'x t -> ('x -> unit) -> 'x t = fun xs f -> iter f xs; xs let (|@>) : 'x t -> ('acc*('acc*'x -> 'acc)) -> 'acc = fun xs (z, f) -> fold_left (fun acc x -> f (acc, x)) z xs let (|?>) : 'x t -> ('x -> bool) -> 'x t = fun xs f -> filter f xs let (|&?>) : 'x t -> ('x -> 'y option) -> 'y t = fun xs f -> filter_map f xs * piping filter map to snd let (|+&?>) : 'x t -> ('x -> 'y option) -> ('x*'y) t = fun xs f -> filter_map (fun x -> match f x with Some y -> Some (x, y) | None -> None) xs end module type Monadic = sig type _ t val return : 'x -> 'x t val bind : 'x t -> ('x -> 'y t) -> 'y t end module MonadOps(M : sig type _ t val return : 'x -> 'x t val bind : 'x t -> ('x -> 'y t) -> 'y t end) = struct let return x = M.return x let (>>=) = M.bind let (>>) : 'x M.t -> 'y M.t -> 'y M.t = fun ma mb -> ma >>= fun _ -> mb let (>|=) : 'x M.t -> ('x -> 'y) -> 'y M.t = fun ma f -> ma >>= fun x -> return (f x) let sequence_list ms = List.fold_left (fun acc m -> acc >>= fun acc -> m >>= fun x -> x :: acc |> return ) (return []) ms >>= fun xs -> List.rev xs |> return let (>>=*) : 'x M.t list -> ('x list -> 'y M.t) -> 'y M.t = fun ms af -> sequence_list ms >>= af end let foldl = List.fold_left * { ! } let foldr f z l = List.fold_right f l z let projected_compare proj a b = compare (proj a) (proj b) let neg = Int.neg let mul = Int.mul let div = Int.div let rem = Int.rem module Either = struct type ('a, 'b) t = Left of 'a | Right of 'b let left x = Left x let right x = Right x end type ('a, 'b) either = ('a, 'b) Either.t module Result = struct include Result * NB - returning only the first error let concat : ('x, 'e) result list -> ('x list, 'e) result = fun rs -> let rec loop acc = function | [] -> Ok acc | Ok x :: rest -> loop (x :: acc) rest | Error e :: _ -> Error e in loop [] (List.rev rs) end module ResultOf(E : sig type err end) = struct type err = E.err type 'x t = ('x, err) result let bind : 'x t -> ('x -> 'y t) -> 'y t = Result.bind let return : 'x -> 'x t = Result.ok end module ResultWithErrmsg0 = struct include ResultOf(struct type err = string end) let protect' : handler:(exn -> string) -> ('x -> 'y) -> ('x -> 'y t) = fun ~handler f x -> try Ok (f x) with exn -> Error (handler exn) let protect : ('x -> 'y) -> ('x -> 'y t) = fun f -> protect' ~handler:Printexc.to_string f end module Queue : sig type 'x t val empty : 'x t val is_empty : 'x t -> bool val push : 'x -> 'x t -> 'x t val push_front : 'x -> 'x t -> 'x t val pop : 'x t -> ('x * 'x t) option val peek : 'x t -> ('x * 'x t) option end = struct type 'x t = 'x list*'x list let empty = [], [] let is_empty = function | [], [] -> true | _ -> false let push x (r,u) = (x :: r, u) let push_front x (r,u) = (r, x :: u) let rec pop (r,u) = match u, r with | hd :: rest, _ -> Some (hd, (r, rest)) | [], (_ :: _) -> pop ([], List.rev r) | [], [] -> None let rec peek (r,u as q) = match u, r with | hd :: _, _ -> Some (hd, q) | [], (_ :: _) -> peek ([], List.rev r) | [], [] -> None end type 'x queue = 'x Queue.t module Option0 = struct include Option let return = some let get = function | Some x -> x | None -> raise Not_found let v default = function | Some x -> x | None -> default let v' gen_default = function | Some x -> x | None -> gen_default() let otherwise otherwise = function | Some x -> Some x | None -> otherwise let otherwise' otherwise_f = function | Some x -> Some x | None -> otherwise_f() let pp vpp ppf = Format.(function | Some x -> fprintf ppf "Some(%a)" vpp x | None -> fprintf ppf "None") let filter pred = function | Some x when pred x -> Some x | _ -> None let fmap f = function | None -> None | Some v -> ( match f v with | None -> None | Some v -> v) let of_bool = function | true -> Some () | false -> None let some_if cond x = if cond then Some x else None let try_make : ?capture:(exn -> bool) -> (unit -> 'x) -> 'x option = fun ?(capture = constant true) f -> try f() |> some with exn -> if capture exn then none else raise exn let if_found : (unit -> 'x) -> 'x option = fun f -> try_make f ~capture:(function Not_found -> true | _ -> false) end module Option = struct include Option0 module Ops_monad = MonadOps(Option0) module Ops = struct include Ops_monad end end let some = Option.some let none = Option.none let (>?) o f = Option.map f o let (>>?) o f = Option.bind o f let (|?) o v = Option.v v o let (|?!) o v = Option.v' v o let (||?) o1 o2 = Option.otherwise o2 o1 let (||?!) o1 o2 = Option.otherwise' o2 o1 let (&>?) : ('x -> 'y option) -> ('y -> 'z) -> ('x -> 'z option) = fun af f -> af &> (Option.map f) module Seq0 = struct include Seq include PipeOps(Seq) let from : (unit -> 'x option) -> 'x t = fun f -> let rec next() = match f() with | None -> Nil | Some x -> Cons (x, next) in next let iota until_exclusive = let counter = ref 0 in from (fun() -> let x = !counter in if x = until_exclusive then None else ( incr counter; Some x ) ) let length s = fold_left (fun c _ -> succ c) 0 s let range ?include_endpoint:(ie=false) start end_ = let end_exclusive = if ie then succ end_ else end_ in iota (end_exclusive - start) |&> (+) start let enum start = let counter = ref start in from (fun () -> get_and_incr counter |> Option.some ) let rec limited quota orig() = if quota > 0 then ( let open Seq in match orig() with | Nil -> Nil | Cons (x, next) -> Cons (x, limited (pred quota) next) ) else Nil let iteri f s = let rec h i = function | Nil -> () | Cons(x, rest) -> f i x; h (i + 1) (rest()) in s() |> h 0 let hd s = match s() with | Nil -> raise Not_found | Cons(x, _) -> x let tl s = match s() with | Nil -> raise Not_found | Cons(_, t) -> t let take n s = match n with | _ when n < 0 -> failwith "panic" | _ -> let rec h n t () = match n, (t()) with | 0, _ -> Nil | _, Nil -> failwith "panic" | _, Cons(x, u) -> Cons(x, h (n - 1) u) in h n s let drop n s = Fn.ntimes n tl s let make n x = match n with | _ when n < 0 -> failwith "panic" | _ -> let rec h i () = match i with | 0 -> Nil | _ -> Cons(x, h (i - 1)) in h n end module Seq = struct include Seq0 module Ops_piping = PipeOps(Seq0) module Ops = struct include Ops_piping end end type 'x seq = 'x Seq.t module Array0 = struct include Array let filter f arr = arr |> to_seq |> Seq.filter f |> of_seq let filter_map f arr = arr |> to_seq |> Seq.filter_map f |> of_seq include PipeOps(struct include Array let filter = filter let filter_map = filter_map end) let of_list_of_length len list = let cell = ref list in init len (fun _ -> match !cell with | hd :: tl -> cell := tl; hd | [] -> raise Not_found) TODO optimization - specialized version when [ ? f ] not given let mean : ?f:('x -> float) -> float t -> float = fun ?f:(f=identity) arr -> let len = Array.length arr in if len = 0 then raise Not_found else let rec labor left right = match right - left with | 0 -> f arr.(left), 1 | 1 -> (f arr.(left) +. f arr.(right) ) /. 2., 2 | rlen -> if rlen < 0 then 0., 0 else let mid = left + (rlen / 2) in let lv, lw = labor left mid and rv, rw = labor (succ mid) right in let (!) = float_of_int in (lv *. !lw +.rv*. !rw) /. !(lw+rw), lw+rw in labor 0 (len-1) |> fst let min cmp arr = match length arr with | 0 -> raise Not_found | _ -> let cand = ref arr.(0) in iter (fun x -> if cmp x !cand < 0 then cand := x) arr; !cand let max cmp arr = match length arr with | 0 -> raise Not_found | _ -> let cand = ref arr.(0) in iter (fun x -> if cmp x !cand > 0 then cand := x) arr; !cand let first arr = match length arr with | 0 -> raise Not_found | _ -> arr.(0) let last arr = match length arr with | 0 -> raise Not_found | n -> arr.(n-1) let sorted cmp arr = sort cmp arr; arr let update : ('a -> 'a) -> 'a array -> int -> unit = fun f arr idx -> arr.(idx) <- f arr.(idx) let update_each : (int -> 'a -> 'a) -> 'a array -> unit = fun f arr -> arr |> Array.iteri (fun i x -> arr.(i) <- f i x) let blastsati : ('a -> bool) -> 'a array -> int = fun pred arr -> let pred i = pred arr.(i) in let rec loop pred l r = if l > r then raise Not_found else if l+1 = r then begin if pred r then r else l end else if l = r then begin if l = 0 && not (pred l) then raise Not_found else l end else let m = (l+r) / 2 in if pred m then loop pred m r else loop pred l (m-1) in loop pred 0 ((length arr) - 1) let blastsat : ('a -> bool) -> 'a array -> 'a = fun pred arr -> blastsati pred arr |> Array.get arr let swap arr idx1 idx2 = let tmp = arr.(idx2) in arr.(idx2) <- arr.(idx1); arr.(idx1) <- tmp fun ?rng:(rng=Random.int) arr -> let len = Array.length arr in for i = len-1 downto 1 do swap arr i (rng (succ i)) done let to_function : 'a array -> (int -> 'a) = fun arr idx -> arr.(idx) end module Array = struct include Array0 module Ops_piping = PipeOps(Array0) module Ops_monad = PipeOps(Array0) module Ops = struct include Ops_piping include Ops_monad end end [%%if ocaml_version < (4, 14, 0)] module Stream = struct include Stream let to_list_rev stream = let result = ref [] in Stream.iter (fun value -> result := value :: !result) stream; !result let to_list stream = to_list_rev stream |> List.rev let hd stream = let open Stream in try next stream with | Failure -> raise Not_found let drop1 stream = let open Stream in let _ = try next stream with | Failure -> raise Not_found in stream let take n stream = let open Stream in let m_lst = try npeek n stream with | Failure -> raise Not_found | Error msg -> failwith msg in match List.length m_lst with | m when m = n -> m_lst | _ -> raise Not_found let drop n s = Fn.ntimes n drop1 s end [%%endif] module List0 = struct include PipeOps(List) include List let iota = function | 0 -> [] | k -> 0 :: (List.init (pred k) succ) let iota1 = function | 0 -> [] | k -> List.init k succ let range = let helper start end_ = iota (end_ - start) |&> (+) start in fun ?include_endpoint:(ie=false) -> if ie then (fun start end_ -> helper start (succ end_)) else (fun start end_ -> helper start end_) let dedup' ~by l = let set = Hashtbl.create (List.length l) in l |?> (fun x -> if Hashtbl.mem set (by x) then false else (Hashtbl.add set (by x) true; true)) let dedup l = dedup' ~by:identity l let update_assoc : 'k -> ('v option -> 'v option) -> ('k*'v) list -> ('k*'v) list = fun k func l -> let l', updated = l |> fold_left (fun (acc, updated) (key, v as ent) -> match updated, k = key with | false, true -> ( match func (some v) with | Some v' -> (key, v') :: acc, true | None -> acc, true) | _ -> ent :: acc, updated ) ([], false) in if not updated then ( match func none with | None -> l | Some v -> (k, v) :: l ) else rev l' let update_assq : 'k -> ('v option -> 'v option) -> ('k*'v) list -> ('k*'v) list = fun k func l -> let l', updated = l |> fold_left (fun (acc, updated) (key, v as ent) -> match updated, k == key with | false, true -> ( match func (some v) with | Some v' -> (key, v') :: acc, true | None -> acc, true) | _ -> ent :: acc, updated ) ([], false) in if not updated then ( match func none with | None -> l | Some v -> (k, v) :: l ) else rev l' let deassoc_opt : 'k -> ('k*'v) list -> 'v option*('k*'v) list = fun k es -> let rec loop (ret, es) = function | [] -> ret, es | (k', v) :: rest when k' = k -> we are not shortcutting here since appending two lists is still O(n ) .. loop (some v, es) rest | e :: rest -> loop (ret, e :: es) rest in loop (none, []) es let deassq_opt : 'k -> ('k*'v) list -> 'v option*('k*'v) list = fun k es -> let rec loop (ret, es) = function | [] -> ret, es | (k', v) :: rest when k' == k -> we are not shortcutting here since appending two lists is still O(n ) .. loop (some v, es) rest | e :: rest -> loop (ret, e :: es) rest in loop (none, []) es let deassoc_opt' : 'k -> ('k*'v) list -> ('v*('k*'v) list) option = fun k es -> match deassoc_opt k es with | Some v, es -> Some (v, es) | None, _ -> None let deassq_opt' : 'k -> ('k*'v) list -> ('v*('k*'v) list) option = fun k es -> match deassq_opt k es with | Some v, es -> Some (v, es) | None, _ -> None let deassoc : 'k -> ('k*'v) list -> 'v*('k*'v) list = fun k es -> let ov, es = deassoc_opt k es in Option.v' (fun() -> raise Not_found) ov, es let deassq : 'k -> ('k*'v) list -> 'v*('k*'v) list = fun k es -> let ov, es = deassq_opt k es in Option.v' (fun() -> raise Not_found) ov, es let group_by : ('x -> 'k) -> 'x t -> ('k*'x t) t = fun kf l -> l |> fold_left (fun acc x -> let k = kf x in update_assoc k (function | Some xs -> x :: xs |> some | None -> some [x]) acc) [] let unzip l = List.fold_left (fun (l,s) (x,y) -> (x::l,y::s)) ([],[]) (List.rev l) let unzip3 l = List.fold_left (fun (l1,l2,l3) (x1,x2,x3) -> (x1::l1,x2::l2,x3::l3)) ([],[],[]) (List.rev l) let reduce f = function | [] -> raise Not_found | hd::tl -> foldl f hd tl let reduce_opt f = function | [] -> none | hd::tl -> foldl f hd tl |> some let min_opt cmp = function | [] -> none | hd::l -> let f acc x = if cmp acc x > 0 then x else acc in fold_left f hd l |> some let max_opt cmp = function | [] -> none | hd::l -> let f acc x = if cmp acc x < 0 then x else acc in fold_left f hd l |> some let min cmp = min_opt cmp &> Option.get let max cmp = min_opt cmp &> Option.get let foldl = foldl let foldr = foldr let hd = function | [] -> raise Not_found | h :: _ -> h let tl = function | [] -> raise Not_found | _ :: tail -> tail let take n l = let rec loop acc = function | 0, _ -> rev acc | n, hd::tl -> loop (hd::acc) (n-1, tl) | _ -> raise Not_found in loop [] (n, l) let drop n l = Fn.ntimes n tl l let make copies x = List.init copies (constant x) let count pred list = foldl (fun count x -> if pred x then succ count else count) 0 list let last list = foldl (fun _ x -> x) (List.hd list) list let and_last : 'x. 'x list -> 'x list*'x = fun xs -> match rev xs with | [] -> raise Not_found | l :: r -> rev r, l let iter' f f_last xs = let rec go = function | [x] -> f_last x | x :: rest -> f x; go rest | [] -> () in go xs let fmap : ('x -> 'y list) -> 'x list -> 'y list = fun f l -> let rec loop acc = function | [] -> acc | x :: r -> loop ((f x |> List.rev) :: acc) r in let rec collect acc = function | [] -> acc | [] :: r' -> collect acc r' | (h :: r) :: r' -> collect (h :: acc) (r :: r') in loop [] l |> collect [] let interpolate y xs = let rec loop acc = function | x :: [] -> x :: acc | [] -> acc | x :: xs -> loop (y :: x :: acc) xs in loop [] xs |> rev let filteri p l = let rec aux i acc = function | [] -> rev acc | x::l -> aux (i + 1) (if p i x then x::acc else acc) l in aux 0 [] l let empty = function [] -> true | _ -> false let to_function : 'a list -> (int -> 'a) = fun xs -> Array.(xs |> of_list |> to_function) let to_hashtbl : ('k*'v) list -> ('k, 'v) Hashtbl.t = fun xs -> Hashtbl.of_seq (to_seq xs) let pp ?sep ?parens vpp ppf xs = let open Format in let popen, pclose = match parens with | Some parens -> parens | None -> "[", "]" in let sep = match sep with | Some s -> s | None -> ";" in fprintf ppf "%s @[" popen; iter (fprintf ppf "%a%s@;" vpp |> Fn.fix2nd sep) xs; fprintf ppf "%s@]" pclose let bind ma af = fmap af ma let return x = [x] end module List = struct include List0 module Ops_piping = PipeOps(List0) module Ops_monad = PipeOps(List0) module Ops = struct include Ops_piping include Ops_monad end end include List.Ops_piping let iota = List.iota let iota1 = List.iota1 module Hashtbl = struct include Hashtbl let rev : ('a, 'b) t -> ('b, 'a) t = fun orig -> to_seq orig |> Seq.map (fun (k,v) -> (v,k)) |> of_seq let to_function : ('a, 'b) t -> 'a -> 'b = Hashtbl.find * [ make n genfunc ] creates a hashtable of [ n ] elements with entries [ { ( fst ( genfunc 0 ) ) |- > ( snd ( genfunc 0 ) ) , ( fst ( genfunc 1 ) ) |- > ( snd ( genfunc 1 ) ) ... , ( fst ( ( n-1 ) ) ) |- > ( snd ( ( n-1 ) ) ) } ] [{ (fst (genfunc 0)) |-> (snd (genfunc 0)) , (fst (genfunc 1)) |-> (snd (genfunc 1)) ... , (fst (genfunc (n-1))) |-> (snd (genfunc (n-1))) }] *) let make ?random : int -> (int -> 'a * 'b) -> ('a, 'b) Hashtbl.t = fun n genfunc -> let table = Hashtbl.create ?random n in Seq.iota n |> Seq.map genfunc |> Hashtbl.add_seq table; table end module String = struct include String * [ empty str ] returns true when is of zero length let empty str = length str = 0 * [ empty_trimmed str ] returns true when is of zero length after being trimmed let empty_trimmed str = length (trim str) = 0 * [ chop_prefix p s ] returns [ s ] minus the prefix [ p ] wrapped in [ Some ] , or [ None ] if [ s ] does not start with [ p ] or [None] if [s] does not start with [p] *) let chop_prefix prefix = let plen = length prefix in fun str -> let slen = length str in if slen < plen then None else if (sub str 0 plen) = prefix then Some (sub str plen (slen-plen)) else None let starts_with prefix str = chop_prefix prefix str |> Option.is_some let ends_with postfix str = let plen, slen = length postfix, length str in if slen < plen then false else (sub str (slen-plen) plen) = postfix * [ chop_prefix p s ] returns [ s ] minus the suffix [ p ] wrapped in [ Some ] , or [ None ] if [ s ] does not end with [ p ] or [None] if [s] does not end with [p] *) let chop_suffix suffix = let plen = length suffix in fun str -> let slen = length str in if slen < plen then None else if (sub str (slen-plen) plen) = suffix then ( Some (sub str 0 (slen-plen)) ) else None let to_bytes = Bytes.of_string let to_list str = to_seq str |> List.of_seq let of_list = List.to_seq &> of_seq let of_array = Array.to_seq &> of_seq let pp_json_escaped : Format.formatter -> string -> unit = fun ppf str -> let len = length str in let getc = unsafe_get str in let addc = Format.pp_print_char ppf in let adds = Format.pp_print_string ppf in let addu x = adds "\\u"; adds (Format.sprintf "%04x" x) in let addb n k = iotaf' (fun i -> addc (getc (n + i))) k in let flush = Format.pp_print_flush ppf in let raise' pos = invalid_arg' "json_escaped: invalid/incomplete utf-8 string at pos %d" pos in let rec loop n = if (n-1) mod 64 = 0 then flush(); let adv k = loop (n + k) in let check k = if not (n + k <= len) then raise' (n+k-1) in if succ n > len then () else ( match getc n with | '"' -> adds "\\\""; adv 1 | '\\' -> adds "\\\\"; adv 1 | '\b' -> adds "\\b"; adv 1 | '\012' -> adds "\\f"; adv 1 | '\n' -> adds "\\n"; adv 1 | '\r' -> adds "\\r"; adv 1 | '\t' -> adds "\\t"; adv 1 | '\127' -> addu 127; adv 1 | c -> let x1 = int_of_char c in if x1 < 32 then (addu x1; adv 1) else if x1 < 127 then (addc c; adv 1) else ( check 2; let spit k = check k; addb n k; adv k in if x1 land 0xe0 = 0xc0 then ( 2byte utf8 ) else if (x1 land 0xf0 = 0xe0) then ( 3byte ) else if (x1 land 0xf8 = 0xf0) then ( ) else raise' n ) ) in loop 0 let json_escaped : string -> string = Format.asprintf "%a" pp_json_escaped end module MapPlus (M : Map.S) = struct let pp' kpp vpp ppf m = let open Format in fprintf ppf "{ "; pp_open_hovbox ppf 0; M.bindings m |> List.iter' (fun (key, value) -> fprintf ppf "@[<hov 0>%a=@,@[<hov 0>%a@];@]@;<1 2>@?" kpp key vpp value) (fun (key, value) -> fprintf ppf "@[<hov 0>%a=@,@[<hov 0>%a@];@] }@?" kpp key vpp value); pp_close_box ppf () [%%if not(re)] let of_list : (M.key * 'v) list -> 'v M.t = fun kvs -> kvs |> M.of_seq % List.to_seq [%%endif] end module StringMap = struct include Map.Make(String) include MapPlus(Map.Make(String)) let pp vpp ppf m = pp' Format.pp_print_string vpp ppf m end module IntMap = struct include Map.Make(Int) include MapPlus(Map.Make(Int)) let pp vpp ppf m = pp' Format.pp_print_int vpp ppf m end module IoPervasives = struct let with_input_file path f = let ch = open_in path in let r = try f ch with e -> close_in ch; raise e in close_in ch; r let with_output_file path f = let ch = open_out path in let r = try f ch with e -> close_out ch; raise e in close_out ch; r let slurp_input ?buf ic = let buf = match buf with | None -> Bytes.make 4096 '\000' | Some buf -> buf in let result = ref "" in let rec loop len = match input ic buf 0 len with | 0 -> result | rlen -> result := !result^(Bytes.sub_string buf 0 rlen); loop len in !(loop (Bytes.length buf)) let slurp_stdin ?buf () = slurp_input ?buf stdin let slurp_file path = with_input_file path slurp_input [@@warning "-48"] let spit_file path str = with_output_file path (Fn.flip output_string str) end include IoPervasives module Timing = struct let timefunc' output f = let t = Sys.time() in let r = f () in output := Sys.time()-.t; r let timefunc f = let time = ref 0. in timefunc' time f |> ignore; !time end module Int53p = struct type int53p_impl_flavor = [ | `int_impl | `int64_impl | `float_impl | `custom_impl of string ] let pp_int53p_impl_flavor : Format.formatter -> int53p_impl_flavor -> unit = fun ppf -> let open Format in function | `int_impl -> pp_print_string ppf "int_impl" | `int64_impl -> pp_print_string ppf "int64_impl" | `float_impl -> pp_print_string ppf "float_impl" | `custom_impl s -> fprintf ppf "custom_impl(%s)" s let show_int53p_impl_flavor : int53p_impl_flavor -> string = Format.asprintf "%a" pp_int53p_impl_flavor module type Ops = sig type int53p val ( ~-% ) : int53p -> int53p val ( ~+% ) : int53p -> int53p val ( +% ) : int53p -> int53p -> int53p val ( -% ) : int53p -> int53p -> int53p val ( *% ) : int53p -> int53p -> int53p val ( /% ) : int53p -> int53p -> int53p end module type S = sig val impl_flavor : int53p_impl_flavor module Ops : Ops include Ops with type int53p = Ops.int53p val zero : int53p val one : int53p val minus_one : int53p val neg : int53p -> int53p val add : int53p -> int53p -> int53p val succ : int53p -> int53p val pred : int53p -> int53p val sub : int53p -> int53p -> int53p val mul : int53p -> int53p -> int53p val div : int53p -> int53p -> int53p val rem : int53p -> int53p -> int53p val abs : int53p -> int53p val equal : int53p -> int53p -> bool val compare : int53p -> int53p -> int val min : int53p -> int53p -> int53p val max : int53p -> int53p -> int53p val to_float : int53p -> float val of_float : float -> int53p val to_int : int53p -> int val of_int : int -> int53p val to_int64 : int53p -> int64 val of_int64 : int64 -> int53p [%%if not(re)] val to_nativeint : int53p -> nativeint val of_nativeint : nativeint -> int53p [%%endif] val to_string : int53p -> string val of_string : string -> int53p end module Internals = struct module MakeOps(M : sig type int53p val neg : int53p -> int53p val add : int53p -> int53p -> int53p val sub : int53p -> int53p -> int53p val mul : int53p -> int53p -> int53p val div : int53p -> int53p -> int53p val rem : int53p -> int53p -> int53p end) : Ops with type int53p = M.int53p = struct type int53p = M.int53p let ( ~-% ) : int53p -> int53p = M.neg let ( ~+% ) : int53p -> int53p = identity let ( +% ) : int53p -> int53p -> int53p = M.add let ( -% ) : int53p -> int53p -> int53p = M.sub let ( *% ) : int53p -> int53p -> int53p = M.mul let ( /% ) : int53p -> int53p -> int53p = M.div let ( /%% ) : int53p -> int53p -> int53p = M.rem end module IntImpl : S = struct let impl_flavor = `int_impl include Int [%%if ocaml_version < (4, 13, 0)] let min (a: int) (b: int) = min a b let max (a: int) (b: int) = max a b [%%endif] module Ops = MakeOps(struct type int53p = int include Int end) include Ops let to_int = identity let of_int = identity let to_int64 = Int64.of_int let of_int64 = Int64.to_int let to_float = float_of_int let of_float = int_of_float [%%if not(re)] let to_nativeint = Nativeint.of_int let of_nativeint = Nativeint.to_int [%%endif] let of_string = int_of_string end module Int64Impl : S = struct let impl_flavor = `int64_impl include Int64 [%%if ocaml_version < (4, 13, 0)] let min (a: int64) (b: int64) = min a b let max (a: int64) (b: int64) = max a b [%%endif] module Ops = MakeOps(struct type int53p = int64 include Int64 end) include Ops let of_int64 = identity let to_int64 = identity end module FloatImpl : S = struct let impl_flavor = `float_impl there is a problem with int_of_float in at least JSOO , and type int = float in both JSOO and BuckleScript runtime and type int = float in both JSOO and BuckleScript runtime *) let to_int, of_int = match Sys.backend_type with | Other "js_of_ocaml" | Other "BS" -> Obj.magic, Obj.magic | _ -> Float.(to_int, of_int) let round_towards_zero x = let open Float in if x < 0. then x |> neg % floor % neg else floor x module Float' = struct let zero = Float.zero let one = Float.one let minus_one = Float.minus_one let succ = Float.succ let pred = Float.pred let neg = Float.neg let add = Float.add let sub = Float.sub let mul = Float.mul let rem = Float.rem let abs = Float.abs let equal = Float.equal let compare = Float.compare let min = Float.min let max = Float.max let div a b = Float.div a b |> round_towards_zero let to_int = to_int let of_int = of_int let to_string = Float.to_string end include Float' module Ops = MakeOps(struct type int53p = float include Float' end) include Ops let of_float = identity let to_float = identity let to_int64 = Int64.of_float let of_int64 = Int64.to_float [%%if not(re)] let to_nativeint = Nativeint.of_float let of_nativeint = Nativeint.to_float [%%endif] let of_string = float_of_string end let current_impl_flavor = if Sys.int_size >= 53 then `int_impl else match Sys.backend_type with | Other "js_of_ocaml" | Other "BS" -> `float_impl | _ -> `int64_impl let impl_of_builtin_flavor : int53p_impl_flavor -> (module S) = function | `int_impl -> (module IntImpl) | `int64_impl -> (module Int64Impl) | `float_impl -> (module FloatImpl) | flavor -> failwith' "non-builtin int53p_impl_flavor: %a" pp_int53p_impl_flavor flavor module CurrentFlavorImpl = (val (impl_of_builtin_flavor current_impl_flavor)) end include Internals.CurrentFlavorImpl end include Int53p.Ops module Datetime0 : sig val leap_year : int -> bool val daycount_of_month : leap:bool -> int -> int val day_of_year : int -> int -> int -> int module type NormalizedTimestamp = sig module Conf : sig val epoch_year : int * the epoch would be at January 1st 00:00:00.0 in [ epoch_year ] val subsecond_resolution : int * e.g. sec - resolution use [ 1 ] and millisec - resolution use [ 1000 ] val min_year : int val max_year : int end val normalize : ?subsec:int -> ?tzoffset:(int*int) -> int*int*int -> int*int*int -> int * [ normalize ? tzoffset:(tzhour , tzmin ) ? subsec ( yy , , dd ) ( hour , min , sec ) ] calculates the normalized timestamp ?tzoffset:(tzhour, tzmin) ?subsec (yy, mm, dd) (hour, min, sec)] calculates the normalized timestamp *) end module EpochNormalizedTimestamp (Conf : sig * see NormalizedTimestamp val epoch_year : int val subsecond_resolution : int end) : NormalizedTimestamp module UnixTimestmapSecRes : NormalizedTimestamp module UnixTimestmapMilliRes : NormalizedTimestamp module UnixTimestmapNanoRes : NormalizedTimestamp end = struct let sum = List.foldl (+) 0 let days_of_months_nonleap = List.to_function @@ [ 0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31; ] let days_of_months_leap = List.to_function @@ [ 0; 31; 29; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31; ] let days_of_months_subsum_nonleap = List.( iota 13 |&> (fun x -> iota x |&> days_of_months_nonleap |> sum) |> to_function) let days_of_months_subsum_leap = let sum = List.foldl (+) 0 in List.( iota 13 |&> (fun x -> iota x |&> days_of_months_leap |> sum) |> to_function) let daycount_of_month ~leap = let table = if leap then days_of_months_leap else days_of_months_nonleap in fun mm -> table mm let leap_year yy = let div x = yy mod x = 0 in if not (div 4) then false else if not (div 100) then true else if div 400 then true else false let day_of_year yy = let table = match leap_year yy with | false -> days_of_months_subsum_nonleap | true -> days_of_months_subsum_leap in fun mm dd -> table mm + dd module type NormalizedTimestamp = sig module Conf : sig val epoch_year : int val subsecond_resolution : int val min_year : int val max_year : int end val normalize : ?subsec:int -> ?tzoffset:(int*int) -> int*int*int -> int*int*int -> int * [ normalize yy mm dd ? subsec hour min sec ] calculates the normalized timestamp end module EpochNormalizedTimestamp (Conf : sig val epoch_year : int val subsecond_resolution : int end) = struct module Conf = struct include Conf let min_year = Conf.epoch_year let max_year = let span = (pred Int.max_int) / (366*24*60*60*subsecond_resolution) in span-1+min_year end open Conf let yearcount_leaping ymin ymax = let roundup div = fun x -> if x mod div = 0 then x else div*(succ (x/div)) in let ncat div = let span = ymax - (roundup div ymin) in if span < 0 then 0 else succ (span/div) in let ncat4 = ncat 4 in let ncat100 = ncat 100 in let ncat400 = ncat 400 in ncat4 - ncat100 + ncat400 let normalize ?subsec ?tzoffset (yy, mm, dd) (hour, min, sec) = let subsec = Option.(value ~default:0 subsec) in if yy < min_year || yy > max_year then invalid_arg Format.(asprintf "%s.normalize - timestamp cannot be handled: \ %d-%d-%d %02d:%02d:%02d (subsec: %d/%d) - \ year out of range (%d-%d)" "/kxclib.ml/.Datetime0.EpochNormalizedTimestamp" yy mm dd hour min sec subsec subsecond_resolution min_year max_year); if subsec >= subsecond_resolution then invalid_arg Format.(sprintf "%s.normalize - subsec out of range (%d-%d)" "/kxclib.ml/.Datetime0.EpochNormalizedTimestamp" 0 (pred subsecond_resolution)); let days_past_years = let ymin, ymax = epoch_year, pred yy in let leaping = yearcount_leaping ymin ymax in let nonleaping = ymax-ymin+1-leaping in leaping*366+nonleaping*365 in let doy = day_of_year yy mm dd in let hour, min = match tzoffset with | None -> hour, min | Some (tzhour, tzmin) -> hour+tzhour, min+tzmin in let nts = sec + min*60 + hour*60*60 + (days_past_years + doy)*24*60*60 in let nts = nts * subsecond_resolution + subsec in nts end module UnixTimestmapSecRes = EpochNormalizedTimestamp(struct let epoch_year = 1970 let subsecond_resolution = 1 end) module UnixTimestmapMilliRes = EpochNormalizedTimestamp(struct let epoch_year = 1970 let subsecond_resolution = 1000 end) module UnixTimestmapNanoRes = EpochNormalizedTimestamp(struct let epoch_year = 1970 let subsecond_resolution = 1000*1000*1000 end) end module ParseArgs = struct type optparser = string -> [`Process_next of bool] let prefset r x = r := x let prefsetv r v _ = r := v let scanfparser fmt fn : optparser = fun str -> Scanf.ksscanf str (fun _ _ -> `Process_next true) fmt fn; `Process_next false let exactparser fmt (fn : unit -> unit) : optparser = function | str when str = fmt -> fn (); `Process_next false | _ -> `Process_next true let parse_opts (optparsers : optparser list) ?argsource:(argsource=Sys.argv, 1) () = let rec tryparse str = function | [] -> raise (Invalid_argument ("unparsed option: "^str)) | p::ps -> match (p : optparser) str with | `Process_next true -> tryparse str ps | `Process_next false -> () in Array.to_list (fst argsource) |> List.drop (snd argsource) |!> Fn.fix2nd optparsers tryparse let parse_opts_args ?optprefix:(optprefix="-") ?optsep:(optsep="--") (optparsers : optparser list) ?argsource:(argsource=Sys.argv, 1) () = let source, startidx = argsource in let optprefixlen = String.length optprefix in let prefixed str = if String.length str < optprefixlen then false else (String.sub str 0 optprefixlen) = optprefix in let argc = Array.length source in let args = ref [] in let rec tryparse str = function | [] -> raise (Invalid_argument ("unparsed option: "^str)) | p::ps -> match p str with | `Process_next true -> tryparse str ps | `Process_next false -> () in let tryparse = Fn.fix2nd optparsers tryparse in let rec loop n parseopt = if n >= argc then List.rev !args else begin let arg = source.(n) in if not parseopt then (refappend args arg; loop (succ n) parseopt) else if arg = optsep then loop (succ n) false else if prefixed arg then (tryparse arg; loop (succ n) parseopt) else (refappend args arg; loop (succ n) parseopt) end in loop startidx true end module ArgOptions = struct type _ named_option = | IntOption : string -> int named_option | FloatOption : string -> float named_option | StringOption : string -> string named_option | InChannelOption : string -> in_channel named_option | OutChannelOption : string -> out_channel named_option | InChannelOption' : string -> (in_channel*channel_desc) named_option | OutChannelOption' : string -> (out_channel*channel_desc) named_option and channel_desc = [ `StandardChannel | `FileChannel of string ] let opt_of_named_option (type x) (opt : x named_option) = match opt with | IntOption opt -> opt | FloatOption opt -> opt | StringOption opt -> opt | InChannelOption opt -> opt | OutChannelOption opt -> opt | InChannelOption' opt -> opt | OutChannelOption' opt -> opt module type FeatureRequests = sig val has_flag : ?argsource:(string array*int) -> ?prefix:string -> bool val get_option : ?argsource:(string array*int) -> ?optprefix:string -> ?optsep:string -> 'x named_option -> 'x val get_option_d : ?argsource:(string array*int) -> ?optprefix:string -> ?optsep:string -> 'x named_option -> 'x val get_option_d' : ?argsource:(string array*int) -> ?optprefix:string -> ?optsep:string -> 'x named_option -> 'x val get_args : ?argsource:(string array*int) -> ?optsep:string -> unit -> string list end let has_flag ?argsource ?prefix:(prefix="") flag = let store = ref false in ParseArgs.( parse_opts [ exactparser (prefix^flag) (fun () -> store := true); (constant (`Process_next false)) ]) ?argsource (); !store let get_option ?argsource ?prefix:(prefix="") ?optsep (type x) : x named_option -> x option = let open ParseArgs in let labor opt f = let state = ref `Init in let result = ref None in let marker_raw = prefix^opt in let marker_eq = marker_raw^"=" in let par arg = match !state with | `Init when arg = marker_raw -> state := `CaptureNext; `Process_next true | `Init -> (match String.chop_prefix marker_eq arg with | Some arg -> result := Some (f arg); `Process_next false | None -> `Process_next true) | `CaptureNext -> (state := `Init; result := Some (f arg)); `Process_next false in parse_opts_args ?argsource ~optprefix:"" ?optsep [par; constant (`Process_next false)] () |> ignore; match !state with | `Init -> !result | `CaptureNext -> invalid_arg ("no argument supplied to option "^opt) in function | IntOption opt -> labor opt (fun arg -> Scanf.sscanf arg "%i%!" identity) | FloatOption opt -> labor opt (fun arg -> Scanf.sscanf arg "%g%!" identity) | StringOption opt -> labor opt identity | InChannelOption opt -> labor opt (function | "-" -> stdin | path -> open_in path) | OutChannelOption opt -> labor opt (function | "-" -> stdout | path -> open_out path) | InChannelOption' opt -> labor opt (function | "-" -> stdin, `StandardChannel | path -> open_in path, `FileChannel path) | OutChannelOption' opt -> labor opt (function | "-" -> stdout, `StandardChannel | path -> open_out path, `FileChannel path) let get_option_exn ?argsource ?prefix ?optsep (type x) : x named_option -> x = fun opt -> match get_option ?argsource ?prefix ?optsep opt with | None -> invalid_arg ("you have to provide option "^(opt_of_named_option opt)) | Some x -> x let get_option_d' ?argsource ?prefix ?optsep (type x) : x named_option -> (unit -> x) -> x = fun opt vp -> match get_option ?argsource ?prefix ?optsep opt with | None -> vp() | Some x -> x let get_option_d ?argsource ?prefix ?optsep (type x) : x named_option -> x -> x = fun opt v -> match get_option ?argsource ?prefix ?optsep opt with | None -> v | Some x -> x let get_absolute_args ?optsep:(optsep="--") ?argsource:(argsource=Sys.argv, 1) () = let source, startidx = argsource in let argc = Array.length source in let args = ref [] in let rec loop n record_arg = if n >= argc then List.rev !args else begin let arg = source.(n) in if record_arg then (refappend args arg; loop (succ n) record_arg) else if arg = optsep then loop (succ n) true else loop (succ n) record_arg end in loop startidx false end module FmtPervasives = struct type ppf = Format.formatter let color_enabled = ref true let fprintf ppf fmt = Format.fprintf ppf fmt let printf fmt = Format.printf fmt let sprintf fmt = Format.asprintf fmt let eprintf fmt = Format.eprintf fmt module Fmt = struct let stdout_ppf = Format.std_formatter let stderr_ppf = Format.err_formatter let null_ppf = Format.formatter_of_out_functions { out_string = (fun _ _ _ -> ()); out_flush = (fun _ -> ()); out_newline = (fun _ -> ()); out_spaces = (fun _ -> ()); out_indent = (fun _ -> ()); } let colored ?style ?color_mode:(m=`Fg) color ppf fmt = if !color_enabled then ( let code_table = function | `Black -> 30, 40 | `Red -> 31, 41 | `Green -> 32, 42 | `Yellow -> 33, 43 | `Blue -> 34, 44 | `Magenta -> 35, 45 | `Cyan -> 36, 46 | `White -> 37, 47 | `Bright_black -> 90, 100 | `Bright_red -> 91, 101 | `Bright_green -> 92, 102 | `Bright_yellow -> 93, 103 | `Bright_blue -> 94, 104 | `Bright_magenta -> 95, 105 | `Bright_cyan -> 96, 106 in let style_table = function | `Bold -> 1 | `Thin -> 2 | `Italic -> 3 | `Underline -> 4 in let esc x = "\027"^x in let reset = "[0m" in let color_code = code_table color |> (match m with `Fg -> fst | `Bg -> snd) |> sprintf "[%dm" in let style_code = style |> function | None -> None | Some s -> style_table s |> sprintf "[%dm" |> Option.some in Format.fprintf ppf "@<0>%s" ((esc color_code)^(style_code |> Option.map esc |? "")); Format.kfprintf (fun ppf -> Format.fprintf ppf "@<0>%s" (esc reset)) ppf fmt ) else Format.fprintf ppf fmt end let condformat cond fmtfunc fmt = if cond then fmtfunc fmt else Format.ifprintf Fmt.null_ppf fmt let pp_of_to_string to_string ppf x = Format.pp_print_string ppf (to_string x) let to_string_of_pp pp = sprintf "%a" pp let pps to_string = pp_of_to_string to_string let spp pp = to_string_of_pp pp let pp_int = Format.pp_print_int let pp_float = Format.pp_print_float let pp_string = Format.pp_print_string let pp_char = Format.pp_print_char let pp_bool = Format.pp_print_bool let pp_unit ppf () = pp_string ppf "unit" let pp_ref_address ppf (r : 'x ref) = fprintf ppf "%#x" (2*(Obj.magic r)) let pp_int32 ppf x = Int32.to_string x |> pp_string ppf let pp_int64 ppf x = Int64.to_string x |> pp_string ppf * print integer with thousand separator let pp_integer_sep' ~padding ppf x = let rec loop acc x = if x > 0 then loop ((x mod 1000) :: acc) (x / 1000) else acc in let chunks = loop [] (abs x) in let chunks = match chunks with | [x] -> [string_of_int x] | h :: r -> string_of_int h :: (r |&> sprintf "%03d") | [] -> ["0"] in if x < 0 then pp_char ppf '-'; let str = String.concat "," chunks in (match padding with | None -> () | Some (0, _) -> () | Some (d, pad) -> let d = d + (Float.ceil (float_of_int d /. 3.) |> int_of_float) - 1 in let slen = String.length str in if d > slen then Fn.ntimes (d-slen) (fun() -> pp_char ppf pad) ()); pp_string ppf str let pp_integer_sep ppf = pp_integer_sep' ~padding:None ppf let pp_multiline ppf str = let open Format in let rec loop = function | [line] -> pp_string ppf line | line :: rest -> pp_string ppf line; pp_force_newline ppf (); loop rest | [] -> () in String.split_on_char '\n' str |> loop let pp_exn ppf exn = Printexc.to_string exn |> Format.pp_print_string ppf let pp_full_exn' ppf (exn, bt) = Format.fprintf ppf "@<2>%s@[<hov>@\n%a@]" (Printexc.to_string exn) pp_multiline Printexc.(bt |> raw_backtrace_to_string) let pp_full_exn ppf exn = pp_full_exn' ppf (exn, Printexc.(get_raw_backtrace())) let string_of_symbolic_output_items : Format.symbolic_output_item list -> string = fun items -> let buf = Buffer.create 0 in items |!> (function | Output_flush -> () | Output_newline -> Buffer.add_char buf '\n' | Output_string str -> Buffer.add_string buf str | Output_spaces n | Output_indent n -> Buffer.add_string buf (String.make n ' ')); Buffer.contents buf end include FmtPervasives module Log0 = struct open Format module Internals = struct let timestamp_func = ref (constant None) let logging_formatter = ref err_formatter end open Internals module LoggingConfig = struct let install_timestamp_function func = timestamp_func := func let set_logging_formatter ppf = logging_formatter := ppf let get_logging_formatter() = !logging_formatter end let logr fmt = fprintf !logging_formatter fmt let log ~label ?modul ?header_style:(style=None) ?header_color:(color=`Magenta) fmt = let header = match modul with | None -> label | Some m -> label^":"^m in let header = match !timestamp_func() with | None -> sprintf "[%s]" header | Some ts -> sprintf "[%s :%.3f]" header ts in let pp_header ppf = Fmt.colored ?style color ppf "%s" in logr "@<1>%s @[<hov>" (asprintf "%a" pp_header header); kfprintf (fun ppf -> fprintf ppf "@]@.") !logging_formatter fmt let verbose ?modul fmt = log ?modul fmt ~label:"VERBOSE" ~header_style:(Some `Thin) ~header_color:`Bright_cyan let info ?modul fmt = log ?modul fmt ~label:"INFO" ~header_style:(Some `Bold) ~header_color:`Bright_cyan let warn ?modul fmt = log ?modul fmt ~label:"WARN" ~header_style:(Some `Bold) ~header_color:`Yellow let debug ?modul fmt = log ?modul fmt ~label:"DEBUG" ~header_style:(Some `Bold) ~header_color:`Magenta let error ?modul fmt = log ?modul fmt ~label:"ERROR" ~header_style:(Some `Bold) ~header_color:`Red module Pervasives = struct let debug ?modul fmt = debug ?modul fmt let info ?modul fmt = info ?modul fmt end end include Log0.Pervasives module Json : sig type jv = [ | `null | `bool of bool | `num of float | `str of string | `arr of jv list | `obj of (string*jv) list ] type jv_field = string*jv type jv_fields = jv_field list val normalize : jv -> jv val normalize_fields : jv_fields -> jv_fields val eqv : jv -> jv -> bool * whether two json value are equivalent , i.e. equal while ignoring ordering of object fields val pp_unparse : ppf -> jv -> unit * [ pp_unparse ppf j ] output [ j ] as a JSON string . NB : this function does not check if [ j ] contains any [ ` str s ] where [ s ] is an invalid UTF-8 string . it just assumes so . NB: this function does not check if [j] contains any [`str s] where [s] is an invalid UTF-8 string. it just assumes so. *) val unparse : jv -> string val pp_lit : ppf -> jv -> unit * [ pp_lit j ] output [ j ] in a format that can be used as an OCaml literal . val show : jv -> string type jvpath = ([ ] as 'path_component) list type legacy = [ | `arr of jv list | `obj of (string*jv) list ] val of_legacy : legacy -> jv val to_legacy : jv -> legacy option type yojson = ([ | `Null | `Bool of bool | `Int of int | `Intlit of string | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list | `Tuple of 't list | `Variant of string * 't option ] as 't) val of_yojson : yojson -> jv val to_yojson : jv -> yojson type yojson' = ([ | `Null | `Bool of bool | `Int of int | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list ] as 't) val yojson_basic_of_safe : yojson -> yojson' val yojson_safe_of_basic : yojson' -> yojson type jsonm = jsonm_token seq and jsonm_token = [ | `Null | `Bool of bool | `String of string | `Float of float | `Name of string | `As | `Ae | `Os | `Oe ] type 'loc jsonm' = ('loc*jsonm_token) seq | `empty_document | `premature_end of 'loc | `expecting_value_at of 'loc | `unexpected_token_at of 'loc*jsonm_token ] val of_jsonm' : 'loc jsonm' -> (jv * 'loc jsonm', 'loc jsonm_pe) result val of_jsonm : jsonm -> (jv * jsonm) option val to_jsonm : jv -> jsonm end = struct type jv = [ | `null | `bool of bool | `num of float | `str of string | `arr of jv list | `obj of (string*jv) list ] let sort_by_key fs = fs |> List.sort_uniq (fun (k1, _) (k2, _) -> String.compare k1 k2) let rec eqv a b = match a, b with | `null, `null -> true | `bool a, `bool b -> a = b | `num a, `num b -> a = b | `str a, `str b -> a = b | `arr xs, `arr ys -> let rec loop = function | [], [] -> true | x :: xs, y :: ys when eqv x y -> loop (xs, ys) | _ -> false in loop (xs, ys) | `obj fs1, `obj fs2 -> let sort = sort_by_key in let fs1, fs2 = sort fs1, sort fs2 in let rec loop = function | [], [] -> true | (k1, x) :: xs, (k2, y) :: ys when k1 = k2 && eqv x y -> loop (xs, ys) | _ -> false in loop (fs1, fs2) | _ -> false type jv_field = string*jv type jv_fields = jv_field list let rec normalize : jv -> jv = function | (`null | `bool _ | `num _ | `str _) as x -> x | `arr xs -> `arr (xs |&> normalize) | `obj fs -> `obj (normalize_fields fs) and normalize_fields : jv_fields -> jv_fields = fun fs -> sort_by_key fs |&> (fun (k, v) -> k, normalize v) let rec pp_unparse = fun ppf -> let self = pp_unparse in let outs = Format.pp_print_string ppf in let outf fmt = Format.fprintf ppf fmt in function | `null -> outs "null" | `bool true -> outs "true" | `bool false -> outs "false" | `num n -> outf "%g" n | `str s -> outf "\"%a\"" String.pp_json_escaped s | `arr [] -> outs "[]" | `arr xs -> outs "["; xs |> List.iter' (fun j -> outf "%a,%!" self j) (fun j -> outf "%a]%!" self j) | `obj [] -> outs "{}" | `obj fs -> outs "{"; fs |> List.iter' (fun (f,j) -> outf "\"%a\":%!%a,%!" String.pp_json_escaped f self j) (fun (f,j) -> outf "\"%a\":%!%a}%!" String.pp_json_escaped f self j) let unparse = sprintf "%a" pp_unparse let rec pp_lit = fun ppf -> let self = pp_lit in let outs = Format.pp_print_string ppf in let outf fmt = Format.fprintf ppf fmt in function | `null -> outs "`null" | `bool true -> outs "`bool true" | `bool false -> outs "`bool false" | `num n -> if n = 0. then outs "`num 0." else if n < 0. then outf "`num (%F)" n else outf "`num %F" n | `str s -> outf "`str %S" s | `arr [] -> outs "`arr []" | `arr xs -> outf "`arr ["; xs |> List.iter' (fun value -> fprintf ppf "@[<hov 0>%a@];@;<1 2>@?" self value) (fun value -> fprintf ppf "@[<hov 0>%a@]]@?" self value); | `obj [] -> outs "`obj []" | `obj fs -> outf "`obj ["; fs |> List.iter' (fun (key, value) -> fprintf ppf "@[<hov 0>%S, @,@[<hov 0>%a@];@]@;<1 2>@?" key self value) (fun (key, value) -> fprintf ppf "@[<hov 0>%S, @,@[<hov 0>%a@]@]]@?" key self value) let show = sprintf "%a" pp_lit type jvpath = ([ | `f of string | `i of int ] as 'path_component) list type legacy = [ | `arr of jv list | `obj of (string*jv) list ] type yojson = ([ | `Null | `Bool of bool | `Int of int | `Intlit of string | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list | `Tuple of 't list | `Variant of string * 't option ] as 't) let of_legacy x = (x :> jv) let to_legacy : jv -> legacy option = function | #legacy as x -> Some x | _ -> None let rec of_yojson : yojson -> jv = function | `Null -> `null | `Bool x -> `bool x | `Int x -> `num (float_of_int x) | `Intlit x -> `num (float_of_string x) | `Float x -> `num x | `String x -> `str x | `Assoc x -> `obj (x |&> ?>of_yojson) | `List x -> `arr (x |&> of_yojson) | `Tuple x -> `arr (x |&> of_yojson) | `Variant (t, Some x) -> `arr [`str t; of_yojson x] | `Variant (t, None) -> `str t let rec to_yojson : jv -> yojson = function | `null -> `Null | `bool x -> `Bool x | `num x -> ( if Float.is_integer x && (x <= (Int.max_int |> float_of_int)) && (x >= (Int.min_int |> float_of_int)) then (`Int (Float.to_int x)) else `Float x) | `str x -> `String x | `arr x -> `List (x |&> to_yojson) | `obj x -> `Assoc (x |&> ?>to_yojson) type yojson' = ([ | `Null | `Bool of bool | `Int of int | `Float of float | `String of string | `Assoc of (string * 't) list | `List of 't list ] as 't) let rec yojson_basic_of_safe : yojson -> yojson' = fun yojson -> match yojson with | `Null -> `Null | `Bool x -> `Bool x | `Int x -> `Int x | `Intlit x -> `Int (int_of_string x) | `Float x -> `Float x | `String x -> `String x | `Assoc xs -> `Assoc (xs |&> fun (n, x) -> (n, yojson_basic_of_safe x)) | `List xs -> `List (xs |&> yojson_basic_of_safe) | `Tuple xs -> `List (xs |&> yojson_basic_of_safe) | `Variant (c, x_opt) -> begin match Option.map yojson_basic_of_safe x_opt with | None -> `List [`String c] | Some x -> `List [`String c; x] end let yojson_safe_of_basic : yojson' -> yojson = fun x -> (x :> yojson) type jsonm = jsonm_token seq and jsonm_token = [ | `Null | `Bool of bool | `String of string | `Float of float | `Name of string | `As | `Ae | `Os | `Oe ] type atomic_jsonm_token = [ | `Null | `Bool of bool | `String of string | `Float of float ] type value_starting_jsonm_token = [ | atomic_jsonm_token | `As | `Os ] type 'loc jsonm' = ('loc*jsonm_token) seq | `empty_document | `premature_end of 'loc | `expecting_value_at of 'loc | `unexpected_token_at of 'loc*jsonm_token ] let of_jsonm' : 'loc jsonm' -> (jv*'loc jsonm', 'loc jsonm_pe) result = fun input -> let (>>=) m f = Result.bind m f in let jv_of_atom : atomic_jsonm_token -> jv = function | `Null -> `null | `Bool x -> `bool x | `String x -> `str x | `Float x -> `num x | _ -> . in let with_next (sloc : 'loc) (next : 'loc jsonm') (kont : 'loc -> 'loc jsonm' -> jsonm_token -> 'r) : 'r = match next() with | Seq.Nil -> Error (`premature_end sloc) | Seq.Cons ((nloc, ntok), next') -> kont nloc next' ntok in let ok next x : (jv*'loc jsonm', 'loc jsonm_pe) result = Ok (x, next) in let rec value loc next = function | #atomic_jsonm_token as tok -> jv_of_atom tok |> ok next | `As -> with_next loc next (collect_array []) | `Os -> with_next loc next (collect_object []) | (`Name _ | `Ae | `Oe) as tok -> Error (`unexpected_token_at (loc, tok)) | _ -> . and collect_array acc sloc next = function | `Ae -> ok next (`arr (List.rev acc)) | #value_starting_jsonm_token as head -> with_next sloc Seq.(cons (sloc, head) next) value >>= (fun (v, next) -> with_next sloc next (fun _nloc -> collect_array (v :: acc) sloc)) | (`Name _ | `Oe) as tok -> Error (`unexpected_token_at (sloc, tok)) | _ -> . and collect_object acc sloc next = function | `Oe -> ok next (`obj (List.rev acc)) | `Name key -> ( with_next sloc next value >>= (fun (v, next) -> with_next sloc next (fun _nloc -> collect_object ((key, v) :: acc) sloc))) | (#value_starting_jsonm_token | `Ae) as tok -> Error (`unexpected_token_at (sloc, tok)) | _ -> . in match input () with | Seq.Nil -> Error (`empty_document) | Seq.Cons ((loc, tok), next) -> ( value loc next tok) let of_jsonm : jsonm -> (jv * jsonm) option = fun jsonm -> Seq.map (fun tok -> ((), tok)) jsonm |> of_jsonm' |> Result.to_option |> Option.map (fun (out, rest) -> (out, Seq.map snd rest)) let rec to_jsonm : jv -> jsonm = function | `null -> Seq.return `Null | `bool x -> Seq.return (`Bool x) | `num x -> Seq.return (`Float x) | `str x -> Seq.return (`String x) | `arr xs -> Seq.cons `As (List.fold_right (fun x seq -> Seq.append (to_jsonm x) seq) xs (Seq.return `Ae)) | `obj xs -> Seq.cons `Os (List.fold_right (fun (name, x) seq -> Seq.append (Seq.cons (`Name name) (to_jsonm x)) seq) xs (Seq.return `Oe)) end module Jv : sig open Json val pump_field : string -> jv -> jv val access : jvpath -> jv -> jv option val access_null : jvpath -> jv -> unit option val access_bool : jvpath -> jv -> bool option val access_num : jvpath -> jv -> float option val access_int : jvpath -> jv -> int option val access_int53p : jvpath -> jv -> int53p option val access_str : jvpath -> jv -> string option val access_arr : jvpath -> jv -> jv list option val access_obj : jvpath -> jv -> jv_fields option val access' : (jv -> 'a option) -> jvpath -> jv -> 'a option val access_arr' : (jv -> 'a option) -> jvpath -> jv -> 'a list option end = struct open Json let pump_field fname : jv -> jv = function | `obj [(_, _)] as jv -> jv | `obj fs as jv -> ( match List.deassoc_opt fname fs with | Some fval, fs' -> `obj ((fname, fval) :: fs') | None, _ -> jv) | jv -> jv let access : jvpath -> jv -> jv option = fun path jv -> let rec go = function | [], x -> some x | `f fname :: path', `obj fs -> fs |> List.find_map (fun (k, v) -> if k = fname then go (path', v) else none ) | `i idx :: path', `arr xs -> List.nth_opt xs idx >>? (fun x -> go (path', x)) | _ -> none in go (path, jv) let access' : (jv -> 'a option) -> jvpath -> jv -> 'a option = fun f path jv -> access path jv >>? f let access_null : jvpath -> jv -> unit option = access' (function | `null -> some () | _ -> none) let access_bool : jvpath -> jv -> bool option = access' (function | `bool x -> some x | _ -> none) let access_num : jvpath -> jv -> float option = access' (function | `num x -> some x | _ -> none) let access_int : jvpath -> jv -> int option = access' (function | `num x when (float_of_int % int_of_float) x = x -> some (x |> int_of_float) | _ -> none) let access_int53p : jvpath -> jv -> int53p option = fun path jv -> access_num path jv >? Int53p.of_float let access_str : jvpath -> jv -> string option = access' (function | `str x -> some x | _ -> none) let access_arr : jvpath -> jv -> jv list option = access' (function | `arr xs -> some xs | _ -> none) let access_obj : jvpath -> jv -> jv_fields option = access' (function | `obj fs -> some fs | _ -> none) let access_arr' : (jv -> 'a option) -> jvpath -> jv -> 'a list option = fun f path jv -> let open Option.Ops_monad in access_arr path jv >? (List.map f &> sequence_list) |> Option.join end module Base64 = struct module type Config = sig * the 62nd character . [ ' + ' ] in rfc4648 , [ ' - ' ] in rfc4648_url . val c62 : char val c63 : char val pad : char option val validate_padding: bool val ignore_newline : bool val ignore_unknown : bool end module type T = sig val encode : ?offset:int -> ?len:int -> bytes -> string val decode : ?offset:int -> ?len:int -> string -> bytes end exception Invalid_base64_padding of [ | `invalid_char_with_position of char * int | `invalid_padding_length of int ] let () = Printexc.register_printer begin function | Invalid_base64_padding (`invalid_char_with_position (c, i)) -> some (sprintf "Invalid_base64_padding - char %c at %d" c i) | Invalid_base64_padding (`invalid_padding_length len) -> some (sprintf "Invalid_base64_padding_len - %d" len) | _ -> none end module Make (C: Config) : T = struct open C let int_A = int_of_char 'A' let int_Z = int_of_char 'Z' let int_a = int_of_char 'a' let int_z = int_of_char 'z' let int_0 = int_of_char '0' let int_9 = int_of_char '9' let c62, c63 = int_of_char c62, int_of_char c63 let sixbit_to_char b = 0 - 9 else if b = 62 then c62 else c63 let char_to_sixbit c = if int_A <= c && c <= int_Z then Some (c - int_A) else if int_a <= c && c <= int_z then Some (c - int_a + 26) else if int_0 <= c && c <= int_9 then Some (c - int_0 + 52) else if c = c62 then Some 62 else if c = c63 then Some 63 else None let encode_buf ?(offset=0) ?len (output: Buffer.t) (input: bytes) = let input_offset, input_end, input_length = let orig_len = Bytes.length input in let len = len |? (orig_len - offset) in let end_index = offset + len in if len < 0 || end_index > orig_len then invalid_arg' "Base64.encode: the input range (offset:%d, len:%d) is out of bounds" offset len else offset, end_index, len in let output_buf = Buffer.create estimated_chars in let write i o len = let set value o = Buffer.add_uint8 output_buf (sixbit_to_char (value land 0x3f)); o + 1 in let get i = Bytes.get_uint8 input i in let b1 = get i in .. b1[5 ] match len with | `S n -> let b2 = get (i+1) in match n with | `S `I -> let b3 = get (i+2) in b3[2] .. ] in let rec go i o = match input_end - i with | 0 -> begin match pad with | Some pad -> let pad_chars = match o mod 4 with when len mod 3 = 0 when len mod 3 = 1 when len mod 3 = 2 | _ -> failwith "impossible" in List.range 0 pad_chars |> List.fold_left (fun o _ -> Buffer.add_char output_buf pad; o+1) o | None -> o end | 1 -> `I |> write i o |> go (i+1) | 2 -> `S `I |> write i o |> go (i+2) | _ -> `S (`S `I) |> write i o |> go (i+3) in let total_bytes = go input_offset 0 in Buffer.add_buffer output output_buf; total_bytes let encode ?offset ?len input = let output = Buffer.create 0 in encode_buf ?offset ?len output input |> ignore; Buffer.contents output let count_lenth_ignoring ?(offset=0) ?len (input: Bytes.t): int = let orig_len = Bytes.length input in let len = len |? (orig_len - offset) in let is_sixbit = char_to_sixbit &> Option.is_some in match ignore_unknown, ignore_newline with | true, _ -> let count acc i = let b = Bytes.get_uint8 input (offset + i) in if (is_sixbit b) then acc + 1 else acc in len |> iotafl count 0 | false, true -> let count acc i = let b = Bytes.get_uint8 input (offset + i) in if (is_sixbit b) then acc + 1 else begin match char_of_int b with | '\r' | '\n' -> acc | _ -> acc + 1 end in len |> iotafl count 0 | false, false -> len let decode_buf ?(offset=0) ?len (output: Buffer.t) (input: string) = let input = Bytes.of_string input in let input_offset, input_end, input_length = let orig_len = Bytes.length input in let len = len |? (orig_len - offset) in let end_index = offset + len in if len < 0 || end_index > orig_len then invalid_arg' "Base64.encode: the input range (offset:%d, len:%d) is out of bounds" offset len else if Option.is_some pad then let actual_len = count_lenth_ignoring ~offset ~len input in if actual_len mod 4 <> 0 then invalid_arg "Base64.decode: wrong padding" else offset, end_index, len else offset, end_index, len in let output_buf = Buffer.create estimated_bytes in let read stack o = let set o value = Buffer.add_uint8 output_buf (value land 0xff); o+1 in match List.rev stack with | [] -> o | [_] -> invalid_arg "Base64.decode: unterminated input" | s1 :: s2 :: ss -> match ss with [ 3n+1 bytes ] 4bits = s2[2] .. s2[5 ] should 've been padded if not ((s2 land 0xf) = 0) then invalid_arg "Base64.decode: unterminated input" else o | s3 :: ss -> s2[2] .. s1[5 ] s3[0] .. [3 ] match ss with [ 3n+2 bytes ] 2bits = s3[4 ] s3[5 ] should 've been padded if not ((s3 land 0x3) = 0) then invalid_arg "Base64.decode: unterminated input" else o [ 3n bytes ] s3[4 ] s3[5 ] s4[0] .. [5 ] | _ -> failwith "impossible" in let rec go stack i o = if i = input_end then read stack o else let c = Bytes.get_uint8 input i in match char_to_sixbit c with | Some s -> let stack = s :: stack in if List.length stack = 4 then let o = read stack o in go [] (i+1) o else go stack (i+1) o | None -> begin match char_of_int c with | _ when ignore_unknown -> go stack (i+1) o | '\r' | '\n' when ignore_newline -> go stack (i+1) o | c when pad = some c && not validate_padding -> read stack o | c when pad = some c && validate_padding -> let pad = c in let validate_pad ignore = let pad_count acc ci = let c = Bytes.get_uint8 input (ci + i + 1) in begin match char_of_int c with | s when s = pad -> acc + 1 | s when ignore s -> acc | s -> raise (Invalid_base64_padding ( `invalid_char_with_position (s, ci + i + 1))) end in let pad_num = (input_end - i - 1) |> iotafl pad_count 0 |> ((+) 1) in let is_valid = 0 < pad_num && pad_num <= 2 in if is_valid then read stack o else raise (Invalid_base64_padding (`invalid_padding_length pad_num)) in begin match ignore_unknown, ignore_newline with | true, _ -> read stack o | false, true -> validate_pad begin function | '\r' | '\n' -> true | _ -> false end | false, false -> validate_pad (fun _ -> false) end | c -> invalid_arg' "Base64.decode: invalid char '%c' at index %d" c i end in let total_bytes = go [] input_offset 0 in Buffer.add_buffer output output_buf; total_bytes let decode ?offset ?len input = let output = Buffer.create 0 in decode_buf ?offset ?len output input |> ignore; Buffer.to_bytes output end module Config_rfc4648 : Config = struct let c62 = '+' let c63 = '/' let pad = Some '=' let validate_padding = true let ignore_newline = false let ignore_unknown = false end module Config_rfc4648_relaxed = struct include Config_rfc4648 let ignore_newline = true end include Make(Config_rfc4648_relaxed) module Config_rfc4648_url : Config = struct let c62 = '-' let c63 = '_' let pad = None let validate_padding = true let ignore_newline = false let ignore_unknown = false end module Config_rfc4648_url_relaxed = struct include Config_rfc4648_url let ignore_newline = true end module Url = Make(Config_rfc4648_url_relaxed) end
61a2c3185792d835a85af06d940bd82415e6e45e7f68d8d675d12afb5fcc0056
JAremko/spacetools
run.clj
(ns spacetools.spacedoc-cli.run "Tools for Spacemacs documentation files in .sdn format." (:gen-class) (:require [cats.core :as m] [cats.monad.exception :as exc :refer [failure]] [clojure.core.match :refer [match]] [clojure.string :as str :refer [join]] [spacetools.fs-io.interface :refer [try-m->output]] [spacetools.spacedoc-cli.actions :as ac] [spacetools.spacedoc-cli.args :refer [*configure! *parse]])) (defn usage [options-summary] (join \newline ["Tools for Spacemacs documentation files in .sdn format." "" ".SDN files are produced by \"sdnizer.el\" Emacs script." "" "Usage: ACTION [OPTIONS]... [ARGS]..." "" "Options:" options-summary "" "Actions:" " validate INS... Validate input .SDN files." " relations INS... Print node relations in the input .SDN files." " orgify SOURCE TARGET TARGET Convert .SDN files into .ORG files." " SOURCE is parent directory with .SDN files." " TARGET is target directory for .ORG files." " describe SPEC Describe spec by fully qualified keyword." " Example :spacetools.spacedoc.node/<keyword>" " layers DIR Create LAYERS.sdn file in DIR using SDN" " files from the directory." ""])) (def ops [["-h" "--help" "Show help message."] ["-c" "--config CONFIG" "Configuration file path" :validate [(complement str/blank?) "Configuration path should be a string"]]]) (defn bad-args-handler [action a-args] (match [action a-args] ["describe" _ ] (failure {} "\"describe\" takes qualified keyword") ["validate" _ ] (failure {} "\"validate\" takes at least 1 input") ["orgify" _ ] (failure {:args a-args} "\"orgify\" takes 2 arguments") ["relations" _ ] (failure {} "\"relations\" takes at least 1 input") ["layers" _ ] (failure {:args a-args} "\"layers\" takes 1 argument") [nil _ ] (failure {} "No action specified") :else (failure {:action action} "Invalid action"))) (defn -main [& args] (try-m->output (m/do-let [{:keys [help summary action a-args config]} (*parse args ops)] (*configure! config) (if help (exc/success (usage summary)) (match ;; Handlers: [action a-args ] ["describe" [key ]] (ac/*describe-spec key) ["validate" [_ & _]] (ac/*validate a-args) ["relations" [_ & _]] (ac/*relations a-args) ["orgify" [src trg ]] (ac/*orgify src trg) ["layers" [src ]] (ac/*layers src) :else (bad-args-handler action a-args))))))
null
https://raw.githubusercontent.com/JAremko/spacetools/d047e99689918b5a4ad483022f35802b2015af5f/bases/spacedoc-cli/src/spacetools/spacedoc_cli/run.clj
clojure
Handlers:
(ns spacetools.spacedoc-cli.run "Tools for Spacemacs documentation files in .sdn format." (:gen-class) (:require [cats.core :as m] [cats.monad.exception :as exc :refer [failure]] [clojure.core.match :refer [match]] [clojure.string :as str :refer [join]] [spacetools.fs-io.interface :refer [try-m->output]] [spacetools.spacedoc-cli.actions :as ac] [spacetools.spacedoc-cli.args :refer [*configure! *parse]])) (defn usage [options-summary] (join \newline ["Tools for Spacemacs documentation files in .sdn format." "" ".SDN files are produced by \"sdnizer.el\" Emacs script." "" "Usage: ACTION [OPTIONS]... [ARGS]..." "" "Options:" options-summary "" "Actions:" " validate INS... Validate input .SDN files." " relations INS... Print node relations in the input .SDN files." " orgify SOURCE TARGET TARGET Convert .SDN files into .ORG files." " SOURCE is parent directory with .SDN files." " TARGET is target directory for .ORG files." " describe SPEC Describe spec by fully qualified keyword." " Example :spacetools.spacedoc.node/<keyword>" " layers DIR Create LAYERS.sdn file in DIR using SDN" " files from the directory." ""])) (def ops [["-h" "--help" "Show help message."] ["-c" "--config CONFIG" "Configuration file path" :validate [(complement str/blank?) "Configuration path should be a string"]]]) (defn bad-args-handler [action a-args] (match [action a-args] ["describe" _ ] (failure {} "\"describe\" takes qualified keyword") ["validate" _ ] (failure {} "\"validate\" takes at least 1 input") ["orgify" _ ] (failure {:args a-args} "\"orgify\" takes 2 arguments") ["relations" _ ] (failure {} "\"relations\" takes at least 1 input") ["layers" _ ] (failure {:args a-args} "\"layers\" takes 1 argument") [nil _ ] (failure {} "No action specified") :else (failure {:action action} "Invalid action"))) (defn -main [& args] (try-m->output (m/do-let [{:keys [help summary action a-args config]} (*parse args ops)] (*configure! config) (if help (exc/success (usage summary)) (match [action a-args ] ["describe" [key ]] (ac/*describe-spec key) ["validate" [_ & _]] (ac/*validate a-args) ["relations" [_ & _]] (ac/*relations a-args) ["orgify" [src trg ]] (ac/*orgify src trg) ["layers" [src ]] (ac/*layers src) :else (bad-args-handler action a-args))))))
ff5ec07e3e971bf4d7cda61216a2cd8190f422126ad90be8c5ee9535cc96c506
emqx/emqx
emqx_retainer_api.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_retainer_api). -behaviour(minirest_api). -include("emqx_retainer.hrl"). -include_lib("hocon/include/hoconsc.hrl"). %% API -export([api_spec/0, paths/0, schema/1, namespace/0, fields/1]). -export([ lookup_retained_warp/2, with_topic_warp/2, config/2 ]). -import(hoconsc, [mk/1, mk/2, ref/1, ref/2, array/1]). -import(emqx_dashboard_swagger, [error_codes/2]). 1 MB = 1024 x 1024 -define(MAX_PAYLOAD_SIZE, 1048576). -define(PREFIX, "/mqtt/retainer"). -define(TAGS, [<<"retainer">>]). namespace() -> "retainer". api_spec() -> emqx_dashboard_swagger:spec(?MODULE, #{check_schema => true}). paths() -> [?PREFIX, ?PREFIX ++ "/messages", ?PREFIX ++ "/message/:topic"]. schema(?PREFIX) -> #{ 'operationId' => config, get => #{ tags => ?TAGS, description => ?DESC(get_config_api), responses => #{ 200 => mk(conf_schema(), #{desc => ?DESC(config_content)}), 404 => error_codes(['NOT_FOUND'], ?DESC(config_not_found)) } }, put => #{ tags => ?TAGS, description => ?DESC(update_retainer_api), 'requestBody' => mk(conf_schema(), #{desc => ?DESC(config_content)}), responses => #{ 200 => mk(conf_schema(), #{desc => ?DESC(update_config_success)}), 400 => error_codes(['UPDATE_FAILED'], ?DESC(update_config_failed)) } } }; schema(?PREFIX ++ "/messages") -> #{ 'operationId' => lookup_retained_warp, get => #{ tags => ?TAGS, description => ?DESC(list_retained_api), parameters => page_params(), responses => #{ 200 => [ {data, mk(array(ref(message_summary)), #{desc => ?DESC(retained_list)})}, {meta, mk(hoconsc:ref(emqx_dashboard_swagger, meta))} ], 400 => error_codes(['BAD_REQUEST'], ?DESC(unsupported_backend)) } } }; schema(?PREFIX ++ "/message/:topic") -> #{ 'operationId' => with_topic_warp, get => #{ tags => ?TAGS, description => ?DESC(lookup_api), parameters => parameters(), responses => #{ 200 => mk(ref(message), #{desc => ?DESC(message_detail)}), 404 => error_codes(['NOT_FOUND'], ?DESC(message_not_exist)), 400 => error_codes(['BAD_REQUEST'], ?DESC(unsupported_backend)) } }, delete => #{ tags => ?TAGS, description => ?DESC(delete_matching_api), parameters => parameters(), responses => #{ 204 => <<>>, 400 => error_codes( ['BAD_REQUEST'], ?DESC(unsupported_backend) ) } } }. page_params() -> emqx_dashboard_swagger:fields(page) ++ emqx_dashboard_swagger:fields(limit). conf_schema() -> ref(emqx_retainer_schema, "retainer"). parameters() -> [ {topic, mk(binary(), #{ in => path, required => true, desc => ?DESC(topic) })} ]. fields(message_summary) -> [ {msgid, mk(binary(), #{desc => ?DESC(msgid)})}, {topic, mk(binary(), #{desc => ?DESC(topic)})}, {qos, mk(emqx_schema:qos(), #{desc => ?DESC(qos)})}, {publish_at, mk(string(), #{desc => ?DESC(publish_at)})}, {from_clientid, mk(binary(), #{desc => ?DESC(from_clientid)})}, {from_username, mk(binary(), #{desc => ?DESC(from_username)})} ]; fields(message) -> [ {payload, mk(binary(), #{desc => ?DESC(payload)})} | fields(message_summary) ]. lookup_retained_warp(Type, Params) -> check_backend(Type, Params, fun lookup_retained/2). with_topic_warp(Type, Params) -> check_backend(Type, Params, fun with_topic/2). config(get, _) -> {200, emqx:get_raw_config([retainer])}; config(put, #{body := Body}) -> try {ok, _} = emqx_retainer:update_config(Body), {200, emqx:get_raw_config([retainer])} catch _:Reason:_ -> {400, #{ code => <<"UPDATE_FAILED">>, message => iolist_to_binary(io_lib:format("~p~n", [Reason])) }} end. %%------------------------------------------------------------------------------ %% Interval Funcs %%------------------------------------------------------------------------------ lookup_retained(get, #{query_string := Qs}) -> Page = maps:get(<<"page">>, Qs, 1), Limit = maps:get(<<"limit">>, Qs, emqx_mgmt:default_row_limit()), {ok, Msgs} = emqx_retainer_mnesia:page_read(undefined, undefined, Page, Limit), {200, #{ data => [format_message(Msg) || Msg <- Msgs], meta => #{page => Page, limit => Limit, count => emqx_retainer_mnesia:size(?TAB_MESSAGE)} }}. with_topic(get, #{bindings := Bindings}) -> Topic = maps:get(topic, Bindings), {ok, Msgs} = emqx_retainer_mnesia:page_read(undefined, Topic, 1, 1), case Msgs of [H | _] -> {200, format_detail_message(H)}; _ -> {404, #{ code => <<"NOT_FOUND">>, message => <<"Viewed message doesn't exist">> }} end; with_topic(delete, #{bindings := Bindings}) -> Topic = maps:get(topic, Bindings), emqx_retainer_mnesia:delete_message(undefined, Topic), {204}. format_message(#message{ id = ID, qos = Qos, topic = Topic, from = From, timestamp = Timestamp, headers = Headers }) -> #{ msgid => emqx_guid:to_hexstr(ID), qos => Qos, topic => Topic, publish_at => list_to_binary( calendar:system_time_to_rfc3339( Timestamp, [{unit, millisecond}] ) ), from_clientid => to_bin_string(From), from_username => maps:get(username, Headers, <<>>) }. format_detail_message(#message{payload = Payload} = Msg) -> Base = format_message(Msg), case erlang:byte_size(Payload) =< ?MAX_PAYLOAD_SIZE of true -> Base#{payload => base64:encode(Payload)}; _ -> Base end. to_bin_string(Data) when is_binary(Data) -> Data; to_bin_string(Data) -> list_to_binary(io_lib:format("~p", [Data])). check_backend(Type, Params, Cont) -> case emqx:get_config([retainer, backend, type]) of built_in_database -> Cont(Type, Params); _ -> {400, 'BAD_REQUEST', <<"This API only support built in database">>} end.
null
https://raw.githubusercontent.com/emqx/emqx/0cfa5e2ce1de93731487ec5785dfb5e5969bc989/apps/emqx_retainer/src/emqx_retainer_api.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------- API ------------------------------------------------------------------------------ Interval Funcs ------------------------------------------------------------------------------
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_retainer_api). -behaviour(minirest_api). -include("emqx_retainer.hrl"). -include_lib("hocon/include/hoconsc.hrl"). -export([api_spec/0, paths/0, schema/1, namespace/0, fields/1]). -export([ lookup_retained_warp/2, with_topic_warp/2, config/2 ]). -import(hoconsc, [mk/1, mk/2, ref/1, ref/2, array/1]). -import(emqx_dashboard_swagger, [error_codes/2]). 1 MB = 1024 x 1024 -define(MAX_PAYLOAD_SIZE, 1048576). -define(PREFIX, "/mqtt/retainer"). -define(TAGS, [<<"retainer">>]). namespace() -> "retainer". api_spec() -> emqx_dashboard_swagger:spec(?MODULE, #{check_schema => true}). paths() -> [?PREFIX, ?PREFIX ++ "/messages", ?PREFIX ++ "/message/:topic"]. schema(?PREFIX) -> #{ 'operationId' => config, get => #{ tags => ?TAGS, description => ?DESC(get_config_api), responses => #{ 200 => mk(conf_schema(), #{desc => ?DESC(config_content)}), 404 => error_codes(['NOT_FOUND'], ?DESC(config_not_found)) } }, put => #{ tags => ?TAGS, description => ?DESC(update_retainer_api), 'requestBody' => mk(conf_schema(), #{desc => ?DESC(config_content)}), responses => #{ 200 => mk(conf_schema(), #{desc => ?DESC(update_config_success)}), 400 => error_codes(['UPDATE_FAILED'], ?DESC(update_config_failed)) } } }; schema(?PREFIX ++ "/messages") -> #{ 'operationId' => lookup_retained_warp, get => #{ tags => ?TAGS, description => ?DESC(list_retained_api), parameters => page_params(), responses => #{ 200 => [ {data, mk(array(ref(message_summary)), #{desc => ?DESC(retained_list)})}, {meta, mk(hoconsc:ref(emqx_dashboard_swagger, meta))} ], 400 => error_codes(['BAD_REQUEST'], ?DESC(unsupported_backend)) } } }; schema(?PREFIX ++ "/message/:topic") -> #{ 'operationId' => with_topic_warp, get => #{ tags => ?TAGS, description => ?DESC(lookup_api), parameters => parameters(), responses => #{ 200 => mk(ref(message), #{desc => ?DESC(message_detail)}), 404 => error_codes(['NOT_FOUND'], ?DESC(message_not_exist)), 400 => error_codes(['BAD_REQUEST'], ?DESC(unsupported_backend)) } }, delete => #{ tags => ?TAGS, description => ?DESC(delete_matching_api), parameters => parameters(), responses => #{ 204 => <<>>, 400 => error_codes( ['BAD_REQUEST'], ?DESC(unsupported_backend) ) } } }. page_params() -> emqx_dashboard_swagger:fields(page) ++ emqx_dashboard_swagger:fields(limit). conf_schema() -> ref(emqx_retainer_schema, "retainer"). parameters() -> [ {topic, mk(binary(), #{ in => path, required => true, desc => ?DESC(topic) })} ]. fields(message_summary) -> [ {msgid, mk(binary(), #{desc => ?DESC(msgid)})}, {topic, mk(binary(), #{desc => ?DESC(topic)})}, {qos, mk(emqx_schema:qos(), #{desc => ?DESC(qos)})}, {publish_at, mk(string(), #{desc => ?DESC(publish_at)})}, {from_clientid, mk(binary(), #{desc => ?DESC(from_clientid)})}, {from_username, mk(binary(), #{desc => ?DESC(from_username)})} ]; fields(message) -> [ {payload, mk(binary(), #{desc => ?DESC(payload)})} | fields(message_summary) ]. lookup_retained_warp(Type, Params) -> check_backend(Type, Params, fun lookup_retained/2). with_topic_warp(Type, Params) -> check_backend(Type, Params, fun with_topic/2). config(get, _) -> {200, emqx:get_raw_config([retainer])}; config(put, #{body := Body}) -> try {ok, _} = emqx_retainer:update_config(Body), {200, emqx:get_raw_config([retainer])} catch _:Reason:_ -> {400, #{ code => <<"UPDATE_FAILED">>, message => iolist_to_binary(io_lib:format("~p~n", [Reason])) }} end. lookup_retained(get, #{query_string := Qs}) -> Page = maps:get(<<"page">>, Qs, 1), Limit = maps:get(<<"limit">>, Qs, emqx_mgmt:default_row_limit()), {ok, Msgs} = emqx_retainer_mnesia:page_read(undefined, undefined, Page, Limit), {200, #{ data => [format_message(Msg) || Msg <- Msgs], meta => #{page => Page, limit => Limit, count => emqx_retainer_mnesia:size(?TAB_MESSAGE)} }}. with_topic(get, #{bindings := Bindings}) -> Topic = maps:get(topic, Bindings), {ok, Msgs} = emqx_retainer_mnesia:page_read(undefined, Topic, 1, 1), case Msgs of [H | _] -> {200, format_detail_message(H)}; _ -> {404, #{ code => <<"NOT_FOUND">>, message => <<"Viewed message doesn't exist">> }} end; with_topic(delete, #{bindings := Bindings}) -> Topic = maps:get(topic, Bindings), emqx_retainer_mnesia:delete_message(undefined, Topic), {204}. format_message(#message{ id = ID, qos = Qos, topic = Topic, from = From, timestamp = Timestamp, headers = Headers }) -> #{ msgid => emqx_guid:to_hexstr(ID), qos => Qos, topic => Topic, publish_at => list_to_binary( calendar:system_time_to_rfc3339( Timestamp, [{unit, millisecond}] ) ), from_clientid => to_bin_string(From), from_username => maps:get(username, Headers, <<>>) }. format_detail_message(#message{payload = Payload} = Msg) -> Base = format_message(Msg), case erlang:byte_size(Payload) =< ?MAX_PAYLOAD_SIZE of true -> Base#{payload => base64:encode(Payload)}; _ -> Base end. to_bin_string(Data) when is_binary(Data) -> Data; to_bin_string(Data) -> list_to_binary(io_lib:format("~p", [Data])). check_backend(Type, Params, Cont) -> case emqx:get_config([retainer, backend, type]) of built_in_database -> Cont(Type, Params); _ -> {400, 'BAD_REQUEST', <<"This API only support built in database">>} end.
d3f5da6ef4f48378482be972c4d316a0d29da31e1b3a8b1d69a37462caffbc60
facebookincubator/hsthrift
Exception.hs
Copyright ( c ) Facebook , Inc. and its affiliates . # LANGUAGE CPP # # LANGUAGE ScopedTypeVariables # module Util.Control.Exception ( -- * Catching all exceptions safely catchAll , handleAll , tryAll -- * Exception predicates , isSyncException , isAsyncException -- * Other utilities , throwLeftIO , throwLeftExceptionIO , tryBracket , tryFinally , onSomeException , afterwards , swallow , logExceptions ) where #if __GLASGOW_HASKELL__ == 804 import Control.Exception ( SomeAsyncException(..) ) #endif import Control.Exception.Lifted import Control.Monad import Control.Monad.Trans.Control import GHC.Stack (HasCallStack, withFrozenCallStack) import Util.Log -- | Catch all exceptions *except* asynchronous exceptions -- (technically, children of 'SomeAsyncException'). Catching -- asynchronous exceptions is almost never what you want to do: it can -- result in ignoring 'ThreadKilled' which can lead to deadlock (see -- </ -- D4745709>). -- Use this instead of the raw ' catch ' when catching ' SomeException ' . -- catchAll :: MonadBaseControl IO m => m a -> (SomeException -> m a) -> m a catchAll action handler = action `catch` \ex -> case fromException ex of Just (_ :: SomeAsyncException) -> throwIO ex Nothing -> handler ex -- | The "try" version of 'catchAll' tryAll :: MonadBaseControl IO m => m a -> m (Either SomeException a) tryAll action = (Right <$> action) `catchAll` (return . Left) -- | Flipped version of 'catchAll' handleAll :: MonadBaseControl IO m => (SomeException -> m a) -> m a -> m a handleAll = flip catchAll throwLeftIO :: Exception e => Either e a -> IO a throwLeftIO = throwLeftExceptionIO id throwLeftExceptionIO :: Exception e => (a -> e) -> Either a b -> IO b throwLeftExceptionIO mkEx e = either (throwIO . mkEx) pure e -- | Detect 'SomeAsyncException' wrapped exceptions versus all others isSyncException :: Exception e => e -> Bool isSyncException e = case fromException (toException e) of Just (SomeAsyncException _) -> False Nothing -> True -- | Detect 'SomeAsyncException' wrapped exceptions versus all others isAsyncException :: Exception e => e -> Bool isAsyncException = not . isSyncException -- | A variant of 'bracket' where the release action also gets to see whether -- the inner action succeeded or threw an exception. tryBracket ^ run first -> (a -> Either SomeException b -> IO ()) -- ^ run finally -> (a -> IO b) -- ^ run in between -> IO b tryBracket before after inner = mask $ \restore -> do a <- before r <- restore (inner a) `catch` \ex -> do after a (Left ex) throwIO ex _ <- after a (Right r) return r -- | A variant of 'finally' where the final action also gets to see whether the first action succeeded or threw an exception . tryFinally ^ run first -> (Either SomeException a -> IO ()) -- ^ run finally -> IO a tryFinally inner after = mask $ \restore -> do r <- restore inner `catch` \ex -> do after (Left ex) throwIO ex _ <- after (Right r) return r -- | Execute an action and invoke a function if it throws any exception. The -- exception is then rethrown. Any exceptions from the function are ignored -- (but logged). onSomeException :: HasCallStack => IO a -> (SomeException -> IO ()) -> IO a onSomeException io f = io `catch` \exc -> do withFrozenCallStack $ swallow $ f exc throwIO exc -- | Execute an action and do something with its result even if it throws a -- synchronous exception. Any exceptions from the function are ignored -- (but logged). afterwards :: HasCallStack => IO a -> (Either SomeException a -> IO ()) -> IO a afterwards io f = do r <- tryAll io withFrozenCallStack $ swallow $ f r case r of Right result -> return result Left exc -> throwIO exc -- | Execute an action and drop its result or any synchronous -- exception it throws. Exceptions are logged. swallow :: HasCallStack => IO a -> IO () swallow io = void io `catchAll` \exc -> do withFrozenCallStack $ logError $ "swallowing exception: " ++ show exc -- | Log and rethrow all synchronous exceptions arising from an IO computation . logExceptions :: (String -> String) -> IO a -> IO a logExceptions f io = io `onSomeException` (logError . f . show)
null
https://raw.githubusercontent.com/facebookincubator/hsthrift/26bc1df3563d1f89b5a482ec1773438e6c4e914f/common/util/Util/Control/Exception.hs
haskell
* Catching all exceptions safely * Exception predicates * Other utilities | Catch all exceptions *except* asynchronous exceptions (technically, children of 'SomeAsyncException'). Catching asynchronous exceptions is almost never what you want to do: it can result in ignoring 'ThreadKilled' which can lead to deadlock (see </ D4745709>). | The "try" version of 'catchAll' | Flipped version of 'catchAll' | Detect 'SomeAsyncException' wrapped exceptions versus all others | Detect 'SomeAsyncException' wrapped exceptions versus all others | A variant of 'bracket' where the release action also gets to see whether the inner action succeeded or threw an exception. ^ run finally ^ run in between | A variant of 'finally' where the final action also gets to see whether ^ run finally | Execute an action and invoke a function if it throws any exception. The exception is then rethrown. Any exceptions from the function are ignored (but logged). | Execute an action and do something with its result even if it throws a synchronous exception. Any exceptions from the function are ignored (but logged). | Execute an action and drop its result or any synchronous exception it throws. Exceptions are logged. | Log and rethrow all synchronous exceptions arising from an
Copyright ( c ) Facebook , Inc. and its affiliates . # LANGUAGE CPP # # LANGUAGE ScopedTypeVariables # module Util.Control.Exception catchAll , handleAll , tryAll , isSyncException , isAsyncException , throwLeftIO , throwLeftExceptionIO , tryBracket , tryFinally , onSomeException , afterwards , swallow , logExceptions ) where #if __GLASGOW_HASKELL__ == 804 import Control.Exception ( SomeAsyncException(..) ) #endif import Control.Exception.Lifted import Control.Monad import Control.Monad.Trans.Control import GHC.Stack (HasCallStack, withFrozenCallStack) import Util.Log Use this instead of the raw ' catch ' when catching ' SomeException ' . catchAll :: MonadBaseControl IO m => m a -> (SomeException -> m a) -> m a catchAll action handler = action `catch` \ex -> case fromException ex of Just (_ :: SomeAsyncException) -> throwIO ex Nothing -> handler ex tryAll :: MonadBaseControl IO m => m a -> m (Either SomeException a) tryAll action = (Right <$> action) `catchAll` (return . Left) handleAll :: MonadBaseControl IO m => (SomeException -> m a) -> m a -> m a handleAll = flip catchAll throwLeftIO :: Exception e => Either e a -> IO a throwLeftIO = throwLeftExceptionIO id throwLeftExceptionIO :: Exception e => (a -> e) -> Either a b -> IO b throwLeftExceptionIO mkEx e = either (throwIO . mkEx) pure e isSyncException :: Exception e => e -> Bool isSyncException e = case fromException (toException e) of Just (SomeAsyncException _) -> False Nothing -> True isAsyncException :: Exception e => e -> Bool isAsyncException = not . isSyncException tryBracket ^ run first -> IO b tryBracket before after inner = mask $ \restore -> do a <- before r <- restore (inner a) `catch` \ex -> do after a (Left ex) throwIO ex _ <- after a (Right r) return r the first action succeeded or threw an exception . tryFinally ^ run first -> IO a tryFinally inner after = mask $ \restore -> do r <- restore inner `catch` \ex -> do after (Left ex) throwIO ex _ <- after (Right r) return r onSomeException :: HasCallStack => IO a -> (SomeException -> IO ()) -> IO a onSomeException io f = io `catch` \exc -> do withFrozenCallStack $ swallow $ f exc throwIO exc afterwards :: HasCallStack => IO a -> (Either SomeException a -> IO ()) -> IO a afterwards io f = do r <- tryAll io withFrozenCallStack $ swallow $ f r case r of Right result -> return result Left exc -> throwIO exc swallow :: HasCallStack => IO a -> IO () swallow io = void io `catchAll` \exc -> do withFrozenCallStack $ logError $ "swallowing exception: " ++ show exc IO computation . logExceptions :: (String -> String) -> IO a -> IO a logExceptions f io = io `onSomeException` (logError . f . show)
5dae0e1ac9b3c6a4216c045ca9830ca3ea65444306a04c596557a7cb93ec24e3
schell/ixshader
Qualifiers.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # {-# LANGUAGE LambdaCase #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE RebindableSyntax # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - orphans # {-# OPTIONS_GHC -fprint-explicit-kinds #-} module Graphics.IxShader.Qualifiers where import Data.Promotion.Prelude hiding (Const) import Data.Singletons.TypeLits import Prelude hiding (Read, return, (>>), (>>=), log) import Graphics.IxShader.Function import Graphics.IxShader.IxShader import Graphics.IxShader.Types newtype Uniform typ name = Uniform { unUniform :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (Uniform t n) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (Uniform t n) where unSocket = unSocket . unUniform socket = Uniform . socket newtype In typ name = In { unIn :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (In t n) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (In t n) where unSocket = unSocket . unIn socket = In . socket newtype Out typ name = Out { unOut :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (Out t n) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (Out t n) where unSocket = unSocket . unOut socket = Out . socket newtype Const typ = Const { unConst :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (Const t) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (Const t) where unSocket = unSocket . unConst socket = Const . socket newtype InOut typ = InOut { unInOut :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (InOut t) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (InOut t) where unSocket = unSocket . unInOut socket = InOut . socket -- Read and write rules type family ReadFrom a where ReadFrom (Uniform t n) = t ReadFrom (In t n) = t ReadFrom (Out t n) = Error '(Out t n, "Cannot be read.") ReadFrom (InOut t) = t ReadFrom (Const t) = t ReadFrom t = t type family WriteTo a where WriteTo (Uniform t n) = Error '(Uniform t n, "Cannot be written.") WriteTo (In t n) = Error '(In t n, "Cannot be written.") WriteTo (Out t n) = t WriteTo (InOut t) = t WriteTo (Const t) = Error '(Const t, "Cannot be written.") WriteTo t = t class Cast a b where cast :: a -> b instance (Socketed a, Socketed (ReadFrom a), b ~ ReadFrom a) => Cast a b where cast = socket . unSocket type Readable a b = ( Socketed (ReadFrom a), Socketed a, Socketed b , ReadFrom a ~ ReadFrom b ) infixl 6 + (+) :: Readable a b => a -> b -> ReadFrom a (+) = callInfix "+" infixl 6 - (-) :: Readable a b => a -> b -> ReadFrom a (-) = callInfix "-" infixl 7 * (*) :: Readable a b => a -> b -> ReadFrom a (*) = callInfix "*" negate :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a negate a = socket $ concat ["(-", unSocket a, ")"] abs :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a abs = call "abs" signum :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a signum = call "sign" infixl 7 / (/) :: Readable a b => a -> b -> ReadFrom a (/) = callInfix "/" exp :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a exp = call "exp" log :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a log = call "log" sqrt :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a sqrt = call "sqrt" (**):: Readable a b => a -> b -> ReadFrom a (**) = call2 "pow" logBase :: Readable a b => a -> b -> ReadFrom a logBase a b = callInfix "/" (log b) (log a) sin :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a sin = call "sin" cos :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a cos = call "cos" tan :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a tan = call "tan" asin :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a asin = call "asin" acos :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a acos = call "acos" atan :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a atan = call "atan" sinh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a sinh = call "sinh" cosh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a cosh = call "cosh" tanh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a tanh = call "tanh" asinh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a asinh = call "asinh" acosh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a acosh = call "acosh" atanh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a atanh = call "atanh" infix 4 == (==) :: Readable a b => a -> b -> Xbool (==) = callInfix "==" infix 4 /= (/=) :: Readable a b => a -> b -> Xbool (/=) = callInfix "!=" infix 4 < (<) :: Readable a b => a -> b -> Xbool (<) = callInfix "<" infix 4 <= (<=) :: Readable a b => a -> b -> Xbool (<=) = callInfix "<=" infix 4 > (>) :: Readable a b => a -> b -> Xbool (>) = callInfix ">" infix 4 >= (>=) :: Readable a b => a -> b -> Xbool (>=) = callInfix ">=" max :: Readable a b => a -> b -> ReadFrom a max = call2 "max" min :: Readable a b => a -> b -> ReadFrom a min = call2 "min" normalize :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a normalize = call "normalize" dot :: Readable a b => a -> b -> Xfloat dot = call2 "dot" -------------------------------------------------------------------------------- Program - level in / out bindings -------------------------------------------------------------------------------- class Binding a t where getVertexBinding :: t getUniformBinding :: t instance KnownSymbol b => Binding (Uniform a b) (Maybe String) where getVertexBinding = Nothing getUniformBinding = Just $ symbolVal $ Proxy @b instance KnownSymbol b => Binding (In a b) (Maybe String) where getVertexBinding = Just $ symbolVal $ Proxy @b getUniformBinding = Nothing instance Binding (Out a b) (Maybe String) where getVertexBinding = Nothing getUniformBinding = Nothing instance Binding (Function a b c) (Maybe String) where getVertexBinding = Nothing getUniformBinding = Nothing instance Binding '[] [t] where getVertexBinding = [] getUniformBinding = [] instance (Binding a t, Binding as [t]) => Binding (a ': as) [t] where getVertexBinding = getVertexBinding @a : getVertexBinding @as getUniformBinding = getUniformBinding @a : getUniformBinding @as -- | An easy way to get the term level value of a type of kind 'GLContext'. class HasContext (a :: GLContext) where getCtx :: GLContext instance HasContext 'OpenGLContext where getCtx = OpenGLContext instance HasContext 'WebGLContext where getCtx = WebGLContext -- | An easy way to get the term level value of a type of kind 'ShaderType'. class HasShaderType (a :: ShaderType) where getShaderType :: ShaderType instance HasShaderType 'VertexShader where getShaderType = VertexShader instance HasShaderType 'FragmentShader where getShaderType = FragmentShader uniform_ :: forall t name ts ctx shadertype. (KnownSymbol name, Socketed t, KnownTypeSymbol t) => IxShader shadertype ctx ts (ts :++ '[Uniform t name]) (Uniform t name) uniform_ = acc decls u u where u = socket $ symbolVal $ Proxy @name decls = unwords ["uniform", toDefinition u, ";"] in_ :: forall t name ts ctx shadertype. (HasContext ctx, HasShaderType shadertype, KnownSymbol name, Socketed t, KnownTypeSymbol t) => IxShader shadertype ctx ts (ts :++ '[In t name]) (In t name) in_ = acc decls i i where i = socket $ symbolVal $ Proxy @name dec = case (getCtx @ctx, getShaderType @shadertype) of (OpenGLContext, _) -> "in" (WebGLContext, VertexShader) -> "attribute" (WebGLContext, FragmentShader) -> "varying" decls = unwords [dec, toDefinition i, ";"] out_ :: forall t name ts ctx shadertype. (HasContext ctx, KnownSymbol name, Socketed t, KnownTypeSymbol t) => IxShader shadertype ctx ts (ts :++ '[Out t name]) (Out t name) out_ = acc decls o o where o = socket $ symbolVal $ Proxy @name dec = case getCtx @ctx of OpenGLContext -> "out" WebGLContext -> "varying" decls = unwords [dec, toDefinition o, ";"] gl_Position :: forall ts ctx. IxVertex ctx ts (ts :++ '[Out Xvec4 "gl_Position"]) (Out Xvec4 "gl_Position") gl_Position = acc [] o o where o = socket "gl_Position" type family GLFragName (a :: GLContext) where GLFragName 'OpenGLContext = "fragColor" GLFragName 'WebGLContext = "gl_FragColor" gl_FragColor :: forall ctx ts. (HasContext ctx, KnownSymbol (GLFragName ctx)) => IxFragment ctx ts (ts :++ '[Out Xvec4 (GLFragName ctx)]) (Out Xvec4 (GLFragName ctx)) gl_FragColor = acc decls o o where o = socket $ symbolVal $ Proxy @(GLFragName ctx) decls = case getCtx @ctx of OpenGLContext -> unwords ["out", toDefinition o, ";"] _ -> [] gl_FragCoord :: Xvec4 gl_FragCoord = Xvec4 "gl_FragCoord"
null
https://raw.githubusercontent.com/schell/ixshader/66e5302fa24bbdc7c948a79ee2422cae688b982f/src/Graphics/IxShader/Qualifiers.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeInType # # LANGUAGE TypeOperators # # OPTIONS_GHC -fprint-explicit-kinds # Read and write rules ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | An easy way to get the term level value of a type of kind 'GLContext'. | An easy way to get the term level value of a type of kind 'ShaderType'.
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE PolyKinds # # LANGUAGE RebindableSyntax # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - missing - signatures # # OPTIONS_GHC -fno - warn - orphans # module Graphics.IxShader.Qualifiers where import Data.Promotion.Prelude hiding (Const) import Data.Singletons.TypeLits import Prelude hiding (Read, return, (>>), (>>=), log) import Graphics.IxShader.Function import Graphics.IxShader.IxShader import Graphics.IxShader.Types newtype Uniform typ name = Uniform { unUniform :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (Uniform t n) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (Uniform t n) where unSocket = unSocket . unUniform socket = Uniform . socket newtype In typ name = In { unIn :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (In t n) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (In t n) where unSocket = unSocket . unIn socket = In . socket newtype Out typ name = Out { unOut :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (Out t n) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (Out t n) where unSocket = unSocket . unOut socket = Out . socket newtype Const typ = Const { unConst :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (Const t) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (Const t) where unSocket = unSocket . unConst socket = Const . socket newtype InOut typ = InOut { unInOut :: typ } instance KnownTypeSymbol t => KnownTypeSymbol (InOut t) where typeSymbolVal _ = typeSymbolVal $ Proxy @t instance Socketed t => Socketed (InOut t) where unSocket = unSocket . unInOut socket = InOut . socket type family ReadFrom a where ReadFrom (Uniform t n) = t ReadFrom (In t n) = t ReadFrom (Out t n) = Error '(Out t n, "Cannot be read.") ReadFrom (InOut t) = t ReadFrom (Const t) = t ReadFrom t = t type family WriteTo a where WriteTo (Uniform t n) = Error '(Uniform t n, "Cannot be written.") WriteTo (In t n) = Error '(In t n, "Cannot be written.") WriteTo (Out t n) = t WriteTo (InOut t) = t WriteTo (Const t) = Error '(Const t, "Cannot be written.") WriteTo t = t class Cast a b where cast :: a -> b instance (Socketed a, Socketed (ReadFrom a), b ~ ReadFrom a) => Cast a b where cast = socket . unSocket type Readable a b = ( Socketed (ReadFrom a), Socketed a, Socketed b , ReadFrom a ~ ReadFrom b ) infixl 6 + (+) :: Readable a b => a -> b -> ReadFrom a (+) = callInfix "+" infixl 6 - (-) :: Readable a b => a -> b -> ReadFrom a (-) = callInfix "-" infixl 7 * (*) :: Readable a b => a -> b -> ReadFrom a (*) = callInfix "*" negate :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a negate a = socket $ concat ["(-", unSocket a, ")"] abs :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a abs = call "abs" signum :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a signum = call "sign" infixl 7 / (/) :: Readable a b => a -> b -> ReadFrom a (/) = callInfix "/" exp :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a exp = call "exp" log :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a log = call "log" sqrt :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a sqrt = call "sqrt" (**):: Readable a b => a -> b -> ReadFrom a (**) = call2 "pow" logBase :: Readable a b => a -> b -> ReadFrom a logBase a b = callInfix "/" (log b) (log a) sin :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a sin = call "sin" cos :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a cos = call "cos" tan :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a tan = call "tan" asin :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a asin = call "asin" acos :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a acos = call "acos" atan :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a atan = call "atan" sinh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a sinh = call "sinh" cosh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a cosh = call "cosh" tanh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a tanh = call "tanh" asinh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a asinh = call "asinh" acosh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a acosh = call "acosh" atanh :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a atanh = call "atanh" infix 4 == (==) :: Readable a b => a -> b -> Xbool (==) = callInfix "==" infix 4 /= (/=) :: Readable a b => a -> b -> Xbool (/=) = callInfix "!=" infix 4 < (<) :: Readable a b => a -> b -> Xbool (<) = callInfix "<" infix 4 <= (<=) :: Readable a b => a -> b -> Xbool (<=) = callInfix "<=" infix 4 > (>) :: Readable a b => a -> b -> Xbool (>) = callInfix ">" infix 4 >= (>=) :: Readable a b => a -> b -> Xbool (>=) = callInfix ">=" max :: Readable a b => a -> b -> ReadFrom a max = call2 "max" min :: Readable a b => a -> b -> ReadFrom a min = call2 "min" normalize :: (Socketed a, Socketed (ReadFrom a)) => a -> ReadFrom a normalize = call "normalize" dot :: Readable a b => a -> b -> Xfloat dot = call2 "dot" Program - level in / out bindings class Binding a t where getVertexBinding :: t getUniformBinding :: t instance KnownSymbol b => Binding (Uniform a b) (Maybe String) where getVertexBinding = Nothing getUniformBinding = Just $ symbolVal $ Proxy @b instance KnownSymbol b => Binding (In a b) (Maybe String) where getVertexBinding = Just $ symbolVal $ Proxy @b getUniformBinding = Nothing instance Binding (Out a b) (Maybe String) where getVertexBinding = Nothing getUniformBinding = Nothing instance Binding (Function a b c) (Maybe String) where getVertexBinding = Nothing getUniformBinding = Nothing instance Binding '[] [t] where getVertexBinding = [] getUniformBinding = [] instance (Binding a t, Binding as [t]) => Binding (a ': as) [t] where getVertexBinding = getVertexBinding @a : getVertexBinding @as getUniformBinding = getUniformBinding @a : getUniformBinding @as class HasContext (a :: GLContext) where getCtx :: GLContext instance HasContext 'OpenGLContext where getCtx = OpenGLContext instance HasContext 'WebGLContext where getCtx = WebGLContext class HasShaderType (a :: ShaderType) where getShaderType :: ShaderType instance HasShaderType 'VertexShader where getShaderType = VertexShader instance HasShaderType 'FragmentShader where getShaderType = FragmentShader uniform_ :: forall t name ts ctx shadertype. (KnownSymbol name, Socketed t, KnownTypeSymbol t) => IxShader shadertype ctx ts (ts :++ '[Uniform t name]) (Uniform t name) uniform_ = acc decls u u where u = socket $ symbolVal $ Proxy @name decls = unwords ["uniform", toDefinition u, ";"] in_ :: forall t name ts ctx shadertype. (HasContext ctx, HasShaderType shadertype, KnownSymbol name, Socketed t, KnownTypeSymbol t) => IxShader shadertype ctx ts (ts :++ '[In t name]) (In t name) in_ = acc decls i i where i = socket $ symbolVal $ Proxy @name dec = case (getCtx @ctx, getShaderType @shadertype) of (OpenGLContext, _) -> "in" (WebGLContext, VertexShader) -> "attribute" (WebGLContext, FragmentShader) -> "varying" decls = unwords [dec, toDefinition i, ";"] out_ :: forall t name ts ctx shadertype. (HasContext ctx, KnownSymbol name, Socketed t, KnownTypeSymbol t) => IxShader shadertype ctx ts (ts :++ '[Out t name]) (Out t name) out_ = acc decls o o where o = socket $ symbolVal $ Proxy @name dec = case getCtx @ctx of OpenGLContext -> "out" WebGLContext -> "varying" decls = unwords [dec, toDefinition o, ";"] gl_Position :: forall ts ctx. IxVertex ctx ts (ts :++ '[Out Xvec4 "gl_Position"]) (Out Xvec4 "gl_Position") gl_Position = acc [] o o where o = socket "gl_Position" type family GLFragName (a :: GLContext) where GLFragName 'OpenGLContext = "fragColor" GLFragName 'WebGLContext = "gl_FragColor" gl_FragColor :: forall ctx ts. (HasContext ctx, KnownSymbol (GLFragName ctx)) => IxFragment ctx ts (ts :++ '[Out Xvec4 (GLFragName ctx)]) (Out Xvec4 (GLFragName ctx)) gl_FragColor = acc decls o o where o = socket $ symbolVal $ Proxy @(GLFragName ctx) decls = case getCtx @ctx of OpenGLContext -> unwords ["out", toDefinition o, ";"] _ -> [] gl_FragCoord :: Xvec4 gl_FragCoord = Xvec4 "gl_FragCoord"
679d173536b55be6ea5751cbf08da7f8e9f05f725ca4f0fac7dd20a08cbbc88f
chovencorp/erlangzmq
erlangzmq_bind.erl
@copyright 2016 Choven Corp. %% This file is part of erlangzmq . %% erlangzmq is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or %% (at your option) any later version. %% %% erlangzmq is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty of %% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %% GNU Affero General Public License for more details. %% You should have received a copy of the GNU Affero General Public License along with erlangzmq . If not , see < / > %% @doc ZeroMQ Listener for new connections. -module(erlangzmq_bind). -include("erlangzmq.hrl"). -export([start_link/2, listener/2]). -spec start_link(Host::string(), Port::number()) -> {ok, BindPid::pid()} | {error, Reason::term()}. start_link(Host, Port) -> ParentPid = self(), case inet:getaddr(Host, inet) of {ok, Addr} -> case gen_tcp:listen(Port, ?SOCKET_OPTS([{ip, Addr}])) of {ok, ListenSocket} -> Pid = spawn_link(?MODULE, listener, [ListenSocket, ParentPid]), {ok, Pid}; {error, Reason} -> error_logger:error_report([ bind_error, {host, Host}, {addr, Addr}, {port, Port}, listen_error, {error, Reason} ]), {error, Reason} end; {error, IpReason} -> error_logger:error_report([ bind_error, {host, Host}, getaddr_error, {error, IpReason} ]), {error, IpReason} end. listener(ListenSocket, ParentPid) -> try {ok, Socket} = gen_tcp:accept(ListenSocket), {ok, PeerPid} = gen_server:call(ParentPid, {accept, Socket}), ok = gen_tcp:controlling_process(Socket, PeerPid), %% Start to negociate greetings after new process is owner gen_server:cast(PeerPid, negotiate_greetings), listener(ListenSocket, ParentPid) catch error:{badmatch, {error, closed}} -> error_logger:info_report({bind_closed}); error:{badmatch, Error} -> error_logger:error_report([ accept_error, {error, Error} ]), listener(ListenSocket, ParentPid) end.
null
https://raw.githubusercontent.com/chovencorp/erlangzmq/2be5c3b36dd78b010d1790a8f74ae2e823f5a424/src/erlangzmq_bind.erl
erlang
(at your option) any later version. erlangzmq is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. @doc ZeroMQ Listener for new connections. Start to negociate greetings after new process is owner
@copyright 2016 Choven Corp. This file is part of erlangzmq . erlangzmq is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU Affero General Public License along with erlangzmq . If not , see < / > -module(erlangzmq_bind). -include("erlangzmq.hrl"). -export([start_link/2, listener/2]). -spec start_link(Host::string(), Port::number()) -> {ok, BindPid::pid()} | {error, Reason::term()}. start_link(Host, Port) -> ParentPid = self(), case inet:getaddr(Host, inet) of {ok, Addr} -> case gen_tcp:listen(Port, ?SOCKET_OPTS([{ip, Addr}])) of {ok, ListenSocket} -> Pid = spawn_link(?MODULE, listener, [ListenSocket, ParentPid]), {ok, Pid}; {error, Reason} -> error_logger:error_report([ bind_error, {host, Host}, {addr, Addr}, {port, Port}, listen_error, {error, Reason} ]), {error, Reason} end; {error, IpReason} -> error_logger:error_report([ bind_error, {host, Host}, getaddr_error, {error, IpReason} ]), {error, IpReason} end. listener(ListenSocket, ParentPid) -> try {ok, Socket} = gen_tcp:accept(ListenSocket), {ok, PeerPid} = gen_server:call(ParentPid, {accept, Socket}), ok = gen_tcp:controlling_process(Socket, PeerPid), gen_server:cast(PeerPid, negotiate_greetings), listener(ListenSocket, ParentPid) catch error:{badmatch, {error, closed}} -> error_logger:info_report({bind_closed}); error:{badmatch, Error} -> error_logger:error_report([ accept_error, {error, Error} ]), listener(ListenSocket, ParentPid) end.
994e0d0676c55b7242cf6e1a8ab2bec8c0786362d3ffae99ffa5efda235ec2c2
con-kitty/categorifier
Integration.hs
# LANGUAGE ApplicativeDo # # LANGUAGE MagicHash # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} {-# LANGUAGE TemplateHaskellQuotes #-} # LANGUAGE TupleSections # # LANGUAGE ViewPatterns # module Categorifier.LinearBase.Integration ( makerMapFun, symbolLookup, ) where import Categorifier.Core.MakerMap ( MakerMapFun, SymbolLookup (..), applyEnrichedCat, applyEnrichedCat', composeCat, curryCat, forkCat, handleAdditionalArgs, makeMaker1, makeMaker2, makeTupleTyWithVar, uncurryCat, ) import Categorifier.Core.Makers (Makers (..)) import Categorifier.Core.Types (Lookup) import Categorifier.Duoidal (joinD, (<*\>), (<=\<), (=<\<)) import qualified Categorifier.GHC.Builtin as Plugins import qualified Categorifier.GHC.Core as Plugins import Categorifier.Hierarchy (findTyCon) import qualified Control.Functor.Linear import qualified Data.Array.Mutable.Linear import qualified Data.Array.Mutable.Unlifted.Linear import qualified Data.Bool.Linear import qualified Data.Either.Linear import qualified Data.Functor.Linear import qualified Data.List.Linear import qualified Data.Map as Map import Data.Maybe (fromMaybe) import qualified Data.Monoid.Linear import qualified Data.Num.Linear import qualified Data.Ord.Linear import qualified Data.Replicator.Linear import qualified Data.Tuple.Linear import qualified Data.V.Linear import qualified Prelude.Linear import qualified Streaming.Prelude.Linear import qualified Unsafe.Linear These instances are pushed upstream in -base/pull/416 and should be in any release of linear - base > 0.2.0 | @linear - base@ does n't export ` MovableOrd ` , so we redefine it and its instances here to use in -- @newtype@-derived instances. newtype MovableOrd a = MovableOrd a instance (Eq a, Prelude.Linear.Movable a) => Data.Ord.Linear.Eq (MovableOrd a) where MovableOrd ar == MovableOrd br = Prelude.Linear.move (ar, br) Prelude.Linear.& \(Prelude.Linear.Ur (a, b)) -> a == b MovableOrd ar /= MovableOrd br = Prelude.Linear.move (ar, br) Prelude.Linear.& \(Prelude.Linear.Ur (a, b)) -> a /= b instance (Prelude.Ord a, Prelude.Linear.Movable a) => Data.Ord.Linear.Ord (MovableOrd a) where MovableOrd ar `compare` MovableOrd br = Prelude.Linear.move (ar, br) Prelude.Linear.& \(Prelude.Linear.Ur (a, b)) -> a `Prelude.compare` b deriving via MovableOrd Int16 instance Data.Ord.Linear.Eq Int16 deriving via MovableOrd Int32 instance Data.Ord.Linear.Eq Int32 deriving via MovableOrd Int64 instance Data.Ord.Linear.Eq Int64 deriving via MovableOrd Int8 instance Data.Ord.Linear.Eq Int8 deriving via MovableOrd Word16 instance Data.Ord.Linear.Eq Word16 deriving via MovableOrd Word32 instance Data.Ord.Linear.Eq Word32 deriving via MovableOrd Word64 instance Data.Ord.Linear.Eq Word64 deriving via MovableOrd Word8 instance Data.Ord.Linear.Eq Word8 deriving via MovableOrd Int16 instance Data.Ord.Linear.Ord Int16 deriving via MovableOrd Int32 instance Data.Ord.Linear.Ord Int32 deriving via MovableOrd Int64 instance Data.Ord.Linear.Ord Int64 deriving via MovableOrd Int8 instance Data.Ord.Linear.Ord Int8 deriving via MovableOrd Word16 instance Data.Ord.Linear.Ord Word16 deriving via MovableOrd Word32 instance Data.Ord.Linear.Ord Word32 deriving via MovableOrd Word64 instance Data.Ord.Linear.Ord Word64 deriving via MovableOrd Word8 instance Data.Ord.Linear.Ord Word8 deriving instance Show (Data.V.Linear.V n a) deriving instance Foldable (Data.V.Linear.V n) deriving instance KnownNat n => Traversable (Data.V.Linear.V n) instance KnownNat n => Applicative (Data.V.Linear.V n) where pure = Data.Functor.Linear.pure Data.V.Linear.Internal.V fs <*> Data.V.Linear.Internal.V xs = Data.V.Linear.Internal.V $ Vector.zipWith (\f x -> f $ x) fs xs symbolLookup :: Lookup SymbolLookup symbolLookup = do array <- findTyCon "Data.Array.Mutable.Linear" "Array" arrayUnlifted <- findTyCon "Data.Array.Mutable.Unlifted.Linear" "Array#" replicator <- findTyCon "Data.Replicator.Linear" "Replicator" v <- findTyCon "Data.V.Linear" "V" stream <- findTyCon "Streaming.Prelude.Linear" "Stream" pure $ SymbolLookup ( Map.fromList [ (''Data.Array.Mutable.Linear.Array, array), (''Data.Array.Mutable.Unlifted.Linear.Array#, arrayUnlifted), (''Data.Replicator.Linear.Replicator, replicator), (''Data.V.Linear.V, v), (''Streaming.Prelude.Linear.Stream, stream) ] ) mempty makerMapFun :: MakerMapFun makerMapFun symLookup _dflags _logger m@Makers {..} n _target expr _cat _var _args _modu _categorifyFun categorifyLambda = makerMap where makerMap = Map.fromListWith const [ ( '(Control.Functor.Linear.<$>), \case f : a : b : functor : rest -> ($ (f : functor : a : b : rest)) =<< Map.lookup 'Control.Functor.Linear.fmap makerMap _ -> Nothing ), ( '(Control.Functor.Linear.<*>), \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : rest -> pure $ maker2 rest =<\< mkAp f a b _ -> Nothing ), ( '(Control.Functor.Linear.>>=), \case Plugins.Type mty : _monad : Plugins.Type a : Plugins.Type b : rest -> pure $ maker2 rest =<\< mkBind mty a b _ -> Nothing ), ( 'Control.Functor.Linear.ap, \case mty : a : b : monad : rest -> ($ (mty : monad : a : b : rest)) =<< Map.lookup '(Control.Functor.Linear.<*>) makerMap _ -> Nothing ), ( 'Control.Functor.Linear.fmap, \case Plugins.Type f : _functor : Plugins.Type a : Plugins.Type b : u : rest -> pure $ mkMap' f a b u rest _ -> Nothing ), ( 'Control.Functor.Linear.liftA2, \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : Plugins.Type c : u : rest -> pure $ mkLiftA2' f a b c u rest _ -> Nothing ), ( 'Control.Functor.Linear.pure, \case Plugins.Type f : _applicative : Plugins.Type a : rest -> pure $ maker1 rest =<\< mkPoint f a _ -> Nothing ), ( 'Control.Functor.Linear.return, \case mty : a : monad : rest -> ($ mty : monad : a : rest) =<< Map.lookup 'Control.Functor.Linear.pure makerMap _ -> Nothing ), ( 'Data.Array.Mutable.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> do array <- Map.lookup ''Data.Array.Mutable.Linear.Array (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConTy array) a b u rest _ -> Nothing ), ( 'Data.Array.Mutable.Unlifted.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> do array <- Map.lookup ''Data.Array.Mutable.Unlifted.Linear.Array# (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConTy array) a b u rest _ -> Nothing ), ('(Data.Bool.Linear.&&), \rest -> pure $ maker2 rest =<\< mkAnd), ('(Data.Bool.Linear.||), \rest -> pure $ maker2 rest =<\< mkOr), ('Data.Bool.Linear.not, \rest -> pure $ maker1 rest =<\< mkNot), ( 'Data.Either.Linear.either, \case Plugins.Type a1 : Plugins.Type b : Plugins.Type a2 : u : v : rest -> As in § 8 : ( λx → U ▽ V ) ≡ curry ( ( uncurry ( λx → U ) ▽ uncurry ( λx → V ) ) ◦ distl ) pure . joinD $ applyEnriched' [u, v] rest <$> mkJoin (nameTuple a1) (nameTuple a2) b <*\> mkDistl (Plugins.varType n) a1 a2 _ -> Nothing ), ( '(Data.Functor.Linear.<*>), \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : rest -> pure $ maker2 rest =<\< mkAp f a b _ -> Nothing ), ( '(Data.Functor.Linear.<$>), \case f : a : b : functor : rest -> ($ (f : functor : a : b : rest)) =<< Map.lookup 'Data.Functor.Linear.fmap makerMap _ -> Nothing ), ( 'Data.Functor.Linear.fmap, \case Plugins.Type f : _functor : Plugins.Type a : Plugins.Type b : u : rest -> pure $ mkMap' f a b u rest _ -> Nothing ), ( 'Data.Functor.Linear.liftA2, \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : Plugins.Type c : u : rest -> pure $ mkLiftA2' f a b c u rest _ -> Nothing ), ( 'Data.Functor.Linear.pure, \case Plugins.Type f : _applicative : Plugins.Type a : rest -> pure $ maker1 rest =<\< mkPoint f a _ -> Nothing ), ( 'Data.Functor.Linear.sequence, \case Plugins.Type t : _traversable : Plugins.Type f : Plugins.Type a : _applicative : rest -> pure $ maker1 rest =<\< mkSequenceA t f a _ -> Nothing ), ( 'Data.Functor.Linear.sequenceA, \case Plugins.Type t : Plugins.Type f : Plugins.Type a : _traversable : _applicative : rest -> pure $ maker1 rest =<\< mkSequenceA t f a _ -> Nothing ), ( 'Data.Functor.Linear.traverse, \case Plugins.Type t : _traversable : Plugins.Type f : Plugins.Type a : Plugins.Type b : _applicative : u : rest -> pure . joinD $ applyEnriched' [u] rest <$> mkTraverse t f (nameTuple a) b <*\> mkStrength t (Plugins.varType n) a _ -> Nothing ), ( '(Data.List.Linear.++), \case Plugins.Type a : rest -> pure $ maker2 rest <=\< mkAppend $ Plugins.mkTyConApp Plugins.listTyCon [a] _ -> Nothing ), ( 'Data.List.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> pure $ mkMap' (Plugins.mkTyConTy Plugins.listTyCon) a b u rest _ -> Nothing ), ( 'Data.List.Linear.sum, \case Plugins.Type a : _num : rest -> pure $ maker1 rest =<\< mkSum (Plugins.mkTyConTy Plugins.listTyCon) a _ -> Nothing ), ( 'Data.List.Linear.traverse', \case Plugins.Type f : Plugins.Type a : Plugins.Type b : _applicative : u : rest -> let list = Plugins.mkTyConTy Plugins.listTyCon in pure . joinD $ applyEnriched' [u] rest <$> mkTraverse list f (nameTuple a) b <*\> mkStrength list (Plugins.varType n) a _ -> Nothing ), ( '(Data.Monoid.Linear.<>), \case Plugins.Type a : _semigroup : rest -> pure $ maker2 rest =<\< mkAppend a _ -> Nothing ), ( 'Data.Monoid.Linear.mappend, fromMaybe (const Nothing) $ Map.lookup '(Data.Monoid.Linear.<>) makerMap ), ( '(Data.Num.Linear.+), \case Plugins.Type ty : _additive : rest -> pure $ maker2 rest =<\< mkPlus ty _ -> Nothing ), TODO : Catch cases on Natural / Word to turn into Monus ( '(Data.Num.Linear.-), \case Plugins.Type ty : _additive : rest -> pure $ maker2 rest =<\< mkMinus ty _ -> Nothing ), ( '(Data.Num.Linear.*), \case Plugins.Type ty : _multiplicative : rest -> pure $ maker2 rest =<\< mkTimes ty _ -> Nothing ), ( 'Data.Num.Linear.abs, \case Plugins.Type ty : _num : rest -> pure $ maker1 rest =<\< mkAbs ty _ -> Nothing ), ( 'Data.Num.Linear.fromInteger, \case Plugins.Type ty : _fromInteger : rest -> pure $ maker1 rest =<\< mkFromInteger ty _ -> Nothing ), ( 'Data.Num.Linear.negate, \case Plugins.Type ty : _additive : rest -> pure $ maker1 rest =<\< mkNegate ty _ -> Nothing ), ( 'Data.Num.Linear.signum, \case Plugins.Type ty : _num : rest -> pure $ maker1 rest =<\< mkSignum ty _ -> Nothing ), ( '(Data.Ord.Linear.==), \case Plugins.Type ty : _eq : rest -> pure $ maker2 rest =<\< mkEqual ty _ -> Nothing ), ( '(Data.Ord.Linear./=), \case Plugins.Type ty : _eq : rest -> pure $ maker2 rest =<\< mkNotEqual ty _ -> Nothing ), ( '(Data.Ord.Linear.<), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkLT ty _ -> Nothing ), ( '(Data.Ord.Linear.<=), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkLE ty _ -> Nothing ), ( '(Data.Ord.Linear.>), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkGT ty _ -> Nothing ), ( '(Data.Ord.Linear.>=), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkGE ty _ -> Nothing ), ( 'Data.Ord.Linear.compare, \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkCompare ty _ -> Nothing ), ( 'Data.Ord.Linear.max, \case Plugins.Type ty : _dupable : _ord : rest -> pure $ maker2 rest =<\< mkMax ty _ -> Nothing ), ( 'Data.Ord.Linear.min, \case Plugins.Type ty : _dupable : _ord : rest -> pure $ maker2 rest =<\< mkMin ty _ -> Nothing ), ( '(Data.Replicator.Linear.<*>), \case Plugins.Type a : Plugins.Type b : rest -> do replicator <- Map.lookup ''Data.Replicator.Linear.Replicator (tyConLookup symLookup) pure $ maker2 rest =<\< mkAp (Plugins.mkTyConTy replicator) a b _ -> Nothing ), ( 'Data.Replicator.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> do replicator <- Map.lookup ''Data.Replicator.Linear.Replicator (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConTy replicator) a b u rest _ -> Nothing ), ( 'Data.Replicator.Linear.pure, \case Plugins.Type a : rest -> do replicator <- Map.lookup ''Data.Replicator.Linear.Replicator (tyConLookup symLookup) pure $ maker1 rest =<\< mkPoint (Plugins.mkTyConTy replicator) a _ -> Nothing ), ( 'Data.Tuple.Linear.curry, \case Plugins.Type a1 : Plugins.Type a2 : Plugins.Type b : Plugins.Type _q : Plugins.Type _q' : u : rest -> -- from: (\n -> curry {{u}}) :: n -> a1 -> a2 -> b -- to: curry (curry (uncurry (categorify n {{u}}) . assoc)) -- :: n `k` (a1 -> a2 -> b) pure . joinD $ applyEnriched rest <$> mkCurry (nameTuple a1) a2 b <*\> mkId (nameTuple a1) <*\> sequenceA [ joinD $ composeCat m <$> (uncurryCat m =<\< categorifyLambda u) <*\> mkRAssoc (Plugins.varType n) a1 a2 ] _ -> Nothing ), ( 'Data.Tuple.Linear.fst, \case Plugins.Type fTy : Plugins.Type sTy : _consumable : rest -> pure $ maker1 rest =<\< mkExl fTy sTy _ -> Nothing ), ( 'Data.Tuple.Linear.snd, \case Plugins.Type fTy : Plugins.Type sTy : _consumable : rest -> pure $ maker1 rest =<\< mkExr fTy sTy _ -> Nothing ), ( 'Data.Tuple.Linear.swap, \case Plugins.Type a : Plugins.Type b : rest -> pure $ maker1 rest =<\< mkSwap a b _ -> Nothing ), ( 'Data.Tuple.Linear.uncurry, \case Plugins.Type a1 : Plugins.Type a2 : Plugins.Type b : Plugins.Type _q : Plugins.Type _q' : u : rest -> -- from: (\n -> uncurry {{u}}) :: n -> (a1, a2) -> b -- to: curry (uncurry (uncurry (categorify n {{u}})) . unassoc) -- :: n `k` ((a1, a2) -> b) pure . joinD $ applyEnriched' [u] rest <$> mkUncurry (nameTuple a1) a2 b <*\> mkLAssoc (Plugins.varType n) a1 a2 _ -> Nothing ), ( '(Data.V.Linear.<*>), \case Plugins.Type n' : Plugins.Type a : Plugins.Type b : rest -> do v <- Map.lookup ''Data.V.Linear.V (tyConLookup symLookup) pure $ maker2 rest =<\< mkAp (Plugins.mkTyConApp v [n']) a b _ -> Nothing ), ( 'Data.V.Linear.map, \case Plugins.Type a : Plugins.Type b : Plugins.Type n' : u : rest -> do v <- Map.lookup ''Data.V.Linear.V (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConApp v [n']) a b u rest _ -> Nothing ), ( 'Data.V.Linear.pure, \case Plugins.Type n' : Plugins.Type a : _knownNat : rest -> do v <- Map.lookup ''Data.V.Linear.V (tyConLookup symLookup) pure $ maker1 rest =<\< mkPoint (Plugins.mkTyConApp v [n']) a _ -> Nothing ), ( '(Prelude.Linear.$), \case Plugins.Type _rep : Plugins.Type a : Plugins.Type b : Plugins.Type _q : Plugins.Type _q' : rest -> pure $ maker2 rest =<\< mkApply a b _ -> Nothing ), ( '(Prelude.Linear..), \case Plugins.Type _rep : Plugins.Type b : Plugins.Type c : Plugins.Type a : Plugins.Type _q : Plugins.Type _q' : Plugins.Type _q'' : f : g : rest -> pure $ case mkCompose2 of Nothing -> -- from: (\n -> {{u}} . {{v}}) :: n -> a -> c -- to: curry -- (compose -- (uncurry (categorify n {{u}})) ( exl & & & uncurry ( categorify n { { v } } ) ) ) -- :: n `k` (a -> c) joinD $ applyEnriched rest <$> mkCompose (nameTuple a) (nameTuple b) c <*\> mkId (nameTuple a) <*\> sequenceA [ uncurryCat m =<\< categorifyLambda f, joinD $ forkCat m <$> mkExl (Plugins.varType n) a <*\> (uncurryCat m =<\< categorifyLambda g) ] Just fn -> handleExtraArgs rest =<\< joinD ( fn (Plugins.varType n) b c a <$> categorifyLambda f <*\> categorifyLambda g ) _ -> Nothing ), ( 'Prelude.Linear.const, \case Plugins.Type _b : Plugins.Type a : Plugins.Type _q : u : rest -> _ _ NB _ _ : this does n't use ` applyEnriched ` because @u@ is n't a function . -- -- from: (\n -> const {{u}}) :: n -> a -> b to : curry ( categorify n { { u } } . ) : : n ` k ` ( a - > b ) pure $ handleExtraArgs rest <=\< curryCat m <=\< joinD $ composeCat m <$> categorifyLambda u <*\> mkExl (Plugins.varType n) a _ -> Nothing ), ( 'Prelude.Linear.id, \case Plugins.Type ty : Plugins.Type _q : rest -> pure $ maker1 rest =<\< mkId ty _ -> Nothing ), ( 'Unsafe.Linear.coerce, \case Plugins.Type from : Plugins.Type to : rest -> pure $ maker1 rest =<\< mkCoerce from to _ -> Nothing ) ] maker1 = makeMaker1 m categorifyLambda maker2 = makeMaker2 m categorifyLambda expr handleExtraArgs = handleAdditionalArgs m categorifyLambda -- from: (\n -> liftA2 {{u}}) :: n -> f a -> f b -> f c -- to: curry (curry (liftA2 (uncurry (uncurry (categorify n {{u}})))) . strength) :: -- n `k` (f a -> f b -> f c) mkLiftA2' f a b c u rest = handleExtraArgs rest =<\< curryCat m =<\< joinD ( composeCat m <$> ( curryCat m =<\< ( Plugins.App <$> mkLiftA2 f (nameTuple a) b c <*\> ( uncurryCat m =<\< uncurryCat m =<\< categorifyLambda u ) ) ) <*\> mkStrength f (Plugins.varType n) a ) -- from: (\n -> fmap {{u}}) :: n -> f a -> f b -- to: curry (fmap (uncurry (categorifyLambda n {{u}})) . strength) :: -- n `k` (f a -> f b) mkMap' f a b u rest = joinD $ applyEnriched' [u] rest <$> mkMap f (nameTuple a) b <*\> mkStrength f (Plugins.varType n) a applyEnriched = applyEnrichedCat m categorifyLambda applyEnriched' = applyEnrichedCat' m categorifyLambda nameTuple = makeTupleTyWithVar n
null
https://raw.githubusercontent.com/con-kitty/categorifier/d8dc1106c4600c2168889519d2c3f843db2e9410/integrations/linear-base/integration/Categorifier/LinearBase/Integration.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # # LANGUAGE TemplateHaskellQuotes # @newtype@-derived instances. from: (\n -> curry {{u}}) :: n -> a1 -> a2 -> b to: curry (curry (uncurry (categorify n {{u}}) . assoc)) :: n `k` (a1 -> a2 -> b) from: (\n -> uncurry {{u}}) :: n -> (a1, a2) -> b to: curry (uncurry (uncurry (categorify n {{u}})) . unassoc) :: n `k` ((a1, a2) -> b) from: (\n -> {{u}} . {{v}}) :: n -> a -> c to: curry (compose (uncurry (categorify n {{u}})) :: n `k` (a -> c) from: (\n -> const {{u}}) :: n -> a -> b from: (\n -> liftA2 {{u}}) :: n -> f a -> f b -> f c to: curry (curry (liftA2 (uncurry (uncurry (categorify n {{u}})))) . strength) :: n `k` (f a -> f b -> f c) from: (\n -> fmap {{u}}) :: n -> f a -> f b to: curry (fmap (uncurry (categorifyLambda n {{u}})) . strength) :: n `k` (f a -> f b)
# LANGUAGE ApplicativeDo # # LANGUAGE MagicHash # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TupleSections # # LANGUAGE ViewPatterns # module Categorifier.LinearBase.Integration ( makerMapFun, symbolLookup, ) where import Categorifier.Core.MakerMap ( MakerMapFun, SymbolLookup (..), applyEnrichedCat, applyEnrichedCat', composeCat, curryCat, forkCat, handleAdditionalArgs, makeMaker1, makeMaker2, makeTupleTyWithVar, uncurryCat, ) import Categorifier.Core.Makers (Makers (..)) import Categorifier.Core.Types (Lookup) import Categorifier.Duoidal (joinD, (<*\>), (<=\<), (=<\<)) import qualified Categorifier.GHC.Builtin as Plugins import qualified Categorifier.GHC.Core as Plugins import Categorifier.Hierarchy (findTyCon) import qualified Control.Functor.Linear import qualified Data.Array.Mutable.Linear import qualified Data.Array.Mutable.Unlifted.Linear import qualified Data.Bool.Linear import qualified Data.Either.Linear import qualified Data.Functor.Linear import qualified Data.List.Linear import qualified Data.Map as Map import Data.Maybe (fromMaybe) import qualified Data.Monoid.Linear import qualified Data.Num.Linear import qualified Data.Ord.Linear import qualified Data.Replicator.Linear import qualified Data.Tuple.Linear import qualified Data.V.Linear import qualified Prelude.Linear import qualified Streaming.Prelude.Linear import qualified Unsafe.Linear These instances are pushed upstream in -base/pull/416 and should be in any release of linear - base > 0.2.0 | @linear - base@ does n't export ` MovableOrd ` , so we redefine it and its instances here to use in newtype MovableOrd a = MovableOrd a instance (Eq a, Prelude.Linear.Movable a) => Data.Ord.Linear.Eq (MovableOrd a) where MovableOrd ar == MovableOrd br = Prelude.Linear.move (ar, br) Prelude.Linear.& \(Prelude.Linear.Ur (a, b)) -> a == b MovableOrd ar /= MovableOrd br = Prelude.Linear.move (ar, br) Prelude.Linear.& \(Prelude.Linear.Ur (a, b)) -> a /= b instance (Prelude.Ord a, Prelude.Linear.Movable a) => Data.Ord.Linear.Ord (MovableOrd a) where MovableOrd ar `compare` MovableOrd br = Prelude.Linear.move (ar, br) Prelude.Linear.& \(Prelude.Linear.Ur (a, b)) -> a `Prelude.compare` b deriving via MovableOrd Int16 instance Data.Ord.Linear.Eq Int16 deriving via MovableOrd Int32 instance Data.Ord.Linear.Eq Int32 deriving via MovableOrd Int64 instance Data.Ord.Linear.Eq Int64 deriving via MovableOrd Int8 instance Data.Ord.Linear.Eq Int8 deriving via MovableOrd Word16 instance Data.Ord.Linear.Eq Word16 deriving via MovableOrd Word32 instance Data.Ord.Linear.Eq Word32 deriving via MovableOrd Word64 instance Data.Ord.Linear.Eq Word64 deriving via MovableOrd Word8 instance Data.Ord.Linear.Eq Word8 deriving via MovableOrd Int16 instance Data.Ord.Linear.Ord Int16 deriving via MovableOrd Int32 instance Data.Ord.Linear.Ord Int32 deriving via MovableOrd Int64 instance Data.Ord.Linear.Ord Int64 deriving via MovableOrd Int8 instance Data.Ord.Linear.Ord Int8 deriving via MovableOrd Word16 instance Data.Ord.Linear.Ord Word16 deriving via MovableOrd Word32 instance Data.Ord.Linear.Ord Word32 deriving via MovableOrd Word64 instance Data.Ord.Linear.Ord Word64 deriving via MovableOrd Word8 instance Data.Ord.Linear.Ord Word8 deriving instance Show (Data.V.Linear.V n a) deriving instance Foldable (Data.V.Linear.V n) deriving instance KnownNat n => Traversable (Data.V.Linear.V n) instance KnownNat n => Applicative (Data.V.Linear.V n) where pure = Data.Functor.Linear.pure Data.V.Linear.Internal.V fs <*> Data.V.Linear.Internal.V xs = Data.V.Linear.Internal.V $ Vector.zipWith (\f x -> f $ x) fs xs symbolLookup :: Lookup SymbolLookup symbolLookup = do array <- findTyCon "Data.Array.Mutable.Linear" "Array" arrayUnlifted <- findTyCon "Data.Array.Mutable.Unlifted.Linear" "Array#" replicator <- findTyCon "Data.Replicator.Linear" "Replicator" v <- findTyCon "Data.V.Linear" "V" stream <- findTyCon "Streaming.Prelude.Linear" "Stream" pure $ SymbolLookup ( Map.fromList [ (''Data.Array.Mutable.Linear.Array, array), (''Data.Array.Mutable.Unlifted.Linear.Array#, arrayUnlifted), (''Data.Replicator.Linear.Replicator, replicator), (''Data.V.Linear.V, v), (''Streaming.Prelude.Linear.Stream, stream) ] ) mempty makerMapFun :: MakerMapFun makerMapFun symLookup _dflags _logger m@Makers {..} n _target expr _cat _var _args _modu _categorifyFun categorifyLambda = makerMap where makerMap = Map.fromListWith const [ ( '(Control.Functor.Linear.<$>), \case f : a : b : functor : rest -> ($ (f : functor : a : b : rest)) =<< Map.lookup 'Control.Functor.Linear.fmap makerMap _ -> Nothing ), ( '(Control.Functor.Linear.<*>), \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : rest -> pure $ maker2 rest =<\< mkAp f a b _ -> Nothing ), ( '(Control.Functor.Linear.>>=), \case Plugins.Type mty : _monad : Plugins.Type a : Plugins.Type b : rest -> pure $ maker2 rest =<\< mkBind mty a b _ -> Nothing ), ( 'Control.Functor.Linear.ap, \case mty : a : b : monad : rest -> ($ (mty : monad : a : b : rest)) =<< Map.lookup '(Control.Functor.Linear.<*>) makerMap _ -> Nothing ), ( 'Control.Functor.Linear.fmap, \case Plugins.Type f : _functor : Plugins.Type a : Plugins.Type b : u : rest -> pure $ mkMap' f a b u rest _ -> Nothing ), ( 'Control.Functor.Linear.liftA2, \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : Plugins.Type c : u : rest -> pure $ mkLiftA2' f a b c u rest _ -> Nothing ), ( 'Control.Functor.Linear.pure, \case Plugins.Type f : _applicative : Plugins.Type a : rest -> pure $ maker1 rest =<\< mkPoint f a _ -> Nothing ), ( 'Control.Functor.Linear.return, \case mty : a : monad : rest -> ($ mty : monad : a : rest) =<< Map.lookup 'Control.Functor.Linear.pure makerMap _ -> Nothing ), ( 'Data.Array.Mutable.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> do array <- Map.lookup ''Data.Array.Mutable.Linear.Array (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConTy array) a b u rest _ -> Nothing ), ( 'Data.Array.Mutable.Unlifted.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> do array <- Map.lookup ''Data.Array.Mutable.Unlifted.Linear.Array# (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConTy array) a b u rest _ -> Nothing ), ('(Data.Bool.Linear.&&), \rest -> pure $ maker2 rest =<\< mkAnd), ('(Data.Bool.Linear.||), \rest -> pure $ maker2 rest =<\< mkOr), ('Data.Bool.Linear.not, \rest -> pure $ maker1 rest =<\< mkNot), ( 'Data.Either.Linear.either, \case Plugins.Type a1 : Plugins.Type b : Plugins.Type a2 : u : v : rest -> As in § 8 : ( λx → U ▽ V ) ≡ curry ( ( uncurry ( λx → U ) ▽ uncurry ( λx → V ) ) ◦ distl ) pure . joinD $ applyEnriched' [u, v] rest <$> mkJoin (nameTuple a1) (nameTuple a2) b <*\> mkDistl (Plugins.varType n) a1 a2 _ -> Nothing ), ( '(Data.Functor.Linear.<*>), \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : rest -> pure $ maker2 rest =<\< mkAp f a b _ -> Nothing ), ( '(Data.Functor.Linear.<$>), \case f : a : b : functor : rest -> ($ (f : functor : a : b : rest)) =<< Map.lookup 'Data.Functor.Linear.fmap makerMap _ -> Nothing ), ( 'Data.Functor.Linear.fmap, \case Plugins.Type f : _functor : Plugins.Type a : Plugins.Type b : u : rest -> pure $ mkMap' f a b u rest _ -> Nothing ), ( 'Data.Functor.Linear.liftA2, \case Plugins.Type f : _ap : Plugins.Type a : Plugins.Type b : Plugins.Type c : u : rest -> pure $ mkLiftA2' f a b c u rest _ -> Nothing ), ( 'Data.Functor.Linear.pure, \case Plugins.Type f : _applicative : Plugins.Type a : rest -> pure $ maker1 rest =<\< mkPoint f a _ -> Nothing ), ( 'Data.Functor.Linear.sequence, \case Plugins.Type t : _traversable : Plugins.Type f : Plugins.Type a : _applicative : rest -> pure $ maker1 rest =<\< mkSequenceA t f a _ -> Nothing ), ( 'Data.Functor.Linear.sequenceA, \case Plugins.Type t : Plugins.Type f : Plugins.Type a : _traversable : _applicative : rest -> pure $ maker1 rest =<\< mkSequenceA t f a _ -> Nothing ), ( 'Data.Functor.Linear.traverse, \case Plugins.Type t : _traversable : Plugins.Type f : Plugins.Type a : Plugins.Type b : _applicative : u : rest -> pure . joinD $ applyEnriched' [u] rest <$> mkTraverse t f (nameTuple a) b <*\> mkStrength t (Plugins.varType n) a _ -> Nothing ), ( '(Data.List.Linear.++), \case Plugins.Type a : rest -> pure $ maker2 rest <=\< mkAppend $ Plugins.mkTyConApp Plugins.listTyCon [a] _ -> Nothing ), ( 'Data.List.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> pure $ mkMap' (Plugins.mkTyConTy Plugins.listTyCon) a b u rest _ -> Nothing ), ( 'Data.List.Linear.sum, \case Plugins.Type a : _num : rest -> pure $ maker1 rest =<\< mkSum (Plugins.mkTyConTy Plugins.listTyCon) a _ -> Nothing ), ( 'Data.List.Linear.traverse', \case Plugins.Type f : Plugins.Type a : Plugins.Type b : _applicative : u : rest -> let list = Plugins.mkTyConTy Plugins.listTyCon in pure . joinD $ applyEnriched' [u] rest <$> mkTraverse list f (nameTuple a) b <*\> mkStrength list (Plugins.varType n) a _ -> Nothing ), ( '(Data.Monoid.Linear.<>), \case Plugins.Type a : _semigroup : rest -> pure $ maker2 rest =<\< mkAppend a _ -> Nothing ), ( 'Data.Monoid.Linear.mappend, fromMaybe (const Nothing) $ Map.lookup '(Data.Monoid.Linear.<>) makerMap ), ( '(Data.Num.Linear.+), \case Plugins.Type ty : _additive : rest -> pure $ maker2 rest =<\< mkPlus ty _ -> Nothing ), TODO : Catch cases on Natural / Word to turn into Monus ( '(Data.Num.Linear.-), \case Plugins.Type ty : _additive : rest -> pure $ maker2 rest =<\< mkMinus ty _ -> Nothing ), ( '(Data.Num.Linear.*), \case Plugins.Type ty : _multiplicative : rest -> pure $ maker2 rest =<\< mkTimes ty _ -> Nothing ), ( 'Data.Num.Linear.abs, \case Plugins.Type ty : _num : rest -> pure $ maker1 rest =<\< mkAbs ty _ -> Nothing ), ( 'Data.Num.Linear.fromInteger, \case Plugins.Type ty : _fromInteger : rest -> pure $ maker1 rest =<\< mkFromInteger ty _ -> Nothing ), ( 'Data.Num.Linear.negate, \case Plugins.Type ty : _additive : rest -> pure $ maker1 rest =<\< mkNegate ty _ -> Nothing ), ( 'Data.Num.Linear.signum, \case Plugins.Type ty : _num : rest -> pure $ maker1 rest =<\< mkSignum ty _ -> Nothing ), ( '(Data.Ord.Linear.==), \case Plugins.Type ty : _eq : rest -> pure $ maker2 rest =<\< mkEqual ty _ -> Nothing ), ( '(Data.Ord.Linear./=), \case Plugins.Type ty : _eq : rest -> pure $ maker2 rest =<\< mkNotEqual ty _ -> Nothing ), ( '(Data.Ord.Linear.<), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkLT ty _ -> Nothing ), ( '(Data.Ord.Linear.<=), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkLE ty _ -> Nothing ), ( '(Data.Ord.Linear.>), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkGT ty _ -> Nothing ), ( '(Data.Ord.Linear.>=), \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkGE ty _ -> Nothing ), ( 'Data.Ord.Linear.compare, \case Plugins.Type ty : _ord : rest -> pure $ maker2 rest =<\< mkCompare ty _ -> Nothing ), ( 'Data.Ord.Linear.max, \case Plugins.Type ty : _dupable : _ord : rest -> pure $ maker2 rest =<\< mkMax ty _ -> Nothing ), ( 'Data.Ord.Linear.min, \case Plugins.Type ty : _dupable : _ord : rest -> pure $ maker2 rest =<\< mkMin ty _ -> Nothing ), ( '(Data.Replicator.Linear.<*>), \case Plugins.Type a : Plugins.Type b : rest -> do replicator <- Map.lookup ''Data.Replicator.Linear.Replicator (tyConLookup symLookup) pure $ maker2 rest =<\< mkAp (Plugins.mkTyConTy replicator) a b _ -> Nothing ), ( 'Data.Replicator.Linear.map, \case Plugins.Type a : Plugins.Type b : u : rest -> do replicator <- Map.lookup ''Data.Replicator.Linear.Replicator (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConTy replicator) a b u rest _ -> Nothing ), ( 'Data.Replicator.Linear.pure, \case Plugins.Type a : rest -> do replicator <- Map.lookup ''Data.Replicator.Linear.Replicator (tyConLookup symLookup) pure $ maker1 rest =<\< mkPoint (Plugins.mkTyConTy replicator) a _ -> Nothing ), ( 'Data.Tuple.Linear.curry, \case Plugins.Type a1 : Plugins.Type a2 : Plugins.Type b : Plugins.Type _q : Plugins.Type _q' : u : rest -> pure . joinD $ applyEnriched rest <$> mkCurry (nameTuple a1) a2 b <*\> mkId (nameTuple a1) <*\> sequenceA [ joinD $ composeCat m <$> (uncurryCat m =<\< categorifyLambda u) <*\> mkRAssoc (Plugins.varType n) a1 a2 ] _ -> Nothing ), ( 'Data.Tuple.Linear.fst, \case Plugins.Type fTy : Plugins.Type sTy : _consumable : rest -> pure $ maker1 rest =<\< mkExl fTy sTy _ -> Nothing ), ( 'Data.Tuple.Linear.snd, \case Plugins.Type fTy : Plugins.Type sTy : _consumable : rest -> pure $ maker1 rest =<\< mkExr fTy sTy _ -> Nothing ), ( 'Data.Tuple.Linear.swap, \case Plugins.Type a : Plugins.Type b : rest -> pure $ maker1 rest =<\< mkSwap a b _ -> Nothing ), ( 'Data.Tuple.Linear.uncurry, \case Plugins.Type a1 : Plugins.Type a2 : Plugins.Type b : Plugins.Type _q : Plugins.Type _q' : u : rest -> pure . joinD $ applyEnriched' [u] rest <$> mkUncurry (nameTuple a1) a2 b <*\> mkLAssoc (Plugins.varType n) a1 a2 _ -> Nothing ), ( '(Data.V.Linear.<*>), \case Plugins.Type n' : Plugins.Type a : Plugins.Type b : rest -> do v <- Map.lookup ''Data.V.Linear.V (tyConLookup symLookup) pure $ maker2 rest =<\< mkAp (Plugins.mkTyConApp v [n']) a b _ -> Nothing ), ( 'Data.V.Linear.map, \case Plugins.Type a : Plugins.Type b : Plugins.Type n' : u : rest -> do v <- Map.lookup ''Data.V.Linear.V (tyConLookup symLookup) pure $ mkMap' (Plugins.mkTyConApp v [n']) a b u rest _ -> Nothing ), ( 'Data.V.Linear.pure, \case Plugins.Type n' : Plugins.Type a : _knownNat : rest -> do v <- Map.lookup ''Data.V.Linear.V (tyConLookup symLookup) pure $ maker1 rest =<\< mkPoint (Plugins.mkTyConApp v [n']) a _ -> Nothing ), ( '(Prelude.Linear.$), \case Plugins.Type _rep : Plugins.Type a : Plugins.Type b : Plugins.Type _q : Plugins.Type _q' : rest -> pure $ maker2 rest =<\< mkApply a b _ -> Nothing ), ( '(Prelude.Linear..), \case Plugins.Type _rep : Plugins.Type b : Plugins.Type c : Plugins.Type a : Plugins.Type _q : Plugins.Type _q' : Plugins.Type _q'' : f : g : rest -> pure $ case mkCompose2 of Nothing -> ( exl & & & uncurry ( categorify n { { v } } ) ) ) joinD $ applyEnriched rest <$> mkCompose (nameTuple a) (nameTuple b) c <*\> mkId (nameTuple a) <*\> sequenceA [ uncurryCat m =<\< categorifyLambda f, joinD $ forkCat m <$> mkExl (Plugins.varType n) a <*\> (uncurryCat m =<\< categorifyLambda g) ] Just fn -> handleExtraArgs rest =<\< joinD ( fn (Plugins.varType n) b c a <$> categorifyLambda f <*\> categorifyLambda g ) _ -> Nothing ), ( 'Prelude.Linear.const, \case Plugins.Type _b : Plugins.Type a : Plugins.Type _q : u : rest -> _ _ NB _ _ : this does n't use ` applyEnriched ` because @u@ is n't a function . to : curry ( categorify n { { u } } . ) : : n ` k ` ( a - > b ) pure $ handleExtraArgs rest <=\< curryCat m <=\< joinD $ composeCat m <$> categorifyLambda u <*\> mkExl (Plugins.varType n) a _ -> Nothing ), ( 'Prelude.Linear.id, \case Plugins.Type ty : Plugins.Type _q : rest -> pure $ maker1 rest =<\< mkId ty _ -> Nothing ), ( 'Unsafe.Linear.coerce, \case Plugins.Type from : Plugins.Type to : rest -> pure $ maker1 rest =<\< mkCoerce from to _ -> Nothing ) ] maker1 = makeMaker1 m categorifyLambda maker2 = makeMaker2 m categorifyLambda expr handleExtraArgs = handleAdditionalArgs m categorifyLambda mkLiftA2' f a b c u rest = handleExtraArgs rest =<\< curryCat m =<\< joinD ( composeCat m <$> ( curryCat m =<\< ( Plugins.App <$> mkLiftA2 f (nameTuple a) b c <*\> ( uncurryCat m =<\< uncurryCat m =<\< categorifyLambda u ) ) ) <*\> mkStrength f (Plugins.varType n) a ) mkMap' f a b u rest = joinD $ applyEnriched' [u] rest <$> mkMap f (nameTuple a) b <*\> mkStrength f (Plugins.varType n) a applyEnriched = applyEnrichedCat m categorifyLambda applyEnriched' = applyEnrichedCat' m categorifyLambda nameTuple = makeTupleTyWithVar n
a316831bd553768ec2923873972f0766c18011f60764d4b35a223fd95861d6d8
mirage/ocaml-git
object_graph.mli
* 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. *) module type S = sig type hash type store module S : Set.S with type elt = hash * An imperative of the store . module K : Graph.Sig.I with type V.t = hash val keys : K.t -> hash list (** [keys graph] returns all hashes recheables in the graph [graph]. *) val of_keys : store -> K.t Lwt.t (** [of_keys store] makes a new graph from all values of a [store]. *) val of_commits : store -> K.t Lwt.t (** [of_commits store] makes a new graph from all commits of a [store]. *) val closure : ?full:bool -> store -> min:S.t -> max:S.t -> K.t Lwt.t val pack : store -> min:S.t -> max:S.t -> (hash * hash Value.t) list Lwt.t val to_dot : store -> Format.formatter -> unit Lwt.t end module Make (Hash : Digestif.S) (Store : Minimal.S with type hash = Hash.t) : S with type hash = Hash.t and type store = Store.t
null
https://raw.githubusercontent.com/mirage/ocaml-git/37c9ef41944b5b19117c34eee83ca672bb63f482/src/git/object_graph.mli
ocaml
* [keys graph] returns all hashes recheables in the graph [graph]. * [of_keys store] makes a new graph from all values of a [store]. * [of_commits store] makes a new graph from all commits of a [store].
* 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. *) module type S = sig type hash type store module S : Set.S with type elt = hash * An imperative of the store . module K : Graph.Sig.I with type V.t = hash val keys : K.t -> hash list val of_keys : store -> K.t Lwt.t val of_commits : store -> K.t Lwt.t val closure : ?full:bool -> store -> min:S.t -> max:S.t -> K.t Lwt.t val pack : store -> min:S.t -> max:S.t -> (hash * hash Value.t) list Lwt.t val to_dot : store -> Format.formatter -> unit Lwt.t end module Make (Hash : Digestif.S) (Store : Minimal.S with type hash = Hash.t) : S with type hash = Hash.t and type store = Store.t
fad88d38fe44fae37a377663bbe80a97db5894f3e0ddfe5aa5dbb4c983a6898b
dgtized/shimmers
index.cljs
(ns shimmers.view.index (:require [clojure.set :as set] [clojure.string :as str] [reagent.core :as r] [reitit.frontend.easy :as rfe] [shimmers.view.sketch :as view-sketch])) (defn sketch-title [sketch] (->> [(when-let [created-at (:created-at sketch)] (subs (.toISOString (js/Date. created-at)) 0 10)) (when-let [tags (seq (:tags sketch))] (str "tags:" (str/join "," (map name tags))))] (filter some?) (str/join " "))) (defn list-sketches [sketches] (into [:ul] (for [sketch sketches] [:li [:a {:href (view-sketch/sketch-link rfe/href (:sketch-id sketch)) :title (sketch-title sketch)} (:sketch-id sketch)]]))) (defonce text-filter (r/atom "")) (defn filter-sketches [sketches] (let [terms @text-filter] (if (empty? terms) [sketches ""] [(filter (fn [sketch] (re-find (re-pattern terms) (name (:sketch-id sketch)))) sketches) terms]))) (defn update-terms [event] (let [term (-> event .-target .-value)] (when (or (empty? term) (try (re-pattern term) (catch js/Object _ false))) (reset! text-filter term)))) (defn filtered-terms [sketches filtered terms] (if (seq terms) [:p "Found " (count filtered) " of " (count sketches) " sketches matching term \"" terms "\""] [:p])) (defn selector [active] (let [pages {::by-alphabetical "Alphabetically" ::by-date "By Date" ::by-tag "By Tag"} search-input [:input {:type :search :placeholder "search by name" :value @text-filter :on-input update-terms}] links (for [[page link-name] pages] [:a {:href (when-not (= page active) (rfe/href page))} link-name])] (into [:div.selector search-input " Listing: "] (interpose [:span " | "] links)))) ;; FIXME: links are *always* fresh now since the seed is baked in (defn by-alphabetical [sketches] (let [[filtered terms] (filter-sketches sketches)] [:section.sketch-list [:h1 (str "All Sketches (" (count sketches) ")")] [:p "A digital sketch-book of generative art, visual effects, computer animation, visualizations of algorithms, and whatever else struck my fancy to implement or explore. Many are complete, and some I periodically revisit and tweak. For those inspired by other's works or tutorials, I do my best to give attribution in the source code."] (selector ::by-alphabetical) (filtered-terms sketches filtered terms) [:div.multi-column (list-sketches filtered)]])) ;; -US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat (defn year-month [{:keys [created-at]}] (let [date (js/Date. created-at) intl (js/Intl.DateTimeFormat. "en-US" #js{:month "long" :timeZone "UTC"})] [(.getUTCFullYear date) (.format intl date)])) (defn by-date [sketches] (let [[filtered terms] (filter-sketches sketches) sketches-by-date (sort-by :created-at filtered) grouped-by-month (partition-by year-month sketches-by-date)] [:section.sketch-list (selector ::by-date) (filtered-terms sketches filtered terms) [:div.multi-column (for [sketches grouped-by-month :let [[year month] (year-month (first sketches))]] [:div.group {:key (str year month)} [:h3 (str month " " year " (" (count sketches) ")")] (list-sketches sketches)])]])) (defn all-tags [sketches] (apply set/union (map :tags sketches))) (defn by-tag [sketches] (let [tagged (remove (fn [s] (empty? (:tags s))) sketches) [filtered terms] (filter-sketches tagged) tags (all-tags filtered)] [:section.sketch-list (selector ::by-tag) (filtered-terms tagged filtered terms) [:div.multi-column (for [tag (sort-by name tags) :let [tagged-sketches (filter #(tag (:tags %)) filtered)]] [:div.group {:key (str tag)} [:h3 (str (str/capitalize (name tag)) " (" (count tagged-sketches) ")")] (list-sketches tagged-sketches)])]]))
null
https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/view/index.cljs
clojure
FIXME: links are *always* fresh now since the seed is baked in -US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
(ns shimmers.view.index (:require [clojure.set :as set] [clojure.string :as str] [reagent.core :as r] [reitit.frontend.easy :as rfe] [shimmers.view.sketch :as view-sketch])) (defn sketch-title [sketch] (->> [(when-let [created-at (:created-at sketch)] (subs (.toISOString (js/Date. created-at)) 0 10)) (when-let [tags (seq (:tags sketch))] (str "tags:" (str/join "," (map name tags))))] (filter some?) (str/join " "))) (defn list-sketches [sketches] (into [:ul] (for [sketch sketches] [:li [:a {:href (view-sketch/sketch-link rfe/href (:sketch-id sketch)) :title (sketch-title sketch)} (:sketch-id sketch)]]))) (defonce text-filter (r/atom "")) (defn filter-sketches [sketches] (let [terms @text-filter] (if (empty? terms) [sketches ""] [(filter (fn [sketch] (re-find (re-pattern terms) (name (:sketch-id sketch)))) sketches) terms]))) (defn update-terms [event] (let [term (-> event .-target .-value)] (when (or (empty? term) (try (re-pattern term) (catch js/Object _ false))) (reset! text-filter term)))) (defn filtered-terms [sketches filtered terms] (if (seq terms) [:p "Found " (count filtered) " of " (count sketches) " sketches matching term \"" terms "\""] [:p])) (defn selector [active] (let [pages {::by-alphabetical "Alphabetically" ::by-date "By Date" ::by-tag "By Tag"} search-input [:input {:type :search :placeholder "search by name" :value @text-filter :on-input update-terms}] links (for [[page link-name] pages] [:a {:href (when-not (= page active) (rfe/href page))} link-name])] (into [:div.selector search-input " Listing: "] (interpose [:span " | "] links)))) (defn by-alphabetical [sketches] (let [[filtered terms] (filter-sketches sketches)] [:section.sketch-list [:h1 (str "All Sketches (" (count sketches) ")")] [:p "A digital sketch-book of generative art, visual effects, computer animation, visualizations of algorithms, and whatever else struck my fancy to implement or explore. Many are complete, and some I periodically revisit and tweak. For those inspired by other's works or tutorials, I do my best to give attribution in the source code."] (selector ::by-alphabetical) (filtered-terms sketches filtered terms) [:div.multi-column (list-sketches filtered)]])) (defn year-month [{:keys [created-at]}] (let [date (js/Date. created-at) intl (js/Intl.DateTimeFormat. "en-US" #js{:month "long" :timeZone "UTC"})] [(.getUTCFullYear date) (.format intl date)])) (defn by-date [sketches] (let [[filtered terms] (filter-sketches sketches) sketches-by-date (sort-by :created-at filtered) grouped-by-month (partition-by year-month sketches-by-date)] [:section.sketch-list (selector ::by-date) (filtered-terms sketches filtered terms) [:div.multi-column (for [sketches grouped-by-month :let [[year month] (year-month (first sketches))]] [:div.group {:key (str year month)} [:h3 (str month " " year " (" (count sketches) ")")] (list-sketches sketches)])]])) (defn all-tags [sketches] (apply set/union (map :tags sketches))) (defn by-tag [sketches] (let [tagged (remove (fn [s] (empty? (:tags s))) sketches) [filtered terms] (filter-sketches tagged) tags (all-tags filtered)] [:section.sketch-list (selector ::by-tag) (filtered-terms tagged filtered terms) [:div.multi-column (for [tag (sort-by name tags) :let [tagged-sketches (filter #(tag (:tags %)) filtered)]] [:div.group {:key (str tag)} [:h3 (str (str/capitalize (name tag)) " (" (count tagged-sketches) ")")] (list-sketches tagged-sketches)])]]))
a646f92929345cf0b00c0aae714a5f0d56e7cc66f9c99edb21f10fce6683a424
Chris00/ocaml-interval
main.ml
open Interval_intel Standard Griewank function without rotation matrix , very easy to maximize let dim = 7 let highbound = 600.0 let lowbound = -. 400.0 let precisionx = 0.01 let precisionfx = 0.0001 let start_inter = Array.init dim (function _i -> {low=lowbound;high=highbound}) let griewank_x v = let s1 = ref 0.0 and s2 = ref 1.0 in for i= 0 to (Array.length v)-1 do s1:= !s1+. v.(i)*. v.(i); s2:= !s2*. (cos (v.(i)/. (sqrt (float (i+1))))) done; let sum = !s1/. 4000.0 -. !s2 +.1. in 1./.(1.+. sum) let griewank_X vec = let s1 = ref I.zero and s2 = ref I.one in for i = 0 to Array.length vec - 1 do s1 := I.(!s1 + vec.(i)**2); s2 := I.(!s2 * cos(vec.(i) / (sqrt (of_int U.(i+1))))) done; let sum = I.((!s1 /. 4000. - !s2) +. 1.) in I.(inv (sum +. 1.)) let _ = let (int,fint,p,pv)= B_and_b.branch_and_bound griewank_x griewank_X start_inter precisionx precisionfx in I.Arr.pr stdout int; print_string " = "; I.pr stdout fint; print_newline (); Array.iter (function x -> Printf.printf "%f " x) p; Printf.printf " = %f\n%!" pv
null
https://raw.githubusercontent.com/Chris00/ocaml-interval/afee6e940837c9e3c690624ca2d7abbdee3c3ffb/examples/B_AND_B/main.ml
ocaml
open Interval_intel Standard Griewank function without rotation matrix , very easy to maximize let dim = 7 let highbound = 600.0 let lowbound = -. 400.0 let precisionx = 0.01 let precisionfx = 0.0001 let start_inter = Array.init dim (function _i -> {low=lowbound;high=highbound}) let griewank_x v = let s1 = ref 0.0 and s2 = ref 1.0 in for i= 0 to (Array.length v)-1 do s1:= !s1+. v.(i)*. v.(i); s2:= !s2*. (cos (v.(i)/. (sqrt (float (i+1))))) done; let sum = !s1/. 4000.0 -. !s2 +.1. in 1./.(1.+. sum) let griewank_X vec = let s1 = ref I.zero and s2 = ref I.one in for i = 0 to Array.length vec - 1 do s1 := I.(!s1 + vec.(i)**2); s2 := I.(!s2 * cos(vec.(i) / (sqrt (of_int U.(i+1))))) done; let sum = I.((!s1 /. 4000. - !s2) +. 1.) in I.(inv (sum +. 1.)) let _ = let (int,fint,p,pv)= B_and_b.branch_and_bound griewank_x griewank_X start_inter precisionx precisionfx in I.Arr.pr stdout int; print_string " = "; I.pr stdout fint; print_newline (); Array.iter (function x -> Printf.printf "%f " x) p; Printf.printf " = %f\n%!" pv
f73e77732df41092a522966552c0fb581d216619d82e9bb3891d372dcf8aa36a
milgra/cljs-brawl
buffers.cljs
(ns cljs-webgl.buffers (:require [cljs-webgl.context :as context] [cljs-webgl.typed-arrays :as ta] [cljs-webgl.constants.capability :as capability] [cljs-webgl.constants.clear-buffer-mask :as clear-buffer] [cljs-webgl.constants.buffer-object :as buffer-object] [cljs-webgl.constants.texture-target :as texture-target] [cljs-webgl.constants.texture-unit :as texture-unit] [cljs-webgl.constants.data-type :as data-type] [cljs-webgl.shaders :as shaders])) (defn create-buffer "Creates a new buffer with initialized `data`. `data` must be a typed-array `target` may be `cljs-webgl.constants.buffer-object/array-buffer` or `cljs-webgl.constants.buffer-object/element-array-buffer` `usage` may be `cljs-webgl.constants.buffer-object/static-draw` or `cljs-webgl.constants.buffer-object/dynamic-draw` `item-size` [optional] will set the item size as an attribute on the buffer, and the calculate the number of items accordingly. Relevant OpenGL ES reference pages: * [glGenBuffers(Similar to createBuffer)]() * [glBindBuffer]() * [glBufferData]()" [gl-context data target usage & [item-size]] (let [buffer (.createBuffer gl-context)] (.bindBuffer gl-context target buffer) (.bufferData gl-context target data usage) (when item-size (set! (.-itemSize buffer) item-size) (set! (.-numItems buffer) (quot (.-length data) item-size))) buffer)) (defn upload-buffer [gl-context buffer data target usage] (.bindBuffer gl-context target buffer) (.bufferData gl-context target data usage)) (defn clear-color-buffer "Clears the color buffer with specified `red`, `green`, `blue` and `alpha` values. Relevant OpenGL ES reference pages: * [glClearColor]() * [glClear]()" [gl-context red green blue alpha] (.clearColor gl-context red green blue alpha) (.clear gl-context clear-buffer/color-buffer-bit) gl-context) (defn clear-depth-buffer "Clears the depth buffer with specified `depth` value. Relevant OpenGL ES reference pages: * [glClearDepthf]() * [glClear]()" [gl-context depth] (.clearDepth gl-context depth) (.clear gl-context clear-buffer/depth-buffer-bit) gl-context) (defn clear-stencil-buffer "Clears the stencil buffer with specified `index` value. Relevant OpenGL ES reference pages: * [glClearStencil]() * [glClear]()" [gl-context index] (.clearStencil gl-context index) (.clear gl-context clear-buffer/stencil-buffer-bit) gl-context) (defn ^:private set-uniform [gl-context shader {:keys [name type values transpose]}] (let [uniform-location (shaders/get-uniform-location gl-context shader name)] (case type :bool (.uniform1fv gl-context uniform-location values) :bvec2 (.uniform2fv gl-context uniform-location values) :bvec3 (.uniform3fv gl-context uniform-location values) :bvec4 (.uniform4fv gl-context uniform-location values) :float (.uniform1fv gl-context uniform-location values) :vec2 (.uniform2fv gl-context uniform-location values) :vec3 (.uniform3fv gl-context uniform-location values) :vec4 (.uniform4fv gl-context uniform-location values) :int (.uniform1iv gl-context uniform-location values) :ivec2 (.uniform2iv gl-context uniform-location values) :ivec3 (.uniform3iv gl-context uniform-location values) :ivec4 (.uniform4iv gl-context uniform-location values) :mat2 (.uniformMatrix2fv gl-context uniform-location transpose values) :mat3 (.uniformMatrix3fv gl-context uniform-location transpose values) :mat4 (.uniformMatrix4fv gl-context uniform-location transpose values) nil))) (defn ^:private set-attribute [gl-context {:keys [buffer location components-per-vertex type normalized? stride offset]}] (.bindBuffer gl-context buffer-object/array-buffer buffer) (.enableVertexAttribArray gl-context location) (.vertexAttribPointer gl-context location (or components-per-vertex (.-itemSize buffer)) (or type data-type/float) (or normalized? false) (or stride 0) (or offset 0))) (defn ^:private set-texture [gl-context shader {:keys [texture name texture-unit]}] (let [unit (if texture-unit (+ texture-unit/texture0 texture-unit) texture-unit/texture0) uniform-index (or texture-unit 0)] (.activeTexture gl-context texture-unit/texture0) (.bindTexture gl-context texture-target/texture-2d texture) (.uniform1i gl-context (shaders/get-uniform-location gl-context shader name) 0))) (def ^:private default-capabilities {capability/blend false capability/cull-face false capability/depth-test false capability/dither true capability/polygon-offset-fill false capability/sample-alpha-to-coverage false capability/sample-coverage false capability/scissor-test false capability/stencil-test false}) (defn ^:private set-capability "Enables/disables according to `enabled?` a given server-side GL `capability` The valid values for `capability` are: `cljs-webgl.constants.capability/blend`, `cljs-webgl.constants.capability/cull-face`, `cljs-webgl.constants.capability/depth-test`, `cljs-webgl.constants.capability/dither`, `cljs-webgl.constants.capability/polygon-offset-fill`, `cljs-webgl.constants.capability/sample-alpha-to-coverage`, `cljs-webgl.constants.capability/sample-coverage`, `cljs-webgl.constants.capability/scissor-test`, `cljs-webgl.constants.capability/stencil-test` Relevant OpenGL ES reference pages: * [glEnable]() * [glDisable]()" [gl-context capability enabled?] (if enabled? (.enable gl-context capability) (.disable gl-context capability)) gl-context) (defn ^:private set-viewport "Sets `gl-context` viewport according to `viewport` which is expected to have the form: {:x, :y, :width, :height} Relevant OpenGL ES reference pages: * [viewport]()" [gl-context {:keys [x y width height] :as viewport}] (.viewport gl-context x y width height)) (defn draw! [gl-context & {:keys [shader draw-mode first count attributes uniforms textures element-array capabilities blend-function viewport] :as opts}] (set-viewport gl-context (or viewport {:x 0, :y 0, :width (context/get-drawing-buffer-width gl-context), :height (context/get-drawing-buffer-height gl-context)})) (.useProgram gl-context shader) (doseq [u uniforms] (set-uniform gl-context shader u)) (doseq [a attributes] (set-attribute gl-context a)) (doseq [t textures] (set-texture gl-context shader t)) (doseq [[capability enabled?] (merge default-capabilities capabilities)] (set-capability gl-context capability enabled?)) (if (nil? element-array) (.drawArrays gl-context draw-mode (or first 0) count) (do (.bindBuffer gl-context buffer-object/element-array-buffer (:buffer element-array)) (.drawElements gl-context draw-mode count (:type element-array) (:offset element-array)))) (doseq [a attributes] (.disableVertexAttribArray gl-context (:location a))) (doseq [[k v] blend-function] (.blendFunc gl-context k v)) gl-context)
null
https://raw.githubusercontent.com/milgra/cljs-brawl/e03cf6f032b1af0f6e38396e43e739f83446a3e4/src/cljs_webgl/buffers.cljs
clojure
(ns cljs-webgl.buffers (:require [cljs-webgl.context :as context] [cljs-webgl.typed-arrays :as ta] [cljs-webgl.constants.capability :as capability] [cljs-webgl.constants.clear-buffer-mask :as clear-buffer] [cljs-webgl.constants.buffer-object :as buffer-object] [cljs-webgl.constants.texture-target :as texture-target] [cljs-webgl.constants.texture-unit :as texture-unit] [cljs-webgl.constants.data-type :as data-type] [cljs-webgl.shaders :as shaders])) (defn create-buffer "Creates a new buffer with initialized `data`. `data` must be a typed-array `target` may be `cljs-webgl.constants.buffer-object/array-buffer` or `cljs-webgl.constants.buffer-object/element-array-buffer` `usage` may be `cljs-webgl.constants.buffer-object/static-draw` or `cljs-webgl.constants.buffer-object/dynamic-draw` `item-size` [optional] will set the item size as an attribute on the buffer, and the calculate the number of items accordingly. Relevant OpenGL ES reference pages: * [glGenBuffers(Similar to createBuffer)]() * [glBindBuffer]() * [glBufferData]()" [gl-context data target usage & [item-size]] (let [buffer (.createBuffer gl-context)] (.bindBuffer gl-context target buffer) (.bufferData gl-context target data usage) (when item-size (set! (.-itemSize buffer) item-size) (set! (.-numItems buffer) (quot (.-length data) item-size))) buffer)) (defn upload-buffer [gl-context buffer data target usage] (.bindBuffer gl-context target buffer) (.bufferData gl-context target data usage)) (defn clear-color-buffer "Clears the color buffer with specified `red`, `green`, `blue` and `alpha` values. Relevant OpenGL ES reference pages: * [glClearColor]() * [glClear]()" [gl-context red green blue alpha] (.clearColor gl-context red green blue alpha) (.clear gl-context clear-buffer/color-buffer-bit) gl-context) (defn clear-depth-buffer "Clears the depth buffer with specified `depth` value. Relevant OpenGL ES reference pages: * [glClearDepthf]() * [glClear]()" [gl-context depth] (.clearDepth gl-context depth) (.clear gl-context clear-buffer/depth-buffer-bit) gl-context) (defn clear-stencil-buffer "Clears the stencil buffer with specified `index` value. Relevant OpenGL ES reference pages: * [glClearStencil]() * [glClear]()" [gl-context index] (.clearStencil gl-context index) (.clear gl-context clear-buffer/stencil-buffer-bit) gl-context) (defn ^:private set-uniform [gl-context shader {:keys [name type values transpose]}] (let [uniform-location (shaders/get-uniform-location gl-context shader name)] (case type :bool (.uniform1fv gl-context uniform-location values) :bvec2 (.uniform2fv gl-context uniform-location values) :bvec3 (.uniform3fv gl-context uniform-location values) :bvec4 (.uniform4fv gl-context uniform-location values) :float (.uniform1fv gl-context uniform-location values) :vec2 (.uniform2fv gl-context uniform-location values) :vec3 (.uniform3fv gl-context uniform-location values) :vec4 (.uniform4fv gl-context uniform-location values) :int (.uniform1iv gl-context uniform-location values) :ivec2 (.uniform2iv gl-context uniform-location values) :ivec3 (.uniform3iv gl-context uniform-location values) :ivec4 (.uniform4iv gl-context uniform-location values) :mat2 (.uniformMatrix2fv gl-context uniform-location transpose values) :mat3 (.uniformMatrix3fv gl-context uniform-location transpose values) :mat4 (.uniformMatrix4fv gl-context uniform-location transpose values) nil))) (defn ^:private set-attribute [gl-context {:keys [buffer location components-per-vertex type normalized? stride offset]}] (.bindBuffer gl-context buffer-object/array-buffer buffer) (.enableVertexAttribArray gl-context location) (.vertexAttribPointer gl-context location (or components-per-vertex (.-itemSize buffer)) (or type data-type/float) (or normalized? false) (or stride 0) (or offset 0))) (defn ^:private set-texture [gl-context shader {:keys [texture name texture-unit]}] (let [unit (if texture-unit (+ texture-unit/texture0 texture-unit) texture-unit/texture0) uniform-index (or texture-unit 0)] (.activeTexture gl-context texture-unit/texture0) (.bindTexture gl-context texture-target/texture-2d texture) (.uniform1i gl-context (shaders/get-uniform-location gl-context shader name) 0))) (def ^:private default-capabilities {capability/blend false capability/cull-face false capability/depth-test false capability/dither true capability/polygon-offset-fill false capability/sample-alpha-to-coverage false capability/sample-coverage false capability/scissor-test false capability/stencil-test false}) (defn ^:private set-capability "Enables/disables according to `enabled?` a given server-side GL `capability` The valid values for `capability` are: `cljs-webgl.constants.capability/blend`, `cljs-webgl.constants.capability/cull-face`, `cljs-webgl.constants.capability/depth-test`, `cljs-webgl.constants.capability/dither`, `cljs-webgl.constants.capability/polygon-offset-fill`, `cljs-webgl.constants.capability/sample-alpha-to-coverage`, `cljs-webgl.constants.capability/sample-coverage`, `cljs-webgl.constants.capability/scissor-test`, `cljs-webgl.constants.capability/stencil-test` Relevant OpenGL ES reference pages: * [glEnable]() * [glDisable]()" [gl-context capability enabled?] (if enabled? (.enable gl-context capability) (.disable gl-context capability)) gl-context) (defn ^:private set-viewport "Sets `gl-context` viewport according to `viewport` which is expected to have the form: {:x, :y, :width, :height} Relevant OpenGL ES reference pages: * [viewport]()" [gl-context {:keys [x y width height] :as viewport}] (.viewport gl-context x y width height)) (defn draw! [gl-context & {:keys [shader draw-mode first count attributes uniforms textures element-array capabilities blend-function viewport] :as opts}] (set-viewport gl-context (or viewport {:x 0, :y 0, :width (context/get-drawing-buffer-width gl-context), :height (context/get-drawing-buffer-height gl-context)})) (.useProgram gl-context shader) (doseq [u uniforms] (set-uniform gl-context shader u)) (doseq [a attributes] (set-attribute gl-context a)) (doseq [t textures] (set-texture gl-context shader t)) (doseq [[capability enabled?] (merge default-capabilities capabilities)] (set-capability gl-context capability enabled?)) (if (nil? element-array) (.drawArrays gl-context draw-mode (or first 0) count) (do (.bindBuffer gl-context buffer-object/element-array-buffer (:buffer element-array)) (.drawElements gl-context draw-mode count (:type element-array) (:offset element-array)))) (doseq [a attributes] (.disableVertexAttribArray gl-context (:location a))) (doseq [[k v] blend-function] (.blendFunc gl-context k v)) gl-context)
b89d4761c0634ab3f604ebfe9cc63516a23b81bbb80f4b853380cd7f43c12a64
erlangonrails/devdb
couch_task_status.erl
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(couch_task_status). -behaviour(gen_server). % This module allows is used to track the status of long running tasks. Long running tasks register ( ) then update their status ( update/1 ) % and the task and status is added to tasks list. When the tracked task dies % it will be automatically removed the tracking. To get the tasks list, use the % all/0 function -export([start_link/0, stop/0]). -export([all/0, add_task/3, update/1, update/2, set_update_frequency/1]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -import(couch_util, [to_binary/1]). -include("couch_db.hrl"). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:cast(?MODULE, stop). all() -> gen_server:call(?MODULE, all). add_task(Type, TaskName, StatusText) -> put(task_status_update, {{0, 0, 0}, 0}), Msg = { add_task, to_binary(Type), to_binary(TaskName), to_binary(StatusText) }, gen_server:call(?MODULE, Msg). set_update_frequency(Msecs) -> put(task_status_update, {{0, 0, 0}, Msecs * 1000}). update(StatusText) -> update("~s", [StatusText]). update(Format, Data) -> {LastUpdateTime, Frequency} = get(task_status_update), case timer:now_diff(Now = now(), LastUpdateTime) >= Frequency of true -> put(task_status_update, {Now, Frequency}), Msg = ?l2b(io_lib:format(Format, Data)), gen_server:cast(?MODULE, {update_status, self(), Msg}); false -> ok end. init([]) -> % read configuration settings and register for configuration changes ets:new(?MODULE, [ordered_set, protected, named_table]), {ok, nil}. terminate(_Reason,_State) -> ok. handle_call({add_task, Type, TaskName, StatusText}, {From, _}, Server) -> case ets:lookup(?MODULE, From) of [] -> true = ets:insert(?MODULE, {From, {Type, TaskName, StatusText}}), erlang:monitor(process, From), {reply, ok, Server}; [_] -> {reply, {add_task_error, already_registered}, Server} end; handle_call(all, _, Server) -> All = [ [ {type, Type}, {task, Task}, {status, Status}, {pid, ?l2b(pid_to_list(Pid))} ] || {Pid, {Type, Task, Status}} <- ets:tab2list(?MODULE) ], {reply, All, Server}. handle_cast({update_status, Pid, StatusText}, Server) -> [{Pid, {Type, TaskName, _StatusText}}] = ets:lookup(?MODULE, Pid), ?LOG_DEBUG("New task status for ~s: ~s",[TaskName, StatusText]), true = ets:insert(?MODULE, {Pid, {Type, TaskName, StatusText}}), {noreply, Server}; handle_cast(stop, State) -> {stop, normal, State}. handle_info({'DOWN', _MonitorRef, _Type, Pid, _Info}, Server) -> should we also : demonitor(_MonitorRef ) , ? ets:delete(?MODULE, Pid), {noreply, Server}. code_change(_OldVsn, State, _Extra) -> {ok, State}.
null
https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/apache-couchdb-0.11.1/src/couchdb/couch_task_status.erl
erlang
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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This module allows is used to track the status of long running tasks. and the task and status is added to tasks list. When the tracked task dies it will be automatically removed the tracking. To get the tasks list, use the all/0 function read configuration settings and register for configuration changes
Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -module(couch_task_status). -behaviour(gen_server). Long running tasks register ( ) then update their status ( update/1 ) -export([start_link/0, stop/0]). -export([all/0, add_task/3, update/1, update/2, set_update_frequency/1]). -export([init/1, terminate/2, code_change/3]). -export([handle_call/3, handle_cast/2, handle_info/2]). -import(couch_util, [to_binary/1]). -include("couch_db.hrl"). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). stop() -> gen_server:cast(?MODULE, stop). all() -> gen_server:call(?MODULE, all). add_task(Type, TaskName, StatusText) -> put(task_status_update, {{0, 0, 0}, 0}), Msg = { add_task, to_binary(Type), to_binary(TaskName), to_binary(StatusText) }, gen_server:call(?MODULE, Msg). set_update_frequency(Msecs) -> put(task_status_update, {{0, 0, 0}, Msecs * 1000}). update(StatusText) -> update("~s", [StatusText]). update(Format, Data) -> {LastUpdateTime, Frequency} = get(task_status_update), case timer:now_diff(Now = now(), LastUpdateTime) >= Frequency of true -> put(task_status_update, {Now, Frequency}), Msg = ?l2b(io_lib:format(Format, Data)), gen_server:cast(?MODULE, {update_status, self(), Msg}); false -> ok end. init([]) -> ets:new(?MODULE, [ordered_set, protected, named_table]), {ok, nil}. terminate(_Reason,_State) -> ok. handle_call({add_task, Type, TaskName, StatusText}, {From, _}, Server) -> case ets:lookup(?MODULE, From) of [] -> true = ets:insert(?MODULE, {From, {Type, TaskName, StatusText}}), erlang:monitor(process, From), {reply, ok, Server}; [_] -> {reply, {add_task_error, already_registered}, Server} end; handle_call(all, _, Server) -> All = [ [ {type, Type}, {task, Task}, {status, Status}, {pid, ?l2b(pid_to_list(Pid))} ] || {Pid, {Type, Task, Status}} <- ets:tab2list(?MODULE) ], {reply, All, Server}. handle_cast({update_status, Pid, StatusText}, Server) -> [{Pid, {Type, TaskName, _StatusText}}] = ets:lookup(?MODULE, Pid), ?LOG_DEBUG("New task status for ~s: ~s",[TaskName, StatusText]), true = ets:insert(?MODULE, {Pid, {Type, TaskName, StatusText}}), {noreply, Server}; handle_cast(stop, State) -> {stop, normal, State}. handle_info({'DOWN', _MonitorRef, _Type, Pid, _Info}, Server) -> should we also : demonitor(_MonitorRef ) , ? ets:delete(?MODULE, Pid), {noreply, Server}. code_change(_OldVsn, State, _Extra) -> {ok, State}.
879bd052f534926c786092e7c6cac6da2a6fd0242c6020aa489b5386bd0e5f57
TrustInSoft/tis-interpreter
GuiGoal.mli
Modified by TrustInSoft (**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (* -------------------------------------------------------------------------- *) (* --- PO Details View --- *) (* -------------------------------------------------------------------------- *) class pane : unit -> object method select : Wpo.t option -> unit method update : unit method coerce : GObj.widget method on_run : (Wpo.t -> VCS.prover -> unit) -> unit method on_src : (Wpo.t option -> unit) -> unit end
null
https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/plugins/wp/GuiGoal.mli
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ -------------------------------------------------------------------------- --- PO Details View --- --------------------------------------------------------------------------
Modified by TrustInSoft This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2015 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . class pane : unit -> object method select : Wpo.t option -> unit method update : unit method coerce : GObj.widget method on_run : (Wpo.t -> VCS.prover -> unit) -> unit method on_src : (Wpo.t option -> unit) -> unit end
eb23afab5a942adc050870d05c433fd770c2c9e40c19ccb99ccbde03d06e1977
lijunsong/pollen-rock
get-contents-handler.rkt
#lang racket ;;; API: get filesystem contents (list directory or get file contents) (require "../http-util.rkt") (require "../logger.rkt") (require json) (require web-server/http/request-structs) (provide get-contents-handler) ;; return spec for file operation (define/contract (get-contents-answer errno [mtime 0] [items false] [contents false]) (->* (integer?) (integer? (or/c list? false) (or/c string? false)) jsexpr?) (cond [(and (eq? items false) (eq? contents false) (= errno 0)) (error 'get-contents-answer "items and contents must not be empty at the same time")] [(not (= errno 0)) (hasheq 'errno errno)] [(eq? items false) (hasheq 'errno errno 'mtime mtime 'contents contents)] [else (hasheq 'errno errno 'mtime mtime 'items items)])) ;; select matched handler from `handler-map` to respond to the `req`. the value of handler - map must be taking one or two positional arguments . If it takes one argument , url - parts will be converted to a path and passed into the function . If two arguments , ` req ` binding ` data ` will be passed as bytes to the second argument . (define (get-contents-handler req url-parts) (log-rest-info "get-contents-handler ~a" url-parts) ;; I have to inline the filter. See comments in static-file-handler (define file-path (apply build-path `(,(current-directory) ,@(filter non-empty-string? url-parts)))) (cond [(directory-exists? file-path) (log-rest-debug "list directory ~a" file-path) (define items (directory-list file-path #:build? false)) (define names (map (lambda (n) (if (directory-exists? (build-path file-path n)) (string-append (path->string n) "/") (path->string n))) items)) (define mtime (file-or-directory-modify-seconds file-path)) (get-contents-answer 0 mtime names)] [(file-exists? file-path) (log-rest-debug "get contents of file ~a" file-path) (define contents (file->string file-path)) (define mtime (file-or-directory-modify-seconds file-path)) (get-contents-answer 0 mtime false contents)] [else (get-contents-answer 1)]))
null
https://raw.githubusercontent.com/lijunsong/pollen-rock/8107c7c1a1ca1e5ab125650f38002683b15b22c9/pollen-rock/handlers/get-contents-handler.rkt
racket
API: get filesystem contents (list directory or get file contents) return spec for file operation select matched handler from `handler-map` to respond to the `req`. I have to inline the filter. See comments in static-file-handler
#lang racket (require "../http-util.rkt") (require "../logger.rkt") (require json) (require web-server/http/request-structs) (provide get-contents-handler) (define/contract (get-contents-answer errno [mtime 0] [items false] [contents false]) (->* (integer?) (integer? (or/c list? false) (or/c string? false)) jsexpr?) (cond [(and (eq? items false) (eq? contents false) (= errno 0)) (error 'get-contents-answer "items and contents must not be empty at the same time")] [(not (= errno 0)) (hasheq 'errno errno)] [(eq? items false) (hasheq 'errno errno 'mtime mtime 'contents contents)] [else (hasheq 'errno errno 'mtime mtime 'items items)])) the value of handler - map must be taking one or two positional arguments . If it takes one argument , url - parts will be converted to a path and passed into the function . If two arguments , ` req ` binding ` data ` will be passed as bytes to the second argument . (define (get-contents-handler req url-parts) (log-rest-info "get-contents-handler ~a" url-parts) (define file-path (apply build-path `(,(current-directory) ,@(filter non-empty-string? url-parts)))) (cond [(directory-exists? file-path) (log-rest-debug "list directory ~a" file-path) (define items (directory-list file-path #:build? false)) (define names (map (lambda (n) (if (directory-exists? (build-path file-path n)) (string-append (path->string n) "/") (path->string n))) items)) (define mtime (file-or-directory-modify-seconds file-path)) (get-contents-answer 0 mtime names)] [(file-exists? file-path) (log-rest-debug "get contents of file ~a" file-path) (define contents (file->string file-path)) (define mtime (file-or-directory-modify-seconds file-path)) (get-contents-answer 0 mtime false contents)] [else (get-contents-answer 1)]))
2e0b2cd7e06e752e9f12ebc077055403d5404360b7dc7c651520c87d1ffecc28
brendanhay/gogol
Patch.hs
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # -- | Module : . . Catalogs . Products . Patch Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) -- -- Updates a specific Product resource. -- /See:/ < -catalog/ Cloud Private Catalog Producer API Reference > for module Gogol.CloudPrivateCatalogProducer.Catalogs.Products.Patch ( -- * Resource CloudPrivateCatalogProducerCatalogsProductsPatchResource, -- ** Constructing a Request CloudPrivateCatalogProducerCatalogsProductsPatch (..), newCloudPrivateCatalogProducerCatalogsProductsPatch, ) where import Gogol.CloudPrivateCatalogProducer.Types import qualified Gogol.Prelude as Core -- | A resource alias for @cloudprivatecatalogproducer.catalogs.products.patch@ method which the -- 'CloudPrivateCatalogProducerCatalogsProductsPatch' request conforms to. type CloudPrivateCatalogProducerCatalogsProductsPatchResource = "v1beta1" Core.:> Core.Capture "name" Core.Text Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "updateMask" Core.FieldMask Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] GoogleCloudPrivatecatalogproducerV1beta1Product Core.:> Core.Patch '[Core.JSON] GoogleCloudPrivatecatalogproducerV1beta1Product -- | Updates a specific Product resource. -- -- /See:/ 'newCloudPrivateCatalogProducerCatalogsProductsPatch' smart constructor. data CloudPrivateCatalogProducerCatalogsProductsPatch = CloudPrivateCatalogProducerCatalogsProductsPatch { -- | V1 error format. xgafv :: (Core.Maybe Xgafv), -- | OAuth access token. accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), | Required . The resource name of the product in the format \`catalogs\/{catalog_id}\/products\/a - z*[a - z0 - 9]\ ' . -- A unique identifier for the product under a catalog , which can not be changed after the product is created . The final segment of the name must between 1 and 256 characters in length . name :: Core.Text, -- | Multipart request metadata. payload :: GoogleCloudPrivatecatalogproducerV1beta1Product, -- | Field mask that controls which fields of the product should be updated. updateMask :: (Core.Maybe Core.FieldMask), | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of with the minimum fields required to make a request . newCloudPrivateCatalogProducerCatalogsProductsPatch :: | Required . The resource name of the product in the format \`catalogs\/{catalog_id}\/products\/a - z*[a - z0 - 9]\ ' . -- A unique identifier for the product under a catalog , which can not be changed after the product is created . The final segment of the name must between 1 and 256 characters in length . See ' name ' . Core.Text -> -- | Multipart request metadata. See 'payload'. GoogleCloudPrivatecatalogproducerV1beta1Product -> CloudPrivateCatalogProducerCatalogsProductsPatch newCloudPrivateCatalogProducerCatalogsProductsPatch name payload = CloudPrivateCatalogProducerCatalogsProductsPatch { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, name = name, payload = payload, updateMask = Core.Nothing, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest CloudPrivateCatalogProducerCatalogsProductsPatch where type Rs CloudPrivateCatalogProducerCatalogsProductsPatch = GoogleCloudPrivatecatalogproducerV1beta1Product type Scopes CloudPrivateCatalogProducerCatalogsProductsPatch = '[CloudPlatform'FullControl] requestClient CloudPrivateCatalogProducerCatalogsProductsPatch {..} = go name xgafv accessToken callback updateMask uploadType uploadProtocol (Core.Just Core.AltJSON) payload cloudPrivateCatalogProducerService where go = Core.buildClient ( Core.Proxy :: Core.Proxy CloudPrivateCatalogProducerCatalogsProductsPatchResource ) Core.mempty
null
https://raw.githubusercontent.com/brendanhay/gogol/77394c4e0f5bd729e6fe27119701c45f9d5e1e9a/lib/services/gogol-cloudprivatecatalogproducer/gen/Gogol/CloudPrivateCatalogProducer/Catalogs/Products/Patch.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated Updates a specific Product resource. * Resource ** Constructing a Request | A resource alias for @cloudprivatecatalogproducer.catalogs.products.patch@ method which the 'CloudPrivateCatalogProducerCatalogsProductsPatch' request conforms to. | Updates a specific Product resource. /See:/ 'newCloudPrivateCatalogProducerCatalogsProductsPatch' smart constructor. | V1 error format. | OAuth access token. | Multipart request metadata. | Field mask that controls which fields of the product should be updated. | Upload protocol for media (e.g. \"raw\", \"multipart\"). | Multipart request metadata. See 'payload'.
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - duplicate - exports # # OPTIONS_GHC -fno - warn - name - shadowing # # OPTIONS_GHC -fno - warn - unused - binds # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Module : . . Catalogs . Products . Patch Copyright : ( c ) 2015 - 2022 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) /See:/ < -catalog/ Cloud Private Catalog Producer API Reference > for module Gogol.CloudPrivateCatalogProducer.Catalogs.Products.Patch CloudPrivateCatalogProducerCatalogsProductsPatchResource, CloudPrivateCatalogProducerCatalogsProductsPatch (..), newCloudPrivateCatalogProducerCatalogsProductsPatch, ) where import Gogol.CloudPrivateCatalogProducer.Types import qualified Gogol.Prelude as Core type CloudPrivateCatalogProducerCatalogsProductsPatchResource = "v1beta1" Core.:> Core.Capture "name" Core.Text Core.:> Core.QueryParam "$.xgafv" Xgafv Core.:> Core.QueryParam "access_token" Core.Text Core.:> Core.QueryParam "callback" Core.Text Core.:> Core.QueryParam "updateMask" Core.FieldMask Core.:> Core.QueryParam "uploadType" Core.Text Core.:> Core.QueryParam "upload_protocol" Core.Text Core.:> Core.QueryParam "alt" Core.AltJSON Core.:> Core.ReqBody '[Core.JSON] GoogleCloudPrivatecatalogproducerV1beta1Product Core.:> Core.Patch '[Core.JSON] GoogleCloudPrivatecatalogproducerV1beta1Product data CloudPrivateCatalogProducerCatalogsProductsPatch = CloudPrivateCatalogProducerCatalogsProductsPatch xgafv :: (Core.Maybe Xgafv), accessToken :: (Core.Maybe Core.Text), | JSONP callback :: (Core.Maybe Core.Text), | Required . The resource name of the product in the format \`catalogs\/{catalog_id}\/products\/a - z*[a - z0 - 9]\ ' . A unique identifier for the product under a catalog , which can not be changed after the product is created . The final segment of the name must between 1 and 256 characters in length . name :: Core.Text, payload :: GoogleCloudPrivatecatalogproducerV1beta1Product, updateMask :: (Core.Maybe Core.FieldMask), | Legacy upload protocol for media ( e.g. \"media\ " , \"multipart\ " ) . uploadType :: (Core.Maybe Core.Text), uploadProtocol :: (Core.Maybe Core.Text) } deriving (Core.Eq, Core.Show, Core.Generic) | Creates a value of with the minimum fields required to make a request . newCloudPrivateCatalogProducerCatalogsProductsPatch :: | Required . The resource name of the product in the format \`catalogs\/{catalog_id}\/products\/a - z*[a - z0 - 9]\ ' . A unique identifier for the product under a catalog , which can not be changed after the product is created . The final segment of the name must between 1 and 256 characters in length . See ' name ' . Core.Text -> GoogleCloudPrivatecatalogproducerV1beta1Product -> CloudPrivateCatalogProducerCatalogsProductsPatch newCloudPrivateCatalogProducerCatalogsProductsPatch name payload = CloudPrivateCatalogProducerCatalogsProductsPatch { xgafv = Core.Nothing, accessToken = Core.Nothing, callback = Core.Nothing, name = name, payload = payload, updateMask = Core.Nothing, uploadType = Core.Nothing, uploadProtocol = Core.Nothing } instance Core.GoogleRequest CloudPrivateCatalogProducerCatalogsProductsPatch where type Rs CloudPrivateCatalogProducerCatalogsProductsPatch = GoogleCloudPrivatecatalogproducerV1beta1Product type Scopes CloudPrivateCatalogProducerCatalogsProductsPatch = '[CloudPlatform'FullControl] requestClient CloudPrivateCatalogProducerCatalogsProductsPatch {..} = go name xgafv accessToken callback updateMask uploadType uploadProtocol (Core.Just Core.AltJSON) payload cloudPrivateCatalogProducerService where go = Core.buildClient ( Core.Proxy :: Core.Proxy CloudPrivateCatalogProducerCatalogsProductsPatchResource ) Core.mempty
2f4d413def326b6ffd5d31a6d9d6d9f168096c42066000e0ee95c23ae7e4a5c2
racket/gui
const.rkt
#lang racket/base (provide (except-out (all-defined-out) <<)) (define GTK_WINDOW_TOPLEVEL 0) (define GTK_WINDOW_POPUP 1) (define << arithmetic-shift) (define GDK_EXPOSURE_MASK (1 . << . 1)) (define GDK_POINTER_MOTION_MASK (1 . << . 2)) (define GDK_POINTER_MOTION_HINT_MASK (1 . << . 3)) (define GDK_BUTTON_MOTION_MASK (1 . << . 4)) (define GDK_BUTTON1_MOTION_MASK (1 . << . 5)) (define GDK_BUTTON2_MOTION_MASK (1 . << . 6)) (define GDK_BUTTON3_MOTION_MASK (1 . << . 7)) (define GDK_BUTTON_PRESS_MASK (1 . << . 8)) (define GDK_BUTTON_RELEASE_MASK (1 . << . 9)) (define GDK_KEY_PRESS_MASK (1 . << . 10)) (define GDK_KEY_RELEASE_MASK (1 . << . 11)) (define GDK_ENTER_NOTIFY_MASK (1 . << . 12)) (define GDK_LEAVE_NOTIFY_MASK (1 . << . 13)) (define GDK_FOCUS_CHANGE_MASK (1 . << . 14)) (define GDK_STRUCTURE_MASK (1 . << . 15)) (define GDK_PROPERTY_CHANGE_MASK (1 . << . 16)) (define GDK_VISIBILITY_NOTIFY_MASK (1 . << . 17)) (define GDK_PROXIMITY_IN_MASK (1 . << . 18)) (define GDK_PROXIMITY_OUT_MASK (1 . << . 19)) (define GDK_SUBSTRUCTURE_MASK (1 . << . 20)) (define GDK_SCROLL_MASK (1 . << . 21)) (define GDK_SMOOTH_SCROLL_MASK (1 . << . 23)) ; added in v3.4 ( define GDK_ALL_EVENTS_MASK # x3FFFFE ) - as of 2.0 , but # x3FFFFFE as of 3.22 (define GTK_TOPLEVEL (1 . << . 4)) (define GTK_NO_WINDOW (1 . << . 5)) (define GTK_REALIZED (1 . << . 6)) (define GTK_MAPPED (1 . << . 7)) (define GTK_VISIBLE (1 . << . 8)) (define GTK_SENSITIVE (1 . << . 9)) (define GTK_PARENT_SENSITIVE (1 . << . 10)) (define GTK_CAN_FOCUS (1 . << . 11)) (define GTK_HAS_FOCUS (1 . << . 12)) (define GTK_CAN_DEFAULT (1 . << . 13)) (define GTK_HAS_DEFAULT (1 . << . 14)) (define GTK_HAS_GRAB (1 . << . 15)) (define GTK_RC_STYLE (1 . << . 16)) (define GTK_COMPOSITE_CHILD (1 . << . 17)) (define GTK_NO_REPARENT (1 . << . 18)) (define GTK_APP_PAINTABLE (1 . << . 19)) (define GTK_RECEIVES_DEFAULT (1 . << . 20)) (define GTK_DOUBLE_BUFFERED (1 . << . 21)) (define GTK_NO_SHOW_ALL (1 . << . 22)) (define GDK_SHIFT_MASK (1 . << . 0)) (define GDK_LOCK_MASK (1 . << . 1)) (define GDK_CONTROL_MASK (1 . << . 2)) (define GDK_MOD1_MASK (1 . << . 3)) (define GDK_MOD2_MASK (1 . << . 4)) (define GDK_MOD3_MASK (1 . << . 5)) (define GDK_MOD4_MASK (1 . << . 6)) (define GDK_MOD5_MASK (1 . << . 7)) (define GDK_BUTTON1_MASK (1 . << . 8)) (define GDK_BUTTON2_MASK (1 . << . 9)) (define GDK_BUTTON3_MASK (1 . << . 10)) (define GDK_BUTTON4_MASK (1 . << . 11)) (define GDK_BUTTON5_MASK (1 . << . 12)) (define GDK_SUPER_MASK (1 . << . 26)) (define GDK_HYPER_MASK (1 . << . 27)) (define GDK_META_MASK (1 . << . 28)) (define GDK_RELEASE_MASK (1 . << . 30)) (define GDK_NOTHING -1) (define GDK_DELETE 0) (define GDK_DESTROY 1) (define GDK_EXPOSE 2) (define GDK_MOTION_NOTIFY 3) (define GDK_BUTTON_PRESS 4) (define GDK_2BUTTON_PRESS 5) (define GDK_3BUTTON_PRESS 6) (define GDK_BUTTON_RELEASE 7) (define GDK_KEY_PRESS 8) (define GDK_KEY_RELEASE 9) (define GDK_ENTER_NOTIFY 10) (define GDK_LEAVE_NOTIFY 11) (define GDK_FOCUS_CHANGE 12) (define GDK_CONFIGURE 13) (define GDK_MAP 14) (define GDK_UNMAP 15) (define GDK_PROPERTY_NOTIFY 16) (define GDK_SELECTION_CLEAR 17) (define GDK_SELECTION_REQUEST 18) (define GDK_SELECTION_NOTIFY 19) (define GDK_PROXIMITY_IN 20) (define GDK_PROXIMITY_OUT 21) (define GDK_DRAG_ENTER 22) (define GDK_DRAG_LEAVE 23) (define GDK_DRAG_MOTION 24) (define GDK_DRAG_STATUS 25) (define GDK_DROP_START 26) (define GDK_DROP_FINISHED 27) (define GDK_CLIENT_EVENT 28) (define GDK_VISIBILITY_NOTIFY 29) (define GDK_NO_EXPOSE 30) (define GDK_SCROLL 31) (define GDK_WINDOW_STATE 32) (define GDK_SETTING 33) (define GDK_OWNER_CHANGE 34) (define GDK_GRAB_BROKEN 35) (define GDK_DAMAGE 36) (define G_TYPE_STRING (16 . << . 2)) (define GTK_POLICY_ALWAYS 0) (define GTK_POLICY_AUTOMATIC 1) (define GTK_POLICY_NEVER 2) (define GDK_WINDOW_STATE_WITHDRAWN (1 . << . 0)) (define GDK_WINDOW_STATE_ICONIFIED (1 . << . 1)) (define GDK_WINDOW_STATE_MAXIMIZED (1 . << . 2)) (define GDK_WINDOW_STATE_STICKY (1 . << . 3)) (define GDK_WINDOW_STATE_FULLSCREEN (1 . << . 4)) (define GDK_WINDOW_STATE_ABOVE (1 . << . 5)) (define GDK_WINDOW_STATE_BELOW (1 . << . 6)) (define GDK_HINT_POS (1 . << . 0)) (define GDK_HINT_MIN_SIZE (1 . << . 1)) (define GDK_HINT_MAX_SIZE (1 . << . 2)) (define GDK_HINT_BASE_SIZE (1 . << . 3)) (define GDK_HINT_ASPECT (1 . << . 4)) (define GDK_HINT_RESIZE_INC (1 . << . 5)) (define GDK_HINT_WIN_GRAVITY (1 . << . 6)) (define GDK_HINT_USER_POS (1 . << . 7)) (define GDK_HINT_USER_SIZE (1 . << . 8)) (define GDK_SCROLL_UP 0) (define GDK_SCROLL_DOWN 1) (define GDK_SCROLL_LEFT 2) (define GDK_SCROLL_RIGHT 3) (define GDK_SCROLL_SMOOTH 4)
null
https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mred/private/wx/gtk/const.rkt
racket
added in v3.4
#lang racket/base (provide (except-out (all-defined-out) <<)) (define GTK_WINDOW_TOPLEVEL 0) (define GTK_WINDOW_POPUP 1) (define << arithmetic-shift) (define GDK_EXPOSURE_MASK (1 . << . 1)) (define GDK_POINTER_MOTION_MASK (1 . << . 2)) (define GDK_POINTER_MOTION_HINT_MASK (1 . << . 3)) (define GDK_BUTTON_MOTION_MASK (1 . << . 4)) (define GDK_BUTTON1_MOTION_MASK (1 . << . 5)) (define GDK_BUTTON2_MOTION_MASK (1 . << . 6)) (define GDK_BUTTON3_MOTION_MASK (1 . << . 7)) (define GDK_BUTTON_PRESS_MASK (1 . << . 8)) (define GDK_BUTTON_RELEASE_MASK (1 . << . 9)) (define GDK_KEY_PRESS_MASK (1 . << . 10)) (define GDK_KEY_RELEASE_MASK (1 . << . 11)) (define GDK_ENTER_NOTIFY_MASK (1 . << . 12)) (define GDK_LEAVE_NOTIFY_MASK (1 . << . 13)) (define GDK_FOCUS_CHANGE_MASK (1 . << . 14)) (define GDK_STRUCTURE_MASK (1 . << . 15)) (define GDK_PROPERTY_CHANGE_MASK (1 . << . 16)) (define GDK_VISIBILITY_NOTIFY_MASK (1 . << . 17)) (define GDK_PROXIMITY_IN_MASK (1 . << . 18)) (define GDK_PROXIMITY_OUT_MASK (1 . << . 19)) (define GDK_SUBSTRUCTURE_MASK (1 . << . 20)) (define GDK_SCROLL_MASK (1 . << . 21)) ( define GDK_ALL_EVENTS_MASK # x3FFFFE ) - as of 2.0 , but # x3FFFFFE as of 3.22 (define GTK_TOPLEVEL (1 . << . 4)) (define GTK_NO_WINDOW (1 . << . 5)) (define GTK_REALIZED (1 . << . 6)) (define GTK_MAPPED (1 . << . 7)) (define GTK_VISIBLE (1 . << . 8)) (define GTK_SENSITIVE (1 . << . 9)) (define GTK_PARENT_SENSITIVE (1 . << . 10)) (define GTK_CAN_FOCUS (1 . << . 11)) (define GTK_HAS_FOCUS (1 . << . 12)) (define GTK_CAN_DEFAULT (1 . << . 13)) (define GTK_HAS_DEFAULT (1 . << . 14)) (define GTK_HAS_GRAB (1 . << . 15)) (define GTK_RC_STYLE (1 . << . 16)) (define GTK_COMPOSITE_CHILD (1 . << . 17)) (define GTK_NO_REPARENT (1 . << . 18)) (define GTK_APP_PAINTABLE (1 . << . 19)) (define GTK_RECEIVES_DEFAULT (1 . << . 20)) (define GTK_DOUBLE_BUFFERED (1 . << . 21)) (define GTK_NO_SHOW_ALL (1 . << . 22)) (define GDK_SHIFT_MASK (1 . << . 0)) (define GDK_LOCK_MASK (1 . << . 1)) (define GDK_CONTROL_MASK (1 . << . 2)) (define GDK_MOD1_MASK (1 . << . 3)) (define GDK_MOD2_MASK (1 . << . 4)) (define GDK_MOD3_MASK (1 . << . 5)) (define GDK_MOD4_MASK (1 . << . 6)) (define GDK_MOD5_MASK (1 . << . 7)) (define GDK_BUTTON1_MASK (1 . << . 8)) (define GDK_BUTTON2_MASK (1 . << . 9)) (define GDK_BUTTON3_MASK (1 . << . 10)) (define GDK_BUTTON4_MASK (1 . << . 11)) (define GDK_BUTTON5_MASK (1 . << . 12)) (define GDK_SUPER_MASK (1 . << . 26)) (define GDK_HYPER_MASK (1 . << . 27)) (define GDK_META_MASK (1 . << . 28)) (define GDK_RELEASE_MASK (1 . << . 30)) (define GDK_NOTHING -1) (define GDK_DELETE 0) (define GDK_DESTROY 1) (define GDK_EXPOSE 2) (define GDK_MOTION_NOTIFY 3) (define GDK_BUTTON_PRESS 4) (define GDK_2BUTTON_PRESS 5) (define GDK_3BUTTON_PRESS 6) (define GDK_BUTTON_RELEASE 7) (define GDK_KEY_PRESS 8) (define GDK_KEY_RELEASE 9) (define GDK_ENTER_NOTIFY 10) (define GDK_LEAVE_NOTIFY 11) (define GDK_FOCUS_CHANGE 12) (define GDK_CONFIGURE 13) (define GDK_MAP 14) (define GDK_UNMAP 15) (define GDK_PROPERTY_NOTIFY 16) (define GDK_SELECTION_CLEAR 17) (define GDK_SELECTION_REQUEST 18) (define GDK_SELECTION_NOTIFY 19) (define GDK_PROXIMITY_IN 20) (define GDK_PROXIMITY_OUT 21) (define GDK_DRAG_ENTER 22) (define GDK_DRAG_LEAVE 23) (define GDK_DRAG_MOTION 24) (define GDK_DRAG_STATUS 25) (define GDK_DROP_START 26) (define GDK_DROP_FINISHED 27) (define GDK_CLIENT_EVENT 28) (define GDK_VISIBILITY_NOTIFY 29) (define GDK_NO_EXPOSE 30) (define GDK_SCROLL 31) (define GDK_WINDOW_STATE 32) (define GDK_SETTING 33) (define GDK_OWNER_CHANGE 34) (define GDK_GRAB_BROKEN 35) (define GDK_DAMAGE 36) (define G_TYPE_STRING (16 . << . 2)) (define GTK_POLICY_ALWAYS 0) (define GTK_POLICY_AUTOMATIC 1) (define GTK_POLICY_NEVER 2) (define GDK_WINDOW_STATE_WITHDRAWN (1 . << . 0)) (define GDK_WINDOW_STATE_ICONIFIED (1 . << . 1)) (define GDK_WINDOW_STATE_MAXIMIZED (1 . << . 2)) (define GDK_WINDOW_STATE_STICKY (1 . << . 3)) (define GDK_WINDOW_STATE_FULLSCREEN (1 . << . 4)) (define GDK_WINDOW_STATE_ABOVE (1 . << . 5)) (define GDK_WINDOW_STATE_BELOW (1 . << . 6)) (define GDK_HINT_POS (1 . << . 0)) (define GDK_HINT_MIN_SIZE (1 . << . 1)) (define GDK_HINT_MAX_SIZE (1 . << . 2)) (define GDK_HINT_BASE_SIZE (1 . << . 3)) (define GDK_HINT_ASPECT (1 . << . 4)) (define GDK_HINT_RESIZE_INC (1 . << . 5)) (define GDK_HINT_WIN_GRAVITY (1 . << . 6)) (define GDK_HINT_USER_POS (1 . << . 7)) (define GDK_HINT_USER_SIZE (1 . << . 8)) (define GDK_SCROLL_UP 0) (define GDK_SCROLL_DOWN 1) (define GDK_SCROLL_LEFT 2) (define GDK_SCROLL_RIGHT 3) (define GDK_SCROLL_SMOOTH 4)
27349b47e36b19d086043d20028da55c4519fc341c22ad938a1d349b4e78e637
CarlosMChica/HaskellBook
Main.hs
module Main where import Lib import System.IO main :: IO () main = do hSetBuffering stdout NoBuffering word <- randomWord' runGame $ freshPuzzle word
null
https://raw.githubusercontent.com/CarlosMChica/HaskellBook/86f82cf36cd00003b1a1aebf264e4b5d606ddfad/chapter14/hangman/app/Main.hs
haskell
module Main where import Lib import System.IO main :: IO () main = do hSetBuffering stdout NoBuffering word <- randomWord' runGame $ freshPuzzle word
585b2cad572bb77e1e508deb2e52189be5a25102cffe1c7cb592c2a44c8cd200
dbuenzli/remat
locv.mli
--------------------------------------------------------------------------- Copyright ( c ) 2015 . All rights reserved . Distributed under the BSD3 license , see license at the end of the file . % % NAME%% release % % --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. Bünzli. All rights reserved. Distributed under the BSD3 license, see license at the end of the file. %%NAME%% release %%VERSION%% ---------------------------------------------------------------------------*) (** Localized values and messages. *) * { 1 Localized values } type 'a t (** The type for localized values of type ['a]. Localized value bind language {{!Lang.range}ranges} to values. *) val empty : 'a t (** [v value] is an empty localized value. *) val is_empty : 'a t -> bool (** [is_empty lv] is [true] iff [lv] is empty. *) val any : 'a -> 'a t * [ any v ] is a localized value with [ v ] mapping to { ! } . val add : 'a t -> Nlang.range -> 'a -> 'a t (** [add lv r v] is [lv] with [r] bound to [v]. *) val rem : 'a t -> Nlang.range -> 'a t (** [rem lv r] is [lv] without [r]'s binding. *) val mem : Nlang.range -> 'a t -> bool (** [mem lv r] is [true] if [lv] has a binding for [r]. *) val find : Nlang.t -> 'a t -> 'a option * [ find l lv ] get a localized value for locale [ l ] in [ lv ] ( if any ) . The algorithm looks for ranges that are matching [ l ] in [ lv ] selects the most precise one , that is the range with most subtags and if there are ties the greatest one according to { ! } . { b Note . } RFC 4647 defines no algorithm to lookup a language range with a language tag , hence the above definition . FIXME review RFC 4647 did you miss something ? The algorithm looks for ranges that are matching [l] in [lv] selects the most precise one, that is the range with most subtags and if there are ties the greatest one according to {!Nlang.Range.compare}. {b Note.} RFC 4647 defines no algorithm to lookup a language range with a language tag, hence the above definition. FIXME review RFC 4647 did you miss something ? *) val find_range : Nlang.t -> 'a t -> Nlang.range option (** [find_range l lv] is the range matched by [l] in [lv] (if any). *) val get : Nlang.t -> 'a t -> 'a (** [get l lv] is like {!find} but @raise Invalid_argument if [l] doesn't match in [lv]. *) val get_range : Nlang.t -> 'a t -> Nlang.range (** [get_range l lv] is like {!find_range} but @raise Invalid_argument if [l] doesn't match in lv. *) val fold : ('b -> Nlang.range -> 'a -> 'b) -> 'b -> 'a t -> 'b (** [ized_fold f acc lv] folds over the bindings of [lv] with [f] starting with [acc]. *) val of_list : (Nlang.range * 'a) list -> 'a t (** [ized_of_list bs] is a localized value from the bindings [bs]. *) val to_list : 'a t -> (Nlang.range * 'a) list (** [ized_to_list lv] is the list of bindings of [lv]. *) * { 1 Localized messages } (** Formatting messages. {b TODO.} Functional unparsing API. *) module Msg : sig type t (** The type for messages. *) val v : string -> t (** [v msg] is a message from [v]. *) val get : t -> string (** [get m] is the message [m]. *) val of_string : string -> [ `Ok of t | `Error of string ] (** [of_string] is like {!v} but returns an [`Error] when parsing fails. *) val to_string : t -> string (** [to_string m] is [m] as a string. *) type map (** The type for message maps. *) module Map : sig type msg = t type key = string type t = map val empty : Nlang.range -> t val locale : t -> Nlang.range val add : map -> key -> msg -> t val rem : map -> key -> map val mem : map -> key -> bool val get : ?absent:msg -> map -> key -> msg val fold : ('b -> key -> msg -> 'b) -> 'b -> map -> 'b end end type msgs = Msg.map t --------------------------------------------------------------------------- Copyright ( c ) 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 nor the names of 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 OWNER OR 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 . --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. Bünzli. 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 Daniel C. Bünzli nor the names of 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 OWNER OR CONTRIBUTORS BE 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. ---------------------------------------------------------------------------*)
null
https://raw.githubusercontent.com/dbuenzli/remat/28d572e77bbd1ad46bbfde87c0ba8bd0ab99ed28/src-www/locv.mli
ocaml
* Localized values and messages. * The type for localized values of type ['a]. Localized value bind language {{!Lang.range}ranges} to values. * [v value] is an empty localized value. * [is_empty lv] is [true] iff [lv] is empty. * [add lv r v] is [lv] with [r] bound to [v]. * [rem lv r] is [lv] without [r]'s binding. * [mem lv r] is [true] if [lv] has a binding for [r]. * [find_range l lv] is the range matched by [l] in [lv] (if any). * [get l lv] is like {!find} but @raise Invalid_argument if [l] doesn't match in [lv]. * [get_range l lv] is like {!find_range} but @raise Invalid_argument if [l] doesn't match in lv. * [ized_fold f acc lv] folds over the bindings of [lv] with [f] starting with [acc]. * [ized_of_list bs] is a localized value from the bindings [bs]. * [ized_to_list lv] is the list of bindings of [lv]. * Formatting messages. {b TODO.} Functional unparsing API. * The type for messages. * [v msg] is a message from [v]. * [get m] is the message [m]. * [of_string] is like {!v} but returns an [`Error] when parsing fails. * [to_string m] is [m] as a string. * The type for message maps.
--------------------------------------------------------------------------- Copyright ( c ) 2015 . All rights reserved . Distributed under the BSD3 license , see license at the end of the file . % % NAME%% release % % --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. Bünzli. All rights reserved. Distributed under the BSD3 license, see license at the end of the file. %%NAME%% release %%VERSION%% ---------------------------------------------------------------------------*) * { 1 Localized values } type 'a t val empty : 'a t val is_empty : 'a t -> bool val any : 'a -> 'a t * [ any v ] is a localized value with [ v ] mapping to { ! } . val add : 'a t -> Nlang.range -> 'a -> 'a t val rem : 'a t -> Nlang.range -> 'a t val mem : Nlang.range -> 'a t -> bool val find : Nlang.t -> 'a t -> 'a option * [ find l lv ] get a localized value for locale [ l ] in [ lv ] ( if any ) . The algorithm looks for ranges that are matching [ l ] in [ lv ] selects the most precise one , that is the range with most subtags and if there are ties the greatest one according to { ! } . { b Note . } RFC 4647 defines no algorithm to lookup a language range with a language tag , hence the above definition . FIXME review RFC 4647 did you miss something ? The algorithm looks for ranges that are matching [l] in [lv] selects the most precise one, that is the range with most subtags and if there are ties the greatest one according to {!Nlang.Range.compare}. {b Note.} RFC 4647 defines no algorithm to lookup a language range with a language tag, hence the above definition. FIXME review RFC 4647 did you miss something ? *) val find_range : Nlang.t -> 'a t -> Nlang.range option val get : Nlang.t -> 'a t -> 'a val get_range : Nlang.t -> 'a t -> Nlang.range val fold : ('b -> Nlang.range -> 'a -> 'b) -> 'b -> 'a t -> 'b val of_list : (Nlang.range * 'a) list -> 'a t val to_list : 'a t -> (Nlang.range * 'a) list * { 1 Localized messages } module Msg : sig type t val v : string -> t val get : t -> string val of_string : string -> [ `Ok of t | `Error of string ] val to_string : t -> string type map module Map : sig type msg = t type key = string type t = map val empty : Nlang.range -> t val locale : t -> Nlang.range val add : map -> key -> msg -> t val rem : map -> key -> map val mem : map -> key -> bool val get : ?absent:msg -> map -> key -> msg val fold : ('b -> key -> msg -> 'b) -> 'b -> map -> 'b end end type msgs = Msg.map t --------------------------------------------------------------------------- Copyright ( c ) 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 nor the names of 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 OWNER OR 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 . --------------------------------------------------------------------------- Copyright (c) 2015 Daniel C. Bünzli. 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 Daniel C. Bünzli nor the names of 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 OWNER OR CONTRIBUTORS BE 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. ---------------------------------------------------------------------------*)
3d5c33b724eac9ade898188129d42820cc5f98ecc79b2e3637650973007d4794
erlang/otp
tftp_binary.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2005 - 2023 . 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. %% %% %CopyrightEnd% %% %% %%%------------------------------------------------------------------- %%% File : tft_binary.erl Author : < > %%% Description : %%% Created : 24 May 2004 by < > %%%------------------------------------------------------------------- -module(tftp_binary). %%%------------------------------------------------------------------- Interface %%%------------------------------------------------------------------- -behaviour(tftp). -export([prepare/6, open/6, read/1, write/2, abort/3]). -record(read_state, {options, blksize, bin, is_native_ascii, is_network_ascii, count}). -record(write_state, {options, blksize, list, is_native_ascii, is_network_ascii}). %%------------------------------------------------------------------- %% Prepare %%------------------------------------------------------------------- prepare(_Peer, Access, Filename, Mode, SuggestedOptions, Initial) when is_list(Initial) -> %% Client side IsNativeAscii = is_native_ascii(Initial), case catch handle_options(Access, Filename, Mode, SuggestedOptions, IsNativeAscii) of {ok, IsNetworkAscii, AcceptedOptions} when Access =:= read, is_binary(Filename) -> State = #read_state{options = AcceptedOptions, blksize = lookup_blksize(AcceptedOptions), bin = Filename, is_network_ascii = IsNetworkAscii, count = byte_size(Filename), is_native_ascii = IsNativeAscii}, {ok, AcceptedOptions, State}; {ok, IsNetworkAscii, AcceptedOptions} when Access =:= write, Filename =:= binary -> State = #write_state{options = AcceptedOptions, blksize = lookup_blksize(AcceptedOptions), list = [], is_network_ascii = IsNetworkAscii, is_native_ascii = IsNativeAscii}, {ok, AcceptedOptions, State}; {ok, _, _} -> {error, {undef, "Illegal callback usage. Mode and filename is incompatible."}}; {error, {Code, Text}} -> {error, {Code, Text}} end; prepare(_Peer, _Access, _Bin, _Mode, _SuggestedOptions, _Initial) -> {error, {undef, "Illegal callback options."}}. %%------------------------------------------------------------------- %% Open %%------------------------------------------------------------------- open(Peer, Access, Filename, Mode, SuggestedOptions, Initial) when is_list(Initial) -> %% Server side case prepare(Peer, Access, Filename, Mode, SuggestedOptions, Initial) of {ok, AcceptedOptions, State} -> open(Peer, Access, Filename, Mode, AcceptedOptions, State); {error, {Code, Text}} -> {error, {Code, Text}} end; open(_Peer, Access, Filename, Mode, NegotiatedOptions, State) when is_record(State, read_state) -> %% Both sides case catch handle_options(Access, Filename, Mode, NegotiatedOptions, State#read_state.is_native_ascii) of {ok, IsNetworkAscii, Options} when Options =:= NegotiatedOptions, IsNetworkAscii =:= State#read_state.is_network_ascii -> {ok, NegotiatedOptions, State}; {error, {Code, Text}} -> {error, {Code, Text}} end; open(_Peer, Access, Filename, Mode, NegotiatedOptions, State) when is_record(State, write_state) -> %% Both sides case catch handle_options(Access, Filename, Mode, NegotiatedOptions, State#write_state.is_native_ascii) of {ok, IsNetworkAscii, Options} when Options =:= NegotiatedOptions, IsNetworkAscii =:= State#write_state.is_network_ascii -> {ok, NegotiatedOptions, State}; {error, {Code, Text}} -> {error, {Code, Text}} end; open(Peer, Access, Filename, Mode, NegotiatedOptions, State) -> %% Handle upgrade from old releases. Please, remove this clause in next release. State2 = upgrade_state(State), open(Peer, Access, Filename, Mode, NegotiatedOptions, State2). %%------------------------------------------------------------------- %% Read %%------------------------------------------------------------------- read(#read_state{bin = Bin} = State) when is_binary(Bin) -> BlkSize = State#read_state.blksize, if byte_size(Bin) >= BlkSize -> <<Block:BlkSize/binary, Bin2/binary>> = Bin, State2 = State#read_state{bin = Bin2}, {more, Block, State2}; byte_size(Bin) < BlkSize -> {last, Bin, State#read_state.count} end; read(State) -> %% Handle upgrade from old releases. Please, remove this clause in next release. State2 = upgrade_state(State), read(State2). %%------------------------------------------------------------------- %% Write %%------------------------------------------------------------------- write(Bin, #write_state{list = List} = State) when is_binary(Bin), is_list(List) -> Size = byte_size(Bin), BlkSize = State#write_state.blksize, if Size =:= BlkSize -> {more, State#write_state{list = [Bin | List]}}; Size < BlkSize -> Bin2 = list_to_binary(lists:reverse([Bin | List])), {last, Bin2} end; write(Bin, State) -> %% Handle upgrade from old releases. Please, remove this clause in next release. State2 = upgrade_state(State), write(Bin, State2). %%------------------------------------------------------------------- %% Abort %%------------------------------------------------------------------- abort(_Code, _Text, #read_state{bin = Bin} = State) when is_record(State, read_state), is_binary(Bin) -> ok; abort(_Code, _Text, #write_state{list = List} = State) when is_record(State, write_state), is_list(List) -> ok; abort(Code, Text, State) -> %% Handle upgrade from old releases. Please, remove this clause in next release. State2 = upgrade_state(State), abort(Code, Text, State2). %%------------------------------------------------------------------- %% Process options %%------------------------------------------------------------------- handle_options(Access, Bin, Mode, Options, IsNativeAscii) -> IsNetworkAscii = handle_mode(Mode, IsNativeAscii), Options2 = do_handle_options(Access, Bin, Options), {ok, IsNetworkAscii, Options2}. handle_mode(Mode, IsNativeAscii) -> case Mode of "netascii" when IsNativeAscii =:= true -> true; "octet" -> false; _ -> throw({error, {badop, "Illegal mode " ++ Mode}}) end. do_handle_options(Access, Bin, [{Key, Val} | T]) -> case Key of "tsize" -> case Access of read when Val =:= "0", is_binary(Bin) -> Tsize = integer_to_list(byte_size(Bin)), [{Key, Tsize} | do_handle_options(Access, Bin, T)]; _ -> handle_integer(Access, Bin, Key, Val, T, 0, infinity) end; "blksize" -> handle_integer(Access, Bin, Key, Val, T, 8, 65464); "timeout" -> handle_integer(Access, Bin, Key, Val, T, 1, 255); _ -> do_handle_options(Access, Bin, T) end; do_handle_options(_Access, _Bin, []) -> []. handle_integer(Access, Bin, Key, Val, Options, Min, Max) -> case catch list_to_integer(Val) of {'EXIT', _} -> do_handle_options(Access, Bin, Options); Int when Int >= Min, Int =< Max -> [{Key, Val} | do_handle_options(Access, Bin, Options)]; Int when Int >= Min, Max =:= infinity -> [{Key, Val} | do_handle_options(Access, Bin, Options)]; _Int -> throw({error, {badopt, "Illegal " ++ Key ++ " value " ++ Val}}) end. lookup_blksize(Options) -> case lists:keysearch("blksize", 1, Options) of {value, {_, Val}} -> list_to_integer(Val); false -> 512 end. is_native_ascii([]) -> is_native_ascii(); is_native_ascii([{native_ascii, Bool}]) -> case Bool of true -> true; false -> false end. is_native_ascii() -> case os:type() of {win32, _} -> true; _ -> false end. %% Handle upgrade from old releases. Please, remove this function in next release. upgrade_state({read_state, Options, Blksize, Bin, IsNetworkAscii, Count}) -> {read_state, Options, Blksize, Bin, false, IsNetworkAscii, Count}; upgrade_state({write_state, Options, Blksize, List, IsNetworkAscii}) -> {write_state, Options, Blksize, List, false, IsNetworkAscii}.
null
https://raw.githubusercontent.com/erlang/otp/2b397d7e5580480dc32fa9751db95f4b89ff029e/lib/tftp/src/tftp_binary.erl
erlang
%CopyrightBegin% 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. %CopyrightEnd% ------------------------------------------------------------------- File : tft_binary.erl Description : ------------------------------------------------------------------- ------------------------------------------------------------------- ------------------------------------------------------------------- ------------------------------------------------------------------- Prepare ------------------------------------------------------------------- Client side ------------------------------------------------------------------- Open ------------------------------------------------------------------- Server side Both sides Both sides Handle upgrade from old releases. Please, remove this clause in next release. ------------------------------------------------------------------- Read ------------------------------------------------------------------- Handle upgrade from old releases. Please, remove this clause in next release. ------------------------------------------------------------------- Write ------------------------------------------------------------------- Handle upgrade from old releases. Please, remove this clause in next release. ------------------------------------------------------------------- Abort ------------------------------------------------------------------- Handle upgrade from old releases. Please, remove this clause in next release. ------------------------------------------------------------------- Process options ------------------------------------------------------------------- Handle upgrade from old releases. Please, remove this function in next release.
Copyright Ericsson AB 2005 - 2023 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , Author : < > Created : 24 May 2004 by < > -module(tftp_binary). Interface -behaviour(tftp). -export([prepare/6, open/6, read/1, write/2, abort/3]). -record(read_state, {options, blksize, bin, is_native_ascii, is_network_ascii, count}). -record(write_state, {options, blksize, list, is_native_ascii, is_network_ascii}). prepare(_Peer, Access, Filename, Mode, SuggestedOptions, Initial) when is_list(Initial) -> IsNativeAscii = is_native_ascii(Initial), case catch handle_options(Access, Filename, Mode, SuggestedOptions, IsNativeAscii) of {ok, IsNetworkAscii, AcceptedOptions} when Access =:= read, is_binary(Filename) -> State = #read_state{options = AcceptedOptions, blksize = lookup_blksize(AcceptedOptions), bin = Filename, is_network_ascii = IsNetworkAscii, count = byte_size(Filename), is_native_ascii = IsNativeAscii}, {ok, AcceptedOptions, State}; {ok, IsNetworkAscii, AcceptedOptions} when Access =:= write, Filename =:= binary -> State = #write_state{options = AcceptedOptions, blksize = lookup_blksize(AcceptedOptions), list = [], is_network_ascii = IsNetworkAscii, is_native_ascii = IsNativeAscii}, {ok, AcceptedOptions, State}; {ok, _, _} -> {error, {undef, "Illegal callback usage. Mode and filename is incompatible."}}; {error, {Code, Text}} -> {error, {Code, Text}} end; prepare(_Peer, _Access, _Bin, _Mode, _SuggestedOptions, _Initial) -> {error, {undef, "Illegal callback options."}}. open(Peer, Access, Filename, Mode, SuggestedOptions, Initial) when is_list(Initial) -> case prepare(Peer, Access, Filename, Mode, SuggestedOptions, Initial) of {ok, AcceptedOptions, State} -> open(Peer, Access, Filename, Mode, AcceptedOptions, State); {error, {Code, Text}} -> {error, {Code, Text}} end; open(_Peer, Access, Filename, Mode, NegotiatedOptions, State) when is_record(State, read_state) -> case catch handle_options(Access, Filename, Mode, NegotiatedOptions, State#read_state.is_native_ascii) of {ok, IsNetworkAscii, Options} when Options =:= NegotiatedOptions, IsNetworkAscii =:= State#read_state.is_network_ascii -> {ok, NegotiatedOptions, State}; {error, {Code, Text}} -> {error, {Code, Text}} end; open(_Peer, Access, Filename, Mode, NegotiatedOptions, State) when is_record(State, write_state) -> case catch handle_options(Access, Filename, Mode, NegotiatedOptions, State#write_state.is_native_ascii) of {ok, IsNetworkAscii, Options} when Options =:= NegotiatedOptions, IsNetworkAscii =:= State#write_state.is_network_ascii -> {ok, NegotiatedOptions, State}; {error, {Code, Text}} -> {error, {Code, Text}} end; open(Peer, Access, Filename, Mode, NegotiatedOptions, State) -> State2 = upgrade_state(State), open(Peer, Access, Filename, Mode, NegotiatedOptions, State2). read(#read_state{bin = Bin} = State) when is_binary(Bin) -> BlkSize = State#read_state.blksize, if byte_size(Bin) >= BlkSize -> <<Block:BlkSize/binary, Bin2/binary>> = Bin, State2 = State#read_state{bin = Bin2}, {more, Block, State2}; byte_size(Bin) < BlkSize -> {last, Bin, State#read_state.count} end; read(State) -> State2 = upgrade_state(State), read(State2). write(Bin, #write_state{list = List} = State) when is_binary(Bin), is_list(List) -> Size = byte_size(Bin), BlkSize = State#write_state.blksize, if Size =:= BlkSize -> {more, State#write_state{list = [Bin | List]}}; Size < BlkSize -> Bin2 = list_to_binary(lists:reverse([Bin | List])), {last, Bin2} end; write(Bin, State) -> State2 = upgrade_state(State), write(Bin, State2). abort(_Code, _Text, #read_state{bin = Bin} = State) when is_record(State, read_state), is_binary(Bin) -> ok; abort(_Code, _Text, #write_state{list = List} = State) when is_record(State, write_state), is_list(List) -> ok; abort(Code, Text, State) -> State2 = upgrade_state(State), abort(Code, Text, State2). handle_options(Access, Bin, Mode, Options, IsNativeAscii) -> IsNetworkAscii = handle_mode(Mode, IsNativeAscii), Options2 = do_handle_options(Access, Bin, Options), {ok, IsNetworkAscii, Options2}. handle_mode(Mode, IsNativeAscii) -> case Mode of "netascii" when IsNativeAscii =:= true -> true; "octet" -> false; _ -> throw({error, {badop, "Illegal mode " ++ Mode}}) end. do_handle_options(Access, Bin, [{Key, Val} | T]) -> case Key of "tsize" -> case Access of read when Val =:= "0", is_binary(Bin) -> Tsize = integer_to_list(byte_size(Bin)), [{Key, Tsize} | do_handle_options(Access, Bin, T)]; _ -> handle_integer(Access, Bin, Key, Val, T, 0, infinity) end; "blksize" -> handle_integer(Access, Bin, Key, Val, T, 8, 65464); "timeout" -> handle_integer(Access, Bin, Key, Val, T, 1, 255); _ -> do_handle_options(Access, Bin, T) end; do_handle_options(_Access, _Bin, []) -> []. handle_integer(Access, Bin, Key, Val, Options, Min, Max) -> case catch list_to_integer(Val) of {'EXIT', _} -> do_handle_options(Access, Bin, Options); Int when Int >= Min, Int =< Max -> [{Key, Val} | do_handle_options(Access, Bin, Options)]; Int when Int >= Min, Max =:= infinity -> [{Key, Val} | do_handle_options(Access, Bin, Options)]; _Int -> throw({error, {badopt, "Illegal " ++ Key ++ " value " ++ Val}}) end. lookup_blksize(Options) -> case lists:keysearch("blksize", 1, Options) of {value, {_, Val}} -> list_to_integer(Val); false -> 512 end. is_native_ascii([]) -> is_native_ascii(); is_native_ascii([{native_ascii, Bool}]) -> case Bool of true -> true; false -> false end. is_native_ascii() -> case os:type() of {win32, _} -> true; _ -> false end. upgrade_state({read_state, Options, Blksize, Bin, IsNetworkAscii, Count}) -> {read_state, Options, Blksize, Bin, false, IsNetworkAscii, Count}; upgrade_state({write_state, Options, Blksize, List, IsNetworkAscii}) -> {write_state, Options, Blksize, List, false, IsNetworkAscii}.
240baad01ff5463e032a467b33008321a115ed9ec3ae93a65985ec26a00feec9
pavankumarbn/DroneGUIROS
_package_SetStayTime.lisp
(cl:in-package tum_ardrone-srv) (cl:export '(DURATION-VAL DURATION STATUS-VAL STATUS ))
null
https://raw.githubusercontent.com/pavankumarbn/DroneGUIROS/745320d73035bc50ac4fea2699e22586e10be800/devel/share/common-lisp/ros/tum_ardrone/srv/_package_SetStayTime.lisp
lisp
(cl:in-package tum_ardrone-srv) (cl:export '(DURATION-VAL DURATION STATUS-VAL STATUS ))
134d8d87816410deac7b1d83929c661bf687a4be0d13590e554c924ece1f6204
uim/sigscheme
bench-case.scm
(define loop (lambda (i l) (case 6 ((1 2 3 4 5) #f) ((6) (if (< i l) (loop (+ 1 i) l) l))))) (write (loop 0 20000)) (newline)
null
https://raw.githubusercontent.com/uim/sigscheme/ccf1f92d6c2a0f45c15d93da82e399c2a78fe5f3/bench/bench-case.scm
scheme
(define loop (lambda (i l) (case 6 ((1 2 3 4 5) #f) ((6) (if (< i l) (loop (+ 1 i) l) l))))) (write (loop 0 20000)) (newline)
59566a67910e0f4e085edb95039c22779935294a4b2ad51198b58d44eca3412d
haskell-mafia/projector
Template.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveTraversable #-} # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module Projector.Html.Data.Template ( Template (..) -- * AST internals -- ** Type signatures , TTypeSig (..) , setTTypeSigAnnotation , TType (..) , setTTypeAnnotation -- ** Html , THtml (..) , TNode (..) , TAttribute (..) , TAttrValue (..) -- ** Expressions , TExpr (..) , setTExprAnnotation , TAlt (..) , TPattern (..) , setTPatAnnotation , TIString (..) , TIChunk (..) -- ** Strings , TId (..) , TPlainText (..) , TAttrName (..) , TConstructor (..) , TTag (..) ) where import Control.Comonad (Comonad(..)) import Data.Data (Data, Typeable) import Data.List.NonEmpty (NonEmpty(..)) import GHC.Generics (Generic) import P data Template a = Template a (Maybe (TTypeSig a)) (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad Template where extract (Template a _ _) = a extend f t@(Template _ g h) = Template (f t) (fmap (extend (const (f t))) g) (extend (const (f t)) h) data TTypeSig a TODO fix location info here , should be per sig = TTypeSig a [(TId, TType a)] (TType a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) setTTypeSigAnnotation :: a -> TTypeSig a -> TTypeSig a setTTypeSigAnnotation a ts = case ts of TTypeSig _ b c -> TTypeSig a b c instance Comonad TTypeSig where extract (TTypeSig a _ _) = a extend f ts@(TTypeSig _ tss ty) = TTypeSig (f ts) (fmap (fmap (extend (const (f ts)))) tss) (extend (const (f ts)) ty) data TType a = TTVar a TId | TTApp a (TType a) (TType a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) setTTypeAnnotation :: a -> TType a -> TType a setTTypeAnnotation a ty = case ty of TTVar _ b -> TTVar a b TTApp _ b c -> TTApp a b c instance Comonad TType where extract ty = case ty of TTVar a _ -> a TTApp a _ _ -> a extend f ty = case ty of TTVar _ x -> TTVar (f ty) x TTApp _ t1 t2 -> TTApp (f ty) (extend f t1) (extend f t2) data THtml a = THtml a [TNode a] deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad THtml where extract (THtml a _) = a extend f h@(THtml _ nodes) = THtml (f h) (fmap (extend (const (f h))) nodes) data TNode a = TElement a (TTag a) [TAttribute a] (THtml a) | TVoidElement a (TTag a) [TAttribute a] | TComment a TPlainText | TPlain a TPlainText | TWhiteSpace a Int | TNewline a | TExprNode a (TExpr a) | THtmlWS a [TNode a] | TTextExprNode a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TNode where extract node = case node of TElement a _ _ _ -> a TVoidElement a _ _ -> a TComment a _ -> a TWhiteSpace a _ -> a TNewline a -> a TExprNode a _ -> a TTextExprNode a _ -> a TPlain a _ -> a THtmlWS a _ -> a extend f node = case node of TElement _ t a h -> TElement (f node) (extend (const (f node)) t) (fmap (extend (const (f node))) a) (extend (const (f node)) h) TVoidElement _ t a -> TVoidElement (f node) (extend (const (f node)) t) (fmap (extend (const (f node))) a) TComment _ t -> TComment (f node) t TWhiteSpace _ x -> TWhiteSpace (f node) x TNewline _ -> TNewline (f node) TExprNode _ e -> TExprNode (f node) (extend (const (f node)) e) TTextExprNode _ e -> TTextExprNode (f node) (extend (const (f node)) e) TPlain _ t -> TPlain (f node) t THtmlWS _ nodes -> THtmlWS (f node) (fmap (extend (const (f node))) nodes) data TAttribute a = TAttribute a TAttrName (TAttrValue a) | TEmptyAttribute a TAttrName | TAttributeExpr a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TAttribute where extract attr = case attr of TAttribute a _ _ -> a TEmptyAttribute a _ -> a TAttributeExpr a _ -> a extend f attr = case attr of TAttribute _ n v -> TAttribute (f attr) n (extend (const (f attr)) v) TEmptyAttribute _ n -> TEmptyAttribute (f attr) n TAttributeExpr _ e -> TAttributeExpr (f attr) (extend (const (f attr)) e) data TAttrValue a = TQuotedAttrValue a (TIString a) TODO rename this | TAttrExpr a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TAttrValue where extract val = case val of TQuotedAttrValue a _ -> a TAttrExpr a _ -> a extend f expr = case expr of TQuotedAttrValue _ t -> TQuotedAttrValue (f expr) (extend (const (f expr)) t) TAttrExpr _ e -> TAttrExpr (f expr) (extend (const (f expr)) e) data TExpr a = TEVar a TId | TELam a (NonEmpty TId) (TExpr a) | TEApp a (TExpr a) (TExpr a) | TECase a (TExpr a) (NonEmpty (TAlt a)) | TEEach a (TExpr a) (TExpr a) | TENode a (THtml a) | TEString a (TIString a) | TEList a [TExpr a] | TEPrj a (TExpr a) TId | TEHole a deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TExpr where extract expr = case expr of TEVar a _ -> a TELam a _ _ -> a TEApp a _ _ -> a TECase a _ _ -> a TEEach a _ _ -> a TENode a _ -> a TEString a _ -> a TEList a _ -> a TEPrj a _ _ -> a TEHole a -> a extend f expr = case expr of TEVar _ a -> TEVar (f expr) a TELam _ ids e -> TELam (f expr) ids (extend f e) TEApp _ e1 e2 -> TEApp (f expr) (extend f e1) (extend f e2) TECase _ e alts -> TECase (f expr) (extend f e) (fmap (extend (const (f expr))) alts) TEEach _ e1 e2 -> TEEach (f expr) (extend f e1) (extend f e2) TENode _ a -> TENode (f expr) (extend (const (f expr)) a) TEString _ s -> TEString (f expr) (extend (const (f expr)) s) TEList _ es -> TEList (f expr) (fmap (extend f) es) TEPrj _ e fn -> TEPrj (f expr) (extend f e) fn TEHole _ -> TEHole (f expr) setTExprAnnotation :: a -> TExpr a -> TExpr a setTExprAnnotation a expr = case expr of TEVar _ b -> TEVar a b TELam _ b c -> TELam a b c TEApp _ b c -> TEApp a b c TECase _ b c -> TECase a b c TEEach _ b c -> TEEach a b c TENode _ b -> TENode a b TEString _ b -> TEString a b TEList _ b -> TEList a b TEPrj _ b c -> TEPrj a b c TEHole _ -> TEHole a data TIString a = TIString a [TIChunk a] deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TIString where extract (TIString a _) = a extend f str = case str of TIString _ ss -> TIString (f str) (fmap (extend (const (f str))) ss) data TIChunk a = TStringChunk a Text | TExprChunk a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TIChunk where extract chunk = case chunk of TStringChunk a _ -> a TExprChunk a _ -> a extend f chunk = case chunk of TStringChunk _ t -> TStringChunk (f chunk) t TExprChunk _ e -> TExprChunk (f chunk) (extend (const (f chunk)) e) data TAlt a = TAlt a (TPattern a) (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TAlt where extract (TAlt a _ _) = a extend f a@(TAlt _ p b) = TAlt (f a) (extend (const (f a)) p) (extend (const (f a)) b) data TPattern a = TPVar a TId | TPCon a TConstructor [TPattern a] | TPWildcard a deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TPattern where extract pat = case pat of TPVar a _ -> a TPCon a _ _ -> a TPWildcard a -> a extend f pat = case pat of (TPVar _ a) -> TPVar (f pat) a TPCon _ a b -> TPCon (f pat) a (fmap (extend f) b) TPWildcard _ -> TPWildcard (f pat) setTPatAnnotation :: a -> TPattern a -> TPattern a setTPatAnnotation a pat = case pat of TPVar _ b -> TPVar a b TPCon _ b c -> TPCon a b c TPWildcard _ -> TPWildcard a data TTag a = TTag a Text deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TTag where extract (TTag a _) = a extend f tag = case tag of TTag _ t -> TTag (f tag) t newtype TId = TId { unTId :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic) newtype TPlainText = TPlainText { unTPlainText :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic) newtype TAttrName = TAttrName { unTAttrName :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic) newtype TConstructor = TConstructor { unTConstructor :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic)
null
https://raw.githubusercontent.com/haskell-mafia/projector/6af7c7f1e8a428b14c2c5a508f7d4a3ac2decd52/projector-html/src/Projector/Html/Data/Template.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveTraversable # # LANGUAGE OverloadedStrings # * AST internals ** Type signatures ** Html ** Expressions ** Strings
# LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # # LANGUAGE NoImplicitPrelude # module Projector.Html.Data.Template ( Template (..) , TTypeSig (..) , setTTypeSigAnnotation , TType (..) , setTTypeAnnotation , THtml (..) , TNode (..) , TAttribute (..) , TAttrValue (..) , TExpr (..) , setTExprAnnotation , TAlt (..) , TPattern (..) , setTPatAnnotation , TIString (..) , TIChunk (..) , TId (..) , TPlainText (..) , TAttrName (..) , TConstructor (..) , TTag (..) ) where import Control.Comonad (Comonad(..)) import Data.Data (Data, Typeable) import Data.List.NonEmpty (NonEmpty(..)) import GHC.Generics (Generic) import P data Template a = Template a (Maybe (TTypeSig a)) (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad Template where extract (Template a _ _) = a extend f t@(Template _ g h) = Template (f t) (fmap (extend (const (f t))) g) (extend (const (f t)) h) data TTypeSig a TODO fix location info here , should be per sig = TTypeSig a [(TId, TType a)] (TType a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) setTTypeSigAnnotation :: a -> TTypeSig a -> TTypeSig a setTTypeSigAnnotation a ts = case ts of TTypeSig _ b c -> TTypeSig a b c instance Comonad TTypeSig where extract (TTypeSig a _ _) = a extend f ts@(TTypeSig _ tss ty) = TTypeSig (f ts) (fmap (fmap (extend (const (f ts)))) tss) (extend (const (f ts)) ty) data TType a = TTVar a TId | TTApp a (TType a) (TType a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) setTTypeAnnotation :: a -> TType a -> TType a setTTypeAnnotation a ty = case ty of TTVar _ b -> TTVar a b TTApp _ b c -> TTApp a b c instance Comonad TType where extract ty = case ty of TTVar a _ -> a TTApp a _ _ -> a extend f ty = case ty of TTVar _ x -> TTVar (f ty) x TTApp _ t1 t2 -> TTApp (f ty) (extend f t1) (extend f t2) data THtml a = THtml a [TNode a] deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad THtml where extract (THtml a _) = a extend f h@(THtml _ nodes) = THtml (f h) (fmap (extend (const (f h))) nodes) data TNode a = TElement a (TTag a) [TAttribute a] (THtml a) | TVoidElement a (TTag a) [TAttribute a] | TComment a TPlainText | TPlain a TPlainText | TWhiteSpace a Int | TNewline a | TExprNode a (TExpr a) | THtmlWS a [TNode a] | TTextExprNode a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TNode where extract node = case node of TElement a _ _ _ -> a TVoidElement a _ _ -> a TComment a _ -> a TWhiteSpace a _ -> a TNewline a -> a TExprNode a _ -> a TTextExprNode a _ -> a TPlain a _ -> a THtmlWS a _ -> a extend f node = case node of TElement _ t a h -> TElement (f node) (extend (const (f node)) t) (fmap (extend (const (f node))) a) (extend (const (f node)) h) TVoidElement _ t a -> TVoidElement (f node) (extend (const (f node)) t) (fmap (extend (const (f node))) a) TComment _ t -> TComment (f node) t TWhiteSpace _ x -> TWhiteSpace (f node) x TNewline _ -> TNewline (f node) TExprNode _ e -> TExprNode (f node) (extend (const (f node)) e) TTextExprNode _ e -> TTextExprNode (f node) (extend (const (f node)) e) TPlain _ t -> TPlain (f node) t THtmlWS _ nodes -> THtmlWS (f node) (fmap (extend (const (f node))) nodes) data TAttribute a = TAttribute a TAttrName (TAttrValue a) | TEmptyAttribute a TAttrName | TAttributeExpr a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TAttribute where extract attr = case attr of TAttribute a _ _ -> a TEmptyAttribute a _ -> a TAttributeExpr a _ -> a extend f attr = case attr of TAttribute _ n v -> TAttribute (f attr) n (extend (const (f attr)) v) TEmptyAttribute _ n -> TEmptyAttribute (f attr) n TAttributeExpr _ e -> TAttributeExpr (f attr) (extend (const (f attr)) e) data TAttrValue a = TQuotedAttrValue a (TIString a) TODO rename this | TAttrExpr a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TAttrValue where extract val = case val of TQuotedAttrValue a _ -> a TAttrExpr a _ -> a extend f expr = case expr of TQuotedAttrValue _ t -> TQuotedAttrValue (f expr) (extend (const (f expr)) t) TAttrExpr _ e -> TAttrExpr (f expr) (extend (const (f expr)) e) data TExpr a = TEVar a TId | TELam a (NonEmpty TId) (TExpr a) | TEApp a (TExpr a) (TExpr a) | TECase a (TExpr a) (NonEmpty (TAlt a)) | TEEach a (TExpr a) (TExpr a) | TENode a (THtml a) | TEString a (TIString a) | TEList a [TExpr a] | TEPrj a (TExpr a) TId | TEHole a deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TExpr where extract expr = case expr of TEVar a _ -> a TELam a _ _ -> a TEApp a _ _ -> a TECase a _ _ -> a TEEach a _ _ -> a TENode a _ -> a TEString a _ -> a TEList a _ -> a TEPrj a _ _ -> a TEHole a -> a extend f expr = case expr of TEVar _ a -> TEVar (f expr) a TELam _ ids e -> TELam (f expr) ids (extend f e) TEApp _ e1 e2 -> TEApp (f expr) (extend f e1) (extend f e2) TECase _ e alts -> TECase (f expr) (extend f e) (fmap (extend (const (f expr))) alts) TEEach _ e1 e2 -> TEEach (f expr) (extend f e1) (extend f e2) TENode _ a -> TENode (f expr) (extend (const (f expr)) a) TEString _ s -> TEString (f expr) (extend (const (f expr)) s) TEList _ es -> TEList (f expr) (fmap (extend f) es) TEPrj _ e fn -> TEPrj (f expr) (extend f e) fn TEHole _ -> TEHole (f expr) setTExprAnnotation :: a -> TExpr a -> TExpr a setTExprAnnotation a expr = case expr of TEVar _ b -> TEVar a b TELam _ b c -> TELam a b c TEApp _ b c -> TEApp a b c TECase _ b c -> TECase a b c TEEach _ b c -> TEEach a b c TENode _ b -> TENode a b TEString _ b -> TEString a b TEList _ b -> TEList a b TEPrj _ b c -> TEPrj a b c TEHole _ -> TEHole a data TIString a = TIString a [TIChunk a] deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TIString where extract (TIString a _) = a extend f str = case str of TIString _ ss -> TIString (f str) (fmap (extend (const (f str))) ss) data TIChunk a = TStringChunk a Text | TExprChunk a (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TIChunk where extract chunk = case chunk of TStringChunk a _ -> a TExprChunk a _ -> a extend f chunk = case chunk of TStringChunk _ t -> TStringChunk (f chunk) t TExprChunk _ e -> TExprChunk (f chunk) (extend (const (f chunk)) e) data TAlt a = TAlt a (TPattern a) (TExpr a) deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TAlt where extract (TAlt a _ _) = a extend f a@(TAlt _ p b) = TAlt (f a) (extend (const (f a)) p) (extend (const (f a)) b) data TPattern a = TPVar a TId | TPCon a TConstructor [TPattern a] | TPWildcard a deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TPattern where extract pat = case pat of TPVar a _ -> a TPCon a _ _ -> a TPWildcard a -> a extend f pat = case pat of (TPVar _ a) -> TPVar (f pat) a TPCon _ a b -> TPCon (f pat) a (fmap (extend f) b) TPWildcard _ -> TPWildcard (f pat) setTPatAnnotation :: a -> TPattern a -> TPattern a setTPatAnnotation a pat = case pat of TPVar _ b -> TPVar a b TPCon _ b c -> TPCon a b c TPWildcard _ -> TPWildcard a data TTag a = TTag a Text deriving (Eq, Ord, Show, Data, Typeable, Generic, Functor, Foldable, Traversable) instance Comonad TTag where extract (TTag a _) = a extend f tag = case tag of TTag _ t -> TTag (f tag) t newtype TId = TId { unTId :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic) newtype TPlainText = TPlainText { unTPlainText :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic) newtype TAttrName = TAttrName { unTAttrName :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic) newtype TConstructor = TConstructor { unTConstructor :: Text } deriving (Eq, Ord, Show, Data, Typeable, Generic)
dca3a7364e852cbb9ae6b3443f16e8da30edaf14597c88dc2aa728e3424699f2
droundy/iolaus-broken
Plumbing.hs
# LANGUAGE CPP # #include "gadts.h" module Git.Plumbing ( Hash, mkHash, Tree, Commit, Blob(Blob), Tag, emptyCommit, catBlob, hashObject, committer, uname, catTree, TreeEntry(..), catCommit, catCommitRaw, CommitEntry(..), catCommitTree, parseRev, maybeParseRev, heads, remoteHeads, quickRemoteHeads, headNames, tagNames, remoteHeadNames, remoteTagNames, remoteAdd, gitInit, sendPack, listRemotes, checkoutCopy, lsfiles, lssomefiles, lsothers, revList, revListHashes, RevListOption(..), nameRevs, formatRev, updateindex, updateIndexForceRemove, updateIndexCacheInfo, writetree, mkTree, readTree, checkoutIndex, updateref, diffFiles, diffTrees, diffTreeCommit, DiffOption(..), gitApply, unpackFile, getColor, getColorWithDefault, getAllConfig, getConfig, setConfig, unsetConfig, ConfigOption(..), commitTree ) where import System.IO ( Handle, hGetContents, hPutStr, hClose ) import System . IO.Pipe ( openPipe ) import System.Exit ( ExitCode(..) ) import System.IO.Error ( isDoesNotExistError ) import System.Directory ( removeFile ) import Control.Exception ( catchJust, ioErrors ) import Control.Monad ( unless, when ) import Control.Concurrent ( forkIO ) import Data.List ( isInfixOf ) #ifdef HAVE_REDIRECTS import System.Process.Redirects ( createProcess, waitForProcess, proc, CreateProcess(..), StdStream(..) ) #else import System.Process ( createProcess, waitForProcess, proc, CreateProcess(..), StdStream(..) ) #endif import qualified Data.ByteString as B import Iolaus.FileName ( FileName, fp2fn, fn2fp ) import Iolaus.Global ( debugMessage ) import Iolaus.Sealed ( Sealed(Sealed) ) import Iolaus.Show ( Show1(..), Eq1(..), Ord1(..), Pretty1(..), Pretty(..) ) data Hash a C(x) = Hash !a !String deriving ( Eq, Ord ) instance Show1 (Hash a) where show1 (Hash _ s) = s instance Show (Hash a C(x)) where show = show1 instance Eq1 (Hash a) where eq1 (Hash _ x) (Hash _ y) = x == y instance Ord1 (Hash a) where compare1 (Hash _ x) (Hash _ y) = compare x y mkHash :: a -> String -> Hash a C(x) mkHash a s = Hash a (cleanhash s) emptyCommit :: Hash Commit C(()) emptyCommit = Hash Commit (take 40 $ repeat '0') mkSHash :: a -> String -> Sealed (Hash a) mkSHash a s = Sealed $ Hash a (cleanhash s) data Tag = Tag deriving ( Show, Eq, Ord ) data Blob = Blob deriving ( Show, Eq, Ord ) data Tree = Tree deriving ( Show, Eq, Ord ) data Commit = Commit deriving ( Show, Eq, Ord ) readTree :: Hash Tree C(x) -> String -> IO () readTree t i = do removeFileMayNotExist (".git/"++i) debugMessage "calling git read-tree --index-output=..." (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["read-tree","--index-output="++".git/"++i, show t]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git read-tree failed" checkoutIndex :: FilePath -> FilePath -> IO () checkoutIndex i pfx = do debugMessage ("calling git checkout-index -a --prefix="++pfx) (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["checkout-index","-a","--prefix="++pfx]) { env = Just [("GIT_INDEX_FILE",".git/"++i)] } ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git checkout-index failed" checkoutCopy :: String -> IO () checkoutCopy pfx = do debugMessage ("calling git checkout-index -a --prefix="++pfx) (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["checkout-index","-a","--prefix="++pfx]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git checkout-index failed" lsfiles :: IO [String] lsfiles = do debugMessage "calling git ls-files" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-files","--exclude-standard", "--others","--cached"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ lines out ExitFailure _ -> fail "git ls-files failed" lssomefiles :: [String] -> IO [String] lssomefiles [] = return [] lssomefiles fs = do debugMessage "calling git ls-files" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("ls-files":"--":fs)) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ lines out ExitFailure _ -> fail "git ls-files failed" lsothers :: IO [String] lsothers = do debugMessage "calling git ls-files --others" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-files","--others", "--exclude-standard"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ lines out ExitFailure _ -> fail "git ls-files failed" class Flag a where toFlags :: a -> [String] data DiffOption = DiffAll | Stat | DiffPatch | NameOnly | DiffRaw | DiffRecursive instance Flag DiffOption where toFlags DiffAll = ["-a"] toFlags Stat = ["--stat"] toFlags DiffPatch = ["-p"] toFlags DiffRaw = ["--raw"] toFlags NameOnly = ["--name-only"] toFlags DiffRecursive = ["-r"] diffFiles :: [DiffOption] -> [FilePath] -> IO String diffFiles opts fs = do let flags = case opts of [] -> ["-p"] _ -> concatMap toFlags opts debugMessage "calling git diff-files" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("diff-files":flags++"--":fs)) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git diff-files failed" diffTrees :: [DiffOption] -> Hash Tree C(x) -> Hash Tree C(y) -> [FilePath] -> IO String diffTrees opts t1 t2 fs = do let flags = case opts of [] -> ["-p"] _ -> concatMap toFlags opts allflags = flags++show t1:show t2:"--":fs debugMessage ("calling git diff-tree "++show allflags) (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("diff-tree":allflags)) {std_out = CreatePipe} out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git diff-tree failed" diffTreeCommit :: [DiffOption] -> Hash Commit C(x) -> [FilePath] -> IO String diffTreeCommit opts c fs = do let flags = case opts of [] -> ["-p"] _ -> concatMap toFlags opts allflags = flags++show c:"--":fs debugMessage ("calling git diff-tree -c "++show allflags) (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("diff-tree":"-c":allflags)) {std_out = CreatePipe} out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git diff-tree failed" updateIndexForceRemove :: FilePath -> IO () updateIndexForceRemove fp = do debugMessage "calling git update-index --force-remove" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["update-index","--force-remove","--",fp]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-index failed" updateIndexCacheInfo :: String -> Hash Blob C(x) -> FilePath -> IO () updateIndexCacheInfo mode sha fp = do debugMessage "calling git update-index" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["update-index", "--cacheinfo",mode,show sha,fp]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-index failed" unpackFile :: Hash Blob C(x) -> IO FilePath unpackFile sha = do debugMessage "calling git unpack-file" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["unpack-file",show sha]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ init out ExitFailure _ -> fail "git unpack-file failed" updateindex :: [String] -> IO () updateindex [] = debugMessage "no need to call git update-index" updateindex fs = do debugMessage "calling git update-index" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("update-index": "--add":"--remove":"--":fs)) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-index failed" writetree :: IO (Sealed (Hash Tree)) writetree = do debugMessage "calling git write-tree" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["write-tree"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkSHash Tree out ExitFailure _ -> fail "git write-tree failed" heads :: IO [Sealed (Hash Commit)] heads = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["rev-parse", "--branches"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ map (mkSHash Commit) $ lines out ExitFailure _ -> fail "parseRev failed" -- | like `remoteHeads`, but tries to avoid using the network if -- possible. quickRemoteHeads :: String -> IO [Sealed (Hash Commit)] quickRemoteHeads repo = map fst `fmap` quickRemoteHeadNames repo quickRemoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] quickRemoteHeadNames repo = do rhns <- sloppyRemoteHeadNames repo case rhns of [] -> remoteHeadNames repo hs -> do -- There is a danger is that if we never pull -- or push from repo, then the -- refs/remotes/repo/master* might never be -- updated. This forkIO addresses that. forkIO $ fetchRemote repo `catch` \_ -> return () return hs sloppyRemoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] sloppyRemoteHeadNames repo = do debugMessage "calling git show-ref" reporef <- remoteRemote repo let parse l | (reporef++"master") `isInfixOf` l = [(mkSHash Commit l, "refs/heads/"++reverse (takeWhile (/= '/') $ reverse l))] parse _ = [] (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["show-ref"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitFailure _ -> return [] ExitSuccess -> return $ concatMap parse $ lines out remoteHeads :: String -> IO [Sealed (Hash Commit)] remoteHeads repo = map fst `fmap` remoteHeadNames repo headNames :: IO [(Sealed (Hash Commit), String)] headNames = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["show-ref", "--heads"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ filter ismaster $ map parse $ lines out ExitFailure _ -> fail "git show-ref failed" where parse l = (mkSHash Commit l, drop 41 l) ismaster = ("master" `isInfixOf`) . snd tagNames :: IO [(Sealed (Hash Tag), String)] tagNames = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["show-ref", "--tags"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ map parse $ lines out ExitFailure _ -> return [] -- show-ref fails if there are no tags where parse l = (mkSHash Tag l, drop 41 l) remoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] remoteHeadNames repo = do fetchRemote repo sloppyRemoteHeadNames repo rawRemoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] rawRemoteHeadNames repo = do debugMessage (unwords ["calling git ls-remote","--heads",repo]) (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-remote", "--heads",repo]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitFailure _ -> return [] -- failure may mean an empty repository ExitSuccess -> return $ filter ismaster $ map parse $ lines out where parse l = (mkSHash Commit l, drop 41 l) ismaster = ("master" `isInfixOf`) . snd remoteTagNames :: String -> IO [(Sealed (Hash Tag), String)] remoteTagNames repo = do debugMessage "calling git ls-remote" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-remote", "--tags",repo]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitFailure _ -> return [] ExitSuccess -> do let ts = map parse $ filter ('^' `notElem`) $ lines out unless (null ts) $ fetchRemote repo return ts where parse l = (mkSHash Tag l, drop 41 l) parseRev :: String -> IO (Sealed (Hash Commit)) parseRev s = do (Nothing, Just stdout, Just stderr, pid) <- createProcess (proc "git" ["rev-parse", "--verify",s]) #ifdef HAVE_REDIRECTS { std_err = Just CreatePipe, std_out = CreatePipe } #else { std_err = CreatePipe, std_out = CreatePipe } #endif out <- hGetContents stdout err <- hGetContents stderr ec <- length (out++err) `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkSHash Commit out ExitFailure _ -> fail ("git rev-parse failed: "++err) maybeParseRev :: String -> IO (Maybe (Sealed (Hash Commit))) maybeParseRev s = do (Nothing, Just stdout, Just stderr, pid) <- createProcess (proc "git" ["rev-parse", "--verify",s]) #ifdef HAVE_REDIRECTS { std_err = Just CreatePipe, std_out = CreatePipe } #else { std_err = CreatePipe, std_out = CreatePipe } #endif out <- hGetContents stdout err <- hGetContents stderr ec <- length (out++err) `seq` waitForProcess pid case ec of ExitSuccess -> return $ Just $ mkSHash Commit out ExitFailure _ -> return Nothing updateref :: String -> Sealed (Hash Commit) -> Maybe (Sealed (Hash Commit)) -> IO () updateref r (Sealed (Hash Commit "0000000000000000000000000000000000000000")) (Just old)= do debugMessage $ unwords ["calling git update-ref -d",r,show old] (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["update-ref","-d",r,show old]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-ref failed" updateref r new mold = do let old = maybe (take 40 $ repeat '0') show mold debugMessage $ unwords $ "calling git update-ref -d":r:show new:[old] (Nothing, Nothing, Just e, pid) <- createProcess (proc "git" ["update-ref",r,show new,old]) #ifdef HAVE_REDIRECTS { std_err = Just CreatePipe } #else { std_err = CreatePipe } #endif err <- hGetContents e ec <- length err `seq` waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail ("git update-ref failed: "++err) commitTree :: Hash Tree C(x) -> [Sealed (Hash Commit)] -> String -> IO (Hash Commit C(x)) commitTree t pars m = do let pflags = concatMap (\p -> ["-p",show p]) pars debugMessage "calling git commit-tree" (Just i, Just o, Nothing, pid) <- createProcess (proc "git" ("commit-tree":show t:pflags)) { std_out = CreatePipe, std_in = CreatePipe } out <- hGetContents o hPutStr i m hClose i ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkHash Commit out ExitFailure _ -> fail "git commit-tree failed" cleanhash :: String -> String cleanhash = take 40 data RevListOption = MediumPretty | OneLine | Authors | TopoOrder | Graph | RelativeDate | MaxCount Int | Skip Int instance Flag RevListOption where toFlags MediumPretty = ["--pretty=medium"] toFlags OneLine = ["--pretty=oneline"] toFlags Authors = ["--pretty=format:%an"] toFlags Graph = ["--graph"] toFlags RelativeDate = ["--date=relative"] toFlags (MaxCount n) = ["--max-count="++show n] toFlags (Skip n) = ["--skip="++show n] toFlags TopoOrder = ["--topo-order"] nameRevs :: IO [String] nameRevs = do debugMessage "calling git name-rev" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["name-rev", "--all"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ concatMap prett $ lines out ExitFailure _ -> fail "git rev-list failed" where prett s = case words s of [_,"undefined"] -> [] [sha,n] | '~' `elem` n -> [sha] | otherwise -> [sha,n] _ -> error "bad stuff in nameRevs" formatRev :: String -> Hash Commit C(x) -> IO String formatRev fmt c = do debugMessage $ unwords ["calling git rev-list --pretty=format:",fmt, show c] (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["rev-list","--max-count=1", "--pretty=format:"++fmt,show c]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ reverse $ dropWhile (=='\n') $ reverse $ drop 1 $ dropWhile (/='\n') out ExitFailure _ -> fail "git rev-list failed" revList :: [String] -> [RevListOption] -> IO String revList version opts = do let flags = concatMap toFlags opts debugMessage "calling git rev-list" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("rev-list":flags++version)) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git rev-list failed" revListHashes :: [Sealed (Hash Commit)] -> [RevListOption] -> IO [Sealed (Hash Commit)] revListHashes version opts = do x <- revList (map show version) opts return $ map (mkSHash Commit) $ words x remoteAdd :: String -> String -> IO () remoteAdd rname url = do debugMessage "calling git remote add" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["remote","add",rname,url]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git remote add failed" -- | FIXME: I believe that init is porcelain... gitInit :: [String] -> IO () gitInit args = do debugMessage "calling git init" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("init":args)) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git init failed" catBlob :: Hash Blob C(x) -> IO B.ByteString catBlob (Hash Blob h) = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["cat-file","blob",h]) { std_out = CreatePipe } out <- B.hGetContents stdout ec <- waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git cat-file blob failed" data TreeEntry C(x) = Subtree (Hash Tree C(x)) | File (Hash Blob C(x)) | Executable (Hash Blob C(x)) | Symlink (Hash Blob C(x)) instance Show1 TreeEntry where show1 (Subtree (Hash Tree h)) = "040000 tree "++h show1 (File (Hash Blob h)) = "100644 blob "++h show1 (Executable (Hash Blob h)) = "100755 blob "++h show1 (Symlink (Hash Blob h)) = "120000 blob "++h instance Show (TreeEntry C(x)) where show = show1 catTree :: Hash Tree C(x) -> IO [(FileName, TreeEntry C(x))] catTree (Hash Tree h) = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["cat-file","-p",h]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> mapM parseit $ lines out ExitFailure _ -> fail "git cat-file -p failed" where parseit x = case splitAt 12 x of ("040000 tree ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, Subtree $ Hash Tree z) (_,[]) -> fail "error tree" ("100755 blob ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, Executable $ Hash Blob z) (_,[]) -> fail "error blob exec" ("100644 blob ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, File $ Hash Blob z) (_,[]) -> fail "error blob" ("120000 blob ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, Symlink $ Hash Blob z) (_,[]) -> fail "error blob exec" _ -> fail "weird line in tree" catCommitTree :: Hash Commit C(x) -> IO (Hash Tree C(x)) catCommitTree c = myTree `fmap` catCommit c data CommitEntry C(x) = CommitEntry { myParents :: [Sealed (Hash Commit)], myTree :: Hash Tree C(x), myAuthor :: String, myCommitter :: String, myMessage :: String } instance Show1 CommitEntry where show1 c | myAuthor c == myCommitter c = unlines $ ("tree "++show (myTree c)) : map (\p -> "parent "++show p) (myParents c) ++ ["author "++myAuthor c,"", myMessage c] show1 c = unlines $ ("tree "++show (myTree c)) : map (\p -> "parent "++show p) (myParents c) ++ ["author "++myAuthor c, "committer "++myCommitter c, "", myMessage c] instance Show (CommitEntry C(x)) where show = show1 instance Pretty1 CommitEntry where pretty1 c | myAuthor c == myCommitter c = myAuthor c++"\n * "++n++"\n"++unlines (map (" "++) cl) where n:cl = lines $ myMessage c pretty1 c = myAuthor c++"\n"++myCommitter c++ "\n * "++n++"\n"++unlines (map (" "++) cl) where n:cl = lines $ myMessage c instance Pretty (CommitEntry C(x)) where pretty = pretty1 catCommitRaw :: Hash Commit C(x) -> IO String catCommitRaw (Hash Commit h0) = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["cat-file","commit",h0]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git cat-file blob failed" catCommit :: Hash Commit C(x) -> IO (CommitEntry C(x)) catCommit h0 = catCommitRaw h0 >>= (parseit . lines) where parseit (x:xs) = case words x of [] -> return $ CommitEntry { myParents = [], myAuthor = "", myCommitter = "", myTree = error "xx234", myMessage = unlines xs } ["tree",h] -> do c <- parseit xs return $ c { myTree = mkHash Tree h } ["parent",h] -> do c <- parseit xs return $ c { myParents = mkSHash Commit h : myParents c } "author":_ -> do c <- parseit xs return $ c { myAuthor = drop 7 x } "committer":_ -> do c <- parseit xs return $ c { myCommitter = drop 10 x } _ -> fail "weird stuff in commitTree" parseit [] = fail "empty commit in commitTree?" hashObject :: (Handle -> IO ()) -> IO (Hash Blob C(x)) hashObject wr = do (Just i, Just o, Nothing, pid) <- createProcess (proc "git" ["hash-object","-w","--stdin"]) { std_in = CreatePipe, std_out = CreatePipe } out <- hGetContents o wr i hClose i ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkHash Blob out ExitFailure _ -> fail ("git hash-object failed\n"++out) mkTree :: [(FileName, TreeEntry C(x))] -> IO (Hash Tree C(x)) mkTree xs = do debugMessage "calling git mk-tree" (Just i, Just o, Nothing, pid) <- createProcess (proc "git" ["mktree"]) { std_in = CreatePipe, std_out = CreatePipe } out <- hGetContents o mapM_ (putStuff i) xs hClose i ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkHash Tree out ExitFailure _ -> fail "git mk-tree failed" where putStuff i (f, te) = hPutStr i (show te++'\t':fn2fp f++"\n") gitApply :: FilePath -> IO () gitApply p = do debugMessage "calling git apply" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["apply", p]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git apply failed" listConfig :: IO [(String, String)] listConfig = do debugMessage "calling git config" (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--null", "--list"]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ parse out ExitFailure _ -> fail "git config failed" where parse "" = [] parse x = case break (== '\n') x of (a,_:b) -> case break (== '\0') b of (c,_:d) -> (a,c) : parse d (c,"") -> [(a,c)] _ -> [] getAllConfig :: String -> IO [String] getAllConfig v = do debugMessage "calling git config" (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--null", "--get-all",v]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ vals out ExitFailure _ -> fail "git config failed" where vals :: String -> [String] vals "" = [] vals s = case break (== '\0') s of (l, []) -> [l] (l, _:s') -> l : vals s' data ConfigOption = Global | System | RepositoryOnly instance Flag ConfigOption where toFlags Global = ["--global"] toFlags System = ["--system"] toFlags RepositoryOnly = ["--file",".git/config"] getConfig :: [ConfigOption] -> String -> IO (Maybe String) getConfig fs v = do debugMessage "calling git config" (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ("config":"--null":concatMap toFlags fs ++["--get",v])) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ Just $ takeWhile (/= '\0') out ExitFailure _ -> return Nothing setConfig :: [ConfigOption] -> String -> String -> IO () setConfig fs c v = do debugMessage "calling git config" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("config":concatMap toFlags fs++[c, v])) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git config failed" unsetConfig :: [ConfigOption] -> String -> IO () unsetConfig fs c = do debugMessage "calling git config" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("config":concatMap toFlags fs++ ["--unset",c])) waitForProcess pid return () remoteUrls :: IO [(String,String)] remoteUrls = concatMap getrepo `fmap` listConfig where getrepo (x,y) = if take 7 x == "remote." && take 4 (reverse x) == "lru." then [(reverse $ drop 4 $ reverse $ drop 7 x, y)] else [] listRemotes :: IO [String] listRemotes = map fst `fmap` remoteUrls parseRemote :: String -> IO String parseRemote r = do xs <- remoteUrls case lookup r xs of Just u -> return u Nothing -> return r fetchRemote :: String -> IO () fetchRemote repo = do debugMessage "am in fetchRemote" nhs <- map sw `fmap` rawRemoteHeadNames repo nhs0 <- map sw `fmap` sloppyRemoteHeadNames repo when (nhs /= nhs0) $ do debugMessage "need to actually update the remote..." fetchPack repo r <- remoteRemote repo the following " drop 11 " cuts off the string -- "refs/heads/" so we can replace it with -- "refs/remotes/remotename/". let upd (n,h) = updateref (r++drop 11 n) h (lookup n nhs0) mapM_ upd nhs let upd2 (n,h) = case lookup n nhs of Nothing -> updateref (r++drop 11 n) (Sealed emptyCommit) (Just h) Just _ -> return () mapM_ upd2 nhs0 where sw (a,b) = (b,a) remoteRemote :: String -> IO String remoteRemote repo0 = do repo <- parseRemote repo0 if repo /= repo0 then return ("refs/remotes/"++repo0++"/") else return $ "refs/remotes/"++concatMap cleanup repo0++"/" where cleanup '/' = "-" cleanup ':' = "_" cleanup '.' = "-" cleanup '\\' = "-" cleanup '@' = "_" cleanup c = [c] fetchPack :: String -> IO () fetchPack repo0 = do repo <- parseRemote repo0 debugMessage ("calling git fetch-pack --all "++repo) (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["fetch-pack", "--all", repo]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git fetch-pack failed" sendPack :: String -> [(Sealed (Hash Commit), String)] -> [String] -> IO () sendPack repo0 xs ts = do repo <- parseRemote repo0 debugMessage ("calling git send-pack --force "++repo) let revs = map (\ (h,r) -> show h++':':r) xs (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("send-pack":"--force":repo:revs++ts)) ec <- waitForProcess pid case ec of ExitSuccess -> fetchRemote repo0 ExitFailure _ -> fail "git send-pack failed" getColor :: String -> IO String getColor c = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--get-color", c]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git config failed" getColorWithDefault :: String -> String -> IO String getColorWithDefault c d = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--get-color", c, d]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git config failed" removeFileMayNotExist :: String -> IO () removeFileMayNotExist f = catchJust ioErrors (removeFile f) $ \e -> if isDoesNotExistError e then return () else ioError e committer :: IO String committer = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["var", "GIT_COMMITTER_IDENT"]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return (takeWhile (/= '>') out++">") ExitFailure _ -> fail "git var failed" uname :: IO String uname = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "uname" ["-n", "-m", "-o"]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ filter (/= '\n') out ExitFailure _ -> fail "uname failed"
null
https://raw.githubusercontent.com/droundy/iolaus-broken/e40c001f3c5a106bf39f437d6349858e7e9bf51e/Git/Plumbing.hs
haskell
| like `remoteHeads`, but tries to avoid using the network if possible. There is a danger is that if we never pull or push from repo, then the refs/remotes/repo/master* might never be updated. This forkIO addresses that. show-ref fails if there are no tags failure may mean an empty repository | FIXME: I believe that init is porcelain... "refs/heads/" so we can replace it with "refs/remotes/remotename/".
# LANGUAGE CPP # #include "gadts.h" module Git.Plumbing ( Hash, mkHash, Tree, Commit, Blob(Blob), Tag, emptyCommit, catBlob, hashObject, committer, uname, catTree, TreeEntry(..), catCommit, catCommitRaw, CommitEntry(..), catCommitTree, parseRev, maybeParseRev, heads, remoteHeads, quickRemoteHeads, headNames, tagNames, remoteHeadNames, remoteTagNames, remoteAdd, gitInit, sendPack, listRemotes, checkoutCopy, lsfiles, lssomefiles, lsothers, revList, revListHashes, RevListOption(..), nameRevs, formatRev, updateindex, updateIndexForceRemove, updateIndexCacheInfo, writetree, mkTree, readTree, checkoutIndex, updateref, diffFiles, diffTrees, diffTreeCommit, DiffOption(..), gitApply, unpackFile, getColor, getColorWithDefault, getAllConfig, getConfig, setConfig, unsetConfig, ConfigOption(..), commitTree ) where import System.IO ( Handle, hGetContents, hPutStr, hClose ) import System . IO.Pipe ( openPipe ) import System.Exit ( ExitCode(..) ) import System.IO.Error ( isDoesNotExistError ) import System.Directory ( removeFile ) import Control.Exception ( catchJust, ioErrors ) import Control.Monad ( unless, when ) import Control.Concurrent ( forkIO ) import Data.List ( isInfixOf ) #ifdef HAVE_REDIRECTS import System.Process.Redirects ( createProcess, waitForProcess, proc, CreateProcess(..), StdStream(..) ) #else import System.Process ( createProcess, waitForProcess, proc, CreateProcess(..), StdStream(..) ) #endif import qualified Data.ByteString as B import Iolaus.FileName ( FileName, fp2fn, fn2fp ) import Iolaus.Global ( debugMessage ) import Iolaus.Sealed ( Sealed(Sealed) ) import Iolaus.Show ( Show1(..), Eq1(..), Ord1(..), Pretty1(..), Pretty(..) ) data Hash a C(x) = Hash !a !String deriving ( Eq, Ord ) instance Show1 (Hash a) where show1 (Hash _ s) = s instance Show (Hash a C(x)) where show = show1 instance Eq1 (Hash a) where eq1 (Hash _ x) (Hash _ y) = x == y instance Ord1 (Hash a) where compare1 (Hash _ x) (Hash _ y) = compare x y mkHash :: a -> String -> Hash a C(x) mkHash a s = Hash a (cleanhash s) emptyCommit :: Hash Commit C(()) emptyCommit = Hash Commit (take 40 $ repeat '0') mkSHash :: a -> String -> Sealed (Hash a) mkSHash a s = Sealed $ Hash a (cleanhash s) data Tag = Tag deriving ( Show, Eq, Ord ) data Blob = Blob deriving ( Show, Eq, Ord ) data Tree = Tree deriving ( Show, Eq, Ord ) data Commit = Commit deriving ( Show, Eq, Ord ) readTree :: Hash Tree C(x) -> String -> IO () readTree t i = do removeFileMayNotExist (".git/"++i) debugMessage "calling git read-tree --index-output=..." (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["read-tree","--index-output="++".git/"++i, show t]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git read-tree failed" checkoutIndex :: FilePath -> FilePath -> IO () checkoutIndex i pfx = do debugMessage ("calling git checkout-index -a --prefix="++pfx) (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["checkout-index","-a","--prefix="++pfx]) { env = Just [("GIT_INDEX_FILE",".git/"++i)] } ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git checkout-index failed" checkoutCopy :: String -> IO () checkoutCopy pfx = do debugMessage ("calling git checkout-index -a --prefix="++pfx) (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["checkout-index","-a","--prefix="++pfx]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git checkout-index failed" lsfiles :: IO [String] lsfiles = do debugMessage "calling git ls-files" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-files","--exclude-standard", "--others","--cached"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ lines out ExitFailure _ -> fail "git ls-files failed" lssomefiles :: [String] -> IO [String] lssomefiles [] = return [] lssomefiles fs = do debugMessage "calling git ls-files" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("ls-files":"--":fs)) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ lines out ExitFailure _ -> fail "git ls-files failed" lsothers :: IO [String] lsothers = do debugMessage "calling git ls-files --others" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-files","--others", "--exclude-standard"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ lines out ExitFailure _ -> fail "git ls-files failed" class Flag a where toFlags :: a -> [String] data DiffOption = DiffAll | Stat | DiffPatch | NameOnly | DiffRaw | DiffRecursive instance Flag DiffOption where toFlags DiffAll = ["-a"] toFlags Stat = ["--stat"] toFlags DiffPatch = ["-p"] toFlags DiffRaw = ["--raw"] toFlags NameOnly = ["--name-only"] toFlags DiffRecursive = ["-r"] diffFiles :: [DiffOption] -> [FilePath] -> IO String diffFiles opts fs = do let flags = case opts of [] -> ["-p"] _ -> concatMap toFlags opts debugMessage "calling git diff-files" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("diff-files":flags++"--":fs)) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git diff-files failed" diffTrees :: [DiffOption] -> Hash Tree C(x) -> Hash Tree C(y) -> [FilePath] -> IO String diffTrees opts t1 t2 fs = do let flags = case opts of [] -> ["-p"] _ -> concatMap toFlags opts allflags = flags++show t1:show t2:"--":fs debugMessage ("calling git diff-tree "++show allflags) (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("diff-tree":allflags)) {std_out = CreatePipe} out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git diff-tree failed" diffTreeCommit :: [DiffOption] -> Hash Commit C(x) -> [FilePath] -> IO String diffTreeCommit opts c fs = do let flags = case opts of [] -> ["-p"] _ -> concatMap toFlags opts allflags = flags++show c:"--":fs debugMessage ("calling git diff-tree -c "++show allflags) (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("diff-tree":"-c":allflags)) {std_out = CreatePipe} out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git diff-tree failed" updateIndexForceRemove :: FilePath -> IO () updateIndexForceRemove fp = do debugMessage "calling git update-index --force-remove" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["update-index","--force-remove","--",fp]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-index failed" updateIndexCacheInfo :: String -> Hash Blob C(x) -> FilePath -> IO () updateIndexCacheInfo mode sha fp = do debugMessage "calling git update-index" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["update-index", "--cacheinfo",mode,show sha,fp]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-index failed" unpackFile :: Hash Blob C(x) -> IO FilePath unpackFile sha = do debugMessage "calling git unpack-file" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["unpack-file",show sha]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ init out ExitFailure _ -> fail "git unpack-file failed" updateindex :: [String] -> IO () updateindex [] = debugMessage "no need to call git update-index" updateindex fs = do debugMessage "calling git update-index" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("update-index": "--add":"--remove":"--":fs)) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-index failed" writetree :: IO (Sealed (Hash Tree)) writetree = do debugMessage "calling git write-tree" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["write-tree"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkSHash Tree out ExitFailure _ -> fail "git write-tree failed" heads :: IO [Sealed (Hash Commit)] heads = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["rev-parse", "--branches"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ map (mkSHash Commit) $ lines out ExitFailure _ -> fail "parseRev failed" quickRemoteHeads :: String -> IO [Sealed (Hash Commit)] quickRemoteHeads repo = map fst `fmap` quickRemoteHeadNames repo quickRemoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] quickRemoteHeadNames repo = do rhns <- sloppyRemoteHeadNames repo case rhns of [] -> remoteHeadNames repo forkIO $ fetchRemote repo `catch` \_ -> return () return hs sloppyRemoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] sloppyRemoteHeadNames repo = do debugMessage "calling git show-ref" reporef <- remoteRemote repo let parse l | (reporef++"master") `isInfixOf` l = [(mkSHash Commit l, "refs/heads/"++reverse (takeWhile (/= '/') $ reverse l))] parse _ = [] (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["show-ref"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitFailure _ -> return [] ExitSuccess -> return $ concatMap parse $ lines out remoteHeads :: String -> IO [Sealed (Hash Commit)] remoteHeads repo = map fst `fmap` remoteHeadNames repo headNames :: IO [(Sealed (Hash Commit), String)] headNames = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["show-ref", "--heads"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ filter ismaster $ map parse $ lines out ExitFailure _ -> fail "git show-ref failed" where parse l = (mkSHash Commit l, drop 41 l) ismaster = ("master" `isInfixOf`) . snd tagNames :: IO [(Sealed (Hash Tag), String)] tagNames = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["show-ref", "--tags"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ map parse $ lines out where parse l = (mkSHash Tag l, drop 41 l) remoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] remoteHeadNames repo = do fetchRemote repo sloppyRemoteHeadNames repo rawRemoteHeadNames :: String -> IO [(Sealed (Hash Commit), String)] rawRemoteHeadNames repo = do debugMessage (unwords ["calling git ls-remote","--heads",repo]) (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-remote", "--heads",repo]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ filter ismaster $ map parse $ lines out where parse l = (mkSHash Commit l, drop 41 l) ismaster = ("master" `isInfixOf`) . snd remoteTagNames :: String -> IO [(Sealed (Hash Tag), String)] remoteTagNames repo = do debugMessage "calling git ls-remote" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["ls-remote", "--tags",repo]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitFailure _ -> return [] ExitSuccess -> do let ts = map parse $ filter ('^' `notElem`) $ lines out unless (null ts) $ fetchRemote repo return ts where parse l = (mkSHash Tag l, drop 41 l) parseRev :: String -> IO (Sealed (Hash Commit)) parseRev s = do (Nothing, Just stdout, Just stderr, pid) <- createProcess (proc "git" ["rev-parse", "--verify",s]) #ifdef HAVE_REDIRECTS { std_err = Just CreatePipe, std_out = CreatePipe } #else { std_err = CreatePipe, std_out = CreatePipe } #endif out <- hGetContents stdout err <- hGetContents stderr ec <- length (out++err) `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkSHash Commit out ExitFailure _ -> fail ("git rev-parse failed: "++err) maybeParseRev :: String -> IO (Maybe (Sealed (Hash Commit))) maybeParseRev s = do (Nothing, Just stdout, Just stderr, pid) <- createProcess (proc "git" ["rev-parse", "--verify",s]) #ifdef HAVE_REDIRECTS { std_err = Just CreatePipe, std_out = CreatePipe } #else { std_err = CreatePipe, std_out = CreatePipe } #endif out <- hGetContents stdout err <- hGetContents stderr ec <- length (out++err) `seq` waitForProcess pid case ec of ExitSuccess -> return $ Just $ mkSHash Commit out ExitFailure _ -> return Nothing updateref :: String -> Sealed (Hash Commit) -> Maybe (Sealed (Hash Commit)) -> IO () updateref r (Sealed (Hash Commit "0000000000000000000000000000000000000000")) (Just old)= do debugMessage $ unwords ["calling git update-ref -d",r,show old] (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["update-ref","-d",r,show old]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git update-ref failed" updateref r new mold = do let old = maybe (take 40 $ repeat '0') show mold debugMessage $ unwords $ "calling git update-ref -d":r:show new:[old] (Nothing, Nothing, Just e, pid) <- createProcess (proc "git" ["update-ref",r,show new,old]) #ifdef HAVE_REDIRECTS { std_err = Just CreatePipe } #else { std_err = CreatePipe } #endif err <- hGetContents e ec <- length err `seq` waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail ("git update-ref failed: "++err) commitTree :: Hash Tree C(x) -> [Sealed (Hash Commit)] -> String -> IO (Hash Commit C(x)) commitTree t pars m = do let pflags = concatMap (\p -> ["-p",show p]) pars debugMessage "calling git commit-tree" (Just i, Just o, Nothing, pid) <- createProcess (proc "git" ("commit-tree":show t:pflags)) { std_out = CreatePipe, std_in = CreatePipe } out <- hGetContents o hPutStr i m hClose i ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkHash Commit out ExitFailure _ -> fail "git commit-tree failed" cleanhash :: String -> String cleanhash = take 40 data RevListOption = MediumPretty | OneLine | Authors | TopoOrder | Graph | RelativeDate | MaxCount Int | Skip Int instance Flag RevListOption where toFlags MediumPretty = ["--pretty=medium"] toFlags OneLine = ["--pretty=oneline"] toFlags Authors = ["--pretty=format:%an"] toFlags Graph = ["--graph"] toFlags RelativeDate = ["--date=relative"] toFlags (MaxCount n) = ["--max-count="++show n] toFlags (Skip n) = ["--skip="++show n] toFlags TopoOrder = ["--topo-order"] nameRevs :: IO [String] nameRevs = do debugMessage "calling git name-rev" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["name-rev", "--all"]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ concatMap prett $ lines out ExitFailure _ -> fail "git rev-list failed" where prett s = case words s of [_,"undefined"] -> [] [sha,n] | '~' `elem` n -> [sha] | otherwise -> [sha,n] _ -> error "bad stuff in nameRevs" formatRev :: String -> Hash Commit C(x) -> IO String formatRev fmt c = do debugMessage $ unwords ["calling git rev-list --pretty=format:",fmt, show c] (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["rev-list","--max-count=1", "--pretty=format:"++fmt,show c]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ reverse $ dropWhile (=='\n') $ reverse $ drop 1 $ dropWhile (/='\n') out ExitFailure _ -> fail "git rev-list failed" revList :: [String] -> [RevListOption] -> IO String revList version opts = do let flags = concatMap toFlags opts debugMessage "calling git rev-list" (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ("rev-list":flags++version)) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git rev-list failed" revListHashes :: [Sealed (Hash Commit)] -> [RevListOption] -> IO [Sealed (Hash Commit)] revListHashes version opts = do x <- revList (map show version) opts return $ map (mkSHash Commit) $ words x remoteAdd :: String -> String -> IO () remoteAdd rname url = do debugMessage "calling git remote add" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["remote","add",rname,url]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git remote add failed" gitInit :: [String] -> IO () gitInit args = do debugMessage "calling git init" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("init":args)) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git init failed" catBlob :: Hash Blob C(x) -> IO B.ByteString catBlob (Hash Blob h) = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["cat-file","blob",h]) { std_out = CreatePipe } out <- B.hGetContents stdout ec <- waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git cat-file blob failed" data TreeEntry C(x) = Subtree (Hash Tree C(x)) | File (Hash Blob C(x)) | Executable (Hash Blob C(x)) | Symlink (Hash Blob C(x)) instance Show1 TreeEntry where show1 (Subtree (Hash Tree h)) = "040000 tree "++h show1 (File (Hash Blob h)) = "100644 blob "++h show1 (Executable (Hash Blob h)) = "100755 blob "++h show1 (Symlink (Hash Blob h)) = "120000 blob "++h instance Show (TreeEntry C(x)) where show = show1 catTree :: Hash Tree C(x) -> IO [(FileName, TreeEntry C(x))] catTree (Hash Tree h) = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["cat-file","-p",h]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> mapM parseit $ lines out ExitFailure _ -> fail "git cat-file -p failed" where parseit x = case splitAt 12 x of ("040000 tree ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, Subtree $ Hash Tree z) (_,[]) -> fail "error tree" ("100755 blob ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, Executable $ Hash Blob z) (_,[]) -> fail "error blob exec" ("100644 blob ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, File $ Hash Blob z) (_,[]) -> fail "error blob" ("120000 blob ",x') -> case splitAt 40 x' of (z, _:fp) -> return (fp2fn fp, Symlink $ Hash Blob z) (_,[]) -> fail "error blob exec" _ -> fail "weird line in tree" catCommitTree :: Hash Commit C(x) -> IO (Hash Tree C(x)) catCommitTree c = myTree `fmap` catCommit c data CommitEntry C(x) = CommitEntry { myParents :: [Sealed (Hash Commit)], myTree :: Hash Tree C(x), myAuthor :: String, myCommitter :: String, myMessage :: String } instance Show1 CommitEntry where show1 c | myAuthor c == myCommitter c = unlines $ ("tree "++show (myTree c)) : map (\p -> "parent "++show p) (myParents c) ++ ["author "++myAuthor c,"", myMessage c] show1 c = unlines $ ("tree "++show (myTree c)) : map (\p -> "parent "++show p) (myParents c) ++ ["author "++myAuthor c, "committer "++myCommitter c, "", myMessage c] instance Show (CommitEntry C(x)) where show = show1 instance Pretty1 CommitEntry where pretty1 c | myAuthor c == myCommitter c = myAuthor c++"\n * "++n++"\n"++unlines (map (" "++) cl) where n:cl = lines $ myMessage c pretty1 c = myAuthor c++"\n"++myCommitter c++ "\n * "++n++"\n"++unlines (map (" "++) cl) where n:cl = lines $ myMessage c instance Pretty (CommitEntry C(x)) where pretty = pretty1 catCommitRaw :: Hash Commit C(x) -> IO String catCommitRaw (Hash Commit h0) = do (Nothing, Just stdout, Nothing, pid) <- createProcess (proc "git" ["cat-file","commit",h0]) { std_out = CreatePipe } out <- hGetContents stdout ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git cat-file blob failed" catCommit :: Hash Commit C(x) -> IO (CommitEntry C(x)) catCommit h0 = catCommitRaw h0 >>= (parseit . lines) where parseit (x:xs) = case words x of [] -> return $ CommitEntry { myParents = [], myAuthor = "", myCommitter = "", myTree = error "xx234", myMessage = unlines xs } ["tree",h] -> do c <- parseit xs return $ c { myTree = mkHash Tree h } ["parent",h] -> do c <- parseit xs return $ c { myParents = mkSHash Commit h : myParents c } "author":_ -> do c <- parseit xs return $ c { myAuthor = drop 7 x } "committer":_ -> do c <- parseit xs return $ c { myCommitter = drop 10 x } _ -> fail "weird stuff in commitTree" parseit [] = fail "empty commit in commitTree?" hashObject :: (Handle -> IO ()) -> IO (Hash Blob C(x)) hashObject wr = do (Just i, Just o, Nothing, pid) <- createProcess (proc "git" ["hash-object","-w","--stdin"]) { std_in = CreatePipe, std_out = CreatePipe } out <- hGetContents o wr i hClose i ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkHash Blob out ExitFailure _ -> fail ("git hash-object failed\n"++out) mkTree :: [(FileName, TreeEntry C(x))] -> IO (Hash Tree C(x)) mkTree xs = do debugMessage "calling git mk-tree" (Just i, Just o, Nothing, pid) <- createProcess (proc "git" ["mktree"]) { std_in = CreatePipe, std_out = CreatePipe } out <- hGetContents o mapM_ (putStuff i) xs hClose i ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ mkHash Tree out ExitFailure _ -> fail "git mk-tree failed" where putStuff i (f, te) = hPutStr i (show te++'\t':fn2fp f++"\n") gitApply :: FilePath -> IO () gitApply p = do debugMessage "calling git apply" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ["apply", p]) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git apply failed" listConfig :: IO [(String, String)] listConfig = do debugMessage "calling git config" (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--null", "--list"]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ parse out ExitFailure _ -> fail "git config failed" where parse "" = [] parse x = case break (== '\n') x of (a,_:b) -> case break (== '\0') b of (c,_:d) -> (a,c) : parse d (c,"") -> [(a,c)] _ -> [] getAllConfig :: String -> IO [String] getAllConfig v = do debugMessage "calling git config" (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--null", "--get-all",v]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ vals out ExitFailure _ -> fail "git config failed" where vals :: String -> [String] vals "" = [] vals s = case break (== '\0') s of (l, []) -> [l] (l, _:s') -> l : vals s' data ConfigOption = Global | System | RepositoryOnly instance Flag ConfigOption where toFlags Global = ["--global"] toFlags System = ["--system"] toFlags RepositoryOnly = ["--file",".git/config"] getConfig :: [ConfigOption] -> String -> IO (Maybe String) getConfig fs v = do debugMessage "calling git config" (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ("config":"--null":concatMap toFlags fs ++["--get",v])) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ Just $ takeWhile (/= '\0') out ExitFailure _ -> return Nothing setConfig :: [ConfigOption] -> String -> String -> IO () setConfig fs c v = do debugMessage "calling git config" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("config":concatMap toFlags fs++[c, v])) ec <- waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git config failed" unsetConfig :: [ConfigOption] -> String -> IO () unsetConfig fs c = do debugMessage "calling git config" (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("config":concatMap toFlags fs++ ["--unset",c])) waitForProcess pid return () remoteUrls :: IO [(String,String)] remoteUrls = concatMap getrepo `fmap` listConfig where getrepo (x,y) = if take 7 x == "remote." && take 4 (reverse x) == "lru." then [(reverse $ drop 4 $ reverse $ drop 7 x, y)] else [] listRemotes :: IO [String] listRemotes = map fst `fmap` remoteUrls parseRemote :: String -> IO String parseRemote r = do xs <- remoteUrls case lookup r xs of Just u -> return u Nothing -> return r fetchRemote :: String -> IO () fetchRemote repo = do debugMessage "am in fetchRemote" nhs <- map sw `fmap` rawRemoteHeadNames repo nhs0 <- map sw `fmap` sloppyRemoteHeadNames repo when (nhs /= nhs0) $ do debugMessage "need to actually update the remote..." fetchPack repo r <- remoteRemote repo the following " drop 11 " cuts off the string let upd (n,h) = updateref (r++drop 11 n) h (lookup n nhs0) mapM_ upd nhs let upd2 (n,h) = case lookup n nhs of Nothing -> updateref (r++drop 11 n) (Sealed emptyCommit) (Just h) Just _ -> return () mapM_ upd2 nhs0 where sw (a,b) = (b,a) remoteRemote :: String -> IO String remoteRemote repo0 = do repo <- parseRemote repo0 if repo /= repo0 then return ("refs/remotes/"++repo0++"/") else return $ "refs/remotes/"++concatMap cleanup repo0++"/" where cleanup '/' = "-" cleanup ':' = "_" cleanup '.' = "-" cleanup '\\' = "-" cleanup '@' = "_" cleanup c = [c] fetchPack :: String -> IO () fetchPack repo0 = do repo <- parseRemote repo0 debugMessage ("calling git fetch-pack --all "++repo) (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["fetch-pack", "--all", repo]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return () ExitFailure _ -> fail "git fetch-pack failed" sendPack :: String -> [(Sealed (Hash Commit), String)] -> [String] -> IO () sendPack repo0 xs ts = do repo <- parseRemote repo0 debugMessage ("calling git send-pack --force "++repo) let revs = map (\ (h,r) -> show h++':':r) xs (Nothing, Nothing, Nothing, pid) <- createProcess (proc "git" ("send-pack":"--force":repo:revs++ts)) ec <- waitForProcess pid case ec of ExitSuccess -> fetchRemote repo0 ExitFailure _ -> fail "git send-pack failed" getColor :: String -> IO String getColor c = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--get-color", c]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git config failed" getColorWithDefault :: String -> String -> IO String getColorWithDefault c d = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["config", "--get-color", c, d]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return out ExitFailure _ -> fail "git config failed" removeFileMayNotExist :: String -> IO () removeFileMayNotExist f = catchJust ioErrors (removeFile f) $ \e -> if isDoesNotExistError e then return () else ioError e committer :: IO String committer = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "git" ["var", "GIT_COMMITTER_IDENT"]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return (takeWhile (/= '>') out++">") ExitFailure _ -> fail "git var failed" uname :: IO String uname = do (Nothing, Just o, Nothing, pid) <- createProcess (proc "uname" ["-n", "-m", "-o"]) { std_out = CreatePipe } out <- hGetContents o ec <- length out `seq` waitForProcess pid case ec of ExitSuccess -> return $ filter (/= '\n') out ExitFailure _ -> fail "uname failed"
0dbd9e10adc0c9e95f063f2d6c124e38c3afed3fe40ac4249541905d39b3c97f
NorfairKing/smos
CompatibilitySpec.hs
module Smos.Data.CompatibilitySpec (spec) where import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as SB import Data.SemVer as Version import qualified Data.Set as S import Path.IO import Smos.Data import System.FilePath import Test.Syd import Test.Syd.Validity spec :: Spec spec = do let supportedVersions = S.fromList [ version 0 0 0 [] [], oldestParsableDataVersion, currentDataVersion, version 1 0 0 [] [], newestParsableDataVersion ] describe "oldestParsableDataVersion" $ it "is older than the current version" $ oldestParsableDataVersion <= currentDataVersion describe "newestParsableDataVersion" $ it "is newer than the current version" $ currentDataVersion <= newestParsableDataVersion forM_ supportedVersions versionParsesSuccesfullySpec versionFailsToParseNicelySpec (version 2 0 0 [] []) it "outputs the same error every time" $ do p <- resolveFile' "test_resources/version-too-new.smos" r <- readSmosFile p case r of Nothing -> expectationFailure "File should have existed." Just errOrSmosFile -> case errOrSmosFile of Left err -> pure $ pureGoldenStringFile "test_resources/version-too-new.error" err Right res -> expectationFailure $ unlines [ "Should have failed to parse, but parsed this instead:", ppShow res ] dirForVer :: Version -> FilePath dirForVer v = "test_resources/compatibility/v" <> Version.toString v parseFunction :: FilePath -> ByteString -> Either String SmosFile parseFunction fp = let ext = takeExtension fp in case ext of ".smos" -> parseSmosFile ".yaml" -> parseSmosFileYaml ".json" -> parseSmosFileJSON ".pretty-json" -> parseSmosFileJSON e -> pure $ Left $ "unknown file format: " <> e versionParsesSuccesfullySpec :: Version -> Spec versionParsesSuccesfullySpec v = scenarioDir (dirForVer v) $ \fp -> it "parses succesfully" $ do bs <- SB.readFile fp case parseFunction fp bs of Left err -> expectationFailure err Right r -> shouldBeValid r versionFailsToParseNicelySpec :: Version -> Spec versionFailsToParseNicelySpec v = scenarioDir (dirForVer v) $ \fp -> it "fails to parse, nicely" $ do bs <- SB.readFile fp case parseFunction fp bs of Left _ -> pure () Right r -> shouldBeValid r
null
https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos-data-gen/test/Smos/Data/CompatibilitySpec.hs
haskell
module Smos.Data.CompatibilitySpec (spec) where import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as SB import Data.SemVer as Version import qualified Data.Set as S import Path.IO import Smos.Data import System.FilePath import Test.Syd import Test.Syd.Validity spec :: Spec spec = do let supportedVersions = S.fromList [ version 0 0 0 [] [], oldestParsableDataVersion, currentDataVersion, version 1 0 0 [] [], newestParsableDataVersion ] describe "oldestParsableDataVersion" $ it "is older than the current version" $ oldestParsableDataVersion <= currentDataVersion describe "newestParsableDataVersion" $ it "is newer than the current version" $ currentDataVersion <= newestParsableDataVersion forM_ supportedVersions versionParsesSuccesfullySpec versionFailsToParseNicelySpec (version 2 0 0 [] []) it "outputs the same error every time" $ do p <- resolveFile' "test_resources/version-too-new.smos" r <- readSmosFile p case r of Nothing -> expectationFailure "File should have existed." Just errOrSmosFile -> case errOrSmosFile of Left err -> pure $ pureGoldenStringFile "test_resources/version-too-new.error" err Right res -> expectationFailure $ unlines [ "Should have failed to parse, but parsed this instead:", ppShow res ] dirForVer :: Version -> FilePath dirForVer v = "test_resources/compatibility/v" <> Version.toString v parseFunction :: FilePath -> ByteString -> Either String SmosFile parseFunction fp = let ext = takeExtension fp in case ext of ".smos" -> parseSmosFile ".yaml" -> parseSmosFileYaml ".json" -> parseSmosFileJSON ".pretty-json" -> parseSmosFileJSON e -> pure $ Left $ "unknown file format: " <> e versionParsesSuccesfullySpec :: Version -> Spec versionParsesSuccesfullySpec v = scenarioDir (dirForVer v) $ \fp -> it "parses succesfully" $ do bs <- SB.readFile fp case parseFunction fp bs of Left err -> expectationFailure err Right r -> shouldBeValid r versionFailsToParseNicelySpec :: Version -> Spec versionFailsToParseNicelySpec v = scenarioDir (dirForVer v) $ \fp -> it "fails to parse, nicely" $ do bs <- SB.readFile fp case parseFunction fp bs of Left _ -> pure () Right r -> shouldBeValid r
032016f9acc047155bae7385783ca0e01bbb0f2eac7ef2f8623ce5ff5b7c0e44
synduce/Synduce
sumevens.ml
* @synduce -s 2 -NB type 'a clist = | CNil | Single of 'a | Concat of 'a clist * 'a clist type 'a list = | Nil | Cons of 'a * 'a list let rec spec = function | Nil -> 0 | Cons (hd, tl) -> (if hd mod 2 = 0 then hd else 0) + spec tl ;; let rec target = function | CNil -> [%synt s0] | Single a -> [%synt f0] | Concat (x, y) -> [%synt odot] ;; let rec repr = function | CNil -> Nil | Single a -> Cons (a, Nil) | Concat (x, y) -> dec y x and dec l = function | CNil -> repr l | Single a -> Cons (a, repr l) | Concat (x, y) -> dec (Concat (l, y)) x ;;
null
https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/list/sumevens.ml
ocaml
* @synduce -s 2 -NB type 'a clist = | CNil | Single of 'a | Concat of 'a clist * 'a clist type 'a list = | Nil | Cons of 'a * 'a list let rec spec = function | Nil -> 0 | Cons (hd, tl) -> (if hd mod 2 = 0 then hd else 0) + spec tl ;; let rec target = function | CNil -> [%synt s0] | Single a -> [%synt f0] | Concat (x, y) -> [%synt odot] ;; let rec repr = function | CNil -> Nil | Single a -> Cons (a, Nil) | Concat (x, y) -> dec y x and dec l = function | CNil -> repr l | Single a -> Cons (a, repr l) | Concat (x, y) -> dec (Concat (l, y)) x ;;
c834b88249a31d2ffba1a1ae55bb0a24925d63ef8b2dfbb452f980fc49dc3a05
cesquivias/rash
info.rkt
#lang info (define collection "rash") (define deps '("base" "rackunit-lib")) (define build-deps '("scribble-lib" "racket-doc")) (define scribblings '()) (define pkg-desc "A *nix shell written in Racket") (define version "0.0") (define pkg-authors '("Cristian Esquivias"))
null
https://raw.githubusercontent.com/cesquivias/rash/91e181b00e09ea44dd6cb89949e13712c73690fb/info.rkt
racket
#lang info (define collection "rash") (define deps '("base" "rackunit-lib")) (define build-deps '("scribble-lib" "racket-doc")) (define scribblings '()) (define pkg-desc "A *nix shell written in Racket") (define version "0.0") (define pkg-authors '("Cristian Esquivias"))
fb044e437778845af678e612bc6561cef3a8de496e5928926111a2c5e5417eb3
lem-project/lem
lem-webview.lisp
(defpackage :lem-webview (:use :cl :lem :lem-jsonrpc :lem-electron-backend :parenscript) (:export :webview-open)) (in-package :lem-webview) (define-command webview-open (url) ("sUrl: ") (js-eval (gen-webview-html)) (notify "webview-open" (alexandria:plist-hash-table `("url" ,url) :test #'equal))) (defun gen-webview-html () (ps (when (= 0 (@ ((@ document get-elements-by-tag-name) "webview") length)) (let* ((lem-editor ((@ document get-element-by-id) "lem-editor")) (view ((@ document create-element) "webview"))) (setf (@ view autosize) "on") (setf (@ view style height) "100%") ((@ lem-editor on) "webview-open" (lambda (params) (setf (@ view src) (@ params url)))) ((@ lem-editor set-pane) view) nil))))
null
https://raw.githubusercontent.com/lem-project/lem/4f620f94a1fd3bdfb8b2364185e7db16efab57a1/frontends/electron/webview/lem-webview.lisp
lisp
(defpackage :lem-webview (:use :cl :lem :lem-jsonrpc :lem-electron-backend :parenscript) (:export :webview-open)) (in-package :lem-webview) (define-command webview-open (url) ("sUrl: ") (js-eval (gen-webview-html)) (notify "webview-open" (alexandria:plist-hash-table `("url" ,url) :test #'equal))) (defun gen-webview-html () (ps (when (= 0 (@ ((@ document get-elements-by-tag-name) "webview") length)) (let* ((lem-editor ((@ document get-element-by-id) "lem-editor")) (view ((@ document create-element) "webview"))) (setf (@ view autosize) "on") (setf (@ view style height) "100%") ((@ lem-editor on) "webview-open" (lambda (params) (setf (@ view src) (@ params url)))) ((@ lem-editor set-pane) view) nil))))
60623b7a0a0896b5551ae077f590fd68463eb6284df952b42ecd9e388ece0bc3
active-group/reacl-c
wc.cljs
(ns reacl-c.main.wc "Functions to define items as a web component. Any function that takes an attribute map as the first argument and returns an item, is a simple web component. Methods, properties and several other settings can be added to a web component with the functions in this namespace. Then, it can be registered in the browser under a unique tag name with [[define-wc!]]." (:require [reacl-c.main :as main] [reacl-c.core :as c :include-macros true] [reacl-c.dom :as dom] [reacl-c.base :as base] [clojure.set :as set] [active.clojure.functions :as f] goog [active.clojure.lens :as lens]) (:refer-clojure :exclude [use])) ;; Note: extending existing elements, as well as having custom ;; elements with child markup, is probably not what people want to do here - it 's the reacl - c item that does the rendering ; One might ;; want to use a different web-component library for that. (defrecord ^:private WebComponent [item-f initial-state connected disconnected adopted attributes properties methods shadow-init]) (defn- lift [v] (assert (or (ifn? v) (instance? WebComponent v))) (if (instance? WebComponent v) v (WebComponent. v nil nil nil nil {} {} {} nil))) (defn initial-state "Sets an initial state for the given web component." [wc initial-state] (assoc (lift wc) :initial-state initial-state)) (defn- comp-handlers [p f state & args] (let [r1 (c/as-returned (apply p state args))] (let [st2 (if (= c/keep-state (c/returned-state r1)) state (c/returned-state r1))] (c/merge-returned r1 (apply f st2 args))))) (defn- conc [obj attr f] (update (lift obj) attr (fn [p] (if (some? p) (f/partial comp-handlers p f) f)))) (defn connected "Adds a handler for the connected callback to the given web component. The given function `f` will be called with the current state and must return a new state or a [[reacl-c.core/return]] value." [wc f] (assert (some? f)) (conc wc :connected f)) (defn disconnected "Adds a handler for the disconnected callback to the given web component. The given function `f` will be called with the current state and must return a new state or a [[reacl-c.core/return]] value." [wc f] (conc wc :disconnected f)) (defn adopted "Adds a handler for the adopted callback to the given web component. The given function `f` will be called with the current state and must return a new state or a [[reacl-c.core/return]] value." [wc f] (conc wc :adopted f)) (let [f (fn [lens state old new] (lens/shove state lens new))] (defn attribute "Adds an attribute declaration to the given web component. Declared attributes, and only those, will be included with their current value in the first argument of the web component rendering function. The given `attr` can be a keyword or a string. The current value of the attribute will be in the attribute map of the component under the key `key`, which defaults to `attr` if not specified." [wc attr & [key]] (assert (or (string? attr) (keyword? attr))) (update (lift wc) :attributes assoc (if (keyword? attr) (name attr) attr) (if (nil? key) attr key)))) (defn attributes "Adds several simple attributes to the given web component, as multiple calls to [[attribute]] would." [wc & attrs] (reduce attribute wc attrs)) (defn ^:no-doc raw-property [wc property descriptor] (assert (string? property)) (update (lift wc) :properties assoc property descriptor)) (defn data-property "Adds a data property the the given web component, with the given default value. Options can be `:writable`, `:configurable` and `:enumerable` according to `js/Object.defineProperty`." [wc property value & [options]] (raw-property wc property (assoc options :value value))) (defn accessor-property "Adds an accessor property the the given web component, with the given getter and optional setter functions. The `get` function is called on the current state of the component and must return the current property value, and the `set` function is called on the current state and the new value, and must return a new state or a [[reacl-c.core/return]] value. Options can be `:configurable` and `:enumerable` according to `js/Object.defineProperty`." [wc property get & [set options]] (raw-property wc property (assoc options :get get :set set))) (let [get (fn [lens state] (lens/yank state lens)) set (fn [lens state value] (lens/shove state lens value))] (defn property "Adds a property to the given web component, that directly reflects a value in its current state. The given `property` can be a keyword, which is then used to get and associate the property value in a map state. Alternatively a lens can be specified for other kinds of state values. If the option `:read-only?` is set to true, no setter is defined for the property. Other options can be `:configurable` and `:enumerable` according to `js/Object.defineProperty`." [wc property & [lens options]] (assert (or (string? property) (keyword? property))) (assert (or (keyword? property) (some? lens))) (let [lens (or lens (if (keyword? property) property (lens/member property)))] (accessor-property wc (if (keyword? property) (name property) property) (f/partial get lens) (when-not (:read-only? options) (f/partial set lens)) (dissoc options :read-only?))))) (defn properties "Adds several simple properties to the given web component, as multiple calls to [[property]] would." [wc & properties] (reduce property wc properties)) (defn method "Adds a custom method to the given web component. When the method is called by the user of the web component, `f` will be called with the current state of the component, a special `return` function, and then any other arguments passed to it. It must then return a new state, or a [[reacl-c.core/return]] value. To actually return a result to the caller of the method itself, return the result of apply the special `return` function as an action. For example: ``` (method wc \"foo\" (fn [state return arg-1] (c/return :state (update state :called inc) :action (return (* arg-1 arg-1))))) ``` This would update the state of the component, and return the square of the first argument passed to the method invocation. See [[accessor-method]] and [[mutator-method]] for simplified versions of this." [wc method f] (assert (string? method)) (update (lift wc) :methods assoc method f)) (let [g (fn [f state return & args] (c/return :action (return (apply f state args))))] (defn accessor-method "Add a method to the given component, which returns a value based on the current state of the component. When the method is called by the user of the component, `f` is called with the current state and any additional arguments of the method call, and must return the result of method call. The state of the component cannot be changed. See [[method]] if you need to return both a result and change the state of the component." [wc method f] (method wc method (f/partial g f)))) (let [g (fn [f state return & args] (apply f state args))] (defn mutator-method "Add a method to the given component, which only changes the state of the component and always returns `nil`. When the method is called by the user of the component, `f` is called with the current state and any additional arguments of the method call, and must return a new state or a [[reacl-c.core/return]] value. See [[method]] if you need to return both a result and change the state of the component." [wc method f] (method wc method (f/partial g f)))) (defn shadow "Specifies that the given web component should be rendered in a 'shadow DOM'. The `init` argument must specify the encapsulation `:mode` as either \"open\" or \"closed\" and the focus behavious as `delegatesFocus`. See `js/HTMLElement.attachShadow` for details. " [wc init] (assoc (lift wc) :shadow-init init)) (defrecord ^:private Event [type options]) (defn event "Return an object to be used with [[dispatch]], contains the type and options for a DOM event. Options are `:bubbles`, `:cancelable` `:composed` according the the constructor of a `js/Event`. If the options contain the key `:detail`, then a `js/CustomEvent` is created." [type & [options]] (assert (string? type) (str "Event type must be a string, got: " (pr-str type))) ;; options :bubbles, :cancelable, :composed, :detail (Event. type options)) (defn- really-dispatch-event! [target event] (assert (some? target) "No target set; dispatch can only be used within a web component.") (let [type (:type event) options (:options event) init (clj->js (dissoc options :detail)) js-event (if (contains? options :detail) (new js/CustomEvent type (do (aset init "detail" (:detail options)) init)) (new js/Event type init))] (.dispatchEvent target js-event))) (c/defn-effect ^:private dispatch* [event target-atom] (really-dispatch-event! @target-atom event)) (c/defn-effect ^:private new-atom! [] (atom nil)) (defn dispatch "Returns an action effect that will dispatch the given event when executed. Must be used from the item that implements a web component only, which is set as the target of the event. See [[event]] to define what kind of event is emitted." [event] (assert (instance? Event event)) (c/seq-effects (new-atom!) (f/partial dispatch* event))) (defrecord ^:private HandleEvent [f args]) (defrecord ^:private HandleAccess [f args result]) (c/defn-effect ^:private set-atom! [a value] (reset! a value)) (let [dispatch-f (base/effect-f (dispatch* nil nil))] (defn- wrap [element attributes item-f] (let [attrs (->> attributes (map (fn [[name key]] (when (.hasAttribute element name) [key (.getAttribute element name)]))) (remove nil?) (into {}))] (as-> (item-f attrs) $ (c/handle-effect $ (fn [state e] ;; we want the user to just emit an effect ;; (dispatch event), so we have to ;; sneak the element reference into the ;; effect, so that they can still use ;; execute-effect, which wraps it in ;; a composed-effect. ...slightly hacky. (let [repl (fn repl [e] (if (base/composed-effect? e) (base/map-composed-effect e repl) (if (= dispatch-f (base/effect-f e)) (let [[event target-atom] (base/effect-args e)] (c/seq-effects (set-atom! target-atom element) (f/constantly e))) e)))] (c/return :action (repl e))))) (c/handle-message (fn [state msg] (condp instance? msg HandleEvent (apply (:f msg) state (:args msg)) HandleAccess (c/return :action (set-atom! (:result msg) (apply (:f msg) state (:args msg)))) ;; other messages should be impossible, as noone can refer to the result of this. (do (assert false (str "Unexpected message received in web component: " (pr-str msg))) (c/return)))) $))))) (let [set-atom-f (base/effect-f (set-atom! nil nil))] (defn- emulate-set-atom! [returned] (let [as (base/returned-actions returned)] (lens/overhaul returned base/returned-actions (fn [as] (reduce (fn [res a] (if (and (base/simple-effect? a) (= set-atom-f (base/effect-f a))) (do (base/run-effect! a) res) (conj res a))) [] as)))))) (defonce ^:private internal-name-suffix (str (random-uuid))) (defn- internal-name [prefix] (str prefix "$" internal-name-suffix)) (let [n (internal-name "reacl_c_app")] (def ^:private app-property-name n) (defn- set-app! [element app] (aset element n app)) (defn- get-app [element] (aget element n))) (let [n (internal-name "reacl_c_definition")] (def def-property-name n) (defn- set-def! [class wc] (aset class n wc)) (defn- get-def [class] (aget class n)) (defn- has-def? [class] ;; not if get-def is nil or not, but if that property is defined (.hasOwnProperty class n))) (let [n (internal-name "reacl_c_instances")] (def ^:private instances-property-name n) (defn- get-instances [class] (or (aget class instances-property-name) #{})) (defn- update-instances! [class f & args] (aset class instances-property-name (apply f (get-instances class) args)))) (defn- eval-event-unmounted [class handler args] (let [wc (get-def class) state (:initial-state wc) ;; we 'emulate' the set-atom effect as an exception; ;; because that is used for methods which should work ;; in the unmounted state too. r (-> (c/as-returned (apply handler state args)) (emulate-set-atom!))] (assert (empty? (c/returned-actions r)) "Cannot return actions from this web component handler in the unmounted state.") (assert (empty? (c/returned-messages r)) "Cannot return messages from this web component handler in the unmounted state.") (let [state (c/returned-state r)] (when (not= c/keep-state state) (set-def! class (assoc wc :initial-state state)))))) (defn- call-handler-wc [class ^js this f & args] (let [app (get-app this)] ;; an attribute change (not also other events), may occur ;; before the connected event (the element is mounted), in ;; which case we don't have a running app yet; in that ;; case, we change the initial-state for now, and complain ;; about actions and messages. (if (some? app) (main/send-message! app (HandleEvent. f args)) (eval-event-unmounted class f args)))) (defn- access-wc [class ^js this f & args] (let [app (get-app this)] ;; if it's called before mount, we have no app yet, and access the initial-state instead. (if (some? app) ;; as of now, event handling is synchronous - if that ;; changes, we hopefully find a lower level access to the ;; current state. (let [result (atom ::fail)] (main/send-message! app (HandleAccess. f args result)) (assert (not= ::fail @result) "Property access failed. Maybe message handling is not synchronous anymore?") @result) (let [wc (get-def class)] (apply f (:initial-state wc) args))))) (defn- property-wc [class descriptor] ;; Note: for more hot code reload, we might lookup descriptor in the definition, but that would be slower. (let [{get :get set :set} descriptor js-descriptor (clj->js (dissoc descriptor :get :set :value))] (when (some? (:get descriptor)) (aset js-descriptor "get" (fn [] (this-as this (access-wc class this get))))) (when (some? (:set descriptor)) (aset js-descriptor "set" (fn [value] (this-as this (call-handler-wc class this set value))))) (when (contains? descriptor :value) (aset js-descriptor "value" (:value descriptor))) js-descriptor)) (defn- call-method-wc [class ^js this f args] ;; Note: for more hot code reload, we might lookup f in the definition, but that would be slower. (let [result (atom nil) extra first arg : an action to return the result of the method . full-args (cons (f/partial set-atom! result) args) app (get-app this)] (if (some? app) ;; as of now, event handling is synchronous (do (main/send-message! app (HandleEvent. f full-args)) @result) (do (eval-event-unmounted class f full-args) @result)))) (defn- method-wc [class f] (fn [& args] (this-as this (call-method-wc class this f args)))) (defn- prototype-of [tag-or-class] (if (string? tag-or-class) (js/Object.getPrototypeOf (js/document.createElement tag-or-class)) (.-prototype tag-or-class))) (defn- attach-shadow-root [element init] (.attachShadow element (clj->js init))) (defn- render! [this ctor] (let [wc (get-def ctor)] (assert (some? (:item-f wc)) wc) (set-app! this (main/run (if-let [init (:shadow-init wc)] (attach-shadow-root this init) this) (wrap this (:attributes wc) (:item-f wc)) {:initial-state (:initial-state wc)})))) (def ^:private hot-update-enabled? goog/DEBUG) (defn- new-empty-wc [] Note : absolutely not sure if all this OO / prototype stuff is correct ; but it seems to work . (let [htmlelement js/HTMLElement super (prototype-of htmlelement) ctor (fn ctor [] ;; = super() (let [this (js/Reflect.construct htmlelement (to-array nil) ctor)] (js/Object.defineProperty this app-property-name #js {:value nil :writable true :enumerable false}) this)) prototype #js {:attributeChangedCallback (fn [attr old new] ;; we always rerender, where all current attribute values are read. (this-as ^js this (render! this ctor)))}] (js/Object.setPrototypeOf prototype super) (set! (.-prototype ctor) prototype) (set! (.-constructor (.-prototype ctor)) ctor) ;; statics (js/Object.defineProperty ctor def-property-name #js {:value nil :writable true :enumerable false}) ctor)) (defn- set-lifecycle-methods! [class wc] (doto (.-prototype class) (aset "connectedCallback" (let [user (:connected wc)] (fn [] (this-as ^js this (when hot-update-enabled? (update-instances! class conj this)) ;; Note: we cannot render before the 'connected event'. ;; Note: a shadow root can apparently be created and filled in the constructor already; but for consistency we do it here. (render! this class) (when user (call-handler-wc class this user)))))) (aset "disconnectedCallback" (let [user (:disconnected wc)] (if (or user hot-update-enabled?) (fn [] (this-as ^js this (when hot-update-enabled? (update-instances! class disj this)) (when user (call-handler-wc class this user)))) js/undefined))) (aset "adoptedCallback" (if-let [user (:adopted wc)] (fn [] (this-as this (call-handler-wc class this user))) js/undefined)))) (defn- list-diff [l1 l2] (let [s1 (set l1) s2 (set l2)] [(set/difference s1 s2) (set/intersection s1 s2) (set/difference s2 s1)])) (defn- map-diff [m1 m2] (list-diff (keys m1) (keys m2))) (defn- methods-update [prev new] (let [[removed changed added] (map-diff prev new)] (fn [class] (let [p (.-prototype class)] (doseq [m-name removed] (js-delete p m-name)) (doseq [m-name (concat changed added)] (aset p m-name (method-wc class (get new m-name)))))))) (defn- properties-update [prev new] (let [[removed changed added] (map-diff prev new)] ;; cannot remove properties, nor change whem in general (we could change some aspects...?) (when (and (empty? removed) (empty? changed)) (fn [class] (js/Object.defineProperties (.-prototype class) (apply js-obj (mapcat (fn [n] [n (property-wc class (get new n))]) added))))))) (defn- define-attributes! [class names] (js/Object.defineProperty class "observedAttributes" #js {:value (to-array names)})) (defn- broadcast-rerender! [class] (doseq [i (get-instances class)] (render! i class))) (defn- try-update! [class wc] 1 . connected , disconnected , adopted can always be updated ; though ;; connected will of course not be called again if an element is ;; already used. 2 . item - f , initial - state and changed attributes require a forced ;; rerendering. 3 . attributes , properties , and methods have to be diffed 4 . attribute names can not change ; adding and removing attributes ;; would require the browser to reevaluate 'observedAttributes' - ;; does it do that? probably not. 5 . shadow - init can not change . (if (not (has-def? class)) false ;; a different web component? (let [prev (get-def class)] ;; prev will be nil initially! (if (and (some? prev) ;; Not done in production: (not hot-update-enabled?)) false (let [mu (methods-update (:method prev) (:methods wc)) pu (properties-update (:properties prev) (:properties wc)) same-attrs? (= (keys (:attributes prev)) (keys (:attributes wc))) same-shadow? (= (:shadow-init prev) (:shadow-init wc))] (if (and mu pu (or (nil? prev) (and same-attrs? same-shadow?))) (do (set-def! class wc) (set-lifecycle-methods! class wc) (mu class) (pu class) (when (nil? prev) (define-attributes! class (keys (:attributes wc)))) ;; tell all connected instances of this class to rerender if needed; ;; Note: not needed initially; (when (and (some? prev) (or (not= (:attributes prev) (:attributes wc)) (not= (:item-f prev) (:item-f wc)) (not= (:initial-state prev) (:initial-state wc)))) (broadcast-rerender! class)) true) false)))))) (defn- wc-class [wc] (let [class (new-empty-wc) r (try-update! class wc)] (assert r "Updating a new class must succeed.") class)) (defn- get-native-wc [n] (js/customElements.get n)) (defn define! "Tries to register or update the given web component under the given name in the browser, returning whether that succeeded." [name wc & [options]] (let [wc (lift wc)] (if-let [class (get-native-wc name)] (try-update! class wc) (do (js/customElements.define name (wc-class wc)) true)))) (c/defn-effect ^:private gen-name [] (name (gensym "reacl-c-web-component"))) (defn- snd [a b] b) (c/defn-item ^:private define-it [wc] (c/with-state-as name (if (nil? name) (c/execute-effect (gen-name) snd) (c/execute-effect (c/effect define! name wc) (fn [st ok?] (if ok? (c/return) ;; set name to nil, will generate a new one and register that. (c/return :state nil))))))) (let [f (fn [[_ name] args] (when name (c/focus lens/first (apply dom/h name args))))] (c/defn-item use "Registers the given web component under a unique name, and returns an item using that component. This can be especially useful during development of a web component." [wc & args] (c/local-state nil (c/fragment (c/focus lens/second (define-it wc)) (c/dynamic f args)))))
null
https://raw.githubusercontent.com/active-group/reacl-c/b8f550a290f0d6a20d4c880390480e76a6217901/src/reacl_c/main/wc.cljs
clojure
Note: extending existing elements, as well as having custom elements with child markup, is probably not what people want to do One might want to use a different web-component library for that. options :bubbles, :cancelable, :composed, :detail we want the user to just emit an effect (dispatch event), so we have to sneak the element reference into the effect, so that they can still use execute-effect, which wraps it in a composed-effect. ...slightly hacky. other messages should be impossible, as noone can refer to the result of this. not if get-def is nil or not, but if that property is defined we 'emulate' the set-atom effect as an exception; because that is used for methods which should work in the unmounted state too. an attribute change (not also other events), may occur before the connected event (the element is mounted), in which case we don't have a running app yet; in that case, we change the initial-state for now, and complain about actions and messages. if it's called before mount, we have no app yet, and access the initial-state instead. as of now, event handling is synchronous - if that changes, we hopefully find a lower level access to the current state. Note: for more hot code reload, we might lookup descriptor in the definition, but that would be slower. Note: for more hot code reload, we might lookup f in the definition, but that would be slower. as of now, event handling is synchronous but it seems to work . = super() we always rerender, where all current attribute values are read. statics Note: we cannot render before the 'connected event'. Note: a shadow root can apparently be created and filled in the constructor already; but for consistency we do it here. cannot remove properties, nor change whem in general (we could change some aspects...?) though connected will of course not be called again if an element is already used. rerendering. adding and removing attributes would require the browser to reevaluate 'observedAttributes' - does it do that? probably not. a different web component? prev will be nil initially! Not done in production: tell all connected instances of this class to rerender if needed; Note: not needed initially; set name to nil, will generate a new one and register that.
(ns reacl-c.main.wc "Functions to define items as a web component. Any function that takes an attribute map as the first argument and returns an item, is a simple web component. Methods, properties and several other settings can be added to a web component with the functions in this namespace. Then, it can be registered in the browser under a unique tag name with [[define-wc!]]." (:require [reacl-c.main :as main] [reacl-c.core :as c :include-macros true] [reacl-c.dom :as dom] [reacl-c.base :as base] [clojure.set :as set] [active.clojure.functions :as f] goog [active.clojure.lens :as lens]) (:refer-clojure :exclude [use])) (defrecord ^:private WebComponent [item-f initial-state connected disconnected adopted attributes properties methods shadow-init]) (defn- lift [v] (assert (or (ifn? v) (instance? WebComponent v))) (if (instance? WebComponent v) v (WebComponent. v nil nil nil nil {} {} {} nil))) (defn initial-state "Sets an initial state for the given web component." [wc initial-state] (assoc (lift wc) :initial-state initial-state)) (defn- comp-handlers [p f state & args] (let [r1 (c/as-returned (apply p state args))] (let [st2 (if (= c/keep-state (c/returned-state r1)) state (c/returned-state r1))] (c/merge-returned r1 (apply f st2 args))))) (defn- conc [obj attr f] (update (lift obj) attr (fn [p] (if (some? p) (f/partial comp-handlers p f) f)))) (defn connected "Adds a handler for the connected callback to the given web component. The given function `f` will be called with the current state and must return a new state or a [[reacl-c.core/return]] value." [wc f] (assert (some? f)) (conc wc :connected f)) (defn disconnected "Adds a handler for the disconnected callback to the given web component. The given function `f` will be called with the current state and must return a new state or a [[reacl-c.core/return]] value." [wc f] (conc wc :disconnected f)) (defn adopted "Adds a handler for the adopted callback to the given web component. The given function `f` will be called with the current state and must return a new state or a [[reacl-c.core/return]] value." [wc f] (conc wc :adopted f)) (let [f (fn [lens state old new] (lens/shove state lens new))] (defn attribute "Adds an attribute declaration to the given web component. Declared attributes, and only those, will be included with their current value in the first argument of the web component rendering function. The given `attr` can be a keyword or a string. The current value of the attribute will be in the attribute map of the component under the key `key`, which defaults to `attr` if not specified." [wc attr & [key]] (assert (or (string? attr) (keyword? attr))) (update (lift wc) :attributes assoc (if (keyword? attr) (name attr) attr) (if (nil? key) attr key)))) (defn attributes "Adds several simple attributes to the given web component, as multiple calls to [[attribute]] would." [wc & attrs] (reduce attribute wc attrs)) (defn ^:no-doc raw-property [wc property descriptor] (assert (string? property)) (update (lift wc) :properties assoc property descriptor)) (defn data-property "Adds a data property the the given web component, with the given default value. Options can be `:writable`, `:configurable` and `:enumerable` according to `js/Object.defineProperty`." [wc property value & [options]] (raw-property wc property (assoc options :value value))) (defn accessor-property "Adds an accessor property the the given web component, with the given getter and optional setter functions. The `get` function is called on the current state of the component and must return the current property value, and the `set` function is called on the current state and the new value, and must return a new state or a [[reacl-c.core/return]] value. Options can be `:configurable` and `:enumerable` according to `js/Object.defineProperty`." [wc property get & [set options]] (raw-property wc property (assoc options :get get :set set))) (let [get (fn [lens state] (lens/yank state lens)) set (fn [lens state value] (lens/shove state lens value))] (defn property "Adds a property to the given web component, that directly reflects a value in its current state. The given `property` can be a keyword, which is then used to get and associate the property value in a map state. Alternatively a lens can be specified for other kinds of state values. If the option `:read-only?` is set to true, no setter is defined for the property. Other options can be `:configurable` and `:enumerable` according to `js/Object.defineProperty`." [wc property & [lens options]] (assert (or (string? property) (keyword? property))) (assert (or (keyword? property) (some? lens))) (let [lens (or lens (if (keyword? property) property (lens/member property)))] (accessor-property wc (if (keyword? property) (name property) property) (f/partial get lens) (when-not (:read-only? options) (f/partial set lens)) (dissoc options :read-only?))))) (defn properties "Adds several simple properties to the given web component, as multiple calls to [[property]] would." [wc & properties] (reduce property wc properties)) (defn method "Adds a custom method to the given web component. When the method is called by the user of the web component, `f` will be called with the current state of the component, a special `return` function, and then any other arguments passed to it. It must then return a new state, or a [[reacl-c.core/return]] value. To actually return a result to the caller of the method itself, return the result of apply the special `return` function as an action. For example: ``` (method wc \"foo\" (fn [state return arg-1] (c/return :state (update state :called inc) :action (return (* arg-1 arg-1))))) ``` This would update the state of the component, and return the square of the first argument passed to the method invocation. See [[accessor-method]] and [[mutator-method]] for simplified versions of this." [wc method f] (assert (string? method)) (update (lift wc) :methods assoc method f)) (let [g (fn [f state return & args] (c/return :action (return (apply f state args))))] (defn accessor-method "Add a method to the given component, which returns a value based on the current state of the component. When the method is called by the user of the component, `f` is called with the current state and any additional arguments of the method call, and must return the result of method call. The state of the component cannot be changed. See [[method]] if you need to return both a result and change the state of the component." [wc method f] (method wc method (f/partial g f)))) (let [g (fn [f state return & args] (apply f state args))] (defn mutator-method "Add a method to the given component, which only changes the state of the component and always returns `nil`. When the method is called by the user of the component, `f` is called with the current state and any additional arguments of the method call, and must return a new state or a [[reacl-c.core/return]] value. See [[method]] if you need to return both a result and change the state of the component." [wc method f] (method wc method (f/partial g f)))) (defn shadow "Specifies that the given web component should be rendered in a 'shadow DOM'. The `init` argument must specify the encapsulation `:mode` as either \"open\" or \"closed\" and the focus behavious as `delegatesFocus`. See `js/HTMLElement.attachShadow` for details. " [wc init] (assoc (lift wc) :shadow-init init)) (defrecord ^:private Event [type options]) (defn event "Return an object to be used with [[dispatch]], contains the type and options for a DOM event. Options are `:bubbles`, `:cancelable` `:composed` according the the constructor of a `js/Event`. If the options contain the key `:detail`, then a `js/CustomEvent` is created." [type & [options]] (assert (string? type) (str "Event type must be a string, got: " (pr-str type))) (Event. type options)) (defn- really-dispatch-event! [target event] (assert (some? target) "No target set; dispatch can only be used within a web component.") (let [type (:type event) options (:options event) init (clj->js (dissoc options :detail)) js-event (if (contains? options :detail) (new js/CustomEvent type (do (aset init "detail" (:detail options)) init)) (new js/Event type init))] (.dispatchEvent target js-event))) (c/defn-effect ^:private dispatch* [event target-atom] (really-dispatch-event! @target-atom event)) (c/defn-effect ^:private new-atom! [] (atom nil)) (defn dispatch "Returns an action effect that will dispatch the given event when executed. Must be used from the item that implements a web component only, which is set as the target of the event. See [[event]] to define what kind of event is emitted." [event] (assert (instance? Event event)) (c/seq-effects (new-atom!) (f/partial dispatch* event))) (defrecord ^:private HandleEvent [f args]) (defrecord ^:private HandleAccess [f args result]) (c/defn-effect ^:private set-atom! [a value] (reset! a value)) (let [dispatch-f (base/effect-f (dispatch* nil nil))] (defn- wrap [element attributes item-f] (let [attrs (->> attributes (map (fn [[name key]] (when (.hasAttribute element name) [key (.getAttribute element name)]))) (remove nil?) (into {}))] (as-> (item-f attrs) $ (c/handle-effect $ (fn [state e] (let [repl (fn repl [e] (if (base/composed-effect? e) (base/map-composed-effect e repl) (if (= dispatch-f (base/effect-f e)) (let [[event target-atom] (base/effect-args e)] (c/seq-effects (set-atom! target-atom element) (f/constantly e))) e)))] (c/return :action (repl e))))) (c/handle-message (fn [state msg] (condp instance? msg HandleEvent (apply (:f msg) state (:args msg)) HandleAccess (c/return :action (set-atom! (:result msg) (apply (:f msg) state (:args msg)))) (do (assert false (str "Unexpected message received in web component: " (pr-str msg))) (c/return)))) $))))) (let [set-atom-f (base/effect-f (set-atom! nil nil))] (defn- emulate-set-atom! [returned] (let [as (base/returned-actions returned)] (lens/overhaul returned base/returned-actions (fn [as] (reduce (fn [res a] (if (and (base/simple-effect? a) (= set-atom-f (base/effect-f a))) (do (base/run-effect! a) res) (conj res a))) [] as)))))) (defonce ^:private internal-name-suffix (str (random-uuid))) (defn- internal-name [prefix] (str prefix "$" internal-name-suffix)) (let [n (internal-name "reacl_c_app")] (def ^:private app-property-name n) (defn- set-app! [element app] (aset element n app)) (defn- get-app [element] (aget element n))) (let [n (internal-name "reacl_c_definition")] (def def-property-name n) (defn- set-def! [class wc] (aset class n wc)) (defn- get-def [class] (aget class n)) (defn- has-def? [class] (.hasOwnProperty class n))) (let [n (internal-name "reacl_c_instances")] (def ^:private instances-property-name n) (defn- get-instances [class] (or (aget class instances-property-name) #{})) (defn- update-instances! [class f & args] (aset class instances-property-name (apply f (get-instances class) args)))) (defn- eval-event-unmounted [class handler args] (let [wc (get-def class) state (:initial-state wc) r (-> (c/as-returned (apply handler state args)) (emulate-set-atom!))] (assert (empty? (c/returned-actions r)) "Cannot return actions from this web component handler in the unmounted state.") (assert (empty? (c/returned-messages r)) "Cannot return messages from this web component handler in the unmounted state.") (let [state (c/returned-state r)] (when (not= c/keep-state state) (set-def! class (assoc wc :initial-state state)))))) (defn- call-handler-wc [class ^js this f & args] (let [app (get-app this)] (if (some? app) (main/send-message! app (HandleEvent. f args)) (eval-event-unmounted class f args)))) (defn- access-wc [class ^js this f & args] (let [app (get-app this)] (if (some? app) (let [result (atom ::fail)] (main/send-message! app (HandleAccess. f args result)) (assert (not= ::fail @result) "Property access failed. Maybe message handling is not synchronous anymore?") @result) (let [wc (get-def class)] (apply f (:initial-state wc) args))))) (defn- property-wc [class descriptor] (let [{get :get set :set} descriptor js-descriptor (clj->js (dissoc descriptor :get :set :value))] (when (some? (:get descriptor)) (aset js-descriptor "get" (fn [] (this-as this (access-wc class this get))))) (when (some? (:set descriptor)) (aset js-descriptor "set" (fn [value] (this-as this (call-handler-wc class this set value))))) (when (contains? descriptor :value) (aset js-descriptor "value" (:value descriptor))) js-descriptor)) (defn- call-method-wc [class ^js this f args] (let [result (atom nil) extra first arg : an action to return the result of the method . full-args (cons (f/partial set-atom! result) args) app (get-app this)] (if (some? app) (do (main/send-message! app (HandleEvent. f full-args)) @result) (do (eval-event-unmounted class f full-args) @result)))) (defn- method-wc [class f] (fn [& args] (this-as this (call-method-wc class this f args)))) (defn- prototype-of [tag-or-class] (if (string? tag-or-class) (js/Object.getPrototypeOf (js/document.createElement tag-or-class)) (.-prototype tag-or-class))) (defn- attach-shadow-root [element init] (.attachShadow element (clj->js init))) (defn- render! [this ctor] (let [wc (get-def ctor)] (assert (some? (:item-f wc)) wc) (set-app! this (main/run (if-let [init (:shadow-init wc)] (attach-shadow-root this init) this) (wrap this (:attributes wc) (:item-f wc)) {:initial-state (:initial-state wc)})))) (def ^:private hot-update-enabled? goog/DEBUG) (defn- new-empty-wc [] (let [htmlelement js/HTMLElement super (prototype-of htmlelement) ctor (fn ctor [] (let [this (js/Reflect.construct htmlelement (to-array nil) ctor)] (js/Object.defineProperty this app-property-name #js {:value nil :writable true :enumerable false}) this)) prototype #js {:attributeChangedCallback (fn [attr old new] (this-as ^js this (render! this ctor)))}] (js/Object.setPrototypeOf prototype super) (set! (.-prototype ctor) prototype) (set! (.-constructor (.-prototype ctor)) ctor) (js/Object.defineProperty ctor def-property-name #js {:value nil :writable true :enumerable false}) ctor)) (defn- set-lifecycle-methods! [class wc] (doto (.-prototype class) (aset "connectedCallback" (let [user (:connected wc)] (fn [] (this-as ^js this (when hot-update-enabled? (update-instances! class conj this)) (render! this class) (when user (call-handler-wc class this user)))))) (aset "disconnectedCallback" (let [user (:disconnected wc)] (if (or user hot-update-enabled?) (fn [] (this-as ^js this (when hot-update-enabled? (update-instances! class disj this)) (when user (call-handler-wc class this user)))) js/undefined))) (aset "adoptedCallback" (if-let [user (:adopted wc)] (fn [] (this-as this (call-handler-wc class this user))) js/undefined)))) (defn- list-diff [l1 l2] (let [s1 (set l1) s2 (set l2)] [(set/difference s1 s2) (set/intersection s1 s2) (set/difference s2 s1)])) (defn- map-diff [m1 m2] (list-diff (keys m1) (keys m2))) (defn- methods-update [prev new] (let [[removed changed added] (map-diff prev new)] (fn [class] (let [p (.-prototype class)] (doseq [m-name removed] (js-delete p m-name)) (doseq [m-name (concat changed added)] (aset p m-name (method-wc class (get new m-name)))))))) (defn- properties-update [prev new] (let [[removed changed added] (map-diff prev new)] (when (and (empty? removed) (empty? changed)) (fn [class] (js/Object.defineProperties (.-prototype class) (apply js-obj (mapcat (fn [n] [n (property-wc class (get new n))]) added))))))) (defn- define-attributes! [class names] (js/Object.defineProperty class "observedAttributes" #js {:value (to-array names)})) (defn- broadcast-rerender! [class] (doseq [i (get-instances class)] (render! i class))) (defn- try-update! [class wc] 2 . item - f , initial - state and changed attributes require a forced 3 . attributes , properties , and methods have to be diffed 5 . shadow - init can not change . (if (not (has-def? class)) (let [prev (get-def class)] (if (and (some? prev) (not hot-update-enabled?)) false (let [mu (methods-update (:method prev) (:methods wc)) pu (properties-update (:properties prev) (:properties wc)) same-attrs? (= (keys (:attributes prev)) (keys (:attributes wc))) same-shadow? (= (:shadow-init prev) (:shadow-init wc))] (if (and mu pu (or (nil? prev) (and same-attrs? same-shadow?))) (do (set-def! class wc) (set-lifecycle-methods! class wc) (mu class) (pu class) (when (nil? prev) (define-attributes! class (keys (:attributes wc)))) (when (and (some? prev) (or (not= (:attributes prev) (:attributes wc)) (not= (:item-f prev) (:item-f wc)) (not= (:initial-state prev) (:initial-state wc)))) (broadcast-rerender! class)) true) false)))))) (defn- wc-class [wc] (let [class (new-empty-wc) r (try-update! class wc)] (assert r "Updating a new class must succeed.") class)) (defn- get-native-wc [n] (js/customElements.get n)) (defn define! "Tries to register or update the given web component under the given name in the browser, returning whether that succeeded." [name wc & [options]] (let [wc (lift wc)] (if-let [class (get-native-wc name)] (try-update! class wc) (do (js/customElements.define name (wc-class wc)) true)))) (c/defn-effect ^:private gen-name [] (name (gensym "reacl-c-web-component"))) (defn- snd [a b] b) (c/defn-item ^:private define-it [wc] (c/with-state-as name (if (nil? name) (c/execute-effect (gen-name) snd) (c/execute-effect (c/effect define! name wc) (fn [st ok?] (if ok? (c/return) (c/return :state nil))))))) (let [f (fn [[_ name] args] (when name (c/focus lens/first (apply dom/h name args))))] (c/defn-item use "Registers the given web component under a unique name, and returns an item using that component. This can be especially useful during development of a web component." [wc & args] (c/local-state nil (c/fragment (c/focus lens/second (define-it wc)) (c/dynamic f args)))))
a1b590a38045849233e54ea15f6c53f985de81d6450bc5a2e5693c37c67bb36b
jackfirth/syntax-warn
filter-index.rkt
#lang racket/base (provide filter/index-result) (module+ test (require rackunit)) (define (filter/index-result p vs) (for/list ([v vs] [i (in-naturals)] #:when (p v)) (list i v))) (module+ test (check-equal? (filter/index-result string? '(1 2 a "b" c "dee" 5 6 "foooo")) '((3 "b") (5 "dee") (8 "foooo"))) (check-equal? (filter/index-result string? '()) '()) (check-equal? (filter/index-result string? '(1 2 a c 5 6)) '()))
null
https://raw.githubusercontent.com/jackfirth/syntax-warn/f17fdd3179aeab8e5275a24e7d091d3ca42960a9/syntax-warn-base/warn/private/filter-index.rkt
racket
#lang racket/base (provide filter/index-result) (module+ test (require rackunit)) (define (filter/index-result p vs) (for/list ([v vs] [i (in-naturals)] #:when (p v)) (list i v))) (module+ test (check-equal? (filter/index-result string? '(1 2 a "b" c "dee" 5 6 "foooo")) '((3 "b") (5 "dee") (8 "foooo"))) (check-equal? (filter/index-result string? '()) '()) (check-equal? (filter/index-result string? '(1 2 a c 5 6)) '()))
c26316abcf9fe8b532fc61b62caf49ec0fb586ed2937837e7c4057c3d2b2977e
TokTok/hs-toxcore
CombinedKeySpec.hs
# LANGUAGE StrictData # # LANGUAGE Trustworthy # module Network.Tox.Crypto.CombinedKeySpec where import Test.Hspec import Test.QuickCheck import qualified Network.Tox.Crypto.CombinedKey as CombinedKey import Network.Tox.Crypto.KeyPair (KeyPair (..)) spec :: Spec spec = describe "precompute" $ do it "always computes the same combined key for the same public/secret keys" $ property $ \sk pk -> do let ck1 = CombinedKey.precompute sk pk let ck2 = CombinedKey.precompute sk pk ck1 `shouldBe` ck2 it "computes the same combined key for pk1/sk2 and pk2/sk1" $ property $ \(KeyPair sk1 pk1) (KeyPair sk2 pk2) -> do let ck1 = CombinedKey.precompute sk1 pk2 let ck2 = CombinedKey.precompute sk2 pk1 ck1 `shouldBe` ck2
null
https://raw.githubusercontent.com/TokTok/hs-toxcore/647c3070cab29aee3d795a456be534d77c167d81/test/Network/Tox/Crypto/CombinedKeySpec.hs
haskell
# LANGUAGE StrictData # # LANGUAGE Trustworthy # module Network.Tox.Crypto.CombinedKeySpec where import Test.Hspec import Test.QuickCheck import qualified Network.Tox.Crypto.CombinedKey as CombinedKey import Network.Tox.Crypto.KeyPair (KeyPair (..)) spec :: Spec spec = describe "precompute" $ do it "always computes the same combined key for the same public/secret keys" $ property $ \sk pk -> do let ck1 = CombinedKey.precompute sk pk let ck2 = CombinedKey.precompute sk pk ck1 `shouldBe` ck2 it "computes the same combined key for pk1/sk2 and pk2/sk1" $ property $ \(KeyPair sk1 pk1) (KeyPair sk2 pk2) -> do let ck1 = CombinedKey.precompute sk1 pk2 let ck2 = CombinedKey.precompute sk2 pk1 ck1 `shouldBe` ck2
468d8ed1debab5bcd08f9dcf1998e24723b623bc2172fa7d9982490be93b1685
mzp/coq-for-ipad
rawwidget.ml
(***********************************************************************) (* *) MLTk , Tcl / Tk interface of Objective Caml (* *) , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . 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 found in the Objective Caml source tree. *) (* *) (***********************************************************************) $ I d : rawwidget.ml 9547 2010 - 01 - 22 12:48:24Z doligez $ open Support (* * Widgets *) exception IllegalWidgetType of string (* Raised when widget command applied illegally*) (***************************************************) (* Widgets *) (* This 'a raw_widget will be 'a Widget.widget *) (***************************************************) type 'a raw_widget = Untyped of string | Typed of string * string type raw_any (* will be Widget.any *) and button and canvas and checkbutton and entry and frame and label and listbox and menu and menubutton and message and radiobutton and scale and scrollbar and text and toplevel let forget_type w = (Obj.magic (w : 'a raw_widget) : raw_any raw_widget) let coe = forget_type (* table of widgets *) let table = (Hashtbl.create 401 : (string, raw_any raw_widget) Hashtbl.t) let name = function Untyped s -> s | Typed (s,_) -> s (* Normally all widgets are known *) (* this is a provision for send commands to external tk processes *) let known_class = function Untyped _ -> "unknown" | Typed (_,c) -> c (* This one is always created by opentk *) let default_toplevel = let wname = "." in let w = Typed (wname, "toplevel") in Hashtbl.add table wname w; w (* Dummy widget to which global callbacks are associated *) (* also passed around by camltotkoption when no widget in context *) let dummy = Untyped "dummy" let remove w = Hashtbl.remove table (name w) Retype widgets returned from Tk JPF report : sometime s is " " , see Protocol.cTKtoCAMLwidget let get_atom s = try Hashtbl.find table s with Not_found -> Untyped s let naming_scheme = [ "button", "b"; "canvas", "ca"; "checkbutton", "cb"; "entry", "en"; "frame", "f"; "label", "l"; "listbox", "li"; "menu", "me"; "menubutton", "mb"; "message", "ms"; "radiobutton", "rb"; "scale", "sc"; "scrollbar", "sb"; "text", "t"; "toplevel", "top" ] let widget_any_table = List.map fst naming_scheme (* subtypes *) let widget_button_table = [ "button" ] and widget_canvas_table = [ "canvas" ] and widget_checkbutton_table = [ "checkbutton" ] and widget_entry_table = [ "entry" ] and widget_frame_table = [ "frame" ] and widget_label_table = [ "label" ] and widget_listbox_table = [ "listbox" ] and widget_menu_table = [ "menu" ] and widget_menubutton_table = [ "menubutton" ] and widget_message_table = [ "message" ] and widget_radiobutton_table = [ "radiobutton" ] and widget_scale_table = [ "scale" ] and widget_scrollbar_table = [ "scrollbar" ] and widget_text_table = [ "text" ] and widget_toplevel_table = [ "toplevel" ] let new_suffix clas n = try (List.assoc clas naming_scheme) ^ (string_of_int n) with Not_found -> "w" ^ (string_of_int n) (* The function called by generic creation *) let counter = ref 0 let new_atom ~parent ?name:nom clas = let parentpath = name parent in let path = match nom with None -> incr counter; if parentpath = "." then "." ^ (new_suffix clas !counter) else parentpath ^ "." ^ (new_suffix clas !counter) | Some name -> if parentpath = "." then "." ^ name else parentpath ^ "." ^ name in let w = Typed(path,clas) in Hashtbl.add table path w; w (* Just create a path. Only to check existence of widgets *) (* Use with care *) let atom ~parent ~name:pathcomp = let parentpath = name parent in let path = if parentpath = "." then "." ^ pathcomp else parentpath ^ "." ^ pathcomp in Untyped path (* LablTk: Redundant with subtyping of Widget, backward compatibility *) let check_class w clas = match w with Untyped _ -> () (* assume run-time check by tk*) | Typed(_,c) -> if List.mem c clas then () else raise (IllegalWidgetType c) (* Checking membership of constructor in subtype table *) let chk_sub errname table c = if List.mem c table then () else raise (Invalid_argument errname)
null
https://raw.githubusercontent.com/mzp/coq-for-ipad/4fb3711723e2581a170ffd734e936f210086396e/src/ocaml-3.12.0/otherlibs/labltk/support/rawwidget.ml
ocaml
********************************************************************* described in file LICENSE found in the Objective Caml source tree. ********************************************************************* * Widgets Raised when widget command applied illegally ************************************************* Widgets This 'a raw_widget will be 'a Widget.widget ************************************************* will be Widget.any table of widgets Normally all widgets are known this is a provision for send commands to external tk processes This one is always created by opentk Dummy widget to which global callbacks are associated also passed around by camltotkoption when no widget in context subtypes The function called by generic creation Just create a path. Only to check existence of widgets Use with care LablTk: Redundant with subtyping of Widget, backward compatibility assume run-time check by tk Checking membership of constructor in subtype table
MLTk , Tcl / Tk interface of Objective Caml , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking $ I d : rawwidget.ml 9547 2010 - 01 - 22 12:48:24Z doligez $ open Support exception IllegalWidgetType of string type 'a raw_widget = Untyped of string | Typed of string * string and button and canvas and checkbutton and entry and frame and label and listbox and menu and menubutton and message and radiobutton and scale and scrollbar and text and toplevel let forget_type w = (Obj.magic (w : 'a raw_widget) : raw_any raw_widget) let coe = forget_type let table = (Hashtbl.create 401 : (string, raw_any raw_widget) Hashtbl.t) let name = function Untyped s -> s | Typed (s,_) -> s let known_class = function Untyped _ -> "unknown" | Typed (_,c) -> c let default_toplevel = let wname = "." in let w = Typed (wname, "toplevel") in Hashtbl.add table wname w; w let dummy = Untyped "dummy" let remove w = Hashtbl.remove table (name w) Retype widgets returned from Tk JPF report : sometime s is " " , see Protocol.cTKtoCAMLwidget let get_atom s = try Hashtbl.find table s with Not_found -> Untyped s let naming_scheme = [ "button", "b"; "canvas", "ca"; "checkbutton", "cb"; "entry", "en"; "frame", "f"; "label", "l"; "listbox", "li"; "menu", "me"; "menubutton", "mb"; "message", "ms"; "radiobutton", "rb"; "scale", "sc"; "scrollbar", "sb"; "text", "t"; "toplevel", "top" ] let widget_any_table = List.map fst naming_scheme let widget_button_table = [ "button" ] and widget_canvas_table = [ "canvas" ] and widget_checkbutton_table = [ "checkbutton" ] and widget_entry_table = [ "entry" ] and widget_frame_table = [ "frame" ] and widget_label_table = [ "label" ] and widget_listbox_table = [ "listbox" ] and widget_menu_table = [ "menu" ] and widget_menubutton_table = [ "menubutton" ] and widget_message_table = [ "message" ] and widget_radiobutton_table = [ "radiobutton" ] and widget_scale_table = [ "scale" ] and widget_scrollbar_table = [ "scrollbar" ] and widget_text_table = [ "text" ] and widget_toplevel_table = [ "toplevel" ] let new_suffix clas n = try (List.assoc clas naming_scheme) ^ (string_of_int n) with Not_found -> "w" ^ (string_of_int n) let counter = ref 0 let new_atom ~parent ?name:nom clas = let parentpath = name parent in let path = match nom with None -> incr counter; if parentpath = "." then "." ^ (new_suffix clas !counter) else parentpath ^ "." ^ (new_suffix clas !counter) | Some name -> if parentpath = "." then "." ^ name else parentpath ^ "." ^ name in let w = Typed(path,clas) in Hashtbl.add table path w; w let atom ~parent ~name:pathcomp = let parentpath = name parent in let path = if parentpath = "." then "." ^ pathcomp else parentpath ^ "." ^ pathcomp in Untyped path let check_class w clas = match w with | Typed(_,c) -> if List.mem c clas then () else raise (IllegalWidgetType c) let chk_sub errname table c = if List.mem c table then () else raise (Invalid_argument errname)
1878382d8e9c8a4311255184236f70eefd0aec0d3065aac90e226210f7692af5
juji-io/datalevin
issues.cljc
(ns datalevin.test.issues (:require [datalevin.core :as d] [datalevin.test.core :as tdc :refer [db-fixture]] [clojure.test :refer [deftest testing is use-fixtures]] [datalevin.util :as u])) (use-fixtures :each db-fixture) (deftest ^{:doc "CLJS `apply` + `vector` will hold onto mutable array of arguments directly"} issue-262 (let [dir (u/tmp-dir (str "query-or-" (random-uuid))) db (d/db-with (d/empty-db dir) [{:attr "A"} {:attr "B"}])] (is (= (d/q '[:find ?a ?b :where [_ :attr ?a] [(vector ?a) ?b]] db) #{["A" ["A"]] ["B" ["B"]]})) (d/close-db db) (u/delete-files dir)))
null
https://raw.githubusercontent.com/juji-io/datalevin/3a1fccc3cb40531901d51719216fdce3b1aa3483/test/datalevin/test/issues.cljc
clojure
(ns datalevin.test.issues (:require [datalevin.core :as d] [datalevin.test.core :as tdc :refer [db-fixture]] [clojure.test :refer [deftest testing is use-fixtures]] [datalevin.util :as u])) (use-fixtures :each db-fixture) (deftest ^{:doc "CLJS `apply` + `vector` will hold onto mutable array of arguments directly"} issue-262 (let [dir (u/tmp-dir (str "query-or-" (random-uuid))) db (d/db-with (d/empty-db dir) [{:attr "A"} {:attr "B"}])] (is (= (d/q '[:find ?a ?b :where [_ :attr ?a] [(vector ?a) ?b]] db) #{["A" ["A"]] ["B" ["B"]]})) (d/close-db db) (u/delete-files dir)))
77ba1ad566d5b89f5b4ebb1fe727a968a48d0913489d6ae2689586b503416e5e
melvinzhang/bit-scheme
eiod.scm
eiod.scm : eval - in - one - define $ I d : eiod.scm , v 1.17 2005/03/26 19:57:44 al Exp $ ;; A minimal implementation of r5rs eval, null-environment, and ;; scheme-report-environment. (And SRFI-46 extensions, too.) Copyright 2002 , 2004 , 2005 < > ;; You may redistribute and/or modify this software under the terms of the GNU General Public License as published by the Free Software Foundation ( fsf.org ) ; either version 2 , or ( at your option ) any ;; later version. ;; Feel free to ask me for different licensing terms. ;; DISCLAIMER: ;; This is only intended as a demonstration of the minimum ;; implementation effort required for an r5rs eval. It serves as a simple , working example of one way to implement the r5rs macro ;; system (and SRFI-46) . Among the reasons that it is ill-suited for ;; production use is the complete lack of error-checking. ;; DATA STRUCTURES: ;; An environment is a procedure that accepts any identifier and ;; returns a denotation. The denotation of an unbound identifier is ;; its name (as a symbol). A bound identifier's denotation is its ;; binding, which is a list of the current value, the binding's type ;; (keyword or variable), and the identifier's name (needed by quote). ;; identifier: [symbol | thunk] ;; denotation: [symbol | binding] ;; binding: [variable-binding | keyword-binding] ;; variable-binding: (value #f symbol) ;; keyword-binding: (special-form #t symbol) ;; special-form: [builtin | transformer] ;; A value is any arbitrary scheme value. Special forms are either a symbol naming a builtin , or a transformer procedure that takes two ;; arguments: a macro use and the environment of the macro use. ;; An explicit-renaming low-level macro facility is supported, upon ;; which syntax-rules is implemented. When a syntax-rules template ;; containing a literal identifier is transcribed, the output will ;; contain a fresh identifier, which is an eq?-unique thunk that when ;; invoked returns the old identifier's denotation in the environment of the macro 's definition . When one of these " renamed " identifiers ;; is looked up in an environment that has no binding for it, the ;; thunk is invoked and the old denotation is returned. (The thunk ;; actually returns the old denotation wrapped inside a unique pair, ;; which is immediately unwrapped. This is necessary to ensure that ;; different rename thunks of the same denotation do not compare eq?.) This environment and denotation model is similar to the one described in the 1991 paper " Macros that Work " by Clinger and Rees . The base environment contains eight keyword bindings and two ;; variable bindings: ;; lambda, set!, and begin are as in the standard. ;; q is like quote, but it does not handle pairs or vectors. ;; def is like define, but it does not handle the (f . args) format. ;; define-syntax makes internal syntax definitions. ;; (get-env) returns the local environment. ;; (syntax x) is like quote, but does not convert identifiers to symbols. ;; The id? procedure is a predicate for identifiers. ;; The new-id procedure takes a denotation and returns a fresh identifier. ;; Quote-and-evaluate captures all the code into the list eiod-source ;; so that we can have fun feeding eval to itself, as in ( ( eval ` ( let ( ) , @eiod - source repl ) ( scheme - report - environment 5 ) ) ) . ;; [Note: using (and even starting) a doubly evaled repl will be *very* slow.] (define-syntax quote-and-evaluate (syntax-rules () ((quote-and-evaluate var . x) (begin (define var 'x) . x)))) ;; The matching close parenthesis is at the end of the file. (quote-and-evaluate eiod-source (define (eval sexp env) (define (new-id den) (define p (list den)) (lambda () p)) (define (old-den id) (car (id))) (define (id? x) (or (symbol? x) (procedure? x))) (define (id->sym id) (if (symbol? id) id (den->sym (old-den id)))) (define (den->sym den) (if (symbol? den) den (get-sym den))) (define (empty-env id) (if (symbol? id) id (old-den id))) (define (extend env id binding) (lambda (i) (if (eq? id i) binding (env i)))) (define (add-var var val env) (extend env var (list val #f (id->sym var)))) (define (add-key key val env) (extend env key (list val #t (id->sym key)))) (define (get-val binding) (car binding)) (define (special? binding) (cadr binding)) (define (get-sym binding) (caddr binding)) (define (set-val! binding val) (set-car! binding val)) (define (make-builtins-env) (do ((specials '(lambda set! begin q def define-syntax syntax get-env) (cdr specials)) (env empty-env (add-key (car specials) (car specials) env))) ((null? specials) (add-var 'new-id new-id (add-var 'id? id? env))))) (define (eval sexp env) (let eval-here ((sexp sexp)) (cond ((id? sexp) (get-val (env sexp))) ((not (pair? sexp)) sexp) (else (let ((head (car sexp)) (tail (cdr sexp))) (let ((head-binding (and (id? head) (env head)))) (if (and head-binding (special? head-binding)) (let ((special (get-val head-binding))) (case special ((get-env) env) ((syntax) (car tail)) ((lambda) (eval-lambda tail env)) ((begin) (eval-seq tail env)) ((set!) (set-val! (env (car tail)) (eval-here (cadr tail)))) ((q) (let ((x (car tail))) (if (id? x) (id->sym x) x))) (else (eval-here (special sexp env))))) (apply (eval-here head) (map1 eval-here tail))))))))) ;; Don't use standard map because it might not be continuationally correct. (define (map1 f l) (if (null? l) '() (cons (f (car l)) (map1 f (cdr l))))) (define (eval-seq tail env) ;; Don't use for-each because we must tail-call the last expression. (do ((sexps tail (cdr sexps))) ((null? (cdr sexps)) (eval (car sexps) env)) (eval (car sexps) env))) (define (eval-lambda tail env) (lambda args (define ienv (do ((args args (cdr args)) (vars (car tail) (cdr vars)) (ienv env (add-var (car vars) (car args) ienv))) ((not (pair? vars)) (if (null? vars) ienv (add-var vars args ienv))))) (let loop ((ienv ienv) (ids '()) (inits '()) (body (cdr tail))) (let ((first (car body)) (rest (cdr body))) (let* ((head (and (pair? first) (car first))) (binding (and (id? head) (ienv head))) (special (and binding (special? binding) (get-val binding)))) (if (procedure? special) (loop ienv ids inits (cons (special first ienv) rest)) (case special ((begin) (loop ienv ids inits (append (cdr first) rest))) ((def define-syntax) (let ((id (cadr first)) (init (caddr first))) (let* ((adder (if (eq? special 'def) add-var add-key)) (ienv (adder id 'undefined ienv))) (loop ienv (cons id ids) (cons init inits) rest)))) (else (let ((ieval (lambda (init) (eval init ienv)))) (for-each set-val! (map ienv ids) (map1 ieval inits)) (eval-seq body ienv)))))))))) ;; We make a copy of the initial input to ensure that subsequent mutation of it does not affect eval 's result . [ 1 ] (eval (let copy ((x sexp)) (cond ((string? x) (string-copy x)) ((pair? x) (cons (copy (car x)) (copy (cdr x)))) ((vector? x) (list->vector (copy (vector->list x)))) (else x))) (or env (make-builtins-env)))) (define null-environment (let () ;; Syntax-rules is implemented as a macro that expands into a call ;; to the syntax-rules* procedure, which returns a transformer ;; procedure. The arguments to syntax-rules* are the arguments to ;; syntax-rules plus the current environment, which is captured ;; with get-env. Syntax-rules** is called once with some basics ;; from the base environment. It creates and returns ;; syntax-rules*. (define (syntax-rules** id? new-id denotation-of-default-ellipsis) (define (syntax-rules* mac-env ellipsis pat-literals rules) (define (pat-literal? id) (memq id pat-literals)) (define (not-pat-literal? id) (not (pat-literal? id))) (define (ellipsis-pair? x) (and (pair? x) (ellipsis? (car x)))) (define (ellipsis? x) (if ellipsis (eq? x ellipsis) (and (id? x) (eq? (mac-env x) denotation-of-default-ellipsis)))) ;; List-ids returns a list of the non-ellipsis ids in a ;; pattern or template for which (pred? id) is true. If ;; include-scalars is false, we only include ids that are within the scope of at least one ellipsis . (define (list-ids x include-scalars pred?) (let collect ((x x) (inc include-scalars) (l '())) (cond ((id? x) (if (and inc (pred? x)) (cons x l) l)) ((vector? x) (collect (vector->list x) inc l)) ((pair? x) (if (ellipsis-pair? (cdr x)) (collect (car x) #t (collect (cddr x) inc l)) (collect (car x) inc (collect (cdr x) inc l)))) (else l)))) ;; Returns #f or an alist mapping each pattern var to a part of the input . Ellipsis vars are mapped to lists of parts ( or ;; lists of lists ...). (define (match-pattern pat use use-env) (call-with-current-continuation (lambda (return) (define (fail) (return #f)) (let match ((pat (cdr pat)) (sexp (cdr use)) (bindings '())) (define (continue-if condition) (if condition bindings (fail))) (cond ((id? pat) (if (pat-literal? pat) (continue-if (and (id? sexp) (eq? (use-env sexp) (mac-env pat)))) (cons (cons pat sexp) bindings))) ((vector? pat) (or (vector? sexp) (fail)) (match (vector->list pat) (vector->list sexp) bindings)) ((not (pair? pat)) (continue-if (equal? pat sexp))) ((ellipsis-pair? (cdr pat)) (let* ((tail-len (length (cddr pat))) (sexp-len (if (list? sexp) (length sexp) (fail))) (seq-len (- sexp-len tail-len)) (sexp-tail (begin (if (negative? seq-len) (fail)) (list-tail sexp seq-len))) (seq (reverse (list-tail (reverse sexp) tail-len))) (vars (list-ids (car pat) #t not-pat-literal?))) (define (match1 sexp) (map cdr (match (car pat) sexp '()))) (append (apply map list vars (map match1 seq)) (match (cddr pat) sexp-tail bindings)))) ((pair? sexp) (match (car pat) (car sexp) (match (cdr pat) (cdr sexp) bindings))) (else (fail))))))) (define (expand-template pat tmpl top-bindings) ;; New-literals is an alist mapping each literal id in the ;; template to a fresh id for inserting into the output. It might have duplicate entries mapping an i d to two different ;; fresh ids, but that's okay because when we go to retrieve a fresh i d , assq will always retrieve the first one . (define new-literals (map (lambda (id) (cons id (new-id (mac-env id)))) (list-ids tmpl #t (lambda (id) (not (assq id top-bindings)))))) (define ellipsis-vars (list-ids (cdr pat) #f not-pat-literal?)) (define (list-ellipsis-vars subtmpl) (list-ids subtmpl #t (lambda (id) (memq id ellipsis-vars)))) (let expand ((tmpl tmpl) (bindings top-bindings)) (let expand-part ((tmpl tmpl)) (cond ((id? tmpl) (cdr (or (assq tmpl bindings) (assq tmpl top-bindings) (assq tmpl new-literals)))) ((vector? tmpl) (list->vector (expand-part (vector->list tmpl)))) ((pair? tmpl) (if (ellipsis-pair? (cdr tmpl)) (let ((vars-to-iterate (list-ellipsis-vars (car tmpl)))) (define (lookup var) (cdr (assq var bindings))) (define (expand-using-vals . vals) (expand (car tmpl) (map cons vars-to-iterate vals))) (let ((val-lists (map lookup vars-to-iterate))) (append (apply map expand-using-vals val-lists) (expand-part (cddr tmpl))))) (cons (expand-part (car tmpl)) (expand-part (cdr tmpl))))) (else tmpl))))) (lambda (use use-env) (let loop ((rules rules)) (let* ((rule (car rules)) (pat (car rule)) (tmpl (cadr rule))) (cond ((match-pattern pat use use-env) => (lambda (bindings) (expand-template pat tmpl bindings))) (else (loop (cdr rules)))))))) syntax-rules*) (define macro-defs '((define-syntax quote (syntax-rules () ('(x . y) (cons 'x 'y)) ('#(x ...) (list->vector '(x ...))) ('x (q x)))) (define-syntax quasiquote (syntax-rules (unquote unquote-splicing quasiquote) (`,x x) (`(,@x . y) (append x `y)) ((_ `x . d) (cons 'quasiquote (quasiquote (x) d))) ((_ ,x d) (cons 'unquote (quasiquote (x) . d))) ((_ ,@x d) (cons 'unquote-splicing (quasiquote (x) . d))) ((_ (x . y) . d) (cons (quasiquote x . d) (quasiquote y . d))) ((_ #(x ...) . d) (list->vector (quasiquote (x ...) . d))) ((_ x . d) 'x))) (define-syntax do (syntax-rules () ((_ ((var init . step) ...) ending expr ...) (let loop ((var init) ...) (cond ending (else expr ... (loop (begin var . step) ...))))))) (define-syntax letrec (syntax-rules () ((_ ((var init) ...) . body) (let () (def var init) ... (let () . body))))) (define-syntax letrec-syntax (syntax-rules () ((_ ((key trans) ...) . body) (let () (define-syntax key trans) ... (let () . body))))) (define-syntax let-syntax (syntax-rules () ((_ () . body) (let () . body)) ((_ ((key trans) . bindings) . body) (letrec-syntax ((temp trans)) (let-syntax bindings (letrec-syntax ((key temp)) . body)))))) (define-syntax let* (syntax-rules () ((_ () . body) (let () . body)) ((_ (first . more) . body) (let (first) (let* more . body))))) (define-syntax let (syntax-rules () ((_ ((var init) ...) . body) ((lambda (var ...) . body) init ...)) ((_ name ((var init) ...) . body) ((letrec ((name (lambda (var ...) . body))) name) init ...)))) (define-syntax case (syntax-rules () ((_ x (test . exprs) ...) (let ((key x)) (cond ((case-test key test) . exprs) ...))))) (define-syntax case-test (syntax-rules (else) ((_ k else) #t) ((_ k atoms) (memv k 'atoms)))) (define-syntax cond (syntax-rules (else =>) ((_) #f) ((_ (else . exps)) (begin #f . exps)) ((_ (x) . rest) (or x (cond . rest))) ((_ (x => proc) . rest) (let ((tmp x)) (cond (tmp (proc tmp)) . rest))) ((_ (x . exps) . rest) (if x (begin . exps) (cond . rest))))) (define-syntax and (syntax-rules () ((_) #t) ((_ test) test) ((_ test . tests) (if test (and . tests) #f)))) (define-syntax or (syntax-rules () ((_) #f) ((_ test) test) ((_ test . tests) (let ((x test)) (if x x (or . tests)))))) (define-syntax define (syntax-rules () ((_ (var . args) . body) (define var (lambda args . body))) ((_ var init) (def var init)))) (define-syntax if (syntax-rules () ((_ x y ...) (if* x (lambda () y) ...)))) (define-syntax delay (syntax-rules () ((_ x) (delay* (lambda () x))))))) (define (if* a b . c) (if a (b) (if (pair? c) ((car c))))) (define (delay* thunk) (delay (thunk))) (define (null-env) ((eval `(lambda (cons append list->vector memv delay* if* syntax-rules**) ((lambda (syntax-rules*) (define-syntax syntax-rules (syntax-rules* (get-env) #f (syntax ()) (syntax (((_ (lit ...) . rules) (syntax-rules #f (lit ...) . rules)) ((_ ellipsis lits . rules) (syntax-rules* (get-env) (syntax ellipsis) (syntax lits) (syntax rules))))))) ((lambda () ,@macro-defs (get-env)))) (syntax-rules** id? new-id ((get-env) (syntax ...))))) #f) cons append list->vector memv delay* if* syntax-rules**)) (define promise (delay (null-env))) (lambda (version) (if (= version 5) (force promise) (open-input-file "sheep-herders/r^-1rs.ltx"))))) (define scheme-report-environment (let-syntax ((extend-env (syntax-rules () ((extend-env env . names) ((eval '(lambda names (get-env)) env) . names))))) (let () (define (r5-env) (extend-env (null-environment 5) eqv? eq? equal? number? complex? real? rational? integer? exact? inexact? = < > <= >= zero? positive? negative? odd? even? max min + * - / abs quotient remainder modulo gcd lcm numerator denominator floor ceiling truncate round rationalize exp log sin cos tan asin acos atan sqrt expt make-rectangular make-polar real-part imag-part magnitude angle exact->inexact inexact->exact number->string string->number not boolean? pair? cons car cdr set-car! set-cdr! caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr null? list? list length append reverse list-tail list-ref memq memv member assq assv assoc symbol? symbol->string string->symbol char? char=? char<? char>? char<=? char>=? char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=? char-alphabetic? char-numeric? char-whitespace? char-upper-case? char-lower-case? char->integer integer->char char-upcase char-downcase string? make-string string string-length string-ref string-set! string=? string-ci=? string<? string>? string<=? string>=? string-ci<? string-ci>? string-ci<=? string-ci>=? substring string-append string->list list->string string-copy string-fill! vector? make-vector vector vector-length vector-ref vector-set! vector->list list->vector vector-fill! procedure? apply map for-each force call-with-current-continuation values call-with-values dynamic-wind eval scheme-report-environment null-environment call-with-input-file call-with-output-file input-port? output-port? current-input-port current-output-port with-input-from-file with-output-to-file open-input-file open-output-file close-input-port close-output-port read read-char peek-char eof-object? char-ready? write display newline write-char)) (define promise (delay (r5-env))) (lambda (version) (if (= version 5) (force promise) (open-input-file "sheep-herders/r^-1rs.ltx")))))) [ 1 ] Some claim that this is not required , and that it is compliant for ;; ( let * ( ( x ( string # \a ) ) ( y ( eval x ( null - environment 5 ) ) ) ) ( string - set ! x 0 # \b ) ;; y) ;; ;; to return "b", but I say that's as bogus as if ;; ;; (let* ((x (string #\1)) ;; (y (string->number x))) ( string - set ! x 0 # \2 ) ;; y) ;; returned 2 . Most implementations disagree with me , however . ;; ;; Note: it would be fine to pass through those strings (and pairs and ;; vectors) that are immutable, but we can't portably detect them. ;; Repl provides a simple read-eval-print loop. It semi-supports ;; top-level definitions and syntax definitions, but each one creates ;; a new binding whose region does not include anything that came ;; before the definition, so if you want mutually recursive top-level ;; procedures, you have to do it the hard way: ;; (define f #f) ;; (define (g) (f)) ;; (set! f (lambda () (g))) ;; Repl does not support macro uses that expand into top-level definitions. (define (repl) (let repl ((env (scheme-report-environment 5))) (display "eiod> ") (let ((exp (read))) (if (not (eof-object? exp)) (case (and (pair? exp) (car exp)) ((define define-syntax) (repl (eval `(let () ,exp (get-env)) env))) (else (for-each (lambda (val) (write val) (newline)) (call-with-values (lambda () (eval exp env)) list)) (repl env))))))) (define (tests noisy) (define env (scheme-report-environment 5)) (for-each (lambda (x) (let* ((exp (car x)) (expected (cadr x))) (if noisy (begin (display "Trying: ") (write exp) (newline))) (let* ((result (eval exp env)) (success (equal? result expected))) (if (not success) (begin (display "Failed: ") (if (not noisy) (write exp)) (display " returned ") (write result) (display ", not ") (write expected) (newline)))))) '((1 1) (#t #t) ("hi" "hi") (#\a #\a) ('1 1) ('foo foo) ('(a b) (a b)) ('#(a b) #(a b)) (((lambda (x) x) 1) 1) ((+ 1 2) 3) (((lambda (x) (set! x 2) x) 1) 2) (((lambda () (define x 1) x)) 1) (((lambda () (define (x) 1) (x))) 1) ((begin 1 2) 2) (((lambda () (begin (define x 1)) x)) 1) (((lambda () (begin) 1)) 1) ((let-syntax ((f (syntax-rules () ((_) 1)))) (f)) 1) ((letrec-syntax ((f (syntax-rules () ((_) (f 1)) ((_ x) x)))) (f)) 1) ((let-syntax ((f (syntax-rules () ((_ x ...) '(x ...))))) (f 1 2)) (1 2)) ((let-syntax ((f (syntax-rules () ((_ (x y) ...) '(x ... y ...)) ((_ x ...) '(x ...))))) (f (x1 y1) (x2 y2))) (x1 x2 y1 y2)) ((let-syntax ((let (syntax-rules () ((_ ((var init) ...) . body) '((lambda (var ...) . body) init ...))))) (let ((x 1) (y 2)) (+ x y))) ((lambda (x y) (+ x y)) 1 2)) ((let ((x 1)) x) 1) ((let* ((x 1) (x (+ x 1))) x) 2) ((let ((call/cc call-with-current-continuation)) (letrec ((x (call/cc list)) (y (call/cc list))) (if (procedure? x) (x (pair? y))) (if (procedure? y) (y (pair? x))) (let ((x (car x)) (y (car y))) (and (call/cc x) (call/cc y) (call/cc x))))) #t) ((if 1 2) 2) ((if #f 2 3) 3) ((and 1 #f 2) #f) ((force (delay 1)) 1) ((let* ((x 0) (p (delay (begin (set! x (+ x 1)) x)))) (force p) (force p)) 1) ((let-syntax ((foo (syntax-rules () ((_ (x ...) #(y z ...) ...) '((z ...) ... #((x y) ...)))))) (foo (a b c) #(1 i j) #(2 k l) #(3 m n))) ((i j) (k l) (m n) #((a 1) (b 2) (c 3)))) ((do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i)) #(0 1 2 3 4)) ((let-syntax ((f (syntax-rules (x) ((_ x) 1) ((_ y) 2)))) (define x (f x)) x) 2) ((let-syntax ((f (syntax-rules () ((_) 'x)))) (f)) x) ((let-syntax ((f (syntax-rules () ((_) (let ((x 1)) (let-syntax ((f (syntax-rules () ((_) 'x)))) (f))))))) (f)) x) ((let-syntax ((f (syntax-rules () ((f e a ...) (let-syntax ((g (syntax-rules ::: () ((g n :::) '((a e n :::) ...))))) (g 1 2 3)))))) (f ::: x y z)) ((x ::: 1 2 3) (y ::: 1 2 3) (z ::: 1 2 3))) ((let-syntax ((m (syntax-rules () ((m x ... y) (y x ...))))) (m 1 2 3 -)) -4)))) ;; matching close paren for quote-and-evaluate at beginning of file. )
null
https://raw.githubusercontent.com/melvinzhang/bit-scheme/b6d367cbc8fbfc42e00d310e2a97d263c38694af/eiod.scm
scheme
A minimal implementation of r5rs eval, null-environment, and scheme-report-environment. (And SRFI-46 extensions, too.) You may redistribute and/or modify this software under the terms of either version 2 , or ( at your option ) any later version. Feel free to ask me for different licensing terms. DISCLAIMER: This is only intended as a demonstration of the minimum implementation effort required for an r5rs eval. It serves as a system (and SRFI-46) . Among the reasons that it is ill-suited for production use is the complete lack of error-checking. DATA STRUCTURES: An environment is a procedure that accepts any identifier and returns a denotation. The denotation of an unbound identifier is its name (as a symbol). A bound identifier's denotation is its binding, which is a list of the current value, the binding's type (keyword or variable), and the identifier's name (needed by quote). identifier: [symbol | thunk] denotation: [symbol | binding] binding: [variable-binding | keyword-binding] variable-binding: (value #f symbol) keyword-binding: (special-form #t symbol) special-form: [builtin | transformer] A value is any arbitrary scheme value. Special forms are either a arguments: a macro use and the environment of the macro use. An explicit-renaming low-level macro facility is supported, upon which syntax-rules is implemented. When a syntax-rules template containing a literal identifier is transcribed, the output will contain a fresh identifier, which is an eq?-unique thunk that when invoked returns the old identifier's denotation in the environment is looked up in an environment that has no binding for it, the thunk is invoked and the old denotation is returned. (The thunk actually returns the old denotation wrapped inside a unique pair, which is immediately unwrapped. This is necessary to ensure that different rename thunks of the same denotation do not compare eq?.) variable bindings: lambda, set!, and begin are as in the standard. q is like quote, but it does not handle pairs or vectors. def is like define, but it does not handle the (f . args) format. define-syntax makes internal syntax definitions. (get-env) returns the local environment. (syntax x) is like quote, but does not convert identifiers to symbols. The id? procedure is a predicate for identifiers. The new-id procedure takes a denotation and returns a fresh identifier. Quote-and-evaluate captures all the code into the list eiod-source so that we can have fun feeding eval to itself, as in [Note: using (and even starting) a doubly evaled repl will be *very* slow.] The matching close parenthesis is at the end of the file. Don't use standard map because it might not be continuationally correct. Don't use for-each because we must tail-call the last expression. We make a copy of the initial input to ensure that subsequent Syntax-rules is implemented as a macro that expands into a call to the syntax-rules* procedure, which returns a transformer procedure. The arguments to syntax-rules* are the arguments to syntax-rules plus the current environment, which is captured with get-env. Syntax-rules** is called once with some basics from the base environment. It creates and returns syntax-rules*. List-ids returns a list of the non-ellipsis ids in a pattern or template for which (pred? id) is true. If include-scalars is false, we only include ids that are Returns #f or an alist mapping each pattern var to a part of lists of lists ...). New-literals is an alist mapping each literal id in the template to a fresh id for inserting into the output. It fresh ids, but that's okay because when we go to retrieve a y) to return "b", but I say that's as bogus as if (let* ((x (string #\1)) (y (string->number x))) y) Note: it would be fine to pass through those strings (and pairs and vectors) that are immutable, but we can't portably detect them. Repl provides a simple read-eval-print loop. It semi-supports top-level definitions and syntax definitions, but each one creates a new binding whose region does not include anything that came before the definition, so if you want mutually recursive top-level procedures, you have to do it the hard way: (define f #f) (define (g) (f)) (set! f (lambda () (g))) Repl does not support macro uses that expand into top-level definitions. matching close paren for quote-and-evaluate at beginning of file.
eiod.scm : eval - in - one - define $ I d : eiod.scm , v 1.17 2005/03/26 19:57:44 al Exp $ Copyright 2002 , 2004 , 2005 < > the GNU General Public License as published by the Free Software simple , working example of one way to implement the r5rs macro symbol naming a builtin , or a transformer procedure that takes two of the macro 's definition . When one of these " renamed " identifiers This environment and denotation model is similar to the one described in the 1991 paper " Macros that Work " by Clinger and Rees . The base environment contains eight keyword bindings and two ( ( eval ` ( let ( ) , @eiod - source repl ) ( scheme - report - environment 5 ) ) ) . (define-syntax quote-and-evaluate (syntax-rules () ((quote-and-evaluate var . x) (begin (define var 'x) . x)))) (quote-and-evaluate eiod-source (define (eval sexp env) (define (new-id den) (define p (list den)) (lambda () p)) (define (old-den id) (car (id))) (define (id? x) (or (symbol? x) (procedure? x))) (define (id->sym id) (if (symbol? id) id (den->sym (old-den id)))) (define (den->sym den) (if (symbol? den) den (get-sym den))) (define (empty-env id) (if (symbol? id) id (old-den id))) (define (extend env id binding) (lambda (i) (if (eq? id i) binding (env i)))) (define (add-var var val env) (extend env var (list val #f (id->sym var)))) (define (add-key key val env) (extend env key (list val #t (id->sym key)))) (define (get-val binding) (car binding)) (define (special? binding) (cadr binding)) (define (get-sym binding) (caddr binding)) (define (set-val! binding val) (set-car! binding val)) (define (make-builtins-env) (do ((specials '(lambda set! begin q def define-syntax syntax get-env) (cdr specials)) (env empty-env (add-key (car specials) (car specials) env))) ((null? specials) (add-var 'new-id new-id (add-var 'id? id? env))))) (define (eval sexp env) (let eval-here ((sexp sexp)) (cond ((id? sexp) (get-val (env sexp))) ((not (pair? sexp)) sexp) (else (let ((head (car sexp)) (tail (cdr sexp))) (let ((head-binding (and (id? head) (env head)))) (if (and head-binding (special? head-binding)) (let ((special (get-val head-binding))) (case special ((get-env) env) ((syntax) (car tail)) ((lambda) (eval-lambda tail env)) ((begin) (eval-seq tail env)) ((set!) (set-val! (env (car tail)) (eval-here (cadr tail)))) ((q) (let ((x (car tail))) (if (id? x) (id->sym x) x))) (else (eval-here (special sexp env))))) (apply (eval-here head) (map1 eval-here tail))))))))) (define (map1 f l) (if (null? l) '() (cons (f (car l)) (map1 f (cdr l))))) (define (eval-seq tail env) (do ((sexps tail (cdr sexps))) ((null? (cdr sexps)) (eval (car sexps) env)) (eval (car sexps) env))) (define (eval-lambda tail env) (lambda args (define ienv (do ((args args (cdr args)) (vars (car tail) (cdr vars)) (ienv env (add-var (car vars) (car args) ienv))) ((not (pair? vars)) (if (null? vars) ienv (add-var vars args ienv))))) (let loop ((ienv ienv) (ids '()) (inits '()) (body (cdr tail))) (let ((first (car body)) (rest (cdr body))) (let* ((head (and (pair? first) (car first))) (binding (and (id? head) (ienv head))) (special (and binding (special? binding) (get-val binding)))) (if (procedure? special) (loop ienv ids inits (cons (special first ienv) rest)) (case special ((begin) (loop ienv ids inits (append (cdr first) rest))) ((def define-syntax) (let ((id (cadr first)) (init (caddr first))) (let* ((adder (if (eq? special 'def) add-var add-key)) (ienv (adder id 'undefined ienv))) (loop ienv (cons id ids) (cons init inits) rest)))) (else (let ((ieval (lambda (init) (eval init ienv)))) (for-each set-val! (map ienv ids) (map1 ieval inits)) (eval-seq body ienv)))))))))) mutation of it does not affect eval 's result . [ 1 ] (eval (let copy ((x sexp)) (cond ((string? x) (string-copy x)) ((pair? x) (cons (copy (car x)) (copy (cdr x)))) ((vector? x) (list->vector (copy (vector->list x)))) (else x))) (or env (make-builtins-env)))) (define null-environment (let () (define (syntax-rules** id? new-id denotation-of-default-ellipsis) (define (syntax-rules* mac-env ellipsis pat-literals rules) (define (pat-literal? id) (memq id pat-literals)) (define (not-pat-literal? id) (not (pat-literal? id))) (define (ellipsis-pair? x) (and (pair? x) (ellipsis? (car x)))) (define (ellipsis? x) (if ellipsis (eq? x ellipsis) (and (id? x) (eq? (mac-env x) denotation-of-default-ellipsis)))) within the scope of at least one ellipsis . (define (list-ids x include-scalars pred?) (let collect ((x x) (inc include-scalars) (l '())) (cond ((id? x) (if (and inc (pred? x)) (cons x l) l)) ((vector? x) (collect (vector->list x) inc l)) ((pair? x) (if (ellipsis-pair? (cdr x)) (collect (car x) #t (collect (cddr x) inc l)) (collect (car x) inc (collect (cdr x) inc l)))) (else l)))) the input . Ellipsis vars are mapped to lists of parts ( or (define (match-pattern pat use use-env) (call-with-current-continuation (lambda (return) (define (fail) (return #f)) (let match ((pat (cdr pat)) (sexp (cdr use)) (bindings '())) (define (continue-if condition) (if condition bindings (fail))) (cond ((id? pat) (if (pat-literal? pat) (continue-if (and (id? sexp) (eq? (use-env sexp) (mac-env pat)))) (cons (cons pat sexp) bindings))) ((vector? pat) (or (vector? sexp) (fail)) (match (vector->list pat) (vector->list sexp) bindings)) ((not (pair? pat)) (continue-if (equal? pat sexp))) ((ellipsis-pair? (cdr pat)) (let* ((tail-len (length (cddr pat))) (sexp-len (if (list? sexp) (length sexp) (fail))) (seq-len (- sexp-len tail-len)) (sexp-tail (begin (if (negative? seq-len) (fail)) (list-tail sexp seq-len))) (seq (reverse (list-tail (reverse sexp) tail-len))) (vars (list-ids (car pat) #t not-pat-literal?))) (define (match1 sexp) (map cdr (match (car pat) sexp '()))) (append (apply map list vars (map match1 seq)) (match (cddr pat) sexp-tail bindings)))) ((pair? sexp) (match (car pat) (car sexp) (match (cdr pat) (cdr sexp) bindings))) (else (fail))))))) (define (expand-template pat tmpl top-bindings) might have duplicate entries mapping an i d to two different fresh i d , assq will always retrieve the first one . (define new-literals (map (lambda (id) (cons id (new-id (mac-env id)))) (list-ids tmpl #t (lambda (id) (not (assq id top-bindings)))))) (define ellipsis-vars (list-ids (cdr pat) #f not-pat-literal?)) (define (list-ellipsis-vars subtmpl) (list-ids subtmpl #t (lambda (id) (memq id ellipsis-vars)))) (let expand ((tmpl tmpl) (bindings top-bindings)) (let expand-part ((tmpl tmpl)) (cond ((id? tmpl) (cdr (or (assq tmpl bindings) (assq tmpl top-bindings) (assq tmpl new-literals)))) ((vector? tmpl) (list->vector (expand-part (vector->list tmpl)))) ((pair? tmpl) (if (ellipsis-pair? (cdr tmpl)) (let ((vars-to-iterate (list-ellipsis-vars (car tmpl)))) (define (lookup var) (cdr (assq var bindings))) (define (expand-using-vals . vals) (expand (car tmpl) (map cons vars-to-iterate vals))) (let ((val-lists (map lookup vars-to-iterate))) (append (apply map expand-using-vals val-lists) (expand-part (cddr tmpl))))) (cons (expand-part (car tmpl)) (expand-part (cdr tmpl))))) (else tmpl))))) (lambda (use use-env) (let loop ((rules rules)) (let* ((rule (car rules)) (pat (car rule)) (tmpl (cadr rule))) (cond ((match-pattern pat use use-env) => (lambda (bindings) (expand-template pat tmpl bindings))) (else (loop (cdr rules)))))))) syntax-rules*) (define macro-defs '((define-syntax quote (syntax-rules () ('(x . y) (cons 'x 'y)) ('#(x ...) (list->vector '(x ...))) ('x (q x)))) (define-syntax quasiquote (syntax-rules (unquote unquote-splicing quasiquote) (`,x x) (`(,@x . y) (append x `y)) ((_ `x . d) (cons 'quasiquote (quasiquote (x) d))) ((_ ,x d) (cons 'unquote (quasiquote (x) . d))) ((_ ,@x d) (cons 'unquote-splicing (quasiquote (x) . d))) ((_ (x . y) . d) (cons (quasiquote x . d) (quasiquote y . d))) ((_ #(x ...) . d) (list->vector (quasiquote (x ...) . d))) ((_ x . d) 'x))) (define-syntax do (syntax-rules () ((_ ((var init . step) ...) ending expr ...) (let loop ((var init) ...) (cond ending (else expr ... (loop (begin var . step) ...))))))) (define-syntax letrec (syntax-rules () ((_ ((var init) ...) . body) (let () (def var init) ... (let () . body))))) (define-syntax letrec-syntax (syntax-rules () ((_ ((key trans) ...) . body) (let () (define-syntax key trans) ... (let () . body))))) (define-syntax let-syntax (syntax-rules () ((_ () . body) (let () . body)) ((_ ((key trans) . bindings) . body) (letrec-syntax ((temp trans)) (let-syntax bindings (letrec-syntax ((key temp)) . body)))))) (define-syntax let* (syntax-rules () ((_ () . body) (let () . body)) ((_ (first . more) . body) (let (first) (let* more . body))))) (define-syntax let (syntax-rules () ((_ ((var init) ...) . body) ((lambda (var ...) . body) init ...)) ((_ name ((var init) ...) . body) ((letrec ((name (lambda (var ...) . body))) name) init ...)))) (define-syntax case (syntax-rules () ((_ x (test . exprs) ...) (let ((key x)) (cond ((case-test key test) . exprs) ...))))) (define-syntax case-test (syntax-rules (else) ((_ k else) #t) ((_ k atoms) (memv k 'atoms)))) (define-syntax cond (syntax-rules (else =>) ((_) #f) ((_ (else . exps)) (begin #f . exps)) ((_ (x) . rest) (or x (cond . rest))) ((_ (x => proc) . rest) (let ((tmp x)) (cond (tmp (proc tmp)) . rest))) ((_ (x . exps) . rest) (if x (begin . exps) (cond . rest))))) (define-syntax and (syntax-rules () ((_) #t) ((_ test) test) ((_ test . tests) (if test (and . tests) #f)))) (define-syntax or (syntax-rules () ((_) #f) ((_ test) test) ((_ test . tests) (let ((x test)) (if x x (or . tests)))))) (define-syntax define (syntax-rules () ((_ (var . args) . body) (define var (lambda args . body))) ((_ var init) (def var init)))) (define-syntax if (syntax-rules () ((_ x y ...) (if* x (lambda () y) ...)))) (define-syntax delay (syntax-rules () ((_ x) (delay* (lambda () x))))))) (define (if* a b . c) (if a (b) (if (pair? c) ((car c))))) (define (delay* thunk) (delay (thunk))) (define (null-env) ((eval `(lambda (cons append list->vector memv delay* if* syntax-rules**) ((lambda (syntax-rules*) (define-syntax syntax-rules (syntax-rules* (get-env) #f (syntax ()) (syntax (((_ (lit ...) . rules) (syntax-rules #f (lit ...) . rules)) ((_ ellipsis lits . rules) (syntax-rules* (get-env) (syntax ellipsis) (syntax lits) (syntax rules))))))) ((lambda () ,@macro-defs (get-env)))) (syntax-rules** id? new-id ((get-env) (syntax ...))))) #f) cons append list->vector memv delay* if* syntax-rules**)) (define promise (delay (null-env))) (lambda (version) (if (= version 5) (force promise) (open-input-file "sheep-herders/r^-1rs.ltx"))))) (define scheme-report-environment (let-syntax ((extend-env (syntax-rules () ((extend-env env . names) ((eval '(lambda names (get-env)) env) . names))))) (let () (define (r5-env) (extend-env (null-environment 5) eqv? eq? equal? number? complex? real? rational? integer? exact? inexact? = < > <= >= zero? positive? negative? odd? even? max min + * - / abs quotient remainder modulo gcd lcm numerator denominator floor ceiling truncate round rationalize exp log sin cos tan asin acos atan sqrt expt make-rectangular make-polar real-part imag-part magnitude angle exact->inexact inexact->exact number->string string->number not boolean? pair? cons car cdr set-car! set-cdr! caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr null? list? list length append reverse list-tail list-ref memq memv member assq assv assoc symbol? symbol->string string->symbol char? char=? char<? char>? char<=? char>=? char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=? char-alphabetic? char-numeric? char-whitespace? char-upper-case? char-lower-case? char->integer integer->char char-upcase char-downcase string? make-string string string-length string-ref string-set! string=? string-ci=? string<? string>? string<=? string>=? string-ci<? string-ci>? string-ci<=? string-ci>=? substring string-append string->list list->string string-copy string-fill! vector? make-vector vector vector-length vector-ref vector-set! vector->list list->vector vector-fill! procedure? apply map for-each force call-with-current-continuation values call-with-values dynamic-wind eval scheme-report-environment null-environment call-with-input-file call-with-output-file input-port? output-port? current-input-port current-output-port with-input-from-file with-output-to-file open-input-file open-output-file close-input-port close-output-port read read-char peek-char eof-object? char-ready? write display newline write-char)) (define promise (delay (r5-env))) (lambda (version) (if (= version 5) (force promise) (open-input-file "sheep-herders/r^-1rs.ltx")))))) [ 1 ] Some claim that this is not required , and that it is compliant for ( let * ( ( x ( string # \a ) ) ( y ( eval x ( null - environment 5 ) ) ) ) ( string - set ! x 0 # \b ) ( string - set ! x 0 # \2 ) returned 2 . Most implementations disagree with me , however . (define (repl) (let repl ((env (scheme-report-environment 5))) (display "eiod> ") (let ((exp (read))) (if (not (eof-object? exp)) (case (and (pair? exp) (car exp)) ((define define-syntax) (repl (eval `(let () ,exp (get-env)) env))) (else (for-each (lambda (val) (write val) (newline)) (call-with-values (lambda () (eval exp env)) list)) (repl env))))))) (define (tests noisy) (define env (scheme-report-environment 5)) (for-each (lambda (x) (let* ((exp (car x)) (expected (cadr x))) (if noisy (begin (display "Trying: ") (write exp) (newline))) (let* ((result (eval exp env)) (success (equal? result expected))) (if (not success) (begin (display "Failed: ") (if (not noisy) (write exp)) (display " returned ") (write result) (display ", not ") (write expected) (newline)))))) '((1 1) (#t #t) ("hi" "hi") (#\a #\a) ('1 1) ('foo foo) ('(a b) (a b)) ('#(a b) #(a b)) (((lambda (x) x) 1) 1) ((+ 1 2) 3) (((lambda (x) (set! x 2) x) 1) 2) (((lambda () (define x 1) x)) 1) (((lambda () (define (x) 1) (x))) 1) ((begin 1 2) 2) (((lambda () (begin (define x 1)) x)) 1) (((lambda () (begin) 1)) 1) ((let-syntax ((f (syntax-rules () ((_) 1)))) (f)) 1) ((letrec-syntax ((f (syntax-rules () ((_) (f 1)) ((_ x) x)))) (f)) 1) ((let-syntax ((f (syntax-rules () ((_ x ...) '(x ...))))) (f 1 2)) (1 2)) ((let-syntax ((f (syntax-rules () ((_ (x y) ...) '(x ... y ...)) ((_ x ...) '(x ...))))) (f (x1 y1) (x2 y2))) (x1 x2 y1 y2)) ((let-syntax ((let (syntax-rules () ((_ ((var init) ...) . body) '((lambda (var ...) . body) init ...))))) (let ((x 1) (y 2)) (+ x y))) ((lambda (x y) (+ x y)) 1 2)) ((let ((x 1)) x) 1) ((let* ((x 1) (x (+ x 1))) x) 2) ((let ((call/cc call-with-current-continuation)) (letrec ((x (call/cc list)) (y (call/cc list))) (if (procedure? x) (x (pair? y))) (if (procedure? y) (y (pair? x))) (let ((x (car x)) (y (car y))) (and (call/cc x) (call/cc y) (call/cc x))))) #t) ((if 1 2) 2) ((if #f 2 3) 3) ((and 1 #f 2) #f) ((force (delay 1)) 1) ((let* ((x 0) (p (delay (begin (set! x (+ x 1)) x)))) (force p) (force p)) 1) ((let-syntax ((foo (syntax-rules () ((_ (x ...) #(y z ...) ...) '((z ...) ... #((x y) ...)))))) (foo (a b c) #(1 i j) #(2 k l) #(3 m n))) ((i j) (k l) (m n) #((a 1) (b 2) (c 3)))) ((do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i)) #(0 1 2 3 4)) ((let-syntax ((f (syntax-rules (x) ((_ x) 1) ((_ y) 2)))) (define x (f x)) x) 2) ((let-syntax ((f (syntax-rules () ((_) 'x)))) (f)) x) ((let-syntax ((f (syntax-rules () ((_) (let ((x 1)) (let-syntax ((f (syntax-rules () ((_) 'x)))) (f))))))) (f)) x) ((let-syntax ((f (syntax-rules () ((f e a ...) (let-syntax ((g (syntax-rules ::: () ((g n :::) '((a e n :::) ...))))) (g 1 2 3)))))) (f ::: x y z)) ((x ::: 1 2 3) (y ::: 1 2 3) (z ::: 1 2 3))) ((let-syntax ((m (syntax-rules () ((m x ... y) (y x ...))))) (m 1 2 3 -)) -4)))) )
ccfdc68aabfb4d90e8dc66a8ed06fdde35f0c2f85f04c6607a2e75455349266b
noinia/hgeometry
Reader.hs
# LANGUAGE UndecidableInstances # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Ipe.Reader ( -- * Reading ipe Files readRawIpeFile , readIpeFile , readSinglePageFile , readSinglePageFileThrow , ConversionError -- * Readiing ipe style files , readIpeStylesheet , addStyleSheetFrom -- * Reading XML directly , fromIpeXML , readXML -- * Read classes , IpeReadText(..) , IpeRead(..) , IpeReadAttr(..) -- * Some low level implementation functions , ipeReadTextWith , ipeReadObject , ipeReadAttrs , ipeReadRec , Coordinate(..) ) where import Control.Applicative ((<|>)) import Control.Lens hiding (Const, rmap) import Control.Monad ((<=<)) import Data.Bifunctor import qualified Data.ByteString as B import Data.Colour.SRGB (RGB(..)) import Data.Either (rights) import Data.Ext import Geometry hiding (head) import Geometry.BezierSpline import Geometry.Box import Geometry.Ellipse (ellipseMatrix) import qualified Geometry.Matrix as Matrix import Ipe.Attributes import Ipe.Color (IpeColor(..)) import Ipe.Matrix import Ipe.ParserPrimitives (pInteger, pWhiteSpace) import Ipe.Path import Ipe.PathParser import Ipe.Types import Ipe.Value import qualified Geometry.Polygon as Polygon import qualified Data.LSeq as LSeq import qualified Data.List as L import qualified Data.List.NonEmpty as NonEmpty import Data.Maybe (fromMaybe, mapMaybe) import Data.Proxy import Data.Singletons import Data.Text (Text) import qualified Data.Text as T import qualified Data.Traversable as Tr import Data.Vinyl hiding (Label) import Data.Vinyl.Functor import Data.Vinyl.TypeLevel import Text.XML.Expat.Tree -------------------------------------------------------------------------------- type ConversionError = Text -- | Given a file path, tries to read an ipe file readRawIpeFile :: (Coordinate r, Eq r) => FilePath -> IO (Either ConversionError (IpeFile r)) readRawIpeFile = fmap fromIpeXML . B.readFile -- | Given a file path, tries to read an ipe file. -- -- This function applies all matrices to objects. readIpeFile :: (Coordinate r, Eq r) => FilePath -> IO (Either ConversionError (IpeFile r)) readIpeFile = fmap (second applyMatrices) . readRawIpeFile | Since most Ipe file contain only one page , we provide a shortcut for that -- as well. -- -- This function applies all matrices, and it makes sure there is at -- least one layer and view in the page. -- readSinglePageFile :: (Coordinate r, Eq r) => FilePath -> IO (Either ConversionError (IpePage r)) readSinglePageFile = fmap (fmap f) . readIpeFile where f :: IpeFile r -> IpePage r f i = withDefaults . NonEmpty.head $ i^.pages -- | Tries to read a single page file, throws an error when this -- fails. See 'readSinglePageFile' for further details. readSinglePageFileThrow :: (Coordinate r, Eq r) => FilePath -> IO (IpePage r) readSinglePageFileThrow fp = readSinglePageFile fp >>= \case Left err -> fail (show err) Right p -> pure p | Given a Bytestring , try to parse the bytestring into anything that is IpeReadable , i.e. any of the Ipe elements . fromIpeXML :: IpeRead (t r) => B.ByteString -> Either ConversionError (t r) fromIpeXML b = readXML b >>= ipeRead | Reads the data from a Bytestring into a proper Node readXML :: B.ByteString -> Either ConversionError (Node Text Text) readXML = first (T.pack . show) . parse' defaultParseOptions -------------------------------------------------------------------------------- -- | Reading an ipe elemtn from a Text value class IpeReadText t where ipeReadText :: Text -> Either ConversionError t -- | Reading an ipe lement from Xml class IpeRead t where ipeRead :: Node Text Text -> Either ConversionError t -------------------------------------------------------------------------------- ReadText instances instance IpeReadText Text where ipeReadText = Right instance IpeReadText Int where ipeReadText = fmap fromInteger . runParser pInteger instance Coordinate r => IpeReadText (Point 2 r) where ipeReadText = readPoint instance Coordinate r => IpeReadText (Matrix.Matrix 3 3 r) where ipeReadText = readMatrix instance IpeReadText LayerName where ipeReadText = Right . LayerName instance IpeReadText PinType where ipeReadText "yes" = Right Yes ipeReadText "h" = Right Horizontal ipeReadText "v" = Right Vertical ipeReadText "" = Right No ipeReadText _ = Left "invalid PinType" instance IpeReadText TransformationTypes where ipeReadText "affine" = Right Affine ipeReadText "rigid" = Right Rigid ipeReadText "translations" = Right Translations ipeReadText _ = Left "invalid TransformationType" instance IpeReadText FillType where ipeReadText "wind" = Right Wind ipeReadText "eofill" = Right EOFill ipeReadText _ = Left "invalid FillType" instance Coordinate r => IpeReadText (IpeArrow r) where ipeReadText t = case T.split (== '/') t of [n,s] -> IpeArrow <$> pure n <*> ipeReadText s _ -> Left "ipeArrow: name contains not exactly 1 / " instance Coordinate r => IpeReadText (IpeDash r) where ipeReadText t = Right . DashNamed $ t -- TODO: Implement proper parsing here instance IpeReadText HorizontalAlignment where ipeReadText = \case "left" -> Right AlignLeft "center" -> Right AlignHCenter "right" -> Right AlignRight _ -> Left "invalid HorizontalAlignment" instance IpeReadText VerticalAlignment where ipeReadText = \case "top" -> Right AlignTop "center" -> Right AlignVCenter "bottom" -> Right AlignBottom "baseline" -> Right AlignBaseline _ -> Left "invalid VerticalAlignment" ipeReadTextWith :: (Text -> Either t v) -> Text -> Either ConversionError (IpeValue v) ipeReadTextWith f t = case f t of Right v -> Right (Valued v) Left _ -> Right (Named t) instance Coordinate r => IpeReadText (Rectangle () r) where ipeReadText = readRectangle instance Coordinate r => IpeReadText (RGB r) where ipeReadText = runParser (pRGB <|> pGrey) where pGrey = (\c -> RGB c c c) <$> pCoordinate pRGB = RGB <$> pCoordinate <* pWhiteSpace <*> pCoordinate <* pWhiteSpace <*> pCoordinate instance Coordinate r => IpeReadText (IpeColor r) where ipeReadText = fmap IpeColor . ipeReadTextWith ipeReadText instance Coordinate r => IpeReadText (IpePen r) where ipeReadText = fmap IpePen . ipeReadTextWith readCoordinate instance Coordinate r => IpeReadText (IpeSize r) where ipeReadText = fmap IpeSize . ipeReadTextWith readCoordinate instance Coordinate r => IpeReadText [Operation r] where ipeReadText = readPathOperations instance (Coordinate r, Fractional r, Eq r) => IpeReadText (NonEmpty.NonEmpty (PathSegment r)) where ipeReadText t = ipeReadText t >>= fromOpsN where fromOpsN xs = case fromOps xs of Left l -> Left l Right [] -> Left "No path segments produced" Right (p:ps) -> Right $ p NonEmpty.:| ps fromOps [] = Right [] fromOps [Ellipse m] = Right [EllipseSegment . view (from ellipseMatrix) $ m] fromOps (MoveTo p:xs) = fromOps' p xs fromOps _ = Left "Path should start with a move to" fromOps' _ [] = Left "Found only a MoveTo operation" fromOps' s (LineTo q:ops) = let (ls,xs) = span' _LineTo ops pts = map ext $ s:q:mapMaybe (^?_LineTo) ls poly = Polygon.unsafeFromPoints . dropRepeats $ pts pl = fromPointsUnsafe pts in case xs of (ClosePath : xs') -> PolygonPath poly <<| xs' _ -> PolyLineSegment pl <<| xs fromOps' s [Spline [a, b]] = Right [QuadraticBezierSegment $ Bezier2 s a b] fromOps' s [Spline [a, b, c]] = Right [CubicBezierSegment $ Bezier3 s a b c] fromOps' s [Spline ps] = Right $ map CubicBezierSegment $ splineToCubicBeziers $ s : ps -- these will not occur anymore with recent ipe files fromOps' s [QCurveTo a b] = Right [QuadraticBezierSegment $ Bezier2 s a b] fromOps' s [CurveTo a b c] = Right [CubicBezierSegment $ Bezier3 s a b c] fromOps' _ _ = Left "fromOpts': rest not implemented yet." span' pr = L.span (not . isn't pr) x <<| xs = (x:) <$> fromOps xs -- | Read a list of control points of a uniform cubic B-spline and conver it to pieces splineToCubicBeziers :: Fractional r => [Point 2 r] -> [BezierSpline 3 2 r] splineToCubicBeziers [a, b, c, d] = [Bezier3 a b c d] splineToCubicBeziers (a : b : c : d : rest) = let p = b .+^ (c .-. b) ^/ 2 q = c .+^ (d .-. c) ^/ 3 r = p .+^ (q .-. p) ^/ 2 in (Bezier3 a b p r) : splineToCubicBeziers (r : q : d : rest) splineToCubicBeziers _ = error "splineToCubicBeziers needs at least four points" dropRepeats :: Eq a => [a] -> [a] dropRepeats = map head . L.group instance (Coordinate r, Fractional r, Eq r) => IpeReadText (Path r) where ipeReadText = fmap (Path . LSeq.fromNonEmpty) . ipeReadText -------------------------------------------------------------------------------- -- Reading attributes -- | Basically IpeReadText for attributes. This class is not really meant to be -- implemented directly. Just define an IpeReadText instance for the type -- (Apply f at), then the generic instance below takes care of looking up the -- name of the attribute, and calling the right ipeReadText value. This class is just so that in ` ipeReadRec ` can select the right -- typeclass when building the rec. class IpeReadAttr t where ipeReadAttr :: Text -> Node Text Text -> Either ConversionError t instance IpeReadText (Apply f at) => IpeReadAttr (Attr f at) where ipeReadAttr n (Element _ ats _) = GAttr <$> Tr.mapM ipeReadText (lookup n ats) ipeReadAttr _ _ = Left "IpeReadAttr: Element expected, Text found" -- | Combination of zipRecWith and traverse zipTraverseWith :: forall f g h i (rs :: [AttributeUniverse]). Applicative h => (forall (x :: AttributeUniverse). f x -> g x -> h (i x)) -> Rec f rs -> Rec g rs -> h (Rec i rs) zipTraverseWith _ RNil RNil = pure RNil zipTraverseWith f (x :& xs) (y :& ys) = (:&) <$> f x y <*> zipTraverseWith f xs ys -- | Reading the Attributes into a Rec (Attr f), all based on the types of f -- (the type family mapping labels to types), and a list of labels (ats). ipeReadRec :: forall f ats. ( RecApplicative ats , ReifyConstraint IpeReadAttr (Attr f) ats , RecAll (Attr f) ats IpeReadAttr , AllConstrained IpeAttrName ats ) => Proxy f -> Proxy ats -> Node Text Text -> Either ConversionError (Rec (Attr f) ats) ipeReadRec _ _ x = zipTraverseWith f (writeAttrNames r) r' where r = rpure (GAttr Nothing) r' = reifyConstraint @IpeReadAttr r f :: forall at. Const Text at -> (Dict IpeReadAttr :. Attr f) at -> Either ConversionError (Attr f at) f (Const n) (Compose (Dict _)) = ipeReadAttr n x -- | Reader for records. Given a proxy of some ipe type i, and a proxy of an -- coordinate type r, read the IpeAttributes for i from the xml node. ipeReadAttrs :: forall proxy proxy' i r f ats. ( f ~ AttrMapSym1 r, ats ~ AttributesOf i , ReifyConstraint IpeReadAttr (Attr f) ats , RecApplicative ats , RecAll (Attr f) ats IpeReadAttr , AllConstrained IpeAttrName ats ) => proxy i -> proxy' r -> Node Text Text -> Either ConversionError (IpeAttributes i r) ipeReadAttrs _ _ = fmap Attrs . ipeReadRec (Proxy :: Proxy f) (Proxy :: Proxy ats) -- testSym :: B.ByteString testSym = " < use name=\"mark / disk(sx)\ " pos=\"320 " size=\"normal\ " stroke=\"black\"/ > " -- readAttrsFromXML :: B.ByteString -> Either readSymAttrs : : Either ConversionError ( IpeAttributes IpeSymbol Double ) -- readSymAttrs = readXML testSym > > = ipeReadAttrs ( Proxy : : Proxy IpeSymbol ) ( Proxy : : Proxy Double ) | If we can ipeRead an ipe element , and we can ipeReadAttrs its attributes we can properly read an ipe object using ipeReadObject ipeReadObject :: ( IpeRead (i r) , f ~ AttrMapSym1 r, ats ~ AttributesOf i , RecApplicative ats , ReifyConstraint IpeReadAttr (Attr f) ats , RecAll (Attr f) ats IpeReadAttr , AllConstrained IpeAttrName ats ) => Proxy i -> proxy r -> Node Text Text -> Either ConversionError (i r :+ IpeAttributes i r) ipeReadObject prI prR xml = (:+) <$> ipeRead xml <*> ipeReadAttrs prI prR xml -------------------------------------------------------------------------------- -- | Ipe read instances instance Coordinate r => IpeRead (IpeSymbol r) where ipeRead (Element "use" ats _) = case lookup "pos" ats of Nothing -> Left "symbol without position" Just ps -> flip Symbol name <$> ipeReadText ps where name = fromMaybe "mark/disk(sx)" $ lookup "name" ats ipeRead _ = Left "symbol element expected, text found" -- | Given a list of Nodes, try to parse all of them as a big text. If we -- encounter anything else then text, the parsing fails. allText :: [Node Text Text] -> Either ConversionError Text allText = fmap T.unlines . mapM unT where unT (Text t) = Right t unT _ = Left "allText: Expected Text, found an Element" instance (Coordinate r, Fractional r, Eq r) => IpeRead (Path r) where ipeRead (Element "path" _ chs) = allText chs >>= ipeReadText ipeRead _ = Left "path: expected element, found text" lookup' :: Text -> [(Text,a)] -> Either ConversionError a lookup' k = maybe (Left $ "lookup' " <> k <> " not found") Right . lookup k instance Coordinate r => IpeRead (TextLabel r) where ipeRead (Element "text" ats chs) | lookup "type" ats == Just "label" = Label <$> allText chs <*> (lookup' "pos" ats >>= ipeReadText) | otherwise = Left "Not a Text label" ipeRead _ = Left "textlabel: Expected element, found text" instance Coordinate r => IpeRead (MiniPage r) where ipeRead (Element "text" ats chs) | lookup "type" ats == Just "minipage" = MiniPage <$> allText chs <*> (lookup' "pos" ats >>= ipeReadText) <*> (lookup' "width" ats >>= readCoordinate) | otherwise = Left "Not a MiniPage" ipeRead _ = Left "MiniPage: Expected element, found text" instance Coordinate r => IpeRead (Image r) where ipeRead (Element "image" ats _) = Image () <$> (lookup' "rect" ats >>= ipeReadText) ipeRead _ = Left "Image: Element expected, text found" instance (Coordinate r, Fractional r, Eq r) => IpeRead (IpeObject r) where ipeRead x = firstRight [ IpeUse <$> ipeReadObject (Proxy :: Proxy IpeSymbol) r x , IpePath <$> ipeReadObject (Proxy :: Proxy Path) r x , IpeGroup <$> ipeReadObject (Proxy :: Proxy Group) r x , IpeTextLabel <$> ipeReadObject (Proxy :: Proxy TextLabel) r x , IpeMiniPage <$> ipeReadObject (Proxy :: Proxy MiniPage) r x , IpeImage <$> ipeReadObject (Proxy :: Proxy Image) r x ] where r = Proxy :: Proxy r firstRight :: [Either ConversionError a] -> Either ConversionError a firstRight = maybe (Left "No matching object") Right . firstOf (traverse._Right) instance (Coordinate r, Eq r) => IpeRead (Group r) where ipeRead (Element "group" _ chs) = Right . Group . rights . map ipeRead $ chs ipeRead _ = Left "ipeRead Group: expected Element, found Text" instance IpeRead LayerName where ipeRead (Element "layer" ats _) = LayerName <$> lookup' "name" ats ipeRead _ = Left "layer: Expected element, found text" instance IpeRead View where ipeRead (Element "view" ats _) = (\lrs a -> View (map LayerName $ T.words lrs) a) <$> lookup' "layers" ats <*> (lookup' "active" ats >>= ipeReadText) ipeRead _ = Left "View Expected element, found text" -- TODO: this instance throws away all of our error collecting (and is pretty -- slow/stupid since it tries parsing all children with all parsers) instance (Coordinate r, Eq r) => IpeRead (IpePage r) where ipeRead (Element "page" _ chs) = Right $ IpePage (readAll chs) (readAll chs) (readAll chs) ipeRead _ = Left "page: Element expected, text found" -- withDef :: b -> Either a b -> Either c b -- withDef d = either (const $ Right d) Right -- readLayers = withDef ["alpha"] . readAll -- readViews = withDef [] . readAll -- readObjects = withDef [] . readAll -- | try reading everything as an a. Throw away whatever fails. readAll :: IpeRead a => [Node Text Text] -> [a] readAll = rights . map ipeRead instance (Coordinate r, Eq r) => IpeRead (IpeFile r) where ipeRead (Element "ipe" _ chs) = case readAll chs of [] -> Left "Ipe: no pages found" pgs -> Right $ IpeFile Nothing [] (NonEmpty.fromList pgs) ipeRead _ = Left "Ipe: Element expected, text found" instance IpeRead IpeStyle where ipeRead = \case xml@(Element "ipestyle" ats _) -> Right $ IpeStyle (lookup "name" ats) xml _ -> Left "ipeStyle exptected. Something else found" | Reads an Ipe stylesheet from Disk . readIpeStylesheet :: FilePath -> IO (Either ConversionError IpeStyle) readIpeStylesheet = fmap (ipeRead <=< readXML) . B.readFile -- | Given a path to a stylesheet, add it to the ipe file with the -- highest priority. Throws an error when this fails. addStyleSheetFrom :: FilePath -> IpeFile r -> IO (IpeFile r) addStyleSheetFrom fp f = readIpeStylesheet fp >>= \case Left err -> fail (show err) Right s -> pure $ addStyleSheet s f --------------------------------------------------------------------------------
null
https://raw.githubusercontent.com/noinia/hgeometry/89cd3d3109ec68f877bf8e34dc34b6df337a4ec1/hgeometry-ipe/src/Ipe/Reader.hs
haskell
# LANGUAGE OverloadedStrings # * Reading ipe Files * Readiing ipe style files * Reading XML directly * Read classes * Some low level implementation functions ------------------------------------------------------------------------------ | Given a file path, tries to read an ipe file | Given a file path, tries to read an ipe file. This function applies all matrices to objects. as well. This function applies all matrices, and it makes sure there is at least one layer and view in the page. | Tries to read a single page file, throws an error when this fails. See 'readSinglePageFile' for further details. ------------------------------------------------------------------------------ | Reading an ipe elemtn from a Text value | Reading an ipe lement from Xml ------------------------------------------------------------------------------ TODO: Implement proper parsing here these will not occur anymore with recent ipe files | Read a list of control points of a uniform cubic B-spline and conver it ------------------------------------------------------------------------------ Reading attributes | Basically IpeReadText for attributes. This class is not really meant to be implemented directly. Just define an IpeReadText instance for the type (Apply f at), then the generic instance below takes care of looking up the name of the attribute, and calling the right ipeReadText value. This class typeclass when building the rec. | Combination of zipRecWith and traverse | Reading the Attributes into a Rec (Attr f), all based on the types of f (the type family mapping labels to types), and a list of labels (ats). | Reader for records. Given a proxy of some ipe type i, and a proxy of an coordinate type r, read the IpeAttributes for i from the xml node. testSym :: B.ByteString readAttrsFromXML :: B.ByteString -> Either readSymAttrs = readXML testSym ------------------------------------------------------------------------------ | Ipe read instances | Given a list of Nodes, try to parse all of them as a big text. If we encounter anything else then text, the parsing fails. TODO: this instance throws away all of our error collecting (and is pretty slow/stupid since it tries parsing all children with all parsers) withDef :: b -> Either a b -> Either c b withDef d = either (const $ Right d) Right readLayers = withDef ["alpha"] . readAll readViews = withDef [] . readAll readObjects = withDef [] . readAll | try reading everything as an a. Throw away whatever fails. | Given a path to a stylesheet, add it to the ipe file with the highest priority. Throws an error when this fails. ------------------------------------------------------------------------------
# LANGUAGE UndecidableInstances # # LANGUAGE ScopedTypeVariables # module Ipe.Reader readRawIpeFile , readIpeFile , readSinglePageFile , readSinglePageFileThrow , ConversionError , readIpeStylesheet , addStyleSheetFrom , fromIpeXML , readXML , IpeReadText(..) , IpeRead(..) , IpeReadAttr(..) , ipeReadTextWith , ipeReadObject , ipeReadAttrs , ipeReadRec , Coordinate(..) ) where import Control.Applicative ((<|>)) import Control.Lens hiding (Const, rmap) import Control.Monad ((<=<)) import Data.Bifunctor import qualified Data.ByteString as B import Data.Colour.SRGB (RGB(..)) import Data.Either (rights) import Data.Ext import Geometry hiding (head) import Geometry.BezierSpline import Geometry.Box import Geometry.Ellipse (ellipseMatrix) import qualified Geometry.Matrix as Matrix import Ipe.Attributes import Ipe.Color (IpeColor(..)) import Ipe.Matrix import Ipe.ParserPrimitives (pInteger, pWhiteSpace) import Ipe.Path import Ipe.PathParser import Ipe.Types import Ipe.Value import qualified Geometry.Polygon as Polygon import qualified Data.LSeq as LSeq import qualified Data.List as L import qualified Data.List.NonEmpty as NonEmpty import Data.Maybe (fromMaybe, mapMaybe) import Data.Proxy import Data.Singletons import Data.Text (Text) import qualified Data.Text as T import qualified Data.Traversable as Tr import Data.Vinyl hiding (Label) import Data.Vinyl.Functor import Data.Vinyl.TypeLevel import Text.XML.Expat.Tree type ConversionError = Text readRawIpeFile :: (Coordinate r, Eq r) => FilePath -> IO (Either ConversionError (IpeFile r)) readRawIpeFile = fmap fromIpeXML . B.readFile readIpeFile :: (Coordinate r, Eq r) => FilePath -> IO (Either ConversionError (IpeFile r)) readIpeFile = fmap (second applyMatrices) . readRawIpeFile | Since most Ipe file contain only one page , we provide a shortcut for that readSinglePageFile :: (Coordinate r, Eq r) => FilePath -> IO (Either ConversionError (IpePage r)) readSinglePageFile = fmap (fmap f) . readIpeFile where f :: IpeFile r -> IpePage r f i = withDefaults . NonEmpty.head $ i^.pages readSinglePageFileThrow :: (Coordinate r, Eq r) => FilePath -> IO (IpePage r) readSinglePageFileThrow fp = readSinglePageFile fp >>= \case Left err -> fail (show err) Right p -> pure p | Given a Bytestring , try to parse the bytestring into anything that is IpeReadable , i.e. any of the Ipe elements . fromIpeXML :: IpeRead (t r) => B.ByteString -> Either ConversionError (t r) fromIpeXML b = readXML b >>= ipeRead | Reads the data from a Bytestring into a proper Node readXML :: B.ByteString -> Either ConversionError (Node Text Text) readXML = first (T.pack . show) . parse' defaultParseOptions class IpeReadText t where ipeReadText :: Text -> Either ConversionError t class IpeRead t where ipeRead :: Node Text Text -> Either ConversionError t ReadText instances instance IpeReadText Text where ipeReadText = Right instance IpeReadText Int where ipeReadText = fmap fromInteger . runParser pInteger instance Coordinate r => IpeReadText (Point 2 r) where ipeReadText = readPoint instance Coordinate r => IpeReadText (Matrix.Matrix 3 3 r) where ipeReadText = readMatrix instance IpeReadText LayerName where ipeReadText = Right . LayerName instance IpeReadText PinType where ipeReadText "yes" = Right Yes ipeReadText "h" = Right Horizontal ipeReadText "v" = Right Vertical ipeReadText "" = Right No ipeReadText _ = Left "invalid PinType" instance IpeReadText TransformationTypes where ipeReadText "affine" = Right Affine ipeReadText "rigid" = Right Rigid ipeReadText "translations" = Right Translations ipeReadText _ = Left "invalid TransformationType" instance IpeReadText FillType where ipeReadText "wind" = Right Wind ipeReadText "eofill" = Right EOFill ipeReadText _ = Left "invalid FillType" instance Coordinate r => IpeReadText (IpeArrow r) where ipeReadText t = case T.split (== '/') t of [n,s] -> IpeArrow <$> pure n <*> ipeReadText s _ -> Left "ipeArrow: name contains not exactly 1 / " instance Coordinate r => IpeReadText (IpeDash r) where ipeReadText t = Right . DashNamed $ t instance IpeReadText HorizontalAlignment where ipeReadText = \case "left" -> Right AlignLeft "center" -> Right AlignHCenter "right" -> Right AlignRight _ -> Left "invalid HorizontalAlignment" instance IpeReadText VerticalAlignment where ipeReadText = \case "top" -> Right AlignTop "center" -> Right AlignVCenter "bottom" -> Right AlignBottom "baseline" -> Right AlignBaseline _ -> Left "invalid VerticalAlignment" ipeReadTextWith :: (Text -> Either t v) -> Text -> Either ConversionError (IpeValue v) ipeReadTextWith f t = case f t of Right v -> Right (Valued v) Left _ -> Right (Named t) instance Coordinate r => IpeReadText (Rectangle () r) where ipeReadText = readRectangle instance Coordinate r => IpeReadText (RGB r) where ipeReadText = runParser (pRGB <|> pGrey) where pGrey = (\c -> RGB c c c) <$> pCoordinate pRGB = RGB <$> pCoordinate <* pWhiteSpace <*> pCoordinate <* pWhiteSpace <*> pCoordinate instance Coordinate r => IpeReadText (IpeColor r) where ipeReadText = fmap IpeColor . ipeReadTextWith ipeReadText instance Coordinate r => IpeReadText (IpePen r) where ipeReadText = fmap IpePen . ipeReadTextWith readCoordinate instance Coordinate r => IpeReadText (IpeSize r) where ipeReadText = fmap IpeSize . ipeReadTextWith readCoordinate instance Coordinate r => IpeReadText [Operation r] where ipeReadText = readPathOperations instance (Coordinate r, Fractional r, Eq r) => IpeReadText (NonEmpty.NonEmpty (PathSegment r)) where ipeReadText t = ipeReadText t >>= fromOpsN where fromOpsN xs = case fromOps xs of Left l -> Left l Right [] -> Left "No path segments produced" Right (p:ps) -> Right $ p NonEmpty.:| ps fromOps [] = Right [] fromOps [Ellipse m] = Right [EllipseSegment . view (from ellipseMatrix) $ m] fromOps (MoveTo p:xs) = fromOps' p xs fromOps _ = Left "Path should start with a move to" fromOps' _ [] = Left "Found only a MoveTo operation" fromOps' s (LineTo q:ops) = let (ls,xs) = span' _LineTo ops pts = map ext $ s:q:mapMaybe (^?_LineTo) ls poly = Polygon.unsafeFromPoints . dropRepeats $ pts pl = fromPointsUnsafe pts in case xs of (ClosePath : xs') -> PolygonPath poly <<| xs' _ -> PolyLineSegment pl <<| xs fromOps' s [Spline [a, b]] = Right [QuadraticBezierSegment $ Bezier2 s a b] fromOps' s [Spline [a, b, c]] = Right [CubicBezierSegment $ Bezier3 s a b c] fromOps' s [Spline ps] = Right $ map CubicBezierSegment $ splineToCubicBeziers $ s : ps fromOps' s [QCurveTo a b] = Right [QuadraticBezierSegment $ Bezier2 s a b] fromOps' s [CurveTo a b c] = Right [CubicBezierSegment $ Bezier3 s a b c] fromOps' _ _ = Left "fromOpts': rest not implemented yet." span' pr = L.span (not . isn't pr) x <<| xs = (x:) <$> fromOps xs to pieces splineToCubicBeziers :: Fractional r => [Point 2 r] -> [BezierSpline 3 2 r] splineToCubicBeziers [a, b, c, d] = [Bezier3 a b c d] splineToCubicBeziers (a : b : c : d : rest) = let p = b .+^ (c .-. b) ^/ 2 q = c .+^ (d .-. c) ^/ 3 r = p .+^ (q .-. p) ^/ 2 in (Bezier3 a b p r) : splineToCubicBeziers (r : q : d : rest) splineToCubicBeziers _ = error "splineToCubicBeziers needs at least four points" dropRepeats :: Eq a => [a] -> [a] dropRepeats = map head . L.group instance (Coordinate r, Fractional r, Eq r) => IpeReadText (Path r) where ipeReadText = fmap (Path . LSeq.fromNonEmpty) . ipeReadText is just so that in ` ipeReadRec ` can select the right class IpeReadAttr t where ipeReadAttr :: Text -> Node Text Text -> Either ConversionError t instance IpeReadText (Apply f at) => IpeReadAttr (Attr f at) where ipeReadAttr n (Element _ ats _) = GAttr <$> Tr.mapM ipeReadText (lookup n ats) ipeReadAttr _ _ = Left "IpeReadAttr: Element expected, Text found" zipTraverseWith :: forall f g h i (rs :: [AttributeUniverse]). Applicative h => (forall (x :: AttributeUniverse). f x -> g x -> h (i x)) -> Rec f rs -> Rec g rs -> h (Rec i rs) zipTraverseWith _ RNil RNil = pure RNil zipTraverseWith f (x :& xs) (y :& ys) = (:&) <$> f x y <*> zipTraverseWith f xs ys ipeReadRec :: forall f ats. ( RecApplicative ats , ReifyConstraint IpeReadAttr (Attr f) ats , RecAll (Attr f) ats IpeReadAttr , AllConstrained IpeAttrName ats ) => Proxy f -> Proxy ats -> Node Text Text -> Either ConversionError (Rec (Attr f) ats) ipeReadRec _ _ x = zipTraverseWith f (writeAttrNames r) r' where r = rpure (GAttr Nothing) r' = reifyConstraint @IpeReadAttr r f :: forall at. Const Text at -> (Dict IpeReadAttr :. Attr f) at -> Either ConversionError (Attr f at) f (Const n) (Compose (Dict _)) = ipeReadAttr n x ipeReadAttrs :: forall proxy proxy' i r f ats. ( f ~ AttrMapSym1 r, ats ~ AttributesOf i , ReifyConstraint IpeReadAttr (Attr f) ats , RecApplicative ats , RecAll (Attr f) ats IpeReadAttr , AllConstrained IpeAttrName ats ) => proxy i -> proxy' r -> Node Text Text -> Either ConversionError (IpeAttributes i r) ipeReadAttrs _ _ = fmap Attrs . ipeReadRec (Proxy :: Proxy f) (Proxy :: Proxy ats) testSym = " < use name=\"mark / disk(sx)\ " pos=\"320 " size=\"normal\ " stroke=\"black\"/ > " readSymAttrs : : Either ConversionError ( IpeAttributes IpeSymbol Double ) > > = ipeReadAttrs ( Proxy : : Proxy IpeSymbol ) ( Proxy : : Proxy Double ) | If we can ipeRead an ipe element , and we can ipeReadAttrs its attributes we can properly read an ipe object using ipeReadObject ipeReadObject :: ( IpeRead (i r) , f ~ AttrMapSym1 r, ats ~ AttributesOf i , RecApplicative ats , ReifyConstraint IpeReadAttr (Attr f) ats , RecAll (Attr f) ats IpeReadAttr , AllConstrained IpeAttrName ats ) => Proxy i -> proxy r -> Node Text Text -> Either ConversionError (i r :+ IpeAttributes i r) ipeReadObject prI prR xml = (:+) <$> ipeRead xml <*> ipeReadAttrs prI prR xml instance Coordinate r => IpeRead (IpeSymbol r) where ipeRead (Element "use" ats _) = case lookup "pos" ats of Nothing -> Left "symbol without position" Just ps -> flip Symbol name <$> ipeReadText ps where name = fromMaybe "mark/disk(sx)" $ lookup "name" ats ipeRead _ = Left "symbol element expected, text found" allText :: [Node Text Text] -> Either ConversionError Text allText = fmap T.unlines . mapM unT where unT (Text t) = Right t unT _ = Left "allText: Expected Text, found an Element" instance (Coordinate r, Fractional r, Eq r) => IpeRead (Path r) where ipeRead (Element "path" _ chs) = allText chs >>= ipeReadText ipeRead _ = Left "path: expected element, found text" lookup' :: Text -> [(Text,a)] -> Either ConversionError a lookup' k = maybe (Left $ "lookup' " <> k <> " not found") Right . lookup k instance Coordinate r => IpeRead (TextLabel r) where ipeRead (Element "text" ats chs) | lookup "type" ats == Just "label" = Label <$> allText chs <*> (lookup' "pos" ats >>= ipeReadText) | otherwise = Left "Not a Text label" ipeRead _ = Left "textlabel: Expected element, found text" instance Coordinate r => IpeRead (MiniPage r) where ipeRead (Element "text" ats chs) | lookup "type" ats == Just "minipage" = MiniPage <$> allText chs <*> (lookup' "pos" ats >>= ipeReadText) <*> (lookup' "width" ats >>= readCoordinate) | otherwise = Left "Not a MiniPage" ipeRead _ = Left "MiniPage: Expected element, found text" instance Coordinate r => IpeRead (Image r) where ipeRead (Element "image" ats _) = Image () <$> (lookup' "rect" ats >>= ipeReadText) ipeRead _ = Left "Image: Element expected, text found" instance (Coordinate r, Fractional r, Eq r) => IpeRead (IpeObject r) where ipeRead x = firstRight [ IpeUse <$> ipeReadObject (Proxy :: Proxy IpeSymbol) r x , IpePath <$> ipeReadObject (Proxy :: Proxy Path) r x , IpeGroup <$> ipeReadObject (Proxy :: Proxy Group) r x , IpeTextLabel <$> ipeReadObject (Proxy :: Proxy TextLabel) r x , IpeMiniPage <$> ipeReadObject (Proxy :: Proxy MiniPage) r x , IpeImage <$> ipeReadObject (Proxy :: Proxy Image) r x ] where r = Proxy :: Proxy r firstRight :: [Either ConversionError a] -> Either ConversionError a firstRight = maybe (Left "No matching object") Right . firstOf (traverse._Right) instance (Coordinate r, Eq r) => IpeRead (Group r) where ipeRead (Element "group" _ chs) = Right . Group . rights . map ipeRead $ chs ipeRead _ = Left "ipeRead Group: expected Element, found Text" instance IpeRead LayerName where ipeRead (Element "layer" ats _) = LayerName <$> lookup' "name" ats ipeRead _ = Left "layer: Expected element, found text" instance IpeRead View where ipeRead (Element "view" ats _) = (\lrs a -> View (map LayerName $ T.words lrs) a) <$> lookup' "layers" ats <*> (lookup' "active" ats >>= ipeReadText) ipeRead _ = Left "View Expected element, found text" instance (Coordinate r, Eq r) => IpeRead (IpePage r) where ipeRead (Element "page" _ chs) = Right $ IpePage (readAll chs) (readAll chs) (readAll chs) ipeRead _ = Left "page: Element expected, text found" readAll :: IpeRead a => [Node Text Text] -> [a] readAll = rights . map ipeRead instance (Coordinate r, Eq r) => IpeRead (IpeFile r) where ipeRead (Element "ipe" _ chs) = case readAll chs of [] -> Left "Ipe: no pages found" pgs -> Right $ IpeFile Nothing [] (NonEmpty.fromList pgs) ipeRead _ = Left "Ipe: Element expected, text found" instance IpeRead IpeStyle where ipeRead = \case xml@(Element "ipestyle" ats _) -> Right $ IpeStyle (lookup "name" ats) xml _ -> Left "ipeStyle exptected. Something else found" | Reads an Ipe stylesheet from Disk . readIpeStylesheet :: FilePath -> IO (Either ConversionError IpeStyle) readIpeStylesheet = fmap (ipeRead <=< readXML) . B.readFile addStyleSheetFrom :: FilePath -> IpeFile r -> IO (IpeFile r) addStyleSheetFrom fp f = readIpeStylesheet fp >>= \case Left err -> fail (show err) Right s -> pure $ addStyleSheet s f
25df0ec56548565bec3eccd0a70619794e82e6ddbd0d7dc127bfdab332e28c24
mstksg/backprop
Internal.hs
# LANGUAGE BangPatterns # {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} # LANGUAGE EmptyCase # {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # {-# LANGUAGE LambdaCase #-} # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE RankNTypes #-} # LANGUAGE RecordWildCards # {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} # LANGUAGE TupleSections # # LANGUAGE TypeApplications # {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE ViewPatterns # # OPTIONS_HADDOCK not - home # -- | -- Module : Numeric.Backprop.Internal -- Copyright : (c) Justin Le 2018 -- License : BSD3 -- Maintainer : -- Stability : experimental -- Portability : non-portable -- -- Provides the types and instances used for the graph -- building/back-propagation for the library. module Numeric.Backprop.Internal ( BVar , W , backpropWithN, evalBPN , constVar , liftOp, liftOp1, liftOp2, liftOp3 , viewVar, setVar, sequenceVar, collectVar, previewVar, toListOfVar , coerceVar -- * Func wrappers , ZeroFunc(..), zfNum, zeroFunc , AddFunc(..), afNum, addFunc , OneFunc(..), ofNum, oneFunc -- * Debug , debugSTN , debugIR ) where import Control.DeepSeq import Control.Exception import Control.Monad import Control.Monad.ST import Control.Monad.Trans.State import Data.Bifunctor import Data.Coerce import Data.Foldable import Data.Function import Data.Functor.Identity import Data.IORef import Data.Kind import Data.Maybe import Data.Monoid hiding (Any(..)) import Data.Proxy import Data.Reflection import Data.Type.Util import Data.Typeable import Data.Vinyl.Core import GHC.Exts (Any) import GHC.Generics as G import Lens.Micro import Lens.Micro.Extras import Numeric.Backprop.Class import Numeric.Backprop.Op import System.IO.Unsafe import Unsafe.Coerce import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import qualified Data.Vinyl.Recursive as VR import qualified Data.Vinyl.XRec as X | " Zero out " all components of a value . For scalar values , this should just be @'const ' 0@. For vectors and matrices , this should set all components to zero , the additive identity . -- -- Should be idempotent: Applying the function twice is the same as -- applying it just once. -- Each type should ideally only have one ' ZeroFunc ' . This coherence constraint is given by the ' Backprop ' . -- @since 0.2.0.0 newtype ZeroFunc a = ZF { runZF :: a -> a } | Add together two values of a type . To combine contributions of -- gradients, so should ideally be information-preserving. -- -- See laws for 'Backprop' for the laws this should be expected to -- preserve. Namely, it should be commutative and associative, with an identity for a valid ' ZeroFunc ' . -- Each type should ideally only have one ' ' . This coherence constraint is given by the ' Backprop ' . -- @since 0.2.0.0 newtype AddFunc a = AF { runAF :: a -> a -> a } | " One " all components of a value . For scalar values , this should -- just be @'const' 1@. For vectors and matrices, this should set all -- components to one, the multiplicative identity. -- -- Should be idempotent: Applying the function twice is the same as -- applying it just once. -- -- Each type should ideally only have one 'OneFunc'. This coherence constraint is given by the ' Backprop ' . -- @since 0.2.0.0 newtype OneFunc a = OF { runOF :: a -> a } | If a type has a ' Num ' instance , this is the canonical ' ZeroFunc ' . -- @since 0.2.0.0 zfNum :: Num a => ZeroFunc a zfNum = ZF (const 0) # INLINE zfNum # | If a type has a ' Num ' instance , this is the canonical ' ' . -- @since 0.2.0.0 afNum :: Num a => AddFunc a afNum = AF (+) # INLINE afNum # -- | If a type has a 'Num' instance, this is the canonical 'OneFunc'. -- @since 0.2.0.0 ofNum :: Num a => OneFunc a ofNum = OF (const 1) # INLINE ofNum # | A @'BVar ' s a@ is a value of type @a@ that can be " backpropagated " . -- Functions referring to ' 's are tracked by the library and can be -- automatically differentiated to get their gradients and results. -- -- For simple numeric values, you can use its 'Num', 'Fractional', and -- 'Floating' instances to manipulate them as if they were the numbers they -- represent. -- -- If @a@ contains items, the items can be accessed and extracted using lenses . A @'Lens '' b a@ can be used to access an @a@ inside a @b@ , using ' ^^. ' ( ' Numeric . Backprop.viewVar ' ): -- -- @ -- ('^.') :: a -> 'Lens'' a b -> b ( ' ^^. ' ) : : ' ' s a - > ' Lens '' a b - > ' ' s b -- @ -- -- There is also '^^?' ('Numeric.Backprop.previewVar'), to use a 'Prism'' -- or 'Traversal'' to extract a target that may or may not be present -- (which can implement pattern matching), '^^..' ( ' Numeric . Backprop.toListOfVar ' ) to use a ' Traversal '' to extract -- targets inside a 'BVar', and '.~~' ('setVar') to set and update values inside a ' ' . -- -- If you have control over your data type definitions, you can also use -- 'Numeric.Backprop.splitBV' and 'Numeric.Backprop.joinBV' to manipulate data types by easily extracting fields out of a ' BVar ' of data types and creating ' BVar 's of data types out of ' 's of their fields . See -- "Numeric.Backprop#hkd" for a tutorial on this use pattern. -- For more complex operations , libraries can provide functions on ' 's -- using 'Numeric.Backprop.liftOp' and related functions. This is how you -- can create primitive functions that users can use to manipulate your -- library's values. See -- <-equipping-your-library.html> for a detailed -- guide. -- -- For example, the /hmatrix/ library has a matrix-vector multiplication -- function, @#> :: L m n -> R n -> L m@. -- A library could instead provide a function @ # > : : ' ' ( L m n ) - > BVar -- (R n) -> BVar (R m)@, which the user can then use to manipulate their ' BVar 's of @L m n@s and @R n@s , etc . -- -- See "Numeric.Backprop#liftops" and documentation for ' Numeric . ' for more information . -- data BVar s a = BV { _bvRef :: !(BRef s) , _bvVal :: !a } -- | @since 0.1.5.1 deriving instance Typeable (BVar s a) | @since 0.2.6.3 instance X.IsoHKD (BVar s) a data BRef (s :: Type) = BRInp !Int | BRIx !Int | BRC deriving (Generic, Show) instance NFData (BRef s) -- | This will force the value inside, as well. instance NFData a => NFData (BVar s a) where rnf (BV r v) = force r `seq` force v `seq` () | Project out a constant value if the ' ' refers to one . bvConst :: BVar s a -> Maybe a bvConst (BV BRC !x) = Just x bvConst _ = Nothing # INLINE bvConst # forceBVar :: BVar s a -> () forceBVar (BV r !_) = force r `seq` () # INLINE forceBVar # data InpRef :: Type -> Type where IR :: { _irIx :: !(BVar s b) , _irAdd :: !(a -> b -> b) , _irEmbed :: !(a -> b) } -> InpRef a forceInpRef :: InpRef a -> () forceInpRef (IR v !_ !_) = forceBVar v `seq` () # INLINE forceInpRef # | Debugging string for an ' InpRef ' . debugIR :: InpRef a -> String debugIR IR{..} = show (_bvRef _irIx) data TapeNode :: Type -> Type where TN :: { _tnInputs :: !(Rec InpRef as) , _tnGrad :: !(a -> Rec Identity as) } -> TapeNode a forceTapeNode :: TapeNode a -> () forceTapeNode (TN inps !_) = VR.rfoldMap forceInpRef inps `seq` () # INLINE forceTapeNode # data SomeTapeNode :: Type where STN :: { _stnNode :: !(TapeNode a) } -> SomeTapeNode forceSomeTapeNode :: SomeTapeNode -> () forceSomeTapeNode (STN n) = forceTapeNode n -- | Debugging string for a 'SomeTapeMode'. debugSTN :: SomeTapeNode -> String debugSTN (STN TN{..}) = show . VR.rfoldMap ((:[]) . debugIR) $ _tnInputs | An ephemeral Tape in the environment . Used internally to -- track of the computational graph of variables. -- -- For the end user, one can just imagine @'Reifies' s 'W'@ as a required -- constraint on @s@ that allows backpropagation to work. newtype W = W { wRef :: IORef (Int, [SomeTapeNode]) } initWengert :: IO W initWengert = W <$> newIORef (0,[]) {-# INLINE initWengert #-} insertNode :: TapeNode a -> a -- ^ val -> W -> IO (BVar s a) insertNode tn !x !w = fmap ((`BV` x) . BRIx) . atomicModifyIORef' (wRef w) $ \(!n,!t) -> let n' = n + 1 t' = STN tn : t in forceTapeNode tn `seq` n' `seq` t' `seq` ((n', t'), n) # INLINE insertNode # -- | Lift a value into a 'BVar' representing a constant value. -- -- This value will not be considered an input, and its gradients will not -- be backpropagated. constVar :: a -> BVar s a constVar = BV BRC # INLINE constVar # liftOp_ :: forall s as b. Reifies s W => Rec AddFunc as -> Op as b -> Rec (BVar s) as -> IO (BVar s b) liftOp_ afs o !vs = case rtraverse (fmap Identity . bvConst) vs of Just xs -> return $ constVar (evalOp o xs) Nothing -> insertNode tn y (reflect (Proxy @s)) where (y,g) = runOpWith o (VR.rmap (Identity . _bvVal) vs) tn = TN { _tnInputs = VR.rzipWith go afs vs , _tnGrad = g } go :: forall a. AddFunc a -> BVar s a -> InpRef a go af !v = forceBVar v `seq` IR v (runAF af) id # INLINE go # # INLINE liftOp _ # -- | 'Numeric.Backprop.liftOp', but with explicit 'add' and 'zero'. liftOp :: forall as b s. Reifies s W => Rec AddFunc as -> Op as b -> Rec (BVar s) as -> BVar s b liftOp afs o !vs = unsafePerformIO $ liftOp_ afs o vs # INLINE liftOp # liftOp1_ :: forall a b s. Reifies s W => AddFunc a -> Op '[a] b -> BVar s a -> IO (BVar s b) liftOp1_ _ o (bvConst->Just x) = return . constVar . evalOp o $ (Identity x :& RNil) liftOp1_ af o v = forceBVar v `seq` insertNode tn y (reflect (Proxy @s)) where (y,g) = runOpWith o (Identity (_bvVal v) :& RNil) tn = TN { _tnInputs = IR v (runAF af) id :& RNil , _tnGrad = g } {-# INLINE liftOp1_ #-} | ' Numeric . Backprop.liftOp1 ' , but with explicit ' add ' and ' zero ' . liftOp1 :: forall a b s. Reifies s W => AddFunc a -> Op '[a] b -> BVar s a -> BVar s b liftOp1 af o !v = unsafePerformIO $ liftOp1_ af o v # INLINE liftOp1 # liftOp2_ :: forall a b c s. Reifies s W => AddFunc a -> AddFunc b -> Op '[a,b] c -> BVar s a -> BVar s b -> IO (BVar s c) liftOp2_ _ _ o (bvConst->Just x) (bvConst->Just y) = return . constVar . evalOp o $ Identity x :& Identity y :& RNil liftOp2_ afa afb o v u = forceBVar v `seq` forceBVar u `seq` insertNode tn y (reflect (Proxy @s)) where (y,g) = runOpWith o $ Identity (_bvVal v) :& Identity (_bvVal u) :& RNil tn = TN { _tnInputs = IR v (runAF afa) id :& IR u (runAF afb) id :& RNil , _tnGrad = g } {-# INLINE liftOp2_ #-} | ' Numeric . Backprop.liftOp2 ' , but with explicit ' add ' and ' zero ' . liftOp2 :: forall a b c s. Reifies s W => AddFunc a -> AddFunc b -> Op '[a,b] c -> BVar s a -> BVar s b -> BVar s c liftOp2 afa afb o !v !u = unsafePerformIO $ liftOp2_ afa afb o v u # INLINE liftOp2 # liftOp3_ :: forall a b c d s. Reifies s W => AddFunc a -> AddFunc b -> AddFunc c -> Op '[a,b,c] d -> BVar s a -> BVar s b -> BVar s c -> IO (BVar s d) liftOp3_ _ _ _ o (bvConst->Just x) (bvConst->Just y) (bvConst->Just z) = return . constVar . evalOp o $ Identity x :& Identity y :& Identity z :& RNil liftOp3_ afa afb afc o v u w = forceBVar v `seq` forceBVar u `seq` forceBVar w `seq` insertNode tn y (reflect (Proxy @s)) where (y, g) = runOpWith o $ Identity (_bvVal v) :& Identity (_bvVal u) :& Identity (_bvVal w) :& RNil tn = TN { _tnInputs = IR v (runAF afa) id :& IR u (runAF afb) id :& IR w (runAF afc) id :& RNil , _tnGrad = g } # INLINE liftOp3 _ # -- | 'Numeric.Backprop.liftOp3', but with explicit 'add' and 'zero'. liftOp3 :: forall a b c d s. Reifies s W => AddFunc a -> AddFunc b -> AddFunc c -> Op '[a,b,c] d -> BVar s a -> BVar s b -> BVar s c -> BVar s d liftOp3 afa afb afc o !v !u !w = unsafePerformIO $ liftOp3_ afa afb afc o v u w # INLINE liftOp3 # TODO : can we get the zero and add func from the bvar ? viewVar_ :: forall a b s. Reifies s W => AddFunc a -> ZeroFunc b -> Lens' b a -> BVar s b -> IO (BVar s a) viewVar_ af z l v = forceBVar v `seq` insertNode tn y (reflect (Proxy @s)) where x = _bvVal v y = x ^. l tn = TN { _tnInputs = IR v (over l . runAF af) (\g -> set l g (runZF z x)) :& RNil , _tnGrad = (:& RNil) . Identity } # INLINE viewVar _ # | ' Numeric . Backprop.viewVar ' , but with explicit ' add ' and ' zero ' . viewVar :: forall a b s. Reifies s W => AddFunc a -> ZeroFunc b -> Lens' b a -> BVar s b -> BVar s a viewVar af z l !v = unsafePerformIO $ viewVar_ af z l v # INLINE viewVar # TODO : can zero and add func be gotten from the input bvars ? setVar_ :: forall a b s. Reifies s W => AddFunc a -> AddFunc b -> ZeroFunc a -> Lens' b a -> BVar s a -> BVar s b -> IO (BVar s b) setVar_ afa afb za l w v = forceBVar v `seq` forceBVar w `seq` insertNode tn y (reflect (Proxy @s)) where y = _bvVal v & l .~ _bvVal w tn = TN { _tnInputs = IR w (runAF afa) id :& IR v (runAF afb) id :& RNil , _tnGrad = \d -> let (dw,dv) = l (\x -> (x, runZF za x)) d in Identity dw :& Identity dv :& RNil } {-# INLINE setVar_ #-} | ' Numeric . Backprop.setVar ' , but with explicit ' add ' and ' zero ' . setVar :: forall a b s. Reifies s W => AddFunc a -> AddFunc b -> ZeroFunc a -> Lens' b a -> BVar s a -> BVar s b -> BVar s b setVar afa afb za l !w !v = unsafePerformIO $ setVar_ afa afb za l w v # INLINE setVar # | ' Numeric . ' , but with explicit ' add ' and ' zero ' . sequenceVar :: forall t a s. (Reifies s W, Traversable t) => AddFunc a -> ZeroFunc a -> BVar s (t a) -> t (BVar s a) sequenceVar af z !v = unsafePerformIO $ traverseVar' af (ZF (fmap (runZF z))) id traverse v # INLINE sequenceVar # TODO : can add funcs and zeros be had from bvars and Functor instance ? collectVar_ :: forall t a s. (Reifies s W, Foldable t, Functor t) => AddFunc a -> ZeroFunc a -> t (BVar s a) -> IO (BVar s (t a)) collectVar_ af z !vs = withVec (toList vs) $ \(vVec :: VecT n (BVar s) a) -> do let tn :: TapeNode (t a) tn = TN { _tnInputs = vecToRec (vmap (\v -> IR v (runAF af) id) vVec) , _tnGrad = vecToRec . zipVecList (\v -> Identity . fromMaybe (runZF z (_bvVal v))) vVec . toList } traverse_ (evaluate . forceBVar) vs insertNode tn (_bvVal <$> vs) (reflect (Proxy @s)) # INLINE collectVar _ # | ' Numeric . ' , but with explicit ' add ' and ' zero ' . collectVar :: forall t a s. (Reifies s W, Foldable t, Functor t) => AddFunc a -> ZeroFunc a -> t (BVar s a) -> BVar s (t a) collectVar af z !vs = unsafePerformIO $ collectVar_ af z vs # INLINE collectVar # traverseVar' :: forall b a f s. (Reifies s W, Traversable f) => AddFunc a -> ZeroFunc b -> (b -> f a) -> Traversal' b a -> BVar s b -> IO (f (BVar s a)) traverseVar' af z f t v = forceBVar v `seq` itraverse go (f x) where x = _bvVal v go :: Int -> a -> IO (BVar s a) go i y = insertNode tn y (reflect (Proxy @s)) where tn = TN { _tnInputs = IR v (over (ixt t i) . runAF af) (\g -> set (ixt t i) g (runZF z x)) :& RNil , _tnGrad = (:& RNil) . Identity } # INLINE go # # INLINE traverseVar ' # -- | 'Numeric.Backprop.previewVar', but with explicit 'add' and 'zero'. previewVar :: forall b a s. Reifies s W => AddFunc a -> ZeroFunc b -> Traversal' b a -> BVar s b -> Maybe (BVar s a) previewVar af z t !v = unsafePerformIO $ traverseVar' af z (preview t) t v # INLINE previewVar # | ' Numeric . Backprop.toListOfVar ' , but with explicit ' add ' and ' zero ' . toListOfVar :: forall b a s. Reifies s W => AddFunc a -> ZeroFunc b -> Traversal' b a -> BVar s b -> [BVar s a] toListOfVar af z t !v = unsafePerformIO $ traverseVar' af z (toListOf t) t v # INLINE toListOfVar # | Coerce a ' BVar ' contents . Useful for things like newtype wrappers . -- -- @since 0.1.5.2 coerceVar :: Coercible a b => BVar s a -> BVar s b coerceVar v@(BV r x) = forceBVar v `seq` BV r (coerce x) data Runner s = R { _rDelta :: !(MV.MVector s (Maybe Any)) , _rInputs :: !(MV.MVector s (Maybe Any)) } initRunner :: (Int, [SomeTapeNode]) -> (Int, [Maybe Any]) -> ST s (Runner s) initRunner (n, stns) (nx,xs) = do delts <- MV.new n for_ (zip [n-1,n-2..] stns) $ \(i, STN (TN{..} :: TapeNode c)) -> MV.write delts i $ unsafeCoerce (Nothing @c) inps <- MV.new nx for_ (zip [0..] xs) . uncurry $ \i z -> MV.write inps i z return $ R delts inps # INLINE initRunner # gradRunner :: forall b s. () ^ one -> Runner s -> (Int, [SomeTapeNode]) -> ST s () gradRunner o R{..} (n,stns) = do when (n > 0) $ MV.write _rDelta (n - 1) (unsafeCoerce (Just o)) zipWithM_ go [n-1,n-2..] stns where go :: Int -> SomeTapeNode -> ST s () go i (STN (TN{..} :: TapeNode c)) = do delt <- MV.read _rDelta i forM_ delt $ \d -> do let gs = _tnGrad (unsafeCoerce d) rzipWithM_ propagate _tnInputs gs # INLINE go # propagate :: forall x. InpRef x -> Identity x -> ST s () propagate (IR v (+*) e) (Identity d) = case _bvRef v of BRInp i -> flip (MV.modify _rInputs) i $ unsafeCoerce . bumpMaybe d (+*) e . unsafeCoerce BRIx i -> flip (MV.modify _rDelta) i $ unsafeCoerce . bumpMaybe d (+*) e . unsafeCoerce BRC -> return () # INLINE propagate # # INLINE gradRunner # bumpMaybe :: a -- ^ val -> (a -> b -> b) -- ^ add -> (a -> b) -- ^ embed -> Maybe b -> Maybe b bumpMaybe x (+*) e = \case Nothing -> Just (e x) Just y -> Just (x +* y) # INLINE bumpMaybe # seqEither :: Either a (b, [SomeTapeNode]) -> Either a (b, [SomeTapeNode]) seqEither e@(Left !_) = e seqEither e@(Right (!_,foldMap forceSomeTapeNode->(!_))) = e # INLINE seqEither # -- | 'Numeric.Backprop.backpropWithN', but with explicit 'zero' and 'one'. -- -- Note that argument order changed in v0.2.4. -- @since 0.2.0.0 backpropWithN :: forall as b. () => Rec ZeroFunc as -> (forall s. Reifies s W => Rec (BVar s) as -> BVar s b) -> Rec Identity as -> (b, b -> Rec Identity as) backpropWithN zfs f !xs = (y, g') where !(seqEither->(!tp0),!y) = unsafePerformIO $ fillWengert f xs g' :: b -> Rec Identity as g' = case tp0 of Left i -> setInput i Right tp -> g tp # INLINE g ' # g :: (Int, [SomeTapeNode]) -> b -> Rec Identity as g tp o = runST $ do r <- initRunner tp . bimap getSum (`appEndo` []) . VR.rfoldMap go -- TODO: use strict tuple? $ xs gradRunner o r tp delts <- toList <$> V.freeze (_rInputs r) return . fromMaybe (internalError "backpropN") $ fillRec (\z -> maybe z (Identity . unsafeCoerce)) (VR.rzipWith (fmap . runZF) zfs xs) delts where go :: forall a. Identity a -> (Sum Int, Endo [Maybe Any]) go _ = (1, Endo (unsafeCoerce (Nothing @a) :)) # INLINE go # setInput :: Int -> b -> Rec Identity as setInput !i !x = go zfs xs 0 where go :: Rec ZeroFunc bs -> Rec Identity bs -> Int -> Rec Identity bs go = \case RNil -> \_ _ -> RNil z :& zs -> \case q :& qs -> \(!j) -> if j == i then Identity (unsafeCoerce x) :& VR.rzipWith coerce zs qs else coerce z q :& go zs qs (j + 1) # INLINE setInput # # INLINE backpropWithN # -- | 'evalBP' generalized to multiple inputs of different types. See documentation for ' Numeric . Backprop.backpropN ' for more details . evalBPN :: forall as b. () => (forall s. Reifies s W => Rec (BVar s) as -> BVar s b) -> Rec Identity as -> b evalBPN f = snd . unsafePerformIO . fillWengert f # INLINE evalBPN # fillWengert :: forall as b. () => (forall s. Reifies s W => Rec (BVar s) as -> BVar s b) -> Rec Identity as -> IO (Either Int (Int, [SomeTapeNode]), b) fillWengert f xs = do w <- initWengert (i, o) <- reify w $ \(Proxy :: Proxy s) -> do let oVar = f (inpRec @s) evaluate (forceBVar oVar) let isInput = case _bvRef oVar of BRInp i -> Just i _ -> Nothing pure (isInput, _bvVal oVar) t <- case i of Nothing -> Right <$> readIORef (wRef w) Just i' -> pure $ Left i' pure (t, o) where inpRec :: forall s. Rec (BVar s) as inpRec = evalState (rtraverse (state . go . runIdentity) xs) 0 where go :: a -> Int -> (BVar s a, Int) go x i = (BV (BRInp i) x, i + 1) # INLINE go # # INLINE inpRec # # INLINE fillWengert # instance (Num a, Reifies s W) => Num (BVar s a) where (+) = liftOp2 afNum afNum (+.) {-# INLINE (+) #-} (-) = liftOp2 afNum afNum (-.) {-# INLINE (-) #-} (*) = liftOp2 afNum afNum (*.) {-# INLINE (*) #-} negate = liftOp1 afNum negateOp # INLINE negate # signum = liftOp1 afNum signumOp # INLINE signum # abs = liftOp1 afNum absOp # INLINE abs # fromInteger = constVar . fromInteger # INLINE fromInteger # instance (Fractional a, Reifies s W) => Fractional (BVar s a) where (/) = liftOp2 afNum afNum (/.) {-# INLINE (/) #-} recip = liftOp1 afNum recipOp # INLINE recip # fromRational = constVar . fromRational # INLINE fromRational # instance (Floating a, Reifies s W) => Floating (BVar s a) where pi = constVar pi # INLINE pi # exp = liftOp1 afNum expOp # INLINE exp # log = liftOp1 afNum logOp # INLINE log # sqrt = liftOp1 afNum sqrtOp # INLINE sqrt # (**) = liftOp2 afNum afNum (**.) {-# INLINE (**) #-} logBase = liftOp2 afNum afNum logBaseOp # INLINE logBase # sin = liftOp1 afNum sinOp # INLINE sin # cos = liftOp1 afNum cosOp # INLINE cos # tan = liftOp1 afNum tanOp {-# INLINE tan #-} asin = liftOp1 afNum asinOp {-# INLINE asin #-} acos = liftOp1 afNum acosOp # INLINE acos # atan = liftOp1 afNum atanOp # INLINE atan # sinh = liftOp1 afNum sinhOp # INLINE sinh # cosh = liftOp1 afNum coshOp # INLINE cosh # tanh = liftOp1 afNum tanhOp # INLINE tanh # asinh = liftOp1 afNum asinhOp # INLINE asinh # acosh = liftOp1 afNum acoshOp # INLINE acosh # atanh = liftOp1 afNum atanhOp # INLINE atanh # | Compares the values inside the ' ' . -- @since 0.1.5.0 instance Eq a => Eq (BVar s a) where (==) = (==) `on` _bvVal (/=) = (/=) `on` _bvVal | Compares the values inside the ' ' . -- @since 0.1.5.0 instance Ord a => Ord (BVar s a) where compare = compare `on` _bvVal (<) = (<) `on` _bvVal (<=) = (<=) `on` _bvVal (>) = (>) `on` _bvVal (>=) = (>=) `on` _bvVal -- Some utility functions to get around a lens dependency itraverse :: forall t a b f. (Traversable t, Monad f) => (Int -> a -> f b) -> t a -> f (t b) itraverse f xs = evalStateT (traverse (StateT . go) xs) 0 where go :: a -> Int -> f (b, Int) go x i = (,i+1) <$> f i x # INLINE itraverse # ixi :: Int -> Lens' [a] a ixi _ _ [] = internalError "ixi" ixi 0 f (x:xs) = (:xs) <$> f x ixi n f (x:xs) = (x:) <$> ixi (n - 1) f xs # INLINE ixi # ixt :: forall b a. Traversal' b a -> Int -> Lens' b a ixt t i f xs = stuff <$> ixi i f contents where contents = xs ^.. t stuff = evalState (traverseOf t (state . const go) xs) where go :: [a] -> (a, [a]) go [] = internalError "ixt" go (y:ys) = (y, ys) {-# INLINE ixt #-} -- | @since 0.2.2.0 instance (Backprop a, Reifies s W) => Backprop (BVar s a) where zero = liftOp1 addFunc . op1 $ \x -> (zero x, zero) # INLINE zero # add = liftOp2 addFunc addFunc . op2 $ \x y -> ( add x y , \d -> (d, d) ) # INLINE add # one = liftOp1 addFunc . op1 $ \x -> (one x, zero) # INLINE one # | The canonical ' ZeroFunc ' for instances of ' Backprop ' . -- @since 0.2.0.0 zeroFunc :: Backprop a => ZeroFunc a zeroFunc = ZF zero # INLINE zeroFunc # | The canonical ' ' for instances of ' Backprop ' . -- @since 0.2.0.0 addFunc :: Backprop a => AddFunc a addFunc = AF add # INLINE addFunc # -- | The canonical 'OneFunc' for instances of 'Backprop'. -- @since 0.2.0.0 oneFunc :: Backprop a => OneFunc a oneFunc = OF one # INLINE oneFunc # internalError :: String -> a internalError m = errorWithoutStackTrace $ "Numeric.Backprop.Internal." ++ m ++ ": unexpected shape involved in gradient computation"
null
https://raw.githubusercontent.com/mstksg/backprop/e8962c2029476c7721c5f5488e8689737294ceee/src/Numeric/Backprop/Internal.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE LambdaCase # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeInType # # LANGUAGE TypeOperators # | Module : Numeric.Backprop.Internal Copyright : (c) Justin Le 2018 License : BSD3 Stability : experimental Portability : non-portable Provides the types and instances used for the graph building/back-propagation for the library. * Func wrappers * Debug Should be idempotent: Applying the function twice is the same as applying it just once. gradients, so should ideally be information-preserving. See laws for 'Backprop' for the laws this should be expected to preserve. Namely, it should be commutative and associative, with an just be @'const' 1@. For vectors and matrices, this should set all components to one, the multiplicative identity. Should be idempotent: Applying the function twice is the same as applying it just once. Each type should ideally only have one 'OneFunc'. This coherence | If a type has a 'Num' instance, this is the canonical 'OneFunc'. automatically differentiated to get their gradients and results. For simple numeric values, you can use its 'Num', 'Fractional', and 'Floating' instances to manipulate them as if they were the numbers they represent. If @a@ contains items, the items can be accessed and extracted using @ ('^.') :: a -> 'Lens'' a b -> b @ There is also '^^?' ('Numeric.Backprop.previewVar'), to use a 'Prism'' or 'Traversal'' to extract a target that may or may not be present (which can implement pattern matching), '^^..' targets inside a 'BVar', and '.~~' ('setVar') to set and update values If you have control over your data type definitions, you can also use 'Numeric.Backprop.splitBV' and 'Numeric.Backprop.joinBV' to manipulate "Numeric.Backprop#hkd" for a tutorial on this use pattern. using 'Numeric.Backprop.liftOp' and related functions. This is how you can create primitive functions that users can use to manipulate your library's values. See <-equipping-your-library.html> for a detailed guide. For example, the /hmatrix/ library has a matrix-vector multiplication function, @#> :: L m n -> R n -> L m@. (R n) -> BVar (R m)@, which the user can then use to manipulate their See "Numeric.Backprop#liftops" and documentation for | @since 0.1.5.1 | This will force the value inside, as well. | Debugging string for a 'SomeTapeMode'. track of the computational graph of variables. For the end user, one can just imagine @'Reifies' s 'W'@ as a required constraint on @s@ that allows backpropagation to work. # INLINE initWengert # ^ val | Lift a value into a 'BVar' representing a constant value. This value will not be considered an input, and its gradients will not be backpropagated. | 'Numeric.Backprop.liftOp', but with explicit 'add' and 'zero'. # INLINE liftOp1_ # # INLINE liftOp2_ # | 'Numeric.Backprop.liftOp3', but with explicit 'add' and 'zero'. # INLINE setVar_ # | 'Numeric.Backprop.previewVar', but with explicit 'add' and 'zero'. @since 0.1.5.2 ^ val ^ add ^ embed | 'Numeric.Backprop.backpropWithN', but with explicit 'zero' and 'one'. Note that argument order changed in v0.2.4. TODO: use strict tuple? | 'evalBP' generalized to multiple inputs of different types. See # INLINE (+) # # INLINE (-) # # INLINE (*) # # INLINE (/) # # INLINE (**) # # INLINE tan # # INLINE asin # Some utility functions to get around a lens dependency # INLINE ixt # | @since 0.2.2.0 | The canonical 'OneFunc' for instances of 'Backprop'.
# LANGUAGE BangPatterns # # LANGUAGE EmptyCase # # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecordWildCards # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # LANGUAGE ViewPatterns # # OPTIONS_HADDOCK not - home # Maintainer : module Numeric.Backprop.Internal ( BVar , W , backpropWithN, evalBPN , constVar , liftOp, liftOp1, liftOp2, liftOp3 , viewVar, setVar, sequenceVar, collectVar, previewVar, toListOfVar , coerceVar , ZeroFunc(..), zfNum, zeroFunc , AddFunc(..), afNum, addFunc , OneFunc(..), ofNum, oneFunc , debugSTN , debugIR ) where import Control.DeepSeq import Control.Exception import Control.Monad import Control.Monad.ST import Control.Monad.Trans.State import Data.Bifunctor import Data.Coerce import Data.Foldable import Data.Function import Data.Functor.Identity import Data.IORef import Data.Kind import Data.Maybe import Data.Monoid hiding (Any(..)) import Data.Proxy import Data.Reflection import Data.Type.Util import Data.Typeable import Data.Vinyl.Core import GHC.Exts (Any) import GHC.Generics as G import Lens.Micro import Lens.Micro.Extras import Numeric.Backprop.Class import Numeric.Backprop.Op import System.IO.Unsafe import Unsafe.Coerce import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import qualified Data.Vinyl.Recursive as VR import qualified Data.Vinyl.XRec as X | " Zero out " all components of a value . For scalar values , this should just be @'const ' 0@. For vectors and matrices , this should set all components to zero , the additive identity . Each type should ideally only have one ' ZeroFunc ' . This coherence constraint is given by the ' Backprop ' . @since 0.2.0.0 newtype ZeroFunc a = ZF { runZF :: a -> a } | Add together two values of a type . To combine contributions of identity for a valid ' ZeroFunc ' . Each type should ideally only have one ' ' . This coherence constraint is given by the ' Backprop ' . @since 0.2.0.0 newtype AddFunc a = AF { runAF :: a -> a -> a } | " One " all components of a value . For scalar values , this should constraint is given by the ' Backprop ' . @since 0.2.0.0 newtype OneFunc a = OF { runOF :: a -> a } | If a type has a ' Num ' instance , this is the canonical ' ZeroFunc ' . @since 0.2.0.0 zfNum :: Num a => ZeroFunc a zfNum = ZF (const 0) # INLINE zfNum # | If a type has a ' Num ' instance , this is the canonical ' ' . @since 0.2.0.0 afNum :: Num a => AddFunc a afNum = AF (+) # INLINE afNum # @since 0.2.0.0 ofNum :: Num a => OneFunc a ofNum = OF (const 1) # INLINE ofNum # | A @'BVar ' s a@ is a value of type @a@ that can be " backpropagated " . Functions referring to ' 's are tracked by the library and can be lenses . A @'Lens '' b a@ can be used to access an @a@ inside a @b@ , using ' ^^. ' ( ' Numeric . Backprop.viewVar ' ): ( ' ^^. ' ) : : ' ' s a - > ' Lens '' a b - > ' ' s b ( ' Numeric . Backprop.toListOfVar ' ) to use a ' Traversal '' to extract inside a ' ' . data types by easily extracting fields out of a ' BVar ' of data types and creating ' BVar 's of data types out of ' 's of their fields . See For more complex operations , libraries can provide functions on ' 's A library could instead provide a function @ # > : : ' ' ( L m n ) - > BVar ' BVar 's of @L m n@s and @R n@s , etc . ' Numeric . ' for more information . data BVar s a = BV { _bvRef :: !(BRef s) , _bvVal :: !a } deriving instance Typeable (BVar s a) | @since 0.2.6.3 instance X.IsoHKD (BVar s) a data BRef (s :: Type) = BRInp !Int | BRIx !Int | BRC deriving (Generic, Show) instance NFData (BRef s) instance NFData a => NFData (BVar s a) where rnf (BV r v) = force r `seq` force v `seq` () | Project out a constant value if the ' ' refers to one . bvConst :: BVar s a -> Maybe a bvConst (BV BRC !x) = Just x bvConst _ = Nothing # INLINE bvConst # forceBVar :: BVar s a -> () forceBVar (BV r !_) = force r `seq` () # INLINE forceBVar # data InpRef :: Type -> Type where IR :: { _irIx :: !(BVar s b) , _irAdd :: !(a -> b -> b) , _irEmbed :: !(a -> b) } -> InpRef a forceInpRef :: InpRef a -> () forceInpRef (IR v !_ !_) = forceBVar v `seq` () # INLINE forceInpRef # | Debugging string for an ' InpRef ' . debugIR :: InpRef a -> String debugIR IR{..} = show (_bvRef _irIx) data TapeNode :: Type -> Type where TN :: { _tnInputs :: !(Rec InpRef as) , _tnGrad :: !(a -> Rec Identity as) } -> TapeNode a forceTapeNode :: TapeNode a -> () forceTapeNode (TN inps !_) = VR.rfoldMap forceInpRef inps `seq` () # INLINE forceTapeNode # data SomeTapeNode :: Type where STN :: { _stnNode :: !(TapeNode a) } -> SomeTapeNode forceSomeTapeNode :: SomeTapeNode -> () forceSomeTapeNode (STN n) = forceTapeNode n debugSTN :: SomeTapeNode -> String debugSTN (STN TN{..}) = show . VR.rfoldMap ((:[]) . debugIR) $ _tnInputs | An ephemeral Tape in the environment . Used internally to newtype W = W { wRef :: IORef (Int, [SomeTapeNode]) } initWengert :: IO W initWengert = W <$> newIORef (0,[]) insertNode :: TapeNode a -> W -> IO (BVar s a) insertNode tn !x !w = fmap ((`BV` x) . BRIx) . atomicModifyIORef' (wRef w) $ \(!n,!t) -> let n' = n + 1 t' = STN tn : t in forceTapeNode tn `seq` n' `seq` t' `seq` ((n', t'), n) # INLINE insertNode # constVar :: a -> BVar s a constVar = BV BRC # INLINE constVar # liftOp_ :: forall s as b. Reifies s W => Rec AddFunc as -> Op as b -> Rec (BVar s) as -> IO (BVar s b) liftOp_ afs o !vs = case rtraverse (fmap Identity . bvConst) vs of Just xs -> return $ constVar (evalOp o xs) Nothing -> insertNode tn y (reflect (Proxy @s)) where (y,g) = runOpWith o (VR.rmap (Identity . _bvVal) vs) tn = TN { _tnInputs = VR.rzipWith go afs vs , _tnGrad = g } go :: forall a. AddFunc a -> BVar s a -> InpRef a go af !v = forceBVar v `seq` IR v (runAF af) id # INLINE go # # INLINE liftOp _ # liftOp :: forall as b s. Reifies s W => Rec AddFunc as -> Op as b -> Rec (BVar s) as -> BVar s b liftOp afs o !vs = unsafePerformIO $ liftOp_ afs o vs # INLINE liftOp # liftOp1_ :: forall a b s. Reifies s W => AddFunc a -> Op '[a] b -> BVar s a -> IO (BVar s b) liftOp1_ _ o (bvConst->Just x) = return . constVar . evalOp o $ (Identity x :& RNil) liftOp1_ af o v = forceBVar v `seq` insertNode tn y (reflect (Proxy @s)) where (y,g) = runOpWith o (Identity (_bvVal v) :& RNil) tn = TN { _tnInputs = IR v (runAF af) id :& RNil , _tnGrad = g } | ' Numeric . Backprop.liftOp1 ' , but with explicit ' add ' and ' zero ' . liftOp1 :: forall a b s. Reifies s W => AddFunc a -> Op '[a] b -> BVar s a -> BVar s b liftOp1 af o !v = unsafePerformIO $ liftOp1_ af o v # INLINE liftOp1 # liftOp2_ :: forall a b c s. Reifies s W => AddFunc a -> AddFunc b -> Op '[a,b] c -> BVar s a -> BVar s b -> IO (BVar s c) liftOp2_ _ _ o (bvConst->Just x) (bvConst->Just y) = return . constVar . evalOp o $ Identity x :& Identity y :& RNil liftOp2_ afa afb o v u = forceBVar v `seq` forceBVar u `seq` insertNode tn y (reflect (Proxy @s)) where (y,g) = runOpWith o $ Identity (_bvVal v) :& Identity (_bvVal u) :& RNil tn = TN { _tnInputs = IR v (runAF afa) id :& IR u (runAF afb) id :& RNil , _tnGrad = g } | ' Numeric . Backprop.liftOp2 ' , but with explicit ' add ' and ' zero ' . liftOp2 :: forall a b c s. Reifies s W => AddFunc a -> AddFunc b -> Op '[a,b] c -> BVar s a -> BVar s b -> BVar s c liftOp2 afa afb o !v !u = unsafePerformIO $ liftOp2_ afa afb o v u # INLINE liftOp2 # liftOp3_ :: forall a b c d s. Reifies s W => AddFunc a -> AddFunc b -> AddFunc c -> Op '[a,b,c] d -> BVar s a -> BVar s b -> BVar s c -> IO (BVar s d) liftOp3_ _ _ _ o (bvConst->Just x) (bvConst->Just y) (bvConst->Just z) = return . constVar . evalOp o $ Identity x :& Identity y :& Identity z :& RNil liftOp3_ afa afb afc o v u w = forceBVar v `seq` forceBVar u `seq` forceBVar w `seq` insertNode tn y (reflect (Proxy @s)) where (y, g) = runOpWith o $ Identity (_bvVal v) :& Identity (_bvVal u) :& Identity (_bvVal w) :& RNil tn = TN { _tnInputs = IR v (runAF afa) id :& IR u (runAF afb) id :& IR w (runAF afc) id :& RNil , _tnGrad = g } # INLINE liftOp3 _ # liftOp3 :: forall a b c d s. Reifies s W => AddFunc a -> AddFunc b -> AddFunc c -> Op '[a,b,c] d -> BVar s a -> BVar s b -> BVar s c -> BVar s d liftOp3 afa afb afc o !v !u !w = unsafePerformIO $ liftOp3_ afa afb afc o v u w # INLINE liftOp3 # TODO : can we get the zero and add func from the bvar ? viewVar_ :: forall a b s. Reifies s W => AddFunc a -> ZeroFunc b -> Lens' b a -> BVar s b -> IO (BVar s a) viewVar_ af z l v = forceBVar v `seq` insertNode tn y (reflect (Proxy @s)) where x = _bvVal v y = x ^. l tn = TN { _tnInputs = IR v (over l . runAF af) (\g -> set l g (runZF z x)) :& RNil , _tnGrad = (:& RNil) . Identity } # INLINE viewVar _ # | ' Numeric . Backprop.viewVar ' , but with explicit ' add ' and ' zero ' . viewVar :: forall a b s. Reifies s W => AddFunc a -> ZeroFunc b -> Lens' b a -> BVar s b -> BVar s a viewVar af z l !v = unsafePerformIO $ viewVar_ af z l v # INLINE viewVar # TODO : can zero and add func be gotten from the input bvars ? setVar_ :: forall a b s. Reifies s W => AddFunc a -> AddFunc b -> ZeroFunc a -> Lens' b a -> BVar s a -> BVar s b -> IO (BVar s b) setVar_ afa afb za l w v = forceBVar v `seq` forceBVar w `seq` insertNode tn y (reflect (Proxy @s)) where y = _bvVal v & l .~ _bvVal w tn = TN { _tnInputs = IR w (runAF afa) id :& IR v (runAF afb) id :& RNil , _tnGrad = \d -> let (dw,dv) = l (\x -> (x, runZF za x)) d in Identity dw :& Identity dv :& RNil } | ' Numeric . Backprop.setVar ' , but with explicit ' add ' and ' zero ' . setVar :: forall a b s. Reifies s W => AddFunc a -> AddFunc b -> ZeroFunc a -> Lens' b a -> BVar s a -> BVar s b -> BVar s b setVar afa afb za l !w !v = unsafePerformIO $ setVar_ afa afb za l w v # INLINE setVar # | ' Numeric . ' , but with explicit ' add ' and ' zero ' . sequenceVar :: forall t a s. (Reifies s W, Traversable t) => AddFunc a -> ZeroFunc a -> BVar s (t a) -> t (BVar s a) sequenceVar af z !v = unsafePerformIO $ traverseVar' af (ZF (fmap (runZF z))) id traverse v # INLINE sequenceVar # TODO : can add funcs and zeros be had from bvars and Functor instance ? collectVar_ :: forall t a s. (Reifies s W, Foldable t, Functor t) => AddFunc a -> ZeroFunc a -> t (BVar s a) -> IO (BVar s (t a)) collectVar_ af z !vs = withVec (toList vs) $ \(vVec :: VecT n (BVar s) a) -> do let tn :: TapeNode (t a) tn = TN { _tnInputs = vecToRec (vmap (\v -> IR v (runAF af) id) vVec) , _tnGrad = vecToRec . zipVecList (\v -> Identity . fromMaybe (runZF z (_bvVal v))) vVec . toList } traverse_ (evaluate . forceBVar) vs insertNode tn (_bvVal <$> vs) (reflect (Proxy @s)) # INLINE collectVar _ # | ' Numeric . ' , but with explicit ' add ' and ' zero ' . collectVar :: forall t a s. (Reifies s W, Foldable t, Functor t) => AddFunc a -> ZeroFunc a -> t (BVar s a) -> BVar s (t a) collectVar af z !vs = unsafePerformIO $ collectVar_ af z vs # INLINE collectVar # traverseVar' :: forall b a f s. (Reifies s W, Traversable f) => AddFunc a -> ZeroFunc b -> (b -> f a) -> Traversal' b a -> BVar s b -> IO (f (BVar s a)) traverseVar' af z f t v = forceBVar v `seq` itraverse go (f x) where x = _bvVal v go :: Int -> a -> IO (BVar s a) go i y = insertNode tn y (reflect (Proxy @s)) where tn = TN { _tnInputs = IR v (over (ixt t i) . runAF af) (\g -> set (ixt t i) g (runZF z x)) :& RNil , _tnGrad = (:& RNil) . Identity } # INLINE go # # INLINE traverseVar ' # previewVar :: forall b a s. Reifies s W => AddFunc a -> ZeroFunc b -> Traversal' b a -> BVar s b -> Maybe (BVar s a) previewVar af z t !v = unsafePerformIO $ traverseVar' af z (preview t) t v # INLINE previewVar # | ' Numeric . Backprop.toListOfVar ' , but with explicit ' add ' and ' zero ' . toListOfVar :: forall b a s. Reifies s W => AddFunc a -> ZeroFunc b -> Traversal' b a -> BVar s b -> [BVar s a] toListOfVar af z t !v = unsafePerformIO $ traverseVar' af z (toListOf t) t v # INLINE toListOfVar # | Coerce a ' BVar ' contents . Useful for things like newtype wrappers . coerceVar :: Coercible a b => BVar s a -> BVar s b coerceVar v@(BV r x) = forceBVar v `seq` BV r (coerce x) data Runner s = R { _rDelta :: !(MV.MVector s (Maybe Any)) , _rInputs :: !(MV.MVector s (Maybe Any)) } initRunner :: (Int, [SomeTapeNode]) -> (Int, [Maybe Any]) -> ST s (Runner s) initRunner (n, stns) (nx,xs) = do delts <- MV.new n for_ (zip [n-1,n-2..] stns) $ \(i, STN (TN{..} :: TapeNode c)) -> MV.write delts i $ unsafeCoerce (Nothing @c) inps <- MV.new nx for_ (zip [0..] xs) . uncurry $ \i z -> MV.write inps i z return $ R delts inps # INLINE initRunner # gradRunner :: forall b s. () ^ one -> Runner s -> (Int, [SomeTapeNode]) -> ST s () gradRunner o R{..} (n,stns) = do when (n > 0) $ MV.write _rDelta (n - 1) (unsafeCoerce (Just o)) zipWithM_ go [n-1,n-2..] stns where go :: Int -> SomeTapeNode -> ST s () go i (STN (TN{..} :: TapeNode c)) = do delt <- MV.read _rDelta i forM_ delt $ \d -> do let gs = _tnGrad (unsafeCoerce d) rzipWithM_ propagate _tnInputs gs # INLINE go # propagate :: forall x. InpRef x -> Identity x -> ST s () propagate (IR v (+*) e) (Identity d) = case _bvRef v of BRInp i -> flip (MV.modify _rInputs) i $ unsafeCoerce . bumpMaybe d (+*) e . unsafeCoerce BRIx i -> flip (MV.modify _rDelta) i $ unsafeCoerce . bumpMaybe d (+*) e . unsafeCoerce BRC -> return () # INLINE propagate # # INLINE gradRunner # bumpMaybe -> Maybe b -> Maybe b bumpMaybe x (+*) e = \case Nothing -> Just (e x) Just y -> Just (x +* y) # INLINE bumpMaybe # seqEither :: Either a (b, [SomeTapeNode]) -> Either a (b, [SomeTapeNode]) seqEither e@(Left !_) = e seqEither e@(Right (!_,foldMap forceSomeTapeNode->(!_))) = e # INLINE seqEither # @since 0.2.0.0 backpropWithN :: forall as b. () => Rec ZeroFunc as -> (forall s. Reifies s W => Rec (BVar s) as -> BVar s b) -> Rec Identity as -> (b, b -> Rec Identity as) backpropWithN zfs f !xs = (y, g') where !(seqEither->(!tp0),!y) = unsafePerformIO $ fillWengert f xs g' :: b -> Rec Identity as g' = case tp0 of Left i -> setInput i Right tp -> g tp # INLINE g ' # g :: (Int, [SomeTapeNode]) -> b -> Rec Identity as g tp o = runST $ do r <- initRunner tp . bimap getSum (`appEndo` []) $ xs gradRunner o r tp delts <- toList <$> V.freeze (_rInputs r) return . fromMaybe (internalError "backpropN") $ fillRec (\z -> maybe z (Identity . unsafeCoerce)) (VR.rzipWith (fmap . runZF) zfs xs) delts where go :: forall a. Identity a -> (Sum Int, Endo [Maybe Any]) go _ = (1, Endo (unsafeCoerce (Nothing @a) :)) # INLINE go # setInput :: Int -> b -> Rec Identity as setInput !i !x = go zfs xs 0 where go :: Rec ZeroFunc bs -> Rec Identity bs -> Int -> Rec Identity bs go = \case RNil -> \_ _ -> RNil z :& zs -> \case q :& qs -> \(!j) -> if j == i then Identity (unsafeCoerce x) :& VR.rzipWith coerce zs qs else coerce z q :& go zs qs (j + 1) # INLINE setInput # # INLINE backpropWithN # documentation for ' Numeric . Backprop.backpropN ' for more details . evalBPN :: forall as b. () => (forall s. Reifies s W => Rec (BVar s) as -> BVar s b) -> Rec Identity as -> b evalBPN f = snd . unsafePerformIO . fillWengert f # INLINE evalBPN # fillWengert :: forall as b. () => (forall s. Reifies s W => Rec (BVar s) as -> BVar s b) -> Rec Identity as -> IO (Either Int (Int, [SomeTapeNode]), b) fillWengert f xs = do w <- initWengert (i, o) <- reify w $ \(Proxy :: Proxy s) -> do let oVar = f (inpRec @s) evaluate (forceBVar oVar) let isInput = case _bvRef oVar of BRInp i -> Just i _ -> Nothing pure (isInput, _bvVal oVar) t <- case i of Nothing -> Right <$> readIORef (wRef w) Just i' -> pure $ Left i' pure (t, o) where inpRec :: forall s. Rec (BVar s) as inpRec = evalState (rtraverse (state . go . runIdentity) xs) 0 where go :: a -> Int -> (BVar s a, Int) go x i = (BV (BRInp i) x, i + 1) # INLINE go # # INLINE inpRec # # INLINE fillWengert # instance (Num a, Reifies s W) => Num (BVar s a) where (+) = liftOp2 afNum afNum (+.) (-) = liftOp2 afNum afNum (-.) (*) = liftOp2 afNum afNum (*.) negate = liftOp1 afNum negateOp # INLINE negate # signum = liftOp1 afNum signumOp # INLINE signum # abs = liftOp1 afNum absOp # INLINE abs # fromInteger = constVar . fromInteger # INLINE fromInteger # instance (Fractional a, Reifies s W) => Fractional (BVar s a) where (/) = liftOp2 afNum afNum (/.) recip = liftOp1 afNum recipOp # INLINE recip # fromRational = constVar . fromRational # INLINE fromRational # instance (Floating a, Reifies s W) => Floating (BVar s a) where pi = constVar pi # INLINE pi # exp = liftOp1 afNum expOp # INLINE exp # log = liftOp1 afNum logOp # INLINE log # sqrt = liftOp1 afNum sqrtOp # INLINE sqrt # (**) = liftOp2 afNum afNum (**.) logBase = liftOp2 afNum afNum logBaseOp # INLINE logBase # sin = liftOp1 afNum sinOp # INLINE sin # cos = liftOp1 afNum cosOp # INLINE cos # tan = liftOp1 afNum tanOp asin = liftOp1 afNum asinOp acos = liftOp1 afNum acosOp # INLINE acos # atan = liftOp1 afNum atanOp # INLINE atan # sinh = liftOp1 afNum sinhOp # INLINE sinh # cosh = liftOp1 afNum coshOp # INLINE cosh # tanh = liftOp1 afNum tanhOp # INLINE tanh # asinh = liftOp1 afNum asinhOp # INLINE asinh # acosh = liftOp1 afNum acoshOp # INLINE acosh # atanh = liftOp1 afNum atanhOp # INLINE atanh # | Compares the values inside the ' ' . @since 0.1.5.0 instance Eq a => Eq (BVar s a) where (==) = (==) `on` _bvVal (/=) = (/=) `on` _bvVal | Compares the values inside the ' ' . @since 0.1.5.0 instance Ord a => Ord (BVar s a) where compare = compare `on` _bvVal (<) = (<) `on` _bvVal (<=) = (<=) `on` _bvVal (>) = (>) `on` _bvVal (>=) = (>=) `on` _bvVal itraverse :: forall t a b f. (Traversable t, Monad f) => (Int -> a -> f b) -> t a -> f (t b) itraverse f xs = evalStateT (traverse (StateT . go) xs) 0 where go :: a -> Int -> f (b, Int) go x i = (,i+1) <$> f i x # INLINE itraverse # ixi :: Int -> Lens' [a] a ixi _ _ [] = internalError "ixi" ixi 0 f (x:xs) = (:xs) <$> f x ixi n f (x:xs) = (x:) <$> ixi (n - 1) f xs # INLINE ixi # ixt :: forall b a. Traversal' b a -> Int -> Lens' b a ixt t i f xs = stuff <$> ixi i f contents where contents = xs ^.. t stuff = evalState (traverseOf t (state . const go) xs) where go :: [a] -> (a, [a]) go [] = internalError "ixt" go (y:ys) = (y, ys) instance (Backprop a, Reifies s W) => Backprop (BVar s a) where zero = liftOp1 addFunc . op1 $ \x -> (zero x, zero) # INLINE zero # add = liftOp2 addFunc addFunc . op2 $ \x y -> ( add x y , \d -> (d, d) ) # INLINE add # one = liftOp1 addFunc . op1 $ \x -> (one x, zero) # INLINE one # | The canonical ' ZeroFunc ' for instances of ' Backprop ' . @since 0.2.0.0 zeroFunc :: Backprop a => ZeroFunc a zeroFunc = ZF zero # INLINE zeroFunc # | The canonical ' ' for instances of ' Backprop ' . @since 0.2.0.0 addFunc :: Backprop a => AddFunc a addFunc = AF add # INLINE addFunc # @since 0.2.0.0 oneFunc :: Backprop a => OneFunc a oneFunc = OF one # INLINE oneFunc # internalError :: String -> a internalError m = errorWithoutStackTrace $ "Numeric.Backprop.Internal." ++ m ++ ": unexpected shape involved in gradient computation"
7e8cd3dca862df4ed8f9caa9f792259ab6414562379c93bc2dba5c332e7ffb28
clojure/core.typed
datatype_ancestor_env.clj
Copyright ( c ) , contributors . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^:skip-wiki clojure.core.typed.checker.datatype-ancestor-env (:require [clojure.core.typed.checker.utils :as u] [clojure.core.typed.contract-utils :as con] [clojure.core.typed.checker.type-rep :as r] [clojure.core.typed.checker.type-ctors :as c] [clojure.core.typed.checker.subst :as subst] [clojure.core.typed :as t] [clojure.core.typed.env :as env] [clojure.core.typed.checker.nilsafe-utils :as nilsafe] [clojure.core.typed.current-impl :as impl] [clojure.set :as set]) (:import (clojure.core.typed.checker.type_rep DataType))) (t/typed-deps clojure.core.typed.checker.type-ctors clojure.core.typed.checker.subst) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Type Aliases (t/defalias DTAncestorEnv "Environment mapping datatype names to sets of ancestor types." (t/Map t/Sym (t/Set r/ScopedType))) (def tmap? (con/hash-c? any? (some-fn delay? r/Scope? r/Type?))) (def dt-ancestor-env? (con/hash-c? symbol? tmap?)) (t/ann ^:no-check inst-ancestors [DataType (t/U nil (t/Seqable r/Type)) -> (t/Set r/Type)]) (defn inst-ancestors "Given a datatype, return its instantiated ancestors" [{poly :poly? :as dt} anctrs] {:pre [(r/DataType? dt) ((some-fn nil? map?) anctrs)] :post [((con/set-c? r/Type?) %)]} (into #{} (map (fn [[_ t]] (c/inst-and-subst (force t) poly))) anctrs)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Interface (defn all-dt-ancestors [] {:post [(map? %)]} (get (env/deref-checker) impl/current-dt-ancestors-kw {})) (t/ann ^:no-check get-datatype-ancestors [DataType -> (t/Set r/Type)]) (defn get-datatype-ancestors "Returns the set of overriden ancestors of the given DataType." [{:keys [poly? the-class] :as dt}] {:pre [(r/DataType? dt)]} (let [as (get (all-dt-ancestors) the-class)] (inst-ancestors dt as))) (t/ann ^:no-check add-datatype-ancestors [t/Sym (t/Map t/Any (t/U (t/Delay r/Type) r/Type)) -> nil]) (def add-datatype-ancestors impl/add-datatype-ancestors) (t/ann ^:no-check reset-datatype-ancestors! [DTAncestorEnv -> nil]) (defn reset-datatype-ancestors! "Reset the current ancestor map." [aenv] {:pre [(dt-ancestor-env? aenv)]} (env/swap-checker! assoc impl/current-dt-ancestors-kw aenv) nil)
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/datatype_ancestor_env.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. Type Aliases
Copyright ( c ) , contributors . (ns ^:skip-wiki clojure.core.typed.checker.datatype-ancestor-env (:require [clojure.core.typed.checker.utils :as u] [clojure.core.typed.contract-utils :as con] [clojure.core.typed.checker.type-rep :as r] [clojure.core.typed.checker.type-ctors :as c] [clojure.core.typed.checker.subst :as subst] [clojure.core.typed :as t] [clojure.core.typed.env :as env] [clojure.core.typed.checker.nilsafe-utils :as nilsafe] [clojure.core.typed.current-impl :as impl] [clojure.set :as set]) (:import (clojure.core.typed.checker.type_rep DataType))) (t/typed-deps clojure.core.typed.checker.type-ctors clojure.core.typed.checker.subst) (t/defalias DTAncestorEnv "Environment mapping datatype names to sets of ancestor types." (t/Map t/Sym (t/Set r/ScopedType))) (def tmap? (con/hash-c? any? (some-fn delay? r/Scope? r/Type?))) (def dt-ancestor-env? (con/hash-c? symbol? tmap?)) (t/ann ^:no-check inst-ancestors [DataType (t/U nil (t/Seqable r/Type)) -> (t/Set r/Type)]) (defn inst-ancestors "Given a datatype, return its instantiated ancestors" [{poly :poly? :as dt} anctrs] {:pre [(r/DataType? dt) ((some-fn nil? map?) anctrs)] :post [((con/set-c? r/Type?) %)]} (into #{} (map (fn [[_ t]] (c/inst-and-subst (force t) poly))) anctrs)) Interface (defn all-dt-ancestors [] {:post [(map? %)]} (get (env/deref-checker) impl/current-dt-ancestors-kw {})) (t/ann ^:no-check get-datatype-ancestors [DataType -> (t/Set r/Type)]) (defn get-datatype-ancestors "Returns the set of overriden ancestors of the given DataType." [{:keys [poly? the-class] :as dt}] {:pre [(r/DataType? dt)]} (let [as (get (all-dt-ancestors) the-class)] (inst-ancestors dt as))) (t/ann ^:no-check add-datatype-ancestors [t/Sym (t/Map t/Any (t/U (t/Delay r/Type) r/Type)) -> nil]) (def add-datatype-ancestors impl/add-datatype-ancestors) (t/ann ^:no-check reset-datatype-ancestors! [DTAncestorEnv -> nil]) (defn reset-datatype-ancestors! "Reset the current ancestor map." [aenv] {:pre [(dt-ancestor-env? aenv)]} (env/swap-checker! assoc impl/current-dt-ancestors-kw aenv) nil)
3cb576a15f0407e15109ad3562b26588708c58fcc7d2752e4c04a9727b5a440a
qfpl/ban-instance
Spec.hs
{-# OPTIONS_GHC -Wno-unused-matches -Wno-unused-top-binds #-} {-# LANGUAGE DataKinds #-} # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} # LANGUAGE UndecidableInstances # import Language.Haskell.Instance.Ban -- Test code generation. We define a class and ban an instance of it, -- checking that the generated code throws no warnings. If this file -- compiles cleanly, the "test" has passed. class TestClass a b | a -> b where testFunction :: a -> b $(banInstance [t|TestClass Char Int|] "because it's really bad") -- Test that we haven't overlapped other instances by mistake. instance TestClass Int Int where testFunction = const 0 main :: IO () main = pure ()
null
https://raw.githubusercontent.com/qfpl/ban-instance/fa47713251ba76ceaef92407c2ed3a6acf635182/test/Spec.hs
haskell
# OPTIONS_GHC -Wno-unused-matches -Wno-unused-top-binds # # LANGUAGE DataKinds # # LANGUAGE RankNTypes # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # Test code generation. We define a class and ban an instance of it, checking that the generated code throws no warnings. If this file compiles cleanly, the "test" has passed. Test that we haven't overlapped other instances by mistake.
# LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # # LANGUAGE UndecidableInstances # import Language.Haskell.Instance.Ban class TestClass a b | a -> b where testFunction :: a -> b $(banInstance [t|TestClass Char Int|] "because it's really bad") instance TestClass Int Int where testFunction = const 0 main :: IO () main = pure ()
48f934395e96e2f688f92caa463e357aff19e02b7d1b3b19ed53e6194adece4b
cbaggers/cepl
touch.lisp
the touch function will nudge a gpu asset and print some metadata . ;; For pipelines it will trigger the upload if this hasnt already happened. ;; For everything (including pipelines) it will check the validity of the ;; gl object in some way. ;; print the metadata & return the metadata in some form
null
https://raw.githubusercontent.com/cbaggers/cepl/d1a10b6c8f4cedc07493bf06aef3a56c7b6f8d5b/core/protocode/touch.lisp
lisp
For pipelines it will trigger the upload if this hasnt already happened. For everything (including pipelines) it will check the validity of the gl object in some way. print the metadata & return the metadata in some form
the touch function will nudge a gpu asset and print some metadata .
f362a5afbad2d0bb6bed775be05f1c24963290d8a69b03f8af77065a317bb22b
macourtney/drift
core.clj
(ns drift.core (:import [java.io File] [java.util Comparator TreeSet]) (:require [clojure.string :as string] [clojure.tools.logging :as logging] [clojure.tools.loading-utils :as loading-utils] [drift.config :as config])) (defn #^{ :doc "Runs the init function with the given args." } run-init [args] (when-let [init-fn (config/find-init-fn)] (init-fn args))) (defn run-finished "runs the finished function" [] (when-let [finished-fn (config/find-finished-fn)] (finished-fn))) (defn with-init-config "run the init fn, merge results into config, then call the next function with that config bound to drift.config/*config-map*" [args f] (let [init-fn (config/find-init-fn) init-config (if init-fn (init-fn args))] (config/with-config-map (merge (config/find-config) (if (map? init-config) init-config)) (fn [] (let [result (f)] (run-finished) result))))) (defn #^{:doc "Returns the directory where Conjure is running from."} user-directory [] (new File (.getProperty (System/getProperties) "user.dir"))) (defn migrate-directory [] (File. (user-directory) (config/find-migrate-dir-name))) (defn #^{:doc "Returns the file object if the given file is in the given directory, nil otherwise."} find-directory [directory file-name] (when (and file-name directory (string? file-name) (instance? File directory)) (let [file (File. (.getPath directory) file-name)] (when (and file (.exists file)) file)))) (defn #^{ :doc "Finds the migrate directory." } find-migrate-directory [] (let [user-directory (user-directory) migrate-dir-name (config/find-migrate-dir-name)] (find-directory user-directory migrate-dir-name))) (defn migrate-namespace-dir ([] (migrate-namespace-dir (config/find-migrate-dir-name))) ([migrate-dir-name] (when migrate-dir-name (.substring migrate-dir-name (count (config/find-src-dir)))))) (defn #^{ :doc "Returns the namespace prefix for the migrate directory name." } migrate-namespace-prefix-from-directory ([] (migrate-namespace-prefix-from-directory (config/find-migrate-dir-name))) ([migrate-dir-name] (loading-utils/slashes-to-dots (loading-utils/underscores-to-dashes (migrate-namespace-dir migrate-dir-name))))) (defn migrate-namespace-prefix [] (or (config/namespace-prefix) (migrate-namespace-prefix-from-directory))) (defn #^{ :doc "Returns a string for the namespace of the given file in the given directory." } namespace-string-for-file [file-name] (when file-name (str (migrate-namespace-prefix) "." (loading-utils/clj-file-to-symbol-string file-name)))) (defn namespace-name-str [migration-namespace] (when migration-namespace (if (string? migration-namespace) migration-namespace (name (ns-name migration-namespace))))) (defn migration-namespace? [migration-namespace] (.startsWith (namespace-name-str migration-namespace) (str (migrate-namespace-prefix) "."))) (defn migration-number-from-namespace [migration-namespace] (when migration-namespace (when-let [migration-number-str (re-find #"^[0-9]+" (last (string/split (namespace-name-str migration-namespace) #"\.")))] (Long/parseLong migration-number-str)))) (defn migration-compartor [ascending?] (reify Comparator (compare [this namespace1 namespace2] (try (if ascending? (.compareTo (migration-number-from-namespace namespace1) (migration-number-from-namespace namespace2)) (.compareTo (migration-number-from-namespace namespace2) (migration-number-from-namespace namespace1))) (catch Throwable t (.printStackTrace t)))) (equals [this object] (= this object)))) (defn user-migration-namespaces [] (when-let [migration-namespaces (config/migration-namespaces)] (migration-namespaces (config/find-migrate-dir-name) (migrate-namespace-prefix)))) (defn default-migration-namespaces [] (map namespace-string-for-file (filter #(re-matches #".*\.clj$" %) (loading-utils/all-class-path-file-names (migrate-namespace-dir))))) (defn sort-migration-namespaces ([migration-namespaces] (sort-migration-namespaces migration-namespaces true)) ([migration-namespaces ascending?] (seq (doto (TreeSet. (migration-compartor ascending?)) (.addAll migration-namespaces))))) (defn unsorted-migration-namespaces [] (set (or (user-migration-namespaces) (default-migration-namespaces)))) (defn migration-namespaces ([] (migration-namespaces true)) ([ascending?] (sort-migration-namespaces (unsorted-migration-namespaces) ascending?))) (defn #^{ :doc "Returns all of the migration file names with numbers between low-number and high-number inclusive." } migration-namespaces-in-range [low-number high-number] (sort-migration-namespaces (filter (fn [migration-namespace] (let [migration-number (migration-number-from-namespace migration-namespace)] (and (>= migration-number low-number) (<= migration-number high-number)))) (unsorted-migration-namespaces)) (< low-number high-number))) (defn #^{ :doc "Returns all of the numbers prepended to the migration files." } migration-numbers ([] (migration-numbers (migration-namespaces))) ([migration-namespaces] (filter identity (map migration-number-from-namespace migration-namespaces)))) (defn max-migration-number "Returns the maximum number of all migration files." ([migration-namespaces] (reduce max 0 (migration-numbers migration-namespaces))) ([] (reduce max 0 (migration-numbers)))) (defn #^{ :doc "Returns the next number to use for a migration file." } find-next-migrate-number [] (inc (max-migration-number))) (defn #^{ :doc "Finds the number of the migration file before the given number" } migration-number-before ([migration-number] (migration-number-before migration-number (migration-namespaces))) ([migration-number migration-namespaces] (when migration-number (apply max 0 (filter #(< %1 migration-number) (migration-numbers migration-namespaces)))))) (defn find-migration-namespace [migration-name] (some #(when (re-find (re-pattern (str (migrate-namespace-prefix) "\\.[0-9]+-" migration-name)) %1) %1) (map namespace-name-str (migration-namespaces)))) (defn #^{ :doc "The migration file with the given migration name." } find-migration-file ([migration-name] (find-migration-file (find-migrate-directory) migration-name)) ([migrate-directory migration-name] (when-let [namespace-str (find-migration-namespace migration-name)] (File. migrate-directory (.getName (File. (loading-utils/symbol-string-to-clj-file namespace-str))))))) (defn #^{ :doc "Returns the migration namespace for the given migration file." } migration-namespace [migration-file] (when migration-file (namespace-string-for-file (.getName migration-file))))
null
https://raw.githubusercontent.com/macourtney/drift/b5cf735ab41ff2c95b0b1d9cf990faa342353171/src/drift/core.clj
clojure
(ns drift.core (:import [java.io File] [java.util Comparator TreeSet]) (:require [clojure.string :as string] [clojure.tools.logging :as logging] [clojure.tools.loading-utils :as loading-utils] [drift.config :as config])) (defn #^{ :doc "Runs the init function with the given args." } run-init [args] (when-let [init-fn (config/find-init-fn)] (init-fn args))) (defn run-finished "runs the finished function" [] (when-let [finished-fn (config/find-finished-fn)] (finished-fn))) (defn with-init-config "run the init fn, merge results into config, then call the next function with that config bound to drift.config/*config-map*" [args f] (let [init-fn (config/find-init-fn) init-config (if init-fn (init-fn args))] (config/with-config-map (merge (config/find-config) (if (map? init-config) init-config)) (fn [] (let [result (f)] (run-finished) result))))) (defn #^{:doc "Returns the directory where Conjure is running from."} user-directory [] (new File (.getProperty (System/getProperties) "user.dir"))) (defn migrate-directory [] (File. (user-directory) (config/find-migrate-dir-name))) (defn #^{:doc "Returns the file object if the given file is in the given directory, nil otherwise."} find-directory [directory file-name] (when (and file-name directory (string? file-name) (instance? File directory)) (let [file (File. (.getPath directory) file-name)] (when (and file (.exists file)) file)))) (defn #^{ :doc "Finds the migrate directory." } find-migrate-directory [] (let [user-directory (user-directory) migrate-dir-name (config/find-migrate-dir-name)] (find-directory user-directory migrate-dir-name))) (defn migrate-namespace-dir ([] (migrate-namespace-dir (config/find-migrate-dir-name))) ([migrate-dir-name] (when migrate-dir-name (.substring migrate-dir-name (count (config/find-src-dir)))))) (defn #^{ :doc "Returns the namespace prefix for the migrate directory name." } migrate-namespace-prefix-from-directory ([] (migrate-namespace-prefix-from-directory (config/find-migrate-dir-name))) ([migrate-dir-name] (loading-utils/slashes-to-dots (loading-utils/underscores-to-dashes (migrate-namespace-dir migrate-dir-name))))) (defn migrate-namespace-prefix [] (or (config/namespace-prefix) (migrate-namespace-prefix-from-directory))) (defn #^{ :doc "Returns a string for the namespace of the given file in the given directory." } namespace-string-for-file [file-name] (when file-name (str (migrate-namespace-prefix) "." (loading-utils/clj-file-to-symbol-string file-name)))) (defn namespace-name-str [migration-namespace] (when migration-namespace (if (string? migration-namespace) migration-namespace (name (ns-name migration-namespace))))) (defn migration-namespace? [migration-namespace] (.startsWith (namespace-name-str migration-namespace) (str (migrate-namespace-prefix) "."))) (defn migration-number-from-namespace [migration-namespace] (when migration-namespace (when-let [migration-number-str (re-find #"^[0-9]+" (last (string/split (namespace-name-str migration-namespace) #"\.")))] (Long/parseLong migration-number-str)))) (defn migration-compartor [ascending?] (reify Comparator (compare [this namespace1 namespace2] (try (if ascending? (.compareTo (migration-number-from-namespace namespace1) (migration-number-from-namespace namespace2)) (.compareTo (migration-number-from-namespace namespace2) (migration-number-from-namespace namespace1))) (catch Throwable t (.printStackTrace t)))) (equals [this object] (= this object)))) (defn user-migration-namespaces [] (when-let [migration-namespaces (config/migration-namespaces)] (migration-namespaces (config/find-migrate-dir-name) (migrate-namespace-prefix)))) (defn default-migration-namespaces [] (map namespace-string-for-file (filter #(re-matches #".*\.clj$" %) (loading-utils/all-class-path-file-names (migrate-namespace-dir))))) (defn sort-migration-namespaces ([migration-namespaces] (sort-migration-namespaces migration-namespaces true)) ([migration-namespaces ascending?] (seq (doto (TreeSet. (migration-compartor ascending?)) (.addAll migration-namespaces))))) (defn unsorted-migration-namespaces [] (set (or (user-migration-namespaces) (default-migration-namespaces)))) (defn migration-namespaces ([] (migration-namespaces true)) ([ascending?] (sort-migration-namespaces (unsorted-migration-namespaces) ascending?))) (defn #^{ :doc "Returns all of the migration file names with numbers between low-number and high-number inclusive." } migration-namespaces-in-range [low-number high-number] (sort-migration-namespaces (filter (fn [migration-namespace] (let [migration-number (migration-number-from-namespace migration-namespace)] (and (>= migration-number low-number) (<= migration-number high-number)))) (unsorted-migration-namespaces)) (< low-number high-number))) (defn #^{ :doc "Returns all of the numbers prepended to the migration files." } migration-numbers ([] (migration-numbers (migration-namespaces))) ([migration-namespaces] (filter identity (map migration-number-from-namespace migration-namespaces)))) (defn max-migration-number "Returns the maximum number of all migration files." ([migration-namespaces] (reduce max 0 (migration-numbers migration-namespaces))) ([] (reduce max 0 (migration-numbers)))) (defn #^{ :doc "Returns the next number to use for a migration file." } find-next-migrate-number [] (inc (max-migration-number))) (defn #^{ :doc "Finds the number of the migration file before the given number" } migration-number-before ([migration-number] (migration-number-before migration-number (migration-namespaces))) ([migration-number migration-namespaces] (when migration-number (apply max 0 (filter #(< %1 migration-number) (migration-numbers migration-namespaces)))))) (defn find-migration-namespace [migration-name] (some #(when (re-find (re-pattern (str (migrate-namespace-prefix) "\\.[0-9]+-" migration-name)) %1) %1) (map namespace-name-str (migration-namespaces)))) (defn #^{ :doc "The migration file with the given migration name." } find-migration-file ([migration-name] (find-migration-file (find-migrate-directory) migration-name)) ([migrate-directory migration-name] (when-let [namespace-str (find-migration-namespace migration-name)] (File. migrate-directory (.getName (File. (loading-utils/symbol-string-to-clj-file namespace-str))))))) (defn #^{ :doc "Returns the migration namespace for the given migration file." } migration-namespace [migration-file] (when migration-file (namespace-string-for-file (.getName migration-file))))
73e5375e2334eb850382bece0e0d6ad4817cba32b19ee11e62a551b01b44c6ba
Decentralized-Pictures/T4L3NT
test_pattern_matching_input.ml
let _ = let x = Some 1 in match[@time.duration pattern_matching] x with Some a -> a | None -> 2
null
https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/lib_time_measurement/ppx/test/valid/test_pattern_matching_input.ml
ocaml
let _ = let x = Some 1 in match[@time.duration pattern_matching] x with Some a -> a | None -> 2
12072772c17e0be763715a271caaf011b6f8174ebb060dd804272aae4c4632f3
gfngfn/otfed
encodeName.ml
open Basic open EncodeBasic open EncodeOperation.Open type relative_offset = int type name_record_and_offset = Value.Name.name_record * relative_offset Makes ( possibly a portion of ) string storage from NameRecords . The offsets in return values are relative to the beggining of the string storage . The offsets in return values are relative to the beggining of the string storage. *) let make_name_string_storage (name_records : Value.Name.name_record list) : (string * name_record_and_offset list) ok = let enc = let open EncodeOperation in let open Value.Name in name_records |> mapM (fun name_record -> current >>= fun reloffset -> e_bytes name_record.name >>= fun () -> return (name_record, reloffset) ) in enc |> EncodeOperation.run Makes a portion of string storage from LangTagRecords . The offsets in return values are relative to the end of the district of the string storage composed by NameRecords . The offsets in return values are relative to the end of the district of the string storage composed by NameRecords. *) let make_lang_tag_string_storage (lang_tags : Value.Name.lang_tag list) : (string * (string * relative_offset) list) ok = let enc = let open EncodeOperation in lang_tags |> mapM (fun lang_tag -> current >>= fun reloffset -> e_bytes lang_tag >>= fun () -> return (lang_tag, reloffset) ) in enc |> EncodeOperation.run let e_name_records (names_and_reloffsets : name_record_and_offset list) : unit encoder = let open EncodeOperation in let open Value.Name in names_and_reloffsets |> e_list (fun (r, reloffset) -> (* Here, `reloffset` is relative to the beginning of the string storage. *) let length = String.length r.name in e_uint16 r.platform_id >>= fun () -> e_uint16 r.encoding_id >>= fun () -> e_uint16 r.language_id >>= fun () -> e_uint16 r.name_id >>= fun () -> e_uint16 length >>= fun () -> e_uint16 reloffset ) let e_lang_tag_records ~starts_at:(starts_at : relative_offset) (lang_tags_and_reloffsets : (string * relative_offset) list) = let open EncodeOperation in lang_tags_and_reloffsets |> e_list (fun (lang_tag, reloffset) -> (* Here, `reloffset` is relative to the end of the area of the string storage where names are stored. *) let length = String.length lang_tag in e_uint16 length >>= fun () -> e_uint16 (starts_at + reloffset) ) let encode_name (name : Value.Name.t) : string ok = let open ResultMonad in let name_records = name.name_records in let count = List.length name_records in make_name_string_storage name.name_records >>= fun (storage1, names_and_reloffsets) -> let length_storage1 = String.length storage1 in match name.lang_tags with | None -> let offset_string_storage = 6 + 12 * count in let enc = let open EncodeOperation in e_uint16 0 >>= fun () -> (* format number *) e_uint16 count >>= fun () -> e_uint16 offset_string_storage >>= fun () -> e_name_records names_and_reloffsets >>= fun () -> e_bytes storage1 in enc |> EncodeOperation.run >>= fun (contents, ()) -> return contents | Some(lang_tags) -> let lang_tag_count = List.length lang_tags in let offset_string_storage = 6 + 12 * count + 4 * lang_tag_count in make_lang_tag_string_storage lang_tags >>= fun (storage2, lang_tags_and_reloffsets) -> let enc = let open EncodeOperation in e_uint16 1 >>= fun () -> (* format number *) e_uint16 count >>= fun () -> e_uint16 offset_string_storage >>= fun () -> e_name_records names_and_reloffsets >>= fun () -> e_uint16 lang_tag_count >>= fun () -> e_lang_tag_records ~starts_at:length_storage1 lang_tags_and_reloffsets >>= fun () -> e_bytes storage1 >>= fun () -> e_bytes storage2 in enc |> EncodeOperation.run >>= fun (contents, ()) -> return contents let make (name : Value.Name.t) : table ok = let open ResultMonad in encode_name name >>= fun contents -> return { tag = Value.Tag.table_name; contents; }
null
https://raw.githubusercontent.com/gfngfn/otfed/3c6d8ea0b05fc18a48cb423451da7858bf73d1d0/src/encodeName.ml
ocaml
Here, `reloffset` is relative to the beginning of the string storage. Here, `reloffset` is relative to the end of the area of the string storage where names are stored. format number format number
open Basic open EncodeBasic open EncodeOperation.Open type relative_offset = int type name_record_and_offset = Value.Name.name_record * relative_offset Makes ( possibly a portion of ) string storage from NameRecords . The offsets in return values are relative to the beggining of the string storage . The offsets in return values are relative to the beggining of the string storage. *) let make_name_string_storage (name_records : Value.Name.name_record list) : (string * name_record_and_offset list) ok = let enc = let open EncodeOperation in let open Value.Name in name_records |> mapM (fun name_record -> current >>= fun reloffset -> e_bytes name_record.name >>= fun () -> return (name_record, reloffset) ) in enc |> EncodeOperation.run Makes a portion of string storage from LangTagRecords . The offsets in return values are relative to the end of the district of the string storage composed by NameRecords . The offsets in return values are relative to the end of the district of the string storage composed by NameRecords. *) let make_lang_tag_string_storage (lang_tags : Value.Name.lang_tag list) : (string * (string * relative_offset) list) ok = let enc = let open EncodeOperation in lang_tags |> mapM (fun lang_tag -> current >>= fun reloffset -> e_bytes lang_tag >>= fun () -> return (lang_tag, reloffset) ) in enc |> EncodeOperation.run let e_name_records (names_and_reloffsets : name_record_and_offset list) : unit encoder = let open EncodeOperation in let open Value.Name in names_and_reloffsets |> e_list (fun (r, reloffset) -> let length = String.length r.name in e_uint16 r.platform_id >>= fun () -> e_uint16 r.encoding_id >>= fun () -> e_uint16 r.language_id >>= fun () -> e_uint16 r.name_id >>= fun () -> e_uint16 length >>= fun () -> e_uint16 reloffset ) let e_lang_tag_records ~starts_at:(starts_at : relative_offset) (lang_tags_and_reloffsets : (string * relative_offset) list) = let open EncodeOperation in lang_tags_and_reloffsets |> e_list (fun (lang_tag, reloffset) -> let length = String.length lang_tag in e_uint16 length >>= fun () -> e_uint16 (starts_at + reloffset) ) let encode_name (name : Value.Name.t) : string ok = let open ResultMonad in let name_records = name.name_records in let count = List.length name_records in make_name_string_storage name.name_records >>= fun (storage1, names_and_reloffsets) -> let length_storage1 = String.length storage1 in match name.lang_tags with | None -> let offset_string_storage = 6 + 12 * count in let enc = let open EncodeOperation in e_uint16 count >>= fun () -> e_uint16 offset_string_storage >>= fun () -> e_name_records names_and_reloffsets >>= fun () -> e_bytes storage1 in enc |> EncodeOperation.run >>= fun (contents, ()) -> return contents | Some(lang_tags) -> let lang_tag_count = List.length lang_tags in let offset_string_storage = 6 + 12 * count + 4 * lang_tag_count in make_lang_tag_string_storage lang_tags >>= fun (storage2, lang_tags_and_reloffsets) -> let enc = let open EncodeOperation in e_uint16 count >>= fun () -> e_uint16 offset_string_storage >>= fun () -> e_name_records names_and_reloffsets >>= fun () -> e_uint16 lang_tag_count >>= fun () -> e_lang_tag_records ~starts_at:length_storage1 lang_tags_and_reloffsets >>= fun () -> e_bytes storage1 >>= fun () -> e_bytes storage2 in enc |> EncodeOperation.run >>= fun (contents, ()) -> return contents let make (name : Value.Name.t) : table ok = let open ResultMonad in encode_name name >>= fun contents -> return { tag = Value.Tag.table_name; contents; }
ae9ec99872d7e6be238785a460a88d8454f87535240c2cbae50d445b3c1a68ad
input-output-hk/cardano-ledger
ShelleyEraGen.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - orphans # module Test.Cardano.Ledger.Shelley.Generator.ShelleyEraGen (genCoin) where import qualified Cardano.Crypto.DSIGN as DSIGN import qualified Cardano.Crypto.KES as KES import Cardano.Crypto.Util (SignableRepresentation) import Cardano.Ledger.AuxiliaryData (AuxiliaryDataHash) import Cardano.Ledger.BaseTypes (StrictMaybe (..)) import Cardano.Ledger.Core import Cardano.Ledger.Crypto (DSIGN, KES) import qualified Cardano.Ledger.Crypto as CC (Crypto) import Cardano.Ledger.Pretty () import Cardano.Ledger.Shelley (ShelleyEra) import Cardano.Ledger.Shelley.API ( Coin (..), DCert, Update, ) import Cardano.Ledger.Shelley.Scripts (MultiSig (..)) import Cardano.Ledger.Shelley.Tx (TxIn (..)) import Cardano.Ledger.Shelley.TxBody ( ShelleyTxBody (ShelleyTxBody, stbInputs, stbOutputs, stbTxFee), ShelleyTxOut (..), Withdrawals (..), ) import Cardano.Ledger.Shelley.TxWits (ShelleyTxWits (ShelleyTxWits)) import Cardano.Ledger.Slot (SlotNo (..)) import Cardano.Ledger.Val ((<+>)) import Cardano.Protocol.TPraos.API (PraosCrypto) import Control.Monad (replicateM) import Data.Sequence.Strict (StrictSeq ((:|>))) import Data.Set (Set) import Lens.Micro.Extras (view) import Test.Cardano.Ledger.Shelley.ConcreteCryptoTypes (Mock) import Test.Cardano.Ledger.Shelley.Generator.Constants (Constants (..)) import Test.Cardano.Ledger.Shelley.Generator.Core ( GenEnv (..), genCoin, genNatural, ) import Test.Cardano.Ledger.Shelley.Generator.EraGen (EraGen (..), MinGenTxout (..)) import Test.Cardano.Ledger.Shelley.Generator.ScriptClass ( Quantifier (..), ScriptClass (..), ) import Test.Cardano.Ledger.Shelley.Generator.Trace.Chain () import Test.Cardano.Ledger.Shelley.Generator.TxAuxData (genMetadata) import Test.Cardano.Ledger.Shelley.Generator.Update (genPParams, genShelleyPParamsUpdate) import Test.QuickCheck (Gen) ----------------------------------------------------------------------------- ShelleyEra instances for EraGen and ScriptClass ---------------------------------------------------------------------------- ShelleyEra instances for EraGen and ScriptClass -----------------------------------------------------------------------------} instance ( PraosCrypto c , DSIGN.Signable (DSIGN c) ~ SignableRepresentation , KES.Signable (KES c) ~ SignableRepresentation ) => EraGen (ShelleyEra c) where genGenesisValue ( GenEnv _keySpace _scriptspace Constants {minGenesisOutputVal, maxGenesisOutputVal} ) = genCoin minGenesisOutputVal maxGenesisOutputVal genEraTxBody _ge _utxo = genTxBody genEraAuxiliaryData = genMetadata updateEraTxBody _utxo _pp _wits body' fee ins out = body' { stbTxFee = fee , stbInputs = stbInputs body' <> ins , stbOutputs = stbOutputs body' :|> out } genEraPParamsUpdate = genShelleyPParamsUpdate @(ShelleyEra c) genEraPParams = genPParams genEraTxWits _ setWitVKey mapScriptWit = ShelleyTxWits setWitVKey mapScriptWit mempty instance CC.Crypto c => ScriptClass (ShelleyEra c) where basescript _proxy = RequireSignature isKey _ (RequireSignature hk) = Just hk isKey _ _ = Nothing quantify _ (RequireAllOf xs) = AllOf xs quantify _ (RequireAnyOf xs) = AnyOf xs quantify _ (RequireMOf n xs) = MOf n xs quantify _ t = Leaf t unQuantify _ (AllOf xs) = RequireAllOf xs unQuantify _ (AnyOf xs) = RequireAnyOf xs unQuantify _ (MOf n xs) = RequireMOf n xs unQuantify _ (Leaf t) = t ----------------------------------------------------------------------------- ShelleyEra generators ---------------------------------------------------------------------------- ShelleyEra generators -----------------------------------------------------------------------------} genTxBody :: EraTxOut era => PParams era -> SlotNo -> Set (TxIn (EraCrypto era)) -> StrictSeq (TxOut era) -> StrictSeq (DCert (EraCrypto era)) -> Withdrawals (EraCrypto era) -> Coin -> StrictMaybe (Update era) -> StrictMaybe (AuxiliaryDataHash (EraCrypto era)) -> Gen (ShelleyTxBody era, [MultiSig era]) genTxBody _pparams slot inputs outputs certs withdrawals fee update adHash = do ttl <- genTimeToLive slot return ( ShelleyTxBody inputs outputs certs withdrawals fee ttl update adHash does not need any additional script witnesses ) genTimeToLive :: SlotNo -> Gen SlotNo genTimeToLive currentSlot = do ttl <- genNatural 50 100 pure $ currentSlot + SlotNo (fromIntegral ttl) instance (Mock c) => MinGenTxout (ShelleyEra c) where calcEraMinUTxO _txout = view ppMinUTxOValueL addValToTxOut v (ShelleyTxOut a u) = ShelleyTxOut a (v <+> u) genEraTxOut _genenv genVal addrs = do values <- replicateM (length addrs) genVal pure (zipWith mkBasicTxOut addrs values)
null
https://raw.githubusercontent.com/input-output-hk/cardano-ledger/38aa337834ccb9b5f47dbf9e81a3b986dcdd57f5/eras/shelley/test-suite/src/Test/Cardano/Ledger/Shelley/Generator/ShelleyEraGen.hs
haskell
--------------------------------------------------------------------------- -------------------------------------------------------------------------- ---------------------------------------------------------------------------} --------------------------------------------------------------------------- -------------------------------------------------------------------------- ---------------------------------------------------------------------------}
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE NamedFieldPuns # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # # OPTIONS_GHC -fno - warn - orphans # module Test.Cardano.Ledger.Shelley.Generator.ShelleyEraGen (genCoin) where import qualified Cardano.Crypto.DSIGN as DSIGN import qualified Cardano.Crypto.KES as KES import Cardano.Crypto.Util (SignableRepresentation) import Cardano.Ledger.AuxiliaryData (AuxiliaryDataHash) import Cardano.Ledger.BaseTypes (StrictMaybe (..)) import Cardano.Ledger.Core import Cardano.Ledger.Crypto (DSIGN, KES) import qualified Cardano.Ledger.Crypto as CC (Crypto) import Cardano.Ledger.Pretty () import Cardano.Ledger.Shelley (ShelleyEra) import Cardano.Ledger.Shelley.API ( Coin (..), DCert, Update, ) import Cardano.Ledger.Shelley.Scripts (MultiSig (..)) import Cardano.Ledger.Shelley.Tx (TxIn (..)) import Cardano.Ledger.Shelley.TxBody ( ShelleyTxBody (ShelleyTxBody, stbInputs, stbOutputs, stbTxFee), ShelleyTxOut (..), Withdrawals (..), ) import Cardano.Ledger.Shelley.TxWits (ShelleyTxWits (ShelleyTxWits)) import Cardano.Ledger.Slot (SlotNo (..)) import Cardano.Ledger.Val ((<+>)) import Cardano.Protocol.TPraos.API (PraosCrypto) import Control.Monad (replicateM) import Data.Sequence.Strict (StrictSeq ((:|>))) import Data.Set (Set) import Lens.Micro.Extras (view) import Test.Cardano.Ledger.Shelley.ConcreteCryptoTypes (Mock) import Test.Cardano.Ledger.Shelley.Generator.Constants (Constants (..)) import Test.Cardano.Ledger.Shelley.Generator.Core ( GenEnv (..), genCoin, genNatural, ) import Test.Cardano.Ledger.Shelley.Generator.EraGen (EraGen (..), MinGenTxout (..)) import Test.Cardano.Ledger.Shelley.Generator.ScriptClass ( Quantifier (..), ScriptClass (..), ) import Test.Cardano.Ledger.Shelley.Generator.Trace.Chain () import Test.Cardano.Ledger.Shelley.Generator.TxAuxData (genMetadata) import Test.Cardano.Ledger.Shelley.Generator.Update (genPParams, genShelleyPParamsUpdate) import Test.QuickCheck (Gen) ShelleyEra instances for EraGen and ScriptClass ShelleyEra instances for EraGen and ScriptClass instance ( PraosCrypto c , DSIGN.Signable (DSIGN c) ~ SignableRepresentation , KES.Signable (KES c) ~ SignableRepresentation ) => EraGen (ShelleyEra c) where genGenesisValue ( GenEnv _keySpace _scriptspace Constants {minGenesisOutputVal, maxGenesisOutputVal} ) = genCoin minGenesisOutputVal maxGenesisOutputVal genEraTxBody _ge _utxo = genTxBody genEraAuxiliaryData = genMetadata updateEraTxBody _utxo _pp _wits body' fee ins out = body' { stbTxFee = fee , stbInputs = stbInputs body' <> ins , stbOutputs = stbOutputs body' :|> out } genEraPParamsUpdate = genShelleyPParamsUpdate @(ShelleyEra c) genEraPParams = genPParams genEraTxWits _ setWitVKey mapScriptWit = ShelleyTxWits setWitVKey mapScriptWit mempty instance CC.Crypto c => ScriptClass (ShelleyEra c) where basescript _proxy = RequireSignature isKey _ (RequireSignature hk) = Just hk isKey _ _ = Nothing quantify _ (RequireAllOf xs) = AllOf xs quantify _ (RequireAnyOf xs) = AnyOf xs quantify _ (RequireMOf n xs) = MOf n xs quantify _ t = Leaf t unQuantify _ (AllOf xs) = RequireAllOf xs unQuantify _ (AnyOf xs) = RequireAnyOf xs unQuantify _ (MOf n xs) = RequireMOf n xs unQuantify _ (Leaf t) = t ShelleyEra generators ShelleyEra generators genTxBody :: EraTxOut era => PParams era -> SlotNo -> Set (TxIn (EraCrypto era)) -> StrictSeq (TxOut era) -> StrictSeq (DCert (EraCrypto era)) -> Withdrawals (EraCrypto era) -> Coin -> StrictMaybe (Update era) -> StrictMaybe (AuxiliaryDataHash (EraCrypto era)) -> Gen (ShelleyTxBody era, [MultiSig era]) genTxBody _pparams slot inputs outputs certs withdrawals fee update adHash = do ttl <- genTimeToLive slot return ( ShelleyTxBody inputs outputs certs withdrawals fee ttl update adHash does not need any additional script witnesses ) genTimeToLive :: SlotNo -> Gen SlotNo genTimeToLive currentSlot = do ttl <- genNatural 50 100 pure $ currentSlot + SlotNo (fromIntegral ttl) instance (Mock c) => MinGenTxout (ShelleyEra c) where calcEraMinUTxO _txout = view ppMinUTxOValueL addValToTxOut v (ShelleyTxOut a u) = ShelleyTxOut a (v <+> u) genEraTxOut _genenv genVal addrs = do values <- replicateM (length addrs) genVal pure (zipWith mkBasicTxOut addrs values)
70a65152723ad2f75f424c5cca8412b1a5e2e9fb497ade1c95c2424c48e12dc8
evincarofautumn/kitten
InstanceCheck.hs
| Module : Kitten . Description : Checking types against signatures Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : GHC Module : Kitten.InstanceCheck Description : Checking types against signatures Copyright : (c) Jon Purdy, 2016 License : MIT Maintainer : Stability : experimental Portability : GHC -} {-# LANGUAGE OverloadedStrings #-} module Kitten.InstanceCheck ( instanceCheck ) where import Control.Monad (forM_, unless) import Data.List (find) import Data.Set (Set) import Kitten.Informer (Informer(..)) import Kitten.Monad (K, attempt) import Kitten.Origin (Origin) import Kitten.Type (Constructor(..), Type(..), TypeId, Var(..)) import Kitten.TypeEnv (TypeEnv, freshTypeId) import qualified Data.Map as Map import qualified Data.Set as Set import qualified Kitten.Free as Free import qualified Kitten.Instantiate as Instantiate import qualified Kitten.Report as Report import qualified Kitten.Substitute as Substitute import qualified Kitten.Type as Type import qualified Kitten.TypeEnv as TypeEnv import qualified Kitten.Unify as Unify import qualified Kitten.Zonk as Zonk import qualified Text.PrettyPrint as Pretty | Checks whether one type is a generic instance of another , used for checking -- type signatures. Remember, when using this function, which way the subtyping relation goes : @∀α . α → α@ is a generic instance of @int → int@ , not the -- other way around! instanceCheck :: Pretty.Doc -> Type -> Pretty.Doc -> Type -> K () instanceCheck aSort aScheme bSort bScheme = do let tenv0 = TypeEnv.empty let aType = aScheme (ids, bType) <- skolemize tenv0 bScheme let envTypes = Map.elems (TypeEnv.tvs tenv0) success <- attempt $ subsumptionCheck tenv0 aType bType unless success failure let escaped = Set.unions $ map (Free.tvs tenv0) (aScheme : bScheme : envTypes) -- Free.tvs tenv0 aScheme `Set.union` Free.tvs tenv0 bScheme let bad = Set.filter (`Set.member` escaped) ids unless (Set.null bad) failure return () where failure = report $ Report.FailedInstanceCheck aScheme bScheme -- | Skolemization replaces each quantified type variable with a type constant -- that unifies only with itself. skolemize :: TypeEnv -> Type -> K (Set TypeId, Type) skolemize tenv0 t = case t of Forall origin (Var name x k) t' -> do c <- freshTypeId tenv0 substituted <- Substitute.type_ tenv0 x (TypeConstant origin $ Var name c k) t' (c', t'') <- skolemize tenv0 substituted return (Set.insert c c', t'') -- TForall _ t' -> skolemize tenv0 t' TypeConstructor origin "Fun" :@ a :@ b :@ e -> do (ids, b') <- skolemize tenv0 b return (ids, Type.fun origin a b' e) _ -> return (Set.empty, t) -- | Subsumption checking is largely the same as unification, accounting for function type variance : if @(a - > b ) < : ( c - > d)@ then @b < : ( covariant ) -- but @c <: a@ (contravariant). subsumptionCheck :: TypeEnv -> Type -> Type -> K TypeEnv subsumptionCheck tenv0 (Forall origin (Var name x k) t) t2 = do (t1, _, tenv1) <- Instantiate.type_ tenv0 origin name x k t subsumptionCheck tenv1 t1 t2 subsumptionCheck tenv0 t1 (TypeConstructor _ "Fun" :@ a' :@ b' :@ e') = do (a, b, e, tenv1) <- Unify.function tenv0 t1 subsumptionCheckFun tenv1 a b e a' b' e' subsumptionCheck tenv0 (TypeConstructor _ "Fun" :@ a :@ b :@ e) t2 = do (a', b', e', tenv1) <- Unify.function tenv0 t2 subsumptionCheckFun tenv1 a b e a' b' e' subsumptionCheck tenv0 t1 t2 = Unify.type_ tenv0 t1 t2 subsumptionCheckFun :: TypeEnv -> Type -> Type -> Type -> Type -> Type -> Type -> K TypeEnv subsumptionCheckFun tenv0 a b e a' b' e' = do tenv1 <- subsumptionCheck tenv0 a' a tenv2 <- subsumptionCheck tenv1 b b' let labels = permissionList $ Zonk.type_ tenv2 e labels' = permissionList $ Zonk.type_ tenv2 e' forM_ labels $ \ (origin, label) -> case find ((label ==) . snd) labels' of Just{} -> return () Nothing -> report $ Report.MissingPermissionLabel e e' origin label return tenv2 where permissionList :: Type -> [(Origin, Constructor)] permissionList (TypeConstructor _ "Join" :@ TypeConstructor origin label :@ es) = (origin, label) : permissionList es permissionList _ = []
null
https://raw.githubusercontent.com/evincarofautumn/kitten/a5301fe24dbb9ea91974abee73ad544156ee4722/lib/Kitten/InstanceCheck.hs
haskell
# LANGUAGE OverloadedStrings # type signatures. Remember, when using this function, which way the subtyping other way around! Free.tvs tenv0 aScheme `Set.union` Free.tvs tenv0 bScheme | Skolemization replaces each quantified type variable with a type constant that unifies only with itself. TForall _ t' -> skolemize tenv0 t' | Subsumption checking is largely the same as unification, accounting for but @c <: a@ (contravariant).
| Module : Kitten . Description : Checking types against signatures Copyright : ( c ) , 2016 License : MIT Maintainer : Stability : experimental Portability : GHC Module : Kitten.InstanceCheck Description : Checking types against signatures Copyright : (c) Jon Purdy, 2016 License : MIT Maintainer : Stability : experimental Portability : GHC -} module Kitten.InstanceCheck ( instanceCheck ) where import Control.Monad (forM_, unless) import Data.List (find) import Data.Set (Set) import Kitten.Informer (Informer(..)) import Kitten.Monad (K, attempt) import Kitten.Origin (Origin) import Kitten.Type (Constructor(..), Type(..), TypeId, Var(..)) import Kitten.TypeEnv (TypeEnv, freshTypeId) import qualified Data.Map as Map import qualified Data.Set as Set import qualified Kitten.Free as Free import qualified Kitten.Instantiate as Instantiate import qualified Kitten.Report as Report import qualified Kitten.Substitute as Substitute import qualified Kitten.Type as Type import qualified Kitten.TypeEnv as TypeEnv import qualified Kitten.Unify as Unify import qualified Kitten.Zonk as Zonk import qualified Text.PrettyPrint as Pretty | Checks whether one type is a generic instance of another , used for checking relation goes : @∀α . α → α@ is a generic instance of @int → int@ , not the instanceCheck :: Pretty.Doc -> Type -> Pretty.Doc -> Type -> K () instanceCheck aSort aScheme bSort bScheme = do let tenv0 = TypeEnv.empty let aType = aScheme (ids, bType) <- skolemize tenv0 bScheme let envTypes = Map.elems (TypeEnv.tvs tenv0) success <- attempt $ subsumptionCheck tenv0 aType bType unless success failure let escaped = Set.unions $ map (Free.tvs tenv0) (aScheme : bScheme : envTypes) let bad = Set.filter (`Set.member` escaped) ids unless (Set.null bad) failure return () where failure = report $ Report.FailedInstanceCheck aScheme bScheme skolemize :: TypeEnv -> Type -> K (Set TypeId, Type) skolemize tenv0 t = case t of Forall origin (Var name x k) t' -> do c <- freshTypeId tenv0 substituted <- Substitute.type_ tenv0 x (TypeConstant origin $ Var name c k) t' (c', t'') <- skolemize tenv0 substituted return (Set.insert c c', t'') TypeConstructor origin "Fun" :@ a :@ b :@ e -> do (ids, b') <- skolemize tenv0 b return (ids, Type.fun origin a b' e) _ -> return (Set.empty, t) function type variance : if @(a - > b ) < : ( c - > d)@ then @b < : ( covariant ) subsumptionCheck :: TypeEnv -> Type -> Type -> K TypeEnv subsumptionCheck tenv0 (Forall origin (Var name x k) t) t2 = do (t1, _, tenv1) <- Instantiate.type_ tenv0 origin name x k t subsumptionCheck tenv1 t1 t2 subsumptionCheck tenv0 t1 (TypeConstructor _ "Fun" :@ a' :@ b' :@ e') = do (a, b, e, tenv1) <- Unify.function tenv0 t1 subsumptionCheckFun tenv1 a b e a' b' e' subsumptionCheck tenv0 (TypeConstructor _ "Fun" :@ a :@ b :@ e) t2 = do (a', b', e', tenv1) <- Unify.function tenv0 t2 subsumptionCheckFun tenv1 a b e a' b' e' subsumptionCheck tenv0 t1 t2 = Unify.type_ tenv0 t1 t2 subsumptionCheckFun :: TypeEnv -> Type -> Type -> Type -> Type -> Type -> Type -> K TypeEnv subsumptionCheckFun tenv0 a b e a' b' e' = do tenv1 <- subsumptionCheck tenv0 a' a tenv2 <- subsumptionCheck tenv1 b b' let labels = permissionList $ Zonk.type_ tenv2 e labels' = permissionList $ Zonk.type_ tenv2 e' forM_ labels $ \ (origin, label) -> case find ((label ==) . snd) labels' of Just{} -> return () Nothing -> report $ Report.MissingPermissionLabel e e' origin label return tenv2 where permissionList :: Type -> [(Origin, Constructor)] permissionList (TypeConstructor _ "Join" :@ TypeConstructor origin label :@ es) = (origin, label) : permissionList es permissionList _ = []
bf7d0916c0065a80e495dbef1f6c6f27271579deb66d3f1c436c93b620416b8b
ldgrp/uptop
HelpView.hs
{-# LANGUAGE OverloadedStrings #-} module UI.HelpView where import Brick.Types import Brick.Widgets.Border import Brick.Widgets.Center import Brick.Widgets.Core import Lens.Micro import Types drawHelp :: State -> [Widget Name] drawHelp st = [ center $ padLeftRight 2 $ hLimit 50 $ vBox [ str $ "uptop " <> st ^. version . versionNumber <> " - (C) 2020 Leo Orpilla III", vLimit 1 $ fill ' ', drawControls, vLimit 1 $ fill ' ', drawVimControls, vLimit 1 $ fill ' ', str "Press any key to return." ] ] drawControls :: Widget Name drawControls = vBox [ hBorderWithLabel (str "Controls"), vLimit 1 $ fill ' ', vLimit 1 $ str "← ↑ ↓ →" <+> fill ' ' <+> str "Left/Up/Down/Right", vLimit 1 $ str "PageUp PageDown" <+> fill ' ' <+> str "Page Up/Page Down", vLimit 1 $ str "Home End" <+> fill ' ' <+> str "Go to first/Go to last", vLimit 1 $ str "C-w ↑" <+> fill ' ' <+> str "Viewport Up", vLimit 1 $ str "C-w ↓" <+> fill ' ' <+> str "Viewport Down", vLimit 1 $ str "Esc" <+> fill ' ' <+> str "Exit" ] drawVimControls :: Widget Name drawVimControls = vBox [ hBorderWithLabel (str "Vim-style"), vLimit 1 $ fill ' ', vLimit 1 $ str "h j k l" <+> fill ' ' <+> str "Left/Up/Down/Right", vLimit 1 $ str "C-b C-f" <+> fill ' ' <+> str "Page Up/Page Down", vLimit 1 $ str "g G" <+> fill ' ' <+> str "Go to first/Go to last", vLimit 1 $ str "C-w k" <+> fill ' ' <+> str "Viewport Up", vLimit 1 $ str "C-w j" <+> fill ' ' <+> str "Viewport Down", vLimit 1 $ str "q" <+> fill ' ' <+> str "Exit" ]
null
https://raw.githubusercontent.com/ldgrp/uptop/53001b39793df4be48c9c3aed9454be0fc178434/up-top/src/UI/HelpView.hs
haskell
# LANGUAGE OverloadedStrings #
module UI.HelpView where import Brick.Types import Brick.Widgets.Border import Brick.Widgets.Center import Brick.Widgets.Core import Lens.Micro import Types drawHelp :: State -> [Widget Name] drawHelp st = [ center $ padLeftRight 2 $ hLimit 50 $ vBox [ str $ "uptop " <> st ^. version . versionNumber <> " - (C) 2020 Leo Orpilla III", vLimit 1 $ fill ' ', drawControls, vLimit 1 $ fill ' ', drawVimControls, vLimit 1 $ fill ' ', str "Press any key to return." ] ] drawControls :: Widget Name drawControls = vBox [ hBorderWithLabel (str "Controls"), vLimit 1 $ fill ' ', vLimit 1 $ str "← ↑ ↓ →" <+> fill ' ' <+> str "Left/Up/Down/Right", vLimit 1 $ str "PageUp PageDown" <+> fill ' ' <+> str "Page Up/Page Down", vLimit 1 $ str "Home End" <+> fill ' ' <+> str "Go to first/Go to last", vLimit 1 $ str "C-w ↑" <+> fill ' ' <+> str "Viewport Up", vLimit 1 $ str "C-w ↓" <+> fill ' ' <+> str "Viewport Down", vLimit 1 $ str "Esc" <+> fill ' ' <+> str "Exit" ] drawVimControls :: Widget Name drawVimControls = vBox [ hBorderWithLabel (str "Vim-style"), vLimit 1 $ fill ' ', vLimit 1 $ str "h j k l" <+> fill ' ' <+> str "Left/Up/Down/Right", vLimit 1 $ str "C-b C-f" <+> fill ' ' <+> str "Page Up/Page Down", vLimit 1 $ str "g G" <+> fill ' ' <+> str "Go to first/Go to last", vLimit 1 $ str "C-w k" <+> fill ' ' <+> str "Viewport Up", vLimit 1 $ str "C-w j" <+> fill ' ' <+> str "Viewport Down", vLimit 1 $ str "q" <+> fill ' ' <+> str "Exit" ]
ad018e60267f1b09dd0e29d1c39d559299b419ff5ed88dba6857c690b256d72d
shriram/mystery-languages
semantics.rkt
#lang racket (require mystery-languages/make-semantics) (provide (rename-out [mod-begin #%module-begin] [ti #%top-interaction])) (define-values (namespaces lang-print-names) (make-namespaces-and-lang-print-names (list 'mystery-languages/fun-calls/L1/semantics 'mystery-languages/fun-calls/L2/semantics 'mystery-languages/fun-calls/L3/semantics))) (define-syntax (multi-runner stx) (syntax-case stx (TEST) [(_ (TEST e r ...)) #`(test-output 'e (list 'r ...) namespaces)] [(_ e) #`(show-output 'e namespaces lang-print-names)])) (define-syntax mod-begin (λ (stx) (syntax-case stx () [(_ b ...) #'(#%printing-module-begin (multi-runner b) ...)]))) (define-syntax ti (λ (stx) (syntax-case stx () ([_ . e] #'(#%top-interaction . (multi-runner e))))))
null
https://raw.githubusercontent.com/shriram/mystery-languages/4683a9d0e86bbf86c44bdd84f41d9ed202c65edf/fun-calls/semantics.rkt
racket
#lang racket (require mystery-languages/make-semantics) (provide (rename-out [mod-begin #%module-begin] [ti #%top-interaction])) (define-values (namespaces lang-print-names) (make-namespaces-and-lang-print-names (list 'mystery-languages/fun-calls/L1/semantics 'mystery-languages/fun-calls/L2/semantics 'mystery-languages/fun-calls/L3/semantics))) (define-syntax (multi-runner stx) (syntax-case stx (TEST) [(_ (TEST e r ...)) #`(test-output 'e (list 'r ...) namespaces)] [(_ e) #`(show-output 'e namespaces lang-print-names)])) (define-syntax mod-begin (λ (stx) (syntax-case stx () [(_ b ...) #'(#%printing-module-begin (multi-runner b) ...)]))) (define-syntax ti (λ (stx) (syntax-case stx () ([_ . e] #'(#%top-interaction . (multi-runner e))))))
9dfcd590f1a35c5b7cb17e09e0c20d0c0d71590988b7e1c790b93e83c9ef8fa3
chiroptical/optics-by-example
Main.hs
module Main where import Lib main :: IO () main = putStrLn "Optics and Monads"
null
https://raw.githubusercontent.com/chiroptical/optics-by-example/3ee33546ee18c3a6f5510eec17a69d34e750198e/chapter13/app/Main.hs
haskell
module Main where import Lib main :: IO () main = putStrLn "Optics and Monads"
34ed38c3af7420a51761ef505639ad5f135561b0086552153df02376e4c8b6a8
rd--/hsc3
bufSampleRate.help.hs
bufSampleRate ; requires = buf ; frequency as fraction of buffer sample - rate ( ie . 48000 / 100 = = 480 ) let b = control kr "buf" 0 f = mce [bufSampleRate kr b * 0.01, 440] in sinOsc ar f 0 * 0.1 ---- ; buffer setup withSc3 (async (b_allocRead 0 (sfResolve "pf-c5.aif") 0 0))
null
https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Ugen/bufSampleRate.help.hs
haskell
-- ; buffer setup
bufSampleRate ; requires = buf ; frequency as fraction of buffer sample - rate ( ie . 48000 / 100 = = 480 ) let b = control kr "buf" 0 f = mce [bufSampleRate kr b * 0.01, 440] in sinOsc ar f 0 * 0.1 withSc3 (async (b_allocRead 0 (sfResolve "pf-c5.aif") 0 0))
6eb3a011bb052960e23701f45d29cd3b53c0ca77715afe63cfdeed4f19daefb8
tonyg/kali-scheme
expand.scm
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1998 by NEC Research Institute , Inc. See file COPYING . Expanding using the Scheme 48 expander . (define (scan-packages packages) (let ((definitions (fold (lambda (package definitions) (let ((cenv (package->environment package))) (fold (lambda (form definitions) (let ((node (expand-form form cenv))) (cond ((define-node? node) (cons (eval-define (expand node cenv) cenv) definitions)) (else (eval-node (expand node cenv) global-ref global-set! eval-primitive) definitions)))) (call-with-values (lambda () (package-source package)) (lambda (files.forms usual-transforms primitives?) (scan-forms (apply append (map cdr files.forms)) cenv))) definitions))) packages '()))) (reverse (map (lambda (var) (let ((value (variable-flag var))) (set-variable-flag! var #f) (cons var value))) definitions)))) (define package->environment (structure-ref packages package->environment)) (define define-node? (node-predicate 'define)) (define (eval-define node cenv) (let* ((form (node-form node)) (value (eval-node (caddr form) global-ref global-set! eval-primitive)) (lhs (cadr form))) (global-set! lhs value) (name->variable-or-value lhs))) (define (global-ref name) (let ((thing (name->variable-or-value name))) (if (variable? thing) (variable-flag thing) thing))) (define (global-set! name value) (let ((thing (name->variable-or-value name))) (if (primitive? thing) (bug "trying to set the value of primitive ~S" thing) (set-variable-flag! thing value)))) (define (name->variable-or-value name) (let ((binding (node-ref name 'binding))) (if (binding? binding) (let ((value (binding-place binding)) (static (binding-static binding))) (cond ((primitive? static) static) ((variable? value) value) ((and (location? value) (constant? (contents value))) (contents value)) (else (bug "global binding is not a variable, primitive or constant ~S" name)))) (user-error "unbound variable ~S" (node-form name)))))
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/ps-compiler/prescheme/expand.scm
scheme
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1998 by NEC Research Institute , Inc. See file COPYING . Expanding using the Scheme 48 expander . (define (scan-packages packages) (let ((definitions (fold (lambda (package definitions) (let ((cenv (package->environment package))) (fold (lambda (form definitions) (let ((node (expand-form form cenv))) (cond ((define-node? node) (cons (eval-define (expand node cenv) cenv) definitions)) (else (eval-node (expand node cenv) global-ref global-set! eval-primitive) definitions)))) (call-with-values (lambda () (package-source package)) (lambda (files.forms usual-transforms primitives?) (scan-forms (apply append (map cdr files.forms)) cenv))) definitions))) packages '()))) (reverse (map (lambda (var) (let ((value (variable-flag var))) (set-variable-flag! var #f) (cons var value))) definitions)))) (define package->environment (structure-ref packages package->environment)) (define define-node? (node-predicate 'define)) (define (eval-define node cenv) (let* ((form (node-form node)) (value (eval-node (caddr form) global-ref global-set! eval-primitive)) (lhs (cadr form))) (global-set! lhs value) (name->variable-or-value lhs))) (define (global-ref name) (let ((thing (name->variable-or-value name))) (if (variable? thing) (variable-flag thing) thing))) (define (global-set! name value) (let ((thing (name->variable-or-value name))) (if (primitive? thing) (bug "trying to set the value of primitive ~S" thing) (set-variable-flag! thing value)))) (define (name->variable-or-value name) (let ((binding (node-ref name 'binding))) (if (binding? binding) (let ((value (binding-place binding)) (static (binding-static binding))) (cond ((primitive? static) static) ((variable? value) value) ((and (location? value) (constant? (contents value))) (contents value)) (else (bug "global binding is not a variable, primitive or constant ~S" name)))) (user-error "unbound variable ~S" (node-form name)))))
7a274ae47297c8eb0d0e6df2fe7494fa573448f000ba1f080c7437906563b3ca
vmchale/kempe
Size.hs
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveFunctor #-} # LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} -- | Frontend AST -- | This module is split out so that the bakend/IR need not depend on -- everything in 'AST'. module Kempe.AST.Size ( KempeTy (..) , StackType (..) , MonoStackType , BuiltinTy (..) , ABI (..) , prettyMonoStackType -- * Sizing bits , SizeEnv , Size , size , size' , sizeStack ) where import Control.DeepSeq (NFData) import Data.Int (Int64) import qualified Data.IntMap as IM import Data.Monoid (Sum (..)) import GHC.Generics (Generic) import Kempe.Name import Kempe.Unique import Prettyprinter (Doc, Pretty (pretty), parens, sep, (<+>)) data KempeTy a = TyBuiltin a BuiltinTy | TyNamed a (TyName a) | TyVar a (Name a) | TyApp a (KempeTy a) (KempeTy a) -- type applied to another, e.g. Just Int deriving (Generic, NFData, Functor, Eq, Ord) -- questionable eq instance but eh data StackType b = StackType { inTypes :: [KempeTy b] , outTypes :: [KempeTy b] } deriving (Generic, NFData, Eq, Ord) type MonoStackType = ([KempeTy ()], [KempeTy ()]) prettyMonoStackType :: ([KempeTy a], [KempeTy a]) -> Doc ann prettyMonoStackType (is, os) = sep (fmap pretty is) <+> "--" <+> sep (fmap pretty os) data BuiltinTy = TyInt | TyBool | TyInt8 | TyWord deriving (Generic, NFData, Eq, Ord) instance Pretty BuiltinTy where pretty TyInt = "Int" pretty TyBool = "Bool" pretty TyInt8 = "Int8" pretty TyWord = "Word" instance Pretty (KempeTy a) where pretty (TyBuiltin _ b) = pretty b pretty (TyNamed _ tn) = pretty tn pretty (TyVar _ n) = pretty n pretty (TyApp _ ty ty') = parens (pretty ty <+> pretty ty') instance Pretty (StackType a) where pretty (StackType ins outs) = sep (fmap pretty ins) <+> "--" <+> sep (fmap pretty outs) data ABI = Cabi | Kabi | Hooked | ArmAbi deriving (Eq, Ord, Generic, NFData) instance Pretty ABI where pretty Cabi = "cabi" pretty Kabi = "kabi" pretty Hooked = "hooked" pretty ArmAbi = "armabi" -- machinery for assigning a constructor to a function of its concrete types -- (and then curry forward...) type Size = [Int64] -> Int64 type SizeEnv = IM.IntMap Size -- the kempe sizing system is kind of fucked (it works tho) -- | Don't call this on ill-kinded types; it won't throw any error. size :: SizeEnv -> KempeTy a -> Size size _ (TyBuiltin _ TyInt) = const 8 size _ (TyBuiltin _ TyBool) = const 1 size _ (TyBuiltin _ TyInt8) = const 1 size _ (TyBuiltin _ TyWord) = const 8 size _ TyVar{} = error "Internal error: type variables should not be present at this stage." size env (TyNamed _ (Name _ (Unique k) _)) = IM.findWithDefault (error "Size not in map!") k env size env (TyApp _ ty ty') = \tys -> size env ty (size env ty' [] : tys) size' :: SizeEnv -> KempeTy a -> Int64 size' env = ($ []) . size env sizeStack :: SizeEnv -> [KempeTy a] -> Int64 sizeStack env = getSum . foldMap (Sum . size' env)
null
https://raw.githubusercontent.com/vmchale/kempe/23d59cb9343902aae33140e2b68ac0e4ab0a60a0/src/Kempe/AST/Size.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE DeriveFunctor # # LANGUAGE OverloadedStrings # | Frontend AST | This module is split out so that the bakend/IR need not depend on everything in 'AST'. * Sizing bits type applied to another, e.g. Just Int questionable eq instance but eh machinery for assigning a constructor to a function of its concrete types (and then curry forward...) the kempe sizing system is kind of fucked (it works tho) | Don't call this on ill-kinded types; it won't throw any error.
# LANGUAGE DeriveGeneric # module Kempe.AST.Size ( KempeTy (..) , StackType (..) , MonoStackType , BuiltinTy (..) , ABI (..) , prettyMonoStackType , SizeEnv , Size , size , size' , sizeStack ) where import Control.DeepSeq (NFData) import Data.Int (Int64) import qualified Data.IntMap as IM import Data.Monoid (Sum (..)) import GHC.Generics (Generic) import Kempe.Name import Kempe.Unique import Prettyprinter (Doc, Pretty (pretty), parens, sep, (<+>)) data KempeTy a = TyBuiltin a BuiltinTy | TyNamed a (TyName a) | TyVar a (Name a) data StackType b = StackType { inTypes :: [KempeTy b] , outTypes :: [KempeTy b] } deriving (Generic, NFData, Eq, Ord) type MonoStackType = ([KempeTy ()], [KempeTy ()]) prettyMonoStackType :: ([KempeTy a], [KempeTy a]) -> Doc ann prettyMonoStackType (is, os) = sep (fmap pretty is) <+> "--" <+> sep (fmap pretty os) data BuiltinTy = TyInt | TyBool | TyInt8 | TyWord deriving (Generic, NFData, Eq, Ord) instance Pretty BuiltinTy where pretty TyInt = "Int" pretty TyBool = "Bool" pretty TyInt8 = "Int8" pretty TyWord = "Word" instance Pretty (KempeTy a) where pretty (TyBuiltin _ b) = pretty b pretty (TyNamed _ tn) = pretty tn pretty (TyVar _ n) = pretty n pretty (TyApp _ ty ty') = parens (pretty ty <+> pretty ty') instance Pretty (StackType a) where pretty (StackType ins outs) = sep (fmap pretty ins) <+> "--" <+> sep (fmap pretty outs) data ABI = Cabi | Kabi | Hooked | ArmAbi deriving (Eq, Ord, Generic, NFData) instance Pretty ABI where pretty Cabi = "cabi" pretty Kabi = "kabi" pretty Hooked = "hooked" pretty ArmAbi = "armabi" type Size = [Int64] -> Int64 type SizeEnv = IM.IntMap Size size :: SizeEnv -> KempeTy a -> Size size _ (TyBuiltin _ TyInt) = const 8 size _ (TyBuiltin _ TyBool) = const 1 size _ (TyBuiltin _ TyInt8) = const 1 size _ (TyBuiltin _ TyWord) = const 8 size _ TyVar{} = error "Internal error: type variables should not be present at this stage." size env (TyNamed _ (Name _ (Unique k) _)) = IM.findWithDefault (error "Size not in map!") k env size env (TyApp _ ty ty') = \tys -> size env ty (size env ty' [] : tys) size' :: SizeEnv -> KempeTy a -> Int64 size' env = ($ []) . size env sizeStack :: SizeEnv -> [KempeTy a] -> Int64 sizeStack env = getSum . foldMap (Sum . size' env)
9c9a8bd70d8fb82ad9d385ddf73e3b9c3964fcd1a94ef2a69f5ffec010168fac
clash-lang/clash-compiler
SimIO.hs
| Copyright : ( C ) 2019 , Google Inc. , 2022 , QBayLogic B.V. License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > I\/O actions that are translatable to HDL Copyright : (C) 2019, Google Inc., 2022, QBayLogic B.V. License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> I\/O actions that are translatable to HDL -} # LANGUAGE CPP # # LANGUAGE BangPatterns , MagicHash , TypeOperators , ScopedTypeVariables , FlexibleContexts # # LANGUAGE DataKinds , GADTs , TypeApplications # module Clash.Explicit.SimIO ( -- * I\/O environment for simulation mealyIO , SimIO -- * Display on stdout , display -- * End of simulation , finish -- * Mutable values , Reg , reg , readReg , writeReg -- * File I\/O , File , openFile , closeFile -- ** Reading and writing characters , getChar , putChar -- ** Reading strings , getLine -- ** Detecting the end of input , isEOF -- ** Buffering operations , flush -- ** Repositioning handles , seek , rewind , tell ) where import Control.Monad (when) #if __GLASGOW_HASKELL__ < 900 import Data.Coerce #endif import Data.IORef import GHC.TypeLits import Prelude hiding (getChar, putChar, getLine) import qualified System.IO as IO import System.IO.Unsafe import Clash.Annotations.Primitive (hasBlackBox) import Clash.Promoted.Nat import Clash.Signal.Internal import Clash.Sized.Unsigned import Clash.Sized.Vector (Vec (..)) import Clash.XException (seqX) | Simulation - level I\/O environment ; synthesizable to HDL I\/O , which in -- itself is unlikely to be synthesisable to a digital circuit. -- -- See 'mealyIO' as to its use. #if __GLASGOW_HASKELL__ >= 900 data SimIO a = SimIO {unSimIO :: !(IO a)} #else newtype SimIO a = SimIO {unSimIO :: IO a} #endif # ANN unSimIO hasBlackBox # instance Functor SimIO where fmap = fmapSimIO# fmapSimIO# :: (a -> b) -> SimIO a -> SimIO b fmapSimIO# f (SimIO m) = SimIO (fmap f m) # NOINLINE fmapSimIO # # {-# ANN fmapSimIO# hasBlackBox #-} instance Applicative SimIO where pure = pureSimIO# (<*>) = apSimIO# pureSimIO# :: a -> SimIO a pureSimIO# a = SimIO (pure a) # NOINLINE pureSimIO # # # ANN pureSimIO # hasBlackBox # apSimIO# :: SimIO (a -> b) -> SimIO a -> SimIO b apSimIO# (SimIO f) (SimIO m) = SimIO (f <*> m) # NOINLINE apSimIO # # # ANN apSimIO # hasBlackBox # instance Monad SimIO where #if !MIN_VERSION_base(4,16,0) return = pureSimIO# #endif (>>=) = bindSimIO# bindSimIO# :: SimIO a -> (a -> SimIO b) -> SimIO b #if __GLASGOW_HASKELL__ >= 900 bindSimIO# (SimIO m) k = SimIO (m >>= (\x -> x `seqX` unSimIO (k x))) #else bindSimIO# (SimIO m) k = SimIO (m >>= (\x -> x `seqX` coerce k x)) #endif # NOINLINE bindSimIO # # # ANN bindSimIO # hasBlackBox # -- | Display a string on /stdout/ display :: String -- ^ String you want to display -> SimIO () display s = SimIO (putStrLn s) # NOINLINE display # # ANN display hasBlackBox # -- | Finish the simulation with an exit code finish :: Integer -- ^ The exit code you want to return at the end of the simulation -> SimIO a finish i = return (error (show i)) # NOINLINE finish # # ANN finish hasBlackBox # -- | Mutable reference #if __GLASGOW_HASKELL__ >= 900 data Reg a = Reg !(IORef a) #else newtype Reg a = Reg (IORef a) #endif -- | Create a new mutable reference with the given starting value reg :: a -- ^ The starting value -> SimIO (Reg a) reg a = SimIO (Reg <$> newIORef a) # NOINLINE reg # {-# ANN reg hasBlackBox #-} -- | Read value from a mutable reference readReg :: Reg a -> SimIO a readReg (Reg a) = SimIO (readIORef a) # NOINLINE readReg # # ANN readReg hasBlackBox # -- | Write new value to the mutable reference writeReg :: Reg a -- ^ The mutable reference -> a -- ^ The new value -> SimIO () writeReg (Reg r) a = SimIO (writeIORef r a) # NOINLINE writeReg # # ANN writeReg hasBlackBox # -- | File handle #if __GLASGOW_HASKELL__ >= 900 data File = File !IO.Handle #else newtype File = File IO.Handle #endif -- | Open a file openFile :: FilePath -- ^ File to open -> String -- ^ File mode: -- -- * "r": Open for reading -- * "w": Create for writing -- * "a": Append -- * "r+": Open for update (reading and writing) -- * "w+": Create for update -- * "a+": Append, open or create for update at end-of-file -> SimIO File #if __GLASGOW_HASKELL__ >= 900 openFile fp "r" = SimIO $ fmap File (IO.openFile fp IO.ReadMode) openFile fp "w" = SimIO $ fmap File (IO.openFile fp IO.WriteMode) openFile fp "a" = SimIO $ fmap File (IO.openFile fp IO.AppendMode) openFile fp "rb" = SimIO $ fmap File (IO.openBinaryFile fp IO.ReadMode) openFile fp "wb" = SimIO $ fmap File (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab" = SimIO $ fmap File (IO.openBinaryFile fp IO.AppendMode) openFile fp "r+" = SimIO $ fmap File (IO.openFile fp IO.ReadWriteMode) openFile fp "w+" = SimIO $ fmap File (IO.openFile fp IO.WriteMode) openFile fp "a+" = SimIO $ fmap File (IO.openFile fp IO.AppendMode) openFile fp "r+b" = SimIO $ fmap File (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "w+b" = SimIO $ fmap File (IO.openBinaryFile fp IO.WriteMode) openFile fp "a+b" = SimIO $ fmap File (IO.openBinaryFile fp IO.AppendMode) openFile fp "rb+" = SimIO $ fmap File (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "wb+" = SimIO $ fmap File (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab+" = SimIO $ fmap File (IO.openBinaryFile fp IO.AppendMode) #else openFile fp "r" = coerce (IO.openFile fp IO.ReadMode) openFile fp "w" = coerce (IO.openFile fp IO.WriteMode) openFile fp "a" = coerce (IO.openFile fp IO.AppendMode) openFile fp "rb" = coerce (IO.openBinaryFile fp IO.ReadMode) openFile fp "wb" = coerce (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab" = coerce (IO.openBinaryFile fp IO.AppendMode) openFile fp "r+" = coerce (IO.openFile fp IO.ReadWriteMode) openFile fp "w+" = coerce (IO.openFile fp IO.WriteMode) openFile fp "a+" = coerce (IO.openFile fp IO.AppendMode) openFile fp "r+b" = coerce (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "w+b" = coerce (IO.openBinaryFile fp IO.WriteMode) openFile fp "a+b" = coerce (IO.openBinaryFile fp IO.AppendMode) openFile fp "rb+" = coerce (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "wb+" = coerce (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab+" = coerce (IO.openBinaryFile fp IO.AppendMode) #endif openFile _ m = error ("openFile unknown mode: " ++ show m) # NOINLINE openFile # # ANN openFile hasBlackBox # -- | Close a file closeFile :: File -> SimIO () closeFile (File fp) = SimIO (IO.hClose fp) # NOINLINE closeFile # # ANN closeFile hasBlackBox # | Read one character from a file getChar :: File -- ^ File to read from -> SimIO Char getChar (File fp) = SimIO (IO.hGetChar fp) {-# NOINLINE getChar #-} # # -- | Insert a character into a buffer specified by the file putChar :: Char -- ^ Character to insert -> File -- ^ Buffer to insert to -> SimIO () putChar c (File fp) = SimIO (IO.hPutChar fp c) {-# NOINLINE putChar #-} # ANN putChar hasBlackBox # | Read one line from a file getLine :: forall n . KnownNat n => File -- ^ File to read from -> Reg (Vec n (Unsigned 8)) -- ^ Vector to store the content -> SimIO Int getLine (File fp) (Reg r) = SimIO $ do s <- IO.hGetLine fp let d = snatToNum (SNat @n) - length s when (d < 0) (IO.hSeek fp IO.RelativeSeek (toInteger d)) modifyIORef r (rep s) return 0 where rep :: String -> Vec m (Unsigned 8) -> Vec m (Unsigned 8) rep [] vs = vs rep (x:xs) (Cons _ vs) = Cons (toEnum (fromEnum x)) (rep xs vs) rep _ Nil = Nil # NOINLINE getLine # # ANN getLine hasBlackBox # -- | Determine whether we've reached the end of the file isEOF :: File -- ^ File we want to inspect -> SimIO Bool isEOF (File fp) = SimIO (IO.hIsEOF fp) # NOINLINE isEOF # # ANN isEOF hasBlackBox # -- | Set the position of the next operation on the file seek :: File -- ^ File to set the position for -> Integer -- ^ Position -> Int -- ^ Mode: -- -- * 0: From the beginning of the file * 1 : From the current position * 2 : From the end of the file -> SimIO Int seek (File fp) pos mode = SimIO (IO.hSeek fp (toEnum mode) pos >> return 0) # NOINLINE seek # # ANN seek hasBlackBox # -- | Set the position of the next operation to the beginning of the file rewind :: File -> SimIO Int rewind (File fp) = SimIO (IO.hSeek fp IO.AbsoluteSeek 0 >> return 0) # NOINLINE rewind # # ANN rewind hasBlackBox # -- | Returns the offset from the beginning of the file (in bytes). tell :: File -- ^ File we want to inspect -> SimIO Integer tell (File fp) = SimIO (IO.hTell fp) # NOINLINE tell # # ANN tell hasBlackBox # -- | Write any buffered output to file flush :: File -> SimIO () flush (File fp) = SimIO (IO.hFlush fp) # NOINLINE flush # # ANN flush hasBlackBox # -- | Simulation-level I/O environment that can be synthesized to HDL-level I\/O. Note that it is unlikely that the HDL - level I\/O can subsequently be -- synthesized to a circuit. -- -- = Example -- -- @ -- tbMachine :: (File,File) -> Int -> SimIO Int -- tbMachine (fileIn,fileOut) regOut = do eofFileOut < - ' isEOF ' fileOut -- eofFileIn <- 'isEOF' fileIn -- when (eofFileIn || eofFileOut) $ do -- 'display' "success" -- 'finish' 0 -- -- goldenIn <- 'getChar' fileIn -- goldenOut <- 'getChar' fileOut -- res <- if regOut == fromEnum goldenOut then do -- return (fromEnum goldenIn) -- else do -- 'display' "Output doesn't match golden output" ' finish ' 1 -- display ("Output matches golden output") -- return res -- -- tbInit :: (File,File) -- tbInit = do -- fileIn <- 'openFile' "./goldenInput00.txt" "r" -- fileOut <- 'openFile' "./goldenOutput00.txt" "r" -- return (fileIn,fileOut) -- -- topEntity :: Signal System Int -- topEntity = regOut -- where -- clk = systemClockGen -- rst = resetGen -- ena = enableGen -- -- regOut = register clk rst ena (fromEnum \'a\') regIn regIn = ' mealyIO ' clk tbMachine tbInit regOut -- @ mealyIO :: KnownDomain dom => Clock dom ^ Clock at which rate the I\/O environment progresses -> (s -> i -> SimIO o) ^ Transition function inside an I\/O environment -> SimIO s -- ^ I/O action to create the initial state -> Signal dom i -> Signal dom o mealyIO !_ f (SimIO i) inp = unsafePerformIO (i >>= go inp) where go q@(~(k :- ks)) s = (:-) <$> unSimIO (f s k) <*> unsafeInterleaveIO ((q `seq` go ks s)) # NOINLINE mealyIO #
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/ba4765139ea0728546bf934005d2d9b77e48d8c7/clash-prelude/src/Clash/Explicit/SimIO.hs
haskell
* I\/O environment for simulation * Display on stdout * End of simulation * Mutable values * File I\/O ** Reading and writing characters ** Reading strings ** Detecting the end of input ** Buffering operations ** Repositioning handles itself is unlikely to be synthesisable to a digital circuit. See 'mealyIO' as to its use. # ANN fmapSimIO# hasBlackBox # | Display a string on /stdout/ ^ String you want to display | Finish the simulation with an exit code ^ The exit code you want to return at the end of the simulation | Mutable reference | Create a new mutable reference with the given starting value ^ The starting value # ANN reg hasBlackBox # | Read value from a mutable reference | Write new value to the mutable reference ^ The mutable reference ^ The new value | File handle | Open a file ^ File to open ^ File mode: * "r": Open for reading * "w": Create for writing * "a": Append * "r+": Open for update (reading and writing) * "w+": Create for update * "a+": Append, open or create for update at end-of-file | Close a file ^ File to read from # NOINLINE getChar # | Insert a character into a buffer specified by the file ^ Character to insert ^ Buffer to insert to # NOINLINE putChar # ^ File to read from ^ Vector to store the content | Determine whether we've reached the end of the file ^ File we want to inspect | Set the position of the next operation on the file ^ File to set the position for ^ Position ^ Mode: * 0: From the beginning of the file | Set the position of the next operation to the beginning of the file | Returns the offset from the beginning of the file (in bytes). ^ File we want to inspect | Write any buffered output to file | Simulation-level I/O environment that can be synthesized to HDL-level I\/O. synthesized to a circuit. = Example @ tbMachine :: (File,File) -> Int -> SimIO Int tbMachine (fileIn,fileOut) regOut = do eofFileIn <- 'isEOF' fileIn when (eofFileIn || eofFileOut) $ do 'display' "success" 'finish' 0 goldenIn <- 'getChar' fileIn goldenOut <- 'getChar' fileOut res <- if regOut == fromEnum goldenOut then do return (fromEnum goldenIn) else do 'display' "Output doesn't match golden output" display ("Output matches golden output") return res tbInit :: (File,File) tbInit = do fileIn <- 'openFile' "./goldenInput00.txt" "r" fileOut <- 'openFile' "./goldenOutput00.txt" "r" return (fileIn,fileOut) topEntity :: Signal System Int topEntity = regOut where clk = systemClockGen rst = resetGen ena = enableGen regOut = register clk rst ena (fromEnum \'a\') regIn @ ^ I/O action to create the initial state
| Copyright : ( C ) 2019 , Google Inc. , 2022 , QBayLogic B.V. License : BSD2 ( see the file LICENSE ) Maintainer : QBayLogic B.V. < > I\/O actions that are translatable to HDL Copyright : (C) 2019, Google Inc., 2022, QBayLogic B.V. License : BSD2 (see the file LICENSE) Maintainer : QBayLogic B.V. <> I\/O actions that are translatable to HDL -} # LANGUAGE CPP # # LANGUAGE BangPatterns , MagicHash , TypeOperators , ScopedTypeVariables , FlexibleContexts # # LANGUAGE DataKinds , GADTs , TypeApplications # module Clash.Explicit.SimIO mealyIO , SimIO , display , finish , Reg , reg , readReg , writeReg , File , openFile , closeFile , getChar , putChar , getLine , isEOF , flush , seek , rewind , tell ) where import Control.Monad (when) #if __GLASGOW_HASKELL__ < 900 import Data.Coerce #endif import Data.IORef import GHC.TypeLits import Prelude hiding (getChar, putChar, getLine) import qualified System.IO as IO import System.IO.Unsafe import Clash.Annotations.Primitive (hasBlackBox) import Clash.Promoted.Nat import Clash.Signal.Internal import Clash.Sized.Unsigned import Clash.Sized.Vector (Vec (..)) import Clash.XException (seqX) | Simulation - level I\/O environment ; synthesizable to HDL I\/O , which in #if __GLASGOW_HASKELL__ >= 900 data SimIO a = SimIO {unSimIO :: !(IO a)} #else newtype SimIO a = SimIO {unSimIO :: IO a} #endif # ANN unSimIO hasBlackBox # instance Functor SimIO where fmap = fmapSimIO# fmapSimIO# :: (a -> b) -> SimIO a -> SimIO b fmapSimIO# f (SimIO m) = SimIO (fmap f m) # NOINLINE fmapSimIO # # instance Applicative SimIO where pure = pureSimIO# (<*>) = apSimIO# pureSimIO# :: a -> SimIO a pureSimIO# a = SimIO (pure a) # NOINLINE pureSimIO # # # ANN pureSimIO # hasBlackBox # apSimIO# :: SimIO (a -> b) -> SimIO a -> SimIO b apSimIO# (SimIO f) (SimIO m) = SimIO (f <*> m) # NOINLINE apSimIO # # # ANN apSimIO # hasBlackBox # instance Monad SimIO where #if !MIN_VERSION_base(4,16,0) return = pureSimIO# #endif (>>=) = bindSimIO# bindSimIO# :: SimIO a -> (a -> SimIO b) -> SimIO b #if __GLASGOW_HASKELL__ >= 900 bindSimIO# (SimIO m) k = SimIO (m >>= (\x -> x `seqX` unSimIO (k x))) #else bindSimIO# (SimIO m) k = SimIO (m >>= (\x -> x `seqX` coerce k x)) #endif # NOINLINE bindSimIO # # # ANN bindSimIO # hasBlackBox # display :: String -> SimIO () display s = SimIO (putStrLn s) # NOINLINE display # # ANN display hasBlackBox # finish :: Integer -> SimIO a finish i = return (error (show i)) # NOINLINE finish # # ANN finish hasBlackBox # #if __GLASGOW_HASKELL__ >= 900 data Reg a = Reg !(IORef a) #else newtype Reg a = Reg (IORef a) #endif reg :: a -> SimIO (Reg a) reg a = SimIO (Reg <$> newIORef a) # NOINLINE reg # readReg :: Reg a -> SimIO a readReg (Reg a) = SimIO (readIORef a) # NOINLINE readReg # # ANN readReg hasBlackBox # writeReg :: Reg a -> a -> SimIO () writeReg (Reg r) a = SimIO (writeIORef r a) # NOINLINE writeReg # # ANN writeReg hasBlackBox # #if __GLASGOW_HASKELL__ >= 900 data File = File !IO.Handle #else newtype File = File IO.Handle #endif openFile :: FilePath -> String -> SimIO File #if __GLASGOW_HASKELL__ >= 900 openFile fp "r" = SimIO $ fmap File (IO.openFile fp IO.ReadMode) openFile fp "w" = SimIO $ fmap File (IO.openFile fp IO.WriteMode) openFile fp "a" = SimIO $ fmap File (IO.openFile fp IO.AppendMode) openFile fp "rb" = SimIO $ fmap File (IO.openBinaryFile fp IO.ReadMode) openFile fp "wb" = SimIO $ fmap File (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab" = SimIO $ fmap File (IO.openBinaryFile fp IO.AppendMode) openFile fp "r+" = SimIO $ fmap File (IO.openFile fp IO.ReadWriteMode) openFile fp "w+" = SimIO $ fmap File (IO.openFile fp IO.WriteMode) openFile fp "a+" = SimIO $ fmap File (IO.openFile fp IO.AppendMode) openFile fp "r+b" = SimIO $ fmap File (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "w+b" = SimIO $ fmap File (IO.openBinaryFile fp IO.WriteMode) openFile fp "a+b" = SimIO $ fmap File (IO.openBinaryFile fp IO.AppendMode) openFile fp "rb+" = SimIO $ fmap File (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "wb+" = SimIO $ fmap File (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab+" = SimIO $ fmap File (IO.openBinaryFile fp IO.AppendMode) #else openFile fp "r" = coerce (IO.openFile fp IO.ReadMode) openFile fp "w" = coerce (IO.openFile fp IO.WriteMode) openFile fp "a" = coerce (IO.openFile fp IO.AppendMode) openFile fp "rb" = coerce (IO.openBinaryFile fp IO.ReadMode) openFile fp "wb" = coerce (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab" = coerce (IO.openBinaryFile fp IO.AppendMode) openFile fp "r+" = coerce (IO.openFile fp IO.ReadWriteMode) openFile fp "w+" = coerce (IO.openFile fp IO.WriteMode) openFile fp "a+" = coerce (IO.openFile fp IO.AppendMode) openFile fp "r+b" = coerce (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "w+b" = coerce (IO.openBinaryFile fp IO.WriteMode) openFile fp "a+b" = coerce (IO.openBinaryFile fp IO.AppendMode) openFile fp "rb+" = coerce (IO.openBinaryFile fp IO.ReadWriteMode) openFile fp "wb+" = coerce (IO.openBinaryFile fp IO.WriteMode) openFile fp "ab+" = coerce (IO.openBinaryFile fp IO.AppendMode) #endif openFile _ m = error ("openFile unknown mode: " ++ show m) # NOINLINE openFile # # ANN openFile hasBlackBox # closeFile :: File -> SimIO () closeFile (File fp) = SimIO (IO.hClose fp) # NOINLINE closeFile # # ANN closeFile hasBlackBox # | Read one character from a file getChar :: File -> SimIO Char getChar (File fp) = SimIO (IO.hGetChar fp) # # putChar :: Char -> File -> SimIO () putChar c (File fp) = SimIO (IO.hPutChar fp c) # ANN putChar hasBlackBox # | Read one line from a file getLine :: forall n . KnownNat n => File -> Reg (Vec n (Unsigned 8)) -> SimIO Int getLine (File fp) (Reg r) = SimIO $ do s <- IO.hGetLine fp let d = snatToNum (SNat @n) - length s when (d < 0) (IO.hSeek fp IO.RelativeSeek (toInteger d)) modifyIORef r (rep s) return 0 where rep :: String -> Vec m (Unsigned 8) -> Vec m (Unsigned 8) rep [] vs = vs rep (x:xs) (Cons _ vs) = Cons (toEnum (fromEnum x)) (rep xs vs) rep _ Nil = Nil # NOINLINE getLine # # ANN getLine hasBlackBox # isEOF :: File -> SimIO Bool isEOF (File fp) = SimIO (IO.hIsEOF fp) # NOINLINE isEOF # # ANN isEOF hasBlackBox # seek :: File -> Integer -> Int * 1 : From the current position * 2 : From the end of the file -> SimIO Int seek (File fp) pos mode = SimIO (IO.hSeek fp (toEnum mode) pos >> return 0) # NOINLINE seek # # ANN seek hasBlackBox # rewind :: File -> SimIO Int rewind (File fp) = SimIO (IO.hSeek fp IO.AbsoluteSeek 0 >> return 0) # NOINLINE rewind # # ANN rewind hasBlackBox # tell :: File -> SimIO Integer tell (File fp) = SimIO (IO.hTell fp) # NOINLINE tell # # ANN tell hasBlackBox # flush :: File -> SimIO () flush (File fp) = SimIO (IO.hFlush fp) # NOINLINE flush # # ANN flush hasBlackBox # Note that it is unlikely that the HDL - level I\/O can subsequently be eofFileOut < - ' isEOF ' fileOut ' finish ' 1 regIn = ' mealyIO ' clk tbMachine tbInit regOut mealyIO :: KnownDomain dom => Clock dom ^ Clock at which rate the I\/O environment progresses -> (s -> i -> SimIO o) ^ Transition function inside an I\/O environment -> SimIO s -> Signal dom i -> Signal dom o mealyIO !_ f (SimIO i) inp = unsafePerformIO (i >>= go inp) where go q@(~(k :- ks)) s = (:-) <$> unSimIO (f s k) <*> unsafeInterleaveIO ((q `seq` go ks s)) # NOINLINE mealyIO #
fd22012137a77cde865a85881eaa6e60b207832e6b7951a074c9fa8e1bb05b9a
cartazio/numbers
Symbolic.hs
-- | Symbolic number, i.e., these are not numbers at all, but just build -- a representation of the expressions. -- This implementation is incomplete in that it allows construction, -- but not deconstruction of the expressions. It's mainly useful for -- debugging. module Data.Number.Symbolic(Sym, var, con, subst, unSym) where import Data.Char(isAlpha) import Data.Maybe(fromMaybe) import Data.List(sortBy) import Data.Function(on) -- | Symbolic numbers over some base type for the literals. data Sym a = Con a | App String ([a]->a) [Sym a] instance (Eq a) => Eq (Sym a) where Con x == Con x' = x == x' App f _ xs == App f' _ xs' = (f, xs) == (f', xs') _ == _ = False instance (Ord a) => Ord (Sym a) where Con x `compare` Con x' = x `compare` x' Con _ `compare` App _ _ _ = LT App _ _ _ `compare` Con _ = GT App f _ xs `compare` App f' _ xs' = (f, xs) `compare` (f', xs') -- | Create a variable. var :: String -> Sym a var s = App s undefined [] -- | Create a constant (useful when it is not a literal). con :: a -> Sym a con = Con | The expression @subst x v e@ substitutes the expression @v@ for each occurence of the variable @x@ in @e@. subst :: (Num a, Eq a) => String -> Sym a -> Sym a -> Sym a subst _ _ e@(Con _) = e subst x v e@(App x' _ []) | x == x' = v | otherwise = e subst x v (App s f es) = case map (subst x v) es of [e] -> unOp (\ x -> f [x]) s e [e1,e2] -> binOp (\ x y -> f [x,y]) e1 s e2 es' -> App s f es' -- Turn a symbolic number into a regular one if it is a constant, -- otherwise generate an error. unSym :: (Show a) => Sym a -> a unSym (Con c) = c unSym e = error $ "unSym called: " ++ show e instance (Show a) => Show (Sym a) where showsPrec p (Con c) = showsPrec p c showsPrec _ (App s _ []) = showString s showsPrec p (App op@(c:_) _ [x, y]) | not (isAlpha c) = showParen (p>q) (showsPrec ql x . showString op . showsPrec qr y) where (ql, q, qr) = fromMaybe (9,9,9) $ lookup op [ ("**", (9,8,8)), ("/", (7,7,8)), ("*", (7,7,8)), ("+", (6,6,7)), ("-", (6,6,7))] showsPrec p (App "negate" _ [x]) = showParen (p>=6) (showString "-" . showsPrec 7 x) showsPrec p (App f _ xs) = showParen (p>10) (foldl (.) (showString f) (map (\ x -> showChar ' ' . showsPrec 11 x) xs)) instance (Num a, Eq a) => Num (Sym a) where x + y = sum' $ concatMap addena [x,y] x - y = binOp (-) x "-" y x * y = binOp (*) x "*" y negate x = unOp negate "negate" x abs x = unOp abs "abs" x signum x = unOp signum "signum" x fromInteger x = Con (fromInteger x) instance (Fractional a, Eq a) => Fractional (Sym a) where x / y = binOp (/) x "/" y fromRational x = Con (fromRational x) -- Assume the numbers are a field and simplify a little binOp :: (Num a, Eq a) => (a->a->a) -> Sym a -> String -> Sym a -> Sym a binOp f (Con x) _ (Con y) = Con (f x y) binOp _ x "+" 0 = x binOp _ 0 "+" x = x binOp _ x "+" y | isCon y && not (isCon x) = binOp (+) y "+" x binOp _ x "+" (App "negate" _ [y]) = x - y binOp _ x "-" 0 = x binOp _ x "-" x' | x == x' = 0 binOp _ x "-" (Con y) | not (isCon x) = Con (-y) + x binOp _ _ "*" 0 = 0 binOp _ x "*" 1 = x binOp _ x "*" (-1) = -x binOp _ 0 "*" _ = 0 binOp _ 1 "*" x = x binOp _ (-1) "*" x = -x binOp _ x "*" (App "*" _ [y, z]) = (x * y) * z binOp _ x "*" y | isCon y && not (isCon x) = y * x binOp _ x "*" (App "/" f [y, z]) = App "/" f [x*y, z] {- binOp _ x "*" (App "+" _ [y, z]) = x*y + x*z binOp _ (App "+" _ [y, z]) "*" x = y*x + z*x -} binOp _ x "/" 1 = x binOp _ x "/" (-1) = -x binOp _ x "/" x' | x == x' = 1 binOp _ x "/" (App "/" f [y, z]) = App "/" f [x*z, y] binOp f (App "**" _ [x, y]) "**" z = binOp f x "**" (y * z) binOp _ _ "**" 0 = 1 binOp _ 0 "**" _ = 0 binOp f x op y = App op (\ [a,b] -> f a b) [x, y] unOp :: (Num a) => (a->a) -> String -> Sym a -> Sym a unOp f _ (Con c) = Con (f c) unOp _ "negate" (App "negate" _ [x]) = x unOp _ "abs" e@(App "abs" _ _) = e unOp _ "signum" e@(App "signum" _ _) = e unOp f op x = App op (\ [a] -> f a) [x] isCon :: Sym a -> Bool isCon (Con _) = True isCon _ = False addena :: Sym t -> [Sym t] addena (App "+" _ [a,b]) = addena a ++ addena b addena a = [a] sum' :: (Eq a, Num a) => [Sym a] -> Sym a sum' [a] = a sum' a = foldl1 (\x y -> binOp (+) x "+" y) $ gather $ sortBy (compare `on` (not . isCon)) a where gather [] = [] gather [t] = [t] gather (t1:n) = let (c,r) = gn t1 n in c : gather r gn t [] = (t,[]) gn t1 (t2:r) = let (c,s) = g1 t1 t2 (cs,rr) = gn c r in (cs, s ++ rr) g1 t1 t2 = case (t1,t2) of (App "*" _ [f1,x1], App "*" _ [f2,x2]) | x1 == x2 -> ((f1 + f2) * x1, []) (App "*" _ [f,x1], x2) | x1 == x2 -> ((f + 1) * x1, []) (x1, App "*" _ [f,x2]) | x1 == x2 -> ((f + 1) * x1, []) (x1,x2) | x1 == x2 -> (2 * x1, []) (Con x, Con y) -> (Con (x + y), []) _ -> (t1, [t2]) instance (Integral a) => Integral (Sym a) where quot x y = binOp quot x "quot" y rem x y = binOp rem x "rem" y quotRem x y = (quot x y, rem x y) div x y = binOp div x "div" y mod x y = binOp mod x "mod" y toInteger (Con c) = toInteger c instance (Enum a) => Enum (Sym a) where toEnum = Con . toEnum fromEnum (Con a) = fromEnum a instance (Real a) => Real (Sym a) where toRational (Con c) = toRational c instance (RealFrac a) => RealFrac (Sym a) where properFraction (Con c) = (i, Con c') where (i, c') = properFraction c instance (Floating a, Eq a) => Floating (Sym a) where pi = var "pi" exp = unOp exp "exp" sqrt = unOp sqrt "sqrt" log = unOp log "log" x ** y = binOp (**) x "**" y logBase x y = binOp logBase x "logBase" y sin = unOp sin "sin" tan = unOp tan "tan" cos = unOp cos "cos" asin = unOp asin "asin" atan = unOp atan "atan" acos = unOp acos "acos" sinh = unOp sinh "sinh" tanh = unOp tanh "tanh" cosh = unOp cosh "cosh" asinh = unOp asinh "asinh" atanh = unOp atanh "atanh" acosh = unOp acosh "acosh" instance (RealFloat a, Show a) => RealFloat (Sym a) where floatRadix = floatRadix . unSym floatDigits = floatDigits . unSym floatRange = floatRange . unSym decodeFloat (Con c) = decodeFloat c encodeFloat m e = Con (encodeFloat m e) exponent (Con c) = exponent c exponent _ = 0 significand (Con c) = Con (significand c) scaleFloat k (Con c) = Con (scaleFloat k c) scaleFloat _ x = x isNaN (Con c) = isNaN c isInfinite (Con c) = isInfinite c isDenormalized (Con c) = isDenormalized c isNegativeZero (Con c) = isNegativeZero c isIEEE = isIEEE . unSym atan2 x y = binOp atan2 x "atan2" y
null
https://raw.githubusercontent.com/cartazio/numbers/6bc3aaeea5f1802766a708522de468ed03d40051/Data/Number/Symbolic.hs
haskell
| Symbolic number, i.e., these are not numbers at all, but just build a representation of the expressions. This implementation is incomplete in that it allows construction, but not deconstruction of the expressions. It's mainly useful for debugging. | Symbolic numbers over some base type for the literals. | Create a variable. | Create a constant (useful when it is not a literal). Turn a symbolic number into a regular one if it is a constant, otherwise generate an error. Assume the numbers are a field and simplify a little binOp _ x "*" (App "+" _ [y, z]) = x*y + x*z binOp _ (App "+" _ [y, z]) "*" x = y*x + z*x
module Data.Number.Symbolic(Sym, var, con, subst, unSym) where import Data.Char(isAlpha) import Data.Maybe(fromMaybe) import Data.List(sortBy) import Data.Function(on) data Sym a = Con a | App String ([a]->a) [Sym a] instance (Eq a) => Eq (Sym a) where Con x == Con x' = x == x' App f _ xs == App f' _ xs' = (f, xs) == (f', xs') _ == _ = False instance (Ord a) => Ord (Sym a) where Con x `compare` Con x' = x `compare` x' Con _ `compare` App _ _ _ = LT App _ _ _ `compare` Con _ = GT App f _ xs `compare` App f' _ xs' = (f, xs) `compare` (f', xs') var :: String -> Sym a var s = App s undefined [] con :: a -> Sym a con = Con | The expression @subst x v e@ substitutes the expression @v@ for each occurence of the variable @x@ in @e@. subst :: (Num a, Eq a) => String -> Sym a -> Sym a -> Sym a subst _ _ e@(Con _) = e subst x v e@(App x' _ []) | x == x' = v | otherwise = e subst x v (App s f es) = case map (subst x v) es of [e] -> unOp (\ x -> f [x]) s e [e1,e2] -> binOp (\ x y -> f [x,y]) e1 s e2 es' -> App s f es' unSym :: (Show a) => Sym a -> a unSym (Con c) = c unSym e = error $ "unSym called: " ++ show e instance (Show a) => Show (Sym a) where showsPrec p (Con c) = showsPrec p c showsPrec _ (App s _ []) = showString s showsPrec p (App op@(c:_) _ [x, y]) | not (isAlpha c) = showParen (p>q) (showsPrec ql x . showString op . showsPrec qr y) where (ql, q, qr) = fromMaybe (9,9,9) $ lookup op [ ("**", (9,8,8)), ("/", (7,7,8)), ("*", (7,7,8)), ("+", (6,6,7)), ("-", (6,6,7))] showsPrec p (App "negate" _ [x]) = showParen (p>=6) (showString "-" . showsPrec 7 x) showsPrec p (App f _ xs) = showParen (p>10) (foldl (.) (showString f) (map (\ x -> showChar ' ' . showsPrec 11 x) xs)) instance (Num a, Eq a) => Num (Sym a) where x + y = sum' $ concatMap addena [x,y] x - y = binOp (-) x "-" y x * y = binOp (*) x "*" y negate x = unOp negate "negate" x abs x = unOp abs "abs" x signum x = unOp signum "signum" x fromInteger x = Con (fromInteger x) instance (Fractional a, Eq a) => Fractional (Sym a) where x / y = binOp (/) x "/" y fromRational x = Con (fromRational x) binOp :: (Num a, Eq a) => (a->a->a) -> Sym a -> String -> Sym a -> Sym a binOp f (Con x) _ (Con y) = Con (f x y) binOp _ x "+" 0 = x binOp _ 0 "+" x = x binOp _ x "+" y | isCon y && not (isCon x) = binOp (+) y "+" x binOp _ x "+" (App "negate" _ [y]) = x - y binOp _ x "-" 0 = x binOp _ x "-" x' | x == x' = 0 binOp _ x "-" (Con y) | not (isCon x) = Con (-y) + x binOp _ _ "*" 0 = 0 binOp _ x "*" 1 = x binOp _ x "*" (-1) = -x binOp _ 0 "*" _ = 0 binOp _ 1 "*" x = x binOp _ (-1) "*" x = -x binOp _ x "*" (App "*" _ [y, z]) = (x * y) * z binOp _ x "*" y | isCon y && not (isCon x) = y * x binOp _ x "*" (App "/" f [y, z]) = App "/" f [x*y, z] binOp _ x "/" 1 = x binOp _ x "/" (-1) = -x binOp _ x "/" x' | x == x' = 1 binOp _ x "/" (App "/" f [y, z]) = App "/" f [x*z, y] binOp f (App "**" _ [x, y]) "**" z = binOp f x "**" (y * z) binOp _ _ "**" 0 = 1 binOp _ 0 "**" _ = 0 binOp f x op y = App op (\ [a,b] -> f a b) [x, y] unOp :: (Num a) => (a->a) -> String -> Sym a -> Sym a unOp f _ (Con c) = Con (f c) unOp _ "negate" (App "negate" _ [x]) = x unOp _ "abs" e@(App "abs" _ _) = e unOp _ "signum" e@(App "signum" _ _) = e unOp f op x = App op (\ [a] -> f a) [x] isCon :: Sym a -> Bool isCon (Con _) = True isCon _ = False addena :: Sym t -> [Sym t] addena (App "+" _ [a,b]) = addena a ++ addena b addena a = [a] sum' :: (Eq a, Num a) => [Sym a] -> Sym a sum' [a] = a sum' a = foldl1 (\x y -> binOp (+) x "+" y) $ gather $ sortBy (compare `on` (not . isCon)) a where gather [] = [] gather [t] = [t] gather (t1:n) = let (c,r) = gn t1 n in c : gather r gn t [] = (t,[]) gn t1 (t2:r) = let (c,s) = g1 t1 t2 (cs,rr) = gn c r in (cs, s ++ rr) g1 t1 t2 = case (t1,t2) of (App "*" _ [f1,x1], App "*" _ [f2,x2]) | x1 == x2 -> ((f1 + f2) * x1, []) (App "*" _ [f,x1], x2) | x1 == x2 -> ((f + 1) * x1, []) (x1, App "*" _ [f,x2]) | x1 == x2 -> ((f + 1) * x1, []) (x1,x2) | x1 == x2 -> (2 * x1, []) (Con x, Con y) -> (Con (x + y), []) _ -> (t1, [t2]) instance (Integral a) => Integral (Sym a) where quot x y = binOp quot x "quot" y rem x y = binOp rem x "rem" y quotRem x y = (quot x y, rem x y) div x y = binOp div x "div" y mod x y = binOp mod x "mod" y toInteger (Con c) = toInteger c instance (Enum a) => Enum (Sym a) where toEnum = Con . toEnum fromEnum (Con a) = fromEnum a instance (Real a) => Real (Sym a) where toRational (Con c) = toRational c instance (RealFrac a) => RealFrac (Sym a) where properFraction (Con c) = (i, Con c') where (i, c') = properFraction c instance (Floating a, Eq a) => Floating (Sym a) where pi = var "pi" exp = unOp exp "exp" sqrt = unOp sqrt "sqrt" log = unOp log "log" x ** y = binOp (**) x "**" y logBase x y = binOp logBase x "logBase" y sin = unOp sin "sin" tan = unOp tan "tan" cos = unOp cos "cos" asin = unOp asin "asin" atan = unOp atan "atan" acos = unOp acos "acos" sinh = unOp sinh "sinh" tanh = unOp tanh "tanh" cosh = unOp cosh "cosh" asinh = unOp asinh "asinh" atanh = unOp atanh "atanh" acosh = unOp acosh "acosh" instance (RealFloat a, Show a) => RealFloat (Sym a) where floatRadix = floatRadix . unSym floatDigits = floatDigits . unSym floatRange = floatRange . unSym decodeFloat (Con c) = decodeFloat c encodeFloat m e = Con (encodeFloat m e) exponent (Con c) = exponent c exponent _ = 0 significand (Con c) = Con (significand c) scaleFloat k (Con c) = Con (scaleFloat k c) scaleFloat _ x = x isNaN (Con c) = isNaN c isInfinite (Con c) = isInfinite c isDenormalized (Con c) = isDenormalized c isNegativeZero (Con c) = isNegativeZero c isIEEE = isIEEE . unSym atan2 x y = binOp atan2 x "atan2" y