_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
f0cab9e2a4a51a06f2740b6daa4c8a1a7641e87ee504e9f6c860bef2e0e6eaf0
simplex-chat/simplex-chat
M20230117_fkey_indexes.hs
# LANGUAGE QuasiQuotes # module Simplex.Chat.Migrations.M20230117_fkey_indexes where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) -- .lint fkey-indexes m20230117_fkey_indexes :: Query m20230117_fkey_indexes = [sql| CREATE INDEX idx_calls_user_id ON calls(user_id); CREATE INDEX idx_calls_chat_item_id ON calls(chat_item_id); CREATE INDEX idx_calls_contact_id ON calls(contact_id); CREATE INDEX idx_chat_items_group_id ON chat_items(group_id); CREATE INDEX idx_commands_user_id ON commands(user_id); CREATE INDEX idx_connections_custom_user_profile_id ON connections(custom_user_profile_id); CREATE INDEX idx_connections_via_user_contact_link ON connections(via_user_contact_link); CREATE INDEX idx_connections_rcv_file_id ON connections(rcv_file_id); CREATE INDEX idx_connections_contact_id ON connections(contact_id); CREATE INDEX idx_connections_user_contact_link_id ON connections(user_contact_link_id); CREATE INDEX idx_connections_via_contact ON connections(via_contact); CREATE INDEX idx_contact_profiles_user_id ON contact_profiles(user_id); CREATE INDEX idx_contact_requests_contact_profile_id ON contact_requests(contact_profile_id); CREATE INDEX idx_contact_requests_user_contact_link_id ON contact_requests(user_contact_link_id); CREATE INDEX idx_contacts_via_group ON contacts(via_group); CREATE INDEX idx_contacts_contact_profile_id ON contacts(contact_profile_id); CREATE INDEX idx_files_chat_item_id ON files(chat_item_id); CREATE INDEX idx_files_user_id ON files(user_id); CREATE INDEX idx_files_group_id ON files(group_id); CREATE INDEX idx_files_contact_id ON files(contact_id); CREATE INDEX idx_group_member_intros_to_group_member_id ON group_member_intros(to_group_member_id); CREATE INDEX idx_group_members_user_id_local_display_name ON group_members(user_id, local_display_name); CREATE INDEX idx_group_members_member_profile_id ON group_members(member_profile_id); CREATE INDEX idx_group_members_contact_id ON group_members(contact_id); CREATE INDEX idx_group_members_contact_profile_id ON group_members(contact_profile_id); CREATE INDEX idx_group_members_user_id ON group_members(user_id); CREATE INDEX idx_group_members_invited_by ON group_members(invited_by); CREATE INDEX idx_group_profiles_user_id ON group_profiles(user_id); CREATE INDEX idx_groups_host_conn_custom_user_profile_id ON groups(host_conn_custom_user_profile_id); CREATE INDEX idx_groups_chat_item_id ON groups(chat_item_id); CREATE INDEX idx_groups_group_profile_id ON groups(group_profile_id); CREATE INDEX idx_messages_group_id ON messages(group_id); CREATE INDEX idx_pending_group_messages_group_member_intro_id ON pending_group_messages(group_member_intro_id); CREATE INDEX idx_pending_group_messages_message_id ON pending_group_messages(message_id); CREATE INDEX idx_pending_group_messages_group_member_id ON pending_group_messages(group_member_id); CREATE INDEX idx_rcv_file_chunks_file_id ON rcv_file_chunks(file_id); CREATE INDEX idx_rcv_files_group_member_id ON rcv_files(group_member_id); CREATE INDEX idx_received_probes_user_id ON received_probes(user_id); CREATE INDEX idx_received_probes_contact_id ON received_probes(contact_id); CREATE INDEX idx_sent_probe_hashes_user_id ON sent_probe_hashes(user_id); CREATE INDEX idx_sent_probe_hashes_contact_id ON sent_probe_hashes(contact_id); CREATE INDEX idx_settings_user_id ON settings(user_id); CREATE INDEX idx_smp_servers_user_id ON smp_servers(user_id); CREATE INDEX idx_snd_file_chunks_file_id_connection_id ON snd_file_chunks(file_id, connection_id); CREATE INDEX idx_snd_files_group_member_id ON snd_files(group_member_id); CREATE INDEX idx_snd_files_connection_id ON snd_files(connection_id); CREATE INDEX idx_snd_files_file_id ON snd_files(file_id); |]
null
https://raw.githubusercontent.com/simplex-chat/simplex-chat/c8fae0ec4390c40675ac9f9aa9924d5da87edbb2/src/Simplex/Chat/Migrations/M20230117_fkey_indexes.hs
haskell
.lint fkey-indexes
# LANGUAGE QuasiQuotes # module Simplex.Chat.Migrations.M20230117_fkey_indexes where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) m20230117_fkey_indexes :: Query m20230117_fkey_indexes = [sql| CREATE INDEX idx_calls_user_id ON calls(user_id); CREATE INDEX idx_calls_chat_item_id ON calls(chat_item_id); CREATE INDEX idx_calls_contact_id ON calls(contact_id); CREATE INDEX idx_chat_items_group_id ON chat_items(group_id); CREATE INDEX idx_commands_user_id ON commands(user_id); CREATE INDEX idx_connections_custom_user_profile_id ON connections(custom_user_profile_id); CREATE INDEX idx_connections_via_user_contact_link ON connections(via_user_contact_link); CREATE INDEX idx_connections_rcv_file_id ON connections(rcv_file_id); CREATE INDEX idx_connections_contact_id ON connections(contact_id); CREATE INDEX idx_connections_user_contact_link_id ON connections(user_contact_link_id); CREATE INDEX idx_connections_via_contact ON connections(via_contact); CREATE INDEX idx_contact_profiles_user_id ON contact_profiles(user_id); CREATE INDEX idx_contact_requests_contact_profile_id ON contact_requests(contact_profile_id); CREATE INDEX idx_contact_requests_user_contact_link_id ON contact_requests(user_contact_link_id); CREATE INDEX idx_contacts_via_group ON contacts(via_group); CREATE INDEX idx_contacts_contact_profile_id ON contacts(contact_profile_id); CREATE INDEX idx_files_chat_item_id ON files(chat_item_id); CREATE INDEX idx_files_user_id ON files(user_id); CREATE INDEX idx_files_group_id ON files(group_id); CREATE INDEX idx_files_contact_id ON files(contact_id); CREATE INDEX idx_group_member_intros_to_group_member_id ON group_member_intros(to_group_member_id); CREATE INDEX idx_group_members_user_id_local_display_name ON group_members(user_id, local_display_name); CREATE INDEX idx_group_members_member_profile_id ON group_members(member_profile_id); CREATE INDEX idx_group_members_contact_id ON group_members(contact_id); CREATE INDEX idx_group_members_contact_profile_id ON group_members(contact_profile_id); CREATE INDEX idx_group_members_user_id ON group_members(user_id); CREATE INDEX idx_group_members_invited_by ON group_members(invited_by); CREATE INDEX idx_group_profiles_user_id ON group_profiles(user_id); CREATE INDEX idx_groups_host_conn_custom_user_profile_id ON groups(host_conn_custom_user_profile_id); CREATE INDEX idx_groups_chat_item_id ON groups(chat_item_id); CREATE INDEX idx_groups_group_profile_id ON groups(group_profile_id); CREATE INDEX idx_messages_group_id ON messages(group_id); CREATE INDEX idx_pending_group_messages_group_member_intro_id ON pending_group_messages(group_member_intro_id); CREATE INDEX idx_pending_group_messages_message_id ON pending_group_messages(message_id); CREATE INDEX idx_pending_group_messages_group_member_id ON pending_group_messages(group_member_id); CREATE INDEX idx_rcv_file_chunks_file_id ON rcv_file_chunks(file_id); CREATE INDEX idx_rcv_files_group_member_id ON rcv_files(group_member_id); CREATE INDEX idx_received_probes_user_id ON received_probes(user_id); CREATE INDEX idx_received_probes_contact_id ON received_probes(contact_id); CREATE INDEX idx_sent_probe_hashes_user_id ON sent_probe_hashes(user_id); CREATE INDEX idx_sent_probe_hashes_contact_id ON sent_probe_hashes(contact_id); CREATE INDEX idx_settings_user_id ON settings(user_id); CREATE INDEX idx_smp_servers_user_id ON smp_servers(user_id); CREATE INDEX idx_snd_file_chunks_file_id_connection_id ON snd_file_chunks(file_id, connection_id); CREATE INDEX idx_snd_files_group_member_id ON snd_files(group_member_id); CREATE INDEX idx_snd_files_connection_id ON snd_files(connection_id); CREATE INDEX idx_snd_files_file_id ON snd_files(file_id); |]
dfcdc75b3db92b244bcd3d021370176d8584c6e7429f0be5cbbbe87f4ce623bd
ndmitchell/supero
Firstify.hs
module Firstify(firstify) where import Yhc.Core hiding (collectAllVars,collectFreeVars,uniqueBoundVars,replaceFreeVars) import Yhc.Core.FreeVar2 import Firstify.Template import Firstify.Prepare import Data.List import Data.Char import Data.Maybe import Control.Monad.State import qualified Data.Set as Set import qualified Data.Map as Map SPECIALISE ALGORITHM Need to generate a specialised version if : * f gets called with more arguments than its arity * any argument is higher order The specialised version has : * a free variable for each non - ho argument * the free variables within a function , for a ho argument SPECIALISE ALGORITHM Need to generate a specialised version if: * f gets called with more arguments than its arity * any argument is higher order The specialised version has: * a free variable for each non-ho argument * the free variables within a function, for a ho argument -} --------------------------------------------------------------------- -- DRIVER if the first result is not null , an error occurred the second result is how far you got firstify :: Core -> Core firstify core = coreReachable ["main"] $ coreSimplify $ fromCoreFuncMap core $ trans $ prepare core data Spec = Spec {specId :: Int ,specCore :: CoreFuncMap ,specMap :: Map.Map (CoreFuncName,Template) CoreFuncName -- the list of items which are currently under evaluation ,specActive :: Set.Set CoreFuncName -- the functions which got finished ,specDone :: Set.Set CoreFuncName -- those which were asked for while in active ,specMissed :: Set.Set CoreFuncName } type SpecM a = State Spec a trans :: CoreFuncMap -> CoreFuncMap trans fm = evalState f newSpec where newSpec = Spec 1 fm Map.empty Set.empty Set.empty Set.empty mainArgs = take (length $ coreFuncArgs $ coreFuncMap fm "main") $ freeVars 'v' prims = [x | CorePrim x _ <- Map.elems fm] f = do lam prims (CoreApp (CoreFun "main") (map CoreVar mainArgs)) s <- get if any (isHO . coreFuncBody . coreFuncMap (specCore s)) $ Set.toList (specMissed s) then put s{specActive=Set.empty, specDone=Set.empty, specMissed=Set.empty} >> f else return $ specCore s coreFuncBody2 (CoreFunc _ _ x) = x should look at the CoreFunc to see if its a primitive lam :: [CoreFuncName] -> CoreExpr -> SpecM CoreExpr lam prims (CoreApp (CoreFun f) xs) | f `elem` ["Prelude.error","error"] = liftM (CoreApp (CoreFun f)) (mapM (lam prims) $ take 1 xs) | f `elem` prims = liftM (CoreApp (CoreFun f)) (mapM (lam prims) xs) | otherwise = do xs <- mapM (lam prims) xs s <- get let func = coreFuncMap (specCore s) f -- make sure that the templating is done (f,xs) <- case useTemplate func xs of Nothing -> return (f,xs) Just (template,args) -> do s <- get case Map.lookup (f,template) (specMap s) of Just f2 -> return (f2,args) Nothing -> do let newname = dropDollar f ++ "$" ++ show (specId s) put s{specId = specId s + 1 ,specCore = Map.insert newname (genTemplate template func newname) (specCore s) ,specMap = Map.insert (f,template) newname (specMap s)} return (newname,args) -- now try and do the transformation on it if required when (not (Set.member f (specDone s)) && not (Set.member f (specActive s))) $ do s <- get put s{specActive = Set.insert f (specActive s)} let func = coreFuncMap (specCore s) f res <- lam prims (coreFuncBody func) modify $ \s -> s{specCore = Map.insert f func{coreFuncBody = res} (specCore s) ,specActive = Set.delete f (specActive s) ,specDone = Set.insert f (specDone s)} -- now inline the function if required s <- get when (not $ Set.member f $ specDone s) $ put s{specMissed = Set.insert f (specMissed s)} let func = coreFuncMap (specCore s) f body = coreFuncBody func if isConLambda body then return $ uncurry coreLam $ coreInlineFuncLambda func xs else if isLambda body then let fresh = take (lamArity body) $ freeVars 'v' \\ concatMap collectAllVars xs in return $ CoreLam fresh $ CoreApp (CoreFun f) (xs ++ map CoreVar fresh) else return $ CoreApp (CoreFun f) xs lam prims (CoreApp (CoreVar x) xs) = liftM (CoreApp (CoreVar x)) (mapM (lam prims) xs) lam prims (CoreApp (CoreCon x) xs) = liftM (CoreApp (CoreCon x)) (mapM (lam prims) xs) lam prims (CoreApp (CoreLam xs body) ys) = lam prims $ coreApp (coreLam (drop n xs) (replaceFreeVars (zip xs ys) body)) (drop n ys) where n = min (length xs) (length ys) lam prims (CoreApp (CoreCase on alts) xs) = lam prims $ CoreCase on [(a, CoreApp b xs) | (a,b) <- alts] lam prims (CoreApp (CoreApp x ys) zs) = lam prims $ CoreApp x (ys++zs) lam prims (CoreApp (CoreLet bind x) xs) | null (map fst bind `intersect` vxs) = lam prims $ CoreLet bind (CoreApp x xs) | otherwise = lam prims $ CoreLet (zip fresh (map snd bind)) (CoreApp x2 xs) where x2 = replaceFreeVars (zip (map fst bind) (map CoreVar fresh)) x fresh = freeVars 'v' \\ (vl ++ vxs) vl = collectAllVars (CoreLet bind x) vxs = nub $ concatMap collectAllVars xs lam prims (CoreLet binds x) = do rhs <- mapM (lam prims . snd) binds let (ho,fo) = partition (isHO . snd) (zip (map fst binds) rhs) x2 <- lam prims $ replaceFreeVars ho x return $ coreLet fo x2 lam prims (CoreCase on alts) = do on2 <- lam prims on case on2 of CoreApp (CoreCon c) xs -> lam prims $ head $ [replaceFreeVars (zip (map fromCoreVar xs2) xs) rhs | (CoreApp (CoreCon c2) xs2, rhs) <- alts, c2 == c] ++ [replaceFreeVars [(lhs,on2)] rhs | (CoreVar lhs,rhs) <- alts] _ -> do rhs <- mapM (lam prims . snd) alts return $ CoreCase on2 (zip (map fst alts) rhs) lam prims x | isCoreLam x || isCoreVar x || isCoreConst x = return x lam prims x = error $ show x dropDollar xs = if not (null nums) && not (null dol) then reverse (tail dol) else xs where (nums,dol) = span isDigit $ reverse xs
null
https://raw.githubusercontent.com/ndmitchell/supero/a8b16ea90862e2c021bb139d7a7e9a83700b43b2/Dead/Firstify.hs
haskell
------------------------------------------------------------------- DRIVER the list of items which are currently under evaluation the functions which got finished those which were asked for while in active make sure that the templating is done now try and do the transformation on it if required now inline the function if required
module Firstify(firstify) where import Yhc.Core hiding (collectAllVars,collectFreeVars,uniqueBoundVars,replaceFreeVars) import Yhc.Core.FreeVar2 import Firstify.Template import Firstify.Prepare import Data.List import Data.Char import Data.Maybe import Control.Monad.State import qualified Data.Set as Set import qualified Data.Map as Map SPECIALISE ALGORITHM Need to generate a specialised version if : * f gets called with more arguments than its arity * any argument is higher order The specialised version has : * a free variable for each non - ho argument * the free variables within a function , for a ho argument SPECIALISE ALGORITHM Need to generate a specialised version if: * f gets called with more arguments than its arity * any argument is higher order The specialised version has: * a free variable for each non-ho argument * the free variables within a function, for a ho argument -} if the first result is not null , an error occurred the second result is how far you got firstify :: Core -> Core firstify core = coreReachable ["main"] $ coreSimplify $ fromCoreFuncMap core $ trans $ prepare core data Spec = Spec {specId :: Int ,specCore :: CoreFuncMap ,specMap :: Map.Map (CoreFuncName,Template) CoreFuncName ,specActive :: Set.Set CoreFuncName ,specDone :: Set.Set CoreFuncName ,specMissed :: Set.Set CoreFuncName } type SpecM a = State Spec a trans :: CoreFuncMap -> CoreFuncMap trans fm = evalState f newSpec where newSpec = Spec 1 fm Map.empty Set.empty Set.empty Set.empty mainArgs = take (length $ coreFuncArgs $ coreFuncMap fm "main") $ freeVars 'v' prims = [x | CorePrim x _ <- Map.elems fm] f = do lam prims (CoreApp (CoreFun "main") (map CoreVar mainArgs)) s <- get if any (isHO . coreFuncBody . coreFuncMap (specCore s)) $ Set.toList (specMissed s) then put s{specActive=Set.empty, specDone=Set.empty, specMissed=Set.empty} >> f else return $ specCore s coreFuncBody2 (CoreFunc _ _ x) = x should look at the CoreFunc to see if its a primitive lam :: [CoreFuncName] -> CoreExpr -> SpecM CoreExpr lam prims (CoreApp (CoreFun f) xs) | f `elem` ["Prelude.error","error"] = liftM (CoreApp (CoreFun f)) (mapM (lam prims) $ take 1 xs) | f `elem` prims = liftM (CoreApp (CoreFun f)) (mapM (lam prims) xs) | otherwise = do xs <- mapM (lam prims) xs s <- get let func = coreFuncMap (specCore s) f (f,xs) <- case useTemplate func xs of Nothing -> return (f,xs) Just (template,args) -> do s <- get case Map.lookup (f,template) (specMap s) of Just f2 -> return (f2,args) Nothing -> do let newname = dropDollar f ++ "$" ++ show (specId s) put s{specId = specId s + 1 ,specCore = Map.insert newname (genTemplate template func newname) (specCore s) ,specMap = Map.insert (f,template) newname (specMap s)} return (newname,args) when (not (Set.member f (specDone s)) && not (Set.member f (specActive s))) $ do s <- get put s{specActive = Set.insert f (specActive s)} let func = coreFuncMap (specCore s) f res <- lam prims (coreFuncBody func) modify $ \s -> s{specCore = Map.insert f func{coreFuncBody = res} (specCore s) ,specActive = Set.delete f (specActive s) ,specDone = Set.insert f (specDone s)} s <- get when (not $ Set.member f $ specDone s) $ put s{specMissed = Set.insert f (specMissed s)} let func = coreFuncMap (specCore s) f body = coreFuncBody func if isConLambda body then return $ uncurry coreLam $ coreInlineFuncLambda func xs else if isLambda body then let fresh = take (lamArity body) $ freeVars 'v' \\ concatMap collectAllVars xs in return $ CoreLam fresh $ CoreApp (CoreFun f) (xs ++ map CoreVar fresh) else return $ CoreApp (CoreFun f) xs lam prims (CoreApp (CoreVar x) xs) = liftM (CoreApp (CoreVar x)) (mapM (lam prims) xs) lam prims (CoreApp (CoreCon x) xs) = liftM (CoreApp (CoreCon x)) (mapM (lam prims) xs) lam prims (CoreApp (CoreLam xs body) ys) = lam prims $ coreApp (coreLam (drop n xs) (replaceFreeVars (zip xs ys) body)) (drop n ys) where n = min (length xs) (length ys) lam prims (CoreApp (CoreCase on alts) xs) = lam prims $ CoreCase on [(a, CoreApp b xs) | (a,b) <- alts] lam prims (CoreApp (CoreApp x ys) zs) = lam prims $ CoreApp x (ys++zs) lam prims (CoreApp (CoreLet bind x) xs) | null (map fst bind `intersect` vxs) = lam prims $ CoreLet bind (CoreApp x xs) | otherwise = lam prims $ CoreLet (zip fresh (map snd bind)) (CoreApp x2 xs) where x2 = replaceFreeVars (zip (map fst bind) (map CoreVar fresh)) x fresh = freeVars 'v' \\ (vl ++ vxs) vl = collectAllVars (CoreLet bind x) vxs = nub $ concatMap collectAllVars xs lam prims (CoreLet binds x) = do rhs <- mapM (lam prims . snd) binds let (ho,fo) = partition (isHO . snd) (zip (map fst binds) rhs) x2 <- lam prims $ replaceFreeVars ho x return $ coreLet fo x2 lam prims (CoreCase on alts) = do on2 <- lam prims on case on2 of CoreApp (CoreCon c) xs -> lam prims $ head $ [replaceFreeVars (zip (map fromCoreVar xs2) xs) rhs | (CoreApp (CoreCon c2) xs2, rhs) <- alts, c2 == c] ++ [replaceFreeVars [(lhs,on2)] rhs | (CoreVar lhs,rhs) <- alts] _ -> do rhs <- mapM (lam prims . snd) alts return $ CoreCase on2 (zip (map fst alts) rhs) lam prims x | isCoreLam x || isCoreVar x || isCoreConst x = return x lam prims x = error $ show x dropDollar xs = if not (null nums) && not (null dol) then reverse (tail dol) else xs where (nums,dol) = span isDigit $ reverse xs
2082a9cb1bea4a162071904df53c9a65d1fa98d9b3cf113221641a7ff3af4f26
danr/hipspec
Scope.hs
# LANGUAGE CPP # module HipSpec.Sig.Scope where import GHC hiding (Sig) import Control.Applicative import Data.Maybe import DataCon #if __GLASGOW_HASKELL__ >= 708 import ConLike #endif getIdsInScope :: (Id -> Id) -> Ghc [Id] getIdsInScope fix_id = do ns <- getNamesInScope things <- catMaybes <$> mapM lookupName ns return [ fix_id i | AnId i <- things ] parseName' :: String -> Ghc [Name] parseName' = handleSourceError (\ _ -> return []) . parseName inScope :: String -> Ghc Bool inScope s = do xs <- parseName' s return $ if null xs then False else True lookupString :: String -> Ghc [TyThing] lookupString s = do xs <- parseName' s catMaybes <$> mapM lookupName xs thingToId :: TyThing -> Maybe Id thingToId (AnId i) = Just i #if __GLASGOW_HASKELL__ >= 708 thingToId (AConLike (RealDataCon dc)) = Just (dataConWorkId dc) thingToId (AConLike (PatSynCon _pc)) = error "HipSpec.Sig.Scope: Pattern synonyms not supported" #else thingToId (ADataCon dc) = Just (dataConWorkId dc) #endif thingToId _ = Nothing mapJust :: (a -> Maybe b) -> [a] -> Maybe b mapJust k = listToMaybe . mapMaybe k
null
https://raw.githubusercontent.com/danr/hipspec/a114db84abd5fee8ce0b026abc5380da11147aa9/src/HipSpec/Sig/Scope.hs
haskell
# LANGUAGE CPP # module HipSpec.Sig.Scope where import GHC hiding (Sig) import Control.Applicative import Data.Maybe import DataCon #if __GLASGOW_HASKELL__ >= 708 import ConLike #endif getIdsInScope :: (Id -> Id) -> Ghc [Id] getIdsInScope fix_id = do ns <- getNamesInScope things <- catMaybes <$> mapM lookupName ns return [ fix_id i | AnId i <- things ] parseName' :: String -> Ghc [Name] parseName' = handleSourceError (\ _ -> return []) . parseName inScope :: String -> Ghc Bool inScope s = do xs <- parseName' s return $ if null xs then False else True lookupString :: String -> Ghc [TyThing] lookupString s = do xs <- parseName' s catMaybes <$> mapM lookupName xs thingToId :: TyThing -> Maybe Id thingToId (AnId i) = Just i #if __GLASGOW_HASKELL__ >= 708 thingToId (AConLike (RealDataCon dc)) = Just (dataConWorkId dc) thingToId (AConLike (PatSynCon _pc)) = error "HipSpec.Sig.Scope: Pattern synonyms not supported" #else thingToId (ADataCon dc) = Just (dataConWorkId dc) #endif thingToId _ = Nothing mapJust :: (a -> Maybe b) -> [a] -> Maybe b mapJust k = listToMaybe . mapMaybe k
7016a0e07be59a1b67541f28ed57178a730234d354096bbbd3d7bf3569ba5a3c
rowangithub/DOrder
ed_main.ml
(**************************************************************************) (* *) : a generic graph library for OCaml Copyright ( C ) 2004 - 2007 , and (* *) (* This software is free software; you can redistribute it and/or *) modify it under the terms of the GNU Library General Public License version 2 , with the special exception on linking (* described in file LICENSE. *) (* *) (* This software 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. *) (* *) (**************************************************************************) This file is a contribution of open Format open Graph open Ed_hyper open Ed_graph open Ed_display open Ed_draw let debug = ref false let trace f x = try f x with e -> eprintf "TRACE: %s@." (Printexc.to_string e); raise e let _ = GMain.Main.init () (* Model for the treeview on the left *) module Model = struct open Gobject.Data let cols = new GTree.column_list let name = cols#add string let vertex = cols#add caml let model = GTree.tree_store cols let rows = H.create 97 let find_row v = try H.find rows v with Not_found -> Format.eprintf "anomaly: no model row for %s@." (string_of_label v); raise Not_found let add_vertex v = let row = model#append () in model#set ~row ~column:name (string_of_label v); model#set ~row ~column:vertex v; H.add rows v row; row let add_edge_1 row_v w = let row = model#append ~parent:row_v () in model#set ~row ~column:name (string_of_label w); model#set ~row ~column:vertex w let add_edge v w = let row_v = find_row v in add_edge_1 row_v w; if not G.is_directed then let row_w = find_row w in add_edge_1 row_w v let find_children row_v w = let nb_child = model#iter_n_children (Some row_v) in let rec find n = let child = model#iter_children ~nth:(n-1) (Some row_v) in let child_vertex = model#get ~row:child ~column:vertex in match n with | 0 -> raise Not_found | n -> if (G.V.equal child_vertex w) then child else find (n-1) in find nb_child let remove_edge_1 row_v w = ignore (model#remove (find_children row_v w)) let remove_edge v w = let row_v = find_row v in remove_edge_1 row_v w; if not G.is_directed then let row_w = find_row w in remove_edge_1 row_w v let remove_vertex vertex = G.iter_succ (fun w -> remove_edge w vertex) !graph vertex; let row = find_row vertex in model#remove row let reset () = H.clear rows; model#clear (); G.iter_vertex (fun v -> let row = add_vertex v in G.iter_succ (add_edge_1 row) !graph v) !graph end let () = Model.reset () open GtkTree let ed_name = "Ocamlgraph's Editor" (* Main GTK window *) let window = GWindow.window ~border_width: 10 ~position: `CENTER () (* usual function to change window title *) let set_window_title () = window#set_title (match !graph_name with | None -> ed_name | Some name -> ed_name^" : "^(Filename.chop_extension (Filename.basename name))) (* menu bar *) let v_box = GPack.vbox ~homogeneous:false ~spacing:30 ~packing:window#add () let menu_bar_box = GPack.vbox ~packing:v_box#pack () (* treeview on the left, canvas on the right *) let h_box = GPack.hbox ~homogeneous:false ~spacing:30 ~packing:v_box#add () let sw = GBin.scrolled_window ~shadow_type:`ETCHED_IN ~hpolicy:`NEVER ~vpolicy:`AUTOMATIC ~packing:h_box#add () let canvas = GnoCanvas.canvas ~aa:!aa ~width:(truncate w) ~height:(truncate h) ~packing:h_box#add () (* unit circle as root of graph drawing *) let canvas_root = let circle_group = GnoCanvas.group ~x:300.0 ~y:300.0 canvas#root in circle_group#lower_to_bottom (); let w2 = 2. in let circle = GnoCanvas.ellipse ~props:[ `X1 (-.w/.2. +.w2); `Y1 (-.h/.2. +.w2); `X2 (w/.2. -.w2) ; `Y2 ( h/.2. -.w2) ; `FILL_COLOR color_circle ; `OUTLINE_COLOR "black" ; `WIDTH_PIXELS (truncate w2) ] circle_group in circle_group#lower_to_bottom (); circle#show(); let graph_root = GnoCanvas.group ~x:(-.300.0) ~y:(-.300.0) circle_group in graph_root#raise_to_top (); set_window_title (); graph_root (* current root used for drawing *) let root = ref (choose_root ()) let load_graph f = Ed_graph.load_graph f; Model.reset (); set_window_title (); root := choose_root () (* refresh rate *) let refresh = ref 0 let do_refresh () = !refresh mod !refresh_rate = 0 (* graph drawing *) let draw tortue canvas = match !root with | None -> () | Some root -> Ed_draw.draw_graph root tortue; Ed_display.draw_graph root canvas; if do_refresh () then canvas_root#canvas#update_now () let refresh_draw () = refresh := 0; let tor = make_turtle !origine 0.0 in draw tor canvas_root let refresh_display () = Ed_display.draw_graph !root canvas_root let root_change vertex ()= root := vertex; origine := start_point; let turtle = make_turtle_origine () in draw turtle canvas_root let node_selection ~(model : GTree.tree_store) path = let row = model#get_iter path in let vertex = model#get ~row ~column: Model.vertex in root_change (Some vertex) () (* usual function ref, for vertex event *) let set_vertex_event_fun = ref (fun _ -> ()) (* type to select nature of modification *) type modification = Add | Remove (* add a vertex with no successor *) let add_node () = let window = GWindow.window ~title: "Choose vertex label" ~width: 300 ~height: 50 ~position: `MOUSE () in let vbox = GPack.vbox ~packing: window#add () in let entry = GEdit.entry ~max_length: 50 ~packing: vbox#add () in entry#set_text "Label"; entry#select_region ~start:0 ~stop:entry#text_length; two check buttons allowing to add node to selection list and to choose this node as root let hbox = GPack.hbox ~packing: vbox#add () in let is_in_selection = ref false in let in_selection = GButton.check_button ~label: "Add to selection" ~active:!is_in_selection ~packing: hbox#add () in ignore (in_selection#connect#toggled ~callback:(fun () ->is_in_selection := in_selection#active )); let is_as_root = ref ((G.nb_vertex !graph)=0) in let as_root = GButton.check_button ~label:"Choose as root" ~active:!is_as_root ~packing:hbox#add () in ignore (as_root#connect#toggled ~callback:(fun () ->is_as_root := as_root#active )); window#show (); (*entry's callback*) ignore( entry#connect#activate ~callback: (fun () -> let text = entry#text in window#destroy (); (* new vertex *) let vertex = G.V.create (make_node_info text) in G.add_vertex !graph vertex ; ignore (Model.add_vertex vertex); Ed_display.add_node canvas_root vertex; !set_vertex_event_fun vertex; if !is_as_root then root_change (Some vertex) () ; if !is_in_selection then update_vertex vertex Select; let tor = make_turtle !origine 0.0 in draw tor canvas_root)) add an edge between n1 and n2 , add link in column and re - draw let add_edge n1 n2 ()= if not (edge n1 n2) then begin G.add_edge_e !graph (G.E.create n1 (make_edge_info ()) n2); Model.add_edge n1 n2; let tor = make_turtle !origine 0.0 in draw tor canvas_root; end let add_edge_no_refresh n1 n2 ()= if not (edge n1 n2) then begin G.add_edge_e !graph (G.E.create n1 (make_edge_info ()) n2); Model.add_edge n1 n2 end remove an edge between n1 and n2 , add un - link in column and re - draw let remove_edge n1 n2 ()= if (edge n1 n2) then begin G.remove_edge !graph n1 n2; Model.remove_edge n1 n2; begin try let _,n = H2.find intern_edges (n1,n2) in n#destroy (); H2.remove intern_edges (n1,n2) with Not_found -> () end; begin try let _,n = H2.find intern_edges (n2,n1) in n#destroy (); H2.remove intern_edges (n2,n1) with Not_found -> () end; begin try let n = H2.find successor_edges (n1,n2) in n#destroy (); H2.remove successor_edges (n1,n2) with Not_found -> () end; begin try let n = H2.find successor_edges (n2,n1) in n#destroy (); H2.remove successor_edges (n2,n1) with Not_found -> () end; let tor = make_turtle !origine 0.0 in draw tor canvas_root; end let remove_edge_no_refresh n1 n2 ()= if (edge n1 n2) then begin G.remove_edge !graph n1 n2; Model.remove_edge n1 n2 end (* add successor node to selected node *) let add_successor node () = let window = GWindow.window ~title: "Choose label name" ~width: 300 ~height: 50 ~position: `MOUSE () in let vbox = GPack.vbox ~packing: window#add () in let entry = GEdit.entry ~max_length: 50 ~packing: vbox#add () in entry#set_text "Label"; entry#select_region ~start:0 ~stop:entry#text_length; window#show (); ignore (entry#connect#activate ~callback:(fun () -> let text = entry#text in window#destroy (); (* new vertex *) let vertex = G.V.create (make_node_info text) in G.add_vertex !graph vertex ; ignore (Model.add_vertex vertex); Ed_display.add_node canvas_root vertex; !set_vertex_event_fun vertex; (* new edge *) G.add_edge_e !graph (G.E.create node (make_edge_info()) vertex); Model.add_edge node vertex; (* redraw *) let tor = make_turtle !origine 0.0 in draw tor canvas_root ) ) let remove_vertex vertex () = G.iter_succ (fun w -> begin try let _,n = H2.find intern_edges (vertex,w) in n#destroy (); H2.remove intern_edges (vertex,w) with Not_found -> () end; begin try let _,n = H2.find intern_edges (w,vertex) in n#destroy (); H2.remove intern_edges (w,vertex) with Not_found -> () end; begin try let n = H2.find successor_edges (vertex,w) in n#destroy (); H2.remove successor_edges (vertex,w) with Not_found -> () end; begin try let n = H2.find successor_edges (w,vertex) in n#destroy (); H2.remove successor_edges (w,vertex) with Not_found -> () end; ) !graph vertex; let (n,_,_) = H.find nodes vertex in n#destroy (); H.remove nodes vertex; ignore (Model.remove_vertex vertex); G.remove_vertex !graph vertex; begin match !root with | None -> () | Some root_v -> if (G.V.equal root_v vertex) then root := choose_root(); end; refresh_draw () let sub_edge_to modif_type vertex list = let ll = List.length list in let nb_sub_menu = (ll - 1)/10 + 1 in let nb_edge = ll / nb_sub_menu -1 in let menu = new GMenu.factory (GMenu.menu()) in let sub_menu =ref (new GMenu.factory (GMenu.menu())) in let add_menu_edge vertex v2 = if not (G.V.equal v2 vertex) then begin match modif_type with | Add -> ignore((!sub_menu)#add_item (string_of_label v2) ~callback:( add_edge v2 vertex)); | Remove -> ignore((!sub_menu)#add_item (string_of_label v2) ~callback:(remove_edge v2 vertex)); end; in let rec make_sub_menu vertex list nb = match list with | [] -> () | v::list -> match nb with | 0 -> begin sub_menu :=new GMenu.factory (GMenu.menu()) ; add_menu_edge vertex v; let string = string_of_label v in ignore (menu#add_item (String.sub string 0 (min (String.length string) 3)^"...") ~submenu: !sub_menu#menu); make_sub_menu vertex list (nb+1); end | n when n= nb_edge-> begin add_menu_edge vertex v; make_sub_menu vertex list 0 end | _ -> begin add_menu_edge vertex v; make_sub_menu vertex list (nb+1) end in if ll > 10 then begin make_sub_menu vertex list 0; menu end else begin let rec make_sub_bis list = match list with | [] -> (); | v::list ->add_menu_edge vertex v; make_sub_bis list in make_sub_bis list; !sub_menu end let edge_to modif_type vertex list = add an edge between current vertex and one of selected vertex sub_edge_to modif_type vertex list let all_edges (edge_menu :#GMenu.menu GMenu.factory) vertex list = (*add all edges as possible from current vertex to selected vertices*) begin let add_all_edge vertex list () = List.iter (fun v -> if not (G.V.equal v vertex) then add_edge_no_refresh v vertex() ) list ; refresh := 0; let tor = make_turtle !origine 0.0 in draw tor canvas_root in ignore (edge_menu#add_item "Add all edges" ~callback:( add_all_edge vertex list)) end let contextual_menu vertex ev = let menu = new GMenu.factory (GMenu.menu ()) in (* change root*) ignore (menu#add_item "As root" ~callback:(root_change (Some vertex))); (*vertex menu*) let vertex_menu = new GMenu.factory (GMenu.menu ()) in begin (* successor *) ignore (vertex_menu#add_item "Add successor" ~callback:(add_successor vertex)); ignore (vertex_menu#add_separator ()); (* remove vertex *) ignore(vertex_menu#add_item "Remove vertex" ~callback:(remove_vertex vertex)); end; ignore(menu#add_item "Vertex ops" ~submenu: vertex_menu#menu); (*edge menu*) begin let add_list = selected_list (ADD_FROM vertex) in let rem_list = selected_list (REMOVE_FROM vertex) in let al =List.length add_list in let rl =List.length rem_list in let isel = is_selected vertex in let menu_bool = ref false in let edge_menu = new GMenu.factory (GMenu.menu ()) in begin (* add menu *) if isel && al=2 || not isel && al=1 then begin ignore (edge_menu#add_item "Add edge with" ~submenu: (edge_to Add vertex add_list)#menu); menu_bool := true; end else begin if isel && al>2 || not isel && al>1 then begin ignore (edge_menu#add_item "Add edge with" ~submenu: (edge_to Add vertex add_list)#menu); all_edges edge_menu vertex add_list; menu_bool := true; end end; (* remove menu *) if isel && rl>=2 || not isel && rl>=1 then begin if !menu_bool then ignore (edge_menu#add_separator ()); ignore (edge_menu#add_item "Remove edge with" ~submenu: (edge_to Remove vertex rem_list)#menu); menu_bool := true; end; if !menu_bool then ignore(menu#add_item "Edge ops" ~submenu: edge_menu#menu); end; end; menu#menu#popup ~button:3 ~time:(GdkEvent.Button.time ev) (* unit circle callback *) let circle_event ev = begin match ev with | `BUTTON_PRESS ev -> if (GdkEvent.Button.button ev) = 3 then begin let menu = new GMenu.factory (GMenu.menu ()) in ignore (menu#add_item " Add node" ~callback:(add_node)); menu#menu#popup ~button:3 ~time:(GdkEvent.Button.time ev) end | _ ->() end; true (* event for each vertex of canvas *) let vertex_event vertex item ellispe ev = (* let vertex_info = G.V.label vertex in*) begin match ev with | `ENTER_NOTIFY _ -> item#grab_focus (); update_vertex vertex Focus; refresh_display () | `LEAVE_NOTIFY ev -> if not (Gdk.Convert.test_modifier `BUTTON1 (GdkEvent.Crossing.state ev)) then begin update_vertex vertex Unfocus; refresh_display () end | `BUTTON_RELEASE ev -> ellispe#parent#ungrab (GdkEvent.Button.time ev); | `MOTION_NOTIFY ev -> incr refresh; let state = GdkEvent.Motion.state ev in if Gdk.Convert.test_modifier `BUTTON1 state then begin let curs = Gdk.Cursor.create `FLEUR in ellispe#parent#grab [`POINTER_MOTION; `BUTTON_RELEASE] curs (GdkEvent.Button.time ev); if do_refresh () then begin let old_origin = !origine in let turtle = motion_turtle ellispe ev in if hspace_dist_sqr turtle <= rlimit_sqr then begin draw turtle canvas_root end else begin origine := old_origin; let turtle = { turtle with pos = old_origin } in draw turtle canvas_root end end end | `BUTTON_PRESS ev -> if (GdkEvent.Button.button ev) = 3 then begin contextual_menu vertex ev end | `TWO_BUTTON_PRESS ev-> if (GdkEvent.Button.button ev) = 1 then begin if (Gdk.Convert.test_modifier `CONTROL (GdkEvent.Button.state ev)) then begin if ( !nb_selected =0) then begin select_all (); update_vertex vertex Focus end else begin unselect_all (); update_vertex vertex Focus end end else begin if (is_selected vertex) then update_vertex vertex Unselect else update_vertex vertex Select; end; refresh_draw (); end; | _ -> () end; true let set_vertex_event vertex = let item,ell,_ = H.find nodes vertex in ignore (item#connect#event (vertex_event vertex item ell)) let () = set_vertex_event_fun := set_vertex_event let set_canvas_event () = (* circle event *) ignore(canvas_root#parent#connect#event (circle_event)); (* vertex event *) G.iter_vertex set_vertex_event !graph (* treeview *) let add_columns ~(view : GTree.view) ~model = let renderer = GTree.cell_renderer_text [`XALIGN 0.] in let vc = GTree.view_column ~title:"Nodes" ~renderer:(renderer, ["text", Model.name]) () in ignore (view#append_column vc); vc#set_sizing `FIXED; vc#set_fixed_width 100; (* vc#set_resizable true;*) vc#set_sizing `AUTOSIZE; view#selection#connect#after#changed ~callback: begin fun () -> List.iter (fun p -> node_selection ~model p) view#selection#get_selected_rows; end let _ = window#connect#destroy~callback:GMain.Main.quit let treeview = GTree.view ~model:Model.model ~packing:sw#add () let () = treeview#set_rules_hint true let () = treeview#selection#set_mode `MULTIPLE let _ = add_columns ~view:treeview ~model:Model.model (* reset *) let reset_table_and_canvas () = let l = canvas_root#get_items in List.iter (fun v -> trace v#destroy ()) l; H2.clear intern_edges; H2.clear successor_edges; reset_display canvas_root; origine := start_point; nb_selected:=0 (* menu action functions *) (* choose a file to load or save to *) let ask_for_file (mode: [< `OPEN | `SAVE]) = let default_file d = function | None -> d | Some v -> v in let all_files () = let f = GFile.filter ~name:"All" () in f#add_pattern "*" ; f in let graph_filter () = GFile.filter ~name:"Fichier de graphes" ~patterns:[ "*.dot"; "*.gml" ] () in let dialog = begin match mode with | `OPEN -> let dialog = GWindow.file_chooser_dialog ~action: `OPEN ~title:"Open graph file" ~parent: window () in dialog#add_button_stock `CANCEL `CANCEL ; dialog#add_select_button_stock `OPEN `OPEN; dialog | `SAVE -> let dialog = GWindow.file_chooser_dialog ~action: `SAVE ~title: "Save graph as..." ~parent: window () in dialog#set_current_name "my_graph.dot"; dialog#add_button_stock `CANCEL `CANCEL ; dialog#add_select_button_stock `SAVE `SAVE; dialog end; in dialog#add_filter (graph_filter ()) ; dialog#add_filter (all_files ()) ; let f = match dialog#run () with | `OPEN -> default_file "<none>" dialog#filename | `SAVE -> default_file "my_graph.dot" dialog#filename | `DELETE_EVENT | `CANCEL -> "<none>" in dialog#destroy (); f (* menu action new graph *) let new_graph () = let alert_window = GWindow.message_dialog ~message:("Are you sure you want to start" ^" a new graph and discard all" ^" unsaved changes to :\n\n" ^"<tt>\t" ^(match !graph_name with | None -> "unamed" | Some name -> name) ^"</tt>") ~use_markup:true ~title:"New graph ?" ~message_type:`QUESTION ~buttons:GWindow.Buttons.yes_no ~parent:window ~resizable:false ~position:`CENTER_ON_PARENT () in begin match alert_window#run () with | `YES -> begin graph := G.create (); Model.reset(); reset_table_and_canvas (); graph_name := None; set_window_title () end | `DELETE_EVENT | `NO -> () end; alert_window#destroy () (* menu action open graph *) let open_graph () = let file = ask_for_file `OPEN in if file <> "<none>" then begin load_graph file; reset_table_and_canvas (); let turtle = make_turtle_origine () in draw turtle canvas_root; set_canvas_event () end (* menu action save graph as *) let save_graph_as () = let file = ask_for_file `SAVE in if file <> "<none>" then begin save_graph file; set_window_title () end (* menu action save graph *) let save_graph () = match !graph_name with | None -> () | Some name -> begin save_graph name; set_window_title () end (* menu action quit *) let quit () = let alert_window = GWindow.message_dialog ~message:("Are you sure you want to quit" ^" and discard all" ^" unsaved changes to :\n\n" ^"<tt>\t" ^(match !graph_name with | None -> "unamed" | Some name -> name) ^"</tt>") ~use_markup:true ~title:"Quit ?" ~message_type:`QUESTION ~buttons:GWindow.Buttons.yes_no ~parent:window ~resizable:false ~position:`CENTER_ON_PARENT () in begin match alert_window#run () with | `YES -> window#destroy () | `DELETE_EVENT | `NO -> () end (* menu action about *) let about () = let dialog = GWindow.about_dialog ~authors:["Ocamlgraph :"; " Sylvain Conchon"; " Jean-Christophe Filliatre"; " Julien Signoles"; ""; ed_name^" :"; " Vadon Benjamin"] ~comments:" Ocamlgraph: a generic graph library for OCaml" ~copyright:"Copyright (C) 2004-2007 Sylvain Conchon, Jean-Christophe Filliatre and Julien Signoles" ~license:" This software is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2, with the special exception on linking described in file LICENSE. This software 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." ~logo:(GdkPixbuf.from_file"ed_icon.xpm" ) ~name:ed_name ~version:"0.99" ~website:"/" ~parent:window ~title:"About" ~resizable:false ~position:`CENTER_ON_PARENT () in try ignore( dialog#run ()) with Not_found -> dialog#destroy () let handbook_text (view:GText.view) = let buffer = view#buffer in (* text's tags *) ignore (buffer#create_tag ~name:"annotation" [`LEFT_MARGIN 10; `RIGHT_MARGIN 10; `SIZE (7*Pango.scale)]); ignore (buffer#create_tag ~name:"center" [`JUSTIFICATION `CENTER]); ignore (buffer#create_tag ~name:"heading" [`UNDERLINE `SINGLE; `WEIGHT `BOLD; `SIZE (14*Pango.scale)]); ignore (buffer#create_tag ~name:"italic" [`LEFT_MARGIN 10; `RIGHT_MARGIN 10; `STYLE `ITALIC]); ignore (buffer#create_tag ~name:"item" [`LEFT_MARGIN 20; `RIGHT_MARGIN 10]); ignore (buffer#create_tag ~name:"subsection" [`LEFT_MARGIN 10; `RIGHT_MARGIN 10]); ignore (buffer#create_tag ~name:"title" [`WEIGHT `BOLD; `SIZE (17*Pango.scale);`JUSTIFICATION `CENTER]); ignore (buffer#create_tag ~name:"word_wrap" [`WRAP_MODE `WORD; `EDITABLE false]); let iter = buffer#get_iter_at_char 0 in (* title *) buffer#insert ~iter ~tag_names:["title"] (ed_name^" Handbook\n"); (* editor's icon *) let image_anchor = buffer#create_child_anchor iter in let image = GMisc.image ~pixbuf:(GdkPixbuf.from_file_at_size "ed_icon.xpm" ~width:70 ~height:70) () in view#add_child_at_anchor image#coerce image_anchor; buffer#insert ~iter "\n\n\n"; let start,stop = buffer#bounds in buffer#apply_tag_by_name "center" ~start ~stop ; (* buffer's text *) buffer#insert ~iter ~tag_names:["heading"] "First words\n"; buffer#insert ~iter ~tag_names:["subsection"] ("\tFirst of all, you have to know this is an experimental application. " ^"If you find a bug, please report it to developpers. " ^"This application have only basic fonctionnalities on graphs, so if you want a new fonctionnality, send it too.\n"); buffer#insert ~iter ~tag_names:["subsection"] (ed_name^" represents a graph in hyperbolic geometry, and precisely in Poincaré's disk representation.\n\n" ^ed_name^" is organized in four parts :\n"); buffer#insert ~iter ~tag_names:["item"] "- a menu bar\n"; buffer#insert ~iter ~tag_names:["item"] "- a vertices list, on the left side\n"; buffer#insert ~iter ~tag_names:["item"] "- the Poincaré's disk\n"; buffer#insert ~iter ~tag_names:["item"] "- and an associated contextual menu\n\n"; buffer#insert ~iter ~tag_names:["heading"] "Menu bar\n"; buffer#insert ~iter ~tag_names:["subsection"] "\t It gives standard fonctionnalities. You can create a new graph, open and save graphs from/to Gml and Dot formats.\n"; buffer#insert ~iter ~tag_names:["italic"] "Don't forget to save your changes before create or load a new graph.\n\n"; buffer#insert ~iter ~tag_names:["heading"] "Vertices list\n"; buffer#insert ~iter ~tag_names:["subsection"] "\t You can change root of graph drawing by clicking on a vertex name. If you expand one, you can see successors of it.\n\n"; buffer#insert ~iter ~tag_names:["heading"] "Poincaré's disk\n"; buffer#insert ~iter ~tag_names:["subsection"] ("\t The graph is displayed in a disk. You can drag a vertex."); buffer#insert ~iter ~tag_names:["annotation"] "[1]\n"; buffer#insert ~iter ~tag_names:["subsection"] ("By double-clicking on a node, you add/remove it to selection.\nWith a <Ctrl>+double-click you select all nodes, or unselect all (if one or more node is already selected)" ^"\n\n"); buffer#insert ~iter ~tag_names:["heading"] "Contextual menu\n"; buffer#insert ~iter ~tag_names:["subsection"] ("\t This is the main way (and the only for the moment) to edit a graph. There are two differents menus, but it is transparent for your use.\n" ^"The first is only composed by an adding node menu, and appear when you click in the disk.\n" ^"The second menu appears when you click on a vertex." ^" You can change root of graph drawing, add a successor or remove focused vertex." ^" Rest of menu depends of selected nodes. You can add or remove an edge with one of selected, or with all." ^"\n\n"); buffer#insert ~iter ~tag_names:["annotation"] "[1] :"; buffer#insert ~iter ~tag_names:["subsection"] " a bug still remains, you can't drag root to much on the right-side, but on the left-side it is infinite"; let start,stop = buffer#bounds in buffer#apply_tag_by_name "word_wrap" ~start ~stop ; () (* menu action handbook *) let handbook () = let dialog = GWindow.dialog ~width:450 ~height:450 ~title:"Handbook" () in let view = GText.view () in let sw = GBin.scrolled_window ~packing:dialog#vbox#add () in sw#add view#coerce; handbook_text view; dialog#add_button_stock `CLOSE `CLOSE; match dialog#run () with | `CLOSE | `DELETE_EVENT -> dialog#destroy () (* menu bar, based on ui_manager *) let ui_info = "<ui>\ <menubar name='MenuBar'>\ <menu action='FileMenu'>\ <menuitem action='New graph'/>\ <menuitem action='Open graph'/>\ <menuitem action='Save graph'/>\ <menuitem action='Save graph as...'/>\ <separator/>\ <menuitem action='Quit'/>\ </menu>\ <menu action='HelpMenu'>\ <menuitem action='About'/>\ <menuitem action='Handbook'/>\ </menu>\ </menubar>\ </ui>" (* choose right menu action *) let activ_action ac = let name = ac#name in match name with | "New graph" -> new_graph () | "Open graph"-> open_graph () | "Save graph" -> save_graph () | "Save graph as..." -> save_graph_as () | "Quit" -> quit () | "About" -> about () | "Handbook" -> handbook () | _ -> Format.eprintf "%s menu is not yet implemented @." name let setup_ui window = let add_action = GAction.add_action in let actions = GAction.action_group ~name:"Actions" () in GAction.add_actions actions [ add_action "FileMenu" ~label:"_File" ; add_action "HelpMenu" ~label:"_Help" ; add_action "New graph" ~stock:`NEW ~tooltip:"Create a new graph" ~callback:activ_action ; add_action "Open graph" ~stock:`OPEN ~tooltip:"Open a graph file" ~callback:activ_action ; add_action "Save graph" ~stock:`SAVE ~tooltip:"Save current graph" ~callback:activ_action ; add_action "Save graph as..." ~stock:`SAVE_AS ~accel:"<Control><Shift>S" ~tooltip:"Save current graph to specified file" ~callback:activ_action ; add_action "Quit" ~stock:`QUIT ~tooltip:"Quit" ~callback:activ_action ; add_action "About" ~label:"_About" ~tooltip:"Who build this" ~callback:activ_action; add_action "Handbook" ~label:"_Handbook" ~accel:"<Control>H" ~tooltip:"How to.." ~callback:activ_action; ] ; let ui_m = GAction.ui_manager () in ui_m#insert_action_group actions 0 ; window#add_accel_group ui_m#get_accel_group ; ignore (ui_m#add_ui_from_string ui_info) ; menu_bar_box#pack (ui_m#get_widget "/MenuBar") let () = reset_table_and_canvas (); draw (make_turtle_origine ()) canvas_root; set_canvas_event (); canvas#set_scroll_region 0. 0. w h ; setup_ui window; ignore (window#show ()); GMain.Main.main ()
null
https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/external/ocamlgraph/editor/ed_main.ml
ocaml
************************************************************************ This software is free software; you can redistribute it and/or described in file LICENSE. This software 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. ************************************************************************ Model for the treeview on the left Main GTK window usual function to change window title menu bar treeview on the left, canvas on the right unit circle as root of graph drawing current root used for drawing refresh rate graph drawing usual function ref, for vertex event type to select nature of modification add a vertex with no successor entry's callback new vertex add successor node to selected node new vertex new edge redraw add all edges as possible from current vertex to selected vertices change root vertex menu successor remove vertex edge menu add menu remove menu unit circle callback event for each vertex of canvas let vertex_info = G.V.label vertex in circle event vertex event treeview vc#set_resizable true; reset menu action functions choose a file to load or save to menu action new graph menu action open graph menu action save graph as menu action save graph menu action quit menu action about text's tags title editor's icon buffer's text menu action handbook menu bar, based on ui_manager choose right menu action
: a generic graph library for OCaml Copyright ( C ) 2004 - 2007 , and modify it under the terms of the GNU Library General Public License version 2 , with the special exception on linking This file is a contribution of open Format open Graph open Ed_hyper open Ed_graph open Ed_display open Ed_draw let debug = ref false let trace f x = try f x with e -> eprintf "TRACE: %s@." (Printexc.to_string e); raise e let _ = GMain.Main.init () module Model = struct open Gobject.Data let cols = new GTree.column_list let name = cols#add string let vertex = cols#add caml let model = GTree.tree_store cols let rows = H.create 97 let find_row v = try H.find rows v with Not_found -> Format.eprintf "anomaly: no model row for %s@." (string_of_label v); raise Not_found let add_vertex v = let row = model#append () in model#set ~row ~column:name (string_of_label v); model#set ~row ~column:vertex v; H.add rows v row; row let add_edge_1 row_v w = let row = model#append ~parent:row_v () in model#set ~row ~column:name (string_of_label w); model#set ~row ~column:vertex w let add_edge v w = let row_v = find_row v in add_edge_1 row_v w; if not G.is_directed then let row_w = find_row w in add_edge_1 row_w v let find_children row_v w = let nb_child = model#iter_n_children (Some row_v) in let rec find n = let child = model#iter_children ~nth:(n-1) (Some row_v) in let child_vertex = model#get ~row:child ~column:vertex in match n with | 0 -> raise Not_found | n -> if (G.V.equal child_vertex w) then child else find (n-1) in find nb_child let remove_edge_1 row_v w = ignore (model#remove (find_children row_v w)) let remove_edge v w = let row_v = find_row v in remove_edge_1 row_v w; if not G.is_directed then let row_w = find_row w in remove_edge_1 row_w v let remove_vertex vertex = G.iter_succ (fun w -> remove_edge w vertex) !graph vertex; let row = find_row vertex in model#remove row let reset () = H.clear rows; model#clear (); G.iter_vertex (fun v -> let row = add_vertex v in G.iter_succ (add_edge_1 row) !graph v) !graph end let () = Model.reset () open GtkTree let ed_name = "Ocamlgraph's Editor" let window = GWindow.window ~border_width: 10 ~position: `CENTER () let set_window_title () = window#set_title (match !graph_name with | None -> ed_name | Some name -> ed_name^" : "^(Filename.chop_extension (Filename.basename name))) let v_box = GPack.vbox ~homogeneous:false ~spacing:30 ~packing:window#add () let menu_bar_box = GPack.vbox ~packing:v_box#pack () let h_box = GPack.hbox ~homogeneous:false ~spacing:30 ~packing:v_box#add () let sw = GBin.scrolled_window ~shadow_type:`ETCHED_IN ~hpolicy:`NEVER ~vpolicy:`AUTOMATIC ~packing:h_box#add () let canvas = GnoCanvas.canvas ~aa:!aa ~width:(truncate w) ~height:(truncate h) ~packing:h_box#add () let canvas_root = let circle_group = GnoCanvas.group ~x:300.0 ~y:300.0 canvas#root in circle_group#lower_to_bottom (); let w2 = 2. in let circle = GnoCanvas.ellipse ~props:[ `X1 (-.w/.2. +.w2); `Y1 (-.h/.2. +.w2); `X2 (w/.2. -.w2) ; `Y2 ( h/.2. -.w2) ; `FILL_COLOR color_circle ; `OUTLINE_COLOR "black" ; `WIDTH_PIXELS (truncate w2) ] circle_group in circle_group#lower_to_bottom (); circle#show(); let graph_root = GnoCanvas.group ~x:(-.300.0) ~y:(-.300.0) circle_group in graph_root#raise_to_top (); set_window_title (); graph_root let root = ref (choose_root ()) let load_graph f = Ed_graph.load_graph f; Model.reset (); set_window_title (); root := choose_root () let refresh = ref 0 let do_refresh () = !refresh mod !refresh_rate = 0 let draw tortue canvas = match !root with | None -> () | Some root -> Ed_draw.draw_graph root tortue; Ed_display.draw_graph root canvas; if do_refresh () then canvas_root#canvas#update_now () let refresh_draw () = refresh := 0; let tor = make_turtle !origine 0.0 in draw tor canvas_root let refresh_display () = Ed_display.draw_graph !root canvas_root let root_change vertex ()= root := vertex; origine := start_point; let turtle = make_turtle_origine () in draw turtle canvas_root let node_selection ~(model : GTree.tree_store) path = let row = model#get_iter path in let vertex = model#get ~row ~column: Model.vertex in root_change (Some vertex) () let set_vertex_event_fun = ref (fun _ -> ()) type modification = Add | Remove let add_node () = let window = GWindow.window ~title: "Choose vertex label" ~width: 300 ~height: 50 ~position: `MOUSE () in let vbox = GPack.vbox ~packing: window#add () in let entry = GEdit.entry ~max_length: 50 ~packing: vbox#add () in entry#set_text "Label"; entry#select_region ~start:0 ~stop:entry#text_length; two check buttons allowing to add node to selection list and to choose this node as root let hbox = GPack.hbox ~packing: vbox#add () in let is_in_selection = ref false in let in_selection = GButton.check_button ~label: "Add to selection" ~active:!is_in_selection ~packing: hbox#add () in ignore (in_selection#connect#toggled ~callback:(fun () ->is_in_selection := in_selection#active )); let is_as_root = ref ((G.nb_vertex !graph)=0) in let as_root = GButton.check_button ~label:"Choose as root" ~active:!is_as_root ~packing:hbox#add () in ignore (as_root#connect#toggled ~callback:(fun () ->is_as_root := as_root#active )); window#show (); ignore( entry#connect#activate ~callback: (fun () -> let text = entry#text in window#destroy (); let vertex = G.V.create (make_node_info text) in G.add_vertex !graph vertex ; ignore (Model.add_vertex vertex); Ed_display.add_node canvas_root vertex; !set_vertex_event_fun vertex; if !is_as_root then root_change (Some vertex) () ; if !is_in_selection then update_vertex vertex Select; let tor = make_turtle !origine 0.0 in draw tor canvas_root)) add an edge between n1 and n2 , add link in column and re - draw let add_edge n1 n2 ()= if not (edge n1 n2) then begin G.add_edge_e !graph (G.E.create n1 (make_edge_info ()) n2); Model.add_edge n1 n2; let tor = make_turtle !origine 0.0 in draw tor canvas_root; end let add_edge_no_refresh n1 n2 ()= if not (edge n1 n2) then begin G.add_edge_e !graph (G.E.create n1 (make_edge_info ()) n2); Model.add_edge n1 n2 end remove an edge between n1 and n2 , add un - link in column and re - draw let remove_edge n1 n2 ()= if (edge n1 n2) then begin G.remove_edge !graph n1 n2; Model.remove_edge n1 n2; begin try let _,n = H2.find intern_edges (n1,n2) in n#destroy (); H2.remove intern_edges (n1,n2) with Not_found -> () end; begin try let _,n = H2.find intern_edges (n2,n1) in n#destroy (); H2.remove intern_edges (n2,n1) with Not_found -> () end; begin try let n = H2.find successor_edges (n1,n2) in n#destroy (); H2.remove successor_edges (n1,n2) with Not_found -> () end; begin try let n = H2.find successor_edges (n2,n1) in n#destroy (); H2.remove successor_edges (n2,n1) with Not_found -> () end; let tor = make_turtle !origine 0.0 in draw tor canvas_root; end let remove_edge_no_refresh n1 n2 ()= if (edge n1 n2) then begin G.remove_edge !graph n1 n2; Model.remove_edge n1 n2 end let add_successor node () = let window = GWindow.window ~title: "Choose label name" ~width: 300 ~height: 50 ~position: `MOUSE () in let vbox = GPack.vbox ~packing: window#add () in let entry = GEdit.entry ~max_length: 50 ~packing: vbox#add () in entry#set_text "Label"; entry#select_region ~start:0 ~stop:entry#text_length; window#show (); ignore (entry#connect#activate ~callback:(fun () -> let text = entry#text in window#destroy (); let vertex = G.V.create (make_node_info text) in G.add_vertex !graph vertex ; ignore (Model.add_vertex vertex); Ed_display.add_node canvas_root vertex; !set_vertex_event_fun vertex; G.add_edge_e !graph (G.E.create node (make_edge_info()) vertex); Model.add_edge node vertex; let tor = make_turtle !origine 0.0 in draw tor canvas_root ) ) let remove_vertex vertex () = G.iter_succ (fun w -> begin try let _,n = H2.find intern_edges (vertex,w) in n#destroy (); H2.remove intern_edges (vertex,w) with Not_found -> () end; begin try let _,n = H2.find intern_edges (w,vertex) in n#destroy (); H2.remove intern_edges (w,vertex) with Not_found -> () end; begin try let n = H2.find successor_edges (vertex,w) in n#destroy (); H2.remove successor_edges (vertex,w) with Not_found -> () end; begin try let n = H2.find successor_edges (w,vertex) in n#destroy (); H2.remove successor_edges (w,vertex) with Not_found -> () end; ) !graph vertex; let (n,_,_) = H.find nodes vertex in n#destroy (); H.remove nodes vertex; ignore (Model.remove_vertex vertex); G.remove_vertex !graph vertex; begin match !root with | None -> () | Some root_v -> if (G.V.equal root_v vertex) then root := choose_root(); end; refresh_draw () let sub_edge_to modif_type vertex list = let ll = List.length list in let nb_sub_menu = (ll - 1)/10 + 1 in let nb_edge = ll / nb_sub_menu -1 in let menu = new GMenu.factory (GMenu.menu()) in let sub_menu =ref (new GMenu.factory (GMenu.menu())) in let add_menu_edge vertex v2 = if not (G.V.equal v2 vertex) then begin match modif_type with | Add -> ignore((!sub_menu)#add_item (string_of_label v2) ~callback:( add_edge v2 vertex)); | Remove -> ignore((!sub_menu)#add_item (string_of_label v2) ~callback:(remove_edge v2 vertex)); end; in let rec make_sub_menu vertex list nb = match list with | [] -> () | v::list -> match nb with | 0 -> begin sub_menu :=new GMenu.factory (GMenu.menu()) ; add_menu_edge vertex v; let string = string_of_label v in ignore (menu#add_item (String.sub string 0 (min (String.length string) 3)^"...") ~submenu: !sub_menu#menu); make_sub_menu vertex list (nb+1); end | n when n= nb_edge-> begin add_menu_edge vertex v; make_sub_menu vertex list 0 end | _ -> begin add_menu_edge vertex v; make_sub_menu vertex list (nb+1) end in if ll > 10 then begin make_sub_menu vertex list 0; menu end else begin let rec make_sub_bis list = match list with | [] -> (); | v::list ->add_menu_edge vertex v; make_sub_bis list in make_sub_bis list; !sub_menu end let edge_to modif_type vertex list = add an edge between current vertex and one of selected vertex sub_edge_to modif_type vertex list let all_edges (edge_menu :#GMenu.menu GMenu.factory) vertex list = begin let add_all_edge vertex list () = List.iter (fun v -> if not (G.V.equal v vertex) then add_edge_no_refresh v vertex() ) list ; refresh := 0; let tor = make_turtle !origine 0.0 in draw tor canvas_root in ignore (edge_menu#add_item "Add all edges" ~callback:( add_all_edge vertex list)) end let contextual_menu vertex ev = let menu = new GMenu.factory (GMenu.menu ()) in ignore (menu#add_item "As root" ~callback:(root_change (Some vertex))); let vertex_menu = new GMenu.factory (GMenu.menu ()) in begin ignore (vertex_menu#add_item "Add successor" ~callback:(add_successor vertex)); ignore (vertex_menu#add_separator ()); ignore(vertex_menu#add_item "Remove vertex" ~callback:(remove_vertex vertex)); end; ignore(menu#add_item "Vertex ops" ~submenu: vertex_menu#menu); begin let add_list = selected_list (ADD_FROM vertex) in let rem_list = selected_list (REMOVE_FROM vertex) in let al =List.length add_list in let rl =List.length rem_list in let isel = is_selected vertex in let menu_bool = ref false in let edge_menu = new GMenu.factory (GMenu.menu ()) in begin if isel && al=2 || not isel && al=1 then begin ignore (edge_menu#add_item "Add edge with" ~submenu: (edge_to Add vertex add_list)#menu); menu_bool := true; end else begin if isel && al>2 || not isel && al>1 then begin ignore (edge_menu#add_item "Add edge with" ~submenu: (edge_to Add vertex add_list)#menu); all_edges edge_menu vertex add_list; menu_bool := true; end end; if isel && rl>=2 || not isel && rl>=1 then begin if !menu_bool then ignore (edge_menu#add_separator ()); ignore (edge_menu#add_item "Remove edge with" ~submenu: (edge_to Remove vertex rem_list)#menu); menu_bool := true; end; if !menu_bool then ignore(menu#add_item "Edge ops" ~submenu: edge_menu#menu); end; end; menu#menu#popup ~button:3 ~time:(GdkEvent.Button.time ev) let circle_event ev = begin match ev with | `BUTTON_PRESS ev -> if (GdkEvent.Button.button ev) = 3 then begin let menu = new GMenu.factory (GMenu.menu ()) in ignore (menu#add_item " Add node" ~callback:(add_node)); menu#menu#popup ~button:3 ~time:(GdkEvent.Button.time ev) end | _ ->() end; true let vertex_event vertex item ellispe ev = begin match ev with | `ENTER_NOTIFY _ -> item#grab_focus (); update_vertex vertex Focus; refresh_display () | `LEAVE_NOTIFY ev -> if not (Gdk.Convert.test_modifier `BUTTON1 (GdkEvent.Crossing.state ev)) then begin update_vertex vertex Unfocus; refresh_display () end | `BUTTON_RELEASE ev -> ellispe#parent#ungrab (GdkEvent.Button.time ev); | `MOTION_NOTIFY ev -> incr refresh; let state = GdkEvent.Motion.state ev in if Gdk.Convert.test_modifier `BUTTON1 state then begin let curs = Gdk.Cursor.create `FLEUR in ellispe#parent#grab [`POINTER_MOTION; `BUTTON_RELEASE] curs (GdkEvent.Button.time ev); if do_refresh () then begin let old_origin = !origine in let turtle = motion_turtle ellispe ev in if hspace_dist_sqr turtle <= rlimit_sqr then begin draw turtle canvas_root end else begin origine := old_origin; let turtle = { turtle with pos = old_origin } in draw turtle canvas_root end end end | `BUTTON_PRESS ev -> if (GdkEvent.Button.button ev) = 3 then begin contextual_menu vertex ev end | `TWO_BUTTON_PRESS ev-> if (GdkEvent.Button.button ev) = 1 then begin if (Gdk.Convert.test_modifier `CONTROL (GdkEvent.Button.state ev)) then begin if ( !nb_selected =0) then begin select_all (); update_vertex vertex Focus end else begin unselect_all (); update_vertex vertex Focus end end else begin if (is_selected vertex) then update_vertex vertex Unselect else update_vertex vertex Select; end; refresh_draw (); end; | _ -> () end; true let set_vertex_event vertex = let item,ell,_ = H.find nodes vertex in ignore (item#connect#event (vertex_event vertex item ell)) let () = set_vertex_event_fun := set_vertex_event let set_canvas_event () = ignore(canvas_root#parent#connect#event (circle_event)); G.iter_vertex set_vertex_event !graph let add_columns ~(view : GTree.view) ~model = let renderer = GTree.cell_renderer_text [`XALIGN 0.] in let vc = GTree.view_column ~title:"Nodes" ~renderer:(renderer, ["text", Model.name]) () in ignore (view#append_column vc); vc#set_sizing `FIXED; vc#set_fixed_width 100; vc#set_sizing `AUTOSIZE; view#selection#connect#after#changed ~callback: begin fun () -> List.iter (fun p -> node_selection ~model p) view#selection#get_selected_rows; end let _ = window#connect#destroy~callback:GMain.Main.quit let treeview = GTree.view ~model:Model.model ~packing:sw#add () let () = treeview#set_rules_hint true let () = treeview#selection#set_mode `MULTIPLE let _ = add_columns ~view:treeview ~model:Model.model let reset_table_and_canvas () = let l = canvas_root#get_items in List.iter (fun v -> trace v#destroy ()) l; H2.clear intern_edges; H2.clear successor_edges; reset_display canvas_root; origine := start_point; nb_selected:=0 let ask_for_file (mode: [< `OPEN | `SAVE]) = let default_file d = function | None -> d | Some v -> v in let all_files () = let f = GFile.filter ~name:"All" () in f#add_pattern "*" ; f in let graph_filter () = GFile.filter ~name:"Fichier de graphes" ~patterns:[ "*.dot"; "*.gml" ] () in let dialog = begin match mode with | `OPEN -> let dialog = GWindow.file_chooser_dialog ~action: `OPEN ~title:"Open graph file" ~parent: window () in dialog#add_button_stock `CANCEL `CANCEL ; dialog#add_select_button_stock `OPEN `OPEN; dialog | `SAVE -> let dialog = GWindow.file_chooser_dialog ~action: `SAVE ~title: "Save graph as..." ~parent: window () in dialog#set_current_name "my_graph.dot"; dialog#add_button_stock `CANCEL `CANCEL ; dialog#add_select_button_stock `SAVE `SAVE; dialog end; in dialog#add_filter (graph_filter ()) ; dialog#add_filter (all_files ()) ; let f = match dialog#run () with | `OPEN -> default_file "<none>" dialog#filename | `SAVE -> default_file "my_graph.dot" dialog#filename | `DELETE_EVENT | `CANCEL -> "<none>" in dialog#destroy (); f let new_graph () = let alert_window = GWindow.message_dialog ~message:("Are you sure you want to start" ^" a new graph and discard all" ^" unsaved changes to :\n\n" ^"<tt>\t" ^(match !graph_name with | None -> "unamed" | Some name -> name) ^"</tt>") ~use_markup:true ~title:"New graph ?" ~message_type:`QUESTION ~buttons:GWindow.Buttons.yes_no ~parent:window ~resizable:false ~position:`CENTER_ON_PARENT () in begin match alert_window#run () with | `YES -> begin graph := G.create (); Model.reset(); reset_table_and_canvas (); graph_name := None; set_window_title () end | `DELETE_EVENT | `NO -> () end; alert_window#destroy () let open_graph () = let file = ask_for_file `OPEN in if file <> "<none>" then begin load_graph file; reset_table_and_canvas (); let turtle = make_turtle_origine () in draw turtle canvas_root; set_canvas_event () end let save_graph_as () = let file = ask_for_file `SAVE in if file <> "<none>" then begin save_graph file; set_window_title () end let save_graph () = match !graph_name with | None -> () | Some name -> begin save_graph name; set_window_title () end let quit () = let alert_window = GWindow.message_dialog ~message:("Are you sure you want to quit" ^" and discard all" ^" unsaved changes to :\n\n" ^"<tt>\t" ^(match !graph_name with | None -> "unamed" | Some name -> name) ^"</tt>") ~use_markup:true ~title:"Quit ?" ~message_type:`QUESTION ~buttons:GWindow.Buttons.yes_no ~parent:window ~resizable:false ~position:`CENTER_ON_PARENT () in begin match alert_window#run () with | `YES -> window#destroy () | `DELETE_EVENT | `NO -> () end let about () = let dialog = GWindow.about_dialog ~authors:["Ocamlgraph :"; " Sylvain Conchon"; " Jean-Christophe Filliatre"; " Julien Signoles"; ""; ed_name^" :"; " Vadon Benjamin"] ~comments:" Ocamlgraph: a generic graph library for OCaml" ~copyright:"Copyright (C) 2004-2007 Sylvain Conchon, Jean-Christophe Filliatre and Julien Signoles" ~license:" This software is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2, with the special exception on linking described in file LICENSE. This software 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." ~logo:(GdkPixbuf.from_file"ed_icon.xpm" ) ~name:ed_name ~version:"0.99" ~website:"/" ~parent:window ~title:"About" ~resizable:false ~position:`CENTER_ON_PARENT () in try ignore( dialog#run ()) with Not_found -> dialog#destroy () let handbook_text (view:GText.view) = let buffer = view#buffer in ignore (buffer#create_tag ~name:"annotation" [`LEFT_MARGIN 10; `RIGHT_MARGIN 10; `SIZE (7*Pango.scale)]); ignore (buffer#create_tag ~name:"center" [`JUSTIFICATION `CENTER]); ignore (buffer#create_tag ~name:"heading" [`UNDERLINE `SINGLE; `WEIGHT `BOLD; `SIZE (14*Pango.scale)]); ignore (buffer#create_tag ~name:"italic" [`LEFT_MARGIN 10; `RIGHT_MARGIN 10; `STYLE `ITALIC]); ignore (buffer#create_tag ~name:"item" [`LEFT_MARGIN 20; `RIGHT_MARGIN 10]); ignore (buffer#create_tag ~name:"subsection" [`LEFT_MARGIN 10; `RIGHT_MARGIN 10]); ignore (buffer#create_tag ~name:"title" [`WEIGHT `BOLD; `SIZE (17*Pango.scale);`JUSTIFICATION `CENTER]); ignore (buffer#create_tag ~name:"word_wrap" [`WRAP_MODE `WORD; `EDITABLE false]); let iter = buffer#get_iter_at_char 0 in buffer#insert ~iter ~tag_names:["title"] (ed_name^" Handbook\n"); let image_anchor = buffer#create_child_anchor iter in let image = GMisc.image ~pixbuf:(GdkPixbuf.from_file_at_size "ed_icon.xpm" ~width:70 ~height:70) () in view#add_child_at_anchor image#coerce image_anchor; buffer#insert ~iter "\n\n\n"; let start,stop = buffer#bounds in buffer#apply_tag_by_name "center" ~start ~stop ; buffer#insert ~iter ~tag_names:["heading"] "First words\n"; buffer#insert ~iter ~tag_names:["subsection"] ("\tFirst of all, you have to know this is an experimental application. " ^"If you find a bug, please report it to developpers. " ^"This application have only basic fonctionnalities on graphs, so if you want a new fonctionnality, send it too.\n"); buffer#insert ~iter ~tag_names:["subsection"] (ed_name^" represents a graph in hyperbolic geometry, and precisely in Poincaré's disk representation.\n\n" ^ed_name^" is organized in four parts :\n"); buffer#insert ~iter ~tag_names:["item"] "- a menu bar\n"; buffer#insert ~iter ~tag_names:["item"] "- a vertices list, on the left side\n"; buffer#insert ~iter ~tag_names:["item"] "- the Poincaré's disk\n"; buffer#insert ~iter ~tag_names:["item"] "- and an associated contextual menu\n\n"; buffer#insert ~iter ~tag_names:["heading"] "Menu bar\n"; buffer#insert ~iter ~tag_names:["subsection"] "\t It gives standard fonctionnalities. You can create a new graph, open and save graphs from/to Gml and Dot formats.\n"; buffer#insert ~iter ~tag_names:["italic"] "Don't forget to save your changes before create or load a new graph.\n\n"; buffer#insert ~iter ~tag_names:["heading"] "Vertices list\n"; buffer#insert ~iter ~tag_names:["subsection"] "\t You can change root of graph drawing by clicking on a vertex name. If you expand one, you can see successors of it.\n\n"; buffer#insert ~iter ~tag_names:["heading"] "Poincaré's disk\n"; buffer#insert ~iter ~tag_names:["subsection"] ("\t The graph is displayed in a disk. You can drag a vertex."); buffer#insert ~iter ~tag_names:["annotation"] "[1]\n"; buffer#insert ~iter ~tag_names:["subsection"] ("By double-clicking on a node, you add/remove it to selection.\nWith a <Ctrl>+double-click you select all nodes, or unselect all (if one or more node is already selected)" ^"\n\n"); buffer#insert ~iter ~tag_names:["heading"] "Contextual menu\n"; buffer#insert ~iter ~tag_names:["subsection"] ("\t This is the main way (and the only for the moment) to edit a graph. There are two differents menus, but it is transparent for your use.\n" ^"The first is only composed by an adding node menu, and appear when you click in the disk.\n" ^"The second menu appears when you click on a vertex." ^" You can change root of graph drawing, add a successor or remove focused vertex." ^" Rest of menu depends of selected nodes. You can add or remove an edge with one of selected, or with all." ^"\n\n"); buffer#insert ~iter ~tag_names:["annotation"] "[1] :"; buffer#insert ~iter ~tag_names:["subsection"] " a bug still remains, you can't drag root to much on the right-side, but on the left-side it is infinite"; let start,stop = buffer#bounds in buffer#apply_tag_by_name "word_wrap" ~start ~stop ; () let handbook () = let dialog = GWindow.dialog ~width:450 ~height:450 ~title:"Handbook" () in let view = GText.view () in let sw = GBin.scrolled_window ~packing:dialog#vbox#add () in sw#add view#coerce; handbook_text view; dialog#add_button_stock `CLOSE `CLOSE; match dialog#run () with | `CLOSE | `DELETE_EVENT -> dialog#destroy () let ui_info = "<ui>\ <menubar name='MenuBar'>\ <menu action='FileMenu'>\ <menuitem action='New graph'/>\ <menuitem action='Open graph'/>\ <menuitem action='Save graph'/>\ <menuitem action='Save graph as...'/>\ <separator/>\ <menuitem action='Quit'/>\ </menu>\ <menu action='HelpMenu'>\ <menuitem action='About'/>\ <menuitem action='Handbook'/>\ </menu>\ </menubar>\ </ui>" let activ_action ac = let name = ac#name in match name with | "New graph" -> new_graph () | "Open graph"-> open_graph () | "Save graph" -> save_graph () | "Save graph as..." -> save_graph_as () | "Quit" -> quit () | "About" -> about () | "Handbook" -> handbook () | _ -> Format.eprintf "%s menu is not yet implemented @." name let setup_ui window = let add_action = GAction.add_action in let actions = GAction.action_group ~name:"Actions" () in GAction.add_actions actions [ add_action "FileMenu" ~label:"_File" ; add_action "HelpMenu" ~label:"_Help" ; add_action "New graph" ~stock:`NEW ~tooltip:"Create a new graph" ~callback:activ_action ; add_action "Open graph" ~stock:`OPEN ~tooltip:"Open a graph file" ~callback:activ_action ; add_action "Save graph" ~stock:`SAVE ~tooltip:"Save current graph" ~callback:activ_action ; add_action "Save graph as..." ~stock:`SAVE_AS ~accel:"<Control><Shift>S" ~tooltip:"Save current graph to specified file" ~callback:activ_action ; add_action "Quit" ~stock:`QUIT ~tooltip:"Quit" ~callback:activ_action ; add_action "About" ~label:"_About" ~tooltip:"Who build this" ~callback:activ_action; add_action "Handbook" ~label:"_Handbook" ~accel:"<Control>H" ~tooltip:"How to.." ~callback:activ_action; ] ; let ui_m = GAction.ui_manager () in ui_m#insert_action_group actions 0 ; window#add_accel_group ui_m#get_accel_group ; ignore (ui_m#add_ui_from_string ui_info) ; menu_bar_box#pack (ui_m#get_widget "/MenuBar") let () = reset_table_and_canvas (); draw (make_turtle_origine ()) canvas_root; set_canvas_event (); canvas#set_scroll_region 0. 0. w h ; setup_ui window; ignore (window#show ()); GMain.Main.main ()
19c82510ed86679dc8ec59162d7db0ac133c3010425e4f213c6bbe3087f82d33
m0cchi/cl-slack
channels.lisp
(in-package :cl-slack.channels) (defmethod archive ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.archive" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod create ((client cl-slack.core:slack-client) (name string) (optionals cl:list)) (cl-slack.core:send "channels.create" (format nil "?token=~A&name=~A~A" (cl-slack.core:token client) name (cl-slack.core:to-param optionals)))) (defmethod info ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.info" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod invite ((client cl-slack.core:slack-client) (channel string) (user string)) (cl-slack.core:send "channels.invite" (format nil "?token=~A&channel=~A&user=~A" (cl-slack.core:token client) channel user))) (defmethod join ((client cl-slack.core:slack-client) (name string) (optionals cl:list)) (cl-slack.core:send "channels.join" (format nil "?token=~A&name=~A~A" (cl-slack.core:token client) name (cl-slack.core:to-param optionals)))) (defmethod kick ((client cl-slack.core:slack-client) (channel string) (user string)) (cl-slack.core:send "channels.kick" (format nil "?token=~A&channel=~A&user=~A" (cl-slack.core:token client) channel user))) (defmethod leave ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.leave" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod mark ((client cl-slack.core:slack-client) (channel string) (ts string)) (cl-slack.core:send "channels.mark" (format nil "?token=~A&channel=~A&ts=~A" (cl-slack.core:token client) channel ts))) (defmethod rename ((client cl-slack.core:slack-client) (channel string) (name string) (optionals cl:list)) (cl-slack.core:send "channels.rename" (format nil "?token=~A&channel=~A&name=~A~A" (cl-slack.core:token client) channel name (cl-slack.core:to-param optionals)))) (defmethod replies ((client cl-slack.core:slack-client) (channel string) (thread-ts string)) (cl-slack.core:send "channels.replies" (format nil "?token=~A&channel=~A&thread_ts=~A" (cl-slack.core:token client) channel thread-ts))) (defmethod set-purpose ((client cl-slack.core:slack-client) (channel string) (purpose string)) (cl-slack.core:send "channels.setPurpose" (format nil "?token=~A&channel=~A&purpose=~A" (cl-slack.core:token client) channel purpose))) (defmethod set-topic ((client cl-slack.core:slack-client) (channel string) (topic string)) (cl-slack.core:send "channels.setTopic" (format nil "?token=~A&channel=~A&topic=~A" (cl-slack.core:token client) channel topic))) (defmethod unarchive ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.unarchive" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod history ((client cl-slack.core:slack-client) (channel string) (optionals cl:list)) (cl-slack.core:send "channels.history" (format nil "?token=~A&channel=~A~A" (cl-slack.core:token client) channel (cl-slack.core:to-param optionals)))) (defmethod list ((client cl-slack.core:slack-client) (optionals cl:list)) (cl-slack.core:send "channels.list" (format nil "?token=~A~A" (cl-slack.core:token client) (cl-slack.core:to-param optionals))))
null
https://raw.githubusercontent.com/m0cchi/cl-slack/019ecb3e9a1605a8671fab85b4e564a257f76a04/src/channels.lisp
lisp
(in-package :cl-slack.channels) (defmethod archive ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.archive" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod create ((client cl-slack.core:slack-client) (name string) (optionals cl:list)) (cl-slack.core:send "channels.create" (format nil "?token=~A&name=~A~A" (cl-slack.core:token client) name (cl-slack.core:to-param optionals)))) (defmethod info ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.info" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod invite ((client cl-slack.core:slack-client) (channel string) (user string)) (cl-slack.core:send "channels.invite" (format nil "?token=~A&channel=~A&user=~A" (cl-slack.core:token client) channel user))) (defmethod join ((client cl-slack.core:slack-client) (name string) (optionals cl:list)) (cl-slack.core:send "channels.join" (format nil "?token=~A&name=~A~A" (cl-slack.core:token client) name (cl-slack.core:to-param optionals)))) (defmethod kick ((client cl-slack.core:slack-client) (channel string) (user string)) (cl-slack.core:send "channels.kick" (format nil "?token=~A&channel=~A&user=~A" (cl-slack.core:token client) channel user))) (defmethod leave ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.leave" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod mark ((client cl-slack.core:slack-client) (channel string) (ts string)) (cl-slack.core:send "channels.mark" (format nil "?token=~A&channel=~A&ts=~A" (cl-slack.core:token client) channel ts))) (defmethod rename ((client cl-slack.core:slack-client) (channel string) (name string) (optionals cl:list)) (cl-slack.core:send "channels.rename" (format nil "?token=~A&channel=~A&name=~A~A" (cl-slack.core:token client) channel name (cl-slack.core:to-param optionals)))) (defmethod replies ((client cl-slack.core:slack-client) (channel string) (thread-ts string)) (cl-slack.core:send "channels.replies" (format nil "?token=~A&channel=~A&thread_ts=~A" (cl-slack.core:token client) channel thread-ts))) (defmethod set-purpose ((client cl-slack.core:slack-client) (channel string) (purpose string)) (cl-slack.core:send "channels.setPurpose" (format nil "?token=~A&channel=~A&purpose=~A" (cl-slack.core:token client) channel purpose))) (defmethod set-topic ((client cl-slack.core:slack-client) (channel string) (topic string)) (cl-slack.core:send "channels.setTopic" (format nil "?token=~A&channel=~A&topic=~A" (cl-slack.core:token client) channel topic))) (defmethod unarchive ((client cl-slack.core:slack-client) (channel string)) (cl-slack.core:send "channels.unarchive" (format nil "?token=~A&channel=~A" (cl-slack.core:token client) channel))) (defmethod history ((client cl-slack.core:slack-client) (channel string) (optionals cl:list)) (cl-slack.core:send "channels.history" (format nil "?token=~A&channel=~A~A" (cl-slack.core:token client) channel (cl-slack.core:to-param optionals)))) (defmethod list ((client cl-slack.core:slack-client) (optionals cl:list)) (cl-slack.core:send "channels.list" (format nil "?token=~A~A" (cl-slack.core:token client) (cl-slack.core:to-param optionals))))
fe79f9926cdea482dfea82a4f38972684a1dd0357f5ffc6324a2b10b1decbd31
mzp/scheme-abc
node.mli
type 'a t = { value: 'a; filename: string; lineno: int; start_pos: int; end_pos: int; } val of_string : string -> char t Stream.t val of_file : string -> char t Stream.t val of_channel : string -> in_channel -> char t Stream.t val ghost : 'a -> 'a t val value : 'a t -> 'a val lift : ('a -> 'b) -> 'a t -> 'b t val concat : ('a list -> 'b) -> 'a t list -> 'b t val to_string : ('a -> string) -> 'a t -> string val report : string -> string t -> unit
null
https://raw.githubusercontent.com/mzp/scheme-abc/2cb541159bcc32ae4d033793dea6e6828566d503/scm/ast/node.mli
ocaml
type 'a t = { value: 'a; filename: string; lineno: int; start_pos: int; end_pos: int; } val of_string : string -> char t Stream.t val of_file : string -> char t Stream.t val of_channel : string -> in_channel -> char t Stream.t val ghost : 'a -> 'a t val value : 'a t -> 'a val lift : ('a -> 'b) -> 'a t -> 'b t val concat : ('a list -> 'b) -> 'a t list -> 'b t val to_string : ('a -> string) -> 'a t -> string val report : string -> string t -> unit
b73420478de36074205f58fdf3a6526ef923322be771d3c3dac2a1be3de53e2c
jserot/hocl
hcl.ml
(**********************************************************************) (* *) This file is part of the HOCL package (* *) Copyright ( c ) 2019 - present , ( ) . (* All rights reserved. *) (* *) (* This source code is licensed under the license found in the *) (* LICENSE file in the root directory of this source tree. *) (* *) (**********************************************************************) HCL backend open Printf type hcl_config = { mutable annot_file: string; mutable default_param_type: string; } let cfg = { annot_file = ""; default_param_type = "nat"; } let collect_types acc e = let open Ir in if not (List.mem e.e_type acc) then e.e_type::acc else acc let output_type oc t = fprintf oc "type %s;\n" t let mk_hcl_fname f = if Filename.check_suffix f "pi" then Misc.replace_suffix "hcl" (Filename.basename f) else f let output_pragma oc n = let open Ir in match n.n_kind, n.n_loop_fn, n.n_init_fn with Subgraph case fprintf oc "#pragma code(\"%s\", \"%s\");\n" n.n_name (mk_hcl_fname n.n_desc) (* .pi -> .hcl *) | "actor", "", _ -> fprintf oc "#pragma code(\"%s\", \"%s\", \"%s\");\n" n.n_name n.n_desc n.n_loop_fn | "actor", _, _ -> fprintf oc "#pragma code(\"%s\", \"%s\", \"%s\", \"%s\");\n" n.n_name n.n_desc n.n_loop_fn n.n_init_fn | _, _, _ -> (* TO FIX ? *) () exception Aie of string * Ir.node_desc * Ir.edge_desc list let get_port_type edges node port = let open Ir in try let io = List.find (fun io -> io.io_name = port.pt_name) node.n_ios in (* For "regular" (C-bound) actors ... *) io.io_type with Not_found -> (* For hierarchical actors (described by a sub-graph), the type must be inferred from the context *) let e = begin match port.pt_kind with | "input" | "cfg_input" -> find_inp_edge edges (node.n_name, port.pt_name) | "output" | "cfg_output" -> find_outp_edge edges (node.n_name, port.pt_name) | _ -> failwith "Hcl.get_port_type" (* should not happen *) end in e.e_type let output_actor oc edges n = let open Ir in match n.n_kind with | "actor" | "broadcast" | "src" | "snk" -> let params = List.filter (fun p -> p.pt_kind = "cfg_input") n.n_ports in let inps = List.filter (fun p -> p.pt_kind = "input") n.n_ports in let outps = List.filter (fun p -> p.pt_kind = "output") n.n_ports in let string_of_port p = let ty = get_port_type edges n p in p.pt_name ^ ": " ^ ty ^ (if p.pt_expr = "" then "" else " \"" ^ p.pt_expr ^ "\"") in begin match n.n_kind, params, inps, outps with "actor", [], _, _ -> fprintf oc "actor %s\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "actor", _, _, _ -> fprintf oc "actor %s\n param (%s)\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " params) (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "broadcast", [], _, _ -> fprintf oc "bcast %s\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "broadcast", _, _, _ -> fprintf oc "bcast %s\n param (%s)\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " params) (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "src", [], _, [p] -> fprintf oc "source %s : %s;\n" n.n_name (get_port_type edges n p) | "src", _, _, [p] -> fprintf oc "source %s (%s) : %s;\n" n.n_name (Misc.string_of_list string_of_port ", " params) (get_port_type edges n p) | "snk", [], [p], _ -> fprintf oc "sink %s : %s;\n" n.n_name (get_port_type edges n p) | "snk", _, [p], _ -> fprintf oc "sink %s (%s) : %s;\n" n.n_name (Misc.string_of_list string_of_port ", " params) (get_port_type edges n p) | _, _, _, _ -> failwith "Hcl.dump_actor" end | _ -> () let output_parameter oc n = let open Ir in match n.n_kind with | "param" -> fprintf oc "parameter %s: %s = %s;\n" n.n_name cfg.default_param_type n.n_desc | "cfg_in_iface" -> fprintf oc "parameter %s: %s;\n" n.n_name cfg.default_param_type | _ -> () let output_defn oc names edges n = let open Ir in let tuplify ios = match ios with [] -> "()" | [x] -> x | _ -> "(" ^ Misc.string_of_list Misc.id "," ios ^ ")" in match n.n_kind with | "actor" | "broadcast" | "src" | "snk" -> Note . This might have to be adjusted for " src " and " snk " nodes if cfg input ports are not explicitely listed ( like in the SIFT examples ) . To be clarified . listed (like in the SIFT examples). To be clarified. *) let params = List.filter (fun p -> p.pt_kind = "cfg_input") n.n_ports in let inps = List.filter (fun p -> p.pt_kind = "input") n.n_ports in let outps = List.filter (fun p -> p.pt_kind = "output") n.n_ports in let mk_edge_spec port = n.n_name, port.pt_name in let mk_dep_name e = try List.assoc (e.e_source, e.e_sourceport) names with Not_found -> if e.e_sourceport = "" then e.e_source else e.e_source ^ "_" ^ e.e_sourceport in let inp_edges = List.map (find_inp_edge edges) (List.map mk_edge_spec inps) in let outp_edges = List.map (find_outp_edge edges) (List.map mk_edge_spec outps) in let param_edges = List.map (find_inp_edge edges) (List.map mk_edge_spec params) in let actual_inps = List.map mk_dep_name inp_edges |> tuplify in let actual_outps = List.map mk_dep_name outp_edges |> tuplify in let actual_params = List.map mk_dep_name param_edges |> tuplify in begin match params with [] -> fprintf oc "let %s = %s %s;\n" actual_outps n.n_name actual_inps | _ -> fprintf oc "let %s = %s %s %s;\n" actual_outps n.n_name actual_params actual_inps end | _ -> () let output ch names nodes edges = let types = List.fold_left collect_types [] edges in List.iter (output_type ch) types; fprintf ch "\n"; List.iter (output_parameter ch) nodes; fprintf ch "\n"; List.iter (output_pragma ch) nodes; fprintf ch "\n"; List.iter (output_actor ch edges) nodes; fprintf ch "\n"; List.iter (output_defn ch names edges) nodes exception Invalid_annotation of string * int let read_annot_file f = let ic = open_in f in printf "Reading annotation file %s\n" f; flush stdout; let res = ref [] in let lineno = ref 0 in try while true do (* Quick and dirty way *) let line = input_line ic in begin try ignore (Scanf.sscanf line "%s %s %s" (fun p s n -> res := ((p,s),n) :: !res)); with _ -> raise (Invalid_annotation (f,!lineno)) end; incr lineno done; !res with End_of_file -> !res let dump annot_file fname p = let open Ir in let sname = Misc.replace_suffix "pi" fname in let names = if annot_file = "" then [] else read_annot_file annot_file in let oc = open_out fname in if annot_file = "" then fprintf oc "-- Generated by pi2hcl from file %s\n\n" sname else fprintf oc "-- Generated by pi2hcl from files %s and %s\n\n" sname annot_file; output oc names p.p_nodes p.p_edges; close_out oc; printf "Generated file %s\n" fname
null
https://raw.githubusercontent.com/jserot/hocl/7ab1dba918e64c3cdbc446e5f2c0cba37181bccf/tools/pi2hcl/hcl.ml
ocaml
******************************************************************** All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. ******************************************************************** .pi -> .hcl TO FIX ? For "regular" (C-bound) actors ... For hierarchical actors (described by a sub-graph), the type must be inferred from the context should not happen Quick and dirty way
This file is part of the HOCL package Copyright ( c ) 2019 - present , ( ) . HCL backend open Printf type hcl_config = { mutable annot_file: string; mutable default_param_type: string; } let cfg = { annot_file = ""; default_param_type = "nat"; } let collect_types acc e = let open Ir in if not (List.mem e.e_type acc) then e.e_type::acc else acc let output_type oc t = fprintf oc "type %s;\n" t let mk_hcl_fname f = if Filename.check_suffix f "pi" then Misc.replace_suffix "hcl" (Filename.basename f) else f let output_pragma oc n = let open Ir in match n.n_kind, n.n_loop_fn, n.n_init_fn with Subgraph case | "actor", "", _ -> fprintf oc "#pragma code(\"%s\", \"%s\", \"%s\");\n" n.n_name n.n_desc n.n_loop_fn | "actor", _, _ -> fprintf oc "#pragma code(\"%s\", \"%s\", \"%s\", \"%s\");\n" n.n_name n.n_desc n.n_loop_fn n.n_init_fn () exception Aie of string * Ir.node_desc * Ir.edge_desc list let get_port_type edges node port = let open Ir in try io.io_type let e = begin match port.pt_kind with | "input" | "cfg_input" -> find_inp_edge edges (node.n_name, port.pt_name) | "output" | "cfg_output" -> find_outp_edge edges (node.n_name, port.pt_name) end in e.e_type let output_actor oc edges n = let open Ir in match n.n_kind with | "actor" | "broadcast" | "src" | "snk" -> let params = List.filter (fun p -> p.pt_kind = "cfg_input") n.n_ports in let inps = List.filter (fun p -> p.pt_kind = "input") n.n_ports in let outps = List.filter (fun p -> p.pt_kind = "output") n.n_ports in let string_of_port p = let ty = get_port_type edges n p in p.pt_name ^ ": " ^ ty ^ (if p.pt_expr = "" then "" else " \"" ^ p.pt_expr ^ "\"") in begin match n.n_kind, params, inps, outps with "actor", [], _, _ -> fprintf oc "actor %s\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "actor", _, _, _ -> fprintf oc "actor %s\n param (%s)\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " params) (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "broadcast", [], _, _ -> fprintf oc "bcast %s\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "broadcast", _, _, _ -> fprintf oc "bcast %s\n param (%s)\n in (%s)\n out (%s);\n" n.n_name (Misc.string_of_list string_of_port ", " params) (Misc.string_of_list string_of_port ", " inps) (Misc.string_of_list string_of_port ", " outps) | "src", [], _, [p] -> fprintf oc "source %s : %s;\n" n.n_name (get_port_type edges n p) | "src", _, _, [p] -> fprintf oc "source %s (%s) : %s;\n" n.n_name (Misc.string_of_list string_of_port ", " params) (get_port_type edges n p) | "snk", [], [p], _ -> fprintf oc "sink %s : %s;\n" n.n_name (get_port_type edges n p) | "snk", _, [p], _ -> fprintf oc "sink %s (%s) : %s;\n" n.n_name (Misc.string_of_list string_of_port ", " params) (get_port_type edges n p) | _, _, _, _ -> failwith "Hcl.dump_actor" end | _ -> () let output_parameter oc n = let open Ir in match n.n_kind with | "param" -> fprintf oc "parameter %s: %s = %s;\n" n.n_name cfg.default_param_type n.n_desc | "cfg_in_iface" -> fprintf oc "parameter %s: %s;\n" n.n_name cfg.default_param_type | _ -> () let output_defn oc names edges n = let open Ir in let tuplify ios = match ios with [] -> "()" | [x] -> x | _ -> "(" ^ Misc.string_of_list Misc.id "," ios ^ ")" in match n.n_kind with | "actor" | "broadcast" | "src" | "snk" -> Note . This might have to be adjusted for " src " and " snk " nodes if cfg input ports are not explicitely listed ( like in the SIFT examples ) . To be clarified . listed (like in the SIFT examples). To be clarified. *) let params = List.filter (fun p -> p.pt_kind = "cfg_input") n.n_ports in let inps = List.filter (fun p -> p.pt_kind = "input") n.n_ports in let outps = List.filter (fun p -> p.pt_kind = "output") n.n_ports in let mk_edge_spec port = n.n_name, port.pt_name in let mk_dep_name e = try List.assoc (e.e_source, e.e_sourceport) names with Not_found -> if e.e_sourceport = "" then e.e_source else e.e_source ^ "_" ^ e.e_sourceport in let inp_edges = List.map (find_inp_edge edges) (List.map mk_edge_spec inps) in let outp_edges = List.map (find_outp_edge edges) (List.map mk_edge_spec outps) in let param_edges = List.map (find_inp_edge edges) (List.map mk_edge_spec params) in let actual_inps = List.map mk_dep_name inp_edges |> tuplify in let actual_outps = List.map mk_dep_name outp_edges |> tuplify in let actual_params = List.map mk_dep_name param_edges |> tuplify in begin match params with [] -> fprintf oc "let %s = %s %s;\n" actual_outps n.n_name actual_inps | _ -> fprintf oc "let %s = %s %s %s;\n" actual_outps n.n_name actual_params actual_inps end | _ -> () let output ch names nodes edges = let types = List.fold_left collect_types [] edges in List.iter (output_type ch) types; fprintf ch "\n"; List.iter (output_parameter ch) nodes; fprintf ch "\n"; List.iter (output_pragma ch) nodes; fprintf ch "\n"; List.iter (output_actor ch edges) nodes; fprintf ch "\n"; List.iter (output_defn ch names edges) nodes exception Invalid_annotation of string * int let read_annot_file f = let ic = open_in f in printf "Reading annotation file %s\n" f; flush stdout; let res = ref [] in let lineno = ref 0 in try let line = input_line ic in begin try ignore (Scanf.sscanf line "%s %s %s" (fun p s n -> res := ((p,s),n) :: !res)); with _ -> raise (Invalid_annotation (f,!lineno)) end; incr lineno done; !res with End_of_file -> !res let dump annot_file fname p = let open Ir in let sname = Misc.replace_suffix "pi" fname in let names = if annot_file = "" then [] else read_annot_file annot_file in let oc = open_out fname in if annot_file = "" then fprintf oc "-- Generated by pi2hcl from file %s\n\n" sname else fprintf oc "-- Generated by pi2hcl from files %s and %s\n\n" sname annot_file; output oc names p.p_nodes p.p_edges; close_out oc; printf "Generated file %s\n" fname
9f1e8689a5724d9030ee319c767e580e3945025dcf1d44ad19c1aca55b4aafa9
Chris00/ocaml-gammu
read1sms.ml
Simple demo / test file that prints some informations and the first sms . open Args_demo open Utils_tests open Printf let () = try let s = Gammu.make () in prepare_phone s; while true do print_string "Enter folder: "; let folder = int_of_string (read_line ()) in print_string "Enter message number: "; let message_number = int_of_string (read_line ()) in let multi_sms = Gammu.SMS.get s ~folder ~message_number in print_multi_sms multi_sms; done with G.Error e -> printf "Error: %s\n" (G.string_of_error e)
null
https://raw.githubusercontent.com/Chris00/ocaml-gammu/ad38c6aff25bda8aa6da1db5fdfe61a224b00250/demo/read1sms.ml
ocaml
Simple demo / test file that prints some informations and the first sms . open Args_demo open Utils_tests open Printf let () = try let s = Gammu.make () in prepare_phone s; while true do print_string "Enter folder: "; let folder = int_of_string (read_line ()) in print_string "Enter message number: "; let message_number = int_of_string (read_line ()) in let multi_sms = Gammu.SMS.get s ~folder ~message_number in print_multi_sms multi_sms; done with G.Error e -> printf "Error: %s\n" (G.string_of_error e)
ae104fcecfb57b5097929f5d27f915f102e2305ce4973f56c0dc48440eb4578f
keechma/keechma-pipelines
runtime.cljs
(ns keechma.pipelines.runtime (:require [promesa.core :as p] [medley.core :refer [dissoc-in]] [cljs.core.async :refer [chan put! <! close! alts!]]) (:require-macros [cljs.core.async.macros :refer [go-loop go]])) (def ^:dynamic *pipeline-depth* 0) (declare invoke-resumable) (declare start-resumable) (declare make-ident) (declare map->Pipeline) (defprotocol IPipelineRuntime (invoke [this pipeline] [this pipeline args] [this pipeline args config]) (cancel [this ident]) (cancel-all [this idents]) (on-cancel [this promise deferred-result]) (wait [this ident]) (wait-all [this idents]) (transact [this transact-fn]) (stop! [this]) (report-error [this error]) (get-pipeline-instance* [this ident]) (get-state* [this]) (get-active [this])) (defprotocol IPipeline (->resumable [this pipeline-name value])) (defprotocol IResumable (->pipeline [this])) (defprotocol IPipelineInstance (get-ident [this]) (get-args [this])) (defrecord Resumable [id ident config args state tail] IResumable (->pipeline [this] (map->Pipeline {:id id :config config :pipeline (:pipeline state)}))) (defrecord Pipeline [id pipeline config] IPipeline (->resumable [_ pipeline-name value] (map->Resumable {:id id :ident (make-ident (or pipeline-name id)) :args value :config config :state {:block :begin :pipeline pipeline :value value}}))) (defrecord Break [value should-break-all]) (defn make-ident [pipeline-id] [pipeline-id (keyword "pipeline" (gensym 'instance))]) (defn make-pipeline [id pipeline] (map->Pipeline {:id id :pipeline pipeline :config {:concurrency {:max js/Infinity} :cancel-on-shutdown true}})) (defn in-pipeline? [] (pos? *pipeline-depth*)) (defn resumable? [val] (instance? Resumable val)) (defn fn->pipeline-step [pipeline-fn] (with-meta pipeline-fn {::pipeline-step? true})) (defn error? [value] (instance? js/Error value)) (defn pipeline? [val] (instance? Pipeline val)) (defn pipeline-step? [value] (let [m (meta value)] (::pipeline-step? m))) (defn as-error [value] (if (error? value) value (ex-info "Unknown Error" {:value value}))) (defn promise->chan [promise] (let [promise-chan (chan)] (->> promise (p/map (fn [v] (when v (put! promise-chan v)) (close! promise-chan))) (p/error (fn [e] (put! promise-chan (as-error e)) (close! promise-chan)))) promise-chan)) (defn interpreter-state->resumable ([stack] (interpreter-state->resumable stack false)) ([stack use-fresh-idents] (reduce (fn [acc v] (let [[pipeline-id instance-id] (:ident v) ident (if use-fresh-idents (make-ident pipeline-id) [pipeline-id instance-id])] (assoc (map->Resumable (assoc v :ident ident)) :tail acc))) nil stack))) (defn execute [runtime context ident action value error get-interpreter-state] (try (let [val (action value (assoc context :pipeline/runtime runtime :pipeline/ident ident) error)] (cond (and (fn? val) (pipeline-step? val)) (val runtime context value error {:parent ident :interpreter-state (get-interpreter-state)}) (pipeline? val) (let [resumable (->resumable val nil value)] (invoke-resumable runtime resumable {:parent ident :interpreter-state (get-interpreter-state)})) :else val)) (catch :default err err))) (defn real-value [value prev-value] (if (nil? value) prev-value value)) (defn resumable-with-resumed-tail [runtime resumable] (if-let [tail (:tail resumable)] (let [ident (:ident resumable) resumed-value (invoke-resumable runtime tail {:parent ident :is-detached false :interpreter-state (:tail tail)})] (-> resumable (assoc :tail nil) (assoc-in [:state :value] resumed-value))) resumable)) (defn run-sync-block [runtime context resumable props] (let [resumable' (resumable-with-resumed-tail runtime resumable) {:keys [ident state]} resumable' {:keys [block prev-value value error pipeline]} state] (loop [block block pipeline pipeline prev-value prev-value value value error error] (let [{:keys [begin rescue finally]} pipeline get-interpreter-state (fn [] (let [{:keys [interpreter-state]} props state {:block block :pipeline (update pipeline block rest) :prev-value prev-value :value value :error error}] (vec (concat [(assoc resumable' :state state)] interpreter-state))))] (cond (= ::cancelled value) [:result value] (= Break (type value)) (let [value' (real-value (:value value) prev-value)] (if (:should-break-all value) [:result (assoc value :value value')] [:result value'])) (resumable? value) [:resumable-state value] (p/promise? value) [:promise (assoc resumable' :state {:pipeline pipeline :block block :value (p/then value #(real-value % prev-value)) :prev-value prev-value :error error})] (pipeline? value) (let [resumable (->resumable value nil prev-value) res (invoke-resumable runtime resumable {:parent ident :interpreter-state (get-interpreter-state)})] (recur block pipeline prev-value (real-value res prev-value) error)) :else (case block :begin (cond (error? value) (cond (boolean rescue) (recur :rescue pipeline prev-value prev-value value) (boolean finally) (recur :finally pipeline prev-value prev-value value) :else [:error value]) (and (not (seq begin)) (boolean finally)) (recur :finally pipeline prev-value value error) (not (seq begin)) [:result value] :else (let [[action & rest-actions] begin next-value (execute runtime context ident action value error get-interpreter-state)] (recur :begin (assoc pipeline :begin rest-actions) value (real-value next-value value) error))) :rescue (cond (error? value) (cond (boolean finally) (recur :finally pipeline prev-value prev-value value) :else [:error value]) (and (not (seq rescue)) (boolean finally)) (recur :finally pipeline prev-value value error) (not (seq rescue)) [:result value] :else (let [[action & rest-actions] rescue next-value (execute runtime context ident action value error get-interpreter-state)] (recur :rescue (assoc pipeline :rescue rest-actions) value (real-value next-value value) error))) :finally (cond (error? value) [:error value] (not (seq finally)) [:result value] :else (let [[action & rest-actions] finally next-value (execute runtime context ident action value error get-interpreter-state)] (recur :finally (assoc pipeline :finally rest-actions) value (real-value next-value value) error))))))))) (defn run-sync-block-until-no-resumable-state [runtime context resumable props] (let [[res-type payload] (transact runtime #(run-sync-block runtime context resumable props))] (if (= :resumable-state res-type) (if (:is-root props) (recur runtime context payload props) [res-type payload]) [res-type payload]))) (defn start-interpreter [runtime context resumable props] (let [{:keys [deferred-result canceller ident]} props [res-type payload] (run-sync-block-until-no-resumable-state runtime context resumable props)] (cond (= :resumable-state res-type) payload (= :result res-type) payload (= :error res-type) (throw payload) :else (do (go-loop [resumable payload] (let [state (:state resumable) [value c] (alts! [(promise->chan (:value state)) canceller])] (cond (or (= ::cancelled (:state (get-pipeline-instance* runtime ident))) (= canceller c)) (do (on-cancel runtime (:value state) deferred-result) nil) (= ::cancelled value) (p/resolve! deferred-result ::cancelled) :else (let [[next-res-type next-payload] (run-sync-block-until-no-resumable-state runtime context (assoc-in resumable [:state :value] value) props)] (cond (= :resumable-state res-type) next-payload (= :result next-res-type) (p/resolve! deferred-result next-payload) (= :error next-res-type) (p/reject! deferred-result next-payload) :else (when next-payload (recur next-payload))))))) deferred-result)))) (def live-states #{::running ::pending ::waiting-children}) (def running-states #{::running ::waiting-children}) (defn process-pipeline [[pipeline-name pipeline]] [pipeline-name (update-in pipeline [:config :queue-name] #(or % pipeline-name))]) (defn get-pipeline-instance [state ident] (get-in state [:instances ident])) (defn can-use-existing? [resumable] (get-in resumable [:config :use-existing])) (defn get-queue [state queue-name] (get-in state [:queues queue-name])) (defn get-queue-config [state queue-name] (get-in state [:queues queue-name :config])) (defn get-queue-queue [state queue-name] (get-in state [:queues queue-name :queue])) (defn get-resumable-queue-name [resumable] (let [queue-name (or (get-in resumable [:config :queue-name]) (:id resumable))] (if (fn? queue-name) (queue-name (:args resumable)) queue-name))) (defn get-existing [state resumable] (let [queue-name (get-resumable-queue-name resumable)] (->> (get-queue-queue state queue-name) (filter (fn [ident] (let [instance (get-pipeline-instance state ident)] (and (= (get-in instance [:resumable :id]) (:id resumable)) (= (get-in instance [:resumable :args]) (:args resumable)) (contains? live-states (:state instance)))))) first (get-pipeline-instance state)))) (defn add-to-parent [state {:keys [ident]}] (let [instance (get-pipeline-instance state ident) parent-ident (get-in instance [:props :parent])] (if parent-ident (update-in state [:instances parent-ident :props :children] #(conj (set %) ident)) state))) (defn remove-from-parent [state {:keys [ident]}] (let [instance (get-pipeline-instance state ident) parent-ident (get-in instance [:props :parent])] (if (and parent-ident (get-in state [:instances parent-ident])) (update-in state [:instances parent-ident :props :children] #(disj (set %) ident)) state))) (defn add-to-queue [state resumable] (let [ident (:ident resumable) queue-name (get-resumable-queue-name resumable) queue (or (get-queue state queue-name) {:config (get-in resumable [:config :concurrency]) :queue []})] (assoc-in state [:queues queue-name] (assoc queue :queue (conj (:queue queue) ident))))) (defn remove-from-queue [state resumable] (let [ident (:ident resumable) queue-name (get-resumable-queue-name resumable) queue-queue (get-queue-queue state queue-name)] (assoc-in state [:queues queue-name :queue] (filterv #(not= ident %) queue-queue)))) (defn can-start-immediately? [state resumable] (let [queue-name (get-resumable-queue-name resumable) queue-config (get-queue-config state queue-name) realized-queue (map #(get-pipeline-instance state %) (get-queue-queue state queue-name)) max-concurrency (get queue-config :max js/Infinity) enqueued (filter #(contains? live-states (:state %)) realized-queue)] (> max-concurrency (count enqueued)))) (defn update-instance-state [state resumable instance-state] (assoc-in state [:instances (:ident resumable) :state] instance-state)) (defn register-instance ([state resumable props] (register-instance state resumable props ::pending)) ([state resumable props instance-state] (-> state (add-to-queue resumable) (assoc-in [:instances (:ident resumable)] {:state instance-state :resumable resumable :props props}) (add-to-parent resumable)))) (defn deregister-instance [state resumable] (-> state (remove-from-queue resumable) (remove-from-parent resumable) (dissoc-in [:instances (:ident resumable)]))) (defn queue-assoc-last-result [state resumable result] (let [queue-name (get-resumable-queue-name resumable)] (assoc-in state [:queues queue-name :last-result] result))) (defn queue-assoc-last-error [state resumable result] (let [queue-name (get-resumable-queue-name resumable)] (assoc-in state [:queues queue-name :last-error] result))) (defn queue-assoc-last [state resumable result] (if (not= ::cancelled result) (if (error? result) (queue-assoc-last-error state resumable result) (queue-assoc-last-result state resumable result)) state)) (defn get-queued-idents-to-cancel [state queue-name] (let [queue (get-queue state queue-name) queue-queue (:queue queue) max-concurrency (get-in queue [:config :max]) behavior (get-in queue [:config :behavior]) free-slots (dec max-concurrency)] (case behavior :restartable (let [cancellable (filterv #(contains? live-states (:state (get-pipeline-instance state %))) queue-queue)] (take (- (count cancellable) free-slots) cancellable)) :keep-latest (filterv #(= ::pending (:state (get-pipeline-instance state %))) queue-queue) []))) (defn get-queued-idents-to-start [state queue-name] (let [queue (get-queue state queue-name) queue-queue (:queue queue) max-concurrency (get-in queue [:config :max]) pending (filterv #(= ::pending (:state (get-pipeline-instance state %))) queue-queue) running (filterv #(contains? running-states (:state (get-pipeline-instance state %))) queue-queue)] (take (- max-concurrency (count running)) pending))) (defn start-next-in-queue [{:keys [state*] :as runtime} queue-name] (let [queued-idents-to-start (get-queued-idents-to-start @state* queue-name)] (doseq [ident queued-idents-to-start] (start-resumable runtime (:resumable (get-pipeline-instance @state* ident)))))) (defn cleanup-parents [{:keys [state*] :as runtime} instance] (let [parent-instance (get-in @state* [:instances (get-in instance [:props :parent])]) children (get-in instance [:props :children])] (when (and (= ::waiting-children (:state parent-instance)) (not (seq children))) (let [resumable (:resumable parent-instance)] (swap! state* deregister-instance resumable) (start-next-in-queue runtime (get-resumable-queue-name resumable)) (recur runtime parent-instance))))) (defn finish-resumable [{:keys [state*] :as runtime} {:keys [ident] :as resumable} result] (let [instance (get-pipeline-instance @state* ident)] (when instance (if (= ::cancelled result) (cancel runtime ident) (if (seq (get-in instance [:props :children])) (swap! state* update-instance-state resumable ::waiting-children) (do (swap! state* (fn [state] (-> state (queue-assoc-last resumable result) (deregister-instance resumable)))) (cleanup-parents runtime instance) (start-next-in-queue runtime (get-resumable-queue-name resumable)))))) (if (and (or (nil? instance) (get-in instance [:props :is-root])) (= Break (type result))) (:value result) result))) (defn enqueue-resumable [{:keys [state*] :as runtime} resumable props] (let [queued-idents-to-cancel (get-queued-idents-to-cancel @state* (get-resumable-queue-name resumable))] (swap! state* (fn [state] (-> state (register-instance resumable props ::pending)))) (cancel-all runtime queued-idents-to-cancel) (:deferred-result props))) (defn start-resumable [{:keys [state* context] :as runtime} {:keys [ident args] :as resumable}] (swap! state* update-instance-state resumable ::running) (let [props (:props (get-pipeline-instance @state* ident)) has-parent (:parent props) deferred-result (:deferred-result props) res (try (start-interpreter runtime context resumable props) (catch :default e (when-not has-parent (report-error runtime e)) e))] (if (p/promise? res) (let [res-promise (->> deferred-result (p/map #(finish-resumable runtime resumable %)) (p/error (fn [error] (when-not has-parent (report-error runtime error)) (finish-resumable runtime resumable error) (p/rejected error))))] (specify! res-promise IPipelineInstance (get-ident [_] ident) (get-args [_] args))) (do (if (error? res) (p/reject! deferred-result res) (p/resolve! deferred-result res)) (finish-resumable runtime resumable res))))) (defn throw-if-queues-not-matching [state resumable] (let [queue-name (get-resumable-queue-name resumable) queue-config (get-queue-config state queue-name) pipeline-config (get-in resumable [:config :concurrency])] (when (and queue-config (not= queue-config pipeline-config)) (throw (ex-info "Pipeline's queue config is not matching queue's config" {:pipeline (:ident resumable) :queue queue-name :queue-config queue-config :pipeline-config pipeline-config}))))) (defn process-resumable [{:keys [state*] :as runtime} resumable props] (cond (can-start-immediately? @state* resumable) (do (swap! state* register-instance resumable props ::running) (start-resumable runtime resumable)) (= :dropping (get-in resumable [:config :concurrency :behavior])) ::cancelled :else (enqueue-resumable runtime resumable props))) (defn invoke-resumable [runtime {:keys [ident args] :as resumable} {:keys [parent] :as pipeline-opts}] (let [{:keys [state*]} runtime deferred-result (specify! (p/deferred) IPipelineInstance (get-ident [_] ident) (get-args [_] args)) canceller (chan) is-detached (get-in resumable [:config :is-detached]) props (merge {:interpreter-state []} pipeline-opts {:canceller canceller :ident (:ident resumable) :is-root (nil? parent) :deferred-result deferred-result :children #{}}) state @state*] (throw-if-queues-not-matching state resumable) (let [res (if (can-use-existing? resumable) (if-let [existing (get-in (get-existing state resumable) [:props :deferred-result])] existing (process-resumable runtime resumable props)) (process-resumable runtime resumable props))] (if-not is-detached res nil)))) (defn get-cancel-root-ident [state ident] (let [instance (get-pipeline-instance state ident) is-detached (get-in instance [:resumable :config :is-detached]) parent-ident (get-in instance [:props :parent])] (if (and parent-ident (not is-detached)) (recur state parent-ident) ident))) (defn get-ident-and-descendant-idents ([state ident] (get-ident-and-descendant-idents state ident [ident])) ([state ident descendants] (let [instance (get-pipeline-instance state ident) children (get-in instance [:props :children])] (if (seq children) (vec (concat descendants (mapcat #(get-ident-and-descendant-idents state %) children))) descendants)))) (defn has-pipeline? [{:keys [state*]} pipeline-name] (boolean (get-in @state* [:pipelines pipeline-name]))) (defrecord PipelineRuntime [context state* pipelines opts] IPipelineRuntime (invoke [this pipeline-name] (invoke this pipeline-name nil nil)) (invoke [this pipeline-name args] (invoke this pipeline-name args nil)) (invoke [this pipeline-name args pipeline-opts] (let [pipeline (if (pipeline? pipeline-name) pipeline-name (get-in @state* [:pipelines pipeline-name]))] (invoke-resumable this (->resumable pipeline pipeline-name args) pipeline-opts))) (transact [_ transaction] (binding [*pipeline-depth* (inc *pipeline-depth*)] (let [{:keys [transactor]} opts] (transactor transaction)))) (report-error [_ error] (let [reporter (:error-reporter opts)] (reporter error))) (get-pipeline-instance* [this ident] (reify IDeref (-deref [_] (get-pipeline-instance @state* ident)))) (cancel [this ident] (let [root-ident (get-cancel-root-ident @state* ident) initial-idents-to-cancel (reverse (get-ident-and-descendant-idents @state* root-ident)) queues-to-refresh (loop [idents-to-cancel initial-idents-to-cancel queues-to-refresh #{}] (if (not (seq idents-to-cancel)) queues-to-refresh (let [[ident-to-cancel & rest-idents-to-cancel] idents-to-cancel instance (get-pipeline-instance @state* ident-to-cancel)] (if instance (let [resumable (:resumable instance) canceller (get-in instance [:props :canceller]) deferred-result (get-in instance [:props :deferred-result]) queue-name (get-resumable-queue-name resumable)] (swap! state* update-instance-state resumable ::cancelled) (close! canceller) (p/resolve! deferred-result ::cancelled) (swap! state* deregister-instance resumable) (recur rest-idents-to-cancel (conj queues-to-refresh queue-name))) (recur rest-idents-to-cancel queues-to-refresh)))))] (doseq [queue-name queues-to-refresh] (start-next-in-queue this queue-name)))) (on-cancel [_ promise deferred-result] (let [on-cancel (:on-cancel opts)] (on-cancel promise deferred-result))) (cancel-all [this idents] (doseq [ident idents] (cancel this ident))) (get-active [this] (let [state @state*] (reduce-kv (fn [m k v] (let [idents (:queue v)] (if (seq idents) (let [info (reduce (fn [acc ident] (assoc acc ident {:config (get-in state [:pipelines k :config]) :state (get-in state [:instances ident :state]) :args (get-in state [:instances ident :resumable :args]) :ident ident})) {} idents)] (assoc m k info)) m))) {} (:queues state)))) (stop! [this] (remove-watch state* ::watcher) (let [instances (:instances @state*) cancellable-idents (->> instances (filter (fn [[_ v]] (get-in v [:resumable :config :cancel-on-shutdown]))) (map first))] (cancel-all this cancellable-idents) (reset! state* ::stopped)))) (defn break ([] (break nil)) ([value] (->Break value false))) (defn break-all ([] (break-all nil)) ([value] (->Break value true))) (defn default-transactor [transaction] (transaction)) (def default-opts {:transactor default-transactor :watcher (fn [& args]) :error-reporter (if goog.DEBUG js/console.error identity) :on-cancel identity}) (defn start! ([context] (start! context nil nil)) ([context pipelines] (start! context pipelines nil)) ([context pipelines opts] (let [opts' (merge default-opts opts) {:keys [watcher]} opts' state* (atom {:pipelines (into {} (map process-pipeline pipelines))})] (add-watch state* ::watcher watcher) (->PipelineRuntime context state* pipelines opts'))))
null
https://raw.githubusercontent.com/keechma/keechma-pipelines/09ae26e5f435401e420c3869dec8e77da74ef7d0/src/keechma/pipelines/runtime.cljs
clojure
(ns keechma.pipelines.runtime (:require [promesa.core :as p] [medley.core :refer [dissoc-in]] [cljs.core.async :refer [chan put! <! close! alts!]]) (:require-macros [cljs.core.async.macros :refer [go-loop go]])) (def ^:dynamic *pipeline-depth* 0) (declare invoke-resumable) (declare start-resumable) (declare make-ident) (declare map->Pipeline) (defprotocol IPipelineRuntime (invoke [this pipeline] [this pipeline args] [this pipeline args config]) (cancel [this ident]) (cancel-all [this idents]) (on-cancel [this promise deferred-result]) (wait [this ident]) (wait-all [this idents]) (transact [this transact-fn]) (stop! [this]) (report-error [this error]) (get-pipeline-instance* [this ident]) (get-state* [this]) (get-active [this])) (defprotocol IPipeline (->resumable [this pipeline-name value])) (defprotocol IResumable (->pipeline [this])) (defprotocol IPipelineInstance (get-ident [this]) (get-args [this])) (defrecord Resumable [id ident config args state tail] IResumable (->pipeline [this] (map->Pipeline {:id id :config config :pipeline (:pipeline state)}))) (defrecord Pipeline [id pipeline config] IPipeline (->resumable [_ pipeline-name value] (map->Resumable {:id id :ident (make-ident (or pipeline-name id)) :args value :config config :state {:block :begin :pipeline pipeline :value value}}))) (defrecord Break [value should-break-all]) (defn make-ident [pipeline-id] [pipeline-id (keyword "pipeline" (gensym 'instance))]) (defn make-pipeline [id pipeline] (map->Pipeline {:id id :pipeline pipeline :config {:concurrency {:max js/Infinity} :cancel-on-shutdown true}})) (defn in-pipeline? [] (pos? *pipeline-depth*)) (defn resumable? [val] (instance? Resumable val)) (defn fn->pipeline-step [pipeline-fn] (with-meta pipeline-fn {::pipeline-step? true})) (defn error? [value] (instance? js/Error value)) (defn pipeline? [val] (instance? Pipeline val)) (defn pipeline-step? [value] (let [m (meta value)] (::pipeline-step? m))) (defn as-error [value] (if (error? value) value (ex-info "Unknown Error" {:value value}))) (defn promise->chan [promise] (let [promise-chan (chan)] (->> promise (p/map (fn [v] (when v (put! promise-chan v)) (close! promise-chan))) (p/error (fn [e] (put! promise-chan (as-error e)) (close! promise-chan)))) promise-chan)) (defn interpreter-state->resumable ([stack] (interpreter-state->resumable stack false)) ([stack use-fresh-idents] (reduce (fn [acc v] (let [[pipeline-id instance-id] (:ident v) ident (if use-fresh-idents (make-ident pipeline-id) [pipeline-id instance-id])] (assoc (map->Resumable (assoc v :ident ident)) :tail acc))) nil stack))) (defn execute [runtime context ident action value error get-interpreter-state] (try (let [val (action value (assoc context :pipeline/runtime runtime :pipeline/ident ident) error)] (cond (and (fn? val) (pipeline-step? val)) (val runtime context value error {:parent ident :interpreter-state (get-interpreter-state)}) (pipeline? val) (let [resumable (->resumable val nil value)] (invoke-resumable runtime resumable {:parent ident :interpreter-state (get-interpreter-state)})) :else val)) (catch :default err err))) (defn real-value [value prev-value] (if (nil? value) prev-value value)) (defn resumable-with-resumed-tail [runtime resumable] (if-let [tail (:tail resumable)] (let [ident (:ident resumable) resumed-value (invoke-resumable runtime tail {:parent ident :is-detached false :interpreter-state (:tail tail)})] (-> resumable (assoc :tail nil) (assoc-in [:state :value] resumed-value))) resumable)) (defn run-sync-block [runtime context resumable props] (let [resumable' (resumable-with-resumed-tail runtime resumable) {:keys [ident state]} resumable' {:keys [block prev-value value error pipeline]} state] (loop [block block pipeline pipeline prev-value prev-value value value error error] (let [{:keys [begin rescue finally]} pipeline get-interpreter-state (fn [] (let [{:keys [interpreter-state]} props state {:block block :pipeline (update pipeline block rest) :prev-value prev-value :value value :error error}] (vec (concat [(assoc resumable' :state state)] interpreter-state))))] (cond (= ::cancelled value) [:result value] (= Break (type value)) (let [value' (real-value (:value value) prev-value)] (if (:should-break-all value) [:result (assoc value :value value')] [:result value'])) (resumable? value) [:resumable-state value] (p/promise? value) [:promise (assoc resumable' :state {:pipeline pipeline :block block :value (p/then value #(real-value % prev-value)) :prev-value prev-value :error error})] (pipeline? value) (let [resumable (->resumable value nil prev-value) res (invoke-resumable runtime resumable {:parent ident :interpreter-state (get-interpreter-state)})] (recur block pipeline prev-value (real-value res prev-value) error)) :else (case block :begin (cond (error? value) (cond (boolean rescue) (recur :rescue pipeline prev-value prev-value value) (boolean finally) (recur :finally pipeline prev-value prev-value value) :else [:error value]) (and (not (seq begin)) (boolean finally)) (recur :finally pipeline prev-value value error) (not (seq begin)) [:result value] :else (let [[action & rest-actions] begin next-value (execute runtime context ident action value error get-interpreter-state)] (recur :begin (assoc pipeline :begin rest-actions) value (real-value next-value value) error))) :rescue (cond (error? value) (cond (boolean finally) (recur :finally pipeline prev-value prev-value value) :else [:error value]) (and (not (seq rescue)) (boolean finally)) (recur :finally pipeline prev-value value error) (not (seq rescue)) [:result value] :else (let [[action & rest-actions] rescue next-value (execute runtime context ident action value error get-interpreter-state)] (recur :rescue (assoc pipeline :rescue rest-actions) value (real-value next-value value) error))) :finally (cond (error? value) [:error value] (not (seq finally)) [:result value] :else (let [[action & rest-actions] finally next-value (execute runtime context ident action value error get-interpreter-state)] (recur :finally (assoc pipeline :finally rest-actions) value (real-value next-value value) error))))))))) (defn run-sync-block-until-no-resumable-state [runtime context resumable props] (let [[res-type payload] (transact runtime #(run-sync-block runtime context resumable props))] (if (= :resumable-state res-type) (if (:is-root props) (recur runtime context payload props) [res-type payload]) [res-type payload]))) (defn start-interpreter [runtime context resumable props] (let [{:keys [deferred-result canceller ident]} props [res-type payload] (run-sync-block-until-no-resumable-state runtime context resumable props)] (cond (= :resumable-state res-type) payload (= :result res-type) payload (= :error res-type) (throw payload) :else (do (go-loop [resumable payload] (let [state (:state resumable) [value c] (alts! [(promise->chan (:value state)) canceller])] (cond (or (= ::cancelled (:state (get-pipeline-instance* runtime ident))) (= canceller c)) (do (on-cancel runtime (:value state) deferred-result) nil) (= ::cancelled value) (p/resolve! deferred-result ::cancelled) :else (let [[next-res-type next-payload] (run-sync-block-until-no-resumable-state runtime context (assoc-in resumable [:state :value] value) props)] (cond (= :resumable-state res-type) next-payload (= :result next-res-type) (p/resolve! deferred-result next-payload) (= :error next-res-type) (p/reject! deferred-result next-payload) :else (when next-payload (recur next-payload))))))) deferred-result)))) (def live-states #{::running ::pending ::waiting-children}) (def running-states #{::running ::waiting-children}) (defn process-pipeline [[pipeline-name pipeline]] [pipeline-name (update-in pipeline [:config :queue-name] #(or % pipeline-name))]) (defn get-pipeline-instance [state ident] (get-in state [:instances ident])) (defn can-use-existing? [resumable] (get-in resumable [:config :use-existing])) (defn get-queue [state queue-name] (get-in state [:queues queue-name])) (defn get-queue-config [state queue-name] (get-in state [:queues queue-name :config])) (defn get-queue-queue [state queue-name] (get-in state [:queues queue-name :queue])) (defn get-resumable-queue-name [resumable] (let [queue-name (or (get-in resumable [:config :queue-name]) (:id resumable))] (if (fn? queue-name) (queue-name (:args resumable)) queue-name))) (defn get-existing [state resumable] (let [queue-name (get-resumable-queue-name resumable)] (->> (get-queue-queue state queue-name) (filter (fn [ident] (let [instance (get-pipeline-instance state ident)] (and (= (get-in instance [:resumable :id]) (:id resumable)) (= (get-in instance [:resumable :args]) (:args resumable)) (contains? live-states (:state instance)))))) first (get-pipeline-instance state)))) (defn add-to-parent [state {:keys [ident]}] (let [instance (get-pipeline-instance state ident) parent-ident (get-in instance [:props :parent])] (if parent-ident (update-in state [:instances parent-ident :props :children] #(conj (set %) ident)) state))) (defn remove-from-parent [state {:keys [ident]}] (let [instance (get-pipeline-instance state ident) parent-ident (get-in instance [:props :parent])] (if (and parent-ident (get-in state [:instances parent-ident])) (update-in state [:instances parent-ident :props :children] #(disj (set %) ident)) state))) (defn add-to-queue [state resumable] (let [ident (:ident resumable) queue-name (get-resumable-queue-name resumable) queue (or (get-queue state queue-name) {:config (get-in resumable [:config :concurrency]) :queue []})] (assoc-in state [:queues queue-name] (assoc queue :queue (conj (:queue queue) ident))))) (defn remove-from-queue [state resumable] (let [ident (:ident resumable) queue-name (get-resumable-queue-name resumable) queue-queue (get-queue-queue state queue-name)] (assoc-in state [:queues queue-name :queue] (filterv #(not= ident %) queue-queue)))) (defn can-start-immediately? [state resumable] (let [queue-name (get-resumable-queue-name resumable) queue-config (get-queue-config state queue-name) realized-queue (map #(get-pipeline-instance state %) (get-queue-queue state queue-name)) max-concurrency (get queue-config :max js/Infinity) enqueued (filter #(contains? live-states (:state %)) realized-queue)] (> max-concurrency (count enqueued)))) (defn update-instance-state [state resumable instance-state] (assoc-in state [:instances (:ident resumable) :state] instance-state)) (defn register-instance ([state resumable props] (register-instance state resumable props ::pending)) ([state resumable props instance-state] (-> state (add-to-queue resumable) (assoc-in [:instances (:ident resumable)] {:state instance-state :resumable resumable :props props}) (add-to-parent resumable)))) (defn deregister-instance [state resumable] (-> state (remove-from-queue resumable) (remove-from-parent resumable) (dissoc-in [:instances (:ident resumable)]))) (defn queue-assoc-last-result [state resumable result] (let [queue-name (get-resumable-queue-name resumable)] (assoc-in state [:queues queue-name :last-result] result))) (defn queue-assoc-last-error [state resumable result] (let [queue-name (get-resumable-queue-name resumable)] (assoc-in state [:queues queue-name :last-error] result))) (defn queue-assoc-last [state resumable result] (if (not= ::cancelled result) (if (error? result) (queue-assoc-last-error state resumable result) (queue-assoc-last-result state resumable result)) state)) (defn get-queued-idents-to-cancel [state queue-name] (let [queue (get-queue state queue-name) queue-queue (:queue queue) max-concurrency (get-in queue [:config :max]) behavior (get-in queue [:config :behavior]) free-slots (dec max-concurrency)] (case behavior :restartable (let [cancellable (filterv #(contains? live-states (:state (get-pipeline-instance state %))) queue-queue)] (take (- (count cancellable) free-slots) cancellable)) :keep-latest (filterv #(= ::pending (:state (get-pipeline-instance state %))) queue-queue) []))) (defn get-queued-idents-to-start [state queue-name] (let [queue (get-queue state queue-name) queue-queue (:queue queue) max-concurrency (get-in queue [:config :max]) pending (filterv #(= ::pending (:state (get-pipeline-instance state %))) queue-queue) running (filterv #(contains? running-states (:state (get-pipeline-instance state %))) queue-queue)] (take (- max-concurrency (count running)) pending))) (defn start-next-in-queue [{:keys [state*] :as runtime} queue-name] (let [queued-idents-to-start (get-queued-idents-to-start @state* queue-name)] (doseq [ident queued-idents-to-start] (start-resumable runtime (:resumable (get-pipeline-instance @state* ident)))))) (defn cleanup-parents [{:keys [state*] :as runtime} instance] (let [parent-instance (get-in @state* [:instances (get-in instance [:props :parent])]) children (get-in instance [:props :children])] (when (and (= ::waiting-children (:state parent-instance)) (not (seq children))) (let [resumable (:resumable parent-instance)] (swap! state* deregister-instance resumable) (start-next-in-queue runtime (get-resumable-queue-name resumable)) (recur runtime parent-instance))))) (defn finish-resumable [{:keys [state*] :as runtime} {:keys [ident] :as resumable} result] (let [instance (get-pipeline-instance @state* ident)] (when instance (if (= ::cancelled result) (cancel runtime ident) (if (seq (get-in instance [:props :children])) (swap! state* update-instance-state resumable ::waiting-children) (do (swap! state* (fn [state] (-> state (queue-assoc-last resumable result) (deregister-instance resumable)))) (cleanup-parents runtime instance) (start-next-in-queue runtime (get-resumable-queue-name resumable)))))) (if (and (or (nil? instance) (get-in instance [:props :is-root])) (= Break (type result))) (:value result) result))) (defn enqueue-resumable [{:keys [state*] :as runtime} resumable props] (let [queued-idents-to-cancel (get-queued-idents-to-cancel @state* (get-resumable-queue-name resumable))] (swap! state* (fn [state] (-> state (register-instance resumable props ::pending)))) (cancel-all runtime queued-idents-to-cancel) (:deferred-result props))) (defn start-resumable [{:keys [state* context] :as runtime} {:keys [ident args] :as resumable}] (swap! state* update-instance-state resumable ::running) (let [props (:props (get-pipeline-instance @state* ident)) has-parent (:parent props) deferred-result (:deferred-result props) res (try (start-interpreter runtime context resumable props) (catch :default e (when-not has-parent (report-error runtime e)) e))] (if (p/promise? res) (let [res-promise (->> deferred-result (p/map #(finish-resumable runtime resumable %)) (p/error (fn [error] (when-not has-parent (report-error runtime error)) (finish-resumable runtime resumable error) (p/rejected error))))] (specify! res-promise IPipelineInstance (get-ident [_] ident) (get-args [_] args))) (do (if (error? res) (p/reject! deferred-result res) (p/resolve! deferred-result res)) (finish-resumable runtime resumable res))))) (defn throw-if-queues-not-matching [state resumable] (let [queue-name (get-resumable-queue-name resumable) queue-config (get-queue-config state queue-name) pipeline-config (get-in resumable [:config :concurrency])] (when (and queue-config (not= queue-config pipeline-config)) (throw (ex-info "Pipeline's queue config is not matching queue's config" {:pipeline (:ident resumable) :queue queue-name :queue-config queue-config :pipeline-config pipeline-config}))))) (defn process-resumable [{:keys [state*] :as runtime} resumable props] (cond (can-start-immediately? @state* resumable) (do (swap! state* register-instance resumable props ::running) (start-resumable runtime resumable)) (= :dropping (get-in resumable [:config :concurrency :behavior])) ::cancelled :else (enqueue-resumable runtime resumable props))) (defn invoke-resumable [runtime {:keys [ident args] :as resumable} {:keys [parent] :as pipeline-opts}] (let [{:keys [state*]} runtime deferred-result (specify! (p/deferred) IPipelineInstance (get-ident [_] ident) (get-args [_] args)) canceller (chan) is-detached (get-in resumable [:config :is-detached]) props (merge {:interpreter-state []} pipeline-opts {:canceller canceller :ident (:ident resumable) :is-root (nil? parent) :deferred-result deferred-result :children #{}}) state @state*] (throw-if-queues-not-matching state resumable) (let [res (if (can-use-existing? resumable) (if-let [existing (get-in (get-existing state resumable) [:props :deferred-result])] existing (process-resumable runtime resumable props)) (process-resumable runtime resumable props))] (if-not is-detached res nil)))) (defn get-cancel-root-ident [state ident] (let [instance (get-pipeline-instance state ident) is-detached (get-in instance [:resumable :config :is-detached]) parent-ident (get-in instance [:props :parent])] (if (and parent-ident (not is-detached)) (recur state parent-ident) ident))) (defn get-ident-and-descendant-idents ([state ident] (get-ident-and-descendant-idents state ident [ident])) ([state ident descendants] (let [instance (get-pipeline-instance state ident) children (get-in instance [:props :children])] (if (seq children) (vec (concat descendants (mapcat #(get-ident-and-descendant-idents state %) children))) descendants)))) (defn has-pipeline? [{:keys [state*]} pipeline-name] (boolean (get-in @state* [:pipelines pipeline-name]))) (defrecord PipelineRuntime [context state* pipelines opts] IPipelineRuntime (invoke [this pipeline-name] (invoke this pipeline-name nil nil)) (invoke [this pipeline-name args] (invoke this pipeline-name args nil)) (invoke [this pipeline-name args pipeline-opts] (let [pipeline (if (pipeline? pipeline-name) pipeline-name (get-in @state* [:pipelines pipeline-name]))] (invoke-resumable this (->resumable pipeline pipeline-name args) pipeline-opts))) (transact [_ transaction] (binding [*pipeline-depth* (inc *pipeline-depth*)] (let [{:keys [transactor]} opts] (transactor transaction)))) (report-error [_ error] (let [reporter (:error-reporter opts)] (reporter error))) (get-pipeline-instance* [this ident] (reify IDeref (-deref [_] (get-pipeline-instance @state* ident)))) (cancel [this ident] (let [root-ident (get-cancel-root-ident @state* ident) initial-idents-to-cancel (reverse (get-ident-and-descendant-idents @state* root-ident)) queues-to-refresh (loop [idents-to-cancel initial-idents-to-cancel queues-to-refresh #{}] (if (not (seq idents-to-cancel)) queues-to-refresh (let [[ident-to-cancel & rest-idents-to-cancel] idents-to-cancel instance (get-pipeline-instance @state* ident-to-cancel)] (if instance (let [resumable (:resumable instance) canceller (get-in instance [:props :canceller]) deferred-result (get-in instance [:props :deferred-result]) queue-name (get-resumable-queue-name resumable)] (swap! state* update-instance-state resumable ::cancelled) (close! canceller) (p/resolve! deferred-result ::cancelled) (swap! state* deregister-instance resumable) (recur rest-idents-to-cancel (conj queues-to-refresh queue-name))) (recur rest-idents-to-cancel queues-to-refresh)))))] (doseq [queue-name queues-to-refresh] (start-next-in-queue this queue-name)))) (on-cancel [_ promise deferred-result] (let [on-cancel (:on-cancel opts)] (on-cancel promise deferred-result))) (cancel-all [this idents] (doseq [ident idents] (cancel this ident))) (get-active [this] (let [state @state*] (reduce-kv (fn [m k v] (let [idents (:queue v)] (if (seq idents) (let [info (reduce (fn [acc ident] (assoc acc ident {:config (get-in state [:pipelines k :config]) :state (get-in state [:instances ident :state]) :args (get-in state [:instances ident :resumable :args]) :ident ident})) {} idents)] (assoc m k info)) m))) {} (:queues state)))) (stop! [this] (remove-watch state* ::watcher) (let [instances (:instances @state*) cancellable-idents (->> instances (filter (fn [[_ v]] (get-in v [:resumable :config :cancel-on-shutdown]))) (map first))] (cancel-all this cancellable-idents) (reset! state* ::stopped)))) (defn break ([] (break nil)) ([value] (->Break value false))) (defn break-all ([] (break-all nil)) ([value] (->Break value true))) (defn default-transactor [transaction] (transaction)) (def default-opts {:transactor default-transactor :watcher (fn [& args]) :error-reporter (if goog.DEBUG js/console.error identity) :on-cancel identity}) (defn start! ([context] (start! context nil nil)) ([context pipelines] (start! context pipelines nil)) ([context pipelines opts] (let [opts' (merge default-opts opts) {:keys [watcher]} opts' state* (atom {:pipelines (into {} (map process-pipeline pipelines))})] (add-watch state* ::watcher watcher) (->PipelineRuntime context state* pipelines opts'))))
31f6aedda0e5a6ed9f9c7bb8fd42f2d2f7cdaf6c041b303f24a605d0d2228484
gator1/jepsen
mv_test.clj
(ns cassandra.mv-test (:require [clojure.test :refer :all] [clojure.pprint :refer [pprint]] [cassandra.mv :refer :all] [cassandra.core-test :refer :all] [jepsen [core :as jepsen] [report :as report]])) ;; Steady state cluster tests (deftest ^:mv ^:steady mv-bridge (run-test! bridge-test)) (deftest ^:mv ^:steady mv-isolate-node (run-test! isolate-node-test)) (deftest ^:mv ^:steady mv-halves (run-test! halves-test)) (deftest ^:mv ^:steady mv-crash-subset (run-test! crash-subset-test)) (deftest ^:mv ^:steady mv-flush-compact (run-test! flush-compact-test)) (deftest ^:clock mv-clock-drift (run-test! clock-drift-test)) ;; Bootstrapping tests (deftest ^:mv ^:bootstrap mv-bridge-bootstrap (run-test! bridge-test-bootstrap)) (deftest ^:mv ^:bootstrap mv-isolate-node-bootstrap (run-test! isolate-node-test-bootstrap)) (deftest ^:mv ^:bootstrap mv-halves-bootstrap (run-test! halves-test-bootstrap)) (deftest ^:mv ^:bootstrap mv-crash-subset-bootstrap (run-test! crash-subset-test-bootstrap)) (deftest ^:clock mv-clock-drift-bootstrap (run-test! clock-drift-test-bootstrap)) ;; Decommission tests (deftest ^:mv ^:decommission mv-bridge-decommission (run-test! bridge-test-decommission)) (deftest ^:mv ^:decommission mv-isolate-node-decommission (run-test! isolate-node-test-decommission)) (deftest ^:mv ^:decommission mv-halves-decommission (run-test! halves-test-decommission)) (deftest ^:mv ^:decommission mv-crash-subset-decommission (run-test! crash-subset-test-decommission)) (deftest ^:clock mv-clock-drift-decommission (run-test! clock-drift-test-decommission)) ;; Consistency delay test (comment (deftest consistency-delay (run-test! delay-test)))
null
https://raw.githubusercontent.com/gator1/jepsen/1932cbd72cbc1f6c2a27abe0fe347ea989f0cfbb/cassandra/test/cassandra/mv_test.clj
clojure
Steady state cluster tests Bootstrapping tests Decommission tests Consistency delay test
(ns cassandra.mv-test (:require [clojure.test :refer :all] [clojure.pprint :refer [pprint]] [cassandra.mv :refer :all] [cassandra.core-test :refer :all] [jepsen [core :as jepsen] [report :as report]])) (deftest ^:mv ^:steady mv-bridge (run-test! bridge-test)) (deftest ^:mv ^:steady mv-isolate-node (run-test! isolate-node-test)) (deftest ^:mv ^:steady mv-halves (run-test! halves-test)) (deftest ^:mv ^:steady mv-crash-subset (run-test! crash-subset-test)) (deftest ^:mv ^:steady mv-flush-compact (run-test! flush-compact-test)) (deftest ^:clock mv-clock-drift (run-test! clock-drift-test)) (deftest ^:mv ^:bootstrap mv-bridge-bootstrap (run-test! bridge-test-bootstrap)) (deftest ^:mv ^:bootstrap mv-isolate-node-bootstrap (run-test! isolate-node-test-bootstrap)) (deftest ^:mv ^:bootstrap mv-halves-bootstrap (run-test! halves-test-bootstrap)) (deftest ^:mv ^:bootstrap mv-crash-subset-bootstrap (run-test! crash-subset-test-bootstrap)) (deftest ^:clock mv-clock-drift-bootstrap (run-test! clock-drift-test-bootstrap)) (deftest ^:mv ^:decommission mv-bridge-decommission (run-test! bridge-test-decommission)) (deftest ^:mv ^:decommission mv-isolate-node-decommission (run-test! isolate-node-test-decommission)) (deftest ^:mv ^:decommission mv-halves-decommission (run-test! halves-test-decommission)) (deftest ^:mv ^:decommission mv-crash-subset-decommission (run-test! crash-subset-test-decommission)) (deftest ^:clock mv-clock-drift-decommission (run-test! clock-drift-test-decommission)) (comment (deftest consistency-delay (run-test! delay-test)))
69692208bb25e5e26923327aab5d4cfb294c046b77fb5f0efb0892d17d605b4a
psg-mit/marshall
marshall.ml
* The main program using [ ] dyadics . module Marshall_bignum = Main.Make(Dyadic_mpfr)
null
https://raw.githubusercontent.com/psg-mit/marshall/65f20ebe02ce71c306c4bb334d119d939f1afdf9/src/marshall.ml
ocaml
* The main program using [ ] dyadics . module Marshall_bignum = Main.Make(Dyadic_mpfr)
ca9df9ffc467434ea1cdf37b8189a3131ae939ca6397489f8ca158b2290babdf
teamwalnut/graphql-ppx
graphql_compiler.ml
module Generator_utils = Generator_utils module Graphql_lexer = Graphql_lexer module Graphql_parser = Graphql_parser module Graphql_parser_document = Graphql_parser_document module Log = Log module Ppx_config = Ppx_config module Read_schema = Read_schema module Result_decoder = Result_decoder module Result_structure = Result_structure module Source_pos = Source_pos module Validations = Validations module Schema = Schema module Schema_printer = Schema_printer module Graphql_ast = Graphql_ast module Type_utils = Type_utils module Option = Option module Traversal_utils = Traversal_utils module Graphql_printer = Graphql_printer module Ast_serializer_apollo = Ast_serializer_apollo module Extract_type_definitions = Extract_type_definitions module Ast_transforms = Ast_transforms
null
https://raw.githubusercontent.com/teamwalnut/graphql-ppx/8276452ebe8d89a748b6b267afc94161650ab620/src/graphql_compiler/graphql_compiler.ml
ocaml
module Generator_utils = Generator_utils module Graphql_lexer = Graphql_lexer module Graphql_parser = Graphql_parser module Graphql_parser_document = Graphql_parser_document module Log = Log module Ppx_config = Ppx_config module Read_schema = Read_schema module Result_decoder = Result_decoder module Result_structure = Result_structure module Source_pos = Source_pos module Validations = Validations module Schema = Schema module Schema_printer = Schema_printer module Graphql_ast = Graphql_ast module Type_utils = Type_utils module Option = Option module Traversal_utils = Traversal_utils module Graphql_printer = Graphql_printer module Ast_serializer_apollo = Ast_serializer_apollo module Extract_type_definitions = Extract_type_definitions module Ast_transforms = Ast_transforms
92fb0a0af29447ae728e677e9844e0bbebf376ea820de45fa78d9a6ccdbd973e
jesperes/aoc_erlang
aoc2019_day18.erl
Advent of Code solution for 2019 day 18 . Created : 2019 - 12 - 18T18:36:27 + 00:00 -module(aoc2019_day18). -include_lib("stdlib/include/assert.hrl"). -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2019, day = 18, name = "Many-Worlds Intepretation", expected = {3856, 1660}, has_input_file = true}. -type input_type() :: {{Width :: integer(), Height :: integer()}, AllKeys :: binary(), Grid :: map()}. -type result_type() :: integer(). -spec parse(Binary :: binary()) -> input_type(). parse(Binary) -> [{Width, _} | _] = binary:matches(Binary, <<"\n">>), ?assertEqual($\n, binary:at(Binary, Width)), Height = byte_size(Binary) div (Width + 1), AllKeys = usort(find_all_keys(Binary)), {{Width, Height}, AllKeys, parse(Binary, 0, Width, #{})}. -spec solve1(Input :: input_type()) -> result_type(). solve1(Input) -> {_, AllKeys, Grid} = Input, [StartPos] = find_start_points(Grid), Grid0 = maps:put(keys, AllKeys, Grid), {found, Node, State} = dijkstra:dijkstra(Grid0, {StartPos, <<>>}, fun eval1/2), length(dijkstra:shortest_path(State, Node)) - 1. %% Part 2 . We assume that each bot can ignore doors for which there %% are no keys in that quadrant. When encountering such a door, the %% bot will simply "wait" until the key is found by another bot. We run the searches independently in each of the four quadrants , and %% sum up the shortest paths. %% %% ... @#@ .@. = > # # # %% ... @#@ %% -spec solve2(Input :: input_type()) -> result_type(). solve2(Input) -> {_, _, Grid} = Input, [Center] = find_start_points(Grid), Grid0 = patch_center(Grid, Center), Bots = lists:sort(find_start_points(Grid0)), Quadrants = lists:zip([nw, sw, ne, se], Bots), lists:foldl(fun({Quadrant, BotPos}, Acc) -> {KeysToFind, Doors} = quadrant(Quadrant, Center, Grid0), DoorsStr = binary_to_list(Doors), KeysStr = binary_to_list(KeysToFind), DoorsToIgnore = lists:filter(fun(C) -> not lists:member(C + 32, KeysStr) end, DoorsStr), EvalFun = fun({Pos, KeysIn}, Graph) -> case KeysIn =:= KeysToFind of true -> found; false -> lists:foldl(fun(Adj, InnerAcc) -> case maps:get(Adj, Graph) of $# -> InnerAcc; C when (C =:= $.) or (C =:= $@) -> [{1, {Adj, KeysIn}} | InnerAcc]; C when (C >= $A) and (C =< $Z) -> case lists:member(C, DoorsToIgnore) of true -> [{1, {Adj, KeysIn}} | InnerAcc]; false -> LC = list_to_binary([C + 32]), case binary:match(KeysIn, LC) of nomatch -> Acc; _ -> [{1, {Adj, KeysIn}} | InnerAcc] end end; C when (C >= $a) and (C =< $z) -> Str = binary_to_list(KeysIn), B = list_to_binary(lists:usort([C | Str])), [{1, {Adj, B}} | InnerAcc] end end, [], adj(Pos)) end end, {found, Node, State} = dijkstra:dijkstra(Grid0, {BotPos, <<>>}, EvalFun), Acc + dijkstra:shortest_dist(State, Node) end, 0, Quadrants). Search callback function for part 1 . See dijkstra.erl . eval1({Pos, KeysIn}, Graph) -> case KeysIn =:= maps:get(keys, Graph) of true -> found; false -> lists:foldl(fun(Adj, Acc) -> case maps:get(Adj, Graph) of $# -> Acc; C when (C =:= $.) or (C =:= $@) -> [{1, {Adj, KeysIn}} | Acc]; C when (C >= $A) and (C =< $Z) -> LC = list_to_binary([C + 32]), case binary:match(KeysIn, LC) of nomatch -> Acc; _ -> [{1, {Adj, KeysIn}} | Acc] end; C when (C >= $a) and (C =< $z) -> Str = binary_to_list(KeysIn), B = list_to_binary(lists:usort([C | Str])), [{1, {Adj, B}} | Acc] end end, [], adj(Pos)) end. %% Return a list of {Keys,Doors} in the given quadrant. quadrant(Quadrant, Center, Grid) -> {Keys, Doors} = maps:fold(fun(K, C, {Kin, Din} = Acc) -> case is_quadrant(Quadrant, K, Center) of false -> Acc; true -> if (C >= $a) and (C =< $z) -> {<<C, Kin/binary>>, Din}; (C >= $A) and (C =< $Z) -> {Kin, <<C, Din/binary>>}; true -> Acc end end end, {<<>>, <<>>}, Grid), {usort(Keys), usort(Doors)}. %% ============================================================ %% Utility functions %% ============================================================ find_all_keys(<<>>) -> <<>>; find_all_keys(<<K, Rest/binary>>) when (K >= $a) and (K =< $z) -> <<K, (find_all_keys(Rest))/binary>>; find_all_keys(<<_, Rest/binary>>) -> find_all_keys(Rest). usort(List) when is_list(List) -> lists:usort(List); usort(Bin) when is_binary(Bin) -> list_to_binary(lists:usort(binary_to_list(Bin))). adj({X, Y}) -> [{X - 1, Y}, {X + 1, Y}, {X, Y + 1}, {X, Y - 1}]. is_quadrant(nw, {X, Y}, {Xc, Yc}) -> (X < Xc) and (Y < Yc); is_quadrant(ne, {X, Y}, {Xc, Yc}) -> (X > Xc) and (Y < Yc); is_quadrant(sw, {X, Y}, {Xc, Yc}) -> (X < Xc) and (Y > Yc); is_quadrant(se, {X, Y}, {Xc, Yc}) -> (X > Xc) and (Y > Yc). %% ============================================================ Parse helpers %% ============================================================ parse(<<>>, _, _Width, Grid) -> Grid; parse(<<$\n, Rest/binary>>, N, Width, Grid) -> parse(Rest, N + 1, Width, Grid); parse(<<C, Rest/binary>>, N, Width, Grid) -> Pos = xy_from_offset(N, Width), parse(Rest, N + 1, Width, maps:put(Pos, C, Grid)). xy_from_offset(N, Width) -> {N rem (Width + 1), N div (Width + 1)}. find_start_points(Grid) -> lists:filtermap(fun ({Pos, $@}) -> {true, Pos}; (_) -> false end, maps:to_list(Grid)). patch_center(Grid, {X, Y}) -> maps:merge(Grid, #{{X - 1, Y - 1} => $@, {X, Y - 1} => $#, {X + 1, Y - 1} => $@, {X - 1, Y} => $#, {X, Y} => $#, {X + 1, Y} => $#, {X - 1, Y + 1} => $@, {X, Y + 1} => $#, {X + 1, Y + 1} => $@}).
null
https://raw.githubusercontent.com/jesperes/aoc_erlang/ec0786088fb9ab886ee57e17ea0149ba3e91810a/src/2019/aoc2019_day18.erl
erlang
are no keys in that quadrant. When encountering such a door, the bot will simply "wait" until the key is found by another bot. We sum up the shortest paths. ... @#@ ... @#@ Return a list of {Keys,Doors} in the given quadrant. ============================================================ Utility functions ============================================================ ============================================================ ============================================================
Advent of Code solution for 2019 day 18 . Created : 2019 - 12 - 18T18:36:27 + 00:00 -module(aoc2019_day18). -include_lib("stdlib/include/assert.hrl"). -behavior(aoc_puzzle). -export([parse/1, solve1/1, solve2/1, info/0]). -include("aoc_puzzle.hrl"). -spec info() -> aoc_puzzle(). info() -> #aoc_puzzle{module = ?MODULE, year = 2019, day = 18, name = "Many-Worlds Intepretation", expected = {3856, 1660}, has_input_file = true}. -type input_type() :: {{Width :: integer(), Height :: integer()}, AllKeys :: binary(), Grid :: map()}. -type result_type() :: integer(). -spec parse(Binary :: binary()) -> input_type(). parse(Binary) -> [{Width, _} | _] = binary:matches(Binary, <<"\n">>), ?assertEqual($\n, binary:at(Binary, Width)), Height = byte_size(Binary) div (Width + 1), AllKeys = usort(find_all_keys(Binary)), {{Width, Height}, AllKeys, parse(Binary, 0, Width, #{})}. -spec solve1(Input :: input_type()) -> result_type(). solve1(Input) -> {_, AllKeys, Grid} = Input, [StartPos] = find_start_points(Grid), Grid0 = maps:put(keys, AllKeys, Grid), {found, Node, State} = dijkstra:dijkstra(Grid0, {StartPos, <<>>}, fun eval1/2), length(dijkstra:shortest_path(State, Node)) - 1. Part 2 . We assume that each bot can ignore doors for which there run the searches independently in each of the four quadrants , and .@. = > # # # -spec solve2(Input :: input_type()) -> result_type(). solve2(Input) -> {_, _, Grid} = Input, [Center] = find_start_points(Grid), Grid0 = patch_center(Grid, Center), Bots = lists:sort(find_start_points(Grid0)), Quadrants = lists:zip([nw, sw, ne, se], Bots), lists:foldl(fun({Quadrant, BotPos}, Acc) -> {KeysToFind, Doors} = quadrant(Quadrant, Center, Grid0), DoorsStr = binary_to_list(Doors), KeysStr = binary_to_list(KeysToFind), DoorsToIgnore = lists:filter(fun(C) -> not lists:member(C + 32, KeysStr) end, DoorsStr), EvalFun = fun({Pos, KeysIn}, Graph) -> case KeysIn =:= KeysToFind of true -> found; false -> lists:foldl(fun(Adj, InnerAcc) -> case maps:get(Adj, Graph) of $# -> InnerAcc; C when (C =:= $.) or (C =:= $@) -> [{1, {Adj, KeysIn}} | InnerAcc]; C when (C >= $A) and (C =< $Z) -> case lists:member(C, DoorsToIgnore) of true -> [{1, {Adj, KeysIn}} | InnerAcc]; false -> LC = list_to_binary([C + 32]), case binary:match(KeysIn, LC) of nomatch -> Acc; _ -> [{1, {Adj, KeysIn}} | InnerAcc] end end; C when (C >= $a) and (C =< $z) -> Str = binary_to_list(KeysIn), B = list_to_binary(lists:usort([C | Str])), [{1, {Adj, B}} | InnerAcc] end end, [], adj(Pos)) end end, {found, Node, State} = dijkstra:dijkstra(Grid0, {BotPos, <<>>}, EvalFun), Acc + dijkstra:shortest_dist(State, Node) end, 0, Quadrants). Search callback function for part 1 . See dijkstra.erl . eval1({Pos, KeysIn}, Graph) -> case KeysIn =:= maps:get(keys, Graph) of true -> found; false -> lists:foldl(fun(Adj, Acc) -> case maps:get(Adj, Graph) of $# -> Acc; C when (C =:= $.) or (C =:= $@) -> [{1, {Adj, KeysIn}} | Acc]; C when (C >= $A) and (C =< $Z) -> LC = list_to_binary([C + 32]), case binary:match(KeysIn, LC) of nomatch -> Acc; _ -> [{1, {Adj, KeysIn}} | Acc] end; C when (C >= $a) and (C =< $z) -> Str = binary_to_list(KeysIn), B = list_to_binary(lists:usort([C | Str])), [{1, {Adj, B}} | Acc] end end, [], adj(Pos)) end. quadrant(Quadrant, Center, Grid) -> {Keys, Doors} = maps:fold(fun(K, C, {Kin, Din} = Acc) -> case is_quadrant(Quadrant, K, Center) of false -> Acc; true -> if (C >= $a) and (C =< $z) -> {<<C, Kin/binary>>, Din}; (C >= $A) and (C =< $Z) -> {Kin, <<C, Din/binary>>}; true -> Acc end end end, {<<>>, <<>>}, Grid), {usort(Keys), usort(Doors)}. find_all_keys(<<>>) -> <<>>; find_all_keys(<<K, Rest/binary>>) when (K >= $a) and (K =< $z) -> <<K, (find_all_keys(Rest))/binary>>; find_all_keys(<<_, Rest/binary>>) -> find_all_keys(Rest). usort(List) when is_list(List) -> lists:usort(List); usort(Bin) when is_binary(Bin) -> list_to_binary(lists:usort(binary_to_list(Bin))). adj({X, Y}) -> [{X - 1, Y}, {X + 1, Y}, {X, Y + 1}, {X, Y - 1}]. is_quadrant(nw, {X, Y}, {Xc, Yc}) -> (X < Xc) and (Y < Yc); is_quadrant(ne, {X, Y}, {Xc, Yc}) -> (X > Xc) and (Y < Yc); is_quadrant(sw, {X, Y}, {Xc, Yc}) -> (X < Xc) and (Y > Yc); is_quadrant(se, {X, Y}, {Xc, Yc}) -> (X > Xc) and (Y > Yc). Parse helpers parse(<<>>, _, _Width, Grid) -> Grid; parse(<<$\n, Rest/binary>>, N, Width, Grid) -> parse(Rest, N + 1, Width, Grid); parse(<<C, Rest/binary>>, N, Width, Grid) -> Pos = xy_from_offset(N, Width), parse(Rest, N + 1, Width, maps:put(Pos, C, Grid)). xy_from_offset(N, Width) -> {N rem (Width + 1), N div (Width + 1)}. find_start_points(Grid) -> lists:filtermap(fun ({Pos, $@}) -> {true, Pos}; (_) -> false end, maps:to_list(Grid)). patch_center(Grid, {X, Y}) -> maps:merge(Grid, #{{X - 1, Y - 1} => $@, {X, Y - 1} => $#, {X + 1, Y - 1} => $@, {X - 1, Y} => $#, {X, Y} => $#, {X + 1, Y} => $#, {X - 1, Y + 1} => $@, {X, Y + 1} => $#, {X + 1, Y + 1} => $@}).
3487a756d00c5ae0d3e3e6314829bac4f31347c641fc2d925de9b77fb0d821c8
ruhatch/mirage-oram
oram_tests.ml
open Alcotest open Core_kernel.Std open Lwt open Testable open Generators let oram_tests = [ "OramFloorLog_One_Zero", `Quick, (fun () -> check int "" 0 (O.floor_log 1L)); "OramFloorLog_OneTwentySeven_Six", `Quick, (fun () -> check int "" 6 (O.floor_log 127L)); "OramFloorLog_OneTwentyEight_Seven", `Quick, (fun () -> check int "" 7 (O.floor_log 128L)); "OramBlockInitialise_Initialised_BlockZeroZero", `Quick, (fun () -> check (lwt_t @@ result error bool) "" (fun () -> return (`Ok true)) (fun () -> newORAM () >>= fun bd -> O.readBucket bd 0L >>= fun bucket -> return (`Ok (List.for_all ~f:(fun (a,d) -> a = -1L) bucket)))); "ORAMWriteFile_EmptyString_ReadOutEmptyString", `Quick, (fun () -> check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd "" >>= fun file -> return (`Ok (file))) (fun () -> newORAM () >>= fun bd -> newFile bd "" >>= fun file -> O.write bd 0L [file] >>= fun () -> let buff = Cstruct.create (Cstruct.len file) in O.read bd 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteFile_String_ReadOutString", `Quick, (fun () -> check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd "All work and no play makes Dave a dull boy" >>= fun file -> return (`Ok (file))) (fun () -> newORAM () >>= fun bd -> newFile bd "All work and no play makes Dave a dull boy" >>= fun file -> O.write bd 0L [file] >>= fun () -> let buff = Cstruct.create (Cstruct.len file) in O.read bd 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteFile_ProjectGutenberg_ReadOutCorrectly", `Quick, (fun () -> let contents = readWholeFile "testFiles/gutenberg/pg61.txt" in check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> return (`Ok file)) (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> O.write bd 0L [file] >>= fun () -> let buff = Cstruct.create (Cstruct.len file) in O.read bd 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteFile_ProjectGutenbergReconnect_ReadOutCorrectly", `Quick, (fun () -> let contents = readWholeFile "testFiles/gutenberg/pg61.txt" in check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> return (`Ok file)) (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> O.write bd 0L [file] >>= fun () -> let%lwt () = O.disconnect bd in Block.connect "disk.img" >>= fun blockDevice -> O.connect blockDevice >>= fun oram -> let buff = Cstruct.create (Cstruct.len file) in O.read oram 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteBucket_QuickCheck_ReadSameValueFromBucket", `Slow, (fun () -> let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in Quickcheck.test (Quickcheck.Generator.tuple2 (addressGenerator info.O.size_sectors) (bucketGenerator info.O.size_sectors info.O.sector_size 4)) (fun (address, bucketToWrite) -> check (lwt_t @@ result error bucket) "" (fun () -> return (`Ok bucketToWrite)) (fun () -> O.writeBucket oram address bucketToWrite >>= fun () -> O.readBucket oram address))); "ORAMWritePathToLeaf_QuickCheck_ReadSamePath", `Slow, (fun () -> Printf.printf "Testing\n"; let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in let structuralInfo = Lwt_main.run (O.getStructuralInfo oram) in Quickcheck.test ~trials:1 ( leafGenerator structuralInfo . O.numLeaves ) (bucketGenerator info.O.size_sectors info.O.sector_size 4)) ~f:(fun (leaf, pathToWrite) -> check (lwt_t @@ result error (list bucket)) "" (fun () -> return (`Ok [pathToWrite])) (fun () -> O.writePathToLeaf oram leaf [pathToWrite] >>= fun () -> O.readPathToLeaf oram leaf))); "ORAMAccess_QuickCheck_ReadSameBlock", `Slow, (fun () -> let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in Quickcheck.test (Quickcheck.Generator.tuple2 (addressGenerator info.O.size_sectors) (cstructGenerator info.O.sector_size)) (fun (address, data) -> check (lwt_t @@ result error cstruct) "" (fun () -> return (`Ok data)) (fun () -> O.access oram O.Write address (Some data) >>= fun _ -> O.access oram O.Read address None))); "ORAMGetSet_QuickCheck_GetSamePosition", `Slow, (fun () -> let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in let structuralInfo = Lwt_main.run (O.getStructuralInfo oram) in Quickcheck.test (Quickcheck.Generator.tuple2 (addressGenerator info.O.size_sectors) (leafGenerator structuralInfo.O.numLeaves)) (fun (address, position) -> check (lwt_t @@ result error int64) "" (fun () -> return (`Ok position)) (fun () -> O.set oram address position >>= fun () -> O.get oram address))); ] let () = Alcotest.run "ORAM Tests" [ "ORAM Tests", oram_tests ]
null
https://raw.githubusercontent.com/ruhatch/mirage-oram/533a7f7726c4a499b60c71ed627b730349a3816b/tests/oram_tests.ml
ocaml
open Alcotest open Core_kernel.Std open Lwt open Testable open Generators let oram_tests = [ "OramFloorLog_One_Zero", `Quick, (fun () -> check int "" 0 (O.floor_log 1L)); "OramFloorLog_OneTwentySeven_Six", `Quick, (fun () -> check int "" 6 (O.floor_log 127L)); "OramFloorLog_OneTwentyEight_Seven", `Quick, (fun () -> check int "" 7 (O.floor_log 128L)); "OramBlockInitialise_Initialised_BlockZeroZero", `Quick, (fun () -> check (lwt_t @@ result error bool) "" (fun () -> return (`Ok true)) (fun () -> newORAM () >>= fun bd -> O.readBucket bd 0L >>= fun bucket -> return (`Ok (List.for_all ~f:(fun (a,d) -> a = -1L) bucket)))); "ORAMWriteFile_EmptyString_ReadOutEmptyString", `Quick, (fun () -> check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd "" >>= fun file -> return (`Ok (file))) (fun () -> newORAM () >>= fun bd -> newFile bd "" >>= fun file -> O.write bd 0L [file] >>= fun () -> let buff = Cstruct.create (Cstruct.len file) in O.read bd 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteFile_String_ReadOutString", `Quick, (fun () -> check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd "All work and no play makes Dave a dull boy" >>= fun file -> return (`Ok (file))) (fun () -> newORAM () >>= fun bd -> newFile bd "All work and no play makes Dave a dull boy" >>= fun file -> O.write bd 0L [file] >>= fun () -> let buff = Cstruct.create (Cstruct.len file) in O.read bd 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteFile_ProjectGutenberg_ReadOutCorrectly", `Quick, (fun () -> let contents = readWholeFile "testFiles/gutenberg/pg61.txt" in check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> return (`Ok file)) (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> O.write bd 0L [file] >>= fun () -> let buff = Cstruct.create (Cstruct.len file) in O.read bd 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteFile_ProjectGutenbergReconnect_ReadOutCorrectly", `Quick, (fun () -> let contents = readWholeFile "testFiles/gutenberg/pg61.txt" in check (lwt_t @@ result error cstruct) "" (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> return (`Ok file)) (fun () -> newORAM () >>= fun bd -> newFile bd contents >>= fun file -> O.write bd 0L [file] >>= fun () -> let%lwt () = O.disconnect bd in Block.connect "disk.img" >>= fun blockDevice -> O.connect blockDevice >>= fun oram -> let buff = Cstruct.create (Cstruct.len file) in O.read oram 0L [buff] >>= fun () -> return (`Ok buff))); "ORAMWriteBucket_QuickCheck_ReadSameValueFromBucket", `Slow, (fun () -> let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in Quickcheck.test (Quickcheck.Generator.tuple2 (addressGenerator info.O.size_sectors) (bucketGenerator info.O.size_sectors info.O.sector_size 4)) (fun (address, bucketToWrite) -> check (lwt_t @@ result error bucket) "" (fun () -> return (`Ok bucketToWrite)) (fun () -> O.writeBucket oram address bucketToWrite >>= fun () -> O.readBucket oram address))); "ORAMWritePathToLeaf_QuickCheck_ReadSamePath", `Slow, (fun () -> Printf.printf "Testing\n"; let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in let structuralInfo = Lwt_main.run (O.getStructuralInfo oram) in Quickcheck.test ~trials:1 ( leafGenerator structuralInfo . O.numLeaves ) (bucketGenerator info.O.size_sectors info.O.sector_size 4)) ~f:(fun (leaf, pathToWrite) -> check (lwt_t @@ result error (list bucket)) "" (fun () -> return (`Ok [pathToWrite])) (fun () -> O.writePathToLeaf oram leaf [pathToWrite] >>= fun () -> O.readPathToLeaf oram leaf))); "ORAMAccess_QuickCheck_ReadSameBlock", `Slow, (fun () -> let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in Quickcheck.test (Quickcheck.Generator.tuple2 (addressGenerator info.O.size_sectors) (cstructGenerator info.O.sector_size)) (fun (address, data) -> check (lwt_t @@ result error cstruct) "" (fun () -> return (`Ok data)) (fun () -> O.access oram O.Write address (Some data) >>= fun _ -> O.access oram O.Read address None))); "ORAMGetSet_QuickCheck_GetSamePosition", `Slow, (fun () -> let oram = match Lwt_main.run (newORAM ()) with | `Ok oram -> oram | `Error _ -> failwith "Failed to connect to ORAM" in let info = Lwt_main.run (O.get_info oram) in let structuralInfo = Lwt_main.run (O.getStructuralInfo oram) in Quickcheck.test (Quickcheck.Generator.tuple2 (addressGenerator info.O.size_sectors) (leafGenerator structuralInfo.O.numLeaves)) (fun (address, position) -> check (lwt_t @@ result error int64) "" (fun () -> return (`Ok position)) (fun () -> O.set oram address position >>= fun () -> O.get oram address))); ] let () = Alcotest.run "ORAM Tests" [ "ORAM Tests", oram_tests ]
23ae81307e88e944d010a5b8166b11a3732bbf043de4aa1a1016795e88aeb504
bootstrapworld/curr
Game5.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname Game5) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") ;; DATA: ; a world is a string number number number number (define-struct world (wstatus archerY wumpusX batX arrowX)) ;; STARTING WORLD (define START (make-world "asleep" 40 210 620 800)) (define NEXT (make-world "asleep" 40 210 580 820)) ;; GRAPHICS (define BACKGROUND (bitmap "Teachpacks/teachpack-images/BG.jpg")) (define DANGER (scale .7 (bitmap "Teachpacks/teachpack-images/wumpus.png"))) (define FLOCK (bitmap "Teachpacks/teachpack-images/bats.png")) (define PLAYER (scale .7 (bitmap "Teachpacks/teachpack-images/archer.png"))) (define ARROW (scale .5 (bitmap "Teachpacks/teachpack-images/arrow.png"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; GRAPHICS FUNCTIONS: ;; draw-world: world -> Image place FLOCK , PLAYER , ARROW , and DANGER onto BACKGROUND at the right coordinates (define (draw-world w) (put-image FLOCK (world-batX w) 210 (put-image PLAYER 50 (world-archerY w) (put-image ARROW (world-arrowX w) (+ 25 (world-archerY w)) (put-image DANGER (world-wumpusX w) 210 BACKGROUND))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UPDATING FUNCTIONS: ;; update-world: world -> world ;; What does your update-world function do? (define (update-world w) (make-world (world-wstatus w) (world-archerY w) (world-wumpusX w) (- (world-batX w) 10) (+ (world-arrowX w) 20))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; KEY EVENTS: ;; keypress: world string -> world ;; What does your keypress function do? ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TESTS FOR COND: ;; off-left? : number -> boolean ;; Checks whether an object has gone off the left side of the screen ;; off-right? : number -> boolean ;; Checks whether an object has gone off the right side of the screen ;; line-length : number number -> number ;; Finds 1D distance ;; distance : number number number number -> number Finds the 2D distance between two points ;; collide? : number number number number -> boolean determines whether two objects are within 50 pixels of eachother ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; big - bang using the START world ;; on a tick-event, use update-world ;; on a draw-event, use draw-world ;; on a key-event, use keypress (big-bang START (on-tick update-world) (on-draw draw-world) )
null
https://raw.githubusercontent.com/bootstrapworld/curr/443015255eacc1c902a29978df0e3e8e8f3b9430/courses/reactive/resources/source-files/Game5.rkt
racket
about the language level of this file in a form that our tools can easily process. DATA: a world is a string number number number number STARTING WORLD GRAPHICS GRAPHICS FUNCTIONS: draw-world: world -> Image UPDATING FUNCTIONS: update-world: world -> world What does your update-world function do? KEY EVENTS: keypress: world string -> world What does your keypress function do? TESTS FOR COND: off-left? : number -> boolean Checks whether an object has gone off the left side of the screen off-right? : number -> boolean Checks whether an object has gone off the right side of the screen line-length : number number -> number Finds 1D distance distance : number number number number -> number collide? : number number number number -> boolean on a tick-event, use update-world on a draw-event, use draw-world on a key-event, use keypress
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname Game5) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (require "Teachpacks/bootstrap-teachpack.rkt") (define-struct world (wstatus archerY wumpusX batX arrowX)) (define START (make-world "asleep" 40 210 620 800)) (define NEXT (make-world "asleep" 40 210 580 820)) (define BACKGROUND (bitmap "Teachpacks/teachpack-images/BG.jpg")) (define DANGER (scale .7 (bitmap "Teachpacks/teachpack-images/wumpus.png"))) (define FLOCK (bitmap "Teachpacks/teachpack-images/bats.png")) (define PLAYER (scale .7 (bitmap "Teachpacks/teachpack-images/archer.png"))) (define ARROW (scale .5 (bitmap "Teachpacks/teachpack-images/arrow.png"))) place FLOCK , PLAYER , ARROW , and DANGER onto BACKGROUND at the right coordinates (define (draw-world w) (put-image FLOCK (world-batX w) 210 (put-image PLAYER 50 (world-archerY w) (put-image ARROW (world-arrowX w) (+ 25 (world-archerY w)) (put-image DANGER (world-wumpusX w) 210 BACKGROUND))))) (define (update-world w) (make-world (world-wstatus w) (world-archerY w) (world-wumpusX w) (- (world-batX w) 10) (+ (world-arrowX w) 20))) Finds the 2D distance between two points determines whether two objects are within 50 pixels of eachother big - bang using the START world (big-bang START (on-tick update-world) (on-draw draw-world) )
88494a6f375cec96597ba014dd866adc6b16d0c0953af49062557e5bc664263d
gheber/kenzo
disk-pasting-test.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 - * (in-package :kenzo-test-7) (in-suite :kenzo-7) (test disk-pasting-cmpr (let* ((c (cat-7:delta 3)) (cmpr (cat-7:disk-pasting-cmpr (cat-7:cmpr c) 'new))) (is (equal :equal (funcall cmpr 'new 'new))) (is (equal :less (funcall cmpr 'new 5))) (is (equal :greater (funcall cmpr 5 'new))) (is (equal :equal (funcall cmpr 5 5))) (is (equal :less (funcall cmpr 5 6))) (is (equal :greater (funcall cmpr 6 5))))) (test disk-pasting-basis (cat-7:cat-init) (let* ((c (cat-7:delta 3)) (basis (cat-7:disk-pasting-basis (cat-7:basis c) 3 'new))) (funcall basis 3) (funcall basis 2))) (test disk-pasting-intr-dffr (cat-7:cat-init) (let* ((c (cat-7:delta 3)) intr) (signals simple-error (setf intr (cat-7:disk-pasting-intr-dffr (cat-7:dffr c) 3 'new (cat-7:cmbn 2 1 7)))) (setf intr (cat-7:disk-pasting-intr-dffr (cat-7:dffr c) 3 'new (cat-7:? c 3 15))) (funcall intr (cat-7:cmbn 2 1 7)) (funcall intr (cat-7:cmbn 3)) (funcall intr (cat-7:cmbn 3 1 15)) (funcall intr (cat-7:cmbn 3 1 'new 1 15)) (funcall intr (cat-7:cmbn 3 1 'new -1 15)) (funcall intr (cat-7:cmbn 3 -1 'new 1 15)) (funcall intr (cat-7:cmbn 3 -1 'new -1 15)))) (test chcm-disk-pasting (cat-7:cat-init) (let* ((c (cat-7:delta 3)) (s3 (cat-7:chcm-disk-pasting c 3 'new (cat-7:? c 3 15)))) (cat-7:homology s3 0 5))) (test disk-pasting-face (cat-7:cat-init) (let* ((c (cat-7:delta 3)) (face (cat-7:disk-pasting-face (cat-7:cmpr c) (cat-7:face c) 3 'new (list 14 (cat-7:absm 0 13) 11 7)))) (funcall face 0 2 7) (funcall face 0 3 15) (dotimes (i 4) (print (funcall face i 3 'new))))) (test disk-pasting (cat-7:cat-init) (let* ((d2 (cat-7:delta 2)) (s2 (cat-7:disk-pasting d2 2 'new '(6 5 3))) s2xs2) (cat-7:homology s2 0 4) (setf s2xs2 (cat-7:crts-prdc s2 s2)) (cat-7:homology s2xs2 0 6))) (test mrph-disk-pasting-intr (cat-7:cat-init) (let* ((m (cat-7:idnt-mrph (cat-7:delta 3))) (intr (cat-7:mrph-disk-pasting-intr m (cat-7:cmpr (cat-7:delta 3)) 3 'new (cat-7:cmbn 3 -1 15)))) (funcall intr (cat-7:cmbn 2 3 7)) (funcall intr (cat-7:cmbn 3)) (funcall intr (cat-7:cmbn 3 4 15)) (funcall intr (cat-7:cmbn 3 1 'new 1 15)) (funcall intr (cat-7:cmbn 3 -1 'new 1 15)))) (test mrph-disk-pasting (cat-7:cat-init) (let* ((d (cat-7:delta 3)) (m (cat-7:idnt-mrph d)) (sorc (cat-7:chcm-disk-pasting d 3 'new (cat-7:? d 3 15))) (nm (cat-7:mrph-disk-pasting m sorc sorc 3 'new (cat-7:cmbn 3 1 'new)))) (cat-7:? nm (cat-7:cmbn 3 2 'new 3 15)))) (test disk-pasting1 (cat-7:cat-init) (let* ((d (cat-7:delta 2)) (s2 (cat-7:disk-pasting d 2 'new '(6 5 3)))) (cat-7:homology s2 0 4))) (test hmeq-disk-pasting (cat-7:cat-init) (let* ((tcc (cat-7:build-chcm :cmpr #'cat-7:s-cmpr :basis #'(lambda (degr) (case degr (0 (list 'a)) (1 (list 'b)) (otherwise nil))) :intr-dffr #'(lambda (degr gnrt) (if (= 1 degr) (cat-7:cmbn 0 1 'a) (cat-7:zero-cmbn (1- degr)))) :strt :gnrt :orgn '(z-z))) (bcc (cat-7:build-chcm :cmpr #'cat-7:s-cmpr :basis #'(lambda (degr) nil) :intr-dffr #'(lambda (degr gnrt) (error "Impossible.")) :strt :gnrt :orgn '(zero))) (rh (cat-7:build-mrph :sorc tcc :trgt tcc :degr +1 :intr #'(lambda (degr gnrt) (if (zerop degr) (cat-7:cmbn 1 1 'b) (cat-7:zero-cmbn 2))) :strt :gnrt :orgn '(rh))) (hmeq (cat-7:build-hmeq :lrdct (cat-7:trivial-rdct tcc) :rrdct (cat-7:build-rdct :f (cat-7:zero-mrph tcc bcc 0) :g (cat-7:zero-mrph bcc tcc 0) :h rh :orgn '(rrdct)))) (nhmeq (cat-7:hmeq-disk-pasting hmeq 1 'new (cat-7:cmbn 0 1 'a)))) (cat-7:pre-check-rdct (cat-7:lrdct nhmeq)) (setf cat-7:*tc* (cat-7:cmbn 0 1 'a)) (setf cat-7:*bc* cat-7:*tc*) (check-rdct) (setf cat-7:*tc* (cat-7:cmbn 1 1 'new 10 'b)) (setf cat-7:*bc* cat-7:*tc*) (check-rdct) (cat-7:pre-check-rdct (cat-7:rrdct nhmeq)) (setf cat-7:*bc* (cat-7:zero-cmbn 0)) (check-rdct) (setf cat-7:*tc* (cat-7:cmbn 0 1 'a)) (check-rdct)))
null
https://raw.githubusercontent.com/gheber/kenzo/48e2ea398b80f39d3b5954157a7df57e07a362d7/test/kenzo-7/disk-pasting-test.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 - *
(in-package :kenzo-test-7) (in-suite :kenzo-7) (test disk-pasting-cmpr (let* ((c (cat-7:delta 3)) (cmpr (cat-7:disk-pasting-cmpr (cat-7:cmpr c) 'new))) (is (equal :equal (funcall cmpr 'new 'new))) (is (equal :less (funcall cmpr 'new 5))) (is (equal :greater (funcall cmpr 5 'new))) (is (equal :equal (funcall cmpr 5 5))) (is (equal :less (funcall cmpr 5 6))) (is (equal :greater (funcall cmpr 6 5))))) (test disk-pasting-basis (cat-7:cat-init) (let* ((c (cat-7:delta 3)) (basis (cat-7:disk-pasting-basis (cat-7:basis c) 3 'new))) (funcall basis 3) (funcall basis 2))) (test disk-pasting-intr-dffr (cat-7:cat-init) (let* ((c (cat-7:delta 3)) intr) (signals simple-error (setf intr (cat-7:disk-pasting-intr-dffr (cat-7:dffr c) 3 'new (cat-7:cmbn 2 1 7)))) (setf intr (cat-7:disk-pasting-intr-dffr (cat-7:dffr c) 3 'new (cat-7:? c 3 15))) (funcall intr (cat-7:cmbn 2 1 7)) (funcall intr (cat-7:cmbn 3)) (funcall intr (cat-7:cmbn 3 1 15)) (funcall intr (cat-7:cmbn 3 1 'new 1 15)) (funcall intr (cat-7:cmbn 3 1 'new -1 15)) (funcall intr (cat-7:cmbn 3 -1 'new 1 15)) (funcall intr (cat-7:cmbn 3 -1 'new -1 15)))) (test chcm-disk-pasting (cat-7:cat-init) (let* ((c (cat-7:delta 3)) (s3 (cat-7:chcm-disk-pasting c 3 'new (cat-7:? c 3 15)))) (cat-7:homology s3 0 5))) (test disk-pasting-face (cat-7:cat-init) (let* ((c (cat-7:delta 3)) (face (cat-7:disk-pasting-face (cat-7:cmpr c) (cat-7:face c) 3 'new (list 14 (cat-7:absm 0 13) 11 7)))) (funcall face 0 2 7) (funcall face 0 3 15) (dotimes (i 4) (print (funcall face i 3 'new))))) (test disk-pasting (cat-7:cat-init) (let* ((d2 (cat-7:delta 2)) (s2 (cat-7:disk-pasting d2 2 'new '(6 5 3))) s2xs2) (cat-7:homology s2 0 4) (setf s2xs2 (cat-7:crts-prdc s2 s2)) (cat-7:homology s2xs2 0 6))) (test mrph-disk-pasting-intr (cat-7:cat-init) (let* ((m (cat-7:idnt-mrph (cat-7:delta 3))) (intr (cat-7:mrph-disk-pasting-intr m (cat-7:cmpr (cat-7:delta 3)) 3 'new (cat-7:cmbn 3 -1 15)))) (funcall intr (cat-7:cmbn 2 3 7)) (funcall intr (cat-7:cmbn 3)) (funcall intr (cat-7:cmbn 3 4 15)) (funcall intr (cat-7:cmbn 3 1 'new 1 15)) (funcall intr (cat-7:cmbn 3 -1 'new 1 15)))) (test mrph-disk-pasting (cat-7:cat-init) (let* ((d (cat-7:delta 3)) (m (cat-7:idnt-mrph d)) (sorc (cat-7:chcm-disk-pasting d 3 'new (cat-7:? d 3 15))) (nm (cat-7:mrph-disk-pasting m sorc sorc 3 'new (cat-7:cmbn 3 1 'new)))) (cat-7:? nm (cat-7:cmbn 3 2 'new 3 15)))) (test disk-pasting1 (cat-7:cat-init) (let* ((d (cat-7:delta 2)) (s2 (cat-7:disk-pasting d 2 'new '(6 5 3)))) (cat-7:homology s2 0 4))) (test hmeq-disk-pasting (cat-7:cat-init) (let* ((tcc (cat-7:build-chcm :cmpr #'cat-7:s-cmpr :basis #'(lambda (degr) (case degr (0 (list 'a)) (1 (list 'b)) (otherwise nil))) :intr-dffr #'(lambda (degr gnrt) (if (= 1 degr) (cat-7:cmbn 0 1 'a) (cat-7:zero-cmbn (1- degr)))) :strt :gnrt :orgn '(z-z))) (bcc (cat-7:build-chcm :cmpr #'cat-7:s-cmpr :basis #'(lambda (degr) nil) :intr-dffr #'(lambda (degr gnrt) (error "Impossible.")) :strt :gnrt :orgn '(zero))) (rh (cat-7:build-mrph :sorc tcc :trgt tcc :degr +1 :intr #'(lambda (degr gnrt) (if (zerop degr) (cat-7:cmbn 1 1 'b) (cat-7:zero-cmbn 2))) :strt :gnrt :orgn '(rh))) (hmeq (cat-7:build-hmeq :lrdct (cat-7:trivial-rdct tcc) :rrdct (cat-7:build-rdct :f (cat-7:zero-mrph tcc bcc 0) :g (cat-7:zero-mrph bcc tcc 0) :h rh :orgn '(rrdct)))) (nhmeq (cat-7:hmeq-disk-pasting hmeq 1 'new (cat-7:cmbn 0 1 'a)))) (cat-7:pre-check-rdct (cat-7:lrdct nhmeq)) (setf cat-7:*tc* (cat-7:cmbn 0 1 'a)) (setf cat-7:*bc* cat-7:*tc*) (check-rdct) (setf cat-7:*tc* (cat-7:cmbn 1 1 'new 10 'b)) (setf cat-7:*bc* cat-7:*tc*) (check-rdct) (cat-7:pre-check-rdct (cat-7:rrdct nhmeq)) (setf cat-7:*bc* (cat-7:zero-cmbn 0)) (check-rdct) (setf cat-7:*tc* (cat-7:cmbn 0 1 'a)) (check-rdct)))
6ae5546d5622bf3f3cba522147bfd5ea7131d7a8b510856df635050aeed7c8c0
coast-framework/db
helper_test.clj
(ns db.schema.helper-test (:require [db.schema.helper :refer [version integer text create-table index foreign-key bool]] [clojure.test :refer [deftest testing is]])) (deftest version-test (is (= {"account" {:column-names #{"id" "name" "email" "password"} :columns [{:type :integer :name :id :primary-key true} {:type :text :name :name :null false} {:type :text :name :email :null false} {:type :text :name :password :null false}] :foreign-keys [] :indexes [[:email "index_email_on_account"]]} "todo" {:column-names #{"id" "name" "account_id" "finished"} :columns [{:type :integer :name :id :primary-key true} {:type :text :name :name :null false} {:type :boolean :name :finished :null false} {:type :integer :name :account-id}] :indexes [[:account-id "index_account_id_on_todo"]] :foreign-keys [[:account :todo]]}} (version "123" (create-table :account (integer :id :primary-key true) (text :name :null false) (text :email :null false) (text :password :null false) (index :email :name "index_email_on_account")) (create-table :todo (integer :id :primary-key true) (text :name :null false) (bool :finished :null false) (integer :account-id) (foreign-key :account :todo) (index :account-id :name "index_account_id_on_todo"))))))
null
https://raw.githubusercontent.com/coast-framework/db/e738cd6402a89c591363ac6f3e7a6e08bcc28a0e/test/db/schema/helper_test.clj
clojure
(ns db.schema.helper-test (:require [db.schema.helper :refer [version integer text create-table index foreign-key bool]] [clojure.test :refer [deftest testing is]])) (deftest version-test (is (= {"account" {:column-names #{"id" "name" "email" "password"} :columns [{:type :integer :name :id :primary-key true} {:type :text :name :name :null false} {:type :text :name :email :null false} {:type :text :name :password :null false}] :foreign-keys [] :indexes [[:email "index_email_on_account"]]} "todo" {:column-names #{"id" "name" "account_id" "finished"} :columns [{:type :integer :name :id :primary-key true} {:type :text :name :name :null false} {:type :boolean :name :finished :null false} {:type :integer :name :account-id}] :indexes [[:account-id "index_account_id_on_todo"]] :foreign-keys [[:account :todo]]}} (version "123" (create-table :account (integer :id :primary-key true) (text :name :null false) (text :email :null false) (text :password :null false) (index :email :name "index_email_on_account")) (create-table :todo (integer :id :primary-key true) (text :name :null false) (bool :finished :null false) (integer :account-id) (foreign-key :account :todo) (index :account-id :name "index_account_id_on_todo"))))))
dda529c5811aff8207e6765b7bf13ce42725cea63f4457a0d582ba1bb2ceea93
janestreet/core
univ_map_intf.ml
* Universal / heterogeneous maps , useful for storing values of arbitrary type in a single map . In order to recover a value , it must be looked up with exactly the [ Key.t ] it was stored in . In other words , given different [ from the same [ string ] , one will not be able to recover the key stored in the other one . This is similar to [ Univ ] in spirit . map. In order to recover a value, it must be looked up with exactly the [Key.t] it was stored in. In other words, given different [Key.t]s from the same [string], one will not be able to recover the key stored in the other one. This is similar to [Univ] in spirit. *) open! Base module type Key = sig type 'a t [@@deriving sexp_of] (** For correct behavior of the map, [type_id] must return the same [Type_equal.Id] on different calls on the same input. *) val type_id : 'a t -> 'a Type_equal.Id.t end module type Data = sig type 'a t [@@deriving sexp_of] end module type Data1 = sig type ('s, 'a) t [@@deriving sexp_of] end module type S1 = sig (** The ['s] parameter is shared across all values stored in the map. *) type 's t [@@deriving sexp_of] module Key : Key type ('s, 'a) data val invariant : _ t -> unit val empty : _ t val singleton : 'a Key.t -> ('s, 'a) data -> 's t val is_empty : _ t -> bool val set : 's t -> key:'a Key.t -> data:('s, 'a) data -> 's t val mem : _ t -> _ Key.t -> bool val mem_by_id : _ t -> Type_equal.Id.Uid.t -> bool val find : 's t -> 'a Key.t -> ('s, 'a) data option val find_exn : 's t -> 'a Key.t -> ('s, 'a) data val add : 's t -> key:'a Key.t -> data:('s, 'a) data -> [ `Ok of 's t | `Duplicate ] val add_exn : 's t -> key:'a Key.t -> data:('s, 'a) data -> 's t val change : 's t -> 'a Key.t -> f:(('s, 'a) data option -> ('s, 'a) data option) -> 's t val change_exn : 's t -> 'a Key.t -> f:(('s, 'a) data -> ('s, 'a) data) -> 's t val update : 's t -> 'a Key.t -> f:(('s, 'a) data option -> ('s, 'a) data) -> 's t val remove : 's t -> 'a Key.t -> 's t val remove_by_id : 's t -> Type_equal.Id.Uid.t -> 's t module Packed : sig type 's t = T : 'a Key.t * ('s, 'a) data -> 's t end val to_alist : 's t -> 's Packed.t list val of_alist_exn : 's Packed.t list -> 's t val type_equal : ('s t, 's Packed.t Map.M(Type_equal.Id.Uid).t) Type_equal.t end module type S = sig type t [@@deriving sexp_of] module Key : Key type 'a data include Invariant.S with type t := t val empty : t val singleton : 'a Key.t -> 'a data -> t val is_empty : t -> bool val set : t -> key:'a Key.t -> data:'a data -> t val mem : t -> 'a Key.t -> bool val mem_by_id : t -> Type_equal.Id.Uid.t -> bool val find : t -> 'a Key.t -> 'a data option val find_exn : t -> 'a Key.t -> 'a data val add : t -> key:'a Key.t -> data:'a data -> [ `Ok of t | `Duplicate ] val add_exn : t -> key:'a Key.t -> data:'a data -> t val change : t -> 'a Key.t -> f:('a data option -> 'a data option) -> t val change_exn : t -> 'a Key.t -> f:('a data -> 'a data) -> t val update : t -> 'a Key.t -> f:('a data option -> 'a data) -> t val remove : t -> 'a Key.t -> t val remove_by_id : t -> Type_equal.Id.Uid.t -> t module Packed : sig type 's t1 = T : 'a Key.t * 'a data -> 's t1 type t = unit t1 end (** [to_alist t] returns all values in [t], in increasing order of key type-id name. *) val to_alist : t -> Packed.t list val of_alist_exn : Packed.t list -> t val type_equal : (t, Packed.t Map.M(Type_equal.Id.Uid).t) Type_equal.t end module type Univ_map = sig module type S = S module type S1 = S1 module type Key = Key module type Data = Data module Type_id_key : Key with type 'a t = 'a Type_equal.Id.t include S with type 'a data = 'a and module Key := Type_id_key (** This binding is convenient because existing call sites often refer to [Univ_map.Key.create]. *) module Key = Type_equal.Id module Make (Key : Key) (Data : Data) : S with type 'a data = 'a Data.t and module Key = Key module Make1 (Key : Key) (Data : Data1) : S1 with type ('s, 'a) data = ('s, 'a) Data.t and module Key = Key module Merge (Key : Key) (Input1_data : Data) (Input2_data : Data) (Output_data : Data) : sig type f = { f : 'a. key:'a Key.t -> [ `Left of 'a Input1_data.t | `Right of 'a Input2_data.t | `Both of 'a Input1_data.t * 'a Input2_data.t ] -> 'a Output_data.t option } (** The analogue of the normal [Map.merge] function. *) val merge : Make(Key)(Input1_data).t -> Make(Key)(Input2_data).t -> f:f -> Make(Key)(Output_data).t end module Merge1 (Key : Key) (Input1_data : Data1) (Input2_data : Data1) (Output_data : Data1) : sig type ('s1, 's2, 's3) f = { f : 'a. key:'a Key.t -> [ `Left of ('s1, 'a) Input1_data.t | `Right of ('s2, 'a) Input2_data.t | `Both of ('s1, 'a) Input1_data.t * ('s2, 'a) Input2_data.t ] -> ('s3, 'a) Output_data.t option } (** The analogue of the normal [Map.merge] function. *) val merge : 's1 Make1(Key)(Input1_data).t -> 's2 Make1(Key)(Input2_data).t -> f:('s1, 's2, 's3) f -> 's3 Make1(Key)(Output_data).t end (** keys with associated default values, so that [find] is no longer partial *) module With_default : sig module Key : sig type 'a t val create : default:'a -> name:string -> ('a -> Sexp.t) -> 'a t val id : 'a t -> 'a Type_equal.Id.t end val set : t -> key:'a Key.t -> data:'a -> t val find : t -> 'a Key.t -> 'a val change : t -> 'a Key.t -> f:('a -> 'a) -> t end (** keys that map to an accumulator value with an associated fold operation *) module With_fold : sig module Key : sig type ('a, 'b) t val create : init:'b -> f:('b -> 'a -> 'b) -> name:string -> ('b -> Sexp.t) -> ('a, 'b) t val id : ('a, 'b) t -> 'b Type_equal.Id.t end (** reset the accumulator *) val set : t -> key:('a, 'b) Key.t -> data:'b -> t (** the current accumulator *) val find : t -> ('a, 'b) Key.t -> 'b (** fold value into accumulator *) val add : t -> key:('a, 'b) Key.t -> data:'a -> t (** accumulator update *) val change : t -> ('a, 'b) Key.t -> f:('b -> 'b) -> t end (** list-accumulating keys with a default value of the empty list *) module Multi : sig module Key : sig type 'a t val create : name:string -> ('a -> Sexp.t) -> 'a t val id : 'a t -> 'a list Type_equal.Id.t end val set : t -> key:'a Key.t -> data:'a list -> t val find : t -> 'a Key.t -> 'a list val add : t -> key:'a Key.t -> data:'a -> t val change : t -> 'a Key.t -> f:('a list -> 'a list) -> t end end
null
https://raw.githubusercontent.com/janestreet/core/f382131ccdcb4a8cd21ebf9a49fa42dcf8183de6/univ_map/src/univ_map_intf.ml
ocaml
* For correct behavior of the map, [type_id] must return the same [Type_equal.Id] on different calls on the same input. * The ['s] parameter is shared across all values stored in the map. * [to_alist t] returns all values in [t], in increasing order of key type-id name. * This binding is convenient because existing call sites often refer to [Univ_map.Key.create]. * The analogue of the normal [Map.merge] function. * The analogue of the normal [Map.merge] function. * keys with associated default values, so that [find] is no longer partial * keys that map to an accumulator value with an associated fold operation * reset the accumulator * the current accumulator * fold value into accumulator * accumulator update * list-accumulating keys with a default value of the empty list
* Universal / heterogeneous maps , useful for storing values of arbitrary type in a single map . In order to recover a value , it must be looked up with exactly the [ Key.t ] it was stored in . In other words , given different [ from the same [ string ] , one will not be able to recover the key stored in the other one . This is similar to [ Univ ] in spirit . map. In order to recover a value, it must be looked up with exactly the [Key.t] it was stored in. In other words, given different [Key.t]s from the same [string], one will not be able to recover the key stored in the other one. This is similar to [Univ] in spirit. *) open! Base module type Key = sig type 'a t [@@deriving sexp_of] val type_id : 'a t -> 'a Type_equal.Id.t end module type Data = sig type 'a t [@@deriving sexp_of] end module type Data1 = sig type ('s, 'a) t [@@deriving sexp_of] end module type S1 = sig type 's t [@@deriving sexp_of] module Key : Key type ('s, 'a) data val invariant : _ t -> unit val empty : _ t val singleton : 'a Key.t -> ('s, 'a) data -> 's t val is_empty : _ t -> bool val set : 's t -> key:'a Key.t -> data:('s, 'a) data -> 's t val mem : _ t -> _ Key.t -> bool val mem_by_id : _ t -> Type_equal.Id.Uid.t -> bool val find : 's t -> 'a Key.t -> ('s, 'a) data option val find_exn : 's t -> 'a Key.t -> ('s, 'a) data val add : 's t -> key:'a Key.t -> data:('s, 'a) data -> [ `Ok of 's t | `Duplicate ] val add_exn : 's t -> key:'a Key.t -> data:('s, 'a) data -> 's t val change : 's t -> 'a Key.t -> f:(('s, 'a) data option -> ('s, 'a) data option) -> 's t val change_exn : 's t -> 'a Key.t -> f:(('s, 'a) data -> ('s, 'a) data) -> 's t val update : 's t -> 'a Key.t -> f:(('s, 'a) data option -> ('s, 'a) data) -> 's t val remove : 's t -> 'a Key.t -> 's t val remove_by_id : 's t -> Type_equal.Id.Uid.t -> 's t module Packed : sig type 's t = T : 'a Key.t * ('s, 'a) data -> 's t end val to_alist : 's t -> 's Packed.t list val of_alist_exn : 's Packed.t list -> 's t val type_equal : ('s t, 's Packed.t Map.M(Type_equal.Id.Uid).t) Type_equal.t end module type S = sig type t [@@deriving sexp_of] module Key : Key type 'a data include Invariant.S with type t := t val empty : t val singleton : 'a Key.t -> 'a data -> t val is_empty : t -> bool val set : t -> key:'a Key.t -> data:'a data -> t val mem : t -> 'a Key.t -> bool val mem_by_id : t -> Type_equal.Id.Uid.t -> bool val find : t -> 'a Key.t -> 'a data option val find_exn : t -> 'a Key.t -> 'a data val add : t -> key:'a Key.t -> data:'a data -> [ `Ok of t | `Duplicate ] val add_exn : t -> key:'a Key.t -> data:'a data -> t val change : t -> 'a Key.t -> f:('a data option -> 'a data option) -> t val change_exn : t -> 'a Key.t -> f:('a data -> 'a data) -> t val update : t -> 'a Key.t -> f:('a data option -> 'a data) -> t val remove : t -> 'a Key.t -> t val remove_by_id : t -> Type_equal.Id.Uid.t -> t module Packed : sig type 's t1 = T : 'a Key.t * 'a data -> 's t1 type t = unit t1 end val to_alist : t -> Packed.t list val of_alist_exn : Packed.t list -> t val type_equal : (t, Packed.t Map.M(Type_equal.Id.Uid).t) Type_equal.t end module type Univ_map = sig module type S = S module type S1 = S1 module type Key = Key module type Data = Data module Type_id_key : Key with type 'a t = 'a Type_equal.Id.t include S with type 'a data = 'a and module Key := Type_id_key module Key = Type_equal.Id module Make (Key : Key) (Data : Data) : S with type 'a data = 'a Data.t and module Key = Key module Make1 (Key : Key) (Data : Data1) : S1 with type ('s, 'a) data = ('s, 'a) Data.t and module Key = Key module Merge (Key : Key) (Input1_data : Data) (Input2_data : Data) (Output_data : Data) : sig type f = { f : 'a. key:'a Key.t -> [ `Left of 'a Input1_data.t | `Right of 'a Input2_data.t | `Both of 'a Input1_data.t * 'a Input2_data.t ] -> 'a Output_data.t option } val merge : Make(Key)(Input1_data).t -> Make(Key)(Input2_data).t -> f:f -> Make(Key)(Output_data).t end module Merge1 (Key : Key) (Input1_data : Data1) (Input2_data : Data1) (Output_data : Data1) : sig type ('s1, 's2, 's3) f = { f : 'a. key:'a Key.t -> [ `Left of ('s1, 'a) Input1_data.t | `Right of ('s2, 'a) Input2_data.t | `Both of ('s1, 'a) Input1_data.t * ('s2, 'a) Input2_data.t ] -> ('s3, 'a) Output_data.t option } val merge : 's1 Make1(Key)(Input1_data).t -> 's2 Make1(Key)(Input2_data).t -> f:('s1, 's2, 's3) f -> 's3 Make1(Key)(Output_data).t end module With_default : sig module Key : sig type 'a t val create : default:'a -> name:string -> ('a -> Sexp.t) -> 'a t val id : 'a t -> 'a Type_equal.Id.t end val set : t -> key:'a Key.t -> data:'a -> t val find : t -> 'a Key.t -> 'a val change : t -> 'a Key.t -> f:('a -> 'a) -> t end module With_fold : sig module Key : sig type ('a, 'b) t val create : init:'b -> f:('b -> 'a -> 'b) -> name:string -> ('b -> Sexp.t) -> ('a, 'b) t val id : ('a, 'b) t -> 'b Type_equal.Id.t end val set : t -> key:('a, 'b) Key.t -> data:'b -> t val find : t -> ('a, 'b) Key.t -> 'b val add : t -> key:('a, 'b) Key.t -> data:'a -> t val change : t -> ('a, 'b) Key.t -> f:('b -> 'b) -> t end module Multi : sig module Key : sig type 'a t val create : name:string -> ('a -> Sexp.t) -> 'a t val id : 'a t -> 'a list Type_equal.Id.t end val set : t -> key:'a Key.t -> data:'a list -> t val find : t -> 'a Key.t -> 'a list val add : t -> key:'a Key.t -> data:'a -> t val change : t -> 'a Key.t -> f:('a list -> 'a list) -> t end end
3473497c6710b39062ae4d42e4c6a037cf17e1981d176c1445a73e62b4524e1b
mbj/stratosphere
JsonBodyProperty.hs
module Stratosphere.WAFv2.WebACL.JsonBodyProperty ( module Exports, JsonBodyProperty(..), mkJsonBodyProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import {-# SOURCE #-} Stratosphere.WAFv2.WebACL.JsonMatchPatternProperty as Exports import Stratosphere.ResourceProperties import Stratosphere.Value data JsonBodyProperty = JsonBodyProperty {invalidFallbackBehavior :: (Prelude.Maybe (Value Prelude.Text)), matchPattern :: JsonMatchPatternProperty, matchScope :: (Value Prelude.Text), oversizeHandling :: (Prelude.Maybe (Value Prelude.Text))} mkJsonBodyProperty :: JsonMatchPatternProperty -> Value Prelude.Text -> JsonBodyProperty mkJsonBodyProperty matchPattern matchScope = JsonBodyProperty {matchPattern = matchPattern, matchScope = matchScope, invalidFallbackBehavior = Prelude.Nothing, oversizeHandling = Prelude.Nothing} instance ToResourceProperties JsonBodyProperty where toResourceProperties JsonBodyProperty {..} = ResourceProperties {awsType = "AWS::WAFv2::WebACL.JsonBody", supportsTags = Prelude.False, properties = Prelude.fromList ((Prelude.<>) ["MatchPattern" JSON..= matchPattern, "MatchScope" JSON..= matchScope] (Prelude.catMaybes [(JSON..=) "InvalidFallbackBehavior" Prelude.<$> invalidFallbackBehavior, (JSON..=) "OversizeHandling" Prelude.<$> oversizeHandling]))} instance JSON.ToJSON JsonBodyProperty where toJSON JsonBodyProperty {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["MatchPattern" JSON..= matchPattern, "MatchScope" JSON..= matchScope] (Prelude.catMaybes [(JSON..=) "InvalidFallbackBehavior" Prelude.<$> invalidFallbackBehavior, (JSON..=) "OversizeHandling" Prelude.<$> oversizeHandling]))) instance Property "InvalidFallbackBehavior" JsonBodyProperty where type PropertyType "InvalidFallbackBehavior" JsonBodyProperty = Value Prelude.Text set newValue JsonBodyProperty {..} = JsonBodyProperty {invalidFallbackBehavior = Prelude.pure newValue, ..} instance Property "MatchPattern" JsonBodyProperty where type PropertyType "MatchPattern" JsonBodyProperty = JsonMatchPatternProperty set newValue JsonBodyProperty {..} = JsonBodyProperty {matchPattern = newValue, ..} instance Property "MatchScope" JsonBodyProperty where type PropertyType "MatchScope" JsonBodyProperty = Value Prelude.Text set newValue JsonBodyProperty {..} = JsonBodyProperty {matchScope = newValue, ..} instance Property "OversizeHandling" JsonBodyProperty where type PropertyType "OversizeHandling" JsonBodyProperty = Value Prelude.Text set newValue JsonBodyProperty {..} = JsonBodyProperty {oversizeHandling = Prelude.pure newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/wafv2/gen/Stratosphere/WAFv2/WebACL/JsonBodyProperty.hs
haskell
# SOURCE #
module Stratosphere.WAFv2.WebACL.JsonBodyProperty ( module Exports, JsonBodyProperty(..), mkJsonBodyProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data JsonBodyProperty = JsonBodyProperty {invalidFallbackBehavior :: (Prelude.Maybe (Value Prelude.Text)), matchPattern :: JsonMatchPatternProperty, matchScope :: (Value Prelude.Text), oversizeHandling :: (Prelude.Maybe (Value Prelude.Text))} mkJsonBodyProperty :: JsonMatchPatternProperty -> Value Prelude.Text -> JsonBodyProperty mkJsonBodyProperty matchPattern matchScope = JsonBodyProperty {matchPattern = matchPattern, matchScope = matchScope, invalidFallbackBehavior = Prelude.Nothing, oversizeHandling = Prelude.Nothing} instance ToResourceProperties JsonBodyProperty where toResourceProperties JsonBodyProperty {..} = ResourceProperties {awsType = "AWS::WAFv2::WebACL.JsonBody", supportsTags = Prelude.False, properties = Prelude.fromList ((Prelude.<>) ["MatchPattern" JSON..= matchPattern, "MatchScope" JSON..= matchScope] (Prelude.catMaybes [(JSON..=) "InvalidFallbackBehavior" Prelude.<$> invalidFallbackBehavior, (JSON..=) "OversizeHandling" Prelude.<$> oversizeHandling]))} instance JSON.ToJSON JsonBodyProperty where toJSON JsonBodyProperty {..} = JSON.object (Prelude.fromList ((Prelude.<>) ["MatchPattern" JSON..= matchPattern, "MatchScope" JSON..= matchScope] (Prelude.catMaybes [(JSON..=) "InvalidFallbackBehavior" Prelude.<$> invalidFallbackBehavior, (JSON..=) "OversizeHandling" Prelude.<$> oversizeHandling]))) instance Property "InvalidFallbackBehavior" JsonBodyProperty where type PropertyType "InvalidFallbackBehavior" JsonBodyProperty = Value Prelude.Text set newValue JsonBodyProperty {..} = JsonBodyProperty {invalidFallbackBehavior = Prelude.pure newValue, ..} instance Property "MatchPattern" JsonBodyProperty where type PropertyType "MatchPattern" JsonBodyProperty = JsonMatchPatternProperty set newValue JsonBodyProperty {..} = JsonBodyProperty {matchPattern = newValue, ..} instance Property "MatchScope" JsonBodyProperty where type PropertyType "MatchScope" JsonBodyProperty = Value Prelude.Text set newValue JsonBodyProperty {..} = JsonBodyProperty {matchScope = newValue, ..} instance Property "OversizeHandling" JsonBodyProperty where type PropertyType "OversizeHandling" JsonBodyProperty = Value Prelude.Text set newValue JsonBodyProperty {..} = JsonBodyProperty {oversizeHandling = Prelude.pure newValue, ..}
a963702ef8cefca08cc4a2db305ce42afbbc2b171531b4680b77e2663dd8fa33
racket/db
connection.rkt
#lang racket/unit (require (for-syntax racket/base) racket/class rackunit "../config.rkt" db/base (only-in db/private/generic/common locking%)) (import config^ database^) (export test^) (define test (test-suite "managing connections" (test-case "connection?" (call-with-connection (lambda (c) (check-true (connection? c))))) (test-case "connected, disconnect" (call-with-connection (lambda (c) (check-true (connected? c)) (disconnect c) (check-false (connected? c))))) (test-case "double disconnect okay" (call-with-connection (lambda (c) (disconnect c) (disconnect c)))) (test-case "dbsystem" (call-with-connection (lambda (c) (let ([sys (connection-dbsystem c)]) (check-true (dbsystem? sys)) (check-pred symbol? (dbsystem-name sys)))))) (test-case "connected?, disconnect work w/ custodian damage" (define c1 (make-custodian)) (define cx (parameterize ((current-custodian c1)) (connect-for-test))) ;; cx's ports (if applicable) are managed by c1 (check-true (connected? cx)) (custodian-shutdown-all c1) (check-completes (lambda () (connected? cx)) "connected?") (when (memq dbsys '(mysql postgresql)) ;; wire-based connection is disconnected; it had better know it (check-false (connected? cx))) (check-completes (lambda () (disconnect cx)) "disconnect") (check-false (connected? cx))) (let () (define (do-kill-safe-test do-query-after-shutdown?) (define c1 (make-custodian)) (define cx (parameterize ((current-custodian c1)) (kill-safe-connection (connect-for-test)))) (check-true (connected? cx)) (custodian-shutdown-all c1) (check-completes (lambda () (connected? cx)) "connected?") (when do-query-after-shutdown? (check-exn #rx"query-value" (lambda () (query-value cx (select-val "1"))))) give mgr time to wait on req channel before asking connected ? , ;; since otherwise we might get a cached answer (sync (system-idle-evt)) (check-false (connected? cx)) (check-completes (lambda () (disconnect cx)) "disconnect") ;; no need for sync here; cached and forwarded answers same (check-false (connected? cx))) (test-case "kill-safe w/ custodian damage (w/ query)" (do-kill-safe-test #t)) (test-case "kill-safe w/ custodian damage (w/o query)" ;; Check that kill-safe cx can tell it's disconnected even without ;; doing a query after custodian shutdown. (do-kill-safe-test #f))) (test-case "connected?, disconnect work w/ kill-thread damage" (let ([cx (connect-for-test)]) (when (is-a? cx locking%) (check-true (connected? cx)) (let ([thd (thread (lambda () (send cx call-with-lock 'test (lambda () (sync never-evt)))))]) (kill-thread thd) (check-completes (lambda () (connected? cx)) "connected?") (check-completes (lambda () (disconnect cx)) "disconnect") (check-false (connected? cx)))))) )) (define TIMEOUT 2) ;; seconds (define (check-completes thunk [msg #f]) (let ([t (thread thunk)]) (check-equal? (sync/timeout TIMEOUT (wrap-evt t (lambda _ 'completed))) 'completed msg)))
null
https://raw.githubusercontent.com/racket/db/0336d2522a613e76ebf60705cea3be4c237c447e/db-test/tests/db/db/connection.rkt
racket
cx's ports (if applicable) are managed by c1 wire-based connection is disconnected; it had better know it since otherwise we might get a cached answer no need for sync here; cached and forwarded answers same Check that kill-safe cx can tell it's disconnected even without doing a query after custodian shutdown. seconds
#lang racket/unit (require (for-syntax racket/base) racket/class rackunit "../config.rkt" db/base (only-in db/private/generic/common locking%)) (import config^ database^) (export test^) (define test (test-suite "managing connections" (test-case "connection?" (call-with-connection (lambda (c) (check-true (connection? c))))) (test-case "connected, disconnect" (call-with-connection (lambda (c) (check-true (connected? c)) (disconnect c) (check-false (connected? c))))) (test-case "double disconnect okay" (call-with-connection (lambda (c) (disconnect c) (disconnect c)))) (test-case "dbsystem" (call-with-connection (lambda (c) (let ([sys (connection-dbsystem c)]) (check-true (dbsystem? sys)) (check-pred symbol? (dbsystem-name sys)))))) (test-case "connected?, disconnect work w/ custodian damage" (define c1 (make-custodian)) (define cx (parameterize ((current-custodian c1)) (connect-for-test))) (check-true (connected? cx)) (custodian-shutdown-all c1) (check-completes (lambda () (connected? cx)) "connected?") (when (memq dbsys '(mysql postgresql)) (check-false (connected? cx))) (check-completes (lambda () (disconnect cx)) "disconnect") (check-false (connected? cx))) (let () (define (do-kill-safe-test do-query-after-shutdown?) (define c1 (make-custodian)) (define cx (parameterize ((current-custodian c1)) (kill-safe-connection (connect-for-test)))) (check-true (connected? cx)) (custodian-shutdown-all c1) (check-completes (lambda () (connected? cx)) "connected?") (when do-query-after-shutdown? (check-exn #rx"query-value" (lambda () (query-value cx (select-val "1"))))) give mgr time to wait on req channel before asking connected ? , (sync (system-idle-evt)) (check-false (connected? cx)) (check-completes (lambda () (disconnect cx)) "disconnect") (check-false (connected? cx))) (test-case "kill-safe w/ custodian damage (w/ query)" (do-kill-safe-test #t)) (test-case "kill-safe w/ custodian damage (w/o query)" (do-kill-safe-test #f))) (test-case "connected?, disconnect work w/ kill-thread damage" (let ([cx (connect-for-test)]) (when (is-a? cx locking%) (check-true (connected? cx)) (let ([thd (thread (lambda () (send cx call-with-lock 'test (lambda () (sync never-evt)))))]) (kill-thread thd) (check-completes (lambda () (connected? cx)) "connected?") (check-completes (lambda () (disconnect cx)) "disconnect") (check-false (connected? cx)))))) )) (define (check-completes thunk [msg #f]) (let ([t (thread thunk)]) (check-equal? (sync/timeout TIMEOUT (wrap-evt t (lambda _ 'completed))) 'completed msg)))
114077d57c90896700748e0985a365f057b583f9b250b53c0b72ef1347486335
YoshikuniJujo/funpaala
userId.hs
type Id = Either Int String name :: Id -> [(Id, String)] -> Maybe String name = lookup users :: [(Id, String)] users = [ (Right "yoshio", "Yoshio Yamada"), (Right "yoshio2", "Yoshio Yamada"), (Left 4492, "Tatsuya Yamashiro"), (Right "keiko", "Keiko Koike"), (Left 8855, "Satoru Hananakajima") ]
null
https://raw.githubusercontent.com/YoshikuniJujo/funpaala/5366130826da0e6b1180992dfff94c4a634cda99/samples/22_adt_poly_rec/userId.hs
haskell
type Id = Either Int String name :: Id -> [(Id, String)] -> Maybe String name = lookup users :: [(Id, String)] users = [ (Right "yoshio", "Yoshio Yamada"), (Right "yoshio2", "Yoshio Yamada"), (Left 4492, "Tatsuya Yamashiro"), (Right "keiko", "Keiko Koike"), (Left 8855, "Satoru Hananakajima") ]
5b81c950e659abbf2d95b3428aa9c9dfa97f52b9a4aa11a3d0afbbfe8a17befd
j0sh/ocaml-mqtt
test.ml
open OUnit open Mqtt open Subscriptions let _ = let tests = Mqtt.tests @ Subscriptions.tests in let suite = "mqtt">:::tests in run_test_tt_main suite
null
https://raw.githubusercontent.com/j0sh/ocaml-mqtt/1bbad53afc86babd15d0925127124ff9793577b2/test/test.ml
ocaml
open OUnit open Mqtt open Subscriptions let _ = let tests = Mqtt.tests @ Subscriptions.tests in let suite = "mqtt">:::tests in run_test_tt_main suite
4543ef34594a51b14c5f132e1c49bca86286fc02cdcb922c8a34f008e4304bd9
s-expressionists/Eclector
client.lisp
(cl:in-package #:eclector.concrete-syntax-tree) (defclass cst-client (eclector.parse-result:parse-result-client) ()) (defvar *cst-client* (make-instance 'cst-client)) (defmethod eclector.parse-result:make-expression-result ((client cst-client) expression children source) (labels ((make-atom-cst (expression &optional source) (make-instance 'cst:atom-cst :raw expression :source source)) (make-list-cst (expression children source) (loop for expression in (loop with reversed = '() for sub-expression on expression do (push sub-expression reversed) finally (return reversed)) for child in (reverse children) for previous = (make-instance 'cst:atom-cst :raw nil) then node for node = (make-instance 'cst:cons-cst :raw expression :first child :rest previous) finally (return (reinitialize-instance node :source source))))) (cond ((atom expression) (make-atom-cst expression source)) ;; List structure with corresponding elements. ((and (eql (ignore-errors (list-length expression)) (length children)) (every (lambda (sub-expression child) (eql sub-expression (cst:raw child))) expression children)) (make-list-cst expression children source)) ;; Structure mismatch, try heuristic reconstruction. (t ;; We don't use ;; ;; (cst:reconstruct expression children client) ;; ;; because we want SOURCE for the outer CONS-CST but not ;; any of its children. (destructuring-bind (car . cdr) expression (make-instance 'cst:cons-cst :raw expression :first (cst:reconstruct car children client) :rest (cst:reconstruct cdr children client) :source source))))))
null
https://raw.githubusercontent.com/s-expressionists/Eclector/acd141db4efdbd88d57a8fe4f258ffc18cc47baa/code/concrete-syntax-tree/client.lisp
lisp
List structure with corresponding elements. Structure mismatch, try heuristic reconstruction. We don't use (cst:reconstruct expression children client) because we want SOURCE for the outer CONS-CST but not any of its children.
(cl:in-package #:eclector.concrete-syntax-tree) (defclass cst-client (eclector.parse-result:parse-result-client) ()) (defvar *cst-client* (make-instance 'cst-client)) (defmethod eclector.parse-result:make-expression-result ((client cst-client) expression children source) (labels ((make-atom-cst (expression &optional source) (make-instance 'cst:atom-cst :raw expression :source source)) (make-list-cst (expression children source) (loop for expression in (loop with reversed = '() for sub-expression on expression do (push sub-expression reversed) finally (return reversed)) for child in (reverse children) for previous = (make-instance 'cst:atom-cst :raw nil) then node for node = (make-instance 'cst:cons-cst :raw expression :first child :rest previous) finally (return (reinitialize-instance node :source source))))) (cond ((atom expression) (make-atom-cst expression source)) ((and (eql (ignore-errors (list-length expression)) (length children)) (every (lambda (sub-expression child) (eql sub-expression (cst:raw child))) expression children)) (make-list-cst expression children source)) (t (destructuring-bind (car . cdr) expression (make-instance 'cst:cons-cst :raw expression :first (cst:reconstruct car children client) :rest (cst:reconstruct cdr children client) :source source))))))
57c92b68e5832f4ba16ccdef319839e7c0f79410adf2b0efc365a4039d3bdb40
blamario/grampa
TH.hs
-- | This module exports the templates for automatic instance deriving of "Rank2" type classes. The most common way to -- use it would be -- > import qualified Rank2.TH -- > data MyDataType f = ... > $ ( Rank2.TH.deriveAll '' ) -- -- or, if you're picky, you can invoke only 'deriveFunctor' and whichever other instances you need instead. {-# Language CPP #-} {-# Language TemplateHaskell #-} -- Adapted from module Rank2.TH (deriveAll, deriveFunctor, deriveApply, unsafeDeriveApply, deriveApplicative, deriveFoldable, deriveTraversable, deriveDistributive, deriveDistributiveTraversable, deriveLogistic) where import Control.Applicative (liftA2, liftA3) import Control.Monad (replicateM) import Data.Distributive (cotraverse) import Data.Functor.Compose (Compose (Compose)) import Data.Functor.Contravariant (contramap) import Data.Functor.Logistic (deliver) import Data.Monoid ((<>)) import qualified Language.Haskell.TH as TH import Language.Haskell.TH (Q, TypeQ, Name, TyVarBndr(KindedTV, PlainTV), Clause, Dec(..), Con(..), Type(..), Exp(..), Inline(Inlinable, Inline), RuleMatch(FunLike), Phases(AllPhases), appE, conE, conP, instanceD, varE, varP, normalB, pragInlD, recConE, recUpdE, wildP) import Language.Haskell.TH.Syntax (BangType, VarBangType, Info(TyConI), getQ, putQ, newName) import qualified Rank2 data Deriving = Deriving { _derivingConstructor :: Name, _derivingVariable :: Name } deriving Show deriveAll :: Name -> Q [Dec] deriveAll ty = foldr f (pure []) [deriveFunctor, deriveApply, deriveApplicative, deriveFoldable, deriveTraversable, deriveDistributive, deriveDistributiveTraversable, deriveLogistic] where f derive rest = (<>) <$> derive ty <*> rest deriveFunctor :: Name -> Q [Dec] deriveFunctor ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Functor ty (constraints, dec) <- genFmap cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD '(Rank2.<$>) Inline FunLike AllPhases]] deriveApply :: Name -> Q [Dec] deriveApply ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Apply ty (constraints, dec) <- genAp cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, genLiftA2 cs, genLiftA3 cs, pragInlD '(Rank2.<*>) Inlinable FunLike AllPhases, pragInlD 'Rank2.liftA2 Inlinable FunLike AllPhases]] -- | This function always succeeds, but the methods it generates may be partial. Use with care. unsafeDeriveApply :: Name -> Q [Dec] unsafeDeriveApply ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Apply ty (constraints, dec) <- genApUnsafely cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, genLiftA2Unsafely cs, genLiftA3Unsafely cs, pragInlD '(Rank2.<*>) Inlinable FunLike AllPhases, pragInlD 'Rank2.liftA2 Inlinable FunLike AllPhases]] deriveApplicative :: Name -> Q [Dec] deriveApplicative ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Applicative ty (constraints, dec) <- genPure cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.pure Inline FunLike AllPhases]] deriveFoldable :: Name -> Q [Dec] deriveFoldable ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Foldable ty (constraints, dec) <- genFoldMap cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.foldMap Inlinable FunLike AllPhases]] deriveTraversable :: Name -> Q [Dec] deriveTraversable ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Traversable ty (constraints, dec) <- genTraverse cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.traverse Inlinable FunLike AllPhases]] deriveDistributive :: Name -> Q [Dec] deriveDistributive ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Distributive ty (constraints, dec) <- genCotraverse cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.cotraverse Inline FunLike AllPhases]] deriveDistributiveTraversable :: Name -> Q [Dec] deriveDistributiveTraversable ty = do (instanceType, cs) <- reifyConstructors ''Rank2.DistributiveTraversable ty (constraints, dec) <- genCotraverseTraversable cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec]] deriveLogistic :: Name -> Q [Dec] deriveLogistic ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Logistic ty (constraints, dec) <- genDeliver cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.deliver Inline FunLike AllPhases]] reifyConstructors :: Name -> Name -> Q (TypeQ, [Con]) reifyConstructors cls ty = do (TyConI tyCon) <- TH.reify ty (tyConName, tyVars, _kind, cs) <- case tyCon of DataD _ nm tyVars kind cs _ -> return (nm, tyVars, kind, cs) NewtypeD _ nm tyVars kind c _ -> return (nm, tyVars, kind, [c]) _ -> fail "deriveApply: tyCon may not be a type synonym." #if MIN_VERSION_template_haskell(2,17,0) let (KindedTV tyVar () (AppT (AppT ArrowT _) StarT)) = last tyVars instanceType = TH.conT cls `TH.appT` foldl apply (TH.conT tyConName) (init tyVars) apply t (PlainTV name _) = TH.appT t (TH.varT name) apply t (KindedTV name _ _) = TH.appT t (TH.varT name) #else let (KindedTV tyVar (AppT (AppT ArrowT _) StarT)) = last tyVars instanceType = TH.conT cls `TH.appT` foldl apply (TH.conT tyConName) (init tyVars) apply t (PlainTV name) = TH.appT t (TH.varT name) apply t (KindedTV name _) = TH.appT t (TH.varT name) #endif putQ (Deriving tyConName tyVar) return (instanceType, cs) genFmap :: [Con] -> Q ([Type], Dec) genFmap cs = do (constraints, clauses) <- unzip <$> mapM genFmapClause cs return (concat constraints, FunD '(Rank2.<$>) clauses) genAp :: [Con] -> Q ([Type], Dec) genAp [con] = do (constraints, clause) <- genApClause False con return (constraints, FunD '(Rank2.<*>) [clause]) genLiftA2 :: [Con] -> Q Dec genLiftA2 [con] = TH.funD 'Rank2.liftA2 [genLiftA2Clause False con] genLiftA3 :: [Con] -> Q Dec genLiftA3 [con] = TH.funD 'Rank2.liftA3 [genLiftA3Clause False con] genApUnsafely :: [Con] -> Q ([Type], Dec) genApUnsafely cons = do (constraints, clauses) <- unzip <$> mapM (genApClause True) cons return (concat constraints, FunD '(Rank2.<*>) clauses) genLiftA2Unsafely :: [Con] -> Q Dec genLiftA2Unsafely cons = TH.funD 'Rank2.liftA2 (genLiftA2Clause True <$> cons) genLiftA3Unsafely :: [Con] -> Q Dec genLiftA3Unsafely cons = TH.funD 'Rank2.liftA3 (genLiftA3Clause True <$> cons) genPure :: [Con] -> Q ([Type], Dec) genPure cs = do (constraints, clauses) <- unzip <$> mapM genPureClause cs return (concat constraints, FunD 'Rank2.pure clauses) genFoldMap :: [Con] -> Q ([Type], Dec) genFoldMap cs = do (constraints, clauses) <- unzip <$> mapM genFoldMapClause cs return (concat constraints, FunD 'Rank2.foldMap clauses) genTraverse :: [Con] -> Q ([Type], Dec) genTraverse cs = do (constraints, clauses) <- unzip <$> mapM genTraverseClause cs return (concat constraints, FunD 'Rank2.traverse clauses) genCotraverse :: [Con] -> Q ([Type], Dec) genCotraverse [con] = do (constraints, clause) <- genCotraverseClause con return (constraints, FunD 'Rank2.cotraverse [clause]) genCotraverseTraversable :: [Con] -> Q ([Type], Dec) genCotraverseTraversable [con] = do (constraints, clause) <- genCotraverseTraversableClause con return (constraints, FunD 'Rank2.cotraverseTraversable [clause]) genDeliver :: [Con] -> Q ([Type], Dec) genDeliver [con] = do (constraints, clause) <- genDeliverClause con return (constraints, FunD 'Rank2.deliver [clause]) genFmapClause :: Con -> Q ([Type], Clause) genFmapClause (NormalC name fieldTypes) = do f <- newName "f" fieldNames <- replicateM (length fieldTypes) (newName "x") let pats = [varP f, conP name (map varP fieldNames)] constraintsAndFields = zipWith newField fieldNames fieldTypes newFields = map (snd <$>) constraintsAndFields body = normalB $ TH.appsE $ conE name : newFields newField :: Name -> BangType -> Q ([Type], Exp) newField x (_, fieldType) = genFmapField (varE f) fieldType (varE x) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats body [] genFmapClause (RecC name fields) = do f <- newName "f" x <- newName "x" let body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newNamedField fields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> genFmapField (varE f) fieldType (appE (varE fieldName) (varE x)) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP f, x `TH.asP` TH.recP name []] body [] genFmapClause (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFmapClause (NormalC name fieldTypes) genFmapClause (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFmapClause (RecC name fields) genFmapClause (ForallC _vars _cxt con) = genFmapClause con genFmapField :: Q Exp -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genFmapField fun fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap fun) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Functor t1) <$> appE (wrap [| ($fun Rank2.<$>) |]) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genFmapField fun t2 fieldAccess (wrap . appE (varE '(<$>))) SigT ty _kind -> genFmapField fun ty fieldAccess wrap ParensT ty -> genFmapField fun ty fieldAccess wrap _ -> (,) [] <$> fieldAccess genLiftA2Clause :: Bool -> Con -> Q Clause genLiftA2Clause unsafely (NormalC name fieldTypes) = do f <- newName "f" fieldNames1 <- replicateM (length fieldTypes) (newName "x") y <- newName "y" fieldNames2 <- replicateM (length fieldTypes) (newName "y") let pats = [varP f, conP name (map varP fieldNames1), varP y] body = normalB $ TH.appsE $ conE name : zipWith newField (zip fieldNames1 fieldNames2) fieldTypes newField :: (Name, Name) -> BangType -> Q Exp newField (x, y) (_, fieldType) = genLiftA2Field unsafely (varE f) fieldType (varE x) (varE y) id TH.clause pats body [TH.valD (conP name $ map varP fieldNames2) (normalB $ varE y) []] genLiftA2Clause unsafely (RecC name fields) = do f <- newName "f" x <- newName "x" y <- newName "y" let body = normalB $ recConE name $ map newNamedField fields newNamedField :: VarBangType -> Q (Name, Exp) newNamedField (fieldName, _, fieldType) = TH.fieldExp fieldName (genLiftA2Field unsafely (varE f) fieldType (getFieldOf x) (getFieldOf y) id) where getFieldOf = appE (varE fieldName) . varE TH.clause [varP f, x `TH.asP` TH.recP name [], varP y] body [] genLiftA2Clause unsafely (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA2Clause unsafely (NormalC name fieldTypes) genLiftA2Clause unsafely (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA2Clause unsafely (RecC name fields) genLiftA2Clause unsafely (ForallC _vars _cxt con) = genLiftA2Clause unsafely con genLiftA2Field :: Bool -> Q Exp -> Type -> Q Exp -> Q Exp -> (Q Exp -> Q Exp) -> Q Exp genLiftA2Field unsafely fun fieldType field1Access field2Access wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> [| $(wrap fun) $field1Access $field2Access |] AppT _ ty | ty == VarT typeVar -> [| $(wrap $ appE (varE 'Rank2.liftA2) fun) $field1Access $field2Access |] AppT t1 t2 | t1 /= VarT typeVar -> genLiftA2Field unsafely fun t2 field1Access field2Access (appE (varE 'liftA2) . wrap) SigT ty _kind -> genLiftA2Field unsafely fun ty field1Access field2Access wrap ParensT ty -> genLiftA2Field unsafely fun ty field1Access field2Access wrap _ | unsafely -> field1Access | otherwise -> error ("Cannot apply liftA2 to field of type " <> show fieldType) genLiftA3Clause :: Bool -> Con -> Q Clause genLiftA3Clause unsafely (NormalC name fieldTypes) = do f <- newName "f" fieldNames1 <- replicateM (length fieldTypes) (newName "x") y <- newName "y" z <- newName "z" fieldNames2 <- replicateM (length fieldTypes) (newName "y") fieldNames3 <- replicateM (length fieldTypes) (newName "z") let pats = [varP f, conP name (map varP fieldNames1), varP y, varP z] body = normalB $ TH.appsE $ conE name : zipWith newField (zip3 fieldNames1 fieldNames2 fieldNames3) fieldTypes newField :: (Name, Name, Name) -> BangType -> Q Exp newField (x, y, z) (_, fieldType) = genLiftA3Field unsafely (varE f) fieldType (varE x) (varE y) (varE z) id TH.clause pats body [TH.valD (conP name $ map varP fieldNames2) (normalB $ varE y) [], TH.valD (conP name $ map varP fieldNames3) (normalB $ varE z) []] genLiftA3Clause unsafely (RecC name fields) = do f <- newName "f" x <- newName "x" y <- newName "y" z <- newName "z" let body = normalB $ recConE name $ map newNamedField fields newNamedField :: VarBangType -> Q (Name, Exp) newNamedField (fieldName, _, fieldType) = TH.fieldExp fieldName (genLiftA3Field unsafely (varE f) fieldType (getFieldOf x) (getFieldOf y) (getFieldOf z) id) where getFieldOf = appE (varE fieldName) . varE TH.clause [varP f, x `TH.asP` TH.recP name [], varP y, varP z] body [] genLiftA3Clause unsafely (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA3Clause unsafely (NormalC name fieldTypes) genLiftA3Clause unsafely (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA3Clause unsafely (RecC name fields) genLiftA3Clause unsafely (ForallC _vars _cxt con) = genLiftA3Clause unsafely con genLiftA3Field :: Bool -> Q Exp -> Type -> Q Exp -> Q Exp -> Q Exp -> (Q Exp -> Q Exp) -> Q Exp genLiftA3Field unsafely fun fieldType field1Access field2Access field3Access wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> [| $(wrap fun) $(field1Access) $(field2Access) $(field3Access) |] AppT _ ty | ty == VarT typeVar -> [| $(wrap $ appE (varE 'Rank2.liftA3) fun) $(field1Access) $(field2Access) $(field3Access) |] AppT t1 t2 | t1 /= VarT typeVar -> genLiftA3Field unsafely fun t2 field1Access field2Access field3Access (appE (varE 'liftA3) . wrap) SigT ty _kind -> genLiftA3Field unsafely fun ty field1Access field2Access field3Access wrap ParensT ty -> genLiftA3Field unsafely fun ty field1Access field2Access field3Access wrap _ | unsafely -> field1Access | otherwise -> error ("Cannot apply liftA3 to field of type " <> show fieldType) genApClause :: Bool -> Con -> Q ([Type], Clause) genApClause unsafely (NormalC name fieldTypes) = do fieldNames1 <- replicateM (length fieldTypes) (newName "x") fieldNames2 <- replicateM (length fieldTypes) (newName "y") rhsName <- newName "rhs" let pats = [conP name (map varP fieldNames1), varP rhsName] constraintsAndFields = zipWith newField (zip fieldNames1 fieldNames2) fieldTypes newFields = map (snd <$>) constraintsAndFields body = normalB $ TH.appsE $ conE name : newFields newField :: (Name, Name) -> BangType -> Q ([Type], Exp) newField (x, y) (_, fieldType) = genApField unsafely fieldType (varE x) (varE y) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats body [TH.valD (conP name $ map varP fieldNames2) (normalB $ varE rhsName) []] genApClause unsafely (RecC name fields) = do x <- newName "x" y <- newName "y" let body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newNamedField fields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> genApField unsafely fieldType (getFieldOf x) (getFieldOf y) id where getFieldOf = appE (varE fieldName) . varE constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [x `TH.asP` TH.recP name [], varP y] body [] genApClause unsafely (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genApClause unsafely (NormalC name fieldTypes) genApClause unsafely (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genApClause unsafely (RecC name fields) genApClause unsafely (ForallC _vars _cxt con) = genApClause unsafely con genApField :: Bool -> Type -> Q Exp -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genApField unsafely fieldType field1Access field2Access wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> [| $(wrap (varE 'Rank2.apply)) $(field1Access) $(field2Access) |] AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Apply t1) <$> [| $(wrap (varE 'Rank2.ap)) $(field1Access) $(field2Access) |] AppT t1 t2 | t1 /= VarT typeVar -> genApField unsafely t2 field1Access field2Access (appE (varE 'liftA2) . wrap) SigT ty _kind -> genApField unsafely ty field1Access field2Access wrap ParensT ty -> genApField unsafely ty field1Access field2Access wrap _ | unsafely -> (,) [] <$> field1Access | otherwise -> error ("Cannot apply ap to field of type " <> show fieldType) genPureClause :: Con -> Q ([Type], Clause) genPureClause (NormalC name fieldTypes) = do argName <- newName "f" let body = normalB $ TH.appsE $ conE name : ((snd <$>) <$> constraintsAndFields) constraintsAndFields = map newField fieldTypes newField :: BangType -> Q ([Type], Exp) newField (_, fieldType) = genPureField fieldType (varE argName) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP argName] body [] genPureClause (RecC name fields) = do argName <- newName "f" let body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newNamedField fields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> genPureField fieldType (varE argName) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP argName] body [] genPureField :: Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genPureField fieldType pureValue wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> wrap pureValue AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Applicative t1) <$> wrap (appE (varE 'Rank2.pure) pureValue) AppT t1 t2 | t1 /= VarT typeVar -> genPureField t2 pureValue (wrap . appE (varE 'pure)) SigT ty _kind -> genPureField ty pureValue wrap ParensT ty -> genPureField ty pureValue wrap _ -> error ("Cannot create a pure field of type " <> show fieldType) genFoldMapClause :: Con -> Q ([Type], Clause) genFoldMapClause (NormalC name fieldTypes) = do f <- newName "f" fieldNames <- replicateM (length fieldTypes) (newName "x") let pats = [varP f, conP name (map varP fieldNames)] constraintsAndFields = zipWith newField fieldNames fieldTypes body | null fieldNames = [| mempty |] | otherwise = foldr1 append $ (snd <$>) <$> constraintsAndFields append a b = [| $(a) <> $(b) |] newField :: Name -> BangType -> Q ([Type], Exp) newField x (_, fieldType) = genFoldMapField f fieldType (varE x) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats (normalB body) [] genFoldMapClause (RecC name fields) = do f <- newName "f" x <- newName "x" let body | null fields = [| mempty |] | otherwise = foldr1 append $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newField fields append a b = [| $(a) <> $(b) |] newField :: VarBangType -> Q ([Type], Exp) newField (fieldName, _, fieldType) = genFoldMapField f fieldType (appE (varE fieldName) (varE x)) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP f, x `TH.asP` TH.recP name []] (normalB body) [] genFoldMapClause (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFoldMapClause (NormalC name fieldTypes) genFoldMapClause (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFoldMapClause (RecC name fields) genFoldMapClause (ForallC _vars _cxt con) = genFoldMapClause con genFoldMapField :: Name -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genFoldMapField funcName fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap $ varE funcName) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Foldable t1) <$> appE (wrap $ appE (varE 'Rank2.foldMap) (varE funcName)) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genFoldMapField funcName t2 fieldAccess (wrap . appE (varE 'foldMap)) SigT ty _kind -> genFoldMapField funcName ty fieldAccess wrap ParensT ty -> genFoldMapField funcName ty fieldAccess wrap _ -> (,) [] <$> [| mempty |] genTraverseClause :: Con -> Q ([Type], Clause) genTraverseClause (NormalC name []) = (,) [] <$> TH.clause [wildP, conP name []] (normalB [| pure $(conE name) |]) [] genTraverseClause (NormalC name fieldTypes) = do f <- newName "f" fieldNames <- replicateM (length fieldTypes) (newName "x") let pats = [varP f, conP name (map varP fieldNames)] constraintsAndFields = zipWith newField fieldNames fieldTypes newFields = map (snd <$>) constraintsAndFields body = normalB $ fst $ foldl apply (conE name, False) newFields apply (a, False) b = ([| $(a) <$> $(b) |], True) apply (a, True) b = ([| $(a) <*> $(b) |], True) newField :: Name -> BangType -> Q ([Type], Exp) newField x (_, fieldType) = genTraverseField (varE f) fieldType (varE x) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats body [] genTraverseClause (RecC name fields) = do f <- newName "f" x <- newName "x" let constraintsAndFields = map newField fields body = normalB $ fst $ foldl apply (conE name, False) $ (snd <$>) <$> constraintsAndFields apply (a, False) b = ([| $(a) <$> $(b) |], True) apply (a, True) b = ([| $(a) <*> $(b) |], True) newField :: VarBangType -> Q ([Type], Exp) newField (fieldName, _, fieldType) = genTraverseField (varE f) fieldType (appE (varE fieldName) (varE x)) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP f, x `TH.asP` TH.recP name []] body [] genTraverseClause (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genTraverseClause (NormalC name fieldTypes) genTraverseClause (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genTraverseClause (RecC name fields) genTraverseClause (ForallC _vars _cxt con) = genTraverseClause con genTraverseField :: Q Exp -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genTraverseField fun fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap fun) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Traversable t1) <$> appE (wrap [| Rank2.traverse $fun |]) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genTraverseField fun t2 fieldAccess (wrap . appE (varE 'traverse)) SigT ty _kind -> genTraverseField fun ty fieldAccess wrap ParensT ty -> genTraverseField fun ty fieldAccess wrap _ -> (,) [] <$> [| pure $fieldAccess |] genCotraverseClause :: Con -> Q ([Type], Clause) genCotraverseClause (NormalC name []) = genCotraverseClause (RecC name []) genCotraverseClause (RecC name fields) = do withName <- newName "w" argName <- newName "f" let constraintsAndFields = map newNamedField fields body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> (genCotraverseField ''Rank2.Distributive (varE 'Rank2.cotraverse) (varE withName) fieldType [| $(varE fieldName) <$> $(varE argName) |] id) constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP withName, varP argName] body [] genCotraverseTraversableClause :: Con -> Q ([Type], Clause) genCotraverseTraversableClause (NormalC name []) = genCotraverseTraversableClause (RecC name []) genCotraverseTraversableClause (RecC name fields) = do withName <- newName "w" argName <- newName "f" let constraintsAndFields = map newNamedField fields body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> (genCotraverseField ''Rank2.DistributiveTraversable (varE 'Rank2.cotraverseTraversable) (varE withName) fieldType [| $(varE fieldName) <$> $(varE argName) |] id) constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP withName, varP argName] body [] genDeliverClause :: Con -> Q ([Type], Clause) genDeliverClause (NormalC name []) = genDeliverClause (RecC name []) genDeliverClause (RecC name fields) = do argName <- newName "f" let constraintsAndFields = map newNamedField fields body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> (genDeliverField ''Rank2.Logistic fieldType (\wrap-> [| \set g-> $(TH.recUpdE [|g|] [(,) fieldName <$> appE (wrap [| Rank2.apply set |]) [| $(varE fieldName) g |]]) |]) (\wrap-> [| \set g-> $(TH.recUpdE [|g|] [(,) fieldName <$> appE (wrap [| set |]) [| $(varE fieldName) g |]]) |]) (varE argName) id id) constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP argName] body [] genCotraverseField :: Name -> Q Exp -> Q Exp -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genCotraverseField className method fun fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap fun) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain className t1) <$> appE (wrap $ appE method fun) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genCotraverseField className method fun t2 fieldAccess (wrap . appE (varE 'cotraverse)) SigT ty _kind -> genCotraverseField className method fun ty fieldAccess wrap ParensT ty -> genCotraverseField className method fun ty fieldAccess wrap genDeliverField :: Name -> Type -> ((Q Exp -> Q Exp) -> Q Exp) -> ((Q Exp -> Q Exp) -> Q Exp) -> Q Exp -> (Q Exp -> Q Exp) -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genDeliverField className fieldType fieldUpdate subRecordUpdate arg outer inner = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> outer (appE [|Compose|] ([|contramap|] `appE` fieldUpdate inner `appE` arg)) AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain className t1) <$> outer (appE [| Rank2.deliver |] ([|contramap|] `appE` subRecordUpdate inner `appE` arg)) AppT t1 t2 | t1 /= VarT typeVar -> genDeliverField className t2 fieldUpdate subRecordUpdate arg (outer . appE (varE 'pure)) (inner . appE (varE 'fmap)) SigT ty _kind -> genDeliverField className ty fieldUpdate subRecordUpdate arg outer inner ParensT ty -> genDeliverField className ty fieldUpdate subRecordUpdate arg outer inner constrain :: Name -> Type -> [Type] constrain _ ConT{} = [] constrain cls t = [ConT cls `AppT` t]
null
https://raw.githubusercontent.com/blamario/grampa/cae7fc65d8d8ad2f54a070170896735c7518eed7/rank2classes/src/Rank2/TH.hs
haskell
| This module exports the templates for automatic instance deriving of "Rank2" type classes. The most common way to use it would be > data MyDataType f = ... or, if you're picky, you can invoke only 'deriveFunctor' and whichever other instances you need instead. # Language CPP # # Language TemplateHaskell # Adapted from | This function always succeeds, but the methods it generates may be partial. Use with care.
> import qualified Rank2.TH > $ ( Rank2.TH.deriveAll '' ) module Rank2.TH (deriveAll, deriveFunctor, deriveApply, unsafeDeriveApply, deriveApplicative, deriveFoldable, deriveTraversable, deriveDistributive, deriveDistributiveTraversable, deriveLogistic) where import Control.Applicative (liftA2, liftA3) import Control.Monad (replicateM) import Data.Distributive (cotraverse) import Data.Functor.Compose (Compose (Compose)) import Data.Functor.Contravariant (contramap) import Data.Functor.Logistic (deliver) import Data.Monoid ((<>)) import qualified Language.Haskell.TH as TH import Language.Haskell.TH (Q, TypeQ, Name, TyVarBndr(KindedTV, PlainTV), Clause, Dec(..), Con(..), Type(..), Exp(..), Inline(Inlinable, Inline), RuleMatch(FunLike), Phases(AllPhases), appE, conE, conP, instanceD, varE, varP, normalB, pragInlD, recConE, recUpdE, wildP) import Language.Haskell.TH.Syntax (BangType, VarBangType, Info(TyConI), getQ, putQ, newName) import qualified Rank2 data Deriving = Deriving { _derivingConstructor :: Name, _derivingVariable :: Name } deriving Show deriveAll :: Name -> Q [Dec] deriveAll ty = foldr f (pure []) [deriveFunctor, deriveApply, deriveApplicative, deriveFoldable, deriveTraversable, deriveDistributive, deriveDistributiveTraversable, deriveLogistic] where f derive rest = (<>) <$> derive ty <*> rest deriveFunctor :: Name -> Q [Dec] deriveFunctor ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Functor ty (constraints, dec) <- genFmap cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD '(Rank2.<$>) Inline FunLike AllPhases]] deriveApply :: Name -> Q [Dec] deriveApply ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Apply ty (constraints, dec) <- genAp cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, genLiftA2 cs, genLiftA3 cs, pragInlD '(Rank2.<*>) Inlinable FunLike AllPhases, pragInlD 'Rank2.liftA2 Inlinable FunLike AllPhases]] unsafeDeriveApply :: Name -> Q [Dec] unsafeDeriveApply ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Apply ty (constraints, dec) <- genApUnsafely cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, genLiftA2Unsafely cs, genLiftA3Unsafely cs, pragInlD '(Rank2.<*>) Inlinable FunLike AllPhases, pragInlD 'Rank2.liftA2 Inlinable FunLike AllPhases]] deriveApplicative :: Name -> Q [Dec] deriveApplicative ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Applicative ty (constraints, dec) <- genPure cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.pure Inline FunLike AllPhases]] deriveFoldable :: Name -> Q [Dec] deriveFoldable ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Foldable ty (constraints, dec) <- genFoldMap cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.foldMap Inlinable FunLike AllPhases]] deriveTraversable :: Name -> Q [Dec] deriveTraversable ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Traversable ty (constraints, dec) <- genTraverse cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.traverse Inlinable FunLike AllPhases]] deriveDistributive :: Name -> Q [Dec] deriveDistributive ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Distributive ty (constraints, dec) <- genCotraverse cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.cotraverse Inline FunLike AllPhases]] deriveDistributiveTraversable :: Name -> Q [Dec] deriveDistributiveTraversable ty = do (instanceType, cs) <- reifyConstructors ''Rank2.DistributiveTraversable ty (constraints, dec) <- genCotraverseTraversable cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec]] deriveLogistic :: Name -> Q [Dec] deriveLogistic ty = do (instanceType, cs) <- reifyConstructors ''Rank2.Logistic ty (constraints, dec) <- genDeliver cs sequence [instanceD (TH.cxt $ map pure constraints) instanceType [pure dec, pragInlD 'Rank2.deliver Inline FunLike AllPhases]] reifyConstructors :: Name -> Name -> Q (TypeQ, [Con]) reifyConstructors cls ty = do (TyConI tyCon) <- TH.reify ty (tyConName, tyVars, _kind, cs) <- case tyCon of DataD _ nm tyVars kind cs _ -> return (nm, tyVars, kind, cs) NewtypeD _ nm tyVars kind c _ -> return (nm, tyVars, kind, [c]) _ -> fail "deriveApply: tyCon may not be a type synonym." #if MIN_VERSION_template_haskell(2,17,0) let (KindedTV tyVar () (AppT (AppT ArrowT _) StarT)) = last tyVars instanceType = TH.conT cls `TH.appT` foldl apply (TH.conT tyConName) (init tyVars) apply t (PlainTV name _) = TH.appT t (TH.varT name) apply t (KindedTV name _ _) = TH.appT t (TH.varT name) #else let (KindedTV tyVar (AppT (AppT ArrowT _) StarT)) = last tyVars instanceType = TH.conT cls `TH.appT` foldl apply (TH.conT tyConName) (init tyVars) apply t (PlainTV name) = TH.appT t (TH.varT name) apply t (KindedTV name _) = TH.appT t (TH.varT name) #endif putQ (Deriving tyConName tyVar) return (instanceType, cs) genFmap :: [Con] -> Q ([Type], Dec) genFmap cs = do (constraints, clauses) <- unzip <$> mapM genFmapClause cs return (concat constraints, FunD '(Rank2.<$>) clauses) genAp :: [Con] -> Q ([Type], Dec) genAp [con] = do (constraints, clause) <- genApClause False con return (constraints, FunD '(Rank2.<*>) [clause]) genLiftA2 :: [Con] -> Q Dec genLiftA2 [con] = TH.funD 'Rank2.liftA2 [genLiftA2Clause False con] genLiftA3 :: [Con] -> Q Dec genLiftA3 [con] = TH.funD 'Rank2.liftA3 [genLiftA3Clause False con] genApUnsafely :: [Con] -> Q ([Type], Dec) genApUnsafely cons = do (constraints, clauses) <- unzip <$> mapM (genApClause True) cons return (concat constraints, FunD '(Rank2.<*>) clauses) genLiftA2Unsafely :: [Con] -> Q Dec genLiftA2Unsafely cons = TH.funD 'Rank2.liftA2 (genLiftA2Clause True <$> cons) genLiftA3Unsafely :: [Con] -> Q Dec genLiftA3Unsafely cons = TH.funD 'Rank2.liftA3 (genLiftA3Clause True <$> cons) genPure :: [Con] -> Q ([Type], Dec) genPure cs = do (constraints, clauses) <- unzip <$> mapM genPureClause cs return (concat constraints, FunD 'Rank2.pure clauses) genFoldMap :: [Con] -> Q ([Type], Dec) genFoldMap cs = do (constraints, clauses) <- unzip <$> mapM genFoldMapClause cs return (concat constraints, FunD 'Rank2.foldMap clauses) genTraverse :: [Con] -> Q ([Type], Dec) genTraverse cs = do (constraints, clauses) <- unzip <$> mapM genTraverseClause cs return (concat constraints, FunD 'Rank2.traverse clauses) genCotraverse :: [Con] -> Q ([Type], Dec) genCotraverse [con] = do (constraints, clause) <- genCotraverseClause con return (constraints, FunD 'Rank2.cotraverse [clause]) genCotraverseTraversable :: [Con] -> Q ([Type], Dec) genCotraverseTraversable [con] = do (constraints, clause) <- genCotraverseTraversableClause con return (constraints, FunD 'Rank2.cotraverseTraversable [clause]) genDeliver :: [Con] -> Q ([Type], Dec) genDeliver [con] = do (constraints, clause) <- genDeliverClause con return (constraints, FunD 'Rank2.deliver [clause]) genFmapClause :: Con -> Q ([Type], Clause) genFmapClause (NormalC name fieldTypes) = do f <- newName "f" fieldNames <- replicateM (length fieldTypes) (newName "x") let pats = [varP f, conP name (map varP fieldNames)] constraintsAndFields = zipWith newField fieldNames fieldTypes newFields = map (snd <$>) constraintsAndFields body = normalB $ TH.appsE $ conE name : newFields newField :: Name -> BangType -> Q ([Type], Exp) newField x (_, fieldType) = genFmapField (varE f) fieldType (varE x) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats body [] genFmapClause (RecC name fields) = do f <- newName "f" x <- newName "x" let body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newNamedField fields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> genFmapField (varE f) fieldType (appE (varE fieldName) (varE x)) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP f, x `TH.asP` TH.recP name []] body [] genFmapClause (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFmapClause (NormalC name fieldTypes) genFmapClause (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFmapClause (RecC name fields) genFmapClause (ForallC _vars _cxt con) = genFmapClause con genFmapField :: Q Exp -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genFmapField fun fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap fun) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Functor t1) <$> appE (wrap [| ($fun Rank2.<$>) |]) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genFmapField fun t2 fieldAccess (wrap . appE (varE '(<$>))) SigT ty _kind -> genFmapField fun ty fieldAccess wrap ParensT ty -> genFmapField fun ty fieldAccess wrap _ -> (,) [] <$> fieldAccess genLiftA2Clause :: Bool -> Con -> Q Clause genLiftA2Clause unsafely (NormalC name fieldTypes) = do f <- newName "f" fieldNames1 <- replicateM (length fieldTypes) (newName "x") y <- newName "y" fieldNames2 <- replicateM (length fieldTypes) (newName "y") let pats = [varP f, conP name (map varP fieldNames1), varP y] body = normalB $ TH.appsE $ conE name : zipWith newField (zip fieldNames1 fieldNames2) fieldTypes newField :: (Name, Name) -> BangType -> Q Exp newField (x, y) (_, fieldType) = genLiftA2Field unsafely (varE f) fieldType (varE x) (varE y) id TH.clause pats body [TH.valD (conP name $ map varP fieldNames2) (normalB $ varE y) []] genLiftA2Clause unsafely (RecC name fields) = do f <- newName "f" x <- newName "x" y <- newName "y" let body = normalB $ recConE name $ map newNamedField fields newNamedField :: VarBangType -> Q (Name, Exp) newNamedField (fieldName, _, fieldType) = TH.fieldExp fieldName (genLiftA2Field unsafely (varE f) fieldType (getFieldOf x) (getFieldOf y) id) where getFieldOf = appE (varE fieldName) . varE TH.clause [varP f, x `TH.asP` TH.recP name [], varP y] body [] genLiftA2Clause unsafely (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA2Clause unsafely (NormalC name fieldTypes) genLiftA2Clause unsafely (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA2Clause unsafely (RecC name fields) genLiftA2Clause unsafely (ForallC _vars _cxt con) = genLiftA2Clause unsafely con genLiftA2Field :: Bool -> Q Exp -> Type -> Q Exp -> Q Exp -> (Q Exp -> Q Exp) -> Q Exp genLiftA2Field unsafely fun fieldType field1Access field2Access wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> [| $(wrap fun) $field1Access $field2Access |] AppT _ ty | ty == VarT typeVar -> [| $(wrap $ appE (varE 'Rank2.liftA2) fun) $field1Access $field2Access |] AppT t1 t2 | t1 /= VarT typeVar -> genLiftA2Field unsafely fun t2 field1Access field2Access (appE (varE 'liftA2) . wrap) SigT ty _kind -> genLiftA2Field unsafely fun ty field1Access field2Access wrap ParensT ty -> genLiftA2Field unsafely fun ty field1Access field2Access wrap _ | unsafely -> field1Access | otherwise -> error ("Cannot apply liftA2 to field of type " <> show fieldType) genLiftA3Clause :: Bool -> Con -> Q Clause genLiftA3Clause unsafely (NormalC name fieldTypes) = do f <- newName "f" fieldNames1 <- replicateM (length fieldTypes) (newName "x") y <- newName "y" z <- newName "z" fieldNames2 <- replicateM (length fieldTypes) (newName "y") fieldNames3 <- replicateM (length fieldTypes) (newName "z") let pats = [varP f, conP name (map varP fieldNames1), varP y, varP z] body = normalB $ TH.appsE $ conE name : zipWith newField (zip3 fieldNames1 fieldNames2 fieldNames3) fieldTypes newField :: (Name, Name, Name) -> BangType -> Q Exp newField (x, y, z) (_, fieldType) = genLiftA3Field unsafely (varE f) fieldType (varE x) (varE y) (varE z) id TH.clause pats body [TH.valD (conP name $ map varP fieldNames2) (normalB $ varE y) [], TH.valD (conP name $ map varP fieldNames3) (normalB $ varE z) []] genLiftA3Clause unsafely (RecC name fields) = do f <- newName "f" x <- newName "x" y <- newName "y" z <- newName "z" let body = normalB $ recConE name $ map newNamedField fields newNamedField :: VarBangType -> Q (Name, Exp) newNamedField (fieldName, _, fieldType) = TH.fieldExp fieldName (genLiftA3Field unsafely (varE f) fieldType (getFieldOf x) (getFieldOf y) (getFieldOf z) id) where getFieldOf = appE (varE fieldName) . varE TH.clause [varP f, x `TH.asP` TH.recP name [], varP y, varP z] body [] genLiftA3Clause unsafely (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA3Clause unsafely (NormalC name fieldTypes) genLiftA3Clause unsafely (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genLiftA3Clause unsafely (RecC name fields) genLiftA3Clause unsafely (ForallC _vars _cxt con) = genLiftA3Clause unsafely con genLiftA3Field :: Bool -> Q Exp -> Type -> Q Exp -> Q Exp -> Q Exp -> (Q Exp -> Q Exp) -> Q Exp genLiftA3Field unsafely fun fieldType field1Access field2Access field3Access wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> [| $(wrap fun) $(field1Access) $(field2Access) $(field3Access) |] AppT _ ty | ty == VarT typeVar -> [| $(wrap $ appE (varE 'Rank2.liftA3) fun) $(field1Access) $(field2Access) $(field3Access) |] AppT t1 t2 | t1 /= VarT typeVar -> genLiftA3Field unsafely fun t2 field1Access field2Access field3Access (appE (varE 'liftA3) . wrap) SigT ty _kind -> genLiftA3Field unsafely fun ty field1Access field2Access field3Access wrap ParensT ty -> genLiftA3Field unsafely fun ty field1Access field2Access field3Access wrap _ | unsafely -> field1Access | otherwise -> error ("Cannot apply liftA3 to field of type " <> show fieldType) genApClause :: Bool -> Con -> Q ([Type], Clause) genApClause unsafely (NormalC name fieldTypes) = do fieldNames1 <- replicateM (length fieldTypes) (newName "x") fieldNames2 <- replicateM (length fieldTypes) (newName "y") rhsName <- newName "rhs" let pats = [conP name (map varP fieldNames1), varP rhsName] constraintsAndFields = zipWith newField (zip fieldNames1 fieldNames2) fieldTypes newFields = map (snd <$>) constraintsAndFields body = normalB $ TH.appsE $ conE name : newFields newField :: (Name, Name) -> BangType -> Q ([Type], Exp) newField (x, y) (_, fieldType) = genApField unsafely fieldType (varE x) (varE y) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats body [TH.valD (conP name $ map varP fieldNames2) (normalB $ varE rhsName) []] genApClause unsafely (RecC name fields) = do x <- newName "x" y <- newName "y" let body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newNamedField fields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> genApField unsafely fieldType (getFieldOf x) (getFieldOf y) id where getFieldOf = appE (varE fieldName) . varE constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [x `TH.asP` TH.recP name [], varP y] body [] genApClause unsafely (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genApClause unsafely (NormalC name fieldTypes) genApClause unsafely (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genApClause unsafely (RecC name fields) genApClause unsafely (ForallC _vars _cxt con) = genApClause unsafely con genApField :: Bool -> Type -> Q Exp -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genApField unsafely fieldType field1Access field2Access wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> [| $(wrap (varE 'Rank2.apply)) $(field1Access) $(field2Access) |] AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Apply t1) <$> [| $(wrap (varE 'Rank2.ap)) $(field1Access) $(field2Access) |] AppT t1 t2 | t1 /= VarT typeVar -> genApField unsafely t2 field1Access field2Access (appE (varE 'liftA2) . wrap) SigT ty _kind -> genApField unsafely ty field1Access field2Access wrap ParensT ty -> genApField unsafely ty field1Access field2Access wrap _ | unsafely -> (,) [] <$> field1Access | otherwise -> error ("Cannot apply ap to field of type " <> show fieldType) genPureClause :: Con -> Q ([Type], Clause) genPureClause (NormalC name fieldTypes) = do argName <- newName "f" let body = normalB $ TH.appsE $ conE name : ((snd <$>) <$> constraintsAndFields) constraintsAndFields = map newField fieldTypes newField :: BangType -> Q ([Type], Exp) newField (_, fieldType) = genPureField fieldType (varE argName) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP argName] body [] genPureClause (RecC name fields) = do argName <- newName "f" let body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newNamedField fields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> genPureField fieldType (varE argName) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP argName] body [] genPureField :: Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genPureField fieldType pureValue wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> wrap pureValue AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Applicative t1) <$> wrap (appE (varE 'Rank2.pure) pureValue) AppT t1 t2 | t1 /= VarT typeVar -> genPureField t2 pureValue (wrap . appE (varE 'pure)) SigT ty _kind -> genPureField ty pureValue wrap ParensT ty -> genPureField ty pureValue wrap _ -> error ("Cannot create a pure field of type " <> show fieldType) genFoldMapClause :: Con -> Q ([Type], Clause) genFoldMapClause (NormalC name fieldTypes) = do f <- newName "f" fieldNames <- replicateM (length fieldTypes) (newName "x") let pats = [varP f, conP name (map varP fieldNames)] constraintsAndFields = zipWith newField fieldNames fieldTypes body | null fieldNames = [| mempty |] | otherwise = foldr1 append $ (snd <$>) <$> constraintsAndFields append a b = [| $(a) <> $(b) |] newField :: Name -> BangType -> Q ([Type], Exp) newField x (_, fieldType) = genFoldMapField f fieldType (varE x) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats (normalB body) [] genFoldMapClause (RecC name fields) = do f <- newName "f" x <- newName "x" let body | null fields = [| mempty |] | otherwise = foldr1 append $ (snd <$>) <$> constraintsAndFields constraintsAndFields = map newField fields append a b = [| $(a) <> $(b) |] newField :: VarBangType -> Q ([Type], Exp) newField (fieldName, _, fieldType) = genFoldMapField f fieldType (appE (varE fieldName) (varE x)) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP f, x `TH.asP` TH.recP name []] (normalB body) [] genFoldMapClause (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFoldMapClause (NormalC name fieldTypes) genFoldMapClause (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genFoldMapClause (RecC name fields) genFoldMapClause (ForallC _vars _cxt con) = genFoldMapClause con genFoldMapField :: Name -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genFoldMapField funcName fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap $ varE funcName) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Foldable t1) <$> appE (wrap $ appE (varE 'Rank2.foldMap) (varE funcName)) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genFoldMapField funcName t2 fieldAccess (wrap . appE (varE 'foldMap)) SigT ty _kind -> genFoldMapField funcName ty fieldAccess wrap ParensT ty -> genFoldMapField funcName ty fieldAccess wrap _ -> (,) [] <$> [| mempty |] genTraverseClause :: Con -> Q ([Type], Clause) genTraverseClause (NormalC name []) = (,) [] <$> TH.clause [wildP, conP name []] (normalB [| pure $(conE name) |]) [] genTraverseClause (NormalC name fieldTypes) = do f <- newName "f" fieldNames <- replicateM (length fieldTypes) (newName "x") let pats = [varP f, conP name (map varP fieldNames)] constraintsAndFields = zipWith newField fieldNames fieldTypes newFields = map (snd <$>) constraintsAndFields body = normalB $ fst $ foldl apply (conE name, False) newFields apply (a, False) b = ([| $(a) <$> $(b) |], True) apply (a, True) b = ([| $(a) <*> $(b) |], True) newField :: Name -> BangType -> Q ([Type], Exp) newField x (_, fieldType) = genTraverseField (varE f) fieldType (varE x) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause pats body [] genTraverseClause (RecC name fields) = do f <- newName "f" x <- newName "x" let constraintsAndFields = map newField fields body = normalB $ fst $ foldl apply (conE name, False) $ (snd <$>) <$> constraintsAndFields apply (a, False) b = ([| $(a) <$> $(b) |], True) apply (a, True) b = ([| $(a) <*> $(b) |], True) newField :: VarBangType -> Q ([Type], Exp) newField (fieldName, _, fieldType) = genTraverseField (varE f) fieldType (appE (varE fieldName) (varE x)) id constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP f, x `TH.asP` TH.recP name []] body [] genTraverseClause (GadtC [name] fieldTypes _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genTraverseClause (NormalC name fieldTypes) genTraverseClause (RecGadtC [name] fields _resultType@(AppT _ (VarT tyVar))) = do Just (Deriving tyConName _tyVar) <- getQ putQ (Deriving tyConName tyVar) genTraverseClause (RecC name fields) genTraverseClause (ForallC _vars _cxt con) = genTraverseClause con genTraverseField :: Q Exp -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genTraverseField fun fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap fun) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain ''Rank2.Traversable t1) <$> appE (wrap [| Rank2.traverse $fun |]) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genTraverseField fun t2 fieldAccess (wrap . appE (varE 'traverse)) SigT ty _kind -> genTraverseField fun ty fieldAccess wrap ParensT ty -> genTraverseField fun ty fieldAccess wrap _ -> (,) [] <$> [| pure $fieldAccess |] genCotraverseClause :: Con -> Q ([Type], Clause) genCotraverseClause (NormalC name []) = genCotraverseClause (RecC name []) genCotraverseClause (RecC name fields) = do withName <- newName "w" argName <- newName "f" let constraintsAndFields = map newNamedField fields body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> (genCotraverseField ''Rank2.Distributive (varE 'Rank2.cotraverse) (varE withName) fieldType [| $(varE fieldName) <$> $(varE argName) |] id) constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP withName, varP argName] body [] genCotraverseTraversableClause :: Con -> Q ([Type], Clause) genCotraverseTraversableClause (NormalC name []) = genCotraverseTraversableClause (RecC name []) genCotraverseTraversableClause (RecC name fields) = do withName <- newName "w" argName <- newName "f" let constraintsAndFields = map newNamedField fields body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> (genCotraverseField ''Rank2.DistributiveTraversable (varE 'Rank2.cotraverseTraversable) (varE withName) fieldType [| $(varE fieldName) <$> $(varE argName) |] id) constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP withName, varP argName] body [] genDeliverClause :: Con -> Q ([Type], Clause) genDeliverClause (NormalC name []) = genDeliverClause (RecC name []) genDeliverClause (RecC name fields) = do argName <- newName "f" let constraintsAndFields = map newNamedField fields body = normalB $ recConE name $ (snd <$>) <$> constraintsAndFields newNamedField :: VarBangType -> Q ([Type], (Name, Exp)) newNamedField (fieldName, _, fieldType) = ((,) fieldName <$>) <$> (genDeliverField ''Rank2.Logistic fieldType (\wrap-> [| \set g-> $(TH.recUpdE [|g|] [(,) fieldName <$> appE (wrap [| Rank2.apply set |]) [| $(varE fieldName) g |]]) |]) (\wrap-> [| \set g-> $(TH.recUpdE [|g|] [(,) fieldName <$> appE (wrap [| set |]) [| $(varE fieldName) g |]]) |]) (varE argName) id id) constraints <- (concat . (fst <$>)) <$> sequence constraintsAndFields (,) constraints <$> TH.clause [varP argName] body [] genCotraverseField :: Name -> Q Exp -> Q Exp -> Type -> Q Exp -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genCotraverseField className method fun fieldType fieldAccess wrap = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> appE (wrap fun) fieldAccess AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain className t1) <$> appE (wrap $ appE method fun) fieldAccess AppT t1 t2 | t1 /= VarT typeVar -> genCotraverseField className method fun t2 fieldAccess (wrap . appE (varE 'cotraverse)) SigT ty _kind -> genCotraverseField className method fun ty fieldAccess wrap ParensT ty -> genCotraverseField className method fun ty fieldAccess wrap genDeliverField :: Name -> Type -> ((Q Exp -> Q Exp) -> Q Exp) -> ((Q Exp -> Q Exp) -> Q Exp) -> Q Exp -> (Q Exp -> Q Exp) -> (Q Exp -> Q Exp) -> Q ([Type], Exp) genDeliverField className fieldType fieldUpdate subRecordUpdate arg outer inner = do Just (Deriving _ typeVar) <- getQ case fieldType of AppT ty _ | ty == VarT typeVar -> (,) [] <$> outer (appE [|Compose|] ([|contramap|] `appE` fieldUpdate inner `appE` arg)) AppT t1 t2 | t2 == VarT typeVar -> (,) (constrain className t1) <$> outer (appE [| Rank2.deliver |] ([|contramap|] `appE` subRecordUpdate inner `appE` arg)) AppT t1 t2 | t1 /= VarT typeVar -> genDeliverField className t2 fieldUpdate subRecordUpdate arg (outer . appE (varE 'pure)) (inner . appE (varE 'fmap)) SigT ty _kind -> genDeliverField className ty fieldUpdate subRecordUpdate arg outer inner ParensT ty -> genDeliverField className ty fieldUpdate subRecordUpdate arg outer inner constrain :: Name -> Type -> [Type] constrain _ ConT{} = [] constrain cls t = [ConT cls `AppT` t]
20c41d0c35dab5295098c54cfe13d84f30cff9e7d7c6c2f4ebe8030b9ecc3088
paulgray/exml
exml.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2011 , Erlang Solutions Ltd. %%% @doc %%% %%% @end Created : 12 Jul 2011 by < > %%%------------------------------------------------------------------- -module(exml). -include("exml_stream.hrl"). -export([parse/1]). -export([to_list/1, to_binary/1, to_iolist/1, to_pretty_iolist/1, to_pretty_iolist/3]). -export([to_list/2, to_binary/2, to_iolist/2, to_pretty_iolist/2, to_pretty_iolist/4]). -export([escape_attr/1, unescape_attr/1, escape_cdata/1, unescape_cdata/1, unescape_cdata_as/2]). -on_load(load/0). Maximum bytes passed to the NIF handler at once Current value is erlang : system_info(context_reductions ) * 10 -define(MAX_BYTES_TO_NIF, 20000). -spec load() -> any(). load() -> PrivDir = case code:priv_dir(?MODULE) of {error, _} -> EbinDir = filename:dirname(code:which(?MODULE)), AppPath = filename:dirname(EbinDir), filename:join(AppPath, "priv"); Path -> Path end, erlang:load_nif(filename:join(PrivDir, "exml_escape"), none). -spec to_list(#xmlstreamstart{} | #xmlstreamend{} | xmlterm()) -> string(). to_list(Element) -> binary_to_list(to_binary(Element)). -spec to_list(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), [escape]) -> string(). to_list(Element, Opts) -> binary_to_list(to_binary(Element, Opts)). -spec to_binary(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> binary(). to_binary(Element) -> list_to_binary(to_iolist(Element)). -spec to_binary(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()], [escape]) -> binary(). to_binary(Element, Opts) -> list_to_binary(to_iolist(Element, Opts)). -spec to_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> iolist(). to_iolist(Elements) -> to_iolist(Elements, []). -spec to_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()], [escape]) -> iolist(). to_iolist(Data, Opts) -> case lists:member(escape, Opts) of true -> to_iolist_escape(Data); false -> to_iolist_clean(Data) end. -spec to_iolist_escape(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> iolist(). to_iolist_escape(Elements) when is_list(Elements) -> lists:map(fun to_iolist_escape/1, Elements); to_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = []}) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], ["<", Name, attrs_to_iolist(EAttrs), "/>"]; to_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = Children}) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], ["<", Name, attrs_to_iolist(EAttrs), ">", to_iolist_escape(Children), "</", Name, ">"]; to_iolist_escape(#xmlstreamstart{name = Name, attrs = Attrs}) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], ["<", Name, attrs_to_iolist(EAttrs), ">"]; to_iolist_escape(#xmlstreamend{name = Name}) -> ["</", Name, ">"]; to_iolist_escape(#xmlcdata{content = Content}) -> [escape_cdata(Content)]. %% ensure we return io*list* -spec to_iolist_clean(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> iolist(). to_iolist_clean(Elements) when is_list(Elements) -> lists:map(fun to_iolist_clean/1, Elements); to_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = []}) -> ["<", Name, attrs_to_iolist(Attrs), "/>"]; to_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = Children}) -> ["<", Name, attrs_to_iolist(Attrs), ">", to_iolist_clean(Children), "</", Name, ">"]; to_iolist_clean(#xmlstreamstart{name = Name, attrs = Attrs}) -> ["<", Name, attrs_to_iolist(Attrs), ">"]; to_iolist_clean(#xmlstreamend{name = Name}) -> ["</", Name, ">"]; to_iolist_clean(#xmlcdata{content = Content}) -> [Content]. %% ensure we return io*list* -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm()) -> iolist(). to_pretty_iolist(Term) -> to_pretty_iolist(Term, 0, " ", []). -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), non_neg_integer(), string()) -> iolist(). to_pretty_iolist(Term, Level, Indent) -> to_pretty_iolist(Term, Level, Indent, []). -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), [escape]) -> iolist(). to_pretty_iolist(Term, Opts) -> to_pretty_iolist(Term, 0, " ", Opts). ` to_pretty_iolist/3 ' is generic enough to express ` to_iolist/1 ' %% by passing an empty string as `Indent', but that would be less efficient, %% so let's leave the implementations separate. -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), non_neg_integer(), string(), [escape]) -> iolist(). to_pretty_iolist(Data, Level, Indent, Opts) -> case lists:member(escape, Opts) of true -> to_pretty_iolist_escape(Data, Level, Indent); false -> to_pretty_iolist_clean(Data, Level, Indent) end. to_pretty_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = []}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), "/>\n"]; to_pretty_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = [#xmlcdata{content = Content}]}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), ">", escape_cdata(Content), "</", Name, ">\n"]; to_pretty_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = Children}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), ">\n", [to_pretty_iolist_escape(C, Level+1, Indent) || C <- Children], Shift, "</", Name, ">\n"]; to_pretty_iolist_escape(#xmlstreamstart{name = Name, attrs = Attrs}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), ">\n"]; to_pretty_iolist_escape(#xmlstreamend{name = Name}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "</", Name, ">\n"]; to_pretty_iolist_escape(#xmlcdata{content = Content}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, escape_cdata(Content), "\n"]. to_pretty_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = []}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), "/>\n"]; to_pretty_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = [#xmlcdata{content = Content}]}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), ">", Content, "</", Name, ">\n"]; to_pretty_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = Children}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), ">\n", [to_pretty_iolist_clean(C, Level+1, Indent) || C <- Children], Shift, "</", Name, ">\n"]; to_pretty_iolist_clean(#xmlstreamstart{name = Name, attrs = Attrs}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), ">\n"]; to_pretty_iolist_clean(#xmlstreamend{name = Name}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "</", Name, ">\n"]; to_pretty_iolist_clean(#xmlcdata{content = Content}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, Content, "\n"]. -spec attrs_to_iolist([{binary(), binary()}]) -> iolist(). attrs_to_iolist(Attrs) -> [ [" ", Name, "='", Value, "'"] || {Name, Value} <- Attrs]. -spec parse(binary()) -> {ok, #xmlel{}} | {error, any()}. parse(XML) -> {ok, Parser} = exml_stream:new_parser(), Stream = <<"<stream>", XML/binary, "</stream>">>, Result = case exml_stream:parse(Parser, Stream) of {ok, _, [#xmlstreamstart{}, Tree, #xmlstreamend{}]} -> {ok, Tree}; {ok, _, Other} -> {error, {bad_parse, Other}}; {error, Error} -> {error, Error} end, ok = exml_stream:free_parser(Parser), Result. -spec escape_cdata(iodata()) -> #xmlcdata{}. escape_cdata(Content) -> BContent = list_to_binary([Content]), NewContent = feed_nif(fun escape_cdata_nif/1, BContent, byte_size(BContent), []), #xmlcdata{content = NewContent}. -spec unescape_cdata(#xmlcdata{}) -> binary(). unescape_cdata(#xmlcdata{content = Content}) -> BContent = list_to_binary([Content]), feed_nif(fun unescape_cdata_nif/1, BContent, byte_size(BContent), []). -spec unescape_cdata_as(binary|list|iodata, #xmlcdata{}) -> binary(). unescape_cdata_as(What, CData) -> unescape_cdata_as_erl(What, CData). -spec escape_cdata_nif(iodata()) -> binary(). escape_cdata_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}). -spec unescape_cdata_nif(iodata()) -> binary(). unescape_cdata_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}). -spec unescape_cdata_as_erl(binary|list|iodata, #xmlcdata{}) -> binary(). unescape_cdata_as_erl(What, #xmlcdata{content=GtEsc}) -> LtEsc = re:replace(GtEsc, "&gt;", ">", [global]), AmpEsc = re:replace(LtEsc, "&lt;", "<", [global]), Text = re:replace(AmpEsc, "&amp;", "\\&", [global, {return, What}]), Text. -spec escape_attr(binary()) -> binary(). escape_attr(Text) -> feed_nif(fun escape_attr_nif/1, Text, byte_size(Text), []). -spec unescape_attr(binary()) -> binary(). unescape_attr(Text) -> feed_nif(fun unescape_attr_nif/1, Text, byte_size(Text), []). -spec feed_nif(function(), binary(), integer(), list()) -> binary(). feed_nif(Fun, Text, Size, Acc) when Size > ?MAX_BYTES_TO_NIF -> <<Chunk:?MAX_BYTES_TO_NIF/binary, Rest/binary>> = Text, Resp = Fun(Chunk), feed_nif(Fun, Rest, Size - ?MAX_BYTES_TO_NIF, [Resp | Acc]); feed_nif(Fun, Text, _Size, Acc) -> Resp = Fun(Text), list_to_binary(lists:reverse([Resp | Acc])). -spec escape_attr_nif(binary()) -> binary(). escape_attr_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}). -spec unescape_attr_nif(binary()) -> binary(). unescape_attr_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}).
null
https://raw.githubusercontent.com/paulgray/exml/d04d0dfc956bd2bf5d9629a7524c6840eb02df28/src/exml.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- ensure we return io*list* ensure we return io*list* by passing an empty string as `Indent', but that would be less efficient, so let's leave the implementations separate.
@author < > ( C ) 2011 , Erlang Solutions Ltd. Created : 12 Jul 2011 by < > -module(exml). -include("exml_stream.hrl"). -export([parse/1]). -export([to_list/1, to_binary/1, to_iolist/1, to_pretty_iolist/1, to_pretty_iolist/3]). -export([to_list/2, to_binary/2, to_iolist/2, to_pretty_iolist/2, to_pretty_iolist/4]). -export([escape_attr/1, unescape_attr/1, escape_cdata/1, unescape_cdata/1, unescape_cdata_as/2]). -on_load(load/0). Maximum bytes passed to the NIF handler at once Current value is erlang : system_info(context_reductions ) * 10 -define(MAX_BYTES_TO_NIF, 20000). -spec load() -> any(). load() -> PrivDir = case code:priv_dir(?MODULE) of {error, _} -> EbinDir = filename:dirname(code:which(?MODULE)), AppPath = filename:dirname(EbinDir), filename:join(AppPath, "priv"); Path -> Path end, erlang:load_nif(filename:join(PrivDir, "exml_escape"), none). -spec to_list(#xmlstreamstart{} | #xmlstreamend{} | xmlterm()) -> string(). to_list(Element) -> binary_to_list(to_binary(Element)). -spec to_list(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), [escape]) -> string(). to_list(Element, Opts) -> binary_to_list(to_binary(Element, Opts)). -spec to_binary(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> binary(). to_binary(Element) -> list_to_binary(to_iolist(Element)). -spec to_binary(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()], [escape]) -> binary(). to_binary(Element, Opts) -> list_to_binary(to_iolist(Element, Opts)). -spec to_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> iolist(). to_iolist(Elements) -> to_iolist(Elements, []). -spec to_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()], [escape]) -> iolist(). to_iolist(Data, Opts) -> case lists:member(escape, Opts) of true -> to_iolist_escape(Data); false -> to_iolist_clean(Data) end. -spec to_iolist_escape(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> iolist(). to_iolist_escape(Elements) when is_list(Elements) -> lists:map(fun to_iolist_escape/1, Elements); to_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = []}) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], ["<", Name, attrs_to_iolist(EAttrs), "/>"]; to_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = Children}) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], ["<", Name, attrs_to_iolist(EAttrs), ">", to_iolist_escape(Children), "</", Name, ">"]; to_iolist_escape(#xmlstreamstart{name = Name, attrs = Attrs}) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], ["<", Name, attrs_to_iolist(EAttrs), ">"]; to_iolist_escape(#xmlstreamend{name = Name}) -> ["</", Name, ">"]; to_iolist_escape(#xmlcdata{content = Content}) -> -spec to_iolist_clean(#xmlstreamstart{} | #xmlstreamend{} | xmlterm() | [xmlterm()]) -> iolist(). to_iolist_clean(Elements) when is_list(Elements) -> lists:map(fun to_iolist_clean/1, Elements); to_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = []}) -> ["<", Name, attrs_to_iolist(Attrs), "/>"]; to_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = Children}) -> ["<", Name, attrs_to_iolist(Attrs), ">", to_iolist_clean(Children), "</", Name, ">"]; to_iolist_clean(#xmlstreamstart{name = Name, attrs = Attrs}) -> ["<", Name, attrs_to_iolist(Attrs), ">"]; to_iolist_clean(#xmlstreamend{name = Name}) -> ["</", Name, ">"]; to_iolist_clean(#xmlcdata{content = Content}) -> -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm()) -> iolist(). to_pretty_iolist(Term) -> to_pretty_iolist(Term, 0, " ", []). -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), non_neg_integer(), string()) -> iolist(). to_pretty_iolist(Term, Level, Indent) -> to_pretty_iolist(Term, Level, Indent, []). -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), [escape]) -> iolist(). to_pretty_iolist(Term, Opts) -> to_pretty_iolist(Term, 0, " ", Opts). ` to_pretty_iolist/3 ' is generic enough to express ` to_iolist/1 ' -spec to_pretty_iolist(#xmlstreamstart{} | #xmlstreamend{} | xmlterm(), non_neg_integer(), string(), [escape]) -> iolist(). to_pretty_iolist(Data, Level, Indent, Opts) -> case lists:member(escape, Opts) of true -> to_pretty_iolist_escape(Data, Level, Indent); false -> to_pretty_iolist_clean(Data, Level, Indent) end. to_pretty_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = []}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), "/>\n"]; to_pretty_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = [#xmlcdata{content = Content}]}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), ">", escape_cdata(Content), "</", Name, ">\n"]; to_pretty_iolist_escape(#xmlel{name = Name, attrs = Attrs, children = Children}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), ">\n", [to_pretty_iolist_escape(C, Level+1, Indent) || C <- Children], Shift, "</", Name, ">\n"]; to_pretty_iolist_escape(#xmlstreamstart{name = Name, attrs = Attrs}, Level, Indent) -> EAttrs = [{AttrName, escape_attr(AttrVal)} || {AttrName, AttrVal} <- Attrs], Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(EAttrs), ">\n"]; to_pretty_iolist_escape(#xmlstreamend{name = Name}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "</", Name, ">\n"]; to_pretty_iolist_escape(#xmlcdata{content = Content}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, escape_cdata(Content), "\n"]. to_pretty_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = []}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), "/>\n"]; to_pretty_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = [#xmlcdata{content = Content}]}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), ">", Content, "</", Name, ">\n"]; to_pretty_iolist_clean(#xmlel{name = Name, attrs = Attrs, children = Children}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), ">\n", [to_pretty_iolist_clean(C, Level+1, Indent) || C <- Children], Shift, "</", Name, ">\n"]; to_pretty_iolist_clean(#xmlstreamstart{name = Name, attrs = Attrs}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "<", Name, attrs_to_iolist(Attrs), ">\n"]; to_pretty_iolist_clean(#xmlstreamend{name = Name}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, "</", Name, ">\n"]; to_pretty_iolist_clean(#xmlcdata{content = Content}, Level, Indent) -> Shift = lists:duplicate(Level, Indent), [Shift, Content, "\n"]. -spec attrs_to_iolist([{binary(), binary()}]) -> iolist(). attrs_to_iolist(Attrs) -> [ [" ", Name, "='", Value, "'"] || {Name, Value} <- Attrs]. -spec parse(binary()) -> {ok, #xmlel{}} | {error, any()}. parse(XML) -> {ok, Parser} = exml_stream:new_parser(), Stream = <<"<stream>", XML/binary, "</stream>">>, Result = case exml_stream:parse(Parser, Stream) of {ok, _, [#xmlstreamstart{}, Tree, #xmlstreamend{}]} -> {ok, Tree}; {ok, _, Other} -> {error, {bad_parse, Other}}; {error, Error} -> {error, Error} end, ok = exml_stream:free_parser(Parser), Result. -spec escape_cdata(iodata()) -> #xmlcdata{}. escape_cdata(Content) -> BContent = list_to_binary([Content]), NewContent = feed_nif(fun escape_cdata_nif/1, BContent, byte_size(BContent), []), #xmlcdata{content = NewContent}. -spec unescape_cdata(#xmlcdata{}) -> binary(). unescape_cdata(#xmlcdata{content = Content}) -> BContent = list_to_binary([Content]), feed_nif(fun unescape_cdata_nif/1, BContent, byte_size(BContent), []). -spec unescape_cdata_as(binary|list|iodata, #xmlcdata{}) -> binary(). unescape_cdata_as(What, CData) -> unescape_cdata_as_erl(What, CData). -spec escape_cdata_nif(iodata()) -> binary(). escape_cdata_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}). -spec unescape_cdata_nif(iodata()) -> binary(). unescape_cdata_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}). -spec unescape_cdata_as_erl(binary|list|iodata, #xmlcdata{}) -> binary(). unescape_cdata_as_erl(What, #xmlcdata{content=GtEsc}) -> LtEsc = re:replace(GtEsc, "&gt;", ">", [global]), AmpEsc = re:replace(LtEsc, "&lt;", "<", [global]), Text = re:replace(AmpEsc, "&amp;", "\\&", [global, {return, What}]), Text. -spec escape_attr(binary()) -> binary(). escape_attr(Text) -> feed_nif(fun escape_attr_nif/1, Text, byte_size(Text), []). -spec unescape_attr(binary()) -> binary(). unescape_attr(Text) -> feed_nif(fun unescape_attr_nif/1, Text, byte_size(Text), []). -spec feed_nif(function(), binary(), integer(), list()) -> binary(). feed_nif(Fun, Text, Size, Acc) when Size > ?MAX_BYTES_TO_NIF -> <<Chunk:?MAX_BYTES_TO_NIF/binary, Rest/binary>> = Text, Resp = Fun(Chunk), feed_nif(Fun, Rest, Size - ?MAX_BYTES_TO_NIF, [Resp | Acc]); feed_nif(Fun, Text, _Size, Acc) -> Resp = Fun(Text), list_to_binary(lists:reverse([Resp | Acc])). -spec escape_attr_nif(binary()) -> binary(). escape_attr_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}). -spec unescape_attr_nif(binary()) -> binary(). unescape_attr_nif(_Data) -> erlang:nif_error({?MODULE, nif_not_loaded}).
19a6db075756fd27a28448a5bfa9d2cc6577f11c59d80e9de2f320caaa6c5fce
sigscale/rim
im_server.erl
%%% im_server.erl %%% vim: ts=3 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 2018 - 2021 SigScale Global Inc. %%% @end 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. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% @doc This {@link //stdlib/gen_server. gen_server} behaviour callback %%% module implements a service access point (SAP) for the public API of the %%% {@link //sigscale_im. sigscale_im} application. %%% -module(im_server). -copyright('Copyright (c) 2018 - 2021 SigScale Global Inc.'). -behaviour(gen_server). %% export the im_server API -export([]). %% export the callbacks needed for gen_server behaviour -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {sup :: pid()}). -type state() :: #state{}. %%---------------------------------------------------------------------- %% The im_server API %%---------------------------------------------------------------------- %%---------------------------------------------------------------------- %% The im_server gen_server callbacks %%---------------------------------------------------------------------- -spec init(Args) -> Result when Args :: [term()], Result :: {ok, State :: state()} | {ok, State :: state(), Timeout :: timeout()} | {stop, Reason :: term()} | ignore. %% @doc Initialize the {@module} server. %% @see //stdlib/gen_server:init/1 @private %% init([Sup] = _Args) -> process_flag(trap_exit, true), {ok, #state{sup = Sup}}. -spec handle_call(Request, From, State) -> Result when Request :: term(), From :: {pid(), Tag :: any()}, State :: state(), Result :: {reply, Reply :: term(), NewState :: state()} | {reply, Reply :: term(), NewState :: state(), timeout() | hibernate} | {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), Reply :: term(), NewState :: state()} | {stop, Reason :: term(), NewState :: state()}. %% @doc Handle a request sent using {@link //stdlib/gen_server:call/2. %% gen_server:call/2,3} or {@link //stdlib/gen_server:multi_call/2. %% gen_server:multi_call/2,3,4}. @see //stdlib / gen_server : handle_call/3 @private %% handle_call(_Request, _From, State) -> {stop, not_implemented, State}. -spec handle_cast(Request, State) -> Result when Request :: term(), State :: state(), Result :: {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. @doc Handle a request sent using { @link //stdlib / gen_server : cast/2 . gen_server : cast/2 } or { @link //stdlib / gen_server : abcast/2 . %% gen_server:abcast/2,3}. %% @see //stdlib/gen_server:handle_cast/2 @private %% handle_cast(stop, State) -> {stop, normal, State}. -spec handle_info(Info, State) -> Result when Info :: timeout | term(), State:: state(), Result :: {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. %% @doc Handle a received message. %% @see //stdlib/gen_server:handle_info/2 @private %% handle_info(_Info, State) -> {stop, not_implemented, State}. -spec terminate(Reason, State) -> any() when Reason :: normal | shutdown | {shutdown, term()} | term(), State::state(). %% @doc Cleanup and exit. @see //stdlib / gen_server : terminate/3 @private %% terminate(_Reason, _State) -> ok. -spec code_change(OldVsn, State, Extra) -> Result when OldVsn :: term() | {down, term()}, State :: state(), Extra :: term(), Result :: {ok, NewState :: state()} | {error, Reason :: term()}. %% @doc Update internal state data during a release upgrade&#047;downgrade. %% @see //stdlib/gen_server:code_change/3 @private %% code_change(_OldVsn, State, _Extra) -> {ok, State}. %%---------------------------------------------------------------------- %% internal functions %%----------------------------------------------------------------------
null
https://raw.githubusercontent.com/sigscale/rim/f806a0c52430f86bf1d54324fd0b4b6e510aea43/src/im_server.erl
erlang
im_server.erl vim: ts=3 @end you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc This {@link //stdlib/gen_server. gen_server} behaviour callback module implements a service access point (SAP) for the public API of the {@link //sigscale_im. sigscale_im} application. export the im_server API export the callbacks needed for gen_server behaviour ---------------------------------------------------------------------- The im_server API ---------------------------------------------------------------------- ---------------------------------------------------------------------- The im_server gen_server callbacks ---------------------------------------------------------------------- @doc Initialize the {@module} server. @see //stdlib/gen_server:init/1 @doc Handle a request sent using {@link //stdlib/gen_server:call/2. gen_server:call/2,3} or {@link //stdlib/gen_server:multi_call/2. gen_server:multi_call/2,3,4}. gen_server:abcast/2,3}. @see //stdlib/gen_server:handle_cast/2 @doc Handle a received message. @see //stdlib/gen_server:handle_info/2 @doc Cleanup and exit. @doc Update internal state data during a release upgrade&#047;downgrade. @see //stdlib/gen_server:code_change/3 ---------------------------------------------------------------------- internal functions ----------------------------------------------------------------------
2018 - 2021 SigScale Global Inc. Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(im_server). -copyright('Copyright (c) 2018 - 2021 SigScale Global Inc.'). -behaviour(gen_server). -export([]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {sup :: pid()}). -type state() :: #state{}. -spec init(Args) -> Result when Args :: [term()], Result :: {ok, State :: state()} | {ok, State :: state(), Timeout :: timeout()} | {stop, Reason :: term()} | ignore. @private init([Sup] = _Args) -> process_flag(trap_exit, true), {ok, #state{sup = Sup}}. -spec handle_call(Request, From, State) -> Result when Request :: term(), From :: {pid(), Tag :: any()}, State :: state(), Result :: {reply, Reply :: term(), NewState :: state()} | {reply, Reply :: term(), NewState :: state(), timeout() | hibernate} | {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), Reply :: term(), NewState :: state()} | {stop, Reason :: term(), NewState :: state()}. @see //stdlib / gen_server : handle_call/3 @private handle_call(_Request, _From, State) -> {stop, not_implemented, State}. -spec handle_cast(Request, State) -> Result when Request :: term(), State :: state(), Result :: {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. @doc Handle a request sent using { @link //stdlib / gen_server : cast/2 . gen_server : cast/2 } or { @link //stdlib / gen_server : abcast/2 . @private handle_cast(stop, State) -> {stop, normal, State}. -spec handle_info(Info, State) -> Result when Info :: timeout | term(), State:: state(), Result :: {noreply, NewState :: state()} | {noreply, NewState :: state(), timeout() | hibernate} | {stop, Reason :: term(), NewState :: state()}. @private handle_info(_Info, State) -> {stop, not_implemented, State}. -spec terminate(Reason, State) -> any() when Reason :: normal | shutdown | {shutdown, term()} | term(), State::state(). @see //stdlib / gen_server : terminate/3 @private terminate(_Reason, _State) -> ok. -spec code_change(OldVsn, State, Extra) -> Result when OldVsn :: term() | {down, term()}, State :: state(), Extra :: term(), Result :: {ok, NewState :: state()} | {error, Reason :: term()}. @private code_change(_OldVsn, State, _Extra) -> {ok, State}.
10c39e55443c5c2dd3785af09e1889591560def99aa69f1e3ecd9922fd024153
robert-strandh/SICL
packages.lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-who-calls-visualizer (:use #:common-lisp) (:export #:visualize))
null
https://raw.githubusercontent.com/robert-strandh/SICL/eee214bc9a8b9a74c2f0cf533f7c502a07df2ef3/Code/Who-calls-visualizer/packages.lisp
lisp
(cl:in-package #:common-lisp-user) (defpackage #:sicl-who-calls-visualizer (:use #:common-lisp) (:export #:visualize))
cbc88faa1755ff1151aa5bc7b97a7844b116ca3a423aefb1ac1fe2aca5f0e12f
rbkmoney/fistful-server
w2w_transfer_machine.erl
%%% %%% w2w transfer machine %%% -module(w2w_transfer_machine). -behaviour(machinery). %% API -type id() :: machinery:id(). -type change() :: w2w_transfer:event(). -type event() :: {integer(), ff_machine:timestamped_event(change())}. -type st() :: ff_machine:st(w2w_transfer()). -type w2w_transfer() :: w2w_transfer:w2w_transfer_state(). -type external_id() :: id(). -type event_range() :: {After :: non_neg_integer() | undefined, Limit :: non_neg_integer() | undefined}. -type params() :: w2w_transfer:params(). -type create_error() :: w2w_transfer:create_error() | exists. -type start_adjustment_error() :: w2w_transfer:start_adjustment_error() | unknown_w2w_transfer_error(). -type unknown_w2w_transfer_error() :: {unknown_w2w_transfer, id()}. -type repair_error() :: ff_repair:repair_error(). -type repair_response() :: ff_repair:repair_response(). -export_type([id/0]). -export_type([st/0]). -export_type([change/0]). -export_type([event/0]). -export_type([params/0]). -export_type([w2w_transfer/0]). -export_type([event_range/0]). -export_type([external_id/0]). -export_type([create_error/0]). -export_type([start_adjustment_error/0]). -export_type([repair_error/0]). -export_type([repair_response/0]). %% API -export([create/2]). -export([get/1]). -export([get/2]). -export([events/2]). -export([repair/2]). -export([start_adjustment/2]). Accessors -export([w2w_transfer/1]). -export([ctx/1]). %% Machinery -export([init/4]). -export([process_timeout/3]). -export([process_repair/4]). -export([process_call/4]). Pipeline -import(ff_pipeline, [do/1, unwrap/1]). %% Internal types -type ctx() :: ff_entity_context:context(). -type adjustment_params() :: w2w_transfer:adjustment_params(). -type call() :: {start_adjustment, adjustment_params()}. -define(NS, 'ff/w2w_transfer_v1'). %% API -spec create(params(), ctx()) -> ok | {error, w2w_transfer:create_error() | exists}. create(Params, Ctx) -> do(fun() -> #{id := ID} = Params, Events = unwrap(w2w_transfer:create(Params)), unwrap(machinery:start(?NS, ID, {Events, Ctx}, backend())) end). -spec get(id()) -> {ok, st()} | {error, unknown_w2w_transfer_error()}. get(ID) -> get(ID, {undefined, undefined}). -spec get(id(), event_range()) -> {ok, st()} | {error, unknown_w2w_transfer_error()}. get(ID, {After, Limit}) -> case ff_machine:get(w2w_transfer, ?NS, ID, {After, Limit, forward}) of {ok, _Machine} = Result -> Result; {error, notfound} -> {error, {unknown_w2w_transfer, ID}} end. -spec events(id(), event_range()) -> {ok, [event()]} | {error, unknown_w2w_transfer_error()}. events(ID, {After, Limit}) -> case machinery:get(?NS, ID, {After, Limit, forward}, backend()) of {ok, #{history := History}} -> {ok, [{EventID, TsEv} || {EventID, _, TsEv} <- History]}; {error, notfound} -> {error, {unknown_w2w_transfer, ID}} end. -spec repair(id(), ff_repair:scenario()) -> {ok, repair_response()} | {error, notfound | working | {failed, repair_error()}}. repair(ID, Scenario) -> machinery:repair(?NS, ID, Scenario, backend()). -spec start_adjustment(id(), adjustment_params()) -> ok | {error, start_adjustment_error()}. start_adjustment(W2WTransferID, Params) -> call(W2WTransferID, {start_adjustment, Params}). Accessors -spec w2w_transfer(st()) -> w2w_transfer(). w2w_transfer(St) -> ff_machine:model(St). -spec ctx(st()) -> ctx(). ctx(St) -> ff_machine:ctx(St). %% Machinery -type machine() :: ff_machine:machine(event()). -type result() :: ff_machine:result(event()). -type handler_opts() :: machinery:handler_opts(_). -type handler_args() :: machinery:handler_args(_). -spec init({[event()], ctx()}, machine(), handler_args(), handler_opts()) -> result(). init({Events, Ctx}, #{}, _, _Opts) -> #{ events => ff_machine:emit_events(Events), action => continue, aux_state => #{ctx => Ctx} }. -spec process_timeout(machine(), handler_args(), handler_opts()) -> result(). process_timeout(Machine, _, _Opts) -> St = ff_machine:collapse(w2w_transfer, Machine), W2WTransfer = w2w_transfer(St), process_result(w2w_transfer:process_transfer(W2WTransfer)). -spec process_call(call(), machine(), handler_args(), handler_opts()) -> {Response, result()} when Response :: ok | {error, w2w_transfer:start_adjustment_error()}. process_call({start_adjustment, Params}, Machine, _, _Opts) -> do_start_adjustment(Params, Machine); process_call(CallArgs, _Machine, _, _Opts) -> erlang:error({unexpected_call, CallArgs}). -spec process_repair(ff_repair:scenario(), machine(), handler_args(), handler_opts()) -> {ok, {repair_response(), result()}} | {error, repair_error()}. process_repair(Scenario, Machine, _Args, _Opts) -> ff_repair:apply_scenario(w2w_transfer, Machine, Scenario). %% Internals backend() -> fistful:backend(?NS). -spec do_start_adjustment(adjustment_params(), machine()) -> {Response, result()} when Response :: ok | {error, w2w_transfer:start_adjustment_error()}. do_start_adjustment(Params, Machine) -> St = ff_machine:collapse(w2w_transfer, Machine), case w2w_transfer:start_adjustment(Params, w2w_transfer(St)) of {ok, Result} -> {ok, process_result(Result)}; {error, _Reason} = Error -> {Error, #{}} end. process_result({Action, Events}) -> genlib_map:compact(#{ events => set_events(Events), action => Action }). set_events([]) -> undefined; set_events(Events) -> ff_machine:emit_events(Events). call(ID, Call) -> case machinery:call(?NS, ID, Call, backend()) of {ok, Reply} -> Reply; {error, notfound} -> {error, {unknown_w2w_transfer, ID}} end.
null
https://raw.githubusercontent.com/rbkmoney/fistful-server/60b964d0e07f911c841903bc61d8d9fb20a32658/apps/w2w/src/w2w_transfer_machine.erl
erlang
w2w transfer machine API API Machinery Internal types API Machinery Internals
-module(w2w_transfer_machine). -behaviour(machinery). -type id() :: machinery:id(). -type change() :: w2w_transfer:event(). -type event() :: {integer(), ff_machine:timestamped_event(change())}. -type st() :: ff_machine:st(w2w_transfer()). -type w2w_transfer() :: w2w_transfer:w2w_transfer_state(). -type external_id() :: id(). -type event_range() :: {After :: non_neg_integer() | undefined, Limit :: non_neg_integer() | undefined}. -type params() :: w2w_transfer:params(). -type create_error() :: w2w_transfer:create_error() | exists. -type start_adjustment_error() :: w2w_transfer:start_adjustment_error() | unknown_w2w_transfer_error(). -type unknown_w2w_transfer_error() :: {unknown_w2w_transfer, id()}. -type repair_error() :: ff_repair:repair_error(). -type repair_response() :: ff_repair:repair_response(). -export_type([id/0]). -export_type([st/0]). -export_type([change/0]). -export_type([event/0]). -export_type([params/0]). -export_type([w2w_transfer/0]). -export_type([event_range/0]). -export_type([external_id/0]). -export_type([create_error/0]). -export_type([start_adjustment_error/0]). -export_type([repair_error/0]). -export_type([repair_response/0]). -export([create/2]). -export([get/1]). -export([get/2]). -export([events/2]). -export([repair/2]). -export([start_adjustment/2]). Accessors -export([w2w_transfer/1]). -export([ctx/1]). -export([init/4]). -export([process_timeout/3]). -export([process_repair/4]). -export([process_call/4]). Pipeline -import(ff_pipeline, [do/1, unwrap/1]). -type ctx() :: ff_entity_context:context(). -type adjustment_params() :: w2w_transfer:adjustment_params(). -type call() :: {start_adjustment, adjustment_params()}. -define(NS, 'ff/w2w_transfer_v1'). -spec create(params(), ctx()) -> ok | {error, w2w_transfer:create_error() | exists}. create(Params, Ctx) -> do(fun() -> #{id := ID} = Params, Events = unwrap(w2w_transfer:create(Params)), unwrap(machinery:start(?NS, ID, {Events, Ctx}, backend())) end). -spec get(id()) -> {ok, st()} | {error, unknown_w2w_transfer_error()}. get(ID) -> get(ID, {undefined, undefined}). -spec get(id(), event_range()) -> {ok, st()} | {error, unknown_w2w_transfer_error()}. get(ID, {After, Limit}) -> case ff_machine:get(w2w_transfer, ?NS, ID, {After, Limit, forward}) of {ok, _Machine} = Result -> Result; {error, notfound} -> {error, {unknown_w2w_transfer, ID}} end. -spec events(id(), event_range()) -> {ok, [event()]} | {error, unknown_w2w_transfer_error()}. events(ID, {After, Limit}) -> case machinery:get(?NS, ID, {After, Limit, forward}, backend()) of {ok, #{history := History}} -> {ok, [{EventID, TsEv} || {EventID, _, TsEv} <- History]}; {error, notfound} -> {error, {unknown_w2w_transfer, ID}} end. -spec repair(id(), ff_repair:scenario()) -> {ok, repair_response()} | {error, notfound | working | {failed, repair_error()}}. repair(ID, Scenario) -> machinery:repair(?NS, ID, Scenario, backend()). -spec start_adjustment(id(), adjustment_params()) -> ok | {error, start_adjustment_error()}. start_adjustment(W2WTransferID, Params) -> call(W2WTransferID, {start_adjustment, Params}). Accessors -spec w2w_transfer(st()) -> w2w_transfer(). w2w_transfer(St) -> ff_machine:model(St). -spec ctx(st()) -> ctx(). ctx(St) -> ff_machine:ctx(St). -type machine() :: ff_machine:machine(event()). -type result() :: ff_machine:result(event()). -type handler_opts() :: machinery:handler_opts(_). -type handler_args() :: machinery:handler_args(_). -spec init({[event()], ctx()}, machine(), handler_args(), handler_opts()) -> result(). init({Events, Ctx}, #{}, _, _Opts) -> #{ events => ff_machine:emit_events(Events), action => continue, aux_state => #{ctx => Ctx} }. -spec process_timeout(machine(), handler_args(), handler_opts()) -> result(). process_timeout(Machine, _, _Opts) -> St = ff_machine:collapse(w2w_transfer, Machine), W2WTransfer = w2w_transfer(St), process_result(w2w_transfer:process_transfer(W2WTransfer)). -spec process_call(call(), machine(), handler_args(), handler_opts()) -> {Response, result()} when Response :: ok | {error, w2w_transfer:start_adjustment_error()}. process_call({start_adjustment, Params}, Machine, _, _Opts) -> do_start_adjustment(Params, Machine); process_call(CallArgs, _Machine, _, _Opts) -> erlang:error({unexpected_call, CallArgs}). -spec process_repair(ff_repair:scenario(), machine(), handler_args(), handler_opts()) -> {ok, {repair_response(), result()}} | {error, repair_error()}. process_repair(Scenario, Machine, _Args, _Opts) -> ff_repair:apply_scenario(w2w_transfer, Machine, Scenario). backend() -> fistful:backend(?NS). -spec do_start_adjustment(adjustment_params(), machine()) -> {Response, result()} when Response :: ok | {error, w2w_transfer:start_adjustment_error()}. do_start_adjustment(Params, Machine) -> St = ff_machine:collapse(w2w_transfer, Machine), case w2w_transfer:start_adjustment(Params, w2w_transfer(St)) of {ok, Result} -> {ok, process_result(Result)}; {error, _Reason} = Error -> {Error, #{}} end. process_result({Action, Events}) -> genlib_map:compact(#{ events => set_events(Events), action => Action }). set_events([]) -> undefined; set_events(Events) -> ff_machine:emit_events(Events). call(ID, Call) -> case machinery:call(?NS, ID, Call, backend()) of {ok, Reply} -> Reply; {error, notfound} -> {error, {unknown_w2w_transfer, ID}} end.
1fa20970b2221c0bc1109036b2452abbcd6be3e03e0eca6050c02e21cc1e32c1
tonyg/kali-scheme
strong.scm
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . ; Code to find the strongly connected components of a graph. ; (TO <vertex>) are the vertices that have an edge to <vertex>. ( SLOT < vertex > ) and ( SET - SLOT ! < vertex > < value > ) is a settable slot ; used by the algorithm. ; ; The components are returned in a backwards topologically sorted list. (define (strongly-connected-components vertices to slot set-slot!) (make-vertices vertices to slot set-slot!) (let loop ((to-do vertices) (index 0) (stack #t) (comps '())) (let ((to-do (find-next-vertex to-do slot))) (cond ((null? to-do) (for-each (lambda (n) (set-slot! n #f)) vertices) comps) (else (call-with-values (lambda () (do-vertex (slot (car to-do)) index stack comps)) (lambda (index stack comps) (loop to-do index stack comps)))))))) (define (find-next-vertex vertices slot) (do ((vertices vertices (cdr vertices))) ((or (null? vertices) (= 0 (vertex-index (slot (car vertices))))) vertices))) (define-record-type vertex :vertex (really-make-vertex data edges stack index parent lowpoint) vertex? (data vertex-data) ; user's data (edges vertex-edges set-vertex-edges!) ; list of vertices (stack vertex-stack set-vertex-stack!) ; next vertex on the stack (index vertex-index set-vertex-index!) ; time at which this vertex was ; reached in the traversal a vertex pointing to this one (lowpoint vertex-lowpoint set-vertex-lowpoint!)) ; lowest index in this ; vertices strongly connected component (define (make-vertex data) (really-make-vertex data '() #f 0 #f #f)) (define (make-vertices vertices to slot set-slot!) (let ((maybe-slot (lambda (n) (let ((s (slot n))) (if (vertex? s) s (error "graph edge points to non-vertex" n)))))) (for-each (lambda (n) (set-slot! n (make-vertex n))) vertices) (for-each (lambda (n) (set-vertex-edges! (slot n) (map maybe-slot (to n)))) vertices) (values))) The numbers are the algorithm step numbers from page 65 of Graph Algorithms , Shimon Even , Computer Science Press , 1979 . 2 (define (do-vertex vertex index stack comps) (let ((index (+ index '1))) (set-vertex-index! vertex index) (set-vertex-lowpoint! vertex index) (set-vertex-stack! vertex stack) (get-strong vertex index vertex comps))) 3 (define (get-strong vertex index stack comps) (if (null? (vertex-edges vertex)) (end-vertex vertex index stack comps) (follow-edge vertex index stack comps))) 7 (define (end-vertex vertex index stack comps) (call-with-values (lambda () (if (= (vertex-index vertex) (vertex-lowpoint vertex)) (unwind-stack vertex stack comps) (values stack comps))) (lambda (stack comps) (cond ((vertex-parent vertex) => (lambda (parent) (if (> (vertex-lowpoint parent) (vertex-lowpoint vertex)) (set-vertex-lowpoint! parent (vertex-lowpoint vertex))) (get-strong parent index stack comps))) (else (values index stack comps)))))) (define (unwind-stack vertex stack comps) (let loop ((n stack) (c '())) (let ((next (vertex-stack n)) (c (cons (vertex-data n) c))) (set-vertex-stack! n #f) (if (eq? n vertex) (values next (cons c comps)) (loop next c))))) 4 (define (follow-edge vertex index stack comps) (let* ((next (pop-vertex-edge! vertex)) (next-index (vertex-index next))) (cond ((= next-index 0) (set-vertex-parent! next vertex) (do-vertex next index stack comps)) (else (if (and (< next-index (vertex-index vertex)) (vertex-stack next) (< next-index (vertex-lowpoint vertex))) (set-vertex-lowpoint! vertex next-index)) (get-strong vertex index stack comps))))) (define (pop-vertex-edge! vertex) (let ((edges (vertex-edges vertex))) (set-vertex-edges! vertex (cdr edges)) (car edges))) GRAPH is ( ( < symbol > . < symbol > * ) * ) ;(define (test-strong graph) ; (let ((vertices (map (lambda (n) ( vector ( car n ) # f # f ) ) ; graph))) ; (for-each (lambda (data vertex) ( vector - set ! vertex 1 ( map ( lambda ( s ) ( first ( lambda ( v ) ; (eq? s (vector-ref v 0))) ; vertices)) ( cdr data ) ) ) ) ; graph ; vertices) ; (map (lambda (l) ; (map (lambda (n) (vector-ref n 0)) l)) ; (strongly-connected-components vertices ( lambda ( v ) ( vector - ref v 1 ) ) ( lambda ( v ) ( vector - ref v 2 ) ) ( lambda ( v ) ( vector - set ! v 2 ) ) ) ) ) )
null
https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/scheme/big/strong.scm
scheme
Code to find the strongly connected components of a graph. (TO <vertex>) are the vertices that have an edge to <vertex>. used by the algorithm. The components are returned in a backwards topologically sorted list. user's data list of vertices next vertex on the stack time at which this vertex was reached in the traversal lowest index in this vertices strongly connected component (define (test-strong graph) (let ((vertices (map (lambda (n) graph))) (for-each (lambda (data vertex) (eq? s (vector-ref v 0))) vertices)) graph vertices) (map (lambda (l) (map (lambda (n) (vector-ref n 0)) l)) (strongly-connected-components vertices
Copyright ( c ) 1993 , 1994 by and . Copyright ( c ) 1996 by NEC Research Institute , Inc. See file COPYING . ( SLOT < vertex > ) and ( SET - SLOT ! < vertex > < value > ) is a settable slot (define (strongly-connected-components vertices to slot set-slot!) (make-vertices vertices to slot set-slot!) (let loop ((to-do vertices) (index 0) (stack #t) (comps '())) (let ((to-do (find-next-vertex to-do slot))) (cond ((null? to-do) (for-each (lambda (n) (set-slot! n #f)) vertices) comps) (else (call-with-values (lambda () (do-vertex (slot (car to-do)) index stack comps)) (lambda (index stack comps) (loop to-do index stack comps)))))))) (define (find-next-vertex vertices slot) (do ((vertices vertices (cdr vertices))) ((or (null? vertices) (= 0 (vertex-index (slot (car vertices))))) vertices))) (define-record-type vertex :vertex (really-make-vertex data edges stack index parent lowpoint) vertex? a vertex pointing to this one (define (make-vertex data) (really-make-vertex data '() #f 0 #f #f)) (define (make-vertices vertices to slot set-slot!) (let ((maybe-slot (lambda (n) (let ((s (slot n))) (if (vertex? s) s (error "graph edge points to non-vertex" n)))))) (for-each (lambda (n) (set-slot! n (make-vertex n))) vertices) (for-each (lambda (n) (set-vertex-edges! (slot n) (map maybe-slot (to n)))) vertices) (values))) The numbers are the algorithm step numbers from page 65 of Graph Algorithms , Shimon Even , Computer Science Press , 1979 . 2 (define (do-vertex vertex index stack comps) (let ((index (+ index '1))) (set-vertex-index! vertex index) (set-vertex-lowpoint! vertex index) (set-vertex-stack! vertex stack) (get-strong vertex index vertex comps))) 3 (define (get-strong vertex index stack comps) (if (null? (vertex-edges vertex)) (end-vertex vertex index stack comps) (follow-edge vertex index stack comps))) 7 (define (end-vertex vertex index stack comps) (call-with-values (lambda () (if (= (vertex-index vertex) (vertex-lowpoint vertex)) (unwind-stack vertex stack comps) (values stack comps))) (lambda (stack comps) (cond ((vertex-parent vertex) => (lambda (parent) (if (> (vertex-lowpoint parent) (vertex-lowpoint vertex)) (set-vertex-lowpoint! parent (vertex-lowpoint vertex))) (get-strong parent index stack comps))) (else (values index stack comps)))))) (define (unwind-stack vertex stack comps) (let loop ((n stack) (c '())) (let ((next (vertex-stack n)) (c (cons (vertex-data n) c))) (set-vertex-stack! n #f) (if (eq? n vertex) (values next (cons c comps)) (loop next c))))) 4 (define (follow-edge vertex index stack comps) (let* ((next (pop-vertex-edge! vertex)) (next-index (vertex-index next))) (cond ((= next-index 0) (set-vertex-parent! next vertex) (do-vertex next index stack comps)) (else (if (and (< next-index (vertex-index vertex)) (vertex-stack next) (< next-index (vertex-lowpoint vertex))) (set-vertex-lowpoint! vertex next-index)) (get-strong vertex index stack comps))))) (define (pop-vertex-edge! vertex) (let ((edges (vertex-edges vertex))) (set-vertex-edges! vertex (cdr edges)) (car edges))) GRAPH is ( ( < symbol > . < symbol > * ) * ) ( vector ( car n ) # f # f ) ) ( vector - set ! vertex 1 ( map ( lambda ( s ) ( first ( lambda ( v ) ( cdr data ) ) ) ) ( lambda ( v ) ( vector - ref v 1 ) ) ( lambda ( v ) ( vector - ref v 2 ) ) ( lambda ( v ) ( vector - set ! v 2 ) ) ) ) ) )
979791286ed354fb806beadd42c426c467e897b0e1e275bb6f94ba08e17dc7b9
rurban/clisp
clos-class6.lisp
Common Lisp Object System for CLISP Class Part n-1 : Generic functions specified in the MOP . 2004 - 05 - 25 2005 - 2008 , 2017 (in-package "CLOS") ;;; =========================================================================== ;; Make creation of <defined-class> instances customizable. ;; Installing the accessor methods can only be done after a class has been ;; initialized, but must be done in a _primary_ initialize-instance method, ;; so that it doesn't interfere with :after/:around methods that a user could install . See MOP p. 60 . (defmethod initialize-instance ((class defined-class) &rest args) (declare (ignore args)) (call-next-method) ; == (apply #'shared-initialize class 't args) (install-class-direct-accessors class) class) (defmethod initialize-instance ((class structure-class) &rest args &key ((defclass-form defclass-form)) &allow-other-keys) (if (eq defclass-form 'defstruct) ; called from DEFINE-STRUCTURE-CLASS ;; we do not (CALL-NEXT-METHOD) because the ;; INITIALIZE-INSTANCE@DEFINED-CLASS method calls ;; INSTALL-CLASS-DIRECT-ACCESSORS which installs slot accessors immediately overwritten by the accessors defined by DEFSTRUCT (apply #'shared-initialize class 't args) (call-next-method)) ; initialize-instance@defined-class class) (setf (fdefinition 'initialize-instance-<built-in-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<built-in-class>) #'make-instance) (setf (fdefinition 'initialize-instance-<structure-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<structure-class>) #'make-instance) (setf (fdefinition 'initialize-instance-<standard-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<standard-class>) #'make-instance) (setf (fdefinition 'initialize-instance-<funcallable-standard-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<funcallable-standard-class>) #'make-instance) ;;; =========================================================================== ;;; Optimized class-xxx accessors. ;;; These are possible thanks to the :fixed-slot-locations class option. (defun check-class-initialized (class level) (unless (>= (class-initialized class) level) (error (TEXT "The class ~S has not yet been initialized.") class))) (defun check-class-finalized (class level) (check-class-initialized class 2) (unless (>= (class-initialized class) level) (error (TEXT "The class ~S has not yet been finalized.") class))) Not in MOP . (defun class-classname (class) (accessor-typecheck class 'potential-class 'class-classname) (sys::%record-ref class *<potential-class>-classname-location*)) (defun (setf class-classname) (new-value class) (accessor-typecheck class 'potential-class '(setf class-classname)) (setf (sys::%record-ref class *<potential-class>-classname-location*) new-value)) MOP p. 76 (defgeneric class-name (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (check-class-initialized class 1) (class-classname class)) (:method ((class forward-reference-to-class)) (slot-value class '$classname))) No extended method check because this GF is specified in ANSI CL . ;(initialize-extended-method-check #'class-name) MOP p. 92 (defgeneric (setf class-name) (new-value class) (declare (dynamically-modifiable)) (:method (new-value (class potential-class)) (unless (symbolp new-value) (error-of-type 'type-error :datum new-value :expected-type 'symbol (TEXT "~S: The name of a class must be a symbol, not ~S") '(setf class-name) new-value)) (when (built-in-class-p class) (error-of-type 'error (TEXT "~S: The name of the built-in class ~S cannot be modified") '(setf class-name) class)) (reinitialize-instance class :name new-value) new-value)) (initialize-extended-method-check #'(setf class-name)) Not in MOP . (defun class-direct-subclasses-table (class) (accessor-typecheck class 'super-class 'class-direct-subclasses-table) (if (potential-class-p class) (sys::%record-ref class *<potential-class>-direct-subclasses-location*) (slot-value class '$direct-subclasses))) (defun (setf class-direct-subclasses-table) (new-value class) (accessor-typecheck class 'super-class '(setf class-direct-subclasses-table)) (if (potential-class-p class) (setf (sys::%record-ref class *<potential-class>-direct-subclasses-location*) new-value) (setf (slot-value class '$direct-subclasses) new-value))) MOP p. 76 (defgeneric class-direct-subclasses (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (check-class-initialized class 2) (list-direct-subclasses class)) (:method ((class forward-reference-to-class)) (list-direct-subclasses class))) (defun class-not-yet-defined (method class) (clos-warning (TEXT "~S being called on ~S, but class ~S is not yet defined.") method class (class-name class))) MOP p. 76 (defgeneric class-direct-superclasses (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (check-class-initialized class 2) (sys::%record-ref class *<defined-class>-direct-superclasses-location*)) (:method ((class forward-reference-to-class)) ;; Broken MOP. Any use of this method is a bug. (class-not-yet-defined 'class-direct-superclasses class) '())) (initialize-extended-method-check #'class-direct-superclasses) Not in MOP . (defun (setf class-direct-superclasses) (new-value class) (accessor-typecheck class 'defined-class '(setf class-direct-superclasses)) (setf (sys::%record-ref class *<defined-class>-direct-superclasses-location*) new-value)) Not in MOP . (defun class-all-superclasses (class) (accessor-typecheck class 'defined-class 'class-all-superclasses) (sys::%record-ref class *<defined-class>-all-superclasses-location*)) (defun (setf class-all-superclasses) (new-value class) (accessor-typecheck class 'defined-class '(setf class-all-superclasses)) (setf (sys::%record-ref class *<defined-class>-all-superclasses-location*) new-value)) MOP p. 76 (defgeneric class-precedence-list (class) (:method ((class defined-class)) (check-class-finalized class 3) (sys::%record-ref class *<defined-class>-precedence-list-location*))) (initialize-extended-method-check #'class-precedence-list) Not in MOP . (defun (setf class-precedence-list) (new-value class) (accessor-typecheck class 'defined-class '(setf class-precedence-list)) (setf (sys::%record-ref class *<defined-class>-precedence-list-location*) new-value)) MOP p. 75 (defgeneric class-direct-slots (class) (:method ((class defined-class)) (check-class-initialized class 2) (sys::%record-ref class *<defined-class>-direct-slots-location*)) (:method ((class forward-reference-to-class)) ;; Broken MOP. Any use of this method is a bug. (class-not-yet-defined 'class-direct-slots class) '())) (initialize-extended-method-check #'class-direct-slots) Not in MOP . (defun (setf class-direct-slots) (new-value class) (accessor-typecheck class 'defined-class '(setf class-direct-slots)) (setf (sys::%record-ref class *<defined-class>-direct-slots-location*) new-value)) MOP p. 77 (defgeneric class-slots (class) (:method ((class defined-class)) (check-class-finalized class 5) (sys::%record-ref class *<defined-class>-slots-location*))) (initialize-extended-method-check #'class-slots) Not in MOP . (defun (setf class-slots) (new-value class) (accessor-typecheck class 'defined-class '(setf class-slots)) (setf (sys::%record-ref class *<defined-class>-slots-location*) new-value)) Not in MOP . (defun class-slot-location-table (class) (accessor-typecheck class 'defined-class 'class-slot-location-table) (sys::%record-ref class *<defined-class>-slot-location-table-location*)) (defun (setf class-slot-location-table) (new-value class) (accessor-typecheck class 'defined-class '(setf class-slot-location-table)) (setf (sys::%record-ref class *<defined-class>-slot-location-table-location*) new-value)) MOP p. 75 (defgeneric class-direct-default-initargs (class) (:method ((class defined-class)) (check-class-initialized class 2) (sys::%record-ref class *<defined-class>-direct-default-initargs-location*)) (:method ((class forward-reference-to-class)) ;; Broken MOP. Any use of this method is a bug. (class-not-yet-defined 'class-direct-default-initargs class) '())) (initialize-extended-method-check #'class-direct-default-initargs) Not in MOP . (defun (setf class-direct-default-initargs) (new-value class) (accessor-typecheck class 'defined-class '(setf class-direct-default-initargs)) (setf (sys::%record-ref class *<defined-class>-direct-default-initargs-location*) new-value)) MOP p. 75 (defgeneric class-default-initargs (class) (:method ((class defined-class)) (check-class-finalized class 6) (sys::%record-ref class *<defined-class>-default-initargs-location*))) (initialize-extended-method-check #'class-default-initargs) Not in MOP . (defun (setf class-default-initargs) (new-value class) (accessor-typecheck class 'defined-class '(setf class-default-initargs)) (setf (sys::%record-ref class *<defined-class>-default-initargs-location*) new-value)) Not in MOP . (defun class-documentation (class) (accessor-typecheck class 'defined-class 'class-documentation) (sys::%record-ref class *<defined-class>-documentation-location*)) (defun (setf class-documentation) (new-value class) (accessor-typecheck class 'defined-class '(setf class-documentation)) (setf (sys::%record-ref class *<defined-class>-documentation-location*) new-value)) Not in MOP . (defun class-listeners (class) (accessor-typecheck class 'defined-class 'class-listeners) (sys::%record-ref class *<defined-class>-listeners-location*)) (defun (setf class-listeners) (new-value class) (accessor-typecheck class 'defined-class '(setf class-listeners)) (setf (sys::%record-ref class *<defined-class>-listeners-location*) new-value)) Not in MOP . (defun class-initialized (class) (accessor-typecheck class 'defined-class 'class-initialized) (sys::%record-ref class *<defined-class>-initialized-location*)) (defun (setf class-initialized) (new-value class) (accessor-typecheck class 'defined-class '(setf class-initialized)) (setf (sys::%record-ref class *<defined-class>-initialized-location*) new-value)) Not in MOP . (defun class-subclass-of-stablehash-p (class) (accessor-typecheck class 'slotted-class 'class-subclass-of-stablehash-p) (sys::%record-ref class *<slotted-class>-subclass-of-stablehash-p-location*)) (defun (setf class-subclass-of-stablehash-p) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-subclass-of-stablehash-p)) (setf (sys::%record-ref class *<slotted-class>-subclass-of-stablehash-p-location*) new-value)) Not in MOP . (defun class-generic-accessors (class) (accessor-typecheck class 'slotted-class 'class-generic-accessors) (sys::%record-ref class *<slotted-class>-generic-accessors-location*)) (defun (setf class-generic-accessors) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-generic-accessors)) (setf (sys::%record-ref class *<slotted-class>-generic-accessors-location*) new-value)) Not in MOP . (defun class-direct-accessors (class) (accessor-typecheck class 'slotted-class 'class-direct-accessors) (sys::%record-ref class *<slotted-class>-direct-accessors-location*)) (defun (setf class-direct-accessors) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-direct-accessors)) (setf (sys::%record-ref class *<slotted-class>-direct-accessors-location*) new-value)) Not in MOP . (defun class-valid-initargs-from-slots (class) (accessor-typecheck class 'slotted-class 'class-valid-initargs-from-slots) (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*)) (defun (setf class-valid-initargs-from-slots) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-valid-initargs-from-slots)) ;; When the valid-initargs-from-slots change, the result of ;; (valid-initarg-keywords class ...) changes, therefore we need to invalidate ;; all the caches that use valid-initarg-keywords: (when (or (eq (sys::%unbound) (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*)) (set-exclusive-or (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*) new-value)) (remhash class *make-instance-table*) (remhash class *reinitialize-instance-table*) (remhash class *update-instance-for-redefined-class-table*) (remhash class *update-instance-for-different-class-table*)) (setf (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*) new-value)) Not in MOP . (defun class-instance-size (class) (accessor-typecheck class 'slotted-class 'class-instance-size) (sys::%record-ref class *<slotted-class>-instance-size-location*)) (defun (setf class-instance-size) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-instance-size)) (setf (sys::%record-ref class *<slotted-class>-instance-size-location*) new-value)) Not in MOP . (defun class-names (class) (accessor-typecheck class 'structure-class 'class-names) (sys::%record-ref class *<structure-class>-names-location*)) (defun (setf class-names) (new-value class) (accessor-typecheck class 'structure-class '(setf class-names)) (setf (sys::%record-ref class *<structure-class>-names-location*) new-value)) Not in MOP . (defun class-kconstructor (class) (accessor-typecheck class 'structure-class 'class-kconstructor) (sys::%record-ref class *<structure-class>-kconstructor-location*)) (defun (setf class-kconstructor) (new-value class) (accessor-typecheck class 'structure-class '(setf class-kconstructor)) (setf (sys::%record-ref class *<structure-class>-kconstructor-location*) new-value)) Not in MOP . (defun class-boa-constructors (class) (accessor-typecheck class 'structure-class 'class-boa-constructors) (sys::%record-ref class *<structure-class>-boa-constructors-location*)) (defun (setf class-boa-constructors) (new-value class) (accessor-typecheck class 'structure-class '(setf class-boa-constructors)) (setf (sys::%record-ref class *<structure-class>-boa-constructors-location*) new-value)) Not in MOP . (defun class-copier (class) (accessor-typecheck class 'structure-class 'class-copier) (sys::%record-ref class *<structure-class>-copier-location*)) (defun (setf class-copier) (new-value class) (accessor-typecheck class 'structure-class '(setf class-copier)) (setf (sys::%record-ref class *<structure-class>-copier-location*) new-value)) Not in MOP . (defun class-predicate (class) (accessor-typecheck class 'structure-class 'class-predicate) (sys::%record-ref class *<structure-class>-predicate-location*)) (defun (setf class-predicate) (new-value class) (accessor-typecheck class 'structure-class '(setf class-predicate)) (setf (sys::%record-ref class *<structure-class>-predicate-location*) new-value)) Not in MOP . (defun class-current-version (class) (accessor-typecheck class 'semi-standard-class 'class-current-version) (sys::%record-ref class *<semi-standard-class>-current-version-location*)) (defun (setf class-current-version) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-current-version)) (setf (sys::%record-ref class *<semi-standard-class>-current-version-location*) new-value)) Not in MOP . (defun class-funcallablep (class) (accessor-typecheck class 'semi-standard-class 'class-funcallablep) (sys::%record-ref class *<semi-standard-class>-funcallablep-location*)) (defun (setf class-funcallablep) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-funcallablep)) (setf (sys::%record-ref class *<semi-standard-class>-funcallablep-location*) new-value)) Not in MOP . (defun class-fixed-slot-locations (class) (accessor-typecheck class 'semi-standard-class 'class-fixed-slot-locations) (sys::%record-ref class *<semi-standard-class>-fixed-slot-locations-location*)) (defun (setf class-fixed-slot-locations) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-fixed-slot-locations)) (setf (sys::%record-ref class *<semi-standard-class>-fixed-slot-locations-location*) new-value)) Not in MOP . (defun class-instantiated (class) (accessor-typecheck class 'semi-standard-class 'class-instantiated) (sys::%record-ref class *<semi-standard-class>-instantiated-location*)) (defun (setf class-instantiated) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-instantiated)) (setf (sys::%record-ref class *<semi-standard-class>-instantiated-location*) new-value)) Not in MOP . (defun class-direct-instance-specializers-table (class) (accessor-typecheck class 'semi-standard-class 'class-direct-instance-specializers-table) (sys::%record-ref class *<semi-standard-class>-direct-instance-specializers-location*)) (defun (setf class-direct-instance-specializers-table) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-direct-instance-specializers-table)) (setf (sys::%record-ref class *<semi-standard-class>-direct-instance-specializers-location*) new-value)) Not in MOP . (defun class-finalized-direct-subclasses-table (class) (accessor-typecheck class 'semi-standard-class 'class-finalized-direct-subclasses-table) (sys::%record-ref class *<semi-standard-class>-finalized-direct-subclasses-location*)) (defun (setf class-finalized-direct-subclasses-table) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-finalized-direct-subclasses-table)) (setf (sys::%record-ref class *<semi-standard-class>-finalized-direct-subclasses-location*) new-value)) MOP p. 77 (defgeneric class-prototype (class) (:method ((class semi-standard-class)) (check-class-finalized class 6) (or (sys::%record-ref class *<semi-standard-class>-prototype-location*) (setf (sys::%record-ref class *<semi-standard-class>-prototype-location*) (let ((old-instantiated (class-instantiated class))) (prog1 (clos::%allocate-instance class) ;; The allocation of the prototype doesn't need to flag the class as being instantiated , because 1 . the prototype is thrown away when the class is redefined , 2 . we do n't want ;; a redefinition with nonexistent or non-finalized ;; superclasses to succeed despite of the prototype. (setf (class-instantiated class) old-instantiated)))))) (:method ((class built-in-class)) (let ((prototype (sys::%record-ref class *<built-in-class>-prototype-location*))) (if (eq (sys::%unbound) prototype) (error (TEXT "~S: ~S is an abstract class and therefore does not have a direct instance") 'class-prototype class) prototype))) CLISP extension : (:method ((class structure-class)) (or (sys::%record-ref class *<structure-class>-prototype-location*) (setf (sys::%record-ref class *<structure-class>-prototype-location*) (clos::%allocate-instance class))))) (initialize-extended-method-check #'class-prototype) Not in MOP . (defun (setf class-prototype) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-prototype)) (setf (sys::%record-ref class *<semi-standard-class>-prototype-location*) new-value)) ;;; =========================================================================== Class Specification Protocol Not in MOP . (defgeneric compute-direct-slot-definition-initargs (class &rest slot-spec) (declare (dynamically-modifiable)) (:method ((class defined-class) &rest slot-spec) slot-spec)) ;;; =========================================================================== Class Finalization Protocol MOP p. 76 (defgeneric class-finalized-p (class) (:method ((class defined-class)) (= (class-initialized class) 6)) (:method ((class forward-reference-to-class)) nil) CLISP extension : Convenience method on symbols . (:method ((name symbol)) (class-finalized-p (find-class name)))) (initialize-extended-method-check #'class-finalized-p) MOP p. 54 (defgeneric finalize-inheritance (class) (:method ((class semi-standard-class)) (finalize-inheritance-<semi-standard-class> class)) CLISP extension : No - op method on other classes . (:method ((class defined-class)) class) CLISP extension : Convenience method on symbols . (:method ((name symbol)) (finalize-inheritance (find-class name)))) (initialize-extended-method-check #'finalize-inheritance) MOP p. 38 (defgeneric compute-class-precedence-list (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (compute-class-precedence-list-<defined-class> class))) Not in MOP . (defgeneric compute-effective-slot-definition-initargs (class direct-slot-definitions) (declare (dynamically-modifiable)) (:method ((class defined-class) direct-slot-definitions) (compute-effective-slot-definition-initargs-<defined-class> class direct-slot-definitions))) MOP p. 42 (defgeneric compute-effective-slot-definition (class slotname direct-slot-definitions) (declare (dynamically-modifiable)) (:method ((class defined-class) slotname direct-slot-definitions) (compute-effective-slot-definition-<defined-class> class slotname direct-slot-definitions))) MOP p. 43 (defgeneric compute-slots (class) (declare (dynamically-modifiable)) (:method ((class semi-standard-class)) (compute-slots-<defined-class>-primary class)) (:method :around ((class semi-standard-class)) (compute-slots-<slotted-class>-around class #'(lambda (c) (call-next-method c))))) MOP p. 39 (defgeneric compute-default-initargs (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (compute-default-initargs-<defined-class> class))) ;;; =========================================================================== ;;; Class definition customization MOP p. 47 (defgeneric ensure-class-using-class (class name &key metaclass direct-superclasses direct-slots direct-default-initargs documentation CLISP specific extension : fixed-slot-locations &allow-other-keys) (declare (dynamically-modifiable)) (:method ((class potential-class) name &rest args) (apply #'ensure-class-using-class-<t> class name args)) (:method ((class null) name &rest args) (apply #'ensure-class-using-class-<t> class name args))) MOP p. 102 (defgeneric validate-superclass (class superclass) (declare (dynamically-modifiable)) (:method ((class potential-class) (superclass potential-class)) (or (eq superclass <t>) (eq (class-of class) (class-of superclass)) (and (eq (class-of class) <funcallable-standard-class>) (eq (class-of superclass) <standard-class>)) ;; This makes no sense: If the superclass is a ;; funcallable-standard-class, it is a subclass of FUNCTION, ;; therefore class will become a subclass of FUNCTION too, but there is no way to FUNCALL or APPLY it . Where did the MOP authors have ;; their brain here? (and (eq (class-of class) <standard-class>) (eq (class-of superclass) <funcallable-standard-class>)) ;; Needed for clos-genfun1.lisp: (and (eq superclass <function>) (eq (class-classname class) 'funcallable-standard-object)) CLISP specific extension : (subclassp (class-of class) (class-of superclass))))) ;;; =========================================================================== Subclass relationship change notification MOP p. 32 (defgeneric add-direct-subclass (class subclass) (declare (dynamically-modifiable)) (:method ((class super-class) (subclass potential-class)) (add-direct-subclass-internal class subclass))) MOP p. 90 (defgeneric remove-direct-subclass (class subclass) (declare (dynamically-modifiable)) (:method ((class super-class) (subclass potential-class)) (remove-direct-subclass-internal class subclass))) ;;; =========================================================================== Accessor definition customization MOP p. 86 (defgeneric reader-method-class (class direct-slot &rest initargs) (declare (dynamically-modifiable)) (:method ((class defined-class) direct-slot &rest initargs) (declare (ignore direct-slot initargs)) <standard-reader-method>)) MOP p. 103 (defgeneric writer-method-class (class direct-slot &rest initargs) (declare (dynamically-modifiable)) (:method ((class defined-class) direct-slot &rest initargs) (declare (ignore direct-slot initargs)) <standard-writer-method>))
null
https://raw.githubusercontent.com/rurban/clisp/75ed2995ff8f5364bcc18727cde9438cca4e7c2c/src/clos-class6.lisp
lisp
=========================================================================== Make creation of <defined-class> instances customizable. Installing the accessor methods can only be done after a class has been initialized, but must be done in a _primary_ initialize-instance method, so that it doesn't interfere with :after/:around methods that a user could == (apply #'shared-initialize class 't args) called from DEFINE-STRUCTURE-CLASS we do not (CALL-NEXT-METHOD) because the INITIALIZE-INSTANCE@DEFINED-CLASS method calls INSTALL-CLASS-DIRECT-ACCESSORS which installs slot accessors initialize-instance@defined-class =========================================================================== Optimized class-xxx accessors. These are possible thanks to the :fixed-slot-locations class option. (initialize-extended-method-check #'class-name) Broken MOP. Any use of this method is a bug. Broken MOP. Any use of this method is a bug. Broken MOP. Any use of this method is a bug. When the valid-initargs-from-slots change, the result of (valid-initarg-keywords class ...) changes, therefore we need to invalidate all the caches that use valid-initarg-keywords: The allocation of the prototype doesn't need to flag the a redefinition with nonexistent or non-finalized superclasses to succeed despite of the prototype. =========================================================================== =========================================================================== =========================================================================== Class definition customization This makes no sense: If the superclass is a funcallable-standard-class, it is a subclass of FUNCTION, therefore class will become a subclass of FUNCTION too, but there their brain here? Needed for clos-genfun1.lisp: =========================================================================== ===========================================================================
Common Lisp Object System for CLISP Class Part n-1 : Generic functions specified in the MOP . 2004 - 05 - 25 2005 - 2008 , 2017 (in-package "CLOS") install . See MOP p. 60 . (defmethod initialize-instance ((class defined-class) &rest args) (declare (ignore args)) (install-class-direct-accessors class) class) (defmethod initialize-instance ((class structure-class) &rest args &key ((defclass-form defclass-form)) &allow-other-keys) immediately overwritten by the accessors defined by DEFSTRUCT (apply #'shared-initialize class 't args) class) (setf (fdefinition 'initialize-instance-<built-in-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<built-in-class>) #'make-instance) (setf (fdefinition 'initialize-instance-<structure-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<structure-class>) #'make-instance) (setf (fdefinition 'initialize-instance-<standard-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<standard-class>) #'make-instance) (setf (fdefinition 'initialize-instance-<funcallable-standard-class>) #'initialize-instance) (setf (fdefinition 'make-instance-<funcallable-standard-class>) #'make-instance) (defun check-class-initialized (class level) (unless (>= (class-initialized class) level) (error (TEXT "The class ~S has not yet been initialized.") class))) (defun check-class-finalized (class level) (check-class-initialized class 2) (unless (>= (class-initialized class) level) (error (TEXT "The class ~S has not yet been finalized.") class))) Not in MOP . (defun class-classname (class) (accessor-typecheck class 'potential-class 'class-classname) (sys::%record-ref class *<potential-class>-classname-location*)) (defun (setf class-classname) (new-value class) (accessor-typecheck class 'potential-class '(setf class-classname)) (setf (sys::%record-ref class *<potential-class>-classname-location*) new-value)) MOP p. 76 (defgeneric class-name (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (check-class-initialized class 1) (class-classname class)) (:method ((class forward-reference-to-class)) (slot-value class '$classname))) No extended method check because this GF is specified in ANSI CL . MOP p. 92 (defgeneric (setf class-name) (new-value class) (declare (dynamically-modifiable)) (:method (new-value (class potential-class)) (unless (symbolp new-value) (error-of-type 'type-error :datum new-value :expected-type 'symbol (TEXT "~S: The name of a class must be a symbol, not ~S") '(setf class-name) new-value)) (when (built-in-class-p class) (error-of-type 'error (TEXT "~S: The name of the built-in class ~S cannot be modified") '(setf class-name) class)) (reinitialize-instance class :name new-value) new-value)) (initialize-extended-method-check #'(setf class-name)) Not in MOP . (defun class-direct-subclasses-table (class) (accessor-typecheck class 'super-class 'class-direct-subclasses-table) (if (potential-class-p class) (sys::%record-ref class *<potential-class>-direct-subclasses-location*) (slot-value class '$direct-subclasses))) (defun (setf class-direct-subclasses-table) (new-value class) (accessor-typecheck class 'super-class '(setf class-direct-subclasses-table)) (if (potential-class-p class) (setf (sys::%record-ref class *<potential-class>-direct-subclasses-location*) new-value) (setf (slot-value class '$direct-subclasses) new-value))) MOP p. 76 (defgeneric class-direct-subclasses (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (check-class-initialized class 2) (list-direct-subclasses class)) (:method ((class forward-reference-to-class)) (list-direct-subclasses class))) (defun class-not-yet-defined (method class) (clos-warning (TEXT "~S being called on ~S, but class ~S is not yet defined.") method class (class-name class))) MOP p. 76 (defgeneric class-direct-superclasses (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (check-class-initialized class 2) (sys::%record-ref class *<defined-class>-direct-superclasses-location*)) (:method ((class forward-reference-to-class)) (class-not-yet-defined 'class-direct-superclasses class) '())) (initialize-extended-method-check #'class-direct-superclasses) Not in MOP . (defun (setf class-direct-superclasses) (new-value class) (accessor-typecheck class 'defined-class '(setf class-direct-superclasses)) (setf (sys::%record-ref class *<defined-class>-direct-superclasses-location*) new-value)) Not in MOP . (defun class-all-superclasses (class) (accessor-typecheck class 'defined-class 'class-all-superclasses) (sys::%record-ref class *<defined-class>-all-superclasses-location*)) (defun (setf class-all-superclasses) (new-value class) (accessor-typecheck class 'defined-class '(setf class-all-superclasses)) (setf (sys::%record-ref class *<defined-class>-all-superclasses-location*) new-value)) MOP p. 76 (defgeneric class-precedence-list (class) (:method ((class defined-class)) (check-class-finalized class 3) (sys::%record-ref class *<defined-class>-precedence-list-location*))) (initialize-extended-method-check #'class-precedence-list) Not in MOP . (defun (setf class-precedence-list) (new-value class) (accessor-typecheck class 'defined-class '(setf class-precedence-list)) (setf (sys::%record-ref class *<defined-class>-precedence-list-location*) new-value)) MOP p. 75 (defgeneric class-direct-slots (class) (:method ((class defined-class)) (check-class-initialized class 2) (sys::%record-ref class *<defined-class>-direct-slots-location*)) (:method ((class forward-reference-to-class)) (class-not-yet-defined 'class-direct-slots class) '())) (initialize-extended-method-check #'class-direct-slots) Not in MOP . (defun (setf class-direct-slots) (new-value class) (accessor-typecheck class 'defined-class '(setf class-direct-slots)) (setf (sys::%record-ref class *<defined-class>-direct-slots-location*) new-value)) MOP p. 77 (defgeneric class-slots (class) (:method ((class defined-class)) (check-class-finalized class 5) (sys::%record-ref class *<defined-class>-slots-location*))) (initialize-extended-method-check #'class-slots) Not in MOP . (defun (setf class-slots) (new-value class) (accessor-typecheck class 'defined-class '(setf class-slots)) (setf (sys::%record-ref class *<defined-class>-slots-location*) new-value)) Not in MOP . (defun class-slot-location-table (class) (accessor-typecheck class 'defined-class 'class-slot-location-table) (sys::%record-ref class *<defined-class>-slot-location-table-location*)) (defun (setf class-slot-location-table) (new-value class) (accessor-typecheck class 'defined-class '(setf class-slot-location-table)) (setf (sys::%record-ref class *<defined-class>-slot-location-table-location*) new-value)) MOP p. 75 (defgeneric class-direct-default-initargs (class) (:method ((class defined-class)) (check-class-initialized class 2) (sys::%record-ref class *<defined-class>-direct-default-initargs-location*)) (:method ((class forward-reference-to-class)) (class-not-yet-defined 'class-direct-default-initargs class) '())) (initialize-extended-method-check #'class-direct-default-initargs) Not in MOP . (defun (setf class-direct-default-initargs) (new-value class) (accessor-typecheck class 'defined-class '(setf class-direct-default-initargs)) (setf (sys::%record-ref class *<defined-class>-direct-default-initargs-location*) new-value)) MOP p. 75 (defgeneric class-default-initargs (class) (:method ((class defined-class)) (check-class-finalized class 6) (sys::%record-ref class *<defined-class>-default-initargs-location*))) (initialize-extended-method-check #'class-default-initargs) Not in MOP . (defun (setf class-default-initargs) (new-value class) (accessor-typecheck class 'defined-class '(setf class-default-initargs)) (setf (sys::%record-ref class *<defined-class>-default-initargs-location*) new-value)) Not in MOP . (defun class-documentation (class) (accessor-typecheck class 'defined-class 'class-documentation) (sys::%record-ref class *<defined-class>-documentation-location*)) (defun (setf class-documentation) (new-value class) (accessor-typecheck class 'defined-class '(setf class-documentation)) (setf (sys::%record-ref class *<defined-class>-documentation-location*) new-value)) Not in MOP . (defun class-listeners (class) (accessor-typecheck class 'defined-class 'class-listeners) (sys::%record-ref class *<defined-class>-listeners-location*)) (defun (setf class-listeners) (new-value class) (accessor-typecheck class 'defined-class '(setf class-listeners)) (setf (sys::%record-ref class *<defined-class>-listeners-location*) new-value)) Not in MOP . (defun class-initialized (class) (accessor-typecheck class 'defined-class 'class-initialized) (sys::%record-ref class *<defined-class>-initialized-location*)) (defun (setf class-initialized) (new-value class) (accessor-typecheck class 'defined-class '(setf class-initialized)) (setf (sys::%record-ref class *<defined-class>-initialized-location*) new-value)) Not in MOP . (defun class-subclass-of-stablehash-p (class) (accessor-typecheck class 'slotted-class 'class-subclass-of-stablehash-p) (sys::%record-ref class *<slotted-class>-subclass-of-stablehash-p-location*)) (defun (setf class-subclass-of-stablehash-p) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-subclass-of-stablehash-p)) (setf (sys::%record-ref class *<slotted-class>-subclass-of-stablehash-p-location*) new-value)) Not in MOP . (defun class-generic-accessors (class) (accessor-typecheck class 'slotted-class 'class-generic-accessors) (sys::%record-ref class *<slotted-class>-generic-accessors-location*)) (defun (setf class-generic-accessors) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-generic-accessors)) (setf (sys::%record-ref class *<slotted-class>-generic-accessors-location*) new-value)) Not in MOP . (defun class-direct-accessors (class) (accessor-typecheck class 'slotted-class 'class-direct-accessors) (sys::%record-ref class *<slotted-class>-direct-accessors-location*)) (defun (setf class-direct-accessors) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-direct-accessors)) (setf (sys::%record-ref class *<slotted-class>-direct-accessors-location*) new-value)) Not in MOP . (defun class-valid-initargs-from-slots (class) (accessor-typecheck class 'slotted-class 'class-valid-initargs-from-slots) (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*)) (defun (setf class-valid-initargs-from-slots) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-valid-initargs-from-slots)) (when (or (eq (sys::%unbound) (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*)) (set-exclusive-or (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*) new-value)) (remhash class *make-instance-table*) (remhash class *reinitialize-instance-table*) (remhash class *update-instance-for-redefined-class-table*) (remhash class *update-instance-for-different-class-table*)) (setf (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*) new-value)) Not in MOP . (defun class-instance-size (class) (accessor-typecheck class 'slotted-class 'class-instance-size) (sys::%record-ref class *<slotted-class>-instance-size-location*)) (defun (setf class-instance-size) (new-value class) (accessor-typecheck class 'slotted-class '(setf class-instance-size)) (setf (sys::%record-ref class *<slotted-class>-instance-size-location*) new-value)) Not in MOP . (defun class-names (class) (accessor-typecheck class 'structure-class 'class-names) (sys::%record-ref class *<structure-class>-names-location*)) (defun (setf class-names) (new-value class) (accessor-typecheck class 'structure-class '(setf class-names)) (setf (sys::%record-ref class *<structure-class>-names-location*) new-value)) Not in MOP . (defun class-kconstructor (class) (accessor-typecheck class 'structure-class 'class-kconstructor) (sys::%record-ref class *<structure-class>-kconstructor-location*)) (defun (setf class-kconstructor) (new-value class) (accessor-typecheck class 'structure-class '(setf class-kconstructor)) (setf (sys::%record-ref class *<structure-class>-kconstructor-location*) new-value)) Not in MOP . (defun class-boa-constructors (class) (accessor-typecheck class 'structure-class 'class-boa-constructors) (sys::%record-ref class *<structure-class>-boa-constructors-location*)) (defun (setf class-boa-constructors) (new-value class) (accessor-typecheck class 'structure-class '(setf class-boa-constructors)) (setf (sys::%record-ref class *<structure-class>-boa-constructors-location*) new-value)) Not in MOP . (defun class-copier (class) (accessor-typecheck class 'structure-class 'class-copier) (sys::%record-ref class *<structure-class>-copier-location*)) (defun (setf class-copier) (new-value class) (accessor-typecheck class 'structure-class '(setf class-copier)) (setf (sys::%record-ref class *<structure-class>-copier-location*) new-value)) Not in MOP . (defun class-predicate (class) (accessor-typecheck class 'structure-class 'class-predicate) (sys::%record-ref class *<structure-class>-predicate-location*)) (defun (setf class-predicate) (new-value class) (accessor-typecheck class 'structure-class '(setf class-predicate)) (setf (sys::%record-ref class *<structure-class>-predicate-location*) new-value)) Not in MOP . (defun class-current-version (class) (accessor-typecheck class 'semi-standard-class 'class-current-version) (sys::%record-ref class *<semi-standard-class>-current-version-location*)) (defun (setf class-current-version) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-current-version)) (setf (sys::%record-ref class *<semi-standard-class>-current-version-location*) new-value)) Not in MOP . (defun class-funcallablep (class) (accessor-typecheck class 'semi-standard-class 'class-funcallablep) (sys::%record-ref class *<semi-standard-class>-funcallablep-location*)) (defun (setf class-funcallablep) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-funcallablep)) (setf (sys::%record-ref class *<semi-standard-class>-funcallablep-location*) new-value)) Not in MOP . (defun class-fixed-slot-locations (class) (accessor-typecheck class 'semi-standard-class 'class-fixed-slot-locations) (sys::%record-ref class *<semi-standard-class>-fixed-slot-locations-location*)) (defun (setf class-fixed-slot-locations) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-fixed-slot-locations)) (setf (sys::%record-ref class *<semi-standard-class>-fixed-slot-locations-location*) new-value)) Not in MOP . (defun class-instantiated (class) (accessor-typecheck class 'semi-standard-class 'class-instantiated) (sys::%record-ref class *<semi-standard-class>-instantiated-location*)) (defun (setf class-instantiated) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-instantiated)) (setf (sys::%record-ref class *<semi-standard-class>-instantiated-location*) new-value)) Not in MOP . (defun class-direct-instance-specializers-table (class) (accessor-typecheck class 'semi-standard-class 'class-direct-instance-specializers-table) (sys::%record-ref class *<semi-standard-class>-direct-instance-specializers-location*)) (defun (setf class-direct-instance-specializers-table) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-direct-instance-specializers-table)) (setf (sys::%record-ref class *<semi-standard-class>-direct-instance-specializers-location*) new-value)) Not in MOP . (defun class-finalized-direct-subclasses-table (class) (accessor-typecheck class 'semi-standard-class 'class-finalized-direct-subclasses-table) (sys::%record-ref class *<semi-standard-class>-finalized-direct-subclasses-location*)) (defun (setf class-finalized-direct-subclasses-table) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-finalized-direct-subclasses-table)) (setf (sys::%record-ref class *<semi-standard-class>-finalized-direct-subclasses-location*) new-value)) MOP p. 77 (defgeneric class-prototype (class) (:method ((class semi-standard-class)) (check-class-finalized class 6) (or (sys::%record-ref class *<semi-standard-class>-prototype-location*) (setf (sys::%record-ref class *<semi-standard-class>-prototype-location*) (let ((old-instantiated (class-instantiated class))) (prog1 (clos::%allocate-instance class) class as being instantiated , because 1 . the prototype is thrown away when the class is redefined , 2 . we do n't want (setf (class-instantiated class) old-instantiated)))))) (:method ((class built-in-class)) (let ((prototype (sys::%record-ref class *<built-in-class>-prototype-location*))) (if (eq (sys::%unbound) prototype) (error (TEXT "~S: ~S is an abstract class and therefore does not have a direct instance") 'class-prototype class) prototype))) CLISP extension : (:method ((class structure-class)) (or (sys::%record-ref class *<structure-class>-prototype-location*) (setf (sys::%record-ref class *<structure-class>-prototype-location*) (clos::%allocate-instance class))))) (initialize-extended-method-check #'class-prototype) Not in MOP . (defun (setf class-prototype) (new-value class) (accessor-typecheck class 'semi-standard-class '(setf class-prototype)) (setf (sys::%record-ref class *<semi-standard-class>-prototype-location*) new-value)) Class Specification Protocol Not in MOP . (defgeneric compute-direct-slot-definition-initargs (class &rest slot-spec) (declare (dynamically-modifiable)) (:method ((class defined-class) &rest slot-spec) slot-spec)) Class Finalization Protocol MOP p. 76 (defgeneric class-finalized-p (class) (:method ((class defined-class)) (= (class-initialized class) 6)) (:method ((class forward-reference-to-class)) nil) CLISP extension : Convenience method on symbols . (:method ((name symbol)) (class-finalized-p (find-class name)))) (initialize-extended-method-check #'class-finalized-p) MOP p. 54 (defgeneric finalize-inheritance (class) (:method ((class semi-standard-class)) (finalize-inheritance-<semi-standard-class> class)) CLISP extension : No - op method on other classes . (:method ((class defined-class)) class) CLISP extension : Convenience method on symbols . (:method ((name symbol)) (finalize-inheritance (find-class name)))) (initialize-extended-method-check #'finalize-inheritance) MOP p. 38 (defgeneric compute-class-precedence-list (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (compute-class-precedence-list-<defined-class> class))) Not in MOP . (defgeneric compute-effective-slot-definition-initargs (class direct-slot-definitions) (declare (dynamically-modifiable)) (:method ((class defined-class) direct-slot-definitions) (compute-effective-slot-definition-initargs-<defined-class> class direct-slot-definitions))) MOP p. 42 (defgeneric compute-effective-slot-definition (class slotname direct-slot-definitions) (declare (dynamically-modifiable)) (:method ((class defined-class) slotname direct-slot-definitions) (compute-effective-slot-definition-<defined-class> class slotname direct-slot-definitions))) MOP p. 43 (defgeneric compute-slots (class) (declare (dynamically-modifiable)) (:method ((class semi-standard-class)) (compute-slots-<defined-class>-primary class)) (:method :around ((class semi-standard-class)) (compute-slots-<slotted-class>-around class #'(lambda (c) (call-next-method c))))) MOP p. 39 (defgeneric compute-default-initargs (class) (declare (dynamically-modifiable)) (:method ((class defined-class)) (compute-default-initargs-<defined-class> class))) MOP p. 47 (defgeneric ensure-class-using-class (class name &key metaclass direct-superclasses direct-slots direct-default-initargs documentation CLISP specific extension : fixed-slot-locations &allow-other-keys) (declare (dynamically-modifiable)) (:method ((class potential-class) name &rest args) (apply #'ensure-class-using-class-<t> class name args)) (:method ((class null) name &rest args) (apply #'ensure-class-using-class-<t> class name args))) MOP p. 102 (defgeneric validate-superclass (class superclass) (declare (dynamically-modifiable)) (:method ((class potential-class) (superclass potential-class)) (or (eq superclass <t>) (eq (class-of class) (class-of superclass)) (and (eq (class-of class) <funcallable-standard-class>) (eq (class-of superclass) <standard-class>)) is no way to FUNCALL or APPLY it . Where did the MOP authors have (and (eq (class-of class) <standard-class>) (eq (class-of superclass) <funcallable-standard-class>)) (and (eq superclass <function>) (eq (class-classname class) 'funcallable-standard-object)) CLISP specific extension : (subclassp (class-of class) (class-of superclass))))) Subclass relationship change notification MOP p. 32 (defgeneric add-direct-subclass (class subclass) (declare (dynamically-modifiable)) (:method ((class super-class) (subclass potential-class)) (add-direct-subclass-internal class subclass))) MOP p. 90 (defgeneric remove-direct-subclass (class subclass) (declare (dynamically-modifiable)) (:method ((class super-class) (subclass potential-class)) (remove-direct-subclass-internal class subclass))) Accessor definition customization MOP p. 86 (defgeneric reader-method-class (class direct-slot &rest initargs) (declare (dynamically-modifiable)) (:method ((class defined-class) direct-slot &rest initargs) (declare (ignore direct-slot initargs)) <standard-reader-method>)) MOP p. 103 (defgeneric writer-method-class (class direct-slot &rest initargs) (declare (dynamically-modifiable)) (:method ((class defined-class) direct-slot &rest initargs) (declare (ignore direct-slot initargs)) <standard-writer-method>))
58a562baba90a82d07fd0014b8e6b978be9a9fe28312a192cef1a39ccd04ab0d
KarlHegbloom/zotero-texmacs-integration
builder.scm
coding : utf-8 ;;; ¶ ;;; (tm-zotero json builder) --- Guile JSON implementation. Copyright ( C ) 2013 Flaque < > ;; ;; This file is part of guile-json. ;; ;; guile-json is free software; you can redistribute it and/or ;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;; ;; guile-json is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Lesser General Public License for more details. ;; You should have received a copy of the GNU Lesser General Public ;; License along with guile-json; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA ;;; Commentary: JSON module for ;;; Code: (define-module (tm-zotero json builder) #:use-module (ice-9 format) #:use-module (ice-9 optargs) #:use-module (srfi srfi-1) # : use - module ( ) #:use-module (srfi srfi-4) #:export (scm->json scm->json-string)) (define bytevector-u8-ref u8vector-ref) (define bytevector-length u8vector-length) ;; ;; String builder helpers ;; (define (unicode->string unicode) (format #f "\\u~4,'0x" unicode)) (define (char->unicode-string c) (let ((unicode (char->integer c))) (if (< unicode 32) (unicode->string unicode) (string c)))) (define (u8v-2->unicode bv) (let ((bv0 (bytevector-u8-ref bv 0)) (bv1 (bytevector-u8-ref bv 1))) (+ (ash (logand bv0 #b00011111) 6) (logand bv1 #b00111111)))) (define (u8v-3->unicode bv) (let ((bv0 (bytevector-u8-ref bv 0)) (bv1 (bytevector-u8-ref bv 1)) (bv2 (bytevector-u8-ref bv 2))) (+ (ash (logand bv0 #b00001111) 12) (ash (logand bv1 #b00111111) 6) (logand bv2 #b00111111)))) (define (build-char-string c) ( bv ( ( string c ) ) ) (bv (list->u8vector (list (char->integer c)))) (len (bytevector-length bv))) (cond A single byte UTF-8 ((eq? len 1) (char->unicode-string c)) If we have a 2 or 3 byte UTF-8 we need to output it as \uHHHH ((or (eq? len 2) (eq? len 3)) (let ((unicode (if (eq? len 2) (u8v-2->unicode bv) (u8v-3->unicode bv)))) (unicode->string unicode))) ;; Anything else should wrong, hopefully. (else (throw 'json-invalid))))) ;; ;; Object builder functions ;; (define (build-object-pair p port escape pretty level) (display (indent-string pretty level) port) (json-build-string (car p) port escape) (display " : " port) (json-build (cdr p) port escape pretty level)) (define (build-newline port pretty) (cond (pretty (newline port)))) (define (indent-string pretty level) (if pretty (format #f "~v_" (* 4 level)) "")) ;; ;; Main builder functions ;; (define (json-build-null port) (display "null" port)) (define (json-build-boolean scm port) (display (if scm "true" "false") port)) (define (json-build-number scm port) (if (and (rational? scm) (not (integer? scm))) (display (number->string (exact->inexact scm)) port) (display (number->string scm) port))) (define (json-build-string scm port escape) (display "\"" port) (display (list->string (fold-right append '() (map (lambda (c) (case c ((#\" #\\) `(#\\ ,c)) ((#\010) '(#\\ #\b)) ((#\014) '(#\\ #\f)) ((#\012) '(#\\ #\n)) ((#\015) '(#\\ #\r)) ((#\011) '(#\\ #\t)) ( ( # \bs ) ' ( # \\ # \b ) ) ;; ((#\ff) '(#\\ #\f)) ;; ((#\lf) '(#\\ #\n)) ( ( # \cr ) ' ( # \\ # \r ) ) ;; ((#\ht) '(#\\ #\t)) ((#\/) (if escape `(#\\ ,c) (list c))) (else (string->list (build-char-string c))))) (string->list scm)))) port) (display "\"" port)) (define (json-build-array scm port escape pretty level) (display "[" port) (if (not (null? scm)) (begin (json-build (car scm) port escape pretty (+ level 1)) (for-each (lambda (v) (display ", " port) (json-build v port escape pretty (+ level 1))) (cdr scm)))) (display "]" port)) (define (json-build-object scm port escape pretty level) (build-newline port pretty) (simple-format port "~A{" (indent-string pretty level)) (build-newline port pretty) (let ((pairs (hash-map->list cons scm))) (if (not (null? pairs)) (begin (build-object-pair (car pairs) port escape pretty (+ level 1)) (for-each (lambda (p) (display "," port) (build-newline port pretty) (build-object-pair p port escape pretty (+ level 1))) (cdr pairs))))) (build-newline port pretty) (simple-format port "~A}" (indent-string pretty level))) (define (json-build scm port escape pretty level) (cond ;;((eq? scm #nil) (json-build-null port)) ((eq? scm '()) (json-build-null port)) ((boolean? scm) (json-build-boolean scm port)) ((number? scm) (json-build-number scm port)) ((string? scm) (json-build-string scm port escape)) ((list? scm) (json-build-array scm port escape pretty level)) ((hash-table? scm) (json-build-object scm port escape pretty level)) (else (throw 'json-invalid)))) ;; ;; Public procedures ;; (define* (scm->json scm #:optional (port (current-output-port)) #:key (escape #f) (pretty #f)) "Creates a JSON document from native. The argument @var{scm} contains the native value of the JSON document. Takes one optional argument, @var{port}, which defaults to the current output port where the JSON document will be written." (json-build scm port escape pretty 0)) (define* (scm->json-string scm #:key (escape #f) (pretty #f)) "Creates a JSON document from native into a string. The argument @var{scm} contains the native value of the JSON document." (call-with-output-string (lambda (p) (scm->json scm p #:escape escape #:pretty pretty)))) ( ) ends here
null
https://raw.githubusercontent.com/KarlHegbloom/zotero-texmacs-integration/39e5db5b22fefc3672b9e5c22b3035b500ffe5b5/progs/tm-zotero/json/builder.scm
scheme
¶ (tm-zotero json builder) --- Guile JSON implementation. This file is part of guile-json. guile-json is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either guile-json is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with guile-json; if not, write to the Free Software Commentary: Code: String builder helpers Anything else should wrong, hopefully. Object builder functions Main builder functions ((#\ff) '(#\\ #\f)) ((#\lf) '(#\\ #\n)) ((#\ht) '(#\\ #\t)) ((eq? scm #nil) (json-build-null port)) Public procedures
coding : utf-8 Copyright ( C ) 2013 Flaque < > version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 USA JSON module for (define-module (tm-zotero json builder) #:use-module (ice-9 format) #:use-module (ice-9 optargs) #:use-module (srfi srfi-1) # : use - module ( ) #:use-module (srfi srfi-4) #:export (scm->json scm->json-string)) (define bytevector-u8-ref u8vector-ref) (define bytevector-length u8vector-length) (define (unicode->string unicode) (format #f "\\u~4,'0x" unicode)) (define (char->unicode-string c) (let ((unicode (char->integer c))) (if (< unicode 32) (unicode->string unicode) (string c)))) (define (u8v-2->unicode bv) (let ((bv0 (bytevector-u8-ref bv 0)) (bv1 (bytevector-u8-ref bv 1))) (+ (ash (logand bv0 #b00011111) 6) (logand bv1 #b00111111)))) (define (u8v-3->unicode bv) (let ((bv0 (bytevector-u8-ref bv 0)) (bv1 (bytevector-u8-ref bv 1)) (bv2 (bytevector-u8-ref bv 2))) (+ (ash (logand bv0 #b00001111) 12) (ash (logand bv1 #b00111111) 6) (logand bv2 #b00111111)))) (define (build-char-string c) ( bv ( ( string c ) ) ) (bv (list->u8vector (list (char->integer c)))) (len (bytevector-length bv))) (cond A single byte UTF-8 ((eq? len 1) (char->unicode-string c)) If we have a 2 or 3 byte UTF-8 we need to output it as \uHHHH ((or (eq? len 2) (eq? len 3)) (let ((unicode (if (eq? len 2) (u8v-2->unicode bv) (u8v-3->unicode bv)))) (unicode->string unicode))) (else (throw 'json-invalid))))) (define (build-object-pair p port escape pretty level) (display (indent-string pretty level) port) (json-build-string (car p) port escape) (display " : " port) (json-build (cdr p) port escape pretty level)) (define (build-newline port pretty) (cond (pretty (newline port)))) (define (indent-string pretty level) (if pretty (format #f "~v_" (* 4 level)) "")) (define (json-build-null port) (display "null" port)) (define (json-build-boolean scm port) (display (if scm "true" "false") port)) (define (json-build-number scm port) (if (and (rational? scm) (not (integer? scm))) (display (number->string (exact->inexact scm)) port) (display (number->string scm) port))) (define (json-build-string scm port escape) (display "\"" port) (display (list->string (fold-right append '() (map (lambda (c) (case c ((#\" #\\) `(#\\ ,c)) ((#\010) '(#\\ #\b)) ((#\014) '(#\\ #\f)) ((#\012) '(#\\ #\n)) ((#\015) '(#\\ #\r)) ((#\011) '(#\\ #\t)) ( ( # \bs ) ' ( # \\ # \b ) ) ( ( # \cr ) ' ( # \\ # \r ) ) ((#\/) (if escape `(#\\ ,c) (list c))) (else (string->list (build-char-string c))))) (string->list scm)))) port) (display "\"" port)) (define (json-build-array scm port escape pretty level) (display "[" port) (if (not (null? scm)) (begin (json-build (car scm) port escape pretty (+ level 1)) (for-each (lambda (v) (display ", " port) (json-build v port escape pretty (+ level 1))) (cdr scm)))) (display "]" port)) (define (json-build-object scm port escape pretty level) (build-newline port pretty) (simple-format port "~A{" (indent-string pretty level)) (build-newline port pretty) (let ((pairs (hash-map->list cons scm))) (if (not (null? pairs)) (begin (build-object-pair (car pairs) port escape pretty (+ level 1)) (for-each (lambda (p) (display "," port) (build-newline port pretty) (build-object-pair p port escape pretty (+ level 1))) (cdr pairs))))) (build-newline port pretty) (simple-format port "~A}" (indent-string pretty level))) (define (json-build scm port escape pretty level) (cond ((eq? scm '()) (json-build-null port)) ((boolean? scm) (json-build-boolean scm port)) ((number? scm) (json-build-number scm port)) ((string? scm) (json-build-string scm port escape)) ((list? scm) (json-build-array scm port escape pretty level)) ((hash-table? scm) (json-build-object scm port escape pretty level)) (else (throw 'json-invalid)))) (define* (scm->json scm #:optional (port (current-output-port)) #:key (escape #f) (pretty #f)) "Creates a JSON document from native. The argument @var{scm} contains the native value of the JSON document. Takes one optional argument, @var{port}, which defaults to the current output port where the JSON document will be written." (json-build scm port escape pretty 0)) (define* (scm->json-string scm #:key (escape #f) (pretty #f)) "Creates a JSON document from native into a string. The argument @var{scm} contains the native value of the JSON document." (call-with-output-string (lambda (p) (scm->json scm p #:escape escape #:pretty pretty)))) ( ) ends here
dd10a47e2655cc006418fabf7b553553e7abbff5dc4ada8ea2f1c786165a40a4
thheller/shadow-cljs
resolve_check.cljs
(ns shadow.resolve-check (:require ["enhanced-resolve" :as er] ["path" :as path] ["fs" :as fs] [cljs.reader :as reader] [cljs.pprint :refer (pprint)])) (defn fail! [test err file] (prn [:fail! test file]) (js/console.log err) (js/process.exit 1)) (-> (.process processor "* org-mode example\n your text goes here") (.then (fn [^js file] (js/console.log (.-result file))))) (defn main [& args] (let [test-dir (path/resolve ".." ".." "test-env") tests (-> (fs/readFileSync "tests.edn") (.toString) (reader/read-string)) cache-fs (er/CachedInputFileSystem. fs 4000)] (doseq [{:keys [from request expected extensions js-package-dirs entry-keys use-browser-overrides] :as test} tests] (let [resolver (er/create.sync #js {:fileSystem cache-fs :aliasFields (if-not (false? use-browser-overrides) #js ["browser"] #js []) :mainFields (clj->js (or entry-keys ["browser" "main" "module"])) :modules (clj->js (or js-package-dirs ["node_modules"])) :extensions (clj->js (or extensions [".js" ".json"]))}) expected (if (string? expected) (path/resolve test-dir expected) expected) from (if from could use resolveToContext , need the dir not the file (let [from-file (resolver #js {} test-dir from #js {})] (path/dirname from-file)) test-dir) file (try (resolver #js {} from request #js {}) (catch :default err (if (:fail-expected test) expected (fail! test err nil))))] (if (not= file expected) (fail! test :expected file) (prn [:OK test]) )))) (println "ALL OK."))
null
https://raw.githubusercontent.com/thheller/shadow-cljs/c89949557e1006df36d9ed2dbd4d479fbf19a580/src/dev/shadow/resolve_check.cljs
clojure
(ns shadow.resolve-check (:require ["enhanced-resolve" :as er] ["path" :as path] ["fs" :as fs] [cljs.reader :as reader] [cljs.pprint :refer (pprint)])) (defn fail! [test err file] (prn [:fail! test file]) (js/console.log err) (js/process.exit 1)) (-> (.process processor "* org-mode example\n your text goes here") (.then (fn [^js file] (js/console.log (.-result file))))) (defn main [& args] (let [test-dir (path/resolve ".." ".." "test-env") tests (-> (fs/readFileSync "tests.edn") (.toString) (reader/read-string)) cache-fs (er/CachedInputFileSystem. fs 4000)] (doseq [{:keys [from request expected extensions js-package-dirs entry-keys use-browser-overrides] :as test} tests] (let [resolver (er/create.sync #js {:fileSystem cache-fs :aliasFields (if-not (false? use-browser-overrides) #js ["browser"] #js []) :mainFields (clj->js (or entry-keys ["browser" "main" "module"])) :modules (clj->js (or js-package-dirs ["node_modules"])) :extensions (clj->js (or extensions [".js" ".json"]))}) expected (if (string? expected) (path/resolve test-dir expected) expected) from (if from could use resolveToContext , need the dir not the file (let [from-file (resolver #js {} test-dir from #js {})] (path/dirname from-file)) test-dir) file (try (resolver #js {} from request #js {}) (catch :default err (if (:fail-expected test) expected (fail! test err nil))))] (if (not= file expected) (fail! test :expected file) (prn [:OK test]) )))) (println "ALL OK."))
12a3facb5dbccd8023ce1dfa094abcb6e619f9cb65834385526566a29dfb0b48
OlivierSohn/hamazed
Sums.hs
# LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} module Test.Imj.Sums ( testSums ) where import Imj.Prelude import Control.Exception (evaluate) import Data.List(foldl', length, replicate) import qualified Data.Set as Set import qualified Data.IntSet as ISet import Data.Text(pack) import System.IO(putStr, putStrLn) import Imj.Data.Class.Quantifiable import qualified Imj.Data.Tree as Filt(Filterable(..)) import Imj.Graphics.Color import Imj.Graphics.Text.ColorString hiding(putStrLn, putStr) import qualified Imj.Graphics.Text.ColorString as CS(putStr) import Imj.Sums import Imj.Timing testSums :: IO () testSums = do testAsOccurences mkSums Set.empty 0 `shouldBe` Set.singleton Set.empty mkSums (Set.fromList [1,2,3,4,5]) 3 `shouldBe` Set.fromList (map Set.fromList [[3],[2,1]]) mkSums (Set.fromList [2,3,4,5]) 18 `shouldBe` Set.empty mkSums (Set.fromList [2,3,4,5]) 1 `shouldBe` Set.empty let maxHamazedNumbers = [1..15] maxSum = sum maxHamazedNumbers `quot` 2 mkSumsArray Set.empty 0 `shouldBe` Set.singleton Set.empty mkSumsArray (Set.fromList [1,2,3,4,5]) 3 `shouldBe` Set.fromList (map Set.fromList [[3],[2,1]]) mkSumsArray (Set.fromList [2,3,4,5]) 18 `shouldBe` Set.empty mkSumsArray (Set.fromList [2,3,4,5]) 1 `shouldBe` Set.empty -- verify all output lists are descending let verify x = Set.fromList (Filt.toList $ x [1,2,3,3,4,5,6,9,9] 3) `shouldBe` Set.fromList [[3],[2,1]] verify mkSumsN verify mkSumsStrictN verify mkSumsStrictN2 verify $ mkSumsStrict . ISet.fromList verify $ mkSumsStrict2 . Set.fromList verify $ mkSumsArray' . Set.fromList verify $ mkSumsArray'' . Set.fromList verify $ mkSumsLazy . Set.fromList -- Using different implementations to find the number of different combinations of length < 6 . -- The fastest way is to use a 'StrictTree' ('mkSumsStrict'). let !numbersL = maxHamazedNumbers !numbersS = Set.fromList maxHamazedNumbers !numbersIS = ISet.fromList maxHamazedNumbers measure n countCombinations = fst <$> withDuration (void $ evaluate $ force $ countCombinations numbersL numbersS numbersIS (quot (maxSum * n) n)) -- trick to force a new evaluation tests = [ (\_ aS _ b -> Set.size $ Set.filter (\s -> Set.size s < 6) $ mkSums aS b , "mkSums filter") , (\_ aS _ b -> Set.size $ Set.filter (\s -> Set.size s < 6) $ mkSumsArray aS b , "mkSumsArray filter") , (\_ aS _ b -> length $ filter (\s -> length s < 6) $ mkSumsArray' aS b , "mkSumsArray' filter") , (\_ aS _ b -> Set.size $ Set.filter (\s -> length s < 6) $ mkSumsArray'' aS b , "mkSumsArray'' filter") , (\_ _ aIS b -> Filt.countValues $ Filt.filter (\s -> length s < 6) $ mkSumsStrict aIS b , "mkSumsStrict filter") , (\_ aS _ b -> Filt.countValues $ Filt.filter (\s -> length s < 6) $ mkSumsLazy aS b , "mkSumsLazy filter") , (\_ aS _ b -> Set.size $ mkSums aS b , "mkSums") , (\_ aS _ b -> Set.size $ mkSumsArray aS b , "mkSumsArray") , (\_ aS _ b -> Filt.countValues $ mkSumsArray' aS b , "mkSumsArray'") , (\_ aS _ b -> Set.size $ mkSumsArray'' aS b , "mkSumsArray''") , (\_ aS _ b -> Filt.countValues $ mkSumsStrict2 aS b , "mkSumsStrict2") , (\_ _ aIS b -> Filt.countValues $ mkSumsStrict aIS b , "mkSumsStrict") , (\_ aS _ b -> Filt.countValues $ mkSumsLazy aS b , "mkSumsLazy") , (\aL _ _ b -> Filt.countValues $ Filt.filter (\s -> length s < 6) $ mkSumsStrictN aL b, "mkSumsStrictN filter") , (\aL _ _ b -> length $ Filt.filter (\s -> length s < 6) $ mkSumsN aL b, "mkSumsN filter'") , (\aL _ _ b -> Filt.countValues $ mkSumsStrictN aL b, "mkSumsStrictN") , (\aL _ _ b -> Filt.countValues $ mkSumsStrictN2 aL b, "mkSumsStrictN2") , (\aL _ _ b -> Filt.countValues $ mkSumsN aL b, "mkSumsN") ] let nTestRepeat = 100 times <- (numbersL, numbersS, numbersIS) `deepseq` mapM (\n -> mapM (measure n . fst) tests) [1..nTestRepeat] :: IO [[Time Duration System]] printTimes $ zip (map snd tests) $ map (readFloat . (/ (fromIntegral nTestRepeat :: Float)) . writeFloat) $ foldl' (zipWith (|+|)) (repeat zeroDuration) times testAsOccurences :: IO () testAsOccurences = do asOccurences [] `shouldBe` [] asOccurences [3] `shouldBe` [ValueOccurences 1 3] asOccurences [3,3] `shouldBe` [ValueOccurences 2 3] asOccurences [3,4] `shouldBe` [ValueOccurences 1 4, ValueOccurences 1 3] -- Note : reversed asOccurences [3,3,5,5,5,6,7,7,9,10] `shouldBe` [ ValueOccurences 1 10 , ValueOccurences 1 9 , ValueOccurences 2 7 , ValueOccurences 1 6 , ValueOccurences 3 5 , ValueOccurences 2 3 ] printTimes :: [(String, Time Duration System)] -> IO () printTimes [] = putStrLn "No time" printTimes times = do putStrLn "micros|Logarithmic scale" forM_ (zip times logTimes) $ \((desc, dt), logRatio) -> do let n = countStars logRatio s = showTime dt s' = replicate (nCharsTime - length s) ' ' ++ s inColor = colored (pack $ replicate n '+') (gray 19) <> colored (pack $ replicate (nStars - n) '.') (gray 5) putStr $ s' ++ " " CS.putStr inColor putStr $ " " ++ desc ++ "\n" where nCharsTime = length $ showTime $ fromMaybe (error "logic") $ maximumMaybe $ map snd times nStars = 120 countStars x = round $ fromIntegral nStars * x logTimes = logarithmically 10 $ map snd times shouldBe :: (Show a, Eq a) => a -> a -> IO () shouldBe actual expected = if actual == expected then return () else error $ "expected\n" ++ show expected ++ " but got\n" ++ show actual
null
https://raw.githubusercontent.com/OlivierSohn/hamazed/6c2b20d839ede7b8651fb7b425cb27ea93808a4a/imj-base/test/Test/Imj/Sums.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE BangPatterns # verify all output lists are descending Using different implementations to find the number The fastest way is to use a 'StrictTree' ('mkSumsStrict'). trick to force a new evaluation Note : reversed
# LANGUAGE NoImplicitPrelude # module Test.Imj.Sums ( testSums ) where import Imj.Prelude import Control.Exception (evaluate) import Data.List(foldl', length, replicate) import qualified Data.Set as Set import qualified Data.IntSet as ISet import Data.Text(pack) import System.IO(putStr, putStrLn) import Imj.Data.Class.Quantifiable import qualified Imj.Data.Tree as Filt(Filterable(..)) import Imj.Graphics.Color import Imj.Graphics.Text.ColorString hiding(putStrLn, putStr) import qualified Imj.Graphics.Text.ColorString as CS(putStr) import Imj.Sums import Imj.Timing testSums :: IO () testSums = do testAsOccurences mkSums Set.empty 0 `shouldBe` Set.singleton Set.empty mkSums (Set.fromList [1,2,3,4,5]) 3 `shouldBe` Set.fromList (map Set.fromList [[3],[2,1]]) mkSums (Set.fromList [2,3,4,5]) 18 `shouldBe` Set.empty mkSums (Set.fromList [2,3,4,5]) 1 `shouldBe` Set.empty let maxHamazedNumbers = [1..15] maxSum = sum maxHamazedNumbers `quot` 2 mkSumsArray Set.empty 0 `shouldBe` Set.singleton Set.empty mkSumsArray (Set.fromList [1,2,3,4,5]) 3 `shouldBe` Set.fromList (map Set.fromList [[3],[2,1]]) mkSumsArray (Set.fromList [2,3,4,5]) 18 `shouldBe` Set.empty mkSumsArray (Set.fromList [2,3,4,5]) 1 `shouldBe` Set.empty let verify x = Set.fromList (Filt.toList $ x [1,2,3,3,4,5,6,9,9] 3) `shouldBe` Set.fromList [[3],[2,1]] verify mkSumsN verify mkSumsStrictN verify mkSumsStrictN2 verify $ mkSumsStrict . ISet.fromList verify $ mkSumsStrict2 . Set.fromList verify $ mkSumsArray' . Set.fromList verify $ mkSumsArray'' . Set.fromList verify $ mkSumsLazy . Set.fromList of different combinations of length < 6 . let !numbersL = maxHamazedNumbers !numbersS = Set.fromList maxHamazedNumbers !numbersIS = ISet.fromList maxHamazedNumbers measure n countCombinations = fst <$> withDuration (void $ evaluate $ force $ tests = [ (\_ aS _ b -> Set.size $ Set.filter (\s -> Set.size s < 6) $ mkSums aS b , "mkSums filter") , (\_ aS _ b -> Set.size $ Set.filter (\s -> Set.size s < 6) $ mkSumsArray aS b , "mkSumsArray filter") , (\_ aS _ b -> length $ filter (\s -> length s < 6) $ mkSumsArray' aS b , "mkSumsArray' filter") , (\_ aS _ b -> Set.size $ Set.filter (\s -> length s < 6) $ mkSumsArray'' aS b , "mkSumsArray'' filter") , (\_ _ aIS b -> Filt.countValues $ Filt.filter (\s -> length s < 6) $ mkSumsStrict aIS b , "mkSumsStrict filter") , (\_ aS _ b -> Filt.countValues $ Filt.filter (\s -> length s < 6) $ mkSumsLazy aS b , "mkSumsLazy filter") , (\_ aS _ b -> Set.size $ mkSums aS b , "mkSums") , (\_ aS _ b -> Set.size $ mkSumsArray aS b , "mkSumsArray") , (\_ aS _ b -> Filt.countValues $ mkSumsArray' aS b , "mkSumsArray'") , (\_ aS _ b -> Set.size $ mkSumsArray'' aS b , "mkSumsArray''") , (\_ aS _ b -> Filt.countValues $ mkSumsStrict2 aS b , "mkSumsStrict2") , (\_ _ aIS b -> Filt.countValues $ mkSumsStrict aIS b , "mkSumsStrict") , (\_ aS _ b -> Filt.countValues $ mkSumsLazy aS b , "mkSumsLazy") , (\aL _ _ b -> Filt.countValues $ Filt.filter (\s -> length s < 6) $ mkSumsStrictN aL b, "mkSumsStrictN filter") , (\aL _ _ b -> length $ Filt.filter (\s -> length s < 6) $ mkSumsN aL b, "mkSumsN filter'") , (\aL _ _ b -> Filt.countValues $ mkSumsStrictN aL b, "mkSumsStrictN") , (\aL _ _ b -> Filt.countValues $ mkSumsStrictN2 aL b, "mkSumsStrictN2") , (\aL _ _ b -> Filt.countValues $ mkSumsN aL b, "mkSumsN") ] let nTestRepeat = 100 times <- (numbersL, numbersS, numbersIS) `deepseq` mapM (\n -> mapM (measure n . fst) tests) [1..nTestRepeat] :: IO [[Time Duration System]] printTimes $ zip (map snd tests) $ map (readFloat . (/ (fromIntegral nTestRepeat :: Float)) . writeFloat) $ foldl' (zipWith (|+|)) (repeat zeroDuration) times testAsOccurences :: IO () testAsOccurences = do asOccurences [] `shouldBe` [] asOccurences [3] `shouldBe` [ValueOccurences 1 3] asOccurences [3,3] `shouldBe` [ValueOccurences 2 3] asOccurences [3,3,5,5,5,6,7,7,9,10] `shouldBe` [ ValueOccurences 1 10 , ValueOccurences 1 9 , ValueOccurences 2 7 , ValueOccurences 1 6 , ValueOccurences 3 5 , ValueOccurences 2 3 ] printTimes :: [(String, Time Duration System)] -> IO () printTimes [] = putStrLn "No time" printTimes times = do putStrLn "micros|Logarithmic scale" forM_ (zip times logTimes) $ \((desc, dt), logRatio) -> do let n = countStars logRatio s = showTime dt s' = replicate (nCharsTime - length s) ' ' ++ s inColor = colored (pack $ replicate n '+') (gray 19) <> colored (pack $ replicate (nStars - n) '.') (gray 5) putStr $ s' ++ " " CS.putStr inColor putStr $ " " ++ desc ++ "\n" where nCharsTime = length $ showTime $ fromMaybe (error "logic") $ maximumMaybe $ map snd times nStars = 120 countStars x = round $ fromIntegral nStars * x logTimes = logarithmically 10 $ map snd times shouldBe :: (Show a, Eq a) => a -> a -> IO () shouldBe actual expected = if actual == expected then return () else error $ "expected\n" ++ show expected ++ " but got\n" ++ show actual
7997e69438155205b38cc318c15a2c57adef37ebfb408f2ca39fab9a50c2c474
amnh/poy5
pdfcodec.mli
(** Encoding and decoding PDF streams *) * { b Currently supported :} - Decoders : ASCIIHexDecode , ASCII85Decode , FlateDecode , LZWDecode , RunLengthDecode . - Encoders : ASCIIHexDecode , ASCII85Decode , FlateDecode , RunLengthDecode . - Predictors : PNG ( all ) , TIFF ( 8 - bit only ) . {b Currently supported:} - Decoders: ASCIIHexDecode, ASCII85Decode, FlateDecode, LZWDecode, RunLengthDecode. - Encoders: ASCIIHexDecode, ASCII85Decode, FlateDecode, RunLengthDecode. - Predictors: PNG (all), TIFF (8-bit only). *) (** There was bad data. *) exception Couldn'tDecodeStream of string (** PdfCaml doesn't support this encoding or its predictor. *) exception DecodeNotSupported * Given a document and stream , decode . The pdf document is updated with the decoded stream . May return either of the exceptions above . with the decoded stream. May return either of the exceptions above. *) val decode_pdfstream : Pdf.pdfdoc -> Pdf.pdfobject -> unit * Given a document and stream decode just one stage . May return either of the exceptions above . exceptions above. *) val decode_pdfstream_onestage : Pdf.pdfdoc -> Pdf.pdfobject -> unit * Given a document and stream decode until there 's an unknown decoder . May return [ Couldn'tDecodeStream ] . return [Couldn'tDecodeStream]. *) val decode_pdfstream_until_unknown : Pdf.pdfdoc -> Pdf.pdfobject -> unit (** Supported encodings. *) type encoding = | ASCIIHex | ASCII85 | RunLength | Flate (** Encode a PDF stream with an encoding. *) val encode_pdfstream : Pdf.pdfdoc -> encoding -> Pdf.pdfobject -> unit (**/**) Given an [ Io.input ] with pointer at the first byte and an inline image stream dictionary , decode the first decoder and its predictor . Return the data , or [ None ] if this decoder is n't supported but the data pointer has been left in the right place . The exceptions above can both be raised , in the case of bad data or a completely unknown encoding . stream dictionary, decode the first decoder and its predictor. Return the data, or [None] if this decoder isn't supported but the data pointer has been left in the right place. The exceptions above can both be raised, in the case of bad data or a completely unknown encoding. *) val decode_from_input : Io.input -> Pdf.pdfobject -> Utility.bytestream option
null
https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/camlpdf-0.3/pdfcodec.mli
ocaml
* Encoding and decoding PDF streams * There was bad data. * PdfCaml doesn't support this encoding or its predictor. * Supported encodings. * Encode a PDF stream with an encoding. */*
* { b Currently supported :} - Decoders : ASCIIHexDecode , ASCII85Decode , FlateDecode , LZWDecode , RunLengthDecode . - Encoders : ASCIIHexDecode , ASCII85Decode , FlateDecode , RunLengthDecode . - Predictors : PNG ( all ) , TIFF ( 8 - bit only ) . {b Currently supported:} - Decoders: ASCIIHexDecode, ASCII85Decode, FlateDecode, LZWDecode, RunLengthDecode. - Encoders: ASCIIHexDecode, ASCII85Decode, FlateDecode, RunLengthDecode. - Predictors: PNG (all), TIFF (8-bit only). *) exception Couldn'tDecodeStream of string exception DecodeNotSupported * Given a document and stream , decode . The pdf document is updated with the decoded stream . May return either of the exceptions above . with the decoded stream. May return either of the exceptions above. *) val decode_pdfstream : Pdf.pdfdoc -> Pdf.pdfobject -> unit * Given a document and stream decode just one stage . May return either of the exceptions above . exceptions above. *) val decode_pdfstream_onestage : Pdf.pdfdoc -> Pdf.pdfobject -> unit * Given a document and stream decode until there 's an unknown decoder . May return [ Couldn'tDecodeStream ] . return [Couldn'tDecodeStream]. *) val decode_pdfstream_until_unknown : Pdf.pdfdoc -> Pdf.pdfobject -> unit type encoding = | ASCIIHex | ASCII85 | RunLength | Flate val encode_pdfstream : Pdf.pdfdoc -> encoding -> Pdf.pdfobject -> unit Given an [ Io.input ] with pointer at the first byte and an inline image stream dictionary , decode the first decoder and its predictor . Return the data , or [ None ] if this decoder is n't supported but the data pointer has been left in the right place . The exceptions above can both be raised , in the case of bad data or a completely unknown encoding . stream dictionary, decode the first decoder and its predictor. Return the data, or [None] if this decoder isn't supported but the data pointer has been left in the right place. The exceptions above can both be raised, in the case of bad data or a completely unknown encoding. *) val decode_from_input : Io.input -> Pdf.pdfobject -> Utility.bytestream option
d7028ab04706d28999103eff0c253e9a783da7ff8883cfe962c1b988572fc4b5
vvvvalvalval/scope-capture
logging.cljc
(ns sc.impl.logging) (defmulti log-cs (fn [logger-id cs-data] logger-id))
null
https://raw.githubusercontent.com/vvvvalvalval/scope-capture/1214ff41459c41df57ef55b3fdf01d965ad611b2/src/sc/impl/logging.cljc
clojure
(ns sc.impl.logging) (defmulti log-cs (fn [logger-id cs-data] logger-id))
ecf5cef6d98d0ef67aecf16d1a82b332524ce1460877c858a82bd9c83b8b0f97
ocsigen/eliom
eliom_content.client.mli
Ocsigen * * Copyright ( C ) 2012 , * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2012 Vincent Balat, Benedikt Becker * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Js_of_ocaml * This module provides the creation of valid XML content , i.e. XML , SVG , and ( X)HTML5 . { b Please read { % < < a_manual chapter="clientserver - html"|Eliom 's manual>>% } for more information on HTML generation . } You can also have a look at the server API of { % < < a_api subproject="server " | module Eliom_content > > % } for an explication of the modules [ F ] and [ D ] . and (X)HTML5. {b Please read {% <<a_manual chapter="clientserver-html"|Eliom's manual>>%} for more information on HTML generation. } You can also have a look at the server API of {% <<a_api subproject="server" | module Eliom_content >> %} for an explication of the modules [F] and [D]. *) module Xml : module type of Eliom_content_core.Xml (** Low-level XML manipulation. *) (** Building valid SVG . *) module Svg : sig * See the Eliom manual for more information on { % < < a_manual chapter="clientserver - html " vs. functional semantics > > % } for HTML5 tree manipulated by client / server application . chapter="clientserver-html" fragment="unique"| dom semantics vs. functional semantics>> %} for HTML5 tree manipulated by client/server application. *) type +'a elt type +'a attrib type uri = Xml.uri * Creation of { e f}unctional content ( copy - able but not referable ) . See { % < < a_api project="tyxml " | module Svg_sigs . T > > % } See {% <<a_api project="tyxml" | module Svg_sigs.T >> %} *) module F : sig * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Svg_sigs.Make(Xml).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end * Creation of content with { e D}OM semantics ( referable See { % < < a_api project="tyxml " | module Svg_sigs . T > > % } See {% <<a_api project="tyxml" | module Svg_sigs.T >> %} *) module D : sig * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Svg_sigs.Make(Xml).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end (** Creation of reactive content *) module R : sig val node : 'a elt React.signal -> 'a elt (** The function [node s] creates an SVG [elt] from a signal [s]. The resulting SVG [elt] can then be used like any other SVG [elt]. *) module Raw : Svg_sigs.Make(Eliom_content_core.Xml_wed).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end (** Creation of content from client-side values. *) module C : sig val node : ?init:'a D.elt -> 'a elt Eliom_client_value.t -> 'a D.elt val attr : ?init:'a attrib -> 'a attrib Eliom_client_value.t -> 'a attrib end (** Node identifiers *) module Id : sig type +'a id (** The type of global SVG element identifier. *) val new_elt_id : ?global:bool -> unit -> 'a id * The function [ new_elt_id ( ) ] creates a new HTML5 element identifier . ( see the Eliom manual for more information on { % < < a_manual project="eliom " chapter="clientserver - html " fragment="global"|global element>>% } ) . identifier. (see the Eliom manual for more information on {% <<a_manual project="eliom" chapter="clientserver-html" fragment="global"|global element>>%}).*) val create_named_elt : id:'a id -> 'a elt -> 'a elt (** The function [create_named_elt ~id elt] create a copy of the element [elt] that will be accessible through the name [id]. *) val create_global_elt : 'a elt -> 'a elt (** The function [create_named_elt elt] is equivalent to [create_named_elt ~id:(new_elt_id ()) elt]. *) val create_request_elt : ?reset:bool -> 'a elt -> 'a elt (** [create_request_elt ?reset elt] creates a referable copy of [elt]. If [~reset = true] is provided (default: false), a new ID is created even if [elt] has an ID already. *) val get_element : 'a id -> 'a elt option * [ get_element i d ] returns the HTML element in the DOM with the given [ i d ] if it exists . the HTML element in the DOM with the given [id] if it exists. *) end (** DOM-like manipulation functions. In this module, all the functions apply only to SVG element with {% <<a_manual chapter="clientserver-html" fragment="unique"|Dom semantics>> %}. *) module Manip : sig val appendChild : ?before:'a elt -> 'b elt -> 'c elt -> unit * [ appendChild e1 e2 ] inserts the element [ e2 ] as last child of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ e2 ] is inserted before [ e3 ] in the list of [ e1 ] children . child of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [e2] is inserted before [e3] in the list of [e1] children. *) val appendChildren : ?before:'a elt -> 'b elt -> 'c elt list -> unit * [ appendChildren e1 elts ] inserts [ elts ] as last children of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ elts ] are inserted before [ e3 ] in the list of [ e1 ] children . of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [elts] are inserted before [e3] in the list of [e1] children. *) val insertFirstChild : 'b elt -> 'c elt -> unit * [ insertFirstChild p c ] inserts [ c ] as first child of [ p ] val nth : 'a elt -> int -> 'b elt option * [ nth e n ] returns the nth child of [ e ] ( first is 0 ) val childLength : 'a elt -> int * [ childLength e ] returns the number of children of [ e ] val removeChild : 'a elt -> 'b elt -> unit * [ removeChild e1 e2 ] removes for [ e2 ] from the list of children of [ e1 ] . children of [e1]. *) val replaceChild : 'a elt -> 'b elt -> 'c elt -> unit (** [replace e1 e2 e3] replaces [e3] by [e2] in the list of children of [e1]. *) val removeChildren : 'a elt -> unit (** [removeChildren e1] removes all children of [e1]. *) val removeSelf : 'a elt -> unit * [ removeSelf e ] removes element e from the DOM . val replaceChildren : 'a elt -> 'b elt list -> unit (** [replaceChildren e1 elts] replaces all the children of [e1] by [elt]. *) val parentNode : 'a elt -> 'b elt option (** [parentNode elt] returns the parent of [elt], if any. *) val nextSibling : 'a elt -> 'b elt option (** [nextSibling elt] returns the next element that has the same parent, if [elt] is not the last. *) val previousSibling : 'a elt -> 'b elt option * [ previousSibling elt ] returns the previous element that has the same parent , if [ elt ] is not the first . that has the same parent, if [elt] is not the first. *) val insertBefore : before:'a elt -> 'b elt -> unit (** [insertBefore ~before elt] insert [elt] before [before]. *) val insertAfter : after:'a elt -> 'b elt -> unit (** [insertAfter ~after elt] insert [elt] after [after]. *) val replaceSelf : 'a elt -> 'b elt -> unit (** [replaceSelf elt1 elt2] replaces [elt1] by [elt2]. *) (* (\** The function [addEventListener elt evt handler] attach the *) (* [handler] for the event [evt] on the element [elt]. See the *) (* Js_of_ocaml manual, for a list of {% <<a_api project="js_of_ocaml" *) text="available events"| module . . Event > > % } . * \ ) (* val addEventListener: *) (* ?capture:bool -> *) (* 'a elt -> *) ( # Dom_html.event as ' b ) > (* ('a elt -> 'b Js.t -> bool) -> *) (* Dom_html.event_listener_id *) * manipulation by element identifier . module Named : sig * The module [ Named ] defines the same functions as [ Eliom_dom ] . They take as parameter an element identifier instead of an element with semantics . Those functions only works if the element is available in the application ( sent in the page or along the page ) . If the element is not available , those functions raise with [ Not_found ] . [Eliom_dom]. They take as parameter an element identifier instead of an element with Dom semantics. Those functions only works if the element is available in the application (sent in the page or along the page). If the element is not available, those functions raise with [Not_found]. *) val appendChild : ?before:'a elt -> 'b Id.id -> 'c elt -> unit (** see [appendChild] *) val appendChildren : ?before:'a elt -> 'b Id.id -> 'c elt list -> unit * see [ appendChildren ] val removeChild : 'a Id.id -> 'b elt -> unit (** see [removeChild] *) val replaceChild : 'a Id.id -> 'b elt -> 'c elt -> unit (** see [replaceChild] *) val removeChildren : 'a Id.id -> unit (** see [removeChildren] *) val replaceChildren : 'a Id.id -> 'b elt list -> unit (** see [replaceChildren] *) (* (\** see [addEventListener] *\) *) (* val addEventListener: *) (* ?capture:bool -> *) (* 'a Id.id -> *) ( # Dom_html.event as ' b ) > (* ('a elt -> 'b Js.t -> bool) -> *) (* Dom_html.event_listener_id *) end (**/**) val childNodes : 'a elt -> Dom.node Js.t list val childElements : 'a elt -> Dom.element Js.t list (**/**) module Class : sig val contain : 'a elt -> string -> bool val remove : 'a elt -> string -> unit val removes : 'a elt -> string list -> unit val add : 'a elt -> string -> unit val adds : 'a elt -> string list -> unit val replace : 'a elt -> string -> string -> unit val clear : 'a elt -> unit val toggle : 'a elt -> string -> unit val toggle2 : 'a elt -> string -> string -> unit end end * Conversion from Svg [ elt]s to Javascript DOM elements ( [ < :] { % < < a_api project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element > > % } ) . One conversion function per source type ( stressed by the [ of _ ] prefix ) . project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element >> %}). One conversion function per source type (stressed by the [of_] prefix). *) module To_dom : sig val of_element : 'a elt -> Dom_html.element Js.t val of_node : 'a elt -> Dom.node Js.t val of_pcdata : [> `Pcdata] elt -> Dom.text Js.t end * Conversion functions from DOM nodes ( { % < < a_api project="js_of_ocaml"| > > % } { % < < a_api project="js_of_ocaml"| type . Js.t > > % } ) to Eliom nodes ( { % < < a_api | type Eliom_content.Html.elt > > % } ) . project="js_of_ocaml"| type Js_of_ocaml.Js.t>> %}) to Eliom nodes ({% <<a_api | type Eliom_content.Html.elt>> %}). *) module Of_dom : sig val of_element : Dom_html.element Js.t -> 'a elt end end (** Building valid (X)HTML5. *) module Html : sig * See the Eliom manual for more information on { % < < a_manual chapter="clientserver - html " vs. functional semantics > > % } for HTML5 tree manipulated by client / server application . chapter="clientserver-html" fragment="unique"| dom semantics vs. functional semantics>> %} for HTML5 tree manipulated by client/server application. *) type +'a elt type +'a attrib type uri = Xml.uri type 'a form_param (** Creation of {e f}unctional HTML5 content (copy-able but not referable). *) module F : sig * { 2 Content creation } See { % < < a_api project="tyxml " | module . T > > % } See {% <<a_api project="tyxml" | module Html_sigs.T >> %} *) * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Html_sigs.Make(Xml)(Svg.F.Raw).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw include Eliom_content_sigs.LINKS_AND_FORMS with type +'a elt := 'a elt and type +'a attrib := 'a attrib and type uri := uri and type ('a, 'b, 'c) star := ('a, 'b, 'c) star and type 'a form_param := 'a form_param end (** Creation of HTML5 content with {e D}OM semantics (referable) *) module D : sig * { 2 Content creation } See { % < < a_api project="tyxml " | module . T > > % } See {% <<a_api project="tyxml" | module Html_sigs.T >> %} *) * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Html_sigs.Make(Xml)(Svg.D.Raw).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw include Eliom_content_sigs.LINKS_AND_FORMS with type +'a elt := 'a elt and type +'a attrib := 'a attrib and type uri := uri and type ('a, 'b, 'c) star := ('a, 'b, 'c) star and type 'a form_param := 'a form_param end (** Creation of HTML5 content from {{:} React} signals. HTML5's trees are automatically updated whenever corresponding signals change. *) module R : sig * { 2 Content creation } See { % < < a_api project="tyxml " | module . T > > % } , If you want to create an untyped form , you will have to use { % < < a_api|module Eliom_content . Html . > > % } otherwise , use the form module . For more information , see { % < < a_manual chapter="server - links " fragment="forms"|the manual > > % } . See {% <<a_api project="tyxml" | module Html_sigs.T >> %}, If you want to create an untyped form, you will have to use {% <<a_api|module Eliom_content.Html.D.Raw>> %} otherwise, use the form module. For more information, see {% <<a_manual chapter="server-links" fragment="forms"|the manual>> %}. *) val node : 'a elt React.signal Eliom_client_value.t -> 'a elt (** Function [node s] create an HTML5 [elt] from a signal [s]. The resulting HTML5 [elt] can then be used like any other HTML5 [elt] *) val filter_attrib : 'a attrib -> bool React.signal -> 'a attrib (** [filter_attrib att on] returns an attrib that behave like [att] when [on] is [true] and behave like if there was no attribute when [on] is [false] *) * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Html_sigs.Make(Eliom_content_core.Xml_wed)(Svg.R.Raw).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end (** Creation of HTML5 content from client-side values. This module is available on client side only to make possible to use C-nodes in shared sections. *) module C : sig * { 2 Content injection } val node : ?init:'a D.elt -> 'a elt Eliom_client_value.t -> 'a D.elt * Those two functions are the identity on client - side ( the [ init ] argument is ignored ) . See Eliom manual for more detail on { % < < a_manual chapter="clientserver - html " fragment="inject " | Dom & Client - values > > % } . (the [init] argument is ignored). See Eliom manual for more detail on {% <<a_manual chapter="clientserver-html" fragment="inject" | Dom & Client-values >>%}. *) val attr : ?init:'a attrib -> 'a attrib Eliom_client_value.t -> 'a attrib end (** Node identifiers *) module Id : sig type +'a id (** The type of global HTML5 element identifier. *) val new_elt_id : ?global:bool -> unit -> 'a id * The function [ new_elt_id ( ) ] creates a new global HTML5 element identifier ( see the Eliom manual for more information on { % < < a_manual project="eliom " chapter="clientserver - html " fragment="global"|global element>>% } ) . identifier (see the Eliom manual for more information on {% <<a_manual project="eliom" chapter="clientserver-html" fragment="global"|global element>>%}).*) val create_named_elt : id:'a id -> 'a elt -> 'a elt (** The function [create_named_elt ~id elt] create a copy of the element [elt] that will be sent to client with the reference [id]. *) val create_global_elt : 'a elt -> 'a elt (** The function [create_named_elt elt] is equivalent to [create_named_elt ~id:(new_elt_id ()) elt]. *) val create_request_elt : ?reset:bool -> 'a elt -> 'a elt (** [create_request_elt ?reset elt] creates a referable copy of [elt]. If [~reset = true] is provided (default: false), a new ID is created even if [elt] has an ID already. *) val get_element : 'a id -> 'a elt option * [ get_element i d ] returns the HTML element in the DOM with the given [ i d ] if it exists . the HTML element in the DOM with the given [id] if it exists. *) end module Custom_data : sig type 'a t (** Custom data with values of type ['a]. *) val create : name:string -> ?default:'a -> to_string:('a -> string) -> of_string:(string -> 'a) -> unit -> 'a t * Create a custom data field by providing string conversion functions . If the [ default ] is provided , calls to { % < < a_api project="eliom " subproject="client " | val Eliom_content . Html . Custom_data.get_dom > > % } return that instead of throwing an exception [ Not_found ] . If the [default] is provided, calls to {% <<a_api project="eliom" subproject="client" | val Eliom_content.Html.Custom_data.get_dom>> %} return that instead of throwing an exception [Not_found]. *) val create_json : name:string -> ?default:'a -> 'a Deriving_Json.t -> 'a t * Create a custom data from a Json - deriving type . val attrib : 'a t -> 'a -> [> `User_data] attrib * [ attrib my_data value ] creates a HTML5 attribute for the custom - data type [ my_data ] with value [ value ] for injecting it into an a HTML5 tree ( { % < < a_api | type Eliom_content.Html.elt > > % } ) . type [my_data] with value [value] for injecting it into an a HTML5 tree ({% <<a_api | type Eliom_content.Html.elt >> %}). *) val get_dom : Dom_html.element Js.t -> 'a t -> 'a val set_dom : Dom_html.element Js.t -> 'a t -> 'a -> unit end module To_dom : Js_of_ocaml_tyxml.Tyxml_cast_sigs.TO with type 'a elt = 'a elt * Conversion from HTML5 [ elt]s to Javascript DOM elements ( [ < :] { % < < a_api project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element > > % } ) . One conversion function per source type ( stressed by the [ of _ ] prefix ) . project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element >> %}). One conversion function per source type (stressed by the [of_] prefix). *) (** DOM-like manipulation functions. In this module, all the functions apply only to HTML5 element with {% <<a_manual chapter="clientserver-html" fragment="unique"|Dom semantics>> %}. *) module Manip : sig val appendChild : ?before:'a elt -> 'b elt -> 'c elt -> unit * [ appendChild e1 e2 ] inserts the element [ e2 ] as last child of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ e2 ] is inserted before [ e3 ] in the list of [ e1 ] children . child of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [e2] is inserted before [e3] in the list of [e1] children. *) val appendToBody : ?before:'a elt -> 'c elt -> unit (** Append to the body of the document. *) val appendChildren : ?before:'a elt -> 'b elt -> 'c elt list -> unit * [ appendChildren e1 elts ] inserts [ elts ] as last children of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ elts ] are inserted before [ e3 ] in the list of [ e1 ] children . of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [elts] are inserted before [e3] in the list of [e1] children. *) val insertFirstChild : 'b elt -> 'c elt -> unit * [ insertFirstChild p c ] inserts [ c ] as first child of [ p ] val nth : 'a elt -> int -> 'b elt option * [ nth e n ] returns the nth child of [ e ] ( first is 0 ) val childLength : 'a elt -> int * [ childLength e ] returns the number of children of [ e ] val removeChild : 'a elt -> 'b elt -> unit * The function [ removeChild e1 e2 ] removes for [ e2 ] from the list of [ e1 ] children . [e1] children. *) val replaceChild : 'a elt -> 'b elt -> 'c elt -> unit (** The function [replace e1 e2 e3] replaces for [e2] by [e3] in the list of [e1] children. *) val removeChildren : 'a elt -> unit (** The function [removeChildren e1] removes [e1] children. *) val removeSelf : 'a elt -> unit * [ removeSelf e ] removes element e from the DOM . val replaceChildren : 'a elt -> 'b elt list -> unit (** The function [replaceChildren e1 elts] replaces all the children of [e1] by [elt]. *) val parentNode : 'a elt -> 'b elt option (** [parentNode elt] returns the parent of [elt], if any. *) val nextSibling : 'a elt -> 'b elt option (** [nextSibling elt] returns the next element that has the same parent, if [elt] is not the last. *) val previousSibling : 'a elt -> 'b elt option * [ previousSibling elt ] returns the previous element that has the same parent , if [ elt ] is not the first . that has the same parent, if [elt] is not the first. *) val insertBefore : before:'a elt -> 'b elt -> unit (** [insertBefore ~before elt] insert [elt] before [before]. *) val insertAfter : after:'a elt -> 'b elt -> unit (** [insertAfter ~after elt] insert [elt] after [after]. *) val replaceSelf : 'a elt -> 'b elt -> unit (** [replaceSelf elt1 elt2] replaces [elt1] by [elt2]. *) val children : 'a elt -> 'b elt list (** [children elt] returns the list of html children of [elt]. *) val addEventListener : ?capture:bool -> 'a elt -> (#Dom_html.event as 'b) Js.t Dom_html.Event.typ -> ('a elt -> 'b Js.t -> bool) -> Dom_html.event_listener_id * The function [ addEventListener elt evt handler ] attach the [ handler ] for the event [ evt ] on the element [ elt ] . See the manual , for a list of { % < < a_api project="js_of_ocaml " text="available events"| module . . Event > > % } . [handler] for the event [evt] on the element [elt]. See the Js_of_ocaml manual, for a list of {% <<a_api project="js_of_ocaml" text="available events"| module Js_of_ocaml.Dom_html.Event >>%}. *) * manipulation by element identifier . module Named : sig * The module [ Named ] defines the same functions as [ Eliom_dom ] . They take as parameter an element identifier instead of an element with semantics . Those functions only works if the element is available in the application ( sent in the page or along the page ) . If the element is not available , those functions raise with [ Not_found ] . [Eliom_dom]. They take as parameter an element identifier instead of an element with Dom semantics. Those functions only works if the element is available in the application (sent in the page or along the page). If the element is not available, those functions raise with [Not_found]. *) val appendChild : ?before:'a elt -> 'b Id.id -> 'c elt -> unit (** see [appendChild] *) val appendChildren : ?before:'a elt -> 'b Id.id -> 'c elt list -> unit * see [ appendChildren ] val removeChild : 'a Id.id -> 'b elt -> unit (** see [removeChild] *) val replaceChild : 'a Id.id -> 'b elt -> 'c elt -> unit (** see [replaceChild] *) val removeChildren : 'a Id.id -> unit (** see [removeChildren] *) val replaceChildren : 'a Id.id -> 'b elt list -> unit (** see [replaceChildren] *) val addEventListener : ?capture:bool -> 'a Id.id -> (#Dom_html.event as 'b) Js.t Dom_html.Event.typ -> ('a elt -> 'b Js.t -> bool) -> Dom_html.event_listener_id (** see [addEventListener] *) end val scrollIntoView : ?bottom:bool -> 'a elt -> unit (** The function [scrollIntoView elt] scroll the page to a position where [elt] is displayed at the top of the window. If the optional parameter [~bottom:true] is present, the page is scrolled to a position where [elt] is displayed at the bottom of the window. *) (**/**) val childNodes : 'a elt -> Dom.node Js.t list val childElements : 'a elt -> Dom.element Js.t list (**/**) (* val get_custom_data : _ elt -> 'a Custom_data.t -> 'a val set_custom_data : _ elt -> 'a Custom_data.t -> 'a -> unit *) module Class : sig val contain : 'a elt -> string -> bool val remove : 'a elt -> string -> unit val removes : 'a elt -> string list -> unit val add : 'a elt -> string -> unit val adds : 'a elt -> string list -> unit val replace : 'a elt -> string -> string -> unit val clear : 'a elt -> unit val toggle : 'a elt -> string -> unit val toggle2 : 'a elt -> string -> string -> unit end module Elt : sig val body : unit -> [`Body] elt end module Ev : sig type ('a, 'b) ev = 'a elt -> ('b Js.t -> bool) -> unit type ('a, 'b) ev_unit = 'a elt -> ('b Js.t -> unit) -> unit val onkeyup : ('a, Dom_html.keyboardEvent) ev val onkeydown : ('a, Dom_html.keyboardEvent) ev val onmouseup : ('a, Dom_html.mouseEvent) ev val onmousedown : ('a, Dom_html.mouseEvent) ev val onmouseout : ('a, Dom_html.mouseEvent) ev val onmouseover : ('a, Dom_html.mouseEvent) ev val onclick : ('a, Dom_html.mouseEvent) ev val ondblclick : ('a, Dom_html.mouseEvent) ev val onload : ('a, Dom_html.event) ev val onerror : ('a, Dom_html.event) ev val onabort : ('a, Dom_html.event) ev val onfocus : ('a, Dom_html.event) ev val onblur : ('a, Dom_html.event) ev val onfocus_textarea : ('a, Dom_html.event) ev val onblur_textarea : ('a, Dom_html.event) ev val onscroll : ('a, Dom_html.event) ev val onreturn : ('a, Dom_html.keyboardEvent) ev_unit val onchange : ('a, Dom_html.event) ev val onchange_select : ('a, Dom_html.event) ev end module Attr : sig val clientWidth : 'a elt -> int val clientHeight : 'a elt -> int val offsetWidth : 'a elt -> int val offsetHeight : 'a elt -> int val clientLeft : 'a elt -> int val clientTop : 'a elt -> int end * Read the CSS properties of DOM elements . module Css : sig val background : 'a elt -> string val backgroundAttachment : 'a elt -> string val backgroundColor : 'a elt -> string val backgroundImage : 'a elt -> string val backgroundPosition : 'a elt -> string val backgroundRepeat : 'a elt -> string val border : 'a elt -> string val borderBottom : 'a elt -> string val borderBottomColor : 'a elt -> string val borderBottomStyle : 'a elt -> string val borderBottomWidth : 'a elt -> string val borderBottomWidthPx : 'a elt -> int val borderCollapse : 'a elt -> string val borderColor : 'a elt -> string val borderLeft : 'a elt -> string val borderLeftColor : 'a elt -> string val borderLeftStyle : 'a elt -> string val borderLeftWidth : 'a elt -> string val borderLeftWidthPx : 'a elt -> int val borderRight : 'a elt -> string val borderRightColor : 'a elt -> string val borderRightStyle : 'a elt -> string val borderRightWidth : 'a elt -> string val borderRightWidthPx : 'a elt -> int val borderSpacing : 'a elt -> string val borderStyle : 'a elt -> string val borderTop : 'a elt -> string val borderTopColor : 'a elt -> string val borderTopStyle : 'a elt -> string val borderTopWidth : 'a elt -> string val borderTopWidthPx : 'a elt -> int val borderWidth : 'a elt -> string val bottom : 'a elt -> string val captionSide : 'a elt -> string val clear : 'a elt -> string val clip : 'a elt -> string val color : 'a elt -> string val content : 'a elt -> string val counterIncrement : 'a elt -> string val counterReset : 'a elt -> string val cssFloat : 'a elt -> string val cssText : 'a elt -> string val cursor : 'a elt -> string val direction : 'a elt -> string val display : 'a elt -> string val emptyCells : 'a elt -> string val font : 'a elt -> string val fontFamily : 'a elt -> string val fontSize : 'a elt -> string val fontStyle : 'a elt -> string val fontVariant : 'a elt -> string val fontWeight : 'a elt -> string val height : 'a elt -> string val heightPx : 'a elt -> int val left : 'a elt -> string val leftPx : 'a elt -> int val letterSpacing : 'a elt -> string val lineHeight : 'a elt -> string val listStyle : 'a elt -> string val listStyleImage : 'a elt -> string val listStylePosition : 'a elt -> string val listStyleType : 'a elt -> string val margin : 'a elt -> string val marginBottom : 'a elt -> string val marginBottomPx : 'a elt -> int val marginLeft : 'a elt -> string val marginLeftPx : 'a elt -> int val marginRight : 'a elt -> string val marginRightPx : 'a elt -> int val marginTop : 'a elt -> string val marginTopPx : 'a elt -> int val maxHeight : 'a elt -> string val maxHeightPx : 'a elt -> int val maxWidth : 'a elt -> string val maxWidthPx : 'a elt -> int val minHeight : 'a elt -> string val minHeightPx : 'a elt -> int val minWidth : 'a elt -> string val minWidthPx : 'a elt -> int val opacity : 'a elt -> string option val outline : 'a elt -> string val outlineColor : 'a elt -> string val outlineOffset : 'a elt -> string val outlineStyle : 'a elt -> string val outlineWidth : 'a elt -> string val overflow : 'a elt -> string val overflowX : 'a elt -> string val overflowY : 'a elt -> string val padding : 'a elt -> string val paddingBottom : 'a elt -> string val paddingBottomPx : 'a elt -> int val paddingLeft : 'a elt -> string val paddingLeftPx : 'a elt -> int val paddingRight : 'a elt -> string val paddingRightPx : 'a elt -> int val paddingTop : 'a elt -> string val paddingTopPx : 'a elt -> int val pageBreakAfter : 'a elt -> string val pageBreakBefore : 'a elt -> string val position : 'a elt -> string val right : 'a elt -> string val rightPx : 'a elt -> int val tableLayout : 'a elt -> string val textAlign : 'a elt -> string val textDecoration : 'a elt -> string val textIndent : 'a elt -> string val textTransform : 'a elt -> string val top : 'a elt -> string val topPx : 'a elt -> int val verticalAlign : 'a elt -> string val visibility : 'a elt -> string val whiteSpace : 'a elt -> string val width : 'a elt -> string val widthPx : 'a elt -> int val wordSpacing : 'a elt -> string val zIndex : 'a elt -> string end * Modify the CSS properties of DOM elements . module SetCss : sig val background : 'a elt -> string -> unit val backgroundAttachment : 'a elt -> string -> unit val backgroundColor : 'a elt -> string -> unit val backgroundImage : 'a elt -> string -> unit val backgroundPosition : 'a elt -> string -> unit val backgroundRepeat : 'a elt -> string -> unit val border : 'a elt -> string -> unit val borderBottom : 'a elt -> string -> unit val borderBottomColor : 'a elt -> string -> unit val borderBottomStyle : 'a elt -> string -> unit val borderBottomWidth : 'a elt -> string -> unit val borderBottomWidthPx : 'a elt -> int -> unit val borderCollapse : 'a elt -> string -> unit val borderColor : 'a elt -> string -> unit val borderLeft : 'a elt -> string -> unit val borderLeftColor : 'a elt -> string -> unit val borderLeftStyle : 'a elt -> string -> unit val borderLeftWidth : 'a elt -> string -> unit val borderLeftWidthPx : 'a elt -> int -> unit val borderRight : 'a elt -> string -> unit val borderRightColor : 'a elt -> string -> unit val borderRightStyle : 'a elt -> string -> unit val borderRightWidth : 'a elt -> string -> unit val borderRightWidthPx : 'a elt -> int -> unit val borderSpacing : 'a elt -> string -> unit val borderStyle : 'a elt -> string -> unit val borderTop : 'a elt -> string -> unit val borderTopColor : 'a elt -> string -> unit val borderTopStyle : 'a elt -> string -> unit val borderTopWidth : 'a elt -> string -> unit val borderTopWidthPx : 'a elt -> int -> unit val borderWidth : 'a elt -> string -> unit val bottom : 'a elt -> string -> unit val bottomPx : 'a elt -> int -> unit val captionSide : 'a elt -> string -> unit val clear : 'a elt -> string -> unit val clip : 'a elt -> string -> unit val color : 'a elt -> string -> unit val content : 'a elt -> string -> unit val counterIncrement : 'a elt -> string -> unit val counterReset : 'a elt -> string -> unit val cssFloat : 'a elt -> string -> unit val cssText : 'a elt -> string -> unit val cursor : 'a elt -> string -> unit val direction : 'a elt -> string -> unit val display : 'a elt -> string -> unit val emptyCells : 'a elt -> string -> unit val font : 'a elt -> string -> unit val fontFamily : 'a elt -> string -> unit val fontSize : 'a elt -> string -> unit val fontStyle : 'a elt -> string -> unit val fontVariant : 'a elt -> string -> unit val fontWeight : 'a elt -> string -> unit val height : 'a elt -> string -> unit val heightPx : 'a elt -> int -> unit val left : 'a elt -> string -> unit val leftPx : 'a elt -> int -> unit val letterSpacing : 'a elt -> string -> unit val lineHeight : 'a elt -> string -> unit val listStyle : 'a elt -> string -> unit val listStyleImage : 'a elt -> string -> unit val listStylePosition : 'a elt -> string -> unit val listStyleType : 'a elt -> string -> unit val margin : 'a elt -> string -> unit val marginBottom : 'a elt -> string -> unit val marginBottomPx : 'a elt -> int -> unit val marginLeft : 'a elt -> string -> unit val marginLeftPx : 'a elt -> int -> unit val marginRight : 'a elt -> string -> unit val marginRightPx : 'a elt -> int -> unit val marginTop : 'a elt -> string -> unit val marginTopPx : 'a elt -> int -> unit val maxHeight : 'a elt -> string -> unit val maxHeightPx : 'a elt -> int -> unit val maxWidth : 'a elt -> string -> unit val maxWidthPx : 'a elt -> int -> unit val minHeight : 'a elt -> string -> unit val minHeightPx : 'a elt -> int -> unit val minWidth : 'a elt -> string -> unit val minWidthPx : 'a elt -> int -> unit val opacity : 'a elt -> string -> unit val outline : 'a elt -> string -> unit val outlineColor : 'a elt -> string -> unit val outlineOffset : 'a elt -> string -> unit val outlineStyle : 'a elt -> string -> unit val outlineWidth : 'a elt -> string -> unit val overflow : 'a elt -> string -> unit val overflowX : 'a elt -> string -> unit val overflowY : 'a elt -> string -> unit val padding : 'a elt -> string -> unit val paddingBottom : 'a elt -> string -> unit val paddingBottomPx : 'a elt -> int -> unit val paddingLeft : 'a elt -> string -> unit val paddingLeftPx : 'a elt -> int -> unit val paddingRight : 'a elt -> string -> unit val paddingRightPx : 'a elt -> int -> unit val paddingTop : 'a elt -> string -> unit val paddingTopPx : 'a elt -> int -> unit val pageBreakAfter : 'a elt -> string -> unit val pageBreakBefore : 'a elt -> string -> unit val position : 'a elt -> string -> unit val right : 'a elt -> string -> unit val rightPx : 'a elt -> int -> unit val tableLayout : 'a elt -> string -> unit val textAlign : 'a elt -> string -> unit val textDecoration : 'a elt -> string -> unit val textIndent : 'a elt -> string -> unit val textTransform : 'a elt -> string -> unit val top : 'a elt -> string -> unit val topPx : 'a elt -> int -> unit val verticalAlign : 'a elt -> string -> unit val visibility : 'a elt -> string -> unit val whiteSpace : 'a elt -> string -> unit val width : 'a elt -> string -> unit val widthPx : 'a elt -> int -> unit val wordSpacing : 'a elt -> string -> unit val zIndex : 'a elt -> string -> unit end end module Of_dom : Js_of_ocaml_tyxml.Tyxml_cast_sigs.OF with type 'a elt = 'a elt * Conversion functions from DOM nodes ( { % < < a_api project="js_of_ocaml"| > > % } { % < < a_api project="js_of_ocaml"| type . Js.t > > % } ) to Eliom nodes ( { % < < a_api | type Eliom_content.Html.elt > > % } ) . project="js_of_ocaml"| type Js_of_ocaml.Js.t>> %}) to Eliom nodes ({% <<a_api | type Eliom_content.Html.elt>> %}). *) end val force_link : unit (**/**) val set_client_fun : ?app:string -> service:('a, 'b, _, _, _, _, _, _, _, _, _) Eliom_service.t -> ('a -> 'b -> Eliom_service.result Lwt.t) -> unit val set_form_error_handler : (unit -> bool Lwt.t) -> unit * With [ set_form_error_handler f ] , [ f ] becomes the action to be called when we are unable to call a client - side service due to invalid form data . If the handler returns [ true ] , nothing happens . If the handler returns [ false ] , we proceed to call the server - side service . The default handler throws an exception ( via [ Lwt.fail_with ] ) . called when we are unable to call a client-side service due to invalid form data. If the handler returns [true], nothing happens. If the handler returns [false], we proceed to call the server-side service. The default handler throws an exception (via [Lwt.fail_with]). *)
null
https://raw.githubusercontent.com/ocsigen/eliom/c3e0eea5bef02e0af3942b6d27585add95d01d6c/src/lib/eliom_content.client.mli
ocaml
* Low-level XML manipulation. * Building valid SVG . * Creation of reactive content * The function [node s] creates an SVG [elt] from a signal [s]. The resulting SVG [elt] can then be used like any other SVG [elt]. * Creation of content from client-side values. * Node identifiers * The type of global SVG element identifier. * The function [create_named_elt ~id elt] create a copy of the element [elt] that will be accessible through the name [id]. * The function [create_named_elt elt] is equivalent to [create_named_elt ~id:(new_elt_id ()) elt]. * [create_request_elt ?reset elt] creates a referable copy of [elt]. If [~reset = true] is provided (default: false), a new ID is created even if [elt] has an ID already. * DOM-like manipulation functions. In this module, all the functions apply only to SVG element with {% <<a_manual chapter="clientserver-html" fragment="unique"|Dom semantics>> %}. * [replace e1 e2 e3] replaces [e3] by [e2] in the list of children of [e1]. * [removeChildren e1] removes all children of [e1]. * [replaceChildren e1 elts] replaces all the children of [e1] by [elt]. * [parentNode elt] returns the parent of [elt], if any. * [nextSibling elt] returns the next element that has the same parent, if [elt] is not the last. * [insertBefore ~before elt] insert [elt] before [before]. * [insertAfter ~after elt] insert [elt] after [after]. * [replaceSelf elt1 elt2] replaces [elt1] by [elt2]. (\** The function [addEventListener elt evt handler] attach the [handler] for the event [evt] on the element [elt]. See the Js_of_ocaml manual, for a list of {% <<a_api project="js_of_ocaml" val addEventListener: ?capture:bool -> 'a elt -> ('a elt -> 'b Js.t -> bool) -> Dom_html.event_listener_id * see [appendChild] * see [removeChild] * see [replaceChild] * see [removeChildren] * see [replaceChildren] (\** see [addEventListener] *\) val addEventListener: ?capture:bool -> 'a Id.id -> ('a elt -> 'b Js.t -> bool) -> Dom_html.event_listener_id */* */* * Building valid (X)HTML5. * Creation of {e f}unctional HTML5 content (copy-able but not referable). * Creation of HTML5 content with {e D}OM semantics (referable) * Creation of HTML5 content from {{:} React} signals. HTML5's trees are automatically updated whenever corresponding signals change. * Function [node s] create an HTML5 [elt] from a signal [s]. The resulting HTML5 [elt] can then be used like any other HTML5 [elt] * [filter_attrib att on] returns an attrib that behave like [att] when [on] is [true] and behave like if there was no attribute when [on] is [false] * Creation of HTML5 content from client-side values. This module is available on client side only to make possible to use C-nodes in shared sections. * Node identifiers * The type of global HTML5 element identifier. * The function [create_named_elt ~id elt] create a copy of the element [elt] that will be sent to client with the reference [id]. * The function [create_named_elt elt] is equivalent to [create_named_elt ~id:(new_elt_id ()) elt]. * [create_request_elt ?reset elt] creates a referable copy of [elt]. If [~reset = true] is provided (default: false), a new ID is created even if [elt] has an ID already. * Custom data with values of type ['a]. * DOM-like manipulation functions. In this module, all the functions apply only to HTML5 element with {% <<a_manual chapter="clientserver-html" fragment="unique"|Dom semantics>> %}. * Append to the body of the document. * The function [replace e1 e2 e3] replaces for [e2] by [e3] in the list of [e1] children. * The function [removeChildren e1] removes [e1] children. * The function [replaceChildren e1 elts] replaces all the children of [e1] by [elt]. * [parentNode elt] returns the parent of [elt], if any. * [nextSibling elt] returns the next element that has the same parent, if [elt] is not the last. * [insertBefore ~before elt] insert [elt] before [before]. * [insertAfter ~after elt] insert [elt] after [after]. * [replaceSelf elt1 elt2] replaces [elt1] by [elt2]. * [children elt] returns the list of html children of [elt]. * see [appendChild] * see [removeChild] * see [replaceChild] * see [removeChildren] * see [replaceChildren] * see [addEventListener] * The function [scrollIntoView elt] scroll the page to a position where [elt] is displayed at the top of the window. If the optional parameter [~bottom:true] is present, the page is scrolled to a position where [elt] is displayed at the bottom of the window. */* */* val get_custom_data : _ elt -> 'a Custom_data.t -> 'a val set_custom_data : _ elt -> 'a Custom_data.t -> 'a -> unit */*
Ocsigen * * Copyright ( C ) 2012 , * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 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 Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * Copyright (C) 2012 Vincent Balat, Benedikt Becker * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open Js_of_ocaml * This module provides the creation of valid XML content , i.e. XML , SVG , and ( X)HTML5 . { b Please read { % < < a_manual chapter="clientserver - html"|Eliom 's manual>>% } for more information on HTML generation . } You can also have a look at the server API of { % < < a_api subproject="server " | module Eliom_content > > % } for an explication of the modules [ F ] and [ D ] . and (X)HTML5. {b Please read {% <<a_manual chapter="clientserver-html"|Eliom's manual>>%} for more information on HTML generation. } You can also have a look at the server API of {% <<a_api subproject="server" | module Eliom_content >> %} for an explication of the modules [F] and [D]. *) module Xml : module type of Eliom_content_core.Xml module Svg : sig * See the Eliom manual for more information on { % < < a_manual chapter="clientserver - html " vs. functional semantics > > % } for HTML5 tree manipulated by client / server application . chapter="clientserver-html" fragment="unique"| dom semantics vs. functional semantics>> %} for HTML5 tree manipulated by client/server application. *) type +'a elt type +'a attrib type uri = Xml.uri * Creation of { e f}unctional content ( copy - able but not referable ) . See { % < < a_api project="tyxml " | module Svg_sigs . T > > % } See {% <<a_api project="tyxml" | module Svg_sigs.T >> %} *) module F : sig * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Svg_sigs.Make(Xml).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end * Creation of content with { e D}OM semantics ( referable See { % < < a_api project="tyxml " | module Svg_sigs . T > > % } See {% <<a_api project="tyxml" | module Svg_sigs.T >> %} *) module D : sig * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Svg_sigs.Make(Xml).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end module R : sig val node : 'a elt React.signal -> 'a elt module Raw : Svg_sigs.Make(Eliom_content_core.Xml_wed).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end module C : sig val node : ?init:'a D.elt -> 'a elt Eliom_client_value.t -> 'a D.elt val attr : ?init:'a attrib -> 'a attrib Eliom_client_value.t -> 'a attrib end module Id : sig type +'a id val new_elt_id : ?global:bool -> unit -> 'a id * The function [ new_elt_id ( ) ] creates a new HTML5 element identifier . ( see the Eliom manual for more information on { % < < a_manual project="eliom " chapter="clientserver - html " fragment="global"|global element>>% } ) . identifier. (see the Eliom manual for more information on {% <<a_manual project="eliom" chapter="clientserver-html" fragment="global"|global element>>%}).*) val create_named_elt : id:'a id -> 'a elt -> 'a elt val create_global_elt : 'a elt -> 'a elt val create_request_elt : ?reset:bool -> 'a elt -> 'a elt val get_element : 'a id -> 'a elt option * [ get_element i d ] returns the HTML element in the DOM with the given [ i d ] if it exists . the HTML element in the DOM with the given [id] if it exists. *) end module Manip : sig val appendChild : ?before:'a elt -> 'b elt -> 'c elt -> unit * [ appendChild e1 e2 ] inserts the element [ e2 ] as last child of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ e2 ] is inserted before [ e3 ] in the list of [ e1 ] children . child of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [e2] is inserted before [e3] in the list of [e1] children. *) val appendChildren : ?before:'a elt -> 'b elt -> 'c elt list -> unit * [ appendChildren e1 elts ] inserts [ elts ] as last children of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ elts ] are inserted before [ e3 ] in the list of [ e1 ] children . of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [elts] are inserted before [e3] in the list of [e1] children. *) val insertFirstChild : 'b elt -> 'c elt -> unit * [ insertFirstChild p c ] inserts [ c ] as first child of [ p ] val nth : 'a elt -> int -> 'b elt option * [ nth e n ] returns the nth child of [ e ] ( first is 0 ) val childLength : 'a elt -> int * [ childLength e ] returns the number of children of [ e ] val removeChild : 'a elt -> 'b elt -> unit * [ removeChild e1 e2 ] removes for [ e2 ] from the list of children of [ e1 ] . children of [e1]. *) val replaceChild : 'a elt -> 'b elt -> 'c elt -> unit val removeChildren : 'a elt -> unit val removeSelf : 'a elt -> unit * [ removeSelf e ] removes element e from the DOM . val replaceChildren : 'a elt -> 'b elt list -> unit val parentNode : 'a elt -> 'b elt option val nextSibling : 'a elt -> 'b elt option val previousSibling : 'a elt -> 'b elt option * [ previousSibling elt ] returns the previous element that has the same parent , if [ elt ] is not the first . that has the same parent, if [elt] is not the first. *) val insertBefore : before:'a elt -> 'b elt -> unit val insertAfter : after:'a elt -> 'b elt -> unit val replaceSelf : 'a elt -> 'b elt -> unit text="available events"| module . . Event > > % } . * \ ) ( # Dom_html.event as ' b ) > * manipulation by element identifier . module Named : sig * The module [ Named ] defines the same functions as [ Eliom_dom ] . They take as parameter an element identifier instead of an element with semantics . Those functions only works if the element is available in the application ( sent in the page or along the page ) . If the element is not available , those functions raise with [ Not_found ] . [Eliom_dom]. They take as parameter an element identifier instead of an element with Dom semantics. Those functions only works if the element is available in the application (sent in the page or along the page). If the element is not available, those functions raise with [Not_found]. *) val appendChild : ?before:'a elt -> 'b Id.id -> 'c elt -> unit val appendChildren : ?before:'a elt -> 'b Id.id -> 'c elt list -> unit * see [ appendChildren ] val removeChild : 'a Id.id -> 'b elt -> unit val replaceChild : 'a Id.id -> 'b elt -> 'c elt -> unit val removeChildren : 'a Id.id -> unit val replaceChildren : 'a Id.id -> 'b elt list -> unit ( # Dom_html.event as ' b ) > end val childNodes : 'a elt -> Dom.node Js.t list val childElements : 'a elt -> Dom.element Js.t list module Class : sig val contain : 'a elt -> string -> bool val remove : 'a elt -> string -> unit val removes : 'a elt -> string list -> unit val add : 'a elt -> string -> unit val adds : 'a elt -> string list -> unit val replace : 'a elt -> string -> string -> unit val clear : 'a elt -> unit val toggle : 'a elt -> string -> unit val toggle2 : 'a elt -> string -> string -> unit end end * Conversion from Svg [ elt]s to Javascript DOM elements ( [ < :] { % < < a_api project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element > > % } ) . One conversion function per source type ( stressed by the [ of _ ] prefix ) . project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element >> %}). One conversion function per source type (stressed by the [of_] prefix). *) module To_dom : sig val of_element : 'a elt -> Dom_html.element Js.t val of_node : 'a elt -> Dom.node Js.t val of_pcdata : [> `Pcdata] elt -> Dom.text Js.t end * Conversion functions from DOM nodes ( { % < < a_api project="js_of_ocaml"| > > % } { % < < a_api project="js_of_ocaml"| type . Js.t > > % } ) to Eliom nodes ( { % < < a_api | type Eliom_content.Html.elt > > % } ) . project="js_of_ocaml"| type Js_of_ocaml.Js.t>> %}) to Eliom nodes ({% <<a_api | type Eliom_content.Html.elt>> %}). *) module Of_dom : sig val of_element : Dom_html.element Js.t -> 'a elt end end module Html : sig * See the Eliom manual for more information on { % < < a_manual chapter="clientserver - html " vs. functional semantics > > % } for HTML5 tree manipulated by client / server application . chapter="clientserver-html" fragment="unique"| dom semantics vs. functional semantics>> %} for HTML5 tree manipulated by client/server application. *) type +'a elt type +'a attrib type uri = Xml.uri type 'a form_param module F : sig * { 2 Content creation } See { % < < a_api project="tyxml " | module . T > > % } See {% <<a_api project="tyxml" | module Html_sigs.T >> %} *) * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Html_sigs.Make(Xml)(Svg.F.Raw).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw include Eliom_content_sigs.LINKS_AND_FORMS with type +'a elt := 'a elt and type +'a attrib := 'a attrib and type uri := uri and type ('a, 'b, 'c) star := ('a, 'b, 'c) star and type 'a form_param := 'a form_param end module D : sig * { 2 Content creation } See { % < < a_api project="tyxml " | module . T > > % } See {% <<a_api project="tyxml" | module Html_sigs.T >> %} *) * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Html_sigs.Make(Xml)(Svg.D.Raw).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw include Eliom_content_sigs.LINKS_AND_FORMS with type +'a elt := 'a elt and type +'a attrib := 'a attrib and type uri := uri and type ('a, 'b, 'c) star := ('a, 'b, 'c) star and type 'a form_param := 'a form_param end module R : sig * { 2 Content creation } See { % < < a_api project="tyxml " | module . T > > % } , If you want to create an untyped form , you will have to use { % < < a_api|module Eliom_content . Html . > > % } otherwise , use the form module . For more information , see { % < < a_manual chapter="server - links " fragment="forms"|the manual > > % } . See {% <<a_api project="tyxml" | module Html_sigs.T >> %}, If you want to create an untyped form, you will have to use {% <<a_api|module Eliom_content.Html.D.Raw>> %} otherwise, use the form module. For more information, see {% <<a_manual chapter="server-links" fragment="forms"|the manual>> %}. *) val node : 'a elt React.signal Eliom_client_value.t -> 'a elt val filter_attrib : 'a attrib -> bool React.signal -> 'a attrib * Cf . { % < < a_api project="tyxml " | module . T > > % } . module Raw : Html_sigs.Make(Eliom_content_core.Xml_wed)(Svg.R.Raw).T with type +'a elt = 'a elt and type +'a attrib = 'a attrib include module type of Raw end module C : sig * { 2 Content injection } val node : ?init:'a D.elt -> 'a elt Eliom_client_value.t -> 'a D.elt * Those two functions are the identity on client - side ( the [ init ] argument is ignored ) . See Eliom manual for more detail on { % < < a_manual chapter="clientserver - html " fragment="inject " | Dom & Client - values > > % } . (the [init] argument is ignored). See Eliom manual for more detail on {% <<a_manual chapter="clientserver-html" fragment="inject" | Dom & Client-values >>%}. *) val attr : ?init:'a attrib -> 'a attrib Eliom_client_value.t -> 'a attrib end module Id : sig type +'a id val new_elt_id : ?global:bool -> unit -> 'a id * The function [ new_elt_id ( ) ] creates a new global HTML5 element identifier ( see the Eliom manual for more information on { % < < a_manual project="eliom " chapter="clientserver - html " fragment="global"|global element>>% } ) . identifier (see the Eliom manual for more information on {% <<a_manual project="eliom" chapter="clientserver-html" fragment="global"|global element>>%}).*) val create_named_elt : id:'a id -> 'a elt -> 'a elt val create_global_elt : 'a elt -> 'a elt val create_request_elt : ?reset:bool -> 'a elt -> 'a elt val get_element : 'a id -> 'a elt option * [ get_element i d ] returns the HTML element in the DOM with the given [ i d ] if it exists . the HTML element in the DOM with the given [id] if it exists. *) end module Custom_data : sig type 'a t val create : name:string -> ?default:'a -> to_string:('a -> string) -> of_string:(string -> 'a) -> unit -> 'a t * Create a custom data field by providing string conversion functions . If the [ default ] is provided , calls to { % < < a_api project="eliom " subproject="client " | val Eliom_content . Html . Custom_data.get_dom > > % } return that instead of throwing an exception [ Not_found ] . If the [default] is provided, calls to {% <<a_api project="eliom" subproject="client" | val Eliom_content.Html.Custom_data.get_dom>> %} return that instead of throwing an exception [Not_found]. *) val create_json : name:string -> ?default:'a -> 'a Deriving_Json.t -> 'a t * Create a custom data from a Json - deriving type . val attrib : 'a t -> 'a -> [> `User_data] attrib * [ attrib my_data value ] creates a HTML5 attribute for the custom - data type [ my_data ] with value [ value ] for injecting it into an a HTML5 tree ( { % < < a_api | type Eliom_content.Html.elt > > % } ) . type [my_data] with value [value] for injecting it into an a HTML5 tree ({% <<a_api | type Eliom_content.Html.elt >> %}). *) val get_dom : Dom_html.element Js.t -> 'a t -> 'a val set_dom : Dom_html.element Js.t -> 'a t -> 'a -> unit end module To_dom : Js_of_ocaml_tyxml.Tyxml_cast_sigs.TO with type 'a elt = 'a elt * Conversion from HTML5 [ elt]s to Javascript DOM elements ( [ < :] { % < < a_api project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element > > % } ) . One conversion function per source type ( stressed by the [ of _ ] prefix ) . project="js_of_ocaml"| class Js_of_ocaml.Dom_html.element >> %}). One conversion function per source type (stressed by the [of_] prefix). *) module Manip : sig val appendChild : ?before:'a elt -> 'b elt -> 'c elt -> unit * [ appendChild e1 e2 ] inserts the element [ e2 ] as last child of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ e2 ] is inserted before [ e3 ] in the list of [ e1 ] children . child of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [e2] is inserted before [e3] in the list of [e1] children. *) val appendToBody : ?before:'a elt -> 'c elt -> unit val appendChildren : ?before:'a elt -> 'b elt -> 'c elt list -> unit * [ appendChildren e1 elts ] inserts [ elts ] as last children of [ e1 ] . If the optional parameter [ ~before : e3 ] is present and if [ e3 ] is a child of [ e1 ] , then [ elts ] are inserted before [ e3 ] in the list of [ e1 ] children . of [e1]. If the optional parameter [~before:e3] is present and if [e3] is a child of [e1], then [elts] are inserted before [e3] in the list of [e1] children. *) val insertFirstChild : 'b elt -> 'c elt -> unit * [ insertFirstChild p c ] inserts [ c ] as first child of [ p ] val nth : 'a elt -> int -> 'b elt option * [ nth e n ] returns the nth child of [ e ] ( first is 0 ) val childLength : 'a elt -> int * [ childLength e ] returns the number of children of [ e ] val removeChild : 'a elt -> 'b elt -> unit * The function [ removeChild e1 e2 ] removes for [ e2 ] from the list of [ e1 ] children . [e1] children. *) val replaceChild : 'a elt -> 'b elt -> 'c elt -> unit val removeChildren : 'a elt -> unit val removeSelf : 'a elt -> unit * [ removeSelf e ] removes element e from the DOM . val replaceChildren : 'a elt -> 'b elt list -> unit val parentNode : 'a elt -> 'b elt option val nextSibling : 'a elt -> 'b elt option val previousSibling : 'a elt -> 'b elt option * [ previousSibling elt ] returns the previous element that has the same parent , if [ elt ] is not the first . that has the same parent, if [elt] is not the first. *) val insertBefore : before:'a elt -> 'b elt -> unit val insertAfter : after:'a elt -> 'b elt -> unit val replaceSelf : 'a elt -> 'b elt -> unit val children : 'a elt -> 'b elt list val addEventListener : ?capture:bool -> 'a elt -> (#Dom_html.event as 'b) Js.t Dom_html.Event.typ -> ('a elt -> 'b Js.t -> bool) -> Dom_html.event_listener_id * The function [ addEventListener elt evt handler ] attach the [ handler ] for the event [ evt ] on the element [ elt ] . See the manual , for a list of { % < < a_api project="js_of_ocaml " text="available events"| module . . Event > > % } . [handler] for the event [evt] on the element [elt]. See the Js_of_ocaml manual, for a list of {% <<a_api project="js_of_ocaml" text="available events"| module Js_of_ocaml.Dom_html.Event >>%}. *) * manipulation by element identifier . module Named : sig * The module [ Named ] defines the same functions as [ Eliom_dom ] . They take as parameter an element identifier instead of an element with semantics . Those functions only works if the element is available in the application ( sent in the page or along the page ) . If the element is not available , those functions raise with [ Not_found ] . [Eliom_dom]. They take as parameter an element identifier instead of an element with Dom semantics. Those functions only works if the element is available in the application (sent in the page or along the page). If the element is not available, those functions raise with [Not_found]. *) val appendChild : ?before:'a elt -> 'b Id.id -> 'c elt -> unit val appendChildren : ?before:'a elt -> 'b Id.id -> 'c elt list -> unit * see [ appendChildren ] val removeChild : 'a Id.id -> 'b elt -> unit val replaceChild : 'a Id.id -> 'b elt -> 'c elt -> unit val removeChildren : 'a Id.id -> unit val replaceChildren : 'a Id.id -> 'b elt list -> unit val addEventListener : ?capture:bool -> 'a Id.id -> (#Dom_html.event as 'b) Js.t Dom_html.Event.typ -> ('a elt -> 'b Js.t -> bool) -> Dom_html.event_listener_id end val scrollIntoView : ?bottom:bool -> 'a elt -> unit val childNodes : 'a elt -> Dom.node Js.t list val childElements : 'a elt -> Dom.element Js.t list module Class : sig val contain : 'a elt -> string -> bool val remove : 'a elt -> string -> unit val removes : 'a elt -> string list -> unit val add : 'a elt -> string -> unit val adds : 'a elt -> string list -> unit val replace : 'a elt -> string -> string -> unit val clear : 'a elt -> unit val toggle : 'a elt -> string -> unit val toggle2 : 'a elt -> string -> string -> unit end module Elt : sig val body : unit -> [`Body] elt end module Ev : sig type ('a, 'b) ev = 'a elt -> ('b Js.t -> bool) -> unit type ('a, 'b) ev_unit = 'a elt -> ('b Js.t -> unit) -> unit val onkeyup : ('a, Dom_html.keyboardEvent) ev val onkeydown : ('a, Dom_html.keyboardEvent) ev val onmouseup : ('a, Dom_html.mouseEvent) ev val onmousedown : ('a, Dom_html.mouseEvent) ev val onmouseout : ('a, Dom_html.mouseEvent) ev val onmouseover : ('a, Dom_html.mouseEvent) ev val onclick : ('a, Dom_html.mouseEvent) ev val ondblclick : ('a, Dom_html.mouseEvent) ev val onload : ('a, Dom_html.event) ev val onerror : ('a, Dom_html.event) ev val onabort : ('a, Dom_html.event) ev val onfocus : ('a, Dom_html.event) ev val onblur : ('a, Dom_html.event) ev val onfocus_textarea : ('a, Dom_html.event) ev val onblur_textarea : ('a, Dom_html.event) ev val onscroll : ('a, Dom_html.event) ev val onreturn : ('a, Dom_html.keyboardEvent) ev_unit val onchange : ('a, Dom_html.event) ev val onchange_select : ('a, Dom_html.event) ev end module Attr : sig val clientWidth : 'a elt -> int val clientHeight : 'a elt -> int val offsetWidth : 'a elt -> int val offsetHeight : 'a elt -> int val clientLeft : 'a elt -> int val clientTop : 'a elt -> int end * Read the CSS properties of DOM elements . module Css : sig val background : 'a elt -> string val backgroundAttachment : 'a elt -> string val backgroundColor : 'a elt -> string val backgroundImage : 'a elt -> string val backgroundPosition : 'a elt -> string val backgroundRepeat : 'a elt -> string val border : 'a elt -> string val borderBottom : 'a elt -> string val borderBottomColor : 'a elt -> string val borderBottomStyle : 'a elt -> string val borderBottomWidth : 'a elt -> string val borderBottomWidthPx : 'a elt -> int val borderCollapse : 'a elt -> string val borderColor : 'a elt -> string val borderLeft : 'a elt -> string val borderLeftColor : 'a elt -> string val borderLeftStyle : 'a elt -> string val borderLeftWidth : 'a elt -> string val borderLeftWidthPx : 'a elt -> int val borderRight : 'a elt -> string val borderRightColor : 'a elt -> string val borderRightStyle : 'a elt -> string val borderRightWidth : 'a elt -> string val borderRightWidthPx : 'a elt -> int val borderSpacing : 'a elt -> string val borderStyle : 'a elt -> string val borderTop : 'a elt -> string val borderTopColor : 'a elt -> string val borderTopStyle : 'a elt -> string val borderTopWidth : 'a elt -> string val borderTopWidthPx : 'a elt -> int val borderWidth : 'a elt -> string val bottom : 'a elt -> string val captionSide : 'a elt -> string val clear : 'a elt -> string val clip : 'a elt -> string val color : 'a elt -> string val content : 'a elt -> string val counterIncrement : 'a elt -> string val counterReset : 'a elt -> string val cssFloat : 'a elt -> string val cssText : 'a elt -> string val cursor : 'a elt -> string val direction : 'a elt -> string val display : 'a elt -> string val emptyCells : 'a elt -> string val font : 'a elt -> string val fontFamily : 'a elt -> string val fontSize : 'a elt -> string val fontStyle : 'a elt -> string val fontVariant : 'a elt -> string val fontWeight : 'a elt -> string val height : 'a elt -> string val heightPx : 'a elt -> int val left : 'a elt -> string val leftPx : 'a elt -> int val letterSpacing : 'a elt -> string val lineHeight : 'a elt -> string val listStyle : 'a elt -> string val listStyleImage : 'a elt -> string val listStylePosition : 'a elt -> string val listStyleType : 'a elt -> string val margin : 'a elt -> string val marginBottom : 'a elt -> string val marginBottomPx : 'a elt -> int val marginLeft : 'a elt -> string val marginLeftPx : 'a elt -> int val marginRight : 'a elt -> string val marginRightPx : 'a elt -> int val marginTop : 'a elt -> string val marginTopPx : 'a elt -> int val maxHeight : 'a elt -> string val maxHeightPx : 'a elt -> int val maxWidth : 'a elt -> string val maxWidthPx : 'a elt -> int val minHeight : 'a elt -> string val minHeightPx : 'a elt -> int val minWidth : 'a elt -> string val minWidthPx : 'a elt -> int val opacity : 'a elt -> string option val outline : 'a elt -> string val outlineColor : 'a elt -> string val outlineOffset : 'a elt -> string val outlineStyle : 'a elt -> string val outlineWidth : 'a elt -> string val overflow : 'a elt -> string val overflowX : 'a elt -> string val overflowY : 'a elt -> string val padding : 'a elt -> string val paddingBottom : 'a elt -> string val paddingBottomPx : 'a elt -> int val paddingLeft : 'a elt -> string val paddingLeftPx : 'a elt -> int val paddingRight : 'a elt -> string val paddingRightPx : 'a elt -> int val paddingTop : 'a elt -> string val paddingTopPx : 'a elt -> int val pageBreakAfter : 'a elt -> string val pageBreakBefore : 'a elt -> string val position : 'a elt -> string val right : 'a elt -> string val rightPx : 'a elt -> int val tableLayout : 'a elt -> string val textAlign : 'a elt -> string val textDecoration : 'a elt -> string val textIndent : 'a elt -> string val textTransform : 'a elt -> string val top : 'a elt -> string val topPx : 'a elt -> int val verticalAlign : 'a elt -> string val visibility : 'a elt -> string val whiteSpace : 'a elt -> string val width : 'a elt -> string val widthPx : 'a elt -> int val wordSpacing : 'a elt -> string val zIndex : 'a elt -> string end * Modify the CSS properties of DOM elements . module SetCss : sig val background : 'a elt -> string -> unit val backgroundAttachment : 'a elt -> string -> unit val backgroundColor : 'a elt -> string -> unit val backgroundImage : 'a elt -> string -> unit val backgroundPosition : 'a elt -> string -> unit val backgroundRepeat : 'a elt -> string -> unit val border : 'a elt -> string -> unit val borderBottom : 'a elt -> string -> unit val borderBottomColor : 'a elt -> string -> unit val borderBottomStyle : 'a elt -> string -> unit val borderBottomWidth : 'a elt -> string -> unit val borderBottomWidthPx : 'a elt -> int -> unit val borderCollapse : 'a elt -> string -> unit val borderColor : 'a elt -> string -> unit val borderLeft : 'a elt -> string -> unit val borderLeftColor : 'a elt -> string -> unit val borderLeftStyle : 'a elt -> string -> unit val borderLeftWidth : 'a elt -> string -> unit val borderLeftWidthPx : 'a elt -> int -> unit val borderRight : 'a elt -> string -> unit val borderRightColor : 'a elt -> string -> unit val borderRightStyle : 'a elt -> string -> unit val borderRightWidth : 'a elt -> string -> unit val borderRightWidthPx : 'a elt -> int -> unit val borderSpacing : 'a elt -> string -> unit val borderStyle : 'a elt -> string -> unit val borderTop : 'a elt -> string -> unit val borderTopColor : 'a elt -> string -> unit val borderTopStyle : 'a elt -> string -> unit val borderTopWidth : 'a elt -> string -> unit val borderTopWidthPx : 'a elt -> int -> unit val borderWidth : 'a elt -> string -> unit val bottom : 'a elt -> string -> unit val bottomPx : 'a elt -> int -> unit val captionSide : 'a elt -> string -> unit val clear : 'a elt -> string -> unit val clip : 'a elt -> string -> unit val color : 'a elt -> string -> unit val content : 'a elt -> string -> unit val counterIncrement : 'a elt -> string -> unit val counterReset : 'a elt -> string -> unit val cssFloat : 'a elt -> string -> unit val cssText : 'a elt -> string -> unit val cursor : 'a elt -> string -> unit val direction : 'a elt -> string -> unit val display : 'a elt -> string -> unit val emptyCells : 'a elt -> string -> unit val font : 'a elt -> string -> unit val fontFamily : 'a elt -> string -> unit val fontSize : 'a elt -> string -> unit val fontStyle : 'a elt -> string -> unit val fontVariant : 'a elt -> string -> unit val fontWeight : 'a elt -> string -> unit val height : 'a elt -> string -> unit val heightPx : 'a elt -> int -> unit val left : 'a elt -> string -> unit val leftPx : 'a elt -> int -> unit val letterSpacing : 'a elt -> string -> unit val lineHeight : 'a elt -> string -> unit val listStyle : 'a elt -> string -> unit val listStyleImage : 'a elt -> string -> unit val listStylePosition : 'a elt -> string -> unit val listStyleType : 'a elt -> string -> unit val margin : 'a elt -> string -> unit val marginBottom : 'a elt -> string -> unit val marginBottomPx : 'a elt -> int -> unit val marginLeft : 'a elt -> string -> unit val marginLeftPx : 'a elt -> int -> unit val marginRight : 'a elt -> string -> unit val marginRightPx : 'a elt -> int -> unit val marginTop : 'a elt -> string -> unit val marginTopPx : 'a elt -> int -> unit val maxHeight : 'a elt -> string -> unit val maxHeightPx : 'a elt -> int -> unit val maxWidth : 'a elt -> string -> unit val maxWidthPx : 'a elt -> int -> unit val minHeight : 'a elt -> string -> unit val minHeightPx : 'a elt -> int -> unit val minWidth : 'a elt -> string -> unit val minWidthPx : 'a elt -> int -> unit val opacity : 'a elt -> string -> unit val outline : 'a elt -> string -> unit val outlineColor : 'a elt -> string -> unit val outlineOffset : 'a elt -> string -> unit val outlineStyle : 'a elt -> string -> unit val outlineWidth : 'a elt -> string -> unit val overflow : 'a elt -> string -> unit val overflowX : 'a elt -> string -> unit val overflowY : 'a elt -> string -> unit val padding : 'a elt -> string -> unit val paddingBottom : 'a elt -> string -> unit val paddingBottomPx : 'a elt -> int -> unit val paddingLeft : 'a elt -> string -> unit val paddingLeftPx : 'a elt -> int -> unit val paddingRight : 'a elt -> string -> unit val paddingRightPx : 'a elt -> int -> unit val paddingTop : 'a elt -> string -> unit val paddingTopPx : 'a elt -> int -> unit val pageBreakAfter : 'a elt -> string -> unit val pageBreakBefore : 'a elt -> string -> unit val position : 'a elt -> string -> unit val right : 'a elt -> string -> unit val rightPx : 'a elt -> int -> unit val tableLayout : 'a elt -> string -> unit val textAlign : 'a elt -> string -> unit val textDecoration : 'a elt -> string -> unit val textIndent : 'a elt -> string -> unit val textTransform : 'a elt -> string -> unit val top : 'a elt -> string -> unit val topPx : 'a elt -> int -> unit val verticalAlign : 'a elt -> string -> unit val visibility : 'a elt -> string -> unit val whiteSpace : 'a elt -> string -> unit val width : 'a elt -> string -> unit val widthPx : 'a elt -> int -> unit val wordSpacing : 'a elt -> string -> unit val zIndex : 'a elt -> string -> unit end end module Of_dom : Js_of_ocaml_tyxml.Tyxml_cast_sigs.OF with type 'a elt = 'a elt * Conversion functions from DOM nodes ( { % < < a_api project="js_of_ocaml"| > > % } { % < < a_api project="js_of_ocaml"| type . Js.t > > % } ) to Eliom nodes ( { % < < a_api | type Eliom_content.Html.elt > > % } ) . project="js_of_ocaml"| type Js_of_ocaml.Js.t>> %}) to Eliom nodes ({% <<a_api | type Eliom_content.Html.elt>> %}). *) end val force_link : unit val set_client_fun : ?app:string -> service:('a, 'b, _, _, _, _, _, _, _, _, _) Eliom_service.t -> ('a -> 'b -> Eliom_service.result Lwt.t) -> unit val set_form_error_handler : (unit -> bool Lwt.t) -> unit * With [ set_form_error_handler f ] , [ f ] becomes the action to be called when we are unable to call a client - side service due to invalid form data . If the handler returns [ true ] , nothing happens . If the handler returns [ false ] , we proceed to call the server - side service . The default handler throws an exception ( via [ Lwt.fail_with ] ) . called when we are unable to call a client-side service due to invalid form data. If the handler returns [true], nothing happens. If the handler returns [false], we proceed to call the server-side service. The default handler throws an exception (via [Lwt.fail_with]). *)
cd1c2cb1ba96bd44dbec82fc5c655a9c921197bb8dade8e567ce9d888a9b761e
FranklinChen/hugs98-plus-Sep2006
Texturing.hs
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Texturing Copyright : ( c ) 2002 - 2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : -- Stability : provisional -- Portability : portable -- This module corresponds to section 3.8 ( Texturing ) of the OpenGL 1.5 specs . -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Texturing ( module Graphics.Rendering.OpenGL.GL.Texturing.Specification, module Graphics.Rendering.OpenGL.GL.Texturing.Parameters, module Graphics.Rendering.OpenGL.GL.Texturing.Objects, module Graphics.Rendering.OpenGL.GL.Texturing.Environments, module Graphics.Rendering.OpenGL.GL.Texturing.Application, module Graphics.Rendering.OpenGL.GL.Texturing.Queries ) where import Graphics.Rendering.OpenGL.GL.Texturing.Specification import Graphics.Rendering.OpenGL.GL.Texturing.Parameters import Graphics.Rendering.OpenGL.GL.Texturing.Objects import Graphics.Rendering.OpenGL.GL.Texturing.Environments import Graphics.Rendering.OpenGL.GL.Texturing.Application import Graphics.Rendering.OpenGL.GL.Texturing.Queries
null
https://raw.githubusercontent.com/FranklinChen/hugs98-plus-Sep2006/54ab69bd6313adbbed1d790b46aca2a0305ea67e/packages/OpenGL/Graphics/Rendering/OpenGL/GL/Texturing.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.Rendering.OpenGL.GL.Texturing License : BSD-style (see the file libraries/OpenGL/LICENSE) Maintainer : Stability : provisional Portability : portable ------------------------------------------------------------------------------
Copyright : ( c ) 2002 - 2005 This module corresponds to section 3.8 ( Texturing ) of the OpenGL 1.5 specs . module Graphics.Rendering.OpenGL.GL.Texturing ( module Graphics.Rendering.OpenGL.GL.Texturing.Specification, module Graphics.Rendering.OpenGL.GL.Texturing.Parameters, module Graphics.Rendering.OpenGL.GL.Texturing.Objects, module Graphics.Rendering.OpenGL.GL.Texturing.Environments, module Graphics.Rendering.OpenGL.GL.Texturing.Application, module Graphics.Rendering.OpenGL.GL.Texturing.Queries ) where import Graphics.Rendering.OpenGL.GL.Texturing.Specification import Graphics.Rendering.OpenGL.GL.Texturing.Parameters import Graphics.Rendering.OpenGL.GL.Texturing.Objects import Graphics.Rendering.OpenGL.GL.Texturing.Environments import Graphics.Rendering.OpenGL.GL.Texturing.Application import Graphics.Rendering.OpenGL.GL.Texturing.Queries
1c62603e76d00e7b549a9b96a89cfba67ffbbaa429e2b6de60c58c6d3caab118
DaMSL/K3
IndexedSet.hs
{-| This module defines routines and utilities associated with the creation and use of a data structure which is equivalent to a set but maintains a number of indexes for quick containment checks. The containment checks must be enumerated statically. -} module Language.K3.Utils.IndexedSet ( module X ) where import Language.K3.Utils.IndexedSet.Class as X import Language.K3.Utils.IndexedSet.TemplateHaskell as X
null
https://raw.githubusercontent.com/DaMSL/K3/51749157844e76ae79dba619116fc5ad9d685643/src/Language/K3/Utils/IndexedSet.hs
haskell
| This module defines routines and utilities associated with the creation and use of a data structure which is equivalent to a set but maintains a number of indexes for quick containment checks. The containment checks must be enumerated statically.
module Language.K3.Utils.IndexedSet ( module X ) where import Language.K3.Utils.IndexedSet.Class as X import Language.K3.Utils.IndexedSet.TemplateHaskell as X
52668ccfe107dce9783965dd780fd9f2926f00ebe9df72cef3fff228a8692a8a
ijvcms/chuanqi_dev
scene_pp.erl
%%%------------------------------------------------------------------- @author zhengsiying ( C ) 2015 , < COMPANY > %%% @doc %%% %%% @end Created : 31 . 七月 2015 下午3:43 %%%------------------------------------------------------------------- -module(scene_pp). %% -include("common.hrl"). -include("record.hrl"). -include("proto.hrl"). -include("config.hrl"). -include("cache.hrl"). -include("language_config.hrl"). -include("gameconfig_config.hrl"). -include("log_type_config.hrl"). %% API -export([ handle/3 ]). %% ==================================================================== %% API functions %% ==================================================================== %% 登陆游戏进入场景 handle(11001, PlayerState, _Data) -> scene_lib:scene_login(PlayerState, _Data); %% 开始移动 handle(11002, PlayerState, Data) -> ?INFO("11002 ~p", [{Data, util_date:longunixtime()}]), #player_state{ scene_pid = ScenePid, player_id = PlayerId } = PlayerState, #req_start_move{ begin_point = #proto_point{x = BX, y = BY}, end_point = #proto_point{x = EX, y = EY}, direction = Direction } = Data, case player_lib:can_action(PlayerState) of true -> scene_obj_lib:start_move(ScenePid, ?OBJ_TYPE_PLAYER, PlayerId, {BX, BY}, {EX, EY}, Direction); _ -> skip end, {ok, PlayerState}; %% 移动同步 handle(11003, PlayerState,_Data) -> ?INFO("11003 ~p", [{_Data, util_date:longunixtime()}]), %% #player_state{ scene_pid = ScenePid , player_id = } = PlayerState , %% #req_move_sync{ %% point = Point, %% direction = Direction %% } = Data, %% case player_lib:can_action(PlayerState) of %% true -> scene_obj_lib : move_sync(ScenePid , ? OBJ_TYPE_PLAYER , , { Point#proto_point.x , Point#proto_point.y } , Direction ) ; %% _ -> %% skip %% end, {ok, PlayerState}; %% 拾取掉落 handle(11006, PlayerState, Data) -> #player_state{ scene_pid = ScenePid, player_id = PlayerId, team_id = TeamId } = PlayerState, #req_pickup{ drop_id = DropId } = Data, DropType = DropId div ?DROP_SECTION_BASE_NUM, case player_lib:can_action(PlayerState) andalso (goods_lib:get_free_bag_num(PlayerState) > 0 orelse DropType =:= ?DROP_TYPE_MONEY) of true -> scene_obj_lib:pickup_drop(ScenePid, PlayerId, TeamId, DropId); _ -> skip end; 获取世界boss刷新时间 handle(11009, PlayerState, _Data) -> ProtoList = scene_lib:get_world_boss_ref_list(), net_send:send_to_client(PlayerState#player_state.socket, 11009, #rep_world_boss_refresh{refresh_list = ProtoList}), PlayerState1 = PlayerState#player_state{ is_world_boss_ui = true }, {ok, PlayerState1}; %% 获取打宝地图boss刷新时间 handle(11010, PlayerState, _Data) -> List = treasure_config:get_list(), CurTime = util_date:unixtime(), ProtoList = [ begin #treasure_conf{ scene_id = SceneId, boss_id = BossId } = treasure_config:get(Id), RefreshTime = case scene_mgr_lib:get_boss_refresh(SceneId, BossId) of #ets_boss_refresh{refresh_time = RT} = _EtsInfo -> max(RT - CurTime, 0); _ -> 0 end, #proto_boss_refresh{id = Id, refresh_time = RefreshTime} end || Id <- List], ?INFO("send data : ~p", [ProtoList]), net_send:send_to_client(PlayerState#player_state.socket, 11010, #rep_treasure_refresh{refresh_list = ProtoList}); %% 获取副本入口信息 handle(11013, PlayerState, Data) -> ?ERR("11013 ~p", [Data]), SceneId = Data#req_instance_entry_info.scene_id, SceneConf = scene_config:get(SceneId), case SceneConf#scene_conf.type of ?SCENE_TYPE_INSTANCE -> {PlayerState1, Times} = player_instance_lib:get_instance_enter_times(PlayerState, SceneId), InstanceConf = instance_config:get(SceneId), %% 获取自己购买的次数信息 BuyFbNum = counter_lib : get_value(PlayerState1#player_state.player_id,?COUNTER_FB_BUY_NUM ) , Times1 = InstanceConf#instance_conf.times_limit - Times, net_send:send_to_client(PlayerState1#player_state.socket, 11013, #rep_instance_entry_info{scene_id = SceneId, enter_times = Times1}), {ok, PlayerState1}; _ -> skip end; %% 获取副本场景统计 handle(11014, PlayerState, _Data) -> SceneId = PlayerState#player_state.scene_id, case is_number(SceneId) of true -> SceneConf = scene_config:get(SceneId), case SceneConf#scene_conf.type of ?SCENE_TYPE_INSTANCE -> ScenePid = PlayerState#player_state.scene_pid, case is_pid(ScenePid) of true -> instance_base_lib:get_instance_info(ScenePid, PlayerState#player_state.pid); _ -> skip end; _ -> skip end; _ -> skip end; %% 退出副本 handle(11016, PlayerState, _Data) -> %% ?ERR("recv 11016", []), scene_mgr_lib:exit_instance(PlayerState); %% 获取沙城活动信息 handle(11018, PlayerState, _Data) -> Data = scene_activity_shacheng_lib:get_rep_shacheng_info(), net_send:send_to_client(PlayerState#player_state.socket, 11018, Data); handle(11021, PlayerState, _Data) -> #player_state{ player_id = PlayerId, scene_pid = ScenePid, socket = Socket } = PlayerState, scene_obj_lib:find_monster(ScenePid, PlayerId, Socket); %% 传送阵传送协议 handle(11022, PlayerState, Data) -> ?INFO("11022 ~p", [Data]), case scene_obj_lib:transfer(PlayerState, Data#req_transfer.id) of {ok, PlayerState1} -> net_send:send_to_client(PlayerState1#player_state.socket, 11022, #rep_transfer{}), {ok, PlayerState1}; {fail, Err} -> net_send:send_to_client(PlayerState#player_state.socket, 11022, #rep_transfer{result = Err}); _ERR -> ?ERR("~p", [_ERR]) end; %% 场景地图标识 handle(11019, PlayerState, _Data) -> ScenePid = PlayerState#player_state.scene_pid, PlayerId = PlayerState#player_state.player_id, TeamId = PlayerState#player_state.team_id, Socket = PlayerState#player_state.socket, scene_send_lib:send_scene_teammate_flag(ScenePid, PlayerId, TeamId, Socket), {ok, PlayerState}; %% 传送点传送协议 handle(11024, PlayerState, Data) -> case cross_lib:transport(PlayerState, Data#req_transport.id) of {ok, PlayerState1} -> {ok, PlayerState1}; {fail, Err} -> net_send:send_to_client(PlayerState#player_state.socket, 11024, #rep_transport{result = Err}) end; %% 获取npc功能状态 handle(11025, PlayerState, Data) -> PlayerStateNew = scene_npc_lib:get_scene_npc_state(PlayerState, Data#req_get_npc_state.id), {ok, PlayerStateNew}; %% 获取新手状态信息 handle(11026, PlayerState, Data) -> Result = guide_lib:get_guide_state(PlayerState#player_state.player_id, Data#req_get_guide_state.guide_step_id), net_send:send_to_client(PlayerState#player_state.socket, 11026, #rep_get_guide_state{result = Result}); %% 快速传送登入场景 handle(11031, PlayerState, #req_quick_change_scene{scene_id = SceneId}) -> ? ERR("scene pp 11031 = = = = = = = = = = = = = = = = = = = > > > > > > > > > > > > > > > > : ~p ~ n " , [ SceneId ] ) , if SceneId =:= 32104 -> %%跨服暗殿 case active_instance_lib:check_wzad_cross_open(SceneId) of true -> cross_lib:change_scene_11031(PlayerState, SceneId, null, null); false -> net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_ACTIVE_NOT_OPEN}) end; (SceneId >= 31002 andalso SceneId =< 31004) orelse (SceneId >= 32109 andalso SceneId =< 32111) -> 跨服火龙 case active_instance_lib:check_dragon_cross_open(SceneId) of true -> cross_lib:change_scene_11031(PlayerState, SceneId, null, null); false -> net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_ACTIVE_NOT_OPEN}) end; true -> cross_lib:change_scene_11031(PlayerState, SceneId, null, null) end; %% 获取世界boss免费传送次数 handle(11032, PlayerState, _Data) -> PlayerId = PlayerState#player_state.player_id, DPB = PlayerState#player_state.db_player_base, VipLv = DPB#db_player_base.vip, Career = DPB#db_player_base.career, VipConf = vip_config:get(VipLv, Career), UseCount = counter_lib:get_value(PlayerId, ?COUNTER_WORLD_BOSS_TRANSFER), LimitCount = VipConf#vip_conf.boss_transfer, Count = LimitCount - UseCount, net_send:send_to_client(PlayerState#player_state.socket, 11032, #rep_get_free_transfer_num{num = Count}); %% 世界boss免费传送 handle(11033, PlayerState, #req_get_free_transfer{scene_id = SceneId}) -> %% PlayerId = PlayerState#player_state.player_id, %% DPB = PlayerState#player_state.db_player_base, %% VipLv = DPB#db_player_base.vip, Career = DPB#db_player_base.career , %% VipConf = vip_config:get(VipLv, Career), %% UseCount = counter_lib : get_value(PlayerId , ? ) , LimitCount = VipConf#vip_conf.boss_transfer , %% Count = LimitCount - UseCount, %% case Count > 0 of %% true -> WorldBossConf = world_boss_config : ) , WorldBossConf#world_boss_conf.scene_id , case scene_mgr_lib : change_scene(PlayerState , self ( ) , ) of %% {ok, PlayerState1} -> %% counter_lib:update(PlayerId, ?COUNTER_WORLD_BOSS_TRANSFER), %% {ok, PlayerState1}; %% _ -> { ok , PlayerState } %% end; %% false -> net_send : send_to_client(PlayerState#player_state.socket , 11033 , # rep_get_free_transfer{result = ? ERR_WORLD_BOSS_TRANSFER_NOT_ENOUGH } ) %% end; cross_lib:change_scene_11031(PlayerState, SceneId, {?ITEM_FLYING_SHOES, 1, ?LOG_TYPE_TRANSFER}, null); %% 获取副本列表 handle(11034, PlayerState, _Data) -> ?INFO("11034 ~p", [11034]), [FBList, PlayerState1] = player_instance_lib:get_instance_list(PlayerState), net_send:send_to_client(PlayerState#player_state.socket, 11034, #rep_get_fb_list{fb_list = FBList}), {ok, PlayerState1}; %% 购买副本次数 handle(11035, PlayerState, Data) -> SceneId = Data#req_buy_fb_num.scene_id, {PlayerState1, Result} = player_instance_lib:buy_fb_num(PlayerState, SceneId), net_send:send_to_client(PlayerState1#player_state.socket, 11035, #rep_buy_fb_num{result = Result}), {ok, PlayerState1}; %% 发送自己消息给其他玩家,获取其他玩家信息 handle(11037, PlayerState, _Data) -> Attr = PlayerState#player_state.db_player_attr, case Attr#db_player_attr.cur_hp < 1 of true -> player_pp:handle(10010, PlayerState, #req_player_die{}); _ -> skip end, scene_send_lib_copy:send_scene_info_data_all(PlayerState), PlayerState1 = PlayerState#player_state{ is_load_over = true }, {ok, PlayerState1}; %% 获取当前场景的线路信息 handle(11038, PlayerState, _Data) -> {SceneLineNum, NewList} = scene_lib:get_line_list(PlayerState), NewData = #rep_get_line_list{ now_line = SceneLineNum, line_info_list = NewList }, net_send:send_to_client(PlayerState#player_state.socket, 11038, NewData); %% 跳转到指定的线路 handle(11039, PlayerState, Data) -> LineNum = Data#req_change_scene_line.line, case is_integer(PlayerState#player_state.scene_id) of true -> SceneConf = scene_config:get(PlayerState#player_state.scene_id), case SceneConf#scene_conf.copy_num of 1 -> skip; _ -> case PlayerState#player_state.scene_line_num =:= LineNum of true -> {ok, PlayerState}; _ -> DbPlayerBase = PlayerState#player_state.db_player_base, #db_player_base{ scene_id = SceneId, x = X, y = Y } = DbPlayerBase, scene_mgr_lib:change_scene_line(PlayerState, PlayerState#player_state.pid, SceneId, ?CHANGE_SCENE_TYPE_CHANGE, {X, Y}, LineNum) end end; _ -> skip end; %% 跳转到指定的线路 handle(11040, PlayerState, _Data) -> List = player_foe_lib:get_foe_list_id(PlayerState#player_state.player_id), net_send:send_to_client(PlayerState#player_state.socket, 11040, #rep_get_foe_list{player_id_list = List}); %% 采集怪物 handle(11043, PlayerState, Data) -> #player_state{ scene_pid = ScenePid, player_id = PlayerId, db_player_base = DPB, pid = PlayerPid } = PlayerState, ObjId = Data#req_collection.id, FreeBag = goods_lib:get_free_bag_num(PlayerState), case player_lib:can_action(PlayerState) of true -> GuildId = DPB#db_player_base.guild_id, scene_obj_lib:collection(ScenePid, PlayerId, GuildId, PlayerPid, FreeBag, ObjId); _ -> net_send:send_to_client(PlayerPid, 11043, #rep_collection{result = ?ERR_COMMON_FAIL}) end; %% 离开bossui handle(11044, PlayerState, _Data) -> ?INFO("11044 ~p", [111]), PlayerState1 = PlayerState#player_state{ is_world_boss_ui = false }, {ok, PlayerState1}; handle(11045, PlayerState, _Data) -> scene_send_lib_copy:get_single_boss_result(PlayerState); handle(11046, PlayerState, _Data) -> player_monster_lib:monster_boss_drop(PlayerState); %% 获取副本场景统计 handle(11047, _PlayerState, _Data) -> null; %% 获取世界boss刷新时间和关注 handle(11048, PlayerState, #req_boss_time_and_follow{type = Type}) -> case Type of 1 -> ProtoList = scene_lib:get_world_boss_ref_follow_list(PlayerState#player_state.player_id), ? ERR("~p " , [ ProtoList ] ) , net_send:send_to_client(PlayerState#player_state.socket, 11048, #rep_boss_time_and_follow{type = Type, boss_list = ProtoList}), PlayerState1 = PlayerState#player_state{ is_world_boss_ui = true }, {ok, PlayerState1}; 2 -> ProtoList = scene_lib:get_vip_boss_ref_follow_list(PlayerState#player_state.player_id), net_send:send_to_client(PlayerState#player_state.socket, 11048, #rep_boss_time_and_follow{type = Type, boss_list = ProtoList}), {ok, PlayerState}; 5 -> ProtoList = scene_lib:get_single_boss_ref_list(PlayerState#player_state.player_id), net_send:send_to_client(PlayerState#player_state.socket, 11048, #rep_boss_time_and_follow{type = Type, boss_list = ProtoList}), {ok, PlayerState} end; handle(11050, PlayerState, _Data) -> player_monster_lib:city_boss_killers(PlayerState); %% 副本通关后继续留在副本中 handle(11051, PlayerState, _Data) -> scene_send_lib_copy:stay_scene(PlayerState); %% 副本通关后继续留在副本中 handle(11053, PlayerState, #req_guise_list{top = _Top}) -> #player_state{scene_pid = ScenePid, pid = PlayerPid, player_id = PlayerId} = PlayerState, scene_send_lib_copy:get_scene_guise(ScenePid, PlayerPid, PlayerId); handle(11054, PlayerState, Data) -> rpc:call(PlayerState#player_state.server_pass, scene_cross, proto_mod, [PlayerState, scene_pp, 11054, Data]); %% 合服地图相关判断 handle(11055, PlayerState, _Data) -> F = fun(X, List) -> case function_db:is_open_scene(X#word_map_conf.scene_id) of true -> List; _ -> MapInfo = #proto_word_map_info{ scene_id = X#word_map_conf.scene_id, state = 1 }, [MapInfo | List] end end, List1 = lists:foldl(F, [], word_map_config:get_list_conf()), Data1 = #rep_word_map_list{ map_info_list = List1 }, ?INFO("~p", [Data1]), net_send:send_to_client(PlayerState#player_state.socket, 11055, Data1); 更新玩家采集状态 handle(11060, PlayerState, Data) -> ?INFO("11060 ~p", [Data]), State = Data#req_update_collection_state.state, Upate = #player_state{collect_state = State}, player_lib:update_player_state(PlayerState, Upate); %% 请求变异地宫击杀boss数量 handle(11061, PlayerStatus, _Data) -> spec_palace_boss_mod:req_boss_info(PlayerStatus#player_state.pid), {ok, PlayerStatus}; %%************************************************************ %% 幻境之城 %%************************************************************ handle(11103, PlayerState, _Data) -> scene_hjzc_lib:get_hjzc_rank_list(PlayerState); %%获取玩家幻境之城的点亮信息 handle(11104, PlayerState, _Data) -> scene_hjzc_lib:get_hjzc_plyaer_info(PlayerState); %%获取玩家幻境之城的点亮信息 handle(11105, PlayerState, #req_hjzc_send_change{room_num = RoomNum}) -> cross_lib:hjzc_send_change_11105(PlayerState, RoomNum); handle(Cmd, PlayerState, Data) -> ?ERR("not define ~p cmd:~nstate: ~p~ndata: ~p", [Cmd, PlayerState, Data]), {ok, PlayerState}. %% ==================================================================== Internal functions %% ====================================================================
null
https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/business/scene/scene_pp.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API ==================================================================== API functions ==================================================================== 登陆游戏进入场景 开始移动 移动同步 #player_state{ #req_move_sync{ point = Point, direction = Direction } = Data, case player_lib:can_action(PlayerState) of true -> _ -> skip end, 拾取掉落 获取打宝地图boss刷新时间 获取副本入口信息 获取自己购买的次数信息 获取副本场景统计 退出副本 ?ERR("recv 11016", []), 获取沙城活动信息 传送阵传送协议 场景地图标识 传送点传送协议 获取npc功能状态 获取新手状态信息 快速传送登入场景 跨服暗殿 获取世界boss免费传送次数 世界boss免费传送 PlayerId = PlayerState#player_state.player_id, DPB = PlayerState#player_state.db_player_base, VipLv = DPB#db_player_base.vip, VipConf = vip_config:get(VipLv, Career), Count = LimitCount - UseCount, true -> {ok, PlayerState1} -> counter_lib:update(PlayerId, ?COUNTER_WORLD_BOSS_TRANSFER), {ok, PlayerState1}; _ -> end; false -> end; 获取副本列表 购买副本次数 发送自己消息给其他玩家,获取其他玩家信息 获取当前场景的线路信息 跳转到指定的线路 跳转到指定的线路 采集怪物 离开bossui 获取副本场景统计 获取世界boss刷新时间和关注 副本通关后继续留在副本中 副本通关后继续留在副本中 合服地图相关判断 请求变异地宫击杀boss数量 ************************************************************ 幻境之城 ************************************************************ 获取玩家幻境之城的点亮信息 获取玩家幻境之城的点亮信息 ==================================================================== ====================================================================
@author zhengsiying ( C ) 2015 , < COMPANY > Created : 31 . 七月 2015 下午3:43 -module(scene_pp). -include("common.hrl"). -include("record.hrl"). -include("proto.hrl"). -include("config.hrl"). -include("cache.hrl"). -include("language_config.hrl"). -include("gameconfig_config.hrl"). -include("log_type_config.hrl"). -export([ handle/3 ]). handle(11001, PlayerState, _Data) -> scene_lib:scene_login(PlayerState, _Data); handle(11002, PlayerState, Data) -> ?INFO("11002 ~p", [{Data, util_date:longunixtime()}]), #player_state{ scene_pid = ScenePid, player_id = PlayerId } = PlayerState, #req_start_move{ begin_point = #proto_point{x = BX, y = BY}, end_point = #proto_point{x = EX, y = EY}, direction = Direction } = Data, case player_lib:can_action(PlayerState) of true -> scene_obj_lib:start_move(ScenePid, ?OBJ_TYPE_PLAYER, PlayerId, {BX, BY}, {EX, EY}, Direction); _ -> skip end, {ok, PlayerState}; handle(11003, PlayerState,_Data) -> ?INFO("11003 ~p", [{_Data, util_date:longunixtime()}]), scene_pid = ScenePid , player_id = } = PlayerState , scene_obj_lib : move_sync(ScenePid , ? OBJ_TYPE_PLAYER , , { Point#proto_point.x , Point#proto_point.y } , Direction ) ; {ok, PlayerState}; handle(11006, PlayerState, Data) -> #player_state{ scene_pid = ScenePid, player_id = PlayerId, team_id = TeamId } = PlayerState, #req_pickup{ drop_id = DropId } = Data, DropType = DropId div ?DROP_SECTION_BASE_NUM, case player_lib:can_action(PlayerState) andalso (goods_lib:get_free_bag_num(PlayerState) > 0 orelse DropType =:= ?DROP_TYPE_MONEY) of true -> scene_obj_lib:pickup_drop(ScenePid, PlayerId, TeamId, DropId); _ -> skip end; 获取世界boss刷新时间 handle(11009, PlayerState, _Data) -> ProtoList = scene_lib:get_world_boss_ref_list(), net_send:send_to_client(PlayerState#player_state.socket, 11009, #rep_world_boss_refresh{refresh_list = ProtoList}), PlayerState1 = PlayerState#player_state{ is_world_boss_ui = true }, {ok, PlayerState1}; handle(11010, PlayerState, _Data) -> List = treasure_config:get_list(), CurTime = util_date:unixtime(), ProtoList = [ begin #treasure_conf{ scene_id = SceneId, boss_id = BossId } = treasure_config:get(Id), RefreshTime = case scene_mgr_lib:get_boss_refresh(SceneId, BossId) of #ets_boss_refresh{refresh_time = RT} = _EtsInfo -> max(RT - CurTime, 0); _ -> 0 end, #proto_boss_refresh{id = Id, refresh_time = RefreshTime} end || Id <- List], ?INFO("send data : ~p", [ProtoList]), net_send:send_to_client(PlayerState#player_state.socket, 11010, #rep_treasure_refresh{refresh_list = ProtoList}); handle(11013, PlayerState, Data) -> ?ERR("11013 ~p", [Data]), SceneId = Data#req_instance_entry_info.scene_id, SceneConf = scene_config:get(SceneId), case SceneConf#scene_conf.type of ?SCENE_TYPE_INSTANCE -> {PlayerState1, Times} = player_instance_lib:get_instance_enter_times(PlayerState, SceneId), InstanceConf = instance_config:get(SceneId), BuyFbNum = counter_lib : get_value(PlayerState1#player_state.player_id,?COUNTER_FB_BUY_NUM ) , Times1 = InstanceConf#instance_conf.times_limit - Times, net_send:send_to_client(PlayerState1#player_state.socket, 11013, #rep_instance_entry_info{scene_id = SceneId, enter_times = Times1}), {ok, PlayerState1}; _ -> skip end; handle(11014, PlayerState, _Data) -> SceneId = PlayerState#player_state.scene_id, case is_number(SceneId) of true -> SceneConf = scene_config:get(SceneId), case SceneConf#scene_conf.type of ?SCENE_TYPE_INSTANCE -> ScenePid = PlayerState#player_state.scene_pid, case is_pid(ScenePid) of true -> instance_base_lib:get_instance_info(ScenePid, PlayerState#player_state.pid); _ -> skip end; _ -> skip end; _ -> skip end; handle(11016, PlayerState, _Data) -> scene_mgr_lib:exit_instance(PlayerState); handle(11018, PlayerState, _Data) -> Data = scene_activity_shacheng_lib:get_rep_shacheng_info(), net_send:send_to_client(PlayerState#player_state.socket, 11018, Data); handle(11021, PlayerState, _Data) -> #player_state{ player_id = PlayerId, scene_pid = ScenePid, socket = Socket } = PlayerState, scene_obj_lib:find_monster(ScenePid, PlayerId, Socket); handle(11022, PlayerState, Data) -> ?INFO("11022 ~p", [Data]), case scene_obj_lib:transfer(PlayerState, Data#req_transfer.id) of {ok, PlayerState1} -> net_send:send_to_client(PlayerState1#player_state.socket, 11022, #rep_transfer{}), {ok, PlayerState1}; {fail, Err} -> net_send:send_to_client(PlayerState#player_state.socket, 11022, #rep_transfer{result = Err}); _ERR -> ?ERR("~p", [_ERR]) end; handle(11019, PlayerState, _Data) -> ScenePid = PlayerState#player_state.scene_pid, PlayerId = PlayerState#player_state.player_id, TeamId = PlayerState#player_state.team_id, Socket = PlayerState#player_state.socket, scene_send_lib:send_scene_teammate_flag(ScenePid, PlayerId, TeamId, Socket), {ok, PlayerState}; handle(11024, PlayerState, Data) -> case cross_lib:transport(PlayerState, Data#req_transport.id) of {ok, PlayerState1} -> {ok, PlayerState1}; {fail, Err} -> net_send:send_to_client(PlayerState#player_state.socket, 11024, #rep_transport{result = Err}) end; handle(11025, PlayerState, Data) -> PlayerStateNew = scene_npc_lib:get_scene_npc_state(PlayerState, Data#req_get_npc_state.id), {ok, PlayerStateNew}; handle(11026, PlayerState, Data) -> Result = guide_lib:get_guide_state(PlayerState#player_state.player_id, Data#req_get_guide_state.guide_step_id), net_send:send_to_client(PlayerState#player_state.socket, 11026, #rep_get_guide_state{result = Result}); handle(11031, PlayerState, #req_quick_change_scene{scene_id = SceneId}) -> ? ERR("scene pp 11031 = = = = = = = = = = = = = = = = = = = > > > > > > > > > > > > > > > > : ~p ~ n " , [ SceneId ] ) , if SceneId =:= 32104 -> case active_instance_lib:check_wzad_cross_open(SceneId) of true -> cross_lib:change_scene_11031(PlayerState, SceneId, null, null); false -> net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_ACTIVE_NOT_OPEN}) end; (SceneId >= 31002 andalso SceneId =< 31004) orelse (SceneId >= 32109 andalso SceneId =< 32111) -> 跨服火龙 case active_instance_lib:check_dragon_cross_open(SceneId) of true -> cross_lib:change_scene_11031(PlayerState, SceneId, null, null); false -> net_send:send_to_client(PlayerState#player_state.socket, 11001, #rep_change_scene{result = ?ERR_ACTIVE_NOT_OPEN}) end; true -> cross_lib:change_scene_11031(PlayerState, SceneId, null, null) end; handle(11032, PlayerState, _Data) -> PlayerId = PlayerState#player_state.player_id, DPB = PlayerState#player_state.db_player_base, VipLv = DPB#db_player_base.vip, Career = DPB#db_player_base.career, VipConf = vip_config:get(VipLv, Career), UseCount = counter_lib:get_value(PlayerId, ?COUNTER_WORLD_BOSS_TRANSFER), LimitCount = VipConf#vip_conf.boss_transfer, Count = LimitCount - UseCount, net_send:send_to_client(PlayerState#player_state.socket, 11032, #rep_get_free_transfer_num{num = Count}); handle(11033, PlayerState, #req_get_free_transfer{scene_id = SceneId}) -> Career = DPB#db_player_base.career , UseCount = counter_lib : get_value(PlayerId , ? ) , LimitCount = VipConf#vip_conf.boss_transfer , case Count > 0 of WorldBossConf = world_boss_config : ) , WorldBossConf#world_boss_conf.scene_id , case scene_mgr_lib : change_scene(PlayerState , self ( ) , ) of { ok , PlayerState } net_send : send_to_client(PlayerState#player_state.socket , 11033 , # rep_get_free_transfer{result = ? ERR_WORLD_BOSS_TRANSFER_NOT_ENOUGH } ) cross_lib:change_scene_11031(PlayerState, SceneId, {?ITEM_FLYING_SHOES, 1, ?LOG_TYPE_TRANSFER}, null); handle(11034, PlayerState, _Data) -> ?INFO("11034 ~p", [11034]), [FBList, PlayerState1] = player_instance_lib:get_instance_list(PlayerState), net_send:send_to_client(PlayerState#player_state.socket, 11034, #rep_get_fb_list{fb_list = FBList}), {ok, PlayerState1}; handle(11035, PlayerState, Data) -> SceneId = Data#req_buy_fb_num.scene_id, {PlayerState1, Result} = player_instance_lib:buy_fb_num(PlayerState, SceneId), net_send:send_to_client(PlayerState1#player_state.socket, 11035, #rep_buy_fb_num{result = Result}), {ok, PlayerState1}; handle(11037, PlayerState, _Data) -> Attr = PlayerState#player_state.db_player_attr, case Attr#db_player_attr.cur_hp < 1 of true -> player_pp:handle(10010, PlayerState, #req_player_die{}); _ -> skip end, scene_send_lib_copy:send_scene_info_data_all(PlayerState), PlayerState1 = PlayerState#player_state{ is_load_over = true }, {ok, PlayerState1}; handle(11038, PlayerState, _Data) -> {SceneLineNum, NewList} = scene_lib:get_line_list(PlayerState), NewData = #rep_get_line_list{ now_line = SceneLineNum, line_info_list = NewList }, net_send:send_to_client(PlayerState#player_state.socket, 11038, NewData); handle(11039, PlayerState, Data) -> LineNum = Data#req_change_scene_line.line, case is_integer(PlayerState#player_state.scene_id) of true -> SceneConf = scene_config:get(PlayerState#player_state.scene_id), case SceneConf#scene_conf.copy_num of 1 -> skip; _ -> case PlayerState#player_state.scene_line_num =:= LineNum of true -> {ok, PlayerState}; _ -> DbPlayerBase = PlayerState#player_state.db_player_base, #db_player_base{ scene_id = SceneId, x = X, y = Y } = DbPlayerBase, scene_mgr_lib:change_scene_line(PlayerState, PlayerState#player_state.pid, SceneId, ?CHANGE_SCENE_TYPE_CHANGE, {X, Y}, LineNum) end end; _ -> skip end; handle(11040, PlayerState, _Data) -> List = player_foe_lib:get_foe_list_id(PlayerState#player_state.player_id), net_send:send_to_client(PlayerState#player_state.socket, 11040, #rep_get_foe_list{player_id_list = List}); handle(11043, PlayerState, Data) -> #player_state{ scene_pid = ScenePid, player_id = PlayerId, db_player_base = DPB, pid = PlayerPid } = PlayerState, ObjId = Data#req_collection.id, FreeBag = goods_lib:get_free_bag_num(PlayerState), case player_lib:can_action(PlayerState) of true -> GuildId = DPB#db_player_base.guild_id, scene_obj_lib:collection(ScenePid, PlayerId, GuildId, PlayerPid, FreeBag, ObjId); _ -> net_send:send_to_client(PlayerPid, 11043, #rep_collection{result = ?ERR_COMMON_FAIL}) end; handle(11044, PlayerState, _Data) -> ?INFO("11044 ~p", [111]), PlayerState1 = PlayerState#player_state{ is_world_boss_ui = false }, {ok, PlayerState1}; handle(11045, PlayerState, _Data) -> scene_send_lib_copy:get_single_boss_result(PlayerState); handle(11046, PlayerState, _Data) -> player_monster_lib:monster_boss_drop(PlayerState); handle(11047, _PlayerState, _Data) -> null; handle(11048, PlayerState, #req_boss_time_and_follow{type = Type}) -> case Type of 1 -> ProtoList = scene_lib:get_world_boss_ref_follow_list(PlayerState#player_state.player_id), ? ERR("~p " , [ ProtoList ] ) , net_send:send_to_client(PlayerState#player_state.socket, 11048, #rep_boss_time_and_follow{type = Type, boss_list = ProtoList}), PlayerState1 = PlayerState#player_state{ is_world_boss_ui = true }, {ok, PlayerState1}; 2 -> ProtoList = scene_lib:get_vip_boss_ref_follow_list(PlayerState#player_state.player_id), net_send:send_to_client(PlayerState#player_state.socket, 11048, #rep_boss_time_and_follow{type = Type, boss_list = ProtoList}), {ok, PlayerState}; 5 -> ProtoList = scene_lib:get_single_boss_ref_list(PlayerState#player_state.player_id), net_send:send_to_client(PlayerState#player_state.socket, 11048, #rep_boss_time_and_follow{type = Type, boss_list = ProtoList}), {ok, PlayerState} end; handle(11050, PlayerState, _Data) -> player_monster_lib:city_boss_killers(PlayerState); handle(11051, PlayerState, _Data) -> scene_send_lib_copy:stay_scene(PlayerState); handle(11053, PlayerState, #req_guise_list{top = _Top}) -> #player_state{scene_pid = ScenePid, pid = PlayerPid, player_id = PlayerId} = PlayerState, scene_send_lib_copy:get_scene_guise(ScenePid, PlayerPid, PlayerId); handle(11054, PlayerState, Data) -> rpc:call(PlayerState#player_state.server_pass, scene_cross, proto_mod, [PlayerState, scene_pp, 11054, Data]); handle(11055, PlayerState, _Data) -> F = fun(X, List) -> case function_db:is_open_scene(X#word_map_conf.scene_id) of true -> List; _ -> MapInfo = #proto_word_map_info{ scene_id = X#word_map_conf.scene_id, state = 1 }, [MapInfo | List] end end, List1 = lists:foldl(F, [], word_map_config:get_list_conf()), Data1 = #rep_word_map_list{ map_info_list = List1 }, ?INFO("~p", [Data1]), net_send:send_to_client(PlayerState#player_state.socket, 11055, Data1); 更新玩家采集状态 handle(11060, PlayerState, Data) -> ?INFO("11060 ~p", [Data]), State = Data#req_update_collection_state.state, Upate = #player_state{collect_state = State}, player_lib:update_player_state(PlayerState, Upate); handle(11061, PlayerStatus, _Data) -> spec_palace_boss_mod:req_boss_info(PlayerStatus#player_state.pid), {ok, PlayerStatus}; handle(11103, PlayerState, _Data) -> scene_hjzc_lib:get_hjzc_rank_list(PlayerState); handle(11104, PlayerState, _Data) -> scene_hjzc_lib:get_hjzc_plyaer_info(PlayerState); handle(11105, PlayerState, #req_hjzc_send_change{room_num = RoomNum}) -> cross_lib:hjzc_send_change_11105(PlayerState, RoomNum); handle(Cmd, PlayerState, Data) -> ?ERR("not define ~p cmd:~nstate: ~p~ndata: ~p", [Cmd, PlayerState, Data]), {ok, PlayerState}. Internal functions
eaf4057b9abc6bfc255251d271948a15b93bbb7e42792c697c7de4d42c0da953
kana-sama/sicp
2.23 - for-each.scm
(define (for-each fn seq) (let loop ((seq seq)) (if (null? seq) #!unspecific (begin (fn (car seq)) (loop (cdr seq)))))) (print (for-each print (list 1 2 3)))
null
https://raw.githubusercontent.com/kana-sama/sicp/fc637d4b057cfcae1bae3d72ebc08e1af52e619d/2/2.23%20-%20for-each.scm
scheme
(define (for-each fn seq) (let loop ((seq seq)) (if (null? seq) #!unspecific (begin (fn (car seq)) (loop (cdr seq)))))) (print (for-each print (list 1 2 3)))
6bc8ea5ebbffb37882990c1423dd3e31a88d501a1e771aad9e170b00509440aa
dharmatech/abstracting
source.scm
(case scheme-implementation ((ypsilon) (require-lib "glut/ypsilon")) ((larceny) (require-lib "glut/larceny")) ((ikarus) (require-lib "glut/ikarus")) ((chicken) (require-lib "glut/chicken")) ((gambit) (load (string-append abstracting-root-directory "/support/gambit/glut/glut"))) )
null
https://raw.githubusercontent.com/dharmatech/abstracting/9dc5d9f45a9de03c6ee379f1928ebb393dfafc52/ext/glut/source.scm
scheme
(case scheme-implementation ((ypsilon) (require-lib "glut/ypsilon")) ((larceny) (require-lib "glut/larceny")) ((ikarus) (require-lib "glut/ikarus")) ((chicken) (require-lib "glut/chicken")) ((gambit) (load (string-append abstracting-root-directory "/support/gambit/glut/glut"))) )
7f88a4b29b1eeaf49b6272ff0bc9542cc2700c34df84b2cdb9330f42f4d57546
deadpendency/deadpendency
StreamQueueMessagesRequest.hs
module SR.Effect.StreamQueueMessages.Model.StreamQueueMessagesRequest ( StreamQueueMessagesRequest (..), ) where data StreamQueueMessagesRequest = StreamQueueMessagesRequest { _pullDlqSubscriptionId :: Text, _pullMainTopic :: Text } deriving stock (Eq, Show, Generic)
null
https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/script-runner/src/SR/Effect/StreamQueueMessages/Model/StreamQueueMessagesRequest.hs
haskell
module SR.Effect.StreamQueueMessages.Model.StreamQueueMessagesRequest ( StreamQueueMessagesRequest (..), ) where data StreamQueueMessagesRequest = StreamQueueMessagesRequest { _pullDlqSubscriptionId :: Text, _pullMainTopic :: Text } deriving stock (Eq, Show, Generic)
aeb19140a1c4ed2be6b4b15fb24016f4391fa2ec170f251cee859716dd047421
michaxm/task-distribution
TaskDefinition.hs
# LANGUAGE DeriveDataTypeable , DeriveGeneric # module Control.Distributed.Task.TaskSpawning.TaskDefinition where import Control.Distributed.Process.Serializable (Serializable) import Data.Binary (Binary) import Data.ByteString.Lazy (ByteString) import Data.Typeable (Typeable) import GHC.Generics (Generic) import Control.Distributed.Task.Types.HdfsConfigTypes The way how code is to be distributed . The approaches have different disadvantages : - source code : very limited type checking , breaks integration of code in regular program - function serialization : special entry point in Main necessary - object code distribution : requires compilation intermediate result , cumbersome to add required libs / modules The way how code is to be distributed. The approaches have different disadvantages: - source code: very limited type checking, breaks integration of code in regular program - function serialization: special entry point in Main necessary - object code distribution: requires compilation intermediate result, cumbersome to add required libs/modules -} data TaskDef = SourceCodeModule { _moduleName :: String, _moduleContent :: String } | DeployFullBinary { _deployable :: ByteString } | PreparedDeployFullBinary { _preparedFullBinaryHash :: Int } | UnevaluatedThunk { _unevaluatedThunk :: ByteString, _deployable :: ByteString } | ObjectCodeModule { _objectCode :: ByteString } deriving (Typeable, Generic) instance Binary TaskDef instance Serializable TaskDef {- Where data comes from: - hdfs data source - very simple file format for testing purposes, files with numbers expected relative to work directory -} data DataDef = HdfsData { _hdfsInputPath :: HdfsPath } | PseudoDB { _pseudoDBFilePath :: FilePath } deriving (Typeable, Generic) instance Binary DataDef instance Serializable DataDef {- Where calculation results go: - simply respond the answer, aggregation happens on master application - only num results: for testing/benchmarking purposes -} data ResultDef = ReturnAsMessage | ReturnOnlyNumResults | HdfsResult { _outputPrefix :: String, _outputSuffix :: String, _outputZipped :: Bool } deriving (Typeable, Generic) instance Binary ResultDef instance Serializable ResultDef
null
https://raw.githubusercontent.com/michaxm/task-distribution/d0dee6a661390b7d1279389fa8c7b711309dab6a/src/Control/Distributed/Task/TaskSpawning/TaskDefinition.hs
haskell
Where data comes from: - hdfs data source - very simple file format for testing purposes, files with numbers expected relative to work directory Where calculation results go: - simply respond the answer, aggregation happens on master application - only num results: for testing/benchmarking purposes
# LANGUAGE DeriveDataTypeable , DeriveGeneric # module Control.Distributed.Task.TaskSpawning.TaskDefinition where import Control.Distributed.Process.Serializable (Serializable) import Data.Binary (Binary) import Data.ByteString.Lazy (ByteString) import Data.Typeable (Typeable) import GHC.Generics (Generic) import Control.Distributed.Task.Types.HdfsConfigTypes The way how code is to be distributed . The approaches have different disadvantages : - source code : very limited type checking , breaks integration of code in regular program - function serialization : special entry point in Main necessary - object code distribution : requires compilation intermediate result , cumbersome to add required libs / modules The way how code is to be distributed. The approaches have different disadvantages: - source code: very limited type checking, breaks integration of code in regular program - function serialization: special entry point in Main necessary - object code distribution: requires compilation intermediate result, cumbersome to add required libs/modules -} data TaskDef = SourceCodeModule { _moduleName :: String, _moduleContent :: String } | DeployFullBinary { _deployable :: ByteString } | PreparedDeployFullBinary { _preparedFullBinaryHash :: Int } | UnevaluatedThunk { _unevaluatedThunk :: ByteString, _deployable :: ByteString } | ObjectCodeModule { _objectCode :: ByteString } deriving (Typeable, Generic) instance Binary TaskDef instance Serializable TaskDef data DataDef = HdfsData { _hdfsInputPath :: HdfsPath } | PseudoDB { _pseudoDBFilePath :: FilePath } deriving (Typeable, Generic) instance Binary DataDef instance Serializable DataDef data ResultDef = ReturnAsMessage | ReturnOnlyNumResults | HdfsResult { _outputPrefix :: String, _outputSuffix :: String, _outputZipped :: Bool } deriving (Typeable, Generic) instance Binary ResultDef instance Serializable ResultDef
53fd7caa42cd1c8853774eeb83c0160988fb4f6619ca26df42cca8bc0cf0ea3b
linuxscout/festival-tts-arabic-voices
clustergen.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; Carnegie Mellon University ; ; Copyright ( c ) 2005 - 2011 ; ; All Rights Reserved . ; ; ;;; ;; ;;; Permission is hereby granted, free of charge, to use and distribute ;; ;;; this software and its documentation without restriction, including ;; ;;; without limitation the rights to use, copy, modify, merge, publish, ;; ;;; distribute, sublicense, and/or sell copies of this work, and to ;; ;;; permit persons to whom this work is furnished to do so, subject to ;; ;;; the following conditions: ;; ;;; 1. The code must retain the above copyright notice, this list of ;; ;;; conditions and the following disclaimer. ;; ;;; 2. Any modifications must be clearly marked as such. ;; 3 . Original authors ' names are not deleted . ; ; ;;; 4. The authors' names are not used to endorse or promote products ;; ;;; derived from this software without specific prior written ;; ;;; permission. ;; ;;; ;; CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;; ;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO ;; EVENT SHALL CARNEGIE MELLON UNIVERSITY NOR ; ; ;;; LIABLE FOR ANY SPECIAL, 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 ; ; ;;; ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR ;; ;;; PERFORMANCE OF THIS SOFTWARE. ;; ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; Author : ( ) Nov 2005 ; ; ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; Run Time Synthesis support for ( HMM - generation ) voices ; ; ;;; ;; ;;; This is voice-independant, and should be in festival/lib but is ;; ;;; currently copied into each voice's festvox/ directory ;; ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar cluster_synth_pre_hooks nil) (defvar cluster_synth_post_hooks nil) (defvar clustergen_mcep_trees nil) (defvar cg:initial_frame_offset 0.0) (defvar cg:frame_shift 0.005) (set! mlsa_beta_param 0.4) (set! cg:mlsa_lpf t) (set! framerate 16000) (cond ;; This mapping should match that in do_clustergen for mcep_sptk_deltas ((equal? framerate 8000) (set! mlsa_alpha_param 0.312)) ((equal? framerate 11025) (set! mlsa_alpha_param 0.357)) ((equal? framerate 16000) (set! mlsa_alpha_param 0.42)) ((equal? framerate 22050) (set! mlsa_alpha_param 0.455)) ((equal? framerate 32000) (set! mlsa_alpha_param 0.504)) ((equal? framerate 44100) (set! mlsa_alpha_param 0.544)) ((equal? framerate 48000) (set! mlsa_alpha_param 0.554)) (t (format t "Unknown framerate %d for mlsa_alpha_param\n" framerate) (exit))) (set! mcep_length 25) deltas / mlpg (defvar cg:F0_smooth t) (set! cg:F0_interpolate t) ;; spline interpolation not as good as mlpg (defvar cg:mlpg t) (defvar cg:gv nil) (defvar cg:vuv nil) (defvar cg:with_v t) (defvar cg:deltas t) (defvar cg:debug nil) (defvar cg:save_param_track nil) (set! cg:multimodel nil) ;; probably doesn't work any more! (set! cg:mcep_clustersize 50) random forests , set this to 20 to get 20 rfs (defvar cg:rfs_models nil) ;; will get loaded at synthesis time (set! cg:rfs_dur nil) ;; random forests for duration (defvar cg:rfs_dur_models nil) ;; will get loaded at synthesis time (defvar cg:gmm_transform nil) (set! cg:mixed_excitation nil) (set! cg:spamf0 nil) (set! cg:spamf0_viterbi nil) (set! cg:vuv_predict_dump nil) (defvar me_filter_track nil) (defvar lpf_track nil) Set (set! cg:phrasyn nil) (set! cg:phrasyn_grammar_ntcount 10) (set! cg:phrasyn_mode 'pos) ;(set! cg:phrasyn_mode 'gpos) (if cg:spamf0 (require 'spamf0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; The main CG synthesis voice , voices using CG should set ;; (Parameter.set 'Synth_Method 'ClusterGen) which is done in INST_LANG_VOX_cg.scm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defSynthType ClusterGen (apply_hooks cluster_synth_pre_hooks utt) (set! clustergen_utt utt) ;; a global variable for debugging ;; Build the state relation (ClusterGen_make_HMMstate utt) ;; Predict number of frames (ClusterGen_make_mcep utt) ;; durations for # of vectors ;; Then predict the frame values (if (assoc 'cg::trajectory clustergen_mcep_trees) predict trajectory ( or ola ) (ClusterGen_predict_mcep utt) ;; predict vector types ) ( ClusterGen_predict_cgv utt ) ; ; predict vectors by Convert predicted mcep track into a waveform (if cg:gmm_transform GMM ( MLPG again ) and MLSA ) (if cg:spamf0 (set! utt (spamf0_utt utt)) ) standard MLSA only (if cg:save_param_track (track.save (utt.feat utt "param_track") "param.track")) (apply_hooks cluster_synth_post_hooks utt) utt ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Various waveform resynthesis wraparound functions ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (cg_wave_synth_external utt) ;; before we had it built-in to Festival (let ((trackname (make_tmp_filename)) (wavename (make_tmp_filename)) ) (track.save (utt.feat utt "param_track") trackname "est") (system (format nil "$FESTVOXDIR/src/clustergen/cg_resynth %s %s" trackname wavename)) (utt.import.wave utt wavename) (delete-file trackname) (delete-file wavename) utt) ) (define (cg_wave_synth utt) (utt.relation.create utt 'Wave) (if cg:mixed_excitation (item.set_feat (utt.relation.append utt 'Wave) "wave" (mlsa_resynthesis (utt.feat utt "param_track") (utt.feat utt "str_params") me_filter_track)) ;; Not mixed excitation (item.set_feat (utt.relation.append utt 'Wave) "wave" (mlsa_resynthesis (utt.feat utt "param_track") nil lpf_track))) utt) (define (cg_wave_synth_sptk utt) ;; before we had it built-in to Festival (let ((trackname (make_tmp_filename)) (wavename (make_tmp_filename)) ) (track.save (utt.feat utt "param_track") trackname "est") (system (format nil "$FESTVOXDIR/src/clustergen/cg_mlsa2 %s %s" trackname wavename)) (utt.import.wave utt wavename) (delete-file trackname) (delete-file wavename) utt) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CGA is a basic voice morphing / adaptation technique using cg -- ;; it is very much experimental and incomplete ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (cg_wave_synth_cga utt) Use loaded cga model to predict a new map_track (format t "In Synth CGA\n") (cga:create_map utt) ;; generate map_track (cga:predict_map utt) (utt.relation.create utt 'Wave) (item.set_feat (utt.relation.append utt 'Wave) "wave" (mlsa_resynthesis (utt.feat utt "map_track"))) utt) (define (cga:create_map utt) ;; predict the map_param converted parameters ;; Need to do better duration stuff (set! map_track (track.copy (utt.feat utt "param_track"))) (utt.set_feat utt "map_track" map_track) (utt.relation.create utt "param_map") (utt.relation.create utt "param_map_link") (set! pseg (utt.relation.first utt "mcep")) (set! m 0) (while pseg (set! mcep_parent (utt.relation.append utt "param_map_link" pseg)) (set! mseg (utt.relation.append utt "param_map")) (item.append_daughter mcep_parent mseg) (item.set_feat mseg "frame_number" m) (item.set_feat mseg "name" (item.feat mseg "R:param_map_link.parent.name")) (set! m (+ 1 m)) (set! pseg (item.next pseg))) utt ) (define (cga:predict_map utt) (let (i j f map_track num_channels s_f0_mean s_f0_stddev t_f0_mean t_f0_stddev) (set! i 0) (set! map_track (utt.feat utt "map_track")) (set! num_channels (track.num_channels map_track)) (set! s_f0_mean (get_param 'cga::source_f0_mean clustergen_cga_trees 140)) (set! s_f0_stddev (get_param 'cga::source_f0_stddev clustergen_cga_trees 20)) (set! t_f0_mean (get_param 'cga::target_f0_mean clustergen_cga_trees 140)) (set! t_f0_stddev (get_param 'cga::target_f0_stddev clustergen_cga_trees 20)) (mapcar (lambda (x) (let ((map_tree (assoc_string (item.name x) clustergen_cga_trees))) (if (null map_tree) (format t "ClusterGenCGA: can't find cluster tree for %s\n" (item.name x)) (begin (set! frame (wagon x (cadr map_tree))) ;; Convert f0 (if (> (track.get map_track i 0) 0) (track.set map_track i 0 (+ t_f0_mean (* t_f0_stddev (/ (- (track.get map_track i 0) s_f0_mean) s_f0_stddev))))) (set! j 1) (set! f (car frame)) (while (< j num_channels) (track.set map_track i j (track.get clustergen_cga_vectors f (* 2 j))) (set! j (+ 1 j))))) (set! i (+ 1 i)))) (utt.relation.items utt "param_map")) utt)) (define (ClusterGen_predict_states seg) ;; The names may change (cdr (assoc_string (item.name seg) phone_to_states))) (define (ClusterGen_make_HMMstate utt) (let ((states) (segstate) (statepos)) Make HMMstate relation and items ( three per phone ) (utt.relation.create utt "HMMstate") (utt.relation.create utt "segstate") (mapcar (lambda (seg) (set! statepos 1) (set! states (ClusterGen_predict_states seg)) (set! segstate (utt.relation.append utt 'segstate seg)) (while states (set! state (utt.relation.append utt 'HMMstate)) (item.append_daughter segstate state) (item.set_feat state "name" (car states)) (item.set_feat state "statepos" statepos) (set! statepos (+ 1 statepos)) (set! states (cdr states))) ) (utt.relation.items utt 'Segment)) ) ) (define (CG_predict_state_duration state) (if cg:rfs_dur ;; Random forest prediction (/ (apply + (mapcar (lambda (dm) (wagon_predict state dm)) cg:rfs_dur_models)) (length cg:rfs_dur_models)) ;; single model (wagon_predict state duration_cart_tree_cg) )) (define (ClusterGen_state_duration state) (let ((zdur (CG_predict_state_duration state)) (ph_info (assoc_string (item.name state) duration_ph_info_cg)) (seg_stretch (item.feat state "R:segstate.parent.dur_stretch")) (syl_stretch (item.feat state "R:segstate.parent.R:SylStructure.parent.dur_stretch")) (tok_stretch (parse-number (item.feat state "R:segstate.parent.R:SylStructure.parent.parent.R:Token.parent.dur_stretch"))) (global_stretch (Parameter.get 'Duration_Stretch)) (stretch 1.0)) (if (string-matches (item.name state) "pau_.*") ;; Its a pau so explicitly set the duration ;; Note we want sentence internal pauses to be about 100ms and sentence final pauses to be 150ms , but there will also sentence initial pauses of 150ms so we can treat all pauses as 100ms , there are three states so we use 50ms (set! zdur (/ (- 0.05 (car (cdr ph_info))) (car (cdr (cdr ph_info)))))) (if (not (string-equal seg_stretch "0")) (setq stretch (* stretch seg_stretch))) (if (not (string-equal syl_stretch "0")) (setq stretch (* stretch syl_stretch))) (if (not (string-equal tok_stretch "0")) (setq stretch (* stretch tok_stretch))) (if (not (string-equal global_stretch "0")) (setq stretch (* stretch global_stretch))) (if ph_info (* stretch (+ (car (cdr ph_info)) ;; mean (* (car (cdr (cdr ph_info))) ;; stddev zdur))) (begin (format t "ClusterGen_state_duration: no dur phone info for %s\n" (item.name state)) 0.1)))) (define (ClusterGen_make_mcep utt) ;; Well its really make params (whatever type they are), ;; they might not be mceps ;; Note this just makes the vectors, it doesn't predict the ;; values of the vectors -- see predict_mcep below (let ((num_frames 0) (frame_advance cg:frame_shift) (end 0.0) (hmmstate_dur)) Make HMMstate relation and items ( three per phone ) (utt.relation.create utt "mcep") (utt.relation.create utt "mcep_link") (mapcar (lambda (state) ;; Predict Duration (set! start end) (set! hmmstate_dur (ClusterGen_state_duration state)) (if (< hmmstate_dur frame_advance) (set! hmmstate_dur frame_advance)) (set! end (+ start hmmstate_dur)) (item.set_feat state "end" end) ;; create that number of mcep frames up to state end (set! mcep_parent (utt.relation.append utt 'mcep_link state)) (while (<= (* (+ 0 num_frames) frame_advance) end) (set! mcep_frame (utt.relation.append utt 'mcep)) (item.append_daughter mcep_parent mcep_frame) (item.set_feat mcep_frame "frame_number" num_frames) (item.set_feat mcep_frame "name" (item.name mcep_parent)) (set! num_frames (+ 1 num_frames)) ) ) (utt.relation.items utt 'HMMstate)) ;; Copy the final state end back up on to the segment for consistency (mapcar (lambda (seg) (item.set_feat seg "end" (item.feat seg "R:segstate.daughtern.end"))) (utt.relation.items utt 'Segment)) (utt.set_feat utt "param_track_num_frames" num_frames) utt) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Some feature functions specific to CG , some of these are just ;; experimental ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (mcep_12 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 12)) (define (mcep_11 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 11)) (define (mcep_10 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 10)) (define (mcep_9 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 9)) (define (mcep_8 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 8)) (define (mcep_7 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 7)) (define (mcep_6 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 6)) (define (mcep_5 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 5)) (define (mcep_4 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 4)) (define (mcep_3 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 3)) (define (mcep_2 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 2)) (define (mcep_1 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 1)) (define (mcep_0 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 0)) (define (v_value i) (track.get clustergen_param_vectors (item.feat i "clustergen_param_frame") (- (track.num_channels clustergen_param_vectors) 2)) ) (define (cg_break s) "(cg_break s) 0, if word internal, 1 if word final, 4 if phrase final, we ignore 3/4 distinguinction in old syl_break" (let ((x (item.feat s "syl_break"))) (cond ((string-equal "0" x) (string-append x)) ((string-equal "1" x) (string-append x)) ((string-equal "0" (item.feat s "R:SylStructure.parent.n.name")) "4") (t "3")))) (define (cg_frame_voiced s) (if (and (string-equal "-" (item.feat s "R:mcep_link.parent.R:segstate.parent.ph_vc")) (string-equal "-" (item.feat s "R:mcep_link.parent.R:segstate.parent.ph_cvox"))) 0 1) ) (define (cg_duration i) (if (item.prev i) (- (item.feat i "end") (item.feat i "p.end")) (item.feat i "end"))) (define (cg_state_pos i) (let ((n (item.name i))) (cond ((not (string-equal n (item.feat i "p.name"))) "b") ((string-equal n (item.feat i "n.name")) "m") (t "e")))) (define (cg_state_place i) (let ((start (item.feat i "R:mcep_link.parent.daughter1.frame_number")) (end (item.feat i "R:mcep_link.parent.daughtern.frame_number")) (this (item.feat i "frame_number"))) (if (eq? 0.0 (- end start)) 0 (/ (- this start) (- end start))))) (define (cg_state_index i) (let ((start (item.feat i "R:mcep_link.parent.daughter1.frame_number")) (this (item.feat i "frame_number"))) (- this start))) (define (cg_state_rindex i) (let ((end (item.feat i "R:mcep_link.parent.daughtern.frame_number")) (this (item.feat i "frame_number"))) (- end this))) (define (cg_phone_place i) (let ((start (item.feat i "R:mcep_link.parent.R:segstate.parent.daughter1.R:mcep_link.daughter1.frame_number")) (end (item.feat i "R:mcep_link.parent.R:segstate.parent.daughtern.R:mcep_link.daughtern.frame_number")) (this (item.feat i "frame_number"))) (if (eq? 0.0 (- end start)) 0 (/ (- this start) (- end start))))) (define (cg_phone_index i) (let ((start (item.feat i "R:mcep_link.parent.R:segstate.parent.daughter1.R:mcep_link.daughter1.frame_number")) (this (item.feat i "frame_number"))) (- this start))) (define (cg_phone_rindex i) (let ((end (item.feat i "R:mcep_link.parent.R:segstate.parent.daughtern.R:mcep_link.daughtern.frame_number")) (this (item.feat i "frame_number"))) (- end this))) (define (cg_utt_fileid i) (utt.feat (item.get_utt i) "fileid")) (define (cg_position_in_sentenceX x) (/ (item.feat x "R:mcep_link.parent.end") (item.feat x "R:mcep_link.parent.R:segstate.parent.R:Segment.last.end"))) (define (cg_position_in_sentence x) (let ((sstart (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Word.first.R:SylStructure.daughter1.daughter1.R:Segment.p.end")) (send (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Word.last.R:SylStructure.daughtern.daughtern.R:Segment.end"))) (set! xyx (if (eq? 0.0 (- send sstart)) -1 (/ (- (* cg:frame_shift (item.feat x "frame_number")) sstart) (- send sstart)))) ; (format t "cg_position_in_sentence2 %f\n" xyx) xyx )) (define (cg_find_phrase_number x) (cond ((item.prev x) (+ 1 (cg_find_phrase_number (item.prev x)))) (t 0))) (define (cg_find_rphrase_number x) (cond ((item.next x) (+ 1 (cg_find_rphrase_number (item.next x)))) (t 0))) (define (cg_position_in_phrase x) (let ((pstart (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughter1.R:SylStructure.daughter1.daughter1.R:Segment.p.end")) (pend (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughtern.R:SylStructure.daughtern.daughtern.R:Segment.end")) (phrasenumber (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.lisp_cg_find_phrase_number"))) (set! xyx (if (eq? 0.0 (- pend pstart)) -1 (+ 0 ;phrasenumber (/ (- (* cg:frame_shift (item.feat x "frame_number")) pstart) (- pend pstart))))) ; (format t "cg_position_in_phrase %f\n" xyx) xyx ) ) (define (cg_position_in_phrasep x) (let ((pstart (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughter1.R:SylStructure.daughter1.daughter1.R:Segment.p.end")) (pend (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughtern.R:SylStructure.daughtern.daughtern.R:Segment.end")) (phrasenumber (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.lisp_cg_find_phrase_number"))) (set! xyx (if (eq? 0.0 (- pend pstart)) -1 (+ phrasenumber (/ (- (* cg:frame_shift (item.feat x "frame_number")) pstart) (- pend pstart))))) ; (format t "cg_position_in_phrase %f\n" xyx) xyx ) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Smoothing functions ( sort of instead of mlpg ) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (cg_F0_smooth track j) (let ((p 0.0) (i 0) (num_frames (- (track.num_frames track) 1))) (set! i 1) (while (< i num_frames) (set! this (track.get track i j)) (set! next (track.get track (+ i 1) j)) (if (> this 0.0) (track.set track i j (/ (+ (if (> p 0.0) p this) this (if (> next 0.0) next this)) 3.0))) (set! p this) (set! i (+ 1 i))) ) ) (define (cg_mcep_smooth track j) (let ((p 0.0) (i 0) (num_frames (- (track.num_frames track) 1))) (set! i 1) (while (< i num_frames) (set! this (track.get track i j)) (set! next (track.get track (+ i 1) j)) (track.set track i j (/ (+ p this next) 3.0)) (set! p this) (set! i (+ 1 i))) ) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; For normal synthesis make unvoiced states unvoiced, but we don't ;; do this during testing (defvar cg_predict_unvoiced t) (define (ClusterGen_predict_F0 mcep f0_val param_track) "(ClusterGen_predict_F0 mcep frame param_track) Predict the F0 (or not)." (if (and cg_predict_unvoiced (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_vc")) (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_cvox"))) (track.set param_track i 0 0.0) ;; make it unvoiced (silence) (track.set param_track i 0 f0_val)) ;; make it voiced ) (define (ClusterGen_mcep_voiced mcep) (if (and cg_predict_unvoiced (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_vc")) (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_cvox"))) nil t)) ;(set! cg_vuv_tree (car (load "vuv/vuv.tree" t))) Default voice / unvoiced prediction : can be trained with bin / make_vuv_model (defvar cg_vuv_tree '((lisp_v_value < 5.5) ((0)) ((1)))) (define (ClusterGen_voicing_v mcep) (let ((vp (car (last (wagon mcep cg_vuv_tree))))) (if cg:vuv_predict_dump (begin ;; only used at vuv_model build time (mapcar (lambda (f) (format cg:vuv_predict_dump "%s " (item.feat mcep f))) cg_vuv_predict_features) (format cg:vuv_predict_dump "\n"))) (cond ((string-equal "pau" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.name")) ;; pauses are always unvoiced nil) ((equal? vp 1) t) (t nil)))) (define (ClusterGen_voicing_v_traj mcep i params) (let ((vvv (track.get params i 102))) ; (format t "%s %f\n" (item.name mcep) vvv) (cond ((string-equal "pau" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.name")) ;; pauses are always unvoiced nil) ((string-equal "+" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_vc")) ;; vowels are always voiced t) ((> vvv 0.4) ;; consonants are what they are t) (t nil)))) (define (cg_do_gmm_transform utt) "(cmu_us_rms_transform::convfilter utt) Filter synthesized voice with transformation filter and reload waveform." (let ((wfile1 (make_tmp_filename)) (wfile2 (make_tmp_filename)) (wfile3 (make_tmp_filename)) (wfile4 (make_tmp_filename)) ) (utt.save utt wfile3) (track.save (utt.feat utt "param_track") wfile4) (system (format nil "(cd %s && csh $FESTVOXDIR/src/vc/scripts/VConvFestival_cg.csh $FESTVOXDIR/src/vc/src param/source-target_param.list %s %s %s %s)" "vc" ;; Need a way set this with the voice dir wfile1 ;; input file wfile3 ;; utterance wfile4 ;; predicted param file wfile2)) (set! new_track (track.load wfile2)) (utt.set_feat utt "param_track" new_track) (delete-file wfile1) (delete-file wfile2) (delete-file wfile3) (delete-file wfile4) utt )) (define (cg_do_mlpg param_track) do on the params (if (boundp 'mlpg) (begin (mlpg param_track)) old version with external mlpg script (let ((trackname (make_tmp_filename)) (mlpgtrack (make_tmp_filename)) ) (track.save param_track trackname "est") (if cg:gv (begin (format t "with gv\n") (system (format nil "$FESTVOXDIR/src/clustergen/cg_mlpg %s %s %s %s" trackname mlpgtrack cg_gv_vm_filename cg_gv_vv_filename ))) (system (format nil "$FESTVOXDIR/src/clustergen/cg_mlpg %s %s" trackname mlpgtrack))) (set! postmlpg (track.load mlpgtrack)) (delete-file trackname) (delete-file mlpgtrack) postmlpg) ))) (define (cg_all_f0 m) ;; global prediction of F0, not unit specific (let ((all_f0 (wagon m (cadr (assoc_string "all" clustergen_f0_all))))) (cadr all_f0))) (define (cg_all_f0f0 m) ;; global prediction of F0, difference (let ((all_f0 (wagon m (cadr (assoc_string "all" clustergen_f0_all)))) (all_f0f0 (wagon m (cadr (assoc_string "all_f0_diff" clustergen_f0_all))))) (- (cadr all_f0) (cadr all_f0f0)))) (define (cg_F0_interpolate_linear utt param_track) (mapcar (lambda (syl) (set! start_index (item.feat syl "R:SylStructure.daughter1.R:segstate.daughter1.R:mcep_link.daughter1.frame_number")) (set! end_index (item.feat syl "R:SylStructure.daughtern.R:segstate.daughter1.R:mcep_link.daughtern.frame_number")) (set! mid_index (nint (/ (+ start_index end_index) 2.0))) (set! start_f0 (track.get param_track start_index 0)) (set! mid_f0 (track.get param_track mid_index 0)) (set! end_f0 (track.get param_track (- end_index 1) 0)) ; (format t "Syl: %s %d %f %d %f %d %f \n" ; (item.feat syl "R:SylStructure.parent.name") start_index start_f0 mid_index mid_f0 end_index end_f0 ) (set! m (/ (- mid_f0 start_f0) (- mid_index start_index))) (set! i 1) (while (< (+ i start_index) mid_index) ( format t " % l % " ( + i start_index ) ( + start_f0 ( * i m ) ) ) (track.set param_track (+ i start_index) 0 (+ start_f0 (* i m))) (set! i (+ i 1))) (set! m (/ (- end_f0 mid_f0) (- end_index mid_index))) (set! i 1) (while (< (+ i mid_index) end_index) (track.set param_track (+ i mid_index) 0 (+ mid_f0 (* i m))) (set! i (+ i 1))) ) (utt.relation.items utt 'Syllable)) utt ) (define (catmull_rom_spline p p0 p1 p2 p3) ;; / (let ((q nil)) (set! q (* 0.5 (+ (* 2 p1) (* (+ (* -1 p0) p2) p) (* (+ (- (* 2 p0) (* 5 p1)) (- (* 4 p2) p3)) (* p p)) (* (+ (* -1 p0) (- (* 3 p1) (* 3 p2)) p3) (* p p p))))) ; (format t "crs: %f %f %f %f %f %f\n" ; q p p0 p1 p2 p3) q)) (define (cg_F0_interpolate_spline utt param_track) (set! mid_f0 -1) (set! end_f0 -1) (mapcar (lambda (syl) (set! start_index (item.feat syl "R:SylStructure.daughter1.R:segstate.daughter1.R:mcep_link.daughter1.frame_number")) (set! end_index (item.feat syl "R:SylStructure.daughtern.R:segstate.daughtern.R:mcep_link.daughtern.frame_number")) (set! mid_index (nint (/ (+ start_index end_index) 2.0))) (set! start_f0 (track.get param_track start_index 0)) (if (> end_f0 0) (set! start_f0 end_f0)) (if (< mid_f0 0) (set! pmid_f0 start_f0) (set! pmid_f0 mid_f0)) (set! mid_f0 (track.get param_track mid_index 0)) (if (item.next syl) (set! end_f0 (/ (+ (track.get param_track (- end_index 1) 0) (track.get param_track end_index 0)) 2.0)) (set! end_f0 (track.get param_track (- end_index 1) 0))) (set! nmid_f0 end_f0) (if (item.next syl) (begin (set! nsi (item.feat syl "n.R:SylStructure.daughter1.R:segstate.daughter1.R:mcep_link.daughter1.frame_number")) (set! nei (item.feat syl "n.R:SylStructure.daughtern.R:segstate.daughtern.R:mcep_link.daughtern.frame_number")) (set! nmi (nint (/ (+ nsi nei) 2.0))) (set! nmid_f0 (track.get param_track nmi 0)))) ( format t " Syl : % s % 2.1f % d % 2.1f % d % 2.1f % d % 2.1f % 2.1f % d\n " ; (item.feat syl "R:SylStructure.parent.name") ; pmid_f0 start_index start_f0 mid_index mid_f0 end_index end_f0 nmid_f0 end_index ) (set! m (/ 1.0 (- mid_index start_index))) (set! i 0) (while (< (+ i start_index) mid_index) (track.set param_track (+ i start_index) 0 (catmull_rom_spline (* i m) pmid_f0 start_f0 mid_f0 end_f0)) (set! i (+ i 1))) (set! m (/ 1.0 (- end_index mid_index))) (set! i 0) (while (< (+ i mid_index) end_index) (track.set param_track (+ i mid_index) 0 (catmull_rom_spline (* i m) start_f0 mid_f0 end_f0 nmid_f0)) (set! i (+ i 1))) ) (utt.relation.items utt 'Syllable)) utt ) (set! cg_F0_interpolate cg_F0_interpolate_spline) (define (ClusterGen_predict_mcep utt) (let ((param_track nil) (frame_advance cg:frame_shift) (frame nil) (f nil) (f0_val) (cg_name_feature "name") (num_channels (/ (track.num_channels clustergen_param_vectors) (if cg:mlpg 1 2))) (num_frames (utt.feat utt "param_track_num_frames")) ) ;; Predict mcep values (set! i 0) (set! param_track (track.resize nil num_frames num_channels)) (utt.set_feat utt "param_track" param_track) (mapcar (lambda (mcep) ;; Predict mcep frame (let ((mcep_tree (assoc_string (item.feat mcep cg_name_feature) clustergen_mcep_trees)) (mcep_tree_delta (assoc_string (item.feat mcep cg_name_feature) (if cg:multimodel clustergen_delta_mcep_trees nil))) (mcep_tree_str (assoc_string (item.feat mcep cg_name_feature) (if (boundp 'clustergen_str_mcep_trees) clustergen_str_mcep_trees nil))) (f0_tree (assoc_string ; "all" (item.feat mcep cg_name_feature) clustergen_f0_trees)) ) (if (null mcep_tree) (format t "ClusterGen: can't find cluster tree for %s\n" (item.name mcep)) (begin ;; F0 prediction (set! f0_val (wagon mcep (cadr f0_tree)) ( list 1.0 ( cg_all_f0 mcep ) ) ) (track.set param_track i 0 (cadr f0_val)) ;; MCEP prediction (set! frame (wagon mcep (cadr mcep_tree))) (if cg:multimodel (set! dframe (wagon mcep (cadr mcep_tree_delta)))) (set! j 1) (set! f (car frame)) (item.set_feat mcep "clustergen_param_frame" f) (if cg:rfs (set! rfs_info (mapcar (lambda (rf_model) (list (cadr rf_model) (car (wagon mcep (cadr (assoc_string (item.feat mcep cg_name_feature) (car rf_model))))))) cg:rfs_models))) (if cg:multimodel (track.set param_track i 0 (/ (+ (cadr f0_val) (track.get clustergen_delta_param_vectors (car dframe) 0) (track.get clustergen_param_vectors f 0)) 3.0))) (while (< j num_channels) (cond ((not (null cg:rfs_models)) (track.set param_track i j (/ (apply + (mapcar (lambda (rfs_item) (track.get (car rfs_item) (cadr rfs_item) (* (if cg:mlpg 1 2) j))) rfs_info)) (length rfs_info)))) ((not (null cg:multimodel)) (begin (if (and (boundp 'clustergen_str_mcep_trees) (> j (* 2 (+ 50))) (< j 112)) (begin (track.set param_track i j (/ (+ (track.get clustergen_str_param_vectors (car (wagon mcep (cadr mcep_tree_str))) (* (if cg:mlpg 1 2) j)) (track.get clustergen_delta_param_vectors (car dframe) (* (if cg:mlpg 1 2) j)) (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j)) ) 3.0) )) (begin (track.set param_track i j (/ (+ (track.get clustergen_delta_param_vectors (car dframe) (* (if cg:mlpg 1 2) j)) (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j)) ) 2.0)))) )) (t (track.set param_track i j (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j))) )) (set! j (+ 1 j))) (set! j (- num_channels 1)) (track.set param_track i j (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j))) )) (track.set_time param_track i (+ cg:initial_frame_offset (* i frame_advance))) (set! i (+ 1 i)))) (utt.relation.items utt 'mcep)) (if cg:mixed_excitation (let ((nf (track.num_frames param_track)) (f 0) (c 0)) (set! str_params (track.resize nil nf 5)) (set! f 0) (while (< f nf) (track.set_time str_params f (track.get_time param_track f)) (set! c 0) (while (< c 5) (track.set str_params f c (track.get param_track f (* 2 (+ c (+ 1 (* 2 mcep_length)) ; after all mcep and deltas )))) (set! c (+ 1 c))) (set! f (+ 1 f))) (utt.set_feat utt "str_params" str_params))) (if cg:F0_interpolate (cg_F0_interpolate utt param_track)) (if (or cg:vuv cg:with_v) ;; need to get rid of the vuv coefficient (last one) (let ((nf (track.num_frames param_track)) (nc (- (track.num_channels param_track) 2)) (f 0) (c 0)) (set! nnn_track (track.resize nil nf nc)) (while (< f nf) (track.set_time nnn_track f (track.get_time param_track f)) (set! c 0) (while (< c nc) (track.set nnn_track f c (track.get param_track f c)) (set! c (+ 1 c))) (set! f (+ 1 f))) (set! param_track nnn_track) )) MLPG (if cg:mlpg ;; assume cg:deltas too (let ((nf (track.num_frames param_track)) (nc (* 2 (+ 1 mcep_length mcep_length))) ;; f0 static delta (mean and stddev) (f 0) (c 0)) (if cg:debug (format t "cg:debug calling mlpg\n")) (set! nnn_track (track.resize nil nf nc)) (while (< f nf) (track.set_time nnn_track f (track.get_time param_track f)) (set! c 0) (while (< c nc) (track.set nnn_track f c (track.get param_track f c)) (set! c (+ 1 c))) (set! f (+ 1 f))) (set! param_track nnn_track) (set! new_param_track (cg_do_mlpg param_track)) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if (and (not cg:mlpg) cg:deltas) (begin ;; have to reduce param_track to remove deltas (set! new_param_track (track.resize param_track (track.num_frames param_track) 26)) ;; not very portable (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if cg:F0_smooth (cg_F0_smooth param_track 0)) (if cg_predict_unvoiced (begin (set! i 0) (mapcar (lambda (frame) ( not ( ClusterGen_mcep_voiced frame ) ) (not (ClusterGen_voicing_v frame)) (track.set param_track i 0 0.0)) (set! i (+ 1 i))) (utt.relation.items utt 'mcep)))) (if cg:param_smooth (mapcar (lambda (x) (cg_mcep_smooth param_track x)) '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25))) utt ) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; CGV : prediction with ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (cgv_reverse_probs pdf) (cond ((null pdf) nil) ((eq (car (cdr (car pdf))) 0) (cgv_reverse_probs (cdr pdf))) (t (cons (list (car (car pdf)) (/ (car (cdr (car pdf))) (cgv_prob (car (car pdf))))) (cgv_reverse_probs (cdr pdf)))))) (define (cgv_prob c) (let ((xxx (assoc_string c cgv_class_probs))) (if xxx (car (cdr xxx)) 0.000012))) (define (cgv_cand_function s) ; (format t "cand_function %s\n" (item.name s)) (let ((mcep_tree (assoc_string (item.name s) clustergen_mcep_trees)) (probs nil)) (cond ((string-equal "S" (item.name s)) (set! probs (cgv_reverse_probs '((S 1))))) ((string-equal "E" (item.name s)) (set! probs (cgv_reverse_probs '((E 1))))) (mcep_tree (set! probs (cgv_reverse_probs (cdr (reverse (wagon s (cadr mcep_tree))))))) (t (format t "ClusterGen: cgv can't find cluster tree for %s\n" (item.name s)) (set! probs nil))) ( format t " % s % " ( item.name s ) probs ) probs)) (define (ClusterGen_predict_cgv utt) (format t "predict cgv\n") (let ((param_track nil) (frame_advance cg:frame_shift) (frame nil) (f nil) (f0_val) (num_channels (/ (track.num_channels clustergen_param_vectors) (if cg:mlpg 1 2))) (num_frames (utt.feat utt "param_track_num_frames")) ) ;; Predict mcep values (set! i 0) (set! param_track (track.resize nil num_frames num_channels)) (utt.set_feat utt "param_track" param_track) (utt.relation.create utt 'cseq) (set! citem (utt.relation.append utt 'cseq nil)) (item.set_feat citem 'name 'S) (mapcar (lambda (m) (set! citem (utt.relation.append utt 'cseq m))) (utt.relation.items utt 'mcep)) (set! citem (utt.relation.append utt 'cseq nil)) (item.set_feat citem 'name 'E) (set! gen_vit_params (list (list 'Relation "cseq") (list 'return_feat "clustergen_class") (list 'p_word "S") (list 'pp_word "S") ; (list 'ngramname 'cgv_ngram) (list 'wfstname 'cgv_wfst) (list 'cand_function 'cgv_cand_function))) (Gen_Viterbi utt) (mapcar (lambda (mcep) ;; Predict mcep frame (let ((f0_tree (assoc_string (item.name mcep) clustergen_f0_trees))) (if (null f0_tree) (format t "ClusterGen: can't find cluster tree for %s\n" (item.name mcep)) (begin ;; F0 prediction (set! f0_val (wagon mcep (cadr f0_tree))) (if (eq (cadr f0_val) 0.0) (track.set param_track i 0 0.0) ;; Wave exp() but its worse (track.set param_track i 0 (cadr f0_val))) ;; MCEP prediction (set! j 1) (set! f (parse-number (string-after (item.feat mcep "clustergen_class") "c"))) (item.set_feat mcep "clustergen_param_frame" f) (while (< j num_channels) (track.set param_track i j (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j)) ) (set! j (+ 1 j))))) (track.set_time param_track i (+ cg:initial_frame_offset (* i frame_advance))) (set! i (+ 1 i)))) (utt.relation.items utt 'mcep)) MLPG (if cg:mlpg ;; assume cg:deltas too (begin (if cg:debug (format t "cg:debug calling mlpg\n")) (set! new_param_track (cg_do_mlpg param_track)) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if (and (not cg:mlpg) cg:deltas) (begin ;; have to reduce param_track to remove deltas (set! new_param_track (track.resize param_track (track.num_frames param_track) 26)) ;; not very portable (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if cg:F0_smooth (cg_F0_smooth param_track 0)) (if cg_predict_unvoiced (begin (set! i 0) (mapcar (lambda (frame) (if (not (ClusterGen_mcep_voiced frame)) (track.set param_track i 0 0.0)) (set! i (+ 1 i))) (utt.relation.items utt 'mcep)))) (if cg:param_smooth (mapcar (lambda (x) (cg_mcep_smooth param_track x)) '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25))) utt ) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Trajectory prediction functions ( including ola ) ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (cg_voiced state) "(cg_voiced state) t if this state is voiced, nil otherwise." (if (and cg_predict_unvoiced (string-equal "-" (item.feat state "R:segstate.parent.ph_vc")) (string-equal "-" (item.feat state "R:segstate.parent.ph_cvox"))) nil t)) (define (ClusterGen_predict_trajectory utt) (let ((param_track nil) (frame_advance cg:frame_shift) (frame nil) (f nil) (f0_val) (num_channels (/ (track.num_channels clustergen_param_vectors) (if cg:mlpg 1 2))) ) ;; Predict mcep values (set! i 0) (set! param_track (track.resize nil (utt.feat utt "param_track_num_frames") num_channels)) (utt.set_feat utt "param_track" param_track) ( set ! param_track ( utt.feat utt " param_track " ) ) (mapcar (lambda (state) ;; Predict mcep frame ;joint (let ((mcep_tree (assoc_string (item.name state) traj::clustergen_mcep_trees)) (let ((mcep_tree (assoc_string (item.name state) clustergen_mcep_trees)) ( ( assoc_string ( item.name mcep ) clustergen_f0_trees ) ) ) (if (null mcep_tree) (format t "ClusterGen: can't find cluster tree for %s\n" (item.name state)) (begin ;; feature prediction (F0 and mcep) (set! trajectory (wagon state (cadr mcep_tree))) (if (item.relation.daughters state 'mcep_link) (begin (if (assoc 'cg::trajectory_ola clustergen_mcep_trees) joint ( if ( assoc ' traj::clustergen_mcep_trees ) (cg:add_trajectory_ola (caar trajectory) (cadr (car trajectory)) state num_channels param_track frame_advance) (cg:add_trajectory (caar trajectory) (cadr (car trajectory)) state num_channels param_track frame_advance)))) )))) (utt.relation.items utt 'HMMstate)) (if (or cg:vuv cg:with_v) ;; need to get rid of the vuv coefficient (last one) (let ((nf (track.num_frames param_track)) (nc (- (track.num_channels param_track) 2)) (f 0) (c 0)) (set! full_param_track param_track) (set! nnn_track (track.resize nil nf nc)) (while (< f nf) (track.set_time nnn_track f (track.get_time param_track f)) (set! c 0) (while (< c nc) (track.set nnn_track f c (track.get param_track f c)) (set! c (+ 1 c))) (set! f (+ 1 f))) (set! param_track nnn_track) )) MLPG (if cg:mlpg (begin (if cg:debug (format t "cg:debug calling mlpg\n")) (set! new_param_track (cg_do_mlpg param_track)) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if (and (not cg:mlpg) cg:deltas) (begin ;; have to reduce param_track to remove deltas (set! new_param_track (track.resize param_track (track.num_frames param_track) 26)) ;; not very portable (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if cg:F0_smooth (cg_F0_smooth param_track 0)) (if cg_predict_unvoiced (begin (set! i 0) (mapcar (lambda (frame) ( not ( ClusterGen_mcep_voiced frame ) ) (not (ClusterGen_voicing_v_traj frame i full_param_track)) (track.set param_track i 0 0.0)) (set! i (+ 1 i))) (utt.relation.items utt 'mcep)))) (if cg:param_smooth (mapcar (lambda (x) (cg_mcep_smooth param_track x)) ; '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25) '( 1 2 3 ) )) utt ) ) (define (cg:add_trajectory s_start s_frames state num_channels param_track frame_advance) "(cg:add_trajectory start n state num_channels) Add trajectory to daughters of state, interpolating as necessary." (let ((j 0) (i 0) (mceps (item.relation.daughters state 'mcep_link))) (set! t_start (item.feat (car mceps) "frame_number")) (set! t_frames (length mceps)) (set! m (/ (- s_frames 1) t_frames)) (set! f 0) (while (< i t_frames) ;; find f (set! s_pos (nint (+ s_start f))) (track.set param_track (+ i t_start) 0 (track.get clustergen_param_vectors s_pos 0)) (set! j 1) (while (< j num_channels) (track.set param_track (+ i t_start) j joint ( + ( * 0.35 ( track.get param_track ( + i t_start ) j ) ) ( * 0.65 ( track.get traj::clustergen_param_vectors s_pos ( * 2 j ) ) ) ) ) (track.get clustergen_param_vectors s_pos (* (if cg:mlpg 1 2) j))) (set! j (+ 1 j))) (set! f (+ m f)) (track.set_time param_track (+ i t_start) (+ cg:initial_frame_offset (* (+ i t_start) frame_advance))) (set! i (+ i 1)) ) ) ) (define (cg:add_trajectory_ola s_start s_frames state num_channels param_track frame_advance) "(cg:add_trajectory start n state num_channels) Add trajectory to daughters of state, interpolating as necessary." (let ((j 0) (i 0) (s1l 0) (s2l 0) (m 0.0) (w 0.0) (t_start 0) (t_frames 0) (s_offset 0) (mceps1 nil) (mceps2 nil)) (set! i 0) (while (< i s_frames) (if (equal? -1.0 (track.get clustergen_param_vectors (+ s_start i) 0)) (set! s1l i)) (set! i (+ i 1))) (if (and (item.prev state) (item.relation.daughters (item.prev state) 'mcep_link) (> s1l 0)) (begin ;; do overlap on previous (set! mceps1 (item.relation.daughters (item.prev state) 'mcep_link)) (set! first_half_delta (/ 1.0 (length mceps1))) (set! t_start (item.feat (car mceps1) "frame_number")) (set! t_frames (length mceps1)) (set! m (/ s1l t_frames)) (set! i 0) (set! w 0.0) (while (< i t_frames) (set! s_offset (nint (* i m))) (if (not (< s_offset s1l)) (begin ; (format t "boing pre\n") (set! s_offset (- s1l 1)))) (set! s_pos (+ s_start s_offset)) (if (< (track.get clustergen_param_vectors s_pos 0) 0) (format t "assigning pre -1/-2 %d %d %f\n" s_pos i m)) ;; F0 Prediction (track.set param_track (+ i t_start) 0 (+ (* (- 1.0 w) (track.get param_track (+ i t_start) 0)) (* w (track.get clustergen_param_vectors s_pos 0)))) ;; MCEP Prediction (set! j 1) (while (< j num_channels) (track.set param_track (+ i t_start) j (+ (* (- 1.0 w) (track.get param_track (+ i t_start) j)) (* w (track.get clustergen_param_vectors s_pos (* (if cg:mlpg 1 2) j)) ) ) ) (set! j (+ 1 j))) (set! i (+ 1 i)) (set! w (+ w first_half_delta)) (if (> w 1.0) (set! w 1.0)) ) )) ;; do assignment on current unit (set! mceps2 (item.relation.daughters state 'mcep_link)) (set! t_start (item.feat (car mceps2) "frame_number")) (set! t_frames (length mceps2)) (set! s2l (- s_frames (+ s1l 2))) (set! s2_start (+ s_start s1l 1)) (set! m (/ s2l t_frames)) (set! i 0) (while (< i t_frames) (set! s_offset (nint (* i m))) (if (not (< s_offset s2l)) (set! s_offset (- s2l 1))) (set! s_pos (+ s2_start s_offset)) (if (< (track.get clustergen_param_vectors s_pos 0) 0) (format t "assigning -1/-2 %d %d %f %f\n" s_pos i m (track.get clustergen_param_vectors s_pos 0))) ;; F0 Prediction (track.set param_track (+ i t_start) 0 (track.get clustergen_param_vectors s_pos 0)) ;; MCEP Prediction (set! j 1) (while (< j num_channels) (track.set param_track (+ i t_start) j (track.get clustergen_param_vectors s_pos (* (if cg:mlpg 1 2) j))) (set! j (+ 1 j))) (track.set_time param_track (+ i t_start) (+ cg:initial_frame_offset (* (+ i t_start) frame_advance))) (set! i (+ 1 i)) ) ) ) ;;; For ClusterGen_predict_mcep ;;; take into account actual and delta and try to combine both ; (if (and nil (> i 0)) ; (begin ;; something a little fancier ( set ! m1 ( track.get cpv f ( * 2 j ) ) ) ; ; mean1 ( set ! s1 ( track.get cpv f ( + ( * 2 j ) 1 ) ) ) ; ; sdev1 ( set ! m2 ( track.get cpv f ( + 26 ( * 2 j ) ) ) ) ; ; mean2 ( delta ) ( set ! s2 ( track.get cpv f ( + 26 ( * 2 j ) 1 ) ) ) ; ; sdev2 ( delta ) ; (set! p1 (track.get param_track (- i 1) j)) ;; p.value ; (if (equal? s2 0) ; (set! p m1) ; (set! p (/ (+ m1 (+ m2 p1)) 2.0)) ; ; (set! p (/ (+ (/ m1 s1) (/ (+ m2 p1) s2)) ; ; (+ (/ 1.0 s1) (/ 1.0 s2)))) ; ) ; (track.set param_track i j p) ; ( format t " m1 % f s1 % f m2 % f s2 % f p % f\n " ; m1 s1 ( + ) ; ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; For VC adpatation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (build_cg_vc_source datafile) (mapcar (lambda (x) (format t "%s Build source files for VC adaptation\n" (car x)) (set! utt1 (SynthText (cadr x))) (utt.save.wave utt1 (format nil "vc/wav/source/%s.wav" (car x))) (track.save (utt.feat utt1 "param_track") "param.track") (system (format nil "$FESTVOXDIR/src/vc/scripts/get_f0mcep %s param.track vc\n" (car x))) ) (load datafile t)) t ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Sort of historical it should be set in INST_LANG_VOX_cg.scm ;; but maybe not in old instantiations ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;(defvar cluster_synth_method ( if ( boundp ' mlsa_resynthesis ) ; cg_wave_synth ; cg_wave_synth_external )) ; (require 'hsm_cg) (define (cg_wave_synth_deltas utt) ;; before we had it built-in to Festival (let ((trackname (make_tmp_filename)) (wavename (make_tmp_filename)) ) (track.save (utt.feat utt "param_track") trackname "est") (system (format nil "$FESTVOXDIR/src/clustergen/cg_resynth_deltas %s %s" trackname wavename)) (utt.import.wave utt wavename) (delete-file trackname) (delete-file wavename) utt) ) (set! cluster_synth_method cg_wave_synth) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide 'clustergen)
null
https://raw.githubusercontent.com/linuxscout/festival-tts-arabic-voices/ab9fe26120bf6cf3079afa2484b985cfd6ecd56a/voices/ara_norm_ziad_hts/festvox/clustergen.scm
scheme
;; ; ; ; ;; Permission is hereby granted, free of charge, to use and distribute ;; this software and its documentation without restriction, including ;; without limitation the rights to use, copy, modify, merge, publish, ;; distribute, sublicense, and/or sell copies of this work, and to ;; permit persons to whom this work is furnished to do so, subject to ;; the following conditions: ;; 1. The code must retain the above copyright notice, this list of ;; conditions and the following disclaimer. ;; 2. Any modifications must be clearly marked as such. ;; ; 4. The authors' names are not used to endorse or promote products ;; derived from this software without specific prior written ;; permission. ;; ;; ; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO ;; ; LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY ;; DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, ;; ; ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR ;; PERFORMANCE OF THIS SOFTWARE. ;; ;; ;; ; ;; ;; ; ;; This is voice-independant, and should be in festival/lib but is ;; currently copied into each voice's festvox/ directory ;; ;; This mapping should match that in do_clustergen for mcep_sptk_deltas spline interpolation probably doesn't work any more! will get loaded at synthesis time random forests for duration will get loaded at synthesis time (set! cg:phrasyn_mode 'gpos) (Parameter.set 'Synth_Method 'ClusterGen) a global variable for debugging Build the state relation Predict number of frames durations for # of vectors Then predict the frame values predict vector types ; predict vectors by Various waveform resynthesis wraparound functions before we had it built-in to Festival Not mixed excitation before we had it built-in to Festival it is very much experimental and incomplete generate map_track predict the map_param converted parameters Need to do better duration stuff Convert f0 The names may change Random forest prediction single model Its a pau so explicitly set the duration Note we want sentence internal pauses to be about 100ms mean stddev Well its really make params (whatever type they are), they might not be mceps Note this just makes the vectors, it doesn't predict the values of the vectors -- see predict_mcep below Predict Duration create that number of mcep frames up to state end Copy the final state end back up on to the segment for consistency experimental (format t "cg_position_in_sentence2 %f\n" xyx) phrasenumber (format t "cg_position_in_phrase %f\n" xyx) (format t "cg_position_in_phrase %f\n" xyx) For normal synthesis make unvoiced states unvoiced, but we don't do this during testing make it unvoiced (silence) make it voiced (set! cg_vuv_tree (car (load "vuv/vuv.tree" t))) only used at vuv_model build time pauses are always unvoiced (format t "%s %f\n" (item.name mcep) vvv) pauses are always unvoiced vowels are always voiced consonants are what they are Need a way set this with the voice dir input file utterance predicted param file global prediction of F0, not unit specific global prediction of F0, difference (format t "Syl: %s %d %f %d %f %d %f \n" (item.feat syl "R:SylStructure.parent.name") / (format t "crs: %f %f %f %f %f %f\n" q p p0 p1 p2 p3) (item.feat syl "R:SylStructure.parent.name") pmid_f0 Predict mcep values Predict mcep frame "all" F0 prediction MCEP prediction after all mcep and deltas need to get rid of the vuv coefficient (last one) assume cg:deltas too f0 static delta (mean and stddev) have to reduce param_track to remove deltas not very portable (format t "cand_function %s\n" (item.name s)) Predict mcep values (list 'ngramname 'cgv_ngram) Predict mcep frame F0 prediction Wave exp() but its worse MCEP prediction assume cg:deltas too have to reduce param_track to remove deltas not very portable Predict mcep values Predict mcep frame joint (let ((mcep_tree (assoc_string (item.name state) traj::clustergen_mcep_trees)) feature prediction (F0 and mcep) need to get rid of the vuv coefficient (last one) have to reduce param_track to remove deltas not very portable '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25) find f do overlap on previous (format t "boing pre\n") F0 Prediction MCEP Prediction do assignment on current unit F0 Prediction MCEP Prediction For ClusterGen_predict_mcep take into account actual and delta and try to combine both (if (and nil (> i 0)) (begin ;; something a little fancier ; mean1 ; sdev1 ; mean2 ( delta ) ; sdev2 ( delta ) (set! p1 (track.get param_track (- i 1) j)) ;; p.value (if (equal? s2 0) (set! p m1) (set! p (/ (+ m1 (+ m2 p1)) 2.0)) ; (set! p (/ (+ (/ m1 s1) (/ (+ m2 p1) s2)) ; (+ (/ 1.0 s1) (/ 1.0 s2)))) ) (track.set param_track i j p) ( format t " m1 % f s1 % f m2 % f s2 % f p % f\n " m1 s1 ( + ) ) For VC adpatation but maybe not in old instantiations (defvar cluster_synth_method cg_wave_synth cg_wave_synth_external )) (require 'hsm_cg) before we had it built-in to Festival
(defvar cluster_synth_pre_hooks nil) (defvar cluster_synth_post_hooks nil) (defvar clustergen_mcep_trees nil) (defvar cg:initial_frame_offset 0.0) (defvar cg:frame_shift 0.005) (set! mlsa_beta_param 0.4) (set! cg:mlsa_lpf t) (set! framerate 16000) (cond ((equal? framerate 8000) (set! mlsa_alpha_param 0.312)) ((equal? framerate 11025) (set! mlsa_alpha_param 0.357)) ((equal? framerate 16000) (set! mlsa_alpha_param 0.42)) ((equal? framerate 22050) (set! mlsa_alpha_param 0.455)) ((equal? framerate 32000) (set! mlsa_alpha_param 0.504)) ((equal? framerate 44100) (set! mlsa_alpha_param 0.544)) ((equal? framerate 48000) (set! mlsa_alpha_param 0.554)) (t (format t "Unknown framerate %d for mlsa_alpha_param\n" framerate) (exit))) (set! mcep_length 25) deltas / mlpg (defvar cg:F0_smooth t) not as good as mlpg (defvar cg:mlpg t) (defvar cg:gv nil) (defvar cg:vuv nil) (defvar cg:with_v t) (defvar cg:deltas t) (defvar cg:debug nil) (defvar cg:save_param_track nil) (set! cg:mcep_clustersize 50) random forests , set this to 20 to get 20 rfs (defvar cg:gmm_transform nil) (set! cg:mixed_excitation nil) (set! cg:spamf0 nil) (set! cg:spamf0_viterbi nil) (set! cg:vuv_predict_dump nil) (defvar me_filter_track nil) (defvar lpf_track nil) Set (set! cg:phrasyn nil) (set! cg:phrasyn_grammar_ntcount 10) (set! cg:phrasyn_mode 'pos) (if cg:spamf0 (require 'spamf0)) The main CG synthesis voice , voices using CG should set which is done in INST_LANG_VOX_cg.scm (defSynthType ClusterGen (apply_hooks cluster_synth_pre_hooks utt) (ClusterGen_make_HMMstate utt) (if (assoc 'cg::trajectory clustergen_mcep_trees) predict trajectory ( or ola ) ) Convert predicted mcep track into a waveform (if cg:gmm_transform GMM ( MLPG again ) and MLSA ) (if cg:spamf0 (set! utt (spamf0_utt utt)) ) standard MLSA only (if cg:save_param_track (track.save (utt.feat utt "param_track") "param.track")) (apply_hooks cluster_synth_post_hooks utt) utt ) (define (cg_wave_synth_external utt) (let ((trackname (make_tmp_filename)) (wavename (make_tmp_filename)) ) (track.save (utt.feat utt "param_track") trackname "est") (system (format nil "$FESTVOXDIR/src/clustergen/cg_resynth %s %s" trackname wavename)) (utt.import.wave utt wavename) (delete-file trackname) (delete-file wavename) utt) ) (define (cg_wave_synth utt) (utt.relation.create utt 'Wave) (if cg:mixed_excitation (item.set_feat (utt.relation.append utt 'Wave) "wave" (mlsa_resynthesis (utt.feat utt "param_track") (utt.feat utt "str_params") me_filter_track)) (item.set_feat (utt.relation.append utt 'Wave) "wave" (mlsa_resynthesis (utt.feat utt "param_track") nil lpf_track))) utt) (define (cg_wave_synth_sptk utt) (let ((trackname (make_tmp_filename)) (wavename (make_tmp_filename)) ) (track.save (utt.feat utt "param_track") trackname "est") (system (format nil "$FESTVOXDIR/src/clustergen/cg_mlsa2 %s %s" trackname wavename)) (utt.import.wave utt wavename) (delete-file trackname) (delete-file wavename) utt) ) CGA is a basic voice morphing / adaptation technique using cg -- (define (cg_wave_synth_cga utt) Use loaded cga model to predict a new map_track (format t "In Synth CGA\n") (cga:predict_map utt) (utt.relation.create utt 'Wave) (item.set_feat (utt.relation.append utt 'Wave) "wave" (mlsa_resynthesis (utt.feat utt "map_track"))) utt) (define (cga:create_map utt) (set! map_track (track.copy (utt.feat utt "param_track"))) (utt.set_feat utt "map_track" map_track) (utt.relation.create utt "param_map") (utt.relation.create utt "param_map_link") (set! pseg (utt.relation.first utt "mcep")) (set! m 0) (while pseg (set! mcep_parent (utt.relation.append utt "param_map_link" pseg)) (set! mseg (utt.relation.append utt "param_map")) (item.append_daughter mcep_parent mseg) (item.set_feat mseg "frame_number" m) (item.set_feat mseg "name" (item.feat mseg "R:param_map_link.parent.name")) (set! m (+ 1 m)) (set! pseg (item.next pseg))) utt ) (define (cga:predict_map utt) (let (i j f map_track num_channels s_f0_mean s_f0_stddev t_f0_mean t_f0_stddev) (set! i 0) (set! map_track (utt.feat utt "map_track")) (set! num_channels (track.num_channels map_track)) (set! s_f0_mean (get_param 'cga::source_f0_mean clustergen_cga_trees 140)) (set! s_f0_stddev (get_param 'cga::source_f0_stddev clustergen_cga_trees 20)) (set! t_f0_mean (get_param 'cga::target_f0_mean clustergen_cga_trees 140)) (set! t_f0_stddev (get_param 'cga::target_f0_stddev clustergen_cga_trees 20)) (mapcar (lambda (x) (let ((map_tree (assoc_string (item.name x) clustergen_cga_trees))) (if (null map_tree) (format t "ClusterGenCGA: can't find cluster tree for %s\n" (item.name x)) (begin (set! frame (wagon x (cadr map_tree))) (if (> (track.get map_track i 0) 0) (track.set map_track i 0 (+ t_f0_mean (* t_f0_stddev (/ (- (track.get map_track i 0) s_f0_mean) s_f0_stddev))))) (set! j 1) (set! f (car frame)) (while (< j num_channels) (track.set map_track i j (track.get clustergen_cga_vectors f (* 2 j))) (set! j (+ 1 j))))) (set! i (+ 1 i)))) (utt.relation.items utt "param_map")) utt)) (define (ClusterGen_predict_states seg) (cdr (assoc_string (item.name seg) phone_to_states))) (define (ClusterGen_make_HMMstate utt) (let ((states) (segstate) (statepos)) Make HMMstate relation and items ( three per phone ) (utt.relation.create utt "HMMstate") (utt.relation.create utt "segstate") (mapcar (lambda (seg) (set! statepos 1) (set! states (ClusterGen_predict_states seg)) (set! segstate (utt.relation.append utt 'segstate seg)) (while states (set! state (utt.relation.append utt 'HMMstate)) (item.append_daughter segstate state) (item.set_feat state "name" (car states)) (item.set_feat state "statepos" statepos) (set! statepos (+ 1 statepos)) (set! states (cdr states))) ) (utt.relation.items utt 'Segment)) ) ) (define (CG_predict_state_duration state) (if cg:rfs_dur (/ (apply + (mapcar (lambda (dm) (wagon_predict state dm)) cg:rfs_dur_models)) (length cg:rfs_dur_models)) (wagon_predict state duration_cart_tree_cg) )) (define (ClusterGen_state_duration state) (let ((zdur (CG_predict_state_duration state)) (ph_info (assoc_string (item.name state) duration_ph_info_cg)) (seg_stretch (item.feat state "R:segstate.parent.dur_stretch")) (syl_stretch (item.feat state "R:segstate.parent.R:SylStructure.parent.dur_stretch")) (tok_stretch (parse-number (item.feat state "R:segstate.parent.R:SylStructure.parent.parent.R:Token.parent.dur_stretch"))) (global_stretch (Parameter.get 'Duration_Stretch)) (stretch 1.0)) (if (string-matches (item.name state) "pau_.*") and sentence final pauses to be 150ms , but there will also sentence initial pauses of 150ms so we can treat all pauses as 100ms , there are three states so we use 50ms (set! zdur (/ (- 0.05 (car (cdr ph_info))) (car (cdr (cdr ph_info)))))) (if (not (string-equal seg_stretch "0")) (setq stretch (* stretch seg_stretch))) (if (not (string-equal syl_stretch "0")) (setq stretch (* stretch syl_stretch))) (if (not (string-equal tok_stretch "0")) (setq stretch (* stretch tok_stretch))) (if (not (string-equal global_stretch "0")) (setq stretch (* stretch global_stretch))) (if ph_info (* stretch zdur))) (begin (format t "ClusterGen_state_duration: no dur phone info for %s\n" (item.name state)) 0.1)))) (define (ClusterGen_make_mcep utt) (let ((num_frames 0) (frame_advance cg:frame_shift) (end 0.0) (hmmstate_dur)) Make HMMstate relation and items ( three per phone ) (utt.relation.create utt "mcep") (utt.relation.create utt "mcep_link") (mapcar (lambda (state) (set! start end) (set! hmmstate_dur (ClusterGen_state_duration state)) (if (< hmmstate_dur frame_advance) (set! hmmstate_dur frame_advance)) (set! end (+ start hmmstate_dur)) (item.set_feat state "end" end) (set! mcep_parent (utt.relation.append utt 'mcep_link state)) (while (<= (* (+ 0 num_frames) frame_advance) end) (set! mcep_frame (utt.relation.append utt 'mcep)) (item.append_daughter mcep_parent mcep_frame) (item.set_feat mcep_frame "frame_number" num_frames) (item.set_feat mcep_frame "name" (item.name mcep_parent)) (set! num_frames (+ 1 num_frames)) ) ) (utt.relation.items utt 'HMMstate)) (mapcar (lambda (seg) (item.set_feat seg "end" (item.feat seg "R:segstate.daughtern.end"))) (utt.relation.items utt 'Segment)) (utt.set_feat utt "param_track_num_frames" num_frames) utt) ) Some feature functions specific to CG , some of these are just (define (mcep_12 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 12)) (define (mcep_11 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 11)) (define (mcep_10 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 10)) (define (mcep_9 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 9)) (define (mcep_8 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 8)) (define (mcep_7 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 7)) (define (mcep_6 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 6)) (define (mcep_5 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 5)) (define (mcep_4 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 4)) (define (mcep_3 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 3)) (define (mcep_2 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 2)) (define (mcep_1 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 1)) (define (mcep_0 i) (track.get (utt.feat (item.get_utt i) "param_track") (item.feat i "frame_number") 0)) (define (v_value i) (track.get clustergen_param_vectors (item.feat i "clustergen_param_frame") (- (track.num_channels clustergen_param_vectors) 2)) ) (define (cg_break s) "(cg_break s) 0, if word internal, 1 if word final, 4 if phrase final, we ignore 3/4 distinguinction in old syl_break" (let ((x (item.feat s "syl_break"))) (cond ((string-equal "0" x) (string-append x)) ((string-equal "1" x) (string-append x)) ((string-equal "0" (item.feat s "R:SylStructure.parent.n.name")) "4") (t "3")))) (define (cg_frame_voiced s) (if (and (string-equal "-" (item.feat s "R:mcep_link.parent.R:segstate.parent.ph_vc")) (string-equal "-" (item.feat s "R:mcep_link.parent.R:segstate.parent.ph_cvox"))) 0 1) ) (define (cg_duration i) (if (item.prev i) (- (item.feat i "end") (item.feat i "p.end")) (item.feat i "end"))) (define (cg_state_pos i) (let ((n (item.name i))) (cond ((not (string-equal n (item.feat i "p.name"))) "b") ((string-equal n (item.feat i "n.name")) "m") (t "e")))) (define (cg_state_place i) (let ((start (item.feat i "R:mcep_link.parent.daughter1.frame_number")) (end (item.feat i "R:mcep_link.parent.daughtern.frame_number")) (this (item.feat i "frame_number"))) (if (eq? 0.0 (- end start)) 0 (/ (- this start) (- end start))))) (define (cg_state_index i) (let ((start (item.feat i "R:mcep_link.parent.daughter1.frame_number")) (this (item.feat i "frame_number"))) (- this start))) (define (cg_state_rindex i) (let ((end (item.feat i "R:mcep_link.parent.daughtern.frame_number")) (this (item.feat i "frame_number"))) (- end this))) (define (cg_phone_place i) (let ((start (item.feat i "R:mcep_link.parent.R:segstate.parent.daughter1.R:mcep_link.daughter1.frame_number")) (end (item.feat i "R:mcep_link.parent.R:segstate.parent.daughtern.R:mcep_link.daughtern.frame_number")) (this (item.feat i "frame_number"))) (if (eq? 0.0 (- end start)) 0 (/ (- this start) (- end start))))) (define (cg_phone_index i) (let ((start (item.feat i "R:mcep_link.parent.R:segstate.parent.daughter1.R:mcep_link.daughter1.frame_number")) (this (item.feat i "frame_number"))) (- this start))) (define (cg_phone_rindex i) (let ((end (item.feat i "R:mcep_link.parent.R:segstate.parent.daughtern.R:mcep_link.daughtern.frame_number")) (this (item.feat i "frame_number"))) (- end this))) (define (cg_utt_fileid i) (utt.feat (item.get_utt i) "fileid")) (define (cg_position_in_sentenceX x) (/ (item.feat x "R:mcep_link.parent.end") (item.feat x "R:mcep_link.parent.R:segstate.parent.R:Segment.last.end"))) (define (cg_position_in_sentence x) (let ((sstart (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Word.first.R:SylStructure.daughter1.daughter1.R:Segment.p.end")) (send (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Word.last.R:SylStructure.daughtern.daughtern.R:Segment.end"))) (set! xyx (if (eq? 0.0 (- send sstart)) -1 (/ (- (* cg:frame_shift (item.feat x "frame_number")) sstart) (- send sstart)))) xyx )) (define (cg_find_phrase_number x) (cond ((item.prev x) (+ 1 (cg_find_phrase_number (item.prev x)))) (t 0))) (define (cg_find_rphrase_number x) (cond ((item.next x) (+ 1 (cg_find_rphrase_number (item.next x)))) (t 0))) (define (cg_position_in_phrase x) (let ((pstart (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughter1.R:SylStructure.daughter1.daughter1.R:Segment.p.end")) (pend (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughtern.R:SylStructure.daughtern.daughtern.R:Segment.end")) (phrasenumber (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.lisp_cg_find_phrase_number"))) (set! xyx (if (eq? 0.0 (- pend pstart)) -1 (/ (- (* cg:frame_shift (item.feat x "frame_number")) pstart) (- pend pstart))))) xyx ) ) (define (cg_position_in_phrasep x) (let ((pstart (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughter1.R:SylStructure.daughter1.daughter1.R:Segment.p.end")) (pend (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.daughtern.R:SylStructure.daughtern.daughtern.R:Segment.end")) (phrasenumber (item.feat x "R:mcep_link.parent.R:segstate.parent.R:SylStructure.parent.parent.R:Phrase.parent.lisp_cg_find_phrase_number"))) (set! xyx (if (eq? 0.0 (- pend pstart)) -1 (+ phrasenumber (/ (- (* cg:frame_shift (item.feat x "frame_number")) pstart) (- pend pstart))))) xyx ) ) Smoothing functions ( sort of instead of mlpg ) (define (cg_F0_smooth track j) (let ((p 0.0) (i 0) (num_frames (- (track.num_frames track) 1))) (set! i 1) (while (< i num_frames) (set! this (track.get track i j)) (set! next (track.get track (+ i 1) j)) (if (> this 0.0) (track.set track i j (/ (+ (if (> p 0.0) p this) this (if (> next 0.0) next this)) 3.0))) (set! p this) (set! i (+ 1 i))) ) ) (define (cg_mcep_smooth track j) (let ((p 0.0) (i 0) (num_frames (- (track.num_frames track) 1))) (set! i 1) (while (< i num_frames) (set! this (track.get track i j)) (set! next (track.get track (+ i 1) j)) (track.set track i j (/ (+ p this next) 3.0)) (set! p this) (set! i (+ 1 i))) ) ) (defvar cg_predict_unvoiced t) (define (ClusterGen_predict_F0 mcep f0_val param_track) "(ClusterGen_predict_F0 mcep frame param_track) Predict the F0 (or not)." (if (and cg_predict_unvoiced (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_vc")) (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_cvox"))) ) (define (ClusterGen_mcep_voiced mcep) (if (and cg_predict_unvoiced (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_vc")) (string-equal "-" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_cvox"))) nil t)) Default voice / unvoiced prediction : can be trained with bin / make_vuv_model (defvar cg_vuv_tree '((lisp_v_value < 5.5) ((0)) ((1)))) (define (ClusterGen_voicing_v mcep) (let ((vp (car (last (wagon mcep cg_vuv_tree))))) (if cg:vuv_predict_dump (mapcar (lambda (f) (format cg:vuv_predict_dump "%s " (item.feat mcep f))) cg_vuv_predict_features) (format cg:vuv_predict_dump "\n"))) (cond ((string-equal "pau" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.name")) nil) ((equal? vp 1) t) (t nil)))) (define (ClusterGen_voicing_v_traj mcep i params) (let ((vvv (track.get params i 102))) (cond ((string-equal "pau" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.name")) nil) ((string-equal "+" (item.feat mcep "R:mcep_link.parent.R:segstate.parent.ph_vc")) t) ((> vvv 0.4) t) (t nil)))) (define (cg_do_gmm_transform utt) "(cmu_us_rms_transform::convfilter utt) Filter synthesized voice with transformation filter and reload waveform." (let ((wfile1 (make_tmp_filename)) (wfile2 (make_tmp_filename)) (wfile3 (make_tmp_filename)) (wfile4 (make_tmp_filename)) ) (utt.save utt wfile3) (track.save (utt.feat utt "param_track") wfile4) (system (format nil "(cd %s && csh $FESTVOXDIR/src/vc/scripts/VConvFestival_cg.csh $FESTVOXDIR/src/vc/src param/source-target_param.list %s %s %s %s)" wfile2)) (set! new_track (track.load wfile2)) (utt.set_feat utt "param_track" new_track) (delete-file wfile1) (delete-file wfile2) (delete-file wfile3) (delete-file wfile4) utt )) (define (cg_do_mlpg param_track) do on the params (if (boundp 'mlpg) (begin (mlpg param_track)) old version with external mlpg script (let ((trackname (make_tmp_filename)) (mlpgtrack (make_tmp_filename)) ) (track.save param_track trackname "est") (if cg:gv (begin (format t "with gv\n") (system (format nil "$FESTVOXDIR/src/clustergen/cg_mlpg %s %s %s %s" trackname mlpgtrack cg_gv_vm_filename cg_gv_vv_filename ))) (system (format nil "$FESTVOXDIR/src/clustergen/cg_mlpg %s %s" trackname mlpgtrack))) (set! postmlpg (track.load mlpgtrack)) (delete-file trackname) (delete-file mlpgtrack) postmlpg) ))) (define (cg_all_f0 m) (let ((all_f0 (wagon m (cadr (assoc_string "all" clustergen_f0_all))))) (cadr all_f0))) (define (cg_all_f0f0 m) (let ((all_f0 (wagon m (cadr (assoc_string "all" clustergen_f0_all)))) (all_f0f0 (wagon m (cadr (assoc_string "all_f0_diff" clustergen_f0_all))))) (- (cadr all_f0) (cadr all_f0f0)))) (define (cg_F0_interpolate_linear utt param_track) (mapcar (lambda (syl) (set! start_index (item.feat syl "R:SylStructure.daughter1.R:segstate.daughter1.R:mcep_link.daughter1.frame_number")) (set! end_index (item.feat syl "R:SylStructure.daughtern.R:segstate.daughter1.R:mcep_link.daughtern.frame_number")) (set! mid_index (nint (/ (+ start_index end_index) 2.0))) (set! start_f0 (track.get param_track start_index 0)) (set! mid_f0 (track.get param_track mid_index 0)) (set! end_f0 (track.get param_track (- end_index 1) 0)) start_index start_f0 mid_index mid_f0 end_index end_f0 ) (set! m (/ (- mid_f0 start_f0) (- mid_index start_index))) (set! i 1) (while (< (+ i start_index) mid_index) ( format t " % l % " ( + i start_index ) ( + start_f0 ( * i m ) ) ) (track.set param_track (+ i start_index) 0 (+ start_f0 (* i m))) (set! i (+ i 1))) (set! m (/ (- end_f0 mid_f0) (- end_index mid_index))) (set! i 1) (while (< (+ i mid_index) end_index) (track.set param_track (+ i mid_index) 0 (+ mid_f0 (* i m))) (set! i (+ i 1))) ) (utt.relation.items utt 'Syllable)) utt ) (define (catmull_rom_spline p p0 p1 p2 p3) (let ((q nil)) (set! q (* 0.5 (+ (* 2 p1) (* (+ (* -1 p0) p2) p) (* (+ (- (* 2 p0) (* 5 p1)) (- (* 4 p2) p3)) (* p p)) (* (+ (* -1 p0) (- (* 3 p1) (* 3 p2)) p3) (* p p p))))) q)) (define (cg_F0_interpolate_spline utt param_track) (set! mid_f0 -1) (set! end_f0 -1) (mapcar (lambda (syl) (set! start_index (item.feat syl "R:SylStructure.daughter1.R:segstate.daughter1.R:mcep_link.daughter1.frame_number")) (set! end_index (item.feat syl "R:SylStructure.daughtern.R:segstate.daughtern.R:mcep_link.daughtern.frame_number")) (set! mid_index (nint (/ (+ start_index end_index) 2.0))) (set! start_f0 (track.get param_track start_index 0)) (if (> end_f0 0) (set! start_f0 end_f0)) (if (< mid_f0 0) (set! pmid_f0 start_f0) (set! pmid_f0 mid_f0)) (set! mid_f0 (track.get param_track mid_index 0)) (if (item.next syl) (set! end_f0 (/ (+ (track.get param_track (- end_index 1) 0) (track.get param_track end_index 0)) 2.0)) (set! end_f0 (track.get param_track (- end_index 1) 0))) (set! nmid_f0 end_f0) (if (item.next syl) (begin (set! nsi (item.feat syl "n.R:SylStructure.daughter1.R:segstate.daughter1.R:mcep_link.daughter1.frame_number")) (set! nei (item.feat syl "n.R:SylStructure.daughtern.R:segstate.daughtern.R:mcep_link.daughtern.frame_number")) (set! nmi (nint (/ (+ nsi nei) 2.0))) (set! nmid_f0 (track.get param_track nmi 0)))) ( format t " Syl : % s % 2.1f % d % 2.1f % d % 2.1f % d % 2.1f % 2.1f % d\n " start_index start_f0 mid_index mid_f0 end_index end_f0 nmid_f0 end_index ) (set! m (/ 1.0 (- mid_index start_index))) (set! i 0) (while (< (+ i start_index) mid_index) (track.set param_track (+ i start_index) 0 (catmull_rom_spline (* i m) pmid_f0 start_f0 mid_f0 end_f0)) (set! i (+ i 1))) (set! m (/ 1.0 (- end_index mid_index))) (set! i 0) (while (< (+ i mid_index) end_index) (track.set param_track (+ i mid_index) 0 (catmull_rom_spline (* i m) start_f0 mid_f0 end_f0 nmid_f0)) (set! i (+ i 1))) ) (utt.relation.items utt 'Syllable)) utt ) (set! cg_F0_interpolate cg_F0_interpolate_spline) (define (ClusterGen_predict_mcep utt) (let ((param_track nil) (frame_advance cg:frame_shift) (frame nil) (f nil) (f0_val) (cg_name_feature "name") (num_channels (/ (track.num_channels clustergen_param_vectors) (if cg:mlpg 1 2))) (num_frames (utt.feat utt "param_track_num_frames")) ) (set! i 0) (set! param_track (track.resize nil num_frames num_channels)) (utt.set_feat utt "param_track" param_track) (mapcar (lambda (mcep) (let ((mcep_tree (assoc_string (item.feat mcep cg_name_feature) clustergen_mcep_trees)) (mcep_tree_delta (assoc_string (item.feat mcep cg_name_feature) (if cg:multimodel clustergen_delta_mcep_trees nil))) (mcep_tree_str (assoc_string (item.feat mcep cg_name_feature) (if (boundp 'clustergen_str_mcep_trees) clustergen_str_mcep_trees nil))) (f0_tree (assoc_string (item.feat mcep cg_name_feature) clustergen_f0_trees)) ) (if (null mcep_tree) (format t "ClusterGen: can't find cluster tree for %s\n" (item.name mcep)) (begin (set! f0_val (wagon mcep (cadr f0_tree)) ( list 1.0 ( cg_all_f0 mcep ) ) ) (track.set param_track i 0 (cadr f0_val)) (set! frame (wagon mcep (cadr mcep_tree))) (if cg:multimodel (set! dframe (wagon mcep (cadr mcep_tree_delta)))) (set! j 1) (set! f (car frame)) (item.set_feat mcep "clustergen_param_frame" f) (if cg:rfs (set! rfs_info (mapcar (lambda (rf_model) (list (cadr rf_model) (car (wagon mcep (cadr (assoc_string (item.feat mcep cg_name_feature) (car rf_model))))))) cg:rfs_models))) (if cg:multimodel (track.set param_track i 0 (/ (+ (cadr f0_val) (track.get clustergen_delta_param_vectors (car dframe) 0) (track.get clustergen_param_vectors f 0)) 3.0))) (while (< j num_channels) (cond ((not (null cg:rfs_models)) (track.set param_track i j (/ (apply + (mapcar (lambda (rfs_item) (track.get (car rfs_item) (cadr rfs_item) (* (if cg:mlpg 1 2) j))) rfs_info)) (length rfs_info)))) ((not (null cg:multimodel)) (begin (if (and (boundp 'clustergen_str_mcep_trees) (> j (* 2 (+ 50))) (< j 112)) (begin (track.set param_track i j (/ (+ (track.get clustergen_str_param_vectors (car (wagon mcep (cadr mcep_tree_str))) (* (if cg:mlpg 1 2) j)) (track.get clustergen_delta_param_vectors (car dframe) (* (if cg:mlpg 1 2) j)) (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j)) ) 3.0) )) (begin (track.set param_track i j (/ (+ (track.get clustergen_delta_param_vectors (car dframe) (* (if cg:mlpg 1 2) j)) (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j)) ) 2.0)))) )) (t (track.set param_track i j (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j))) )) (set! j (+ 1 j))) (set! j (- num_channels 1)) (track.set param_track i j (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j))) )) (track.set_time param_track i (+ cg:initial_frame_offset (* i frame_advance))) (set! i (+ 1 i)))) (utt.relation.items utt 'mcep)) (if cg:mixed_excitation (let ((nf (track.num_frames param_track)) (f 0) (c 0)) (set! str_params (track.resize nil nf 5)) (set! f 0) (while (< f nf) (track.set_time str_params f (track.get_time param_track f)) (set! c 0) (while (< c 5) (track.set str_params f c (track.get param_track f (* 2 (+ c )))) (set! c (+ 1 c))) (set! f (+ 1 f))) (utt.set_feat utt "str_params" str_params))) (if cg:F0_interpolate (cg_F0_interpolate utt param_track)) (if (or cg:vuv cg:with_v) (let ((nf (track.num_frames param_track)) (nc (- (track.num_channels param_track) 2)) (f 0) (c 0)) (set! nnn_track (track.resize nil nf nc)) (while (< f nf) (track.set_time nnn_track f (track.get_time param_track f)) (set! c 0) (while (< c nc) (track.set nnn_track f c (track.get param_track f c)) (set! c (+ 1 c))) (set! f (+ 1 f))) (set! param_track nnn_track) )) MLPG (let ((nf (track.num_frames param_track)) (f 0) (c 0)) (if cg:debug (format t "cg:debug calling mlpg\n")) (set! nnn_track (track.resize nil nf nc)) (while (< f nf) (track.set_time nnn_track f (track.get_time param_track f)) (set! c 0) (while (< c nc) (track.set nnn_track f c (track.get param_track f c)) (set! c (+ 1 c))) (set! f (+ 1 f))) (set! param_track nnn_track) (set! new_param_track (cg_do_mlpg param_track)) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if (and (not cg:mlpg) cg:deltas) (set! new_param_track (track.resize param_track (track.num_frames param_track) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if cg:F0_smooth (cg_F0_smooth param_track 0)) (if cg_predict_unvoiced (begin (set! i 0) (mapcar (lambda (frame) ( not ( ClusterGen_mcep_voiced frame ) ) (not (ClusterGen_voicing_v frame)) (track.set param_track i 0 0.0)) (set! i (+ 1 i))) (utt.relation.items utt 'mcep)))) (if cg:param_smooth (mapcar (lambda (x) (cg_mcep_smooth param_track x)) '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25))) utt ) ) CGV : prediction with (define (cgv_reverse_probs pdf) (cond ((null pdf) nil) ((eq (car (cdr (car pdf))) 0) (cgv_reverse_probs (cdr pdf))) (t (cons (list (car (car pdf)) (/ (car (cdr (car pdf))) (cgv_prob (car (car pdf))))) (cgv_reverse_probs (cdr pdf)))))) (define (cgv_prob c) (let ((xxx (assoc_string c cgv_class_probs))) (if xxx (car (cdr xxx)) 0.000012))) (define (cgv_cand_function s) (let ((mcep_tree (assoc_string (item.name s) clustergen_mcep_trees)) (probs nil)) (cond ((string-equal "S" (item.name s)) (set! probs (cgv_reverse_probs '((S 1))))) ((string-equal "E" (item.name s)) (set! probs (cgv_reverse_probs '((E 1))))) (mcep_tree (set! probs (cgv_reverse_probs (cdr (reverse (wagon s (cadr mcep_tree))))))) (t (format t "ClusterGen: cgv can't find cluster tree for %s\n" (item.name s)) (set! probs nil))) ( format t " % s % " ( item.name s ) probs ) probs)) (define (ClusterGen_predict_cgv utt) (format t "predict cgv\n") (let ((param_track nil) (frame_advance cg:frame_shift) (frame nil) (f nil) (f0_val) (num_channels (/ (track.num_channels clustergen_param_vectors) (if cg:mlpg 1 2))) (num_frames (utt.feat utt "param_track_num_frames")) ) (set! i 0) (set! param_track (track.resize nil num_frames num_channels)) (utt.set_feat utt "param_track" param_track) (utt.relation.create utt 'cseq) (set! citem (utt.relation.append utt 'cseq nil)) (item.set_feat citem 'name 'S) (mapcar (lambda (m) (set! citem (utt.relation.append utt 'cseq m))) (utt.relation.items utt 'mcep)) (set! citem (utt.relation.append utt 'cseq nil)) (item.set_feat citem 'name 'E) (set! gen_vit_params (list (list 'Relation "cseq") (list 'return_feat "clustergen_class") (list 'p_word "S") (list 'pp_word "S") (list 'wfstname 'cgv_wfst) (list 'cand_function 'cgv_cand_function))) (Gen_Viterbi utt) (mapcar (lambda (mcep) (let ((f0_tree (assoc_string (item.name mcep) clustergen_f0_trees))) (if (null f0_tree) (format t "ClusterGen: can't find cluster tree for %s\n" (item.name mcep)) (begin (set! f0_val (wagon mcep (cadr f0_tree))) (if (eq (cadr f0_val) 0.0) (track.set param_track i 0 0.0) (track.set param_track i 0 (cadr f0_val))) (set! j 1) (set! f (parse-number (string-after (item.feat mcep "clustergen_class") "c"))) (item.set_feat mcep "clustergen_param_frame" f) (while (< j num_channels) (track.set param_track i j (track.get clustergen_param_vectors f (* (if cg:mlpg 1 2) j)) ) (set! j (+ 1 j))))) (track.set_time param_track i (+ cg:initial_frame_offset (* i frame_advance))) (set! i (+ 1 i)))) (utt.relation.items utt 'mcep)) MLPG (begin (if cg:debug (format t "cg:debug calling mlpg\n")) (set! new_param_track (cg_do_mlpg param_track)) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if (and (not cg:mlpg) cg:deltas) (set! new_param_track (track.resize param_track (track.num_frames param_track) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if cg:F0_smooth (cg_F0_smooth param_track 0)) (if cg_predict_unvoiced (begin (set! i 0) (mapcar (lambda (frame) (if (not (ClusterGen_mcep_voiced frame)) (track.set param_track i 0 0.0)) (set! i (+ 1 i))) (utt.relation.items utt 'mcep)))) (if cg:param_smooth (mapcar (lambda (x) (cg_mcep_smooth param_track x)) '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25))) utt ) ) Trajectory prediction functions ( including ola ) (define (cg_voiced state) "(cg_voiced state) t if this state is voiced, nil otherwise." (if (and cg_predict_unvoiced (string-equal "-" (item.feat state "R:segstate.parent.ph_vc")) (string-equal "-" (item.feat state "R:segstate.parent.ph_cvox"))) nil t)) (define (ClusterGen_predict_trajectory utt) (let ((param_track nil) (frame_advance cg:frame_shift) (frame nil) (f nil) (f0_val) (num_channels (/ (track.num_channels clustergen_param_vectors) (if cg:mlpg 1 2))) ) (set! i 0) (set! param_track (track.resize nil (utt.feat utt "param_track_num_frames") num_channels)) (utt.set_feat utt "param_track" param_track) ( set ! param_track ( utt.feat utt " param_track " ) ) (mapcar (lambda (state) (let ((mcep_tree (assoc_string (item.name state) clustergen_mcep_trees)) ( ( assoc_string ( item.name mcep ) clustergen_f0_trees ) ) ) (if (null mcep_tree) (format t "ClusterGen: can't find cluster tree for %s\n" (item.name state)) (begin (set! trajectory (wagon state (cadr mcep_tree))) (if (item.relation.daughters state 'mcep_link) (begin (if (assoc 'cg::trajectory_ola clustergen_mcep_trees) joint ( if ( assoc ' traj::clustergen_mcep_trees ) (cg:add_trajectory_ola (caar trajectory) (cadr (car trajectory)) state num_channels param_track frame_advance) (cg:add_trajectory (caar trajectory) (cadr (car trajectory)) state num_channels param_track frame_advance)))) )))) (utt.relation.items utt 'HMMstate)) (if (or cg:vuv cg:with_v) (let ((nf (track.num_frames param_track)) (nc (- (track.num_channels param_track) 2)) (f 0) (c 0)) (set! full_param_track param_track) (set! nnn_track (track.resize nil nf nc)) (while (< f nf) (track.set_time nnn_track f (track.get_time param_track f)) (set! c 0) (while (< c nc) (track.set nnn_track f c (track.get param_track f c)) (set! c (+ 1 c))) (set! f (+ 1 f))) (set! param_track nnn_track) )) MLPG (if cg:mlpg (begin (if cg:debug (format t "cg:debug calling mlpg\n")) (set! new_param_track (cg_do_mlpg param_track)) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if (and (not cg:mlpg) cg:deltas) (set! new_param_track (track.resize param_track (track.num_frames param_track) (utt.set_feat utt "param_track" new_param_track) (set! param_track new_param_track))) (if cg:F0_smooth (cg_F0_smooth param_track 0)) (if cg_predict_unvoiced (begin (set! i 0) (mapcar (lambda (frame) ( not ( ClusterGen_mcep_voiced frame ) ) (not (ClusterGen_voicing_v_traj frame i full_param_track)) (track.set param_track i 0 0.0)) (set! i (+ 1 i))) (utt.relation.items utt 'mcep)))) (if cg:param_smooth (mapcar (lambda (x) (cg_mcep_smooth param_track x)) '( 1 2 3 ) )) utt ) ) (define (cg:add_trajectory s_start s_frames state num_channels param_track frame_advance) "(cg:add_trajectory start n state num_channels) Add trajectory to daughters of state, interpolating as necessary." (let ((j 0) (i 0) (mceps (item.relation.daughters state 'mcep_link))) (set! t_start (item.feat (car mceps) "frame_number")) (set! t_frames (length mceps)) (set! m (/ (- s_frames 1) t_frames)) (set! f 0) (while (< i t_frames) (set! s_pos (nint (+ s_start f))) (track.set param_track (+ i t_start) 0 (track.get clustergen_param_vectors s_pos 0)) (set! j 1) (while (< j num_channels) (track.set param_track (+ i t_start) j joint ( + ( * 0.35 ( track.get param_track ( + i t_start ) j ) ) ( * 0.65 ( track.get traj::clustergen_param_vectors s_pos ( * 2 j ) ) ) ) ) (track.get clustergen_param_vectors s_pos (* (if cg:mlpg 1 2) j))) (set! j (+ 1 j))) (set! f (+ m f)) (track.set_time param_track (+ i t_start) (+ cg:initial_frame_offset (* (+ i t_start) frame_advance))) (set! i (+ i 1)) ) ) ) (define (cg:add_trajectory_ola s_start s_frames state num_channels param_track frame_advance) "(cg:add_trajectory start n state num_channels) Add trajectory to daughters of state, interpolating as necessary." (let ((j 0) (i 0) (s1l 0) (s2l 0) (m 0.0) (w 0.0) (t_start 0) (t_frames 0) (s_offset 0) (mceps1 nil) (mceps2 nil)) (set! i 0) (while (< i s_frames) (if (equal? -1.0 (track.get clustergen_param_vectors (+ s_start i) 0)) (set! s1l i)) (set! i (+ i 1))) (if (and (item.prev state) (item.relation.daughters (item.prev state) 'mcep_link) (> s1l 0)) (set! mceps1 (item.relation.daughters (item.prev state) 'mcep_link)) (set! first_half_delta (/ 1.0 (length mceps1))) (set! t_start (item.feat (car mceps1) "frame_number")) (set! t_frames (length mceps1)) (set! m (/ s1l t_frames)) (set! i 0) (set! w 0.0) (while (< i t_frames) (set! s_offset (nint (* i m))) (if (not (< s_offset s1l)) (begin (set! s_offset (- s1l 1)))) (set! s_pos (+ s_start s_offset)) (if (< (track.get clustergen_param_vectors s_pos 0) 0) (format t "assigning pre -1/-2 %d %d %f\n" s_pos i m)) (track.set param_track (+ i t_start) 0 (+ (* (- 1.0 w) (track.get param_track (+ i t_start) 0)) (* w (track.get clustergen_param_vectors s_pos 0)))) (set! j 1) (while (< j num_channels) (track.set param_track (+ i t_start) j (+ (* (- 1.0 w) (track.get param_track (+ i t_start) j)) (* w (track.get clustergen_param_vectors s_pos (* (if cg:mlpg 1 2) j)) ) ) ) (set! j (+ 1 j))) (set! i (+ 1 i)) (set! w (+ w first_half_delta)) (if (> w 1.0) (set! w 1.0)) ) )) (set! mceps2 (item.relation.daughters state 'mcep_link)) (set! t_start (item.feat (car mceps2) "frame_number")) (set! t_frames (length mceps2)) (set! s2l (- s_frames (+ s1l 2))) (set! s2_start (+ s_start s1l 1)) (set! m (/ s2l t_frames)) (set! i 0) (while (< i t_frames) (set! s_offset (nint (* i m))) (if (not (< s_offset s2l)) (set! s_offset (- s2l 1))) (set! s_pos (+ s2_start s_offset)) (if (< (track.get clustergen_param_vectors s_pos 0) 0) (format t "assigning -1/-2 %d %d %f %f\n" s_pos i m (track.get clustergen_param_vectors s_pos 0))) (track.set param_track (+ i t_start) 0 (track.get clustergen_param_vectors s_pos 0)) (set! j 1) (while (< j num_channels) (track.set param_track (+ i t_start) j (track.get clustergen_param_vectors s_pos (* (if cg:mlpg 1 2) j))) (set! j (+ 1 j))) (track.set_time param_track (+ i t_start) (+ cg:initial_frame_offset (* (+ i t_start) frame_advance))) (set! i (+ 1 i)) ) ) ) (define (build_cg_vc_source datafile) (mapcar (lambda (x) (format t "%s Build source files for VC adaptation\n" (car x)) (set! utt1 (SynthText (cadr x))) (utt.save.wave utt1 (format nil "vc/wav/source/%s.wav" (car x))) (track.save (utt.feat utt1 "param_track") "param.track") (system (format nil "$FESTVOXDIR/src/vc/scripts/get_f0mcep %s param.track vc\n" (car x))) ) (load datafile t)) t ) Sort of historical it should be set in INST_LANG_VOX_cg.scm ( if ( boundp ' mlsa_resynthesis ) (define (cg_wave_synth_deltas utt) (let ((trackname (make_tmp_filename)) (wavename (make_tmp_filename)) ) (track.save (utt.feat utt "param_track") trackname "est") (system (format nil "$FESTVOXDIR/src/clustergen/cg_resynth_deltas %s %s" trackname wavename)) (utt.import.wave utt wavename) (delete-file trackname) (delete-file wavename) utt) ) (set! cluster_synth_method cg_wave_synth) (provide 'clustergen)
361378d708f14c7b358e287ce29591c2dbcd9ba5f765c926f575e88ec4767077
ruedigergad/bowerick
consumer.clj
(fn [m x] (println (type m) x))
null
https://raw.githubusercontent.com/ruedigergad/bowerick/f57155f8d1fba9a66ffae7d69de9225f5dc81326/examples/consumer.clj
clojure
(fn [m x] (println (type m) x))
e092110128109468eda429c9cf8345076ac51a64f0bc6e1a46f7b48808c44a5c
ghc/packages-dph
Prim.hs
{-# OPTIONS_HADDOCK hide #-} |This modules defines the interface between the DPH libraries and the compiler . In particular , -- it exports exactly those definitions that are used by either the desugarer (to remove parallel -- array syntax) or by the vectoriser (to generate vectorised code). -- The DPH libraries can evolve between compiler releases as long as this interface remains the -- same. -- -- WARNING: All modules in this package that need to be vectorised (i.e., are compiled with -- '-fvectorise' must directly or indirectly import this module). This is to ensure that -- the build system does not attempt to compile a vectorised module before all definitions -- that are required by the vectoriser are available. -- #hide module Data.Array.Parallel.Prim ( PArray, PData, PDatas(..), PRepr, PA(..), PR(..), replicatePD, emptyPD, packByTagPD, combine2PD, Scalar(..), scalar_map, scalar_zipWith, scalar_zipWith3, scalar_zipWith4, scalar_zipWith5, scalar_zipWith6, scalar_zipWith7, scalar_zipWith8, Void, Sum2(..), Sum3(..), Wrap(..), void, fromVoid, pvoid, pvoids#, punit, (:->)(..), closure, liftedClosure, ($:), liftedApply, closure1, closure2, closure3, closure4, closure5, closure6, closure7, closure8, Sel2, replicateSel2#, tagsSel2, elementsSel2_0#, elementsSel2_1#, Sels2, lengthSels2#, replicatePA_Int#, replicatePA_Double#, emptyPA_Int#, emptyPA_Double#, packByTagPA_Int#, packByTagPA_Double#, combine2PA_Int#, combine2PA_Double#, tup2, tup3, tup4, tup5 ) where -- We use explicit import lists here to make the vectoriser interface explicit and keep it under -- tight control. -- import Data.Array.Parallel.PArray.Base (PArray) import Data.Array.Parallel.PArray.Scalar (Scalar(..)) import Data.Array.Parallel.PArray.ScalarInstances ( {-we require instances-} ) import Data.Array.Parallel.PArray.PRepr (PRepr, PA(..), replicatePD, emptyPD, packByTagPD, combine2PD) import Data.Array.Parallel.PArray.Types (Void, Sum2(..), Sum3(..), Wrap(..), void, fromVoid) import Data.Array.Parallel.PArray.PReprInstances ( {-we required instances-} ) import Data.Array.Parallel.PArray.PData (PData, PDatas, PR(..)) import Data.Array.Parallel.PArray.PDataInstances (pvoid, punit, Sels2) import Data.Array.Parallel.Lifted.Closure ((:->)(..), closure, liftedClosure, ($:), liftedApply, closure1, closure2, closure3, closure4, closure5, closure6, closure7, closure8) import Data.Array.Parallel.Lifted.Unboxed (Sel2, replicateSel2#, tagsSel2, elementsSel2_0#, elementsSel2_1#, replicatePA_Int#, replicatePA_Double#, emptyPA_Int#, emptyPA_Double#, {- packByTagPA_Int#, packByTagPA_Double# -} combine2PA_Int#, combine2PA_Double#) import Data.Array.Parallel.Lifted.Scalar (scalar_map, scalar_zipWith, scalar_zipWith3, scalar_zipWith4, scalar_zipWith5, scalar_zipWith6, scalar_zipWith7, scalar_zipWith8) import Data.Array.Parallel.Prelude.Tuple (tup2, tup3, tup4) import GHC.Exts packByTagPA_Int#, packByTagPA_Double# :: a packByTagPA_Int# = error "Data.Array.Parallel.Prim: 'packByTagPA_Int#' not implemented" packByTagPA_Double# = error "Data.Array.Parallel.Prim: 'packByTagPA_Double#' not implemented" -- Fake definitions involving PDatas. -- The dph-lifted-copy backend doesn't used PDatas, but we need to define -- this stuff as the vectoriser expects it to be here. The vectoriser will generate instances of the PA dictionary involving -- PDatas, but this backend will never call those methods. pvoids# :: Int# -> PDatas Void pvoids# = error "Data.Array.Parallel.Prim.voids: not used in this backend" lengthSels2# :: Sels2 -> Int# lengthSels2# _ = 0# tup5 :: (PA a, PA b, PA c, PA d) => a :-> b :-> c :-> d :-> e :-> (a, b, c, d, e) tup5 = error "Data.Array.Paralle.Prim.tup5: not used in this backend" data instance PDatas (a, b, c) = PTuple3s (PDatas a) (PDatas b) (PDatas c) data instance PDatas (a, b, c, d) = PTuple4s (PDatas a) (PDatas b) (PDatas c) (PDatas d) data instance PDatas (a, b, c, d, e) = PTuple5s (PDatas a) (PDatas b) (PDatas c) (PDatas d) (PDatas e) newtype instance PDatas (Wrap a) = PWraps (PDatas a)
null
https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-lifted-copy/Data/Array/Parallel/Prim.hs
haskell
# OPTIONS_HADDOCK hide # it exports exactly those definitions that are used by either the desugarer (to remove parallel array syntax) or by the vectoriser (to generate vectorised code). same. WARNING: All modules in this package that need to be vectorised (i.e., are compiled with '-fvectorise' must directly or indirectly import this module). This is to ensure that the build system does not attempt to compile a vectorised module before all definitions that are required by the vectoriser are available. #hide We use explicit import lists here to make the vectoriser interface explicit and keep it under tight control. we require instances we required instances packByTagPA_Int#, packByTagPA_Double# Fake definitions involving PDatas. The dph-lifted-copy backend doesn't used PDatas, but we need to define this stuff as the vectoriser expects it to be here. PDatas, but this backend will never call those methods.
|This modules defines the interface between the DPH libraries and the compiler . In particular , The DPH libraries can evolve between compiler releases as long as this interface remains the module Data.Array.Parallel.Prim ( PArray, PData, PDatas(..), PRepr, PA(..), PR(..), replicatePD, emptyPD, packByTagPD, combine2PD, Scalar(..), scalar_map, scalar_zipWith, scalar_zipWith3, scalar_zipWith4, scalar_zipWith5, scalar_zipWith6, scalar_zipWith7, scalar_zipWith8, Void, Sum2(..), Sum3(..), Wrap(..), void, fromVoid, pvoid, pvoids#, punit, (:->)(..), closure, liftedClosure, ($:), liftedApply, closure1, closure2, closure3, closure4, closure5, closure6, closure7, closure8, Sel2, replicateSel2#, tagsSel2, elementsSel2_0#, elementsSel2_1#, Sels2, lengthSels2#, replicatePA_Int#, replicatePA_Double#, emptyPA_Int#, emptyPA_Double#, packByTagPA_Int#, packByTagPA_Double#, combine2PA_Int#, combine2PA_Double#, tup2, tup3, tup4, tup5 ) where import Data.Array.Parallel.PArray.Base (PArray) import Data.Array.Parallel.PArray.Scalar (Scalar(..)) import Data.Array.Parallel.PArray.PRepr (PRepr, PA(..), replicatePD, emptyPD, packByTagPD, combine2PD) import Data.Array.Parallel.PArray.Types (Void, Sum2(..), Sum3(..), Wrap(..), void, fromVoid) import Data.Array.Parallel.PArray.PData (PData, PDatas, PR(..)) import Data.Array.Parallel.PArray.PDataInstances (pvoid, punit, Sels2) import Data.Array.Parallel.Lifted.Closure ((:->)(..), closure, liftedClosure, ($:), liftedApply, closure1, closure2, closure3, closure4, closure5, closure6, closure7, closure8) import Data.Array.Parallel.Lifted.Unboxed (Sel2, replicateSel2#, tagsSel2, elementsSel2_0#, elementsSel2_1#, replicatePA_Int#, replicatePA_Double#, emptyPA_Int#, emptyPA_Double#, combine2PA_Int#, combine2PA_Double#) import Data.Array.Parallel.Lifted.Scalar (scalar_map, scalar_zipWith, scalar_zipWith3, scalar_zipWith4, scalar_zipWith5, scalar_zipWith6, scalar_zipWith7, scalar_zipWith8) import Data.Array.Parallel.Prelude.Tuple (tup2, tup3, tup4) import GHC.Exts packByTagPA_Int#, packByTagPA_Double# :: a packByTagPA_Int# = error "Data.Array.Parallel.Prim: 'packByTagPA_Int#' not implemented" packByTagPA_Double# = error "Data.Array.Parallel.Prim: 'packByTagPA_Double#' not implemented" The vectoriser will generate instances of the PA dictionary involving pvoids# :: Int# -> PDatas Void pvoids# = error "Data.Array.Parallel.Prim.voids: not used in this backend" lengthSels2# :: Sels2 -> Int# lengthSels2# _ = 0# tup5 :: (PA a, PA b, PA c, PA d) => a :-> b :-> c :-> d :-> e :-> (a, b, c, d, e) tup5 = error "Data.Array.Paralle.Prim.tup5: not used in this backend" data instance PDatas (a, b, c) = PTuple3s (PDatas a) (PDatas b) (PDatas c) data instance PDatas (a, b, c, d) = PTuple4s (PDatas a) (PDatas b) (PDatas c) (PDatas d) data instance PDatas (a, b, c, d, e) = PTuple5s (PDatas a) (PDatas b) (PDatas c) (PDatas d) (PDatas e) newtype instance PDatas (Wrap a) = PWraps (PDatas a)
7767af1714a3232789b8903a0ee9bc28e843195f755a500d3753ccff14a3a8a9
gergoerdi/hm-compo
Parser.hs
# LANGUAGE RecordWildCards # module Language.HM.Parser ( parseSource, Decl(..) , SrcSpanInfo(..), SrcLoc(..), HSE.getPointLoc ) where import Language.HM.Syntax import Language.HM.Pretty import Control.Unification import Data.Functor.Fixedpoint import Data.Map (Map) import qualified Data.Map as Map import Control.Monad (forM) import Text.PrettyPrint import Text.PrettyPrint.HughesPJClass import Language.Haskell.Exts.Parser import Language.Haskell.Exts (SrcSpanInfo, SrcLoc, ParseResult(..)) import qualified Language.Haskell.Exts as HSE data Decl tag = DataDef DCon PolyTy | VarDef Var (Term tag) deriving Show type ParseError = (SrcLoc, String) parseSource :: FilePath -> String -> Either Doc [Decl SrcSpanInfo] parseSource sourceName s = case fromModule =<< parseModuleWithMode mode s of ParseOk decls -> Right decls ParseFailed loc err -> Left $ pPrint loc $$ text err where mode = HSE.defaultParseMode{ HSE.parseFilename = sourceName } err :: (HSE.SrcInfo loc, HSE.Annotated ast) => ast loc -> ParseResult a err ast = ParseFailed (HSE.getPointLoc . HSE.ann $ ast) "Unsupported Haskell syntax" fromModule :: (HSE.SrcInfo loc) => HSE.Module loc -> ParseResult [Decl loc] fromModule (HSE.Module _ Nothing [] [] decls) = concat <$> mapM fromDecl decls fromModule mod = err mod fromName :: (HSE.SrcInfo loc) => HSE.Name loc -> ParseResult String fromName (HSE.Ident _ var) = return var fromName name = err name fromQName :: (HSE.SrcInfo loc) => HSE.QName loc -> ParseResult String fromQName (HSE.UnQual _ name) = fromName name fromQName qname = err qname fromDecl :: (HSE.SrcInfo loc) => HSE.Decl loc -> ParseResult [Decl loc] fromDecl (HSE.DataDecl _ (HSE.DataType _) Nothing dhead cons Nothing) = fromData dhead cons fromDecl decl = do (name, term) <- fromBind decl return [VarDef name term] fromBind :: (HSE.SrcInfo loc) => HSE.Decl loc -> ParseResult (Var, Term loc) fromBind (HSE.PatBind _ (HSE.PVar _ name) (HSE.UnGuardedRhs _ exp) Nothing) = (,) <$> fromName name <*> fromExp exp fromBind decl = err decl fromData :: (HSE.SrcInfo loc) => HSE.DeclHead loc -> [HSE.QualConDecl loc] -> HSE.ParseResult [Decl loc] fromData dhead cons = do (tcon, tvNames) <- splitDataHead dhead let tvs = tvNames `zip` [0..] ty = UTerm $ TApp tcon $ map (UVar . snd) tvs toDConTy = foldr (\t u -> UTerm $ TFun t u) ty forM cons $ \con -> do (dcon, argTys) <- fromCon (Map.fromList tvs) con return $ DataDef dcon $ toDConTy argTys splitDataHead :: (HSE.SrcInfo loc) => HSE.DeclHead loc -> ParseResult (TCon, [String]) splitDataHead dhead = case dhead of HSE.DHead _ dcon -> do dcon <- fromName dcon return (dcon, []) HSE.DHParen _ dhead -> splitDataHead dhead HSE.DHApp _ dhead (HSE.UnkindedVar _ tvName) -> do (dcon, tvs) <- splitDataHead dhead tv <- fromName tvName return (dcon, tvs ++ [tv]) dhead -> err dhead fromCon :: (HSE.SrcInfo loc) => Map String TVar -> HSE.QualConDecl loc -> ParseResult (DCon, [PolyTy]) fromCon tvs (HSE.QualConDecl _ Nothing Nothing (HSE.ConDecl _ dcon tys)) = do dcon <- fromName dcon tys <- mapM (fromTy []) tys return (dcon, tys) where fromTy tyArgs (HSE.TyVar _ tvName) = do tvName <- fromName tvName UVar <$> tv tvName fromTy tyArgs (HSE.TyCon _ qname) = do tcon <- fromQName qname return $ UTerm $ TApp tcon tyArgs fromTy tyArgs (HSE.TyApp _ t u) = do u <- fromTy [] u fromTy (u:tyArgs) t fromTy [] (HSE.TyFun _ t u) = UTerm <$> (TFun <$> fromTy [] t <*> fromTy [] u) fromTy tyArgs (HSE.TyParen _ ty) = fromTy tyArgs ty fromTy _ ty = err ty tv a = maybe (fail "Unsupported: existential type variables") return $ Map.lookup a tvs fromCon tvs qcd = err qcd fromExp :: (HSE.SrcInfo loc) => HSE.Exp loc -> ParseResult (Term loc) fromExp (HSE.Var loc qname) = Tagged loc <$> (Var <$> fromQName qname) fromExp (HSE.Con loc qname) = Tagged loc <$> (Con <$> fromQName qname) fromExp (HSE.Lambda loc [HSE.PVar _ var] body) = Tagged loc <$> (Lam <$> fromName var <*> fromExp body) fromExp (HSE.App loc f e) = Tagged loc <$> (App <$> fromExp f <*> fromExp e) fromExp (HSE.Let loc binds body) = Tagged loc <$> (Let <$> fromBinds binds <*> fromExp body) fromExp (HSE.Case loc exp alts) = Tagged loc <$> (Case <$> fromExp exp <*> mapM fromAlt alts) fromExp (HSE.Paren _ exp) = fromExp exp fromExp exp = err exp fromBinds :: (HSE.SrcInfo loc) => HSE.Binds loc -> ParseResult [(Var, Term loc)] fromBinds (HSE.BDecls _ decls) = mapM fromBind decls fromBinds b = err b fromAlt :: (HSE.SrcInfo loc) => HSE.Alt loc -> ParseResult (Pat loc, Term loc) fromAlt (HSE.Alt _ pat (HSE.UnGuardedRhs _ exp) Nothing) = (,) <$> fromPat pat <*> fromExp exp fromAlt alt = err alt fromPat :: (HSE.SrcInfo loc) => HSE.Pat loc -> ParseResult (Pat loc) fromPat (HSE.PVar loc var) = Tagged loc <$> (PVar <$> fromName var) fromPat (HSE.PWildCard loc) = return $ Tagged loc PWild fromPat (HSE.PApp loc qname pats) = Tagged loc <$> (PCon <$> fromQName qname <*> mapM fromPat pats) fromPat (HSE.PParen _ pat) = fromPat pat fromPat pat = err pat
null
https://raw.githubusercontent.com/gergoerdi/hm-compo/386826e570fc6b6a078927bde85f3941e9a77e87/src/Language/HM/Parser.hs
haskell
# LANGUAGE RecordWildCards # module Language.HM.Parser ( parseSource, Decl(..) , SrcSpanInfo(..), SrcLoc(..), HSE.getPointLoc ) where import Language.HM.Syntax import Language.HM.Pretty import Control.Unification import Data.Functor.Fixedpoint import Data.Map (Map) import qualified Data.Map as Map import Control.Monad (forM) import Text.PrettyPrint import Text.PrettyPrint.HughesPJClass import Language.Haskell.Exts.Parser import Language.Haskell.Exts (SrcSpanInfo, SrcLoc, ParseResult(..)) import qualified Language.Haskell.Exts as HSE data Decl tag = DataDef DCon PolyTy | VarDef Var (Term tag) deriving Show type ParseError = (SrcLoc, String) parseSource :: FilePath -> String -> Either Doc [Decl SrcSpanInfo] parseSource sourceName s = case fromModule =<< parseModuleWithMode mode s of ParseOk decls -> Right decls ParseFailed loc err -> Left $ pPrint loc $$ text err where mode = HSE.defaultParseMode{ HSE.parseFilename = sourceName } err :: (HSE.SrcInfo loc, HSE.Annotated ast) => ast loc -> ParseResult a err ast = ParseFailed (HSE.getPointLoc . HSE.ann $ ast) "Unsupported Haskell syntax" fromModule :: (HSE.SrcInfo loc) => HSE.Module loc -> ParseResult [Decl loc] fromModule (HSE.Module _ Nothing [] [] decls) = concat <$> mapM fromDecl decls fromModule mod = err mod fromName :: (HSE.SrcInfo loc) => HSE.Name loc -> ParseResult String fromName (HSE.Ident _ var) = return var fromName name = err name fromQName :: (HSE.SrcInfo loc) => HSE.QName loc -> ParseResult String fromQName (HSE.UnQual _ name) = fromName name fromQName qname = err qname fromDecl :: (HSE.SrcInfo loc) => HSE.Decl loc -> ParseResult [Decl loc] fromDecl (HSE.DataDecl _ (HSE.DataType _) Nothing dhead cons Nothing) = fromData dhead cons fromDecl decl = do (name, term) <- fromBind decl return [VarDef name term] fromBind :: (HSE.SrcInfo loc) => HSE.Decl loc -> ParseResult (Var, Term loc) fromBind (HSE.PatBind _ (HSE.PVar _ name) (HSE.UnGuardedRhs _ exp) Nothing) = (,) <$> fromName name <*> fromExp exp fromBind decl = err decl fromData :: (HSE.SrcInfo loc) => HSE.DeclHead loc -> [HSE.QualConDecl loc] -> HSE.ParseResult [Decl loc] fromData dhead cons = do (tcon, tvNames) <- splitDataHead dhead let tvs = tvNames `zip` [0..] ty = UTerm $ TApp tcon $ map (UVar . snd) tvs toDConTy = foldr (\t u -> UTerm $ TFun t u) ty forM cons $ \con -> do (dcon, argTys) <- fromCon (Map.fromList tvs) con return $ DataDef dcon $ toDConTy argTys splitDataHead :: (HSE.SrcInfo loc) => HSE.DeclHead loc -> ParseResult (TCon, [String]) splitDataHead dhead = case dhead of HSE.DHead _ dcon -> do dcon <- fromName dcon return (dcon, []) HSE.DHParen _ dhead -> splitDataHead dhead HSE.DHApp _ dhead (HSE.UnkindedVar _ tvName) -> do (dcon, tvs) <- splitDataHead dhead tv <- fromName tvName return (dcon, tvs ++ [tv]) dhead -> err dhead fromCon :: (HSE.SrcInfo loc) => Map String TVar -> HSE.QualConDecl loc -> ParseResult (DCon, [PolyTy]) fromCon tvs (HSE.QualConDecl _ Nothing Nothing (HSE.ConDecl _ dcon tys)) = do dcon <- fromName dcon tys <- mapM (fromTy []) tys return (dcon, tys) where fromTy tyArgs (HSE.TyVar _ tvName) = do tvName <- fromName tvName UVar <$> tv tvName fromTy tyArgs (HSE.TyCon _ qname) = do tcon <- fromQName qname return $ UTerm $ TApp tcon tyArgs fromTy tyArgs (HSE.TyApp _ t u) = do u <- fromTy [] u fromTy (u:tyArgs) t fromTy [] (HSE.TyFun _ t u) = UTerm <$> (TFun <$> fromTy [] t <*> fromTy [] u) fromTy tyArgs (HSE.TyParen _ ty) = fromTy tyArgs ty fromTy _ ty = err ty tv a = maybe (fail "Unsupported: existential type variables") return $ Map.lookup a tvs fromCon tvs qcd = err qcd fromExp :: (HSE.SrcInfo loc) => HSE.Exp loc -> ParseResult (Term loc) fromExp (HSE.Var loc qname) = Tagged loc <$> (Var <$> fromQName qname) fromExp (HSE.Con loc qname) = Tagged loc <$> (Con <$> fromQName qname) fromExp (HSE.Lambda loc [HSE.PVar _ var] body) = Tagged loc <$> (Lam <$> fromName var <*> fromExp body) fromExp (HSE.App loc f e) = Tagged loc <$> (App <$> fromExp f <*> fromExp e) fromExp (HSE.Let loc binds body) = Tagged loc <$> (Let <$> fromBinds binds <*> fromExp body) fromExp (HSE.Case loc exp alts) = Tagged loc <$> (Case <$> fromExp exp <*> mapM fromAlt alts) fromExp (HSE.Paren _ exp) = fromExp exp fromExp exp = err exp fromBinds :: (HSE.SrcInfo loc) => HSE.Binds loc -> ParseResult [(Var, Term loc)] fromBinds (HSE.BDecls _ decls) = mapM fromBind decls fromBinds b = err b fromAlt :: (HSE.SrcInfo loc) => HSE.Alt loc -> ParseResult (Pat loc, Term loc) fromAlt (HSE.Alt _ pat (HSE.UnGuardedRhs _ exp) Nothing) = (,) <$> fromPat pat <*> fromExp exp fromAlt alt = err alt fromPat :: (HSE.SrcInfo loc) => HSE.Pat loc -> ParseResult (Pat loc) fromPat (HSE.PVar loc var) = Tagged loc <$> (PVar <$> fromName var) fromPat (HSE.PWildCard loc) = return $ Tagged loc PWild fromPat (HSE.PApp loc qname pats) = Tagged loc <$> (PCon <$> fromQName qname <*> mapM fromPat pats) fromPat (HSE.PParen _ pat) = fromPat pat fromPat pat = err pat
a63fce5b09406f21f9ba9b2fd53d6269b53050ef16a8cb03a81c8ee82fc01bd5
exercism/clojure
octal.clj
(ns octal) (defn to-decimal [] ;; <- arglist goes here ;; your code goes here )
null
https://raw.githubusercontent.com/exercism/clojure/7ed96a5ae3c471c37db2602baf3db2be3b5a2d1a/exercises/practice/octal/src/octal.clj
clojure
<- arglist goes here your code goes here
(ns octal) )
773675153d8bc9770c1eea212f38653b63c7835be19bf992aa6d0b069381baa6
yallop/ocaml-ctypes
sigset.mli
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open PosixTypes open Ctypes type t = sigset_t ptr val t : sigset_t ptr typ val empty : unit -> t val full : unit -> t val add : t -> int -> unit val del : t -> int -> unit val mem : t -> int -> bool
null
https://raw.githubusercontent.com/yallop/ocaml-ctypes/52ff621f47dbc1ee5a90c30af0ae0474549946b4/examples/sigset/sigset.mli
ocaml
* Copyright ( c ) 2013 . * * This file is distributed under the terms of the MIT License . * See the file LICENSE for details . * Copyright (c) 2013 Jeremy Yallop. * * This file is distributed under the terms of the MIT License. * See the file LICENSE for details. *) open PosixTypes open Ctypes type t = sigset_t ptr val t : sigset_t ptr typ val empty : unit -> t val full : unit -> t val add : t -> int -> unit val del : t -> int -> unit val mem : t -> int -> bool
6330c30c51b6ff0536aa6cc336f7cf5f5fa353c20e5f6dae6704a5580040206f
haskell/lsp
ServerCapabilities.hs
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} # LANGUAGE DuplicateRecordFields # module Language.LSP.Types.ServerCapabilities where import Data.Aeson import Data.Aeson.TH import Data.Text (Text) import Language.LSP.Types.CallHierarchy import Language.LSP.Types.CodeAction import Language.LSP.Types.CodeLens import Language.LSP.Types.Command import Language.LSP.Types.Common import Language.LSP.Types.Completion import Language.LSP.Types.Declaration import Language.LSP.Types.Definition import Language.LSP.Types.DocumentColor import Language.LSP.Types.DocumentHighlight import Language.LSP.Types.DocumentLink import Language.LSP.Types.DocumentSymbol import Language.LSP.Types.FoldingRange import Language.LSP.Types.Formatting import Language.LSP.Types.Hover import Language.LSP.Types.Implementation import Language.LSP.Types.References import Language.LSP.Types.Rename import Language.LSP.Types.SelectionRange import Language.LSP.Types.SemanticTokens import Language.LSP.Types.SignatureHelp import Language.LSP.Types.TextDocument import Language.LSP.Types.TypeDefinition import Language.LSP.Types.Utils import Language.LSP.Types.WorkspaceSymbol -- --------------------------------------------------------------------- data WorkspaceFoldersServerCapabilities = WorkspaceFoldersServerCapabilities { -- | The server has support for workspace folders _supported :: Maybe Bool -- | Whether the server wants to receive workspace folder -- change notifications. -- If a strings is provided the string is treated as a ID -- under which the notification is registered on the client -- side. The ID can be used to unregister for these events -- using the `client/unregisterCapability` request. , _changeNotifications :: Maybe (Text |? Bool) } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkspaceFoldersServerCapabilities data WorkspaceServerCapabilities = WorkspaceServerCapabilities | The server supports workspace folder . Since LSP 3.6 -- @since 0.7.0.0 _workspaceFolders :: Maybe WorkspaceFoldersServerCapabilities } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkspaceServerCapabilities data ServerCapabilities = ServerCapabilities { -- | Defines how text documents are synced. Is either a detailed structure -- defining each notification or for backwards compatibility the -- 'TextDocumentSyncKind' number. -- If omitted it defaults to 'TdSyncNone'. _textDocumentSync :: Maybe (TextDocumentSyncOptions |? TextDocumentSyncKind) -- | The server provides hover support. , _hoverProvider :: Maybe (Bool |? HoverOptions) -- | The server provides completion support. , _completionProvider :: Maybe CompletionOptions -- | The server provides signature help support. , _signatureHelpProvider :: Maybe SignatureHelpOptions -- | The server provides go to declaration support. -- Since LSP 3.14.0 , _declarationProvider :: Maybe (Bool |? DeclarationOptions |? DeclarationRegistrationOptions) -- | The server provides goto definition support. , _definitionProvider :: Maybe (Bool |? DefinitionOptions) | The server provides Goto Type Definition support . Since LSP 3.6 -- @since 0.7.0.0 , _typeDefinitionProvider :: Maybe (Bool |? TypeDefinitionOptions |? TypeDefinitionRegistrationOptions) | The server provides Goto Implementation support . Since LSP 3.6 -- @since 0.7.0.0 , _implementationProvider :: Maybe (Bool |? ImplementationOptions |? ImplementationRegistrationOptions) -- | The server provides find references support. , _referencesProvider :: Maybe (Bool |? ReferenceOptions) -- | The server provides document highlight support. , _documentHighlightProvider :: Maybe (Bool |? DocumentHighlightOptions) -- | The server provides document symbol support. , _documentSymbolProvider :: Maybe (Bool |? DocumentSymbolOptions) -- | The server provides code actions. , _codeActionProvider :: Maybe (Bool |? CodeActionOptions) -- | The server provides code lens. , _codeLensProvider :: Maybe CodeLensOptions -- | The server provides document link support. , _documentLinkProvider :: Maybe DocumentLinkOptions | The server provides color provider support . Since LSP 3.6 -- @since 0.7.0.0 , _colorProvider :: Maybe (Bool |? DocumentColorOptions |? DocumentColorRegistrationOptions) -- | The server provides document formatting. , _documentFormattingProvider :: Maybe (Bool |? DocumentFormattingOptions) -- | The server provides document range formatting. , _documentRangeFormattingProvider :: Maybe (Bool |? DocumentRangeFormattingOptions) -- | The server provides document formatting on typing. , _documentOnTypeFormattingProvider :: Maybe DocumentOnTypeFormattingOptions -- | The server provides rename support. , _renameProvider :: Maybe (Bool |? RenameOptions) | The server provides folding provider support . Since LSP 3.10 -- @since 0.7.0.0 , _foldingRangeProvider :: Maybe (Bool |? FoldingRangeOptions |? FoldingRangeRegistrationOptions) -- | The server provides execute command support. , _executeCommandProvider :: Maybe ExecuteCommandOptions | The server provides selection range support . Since LSP 3.15 , _selectionRangeProvider :: Maybe (Bool |? SelectionRangeOptions |? SelectionRangeRegistrationOptions) -- | The server provides call hierarchy support. , _callHierarchyProvider :: Maybe (Bool |? CallHierarchyOptions |? CallHierarchyRegistrationOptions) -- | The server provides semantic tokens support. -- @since 3.16.0 , _semanticTokensProvider :: Maybe (SemanticTokensOptions |? SemanticTokensRegistrationOptions) -- | The server provides workspace symbol support. , _workspaceSymbolProvider :: Maybe (Bool |? WorkspaceSymbolOptions) -- | Workspace specific server capabilities , _workspace :: Maybe WorkspaceServerCapabilities -- | Experimental server capabilities. , _experimental :: Maybe Value } deriving (Show, Read, Eq) deriveJSON lspOptions ''ServerCapabilities
null
https://raw.githubusercontent.com/haskell/lsp/ce1a4538508b2c393e0f36a888717b7e5c7f08a9/lsp-types/src/Language/LSP/Types/ServerCapabilities.hs
haskell
# LANGUAGE TemplateHaskell # # LANGUAGE TypeOperators # --------------------------------------------------------------------- | The server has support for workspace folders | Whether the server wants to receive workspace folder change notifications. If a strings is provided the string is treated as a ID under which the notification is registered on the client side. The ID can be used to unregister for these events using the `client/unregisterCapability` request. | Defines how text documents are synced. Is either a detailed structure defining each notification or for backwards compatibility the 'TextDocumentSyncKind' number. If omitted it defaults to 'TdSyncNone'. | The server provides hover support. | The server provides completion support. | The server provides signature help support. | The server provides go to declaration support. | The server provides goto definition support. | The server provides find references support. | The server provides document highlight support. | The server provides document symbol support. | The server provides code actions. | The server provides code lens. | The server provides document link support. | The server provides document formatting. | The server provides document range formatting. | The server provides document formatting on typing. | The server provides rename support. | The server provides execute command support. | The server provides call hierarchy support. | The server provides semantic tokens support. | The server provides workspace symbol support. | Workspace specific server capabilities | Experimental server capabilities.
# LANGUAGE DuplicateRecordFields # module Language.LSP.Types.ServerCapabilities where import Data.Aeson import Data.Aeson.TH import Data.Text (Text) import Language.LSP.Types.CallHierarchy import Language.LSP.Types.CodeAction import Language.LSP.Types.CodeLens import Language.LSP.Types.Command import Language.LSP.Types.Common import Language.LSP.Types.Completion import Language.LSP.Types.Declaration import Language.LSP.Types.Definition import Language.LSP.Types.DocumentColor import Language.LSP.Types.DocumentHighlight import Language.LSP.Types.DocumentLink import Language.LSP.Types.DocumentSymbol import Language.LSP.Types.FoldingRange import Language.LSP.Types.Formatting import Language.LSP.Types.Hover import Language.LSP.Types.Implementation import Language.LSP.Types.References import Language.LSP.Types.Rename import Language.LSP.Types.SelectionRange import Language.LSP.Types.SemanticTokens import Language.LSP.Types.SignatureHelp import Language.LSP.Types.TextDocument import Language.LSP.Types.TypeDefinition import Language.LSP.Types.Utils import Language.LSP.Types.WorkspaceSymbol data WorkspaceFoldersServerCapabilities = WorkspaceFoldersServerCapabilities _supported :: Maybe Bool , _changeNotifications :: Maybe (Text |? Bool) } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkspaceFoldersServerCapabilities data WorkspaceServerCapabilities = WorkspaceServerCapabilities | The server supports workspace folder . Since LSP 3.6 @since 0.7.0.0 _workspaceFolders :: Maybe WorkspaceFoldersServerCapabilities } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkspaceServerCapabilities data ServerCapabilities = ServerCapabilities _textDocumentSync :: Maybe (TextDocumentSyncOptions |? TextDocumentSyncKind) , _hoverProvider :: Maybe (Bool |? HoverOptions) , _completionProvider :: Maybe CompletionOptions , _signatureHelpProvider :: Maybe SignatureHelpOptions Since LSP 3.14.0 , _declarationProvider :: Maybe (Bool |? DeclarationOptions |? DeclarationRegistrationOptions) , _definitionProvider :: Maybe (Bool |? DefinitionOptions) | The server provides Goto Type Definition support . Since LSP 3.6 @since 0.7.0.0 , _typeDefinitionProvider :: Maybe (Bool |? TypeDefinitionOptions |? TypeDefinitionRegistrationOptions) | The server provides Goto Implementation support . Since LSP 3.6 @since 0.7.0.0 , _implementationProvider :: Maybe (Bool |? ImplementationOptions |? ImplementationRegistrationOptions) , _referencesProvider :: Maybe (Bool |? ReferenceOptions) , _documentHighlightProvider :: Maybe (Bool |? DocumentHighlightOptions) , _documentSymbolProvider :: Maybe (Bool |? DocumentSymbolOptions) , _codeActionProvider :: Maybe (Bool |? CodeActionOptions) , _codeLensProvider :: Maybe CodeLensOptions , _documentLinkProvider :: Maybe DocumentLinkOptions | The server provides color provider support . Since LSP 3.6 @since 0.7.0.0 , _colorProvider :: Maybe (Bool |? DocumentColorOptions |? DocumentColorRegistrationOptions) , _documentFormattingProvider :: Maybe (Bool |? DocumentFormattingOptions) , _documentRangeFormattingProvider :: Maybe (Bool |? DocumentRangeFormattingOptions) , _documentOnTypeFormattingProvider :: Maybe DocumentOnTypeFormattingOptions , _renameProvider :: Maybe (Bool |? RenameOptions) | The server provides folding provider support . Since LSP 3.10 @since 0.7.0.0 , _foldingRangeProvider :: Maybe (Bool |? FoldingRangeOptions |? FoldingRangeRegistrationOptions) , _executeCommandProvider :: Maybe ExecuteCommandOptions | The server provides selection range support . Since LSP 3.15 , _selectionRangeProvider :: Maybe (Bool |? SelectionRangeOptions |? SelectionRangeRegistrationOptions) , _callHierarchyProvider :: Maybe (Bool |? CallHierarchyOptions |? CallHierarchyRegistrationOptions) @since 3.16.0 , _semanticTokensProvider :: Maybe (SemanticTokensOptions |? SemanticTokensRegistrationOptions) , _workspaceSymbolProvider :: Maybe (Bool |? WorkspaceSymbolOptions) , _workspace :: Maybe WorkspaceServerCapabilities , _experimental :: Maybe Value } deriving (Show, Read, Eq) deriveJSON lspOptions ''ServerCapabilities
bcf17fc4068802812dfd9694de8da5ae5e1770f4fb77b09772a8a54147612d8e
WorksHub/client
tracking_pixels.cljs
(ns wh.common.fx.tracking-pixels (:require [re-frame.core :refer [reg-fx]] [wh.common.tracking-pixels :as tracking-pixels])) (reg-fx :tracking-pixels/init-application-pixels tracking-pixels/add-application-tracking-pixels) (reg-fx :tracking-pixels/init-job-pixels tracking-pixels/add-job-tracking-pixels)
null
https://raw.githubusercontent.com/WorksHub/client/04af27577b79bb2c50e203a58f5a602146a8ebc3/client/src/wh/common/fx/tracking_pixels.cljs
clojure
(ns wh.common.fx.tracking-pixels (:require [re-frame.core :refer [reg-fx]] [wh.common.tracking-pixels :as tracking-pixels])) (reg-fx :tracking-pixels/init-application-pixels tracking-pixels/add-application-tracking-pixels) (reg-fx :tracking-pixels/init-job-pixels tracking-pixels/add-job-tracking-pixels)
f21a638f81a1410ba67355c2f64d78d2370bf52bf051417f6cb54105dde75d89
haskell/hackage-security
Paths.hs
-- | Additional paths module Hackage.Security.RepoTool.Paths ( -- * Repo RepoLoc(..) -- * Keys , KeyRoot , KeyPath , KeysLoc(..) ) where import Hackage.Security.Util.Path import Hackage.Security.Util.Pretty {------------------------------------------------------------------------------- Repo -------------------------------------------------------------------------------} newtype RepoLoc = RepoLoc { repoLocPath :: Path Absolute } deriving Eq {------------------------------------------------------------------------------- Keys -------------------------------------------------------------------------------} -- | The key directory data KeyRoot type KeyPath = Path KeyRoot instance Pretty (Path KeyRoot) where pretty (Path fp) = "<keys>/" ++ fp newtype KeysLoc = KeysLoc { keysLocPath :: Path Absolute } deriving Eq
null
https://raw.githubusercontent.com/haskell/hackage-security/048844cb006eb880e256d7393928d6fd422ab6dd/hackage-repo-tool/src/Hackage/Security/RepoTool/Paths.hs
haskell
| Additional paths * Repo * Keys ------------------------------------------------------------------------------ Repo ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Keys ------------------------------------------------------------------------------ | The key directory
module Hackage.Security.RepoTool.Paths ( RepoLoc(..) , KeyRoot , KeyPath , KeysLoc(..) ) where import Hackage.Security.Util.Path import Hackage.Security.Util.Pretty newtype RepoLoc = RepoLoc { repoLocPath :: Path Absolute } deriving Eq data KeyRoot type KeyPath = Path KeyRoot instance Pretty (Path KeyRoot) where pretty (Path fp) = "<keys>/" ++ fp newtype KeysLoc = KeysLoc { keysLocPath :: Path Absolute } deriving Eq
c525524ff9eb2bd28556dae9b4cd6646992c5d0c7887bad3b1116c6a58e2d3d8
erlymon/erlymon
em_http_api_session_handler.erl
%%%------------------------------------------------------------------- @author ( C ) 2015 , < > %%% @doc Erlymon is an open source GPS tracking system for various GPS tracking devices . %%% Copyright ( C ) 2015 , < > . %%% This file is part of Erlymon . %%% Erlymon is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . %%% Erlymon 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 </>. %%% @end %%%------------------------------------------------------------------- -module(em_http_api_session_handler). -author("Sergey Penkovsky <>"). %% API -export([init/2]). -include("em_http.hrl"). -include("em_records.hrl"). %% GET QUERY STRING : _ %% ANSWER: 200 { " id":12371,"name":"asd","email":"","readonly":false,"admin":false,"map":null,"language":null,"distanceUnit":null,"speedUnit":null,"latitude":0.0,"longitude":0.0,"zoom":0,"password":null } %% or 404 -spec init(Req::cowboy_req:req(), Opts::any()) -> {ok, cowboy_req:req(), any()}. init(Req, Opts) -> Method = cowboy_req:method(Req), {ok, request(Method, Req), Opts}. -spec request(Method::binary(), Opts::any()) -> cowboy_req:req(). request(?GET, Req) -> get_session(Req); request(?POST, Req) -> add_session(Req); request(?DELETE, Req) -> remove_session(Req); request(_, Req) -> %% Method not allowed. cowboy_req:reply(?STATUS_METHOD_NOT_ALLOWED, Req). -spec get_session(Req::cowboy_req:req()) -> cowboy_req:req(). get_session(Req) -> %% {"id":12371,"name":"asd","email":"","readonly":false,"admin":false,"map":null,"language":null,"distanceUnit":null,"speedUnit":null,"latitude":0.0,"longitude":0.0,"zoom":0,"password":null} %% or 404 case cowboy_session:get(user, Req) of {undefined, Req2} -> cowboy_req:reply(?STATUS_NOT_FOUND, Req2); {User, Req2} -> cowboy_req:reply(?STATUS_OK, ?HEADERS, str(User), Req2) end. -spec add_session(Req::cowboy_req:req()) -> cowboy_req:req(). add_session(Req) -> {ok, PostVals, Req2} = cowboy_req:body_qs(Req), Result = emodel:from_proplist(PostVals, #user{}, [ {<<"email">>, required, string, #user.email, []}, {<<"password">>, required, string, #user.password, []} ]), case Result of {ok, #user{email = Email, password = Password}} -> case em_data_manager:check_user(Email, Password) of {error, Reason} -> cowboy_req:reply(?STATUS_UNAUTHORIZED, [], Reason, Req2); {ok, User} -> em_logger:info("SESSION SAVE: ~w", [User]), {ok, Req3} = cowboy_session:set(user, User, Req2), cowboy_req:reply(?STATUS_OK, ?HEADERS, str(User), Req3) end; {error, _Reason} -> Encode end set error cowboy_req:reply(?STATUS_UNAUTHORIZED, Req2) end. -spec remove_session(Req::cowboy_req:req()) -> cowboy_req:req(). remove_session(Req) -> {ok, Req2} = cowboy_session:expire(Req), cowboy_req:reply(?STATUS_OK, Req2). str(Rec) -> em_json:encode(#{ <<"id">> => Rec#user.id, <<"name">> => Rec#user.name, <<"email">> => Rec#user.email, <<"readonly">> => Rec#user.readonly, <<"admin">> => Rec#user.admin, <<"map">> => Rec#user.map, <<"language">> => Rec#user.language, <<"distanceUnit">> => Rec#user.distanceUnit, <<"speedUnit">> => Rec#user.speedUnit, <<"latitude">> => Rec#user.latitude, <<"longitude">> => Rec#user.longitude, <<"zoom">> => Rec#user.zoom, <<"password">> => <<"">> }).
null
https://raw.githubusercontent.com/erlymon/erlymon/2250619783d6da1e33a502911a8fa52ce016c094/apps/erlymon/src/em_http/handlers/em_http_api_session_handler.erl
erlang
------------------------------------------------------------------- @doc but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the along with this program. If not, see </>. @end ------------------------------------------------------------------- API GET ANSWER: or Method not allowed. {"id":12371,"name":"asd","email":"","readonly":false,"admin":false,"map":null,"language":null,"distanceUnit":null,"speedUnit":null,"latitude":0.0,"longitude":0.0,"zoom":0,"password":null} or
@author ( C ) 2015 , < > Erlymon is an open source GPS tracking system for various GPS tracking devices . Copyright ( C ) 2015 , < > . This file is part of Erlymon . Erlymon is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License , version 3 , as published by the Free Software Foundation . Erlymon is distributed in the hope that it will be useful , GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License -module(em_http_api_session_handler). -author("Sergey Penkovsky <>"). -export([init/2]). -include("em_http.hrl"). -include("em_records.hrl"). QUERY STRING : _ 200 { " id":12371,"name":"asd","email":"","readonly":false,"admin":false,"map":null,"language":null,"distanceUnit":null,"speedUnit":null,"latitude":0.0,"longitude":0.0,"zoom":0,"password":null } 404 -spec init(Req::cowboy_req:req(), Opts::any()) -> {ok, cowboy_req:req(), any()}. init(Req, Opts) -> Method = cowboy_req:method(Req), {ok, request(Method, Req), Opts}. -spec request(Method::binary(), Opts::any()) -> cowboy_req:req(). request(?GET, Req) -> get_session(Req); request(?POST, Req) -> add_session(Req); request(?DELETE, Req) -> remove_session(Req); request(_, Req) -> cowboy_req:reply(?STATUS_METHOD_NOT_ALLOWED, Req). -spec get_session(Req::cowboy_req:req()) -> cowboy_req:req(). get_session(Req) -> 404 case cowboy_session:get(user, Req) of {undefined, Req2} -> cowboy_req:reply(?STATUS_NOT_FOUND, Req2); {User, Req2} -> cowboy_req:reply(?STATUS_OK, ?HEADERS, str(User), Req2) end. -spec add_session(Req::cowboy_req:req()) -> cowboy_req:req(). add_session(Req) -> {ok, PostVals, Req2} = cowboy_req:body_qs(Req), Result = emodel:from_proplist(PostVals, #user{}, [ {<<"email">>, required, string, #user.email, []}, {<<"password">>, required, string, #user.password, []} ]), case Result of {ok, #user{email = Email, password = Password}} -> case em_data_manager:check_user(Email, Password) of {error, Reason} -> cowboy_req:reply(?STATUS_UNAUTHORIZED, [], Reason, Req2); {ok, User} -> em_logger:info("SESSION SAVE: ~w", [User]), {ok, Req3} = cowboy_session:set(user, User, Req2), cowboy_req:reply(?STATUS_OK, ?HEADERS, str(User), Req3) end; {error, _Reason} -> Encode end set error cowboy_req:reply(?STATUS_UNAUTHORIZED, Req2) end. -spec remove_session(Req::cowboy_req:req()) -> cowboy_req:req(). remove_session(Req) -> {ok, Req2} = cowboy_session:expire(Req), cowboy_req:reply(?STATUS_OK, Req2). str(Rec) -> em_json:encode(#{ <<"id">> => Rec#user.id, <<"name">> => Rec#user.name, <<"email">> => Rec#user.email, <<"readonly">> => Rec#user.readonly, <<"admin">> => Rec#user.admin, <<"map">> => Rec#user.map, <<"language">> => Rec#user.language, <<"distanceUnit">> => Rec#user.distanceUnit, <<"speedUnit">> => Rec#user.speedUnit, <<"latitude">> => Rec#user.latitude, <<"longitude">> => Rec#user.longitude, <<"zoom">> => Rec#user.zoom, <<"password">> => <<"">> }).
2d4d7925f0f69587fe310416c5d5f65b9790bcf57da2cc26e09525b561ac310f
Ptival/chick
Utils.hs
module Utils ( extractApps, extractLams, extractPi, extractPis, extractSomeApps, extractSomeLams, extractSomePis, foldlWith, foldrWith, isPi, mapWithIndex, mkApps, mkLams, mkPis, orElse, orElse', splitList, unzipMaybe, withState, ) where import Control.Lens (Field2 (_2), over) import qualified Control.Monad.Error.Class as ME import Polysemy (Member, Sem) import Polysemy.Error (Error, throw) import Polysemy.State (State, get, put) import Term.Term ( Binder, ScopedTerm, TermX (App, Lam, Pi), TypeX, Variable, abstractBinder, unscopeTerm, ) import Text.Printf (printf) foldlWith :: Foldable t => (b -> a -> b) -> t a -> b -> b foldlWith f l a = foldl f a l foldrWith :: Foldable t => (a -> b -> b) -> t a -> b -> b foldrWith f l a = foldr f a l isPi :: TermX ξ ν -> Maybe (ξ, TypeX ξ ν, ScopedTerm (TypeX ξ) ν) isPi (Pi a b c) = Just (a, b, c) isPi _ = Nothing mapWithIndex :: (a -> Int -> b) -> [a] -> [b] mapWithIndex f l = zipWith f l [0 ..] orElse :: ME.MonadError e m => Maybe a -> e -> m a orElse Nothing e = ME.throwError e orElse (Just a) _ = return a orElse' :: ME.MonadError e m => Bool -> e -> m () orElse' False e = ME.throwError e orElse' True _ = return () dumb , but has the same signature as ` runTrace ` , so easier to interchange -- runSkipTrace :: Sem '[Trace] a -> IO a -- runSkipTrace = return <$> skipTrace -- -- skipTrace :: Sem '[Trace] a -> a skipTrace ( ) = x -- skipTrace (E u q) = -- case extract u of -- Trace _ -> skipTrace (qApp q ()) splitList :: Int -> [a] -> Maybe ([a], a, [a]) splitList n xs = revL <$> go n xs where go 0 (h : t) = Just ([], h, t) go m (h : t) = prependL h <$> go (m - 1) t go _ [] = Nothing prependL h (revl, x, r) = (h : revl, x, r) revL (l, x, r) = (reverse l, x, r) unzipMaybe :: Maybe (a, b) -> (Maybe a, Maybe b) unzipMaybe Nothing = (Nothing, Nothing) unzipMaybe (Just (a, b)) = (Just a, Just b) -- | `withState` localizes a modification of the state to a given effectful computation withState :: Member (State s) r => (s -> s) -> Sem r a -> Sem r a withState f e = do s <- get put (f s) r <- e put s return r -- | `f a b c` becomes `(f, [a, b, c])` extractApps :: TermX α Variable -> Sem r (TermX α Variable, [(α, TermX α Variable)]) extractApps t = over _2 reverse <$> go t where go (App a t1 t2) = do (f, args) <- go t1 return (f, (a, t2) : args) go t1 = return (t1, []) extractSomeApps :: ( Member (Error String) r, Show α ) => Int -> TermX α Variable -> Sem r (TermX α Variable, [(α, TermX α Variable)]) extractSomeApps 0 t = return (t, []) extractSomeApps n (App a t1 t2) = do (f, args) <- extractSomeApps (n - 1) t1 return (f, args ++ [(a, t2)]) -- TODO: make this not quadratic, I'm being lazy extractSomeApps _ t = let e :: String = printf "extractLams: not a Lam: %s" (show t) in throw e extractSomeLams :: ( Member (Error String) r, Show α ) => Int -> TermX α Variable -> Sem r ([(α, Binder Variable)], TermX α Variable) extractSomeLams 0 t = return ([], t) extractSomeLams n (Lam a bt) = do let (b, t) = unscopeTerm bt (l, rest) <- extractSomeLams (n - 1) t return ((a, b) : l, rest) extractSomeLams _ t = let e :: String = printf "extractLams: not a Lam: %s" (show t) in throw e extractLams :: TermX α Variable -> Sem r ([(α, Binder Variable)], TermX α Variable) extractLams = \case Lam a bt -> do let (b, t) = unscopeTerm bt (l, rest) <- extractLams t return ((a, b) : l, rest) t -> return ([], t) extractSomePis :: Member (Error String) r => Show α => Int -> TermX α Variable -> Sem r ([(α, Binder Variable, TermX α Variable)], TermX α Variable) extractSomePis 0 t = return ([], t) extractSomePis n (Pi a τ1 bτ2) = do let (b, τ2) = unscopeTerm bτ2 (l, rest) <- extractSomePis (n - 1) τ2 return ((a, b, τ1) : l, rest) extractSomePis _ t = let e :: String = printf "extractPis: not a Pi: %s" (show t) in throw e extractPis :: TermX α Variable -> Sem r ([(α, Binder Variable, TermX α Variable)], TermX α Variable) extractPis = \case Pi a τ1 bτ2 -> do let (b, τ2) = unscopeTerm bτ2 (l, rest) <- extractPis τ2 return ((a, b, τ1) : l, rest) t -> return ([], t) extractPi :: Member (Error String) r => Show α => TermX α Variable -> Sem r (α, TermX α Variable, Binder Variable, TermX α Variable) extractPi = \case Pi a τ1 bτ2 -> do let (b, τ2) = unscopeTerm bτ2 return (a, τ1, b, τ2) t -> let e :: String = printf "extractPi: not a Pi: %s" (show t) in throw e mkApps :: TermX α Variable -> [(α, TermX α Variable)] -> TermX α Variable mkApps f [] = f mkApps f ((a, e) : t) = mkApps (App a f e) t mkLams :: [(α, Binder Variable)] -> TermX α Variable -> TermX α Variable mkLams [] rest = rest mkLams ((a, b) : t) rest = Lam a (abstractBinder b (mkLams t rest)) mkPis :: [(α, Binder Variable, TermX α Variable)] -> TermX α Variable -> TermX α Variable mkPis [] rest = rest mkPis ((a, b, τ1) : t) rest = Pi a τ1 (abstractBinder b (mkPis t rest))
null
https://raw.githubusercontent.com/Ptival/chick/a5ce39a842ff72348f1c9cea303997d5300163e2/backend/lib/Utils.hs
haskell
runSkipTrace :: Sem '[Trace] a -> IO a runSkipTrace = return <$> skipTrace skipTrace :: Sem '[Trace] a -> a skipTrace (E u q) = case extract u of Trace _ -> skipTrace (qApp q ()) | `withState` localizes a modification of the state to a given effectful computation | `f a b c` becomes `(f, [a, b, c])` TODO: make this not quadratic, I'm being lazy
module Utils ( extractApps, extractLams, extractPi, extractPis, extractSomeApps, extractSomeLams, extractSomePis, foldlWith, foldrWith, isPi, mapWithIndex, mkApps, mkLams, mkPis, orElse, orElse', splitList, unzipMaybe, withState, ) where import Control.Lens (Field2 (_2), over) import qualified Control.Monad.Error.Class as ME import Polysemy (Member, Sem) import Polysemy.Error (Error, throw) import Polysemy.State (State, get, put) import Term.Term ( Binder, ScopedTerm, TermX (App, Lam, Pi), TypeX, Variable, abstractBinder, unscopeTerm, ) import Text.Printf (printf) foldlWith :: Foldable t => (b -> a -> b) -> t a -> b -> b foldlWith f l a = foldl f a l foldrWith :: Foldable t => (a -> b -> b) -> t a -> b -> b foldrWith f l a = foldr f a l isPi :: TermX ξ ν -> Maybe (ξ, TypeX ξ ν, ScopedTerm (TypeX ξ) ν) isPi (Pi a b c) = Just (a, b, c) isPi _ = Nothing mapWithIndex :: (a -> Int -> b) -> [a] -> [b] mapWithIndex f l = zipWith f l [0 ..] orElse :: ME.MonadError e m => Maybe a -> e -> m a orElse Nothing e = ME.throwError e orElse (Just a) _ = return a orElse' :: ME.MonadError e m => Bool -> e -> m () orElse' False e = ME.throwError e orElse' True _ = return () dumb , but has the same signature as ` runTrace ` , so easier to interchange skipTrace ( ) = x splitList :: Int -> [a] -> Maybe ([a], a, [a]) splitList n xs = revL <$> go n xs where go 0 (h : t) = Just ([], h, t) go m (h : t) = prependL h <$> go (m - 1) t go _ [] = Nothing prependL h (revl, x, r) = (h : revl, x, r) revL (l, x, r) = (reverse l, x, r) unzipMaybe :: Maybe (a, b) -> (Maybe a, Maybe b) unzipMaybe Nothing = (Nothing, Nothing) unzipMaybe (Just (a, b)) = (Just a, Just b) withState :: Member (State s) r => (s -> s) -> Sem r a -> Sem r a withState f e = do s <- get put (f s) r <- e put s return r extractApps :: TermX α Variable -> Sem r (TermX α Variable, [(α, TermX α Variable)]) extractApps t = over _2 reverse <$> go t where go (App a t1 t2) = do (f, args) <- go t1 return (f, (a, t2) : args) go t1 = return (t1, []) extractSomeApps :: ( Member (Error String) r, Show α ) => Int -> TermX α Variable -> Sem r (TermX α Variable, [(α, TermX α Variable)]) extractSomeApps 0 t = return (t, []) extractSomeApps n (App a t1 t2) = do (f, args) <- extractSomeApps (n - 1) t1 extractSomeApps _ t = let e :: String = printf "extractLams: not a Lam: %s" (show t) in throw e extractSomeLams :: ( Member (Error String) r, Show α ) => Int -> TermX α Variable -> Sem r ([(α, Binder Variable)], TermX α Variable) extractSomeLams 0 t = return ([], t) extractSomeLams n (Lam a bt) = do let (b, t) = unscopeTerm bt (l, rest) <- extractSomeLams (n - 1) t return ((a, b) : l, rest) extractSomeLams _ t = let e :: String = printf "extractLams: not a Lam: %s" (show t) in throw e extractLams :: TermX α Variable -> Sem r ([(α, Binder Variable)], TermX α Variable) extractLams = \case Lam a bt -> do let (b, t) = unscopeTerm bt (l, rest) <- extractLams t return ((a, b) : l, rest) t -> return ([], t) extractSomePis :: Member (Error String) r => Show α => Int -> TermX α Variable -> Sem r ([(α, Binder Variable, TermX α Variable)], TermX α Variable) extractSomePis 0 t = return ([], t) extractSomePis n (Pi a τ1 bτ2) = do let (b, τ2) = unscopeTerm bτ2 (l, rest) <- extractSomePis (n - 1) τ2 return ((a, b, τ1) : l, rest) extractSomePis _ t = let e :: String = printf "extractPis: not a Pi: %s" (show t) in throw e extractPis :: TermX α Variable -> Sem r ([(α, Binder Variable, TermX α Variable)], TermX α Variable) extractPis = \case Pi a τ1 bτ2 -> do let (b, τ2) = unscopeTerm bτ2 (l, rest) <- extractPis τ2 return ((a, b, τ1) : l, rest) t -> return ([], t) extractPi :: Member (Error String) r => Show α => TermX α Variable -> Sem r (α, TermX α Variable, Binder Variable, TermX α Variable) extractPi = \case Pi a τ1 bτ2 -> do let (b, τ2) = unscopeTerm bτ2 return (a, τ1, b, τ2) t -> let e :: String = printf "extractPi: not a Pi: %s" (show t) in throw e mkApps :: TermX α Variable -> [(α, TermX α Variable)] -> TermX α Variable mkApps f [] = f mkApps f ((a, e) : t) = mkApps (App a f e) t mkLams :: [(α, Binder Variable)] -> TermX α Variable -> TermX α Variable mkLams [] rest = rest mkLams ((a, b) : t) rest = Lam a (abstractBinder b (mkLams t rest)) mkPis :: [(α, Binder Variable, TermX α Variable)] -> TermX α Variable -> TermX α Variable mkPis [] rest = rest mkPis ((a, b, τ1) : t) rest = Pi a τ1 (abstractBinder b (mkPis t rest))
198734af3d754a32971b34a0c3f319622b826fb14f0f4de7adf3e1baa989aa79
tud-fop/vanda-haskell
WTA_BHPS.hs
----------------------------------------------------------------------------- -- | Module : . Grammar . . WTA_BHPS Copyright : ( c ) Technische Universität Dresden 2013 -- License : BSD-style -- -- Maintainer : -- Stability : unknown -- Portability : portable -- Queries an Automaton that represents an n - gram model . Assigns weights as -- early as possible to enable early pruning. -- ----------------------------------------------------------------------------- module Vanda.Grammar.NGrams.WTA_BHPS ( State' , delta , mapState , makeWTA ) where import Data.Hashable import Data.WTA import Vanda.Grammar.LM import qualified Data.Vector.Unboxed as VU data State' v = Binary [v] [v] deriving (Eq, Ord, Show) instance Hashable i => Hashable (State' i) where hashWithSalt s (Binary a b) = s `hashWithSalt` a `hashWithSalt` b mapState' :: (v -> v') -> State' v -> State' v' mapState' f (Binary b1 b2) = Binary (map f b1) (map f b2) instance State State' where mapState = mapState' instance Functor State' where fmap = mapState' makeWTA :: LM a => a -> (Int -> Int) -> [Int] -> WTA Int (State' Int) makeWTA lm rel gamma = WTA (delta' lm rel gamma) (const 1) delta' :: LM a => a -- ^ language model -> (Int -> Int) -- ^ relabelling -> [Int] -- ^ Gamma -> [State' Int] -- ^ in-states -> [Int] -- ^ input symbol -> [(State' Int, Double)] -- ^ out-states with weights delta' lm rel gamma [] w = let nM = order lm - 1 in [ (Binary w1 w2, score lm . VU.fromList $ map rel (w1 ++ w)) | w1 <- sequence . take nM $ repeat gamma , let w2 = last' nM $ w1 ++ w ] delta' _ _ _ xs _ = let check _ [] = True check (Binary _ lr) (r@(Binary rl _):qs) = (lr == rl) && check r qs check' (q:qs) = check q qs check' _ = True lft = (\(Binary a _) -> a) $ head xs rgt = (\(Binary _ b) -> b) $ last xs q' = Binary lft rgt in [ (q', 1) | check' xs ] last' :: Int -> [v] -> [v] last' n xs = drop (length xs - n) xs
null
https://raw.githubusercontent.com/tud-fop/vanda-haskell/3214966361b6dbf178155950c94423eee7f9453e/library/Vanda/Grammar/NGrams/WTA_BHPS.hs
haskell
--------------------------------------------------------------------------- | License : BSD-style Maintainer : Stability : unknown Portability : portable early as possible to enable early pruning. --------------------------------------------------------------------------- ^ language model ^ relabelling ^ Gamma ^ in-states ^ input symbol ^ out-states with weights
Module : . Grammar . . WTA_BHPS Copyright : ( c ) Technische Universität Dresden 2013 Queries an Automaton that represents an n - gram model . Assigns weights as module Vanda.Grammar.NGrams.WTA_BHPS ( State' , delta , mapState , makeWTA ) where import Data.Hashable import Data.WTA import Vanda.Grammar.LM import qualified Data.Vector.Unboxed as VU data State' v = Binary [v] [v] deriving (Eq, Ord, Show) instance Hashable i => Hashable (State' i) where hashWithSalt s (Binary a b) = s `hashWithSalt` a `hashWithSalt` b mapState' :: (v -> v') -> State' v -> State' v' mapState' f (Binary b1 b2) = Binary (map f b1) (map f b2) instance State State' where mapState = mapState' instance Functor State' where fmap = mapState' makeWTA :: LM a => a -> (Int -> Int) -> [Int] -> WTA Int (State' Int) makeWTA lm rel gamma = WTA (delta' lm rel gamma) (const 1) delta' :: LM a delta' lm rel gamma [] w = let nM = order lm - 1 in [ (Binary w1 w2, score lm . VU.fromList $ map rel (w1 ++ w)) | w1 <- sequence . take nM $ repeat gamma , let w2 = last' nM $ w1 ++ w ] delta' _ _ _ xs _ = let check _ [] = True check (Binary _ lr) (r@(Binary rl _):qs) = (lr == rl) && check r qs check' (q:qs) = check q qs check' _ = True lft = (\(Binary a _) -> a) $ head xs rgt = (\(Binary _ b) -> b) $ last xs q' = Binary lft rgt in [ (q', 1) | check' xs ] last' :: Int -> [v] -> [v] last' n xs = drop (length xs - n) xs
387235ab28dd45b2ff9541fba9665e0ace5297cf3384b29bfcec6823a7b5e608
janestreet/jsonaf
jsonafable.mli
open! Base include module type of Jsonaf_kernel.Jsonafable module Of_jsonafable (Jsonafable : S) (M : sig type t val of_jsonafable : Jsonafable.t -> t val to_jsonafable : t -> Jsonafable.t end) : S with type t := M.t module Of_stringable (M : Stringable.S) : S with type t := M.t module Stable : sig module Of_jsonafable : sig module V1 : module type of Of_jsonafable end module Of_stringable : sig module V1 : module type of Of_stringable end end
null
https://raw.githubusercontent.com/janestreet/jsonaf/9f8226165a329db47119f751d02449f2751d87c9/src/jsonafable.mli
ocaml
open! Base include module type of Jsonaf_kernel.Jsonafable module Of_jsonafable (Jsonafable : S) (M : sig type t val of_jsonafable : Jsonafable.t -> t val to_jsonafable : t -> Jsonafable.t end) : S with type t := M.t module Of_stringable (M : Stringable.S) : S with type t := M.t module Stable : sig module Of_jsonafable : sig module V1 : module type of Of_jsonafable end module Of_stringable : sig module V1 : module type of Of_stringable end end
a2c8b684a725fde7b18a147ac534380f8a8ec58f46e2042ee81139aa0e035d4b
NorfairKing/smos
Clock.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Smos.Report.Clock ( module Smos.Report.Clock, module Smos.Report.Clock.Types, ) where import Cursor.Simple.Forest import Cursor.Simple.Tree import Data.Function import Data.List import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE import Data.Maybe import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import Data.Time import Data.Time.Calendar.WeekDate import Data.Validity import Data.Validity.Path () import Lens.Micro import Path import Smos.Data import Smos.Report.Clock.Types import Smos.Report.Filter import Smos.Report.Period import Smos.Report.Streaming import Smos.Report.TimeBlock | Reset the timers of every entry that does n't match the filter to zero zeroOutByFilter :: EntryFilter -> Path Rel File -> SmosFile -> SmosFile zeroOutByFilter f rp sf = let cursors = forestCursors $ smosFileForest sf in sf {smosFileForest = map (fmap go) cursors} where go :: ForestCursor Entry -> Entry go fc = ( if filterPredicate f (rp, fc) then id else zeroOutEntry ) (fc ^. (forestCursorSelectedTreeL . treeCursorCurrentL)) zeroOutEntry :: Entry -> Entry zeroOutEntry e = e {entryLogbook = emptyLogbook} findFileTimes :: UTCTime -> Path Rel File -> SmosFile -> Maybe FileTimes findFileTimes now rp sf = do ne <- goF (smosFileForest sf) pure $ FileTimes {clockTimeFile = rp, clockTimeForest = ne} where goF :: Forest Entry -> Maybe (TForest HeaderTimes) goF = NE.nonEmpty . mapMaybe goT goT :: Tree Entry -> Maybe (TTree HeaderTimes) goT (Node e ts_) = case goF ts_ of Nothing -> do hts <- headerTimesNonEmpty $ findHeaderTimes now e pure $ TLeaf hts Just f -> pure $ TBranch (findHeaderTimes now e) f findHeaderTimes :: UTCTime -> Entry -> HeaderTimes [] findHeaderTimes now Entry {..} = case entryLogbook of LogOpen s es -> ht $ (LogbookEntry {logbookEntryStart = s, logbookEntryEnd = now}) : es LogClosed es -> ht es where ht es = HeaderTimes {headerTimesHeader = entryHeader, headerTimesEntries = es} headerTimesList :: HeaderTimes NonEmpty -> HeaderTimes [] headerTimesList hts = HeaderTimes { headerTimesHeader = headerTimesHeader hts, headerTimesEntries = NE.toList $ headerTimesEntries hts } headerTimesNonEmpty :: HeaderTimes [] -> Maybe (HeaderTimes NonEmpty) headerTimesNonEmpty hts = do ne <- NE.nonEmpty $ headerTimesEntries hts pure $ HeaderTimes {headerTimesHeader = headerTimesHeader hts, headerTimesEntries = ne} trimHeaderTimes :: ZonedTime -> Period -> HeaderTimes [] -> HeaderTimes [] trimHeaderTimes zt cp ht = let es' = mapMaybe (trimLogbookEntry zt cp) $ headerTimesEntries ht in ht {headerTimesEntries = es'} trimLogbookEntry :: ZonedTime -> Period -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntry now cp = case cp of AllTime -> pure Yesterday -> trimLogbookEntryToDay tz (pred today) Today -> trimLogbookEntryToDay tz today Tomorrow -> trimLogbookEntryToDay tz (succ today) LastWeek -> trimLogbookEntryTo tz lastWeekStart lastWeekEnd ThisWeek -> trimLogbookEntryTo tz thisWeekStart thisWeekEnd NextWeek -> trimLogbookEntryTo tz nextWeekStart nextWeekEnd LastMonth -> trimLogbookEntryTo tz lastMonthStart lastMonthEnd ThisMonth -> trimLogbookEntryTo tz thisMonthStart thisMonthEnd NextMonth -> trimLogbookEntryTo tz nextMonthStart nextMonthEnd LastYear -> trimLogbookEntryTo tz lastYearStart lastYearEnd ThisYear -> trimLogbookEntryTo tz thisYearStart thisYearEnd NextYear -> trimLogbookEntryTo tz nextYearStart nextYearEnd BeginOnly begin -> trimLogbookEntryToM tz (Just begin) Nothing EndOnly end -> trimLogbookEntryToM tz Nothing (Just end) BeginEnd begin end -> trimLogbookEntryTo tz begin end where tz :: TimeZone tz = zonedTimeZone now nowLocal :: LocalTime nowLocal = zonedTimeToLocalTime now today :: Day today = localDay nowLocal lastWeekStart :: LocalTime lastWeekStart = let (y, wn, _) = toWeekDate today TODO this will fail around newyear lastWeekEnd :: LocalTime lastWeekEnd = thisWeekStart thisWeekStart :: LocalTime thisWeekStart = let (y, wn, _) = toWeekDate today in LocalTime (fromWeekDate y wn 1) midnight thisWeekEnd :: LocalTime thisWeekEnd = let (y, wn, _) = toWeekDate today FIXME this can wrong at the end of the year nextWeekStart :: LocalTime nextWeekStart = thisWeekEnd nextWeekEnd :: LocalTime nextWeekEnd = let (y, wn, _) = toWeekDate today FIXME this can wrong at the end of the year lastMonthStart :: LocalTime lastMonthStart = let (y, m, _) = toGregorian today FIXME This will fail around newyear lastMonthEnd :: LocalTime lastMonthEnd = thisMonthStart thisMonthStart :: LocalTime thisMonthStart = let (y, m, _) = toGregorian today in LocalTime (fromGregorian y m 1) midnight thisMonthEnd :: LocalTime thisMonthEnd = let (y, m, _) = toGregorian today in LocalTime (fromGregorian y m 31) midnight nextMonthStart :: LocalTime nextMonthStart = thisMonthEnd nextMonthEnd :: LocalTime nextMonthEnd = let (y, m, _) = toGregorian today FIXME This will fail around newyear lastYearStart :: LocalTime lastYearStart = let (y, _, _) = toGregorian today FIXME This will fail around newyear lastYearEnd :: LocalTime lastYearEnd = thisYearEnd thisYearStart :: LocalTime thisYearStart = let (y, _, _) = toGregorian today in LocalTime (fromGregorian y 1 1) midnight thisYearEnd :: LocalTime thisYearEnd = let (y, _, _) = toGregorian today in LocalTime (fromGregorian y 12 31) midnight nextYearStart :: LocalTime nextYearStart = thisYearEnd nextYearEnd :: LocalTime nextYearEnd = let (y, _, _) = toGregorian today FIXME this will fail around newyear trimLogbookEntryToDay :: TimeZone -> Day -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntryToDay tz d = trimLogbookEntryTo tz dayStart dayEnd where dayStart = LocalTime d midnight dayEnd = LocalTime (addDays 1 d) midnight trimLogbookEntryTo :: TimeZone -> LocalTime -> LocalTime -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntryTo tz begin end = trimLogbookEntryToM tz (Just begin) (Just end) trimLogbookEntryToM :: TimeZone -> Maybe LocalTime -> Maybe LocalTime -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntryToM tz mBegin mEnd LogbookEntry {..} = constructValid $ LogbookEntry { logbookEntryStart = case mBegin of Nothing -> logbookEntryStart Just begin -> if toLocal logbookEntryStart >= begin then logbookEntryStart else fromLocal begin, logbookEntryEnd = case mEnd of Nothing -> logbookEntryEnd Just end -> if toLocal logbookEntryEnd < end then logbookEntryEnd else fromLocal end } where toLocal :: UTCTime -> LocalTime toLocal = utcToLocalTime tz fromLocal :: LocalTime -> UTCTime fromLocal = localTimeToUTC tz divideIntoClockTimeBlocks :: ZonedTime -> TimeBlock -> [FileTimes] -> [ClockTimeBlock Text] divideIntoClockTimeBlocks zt cb cts = case cb of OneBlock -> [Block {blockTitle = "All Time", blockEntries = cts}] YearBlock -> divideClockTimeIntoTimeBlocks formatYearTitle dayYear yearPeriod MonthBlock -> divideClockTimeIntoTimeBlocks formatMonthTitle dayMonth monthPeriod WeekBlock -> divideClockTimeIntoTimeBlocks formatWeekTitle dayWeek weekPeriod DayBlock -> divideClockTimeIntoTimeBlocks formatDayTitle id dayPeriod where divideClockTimeIntoTimeBlocks :: (Ord t, Enum t) => (t -> Text) -> (Day -> t) -> (t -> Period) -> [ClockTimeBlock Text] divideClockTimeIntoTimeBlocks format fromDay toPeriod = map (mapBlockTitle format) $ combineBlocksByName $ concatMap ( divideClockTimeIntoBlocks zt (fromDay . localDay . utcToLocalTime (zonedTimeZone zt)) toPeriod ) cts divideClockTimeIntoBlocks :: forall t. (Enum t, Ord t) => ZonedTime -> (UTCTime -> t) -> (t -> Period) -> FileTimes -> [ClockTimeBlock t] divideClockTimeIntoBlocks zt func toPeriod = map (uncurry makeClockTimeBlock) . sortAndGroupCombineOrd . divideFileTimes where makeClockTimeBlock :: a -> [FileTimes] -> ClockTimeBlock a makeClockTimeBlock n cts = Block {blockTitle = n, blockEntries = cts} divideFileTimes :: FileTimes -> [(t, FileTimes)] divideFileTimes fts = mapMaybe (\d -> (,) d <$> trimFileTimes zt (toPeriod d) fts) (S.toList $ fileTimesDays fts) fileTimesDays :: FileTimes -> Set t fileTimesDays = goTF . clockTimeForest where goTF :: TForest HeaderTimes -> Set t goTF = S.unions . map goTT . NE.toList goTT :: TTree HeaderTimes -> Set t goTT (TLeaf hts) = goHT $ headerTimesList hts goTT (TBranch hts tf) = goHT hts `S.union` goTF tf goHT :: HeaderTimes [] -> Set t goHT = S.unions . map logbookEntryDays . headerTimesEntries logbookEntryDays :: LogbookEntry -> Set t logbookEntryDays LogbookEntry {..} = S.fromList [func logbookEntryStart .. func logbookEntryEnd] trimFileTimesToDay :: TimeZone -> Day -> FileTimes -> Maybe FileTimes trimFileTimesToDay tz d fts = (\f -> fts {clockTimeForest = f}) <$> goTF (clockTimeForest fts) where goTF :: TForest HeaderTimes -> Maybe (TForest HeaderTimes) goTF ts = do let ts' = mapMaybe goTT $ NE.toList ts NE.nonEmpty ts' goTT :: TTree HeaderTimes -> Maybe (TTree HeaderTimes) goTT (TLeaf hts) = do hts' <- headerTimesNonEmpty $ goHT $ headerTimesList hts pure $ TLeaf hts' goTT (TBranch hts tf) = case goTF tf of Nothing -> TLeaf <$> headerTimesNonEmpty (goHT hts) Just f -> pure $ TBranch (goHT hts) f goHT :: HeaderTimes [] -> HeaderTimes [] goHT hts = hts {headerTimesEntries = mapMaybe (trimLogbookEntryToDay tz d) (headerTimesEntries hts)} sortAndGroupCombineOrd :: Ord a => [(a, b)] -> [(a, [b])] sortAndGroupCombineOrd = sortGroupCombine compare sortGroupCombine :: (a -> a -> Ordering) -> [(a, b)] -> [(a, [b])] sortGroupCombine func = map combine . groupBy ((\a1 a2 -> func a1 a2 == EQ) `on` fst) . sortBy (func `on` fst) where combine [] = error "cannot happen due to groupBy above" combine ts@((a, _) : _) = (a, map snd ts) makeClockTable :: [ClockTimeBlock Text] -> ClockTable makeClockTable = map makeClockTableBlock makeClockTableBlock :: ClockTimeBlock Text -> ClockTableBlock makeClockTableBlock Block {..} = Block {blockTitle = blockTitle, blockEntries = map makeClockTableFile blockEntries} makeClockTableFile :: FileTimes -> ClockTableFile makeClockTableFile FileTimes {..} = ClockTableFile {clockTableFile = clockTimeFile, clockTableForest = unTForest clockTimeForest} unTForest :: TForest HeaderTimes -> Forest ClockTableHeaderEntry unTForest = map unTTree . NE.toList unTTree :: TTree HeaderTimes -> Tree ClockTableHeaderEntry unTTree (TLeaf hts) = Node (makeClockTableHeaderEntry $ headerTimesList hts) [] unTTree (TBranch hts tf) = Node (makeClockTableHeaderEntry hts) (unTForest tf) makeClockTableHeaderEntry :: HeaderTimes [] -> ClockTableHeaderEntry makeClockTableHeaderEntry HeaderTimes {..} = ClockTableHeaderEntry { clockTableHeaderEntryHeader = headerTimesHeader, clockTableHeaderEntryTime = sumLogbookEntryTime headerTimesEntries } sumLogbookEntryTime :: [LogbookEntry] -> NominalDiffTime sumLogbookEntryTime = foldl' (+) 0 . map go where go :: LogbookEntry -> NominalDiffTime go LogbookEntry {..} = diffUTCTime logbookEntryEnd logbookEntryStart trimFileTimes :: ZonedTime -> Period -> FileTimes -> Maybe FileTimes trimFileTimes zt cp fts = do f <- goF $ clockTimeForest fts pure $ fts {clockTimeForest = f} where goF :: TForest HeaderTimes -> Maybe (TForest HeaderTimes) goF tf = NE.nonEmpty $ mapMaybe goT $ NE.toList tf goT :: TTree HeaderTimes -> Maybe (TTree HeaderTimes) goT (TLeaf hts) = TLeaf <$> headerTimesNonEmpty (trimHeaderTimes zt cp (headerTimesList hts)) goT (TBranch hts tf) = case goF tf of Nothing -> TLeaf <$> headerTimesNonEmpty (trimHeaderTimes zt cp hts) Just f -> pure $ TBranch (trimHeaderTimes zt cp hts) f
null
https://raw.githubusercontent.com/NorfairKing/smos/4891d1c7a462040ac63771058ab35e35abb4e46d/smos-report/src/Smos/Report/Clock.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # module Smos.Report.Clock ( module Smos.Report.Clock, module Smos.Report.Clock.Types, ) where import Cursor.Simple.Forest import Cursor.Simple.Tree import Data.Function import Data.List import Data.List.NonEmpty (NonEmpty (..)) import qualified Data.List.NonEmpty as NE import Data.Maybe import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import Data.Time import Data.Time.Calendar.WeekDate import Data.Validity import Data.Validity.Path () import Lens.Micro import Path import Smos.Data import Smos.Report.Clock.Types import Smos.Report.Filter import Smos.Report.Period import Smos.Report.Streaming import Smos.Report.TimeBlock | Reset the timers of every entry that does n't match the filter to zero zeroOutByFilter :: EntryFilter -> Path Rel File -> SmosFile -> SmosFile zeroOutByFilter f rp sf = let cursors = forestCursors $ smosFileForest sf in sf {smosFileForest = map (fmap go) cursors} where go :: ForestCursor Entry -> Entry go fc = ( if filterPredicate f (rp, fc) then id else zeroOutEntry ) (fc ^. (forestCursorSelectedTreeL . treeCursorCurrentL)) zeroOutEntry :: Entry -> Entry zeroOutEntry e = e {entryLogbook = emptyLogbook} findFileTimes :: UTCTime -> Path Rel File -> SmosFile -> Maybe FileTimes findFileTimes now rp sf = do ne <- goF (smosFileForest sf) pure $ FileTimes {clockTimeFile = rp, clockTimeForest = ne} where goF :: Forest Entry -> Maybe (TForest HeaderTimes) goF = NE.nonEmpty . mapMaybe goT goT :: Tree Entry -> Maybe (TTree HeaderTimes) goT (Node e ts_) = case goF ts_ of Nothing -> do hts <- headerTimesNonEmpty $ findHeaderTimes now e pure $ TLeaf hts Just f -> pure $ TBranch (findHeaderTimes now e) f findHeaderTimes :: UTCTime -> Entry -> HeaderTimes [] findHeaderTimes now Entry {..} = case entryLogbook of LogOpen s es -> ht $ (LogbookEntry {logbookEntryStart = s, logbookEntryEnd = now}) : es LogClosed es -> ht es where ht es = HeaderTimes {headerTimesHeader = entryHeader, headerTimesEntries = es} headerTimesList :: HeaderTimes NonEmpty -> HeaderTimes [] headerTimesList hts = HeaderTimes { headerTimesHeader = headerTimesHeader hts, headerTimesEntries = NE.toList $ headerTimesEntries hts } headerTimesNonEmpty :: HeaderTimes [] -> Maybe (HeaderTimes NonEmpty) headerTimesNonEmpty hts = do ne <- NE.nonEmpty $ headerTimesEntries hts pure $ HeaderTimes {headerTimesHeader = headerTimesHeader hts, headerTimesEntries = ne} trimHeaderTimes :: ZonedTime -> Period -> HeaderTimes [] -> HeaderTimes [] trimHeaderTimes zt cp ht = let es' = mapMaybe (trimLogbookEntry zt cp) $ headerTimesEntries ht in ht {headerTimesEntries = es'} trimLogbookEntry :: ZonedTime -> Period -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntry now cp = case cp of AllTime -> pure Yesterday -> trimLogbookEntryToDay tz (pred today) Today -> trimLogbookEntryToDay tz today Tomorrow -> trimLogbookEntryToDay tz (succ today) LastWeek -> trimLogbookEntryTo tz lastWeekStart lastWeekEnd ThisWeek -> trimLogbookEntryTo tz thisWeekStart thisWeekEnd NextWeek -> trimLogbookEntryTo tz nextWeekStart nextWeekEnd LastMonth -> trimLogbookEntryTo tz lastMonthStart lastMonthEnd ThisMonth -> trimLogbookEntryTo tz thisMonthStart thisMonthEnd NextMonth -> trimLogbookEntryTo tz nextMonthStart nextMonthEnd LastYear -> trimLogbookEntryTo tz lastYearStart lastYearEnd ThisYear -> trimLogbookEntryTo tz thisYearStart thisYearEnd NextYear -> trimLogbookEntryTo tz nextYearStart nextYearEnd BeginOnly begin -> trimLogbookEntryToM tz (Just begin) Nothing EndOnly end -> trimLogbookEntryToM tz Nothing (Just end) BeginEnd begin end -> trimLogbookEntryTo tz begin end where tz :: TimeZone tz = zonedTimeZone now nowLocal :: LocalTime nowLocal = zonedTimeToLocalTime now today :: Day today = localDay nowLocal lastWeekStart :: LocalTime lastWeekStart = let (y, wn, _) = toWeekDate today TODO this will fail around newyear lastWeekEnd :: LocalTime lastWeekEnd = thisWeekStart thisWeekStart :: LocalTime thisWeekStart = let (y, wn, _) = toWeekDate today in LocalTime (fromWeekDate y wn 1) midnight thisWeekEnd :: LocalTime thisWeekEnd = let (y, wn, _) = toWeekDate today FIXME this can wrong at the end of the year nextWeekStart :: LocalTime nextWeekStart = thisWeekEnd nextWeekEnd :: LocalTime nextWeekEnd = let (y, wn, _) = toWeekDate today FIXME this can wrong at the end of the year lastMonthStart :: LocalTime lastMonthStart = let (y, m, _) = toGregorian today FIXME This will fail around newyear lastMonthEnd :: LocalTime lastMonthEnd = thisMonthStart thisMonthStart :: LocalTime thisMonthStart = let (y, m, _) = toGregorian today in LocalTime (fromGregorian y m 1) midnight thisMonthEnd :: LocalTime thisMonthEnd = let (y, m, _) = toGregorian today in LocalTime (fromGregorian y m 31) midnight nextMonthStart :: LocalTime nextMonthStart = thisMonthEnd nextMonthEnd :: LocalTime nextMonthEnd = let (y, m, _) = toGregorian today FIXME This will fail around newyear lastYearStart :: LocalTime lastYearStart = let (y, _, _) = toGregorian today FIXME This will fail around newyear lastYearEnd :: LocalTime lastYearEnd = thisYearEnd thisYearStart :: LocalTime thisYearStart = let (y, _, _) = toGregorian today in LocalTime (fromGregorian y 1 1) midnight thisYearEnd :: LocalTime thisYearEnd = let (y, _, _) = toGregorian today in LocalTime (fromGregorian y 12 31) midnight nextYearStart :: LocalTime nextYearStart = thisYearEnd nextYearEnd :: LocalTime nextYearEnd = let (y, _, _) = toGregorian today FIXME this will fail around newyear trimLogbookEntryToDay :: TimeZone -> Day -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntryToDay tz d = trimLogbookEntryTo tz dayStart dayEnd where dayStart = LocalTime d midnight dayEnd = LocalTime (addDays 1 d) midnight trimLogbookEntryTo :: TimeZone -> LocalTime -> LocalTime -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntryTo tz begin end = trimLogbookEntryToM tz (Just begin) (Just end) trimLogbookEntryToM :: TimeZone -> Maybe LocalTime -> Maybe LocalTime -> LogbookEntry -> Maybe LogbookEntry trimLogbookEntryToM tz mBegin mEnd LogbookEntry {..} = constructValid $ LogbookEntry { logbookEntryStart = case mBegin of Nothing -> logbookEntryStart Just begin -> if toLocal logbookEntryStart >= begin then logbookEntryStart else fromLocal begin, logbookEntryEnd = case mEnd of Nothing -> logbookEntryEnd Just end -> if toLocal logbookEntryEnd < end then logbookEntryEnd else fromLocal end } where toLocal :: UTCTime -> LocalTime toLocal = utcToLocalTime tz fromLocal :: LocalTime -> UTCTime fromLocal = localTimeToUTC tz divideIntoClockTimeBlocks :: ZonedTime -> TimeBlock -> [FileTimes] -> [ClockTimeBlock Text] divideIntoClockTimeBlocks zt cb cts = case cb of OneBlock -> [Block {blockTitle = "All Time", blockEntries = cts}] YearBlock -> divideClockTimeIntoTimeBlocks formatYearTitle dayYear yearPeriod MonthBlock -> divideClockTimeIntoTimeBlocks formatMonthTitle dayMonth monthPeriod WeekBlock -> divideClockTimeIntoTimeBlocks formatWeekTitle dayWeek weekPeriod DayBlock -> divideClockTimeIntoTimeBlocks formatDayTitle id dayPeriod where divideClockTimeIntoTimeBlocks :: (Ord t, Enum t) => (t -> Text) -> (Day -> t) -> (t -> Period) -> [ClockTimeBlock Text] divideClockTimeIntoTimeBlocks format fromDay toPeriod = map (mapBlockTitle format) $ combineBlocksByName $ concatMap ( divideClockTimeIntoBlocks zt (fromDay . localDay . utcToLocalTime (zonedTimeZone zt)) toPeriod ) cts divideClockTimeIntoBlocks :: forall t. (Enum t, Ord t) => ZonedTime -> (UTCTime -> t) -> (t -> Period) -> FileTimes -> [ClockTimeBlock t] divideClockTimeIntoBlocks zt func toPeriod = map (uncurry makeClockTimeBlock) . sortAndGroupCombineOrd . divideFileTimes where makeClockTimeBlock :: a -> [FileTimes] -> ClockTimeBlock a makeClockTimeBlock n cts = Block {blockTitle = n, blockEntries = cts} divideFileTimes :: FileTimes -> [(t, FileTimes)] divideFileTimes fts = mapMaybe (\d -> (,) d <$> trimFileTimes zt (toPeriod d) fts) (S.toList $ fileTimesDays fts) fileTimesDays :: FileTimes -> Set t fileTimesDays = goTF . clockTimeForest where goTF :: TForest HeaderTimes -> Set t goTF = S.unions . map goTT . NE.toList goTT :: TTree HeaderTimes -> Set t goTT (TLeaf hts) = goHT $ headerTimesList hts goTT (TBranch hts tf) = goHT hts `S.union` goTF tf goHT :: HeaderTimes [] -> Set t goHT = S.unions . map logbookEntryDays . headerTimesEntries logbookEntryDays :: LogbookEntry -> Set t logbookEntryDays LogbookEntry {..} = S.fromList [func logbookEntryStart .. func logbookEntryEnd] trimFileTimesToDay :: TimeZone -> Day -> FileTimes -> Maybe FileTimes trimFileTimesToDay tz d fts = (\f -> fts {clockTimeForest = f}) <$> goTF (clockTimeForest fts) where goTF :: TForest HeaderTimes -> Maybe (TForest HeaderTimes) goTF ts = do let ts' = mapMaybe goTT $ NE.toList ts NE.nonEmpty ts' goTT :: TTree HeaderTimes -> Maybe (TTree HeaderTimes) goTT (TLeaf hts) = do hts' <- headerTimesNonEmpty $ goHT $ headerTimesList hts pure $ TLeaf hts' goTT (TBranch hts tf) = case goTF tf of Nothing -> TLeaf <$> headerTimesNonEmpty (goHT hts) Just f -> pure $ TBranch (goHT hts) f goHT :: HeaderTimes [] -> HeaderTimes [] goHT hts = hts {headerTimesEntries = mapMaybe (trimLogbookEntryToDay tz d) (headerTimesEntries hts)} sortAndGroupCombineOrd :: Ord a => [(a, b)] -> [(a, [b])] sortAndGroupCombineOrd = sortGroupCombine compare sortGroupCombine :: (a -> a -> Ordering) -> [(a, b)] -> [(a, [b])] sortGroupCombine func = map combine . groupBy ((\a1 a2 -> func a1 a2 == EQ) `on` fst) . sortBy (func `on` fst) where combine [] = error "cannot happen due to groupBy above" combine ts@((a, _) : _) = (a, map snd ts) makeClockTable :: [ClockTimeBlock Text] -> ClockTable makeClockTable = map makeClockTableBlock makeClockTableBlock :: ClockTimeBlock Text -> ClockTableBlock makeClockTableBlock Block {..} = Block {blockTitle = blockTitle, blockEntries = map makeClockTableFile blockEntries} makeClockTableFile :: FileTimes -> ClockTableFile makeClockTableFile FileTimes {..} = ClockTableFile {clockTableFile = clockTimeFile, clockTableForest = unTForest clockTimeForest} unTForest :: TForest HeaderTimes -> Forest ClockTableHeaderEntry unTForest = map unTTree . NE.toList unTTree :: TTree HeaderTimes -> Tree ClockTableHeaderEntry unTTree (TLeaf hts) = Node (makeClockTableHeaderEntry $ headerTimesList hts) [] unTTree (TBranch hts tf) = Node (makeClockTableHeaderEntry hts) (unTForest tf) makeClockTableHeaderEntry :: HeaderTimes [] -> ClockTableHeaderEntry makeClockTableHeaderEntry HeaderTimes {..} = ClockTableHeaderEntry { clockTableHeaderEntryHeader = headerTimesHeader, clockTableHeaderEntryTime = sumLogbookEntryTime headerTimesEntries } sumLogbookEntryTime :: [LogbookEntry] -> NominalDiffTime sumLogbookEntryTime = foldl' (+) 0 . map go where go :: LogbookEntry -> NominalDiffTime go LogbookEntry {..} = diffUTCTime logbookEntryEnd logbookEntryStart trimFileTimes :: ZonedTime -> Period -> FileTimes -> Maybe FileTimes trimFileTimes zt cp fts = do f <- goF $ clockTimeForest fts pure $ fts {clockTimeForest = f} where goF :: TForest HeaderTimes -> Maybe (TForest HeaderTimes) goF tf = NE.nonEmpty $ mapMaybe goT $ NE.toList tf goT :: TTree HeaderTimes -> Maybe (TTree HeaderTimes) goT (TLeaf hts) = TLeaf <$> headerTimesNonEmpty (trimHeaderTimes zt cp (headerTimesList hts)) goT (TBranch hts tf) = case goF tf of Nothing -> TLeaf <$> headerTimesNonEmpty (trimHeaderTimes zt cp hts) Just f -> pure $ TBranch (trimHeaderTimes zt cp hts) f
b54589e8fb67b6b70425572fc84bc48218d95ebc577f85209587f6b27352993e
bitwize/gamsock
gamsock.scm
Gamsock -- an enhanced socket library for Gambit built around the Scsh ; socket API. Copyright ( c ) 2006 - 2007 by . Scsh constant files copyright ( c ) 1993 - 1994 by and Carlstrom . ; For redistribution conditions, please see the file COPYING. (include "gamsock-headers.scm") (c-declare " #ifndef UNIX_PATH_MAX #define UNIX_PATH_MAX 108 #endif ") (define-macro (define-c-constant var type . const) (let* ((const (if (not (null? const)) (car const) (symbol->string var))) (str (string-append "___result = " const ";"))) `(define ,var ((c-lambda () ,type ,str))))) (define-macro (define-int-c-constants prefix . constants) (let* ((base (cond ((string? prefix) prefix) ((symbol? prefix) (symbol->string prefix)) (else (error "Symbol or string required for define-enum-constants prefix"))))) `(begin ,@(map (lambda (x) `(define-c-constant ,(string->symbol (string-append base "/" (symbol->string (car x)))) int ,(cadr x))) constants)))) (define-macro (define-enum-constants prefix . constants) (let* ((base (cond ((string? prefix) prefix) ((symbol? prefix) (symbol->string prefix)) (else (error "Symbol or string required for define-enum-constants prefix"))))) `(begin ,@(map (lambda (x) `(define ,(string->symbol (string-append base "/" (symbol->string (car x)))) ,(cadr x))) constants)))) (include "gamsock-constants.scm") ; This is the definition of the socket type. It should be treated as opaque. (define-type socket id: 98e94265-558a-d985-b3fe-e67f32458c35 type-exhibitor: macro-type-socket constructor: macro-make-socket implementer: implement-type-socket opaque: macros: prefix: macro- predicate: macro-socket? (fd unprintable:) (will unprintable:)) (implement-type-socket) ; This is the definition of the socket address type. (c-define-type socket-address (pointer (struct "sockaddr_storage") socket-address)) (c-declare " size_t c_sockaddr_size(struct sockaddr_storage *sa_st) { switch(sa_st->ss_family) { case AF_INET: return sizeof(struct sockaddr_in); case AF_UNIX: return sizeof(struct sockaddr_un); case AF_INET6: return sizeof(struct sockaddr_in6); default: return sizeof(struct sockaddr); } } " ) ; This is the definition of an internal type which holds ; all of the data for an IPv6 address. (define-type sockaddr-inet6-info id: 74065378-a567-ba71-0047-22b413ad9797 type-exhibitor: macro-type-sockaddr-inet6-info constructor: macro-make-sockaddr-inet6-info implementer: implement-type-sockaddr-inet6-info opaque: macros: prefix: macro- predicate: macro-sockaddr-inet6-info? (host unprintable:) (port unprintable:) (flowinfo unprintable:) (scope-id unprintable:)) (implement-type-sockaddr-inet6-info) (define socket-address-family (c-lambda (socket-address) int " ___return(___arg1->ss_family); ")) ; An exception that is raised when you try to access address information ; from a socket address of the wrong family (e.g., trying to get the IP ; address of a UNIX socket). (define-record-type invalid-socket-address-family-exception (make-invalid-sockaddr-exception n expected-family proc args) invalid-sockaddr-exception? (n invalid-sockaddr-argument-number) (expected-family invalid-sockaddr-exception-expected-family) (proc invalid-sockaddr-exception-procedure) (args invalid-sockaddr-exception-arguments)) ; Socket and socket-address type predicates. (define (socket-address? obj) (let ((f (foreign-tags obj))) (and f (eq? (car f) 'socket-address)))) (define (socket? obj) (macro-socket? obj)) (define (check-socket-address obj fam n proc args) (if (not (socket-address? obj)) (##raise-type-exception n 'socket-address proc args)) (if (not (= (socket-address-family obj) fam)) (raise (make-invalid-sockaddr-exception n fam proc args)))) (define-macro (define-sockaddr-family-pred name family) `(define (,name a) (and (socket-address? a) (= (socket-address-family a) ,family)))) Converts a " UNIX address " or file name ( named the procedure , not me ! ) to a socket address for a UNIX socket . ; This does not yet work with character encodings except ASCII/Latin-1. (define unix-path-max ((c-lambda () int "___return(UNIX_PATH_MAX);"))) (define (unix-address->socket-address fn) (let* ( (l (string-length fn)) ) (if (>= l unix-path-max) (error "unix-address->socket-address: path too long" fn) ((c-lambda (nonnull-char-string) socket-address " struct sockaddr_un *sa_un = (struct sockaddr_un *)malloc(sizeof(struct sockaddr_un)); if(sa_un != NULL) { sa_un->sun_family = AF_UNIX; strncpy(sa_un->sun_path,___arg1,UNIX_PATH_MAX); sa_un->sun_path[UNIX_PATH_MAX - 1] = '\\0'; } ___return((void *)sa_un); ") fn)))) ; Predicate for UNIX-socket-address-ness. (define-sockaddr-family-pred unix-socket-address? address-family/unix) Given a UNIX socket address , returns the " address " ( file name ) for the ; socket. (define (socket-address->unix-address a) ((c-lambda (socket-address) nonnull-char-string " struct sockaddr_un *sa_un = (struct sockaddr_un *)(___arg1); ___return(sa_un->sun_path); ") a)) (define (integer->network-order-vector-16 n) (u8vector (bitwise-and (arithmetic-shift n -8) 255) (bitwise-and n 255))) (define (integer->network-order-vector-32 n) (u8vector (bitwise-and (arithmetic-shift n -24) 255) (bitwise-and (arithmetic-shift n -16) 255) (bitwise-and (arithmetic-shift n -8) 255) (bitwise-and n 255))) (define (network-order-vector->integer-16 v) (bitwise-ior (arithmetic-shift (u8vector-ref v 0) 8) (u8vector-ref v 1))) (define (network-order-vector->integer-32 v) (bitwise-ior (arithmetic-shift (u8vector-ref v 0) 24) (arithmetic-shift (u8vector-ref v 1) 16) (arithmetic-shift (u8vector-ref v 2) 8) (u8vector-ref v 3))) (define (raise-not-an-ip-address) (error "not an ip address")) (define (check-ip4-address v) (let* ((e raise-not-an-ip-address)) (if (not (and (u8vector? v) (= (u8vector-length v) 4))) (e)))) (define (check-ip6-address v) (let* ((e raise-not-an-ip-address)) (if (not (and (u8vector? v) (= (u8vector-length v) 16))) (e)))) Some important IPv4 address and port constants . (define ip-address/any (u8vector 0 0 0 0)) (define ip-address/loopback (u8vector 127 0 0 1)) (define ip-address/broadcast (u8vector 255 255 255 255)) (define port/any 0) Creates a new IPv4 socket address from a host IP address ; and port number. (define (internet-address->socket-address host port) (check-ip4-address host) ((c-lambda (scheme-object int) socket-address " struct sockaddr_storage *sa_st = (struct sockaddr_storage *)malloc(sizeof(struct sockaddr_storage)); struct sockaddr_in *sa_in = (struct sockaddr_in *)sa_st; if(sa_in != NULL) { sa_in->sin_family = AF_INET; sa_in->sin_port = htons(___arg2); memcpy((void *)(&(sa_in->sin_addr)),(const void *)___BODY_AS(___arg1,___tSUBTYPED),sizeof(struct in_addr)); } ___return(sa_st); ") host port)) IPv4 socket - address predicate . (define-sockaddr-family-pred internet-socket-address? address-family/internet) Returns the address ( host and port number as 2 values ) of an IPv4 socket address . (define (socket-address->internet-address a) (check-socket-address a address-family/internet 0 socket-address->internet-address (list a)) (let ((portno ((c-lambda (socket-address) int " struct sockaddr_in *sa_in = (struct sockaddr_in *)(___arg1); ___return(ntohs(sa_in->sin_port)); ") a)) (ip-addr (make-u8vector 4))) ((c-lambda (socket-address scheme-object) void " struct sockaddr_in *sa_in = (struct sockaddr_in *)(___arg1); memcpy((void *)___BODY_AS(___arg2,___tSUBTYPED),(const void *)(&(sa_in->sin_addr)),4); ") a ip-addr) (values ip-addr portno))) ; Creates a new IPv6 socket address from a host IP address, ; port number, flow info and scope ID. (define (internet6-address->socket-address host port flowinfo scope-id) (check-ip6-address host) ((c-lambda (scheme-object int int int) socket-address " struct sockaddr_storage *sa_st = (struct sockaddr_storage *)malloc(sizeof(struct sockaddr_storage)); struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)sa_st; if(sa_in6 != NULL) { sa_in6->sin6_family = AF_INET; sa_in6->sin6_port = htons(___arg2); sa_in6->sin6_flowinfo = htonl(___arg3); sa_in6->sin6_scope_id = htonl(___arg4); memcpy((void *)(&(sa_in6->sin6_addr)),(const void *)___BODY_AS(___arg1,___tSUBTYPED),sizeof(struct in6_addr)); } ___result_voidstar = sa_st; ") host port flowinfo scope-id)) ; IPv6 socket-address predicate. (define-sockaddr-family-pred internet6-socket-address? address-family/internet6) ; Returns the IPv6 address info associated with an IPv6 ; socket address. (define (socket-address->internet6-address a) (check-socket-address a address-family/internet6 0 socket-address->internet-address (list a)) (let ((portno ((c-lambda (socket-address) int "___result = ((struct sockaddr_in6 *)___arg1)->sin6_port;") a)) (flowinfo ((c-lambda (socket-address) int "___result = ((struct sockaddr_in6 *)___arg1)->sin6_flowinfo;") a)) (scope-id ((c-lambda (socket-address) int "___result = ((struct sockaddr_in6 *)___arg1)->sin6_scope_id;") a)) (ip6-addr (make-u8vector 16))) ((c-lambda (socket-address scheme-object) void " struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)(___arg1); memcpy((void *)___BODY_AS(___arg2,___tSUBTYPED),(const void *)(&(sa_in6->sin6_addr)),16); ") a ip6-addr) (values ip6-addr portno flowinfo scope-id))) ; Creates a new unspecified socket address. (define (make-unspecified-socket-address) ((c-lambda () socket-address " struct sockaddr_storage *sa_st = (struct sockaddr_storage *)malloc(sizeof(struct sockaddr_storage)); if(sa_st != NULL) { sa_st->ss_family = AF_UNSPEC; } ___return((void *)sa_st); "))) ;; ; Predicate to test for an unspecified socket address. ;; (define-sockaddr-family-pred unspecified-socket-address? address-family/unspecified) ;; ; All socket related procedures propagate errors from the operating system ;; ; by raising a Gambit os-exception with the errno as the exception code. ; The exceptions are EAGAIN , EWOULDBLOCK , and ; all of which ;; ; simply retry the operation until it's successful or raises another error. (define errno (c-lambda () int "___return(errno);")) (define (raise-socket-exception-if-error thunk proc . args) (let loop ((b (thunk))) (if (< b 0) (let* ((e (errno))) (if (or (= e errno/again) (= e errno/wouldblock) (= e errno/intr)) (begin (thread-yield!) ; to avoid tying up the CPU (loop (thunk))) (apply ##raise-os-exception (append (list #f e proc ) args )))) b))) (define-macro (macro-really-make-socket fd) `(let* ( (sockobj (macro-make-socket ,fd #f))) (macro-socket-will-set! sockobj (make-will sockobj (lambda (s) (close-socket s)))) sockobj)) ; These are C wrappers for the socket-related system calls exposed by gamsock. ; They are kept in a private namespace "gamsock-c#". MESSING WITH THEM IS BAD as their exact interfaces are likely to change . Gamsock 's external interface is likely to be stable , leaving our internals to be AS MESSY AS ; WE WANNA BE. (namespace ("gamsock-c#" c-socket c-bind c-connect c-send c-sendto c-recvfrom c-listen c-accept c-do-boolean-socket-option c-do-integer-socket-option c-do-timeout-socket-option c-do-boolean-set-socket-option c-do-integer-set-socket-option c-do-timeout-set-socket-option c-close)) (define c-socket (c-lambda (int int int) int #<<C-END int s = socket(___arg1,___arg2,___arg3); int fl = fcntl(s,F_GETFL); fcntl(s,F_SETFL,fl | O_NONBLOCK); ___return(s); C-END )) (define c-bind (c-lambda (int socket-address) int #<<C-END int mysize; mysize = c_sockaddr_size((struct sockaddr_storage *)(___arg2)); ___return(bind(___arg1,(struct sockaddr *)(___arg2),mysize)); C-END )) (define c-connect (c-lambda (int socket-address) int #<<C-END int mysize; mysize = c_sockaddr_size((struct sockaddr_storage *)(___arg2)); ___return(connect(___arg1, (struct sockaddr *)___arg2,mysize)); C-END )) (define c-send (c-lambda (int scheme-object int) int #<<C-END int soc = ___arg1; void *buf = ___CAST(void *,___BODY_AS(___arg2,___tSUBTYPED)); size_t bufsiz = ___CAST(size_t,___INT(___U8VECTORLENGTH(___arg2))); int fl = ___CAST(int,___INT(___arg3)); ___return(send(soc,buf,bufsiz,fl)); C-END )) (define c-sendto (c-lambda (int scheme-object int socket-address) int #<<C-END struct sockaddr_storage *sa = ___arg4; int sa_size; int soc = ___arg1; void *buf = ___CAST(void *,___BODY_AS(___arg2,___tSUBTYPED)); size_t bufsiz = ___CAST(size_t,___INT(___U8VECTORLENGTH(___arg2))); int fl = ___CAST(int,___INT(___arg3)); sa_size = c_sockaddr_size((struct sockaddr_storage *)sa); ___return(sendto(soc,buf,bufsiz,fl,(struct sockaddr *)sa,sa_size)); C-END )) (define c-recvfrom (c-lambda (int scheme-object int socket-address) int #<<C-END struct sockaddr_storage *sa = ___arg4; socklen_t sa_size; int soc = ___arg1; void *buf = ___CAST(void *,___BODY_AS(___arg2,___tSUBTYPED)); size_t bufsiz = ___CAST(size_t,___INT(___U8VECTORLENGTH(___arg2))); int fl = ___CAST(int,___INT(___arg3)); ___return(recvfrom(soc,buf,bufsiz,fl,(struct sockaddr *)sa,&sa_size)); C-END )) (define c-listen (c-lambda (int int) int #<<C-END int soc = ___arg1; ___return(listen(soc,___arg2)); C-END )) (define c-accept (c-lambda (int socket-address) int #<<C-END struct sockaddr_storage *ss = ___arg2; socklen_t sslen = sizeof(struct sockaddr_storage); int soc = ___arg1; int r = accept(soc,(struct sockaddr *)ss,&sslen); if(r < 0) { ___return(r); } else { int fl = fcntl(r,F_GETFL); fcntl(r,F_SETFL,fl | O_NONBLOCK); ___return(r); } C-END )) (define c-do-boolean-socket-option (c-lambda (int int int scheme-object) int #<<C-END int optval = 0; socklen_t optlen = sizeof(optval); int r; int soc = ___arg1; r = getsockopt(soc,___arg2,___arg3,&optval,&optlen); ___VECTORSET(___arg4,___FIX(0L),___FIX(optval)); ___return(r); C-END )) (define c-do-integer-socket-option (c-lambda (int int int scheme-object) int #<<C-END int optval = 0; socklen_t optlen = sizeof(optval); int r; int soc = ___arg1; r = getsockopt(soc,___arg2,___arg3,&optval,&optlen); ___VECTORSET(___arg4,___FIX(0L),___FIX(optval)); ___return(r); C-END )) (define c-do-timeout-socket-option (c-lambda (int int int scheme-object) int #<<C-END struct timeval optval; socklen_t optlen = sizeof(optval); int r; int soc = ___arg1; r = getsockopt(soc,___arg2,___arg3,&optval,&optlen); ___VECTORSET(___arg4,___FIX(0L),___FIX(optval.tv_sec)); ___VECTORSET(___arg4,___FIX(1L),___FIX(optval.tv_usec)); ___return(r); C-END )) (define c-do-boolean-set-socket-option (c-lambda (int int int scheme-object) int #<<C-END int optval = 0; socklen_t optlen = sizeof(optval); int r; int soc = ___arg1; if(___arg4 != ___FAL) { optval = 1; } else { optval = 0; } r = setsockopt(soc,___arg2,___arg3,&optval,optlen); ___return(r); C-END )) (define c-do-integer-set-socket-option (c-lambda (int int int int) int #<<C-END int optval = ___arg4; socklen_t optlen = sizeof(optval); int r; int soc = ___arg1; r = setsockopt(soc,___arg2,___arg3,&optval,optlen); ___return(r); C-END )) (define c-do-timeout-set-socket-option (c-lambda (int int int int int) int #<<C-END struct timeval optval; socklen_t optlen = sizeof(optval); int r; int soc = ___arg1; optval.tv_sec = ___arg4; optval.tv_usec = ___arg5; r = setsockopt(soc,___arg2,___arg3,&optval,optlen); ___return(r); C-END )) (define c-close (c-lambda (int) int "___return(close(___arg1));")) ; GAMSOCK API begins here. ; Closes an open socket. (define (close-socket sock) (c-close (macro-socket-fd sock))) ; Creates a new socket of the specified domain (protocol family), ; type (e.g., stream, datagram), and optional protocol. (define (create-socket domain type #!optional (protocol 0)) (macro-really-make-socket (raise-socket-exception-if-error (lambda () (c-socket domain type protocol)) create-socket))) ; Binds a socket to a local address. (define (bind-socket sock addr) (if (not (socket? sock)) (##raise-type-exception 0 'socket bind-socket (list sock addr)) (if (not (socket-address? addr)) (##raise-type-exception 1 'socket-address bind-socket (list sock addr)) (raise-socket-exception-if-error (lambda () (c-bind (macro-socket-fd sock) addr)) bind-socket))) (if #f #f)) ; Connects a socket to a remote address. (define (connect-socket sock addr) (if (not (socket? sock)) (##raise-type-exception 0 'socket connect-socket (list sock addr)) (if (not (socket-address? addr)) (##raise-type-exception 1 'socket-address connect-socket (list sock addr)) (raise-socket-exception-if-error (lambda () (c-connect (macro-socket-fd sock) addr)) connect-socket))) (if #f #f)) ; Sends a message on a socket. The message must be a u8vector or, if ; start and end parameters are given, a slice of the u8vector bound by ; the start and end params. ; Optional flags and a destination address may also be specified; the latter is only useful for connectionless sockets ( e.g. , UDP / IP ) . (define (send-message sock vec #!optional (start 0) (end #f) (flags 0) (addr #f)) (let ((svec (if (and (= start 0) (not end)) vec (subu8vector vec start (if (not end) (u8vector-length vec) end))))) (if (not (socket? sock)) (##raise-type-exception 0 'socket send-message (list sock vec start end flags addr))) (if (not (u8vector? vec)) (##raise-type-exception 1 'u8vector send-message (list sock vec start end flags addr))) (if (not addr) (raise-socket-exception-if-error (lambda () (c-send (macro-socket-fd sock) svec flags)) send-message) (if (not (socket-address? addr)) (##raise-type-exception 3 'socket-address send-message (list sock vec start end flags addr)) (raise-socket-exception-if-error (lambda () (c-sendto (macro-socket-fd sock) svec flags addr)) send-message))))) ; Receives a message from a socket of a given length and returns it as a ; u8vector. Optional flags may be specified. This procedure actually returns two values : the received message and the source address . (define (receive-message sock len #!optional (flags 0)) (let ((addr (make-unspecified-socket-address)) (vec (make-u8vector len 0))) (if (not (socket? sock)) (##raise-type-exception 0 'socket receive-message (list sock len flags))) (let* ((size-actually-recvd (raise-socket-exception-if-error (lambda () (c-recvfrom (macro-socket-fd sock) vec flags addr)) receive-message))) (values (subu8vector vec 0 size-actually-recvd) addr)))) ; Sets up a socket to listen for incoming connections, with the specified number ; of backlogged connections allowed. (define (listen-socket sock backlog) (if (not (socket? sock)) (##raise-type-exception 0 'socket listen-socket (list sock backlog))) (raise-socket-exception-if-error (lambda () (c-listen (macro-socket-fd sock) backlog)) listen-socket) (if #f #f) ) ; Returns the local socket address of the socket. (define (socket-local-address sock) (let* ( (dummy-sockaddr (make-unspecified-socket-address)) (c-getsockname (c-lambda (int socket-address) int " struct sockaddr_storage* ss = ___arg2; socklen_t sslen = sizeof(struct sockaddr_storage); int soc = ___arg1; int r = getsockname(soc,(struct sockaddr *)&ss,&sslen); ___return(r); "))) (if (not (socket? sock)) (##raise-type-exception 0 'socket socket-local-address (list sock))) (raise-socket-exception-if-error (lambda () (c-getsockname (macro-socket-fd sock) dummy-sockaddr)) socket-local-address) dummy-sockaddr)) ; Returns the remote socket address of a socket. (define (socket-remote-address sock) (let* ( (dummy-sockaddr (make-unspecified-socket-address)) (c-getpeername (c-lambda (int socket-address) int " struct sockaddr_storage ss; socklen_t sslen = sizeof(struct sockaddr_storage); int soc = ___arg1; int r = getpeername(soc,(struct sockaddr *)&ss,&sslen); ___return(r); "))) (if (not (socket? sock)) (##raise-type-exception 0 'socket socket-remote-address (list sock))) (raise-socket-exception-if-error (lambda () (c-getpeername (macro-socket-fd sock) dummy-sockaddr)) socket-remote-address) dummy-sockaddr)) Accepts a connection on a socket . Returns two values : a new socket corresponding to ; the connection, and the address of the other side of the connection. (define (accept-connection sock) (let ((dummy-sockaddr (make-unspecified-socket-address))) (if (not (socket? sock)) (##raise-type-exception 0 'socket accept-connection (list sock))) (let ((s2 (raise-socket-exception-if-error (lambda () (c-accept (macro-socket-fd sock) dummy-sockaddr)) accept-connection))) (values (macro-really-make-socket s2) dummy-sockaddr)))) (define (boolean-socket-option? optname) (member optname boolean-socket-options)) (define (integer-socket-option? optname) (member optname integer-socket-options)) (define (timeout-socket-option? optname) (member optname timeout-socket-options)) # # # Socket Option Getters # # # (define (do-boolean-socket-option socket level optname) (let ((v (make-vector 1))) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname))) (raise-socket-exception-if-error (lambda () (c-do-boolean-socket-option (macro-socket-fd socket) level optname v)) socket-option) (not (zero? (vector-ref v 0))))) (define (do-integer-socket-option socket level optname) (let ((v (make-vector 1))) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname))) (raise-socket-exception-if-error (lambda () (c-do-integer-socket-option (macro-socket-fd socket) level optname v)) socket-option) (vector-ref v 0))) (define (do-timeout-socket-option socket level optname) (let ((v (make-vector 2))) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname))) (raise-socket-exception-if-error (lambda () (c-do-timeout-socket-option (macro-socket-fd socket) level optname v)) socket-option) (+ (vector-ref v 0) (/ (vector-ref v 1) 1000000.0)))) (define (socket-option socket level optname) (cond ((boolean-socket-option? optname) (do-boolean-socket-option socket level optname)) ((integer-socket-option? optname) (do-integer-socket-option socket level optname)) ((timeout-socket-option? optname) (do-timeout-socket-option socket level optname)) (else (error "unsupported socket option")))) # # # Socket option setters # # # (define (do-boolean-set-socket-option socket level optname optval) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname optval))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname optval))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname optval))) (raise-socket-exception-if-error (lambda () (c-do-boolean-set-socket-option (macro-socket-fd socket) level optname optval)) socket-option) #!void) (define (do-integer-set-socket-option socket level optname optval) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname optval))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname optval))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname optval))) (if (not (integer? optval)) (##raise-type-exception 3 'integer socket-option (list socket level optname optval))) (raise-socket-exception-if-error (lambda () (c-do-integer-set-socket-option (macro-socket-fd socket) level optname optval)) socket-option) #!void) (define (do-timeout-set-socket-option socket level optname optval) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname optval))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname optval))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname optval))) (if (not (real? optval)) (##raise-type-exception 3 'integer socket-option (list socket level optname optval))) (let* ((sec (inexact->exact (truncate optval))) (usec (inexact->exact (truncate (* (- optval sec) 1000000.))))) (raise-socket-exception-if-error (lambda () (c-do-timeout-set-socket-option (macro-socket-fd socket) level optname sec usec)) socket-option)) #!void) (define (set-socket-option socket level optname optval) (cond ((boolean-socket-option? optname) (do-boolean-set-socket-option socket level optname optval)) ((integer-socket-option? optname) (do-integer-set-socket-option socket level optname optval)) ((timeout-socket-option? optname) (do-timeout-set-socket-option socket level optname optval)) (else (error "unsupported socket option")))) (namespace ("")) (set! ##type-exception-names (cons '(socket . "SOCKET object") (cons '(socket-address . "SOCKET ADDRESS") ##type-exception-names)))
null
https://raw.githubusercontent.com/bitwize/gamsock/a2ac717614cbf7b5d4a37a6208932f91221c32c3/gamsock.scm
scheme
socket API. For redistribution conditions, please see the file COPYING. This is the definition of the socket type. It should be treated as opaque. This is the definition of the socket address type. This is the definition of an internal type which holds all of the data for an IPv6 address. An exception that is raised when you try to access address information from a socket address of the wrong family (e.g., trying to get the IP address of a UNIX socket). Socket and socket-address type predicates. This does not yet work with character encodings except ASCII/Latin-1. Predicate for UNIX-socket-address-ness. socket. and port number. Creates a new IPv6 socket address from a host IP address, port number, flow info and scope ID. IPv6 socket-address predicate. Returns the IPv6 address info associated with an IPv6 socket address. Creates a new unspecified socket address. ; Predicate to test for an unspecified socket address. (define-sockaddr-family-pred unspecified-socket-address? address-family/unspecified) ; All socket related procedures propagate errors from the operating system ; by raising a Gambit os-exception with the errno as the exception code. The exceptions are EAGAIN , EWOULDBLOCK , and ; all of which ; simply retry the operation until it's successful or raises another error. to avoid tying up the CPU These are C wrappers for the socket-related system calls exposed by gamsock. They are kept in a private namespace "gamsock-c#". MESSING WITH THEM IS BAD WE WANNA BE. GAMSOCK API begins here. Closes an open socket. Creates a new socket of the specified domain (protocol family), type (e.g., stream, datagram), and optional protocol. Binds a socket to a local address. Connects a socket to a remote address. Sends a message on a socket. The message must be a u8vector or, if start and end parameters are given, a slice of the u8vector bound by the start and end params. Optional flags and a destination address may also be specified; the latter Receives a message from a socket of a given length and returns it as a u8vector. Optional flags may be specified. This procedure actually returns Sets up a socket to listen for incoming connections, with the specified number of backlogged connections allowed. Returns the local socket address of the socket. Returns the remote socket address of a socket. the connection, and the address of the other side of the connection.
Gamsock -- an enhanced socket library for Gambit built around the Scsh Copyright ( c ) 2006 - 2007 by . Scsh constant files copyright ( c ) 1993 - 1994 by and Carlstrom . (include "gamsock-headers.scm") (c-declare " #ifndef UNIX_PATH_MAX #define UNIX_PATH_MAX 108 #endif ") (define-macro (define-c-constant var type . const) (let* ((const (if (not (null? const)) (car const) (symbol->string var))) (str (string-append "___result = " const ";"))) `(define ,var ((c-lambda () ,type ,str))))) (define-macro (define-int-c-constants prefix . constants) (let* ((base (cond ((string? prefix) prefix) ((symbol? prefix) (symbol->string prefix)) (else (error "Symbol or string required for define-enum-constants prefix"))))) `(begin ,@(map (lambda (x) `(define-c-constant ,(string->symbol (string-append base "/" (symbol->string (car x)))) int ,(cadr x))) constants)))) (define-macro (define-enum-constants prefix . constants) (let* ((base (cond ((string? prefix) prefix) ((symbol? prefix) (symbol->string prefix)) (else (error "Symbol or string required for define-enum-constants prefix"))))) `(begin ,@(map (lambda (x) `(define ,(string->symbol (string-append base "/" (symbol->string (car x)))) ,(cadr x))) constants)))) (include "gamsock-constants.scm") (define-type socket id: 98e94265-558a-d985-b3fe-e67f32458c35 type-exhibitor: macro-type-socket constructor: macro-make-socket implementer: implement-type-socket opaque: macros: prefix: macro- predicate: macro-socket? (fd unprintable:) (will unprintable:)) (implement-type-socket) (c-define-type socket-address (pointer (struct "sockaddr_storage") socket-address)) (c-declare " size_t c_sockaddr_size(struct sockaddr_storage *sa_st) { switch(sa_st->ss_family) { case AF_INET: case AF_UNIX: case AF_INET6: default: } } " ) (define-type sockaddr-inet6-info id: 74065378-a567-ba71-0047-22b413ad9797 type-exhibitor: macro-type-sockaddr-inet6-info constructor: macro-make-sockaddr-inet6-info implementer: implement-type-sockaddr-inet6-info opaque: macros: prefix: macro- predicate: macro-sockaddr-inet6-info? (host unprintable:) (port unprintable:) (flowinfo unprintable:) (scope-id unprintable:)) (implement-type-sockaddr-inet6-info) (define socket-address-family (c-lambda (socket-address) int " ")) (define-record-type invalid-socket-address-family-exception (make-invalid-sockaddr-exception n expected-family proc args) invalid-sockaddr-exception? (n invalid-sockaddr-argument-number) (expected-family invalid-sockaddr-exception-expected-family) (proc invalid-sockaddr-exception-procedure) (args invalid-sockaddr-exception-arguments)) (define (socket-address? obj) (let ((f (foreign-tags obj))) (and f (eq? (car f) 'socket-address)))) (define (socket? obj) (macro-socket? obj)) (define (check-socket-address obj fam n proc args) (if (not (socket-address? obj)) (##raise-type-exception n 'socket-address proc args)) (if (not (= (socket-address-family obj) fam)) (raise (make-invalid-sockaddr-exception n fam proc args)))) (define-macro (define-sockaddr-family-pred name family) `(define (,name a) (and (socket-address? a) (= (socket-address-family a) ,family)))) Converts a " UNIX address " or file name ( named the procedure , not me ! ) to a socket address for a UNIX socket . (define unix-path-max ((c-lambda () int "___return(UNIX_PATH_MAX);"))) (define (unix-address->socket-address fn) (let* ( (l (string-length fn)) ) (if (>= l unix-path-max) (error "unix-address->socket-address: path too long" fn) ((c-lambda (nonnull-char-string) socket-address " if(sa_un != NULL) { } ") fn)))) (define-sockaddr-family-pred unix-socket-address? address-family/unix) Given a UNIX socket address , returns the " address " ( file name ) for the (define (socket-address->unix-address a) ((c-lambda (socket-address) nonnull-char-string " ") a)) (define (integer->network-order-vector-16 n) (u8vector (bitwise-and (arithmetic-shift n -8) 255) (bitwise-and n 255))) (define (integer->network-order-vector-32 n) (u8vector (bitwise-and (arithmetic-shift n -24) 255) (bitwise-and (arithmetic-shift n -16) 255) (bitwise-and (arithmetic-shift n -8) 255) (bitwise-and n 255))) (define (network-order-vector->integer-16 v) (bitwise-ior (arithmetic-shift (u8vector-ref v 0) 8) (u8vector-ref v 1))) (define (network-order-vector->integer-32 v) (bitwise-ior (arithmetic-shift (u8vector-ref v 0) 24) (arithmetic-shift (u8vector-ref v 1) 16) (arithmetic-shift (u8vector-ref v 2) 8) (u8vector-ref v 3))) (define (raise-not-an-ip-address) (error "not an ip address")) (define (check-ip4-address v) (let* ((e raise-not-an-ip-address)) (if (not (and (u8vector? v) (= (u8vector-length v) 4))) (e)))) (define (check-ip6-address v) (let* ((e raise-not-an-ip-address)) (if (not (and (u8vector? v) (= (u8vector-length v) 16))) (e)))) Some important IPv4 address and port constants . (define ip-address/any (u8vector 0 0 0 0)) (define ip-address/loopback (u8vector 127 0 0 1)) (define ip-address/broadcast (u8vector 255 255 255 255)) (define port/any 0) Creates a new IPv4 socket address from a host IP address (define (internet-address->socket-address host port) (check-ip4-address host) ((c-lambda (scheme-object int) socket-address " if(sa_in != NULL) { } ") host port)) IPv4 socket - address predicate . (define-sockaddr-family-pred internet-socket-address? address-family/internet) Returns the address ( host and port number as 2 values ) of an IPv4 socket address . (define (socket-address->internet-address a) (check-socket-address a address-family/internet 0 socket-address->internet-address (list a)) (let ((portno ((c-lambda (socket-address) int " ") a)) (ip-addr (make-u8vector 4))) ((c-lambda (socket-address scheme-object) void " ") a ip-addr) (values ip-addr portno))) (define (internet6-address->socket-address host port flowinfo scope-id) (check-ip6-address host) ((c-lambda (scheme-object int int int) socket-address " if(sa_in6 != NULL) { } ") host port flowinfo scope-id)) (define-sockaddr-family-pred internet6-socket-address? address-family/internet6) (define (socket-address->internet6-address a) (check-socket-address a address-family/internet6 0 socket-address->internet-address (list a)) (let ((portno ((c-lambda (socket-address) int "___result = ((struct sockaddr_in6 *)___arg1)->sin6_port;") a)) (flowinfo ((c-lambda (socket-address) int "___result = ((struct sockaddr_in6 *)___arg1)->sin6_flowinfo;") a)) (scope-id ((c-lambda (socket-address) int "___result = ((struct sockaddr_in6 *)___arg1)->sin6_scope_id;") a)) (ip6-addr (make-u8vector 16))) ((c-lambda (socket-address scheme-object) void " ") a ip6-addr) (values ip6-addr portno flowinfo scope-id))) (define (make-unspecified-socket-address) ((c-lambda () socket-address " if(sa_st != NULL) { } "))) (define errno (c-lambda () int "___return(errno);")) (define (raise-socket-exception-if-error thunk proc . args) (let loop ((b (thunk))) (if (< b 0) (let* ((e (errno))) (if (or (= e errno/again) (= e errno/wouldblock) (= e errno/intr)) (begin (loop (thunk))) (apply ##raise-os-exception (append (list #f e proc ) args )))) b))) (define-macro (macro-really-make-socket fd) `(let* ( (sockobj (macro-make-socket ,fd #f))) (macro-socket-will-set! sockobj (make-will sockobj (lambda (s) (close-socket s)))) sockobj)) as their exact interfaces are likely to change . Gamsock 's external interface is likely to be stable , leaving our internals to be AS MESSY AS (namespace ("gamsock-c#" c-socket c-bind c-connect c-send c-sendto c-recvfrom c-listen c-accept c-do-boolean-socket-option c-do-integer-socket-option c-do-timeout-socket-option c-do-boolean-set-socket-option c-do-integer-set-socket-option c-do-timeout-set-socket-option c-close)) (define c-socket (c-lambda (int int int) int #<<C-END C-END )) (define c-bind (c-lambda (int socket-address) int #<<C-END C-END )) (define c-connect (c-lambda (int socket-address) int #<<C-END ___return(connect(___arg1, C-END )) (define c-send (c-lambda (int scheme-object int) int #<<C-END C-END )) (define c-sendto (c-lambda (int scheme-object int socket-address) int #<<C-END C-END )) (define c-recvfrom (c-lambda (int scheme-object int socket-address) int #<<C-END C-END )) (define c-listen (c-lambda (int int) int #<<C-END C-END )) (define c-accept (c-lambda (int socket-address) int #<<C-END if(r < 0) { } else { } C-END )) (define c-do-boolean-socket-option (c-lambda (int int int scheme-object) int #<<C-END C-END )) (define c-do-integer-socket-option (c-lambda (int int int scheme-object) int #<<C-END C-END )) (define c-do-timeout-socket-option (c-lambda (int int int scheme-object) int #<<C-END C-END )) (define c-do-boolean-set-socket-option (c-lambda (int int int scheme-object) int #<<C-END if(___arg4 != ___FAL) { } else { } C-END )) (define c-do-integer-set-socket-option (c-lambda (int int int int) int #<<C-END C-END )) (define c-do-timeout-set-socket-option (c-lambda (int int int int int) int #<<C-END C-END )) (define c-close (c-lambda (int) int "___return(close(___arg1));")) (define (close-socket sock) (c-close (macro-socket-fd sock))) (define (create-socket domain type #!optional (protocol 0)) (macro-really-make-socket (raise-socket-exception-if-error (lambda () (c-socket domain type protocol)) create-socket))) (define (bind-socket sock addr) (if (not (socket? sock)) (##raise-type-exception 0 'socket bind-socket (list sock addr)) (if (not (socket-address? addr)) (##raise-type-exception 1 'socket-address bind-socket (list sock addr)) (raise-socket-exception-if-error (lambda () (c-bind (macro-socket-fd sock) addr)) bind-socket))) (if #f #f)) (define (connect-socket sock addr) (if (not (socket? sock)) (##raise-type-exception 0 'socket connect-socket (list sock addr)) (if (not (socket-address? addr)) (##raise-type-exception 1 'socket-address connect-socket (list sock addr)) (raise-socket-exception-if-error (lambda () (c-connect (macro-socket-fd sock) addr)) connect-socket))) (if #f #f)) is only useful for connectionless sockets ( e.g. , UDP / IP ) . (define (send-message sock vec #!optional (start 0) (end #f) (flags 0) (addr #f)) (let ((svec (if (and (= start 0) (not end)) vec (subu8vector vec start (if (not end) (u8vector-length vec) end))))) (if (not (socket? sock)) (##raise-type-exception 0 'socket send-message (list sock vec start end flags addr))) (if (not (u8vector? vec)) (##raise-type-exception 1 'u8vector send-message (list sock vec start end flags addr))) (if (not addr) (raise-socket-exception-if-error (lambda () (c-send (macro-socket-fd sock) svec flags)) send-message) (if (not (socket-address? addr)) (##raise-type-exception 3 'socket-address send-message (list sock vec start end flags addr)) (raise-socket-exception-if-error (lambda () (c-sendto (macro-socket-fd sock) svec flags addr)) send-message))))) two values : the received message and the source address . (define (receive-message sock len #!optional (flags 0)) (let ((addr (make-unspecified-socket-address)) (vec (make-u8vector len 0))) (if (not (socket? sock)) (##raise-type-exception 0 'socket receive-message (list sock len flags))) (let* ((size-actually-recvd (raise-socket-exception-if-error (lambda () (c-recvfrom (macro-socket-fd sock) vec flags addr)) receive-message))) (values (subu8vector vec 0 size-actually-recvd) addr)))) (define (listen-socket sock backlog) (if (not (socket? sock)) (##raise-type-exception 0 'socket listen-socket (list sock backlog))) (raise-socket-exception-if-error (lambda () (c-listen (macro-socket-fd sock) backlog)) listen-socket) (if #f #f) ) (define (socket-local-address sock) (let* ( (dummy-sockaddr (make-unspecified-socket-address)) (c-getsockname (c-lambda (int socket-address) int " "))) (if (not (socket? sock)) (##raise-type-exception 0 'socket socket-local-address (list sock))) (raise-socket-exception-if-error (lambda () (c-getsockname (macro-socket-fd sock) dummy-sockaddr)) socket-local-address) dummy-sockaddr)) (define (socket-remote-address sock) (let* ( (dummy-sockaddr (make-unspecified-socket-address)) (c-getpeername (c-lambda (int socket-address) int " "))) (if (not (socket? sock)) (##raise-type-exception 0 'socket socket-remote-address (list sock))) (raise-socket-exception-if-error (lambda () (c-getpeername (macro-socket-fd sock) dummy-sockaddr)) socket-remote-address) dummy-sockaddr)) Accepts a connection on a socket . Returns two values : a new socket corresponding to (define (accept-connection sock) (let ((dummy-sockaddr (make-unspecified-socket-address))) (if (not (socket? sock)) (##raise-type-exception 0 'socket accept-connection (list sock))) (let ((s2 (raise-socket-exception-if-error (lambda () (c-accept (macro-socket-fd sock) dummy-sockaddr)) accept-connection))) (values (macro-really-make-socket s2) dummy-sockaddr)))) (define (boolean-socket-option? optname) (member optname boolean-socket-options)) (define (integer-socket-option? optname) (member optname integer-socket-options)) (define (timeout-socket-option? optname) (member optname timeout-socket-options)) # # # Socket Option Getters # # # (define (do-boolean-socket-option socket level optname) (let ((v (make-vector 1))) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname))) (raise-socket-exception-if-error (lambda () (c-do-boolean-socket-option (macro-socket-fd socket) level optname v)) socket-option) (not (zero? (vector-ref v 0))))) (define (do-integer-socket-option socket level optname) (let ((v (make-vector 1))) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname))) (raise-socket-exception-if-error (lambda () (c-do-integer-socket-option (macro-socket-fd socket) level optname v)) socket-option) (vector-ref v 0))) (define (do-timeout-socket-option socket level optname) (let ((v (make-vector 2))) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname))) (raise-socket-exception-if-error (lambda () (c-do-timeout-socket-option (macro-socket-fd socket) level optname v)) socket-option) (+ (vector-ref v 0) (/ (vector-ref v 1) 1000000.0)))) (define (socket-option socket level optname) (cond ((boolean-socket-option? optname) (do-boolean-socket-option socket level optname)) ((integer-socket-option? optname) (do-integer-socket-option socket level optname)) ((timeout-socket-option? optname) (do-timeout-socket-option socket level optname)) (else (error "unsupported socket option")))) # # # Socket option setters # # # (define (do-boolean-set-socket-option socket level optname optval) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname optval))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname optval))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname optval))) (raise-socket-exception-if-error (lambda () (c-do-boolean-set-socket-option (macro-socket-fd socket) level optname optval)) socket-option) #!void) (define (do-integer-set-socket-option socket level optname optval) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname optval))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname optval))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname optval))) (if (not (integer? optval)) (##raise-type-exception 3 'integer socket-option (list socket level optname optval))) (raise-socket-exception-if-error (lambda () (c-do-integer-set-socket-option (macro-socket-fd socket) level optname optval)) socket-option) #!void) (define (do-timeout-set-socket-option socket level optname optval) (if (not (socket? socket)) (##raise-type-exception 0 'socket socket-option (list socket level optname optval))) (if (not (integer? level)) (##raise-type-exception 1 'integer socket-option (list socket level optname optval))) (if (not (integer? optname)) (##raise-type-exception 2 'integer socket-option (list socket level optname optval))) (if (not (real? optval)) (##raise-type-exception 3 'integer socket-option (list socket level optname optval))) (let* ((sec (inexact->exact (truncate optval))) (usec (inexact->exact (truncate (* (- optval sec) 1000000.))))) (raise-socket-exception-if-error (lambda () (c-do-timeout-set-socket-option (macro-socket-fd socket) level optname sec usec)) socket-option)) #!void) (define (set-socket-option socket level optname optval) (cond ((boolean-socket-option? optname) (do-boolean-set-socket-option socket level optname optval)) ((integer-socket-option? optname) (do-integer-set-socket-option socket level optname optval)) ((timeout-socket-option? optname) (do-timeout-set-socket-option socket level optname optval)) (else (error "unsupported socket option")))) (namespace ("")) (set! ##type-exception-names (cons '(socket . "SOCKET object") (cons '(socket-address . "SOCKET ADDRESS") ##type-exception-names)))
d632036157882acf4342f8cb01d9f4c7559c49b284ee9edb55d2955a9a645a16
neongreen/haskell-ex
Main.hs
# LANGUAGE InstanceSigs # -------------------------------------------------------------------------------- 18 . Trie /{trie}/ -- Construct a trie from all words in a dictionary and implement search for -- words by prefix. Here's an example of a trie for -- /{cool, cat, coal, bet, bean}/: -- -- b c -- / / \ -- e a o -- / \ / / \ -- t a t a o -- | | | -- n l l -- -- You should read the words file, construct a trie, say how many nodes are in the trie ( e.g. in the sample one there are 13 nodes ) , and then answer user 's -- queries to find all words starting with given letters: -- Trie created . There are 13 nodes . -- -- > be -- bean bet -- -- > c -- cat coal cool -- -- > co -- coal cool -- -- You can use the following type for the trie (but feel free to use something -- else): -- data Trie a = Empty | Node ( Map a ( Trie a ) ) -- -- The list of words in available in the /data\// folder in the repository. -------------------------------------------------------------------------------- module Main where import Control.Monad (forever) import Data.Monoid import Data.List import Data.Maybe import Data.Map.Strict (Map) import qualified Data.Map.Strict as M filepath :: FilePath filepath = "data/words" main :: IO () main = do contents <- readFile filepath let t = fromFileContents contents :: Trie Char putStrLn $ "Trie created. There are " ++ show (size t) ++ " nodes." forever $ do putStr "> " query <- getLine putStrLn . renderQueryResults . queryTrie t $ query return () where -- assume that the words on a file are each on separate lines fromFileContents :: String -> Trie Char fromFileContents = foldl' mappend mempty . fmap fromList . lines queryTrie :: Trie Char -> String -> Maybe [String] queryTrie t query = fmap (fmap (query ++) . toList) . subTrie t $ query renderQueryResults :: Maybe [String] -> String renderQueryResults = unwords . fromMaybe [""] ------------------------------------------------------------------------ Declare a Trie and useful typeclasses data Trie a = Empty | Node (Map a (Trie a)) deriving (Show) instance Ord a => Monoid (Trie a) where mempty :: Trie a mempty = Empty mappend :: Trie a -> Trie a -> Trie a mappend Empty t = t mappend t Empty = t mappend (Node t0) (Node t1) = Node $ M.unionWith mappend t0 t1 A Trie can be constructed from a list fromList :: Ord a => [a] -> Trie a fromList [] = Empty fromList (a:as) = Node . M.singleton a . fromList $ as A Trie can be deconstructed to a list of lists toList :: Trie a -> [[a]] toList Empty = [[]] toList (Node m) = concat . M.elems . M.mapWithKey go $ m where go :: a -> Trie a -> [[a]] go k = fmap (k:) . toList -- get the number of nodes in the trie size :: Trie a -> Int size Empty = 0 size (Node m) = M.size m + sum (M.map size m) -- return a sub tree at some point of traversal subTrie :: Ord a => Trie a -> [a] -> Maybe (Trie a) subTrie Empty as = Nothing subTrie m [] = Just m subTrie (Node m) (a:as) = M.lookup a m >>= (`subTrie` as)
null
https://raw.githubusercontent.com/neongreen/haskell-ex/345115444fdf370a43390fd942e2851b9b1963ad/week4/trie/stites/Main.hs
haskell
------------------------------------------------------------------------------ words by prefix. Here's an example of a trie for /{cool, cat, coal, bet, bean}/: b c / / \ e a o / \ / / \ t a t a o | | | n l l You should read the words file, construct a trie, say how many nodes are in queries to find all words starting with given letters: > be bean bet > c cat coal cool > co coal cool You can use the following type for the trie (but feel free to use something else): The list of words in available in the /data\// folder in the repository. ------------------------------------------------------------------------------ assume that the words on a file are each on separate lines ---------------------------------------------------------------------- get the number of nodes in the trie return a sub tree at some point of traversal
# LANGUAGE InstanceSigs # 18 . Trie /{trie}/ Construct a trie from all words in a dictionary and implement search for the trie ( e.g. in the sample one there are 13 nodes ) , and then answer user 's Trie created . There are 13 nodes . data Trie a = Empty | Node ( Map a ( Trie a ) ) module Main where import Control.Monad (forever) import Data.Monoid import Data.List import Data.Maybe import Data.Map.Strict (Map) import qualified Data.Map.Strict as M filepath :: FilePath filepath = "data/words" main :: IO () main = do contents <- readFile filepath let t = fromFileContents contents :: Trie Char putStrLn $ "Trie created. There are " ++ show (size t) ++ " nodes." forever $ do putStr "> " query <- getLine putStrLn . renderQueryResults . queryTrie t $ query return () where fromFileContents :: String -> Trie Char fromFileContents = foldl' mappend mempty . fmap fromList . lines queryTrie :: Trie Char -> String -> Maybe [String] queryTrie t query = fmap (fmap (query ++) . toList) . subTrie t $ query renderQueryResults :: Maybe [String] -> String renderQueryResults = unwords . fromMaybe [""] Declare a Trie and useful typeclasses data Trie a = Empty | Node (Map a (Trie a)) deriving (Show) instance Ord a => Monoid (Trie a) where mempty :: Trie a mempty = Empty mappend :: Trie a -> Trie a -> Trie a mappend Empty t = t mappend t Empty = t mappend (Node t0) (Node t1) = Node $ M.unionWith mappend t0 t1 A Trie can be constructed from a list fromList :: Ord a => [a] -> Trie a fromList [] = Empty fromList (a:as) = Node . M.singleton a . fromList $ as A Trie can be deconstructed to a list of lists toList :: Trie a -> [[a]] toList Empty = [[]] toList (Node m) = concat . M.elems . M.mapWithKey go $ m where go :: a -> Trie a -> [[a]] go k = fmap (k:) . toList size :: Trie a -> Int size Empty = 0 size (Node m) = M.size m + sum (M.map size m) subTrie :: Ord a => Trie a -> [a] -> Maybe (Trie a) subTrie Empty as = Nothing subTrie m [] = Just m subTrie (Node m) (a:as) = M.lookup a m >>= (`subTrie` as)
b1e2e75962a936c8d1489b06599044bce6447f5f7ef5e6c42eaef76ea0c4903f
bortexz/tacos
tacos.clj
(ns bortexz.tacos (:require [clojure.math.numeric-tower :as math-nt] [bortexz.utils.math :as umath] [bortexz.graphcom :as g] [better-cond.core :as bc] [bortexz.tacos.timeseries :as ts])) (defn derived "Creates a new derived timeseries node (a.k.a indicator) given the following args: - `tl` A graphcom node whose emitted value implements [[tacos.timeseires/Timeline]]. - `sources` Map of dependency nodes. Timeline node will be merged into sources under `::timeline` keyword automatically. - `compute-ts` 3-arity fn that will be called with args [current-value sources-values timestamp], and must return the value of this timeseries at `timestamp`. Note that timestamp can be any type that can be compared with `compare`. You could use integers (e.g epoch milliseconds), java.time instants, ISO strings, etc Returns node that will emit a derived timeseries as value." [tl sources compute-ts] (g/compute-node (merge sources {::timeline tl}) (fn derived-handler- [current-value {::keys [timeline] :as sources}] (ts/-apply-timeline timeline current-value (fn [v ts] (compute-ts v sources ts)))))) (defn delta-source "Sources: - `input` input node that contain partial timeseries of new items to introduce into the graph. Opts: - `max-size` the maximum size used for [[tacos.timeseries/delta-timeline]]. Returns tuple of nodes [delta-tl src] that can be used to introduce new values into a graph of derived timeseries: - `delta-tl` is a node that emits [[tacos.timeseries/delta-timeline]] using `max-size` and the timestamps of timeseries in `input`. - `src` is a timeseries node that accumulates new values from `input`, up to a maximum of `max-size`, presumably to be used as the source for other derived timeseries." [{:keys [input] :as sources} {:keys [max-size] :as opts}] (let [tl (g/compute-node sources (fn delta-entrypoint-tl- [_ {:keys [input]}] (ts/delta-timeline (keys input) max-size))) src (derived tl sources (fn [_ {:keys [input]} k] (get input k)))] [tl src])) (defn map-some "Returns node that applies f to each timestamp value of each node, when current timestamp values for all nodes are non-nil. e.g: - sum each timestamp's val of different timeseries `(map-some tl + x y z)` - mean of x,y,z nodes `(map-some tl (fn [& xs] (/ (reduce + 0 xs) (count xs))) x y z)`" ([tl f n1] (derived tl {:n1 n1} (fn map-some-1 [_ {:keys [n1]} k] (bc/when-some [v1 (get n1 k)] (f v1))))) ([tl f n1 n2] (derived tl {:n1 n1 :n2 n2} (fn map-some-2 [_ {:keys [n1 n2]} k] (bc/when-some [v1 (get n1 k) v2 (get n2 k)] (f v1 v2))))) ([tl f n1 n2 n3] (derived tl {:n1 n1 :n2 n2 :n3 n3} (fn map-some-3 [_ {:keys [n1 n2 n3]} k] (bc/when-some [v1 (get n1 k) v2 (get n2 k) v3 (get n3 k)] (f v1 v2 v3))))) ([tl f n1 n2 n3 n4] (derived tl {:n1 n1 :n2 n2 :n3 n3 :n4 n4} (fn map-some-3 [_ {:keys [n1 n2 n3 n4]} k] (bc/when-some [v1 (get n1 k) v2 (get n2 k) v3 (get n3 k) v4 (get n4 k)] (f v1 v2 v3 v4))))) ([tl f n1 n2 n3 n4 & nodes] (let [xm (zipmap (range) (into [n1 n2 n3 n4] nodes)) ks (vec (range (count xm)))] (derived tl xm (fn map-some-n [_ xm k] (bc/when-let [xs (some-> (reduce (fn [acc idx] (if-let [tsv (get (get xm idx) k)] (conj! acc tsv) (reduced nil))) (transient []) ks) (persistent!))] (apply f xs))))))) (defn sources-map "Returns timeseries node whose values combine current timestamp for all sources in a hash map, under same keyword as specified in `sources`, when all have a value. E.g candles (sources-map tl {:high high :low low :close close :open open}) will have values as map of `{:open ,,, :close ,,, :high ,,, :low ,,,}`. Useful to combine multiple indicators that share the same timeline into one to use it as a single timeseries." [tl sources] (let [ks (keys sources)] (derived tl sources (fn [_ srcs ts] (some-> (reduce (fn [acc k] (if-let [v (get (get srcs k) ts)] (assoc! acc k v) (reduced nil))) (transient {}) ks) (persistent!)))))) (defn spread-map "Given a timeseries node `map-source` that has maps as values and map of opts, returns a map of new nodes with keys `ks` where values are new nodes that each one contains the values of key in map-src, possibly transformed. Sources: - `map-source` Opts: - `ks` set of keys to extract as indicators - `transform` function to transform each of the values, if needed. Defaults to identity. E.g (spread-map tl candles-node [:open :close :high :low]) returns a map of nodes #{:open :close :high :low} each one with the corresponding candle value." [tl map-source {:keys [ks transform] :or {transform identity}}] (zipmap ks (map #(map-some tl (comp transform %) map-source) ks))) (defn momentum "src(i) - src(i-period) Sources: - `src` Opts: - `period` Defaults to 1." ([tl sources] (momentum tl sources {})) ([tl {:keys [src] :as sources} {:keys [period] :or {period 1}}] (derived tl sources (fn momentum- [_ {:keys [src]} k] (bc/when-let [curr (get src k) prev (ts/shift src k (- period) {:vf val})] (- curr prev)))))) (defn rate-of-change "(src - src(i-period)) / src(i-period), vals between -1 and 1, except the case when src(i-period) is zero, then returns opt `nan-val` Sources: - `src` Opts: - `period` Defaults to 1. - `nan-val` defaults to Double/NaN" ([tl sources] (rate-of-change tl sources {})) ([tl {:keys [src] :as sources} {:keys [period nan-val] :or {period 1 nan-val Double/NaN}}] (derived tl sources (fn rate-of-change- [_ {:keys [src]} k] (bc/when-let [curr (get src k) prev (ts/shift src k (- period) {:vf val})] (if (zero? prev) nan-val (/ (- curr prev) prev))))))) (defn envelope "Returns tuple of nodes [upper lower], where: pos = src + (src * multiplier) neg = src - (src * multiplier) Sources: - `src Opts: - `multiplier` percentage number. e.g. 0.01 will create a 1% envelope around `src`." [tl {:keys [src]} {:keys [multiplier]}] (let [upper (map-some tl (fn [x] (+ x (* x multiplier))) src) lower (map-some tl (fn [x] (- x (* x multiplier))) src)] [upper lower])) (defn mean "Returns node that computes the mean of all nodes specified. e.g ohlc4 = (mean tl open close high low) where open,close,high,low are indicators of each candle value." [tl & srcv] (apply map-some tl (fn [& xs] (umath/mean xs)) srcv)) (defn hl2 "(high + low)/2 Sources: - `high` - `low`" [tl {:keys [high low]}] (mean tl high low)) (defn hlc3 "(high+low+close)/3 Sources: - `high` - `low` - `close`" [tl {:keys [high low close]}] (mean tl high low close)) (defn ohlc4 "(open+high+low+close)/4 Sources: - `open` - `high` - `low` - `close`" [tl {:keys [open high low close]}] (mean tl open high low close)) (defn heikin-ashi "Returns node that calculates Heikin ashi candles whose values are maps of keys #{:open :close :high :low} Sources: - `open` - `close` - `high` - `low` Reference: - -ashi-better-candlestick/" [tl {:keys [open close high low] :as sources}] (derived tl sources (fn heikin-ashi- [ha {:keys [open close high low]} k] (let [[o c h l :as ohlc] (mapv #(get % k) [open close high low])] (when (every? some? ohlc) (let [prev-k (ts/shift close k -1 {:vf key}) prev-ha (get ha prev-k) ha-close (umath/mean ohlc) ha-open (if prev-ha (/ (+ (:open prev-ha) (:close prev-ha)) 2) (/ (+ o c) 2))] {:open ha-open :close ha-close :high (max ha-open ha-close h) :low (min ha-open ha-close l)})))))) (defn simple-moving-average "Reference: - -moving-average/ Sources: - `src` Opts: - `period` Notes: - Assumes that only latest time points are added (either new later timestamp, or replacement of current latest). This should be the case most of the time. For earlier than latest arriving time points, you need to recompute all from earlier time point to latest for correct results, by specifying them on the timeline. - Keeps an internal summatory to work on log-n (n=size of timeseries) instead of reducing tail all the time." [tl {:keys [src] :as sources} {:keys [period]}] (let [acc (derived tl sources (fn [x {:keys [src]} k] (let [to-remove (ts/shift src k (- period) {:vf val}) to-add (get src k) prev-k (ts/shift src k -1 {:vf key}) prev (when prev-k (get x prev-k)) {:keys [sum]} (or prev {:sum 0 :ready? false})] {:sum (when to-add (+ (or sum 0) to-add (if to-remove (- to-remove) 0))) :ready? (some? to-remove)})))] (derived tl {:acc acc} (fn [_ {:keys [acc]} k] (let [{:keys [sum ready?]} (get acc k)] (when ready? (/ sum period))))))) (defn weighted-moving-average "Reference: - -weighted-moving-average/ Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (let [divisor (/ (* period (inc period)) 2)] (derived tl sources (fn weighted-moving-average- [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val})] (/ (reduce-kv (fn [acc idx v] (+ acc (* (inc idx) v))) 0 t) divisor)))))) (defn exponential-moving-average "Reference: - -exponential-moving-average/ Sources: - `src` Opts: - `period` - `multiplier` defaults to (/ 2 (inc period))." [tl {:keys [src] :as sources} {:keys [multiplier period]}] (let [multiplier (or multiplier (/ 2 (inc period)))] (derived tl sources (fn exponential-moving-average- [ema {:keys [src]} k] (bc/when-let [prev-k (ts/shift src k -1 {:vf key}) :let [prev-ema (get ema prev-k)] curr (get src k)] (if prev-ema (+ (* curr multiplier) (* prev-ema (- 1 multiplier))) (ts/moving-average src prev-k period))))))) (defn double-exponential-moving-average "Reference: - -double-exponential-moving-average-ema/ Sources: - `src` Opts: - `period` sent to internal exponential moving averages - `multiplier` sent to internal exponential moving averages - `ema1-opts` if specified, will be used instead of top level `opts` for ema1 - `ema2-opts` if specified, will be used instead of top level `opts` for ema2" [tl {:keys [src] :as sources} {:keys [ema1-opts ema2-opts period] :as opts}] (let [ema1 (exponential-moving-average tl sources (or ema1-opts opts)) ema2 (exponential-moving-average tl {:src ema1} (or ema2-opts opts))] (map-some tl (fn [ema1 ema2] (- (* 2 ema1) ema2)) ema1 ema2))) (defn triple-exponential-moving-average "Reference: - -triple-ema/ Sources: - `src` Opts: - `period` sent to internal exponential moving averages - `multiplier` sent to internal exponential moving averages - `ema1-opts` if specified, will be used instead of top level `opts` for ema1 - `ema2-opts` if specified, will be used instead of top level `opts` for ema2 - `ema3-opts` if specified, will be used instead of top level `opts` for ema3" [tl {:keys [src] :as sources} {:keys [period ema1-opts ema2-opts ema3-opts] :as opts}] (let [ema1 (exponential-moving-average tl sources (or ema1-opts opts)) ema2 (exponential-moving-average tl {:src ema1} (or ema2-opts opts)) ema3 (exponential-moving-average tl {:src ema2} (or ema3-opts opts))] (map-some tl (fn [ema1 ema2 ema3] (+ (* 3 ema1) (- (* 3 ema2)) ema3)) ema1 ema2 ema3))) (defn relative-moving-average "Relative (WildeR's) moving average, is an Exponential moving average using 1/period as multiplier. Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (exponential-moving-average tl sources {:period period :multiplier (/ period)})) (defn smoothed-moving-average "Reference: - Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (derived tl sources (fn relative-moving-average- [curr {:keys [src]} k] (bc/when-let [c (get src k)] (let [prev-k (ts/shift src k -1 {:vf key}) prev (get curr prev-k)] (if-not prev (ts/moving-average src k period) (/ (+ (* prev (dec period)) c) period))))))) (defn hull-moving-average "Reference: - -hull-moving-average/ Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (let [base-wma (weighted-moving-average tl sources opts) n2-wma (weighted-moving-average tl sources {:period (int (math-nt/floor (double (/ period 2))))}) comb (map-some tl (fn [b n2] (- (* n2 2) b)) base-wma n2-wma)] (weighted-moving-average tl {:src comb} {:period (int (math-nt/floor (math-nt/sqrt period)))}))) (defn volume-weighted-moving-average "Calculates volume-weighted-moving-average where given price and volume are timeseries nodes. Reference: - -weighted-moving-average-vwma/ Sources: - `price` - `volume` Opts: - `period`" [tl {:keys [src volume] :as sources} {:keys [period]}] (derived tl sources (fn volume-weighted-moving-average- [_ {:keys [src volume]} k] (bc/when-let [volume-tail (ts/tail volume period {:endk k :vf val}) src-tail (ts/tail src period {:endk k :vf val})] (/ (->> (map * volume-tail src-tail) (reduce + 0)) (reduce + 0 volume-tail)))))) (defn moving-average-convergence-divergence-line "MACD base line. ma(src, fast-opts) - ma(src, slow-opts). Sources: - `src` Opts: - `fast-avg-indicator` defaults to [[exponential-moving-average]] - `fast-sources` if specified, overrides top level `sources` passed to `fast-avg-indicator` - `fast-opts` passed to `fast-avg-indicator` - `slow-avg-indicator` defaults to [[exponential-moving-average]] - `slow-sources` if specified, overrides top level `sources` passed to `slow-avg-indicator` - `slow-opts` passed to `slow-avg-indicator`" [tl {:keys [src] :as sources} {:keys [fast-avg-indicator fast-sources fast-opts slow-avg-indicator slow-sources slow-opts] :or {fast-avg-indicator simple-moving-average slow-avg-indicator simple-moving-average}}] (map-some tl - (fast-avg-indicator tl (or fast-sources sources) fast-opts) (slow-avg-indicator tl (or slow-sources sources) slow-opts))) (defn moving-average-convergence-divergence "Returns tuple of indicators [macd-line signal histogram]. macd-line = macd-line(src, opts) See [[macd-line]] signal = signal-avg-indicator(macd, signal-opts) hist = macd - signal Reference: - -macd-moving-average-convergence-divergence/ Sources will be passed to [[moving-average-convergence-divergence-line]], if using defaults: - `src` Opts are those accepted by [[moving-average-convergence-divergence-line]], plus: - `signal-avg-indicator` defaults to [[exponential-moving-average]], must accept source as `:src` key - `signal-opts`" [tl {:keys [src] :as sources} {:keys [signal-avg-indicator signal-opts] :or {signal-avg-indicator exponential-moving-average} :as opts}] (let [macd (moving-average-convergence-divergence-line tl sources opts) signal (signal-avg-indicator tl {:src macd} signal-opts) hist (map-some tl - macd signal)] [macd signal hist])) (defn percentage-price-oscillator-line "percentage-price-oscillator base line, values between -1 and 1. Sources: - `src` Opts: - `fast-avg-indicator` defaults to [[exponential-moving-average]] - `fast-sources` if specified, overrides top level `sources` passed to `fast-avg-indicatorº` - `fast-opts` passed to `fast-avg-indicator` - `slow-avg-indicator` defaults to [[exponential-moving-average]] - `slow-opts` passed to `slow-avg-indicator`" [tl {:keys [src] :as sources} {:keys [fast-avg-indicator fast-sources fast-opts slow-avg-indicator slow-sources slow-opts] :or {fast-avg-indicator exponential-moving-average slow-avg-indicator exponential-moving-average}}] (map-some tl (fn [ma1 ma2] (/ (- ma1 ma2) ma2)) (fast-avg-indicator tl (or fast-sources sources) fast-opts) (slow-avg-indicator tl (or slow-sources sources) slow-opts))) (defn percentage-price-oscillator "returns tuple of indicators [ppo-line signal histogram], ppo-line vals between -100 and 100. Similar to [[moving-average-convergence-divergence]], but returns percentage instead of absolute price changes. Reference: - Sources: - `src` Opts are those accepted by [[ppo-line]], plus: - `signal-avg-indicator` defaults to [[exponential-moving-average]], must accept a source on `:src` key - `signal-opts` passed to `signal-avg-indicator`" [tl {:keys [src] :as sources} {:keys [signal-avg-indicator signal-opts] :or {signal-avg-indicator exponential-moving-average} :as opts}] (let [ppo (percentage-price-oscillator-line tl sources opts) signal (signal-avg-indicator tl {:src ppo} signal-opts) hist (map-some tl - ppo signal)] [ppo signal hist])) (defn mean-deviation "deviation of prices from a moving average. Sources: - `src` Opts: - `avg-indicator` defaults to [[simple-moving-average]], must accept a source under `:src` key - `period` - `avg-opts` overrides top level `opts` for `avg-indicator` if specified " [tl {:keys [src] :as sources} {:keys [period avg-indicator avg-opts] :or {avg-indicator simple-moving-average} :as opts}] (derived tl (merge sources {:ma (avg-indicator tl sources (or avg-opts opts))}) (fn mean-deviation- [_ {:keys [src ma]} k] (bc/when-let [curr-ma (get ma k) tail (ts/tail src period {:endk k :vf val})] (/ (reduce (fn [acc curr] (+ acc (abs (- curr curr-ma)))) 0 tail) period))))) (defn standard-deviation "standard deviation of prices during period Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (derived tl sources (fn standard-deviation- [_ {:keys [src]} k] (when-let [tail (ts/tail src period {:endk k :vf val})] (umath/standard-deviation tail))))) (defn parabolic-stop-and-reverse "Reference: - -to-parabolic-sar/ Reference impl: - -core/src/main/java/org/ta4j/core/indicators/ParabolicSarIndicator.java Sources: - `close` - `high` - `low` Opts: - `start` - `increment` - `max-value` Values are maps of: - `ct` current-trend (true if uptrend, false if downtrend) - `sar` sar val - `af` acceleration factor - `ep` extreme point" [tl {:keys [close high low] :as sources} {:keys [start increment max-value]}] (derived tl sources (fn parabolic-stop-and-reverse*- [sar {:keys [close high low]} k] (let [[prev-k prev-c] (ts/shift close k -1) prev-sar (get sar prev-k) curr-c (get close k) curr-h (get high k) curr-l (get low k)] (cond (and prev-sar curr-h curr-l) (let [{:keys [ct ep af sar]} prev-sar] (if ct ;; uptrend (let [curr-ep (max ep curr-h) curr-af (if (> curr-ep ep) (min (+ af increment)) af) new-sar (+ sar (* curr-af (- curr-ep sar))) uptrend (<= new-sar curr-l)] (if (not uptrend) {:ct false :sar ep :af start :ep curr-l} {:ct true :sar new-sar :ep curr-ep :af curr-af})) ;; downtrend (let [curr-ep (min ep curr-l) curr-af (if (< curr-ep ep) (min max-value (+ af increment)) af) new-sar (- sar (* curr-af (- sar curr-ep))) downtrend (>= new-sar curr-h)] (if (not downtrend) {:ct true :sar ep :af start :ep curr-h} {:ct false :sar new-sar :ep curr-ep :af curr-af})))) (and (not prev-sar) prev-c curr-c curr-l curr-h) (let [ct (> curr-c prev-c) sar (if ct curr-l curr-h)] {:ct ct :sar sar :af start :ep sar}) :else nil))))) (defn stochastic-kline "non-smoothed k-line component of [[stochastic-oscillator]], between 0 and 1. Sources: - `close` - `high` - `low` Opts: - `period`" [tl {:keys [close high low] :as sources} {:keys [period]}] (derived tl sources (fn stochastic-kline- [_ {:keys [close high low]} k] (bc/when-let [tail-h (ts/tail high period {:endk k :vf val}) tail-l (ts/tail low period {:endk k :vf val}) curr-c (get close k) lowest (reduce min tail-l) highest (reduce max tail-h)] (/ (- curr-c lowest) (- highest lowest)))))) (defn stochastic-oscillator "returns tuple of nodes [k-line d-line] of stochastic oscillator, with vals between 0 and 1. Reference: - -stochastic-stoch/ Sources: - `close` - `high` - `low` Opts: - `k-line-opts` opts passed to [[stochastic-kline]] - `avg-k-indicator` defaults to [[simple-moving-average]], must accept source as `:src` - `avg-k-opts` passed to `avg-k-indicator` - `avg-d-indicator` defaults to [[simple-moving-average]], must accept source as `:src` - `avg-d-opts` passed to `avg-d-indicator`" [tl {:keys [close high low] :as sources} {:keys [k-line-opts avg-k-indicator avg-k-opts avg-d-indicator avg-d-opts] :or {avg-k-indicator simple-moving-average avg-d-indicator simple-moving-average}}] (let [k-line-base (stochastic-kline tl sources k-line-opts) k-line (avg-k-indicator tl {:src k-line-base} avg-k-opts) d-line (avg-d-indicator tl {:src k-line} avg-d-opts)] [k-line d-line])) (defn relative-strength-g-l "returns tuple of nodes [gains losses], part of [[relative-strength-index]]. gains: if (pos? x - (x-1)) then x else 0 losses: if (neg? x - (x-1)) then -x else 0 Sources: - `src`" [tl {:keys [src] :as sources}] [(map-some tl (fn [x] (if (pos? x) x 0)) (momentum tl sources)) (map-some tl (fn [x] (if (neg? x) (abs x) 0)) (momentum tl sources))]) (defn relative-strength-index "Values between 0 and 1. Reference: - -relative-strength-index-rsi/ Sources - `src` Opts: - `avg-indicator` used to average both [[relative-strength-g-l]]. Defaults to [[relative-moving-average]], must accept source as `:src` - `avg-opts` if specified, overrides top level opts passed to `avg-indicator`" [tl {:keys [src] :as sources} {:keys [avg-indicator avg-opts] :or {avg-indicator relative-moving-average} :as opts}] (let [[g l] (relative-strength-g-l tl sources)] (map-some tl (fn [g l] (cond (zero? l) 1 (zero? g) 0 :else (/ g (+ g l)))) (avg-indicator tl {:src g} (or avg-opts opts)) (avg-indicator tl {:src l} (or avg-opts opts))))) (defn commodity-channel-index "Reference: - -help/x-study/technical-indicator-definitions/commodity-channel-index-cci/ Sources: - `src` can be any number series, although the original formula specifies typical price to be [[hlc3]]. Opts: - `avg-indicator` defaults to [[simple-moving-average]], must accept src as `:src` - `avg-opts` if specified, overrides top level `opts` on `avg-indicator` - `mean-dev-opts` if specified, overrides top level `opts` on internal [[mean-deviation]] - `constant-factor` double. defaults to 0.015" [tl {:keys [src] :as sources} {:keys [avg-indicator avg-opts mean-dev-opts period constant-factor] :or {avg-indicator simple-moving-average constant-factor 0.015} :as opts}] (derived tl {:src src :ma (avg-indicator tl sources (or avg-opts opts)) :mean-dev (mean-deviation tl sources (or mean-dev-opts opts))} (fn commodity-channel-index- [curr {:keys [mean-dev ma src]} k] (bc/when-let [price (get src k) ma (get ma k) mean-dev (get mean-dev k) cci-val (if-not (zero? mean-dev) (/ (- price ma) (* mean-dev constant-factor)) Double/NaN)] (if (Double/isNaN cci-val) (get curr (ts/shift src k -1 {:vf key})) cci-val))))) (defn relative-volatility-u-s "Returns nodes tuple [u s] of [[relative-volatility-index]] u and s components. Similar to [[relative-strength-g-l]], but use standard-deviation of price-change instead of absolute price change. Sources: - `src` Opts are those of [[standard-deviation]] Reference: - (RVIOrig)" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (let [std (standard-deviation tl sources opts) vch (momentum tl sources) u (map-some tl (fn [vch std] (if (not (neg? vch)) std 0)) vch std) s (map-some tl (fn [vch std] (if (neg? vch) std 0)) vch std)] [u s])) (defn relative-volatility-index "Values from 0 to 1. Reference: - (RVIOrig) Sources: - `src` Opts: - `avg-indicator` defaults to [[exponential-moving-average]], must accept source as `:src` - `stdev-opts` if specified, overrides top level `opts` passed to [[relative-volatility-u-s]] - `avg-opts` if specified, overrides top level `opts` passed to `avg-indicator`" [tl {:keys [src] :as sources} {:keys [avg-indicator avg-opts stdev-opts period] :or {avg-indicator exponential-moving-average} :as opts}] (let [[u s] (relative-volatility-u-s tl sources (or stdev-opts opts))] (map-some tl (fn [u s] (/ u (+ s u))) (avg-indicator tl {:src u} (or avg-opts opts)) (avg-indicator tl {:src s} (or avg-opts opts))))) (defn refined-relative-volatility-index "(rvi(high) + rvi(low) / 2), with values between 0 and 1. Reference: - (RVI) Sources: - `high` - `low` Opts are those accepted by [[relative-volatility-index]]" ([tl {:keys [high low] :as sources} {:keys [avg-indicator avg-opts stdev-opts period] :as opts}] (mean tl (relative-volatility-index tl {:src high} opts) (relative-volatility-index tl {:src low} opts)))) (defn base-range "high - low Sources: - `high` - `low`" [tl {:keys [high low]}] (map-some tl - high low)) (defn true-range "Reference: - (TR) Sources: - `close` - `high` - `low`" [tl {:keys [close high low] :as sources}] (derived tl sources (fn true-range- [_ {:keys [close high low]} k] (bc/when-let [curr-h (get high k) curr-l (get low k) prev-c (ts/shift close k -1 {:vf val}) hl-dif (- curr-h curr-l) hc (abs (- curr-h prev-c)) lc (abs (- curr-l prev-c))] (max hl-dif hc lc))))) (defn average-base-range "moving average of [[base-range]]. Sources: - `high` - `low` Opts: - `avg-indicator` defaults to [[relative-moving-average]], must accept source as `:src` - `period` passed to `avg-indicator` as :period" [tl {:keys [high low] :as sources} {:keys [avg-indicator period] :or {avg-indicator relative-moving-average}}] (avg-indicator tl {:src (base-range tl sources)} {:period period})) (defn average-true-range "moving average of [[true-range]]. Reference: - (ATR) Sources: - `close` - `high` - `low` Opts: - `avg-indicator` defaults to [[relative-moving-average]], must accept source as `:src` - `period` passed to `avg-indicator` as :period" [tl {:keys [close high low] :as sources} {:keys [avg-indicator period] :or {avg-indicator relative-moving-average}}] (avg-indicator tl {:src (true-range tl sources)} {:period period})) (defn bollinger-bands "Returns tuple of nodes [upper middle lower] for bollinger bands. Reference: - Sources: - `src` Opts: - `avg-indicator` for middle band. Defaults to [[simple-moving-average]], must accept source as `:src` - `avg-opts` if specified, overrides top level `opts` for `avg-indicator` - `stdev-opts` if specified, overrides top level `opts` for [[standard-deviation]] " [tl {:keys [src] :as sources} {:keys [avg-indicator period avg-opts stdev-opts multiplier] :or {avg-indicator simple-moving-average} :as opts}] (let [middle (avg-indicator tl sources (or avg-opts opts)) offset (standard-deviation tl sources (or stdev-opts opts)) upper (map-some tl (fn [m off] (+ m (* multiplier off))) middle offset) lower (map-some tl (fn [m off] (- m (* multiplier off))) middle offset)] [upper middle lower])) (defn keltner-channels "Returns tuple of nodes [upper middle lower] Reference: - -keltner-channels-kc/ Sources: - `close` (atr) - `high` (atr) - `low` (atr) - `src` (middle band) Opts: - `avg-indicator` for middle band. Defaults to [[exponential-moving-average]], will be passed top level sources. - `avg-opts` if specified, overrides top level `opts` for `avg-indicator` - `range-indicator` for use as range indicator. Defaults to [[average-true-range]]. Will be passed top level `sources` unchanged. - `range-opts` if specified, overrides top level `opts` for range indicator. - `multiplier`" [tl {:keys [close high low src] :as sources} {:keys [avg-indicator avg-opts range-indicator range-opts multiplier] :or {avg-indicator exponential-moving-average range-indicator average-true-range} :as opts}] (let [middle (avg-indicator tl sources (or avg-opts opts)) rng (range-indicator tl sources (or range-opts opts)) upper (map-some tl (fn [m rng] (+ m (* multiplier rng))) middle rng) lower (map-some tl (fn [m rng] (- m (* multiplier rng))) middle rng)] [upper middle lower])) (defn average-directional-index "Returns tuple of [adx di+ di-] nodes, where adx is between 0 and 1. Reference: - -average-directional-index-adx-calculated-and-what-formula.asp Sources: - `close` - `high` - `low` Opts: - `range-indicator` range indicator to use, will be called with top level `sources`. Defaults to [[average-true-range]] - `range-opts` if specified, overrides top level `opts` passed to range indicator. - `line-avg-indicator` defaults to [[exponential-moving-average]] - `line-avg-opts` if specified, overrides top level opts passed to `line-avg-indicator` - `adx-avg-indicator` defaults to [[exponential-moving-average]] - `adx-avg-opts` if specified, overrides top level `opts` on `adx-avg-indicator`" [tl {:keys [close high low] :as sources} {:keys [adx-avg-indicator adx-avg-opts range-indicator range-opts line-avg-indicator line-avg-opts] :or {adx-avg-indicator exponential-moving-average range-indicator average-true-range line-avg-indicator exponential-moving-average} :as opts}] (let [high-ch (momentum tl {:src high}) low-ch (momentum tl {:src low}) rng (range-indicator tl sources (or range-opts opts)) base-di (fn [x1 x2] (map-some tl (fn [x1 x2 rng] (/ (if (and (> x1 x2) (> x1 0)) x1 0) rng)) x1 x2 rng)) +di (line-avg-indicator tl {:src (base-di high-ch low-ch)} (or line-avg-opts opts)) -di (line-avg-indicator tl {:src (base-di low-ch high-ch)} (or line-avg-opts opts)) adx (map-some tl (fn [p n] (abs (/ (- p n) (+ p n)))) +di -di) adx (adx-avg-indicator tl {:src adx} (or adx-avg-opts opts))] [adx +di -di])) (defn on-balance-volume "Reference: - Sources: - `src` - `volume`" [tl {:keys [src volume] :as sources}] (derived tl sources (fn on-balance-volume- [obv {:keys [src volume]} k] (bc/when-let [[prev-k prev-c] (ts/shift src k -1) :let [prev-obv (get obv prev-k)] curr-c (get src k) curr-v (get volume k)] (cond (not prev-obv) 0 (> curr-c prev-c) (+ prev-obv curr-v) (< curr-c prev-c) (- prev-obv curr-v) (= curr-c prev-c) prev-obv))))) (defn accumulation-distribution-line "Returns tuple of [adl money-flow-multiplier money-flow-volume] indicators. Reference: - -accumulation-distribution-adl/ Sources: - `close` - `high` - `low` - `volume`" [tl {:keys [close high low volume] :as sources}] (let [mfm (derived tl sources (fn [curr {:keys [close high low]} k] (bc/when-let [h (get high k) c (get close k) l (get low k)] (if (= h l) (get curr (ts/shift close k -1 {:vf key})) (/ (- (- c l) (- h c)) (- h l)))))) mfv (map-some tl * mfm volume) adl (derived tl {:mfv mfv} (fn [v {:keys [mfv]} k] (when-let [curr-mfv (get mfv k)] (if-let [prev (get v (ts/shift mfv k -1 {:vf key}))] (+ prev curr-mfv) curr-mfv))))] [adl mfm mfv])) (defn highest-val "Returns highest value of latest period items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val})] (second (ts/select t >=)))))) (defn lowest-val "Returns lowest value of latest period items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val})] (second (ts/select t <=)))))) (defn since-highest-val "Returns number of items since highest value on latest `period` items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val}) [sidx _] (ts/select t >=)] (- period (inc sidx)))))) (defn since-lowest-val "Returns number of items since lowest value on latest `period` items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val}) [sidx _] (ts/select t <=)] (- period (inc sidx)))))) (defn aroon-oscillator "Returns tuple of nodes [aroon-oscillator aroon-up aroon-down], vals between 0 and 1 Reference: - Sources: - `high` - `low` Opts: - `period`" [tl {:keys [high low]} {:keys [period] :as opts}] (let [aup (map-some tl (fn [x] (/ (- period x) period)) (since-highest-val tl {:src high} opts)) adown (map-some tl (fn [x] (/ (- period x) period)) (since-lowest-val tl {:src low} opts)) aroon (map-some tl - aup adown)] [aroon aup adown])) (defn chandelier-exits "Returns tuple of chandelier exits nodes [long short] Reference: - :chandelier_exit Sources: - `close` - `high` - `low` Opts: - `range-indicator` Defaults to [[average-true-range]], will be passed top level `sources`. - `range-opts` if specified, overrides top level `opts` passed to `range-indicator` - `highest-opts` if specified, overrides top level `opts` passed to [[highest-val]] - `lowest-opts` if specified, overrides top level `opts` passed to [[lowest-val]] - `multiplier`" [tl {:keys [close high low] :as sources} {:keys [range-indicator range-opts highest-opts lowest-opts multiplier] :or {range-indicator average-true-range} :as opts}] (let [highest (highest-val tl {:src high} (or highest-opts opts)) lowest (lowest-val tl {:src low} (or lowest-opts opts)) rng (range-indicator tl sources (or range-opts opts)) long (map-some tl (fn [h atr] (- h (* multiplier atr))) highest rng) short (map-some tl (fn [l atr] (+ l (* multiplier atr))) lowest rng)] [long short])) (defn donchian-channels "Returns tuple of [mid high low] nodes Sources: - `high` - `low` Opts: - `highest-opts` if specified, overrides top level `opts` on [[highest-val]] - `lowest-opts` if specified, overrides top level `opts` on [[lowest-val]] Reference: - " [tl {:keys [high low]} {:keys [highest-opts lowest-opts] :as opts}] (let [highest (highest-val tl {:src high} (or highest-opts opts)) lowest (lowest-val tl {:src low} (or lowest-opts opts)) mid (mean tl highest lowest)] [mid highest lowest])) (defn supertrend "Reference impl: - -ta/blob/main/pandas_ta/overlap/supertrend.py Sources: - `close` - `high` - `low` Opts: - `range-indicator` defaults to [[average-true-range]], will be passed top level `sources` - `range-opts` if specified, overrides top level `opts` for `range-indicator` - `multiplier` Values are map of: - `trend` e/o #{:long :short} - `value` number - `_upper` - `_lower`" [tl {:keys [close high low] :as sources} {:keys [multiplier range-indicator range-opts] :or {range-indicator average-true-range} :as opts}] (let [rng (range-indicator tl sources (or range-opts opts)) hl2' (hl2 tl sources) basic-upper (map-some tl (fn [hlm rng] (+ hlm (* multiplier rng))) hl2' rng) basic-lower (map-some tl (fn [hlm rng] (- hlm (* multiplier rng))) hl2' rng)] (derived tl {:close close :upper basic-upper :lower basic-lower} (fn [st {:keys [close upper lower]} k] (bc/when-let [prev-k (ts/shift close k -1 {:vf key}) :let [prev-st (get st prev-k)] curr-c (get close k) curr-up (get upper k) curr-lo (get lower k)] (cond (and prev-st (> curr-c (:_upper prev-st))) {:trend :long :value curr-lo :_upper curr-up :_lower curr-lo} (and prev-st (< curr-c (:_lower prev-st))) {:trend :short :value curr-up :_upper curr-up :_lower curr-lo} :else (let [trend (or (:trend prev-st) :long) lower (if (and (= :long trend) prev-st (< curr-lo (:_lower prev-st))) (:_lower prev-st) curr-lo) upper (if (and (= :short trend) prev-st (> curr-up (:_upper prev-st))) (:_upper prev-st) curr-up)] {:trend trend :_upper upper :_lower lower :value (case trend :long lower :short upper)}))))))) (defn kaufman-efficiency-ratio "Reference: - :kaufman_s_adaptive_moving_average (ER) Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl {:mom (momentum tl sources)} (fn kaufman-efficiency-ratio- [_ {:keys [mom]} k] (bc/when-let [ch (some-> (get mom k) abs) ch-tail (ts/tail mom period {:endk k :vf val})] (/ ch (reduce (fn [a n] (+ a (abs n))) 0 ch-tail)))))) (defn kaufman-adaptive-moving-average "Reference: - :kaufman_s_adaptive_moving_average (KAMA) Sources: - `src` Opts: - `er-period` period to use on [[kaufman-efficiency-ratio]] - `slow-period` - `fast-period`" [tl {:keys [src] :as sources} {:keys [er-period slow-period fast-period]}] (let [ssc (/ 2 (inc slow-period)) fsc (/ 2 (inc fast-period)) sc (map-some tl (fn [er] (math-nt/expt (+ (* er (- fsc ssc)) ssc) 2)) (kaufman-efficiency-ratio tl sources {:period er-period}))] (derived tl {:src src :sc sc} (fn [kama {:keys [src sc]} k] (bc/when-let [curr-p (get src k) curr-sc (get sc k) :let [prev-kama (get kama (ts/shift src k -1 {:vf key}))]] (if prev-kama (+ prev-kama (* curr-sc (- curr-p prev-kama))) (ts/moving-average src k er-period)))))))
null
https://raw.githubusercontent.com/bortexz/tacos/5e3bdc828b54bb992bd48d21064e318ba3848404/src/bortexz/tacos.clj
clojure
uptrend downtrend
(ns bortexz.tacos (:require [clojure.math.numeric-tower :as math-nt] [bortexz.utils.math :as umath] [bortexz.graphcom :as g] [better-cond.core :as bc] [bortexz.tacos.timeseries :as ts])) (defn derived "Creates a new derived timeseries node (a.k.a indicator) given the following args: - `tl` A graphcom node whose emitted value implements [[tacos.timeseires/Timeline]]. - `sources` Map of dependency nodes. Timeline node will be merged into sources under `::timeline` keyword automatically. - `compute-ts` 3-arity fn that will be called with args [current-value sources-values timestamp], and must return the value of this timeseries at `timestamp`. Note that timestamp can be any type that can be compared with `compare`. You could use integers (e.g epoch milliseconds), java.time instants, ISO strings, etc Returns node that will emit a derived timeseries as value." [tl sources compute-ts] (g/compute-node (merge sources {::timeline tl}) (fn derived-handler- [current-value {::keys [timeline] :as sources}] (ts/-apply-timeline timeline current-value (fn [v ts] (compute-ts v sources ts)))))) (defn delta-source "Sources: - `input` input node that contain partial timeseries of new items to introduce into the graph. Opts: - `max-size` the maximum size used for [[tacos.timeseries/delta-timeline]]. Returns tuple of nodes [delta-tl src] that can be used to introduce new values into a graph of derived timeseries: - `delta-tl` is a node that emits [[tacos.timeseries/delta-timeline]] using `max-size` and the timestamps of timeseries in `input`. - `src` is a timeseries node that accumulates new values from `input`, up to a maximum of `max-size`, presumably to be used as the source for other derived timeseries." [{:keys [input] :as sources} {:keys [max-size] :as opts}] (let [tl (g/compute-node sources (fn delta-entrypoint-tl- [_ {:keys [input]}] (ts/delta-timeline (keys input) max-size))) src (derived tl sources (fn [_ {:keys [input]} k] (get input k)))] [tl src])) (defn map-some "Returns node that applies f to each timestamp value of each node, when current timestamp values for all nodes are non-nil. e.g: - sum each timestamp's val of different timeseries `(map-some tl + x y z)` - mean of x,y,z nodes `(map-some tl (fn [& xs] (/ (reduce + 0 xs) (count xs))) x y z)`" ([tl f n1] (derived tl {:n1 n1} (fn map-some-1 [_ {:keys [n1]} k] (bc/when-some [v1 (get n1 k)] (f v1))))) ([tl f n1 n2] (derived tl {:n1 n1 :n2 n2} (fn map-some-2 [_ {:keys [n1 n2]} k] (bc/when-some [v1 (get n1 k) v2 (get n2 k)] (f v1 v2))))) ([tl f n1 n2 n3] (derived tl {:n1 n1 :n2 n2 :n3 n3} (fn map-some-3 [_ {:keys [n1 n2 n3]} k] (bc/when-some [v1 (get n1 k) v2 (get n2 k) v3 (get n3 k)] (f v1 v2 v3))))) ([tl f n1 n2 n3 n4] (derived tl {:n1 n1 :n2 n2 :n3 n3 :n4 n4} (fn map-some-3 [_ {:keys [n1 n2 n3 n4]} k] (bc/when-some [v1 (get n1 k) v2 (get n2 k) v3 (get n3 k) v4 (get n4 k)] (f v1 v2 v3 v4))))) ([tl f n1 n2 n3 n4 & nodes] (let [xm (zipmap (range) (into [n1 n2 n3 n4] nodes)) ks (vec (range (count xm)))] (derived tl xm (fn map-some-n [_ xm k] (bc/when-let [xs (some-> (reduce (fn [acc idx] (if-let [tsv (get (get xm idx) k)] (conj! acc tsv) (reduced nil))) (transient []) ks) (persistent!))] (apply f xs))))))) (defn sources-map "Returns timeseries node whose values combine current timestamp for all sources in a hash map, under same keyword as specified in `sources`, when all have a value. E.g candles (sources-map tl {:high high :low low :close close :open open}) will have values as map of `{:open ,,, :close ,,, :high ,,, :low ,,,}`. Useful to combine multiple indicators that share the same timeline into one to use it as a single timeseries." [tl sources] (let [ks (keys sources)] (derived tl sources (fn [_ srcs ts] (some-> (reduce (fn [acc k] (if-let [v (get (get srcs k) ts)] (assoc! acc k v) (reduced nil))) (transient {}) ks) (persistent!)))))) (defn spread-map "Given a timeseries node `map-source` that has maps as values and map of opts, returns a map of new nodes with keys `ks` where values are new nodes that each one contains the values of key in map-src, possibly transformed. Sources: - `map-source` Opts: - `ks` set of keys to extract as indicators - `transform` function to transform each of the values, if needed. Defaults to identity. E.g (spread-map tl candles-node [:open :close :high :low]) returns a map of nodes #{:open :close :high :low} each one with the corresponding candle value." [tl map-source {:keys [ks transform] :or {transform identity}}] (zipmap ks (map #(map-some tl (comp transform %) map-source) ks))) (defn momentum "src(i) - src(i-period) Sources: - `src` Opts: - `period` Defaults to 1." ([tl sources] (momentum tl sources {})) ([tl {:keys [src] :as sources} {:keys [period] :or {period 1}}] (derived tl sources (fn momentum- [_ {:keys [src]} k] (bc/when-let [curr (get src k) prev (ts/shift src k (- period) {:vf val})] (- curr prev)))))) (defn rate-of-change "(src - src(i-period)) / src(i-period), vals between -1 and 1, except the case when src(i-period) is zero, then returns opt `nan-val` Sources: - `src` Opts: - `period` Defaults to 1. - `nan-val` defaults to Double/NaN" ([tl sources] (rate-of-change tl sources {})) ([tl {:keys [src] :as sources} {:keys [period nan-val] :or {period 1 nan-val Double/NaN}}] (derived tl sources (fn rate-of-change- [_ {:keys [src]} k] (bc/when-let [curr (get src k) prev (ts/shift src k (- period) {:vf val})] (if (zero? prev) nan-val (/ (- curr prev) prev))))))) (defn envelope "Returns tuple of nodes [upper lower], where: pos = src + (src * multiplier) neg = src - (src * multiplier) Sources: - `src Opts: - `multiplier` percentage number. e.g. 0.01 will create a 1% envelope around `src`." [tl {:keys [src]} {:keys [multiplier]}] (let [upper (map-some tl (fn [x] (+ x (* x multiplier))) src) lower (map-some tl (fn [x] (- x (* x multiplier))) src)] [upper lower])) (defn mean "Returns node that computes the mean of all nodes specified. e.g ohlc4 = (mean tl open close high low) where open,close,high,low are indicators of each candle value." [tl & srcv] (apply map-some tl (fn [& xs] (umath/mean xs)) srcv)) (defn hl2 "(high + low)/2 Sources: - `high` - `low`" [tl {:keys [high low]}] (mean tl high low)) (defn hlc3 "(high+low+close)/3 Sources: - `high` - `low` - `close`" [tl {:keys [high low close]}] (mean tl high low close)) (defn ohlc4 "(open+high+low+close)/4 Sources: - `open` - `high` - `low` - `close`" [tl {:keys [open high low close]}] (mean tl open high low close)) (defn heikin-ashi "Returns node that calculates Heikin ashi candles whose values are maps of keys #{:open :close :high :low} Sources: - `open` - `close` - `high` - `low` Reference: - -ashi-better-candlestick/" [tl {:keys [open close high low] :as sources}] (derived tl sources (fn heikin-ashi- [ha {:keys [open close high low]} k] (let [[o c h l :as ohlc] (mapv #(get % k) [open close high low])] (when (every? some? ohlc) (let [prev-k (ts/shift close k -1 {:vf key}) prev-ha (get ha prev-k) ha-close (umath/mean ohlc) ha-open (if prev-ha (/ (+ (:open prev-ha) (:close prev-ha)) 2) (/ (+ o c) 2))] {:open ha-open :close ha-close :high (max ha-open ha-close h) :low (min ha-open ha-close l)})))))) (defn simple-moving-average "Reference: - -moving-average/ Sources: - `src` Opts: - `period` Notes: - Assumes that only latest time points are added (either new later timestamp, or replacement of current latest). This should be the case most of the time. For earlier than latest arriving time points, you need to recompute all from earlier time point to latest for correct results, by specifying them on the timeline. - Keeps an internal summatory to work on log-n (n=size of timeseries) instead of reducing tail all the time." [tl {:keys [src] :as sources} {:keys [period]}] (let [acc (derived tl sources (fn [x {:keys [src]} k] (let [to-remove (ts/shift src k (- period) {:vf val}) to-add (get src k) prev-k (ts/shift src k -1 {:vf key}) prev (when prev-k (get x prev-k)) {:keys [sum]} (or prev {:sum 0 :ready? false})] {:sum (when to-add (+ (or sum 0) to-add (if to-remove (- to-remove) 0))) :ready? (some? to-remove)})))] (derived tl {:acc acc} (fn [_ {:keys [acc]} k] (let [{:keys [sum ready?]} (get acc k)] (when ready? (/ sum period))))))) (defn weighted-moving-average "Reference: - -weighted-moving-average/ Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (let [divisor (/ (* period (inc period)) 2)] (derived tl sources (fn weighted-moving-average- [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val})] (/ (reduce-kv (fn [acc idx v] (+ acc (* (inc idx) v))) 0 t) divisor)))))) (defn exponential-moving-average "Reference: - -exponential-moving-average/ Sources: - `src` Opts: - `period` - `multiplier` defaults to (/ 2 (inc period))." [tl {:keys [src] :as sources} {:keys [multiplier period]}] (let [multiplier (or multiplier (/ 2 (inc period)))] (derived tl sources (fn exponential-moving-average- [ema {:keys [src]} k] (bc/when-let [prev-k (ts/shift src k -1 {:vf key}) :let [prev-ema (get ema prev-k)] curr (get src k)] (if prev-ema (+ (* curr multiplier) (* prev-ema (- 1 multiplier))) (ts/moving-average src prev-k period))))))) (defn double-exponential-moving-average "Reference: - -double-exponential-moving-average-ema/ Sources: - `src` Opts: - `period` sent to internal exponential moving averages - `multiplier` sent to internal exponential moving averages - `ema1-opts` if specified, will be used instead of top level `opts` for ema1 - `ema2-opts` if specified, will be used instead of top level `opts` for ema2" [tl {:keys [src] :as sources} {:keys [ema1-opts ema2-opts period] :as opts}] (let [ema1 (exponential-moving-average tl sources (or ema1-opts opts)) ema2 (exponential-moving-average tl {:src ema1} (or ema2-opts opts))] (map-some tl (fn [ema1 ema2] (- (* 2 ema1) ema2)) ema1 ema2))) (defn triple-exponential-moving-average "Reference: - -triple-ema/ Sources: - `src` Opts: - `period` sent to internal exponential moving averages - `multiplier` sent to internal exponential moving averages - `ema1-opts` if specified, will be used instead of top level `opts` for ema1 - `ema2-opts` if specified, will be used instead of top level `opts` for ema2 - `ema3-opts` if specified, will be used instead of top level `opts` for ema3" [tl {:keys [src] :as sources} {:keys [period ema1-opts ema2-opts ema3-opts] :as opts}] (let [ema1 (exponential-moving-average tl sources (or ema1-opts opts)) ema2 (exponential-moving-average tl {:src ema1} (or ema2-opts opts)) ema3 (exponential-moving-average tl {:src ema2} (or ema3-opts opts))] (map-some tl (fn [ema1 ema2 ema3] (+ (* 3 ema1) (- (* 3 ema2)) ema3)) ema1 ema2 ema3))) (defn relative-moving-average "Relative (WildeR's) moving average, is an Exponential moving average using 1/period as multiplier. Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (exponential-moving-average tl sources {:period period :multiplier (/ period)})) (defn smoothed-moving-average "Reference: - Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (derived tl sources (fn relative-moving-average- [curr {:keys [src]} k] (bc/when-let [c (get src k)] (let [prev-k (ts/shift src k -1 {:vf key}) prev (get curr prev-k)] (if-not prev (ts/moving-average src k period) (/ (+ (* prev (dec period)) c) period))))))) (defn hull-moving-average "Reference: - -hull-moving-average/ Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (let [base-wma (weighted-moving-average tl sources opts) n2-wma (weighted-moving-average tl sources {:period (int (math-nt/floor (double (/ period 2))))}) comb (map-some tl (fn [b n2] (- (* n2 2) b)) base-wma n2-wma)] (weighted-moving-average tl {:src comb} {:period (int (math-nt/floor (math-nt/sqrt period)))}))) (defn volume-weighted-moving-average "Calculates volume-weighted-moving-average where given price and volume are timeseries nodes. Reference: - -weighted-moving-average-vwma/ Sources: - `price` - `volume` Opts: - `period`" [tl {:keys [src volume] :as sources} {:keys [period]}] (derived tl sources (fn volume-weighted-moving-average- [_ {:keys [src volume]} k] (bc/when-let [volume-tail (ts/tail volume period {:endk k :vf val}) src-tail (ts/tail src period {:endk k :vf val})] (/ (->> (map * volume-tail src-tail) (reduce + 0)) (reduce + 0 volume-tail)))))) (defn moving-average-convergence-divergence-line "MACD base line. ma(src, fast-opts) - ma(src, slow-opts). Sources: - `src` Opts: - `fast-avg-indicator` defaults to [[exponential-moving-average]] - `fast-sources` if specified, overrides top level `sources` passed to `fast-avg-indicator` - `fast-opts` passed to `fast-avg-indicator` - `slow-avg-indicator` defaults to [[exponential-moving-average]] - `slow-sources` if specified, overrides top level `sources` passed to `slow-avg-indicator` - `slow-opts` passed to `slow-avg-indicator`" [tl {:keys [src] :as sources} {:keys [fast-avg-indicator fast-sources fast-opts slow-avg-indicator slow-sources slow-opts] :or {fast-avg-indicator simple-moving-average slow-avg-indicator simple-moving-average}}] (map-some tl - (fast-avg-indicator tl (or fast-sources sources) fast-opts) (slow-avg-indicator tl (or slow-sources sources) slow-opts))) (defn moving-average-convergence-divergence "Returns tuple of indicators [macd-line signal histogram]. macd-line = macd-line(src, opts) See [[macd-line]] signal = signal-avg-indicator(macd, signal-opts) hist = macd - signal Reference: - -macd-moving-average-convergence-divergence/ Sources will be passed to [[moving-average-convergence-divergence-line]], if using defaults: - `src` Opts are those accepted by [[moving-average-convergence-divergence-line]], plus: - `signal-avg-indicator` defaults to [[exponential-moving-average]], must accept source as `:src` key - `signal-opts`" [tl {:keys [src] :as sources} {:keys [signal-avg-indicator signal-opts] :or {signal-avg-indicator exponential-moving-average} :as opts}] (let [macd (moving-average-convergence-divergence-line tl sources opts) signal (signal-avg-indicator tl {:src macd} signal-opts) hist (map-some tl - macd signal)] [macd signal hist])) (defn percentage-price-oscillator-line "percentage-price-oscillator base line, values between -1 and 1. Sources: - `src` Opts: - `fast-avg-indicator` defaults to [[exponential-moving-average]] - `fast-sources` if specified, overrides top level `sources` passed to `fast-avg-indicatorº` - `fast-opts` passed to `fast-avg-indicator` - `slow-avg-indicator` defaults to [[exponential-moving-average]] - `slow-opts` passed to `slow-avg-indicator`" [tl {:keys [src] :as sources} {:keys [fast-avg-indicator fast-sources fast-opts slow-avg-indicator slow-sources slow-opts] :or {fast-avg-indicator exponential-moving-average slow-avg-indicator exponential-moving-average}}] (map-some tl (fn [ma1 ma2] (/ (- ma1 ma2) ma2)) (fast-avg-indicator tl (or fast-sources sources) fast-opts) (slow-avg-indicator tl (or slow-sources sources) slow-opts))) (defn percentage-price-oscillator "returns tuple of indicators [ppo-line signal histogram], ppo-line vals between -100 and 100. Similar to [[moving-average-convergence-divergence]], but returns percentage instead of absolute price changes. Reference: - Sources: - `src` Opts are those accepted by [[ppo-line]], plus: - `signal-avg-indicator` defaults to [[exponential-moving-average]], must accept a source on `:src` key - `signal-opts` passed to `signal-avg-indicator`" [tl {:keys [src] :as sources} {:keys [signal-avg-indicator signal-opts] :or {signal-avg-indicator exponential-moving-average} :as opts}] (let [ppo (percentage-price-oscillator-line tl sources opts) signal (signal-avg-indicator tl {:src ppo} signal-opts) hist (map-some tl - ppo signal)] [ppo signal hist])) (defn mean-deviation "deviation of prices from a moving average. Sources: - `src` Opts: - `avg-indicator` defaults to [[simple-moving-average]], must accept a source under `:src` key - `period` - `avg-opts` overrides top level `opts` for `avg-indicator` if specified " [tl {:keys [src] :as sources} {:keys [period avg-indicator avg-opts] :or {avg-indicator simple-moving-average} :as opts}] (derived tl (merge sources {:ma (avg-indicator tl sources (or avg-opts opts))}) (fn mean-deviation- [_ {:keys [src ma]} k] (bc/when-let [curr-ma (get ma k) tail (ts/tail src period {:endk k :vf val})] (/ (reduce (fn [acc curr] (+ acc (abs (- curr curr-ma)))) 0 tail) period))))) (defn standard-deviation "standard deviation of prices during period Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period]}] (derived tl sources (fn standard-deviation- [_ {:keys [src]} k] (when-let [tail (ts/tail src period {:endk k :vf val})] (umath/standard-deviation tail))))) (defn parabolic-stop-and-reverse "Reference: - -to-parabolic-sar/ Reference impl: - -core/src/main/java/org/ta4j/core/indicators/ParabolicSarIndicator.java Sources: - `close` - `high` - `low` Opts: - `start` - `increment` - `max-value` Values are maps of: - `ct` current-trend (true if uptrend, false if downtrend) - `sar` sar val - `af` acceleration factor - `ep` extreme point" [tl {:keys [close high low] :as sources} {:keys [start increment max-value]}] (derived tl sources (fn parabolic-stop-and-reverse*- [sar {:keys [close high low]} k] (let [[prev-k prev-c] (ts/shift close k -1) prev-sar (get sar prev-k) curr-c (get close k) curr-h (get high k) curr-l (get low k)] (cond (and prev-sar curr-h curr-l) (let [{:keys [ct ep af sar]} prev-sar] (if ct (let [curr-ep (max ep curr-h) curr-af (if (> curr-ep ep) (min (+ af increment)) af) new-sar (+ sar (* curr-af (- curr-ep sar))) uptrend (<= new-sar curr-l)] (if (not uptrend) {:ct false :sar ep :af start :ep curr-l} {:ct true :sar new-sar :ep curr-ep :af curr-af})) (let [curr-ep (min ep curr-l) curr-af (if (< curr-ep ep) (min max-value (+ af increment)) af) new-sar (- sar (* curr-af (- sar curr-ep))) downtrend (>= new-sar curr-h)] (if (not downtrend) {:ct true :sar ep :af start :ep curr-h} {:ct false :sar new-sar :ep curr-ep :af curr-af})))) (and (not prev-sar) prev-c curr-c curr-l curr-h) (let [ct (> curr-c prev-c) sar (if ct curr-l curr-h)] {:ct ct :sar sar :af start :ep sar}) :else nil))))) (defn stochastic-kline "non-smoothed k-line component of [[stochastic-oscillator]], between 0 and 1. Sources: - `close` - `high` - `low` Opts: - `period`" [tl {:keys [close high low] :as sources} {:keys [period]}] (derived tl sources (fn stochastic-kline- [_ {:keys [close high low]} k] (bc/when-let [tail-h (ts/tail high period {:endk k :vf val}) tail-l (ts/tail low period {:endk k :vf val}) curr-c (get close k) lowest (reduce min tail-l) highest (reduce max tail-h)] (/ (- curr-c lowest) (- highest lowest)))))) (defn stochastic-oscillator "returns tuple of nodes [k-line d-line] of stochastic oscillator, with vals between 0 and 1. Reference: - -stochastic-stoch/ Sources: - `close` - `high` - `low` Opts: - `k-line-opts` opts passed to [[stochastic-kline]] - `avg-k-indicator` defaults to [[simple-moving-average]], must accept source as `:src` - `avg-k-opts` passed to `avg-k-indicator` - `avg-d-indicator` defaults to [[simple-moving-average]], must accept source as `:src` - `avg-d-opts` passed to `avg-d-indicator`" [tl {:keys [close high low] :as sources} {:keys [k-line-opts avg-k-indicator avg-k-opts avg-d-indicator avg-d-opts] :or {avg-k-indicator simple-moving-average avg-d-indicator simple-moving-average}}] (let [k-line-base (stochastic-kline tl sources k-line-opts) k-line (avg-k-indicator tl {:src k-line-base} avg-k-opts) d-line (avg-d-indicator tl {:src k-line} avg-d-opts)] [k-line d-line])) (defn relative-strength-g-l "returns tuple of nodes [gains losses], part of [[relative-strength-index]]. gains: if (pos? x - (x-1)) then x else 0 losses: if (neg? x - (x-1)) then -x else 0 Sources: - `src`" [tl {:keys [src] :as sources}] [(map-some tl (fn [x] (if (pos? x) x 0)) (momentum tl sources)) (map-some tl (fn [x] (if (neg? x) (abs x) 0)) (momentum tl sources))]) (defn relative-strength-index "Values between 0 and 1. Reference: - -relative-strength-index-rsi/ Sources - `src` Opts: - `avg-indicator` used to average both [[relative-strength-g-l]]. Defaults to [[relative-moving-average]], must accept source as `:src` - `avg-opts` if specified, overrides top level opts passed to `avg-indicator`" [tl {:keys [src] :as sources} {:keys [avg-indicator avg-opts] :or {avg-indicator relative-moving-average} :as opts}] (let [[g l] (relative-strength-g-l tl sources)] (map-some tl (fn [g l] (cond (zero? l) 1 (zero? g) 0 :else (/ g (+ g l)))) (avg-indicator tl {:src g} (or avg-opts opts)) (avg-indicator tl {:src l} (or avg-opts opts))))) (defn commodity-channel-index "Reference: - -help/x-study/technical-indicator-definitions/commodity-channel-index-cci/ Sources: - `src` can be any number series, although the original formula specifies typical price to be [[hlc3]]. Opts: - `avg-indicator` defaults to [[simple-moving-average]], must accept src as `:src` - `avg-opts` if specified, overrides top level `opts` on `avg-indicator` - `mean-dev-opts` if specified, overrides top level `opts` on internal [[mean-deviation]] - `constant-factor` double. defaults to 0.015" [tl {:keys [src] :as sources} {:keys [avg-indicator avg-opts mean-dev-opts period constant-factor] :or {avg-indicator simple-moving-average constant-factor 0.015} :as opts}] (derived tl {:src src :ma (avg-indicator tl sources (or avg-opts opts)) :mean-dev (mean-deviation tl sources (or mean-dev-opts opts))} (fn commodity-channel-index- [curr {:keys [mean-dev ma src]} k] (bc/when-let [price (get src k) ma (get ma k) mean-dev (get mean-dev k) cci-val (if-not (zero? mean-dev) (/ (- price ma) (* mean-dev constant-factor)) Double/NaN)] (if (Double/isNaN cci-val) (get curr (ts/shift src k -1 {:vf key})) cci-val))))) (defn relative-volatility-u-s "Returns nodes tuple [u s] of [[relative-volatility-index]] u and s components. Similar to [[relative-strength-g-l]], but use standard-deviation of price-change instead of absolute price change. Sources: - `src` Opts are those of [[standard-deviation]] Reference: - (RVIOrig)" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (let [std (standard-deviation tl sources opts) vch (momentum tl sources) u (map-some tl (fn [vch std] (if (not (neg? vch)) std 0)) vch std) s (map-some tl (fn [vch std] (if (neg? vch) std 0)) vch std)] [u s])) (defn relative-volatility-index "Values from 0 to 1. Reference: - (RVIOrig) Sources: - `src` Opts: - `avg-indicator` defaults to [[exponential-moving-average]], must accept source as `:src` - `stdev-opts` if specified, overrides top level `opts` passed to [[relative-volatility-u-s]] - `avg-opts` if specified, overrides top level `opts` passed to `avg-indicator`" [tl {:keys [src] :as sources} {:keys [avg-indicator avg-opts stdev-opts period] :or {avg-indicator exponential-moving-average} :as opts}] (let [[u s] (relative-volatility-u-s tl sources (or stdev-opts opts))] (map-some tl (fn [u s] (/ u (+ s u))) (avg-indicator tl {:src u} (or avg-opts opts)) (avg-indicator tl {:src s} (or avg-opts opts))))) (defn refined-relative-volatility-index "(rvi(high) + rvi(low) / 2), with values between 0 and 1. Reference: - (RVI) Sources: - `high` - `low` Opts are those accepted by [[relative-volatility-index]]" ([tl {:keys [high low] :as sources} {:keys [avg-indicator avg-opts stdev-opts period] :as opts}] (mean tl (relative-volatility-index tl {:src high} opts) (relative-volatility-index tl {:src low} opts)))) (defn base-range "high - low Sources: - `high` - `low`" [tl {:keys [high low]}] (map-some tl - high low)) (defn true-range "Reference: - (TR) Sources: - `close` - `high` - `low`" [tl {:keys [close high low] :as sources}] (derived tl sources (fn true-range- [_ {:keys [close high low]} k] (bc/when-let [curr-h (get high k) curr-l (get low k) prev-c (ts/shift close k -1 {:vf val}) hl-dif (- curr-h curr-l) hc (abs (- curr-h prev-c)) lc (abs (- curr-l prev-c))] (max hl-dif hc lc))))) (defn average-base-range "moving average of [[base-range]]. Sources: - `high` - `low` Opts: - `avg-indicator` defaults to [[relative-moving-average]], must accept source as `:src` - `period` passed to `avg-indicator` as :period" [tl {:keys [high low] :as sources} {:keys [avg-indicator period] :or {avg-indicator relative-moving-average}}] (avg-indicator tl {:src (base-range tl sources)} {:period period})) (defn average-true-range "moving average of [[true-range]]. Reference: - (ATR) Sources: - `close` - `high` - `low` Opts: - `avg-indicator` defaults to [[relative-moving-average]], must accept source as `:src` - `period` passed to `avg-indicator` as :period" [tl {:keys [close high low] :as sources} {:keys [avg-indicator period] :or {avg-indicator relative-moving-average}}] (avg-indicator tl {:src (true-range tl sources)} {:period period})) (defn bollinger-bands "Returns tuple of nodes [upper middle lower] for bollinger bands. Reference: - Sources: - `src` Opts: - `avg-indicator` for middle band. Defaults to [[simple-moving-average]], must accept source as `:src` - `avg-opts` if specified, overrides top level `opts` for `avg-indicator` - `stdev-opts` if specified, overrides top level `opts` for [[standard-deviation]] " [tl {:keys [src] :as sources} {:keys [avg-indicator period avg-opts stdev-opts multiplier] :or {avg-indicator simple-moving-average} :as opts}] (let [middle (avg-indicator tl sources (or avg-opts opts)) offset (standard-deviation tl sources (or stdev-opts opts)) upper (map-some tl (fn [m off] (+ m (* multiplier off))) middle offset) lower (map-some tl (fn [m off] (- m (* multiplier off))) middle offset)] [upper middle lower])) (defn keltner-channels "Returns tuple of nodes [upper middle lower] Reference: - -keltner-channels-kc/ Sources: - `close` (atr) - `high` (atr) - `low` (atr) - `src` (middle band) Opts: - `avg-indicator` for middle band. Defaults to [[exponential-moving-average]], will be passed top level sources. - `avg-opts` if specified, overrides top level `opts` for `avg-indicator` - `range-indicator` for use as range indicator. Defaults to [[average-true-range]]. Will be passed top level `sources` unchanged. - `range-opts` if specified, overrides top level `opts` for range indicator. - `multiplier`" [tl {:keys [close high low src] :as sources} {:keys [avg-indicator avg-opts range-indicator range-opts multiplier] :or {avg-indicator exponential-moving-average range-indicator average-true-range} :as opts}] (let [middle (avg-indicator tl sources (or avg-opts opts)) rng (range-indicator tl sources (or range-opts opts)) upper (map-some tl (fn [m rng] (+ m (* multiplier rng))) middle rng) lower (map-some tl (fn [m rng] (- m (* multiplier rng))) middle rng)] [upper middle lower])) (defn average-directional-index "Returns tuple of [adx di+ di-] nodes, where adx is between 0 and 1. Reference: - -average-directional-index-adx-calculated-and-what-formula.asp Sources: - `close` - `high` - `low` Opts: - `range-indicator` range indicator to use, will be called with top level `sources`. Defaults to [[average-true-range]] - `range-opts` if specified, overrides top level `opts` passed to range indicator. - `line-avg-indicator` defaults to [[exponential-moving-average]] - `line-avg-opts` if specified, overrides top level opts passed to `line-avg-indicator` - `adx-avg-indicator` defaults to [[exponential-moving-average]] - `adx-avg-opts` if specified, overrides top level `opts` on `adx-avg-indicator`" [tl {:keys [close high low] :as sources} {:keys [adx-avg-indicator adx-avg-opts range-indicator range-opts line-avg-indicator line-avg-opts] :or {adx-avg-indicator exponential-moving-average range-indicator average-true-range line-avg-indicator exponential-moving-average} :as opts}] (let [high-ch (momentum tl {:src high}) low-ch (momentum tl {:src low}) rng (range-indicator tl sources (or range-opts opts)) base-di (fn [x1 x2] (map-some tl (fn [x1 x2 rng] (/ (if (and (> x1 x2) (> x1 0)) x1 0) rng)) x1 x2 rng)) +di (line-avg-indicator tl {:src (base-di high-ch low-ch)} (or line-avg-opts opts)) -di (line-avg-indicator tl {:src (base-di low-ch high-ch)} (or line-avg-opts opts)) adx (map-some tl (fn [p n] (abs (/ (- p n) (+ p n)))) +di -di) adx (adx-avg-indicator tl {:src adx} (or adx-avg-opts opts))] [adx +di -di])) (defn on-balance-volume "Reference: - Sources: - `src` - `volume`" [tl {:keys [src volume] :as sources}] (derived tl sources (fn on-balance-volume- [obv {:keys [src volume]} k] (bc/when-let [[prev-k prev-c] (ts/shift src k -1) :let [prev-obv (get obv prev-k)] curr-c (get src k) curr-v (get volume k)] (cond (not prev-obv) 0 (> curr-c prev-c) (+ prev-obv curr-v) (< curr-c prev-c) (- prev-obv curr-v) (= curr-c prev-c) prev-obv))))) (defn accumulation-distribution-line "Returns tuple of [adl money-flow-multiplier money-flow-volume] indicators. Reference: - -accumulation-distribution-adl/ Sources: - `close` - `high` - `low` - `volume`" [tl {:keys [close high low volume] :as sources}] (let [mfm (derived tl sources (fn [curr {:keys [close high low]} k] (bc/when-let [h (get high k) c (get close k) l (get low k)] (if (= h l) (get curr (ts/shift close k -1 {:vf key})) (/ (- (- c l) (- h c)) (- h l)))))) mfv (map-some tl * mfm volume) adl (derived tl {:mfv mfv} (fn [v {:keys [mfv]} k] (when-let [curr-mfv (get mfv k)] (if-let [prev (get v (ts/shift mfv k -1 {:vf key}))] (+ prev curr-mfv) curr-mfv))))] [adl mfm mfv])) (defn highest-val "Returns highest value of latest period items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val})] (second (ts/select t >=)))))) (defn lowest-val "Returns lowest value of latest period items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val})] (second (ts/select t <=)))))) (defn since-highest-val "Returns number of items since highest value on latest `period` items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val}) [sidx _] (ts/select t >=)] (- period (inc sidx)))))) (defn since-lowest-val "Returns number of items since lowest value on latest `period` items Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl sources (fn [_ {:keys [src]} k] (bc/when-let [t (ts/tail src period {:endk k :vf val}) [sidx _] (ts/select t <=)] (- period (inc sidx)))))) (defn aroon-oscillator "Returns tuple of nodes [aroon-oscillator aroon-up aroon-down], vals between 0 and 1 Reference: - Sources: - `high` - `low` Opts: - `period`" [tl {:keys [high low]} {:keys [period] :as opts}] (let [aup (map-some tl (fn [x] (/ (- period x) period)) (since-highest-val tl {:src high} opts)) adown (map-some tl (fn [x] (/ (- period x) period)) (since-lowest-val tl {:src low} opts)) aroon (map-some tl - aup adown)] [aroon aup adown])) (defn chandelier-exits "Returns tuple of chandelier exits nodes [long short] Reference: - :chandelier_exit Sources: - `close` - `high` - `low` Opts: - `range-indicator` Defaults to [[average-true-range]], will be passed top level `sources`. - `range-opts` if specified, overrides top level `opts` passed to `range-indicator` - `highest-opts` if specified, overrides top level `opts` passed to [[highest-val]] - `lowest-opts` if specified, overrides top level `opts` passed to [[lowest-val]] - `multiplier`" [tl {:keys [close high low] :as sources} {:keys [range-indicator range-opts highest-opts lowest-opts multiplier] :or {range-indicator average-true-range} :as opts}] (let [highest (highest-val tl {:src high} (or highest-opts opts)) lowest (lowest-val tl {:src low} (or lowest-opts opts)) rng (range-indicator tl sources (or range-opts opts)) long (map-some tl (fn [h atr] (- h (* multiplier atr))) highest rng) short (map-some tl (fn [l atr] (+ l (* multiplier atr))) lowest rng)] [long short])) (defn donchian-channels "Returns tuple of [mid high low] nodes Sources: - `high` - `low` Opts: - `highest-opts` if specified, overrides top level `opts` on [[highest-val]] - `lowest-opts` if specified, overrides top level `opts` on [[lowest-val]] Reference: - " [tl {:keys [high low]} {:keys [highest-opts lowest-opts] :as opts}] (let [highest (highest-val tl {:src high} (or highest-opts opts)) lowest (lowest-val tl {:src low} (or lowest-opts opts)) mid (mean tl highest lowest)] [mid highest lowest])) (defn supertrend "Reference impl: - -ta/blob/main/pandas_ta/overlap/supertrend.py Sources: - `close` - `high` - `low` Opts: - `range-indicator` defaults to [[average-true-range]], will be passed top level `sources` - `range-opts` if specified, overrides top level `opts` for `range-indicator` - `multiplier` Values are map of: - `trend` e/o #{:long :short} - `value` number - `_upper` - `_lower`" [tl {:keys [close high low] :as sources} {:keys [multiplier range-indicator range-opts] :or {range-indicator average-true-range} :as opts}] (let [rng (range-indicator tl sources (or range-opts opts)) hl2' (hl2 tl sources) basic-upper (map-some tl (fn [hlm rng] (+ hlm (* multiplier rng))) hl2' rng) basic-lower (map-some tl (fn [hlm rng] (- hlm (* multiplier rng))) hl2' rng)] (derived tl {:close close :upper basic-upper :lower basic-lower} (fn [st {:keys [close upper lower]} k] (bc/when-let [prev-k (ts/shift close k -1 {:vf key}) :let [prev-st (get st prev-k)] curr-c (get close k) curr-up (get upper k) curr-lo (get lower k)] (cond (and prev-st (> curr-c (:_upper prev-st))) {:trend :long :value curr-lo :_upper curr-up :_lower curr-lo} (and prev-st (< curr-c (:_lower prev-st))) {:trend :short :value curr-up :_upper curr-up :_lower curr-lo} :else (let [trend (or (:trend prev-st) :long) lower (if (and (= :long trend) prev-st (< curr-lo (:_lower prev-st))) (:_lower prev-st) curr-lo) upper (if (and (= :short trend) prev-st (> curr-up (:_upper prev-st))) (:_upper prev-st) curr-up)] {:trend trend :_upper upper :_lower lower :value (case trend :long lower :short upper)}))))))) (defn kaufman-efficiency-ratio "Reference: - :kaufman_s_adaptive_moving_average (ER) Sources: - `src` Opts: - `period`" [tl {:keys [src] :as sources} {:keys [period] :as opts}] (derived tl {:mom (momentum tl sources)} (fn kaufman-efficiency-ratio- [_ {:keys [mom]} k] (bc/when-let [ch (some-> (get mom k) abs) ch-tail (ts/tail mom period {:endk k :vf val})] (/ ch (reduce (fn [a n] (+ a (abs n))) 0 ch-tail)))))) (defn kaufman-adaptive-moving-average "Reference: - :kaufman_s_adaptive_moving_average (KAMA) Sources: - `src` Opts: - `er-period` period to use on [[kaufman-efficiency-ratio]] - `slow-period` - `fast-period`" [tl {:keys [src] :as sources} {:keys [er-period slow-period fast-period]}] (let [ssc (/ 2 (inc slow-period)) fsc (/ 2 (inc fast-period)) sc (map-some tl (fn [er] (math-nt/expt (+ (* er (- fsc ssc)) ssc) 2)) (kaufman-efficiency-ratio tl sources {:period er-period}))] (derived tl {:src src :sc sc} (fn [kama {:keys [src sc]} k] (bc/when-let [curr-p (get src k) curr-sc (get sc k) :let [prev-kama (get kama (ts/shift src k -1 {:vf key}))]] (if prev-kama (+ prev-kama (* curr-sc (- curr-p prev-kama))) (ts/moving-average src k er-period)))))))
d63042b61a6322604a0308509839850cb9ca454155adf319ef1f1a250896d9ca
fulcrologic/fulcro-rad-datomic
indexed_access_spec.clj
(ns com.fulcrologic.rad.database-adapters.indexed-access-spec (:require [clojure.test :refer [use-fixtures]] [com.fulcrologic.rad.database-adapters.datomic :as datomic] [com.fulcrologic.rad.database-adapters.indexed-access-checks :refer [run-checks]] [datomic.api :as d] [fulcro-spec.core :refer [specification]] [com.fulcrologic.rad.type-support.date-time :as dt])) (use-fixtures :once (fn [t] (datomic/reset-migrated-dbs!) (dt/with-timezone "America/Los_Angeles" (t)))) (specification "Datomic On-Prem Indexed Access" (run-checks (assoc datomic/datomic-api :generate-resolvers datomic/generate-resolvers :make-connection datomic/empty-db-connection)))
null
https://raw.githubusercontent.com/fulcrologic/fulcro-rad-datomic/0234b6d15524a0e37e26cfd7b26aafda52b07265/src/test/com/fulcrologic/rad/database_adapters/indexed_access_spec.clj
clojure
(ns com.fulcrologic.rad.database-adapters.indexed-access-spec (:require [clojure.test :refer [use-fixtures]] [com.fulcrologic.rad.database-adapters.datomic :as datomic] [com.fulcrologic.rad.database-adapters.indexed-access-checks :refer [run-checks]] [datomic.api :as d] [fulcro-spec.core :refer [specification]] [com.fulcrologic.rad.type-support.date-time :as dt])) (use-fixtures :once (fn [t] (datomic/reset-migrated-dbs!) (dt/with-timezone "America/Los_Angeles" (t)))) (specification "Datomic On-Prem Indexed Access" (run-checks (assoc datomic/datomic-api :generate-resolvers datomic/generate-resolvers :make-connection datomic/empty-db-connection)))
ac5b3991bb71e5b472e15a68804897caffd0b27c3ab12ef331ed1d1589bbe3e1
acieroid/scala-am
pcounter9.scm
(letrec ((counter (atom 0)) (thread (lambda (n) (letrec ((old (deref counter)) (new (+ old 1))) (if (compare-and-set! counter old new) #t (thread n))))) (t1 (future (thread 1))) (t2 (future (thread 2))) (t3 (future (thread 3))) (t4 (future (thread 4))) (t5 (future (thread 5))) (t6 (future (thread 6))) (t7 (future (thread 7))) (t8 (future (thread 8))) (t9 (future (thread 9)))) (deref t1) (deref t2) (deref t3) (deref t4) (deref t5) (deref t6) (deref t7) (deref t8) (deref t9) (= counter 9))
null
https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/futures/variations/pcounter9.scm
scheme
(letrec ((counter (atom 0)) (thread (lambda (n) (letrec ((old (deref counter)) (new (+ old 1))) (if (compare-and-set! counter old new) #t (thread n))))) (t1 (future (thread 1))) (t2 (future (thread 2))) (t3 (future (thread 3))) (t4 (future (thread 4))) (t5 (future (thread 5))) (t6 (future (thread 6))) (t7 (future (thread 7))) (t8 (future (thread 8))) (t9 (future (thread 9)))) (deref t1) (deref t2) (deref t3) (deref t4) (deref t5) (deref t6) (deref t7) (deref t8) (deref t9) (= counter 9))
bd05762e73bd4e275b5c18ed915873da823881ffe78e5f4627d70421aab8a9cf
mklinik/hmud
Test.hs
module Hmud.Test where import Test.Hspec.HUnit import Test.Hspec import Test.HUnit import Data.Maybe (fromJust, isNothing, isJust) import Data.Either.Unwrap import qualified Data.Map as Map import Data.Map (Map) import qualified Data.List as List import System.IO import qualified Control.Monad.State as State import Control.Monad.State (State) import Hmud.World import Hmud.Character import Hmud.Room import Hmud.TestData import Hmud.Hmud import Hmud.Message import Hmud.Item import Hmud.Commands import Xmpp.Util emptyWorld = World { worldRooms = [], idleCharacters = [] } specs :: Specs specs = descriptions [ describe "insertCharacterToRoom" [ it "returns Nothing when there is no such room in the world" (either (const True) (const False) $ insertCharacterToRoom player0 "what where?" emptyWorld) , it "returns Nothing when there is no such room in the world" (either (const True) (const False) $ insertCharacterToRoom player0 "what where?" world) , it "returns the world where the player is in the desired room on success" ((do w <- insertCharacterToRoom player0 "Black Unicorn" world r <- findRoom "Black Unicorn" w findCharacterInRoom "player0" r ) == Right player0) , it "works with abbreviated room name" ((do w <- insertCharacterToRoom player0 "Bl" world r <- findRoom "Black Unicorn" w findCharacterInRoom "player0" r ) == Right player0) ] , describe "gotoFromTo" [ it "returns Nothing if there is no such *from* room" (either (const True) (const False) $ gotoFromTo "player0addr" "what where?" "Black Unicorn" world) , it "returns Nothing if there is no such *to* room" (either (const True) (const False) $ gotoFromTo "player0addr" "Black Unicorn" "what where?" world) , it "returns Nothing if there is no such character in the *from* room" (either (const True) (const False) $ gotoFromTo "slayer0" "Black Unicorn" "town square" world) , it "works when everything is fine" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world let (w3, _, _, _) = fromRight $ gotoFromTo "player0addr" "Black Unicorn" "town square" w2 let fromRoom = fromRight $ findRoom "Black Unicorn" w3 let toRoom = fromRight $ findRoom "town square" w3 assertBool "player is no longer in *fromRoom*" $ isLeft (findCharacterInRoom "player0" fromRoom) assertEqual "player is now in *toRoom*" (Right player0) (findCharacterInRoom "player0" toRoom) ) , it "does not work with abbreviated names" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black" world assertBool "no such player pl" $ isLeft $ gotoFromTo "pl" "Th" "to" w2 ) , it "fails when trying to go to the same room again" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world assertBool "going to the same room fails" $ isLeft $ gotoFromTo "player0addr" "Black" "Black Un" w2 ) ] , describe "findCharacterByAddress" [ it "succeeds when everything is fine" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world assertEqual "player found" (Right player0) (findCharacterByAddress "player0addr" w2) assertBool "player not found" $ isLeft (findCharacterByAddress "slayer0" w2) ) , it "fails in the empty world" (TestCase $ do assertBool "player not found" $ isLeft (findCharacterByAddress "player0addr" emptyWorld) assertBool "player not found" $ isLeft (findCharacterByAddress "slayer0" emptyWorld) ) , it "fails with partial names" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world assertBool "player not found" $ isLeft (findCharacterByAddress "pla" w2) ) ] -- Xmpp.Users , describe "jid2player" [ it "returns the capitalized resource for conference JIDs" (jid2player "/markus.klinik" == "Markus Klinik") , it "returns the capitalized username for personal JIDs" (jid2player "markus.klinik@localhost/Gajim" == "Markus Klinik") ] -- system tests, maps input messages to output messages , describe "system tests" [ it "a player joins, and is put to Black Unicorn" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [(MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs assertEqual "player0 is in the Unicorn" "Black Unicorn" (roomName (fromRight $ findRoomOfPlayerByAddress "player0" newWorld)) ) , it "a player joins, then goes to town square" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player0" (words "goto town square")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let room = fromRight $ findRoomOfPlayerByAddress "player0" newWorld assertEqual "player0 is in town square" "town square" (roomName room) let player = fromRight $ findCharacterInRoomByAddress "player0" room let (_, MsgGoto fromRoom char toRoom) = head $ List.filter (isMsgGoto . snd) outputMsgs assertEqual "fromRoom is the Unicorn" "Black Unicorn" (roomName fromRoom) assertEqual "player is Hel Mut" "Hel Mut" (charName char) assertEqual "toRoom is town square" "town square" (roomName toRoom) ) , it "a player joins, then picks up the scroll of forgery, then forges an item" ( TestCase $ do let world2 = fromRight $ insertItemToRoom scroll1 "Black Unicorn" world let (world3, (inputMsgs, outputMsgs, _)) = State.runState (run world2) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player0" (words "take scroll")) , (MsgCommand "player0" (words "forge mug of beer $ hmmmmm, beer")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs assertEqual "we got exactly one take message" 1 (length $ List.filter (isMsgTake . snd) outputMsgs) let room = fromRight $ findRoomOfPlayerByAddress "player0" world3 assertBool "scroll is not in the room" $ isLeft $ findItemInRoom "scroll of forgery" room let char = fromRight $ findCharacterByAddress "player0" world3 assertBool "scroll is in the players inventory" $ isRight $ characterFindItem "scroll of forgery" char assertBool "beer is in the players inventory" $ isRight $ characterFindItem "mug of beer" char let (_, MsgForge c it) = head $ List.filter (isMsgForge . snd) outputMsgs assertEqual "character forged something" "Hel Mut" (charName c) assertEqual "forged item is mug of beer" "mug of beer" (itemName it) ) , it "three players join, one picks up the scroll and drops the scroll again" ( TestCase $ do let world2 = fromRight $ insertItemToRoom scroll1 "Black Unicorn" world let (world3, (inputMsgs, outputMsgs, _)) = State.runState (run world2) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerEnters "player2" "Bil Bo" "bil.bo@localhost") , (MsgCommand "player0" (words "take scroll")) , (MsgCommand "player0" (words "put scroll")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let takeMsgs = List.filter (isMsgTake . snd) outputMsgs let putMsgs = List.filter (isMsgPut . snd) outputMsgs assertEqual "we got three take messages" 3 (length takeMsgs) assertEqual "we got three put messages" 3 (length putMsgs) assertBool "one take message is to player0" $ isJust $ List.find (\(addr, _) -> addr == "player0") takeMsgs assertBool "one take message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") takeMsgs assertBool "one take message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") takeMsgs assertBool "one put message is to player0" $ isJust $ List.find (\(addr, _) -> addr == "player0") putMsgs assertBool "one put message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") putMsgs assertBool "one put message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") putMsgs ) , it "two players A and B enter. B exits and leaves its character behind. A changes it's nick to the nick of B, but must still control A's character." ( TestCase $ do let (world2, (inputMsgs, outputMsgs, debugs)) = State.runState (run world) ( [ (MsgPlayerEnters "playerA" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "playerB" "Ara Gorn" "ara.gorn@localhost") now , leaves and playerA tries to impersonate playerB , (MsgPlayerEnters "playerB" "Hel Mut" "hel.mut@localhost") , (MsgCommand "playerB" (words "goto town")) ], []::[TestStateOutgoing], []::[String]) mapM_ (hPutStrLn stderr) debugs let unicorn = fromRight $ findRoom "Black Unicorn" world2 let townSqr = fromRight $ findRoom "town square" world2 assertBool "Ara Gorn is still in The Unicorn" $ isRight $ findCharacterInRoom "Ara Gorn" unicorn assertBool "Hel Mut went to town square" $ isRight $ findCharacterInRoom "Hel Mut" townSqr ) ] , describe "say" [ it "can only be heard in the current room" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerEnters "player2" "Bil Bo" "bil.bo@localhost") , (MsgCommand "player0" (words "goto town")) , (MsgCommand "player1" (words "say hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let sayMsgs = List.filter (isMsgSay . snd) outputMsgs assertEqual "we got 2 say messages" 2 $ length sayMsgs assertBool "one say message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") sayMsgs assertBool "one say message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") sayMsgs ) ] , describe "tell" [ it "can only be heard by the receipient and the speaker" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerEnters "player2" "Bil Bo" "bil.bo@localhost") , (MsgCommand "player0" (words "goto town")) , (MsgCommand "player1" (words "tell Bil $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertEqual "we got 2 tell messages" 2 $ length tellMsgs assertBool "one say message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") tellMsgs assertBool "one say message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") tellMsgs ) ] , describe "MsgPlayerLeaves" [ it "puts the leaving player from the room in the idle list" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerLeaves "player0") ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let unicorn = fromRight $ findRoom "Black Unicorn" newWorld assertBool "Black Unicorn is empty" $ null $ roomCharacters unicorn assertBool "Hel Mut is in the idle list" $ isJust $ List.find (\c -> charAddress c == "player0") (idleCharacters newWorld) ) , it "inserts a player back to the game when the player enters again" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerLeaves "player0") , (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let unicorn = fromRight $ findRoom "Black Unicorn" newWorld assertEqual "Black Unicorn is not empty" 1 (length $ roomCharacters unicorn) assertBool "the idle list is empty" $ null $ (idleCharacters newWorld) ) , it "other players can not speak to a left player" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerLeaves "player0") , (MsgCommand "player1" (words "tell Hel Mut $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertBool "we got no tell messages" $ null tellMsgs ) , it "when a player enters again, everything is back to normal" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerLeaves "player0") , (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player1" (words "tell Hel Mut $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertEqual "we got 2 tell messages" 2 $ length tellMsgs assertBool "one tell message is to player0" $ isJust $ List.find (\(addr, _) -> addr == "player0") tellMsgs assertBool "one tell message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") tellMsgs assertBool "the idle list is empty" $ null $ (idleCharacters newWorld) ) , it "when a player enters again but with a different address, everything works just fine" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerLeaves "player0") , (MsgPlayerEnters "player2" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player1" (words "tell Hel Mut $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertEqual "we got 2 tell messages" 2 $ length tellMsgs assertBool "one tell message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") tellMsgs assertBool "one tell message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") tellMsgs assertBool "the idle list is empty" $ null $ (idleCharacters newWorld) ) ] ] main = hspec specs
null
https://raw.githubusercontent.com/mklinik/hmud/5ba32f29170a098e007d50688df32cf8919b6bf1/Hmud/Test.hs
haskell
Xmpp.Users system tests, maps input messages to output messages
module Hmud.Test where import Test.Hspec.HUnit import Test.Hspec import Test.HUnit import Data.Maybe (fromJust, isNothing, isJust) import Data.Either.Unwrap import qualified Data.Map as Map import Data.Map (Map) import qualified Data.List as List import System.IO import qualified Control.Monad.State as State import Control.Monad.State (State) import Hmud.World import Hmud.Character import Hmud.Room import Hmud.TestData import Hmud.Hmud import Hmud.Message import Hmud.Item import Hmud.Commands import Xmpp.Util emptyWorld = World { worldRooms = [], idleCharacters = [] } specs :: Specs specs = descriptions [ describe "insertCharacterToRoom" [ it "returns Nothing when there is no such room in the world" (either (const True) (const False) $ insertCharacterToRoom player0 "what where?" emptyWorld) , it "returns Nothing when there is no such room in the world" (either (const True) (const False) $ insertCharacterToRoom player0 "what where?" world) , it "returns the world where the player is in the desired room on success" ((do w <- insertCharacterToRoom player0 "Black Unicorn" world r <- findRoom "Black Unicorn" w findCharacterInRoom "player0" r ) == Right player0) , it "works with abbreviated room name" ((do w <- insertCharacterToRoom player0 "Bl" world r <- findRoom "Black Unicorn" w findCharacterInRoom "player0" r ) == Right player0) ] , describe "gotoFromTo" [ it "returns Nothing if there is no such *from* room" (either (const True) (const False) $ gotoFromTo "player0addr" "what where?" "Black Unicorn" world) , it "returns Nothing if there is no such *to* room" (either (const True) (const False) $ gotoFromTo "player0addr" "Black Unicorn" "what where?" world) , it "returns Nothing if there is no such character in the *from* room" (either (const True) (const False) $ gotoFromTo "slayer0" "Black Unicorn" "town square" world) , it "works when everything is fine" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world let (w3, _, _, _) = fromRight $ gotoFromTo "player0addr" "Black Unicorn" "town square" w2 let fromRoom = fromRight $ findRoom "Black Unicorn" w3 let toRoom = fromRight $ findRoom "town square" w3 assertBool "player is no longer in *fromRoom*" $ isLeft (findCharacterInRoom "player0" fromRoom) assertEqual "player is now in *toRoom*" (Right player0) (findCharacterInRoom "player0" toRoom) ) , it "does not work with abbreviated names" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black" world assertBool "no such player pl" $ isLeft $ gotoFromTo "pl" "Th" "to" w2 ) , it "fails when trying to go to the same room again" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world assertBool "going to the same room fails" $ isLeft $ gotoFromTo "player0addr" "Black" "Black Un" w2 ) ] , describe "findCharacterByAddress" [ it "succeeds when everything is fine" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world assertEqual "player found" (Right player0) (findCharacterByAddress "player0addr" w2) assertBool "player not found" $ isLeft (findCharacterByAddress "slayer0" w2) ) , it "fails in the empty world" (TestCase $ do assertBool "player not found" $ isLeft (findCharacterByAddress "player0addr" emptyWorld) assertBool "player not found" $ isLeft (findCharacterByAddress "slayer0" emptyWorld) ) , it "fails with partial names" (TestCase $ do let w2 = fromRight $ insertCharacterToRoom player0 "Black Unicorn" world assertBool "player not found" $ isLeft (findCharacterByAddress "pla" w2) ) ] , describe "jid2player" [ it "returns the capitalized resource for conference JIDs" (jid2player "/markus.klinik" == "Markus Klinik") , it "returns the capitalized username for personal JIDs" (jid2player "markus.klinik@localhost/Gajim" == "Markus Klinik") ] , describe "system tests" [ it "a player joins, and is put to Black Unicorn" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [(MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs assertEqual "player0 is in the Unicorn" "Black Unicorn" (roomName (fromRight $ findRoomOfPlayerByAddress "player0" newWorld)) ) , it "a player joins, then goes to town square" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player0" (words "goto town square")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let room = fromRight $ findRoomOfPlayerByAddress "player0" newWorld assertEqual "player0 is in town square" "town square" (roomName room) let player = fromRight $ findCharacterInRoomByAddress "player0" room let (_, MsgGoto fromRoom char toRoom) = head $ List.filter (isMsgGoto . snd) outputMsgs assertEqual "fromRoom is the Unicorn" "Black Unicorn" (roomName fromRoom) assertEqual "player is Hel Mut" "Hel Mut" (charName char) assertEqual "toRoom is town square" "town square" (roomName toRoom) ) , it "a player joins, then picks up the scroll of forgery, then forges an item" ( TestCase $ do let world2 = fromRight $ insertItemToRoom scroll1 "Black Unicorn" world let (world3, (inputMsgs, outputMsgs, _)) = State.runState (run world2) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player0" (words "take scroll")) , (MsgCommand "player0" (words "forge mug of beer $ hmmmmm, beer")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs assertEqual "we got exactly one take message" 1 (length $ List.filter (isMsgTake . snd) outputMsgs) let room = fromRight $ findRoomOfPlayerByAddress "player0" world3 assertBool "scroll is not in the room" $ isLeft $ findItemInRoom "scroll of forgery" room let char = fromRight $ findCharacterByAddress "player0" world3 assertBool "scroll is in the players inventory" $ isRight $ characterFindItem "scroll of forgery" char assertBool "beer is in the players inventory" $ isRight $ characterFindItem "mug of beer" char let (_, MsgForge c it) = head $ List.filter (isMsgForge . snd) outputMsgs assertEqual "character forged something" "Hel Mut" (charName c) assertEqual "forged item is mug of beer" "mug of beer" (itemName it) ) , it "three players join, one picks up the scroll and drops the scroll again" ( TestCase $ do let world2 = fromRight $ insertItemToRoom scroll1 "Black Unicorn" world let (world3, (inputMsgs, outputMsgs, _)) = State.runState (run world2) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerEnters "player2" "Bil Bo" "bil.bo@localhost") , (MsgCommand "player0" (words "take scroll")) , (MsgCommand "player0" (words "put scroll")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let takeMsgs = List.filter (isMsgTake . snd) outputMsgs let putMsgs = List.filter (isMsgPut . snd) outputMsgs assertEqual "we got three take messages" 3 (length takeMsgs) assertEqual "we got three put messages" 3 (length putMsgs) assertBool "one take message is to player0" $ isJust $ List.find (\(addr, _) -> addr == "player0") takeMsgs assertBool "one take message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") takeMsgs assertBool "one take message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") takeMsgs assertBool "one put message is to player0" $ isJust $ List.find (\(addr, _) -> addr == "player0") putMsgs assertBool "one put message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") putMsgs assertBool "one put message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") putMsgs ) , it "two players A and B enter. B exits and leaves its character behind. A changes it's nick to the nick of B, but must still control A's character." ( TestCase $ do let (world2, (inputMsgs, outputMsgs, debugs)) = State.runState (run world) ( [ (MsgPlayerEnters "playerA" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "playerB" "Ara Gorn" "ara.gorn@localhost") now , leaves and playerA tries to impersonate playerB , (MsgPlayerEnters "playerB" "Hel Mut" "hel.mut@localhost") , (MsgCommand "playerB" (words "goto town")) ], []::[TestStateOutgoing], []::[String]) mapM_ (hPutStrLn stderr) debugs let unicorn = fromRight $ findRoom "Black Unicorn" world2 let townSqr = fromRight $ findRoom "town square" world2 assertBool "Ara Gorn is still in The Unicorn" $ isRight $ findCharacterInRoom "Ara Gorn" unicorn assertBool "Hel Mut went to town square" $ isRight $ findCharacterInRoom "Hel Mut" townSqr ) ] , describe "say" [ it "can only be heard in the current room" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerEnters "player2" "Bil Bo" "bil.bo@localhost") , (MsgCommand "player0" (words "goto town")) , (MsgCommand "player1" (words "say hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let sayMsgs = List.filter (isMsgSay . snd) outputMsgs assertEqual "we got 2 say messages" 2 $ length sayMsgs assertBool "one say message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") sayMsgs assertBool "one say message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") sayMsgs ) ] , describe "tell" [ it "can only be heard by the receipient and the speaker" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerEnters "player2" "Bil Bo" "bil.bo@localhost") , (MsgCommand "player0" (words "goto town")) , (MsgCommand "player1" (words "tell Bil $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertEqual "we got 2 tell messages" 2 $ length tellMsgs assertBool "one say message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") tellMsgs assertBool "one say message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") tellMsgs ) ] , describe "MsgPlayerLeaves" [ it "puts the leaving player from the room in the idle list" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerLeaves "player0") ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let unicorn = fromRight $ findRoom "Black Unicorn" newWorld assertBool "Black Unicorn is empty" $ null $ roomCharacters unicorn assertBool "Hel Mut is in the idle list" $ isJust $ List.find (\c -> charAddress c == "player0") (idleCharacters newWorld) ) , it "inserts a player back to the game when the player enters again" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerLeaves "player0") , (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let unicorn = fromRight $ findRoom "Black Unicorn" newWorld assertEqual "Black Unicorn is not empty" 1 (length $ roomCharacters unicorn) assertBool "the idle list is empty" $ null $ (idleCharacters newWorld) ) , it "other players can not speak to a left player" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerLeaves "player0") , (MsgCommand "player1" (words "tell Hel Mut $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertBool "we got no tell messages" $ null tellMsgs ) , it "when a player enters again, everything is back to normal" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerLeaves "player0") , (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player1" (words "tell Hel Mut $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertEqual "we got 2 tell messages" 2 $ length tellMsgs assertBool "one tell message is to player0" $ isJust $ List.find (\(addr, _) -> addr == "player0") tellMsgs assertBool "one tell message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") tellMsgs assertBool "the idle list is empty" $ null $ (idleCharacters newWorld) ) , it "when a player enters again but with a different address, everything works just fine" ( TestCase $ do let (newWorld, (inputMsgs, outputMsgs, _)) = State.runState (run world) ( [ (MsgPlayerEnters "player0" "Hel Mut" "hel.mut@localhost") , (MsgPlayerEnters "player1" "Ara Gorn" "ara.gorn@localhost") , (MsgPlayerLeaves "player0") , (MsgPlayerEnters "player2" "Hel Mut" "hel.mut@localhost") , (MsgCommand "player1" (words "tell Hel Mut $ hello")) ], []::[TestStateOutgoing], []::[String]) assertBool "input messages are all consumed" $ null inputMsgs let tellMsgs = List.filter (isMsgTell . snd) outputMsgs assertEqual "we got 2 tell messages" 2 $ length tellMsgs assertBool "one tell message is to player2" $ isJust $ List.find (\(addr, _) -> addr == "player2") tellMsgs assertBool "one tell message is to player1" $ isJust $ List.find (\(addr, _) -> addr == "player1") tellMsgs assertBool "the idle list is empty" $ null $ (idleCharacters newWorld) ) ] ] main = hspec specs
28c287a871876bd308798390e8cd87cdfd0262a059599706f49c553bd3c62066
damienlepage/vhector
hector.clj
(ns vhector.internal.hector (:use [vhector.internal.util :only [single?]]) (:import [me.prettyprint.hector.api.factory HFactory] [me.prettyprint.cassandra.serializers BytesArraySerializer] [me.prettyprint.cassandra.model CqlQuery] [java.io DataOutputStream ByteArrayOutputStream DataInputStream ByteArrayInputStream])) (def DEFAULT_MAX_ROWS 1000000) (def DEFAULT_MAX_COLS Integer/MAX_VALUE) (def LONG_SUFFIX "?long") (def DOUBLE_SUFFIX "?double") (def END_SUFFIX "?zzz") (def se (BytesArraySerializer/get)) (defn create-keyspace [cluster-name host port ks] (let [cluster (HFactory/getOrCreateCluster cluster-name (str host ":" port))] (HFactory/createKeyspace ks cluster))) (defn init [cluster-name host port ks typed-columns] (def ^:dynamic *keyspace* (create-keyspace cluster-name host port ks)) (def ^:dynamic *typed-columns* typed-columns)) (defn longable? [x] (or (instance? Short x) (instance? Integer x) (instance? Long x))) (defn doublable? [x] (or (instance? Double x) (instance? Float x))) (defn get-data-suffix [x] (cond (longable? x) LONG_SUFFIX (doublable? x) DOUBLE_SUFFIX :default nil)) (defn encode-number [x conv-fct] (let [baos (ByteArrayOutputStream.) dos (DataOutputStream. baos)] (conv-fct x dos) (.toByteArray baos))) (defn encode-string ([x] (encode-string x nil)) ([x suffix] (let [s (str x suffix) s2 (if (keyword? x) s (pr-str s))] (.getBytes s2 "UTF-8")))) (defn encode ([data] (encode data nil)) ([data suffix] (cond (or (nil? data) (= :FROM-FIRST data) (= :TO-LAST data)) nil (coll? data) (map encode data) (and *typed-columns* (doublable? data)) (encode-number data #(.writeDouble %2 (double %1))) (and *typed-columns* (longable? data)) (encode-number data #(.writeLong %2 (long %1))) :default (encode-string data suffix)))) (defn decode-number [bytes-arr conv-fct] (when-not (nil? bytes-arr) (let [bais (ByteArrayInputStream. bytes-arr) dis (DataInputStream. bais)] (conv-fct dis)))) (defn to-string [bytes-arr] (when-not (nil? bytes-arr) (with-in-str (String. bytes-arr "UTF-8") (read)))) (defn decode ([bytes-arr] (decode bytes-arr nil)) ([bytes-arr suffix] (cond (= suffix LONG_SUFFIX) (decode-number bytes-arr #(.readLong %)) (= suffix DOUBLE_SUFFIX) (decode-number bytes-arr #(.readDouble %)) :default (to-string bytes-arr)))) (defn expand-tree [t] (if (map? t) (for [[k v] t, w (expand-tree v)] (cons k w)) (list (list t)))) (defn get-suffix-from-col [col] (let [s (str col) idx (.indexOf s "?")] (if (pos? idx) (.substring s idx) s))) (defn remove-suffix [col] (let [s (str col) idx (.indexOf s "?") new-col (if (pos? idx) (.substring s 0 idx) s)] (if (keyword? col) (with-in-str new-col (read)) new-col))) (defn convert-slice [slice] (let [cols (.getColumns slice) cols-seq (iterator-seq (.iterator cols))] (reduce (fn [m col] (let [full-col-name (decode (.getName col)) suffix (get-suffix-from-col full-col-name) col-name (remove-suffix full-col-name)] (if (and (not= "KEY" col-name) (nil? (m col-name))) ; make sure we don't overwrite due to typed-columns (assoc m col-name (decode (.getValue col) suffix)) m))) {} cols-seq))) (defn convert-super-slice [super-slice] (let [super-cols (.getSuperColumns super-slice) super-cols-seq (iterator-seq (.iterator super-cols))] (reduce (fn [m super-col] (assoc m (decode (.getName super-col)) (convert-slice super-col))) {} super-cols-seq))) (defn extract-columns [row] (convert-slice (.getColumnSlice row))) (defn extract-columns-with-super [super row] {super (convert-slice (.getColumnSlice row))}) (defn extract-super-columns [row] (convert-super-slice (.getSuperSlice row))) (defn extract-rows ([rows] (extract-rows rows extract-columns)) ([rows extract-fn] (let [rows-seq (iterator-seq (.iterator rows))] (reduce (fn [m row] (assoc m (decode (.getKey row)) (extract-fn row))) {} rows-seq)))) (defn set-column-names [query crit] (let [arr (if (vector? crit) crit [crit])] (doto query (.setColumnNames (to-array (encode arr)))))) (defn set-super-column [query crit] (doto query (.setSuperColumn (encode crit)))) (defn is-reversed [start stop raw-stop] (if (= :FROM-FIRST raw-stop) true (if-let [real-stop stop] (pos? (compare start real-stop)) false))) ; consider that nil as stop means normal order (defn apply-range [query crit max-res] (if (map? crit) (let [crit-start (first (keys crit)) crit-stop (get crit crit-start) nillify-special #(if (or (= :FROM-FIRST %) (= :TO-LAST %)) nil %) crit-start2 (nillify-special crit-start) crit-stop2 (nillify-special crit-stop) reversed (is-reversed crit-start2 crit-stop2 crit-stop) encoded-start (if reversed (encode crit-start END_SUFFIX) (encode crit-start)) ; make sure typed cols are included in the range by appending ? zzz (doto query (.setRange encoded-start encoded-stop reversed max-res))) (set-column-names query crit))) (defn execute-query [query cf ks] (let [ks-vec (if (vector? ks) ks [ks])] (doto query (.setColumnFamily cf) (.setKeys (to-array (encode ks-vec)))) (-> query .execute .get))) (defn concat-suffix [x suffix] (let [s (str x suffix)] (if (keyword? x) (with-in-str s (read)) s))) (defn expand-possible-cols [cols] (if-not (map? cols) (apply vector (mapcat #(vector % (concat-suffix % %2) (concat-suffix % %3)) (if (vector? cols) cols [cols]) (repeat LONG_SUFFIX) (repeat DOUBLE_SUFFIX))) cols)) (defn read-rows ([cf ks cols] (read-rows cf ks cols DEFAULT_MAX_COLS)) ([cf ks cols max-cols] (let [cols+ (expand-possible-cols cols) query (HFactory/createMultigetSliceQuery *keyspace* se se se)] (apply-range query cols+ max-cols) (extract-rows (execute-query query cf ks))))) (defn read-row-super ([cf ks super cols] (read-row-super cf ks super cols DEFAULT_MAX_COLS)) ([cf ks super cols max-cols] (let [cols+ (expand-possible-cols cols) query (HFactory/createMultigetSubSliceQuery *keyspace* se se se se)] (apply-range query cols+ max-cols) (doto query (.setSuperColumn (encode super))) (extract-rows (execute-query query cf ks) (partial extract-columns-with-super super))))) (defn read-rows-super ([cf ks sups cols] (read-rows-super cf ks sups cols DEFAULT_MAX_COLS)) ([cf ks sups cols max-sups] (let [query (HFactory/createMultigetSuperSliceQuery *keyspace* se se se se)] (apply-range query sups max-sups) (extract-rows (execute-query query cf ks) extract-super-columns)))) (defn prep-range-query [cf ks max-rows query] (let [key-start (first (keys ks)) key-stop (get ks key-start)] (doto query (.setColumnFamily cf) (.setKeys (encode key-start) (encode key-stop)) (.setRowCount max-rows)))) (defn read-range-rows ([cf ks cols] (read-range-rows cf ks cols DEFAULT_MAX_ROWS)) ([cf ks cols max-rows] (read-range-rows cf ks cols max-rows DEFAULT_MAX_COLS)) ([cf ks cols max-rows max-cols] (let [cols+ (expand-possible-cols cols) q (HFactory/createRangeSlicesQuery *keyspace* se se se) range-slices-query (prep-range-query cf ks max-rows q)] (apply-range range-slices-query cols+ max-cols) (-> range-slices-query .execute .get extract-rows)))) (defn read-range-rows-super ([cf ks sups cols] (read-range-rows-super cf ks sups cols DEFAULT_MAX_ROWS)) ([cf ks sups cols max-rows] (read-range-rows-super cf ks sups cols max-rows DEFAULT_MAX_COLS)) ([cf ks sups cols max-rows max-cols] (if (single? sups) (let [cols+ (expand-possible-cols cols) q (HFactory/createRangeSubSlicesQuery *keyspace* se se se se) range-slices-query (prep-range-query cf ks max-rows q)] (doto range-slices-query (.setSuperColumn (encode sups))) (apply-range range-slices-query cols+ max-cols) (extract-rows (-> range-slices-query .execute .get) (partial extract-columns-with-super sups))) (let [q (HFactory/createRangeSuperSlicesQuery *keyspace* se se se se) range-slices-query (prep-range-query cf ks max-rows q)] (apply-range range-slices-query sups max-cols) (extract-rows (-> range-slices-query .execute .get) extract-super-columns))))) (defn add-insertion ([mutator cf k col v] (add-insertion mutator cf nil k col v)) ([mutator cf super k col v] (let [encoded-col (encode col (get-data-suffix v)) stringcol (HFactory/createColumn encoded-col (encode v) se se)] (if (nil? super) (.addInsertion mutator (encode k) cf stringcol) (let [super-col (HFactory/createSuperColumn (encode k) [stringcol] se se se)] (.addInsertion mutator (encode super) cf super-col)))))) (defn add-deletion ([mutator cf ks] (if-not (vector? ks) (add-deletion mutator cf [ks]) (doseq [k ks] (.addDeletion mutator (encode k) cf)))) ([mutator cf k cols] (if-not (vector? cols) (add-deletion mutator cf k [cols]) (let [cols+ (expand-possible-cols cols)] (doseq [col cols+] (.addDeletion mutator (encode k) cf (encode col) se))))) ([mutator cf k super cols] (if-not (vector? cols) (add-deletion mutator cf k super [cols]) (let [cols+ (expand-possible-cols cols)] (doseq [col-name cols+] (let [stringcol (HFactory/createColumn (encode col-name) (encode-string "") se se) ; value is not used but must not be null super-col (HFactory/createSuperColumn (encode super) [stringcol] se se se)] (.addSubDelete mutator (encode k) cf super-col))))))) (defn process-tree [tree func] (let [mutator (HFactory/createMutator *keyspace* se) records (expand-tree tree)] (doseq [record records] (apply func mutator record)) (.execute mutator))) (defn internal-insert! [tree] (process-tree tree add-insertion)) (defn internal-delete! [tree] (process-tree tree add-deletion)) (defn build-cql-cols [cols] (cond (= cols [:COUNT]) "1" ; count(*) => (empty? cols) "*" :default (str "'" (reduce str (interpose "', '" (expand-possible-cols cols))) "'"))) (defn escape-cql ([x] (escape-cql x nil)) ([x suffix] (cond (doublable? x) x (longable? x) x (string? x) (str "'" (pr-str (str x suffix)) "'") :default (str "'" x suffix "'")))) ; keyword (defn to-cql-crit [where m] e.g. : WHERE>= gives operator > = (apply vector (for [[k v] m] (let [encoded-k (escape-cql k (get-data-suffix v)) encoded-v (escape-cql v)] (str encoded-k " " operator " " encoded-v)))))) (defn build-cql-where-clauses [cql-args] (when-not (empty? cql-args) (concat (to-cql-crit (first cql-args) (second cql-args)) (build-cql-where-clauses (nnext cql-args))))) (defn build-cql-where-string [clauses] (when-not (empty? clauses) (let [and-clauses (interpose " AND " clauses)] (str " WHERE " (reduce str and-clauses))))) (defn build-cql-query [cf cols & cql-args] (let [cols-cql (build-cql-cols cols) clauses-cql (build-cql-where-clauses cql-args) where-cql (build-cql-where-string clauses-cql) cql (str "SELECT " cols-cql " FROM " cf where-cql )] ( println " CQL= " cql ) cql)) (defn cql [cf cols & cql-args] (let [query (CqlQuery. *keyspace* se se se) _ (doto query (.setQuery (apply build-cql-query cf cols cql-args))) res (-> query .execute .get)] (when res (if (= cols [:COUNT]) .getAsCount ? (extract-rows res)))))
null
https://raw.githubusercontent.com/damienlepage/vhector/0cd9697ab0d3a1327a76b0f5c3ee7fa7b9309b0e/src/vhector/internal/hector.clj
clojure
make sure we don't overwrite due to typed-columns consider that nil as stop means normal order make sure typed cols are included in the value is not used but must not be null count(*) => keyword
(ns vhector.internal.hector (:use [vhector.internal.util :only [single?]]) (:import [me.prettyprint.hector.api.factory HFactory] [me.prettyprint.cassandra.serializers BytesArraySerializer] [me.prettyprint.cassandra.model CqlQuery] [java.io DataOutputStream ByteArrayOutputStream DataInputStream ByteArrayInputStream])) (def DEFAULT_MAX_ROWS 1000000) (def DEFAULT_MAX_COLS Integer/MAX_VALUE) (def LONG_SUFFIX "?long") (def DOUBLE_SUFFIX "?double") (def END_SUFFIX "?zzz") (def se (BytesArraySerializer/get)) (defn create-keyspace [cluster-name host port ks] (let [cluster (HFactory/getOrCreateCluster cluster-name (str host ":" port))] (HFactory/createKeyspace ks cluster))) (defn init [cluster-name host port ks typed-columns] (def ^:dynamic *keyspace* (create-keyspace cluster-name host port ks)) (def ^:dynamic *typed-columns* typed-columns)) (defn longable? [x] (or (instance? Short x) (instance? Integer x) (instance? Long x))) (defn doublable? [x] (or (instance? Double x) (instance? Float x))) (defn get-data-suffix [x] (cond (longable? x) LONG_SUFFIX (doublable? x) DOUBLE_SUFFIX :default nil)) (defn encode-number [x conv-fct] (let [baos (ByteArrayOutputStream.) dos (DataOutputStream. baos)] (conv-fct x dos) (.toByteArray baos))) (defn encode-string ([x] (encode-string x nil)) ([x suffix] (let [s (str x suffix) s2 (if (keyword? x) s (pr-str s))] (.getBytes s2 "UTF-8")))) (defn encode ([data] (encode data nil)) ([data suffix] (cond (or (nil? data) (= :FROM-FIRST data) (= :TO-LAST data)) nil (coll? data) (map encode data) (and *typed-columns* (doublable? data)) (encode-number data #(.writeDouble %2 (double %1))) (and *typed-columns* (longable? data)) (encode-number data #(.writeLong %2 (long %1))) :default (encode-string data suffix)))) (defn decode-number [bytes-arr conv-fct] (when-not (nil? bytes-arr) (let [bais (ByteArrayInputStream. bytes-arr) dis (DataInputStream. bais)] (conv-fct dis)))) (defn to-string [bytes-arr] (when-not (nil? bytes-arr) (with-in-str (String. bytes-arr "UTF-8") (read)))) (defn decode ([bytes-arr] (decode bytes-arr nil)) ([bytes-arr suffix] (cond (= suffix LONG_SUFFIX) (decode-number bytes-arr #(.readLong %)) (= suffix DOUBLE_SUFFIX) (decode-number bytes-arr #(.readDouble %)) :default (to-string bytes-arr)))) (defn expand-tree [t] (if (map? t) (for [[k v] t, w (expand-tree v)] (cons k w)) (list (list t)))) (defn get-suffix-from-col [col] (let [s (str col) idx (.indexOf s "?")] (if (pos? idx) (.substring s idx) s))) (defn remove-suffix [col] (let [s (str col) idx (.indexOf s "?") new-col (if (pos? idx) (.substring s 0 idx) s)] (if (keyword? col) (with-in-str new-col (read)) new-col))) (defn convert-slice [slice] (let [cols (.getColumns slice) cols-seq (iterator-seq (.iterator cols))] (reduce (fn [m col] (let [full-col-name (decode (.getName col)) suffix (get-suffix-from-col full-col-name) col-name (remove-suffix full-col-name)] (if (assoc m col-name (decode (.getValue col) suffix)) m))) {} cols-seq))) (defn convert-super-slice [super-slice] (let [super-cols (.getSuperColumns super-slice) super-cols-seq (iterator-seq (.iterator super-cols))] (reduce (fn [m super-col] (assoc m (decode (.getName super-col)) (convert-slice super-col))) {} super-cols-seq))) (defn extract-columns [row] (convert-slice (.getColumnSlice row))) (defn extract-columns-with-super [super row] {super (convert-slice (.getColumnSlice row))}) (defn extract-super-columns [row] (convert-super-slice (.getSuperSlice row))) (defn extract-rows ([rows] (extract-rows rows extract-columns)) ([rows extract-fn] (let [rows-seq (iterator-seq (.iterator rows))] (reduce (fn [m row] (assoc m (decode (.getKey row)) (extract-fn row))) {} rows-seq)))) (defn set-column-names [query crit] (let [arr (if (vector? crit) crit [crit])] (doto query (.setColumnNames (to-array (encode arr)))))) (defn set-super-column [query crit] (doto query (.setSuperColumn (encode crit)))) (defn is-reversed [start stop raw-stop] (if (= :FROM-FIRST raw-stop) true (if-let [real-stop stop] (pos? (compare start real-stop)) (defn apply-range [query crit max-res] (if (map? crit) (let [crit-start (first (keys crit)) crit-stop (get crit crit-start) nillify-special #(if (or (= :FROM-FIRST %) (= :TO-LAST %)) nil %) crit-start2 (nillify-special crit-start) crit-stop2 (nillify-special crit-stop) reversed (is-reversed crit-start2 crit-stop2 crit-stop) range by appending ? zzz (doto query (.setRange encoded-start encoded-stop reversed max-res))) (set-column-names query crit))) (defn execute-query [query cf ks] (let [ks-vec (if (vector? ks) ks [ks])] (doto query (.setColumnFamily cf) (.setKeys (to-array (encode ks-vec)))) (-> query .execute .get))) (defn concat-suffix [x suffix] (let [s (str x suffix)] (if (keyword? x) (with-in-str s (read)) s))) (defn expand-possible-cols [cols] (if-not (map? cols) (apply vector (mapcat #(vector % (concat-suffix % %2) (concat-suffix % %3)) (if (vector? cols) cols [cols]) (repeat LONG_SUFFIX) (repeat DOUBLE_SUFFIX))) cols)) (defn read-rows ([cf ks cols] (read-rows cf ks cols DEFAULT_MAX_COLS)) ([cf ks cols max-cols] (let [cols+ (expand-possible-cols cols) query (HFactory/createMultigetSliceQuery *keyspace* se se se)] (apply-range query cols+ max-cols) (extract-rows (execute-query query cf ks))))) (defn read-row-super ([cf ks super cols] (read-row-super cf ks super cols DEFAULT_MAX_COLS)) ([cf ks super cols max-cols] (let [cols+ (expand-possible-cols cols) query (HFactory/createMultigetSubSliceQuery *keyspace* se se se se)] (apply-range query cols+ max-cols) (doto query (.setSuperColumn (encode super))) (extract-rows (execute-query query cf ks) (partial extract-columns-with-super super))))) (defn read-rows-super ([cf ks sups cols] (read-rows-super cf ks sups cols DEFAULT_MAX_COLS)) ([cf ks sups cols max-sups] (let [query (HFactory/createMultigetSuperSliceQuery *keyspace* se se se se)] (apply-range query sups max-sups) (extract-rows (execute-query query cf ks) extract-super-columns)))) (defn prep-range-query [cf ks max-rows query] (let [key-start (first (keys ks)) key-stop (get ks key-start)] (doto query (.setColumnFamily cf) (.setKeys (encode key-start) (encode key-stop)) (.setRowCount max-rows)))) (defn read-range-rows ([cf ks cols] (read-range-rows cf ks cols DEFAULT_MAX_ROWS)) ([cf ks cols max-rows] (read-range-rows cf ks cols max-rows DEFAULT_MAX_COLS)) ([cf ks cols max-rows max-cols] (let [cols+ (expand-possible-cols cols) q (HFactory/createRangeSlicesQuery *keyspace* se se se) range-slices-query (prep-range-query cf ks max-rows q)] (apply-range range-slices-query cols+ max-cols) (-> range-slices-query .execute .get extract-rows)))) (defn read-range-rows-super ([cf ks sups cols] (read-range-rows-super cf ks sups cols DEFAULT_MAX_ROWS)) ([cf ks sups cols max-rows] (read-range-rows-super cf ks sups cols max-rows DEFAULT_MAX_COLS)) ([cf ks sups cols max-rows max-cols] (if (single? sups) (let [cols+ (expand-possible-cols cols) q (HFactory/createRangeSubSlicesQuery *keyspace* se se se se) range-slices-query (prep-range-query cf ks max-rows q)] (doto range-slices-query (.setSuperColumn (encode sups))) (apply-range range-slices-query cols+ max-cols) (extract-rows (-> range-slices-query .execute .get) (partial extract-columns-with-super sups))) (let [q (HFactory/createRangeSuperSlicesQuery *keyspace* se se se se) range-slices-query (prep-range-query cf ks max-rows q)] (apply-range range-slices-query sups max-cols) (extract-rows (-> range-slices-query .execute .get) extract-super-columns))))) (defn add-insertion ([mutator cf k col v] (add-insertion mutator cf nil k col v)) ([mutator cf super k col v] (let [encoded-col (encode col (get-data-suffix v)) stringcol (HFactory/createColumn encoded-col (encode v) se se)] (if (nil? super) (.addInsertion mutator (encode k) cf stringcol) (let [super-col (HFactory/createSuperColumn (encode k) [stringcol] se se se)] (.addInsertion mutator (encode super) cf super-col)))))) (defn add-deletion ([mutator cf ks] (if-not (vector? ks) (add-deletion mutator cf [ks]) (doseq [k ks] (.addDeletion mutator (encode k) cf)))) ([mutator cf k cols] (if-not (vector? cols) (add-deletion mutator cf k [cols]) (let [cols+ (expand-possible-cols cols)] (doseq [col cols+] (.addDeletion mutator (encode k) cf (encode col) se))))) ([mutator cf k super cols] (if-not (vector? cols) (add-deletion mutator cf k super [cols]) (let [cols+ (expand-possible-cols cols)] (doseq [col-name cols+] super-col (HFactory/createSuperColumn (encode super) [stringcol] se se se)] (.addSubDelete mutator (encode k) cf super-col))))))) (defn process-tree [tree func] (let [mutator (HFactory/createMutator *keyspace* se) records (expand-tree tree)] (doseq [record records] (apply func mutator record)) (.execute mutator))) (defn internal-insert! [tree] (process-tree tree add-insertion)) (defn internal-delete! [tree] (process-tree tree add-deletion)) (defn build-cql-cols [cols] (cond (empty? cols) "*" :default (str "'" (reduce str (interpose "', '" (expand-possible-cols cols))) "'"))) (defn escape-cql ([x] (escape-cql x nil)) ([x suffix] (cond (doublable? x) x (longable? x) x (string? x) (str "'" (pr-str (str x suffix)) "'") (defn to-cql-crit [where m] e.g. : WHERE>= gives operator > = (apply vector (for [[k v] m] (let [encoded-k (escape-cql k (get-data-suffix v)) encoded-v (escape-cql v)] (str encoded-k " " operator " " encoded-v)))))) (defn build-cql-where-clauses [cql-args] (when-not (empty? cql-args) (concat (to-cql-crit (first cql-args) (second cql-args)) (build-cql-where-clauses (nnext cql-args))))) (defn build-cql-where-string [clauses] (when-not (empty? clauses) (let [and-clauses (interpose " AND " clauses)] (str " WHERE " (reduce str and-clauses))))) (defn build-cql-query [cf cols & cql-args] (let [cols-cql (build-cql-cols cols) clauses-cql (build-cql-where-clauses cql-args) where-cql (build-cql-where-string clauses-cql) cql (str "SELECT " cols-cql " FROM " cf where-cql )] ( println " CQL= " cql ) cql)) (defn cql [cf cols & cql-args] (let [query (CqlQuery. *keyspace* se se se) _ (doto query (.setQuery (apply build-cql-query cf cols cql-args))) res (-> query .execute .get)] (when res (if (= cols [:COUNT]) .getAsCount ? (extract-rows res)))))
c215372f260e54ce130f1fbcb70d01250ee0d0706614a54ad207d6a0c31223f5
REMath/mit_16.399
symbol_Table.mli
(* symbol_Table.mli *) type variable = int (* symbol table *) val init_symb_table : unit -> unit val add_symb_table : string -> variable (* variables *) val number_of_variables : unit -> int val for_all_variables : (variable -> 'a) -> unit val print_variable : variable -> unit val print_map_variables : (variable -> unit) -> unit
null
https://raw.githubusercontent.com/REMath/mit_16.399/3f395d6a9dfa1ed232d307c3c542df3dbd5b614a/project/Generic-FW-Abstract-Interpreter/symbol_Table.mli
ocaml
symbol_Table.mli symbol table variables
type variable = int val init_symb_table : unit -> unit val add_symb_table : string -> variable val number_of_variables : unit -> int val for_all_variables : (variable -> 'a) -> unit val print_variable : variable -> unit val print_map_variables : (variable -> unit) -> unit
b0b66d58b718e6a148ea5d96084d719da715a26d2f78891b12252a65707d462f
krisajenkins/yesql
util.clj
(ns yesql.util (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.pprint :refer [pprint]]) (:import [java.io FileNotFoundException])) (defn underscores-to-dashes [string] (when string (string/replace string "_" "-"))) (defn str-non-nil "Exactly like `clojure.core/str`, except it returns an empty string with no args (whereas `str` would return `nil`)." [& args] (apply str "" args)) (defn slurp-from-classpath "Slurps a file from the classpath." [path] (or (some-> path io/resource slurp) (throw (FileNotFoundException. path)))) TODO There may well be a built - in for this . If there is , I have not found it . (defn create-root-var "Given a name and a value, intern a var in the current namespace, taking metadata from the value." ([name value] (create-root-var *ns* name value)) ([ns name value] (intern ns (with-meta (symbol name) (meta value)) value)))
null
https://raw.githubusercontent.com/krisajenkins/yesql/333750e5bc90aebba3a8578b744cfa146cf68ba9/src/yesql/util.clj
clojure
(ns yesql.util (:require [clojure.java.io :as io] [clojure.string :as string] [clojure.pprint :refer [pprint]]) (:import [java.io FileNotFoundException])) (defn underscores-to-dashes [string] (when string (string/replace string "_" "-"))) (defn str-non-nil "Exactly like `clojure.core/str`, except it returns an empty string with no args (whereas `str` would return `nil`)." [& args] (apply str "" args)) (defn slurp-from-classpath "Slurps a file from the classpath." [path] (or (some-> path io/resource slurp) (throw (FileNotFoundException. path)))) TODO There may well be a built - in for this . If there is , I have not found it . (defn create-root-var "Given a name and a value, intern a var in the current namespace, taking metadata from the value." ([name value] (create-root-var *ns* name value)) ([ns name value] (intern ns (with-meta (symbol name) (meta value)) value)))
e2091f2ae1fdb9c587baf225aa47d7a951f29fc12cc1447cc1e9ed69f3d92750
rd--/hsc3
b_write.help.hs
Sound.Sc3.Lang.Help.viewServerHelp "/b_write"
null
https://raw.githubusercontent.com/rd--/hsc3/024d45b6b5166e5cd3f0142fbf65aeb6ef642d46/Help/Server/b_write.help.hs
haskell
Sound.Sc3.Lang.Help.viewServerHelp "/b_write"
fd3d996f215d1f2c0f99b56483cb90864ed305271e85f3f529e39d95180bad76
pschachte/wybe
BodyBuilder.hs
-- File : BodyBuilder.hs Author : -- Purpose : A monad to build up a procedure Body, with copy propagation Copyright : ( c ) 2015 . All rights reserved . License : Licensed under terms of the MIT license . See the file -- : LICENSE in the root directory of this project. module BodyBuilder ( BodyBuilder, buildBody, freshVarName, instr, buildFork, completeFork, beginBranch, endBranch, definiteVariableValue, argExpandedPrim ) where import AST import Debug.Trace import Snippets ( boolType, intType, primMove ) import Util import Config (minimumSwitchCases, wordSize) import Options (LogSelection(BodyBuilder)) import Data.Map as Map import Data.List as List import Data.Set as Set import UnivSet as USet import Data.Maybe import Data.Tuple.HT (mapFst) import Data.Bits import Data.Function import Control.Monad import Control.Monad.Extra (whenJust, whenM) import Control.Monad.Trans (lift) import Control.Monad.Trans.State ---------------------------------------------------------------- -- The BodyBuilder Monad -- This monad is used to build up a ProcBody one instruction at a time . -- -- buildBody runs the monad, producing a ProcBody. -- instr adds a single instruction to then end of the procBody being built. Forks are produced by the following functions : -- buildFork initiates a fork on a specified variable -- beginBranch starts a new branch of the current fork ends the current branch -- completeFork completes the current fork -- -- A ProcBody is considered to have a unique continuation if it either -- does not end in a branch, or if all but at most one of the branches -- it ends with ends with a definite failure (a PrimTest (ArgInt 0 _)). -- No instructions can be added between buildFork and , or between endBranch and beginBranch , or if the current state does not have -- a unique continuation. A new fork can be built within a branch, but must -- be completed before the branch is ended. -- -- The ProcBody type does not support having anything follow a fork. Once a -- ProcBody forks, the branches do not join again. Instead, each branch of -- a fork should end with a call to another proc, which does whatever -- should come after the fork. To handle this, once a fork is completed, the BodyBuilder starts a new Unforked instruction sequence , and records -- the completed fork as the prev of the Unforked sequence. This -- also permits a fork to follow the Unforked sequence which follows a -- fork. When producing the final ProcBody, if the current Unforked -- sequence is short (or empty) and there is a prev fork, we simply -- add the sequence to the end of each of branch of the fork and remove the -- Unforked sequence. If it is not short and there is a prev, we -- create a fresh proc whose input arguments are all the live variables, -- whose outputs are the current proc's outputs, and whose body is built -- from Unforked sequence, add a call to this fresh proc to each branch of the previous Forked sequence , and remove the Unforked . -- -- We handle a Forked sequence by generating a ProcBody for each branch, -- collecting these as the branches of a ProcBody, and taking the instructions from the preceding Unforked as the instruction sequence of -- the ProcBody. -- -- Note that for convenience/efficiency, we collect the instructions in a -- sequence and the branches in a fork in reverse order, so these are -- reversed when converting to a ProcBody. -- Some transformation is performed by the BodyBuilder monad ; in -- particular, we keep track of variable=variable assignments, and replace -- references to the destination (left) variable with the source (right) -- variable. This usually leaves the assignment dead, to be removed in -- a later pass. We also keep track of previous instructions, and later -- calls to the same instructions with the same inputs are replaced by -- assignments to the outputs with the old outputs. We also handle some arithmetic equivalences , , and tautologies ( eg , on a branch where we know , a call to x<=y will always return true ; for unsigned x , x<0 is always false , and is replaced with x!=0 ) . -- We also maintain a counter for temporary variable names. -- The BodyState has two constructors : Unforked is used before the first -- fork, and after each new branch is created. Instructions can just be -- added to this. Forked is used after a new fork is begun and before its first branch is created , between ending a branch and starting a new one , -- and after the fork is completed. New instructions can be added and new -- forks built only when in the Unforked state. In the Forked state, we can -- only create a new branch. -- -- These constructors are used in a zipper-like structure, where the top of the -- structure is the part we're building, and below that is the parent, ie, -- the fork structure of which it's a part. This is implemented as follows: -- buildFork is called when the state is Unforked . It creates a new -- Forked state, with the old state as its origin and an empty list -- of bodies. The new parent is the same as the old one. -- -- beginBranch is called when the state is Forked. It creates a new -- Unforked state with the old state as parent. -- is called with either a Forked or Unforked state . It -- adds the current state to the parent state's list of bodies and -- makes that the new state. -- -- completeFork is called when the state is Forked. It doesn't -- change the state. ---------------------------------------------------------------- type BodyBuilder = StateT BodyState Compiler -- Holds the content of a ProcBody while we're building it. data BodyState = BodyState { currBuild :: [Placed Prim], -- ^The body we're building, reversed currSubst :: Substitution, -- ^variable substitutions to propagate blockDefs :: Set PrimVarName, -- ^All variables defined in this block forkConsts :: Set PrimVarName, -- ^Consts in some branches of prev fork outSubst :: VarSubstitution, -- ^Substitutions for var assignments subExprs :: ComputedCalls, -- ^Previously computed calls to reuse failed :: Bool, -- ^True if this body always fails tmpCount :: Int, -- ^The next temp variable number to use buildState :: BuildState, -- ^The fork at the bottom of this node parent :: Maybe BodyState, -- ^What comes before/above this globalsLoaded :: Map GlobalInfo PrimArg, -- ^The set of globals that we currently -- know the value of reifiedConstr :: Map PrimVarName Constraint ^Constraints attached to Boolean vars } deriving (Eq,Show) data BuildState = Unforked -- ^Still building; ready for more instrs | Forked { forkingVar :: PrimVarName, -- ^Variable that selects branch to take forkingVarTy :: TypeSpec, -- ^Type of forkingVar knownVal :: Maybe Integer, -- ^Definite value of forkingVar if known ^forkingVar is a constant in every -- branch in the parent fork, so this -- fork will be fused with parent fork bodies :: [BodyState], -- ^Rev'd BodyStates of branches so far defaultBody :: Maybe BodyState, -- ^Body of the default fork branch complete :: Bool -- ^Whether the fork has been completed } -- ^Building a new fork deriving (Eq,Show) | A fresh BodyState with specified temp counter and output var substitution initState :: Int -> VarSubstitution -> BodyState initState tmp oSubst = BodyState [] Map.empty Set.empty Set.empty oSubst Map.empty False tmp Unforked Nothing Map.empty Map.empty | Set up a BodyState as a new child of the specified BodyState childState :: BodyState -> BuildState -> BodyState childState st@BodyState{currSubst=iSubst,outSubst=oSubst,subExprs=subs, tmpCount=tmp, forkConsts=consts, globalsLoaded=loaded, reifiedConstr=reif} bld = BodyState [] iSubst Set.empty consts oSubst subs False tmp bld (Just st) loaded reif -- | A mapping from variables to definite values, in service to constant -- propagation. type Substitution = Map PrimVarName PrimArg -- | A mapping from variables to their renamings. This is in service to -- variable elimination. type VarSubstitution = Map PrimVarName PrimVarName -- To handle common subexpression elimination, we keep a map from previous -- calls with their outputs removed. This type encapsulates that . In the Prim keys , all PrimArgs are inputs . type ComputedCalls = Map Prim [PrimArg] -- |Allocate the next temp variable name and ensure it's not allocated again freshVarName :: BodyBuilder PrimVarName freshVarName = do tmp <- gets tmpCount logBuild $ "Generating fresh variable " ++ mkTempName tmp modify (\st -> st {tmpCount = tmp + 1}) return $ PrimVarName (mkTempName tmp) 0 ---------------------------------------------------------------- -- Tracking Integer Constraints -- -- We maintain constraints on integer variables, in particular to handle reified constraints . LPVM Integer tests are all reified , producing a result as a -- separate value, and conditionals are always based on those reified values. -- This code allows us to remember what constraint stems from the reified value, -- so we can use that information in conditionals. For now we only support -- equality and disequality, as these are most useful. ---------------------------------------------------------------- data Constraint = Equal PrimVarName TypeSpec PrimArg | NotEqual PrimVarName TypeSpec PrimArg deriving (Eq) instance Show Constraint where show (Equal v t a) = show v ++ ":" ++ show t ++ " = " ++ show a show (NotEqual v t a) = show v ++ ":" ++ show t ++ " ~= " ++ show a -- negateConstraint :: Constraint -> Constraint -- negateConstraint (Equal v n) = NotEqual v n negateConstraint ( NotEqual v n ) = Equal v n ---------------------------------------------------------------- BodyBuilder Primitive Operations ---------------------------------------------------------------- |Run a BodyBuilder monad and extract the final proc body , along with the -- final temp variable count and the set of variables used in the body. buildBody :: Int -> VarSubstitution -> BodyBuilder a -> Compiler (a, Int, Set PrimVarName, Set GlobalInfo, ProcBody) buildBody tmp oSubst builder = do logMsg BodyBuilder "<<<< Beginning to build a proc body" (a, st) <- runStateT builder $ initState tmp oSubst logMsg BodyBuilder ">>>> Finished building a proc body" logMsg BodyBuilder " Final state:" logMsg BodyBuilder $ fst $ showState 8 st st' <- fuseBodies st (tmp', used, stored, body) <- currBody (ProcBody [] NoFork) st' return (a, tmp', used, stored, body) -- |Start a new fork on var of type ty buildFork :: PrimVarName -> TypeSpec -> BodyBuilder () buildFork var ty = do st <- get var' <- expandVar var ty logBuild $ "<<<< beginning to build a new fork on " ++ show var case buildState st of Forked{complete=True} -> shouldnt "Building a fork in Forked state" Forked{complete=False} -> shouldnt "Building a fork in Forking state" Unforked -> do logBuild $ " (expands to " ++ show var' ++ ")" case var' of ArgInt n _ -> -- fork variable value known at compile-time put $ childState st $ Forked var ty (Just n) False [] Nothing False ArgVar{argVarName=var'',argVarType=varType} -> do -- statically unknown result consts <- gets forkConsts logBuild $ "Consts from parent fork = " ++ show consts let fused = Set.member var'' consts logBuild $ "This fork " ++ (if fused then "WILL " else "will NOT ") ++ "be fused with parent" put $ st {buildState=Forked var'' ty Nothing fused [] Nothing False} _ -> shouldnt "switch on non-integer variable" logState -- |Complete a fork previously initiated by buildFork. completeFork :: BodyBuilder () completeFork = do st <- get case buildState st of Forked{complete=True} -> shouldnt "Completing an already-completed fork" Unforked -> shouldnt "Completing an un-built fork" Forked var ty val fused bods deflt False -> do logBuild $ ">>>> ending fork on " ++ show var -- let branchMap = List.foldr1 (Map.intersectionWith Set.union) ( Map.map Set.singleton . Map.filter argIsConst . < $ > bods ) let branchMaps = Map.filter argIsConst . currSubst <$> (bods ++ maybeToList deflt) -- Variables set to the same constant in every branch let extraSubsts = List.foldr1 intersectMapIdentity branchMaps logBuild $ " extraSubsts = " ++ show extraSubsts -- Variables with a constant value in each branch. These can be -- used later to fuse branches of subsequent forks on those variables -- with this fork. let consts = List.foldr1 Set.union $ List.map Map.keysSet branchMaps logBuild $ " definite variables in all branches: " ++ show consts -- Prepare for any instructions coming after the fork let parent = st {buildState = Forked var ty val fused bods deflt True, tmpCount = maximum $ tmpCount <$> bods } let child = childState parent Unforked put $ child { forkConsts = consts, currSubst = Map.union extraSubsts $ currSubst child} logState -- |Start a new branch for the next integer value of the switch variable. beginBranch :: BodyBuilder () beginBranch = do st <- get case buildState st of Forked{complete=True} -> shouldnt "Beginning a branch in an already-completed fork" Unforked -> shouldnt "Beginning a branch in an un-built fork" Forked var ty val fused bods deflt False -> do let branchNum = length bods logBuild $ "<<<< <<<< Beginning to build " ++ (if fused then "fused " else "") ++ "branch " ++ show branchNum ++ " on " ++ show var gets tmpCount >>= logBuild . (" tmpCount = "++) . show when fused $ do par <- gets $ trustFromJust "forkConst with no parent branch" . parent case buildState par of Forked{bodies=bods, defaultBody=deflt} -> do let matchingSubsts = List.map currSubst $ List.filter (matchingSubst var branchNum) bods let extraSubsts = if List.null matchingSubsts then Map.empty else List.foldr1 intersectMapIdentity matchingSubsts logBuild $ " Adding substs " ++ show extraSubsts modify $ \st -> st { currSubst = Map.union extraSubsts (currSubst st) } Unforked -> shouldnt "forkConst predicted parent branch" put $ childState st Unforked when (isNothing val && not fused) $ do addSubst var $ ArgInt (fromIntegral branchNum) intType noteBranchConstraints var intType branchNum logState -- |End the current branch. endBranch :: BodyBuilder () endBranch = do st <- get (par,st,var,ty,val,fused,bodies,deflt) <- gets popParent logBuild $ ">>>> >>>> Ending branch " ++ show (length bodies) ++ " on " ++ show var tmp <- gets tmpCount logBuild $ " tmpCount = " ++ show tmp put $ par { buildState=Forked var ty val fused (st:bodies) deflt False , tmpCount = tmp } logState |Return the closest Forking ancestor of a state , and fix its immediate -- child to no longer list it as parent popParent :: BodyState -> (BodyState,BodyState,PrimVarName,TypeSpec, Maybe Integer,Bool,[BodyState],Maybe BodyState) popParent st@BodyState{parent=Nothing} = shouldnt "endBranch with no open branch to end" popParent st@BodyState{parent=(Just par@BodyState{buildState=(Forked var ty val fused brs deflt False)})} = (par, st {parent = Nothing}, var, ty, val, fused, brs, deflt) popParent st@BodyState{parent=Just par} = let (anc, fixedPar, var, ty, val, fused, branches, deflt) = popParent par in (anc,st {parent=Just fixedPar}, var, ty, val, fused, branches, deflt) -- | Record whatever we can deduce from our current branch variable and branch -- number, based on previously computed reified constraints. noteBranchConstraints :: PrimVarName -> TypeSpec -> Int -> BodyBuilder () noteBranchConstraints var ty val = do constr <- gets $ Map.lookup var . reifiedConstr case (val,constr) of (1, Just (Equal origVar _ origVal)) -> addSubst origVar origVal (0, Just (NotEqual origVar _ origVal)) -> addSubst origVar origVal _ -> return () -- | Test if the specified variable is bound to the specified constant in the specified BodyState . matchingSubst :: PrimVarName -> Int -> BodyState -> Bool matchingSubst var branchNum bod = maybe False ((== branchNum) . fromIntegral) $ varIntValue var bod -- |Return Just the known value of the specified variable, or Nothing varIntValue :: PrimVarName -> BodyState -> Maybe Integer varIntValue var bod = Map.lookup var (currSubst bod) >>= argIntegerValue definiteVariableValue :: PrimVarName -> BodyBuilder (Maybe PrimArg) definiteVariableValue var = do arg <- expandVar var AnyType case arg of ArgVar{} -> return Nothing -- variable (unknown) result _ -> return $ Just arg -- |Add an instruction to the current body, after applying the current -- substitution. If it's a move instruction, add it to the current -- substitution. instr :: Prim -> OptPos -> BodyBuilder () instr prim pos = do st <- get case st of BodyState{failed=True} -> do -- ignore if we've already failed logBuild $ " Failing branch: ignoring instruction " ++ show prim return () BodyState{failed=False,buildState=Unforked} -> do prim' <- argExpandedPrim prim outNaming <- gets outSubst logBuild $ "With outSubst " ++ simpleShowMap outNaming logBuild $ "Generating instr " ++ show prim ++ " -> " ++ show prim' instr' prim' pos _ -> shouldnt "instr in Forked context" -- Actually do the work of instr instr' :: Prim -> OptPos -> BodyBuilder () instr' prim@(PrimForeign "llvm" "move" [] [val, argvar@ArgVar{argVarName=var, argVarFlow=flow}]) pos = do logBuild $ " Expanding move(" ++ show val ++ ", " ++ show argvar ++ ")" unless (flow == FlowOut && argFlowDirection val == FlowIn) $ shouldnt $ "move instruction with wrong flow" ++ show prim outVar <- gets (Map.findWithDefault var var . outSubst) addSubst outVar val -- XXX since we're recording the subst, so this instr will be removed later, -- can we just not generate it? rawInstr prim pos recordVarSet argvar -- The following equation is a bit of a hack to work around not threading a heap -- through the code, which causes the compiler to try to reuse the results of -- calls to alloc. Since the mutate primitives already have an output value, -- that should stop us from trying to reuse modified structures or the results -- of calls to access after a structure is modified, so alloc should be the only -- problem that needs fixing. We don't want to fix this by threading a heap -- through, because it's fine to reorder calls to alloc. We can't handle this -- with impurity because if we forgot the impurity modifier on any alloc, -- disaster would ensue, and an impure alloc wouldn't be removed if the -- structure weren't needed, which we want. instr' prim@(PrimForeign "lpvm" "alloc" [] [_,argvar]) pos = do logBuild " Leaving alloc alone" rawInstr prim pos recordVarSet argvar instr' prim@(PrimForeign "lpvm" "cast" [] [from, to@ArgVar{argVarName=var, argVarFlow=flow}]) pos = do logBuild $ " Expanding cast(" ++ show from ++ ", " ++ show to ++ ")" unless (argFlowDirection from == FlowIn && flow == FlowOut) $ shouldnt "cast instruction with wrong flow" if argType from == argType to then instr' (PrimForeign "llvm" "move" [] [from, to]) pos else ordinaryInstr prim pos instr' prim@(PrimForeign "lpvm" "load" _ [ArgGlobal info _, var]) pos = do logBuild $ " Checking if we know the value of " ++ show info loaded <- gets globalsLoaded case Map.lookup info loaded of Just val -> do logBuild $ " ... we do(" ++ show val ++ "), moving instead" instr' (PrimForeign "llvm" "move" [] [mkInput val, var]) pos Nothing -> do logBuild " ... we don't, need to load" ordinaryInstr prim pos instr' prim@(PrimForeign "lpvm" "store" _ [var, ArgGlobal info _]) pos = do logBuild $ " Checking if we know the value of " ++ show info ++ " and it is the same as " ++ show var mbVal <- Map.lookup info <$> gets globalsLoaded logBuild $ " ... found value " ++ show mbVal case mbVal of Just val | on (==) (mkInput . canonicaliseArg) var val -> do logBuild " ... it is, no need to store" _ -> do logBuild " ... it isn't, we need to store" ordinaryInstr prim pos instr' prim pos = ordinaryInstr prim pos Do the normal work of instr . First check if we 've already computed its -- outputs, and if so, just add a move instruction to reuse the results. -- Otherwise, generate the instruction and record it for reuse. ordinaryInstr :: Prim -> OptPos -> BodyBuilder () ordinaryInstr prim pos = do let (prim',newOuts) = splitPrimOutputs prim logBuild $ "Looking for computed instr " ++ show prim' ++ " ..." currSubExprs <- gets subExprs logBuild $ " with subExprs = " ++ show currSubExprs match <- gets (Map.lookup prim' . subExprs) case match of Nothing -> do -- record prim executed (and other modes), and generate instr logBuild "not found" impurity <- lift $ primImpurity prim let gFlows = snd $ primArgs prim when (impurity <= Pure && gFlows == emptyGlobalFlows) $ recordEntailedPrims prim recordReifications prim rawInstr prim pos mapM_ recordVarSet $ primOutputs prim Just oldOuts -> do -- common subexpr: just need to record substitutions logBuild $ "found it; substituting " ++ show oldOuts ++ " for " ++ show newOuts mapM_ (\(newOut,oldOut) -> primMove (mkInput oldOut) newOut `instr'` pos) $ zip newOuts oldOuts -- | Invert an output arg to be an input arg. mkInput :: PrimArg -> PrimArg mkInput (ArgVar name ty _ _ lst) = ArgVar name ty FlowIn Ordinary False mkInput arg@ArgInt{} = arg mkInput arg@ArgFloat{} = arg mkInput arg@ArgString{} = arg mkInput arg@ArgChar{} = arg mkInput arg@ArgClosure{} = arg mkInput (ArgUnneeded _ ty) = ArgUnneeded FlowIn ty mkInput arg@ArgGlobal{} = arg mkInput arg@ArgUndef{} = arg argExpandedPrim :: Prim -> BodyBuilder Prim argExpandedPrim call@(PrimCall id pspec impurity args gFlows) = do args' <- transformUnneededArgs pspec args return $ PrimCall id pspec impurity args' gFlows argExpandedPrim call@(PrimHigher id fn impurity args) = do logBuild $ "Expanding Higher call " ++ show call fn' <- expandArg fn case fn' of ArgClosure pspec clsd _ -> do pspec' <- fromMaybe pspec <$> lift (maybeGetClosureOf pspec) logBuild $ "As first-order call to " ++ show pspec' params <- lift $ getPrimParams pspec' let args' = zipWith (setArgType . primParamType) params args gFlows <- lift $ getProcGlobalFlows pspec argExpandedPrim $ PrimCall id pspec' impurity (clsd ++ args') gFlows _ -> do logBuild $ "Leaving as higher call to " ++ show fn' args' <- mapM expandArg args return $ PrimHigher id fn' impurity args' argExpandedPrim (PrimForeign lang nm flags args) = do args' <- mapM expandArg args return $ simplifyForeign lang nm flags args' -- |Replace any unneeded arguments corresponding to unneeded parameters with ArgUnneeded . For unneeded * output * parameters , there must be an -- input with the same name. We must set the output argument variable -- to the corresponding input argument, so the value is defined. transformUnneededArgs :: ProcSpec -> [PrimArg] -> BodyBuilder [PrimArg] transformUnneededArgs pspec args = do args' <- mapM expandArg args params <- lift $ primProtoParams <$> getProcPrimProto pspec zipWithM (transformUnneededArg $ zip params args) params args' -- |Replace an unneeded argument corresponding to unneeded parameters with ArgUnneeded . transformUnneededArg :: [(PrimParam,PrimArg)] -> PrimParam -> PrimArg -> BodyBuilder PrimArg transformUnneededArg pairs PrimParam{primParamInfo=ParamInfo{paramInfoUnneeded=True}, primParamFlow=flow, primParamType=typ, primParamName=name} arg = do logBuild $ "Marking unneeded argument " ++ show arg when (isOutputFlow flow) $ do case List.filter (\(p,a)-> primParamName p == name && isInputFlow (primParamFlow p)) pairs of [] -> shouldnt $ "No input param matching output " ++ show name [(_,a)] -> do logBuild $ "Adding move instruction for unneeded output " ++ show arg instr' (PrimForeign "llvm" "move" [] [a, arg]) Nothing _ -> shouldnt $ "Multiple input params match output " ++ show name return $ ArgUnneeded flow typ transformUnneededArg _ _ (ArgClosure pspec args ty) = do args' <- transformUnneededArgs pspec args return $ ArgClosure pspec args' ty transformUnneededArg _ _ arg = return arg |Construct a fake version of a Prim instruction containing only its -- inputs, and with inessential parts canonicalised away. Also return the -- outputs of the instruction. splitPrimOutputs :: Prim -> (Prim, [PrimArg]) splitPrimOutputs prim = let (args, gFlows) = primArgs prim (inArgs,outArgs) = splitArgsByMode args in (canonicalisePrim $ replacePrimArgs prim (canonicaliseArg <$> inArgs) gFlows, outArgs) |Returns a list of all output arguments of the input Prim primOutputs :: Prim -> [PrimArg] primOutputs prim = List.filter (isOutputFlow . argFlowDirection) $ fst $ primArgs prim -- |Add a binding for a variable. If that variable is an output for the -- proc being defined, also add an explicit assignment to that variable. addSubst :: PrimVarName -> PrimArg -> BodyBuilder () addSubst var val = do logBuild $ " adding subst " ++ show var ++ " -> " ++ show val modify (\s -> s { currSubst = Map.insert var val $ currSubst s }) subst <- gets currSubst logBuild $ " new subst = " ++ show subst |Record that the specified arg ( which must be a variable ) has been set . recordVarSet :: PrimArg -> BodyBuilder () recordVarSet ArgVar{argVarName=nm, argVarFlow=flow} | isOutputFlow flow = modify (\s -> s { blockDefs = Set.insert nm $ blockDefs s }) recordVarSet (ArgUnneeded flow _) | isOutputFlow flow = return () recordVarSet arg = shouldnt $ "recordVarSet of non-output argument " ++ show arg |Record all instructions equivalent to the input prim in the lookup table , -- so if we later see an equivalent instruction we don't repeat it but -- reuse the already-computed outputs. This implements common subexpression -- elimination. It can also handle optimisations like recognizing the -- reconstruction of a deconstructed value, and accounts for commutative -- operations and inverse operations. recordEntailedPrims :: Prim -> BodyBuilder () recordEntailedPrims prim = do instrPairs <- (splitPrimOutputs prim:) <$> lift (instrConsequences prim) logBuild $ "Recording computed instrs" ++ List.concatMap (\(p,o)-> "\n " ++ show p ++ " -> " ++ show o) instrPairs modify (\s -> s {subExprs = List.foldr (uncurry Map.insert) (subExprs s) instrPairs}) -- |Return a list of instructions that have effectively already been -- computed, mostly because they are inverses of instructions already -- computed, or because of commutativity. XXX Does n't yet handle multiple modes for PrimCalls instrConsequences :: Prim -> Compiler [(Prim,[PrimArg])] instrConsequences prim = List.map (mapFst canonicalisePrim) <$> instrConsequences' prim instrConsequences' :: Prim -> Compiler [(Prim,[PrimArg])] instrConsequences' (PrimForeign "lpvm" "cast" flags [a1,a2]) = return [(PrimForeign "lpvm" "cast" flags [a2], [a1])] -- XXX this doesn't handle mutate to other fields leaving value unchanged instrConsequences' (PrimForeign "lpvm" "mutate" [] [_,addr,offset,_,size,startOffset,val]) = return [(PrimForeign "lpvm" "access" [] [addr,offset,size,startOffset], [val])] -- XXX handle flags instrConsequences' (PrimForeign "lpvm" "access" [] [struct,offset,size,startOffset,val]) = return [(PrimForeign "lpvm" "mutate" [] [struct,offset,ArgInt 1 intType,size,startOffset, val], [struct]), (PrimForeign "lpvm" "mutate" [] [struct,offset,ArgInt 0 intType,size,startOffset, val], [struct])] instrConsequences' (PrimForeign "llvm" "add" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "sub" flags [a3,a2], [a1]), (PrimForeign "llvm" "sub" flags [a3,a1], [a2]), (PrimForeign "llvm" "add" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "sub" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "add" flags [a3,a2], [a1]), (PrimForeign "llvm" "add" flags [a2,a3], [a1]), (PrimForeign "llvm" "sub" flags [a1,a3], [a2])] instrConsequences' (PrimForeign "llvm" "mul" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "mul" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "fadd" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "fadd" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "fmul" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "fmul" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "and" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "and" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "or" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "or" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_eq" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_eq" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ne" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ne" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_slt" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_sgt" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_sgt" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_slt" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ult" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ugt" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ugt" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ult" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_sle" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_sge" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_sge" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_sle" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ule" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_uge" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_uge" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ule" flags [a2,a1], [a3])] instrConsequences' _ = return [] -- |If this instruction reifies a constrant, record the fact, so that we know -- the constraint (or its negation) holds in contexts where we know the value of the Boolean variable . recordReifications :: Prim -> BodyBuilder () recordReifications (PrimForeign "llvm" instr flags [a1,a2,ArgVar{argVarName=reifVar,argVarFlow=FlowOut}]) = case reification instr a1 a2 of Just constr -> do modify (\s -> s { reifiedConstr = Map.insert reifVar constr $ reifiedConstr s }) logBuild $ "Recording reification " ++ show reifVar ++ " <-> " ++ show constr Nothing -> logBuild "No reification found" recordReifications _ = return () -- |Given an LLVM comparison instruction and its input arguments, return Just -- the coresponding constraint, if there is one; otherwise Nothing. reification :: String -> PrimArg -> PrimArg -> Maybe Constraint reification "icmp_eq" ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} arg = Just $ Equal var ty arg reification "icmp_eq" arg ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} = Just $ Equal var ty arg reification "icmp_ne" ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} arg = Just $ NotEqual var ty arg reification "icmp_ne" arg ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} = Just $ NotEqual var ty arg reification _ _ _ = Nothing -- |Unconditionally add an instr to the current body rawInstr :: Prim -> OptPos -> BodyBuilder () rawInstr prim pos = do logBuild $ "---- adding instruction " ++ show prim validateInstr prim updateGlobalsLoaded prim pos modify $ addInstrToState (maybePlace prim pos) splitArgsByMode :: [PrimArg] -> ([PrimArg], [PrimArg]) splitArgsByMode = List.partition (isInputFlow . argFlowDirection) canonicalisePrim :: Prim -> Prim canonicalisePrim (PrimCall _ nm impurity args gFlows) = PrimCall 0 nm impurity (canonicaliseArg . mkInput <$> args) gFlows canonicalisePrim (PrimHigher _ var impurity args) = PrimHigher 0 (canonicaliseArg $ mkInput var) impurity $ canonicaliseArg . mkInput <$> args canonicalisePrim (PrimForeign lang op flags args) = PrimForeign lang op flags $ List.map (canonicaliseArg . mkInput) args -- |Standardise unimportant info in an arg, so that it is equal to any -- other arg with the same content. canonicaliseArg :: PrimArg -> PrimArg canonicaliseArg ArgVar{argVarName=nm, argVarFlow=fl} = ArgVar nm AnyType fl Ordinary False canonicaliseArg (ArgClosure ms as _) = ArgClosure ms (canonicaliseArg <$> as) AnyType canonicaliseArg (ArgInt v _) = ArgInt v AnyType canonicaliseArg (ArgFloat v _) = ArgFloat v AnyType canonicaliseArg (ArgString v r _) = ArgString v r AnyType canonicaliseArg (ArgChar v _) = ArgChar v AnyType canonicaliseArg (ArgGlobal info _) = ArgGlobal info AnyType canonicaliseArg (ArgUnneeded dir _) = ArgUnneeded dir AnyType canonicaliseArg (ArgUndef _) = ArgUndef AnyType validateInstr :: Prim -> BodyBuilder () validateInstr p@(PrimCall _ _ _ args _) = mapM_ (validateArg p) args validateInstr p@(PrimHigher _ fn _ args) = mapM_ (validateArg p) $ fn:args validateInstr p@(PrimForeign _ _ _ args) = mapM_ (validateArg p) args validateArg :: Prim -> PrimArg -> BodyBuilder () validateArg instr ArgVar{argVarType=ty} = validateType ty instr validateArg instr (ArgInt _ ty) = validateType ty instr validateArg instr (ArgFloat _ ty) = validateType ty instr validateArg instr (ArgString _ _ ty) = validateType ty instr validateArg instr (ArgChar _ ty) = validateType ty instr validateArg instr (ArgClosure _ _ ty) = validateType ty instr validateArg instr (ArgGlobal _ ty) = validateType ty instr validateArg instr (ArgUnneeded _ ty) = validateType ty instr validateArg instr (ArgUndef ty) = validateType ty instr validateType :: TypeSpec -> Prim -> BodyBuilder () validateType InvalidType instr = shouldnt $ "InvalidType in argument of " ++ show instr validateType _ instr = return () Add an instruction to the given BodyState . If unforked , add it at the front -- of the list of instructions, otherwise add it to all branches in the fork. addInstrToState :: Placed Prim -> BodyState -> BodyState addInstrToState ins st@BodyState{buildState=Unforked} = st { currBuild = ins:currBuild st} addInstrToState ins st@BodyState{buildState=bld@Forked{bodies=bods}} = st { buildState = bld {bodies=List.map (addInstrToState ins) bods} } -- |Return the current ultimate value of the specified variable name and type expandVar :: PrimVarName -> TypeSpec -> BodyBuilder PrimArg expandVar var ty = expandArg $ ArgVar var ty FlowIn Ordinary False -- |Return the current ultimate value of the input argument. expandArg :: PrimArg -> BodyBuilder PrimArg expandArg arg@ArgVar{argVarName=var, argVarFlow=flow} | isInputFlow flow = do var' <- gets (Map.lookup var . currSubst) let ty = argVarType arg let var'' = setArgType ty <$> var' logBuild $ "Expanded " ++ show var ++ " to " ++ show var'' maybe (return arg) expandArg var'' expandArg arg@ArgVar{argVarName=var, argVarFlow=flow} | isOutputFlow flow = do var' <- gets (Map.findWithDefault var var . outSubst) when (var /= var') $ logBuild $ "Replaced output variable " ++ show var ++ " with " ++ show var' return arg{argVarName=var'} expandArg arg@(ArgClosure ps as ty) = do as' <- mapM expandArg as return $ ArgClosure ps as' ty expandArg arg = return arg updateGlobalsLoaded :: Prim -> OptPos -> BodyBuilder () updateGlobalsLoaded prim pos = do loaded <- gets globalsLoaded case prim of PrimForeign "lpvm" "load" _ [ArgGlobal info _, var] -> modify $ \s -> s{globalsLoaded=Map.insert info var loaded} PrimForeign "lpvm" "store" _ [var, ArgGlobal info _] -> modify $ \s -> s{globalsLoaded=Map.insert info var loaded} _ -> do let gFlows = snd $ primArgs prim logBuild $ "Call has global flows: " ++ show gFlows let filter info _ = not $ hasGlobalFlow gFlows FlowOut info modify $ \s -> s {globalsLoaded=Map.filterWithKey filter loaded} loaded' <- gets globalsLoaded when (loaded /= loaded') $ do logBuild $ "Globals Loaded: " ++ simpleShowMap loaded logBuild $ " -> " ++ simpleShowMap loaded' ---------------------------------------------------------------- ---------------------------------------------------------------- -- |Transform primitives with all inputs known into a move instruction by -- performing the operation at compile-time. simplifyForeign :: String -> ProcName -> [Ident] -> [PrimArg] -> Prim simplifyForeign "llvm" op flags args = simplifyOp op flags args simplifyForeign lang op flags args = PrimForeign lang op flags args | Simplify and instructions where possible . This -- handles constant folding and simple (single-operation) algebraic -- simplifications (left and right identities and annihilators). -- Commutative ops are canonicalised by putting the smaller argument first , but only for integer ops . Integer inequalities are canonicalised by putting smaller argument first and flipping -- comparison if necessary. simplifyOp :: ProcName -> [Ident] -> [PrimArg] -> Prim Integer ops simplifyOp "add" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1+n2) ty) output simplifyOp "add" _ [ArgInt 0 ty, arg, output] = primMove arg output simplifyOp "add" _ [arg, ArgInt 0 ty, output] = primMove arg output simplifyOp "add" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "add" flags [arg2, arg1, output] simplifyOp "sub" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1-n2) ty) output simplifyOp "sub" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "mul" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1*n2) ty) output simplifyOp "mul" _ [ArgInt 1 ty, arg, output] = primMove arg output simplifyOp "mul" _ [arg, ArgInt 1 ty, output] = primMove arg output simplifyOp "mul" _ [ArgInt 0 ty, _, output] = primMove (ArgInt 0 ty) output simplifyOp "mul" _ [_, ArgInt 0 ty, output] = primMove (ArgInt 0 ty) output simplifyOp "mul" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "mul" flags [arg2, arg1, output] simplifyOp "div" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1 `div` n2) ty) output simplifyOp "div" _ [arg, ArgInt 1 _, output] = primMove arg output Bitstring ops simplifyOp "and" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (fromIntegral n1 .&. fromIntegral n2) ty) output simplifyOp "and" _ [ArgInt 0 ty, _, output] = primMove (ArgInt 0 ty) output simplifyOp "and" _ [_, ArgInt 0 ty, output] = primMove (ArgInt 0 ty) output simplifyOp "and" _ [ArgInt (-1) _, arg, output] = primMove arg output simplifyOp "and" _ [arg, ArgInt (-1) _, output] = primMove arg output simplifyOp "and" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "and" flags [arg2, arg1, output] simplifyOp "or" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (fromIntegral n1 .|. fromIntegral n2) ty) output simplifyOp "or" _ [ArgInt (-1) ty, _, output] = primMove (ArgInt (-1) ty) output simplifyOp "or" _ [_, ArgInt (-1) ty, output] = primMove (ArgInt (-1) ty) output simplifyOp "or" _ [ArgInt 0 _, arg, output] = primMove arg output simplifyOp "or" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "or" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "or" flags [arg2, arg1, output] simplifyOp "xor" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (fromIntegral n1 `xor` fromIntegral n2) ty) output simplifyOp "xor" _ [ArgInt 0 _, arg, output] = primMove arg output simplifyOp "xor" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "xor" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "xor" flags [arg2, arg1, output] simplifyOp "shl" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1 `shiftL` fromIntegral n2) ty) output simplifyOp "shl" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "shl" _ [arg@(ArgInt 0 _), _, output] = primMove arg output simplifyOp "ashr" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1 `shiftR` fromIntegral n2) ty) output simplifyOp "ashr" _ [arg, ArgInt 0 _, output] = primMove arg output -- XXX Need to convert both to unsigned before shifting simplifyOp " lshr " _ [ ArgInt n1 ty , ArgInt n2 _ , output ] = primMove ( ArgInt ( n1 ` shiftR ` fromIntegral n2 ) ty ) output simplifyOp "lshr" _ [arg, ArgInt 0 _, output] = primMove arg output Integer comparisons , including special handling of unsigned comparison to 0 simplifyOp "icmp_eq" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1==n2) output simplifyOp "icmp_eq" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_eq" flags [arg2, arg1, output] simplifyOp "icmp_ne" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1/=n2) output simplifyOp "icmp_ne" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ne" flags [arg2, arg1, output] simplifyOp "icmp_slt" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1<n2) output simplifyOp "icmp_slt" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_sgt" flags [arg2, arg1, output] simplifyOp "icmp_sle" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1<=n2) output simplifyOp "icmp_sle" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_sge" flags [arg2, arg1, output] simplifyOp "icmp_sgt" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1>n2) output simplifyOp "icmp_sgt" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_slt" flags [arg2, arg1, output] simplifyOp "icmp_sge" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1>=n2) output simplifyOp "icmp_sge" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_sle" flags [arg2, arg1, output] simplifyOp "icmp_ult" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'<n2') output simplifyOp "icmp_ult" _ [_, ArgInt 0 _, output] = -- nothing is < 0 primMove (ArgInt 0 boolType) output only 0 is < 1 PrimForeign "llvm" "icmp_eq" flags [a1,ArgInt 0 ty,output] simplifyOp "icmp_ult" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ugt" flags [arg2, arg1, output] simplifyOp "icmp_ule" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'<=n2') output simplifyOp "icmp_ule" _ [ArgInt 0 _, _, output] = -- 0 is <= everything primMove (ArgInt 1 boolType) output 1 is < = all but 0 PrimForeign "llvm" "icmp_ne" flags [ArgInt 0 ty,a2,output] simplifyOp "icmp_ule" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_uge" flags [arg2, arg1, output] simplifyOp "icmp_ugt" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'>n2') output simplifyOp "icmp_ugt" _ [ArgInt 0 _, _, output] = -- 0 is > nothing primMove (ArgInt 0 boolType) output 1 is > only 0 PrimForeign "llvm" "icmp_eq" flags [ArgInt 0 ty,a2,output] simplifyOp "icmp_ugt" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ult" flags [arg2, arg1, output] simplifyOp "icmp_uge" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'>=n2') output everything is > = 0 primMove (ArgInt 1 boolType) output all but 0 is > = 1 PrimForeign "llvm" "icmp_ne" flags [a1,ArgInt 0 ty,output] simplifyOp "icmp_uge" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ule" flags [arg2, arg1, output] -- Float ops simplifyOp "fadd" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1+n2) ty) output simplifyOp "fadd" _ [ArgFloat 0 _, arg, output] = primMove arg output simplifyOp "fadd" _ [arg, ArgFloat 0 _, output] = primMove arg output simplifyOp "fsub" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1-n2) ty) output simplifyOp "fsub" _ [arg, ArgFloat 0 _, output] = primMove arg output simplifyOp "fmul" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1*n2) ty) output simplifyOp "fmul" _ [arg, ArgFloat 1 _, output] = primMove arg output simplifyOp "fmul" _ [ArgFloat 1 _, arg, output] = primMove arg output We do n't handle float * 0.0 because of the semantics of IEEE floating mult . simplifyOp "fdiv" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1/n2) ty) output simplifyOp "fdiv" _ [arg, ArgFloat 1 _, output] = primMove arg output -- Float comparisons simplifyOp "fcmp_eq" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1==n2) output simplifyOp "fcmp_ne" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1/=n2) output simplifyOp "fcmp_slt" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1<n2) output simplifyOp "fcmp_sle" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1<=n2) output simplifyOp "fcmp_sgt" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1>n2) output simplifyOp "fcmp_sge" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1>=n2) output simplifyOp name flags args = PrimForeign "llvm" name flags args boolConstant :: Bool -> PrimArg boolConstant bool = ArgInt (fromIntegral $ fromEnum bool) boolType ---------------------------------------------------------------- Fusing Forks in BodyStates -- BodyStates allow code to follow a branch ; this code injects subsequent code -- at the end of previous code. Crucially, it also uses information about fixed -- variable values from earlier forks to specialise following forks. In particular , when appending a fork to the end of an earlier fork , it is often -- possible to determine the branch that will be selected in the later fork, -- avoiding the need for the test. This has the effect of fusing successive -- forks on the same variable into a single fork. -- -- This code ensures that code is compatible with LPVM form by producing a BodyState that has no parent , and where all the bodies recursively within the BuildState also have no parent . ---------------------------------------------------------------- | Recursively fuse Bodystate , as described above . fuseBodies :: BodyState -> Compiler BodyState fuseBodies st@BodyState{parent=Nothing, buildState=bst} = do logMsg BodyBuilder $ "Fusing origin bodyState:" ++ fst (showState 4 st) bst' <- fuseBranches bst let st' = st {buildState = bst'} logMsg BodyBuilder $ "Fused origin state:" ++ fst (showState 4 st') return st' fuseBodies st@BodyState{parent=Just par, buildState=bst} = do logMsg BodyBuilder $ "Fusing child bodyState:" ++ fst (showState 4 st) par' <- fuseBodies par st' <- addBodyContinuation par' $ st {parent=Nothing} logMsg BodyBuilder $ "Fused child state:" ++ fst (showState 4 st') return st' fuseBranches :: BuildState -> Compiler BuildState fuseBranches Unforked = return Unforked fuseBranches bst@Forked{forkingVar=var,bodies=bods} = do logMsg BodyBuilder $ "Fusing branches of fork on " ++ show var bods' <- mapM fuseBodies $ bodies bst return $ bst {bodies=bods'} | Add the second BodyState at the end of the first . The second BodyState is -- known to be a tree, ie, its parent is Nothing, and its branches, if it has -- any, have been fused. addBodyContinuation :: BodyState -> BodyState -> Compiler BodyState addBodyContinuation _ next@BodyState{parent=Just _} = shouldnt $ "addBodyContinuation with non-singular second argument:" ++ fst (showState 4 next) addBodyContinuation prev@BodyState{buildState=Unforked, currBuild=bld, currSubst=subst, blockDefs=defs, outSubst=osubst} next = do logMsg BodyBuilder $ "Adding state:" ++ fst (showState 4 next) logMsg BodyBuilder $ "... after unforked body:" ++ fst (showState 4 prev) addSelectedContinuation bld subst defs osubst next addBodyContinuation prev@BodyState{buildState=Forked{}} next = do logMsg BodyBuilder $ "Adding state:" ++ fst (showState 4 next) logMsg BodyBuilder $ "... after forked body:" ++ fst (showState 4 prev) let build = buildState prev bods <- mapM (`addBodyContinuation` next) $ bodies build return $ prev {buildState = build {bodies = bods}} -- | Add the appropriate branch(es) to follow the specified list of prims, which -- includes both the prims of the previous unforked body and the unforked part -- of the following addSelectedContinuation :: [Placed Prim] -> Substitution -> Set PrimVarName -> VarSubstitution -> BodyState -> Compiler BodyState XXX Must merge subst with currSubst of st addSelectedContinuation prevPrims subst defs osubst st@BodyState{buildState=Unforked} = do let subst' = Map.union (currSubst st) subst let defs' = Set.union (blockDefs st) defs let oSubst' = Map.union (outSubst st) osubst let st' = st { currBuild = currBuild st ++ prevPrims , currSubst = subst' , blockDefs = defs' , outSubst = oSubst' } logMsg BodyBuilder $ "Adding unforked continuation produces:" ++ fst (showState 4 st') return st' addSelectedContinuation prevPrims subst defs osubst st@BodyState{buildState=bst@Forked{}} = do let subst' = Map.union (currSubst st) subst let defs' = Set.union (blockDefs st) defs let osubst' = Map.union (outSubst st) osubst case selectedBranch subst bst of Nothing -> do bst <- fuseBranches $ buildState st let st' = st { currBuild = currBuild st ++ prevPrims , currSubst = subst' , blockDefs = defs' , outSubst = osubst' , buildState = bst } logMsg BodyBuilder $ "No fork selection possible, producing:" ++ fst (showState 4 st') return st' Just branchNum -> do let selectedBranch = revSelectElt branchNum $ bodies bst logMsg BodyBuilder $ "Selected branch " ++ show branchNum selectedBranch' <- fuseBodies selectedBranch addSelectedContinuation (currBuild st ++ prevPrims) subst' defs' osubst' selectedBranch' -- |Given a variable substitution, determine which branch will be selected, -- if possible. selectedBranch :: Substitution -> BuildState -> Maybe Integer selectedBranch subst Unforked = Nothing selectedBranch subst Forked{knownVal=known, forkingVar=var} = known `orElse` (Map.lookup var subst >>= argIntegerValue) ---------------------------------------------------------------- Reassembling the ProcBody -- Once we 've built up a BodyState , this code assembles it into a new ProcBody . -- While we're at it, we also mark the last use of each variable, eliminate -- calls that don't produce any output needed later in the body, and eliminate -- any move instruction that moves a variable defined in the same block as the -- move and not used after the move. Most other move instructions were removed while building BodyState , but that approach can not eliminate moves to output -- parameters. ---------------------------------------------------------------- currBody :: ProcBody -> BodyState -> Compiler (Int,Set PrimVarName,Set GlobalInfo,ProcBody) currBody body st@BodyState{tmpCount=tmp} = do logMsg BodyBuilder $ "Now reconstructing body with usedLater = " ++ intercalate ", " (show <$> Map.keys (outSubst st)) st' <- execStateT (rebuildBody st) $ BkwdBuilderState (Map.keysSet $ outSubst st) Nothing Map.empty 0 Set.empty body let BkwdBuilderState{bkwdUsedLater=usedLater, bkwdFollowing=following, bkwdGlobalStored=stored} = st' logMsg BodyBuilder ">>>> Finished rebuilding a proc body" logMsg BodyBuilder " Final state:" logMsg BodyBuilder $ showBlock 5 following return (tmp, usedLater, stored, following) -- |Another monad, this one for rebuilding a proc body bottom-up. type BkwdBuilder = StateT BkwdBuilderState Compiler -- |BkwdBuilderState is used to store context info while building a ProcBody backwards from a BodyState , itself the result of rebuilding a ProcBody -- forwards. Because construction runs backwards, the state mostly holds -- information about the following code. data BkwdBuilderState = BkwdBuilderState { bkwdUsedLater :: Set PrimVarName, -- ^Vars used later in computation, -- but not defined later bkwdBranchesUsedLater :: Maybe [Set PrimVarName], -- ^The usedLater set for each -- following branch, used for fused -- branches. bkwdRenaming :: VarSubstitution, -- ^Variable substitution to apply bkwdTmpCount :: Int, -- ^Highest temporary variable number bkwdGlobalStored :: Set GlobalInfo, -- ^The set of globals we have -- recently stored bkwdFollowing :: ProcBody -- ^Code to come later } deriving (Eq,Show) rebuildBody :: BodyState -> BkwdBuilder () rebuildBody st@BodyState{parent=Just par} = shouldnt $ "Body parent left by fusion: " ++ fst (showState 4 par) rebuildBody st@BodyState{currBuild=prims, currSubst=subst, blockDefs=defs, buildState=bldst, parent=Nothing, reifiedConstr=reif} = do usedLater <- gets bkwdUsedLater following <- gets bkwdFollowing logBkwd $ "Rebuilding body:" ++ fst (showState 8 st) ++ "\nwith currSubst = " ++ simpleShowMap subst ++ "\n usedLater = " ++ simpleShowSet usedLater ++ "\n currBuild = " ++ showPlacedPrims 17 prims case bldst of Unforked -> mapM_ (placedApply (bkwdBuildStmt defs)) prims Forked{complete=False} -> shouldnt "Building proc body for bodystate with incomplete fork" Forked var ty fixedval fused b d True -> do let bods = reverse b case fixedval of Just val -> do rebuildBody $ selectElt val bods mapM_ (placedApply (bkwdBuildStmt defs)) prims Nothing -> do -- XXX Perhaps we should generate a new proc for the parent par in -- cases where it's more than a few prims. (prims', var', ty', bods', deflt') <- rebuildSwitch prims var ty bods d reif sts <- mapM (rebuildBranch subst) bods' deflt'' <- mapM (rebuildBranch subst) deflt' usedLater' <- gets bkwdUsedLater let sts' = sts ++ maybeToList deflt'' let usedLaters = bkwdUsedLater <$> sts' -- XXX Not right! When processing the prims prior to each fork -- being assembled into a switch, we must only consider the -- usedLater set from *following* code. Doing the following winds up keeping Undef assignments to variables that will be assigned -- later if they are needed. let usedLater'' = List.foldr Set.union usedLater' usedLaters let branchesUsedLater = if fused then Just usedLaters else Nothing logBkwd $ "Switch on " ++ show var' ++ " with " ++ show (length sts) ++ " branches" ++ if isJust deflt' then " and a default" else "" logBkwd $ " usedLater = " ++ simpleShowSet usedLater'' logBkwd $ " branchesUsedLater = " ++ show branchesUsedLater let lastUse = Set.notMember var' usedLater'' let usedLater''' = Set.insert var' usedLater'' let tmp = maximum $ List.map bkwdTmpCount sts' let followingBranches = List.map bkwdFollowing sts let gStored = List.foldr1 Set.intersection (bkwdGlobalStored <$> sts') put $ BkwdBuilderState usedLater''' branchesUsedLater Map.empty tmp gStored $ ProcBody [] $ PrimFork var' ty' lastUse followingBranches (bkwdFollowing <$> deflt'') mapM_ (placedApply (bkwdBuildStmt defs)) prims' finalUsedLater <- gets bkwdUsedLater logBkwd $ "Finished rebuild with usedLater = " ++ show finalUsedLater |Select the element of specified by num selectElt :: Integral a => a -> [b] -> b selectElt num bods = if num' >= 0 && num' < length bods then bods !! num' else shouldnt $ "Out-of-bounds fixed value in fork " ++ show num' where num' = fromIntegral num |Select the element of , which is reversed , by num revSelectElt :: Integral a => a -> [b] -> b revSelectElt num revBods = selectElt (length revBods - 1 - fromIntegral num) revBods -- | Try to turn nested branches into a single switch, where we have a nested -- elseif ... elseif ... elseif ... else structure, and the tests are equality -- tests about the same variable. We also handle nested cases of disequalities -- where we look instead for cascading on the then instead of else branches. -- Arguments are straight-line code preceding the tests, the variable switched -- on and its type, the branches for the current fork, and the current default branch . NB : the straight line code is in reversed order at this point , but -- branches are in normal order. Returns Nothing if we can't convert the fork -- into a switch, or Just a tuple of the straight line code, the switch variable -- and its type, the branches, and the default branch. rebuildSwitch :: [Placed Prim] -> PrimVarName -> TypeSpec -> [BodyState] -> Maybe BodyState -> Map PrimVarName Constraint -> BkwdBuilder ([Placed Prim], PrimVarName, TypeSpec, [BodyState], Maybe BodyState) rebuildSwitch prims var ty branches@[branch0,branch1] Nothing reif = do logBkwd $ "Rebuild fork on " ++ show var ++ ", reified from " ++ show (Map.lookup var reif) case Map.lookup var reif of Nothing -> return (prims, var, ty, branches, Nothing) Just (Equal var' ty' (ArgInt val _)) -> do sw <- rebuildSwitch' prims var' ty' branch0 $ Map.singleton val branch1 return $ fromMaybe (prims, var, ty, branches, Nothing) sw Just (NotEqual var' ty' (ArgInt val _)) -> do sw <- rebuildSwitch' prims var' ty' branch1 $ Map.singleton val branch0 return $ fromMaybe (prims, var, ty, branches, Nothing) sw _ -> return (prims, var, ty, branches, Nothing) rebuildSwitch prims var ty branches deflt _ = return (prims, var, ty, branches, deflt) -- | Try to add more cases to a switch. rebuildSwitch' :: [Placed Prim] -> PrimVarName -> TypeSpec -> BodyState -> Map Integer BodyState -> BkwdBuilder (Maybe ([Placed Prim], PrimVarName, TypeSpec, [BodyState], Maybe BodyState)) rebuildSwitch' prims var ty st@BodyState{buildState=bldst@(Forked v _ _ _ [b1,b0] _ _), parent=Nothing, currBuild=prims', reifiedConstr=reif} cases | isJust constr = do logBkwd $ "Rebuild nested fork on " ++ show v ++ ", reified from " ++ show constr case fromJust constr of Equal var' _ (ArgInt val _) | var == var' -> rebuildSwitch' prims'' var ty b0 $ Map.insert val b1 cases NotEqual var' _ (ArgInt val _) | var == var' -> rebuildSwitch' prims'' var ty b1 $ Map.insert val b0 cases _ -> completeSwitch prims'' var ty st cases where constr = Map.lookup v reif -- XXX must check that it's OK to combine prims. prims'' = prims' ++ prims rebuildSwitch' prims var ty st cases = do logBkwd $ "Nested branch not switching on " ++ show var case buildState st of Forked{forkingVar=v} -> logBkwd $ " Fork on " ++ show v ++ ", where " ++ show cases Unforked -> logBkwd " Not a fork" completeSwitch prims var ty st cases -- | Finish building a switch, if there are enough branches for it to be -- worthwhile. completeSwitch :: [Placed Prim] -> PrimVarName -> TypeSpec -> BodyState -> Map Integer BodyState -> BkwdBuilder (Maybe ([Placed Prim], PrimVarName, TypeSpec, [BodyState], Maybe BodyState)) completeSwitch prims var ty deflt cases | Map.size cases >= minimumSwitchCases = do let cases' = Map.toAscList cases let maxCase = fst $ last cases' if (fst <$> cases') == [0..maxCase] then do logBkwd $ "Producing switch with cases " ++ show (fst <$> cases') ++ " and a default" logBkwd $ "Switch variable type: " ++ show ty switchVarRep <- lift $ lookupTypeRepresentation ty let maxPossible = 2^(maybe wordSize typeRepSize switchVarRep)-1 logBkwd $ "Max possible switch var value: " ++ show maxPossible return $ Just (prims, var, ty, snd <$> cases', if maxPossible >= maxCase then Nothing else Just deflt) else do logBkwd $ "Not producing switch: non-dense cases " ++ show (fst <$> cases') return Nothing -- XXX generalise to handle more switches | otherwise = do logBkwd $ "Not producing switch (only " ++ show (Map.size cases) ++ " case(s))" return Nothing rebuildBranch :: Substitution -> BodyState -> BkwdBuilder BkwdBuilderState rebuildBranch subst bod = do bkwdSt <- get lift $ execStateT (rebuildBody bod) bkwdSt bkwdBuildStmt :: Set PrimVarName -> Prim -> OptPos -> BkwdBuilder () bkwdBuildStmt defs prim pos = do usedLater <- gets bkwdUsedLater renaming <- gets bkwdRenaming gStored <- gets bkwdGlobalStored logBkwd $ " Rebuilding prim: " ++ show prim ++ "\n with usedLater = " ++ show usedLater ++ "\n and bkwdRenaming = " ++ simpleShowMap renaming ++ "\n and defs = " ++ simpleShowSet defs ++ "\n and globalStored = " ++ simpleShowSet gStored let (args, gFlows) = primArgs prim args' <- mapM renameArg args logBkwd $ " renamed args = " ++ show args' case (prim,args') of (PrimForeign "llvm" "move" [] _, [ArgVar{argVarName=fromVar}, ArgVar{argVarName=toVar}]) | Set.notMember fromVar usedLater && Set.member fromVar defs -> modify $ \s -> s { bkwdRenaming = Map.insert fromVar toVar $ bkwdRenaming s } _ -> do let (ins, outs) = splitArgsByMode $ List.filter argIsVar $ flattenArgs args' let gOuts = globalFlowsOut gFlows purity <- lift $ primImpurity prim -- Filter out pure instructions that produce no needed outputs nor -- out flowing globals that arent stored to later when (purity > Pure || any (`Set.member` usedLater) (argVarName <$> outs) || not (USet.isEmpty $ whenFinite (Set.\\ gStored) gOuts)) $ do -- XXX Careful: probably shouldn't mark last use of variable -- passed as input argument more than once in the call let prim' = replacePrimArgs prim (markIfLastUse usedLater <$> args') gFlows logBkwd $ " updated prim = " ++ show prim' -- Don't consider variables assigned here to be used later. -- Variables should only be assigned once, but rearranging nested forks into a switch can move Undef assignments in -- front of real assignments, and we want those to be considered -- to be unneeded. let usedLater' = List.foldr Set.insert (List.foldr Set.delete usedLater $ argVarName <$> outs) $ argVarName <$> ins Add all globals that FlowOut from this prim , then remove all that FlowIn FlowOut means it is overwritten , FlowIn means the value may be read let gStored' = Set.filter (not . hasGlobalFlow gFlows FlowIn) $ gStored `Set.union` USet.toSet Set.empty gOuts st@BkwdBuilderState{bkwdFollowing=bd@ProcBody{bodyPrims=prims}} <- get put $ st { bkwdFollowing = bd { bodyPrims = maybePlace prim' pos : prims }, bkwdUsedLater = usedLater', bkwdGlobalStored = gStored' } renameArg :: PrimArg -> BkwdBuilder PrimArg renameArg arg@ArgVar{argVarName=name} = do name' <- gets (Map.findWithDefault name name . bkwdRenaming) return $ arg {argVarName=name'} renameArg (ArgClosure ps args ts) = do args' <- mapM renameArg args return $ ArgClosure ps args' ts renameArg arg = return arg flattenArgs :: [PrimArg] -> [PrimArg] flattenArgs = concatMap flattenArg flattenArg :: PrimArg -> [PrimArg] flattenArg arg@(ArgClosure _ as ts) = arg:flattenArgs as flattenArg arg = [arg] markIfLastUse :: Set PrimVarName -> PrimArg -> PrimArg markIfLastUse usedLater arg@ArgVar{argVarName=nm,argVarFlow=flow} | isInputFlow flow = arg {argVarFinal=Set.notMember nm usedLater} markIfLastUse _ arg = arg ---------------------------------------------------------------- -- Logging ---------------------------------------------------------------- -- |Log a message, if we are logging body building activity. logBuild :: String -> BodyBuilder () logBuild s = lift $ logMsg BodyBuilder s -- |Log a message, if we are logging body building activity. logBkwd :: String -> BkwdBuilder () logBkwd s = lift $ logMsg BodyBuilder s -- | Log the current builder state logState :: BodyBuilder () logState = do st <- get logBuild $ " Current state:" ++ fst (showState 8 st) return () -- | Show the current builder state. Since the builder builds upside down, we -- start by showing the parent, then we show the current state. showState :: Int -> BodyState -> (String,Int) showState indent BodyState{parent=par, currBuild=revPrims, buildState=bld, blockDefs=defs, forkConsts=consts, currSubst=substs, globalsLoaded=loaded, reifiedConstr=reifs} = let (str ,indent') = maybe ("",indent) (mapFst (++ (startLine indent ++ "----------")) . showState indent) par substStr = startLine indent ++ "# Substs : " ++ simpleShowMap substs globalStr = startLine indent ++ "# Loaded globals : " ++ simpleShowMap loaded str' = showPlacedPrims indent' (reverse revPrims) sets = if List.null revPrims then "" else startLine indent ++ "# Vars defined: " ++ simpleShowSet defs suffix = case bld of Forked{} -> startLine indent ++ "# Fusion consts: " ++ show consts _ -> "" reifstr = startLine indent ++ "# Reifications : " ++ showReifications reifs (str'',indent'') = showBuildState indent' bld in (str ++ str' ++ substStr ++ sets ++ globalStr ++ str'' ++ suffix ++ reifstr , indent'') -- | Show the current reifications showReifications :: Map PrimVarName Constraint -> String showReifications reifs = intercalate ", " [show k ++ " <-> " ++ show c | (k,c) <- Map.assocs reifs] -- | Show the current part of a build state. showBuildState :: Int -> BuildState -> (String,Int) showBuildState indent Unforked = ("", indent) showBuildState indent (Forked var ty val fused bodies deflt complete) = let intro = showSwitch indent var ty val fused content = showBranches indent 0 complete (reverse bodies) deflt indent' = indent + 4 in (intro++content,indent') -- | Show a list of branches of a build state. showBranches :: Int -> Int -> Bool -> [BodyState] -> Maybe BodyState -> String showBranches indent bodyNum False [] Nothing = showCase indent bodyNum ++ "..." showBranches indent bodyNum False [] (Just d) = shouldnt "Incomplete fork with default: " ++ show d showBranches indent bodyNum True [] deflt = maybe "" (((startLine indent ++ "else::") ++) . fst . showState (indent+4)) deflt showBranches indent bodyNum complete (body:bodies) deflt = showCase indent bodyNum ++ fst (showState (indent+4) body) ++ showBranches indent (bodyNum+1) complete bodies deflt -- | Show a single branch of a build state showCase indent bodyNum = startLine indent ++ show bodyNum ++ "::" -- | Show the fork part of a build state showSwitch indent var ty val fused = startLine indent ++ "case " ++ show var ++ ":" ++ show ty ++ (if fused then " (fused)" else " (not fused)") ++ maybe "" (\v-> " (=" ++ show v ++ ")") val ++ " of" -- | Start a new line with the specified indent. startLine :: Int -> String startLine tab = '\n' : replicate tab ' '
null
https://raw.githubusercontent.com/pschachte/wybe/7914ff3bd3649fb22b3e6d884f46ef95f6effb0d/src/BodyBuilder.hs
haskell
File : BodyBuilder.hs Purpose : A monad to build up a procedure Body, with copy propagation : LICENSE in the root directory of this project. -------------------------------------------------------------- The BodyBuilder Monad buildBody runs the monad, producing a ProcBody. instr adds a single instruction to then end of the procBody being built. buildFork initiates a fork on a specified variable beginBranch starts a new branch of the current fork completeFork completes the current fork A ProcBody is considered to have a unique continuation if it either does not end in a branch, or if all but at most one of the branches it ends with ends with a definite failure (a PrimTest (ArgInt 0 _)). a unique continuation. A new fork can be built within a branch, but must be completed before the branch is ended. The ProcBody type does not support having anything follow a fork. Once a ProcBody forks, the branches do not join again. Instead, each branch of a fork should end with a call to another proc, which does whatever should come after the fork. To handle this, once a fork is completed, the completed fork as the prev of the Unforked sequence. This also permits a fork to follow the Unforked sequence which follows a fork. When producing the final ProcBody, if the current Unforked sequence is short (or empty) and there is a prev fork, we simply add the sequence to the end of each of branch of the fork and remove the Unforked sequence. If it is not short and there is a prev, we create a fresh proc whose input arguments are all the live variables, whose outputs are the current proc's outputs, and whose body is built from Unforked sequence, add a call to this fresh proc to each branch of We handle a Forked sequence by generating a ProcBody for each branch, collecting these as the branches of a ProcBody, and taking the the ProcBody. Note that for convenience/efficiency, we collect the instructions in a sequence and the branches in a fork in reverse order, so these are reversed when converting to a ProcBody. particular, we keep track of variable=variable assignments, and replace references to the destination (left) variable with the source (right) variable. This usually leaves the assignment dead, to be removed in a later pass. We also keep track of previous instructions, and later calls to the same instructions with the same inputs are replaced by assignments to the outputs with the old outputs. We also handle some We also maintain a counter for temporary variable names. fork, and after each new branch is created. Instructions can just be added to this. Forked is used after a new fork is begun and before its and after the fork is completed. New instructions can be added and new forks built only when in the Unforked state. In the Forked state, we can only create a new branch. These constructors are used in a zipper-like structure, where the top of the structure is the part we're building, and below that is the parent, ie, the fork structure of which it's a part. This is implemented as follows: Forked state, with the old state as its origin and an empty list of bodies. The new parent is the same as the old one. beginBranch is called when the state is Forked. It creates a new Unforked state with the old state as parent. adds the current state to the parent state's list of bodies and makes that the new state. completeFork is called when the state is Forked. It doesn't change the state. -------------------------------------------------------------- Holds the content of a ProcBody while we're building it. ^The body we're building, reversed ^variable substitutions to propagate ^All variables defined in this block ^Consts in some branches of prev fork ^Substitutions for var assignments ^Previously computed calls to reuse ^True if this body always fails ^The next temp variable number to use ^The fork at the bottom of this node ^What comes before/above this ^The set of globals that we currently know the value of ^Still building; ready for more instrs ^Variable that selects branch to take ^Type of forkingVar ^Definite value of forkingVar if known branch in the parent fork, so this fork will be fused with parent fork ^Rev'd BodyStates of branches so far ^Body of the default fork branch ^Whether the fork has been completed ^Building a new fork | A mapping from variables to definite values, in service to constant propagation. | A mapping from variables to their renamings. This is in service to variable elimination. To handle common subexpression elimination, we keep a map from previous calls with their outputs removed. This type encapsulates |Allocate the next temp variable name and ensure it's not allocated again -------------------------------------------------------------- Tracking Integer Constraints We maintain constraints on integer variables, in particular to handle reified separate value, and conditionals are always based on those reified values. This code allows us to remember what constraint stems from the reified value, so we can use that information in conditionals. For now we only support equality and disequality, as these are most useful. -------------------------------------------------------------- negateConstraint :: Constraint -> Constraint negateConstraint (Equal v n) = NotEqual v n -------------------------------------------------------------- -------------------------------------------------------------- final temp variable count and the set of variables used in the body. |Start a new fork on var of type ty fork variable value known at compile-time statically unknown result |Complete a fork previously initiated by buildFork. let branchMap = List.foldr1 (Map.intersectionWith Set.union) Variables set to the same constant in every branch Variables with a constant value in each branch. These can be used later to fuse branches of subsequent forks on those variables with this fork. Prepare for any instructions coming after the fork |Start a new branch for the next integer value of the switch variable. |End the current branch. child to no longer list it as parent | Record whatever we can deduce from our current branch variable and branch number, based on previously computed reified constraints. | Test if the specified variable is bound to the specified constant in the |Return Just the known value of the specified variable, or Nothing variable (unknown) result |Add an instruction to the current body, after applying the current substitution. If it's a move instruction, add it to the current substitution. ignore if we've already failed Actually do the work of instr XXX since we're recording the subst, so this instr will be removed later, can we just not generate it? The following equation is a bit of a hack to work around not threading a heap through the code, which causes the compiler to try to reuse the results of calls to alloc. Since the mutate primitives already have an output value, that should stop us from trying to reuse modified structures or the results of calls to access after a structure is modified, so alloc should be the only problem that needs fixing. We don't want to fix this by threading a heap through, because it's fine to reorder calls to alloc. We can't handle this with impurity because if we forgot the impurity modifier on any alloc, disaster would ensue, and an impure alloc wouldn't be removed if the structure weren't needed, which we want. outputs, and if so, just add a move instruction to reuse the results. Otherwise, generate the instruction and record it for reuse. record prim executed (and other modes), and generate instr common subexpr: just need to record substitutions | Invert an output arg to be an input arg. |Replace any unneeded arguments corresponding to unneeded parameters with input with the same name. We must set the output argument variable to the corresponding input argument, so the value is defined. |Replace an unneeded argument corresponding to unneeded parameters with inputs, and with inessential parts canonicalised away. Also return the outputs of the instruction. |Add a binding for a variable. If that variable is an output for the proc being defined, also add an explicit assignment to that variable. so if we later see an equivalent instruction we don't repeat it but reuse the already-computed outputs. This implements common subexpression elimination. It can also handle optimisations like recognizing the reconstruction of a deconstructed value, and accounts for commutative operations and inverse operations. |Return a list of instructions that have effectively already been computed, mostly because they are inverses of instructions already computed, or because of commutativity. XXX this doesn't handle mutate to other fields leaving value unchanged XXX handle flags |If this instruction reifies a constrant, record the fact, so that we know the constraint (or its negation) holds in contexts where we know the value of |Given an LLVM comparison instruction and its input arguments, return Just the coresponding constraint, if there is one; otherwise Nothing. |Unconditionally add an instr to the current body |Standardise unimportant info in an arg, so that it is equal to any other arg with the same content. of the list of instructions, otherwise add it to all branches in the fork. |Return the current ultimate value of the specified variable name and type |Return the current ultimate value of the input argument. -------------------------------------------------------------- -------------------------------------------------------------- |Transform primitives with all inputs known into a move instruction by performing the operation at compile-time. handles constant folding and simple (single-operation) algebraic simplifications (left and right identities and annihilators). Commutative ops are canonicalised by putting the smaller argument comparison if necessary. XXX Need to convert both to unsigned before shifting nothing is < 0 0 is <= everything 0 is > nothing Float ops Float comparisons -------------------------------------------------------------- at the end of previous code. Crucially, it also uses information about fixed variable values from earlier forks to specialise following forks. In possible to determine the branch that will be selected in the later fork, avoiding the need for the test. This has the effect of fusing successive forks on the same variable into a single fork. This code ensures that code is compatible with LPVM form by producing a -------------------------------------------------------------- known to be a tree, ie, its parent is Nothing, and its branches, if it has any, have been fused. | Add the appropriate branch(es) to follow the specified list of prims, which includes both the prims of the previous unforked body and the unforked part of the following |Given a variable substitution, determine which branch will be selected, if possible. -------------------------------------------------------------- While we're at it, we also mark the last use of each variable, eliminate calls that don't produce any output needed later in the body, and eliminate any move instruction that moves a variable defined in the same block as the move and not used after the move. Most other move instructions were removed parameters. -------------------------------------------------------------- |Another monad, this one for rebuilding a proc body bottom-up. |BkwdBuilderState is used to store context info while building a ProcBody forwards. Because construction runs backwards, the state mostly holds information about the following code. ^Vars used later in computation, but not defined later ^The usedLater set for each following branch, used for fused branches. ^Variable substitution to apply ^Highest temporary variable number ^The set of globals we have recently stored ^Code to come later XXX Perhaps we should generate a new proc for the parent par in cases where it's more than a few prims. XXX Not right! When processing the prims prior to each fork being assembled into a switch, we must only consider the usedLater set from *following* code. Doing the following winds later if they are needed. | Try to turn nested branches into a single switch, where we have a nested elseif ... elseif ... elseif ... else structure, and the tests are equality tests about the same variable. We also handle nested cases of disequalities where we look instead for cascading on the then instead of else branches. Arguments are straight-line code preceding the tests, the variable switched on and its type, the branches for the current fork, and the current default branches are in normal order. Returns Nothing if we can't convert the fork into a switch, or Just a tuple of the straight line code, the switch variable and its type, the branches, and the default branch. | Try to add more cases to a switch. XXX must check that it's OK to combine prims. | Finish building a switch, if there are enough branches for it to be worthwhile. XXX generalise to handle more switches Filter out pure instructions that produce no needed outputs nor out flowing globals that arent stored to later XXX Careful: probably shouldn't mark last use of variable passed as input argument more than once in the call Don't consider variables assigned here to be used later. Variables should only be assigned once, but rearranging front of real assignments, and we want those to be considered to be unneeded. -------------------------------------------------------------- Logging -------------------------------------------------------------- |Log a message, if we are logging body building activity. |Log a message, if we are logging body building activity. | Log the current builder state | Show the current builder state. Since the builder builds upside down, we start by showing the parent, then we show the current state. | Show the current reifications | Show the current part of a build state. | Show a list of branches of a build state. | Show a single branch of a build state | Show the fork part of a build state | Start a new line with the specified indent.
Author : Copyright : ( c ) 2015 . All rights reserved . License : Licensed under terms of the MIT license . See the file module BodyBuilder ( BodyBuilder, buildBody, freshVarName, instr, buildFork, completeFork, beginBranch, endBranch, definiteVariableValue, argExpandedPrim ) where import AST import Debug.Trace import Snippets ( boolType, intType, primMove ) import Util import Config (minimumSwitchCases, wordSize) import Options (LogSelection(BodyBuilder)) import Data.Map as Map import Data.List as List import Data.Set as Set import UnivSet as USet import Data.Maybe import Data.Tuple.HT (mapFst) import Data.Bits import Data.Function import Control.Monad import Control.Monad.Extra (whenJust, whenM) import Control.Monad.Trans (lift) import Control.Monad.Trans.State This monad is used to build up a ProcBody one instruction at a time . Forks are produced by the following functions : ends the current branch No instructions can be added between buildFork and , or between endBranch and beginBranch , or if the current state does not have the BodyBuilder starts a new Unforked instruction sequence , and records the previous Forked sequence , and remove the Unforked . instructions from the preceding Unforked as the instruction sequence of Some transformation is performed by the BodyBuilder monad ; in arithmetic equivalences , , and tautologies ( eg , on a branch where we know , a call to x<=y will always return true ; for unsigned x , x<0 is always false , and is replaced with x!=0 ) . The BodyState has two constructors : Unforked is used before the first first branch is created , between ending a branch and starting a new one , buildFork is called when the state is Unforked . It creates a new is called with either a Forked or Unforked state . It type BodyBuilder = StateT BodyState Compiler data BodyState = BodyState { globalsLoaded :: Map GlobalInfo PrimArg, reifiedConstr :: Map PrimVarName Constraint ^Constraints attached to Boolean vars } deriving (Eq,Show) data BuildState | Forked { ^forkingVar is a constant in every deriving (Eq,Show) | A fresh BodyState with specified temp counter and output var substitution initState :: Int -> VarSubstitution -> BodyState initState tmp oSubst = BodyState [] Map.empty Set.empty Set.empty oSubst Map.empty False tmp Unforked Nothing Map.empty Map.empty | Set up a BodyState as a new child of the specified BodyState childState :: BodyState -> BuildState -> BodyState childState st@BodyState{currSubst=iSubst,outSubst=oSubst,subExprs=subs, tmpCount=tmp, forkConsts=consts, globalsLoaded=loaded, reifiedConstr=reif} bld = BodyState [] iSubst Set.empty consts oSubst subs False tmp bld (Just st) loaded reif type Substitution = Map PrimVarName PrimArg type VarSubstitution = Map PrimVarName PrimVarName that . In the Prim keys , all PrimArgs are inputs . type ComputedCalls = Map Prim [PrimArg] freshVarName :: BodyBuilder PrimVarName freshVarName = do tmp <- gets tmpCount logBuild $ "Generating fresh variable " ++ mkTempName tmp modify (\st -> st {tmpCount = tmp + 1}) return $ PrimVarName (mkTempName tmp) 0 constraints . LPVM Integer tests are all reified , producing a result as a data Constraint = Equal PrimVarName TypeSpec PrimArg | NotEqual PrimVarName TypeSpec PrimArg deriving (Eq) instance Show Constraint where show (Equal v t a) = show v ++ ":" ++ show t ++ " = " ++ show a show (NotEqual v t a) = show v ++ ":" ++ show t ++ " ~= " ++ show a negateConstraint ( NotEqual v n ) = Equal v n BodyBuilder Primitive Operations |Run a BodyBuilder monad and extract the final proc body , along with the buildBody :: Int -> VarSubstitution -> BodyBuilder a -> Compiler (a, Int, Set PrimVarName, Set GlobalInfo, ProcBody) buildBody tmp oSubst builder = do logMsg BodyBuilder "<<<< Beginning to build a proc body" (a, st) <- runStateT builder $ initState tmp oSubst logMsg BodyBuilder ">>>> Finished building a proc body" logMsg BodyBuilder " Final state:" logMsg BodyBuilder $ fst $ showState 8 st st' <- fuseBodies st (tmp', used, stored, body) <- currBody (ProcBody [] NoFork) st' return (a, tmp', used, stored, body) buildFork :: PrimVarName -> TypeSpec -> BodyBuilder () buildFork var ty = do st <- get var' <- expandVar var ty logBuild $ "<<<< beginning to build a new fork on " ++ show var case buildState st of Forked{complete=True} -> shouldnt "Building a fork in Forked state" Forked{complete=False} -> shouldnt "Building a fork in Forking state" Unforked -> do logBuild $ " (expands to " ++ show var' ++ ")" case var' of put $ childState st $ Forked var ty (Just n) False [] Nothing False ArgVar{argVarName=var'',argVarType=varType} -> do consts <- gets forkConsts logBuild $ "Consts from parent fork = " ++ show consts let fused = Set.member var'' consts logBuild $ "This fork " ++ (if fused then "WILL " else "will NOT ") ++ "be fused with parent" put $ st {buildState=Forked var'' ty Nothing fused [] Nothing False} _ -> shouldnt "switch on non-integer variable" logState completeFork :: BodyBuilder () completeFork = do st <- get case buildState st of Forked{complete=True} -> shouldnt "Completing an already-completed fork" Unforked -> shouldnt "Completing an un-built fork" Forked var ty val fused bods deflt False -> do logBuild $ ">>>> ending fork on " ++ show var ( Map.map Set.singleton . Map.filter argIsConst . < $ > bods ) let branchMaps = Map.filter argIsConst . currSubst <$> (bods ++ maybeToList deflt) let extraSubsts = List.foldr1 intersectMapIdentity branchMaps logBuild $ " extraSubsts = " ++ show extraSubsts let consts = List.foldr1 Set.union $ List.map Map.keysSet branchMaps logBuild $ " definite variables in all branches: " ++ show consts let parent = st {buildState = Forked var ty val fused bods deflt True, tmpCount = maximum $ tmpCount <$> bods } let child = childState parent Unforked put $ child { forkConsts = consts, currSubst = Map.union extraSubsts $ currSubst child} logState beginBranch :: BodyBuilder () beginBranch = do st <- get case buildState st of Forked{complete=True} -> shouldnt "Beginning a branch in an already-completed fork" Unforked -> shouldnt "Beginning a branch in an un-built fork" Forked var ty val fused bods deflt False -> do let branchNum = length bods logBuild $ "<<<< <<<< Beginning to build " ++ (if fused then "fused " else "") ++ "branch " ++ show branchNum ++ " on " ++ show var gets tmpCount >>= logBuild . (" tmpCount = "++) . show when fused $ do par <- gets $ trustFromJust "forkConst with no parent branch" . parent case buildState par of Forked{bodies=bods, defaultBody=deflt} -> do let matchingSubsts = List.map currSubst $ List.filter (matchingSubst var branchNum) bods let extraSubsts = if List.null matchingSubsts then Map.empty else List.foldr1 intersectMapIdentity matchingSubsts logBuild $ " Adding substs " ++ show extraSubsts modify $ \st -> st { currSubst = Map.union extraSubsts (currSubst st) } Unforked -> shouldnt "forkConst predicted parent branch" put $ childState st Unforked when (isNothing val && not fused) $ do addSubst var $ ArgInt (fromIntegral branchNum) intType noteBranchConstraints var intType branchNum logState endBranch :: BodyBuilder () endBranch = do st <- get (par,st,var,ty,val,fused,bodies,deflt) <- gets popParent logBuild $ ">>>> >>>> Ending branch " ++ show (length bodies) ++ " on " ++ show var tmp <- gets tmpCount logBuild $ " tmpCount = " ++ show tmp put $ par { buildState=Forked var ty val fused (st:bodies) deflt False , tmpCount = tmp } logState |Return the closest Forking ancestor of a state , and fix its immediate popParent :: BodyState -> (BodyState,BodyState,PrimVarName,TypeSpec, Maybe Integer,Bool,[BodyState],Maybe BodyState) popParent st@BodyState{parent=Nothing} = shouldnt "endBranch with no open branch to end" popParent st@BodyState{parent=(Just par@BodyState{buildState=(Forked var ty val fused brs deflt False)})} = (par, st {parent = Nothing}, var, ty, val, fused, brs, deflt) popParent st@BodyState{parent=Just par} = let (anc, fixedPar, var, ty, val, fused, branches, deflt) = popParent par in (anc,st {parent=Just fixedPar}, var, ty, val, fused, branches, deflt) noteBranchConstraints :: PrimVarName -> TypeSpec -> Int -> BodyBuilder () noteBranchConstraints var ty val = do constr <- gets $ Map.lookup var . reifiedConstr case (val,constr) of (1, Just (Equal origVar _ origVal)) -> addSubst origVar origVal (0, Just (NotEqual origVar _ origVal)) -> addSubst origVar origVal _ -> return () specified BodyState . matchingSubst :: PrimVarName -> Int -> BodyState -> Bool matchingSubst var branchNum bod = maybe False ((== branchNum) . fromIntegral) $ varIntValue var bod varIntValue :: PrimVarName -> BodyState -> Maybe Integer varIntValue var bod = Map.lookup var (currSubst bod) >>= argIntegerValue definiteVariableValue :: PrimVarName -> BodyBuilder (Maybe PrimArg) definiteVariableValue var = do arg <- expandVar var AnyType case arg of _ -> return $ Just arg instr :: Prim -> OptPos -> BodyBuilder () instr prim pos = do st <- get case st of logBuild $ " Failing branch: ignoring instruction " ++ show prim return () BodyState{failed=False,buildState=Unforked} -> do prim' <- argExpandedPrim prim outNaming <- gets outSubst logBuild $ "With outSubst " ++ simpleShowMap outNaming logBuild $ "Generating instr " ++ show prim ++ " -> " ++ show prim' instr' prim' pos _ -> shouldnt "instr in Forked context" instr' :: Prim -> OptPos -> BodyBuilder () instr' prim@(PrimForeign "llvm" "move" [] [val, argvar@ArgVar{argVarName=var, argVarFlow=flow}]) pos = do logBuild $ " Expanding move(" ++ show val ++ ", " ++ show argvar ++ ")" unless (flow == FlowOut && argFlowDirection val == FlowIn) $ shouldnt $ "move instruction with wrong flow" ++ show prim outVar <- gets (Map.findWithDefault var var . outSubst) addSubst outVar val rawInstr prim pos recordVarSet argvar instr' prim@(PrimForeign "lpvm" "alloc" [] [_,argvar]) pos = do logBuild " Leaving alloc alone" rawInstr prim pos recordVarSet argvar instr' prim@(PrimForeign "lpvm" "cast" [] [from, to@ArgVar{argVarName=var, argVarFlow=flow}]) pos = do logBuild $ " Expanding cast(" ++ show from ++ ", " ++ show to ++ ")" unless (argFlowDirection from == FlowIn && flow == FlowOut) $ shouldnt "cast instruction with wrong flow" if argType from == argType to then instr' (PrimForeign "llvm" "move" [] [from, to]) pos else ordinaryInstr prim pos instr' prim@(PrimForeign "lpvm" "load" _ [ArgGlobal info _, var]) pos = do logBuild $ " Checking if we know the value of " ++ show info loaded <- gets globalsLoaded case Map.lookup info loaded of Just val -> do logBuild $ " ... we do(" ++ show val ++ "), moving instead" instr' (PrimForeign "llvm" "move" [] [mkInput val, var]) pos Nothing -> do logBuild " ... we don't, need to load" ordinaryInstr prim pos instr' prim@(PrimForeign "lpvm" "store" _ [var, ArgGlobal info _]) pos = do logBuild $ " Checking if we know the value of " ++ show info ++ " and it is the same as " ++ show var mbVal <- Map.lookup info <$> gets globalsLoaded logBuild $ " ... found value " ++ show mbVal case mbVal of Just val | on (==) (mkInput . canonicaliseArg) var val -> do logBuild " ... it is, no need to store" _ -> do logBuild " ... it isn't, we need to store" ordinaryInstr prim pos instr' prim pos = ordinaryInstr prim pos Do the normal work of instr . First check if we 've already computed its ordinaryInstr :: Prim -> OptPos -> BodyBuilder () ordinaryInstr prim pos = do let (prim',newOuts) = splitPrimOutputs prim logBuild $ "Looking for computed instr " ++ show prim' ++ " ..." currSubExprs <- gets subExprs logBuild $ " with subExprs = " ++ show currSubExprs match <- gets (Map.lookup prim' . subExprs) case match of Nothing -> do logBuild "not found" impurity <- lift $ primImpurity prim let gFlows = snd $ primArgs prim when (impurity <= Pure && gFlows == emptyGlobalFlows) $ recordEntailedPrims prim recordReifications prim rawInstr prim pos mapM_ recordVarSet $ primOutputs prim Just oldOuts -> do logBuild $ "found it; substituting " ++ show oldOuts ++ " for " ++ show newOuts mapM_ (\(newOut,oldOut) -> primMove (mkInput oldOut) newOut `instr'` pos) $ zip newOuts oldOuts mkInput :: PrimArg -> PrimArg mkInput (ArgVar name ty _ _ lst) = ArgVar name ty FlowIn Ordinary False mkInput arg@ArgInt{} = arg mkInput arg@ArgFloat{} = arg mkInput arg@ArgString{} = arg mkInput arg@ArgChar{} = arg mkInput arg@ArgClosure{} = arg mkInput (ArgUnneeded _ ty) = ArgUnneeded FlowIn ty mkInput arg@ArgGlobal{} = arg mkInput arg@ArgUndef{} = arg argExpandedPrim :: Prim -> BodyBuilder Prim argExpandedPrim call@(PrimCall id pspec impurity args gFlows) = do args' <- transformUnneededArgs pspec args return $ PrimCall id pspec impurity args' gFlows argExpandedPrim call@(PrimHigher id fn impurity args) = do logBuild $ "Expanding Higher call " ++ show call fn' <- expandArg fn case fn' of ArgClosure pspec clsd _ -> do pspec' <- fromMaybe pspec <$> lift (maybeGetClosureOf pspec) logBuild $ "As first-order call to " ++ show pspec' params <- lift $ getPrimParams pspec' let args' = zipWith (setArgType . primParamType) params args gFlows <- lift $ getProcGlobalFlows pspec argExpandedPrim $ PrimCall id pspec' impurity (clsd ++ args') gFlows _ -> do logBuild $ "Leaving as higher call to " ++ show fn' args' <- mapM expandArg args return $ PrimHigher id fn' impurity args' argExpandedPrim (PrimForeign lang nm flags args) = do args' <- mapM expandArg args return $ simplifyForeign lang nm flags args' ArgUnneeded . For unneeded * output * parameters , there must be an transformUnneededArgs :: ProcSpec -> [PrimArg] -> BodyBuilder [PrimArg] transformUnneededArgs pspec args = do args' <- mapM expandArg args params <- lift $ primProtoParams <$> getProcPrimProto pspec zipWithM (transformUnneededArg $ zip params args) params args' ArgUnneeded . transformUnneededArg :: [(PrimParam,PrimArg)] -> PrimParam -> PrimArg -> BodyBuilder PrimArg transformUnneededArg pairs PrimParam{primParamInfo=ParamInfo{paramInfoUnneeded=True}, primParamFlow=flow, primParamType=typ, primParamName=name} arg = do logBuild $ "Marking unneeded argument " ++ show arg when (isOutputFlow flow) $ do case List.filter (\(p,a)-> primParamName p == name && isInputFlow (primParamFlow p)) pairs of [] -> shouldnt $ "No input param matching output " ++ show name [(_,a)] -> do logBuild $ "Adding move instruction for unneeded output " ++ show arg instr' (PrimForeign "llvm" "move" [] [a, arg]) Nothing _ -> shouldnt $ "Multiple input params match output " ++ show name return $ ArgUnneeded flow typ transformUnneededArg _ _ (ArgClosure pspec args ty) = do args' <- transformUnneededArgs pspec args return $ ArgClosure pspec args' ty transformUnneededArg _ _ arg = return arg |Construct a fake version of a Prim instruction containing only its splitPrimOutputs :: Prim -> (Prim, [PrimArg]) splitPrimOutputs prim = let (args, gFlows) = primArgs prim (inArgs,outArgs) = splitArgsByMode args in (canonicalisePrim $ replacePrimArgs prim (canonicaliseArg <$> inArgs) gFlows, outArgs) |Returns a list of all output arguments of the input Prim primOutputs :: Prim -> [PrimArg] primOutputs prim = List.filter (isOutputFlow . argFlowDirection) $ fst $ primArgs prim addSubst :: PrimVarName -> PrimArg -> BodyBuilder () addSubst var val = do logBuild $ " adding subst " ++ show var ++ " -> " ++ show val modify (\s -> s { currSubst = Map.insert var val $ currSubst s }) subst <- gets currSubst logBuild $ " new subst = " ++ show subst |Record that the specified arg ( which must be a variable ) has been set . recordVarSet :: PrimArg -> BodyBuilder () recordVarSet ArgVar{argVarName=nm, argVarFlow=flow} | isOutputFlow flow = modify (\s -> s { blockDefs = Set.insert nm $ blockDefs s }) recordVarSet (ArgUnneeded flow _) | isOutputFlow flow = return () recordVarSet arg = shouldnt $ "recordVarSet of non-output argument " ++ show arg |Record all instructions equivalent to the input prim in the lookup table , recordEntailedPrims :: Prim -> BodyBuilder () recordEntailedPrims prim = do instrPairs <- (splitPrimOutputs prim:) <$> lift (instrConsequences prim) logBuild $ "Recording computed instrs" ++ List.concatMap (\(p,o)-> "\n " ++ show p ++ " -> " ++ show o) instrPairs modify (\s -> s {subExprs = List.foldr (uncurry Map.insert) (subExprs s) instrPairs}) XXX Does n't yet handle multiple modes for PrimCalls instrConsequences :: Prim -> Compiler [(Prim,[PrimArg])] instrConsequences prim = List.map (mapFst canonicalisePrim) <$> instrConsequences' prim instrConsequences' :: Prim -> Compiler [(Prim,[PrimArg])] instrConsequences' (PrimForeign "lpvm" "cast" flags [a1,a2]) = return [(PrimForeign "lpvm" "cast" flags [a2], [a1])] instrConsequences' (PrimForeign "lpvm" "mutate" [] [_,addr,offset,_,size,startOffset,val]) = return [(PrimForeign "lpvm" "access" [] [addr,offset,size,startOffset], [val])] instrConsequences' (PrimForeign "lpvm" "access" [] [struct,offset,size,startOffset,val]) = return [(PrimForeign "lpvm" "mutate" [] [struct,offset,ArgInt 1 intType,size,startOffset, val], [struct]), (PrimForeign "lpvm" "mutate" [] [struct,offset,ArgInt 0 intType,size,startOffset, val], [struct])] instrConsequences' (PrimForeign "llvm" "add" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "sub" flags [a3,a2], [a1]), (PrimForeign "llvm" "sub" flags [a3,a1], [a2]), (PrimForeign "llvm" "add" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "sub" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "add" flags [a3,a2], [a1]), (PrimForeign "llvm" "add" flags [a2,a3], [a1]), (PrimForeign "llvm" "sub" flags [a1,a3], [a2])] instrConsequences' (PrimForeign "llvm" "mul" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "mul" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "fadd" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "fadd" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "fmul" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "fmul" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "and" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "and" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "or" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "or" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_eq" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_eq" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ne" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ne" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_slt" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_sgt" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_sgt" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_slt" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ult" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ugt" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ugt" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ult" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_sle" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_sge" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_sge" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_sle" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_ule" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_uge" flags [a2,a1], [a3])] instrConsequences' (PrimForeign "llvm" "icmp_uge" flags [a1,a2,a3]) = return [(PrimForeign "llvm" "icmp_ule" flags [a2,a1], [a3])] instrConsequences' _ = return [] the Boolean variable . recordReifications :: Prim -> BodyBuilder () recordReifications (PrimForeign "llvm" instr flags [a1,a2,ArgVar{argVarName=reifVar,argVarFlow=FlowOut}]) = case reification instr a1 a2 of Just constr -> do modify (\s -> s { reifiedConstr = Map.insert reifVar constr $ reifiedConstr s }) logBuild $ "Recording reification " ++ show reifVar ++ " <-> " ++ show constr Nothing -> logBuild "No reification found" recordReifications _ = return () reification :: String -> PrimArg -> PrimArg -> Maybe Constraint reification "icmp_eq" ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} arg = Just $ Equal var ty arg reification "icmp_eq" arg ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} = Just $ Equal var ty arg reification "icmp_ne" ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} arg = Just $ NotEqual var ty arg reification "icmp_ne" arg ArgVar{argVarName=var,argVarType=ty,argVarFlow=FlowIn} = Just $ NotEqual var ty arg reification _ _ _ = Nothing rawInstr :: Prim -> OptPos -> BodyBuilder () rawInstr prim pos = do logBuild $ "---- adding instruction " ++ show prim validateInstr prim updateGlobalsLoaded prim pos modify $ addInstrToState (maybePlace prim pos) splitArgsByMode :: [PrimArg] -> ([PrimArg], [PrimArg]) splitArgsByMode = List.partition (isInputFlow . argFlowDirection) canonicalisePrim :: Prim -> Prim canonicalisePrim (PrimCall _ nm impurity args gFlows) = PrimCall 0 nm impurity (canonicaliseArg . mkInput <$> args) gFlows canonicalisePrim (PrimHigher _ var impurity args) = PrimHigher 0 (canonicaliseArg $ mkInput var) impurity $ canonicaliseArg . mkInput <$> args canonicalisePrim (PrimForeign lang op flags args) = PrimForeign lang op flags $ List.map (canonicaliseArg . mkInput) args canonicaliseArg :: PrimArg -> PrimArg canonicaliseArg ArgVar{argVarName=nm, argVarFlow=fl} = ArgVar nm AnyType fl Ordinary False canonicaliseArg (ArgClosure ms as _) = ArgClosure ms (canonicaliseArg <$> as) AnyType canonicaliseArg (ArgInt v _) = ArgInt v AnyType canonicaliseArg (ArgFloat v _) = ArgFloat v AnyType canonicaliseArg (ArgString v r _) = ArgString v r AnyType canonicaliseArg (ArgChar v _) = ArgChar v AnyType canonicaliseArg (ArgGlobal info _) = ArgGlobal info AnyType canonicaliseArg (ArgUnneeded dir _) = ArgUnneeded dir AnyType canonicaliseArg (ArgUndef _) = ArgUndef AnyType validateInstr :: Prim -> BodyBuilder () validateInstr p@(PrimCall _ _ _ args _) = mapM_ (validateArg p) args validateInstr p@(PrimHigher _ fn _ args) = mapM_ (validateArg p) $ fn:args validateInstr p@(PrimForeign _ _ _ args) = mapM_ (validateArg p) args validateArg :: Prim -> PrimArg -> BodyBuilder () validateArg instr ArgVar{argVarType=ty} = validateType ty instr validateArg instr (ArgInt _ ty) = validateType ty instr validateArg instr (ArgFloat _ ty) = validateType ty instr validateArg instr (ArgString _ _ ty) = validateType ty instr validateArg instr (ArgChar _ ty) = validateType ty instr validateArg instr (ArgClosure _ _ ty) = validateType ty instr validateArg instr (ArgGlobal _ ty) = validateType ty instr validateArg instr (ArgUnneeded _ ty) = validateType ty instr validateArg instr (ArgUndef ty) = validateType ty instr validateType :: TypeSpec -> Prim -> BodyBuilder () validateType InvalidType instr = shouldnt $ "InvalidType in argument of " ++ show instr validateType _ instr = return () Add an instruction to the given BodyState . If unforked , add it at the front addInstrToState :: Placed Prim -> BodyState -> BodyState addInstrToState ins st@BodyState{buildState=Unforked} = st { currBuild = ins:currBuild st} addInstrToState ins st@BodyState{buildState=bld@Forked{bodies=bods}} = st { buildState = bld {bodies=List.map (addInstrToState ins) bods} } expandVar :: PrimVarName -> TypeSpec -> BodyBuilder PrimArg expandVar var ty = expandArg $ ArgVar var ty FlowIn Ordinary False expandArg :: PrimArg -> BodyBuilder PrimArg expandArg arg@ArgVar{argVarName=var, argVarFlow=flow} | isInputFlow flow = do var' <- gets (Map.lookup var . currSubst) let ty = argVarType arg let var'' = setArgType ty <$> var' logBuild $ "Expanded " ++ show var ++ " to " ++ show var'' maybe (return arg) expandArg var'' expandArg arg@ArgVar{argVarName=var, argVarFlow=flow} | isOutputFlow flow = do var' <- gets (Map.findWithDefault var var . outSubst) when (var /= var') $ logBuild $ "Replaced output variable " ++ show var ++ " with " ++ show var' return arg{argVarName=var'} expandArg arg@(ArgClosure ps as ty) = do as' <- mapM expandArg as return $ ArgClosure ps as' ty expandArg arg = return arg updateGlobalsLoaded :: Prim -> OptPos -> BodyBuilder () updateGlobalsLoaded prim pos = do loaded <- gets globalsLoaded case prim of PrimForeign "lpvm" "load" _ [ArgGlobal info _, var] -> modify $ \s -> s{globalsLoaded=Map.insert info var loaded} PrimForeign "lpvm" "store" _ [var, ArgGlobal info _] -> modify $ \s -> s{globalsLoaded=Map.insert info var loaded} _ -> do let gFlows = snd $ primArgs prim logBuild $ "Call has global flows: " ++ show gFlows let filter info _ = not $ hasGlobalFlow gFlows FlowOut info modify $ \s -> s {globalsLoaded=Map.filterWithKey filter loaded} loaded' <- gets globalsLoaded when (loaded /= loaded') $ do logBuild $ "Globals Loaded: " ++ simpleShowMap loaded logBuild $ " -> " ++ simpleShowMap loaded' simplifyForeign :: String -> ProcName -> [Ident] -> [PrimArg] -> Prim simplifyForeign "llvm" op flags args = simplifyOp op flags args simplifyForeign lang op flags args = PrimForeign lang op flags args | Simplify and instructions where possible . This first , but only for integer ops . Integer inequalities are canonicalised by putting smaller argument first and flipping simplifyOp :: ProcName -> [Ident] -> [PrimArg] -> Prim Integer ops simplifyOp "add" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1+n2) ty) output simplifyOp "add" _ [ArgInt 0 ty, arg, output] = primMove arg output simplifyOp "add" _ [arg, ArgInt 0 ty, output] = primMove arg output simplifyOp "add" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "add" flags [arg2, arg1, output] simplifyOp "sub" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1-n2) ty) output simplifyOp "sub" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "mul" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1*n2) ty) output simplifyOp "mul" _ [ArgInt 1 ty, arg, output] = primMove arg output simplifyOp "mul" _ [arg, ArgInt 1 ty, output] = primMove arg output simplifyOp "mul" _ [ArgInt 0 ty, _, output] = primMove (ArgInt 0 ty) output simplifyOp "mul" _ [_, ArgInt 0 ty, output] = primMove (ArgInt 0 ty) output simplifyOp "mul" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "mul" flags [arg2, arg1, output] simplifyOp "div" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1 `div` n2) ty) output simplifyOp "div" _ [arg, ArgInt 1 _, output] = primMove arg output Bitstring ops simplifyOp "and" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (fromIntegral n1 .&. fromIntegral n2) ty) output simplifyOp "and" _ [ArgInt 0 ty, _, output] = primMove (ArgInt 0 ty) output simplifyOp "and" _ [_, ArgInt 0 ty, output] = primMove (ArgInt 0 ty) output simplifyOp "and" _ [ArgInt (-1) _, arg, output] = primMove arg output simplifyOp "and" _ [arg, ArgInt (-1) _, output] = primMove arg output simplifyOp "and" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "and" flags [arg2, arg1, output] simplifyOp "or" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (fromIntegral n1 .|. fromIntegral n2) ty) output simplifyOp "or" _ [ArgInt (-1) ty, _, output] = primMove (ArgInt (-1) ty) output simplifyOp "or" _ [_, ArgInt (-1) ty, output] = primMove (ArgInt (-1) ty) output simplifyOp "or" _ [ArgInt 0 _, arg, output] = primMove arg output simplifyOp "or" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "or" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "or" flags [arg2, arg1, output] simplifyOp "xor" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (fromIntegral n1 `xor` fromIntegral n2) ty) output simplifyOp "xor" _ [ArgInt 0 _, arg, output] = primMove arg output simplifyOp "xor" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "xor" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "xor" flags [arg2, arg1, output] simplifyOp "shl" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1 `shiftL` fromIntegral n2) ty) output simplifyOp "shl" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp "shl" _ [arg@(ArgInt 0 _), _, output] = primMove arg output simplifyOp "ashr" _ [ArgInt n1 ty, ArgInt n2 _, output] = primMove (ArgInt (n1 `shiftR` fromIntegral n2) ty) output simplifyOp "ashr" _ [arg, ArgInt 0 _, output] = primMove arg output simplifyOp " lshr " _ [ ArgInt n1 ty , ArgInt n2 _ , output ] = primMove ( ArgInt ( n1 ` shiftR ` fromIntegral n2 ) ty ) output simplifyOp "lshr" _ [arg, ArgInt 0 _, output] = primMove arg output Integer comparisons , including special handling of unsigned comparison to 0 simplifyOp "icmp_eq" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1==n2) output simplifyOp "icmp_eq" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_eq" flags [arg2, arg1, output] simplifyOp "icmp_ne" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1/=n2) output simplifyOp "icmp_ne" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ne" flags [arg2, arg1, output] simplifyOp "icmp_slt" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1<n2) output simplifyOp "icmp_slt" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_sgt" flags [arg2, arg1, output] simplifyOp "icmp_sle" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1<=n2) output simplifyOp "icmp_sle" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_sge" flags [arg2, arg1, output] simplifyOp "icmp_sgt" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1>n2) output simplifyOp "icmp_sgt" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_slt" flags [arg2, arg1, output] simplifyOp "icmp_sge" _ [ArgInt n1 _, ArgInt n2 _, output] = primMove (boolConstant $ n1>=n2) output simplifyOp "icmp_sge" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_sle" flags [arg2, arg1, output] simplifyOp "icmp_ult" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'<n2') output primMove (ArgInt 0 boolType) output only 0 is < 1 PrimForeign "llvm" "icmp_eq" flags [a1,ArgInt 0 ty,output] simplifyOp "icmp_ult" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ugt" flags [arg2, arg1, output] simplifyOp "icmp_ule" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'<=n2') output primMove (ArgInt 1 boolType) output 1 is < = all but 0 PrimForeign "llvm" "icmp_ne" flags [ArgInt 0 ty,a2,output] simplifyOp "icmp_ule" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_uge" flags [arg2, arg1, output] simplifyOp "icmp_ugt" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'>n2') output primMove (ArgInt 0 boolType) output 1 is > only 0 PrimForeign "llvm" "icmp_eq" flags [ArgInt 0 ty,a2,output] simplifyOp "icmp_ugt" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ult" flags [arg2, arg1, output] simplifyOp "icmp_uge" _ [ArgInt n1 _, ArgInt n2 _, output] = let n1' = fromIntegral n1 :: Word n2' = fromIntegral n2 :: Word in primMove (boolConstant $ n1'>=n2') output everything is > = 0 primMove (ArgInt 1 boolType) output all but 0 is > = 1 PrimForeign "llvm" "icmp_ne" flags [a1,ArgInt 0 ty,output] simplifyOp "icmp_uge" flags [arg1, arg2, output] | arg2 < arg1 = PrimForeign "llvm" "icmp_ule" flags [arg2, arg1, output] simplifyOp "fadd" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1+n2) ty) output simplifyOp "fadd" _ [ArgFloat 0 _, arg, output] = primMove arg output simplifyOp "fadd" _ [arg, ArgFloat 0 _, output] = primMove arg output simplifyOp "fsub" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1-n2) ty) output simplifyOp "fsub" _ [arg, ArgFloat 0 _, output] = primMove arg output simplifyOp "fmul" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1*n2) ty) output simplifyOp "fmul" _ [arg, ArgFloat 1 _, output] = primMove arg output simplifyOp "fmul" _ [ArgFloat 1 _, arg, output] = primMove arg output We do n't handle float * 0.0 because of the semantics of IEEE floating mult . simplifyOp "fdiv" _ [ArgFloat n1 ty, ArgFloat n2 _, output] = primMove (ArgFloat (n1/n2) ty) output simplifyOp "fdiv" _ [arg, ArgFloat 1 _, output] = primMove arg output simplifyOp "fcmp_eq" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1==n2) output simplifyOp "fcmp_ne" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1/=n2) output simplifyOp "fcmp_slt" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1<n2) output simplifyOp "fcmp_sle" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1<=n2) output simplifyOp "fcmp_sgt" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1>n2) output simplifyOp "fcmp_sge" _ [ArgFloat n1 _, ArgFloat n2 _, output] = primMove (boolConstant $ n1>=n2) output simplifyOp name flags args = PrimForeign "llvm" name flags args boolConstant :: Bool -> PrimArg boolConstant bool = ArgInt (fromIntegral $ fromEnum bool) boolType Fusing Forks in BodyStates BodyStates allow code to follow a branch ; this code injects subsequent code particular , when appending a fork to the end of an earlier fork , it is often BodyState that has no parent , and where all the bodies recursively within the BuildState also have no parent . | Recursively fuse Bodystate , as described above . fuseBodies :: BodyState -> Compiler BodyState fuseBodies st@BodyState{parent=Nothing, buildState=bst} = do logMsg BodyBuilder $ "Fusing origin bodyState:" ++ fst (showState 4 st) bst' <- fuseBranches bst let st' = st {buildState = bst'} logMsg BodyBuilder $ "Fused origin state:" ++ fst (showState 4 st') return st' fuseBodies st@BodyState{parent=Just par, buildState=bst} = do logMsg BodyBuilder $ "Fusing child bodyState:" ++ fst (showState 4 st) par' <- fuseBodies par st' <- addBodyContinuation par' $ st {parent=Nothing} logMsg BodyBuilder $ "Fused child state:" ++ fst (showState 4 st') return st' fuseBranches :: BuildState -> Compiler BuildState fuseBranches Unforked = return Unforked fuseBranches bst@Forked{forkingVar=var,bodies=bods} = do logMsg BodyBuilder $ "Fusing branches of fork on " ++ show var bods' <- mapM fuseBodies $ bodies bst return $ bst {bodies=bods'} | Add the second BodyState at the end of the first . The second BodyState is addBodyContinuation :: BodyState -> BodyState -> Compiler BodyState addBodyContinuation _ next@BodyState{parent=Just _} = shouldnt $ "addBodyContinuation with non-singular second argument:" ++ fst (showState 4 next) addBodyContinuation prev@BodyState{buildState=Unforked, currBuild=bld, currSubst=subst, blockDefs=defs, outSubst=osubst} next = do logMsg BodyBuilder $ "Adding state:" ++ fst (showState 4 next) logMsg BodyBuilder $ "... after unforked body:" ++ fst (showState 4 prev) addSelectedContinuation bld subst defs osubst next addBodyContinuation prev@BodyState{buildState=Forked{}} next = do logMsg BodyBuilder $ "Adding state:" ++ fst (showState 4 next) logMsg BodyBuilder $ "... after forked body:" ++ fst (showState 4 prev) let build = buildState prev bods <- mapM (`addBodyContinuation` next) $ bodies build return $ prev {buildState = build {bodies = bods}} addSelectedContinuation :: [Placed Prim] -> Substitution -> Set PrimVarName -> VarSubstitution -> BodyState -> Compiler BodyState XXX Must merge subst with currSubst of st addSelectedContinuation prevPrims subst defs osubst st@BodyState{buildState=Unforked} = do let subst' = Map.union (currSubst st) subst let defs' = Set.union (blockDefs st) defs let oSubst' = Map.union (outSubst st) osubst let st' = st { currBuild = currBuild st ++ prevPrims , currSubst = subst' , blockDefs = defs' , outSubst = oSubst' } logMsg BodyBuilder $ "Adding unforked continuation produces:" ++ fst (showState 4 st') return st' addSelectedContinuation prevPrims subst defs osubst st@BodyState{buildState=bst@Forked{}} = do let subst' = Map.union (currSubst st) subst let defs' = Set.union (blockDefs st) defs let osubst' = Map.union (outSubst st) osubst case selectedBranch subst bst of Nothing -> do bst <- fuseBranches $ buildState st let st' = st { currBuild = currBuild st ++ prevPrims , currSubst = subst' , blockDefs = defs' , outSubst = osubst' , buildState = bst } logMsg BodyBuilder $ "No fork selection possible, producing:" ++ fst (showState 4 st') return st' Just branchNum -> do let selectedBranch = revSelectElt branchNum $ bodies bst logMsg BodyBuilder $ "Selected branch " ++ show branchNum selectedBranch' <- fuseBodies selectedBranch addSelectedContinuation (currBuild st ++ prevPrims) subst' defs' osubst' selectedBranch' selectedBranch :: Substitution -> BuildState -> Maybe Integer selectedBranch subst Unforked = Nothing selectedBranch subst Forked{knownVal=known, forkingVar=var} = known `orElse` (Map.lookup var subst >>= argIntegerValue) Reassembling the ProcBody Once we 've built up a BodyState , this code assembles it into a new ProcBody . while building BodyState , but that approach can not eliminate moves to output currBody :: ProcBody -> BodyState -> Compiler (Int,Set PrimVarName,Set GlobalInfo,ProcBody) currBody body st@BodyState{tmpCount=tmp} = do logMsg BodyBuilder $ "Now reconstructing body with usedLater = " ++ intercalate ", " (show <$> Map.keys (outSubst st)) st' <- execStateT (rebuildBody st) $ BkwdBuilderState (Map.keysSet $ outSubst st) Nothing Map.empty 0 Set.empty body let BkwdBuilderState{bkwdUsedLater=usedLater, bkwdFollowing=following, bkwdGlobalStored=stored} = st' logMsg BodyBuilder ">>>> Finished rebuilding a proc body" logMsg BodyBuilder " Final state:" logMsg BodyBuilder $ showBlock 5 following return (tmp, usedLater, stored, following) type BkwdBuilder = StateT BkwdBuilderState Compiler backwards from a BodyState , itself the result of rebuilding a ProcBody data BkwdBuilderState = BkwdBuilderState { bkwdBranchesUsedLater :: Maybe [Set PrimVarName], } deriving (Eq,Show) rebuildBody :: BodyState -> BkwdBuilder () rebuildBody st@BodyState{parent=Just par} = shouldnt $ "Body parent left by fusion: " ++ fst (showState 4 par) rebuildBody st@BodyState{currBuild=prims, currSubst=subst, blockDefs=defs, buildState=bldst, parent=Nothing, reifiedConstr=reif} = do usedLater <- gets bkwdUsedLater following <- gets bkwdFollowing logBkwd $ "Rebuilding body:" ++ fst (showState 8 st) ++ "\nwith currSubst = " ++ simpleShowMap subst ++ "\n usedLater = " ++ simpleShowSet usedLater ++ "\n currBuild = " ++ showPlacedPrims 17 prims case bldst of Unforked -> mapM_ (placedApply (bkwdBuildStmt defs)) prims Forked{complete=False} -> shouldnt "Building proc body for bodystate with incomplete fork" Forked var ty fixedval fused b d True -> do let bods = reverse b case fixedval of Just val -> do rebuildBody $ selectElt val bods mapM_ (placedApply (bkwdBuildStmt defs)) prims Nothing -> do (prims', var', ty', bods', deflt') <- rebuildSwitch prims var ty bods d reif sts <- mapM (rebuildBranch subst) bods' deflt'' <- mapM (rebuildBranch subst) deflt' usedLater' <- gets bkwdUsedLater let sts' = sts ++ maybeToList deflt'' let usedLaters = bkwdUsedLater <$> sts' up keeping Undef assignments to variables that will be assigned let usedLater'' = List.foldr Set.union usedLater' usedLaters let branchesUsedLater = if fused then Just usedLaters else Nothing logBkwd $ "Switch on " ++ show var' ++ " with " ++ show (length sts) ++ " branches" ++ if isJust deflt' then " and a default" else "" logBkwd $ " usedLater = " ++ simpleShowSet usedLater'' logBkwd $ " branchesUsedLater = " ++ show branchesUsedLater let lastUse = Set.notMember var' usedLater'' let usedLater''' = Set.insert var' usedLater'' let tmp = maximum $ List.map bkwdTmpCount sts' let followingBranches = List.map bkwdFollowing sts let gStored = List.foldr1 Set.intersection (bkwdGlobalStored <$> sts') put $ BkwdBuilderState usedLater''' branchesUsedLater Map.empty tmp gStored $ ProcBody [] $ PrimFork var' ty' lastUse followingBranches (bkwdFollowing <$> deflt'') mapM_ (placedApply (bkwdBuildStmt defs)) prims' finalUsedLater <- gets bkwdUsedLater logBkwd $ "Finished rebuild with usedLater = " ++ show finalUsedLater |Select the element of specified by num selectElt :: Integral a => a -> [b] -> b selectElt num bods = if num' >= 0 && num' < length bods then bods !! num' else shouldnt $ "Out-of-bounds fixed value in fork " ++ show num' where num' = fromIntegral num |Select the element of , which is reversed , by num revSelectElt :: Integral a => a -> [b] -> b revSelectElt num revBods = selectElt (length revBods - 1 - fromIntegral num) revBods branch . NB : the straight line code is in reversed order at this point , but rebuildSwitch :: [Placed Prim] -> PrimVarName -> TypeSpec -> [BodyState] -> Maybe BodyState -> Map PrimVarName Constraint -> BkwdBuilder ([Placed Prim], PrimVarName, TypeSpec, [BodyState], Maybe BodyState) rebuildSwitch prims var ty branches@[branch0,branch1] Nothing reif = do logBkwd $ "Rebuild fork on " ++ show var ++ ", reified from " ++ show (Map.lookup var reif) case Map.lookup var reif of Nothing -> return (prims, var, ty, branches, Nothing) Just (Equal var' ty' (ArgInt val _)) -> do sw <- rebuildSwitch' prims var' ty' branch0 $ Map.singleton val branch1 return $ fromMaybe (prims, var, ty, branches, Nothing) sw Just (NotEqual var' ty' (ArgInt val _)) -> do sw <- rebuildSwitch' prims var' ty' branch1 $ Map.singleton val branch0 return $ fromMaybe (prims, var, ty, branches, Nothing) sw _ -> return (prims, var, ty, branches, Nothing) rebuildSwitch prims var ty branches deflt _ = return (prims, var, ty, branches, deflt) rebuildSwitch' :: [Placed Prim] -> PrimVarName -> TypeSpec -> BodyState -> Map Integer BodyState -> BkwdBuilder (Maybe ([Placed Prim], PrimVarName, TypeSpec, [BodyState], Maybe BodyState)) rebuildSwitch' prims var ty st@BodyState{buildState=bldst@(Forked v _ _ _ [b1,b0] _ _), parent=Nothing, currBuild=prims', reifiedConstr=reif} cases | isJust constr = do logBkwd $ "Rebuild nested fork on " ++ show v ++ ", reified from " ++ show constr case fromJust constr of Equal var' _ (ArgInt val _) | var == var' -> rebuildSwitch' prims'' var ty b0 $ Map.insert val b1 cases NotEqual var' _ (ArgInt val _) | var == var' -> rebuildSwitch' prims'' var ty b1 $ Map.insert val b0 cases _ -> completeSwitch prims'' var ty st cases where constr = Map.lookup v reif prims'' = prims' ++ prims rebuildSwitch' prims var ty st cases = do logBkwd $ "Nested branch not switching on " ++ show var case buildState st of Forked{forkingVar=v} -> logBkwd $ " Fork on " ++ show v ++ ", where " ++ show cases Unforked -> logBkwd " Not a fork" completeSwitch prims var ty st cases completeSwitch :: [Placed Prim] -> PrimVarName -> TypeSpec -> BodyState -> Map Integer BodyState -> BkwdBuilder (Maybe ([Placed Prim], PrimVarName, TypeSpec, [BodyState], Maybe BodyState)) completeSwitch prims var ty deflt cases | Map.size cases >= minimumSwitchCases = do let cases' = Map.toAscList cases let maxCase = fst $ last cases' if (fst <$> cases') == [0..maxCase] then do logBkwd $ "Producing switch with cases " ++ show (fst <$> cases') ++ " and a default" logBkwd $ "Switch variable type: " ++ show ty switchVarRep <- lift $ lookupTypeRepresentation ty let maxPossible = 2^(maybe wordSize typeRepSize switchVarRep)-1 logBkwd $ "Max possible switch var value: " ++ show maxPossible return $ Just (prims, var, ty, snd <$> cases', if maxPossible >= maxCase then Nothing else Just deflt) else do logBkwd $ "Not producing switch: non-dense cases " ++ show (fst <$> cases') | otherwise = do logBkwd $ "Not producing switch (only " ++ show (Map.size cases) ++ " case(s))" return Nothing rebuildBranch :: Substitution -> BodyState -> BkwdBuilder BkwdBuilderState rebuildBranch subst bod = do bkwdSt <- get lift $ execStateT (rebuildBody bod) bkwdSt bkwdBuildStmt :: Set PrimVarName -> Prim -> OptPos -> BkwdBuilder () bkwdBuildStmt defs prim pos = do usedLater <- gets bkwdUsedLater renaming <- gets bkwdRenaming gStored <- gets bkwdGlobalStored logBkwd $ " Rebuilding prim: " ++ show prim ++ "\n with usedLater = " ++ show usedLater ++ "\n and bkwdRenaming = " ++ simpleShowMap renaming ++ "\n and defs = " ++ simpleShowSet defs ++ "\n and globalStored = " ++ simpleShowSet gStored let (args, gFlows) = primArgs prim args' <- mapM renameArg args logBkwd $ " renamed args = " ++ show args' case (prim,args') of (PrimForeign "llvm" "move" [] _, [ArgVar{argVarName=fromVar}, ArgVar{argVarName=toVar}]) | Set.notMember fromVar usedLater && Set.member fromVar defs -> modify $ \s -> s { bkwdRenaming = Map.insert fromVar toVar $ bkwdRenaming s } _ -> do let (ins, outs) = splitArgsByMode $ List.filter argIsVar $ flattenArgs args' let gOuts = globalFlowsOut gFlows purity <- lift $ primImpurity prim when (purity > Pure || any (`Set.member` usedLater) (argVarName <$> outs) || not (USet.isEmpty $ whenFinite (Set.\\ gStored) gOuts)) $ do let prim' = replacePrimArgs prim (markIfLastUse usedLater <$> args') gFlows logBkwd $ " updated prim = " ++ show prim' nested forks into a switch can move Undef assignments in let usedLater' = List.foldr Set.insert (List.foldr Set.delete usedLater $ argVarName <$> outs) $ argVarName <$> ins Add all globals that FlowOut from this prim , then remove all that FlowIn FlowOut means it is overwritten , FlowIn means the value may be read let gStored' = Set.filter (not . hasGlobalFlow gFlows FlowIn) $ gStored `Set.union` USet.toSet Set.empty gOuts st@BkwdBuilderState{bkwdFollowing=bd@ProcBody{bodyPrims=prims}} <- get put $ st { bkwdFollowing = bd { bodyPrims = maybePlace prim' pos : prims }, bkwdUsedLater = usedLater', bkwdGlobalStored = gStored' } renameArg :: PrimArg -> BkwdBuilder PrimArg renameArg arg@ArgVar{argVarName=name} = do name' <- gets (Map.findWithDefault name name . bkwdRenaming) return $ arg {argVarName=name'} renameArg (ArgClosure ps args ts) = do args' <- mapM renameArg args return $ ArgClosure ps args' ts renameArg arg = return arg flattenArgs :: [PrimArg] -> [PrimArg] flattenArgs = concatMap flattenArg flattenArg :: PrimArg -> [PrimArg] flattenArg arg@(ArgClosure _ as ts) = arg:flattenArgs as flattenArg arg = [arg] markIfLastUse :: Set PrimVarName -> PrimArg -> PrimArg markIfLastUse usedLater arg@ArgVar{argVarName=nm,argVarFlow=flow} | isInputFlow flow = arg {argVarFinal=Set.notMember nm usedLater} markIfLastUse _ arg = arg logBuild :: String -> BodyBuilder () logBuild s = lift $ logMsg BodyBuilder s logBkwd :: String -> BkwdBuilder () logBkwd s = lift $ logMsg BodyBuilder s logState :: BodyBuilder () logState = do st <- get logBuild $ " Current state:" ++ fst (showState 8 st) return () showState :: Int -> BodyState -> (String,Int) showState indent BodyState{parent=par, currBuild=revPrims, buildState=bld, blockDefs=defs, forkConsts=consts, currSubst=substs, globalsLoaded=loaded, reifiedConstr=reifs} = let (str ,indent') = maybe ("",indent) (mapFst (++ (startLine indent ++ "----------")) . showState indent) par substStr = startLine indent ++ "# Substs : " ++ simpleShowMap substs globalStr = startLine indent ++ "# Loaded globals : " ++ simpleShowMap loaded str' = showPlacedPrims indent' (reverse revPrims) sets = if List.null revPrims then "" else startLine indent ++ "# Vars defined: " ++ simpleShowSet defs suffix = case bld of Forked{} -> startLine indent ++ "# Fusion consts: " ++ show consts _ -> "" reifstr = startLine indent ++ "# Reifications : " ++ showReifications reifs (str'',indent'') = showBuildState indent' bld in (str ++ str' ++ substStr ++ sets ++ globalStr ++ str'' ++ suffix ++ reifstr , indent'') showReifications :: Map PrimVarName Constraint -> String showReifications reifs = intercalate ", " [show k ++ " <-> " ++ show c | (k,c) <- Map.assocs reifs] showBuildState :: Int -> BuildState -> (String,Int) showBuildState indent Unforked = ("", indent) showBuildState indent (Forked var ty val fused bodies deflt complete) = let intro = showSwitch indent var ty val fused content = showBranches indent 0 complete (reverse bodies) deflt indent' = indent + 4 in (intro++content,indent') showBranches :: Int -> Int -> Bool -> [BodyState] -> Maybe BodyState -> String showBranches indent bodyNum False [] Nothing = showCase indent bodyNum ++ "..." showBranches indent bodyNum False [] (Just d) = shouldnt "Incomplete fork with default: " ++ show d showBranches indent bodyNum True [] deflt = maybe "" (((startLine indent ++ "else::") ++) . fst . showState (indent+4)) deflt showBranches indent bodyNum complete (body:bodies) deflt = showCase indent bodyNum ++ fst (showState (indent+4) body) ++ showBranches indent (bodyNum+1) complete bodies deflt showCase indent bodyNum = startLine indent ++ show bodyNum ++ "::" showSwitch indent var ty val fused = startLine indent ++ "case " ++ show var ++ ":" ++ show ty ++ (if fused then " (fused)" else " (not fused)") ++ maybe "" (\v-> " (=" ++ show v ++ ")") val ++ " of" startLine :: Int -> String startLine tab = '\n' : replicate tab ' '
c3f4874d4e0f0d22100e6f7bf6b18a5eae70b510d4e7452d8f7f07e0e9df79b3
mfikes/fifth-postulate
ns119.cljs
(ns fifth-postulate.ns119) (defn solve-for01 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for02 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for03 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for04 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for05 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for06 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for07 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for08 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for09 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for10 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for11 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for12 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for13 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for14 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for15 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for16 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for17 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for18 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for19 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
null
https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns119.cljs
clojure
(ns fifth-postulate.ns119) (defn solve-for01 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for02 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for03 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for04 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for05 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for06 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for07 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for08 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for09 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for10 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for11 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for12 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for13 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for14 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for15 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for16 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for17 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for18 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))) (defn solve-for19 [xs v] (for [ndx0 (range 0 (- (count xs) 3)) ndx1 (range (inc ndx0) (- (count xs) 2)) ndx2 (range (inc ndx1) (- (count xs) 1)) ndx3 (range (inc ndx2) (count xs)) :when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))] (list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
93dde6493d351ce51d3b8a32fc94531b39510430957574562179569f1c3d1a57
cnuernber/dtype-next
ffi.clj
(ns tech.v3.datatype.ffi) (defmacro define-library! [lib-varname lib-fns _lib-symbols _error-checker] (let [fn-defs (second lib-fns)] `(do (def ~lib-varname :ok) ~@(map (fn [[fn-name fn-data]] (let [argvec (mapv first (:argtypes fn-data))] `(defn ~(symbol (name fn-name)) ~argvec (apply + ~argvec)))) fn-defs))))
null
https://raw.githubusercontent.com/cnuernber/dtype-next/4e43212942aafa0145640cf6b655bb83855f567d/resources/clj-kondo.exports/cnuernber/dtype-next/tech/v3/datatype/ffi.clj
clojure
(ns tech.v3.datatype.ffi) (defmacro define-library! [lib-varname lib-fns _lib-symbols _error-checker] (let [fn-defs (second lib-fns)] `(do (def ~lib-varname :ok) ~@(map (fn [[fn-name fn-data]] (let [argvec (mapv first (:argtypes fn-data))] `(defn ~(symbol (name fn-name)) ~argvec (apply + ~argvec)))) fn-defs))))
abe188fdb128522063c66580bf821526f6e49adcb608b1833853b3901089e280
iij/lmq
lmq_hook_crash.erl
-module(lmq_hook_crash). -export([init/0, hooks/0, activate/1, deactivate/1]). -export([hook1/2]). init() -> ok. hooks() -> [hook1, hook2]. activate([N]) -> {ok, N}. deactivate(N) -> N / 0. hook1(N, State) -> State / N.
null
https://raw.githubusercontent.com/iij/lmq/3f01c555af973a07a3f2b22ff95a2bc1c7930bc2/test/lmq_hook_crash.erl
erlang
-module(lmq_hook_crash). -export([init/0, hooks/0, activate/1, deactivate/1]). -export([hook1/2]). init() -> ok. hooks() -> [hook1, hook2]. activate([N]) -> {ok, N}. deactivate(N) -> N / 0. hook1(N, State) -> State / N.
14323f34b3eed6793896f7143c3318fd0ccc4e71b8d9a99bae7fe6319073aaf0
scarvalhojr/haskellbook
section24.11.hs
import Data.Char (digitToInt) import Control.Applicative ((<|>), (<*), (*>)) import Text.Parser.Char (char, oneOf) import Text.Parser.Combinators (some) import Text.Trifecta (Parser, parseString) 2 . parseDigit :: Parser Char parseDigit = oneOf ['0'..'9'] base10Integer :: Parser Integer base10Integer = read <$> some parseDigit 3 . base10Integer' :: Parser Integer base10Integer' = (char '-' *> (negate <$> base10Integer)) <|> base10Integer 4 . type NumberingPlanArea = Int type Exchange = Int type LineNumber = Int data PhoneNumber = PhoneNumber NumberingPlanArea Exchange LineNumber deriving (Eq, Show) parsePhone :: Parser PhoneNumber parsePhone = undefined
null
https://raw.githubusercontent.com/scarvalhojr/haskellbook/6016a5a78da3fc4a29f5ea68b239563895c448d5/chapter24/section24.11.hs
haskell
import Data.Char (digitToInt) import Control.Applicative ((<|>), (<*), (*>)) import Text.Parser.Char (char, oneOf) import Text.Parser.Combinators (some) import Text.Trifecta (Parser, parseString) 2 . parseDigit :: Parser Char parseDigit = oneOf ['0'..'9'] base10Integer :: Parser Integer base10Integer = read <$> some parseDigit 3 . base10Integer' :: Parser Integer base10Integer' = (char '-' *> (negate <$> base10Integer)) <|> base10Integer 4 . type NumberingPlanArea = Int type Exchange = Int type LineNumber = Int data PhoneNumber = PhoneNumber NumberingPlanArea Exchange LineNumber deriving (Eq, Show) parsePhone :: Parser PhoneNumber parsePhone = undefined
6bfb404e521f05cb46a11d126abf96ecadf9b63e9d3770aec0409012e97fde3d
derekmcloughlin/pearls
chap09e.hs
import System.IO import Data.List data Person = Person String | Celebrity String deriving (Show, Eq) type Party = [Person] knows :: Person -> Person -> Bool knows (Person p) (Celebrity c) = True knows (Celebrity c) (Person p) = False knows (Celebrity c1) (Celebrity c2) = True -- Most people at the party don't know each other except for and knows (Person "Ernie") (Person "Bert") = True knows (Person "Bert") (Person "Ernie") = True -- Everyone knows themselves knows (Person p1) (Person p2) | p1 == p2 = True | otherwise = False tom = Celebrity "Tom Cruise" cam = Celebrity "Cameron Diaz" matt = Celebrity "Matt Damon" john = Person "John Doe" jane = Person "Jane Doe" joe = Person "Joe Bloggs" ernie = Person "Ernie" bert = Person "Bert" celebs :: [Person] celebs = [cam, matt, tom] party = [bert, cam, ernie, joe, john, jane, matt, tom] subseqs [] = [[]] subseqs (x : xs) = map (x:) (subseqs xs) ++ subseqs xs splitIntoTwo :: [a] -> [([a], [a])] splitIntoTwo [] = [] splitIntoTwo xs = zip subs $ reverse subs where subs = subseqs xs is_clique :: ([Person], [Person]) -> Bool is_clique ([], _) = False is_clique (_, []) = False is_clique (cs, ps) = and [p `knows` c | c <- cs, p <- ps] && and [not (c `knows` p) | c <- cs, p <- ps] find_clique :: Party -> [Person] find_clique p = head [cs | (cs, ps) <- splitIntoTwo p, is_clique (cs, ps) == True] iff :: Bool -> Bool -> Bool iff a b = (not a || b) && (not b || a) nonmember :: Person -> [Person] -> Bool nonmember p cs = and [p `knows` c && not (c `knows` p) | c <- cs] member :: Person -> [Person] -> [Person] -> Bool member p ps cs = and [x `knows` p && iff (p `knows` x) (x `elem` cs) | x <- ps] cclique :: Party -> [Person] cclique = head . ccliques ccliques [] = [[]] ccliques (p : ps) = map (p:) (filter (member p ps) css) ++ filter (nonmember p) css where css = ccliques ps cclique' :: Party -> [Person] cclique' = foldr op [] op p cs | null cs = [p] | not (p `knows` c) = [p] | not (c `knows` p) = cs | otherwise = p:cs where c = head cs make_person :: Char -> String -> Person make_person c s | head s == c = Celebrity s | otherwise = Person s main = do handle <- openFile "names-200.txt" ReadMode contents <- hGetContents handle let irish_party = map (make_person 'S') $ lines contents putStrLn $ show $ cclique' irish_party
null
https://raw.githubusercontent.com/derekmcloughlin/pearls/42bc6ea0fecc105386a8b75789f563d44e05b772/chap09/chap09e.hs
haskell
Most people at the party don't know each other Everyone knows themselves
import System.IO import Data.List data Person = Person String | Celebrity String deriving (Show, Eq) type Party = [Person] knows :: Person -> Person -> Bool knows (Person p) (Celebrity c) = True knows (Celebrity c) (Person p) = False knows (Celebrity c1) (Celebrity c2) = True except for and knows (Person "Ernie") (Person "Bert") = True knows (Person "Bert") (Person "Ernie") = True knows (Person p1) (Person p2) | p1 == p2 = True | otherwise = False tom = Celebrity "Tom Cruise" cam = Celebrity "Cameron Diaz" matt = Celebrity "Matt Damon" john = Person "John Doe" jane = Person "Jane Doe" joe = Person "Joe Bloggs" ernie = Person "Ernie" bert = Person "Bert" celebs :: [Person] celebs = [cam, matt, tom] party = [bert, cam, ernie, joe, john, jane, matt, tom] subseqs [] = [[]] subseqs (x : xs) = map (x:) (subseqs xs) ++ subseqs xs splitIntoTwo :: [a] -> [([a], [a])] splitIntoTwo [] = [] splitIntoTwo xs = zip subs $ reverse subs where subs = subseqs xs is_clique :: ([Person], [Person]) -> Bool is_clique ([], _) = False is_clique (_, []) = False is_clique (cs, ps) = and [p `knows` c | c <- cs, p <- ps] && and [not (c `knows` p) | c <- cs, p <- ps] find_clique :: Party -> [Person] find_clique p = head [cs | (cs, ps) <- splitIntoTwo p, is_clique (cs, ps) == True] iff :: Bool -> Bool -> Bool iff a b = (not a || b) && (not b || a) nonmember :: Person -> [Person] -> Bool nonmember p cs = and [p `knows` c && not (c `knows` p) | c <- cs] member :: Person -> [Person] -> [Person] -> Bool member p ps cs = and [x `knows` p && iff (p `knows` x) (x `elem` cs) | x <- ps] cclique :: Party -> [Person] cclique = head . ccliques ccliques [] = [[]] ccliques (p : ps) = map (p:) (filter (member p ps) css) ++ filter (nonmember p) css where css = ccliques ps cclique' :: Party -> [Person] cclique' = foldr op [] op p cs | null cs = [p] | not (p `knows` c) = [p] | not (c `knows` p) = cs | otherwise = p:cs where c = head cs make_person :: Char -> String -> Person make_person c s | head s == c = Celebrity s | otherwise = Person s main = do handle <- openFile "names-200.txt" ReadMode contents <- hGetContents handle let irish_party = map (make_person 'S') $ lines contents putStrLn $ show $ cclique' irish_party
b318e016e8ce51dab5920c1d2ff3599b8d7e436f425446e181fc7e50bd0dd501
lispgames/glop
glop.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*- (in-package #:glop) (defdfun gl-get-proc-address (proc-name) "Get foreign pointer to the GL extension designed by PROC-NAME." (declare (ignore proc-name)) (error 'not-implemented)) ;;; Display management (defgeneric list-video-modes () (:documentation "Returns a list of all available video modes as a list video-mode structs.")) (defgeneric set-video-mode (mode) (:documentation "Attempts to set the provided video mode.")) (defgeneric current-video-mode () (:documentation "Returns the current video mode.")) ;; XXX: stupid distance match is maybe not the best option here... (defun closest-video-mode (current-mode modes-list dwidth dheight &optional ddepth drate) "Try to find the closest video mode matching desired parameters within modes-list. Returns NIL if no match is found." (unless drate (setf drate (video-mode-rate current-mode))) (unless ddepth (setf ddepth (video-mode-depth current-mode))) (loop with best-match = nil with best-dist = most-positive-fixnum for mode in (remove-if (lambda (it) (or (/= (video-mode-rate it) drate) (/= (video-mode-depth it) ddepth))) modes-list) for current-dist = (+ (* (- dwidth (video-mode-width mode)) (- dwidth (video-mode-width mode))) (* (- dheight (video-mode-height mode)) (- dheight (video-mode-height mode)))) when (< current-dist best-dist) do (setf best-dist current-dist best-match mode) finally (return best-match))) ;;; Context management (defgeneric create-gl-context (window &key make-current major minor forward-compat debug profile) (:documentation "Creates a new OpenGL context of the specified version for the provided window and optionally make it current (default). If major and minor are NIL old style context creation is used. Otherwise a context compatible with minimum major.minor version is created. If you request a specific context version, you may use the additional arguments to setup context options. The foward-compat argument specify whether to disallow legacy functionalities (only for GL version >= 3.0). The debug argument specify whether a debug context should be created. You may request a specific context profile by specifiying either :core or :compat as the profile argument value.")) (defgeneric destroy-gl-context (ctx) (:documentation "Detach and release the provided OpenGL context.")) (defgeneric attach-gl-context (window ctx) (:documentation "Makes CTX the current OpenGL context and attach it to WINDOW.")) (defgeneric detach-gl-context (ctx) (:documentation "Make the provided OpenGL context no longer current.")) ;;; Window management (defgeneric open-window (window title width height &key x y rgba double-buffer stereo red-size green-size blue-size alpha-size depth-size accum-buffer accum-red-size accum-green-size accum-blue-size stencil-buffer stencil-size) (:documentation "Creates a new window *without* any GL context.")) (defgeneric close-window (window) (:documentation "Closes the provided window *without* releasing any attached GL context.")) (defgeneric %init-swap-interval (window) (:method (w) (setf (swap-interval-function w) :unsupported))) (defun create-window (title width height &key (x 0) (y 0) major minor fullscreen (win-class 'window) (double-buffer t) stereo (red-size 4) (green-size 4) (blue-size 4) (alpha-size 4) (depth-size 16) accum-buffer (accum-red-size 0) (accum-green-size 0) (accum-blue-size 0) stencil-buffer (stencil-size 0) profile (gl t)) "Creates a new window with an attached GL context using the provided visual attributes. Major and minor arguments specify the context version to use. When NIL (default value) old style gl context creation is used. Some combinations of platforms and drivers may require :PROFILE :CORE to use versions newer than 2.1, while others will use newest version even if version is not specified. The created window will be of the WINDOW class, you can override this by specifying your own class using :WIN-CLASS." (let ((win (make-instance win-class))) (open-window win title width height :x x :y y :double-buffer double-buffer :stereo stereo :red-size red-size :green-size green-size :blue-size blue-size :alpha-size alpha-size :depth-size depth-size :accum-buffer accum-buffer :accum-red-size accum-red-size :accum-green-size accum-green-size :accum-blue-size accum-blue-size :stencil-buffer stencil-buffer :stencil-size stencil-size) (if gl (create-gl-context win :major major :minor minor :make-current t :profile profile) (setf (window-gl-context win) nil)) (show-window win) (set-fullscreen win fullscreen) win)) (defun destroy-window (window) "Destroy the provided window and any attached GL context." (set-fullscreen window nil) (when (window-gl-context window) (destroy-gl-context (window-gl-context window))) (close-window window)) (defgeneric set-fullscreen (window &optional state) (:documentation "Set window to fullscreen state.")) ( defmethod set - fullscreen : around ( window & optional state ) ;; (unless (eq state (window-fullscreen window)) ;; (call-next-method) ( setf ( window - fullscreen window ) state ) ) ) (defun toggle-fullscreen (window) "Attempt to change display mode to the mode closest to geometry and set window fullscreen state." (cond ((and (window-previous-video-mode window) (window-fullscreen window)) (progn (set-fullscreen window nil) (set-video-mode (window-previous-video-mode window)) (setf (window-previous-video-mode window) nil))) ((not (window-fullscreen window)) (progn (setf (window-previous-video-mode window) (current-video-mode)) (set-video-mode (closest-video-mode (current-video-mode) (list-video-modes) (window-width window) (window-height window))) (set-fullscreen window t))))) (defgeneric set-geometry (window x y width height) (:documentation "Configure window geometry.")) (defmethod (setf window-x) (x (win window)) (set-geometry win x (window-y win) (window-width win) (window-height win))) (defmethod (setf window-y) (y (win window)) (set-geometry win (window-x win) y (window-width win) (window-height win))) (defmethod (setf window-width) (width (win window)) (set-geometry win (window-x win) (window-y win) width (window-height win))) (defmethod (setf window-height) (height (win window)) (set-geometry win (window-x win) (window-y win) (window-width win) height)) (defgeneric show-window (window) (:documentation "Make WINDOW visible. (may need to be called twice when window is shown for the first time on Windows.)")) (defgeneric hide-window (window) (:documentation "Make WINDOW not visible.")) (defgeneric set-window-title (window title) (:documentation "Set WINDOW title to TITLE.")) (defgeneric swap-buffers (window) (:documentation "Swaps GL buffers.")) (defgeneric swap-interval (window interval) (:documentation "Specify number of vsync intervals to wait before swap-buffers takes effect. Use 0 for no vsync, 1 for normal vsync, 2 for 1/2 monitor refresh rate, etc. If INTERVAL is negativem the absolute value is used, and when supported swap won't wait for vsync if specified interval has already elapsed. May be ignored or only partially supported depending on platform and user settings.") windows : only supports 0/1 when dwm is enabled ( always on win8 + i think ? ) ( possibly could support > 1 with dwm , but hard to detect if some vsync ;; already passed so would always wait N frames. Possibly could combine a normal SwapInterval call with N-1 and a dwmFlush ? ) linux : todo ( depends on GLX_EXT_swap_control , GLX_EXT_swap_control_tear osx : todo ;; todo: some way to query supported options (:method (w i) ;; just do nothing by default for now (declare (ignore w i)))) (defgeneric show-cursor (window) (:documentation "Enable cursor display for WINDOW")) (defgeneric hide-cursor (window) (:documentation "Disable cursor display for WINDOW")) ;; slightly lower-level API for things related to fullscreen (defgeneric maximize-window (window) (:documentation "'Maximize' a window to fill screen, without changing screen mode or window decoractions.")) (defgeneric restore-window (window) (:documentation "Undo the effects of MAXIMIZE-WINDOW")) (defgeneric remove-window-decorations (window) (:documentation "Remove window border, title, etc. if possible.")) (defgeneric restore-window-decorations (window) (:documentation "Restore window border, title, etc.")) ;;; Events handling (defmacro define-simple-print-object (type &rest attribs) `(defmethod print-object ((event ,type) stream) (with-slots ,attribs event (format stream ,(format nil "#<~~s~{ ~s ~~s~}>" attribs) (type-of event) ,@attribs)))) (defclass event () () (:documentation "Common ancestor for all events.")) (defclass key-event (event) ((keycode :initarg :keycode :reader keycode) (keysym :initarg :keysym :reader keysym) (text :initarg :text :reader text) (pressed :initarg :pressed :reader pressed)) (:documentation "Keyboard key press or release.")) (define-simple-print-object key-event keycode keysym text pressed) (defclass key-press-event (key-event) () (:default-initargs :pressed t) (:documentation "Keyboard key press.")) (defclass key-release-event (key-event) () (:default-initargs :pressed nil) (:documentation "Keyboard key release.")) (defclass button-event (event) ((button :initarg :button :reader button) (pressed :initarg :pressed :reader pressed)) (:documentation "Mouse button press or release.")) (define-simple-print-object button-event button pressed) (defclass button-press-event (button-event) () (:default-initargs :pressed t) (:documentation "Mouse button press.")) (defclass button-release-event (button-event) () (:default-initargs :pressed nil) (:documentation "Mouse button release.")) (defclass mouse-motion-event (event) ((x :initarg :x :reader x) (y :initarg :y :reader y) (dx :initarg :dx :reader dx) (dy :initarg :dy :reader dy)) (:documentation "Mouse motion.")) (define-simple-print-object mouse-motion-event x y dx dy) (defclass expose-event (event) ((width :initarg :width :reader width) (height :initarg :height :reader height)) (:documentation "Window expose.")) (define-simple-print-object expose-event width height) (defclass resize-event (event) ((width :initarg :width :reader width) (height :initarg :height :reader height)) (:documentation "Window resized.")) (define-simple-print-object resize-event width height) (defclass close-event (event) () (:documentation "Window closed.")) (defclass visibility-event (event) ((visible :initarg :visible :reader visible)) (:documentation "Window visibility changed.")) (define-simple-print-object visibility-event visible) (defclass visibility-obscured-event (visibility-event) () (:default-initargs :visible nil) (:documentation "Window was fully obscured.")) (defclass visibility-unobscured-event (visibility-event) () (:default-initargs :visible t) (:documentation "Window was unobscured.")) (defclass focus-event (event) ((focused :initarg :focused :reader focused)) (:documentation "Window focus state changed.")) (define-simple-print-object focus-event focused) (defclass focus-in-event (focus-event) () (:default-initargs :focused t) (:documentation "Window received focus.")) (defclass focus-out-event (focus-event) () (:default-initargs :focused nil) (:documentation "Window lost focus.")) (defclass child-event (event) ;; 'child' is platform specific id of child window for now. ;; might be nicer to wrap it in some class, but then we would have ;; to maintain a mapping of IDs to instances, and would probably ;; want some way for applications to specify which class as well ((child :initarg :child :reader child)) (:documentation "Status of child window changed.")) (defclass child-created-event (child-event) ;; 'parent' is a platform specific ID, for similar reasons to ;; 'child' above... ((parent :initarg :parent :reader parent) (x :initarg :x :reader x) (y :initarg :y :reader y) (width :initarg :width :reader width) (height :initarg :height :reader height))) (define-simple-print-object child-created-event x y width height) (defclass child-destroyed-event (child-event) ;; 'parent' is a platform specific ID, for similar reasons to ;; 'child' above... ((parent :initarg :parent :reader parent))) (define-simple-print-object child-destroyed-event parent child) (defclass child-reparent-event (child-event) ;; 'parent' is a platform specific ID, for similar reasons to ;; 'child' above... ((parent :initarg :parent :reader parent) (x :initarg :x :reader x) (y :initarg :y :reader y))) (define-simple-print-object child-reparent-event x y) (defclass child-visibility-event (child-event) ((visible :initarg :visible :reader visible)) (:documentation "Child window visibility changed.")) (define-simple-print-object child-visibility-event visible) (defclass child-visibility-obscured-event (child-visibility-event) () (:default-initargs :visible nil) (:documentation "Child window was fully obscured.")) (defclass child-visibility-unobscured-event (child-visibility-event) () (:default-initargs :visible t) (:documentation "Child window was unobscured.")) (defclass child-resize-event (child-event) ;; possibly should store position too unless we figure out how to map ;; child IDs to actual window instances? ((width :initarg :width :reader width) (height :initarg :height :reader height)) (:documentation "Child window resized.")) (define-simple-print-object child-resize-event width height) (defun push-event (window evt) "Push an artificial event into the event processing system. Note that this has no effect on the underlying window system." (setf (window-pushed-event window) evt)) (defun push-close-event (window) "Push an artificial :close event into the event processing system." (push-event window (make-instance 'close-event))) (defgeneric next-event (window &key blocking) (:documentation "Returns next available event for manual processing. If :blocking is true, wait for an event.")) (defmethod next-event ((win window) &key blocking) (let ((pushed-evt (window-pushed-event win))) (if pushed-evt (progn (setf (window-pushed-event win) nil) pushed-evt) (%next-event win :blocking blocking)))) (defdfun %next-event (window &key blocking) "Real next-event implementation." (declare (ignore window blocking)) (error 'not-implemented)) ;; method based event handling (defmacro dispatch-events (window &key blocking (on-foo t)) "Process all pending system events and call corresponding methods. When :blocking is non-nil calls event handling func that will block until an event occurs. Returns NIL on :CLOSE event, T otherwise." (let ((evt (gensym))) `(block dispatch-events (loop for ,evt = (next-event ,window :blocking ,blocking) while ,evt do ,(if on-foo `(typecase ,evt (key-press-event (on-key ,window t (keycode ,evt) (keysym ,evt) (text ,evt))) (key-release-event (on-key ,window nil (keycode ,evt) (keysym ,evt) (text ,evt))) (button-press-event (on-button ,window t (button ,evt))) (button-release-event (on-button ,window nil (button ,evt))) (mouse-motion-event (on-mouse-motion ,window (x ,evt) (y ,evt) (dx ,evt) (dy ,evt))) (resize-event (on-resize ,window (width ,evt) (height ,evt))) (expose-event (on-resize ,window (width ,evt) (height ,evt)) (on-draw ,window)) (visibility-event (on-visibility ,window (visible ,evt))) (focus-event (on-focus ,window (focused ,evt))) (close-event (on-close ,window) (return-from dispatch-events nil)) (t (format t "Unhandled event type: ~S~%" (type-of ,evt)))) `(progn (on-event ,window ,evt) (when (eql (type-of ,evt) 'close-event) (return-from dispatch-events nil)))) finally (return t))))) ;; implement this genfun when calling dispatch-events with :on-foo NIL (defgeneric on-event (window event)) (defmethod on-event (window event) (declare (ignore window)) (format t "Unhandled event: ~S~%" event)) ;; implement those when calling dispatch-events with :on-foo T (defgeneric on-key (window pressed keycode keysym string)) (defgeneric on-button (window pressed button)) (defgeneric on-mouse-motion (window x y dx dy)) (defgeneric on-resize (window w h)) (defgeneric on-draw (window)) (defgeneric on-close (window)) ;; these are here for completeness but default methods are provided (defgeneric on-visibility (window visible)) (defgeneric on-focus (window focused)) (defmethod on-visibility (window visible) (declare (ignore window visible))) (defmethod on-focus (window focused-p) (declare (ignore window focused-p))) ;; main loop anyone? (defmacro with-idle-forms (window &body idle-forms) (let ((blocking (unless idle-forms t)) (res (gensym))) `(loop with ,res = (dispatch-events ,window :blocking ,blocking) while ,res do ,(if idle-forms `(progn ,@idle-forms) t)))) (defmacro with-window ((win-sym title width height &rest attribs) &body body) "Creates a window and binds it to WIN-SYM. The window is detroyed when body exits." `(let ((,win-sym (create-window ,title ,width ,height ,@attribs))) (when ,win-sym (unwind-protect (progn ,@body) (destroy-window ,win-sym))))) ;; multiple windows management (defun set-gl-window (window) "Make WINDOW current for GL rendering." (attach-gl-context window (window-gl-context window)))
null
https://raw.githubusercontent.com/lispgames/glop/45e722ab4a0cd2944d550bf790206b3326041e38/src/glop.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 ; indent - tabs - mode : nil -*- Display management XXX: stupid distance match is maybe not the best option here... Context management Window management (unless (eq state (window-fullscreen window)) (call-next-method) already passed so would always wait N frames. Possibly could combine todo: some way to query supported options just do nothing by default for now slightly lower-level API for things related to fullscreen Events handling 'child' is platform specific id of child window for now. might be nicer to wrap it in some class, but then we would have to maintain a mapping of IDs to instances, and would probably want some way for applications to specify which class as well 'parent' is a platform specific ID, for similar reasons to 'child' above... 'parent' is a platform specific ID, for similar reasons to 'child' above... 'parent' is a platform specific ID, for similar reasons to 'child' above... possibly should store position too unless we figure out how to map child IDs to actual window instances? method based event handling implement this genfun when calling dispatch-events with :on-foo NIL implement those when calling dispatch-events with :on-foo T these are here for completeness but default methods are provided main loop anyone? multiple windows management
(in-package #:glop) (defdfun gl-get-proc-address (proc-name) "Get foreign pointer to the GL extension designed by PROC-NAME." (declare (ignore proc-name)) (error 'not-implemented)) (defgeneric list-video-modes () (:documentation "Returns a list of all available video modes as a list video-mode structs.")) (defgeneric set-video-mode (mode) (:documentation "Attempts to set the provided video mode.")) (defgeneric current-video-mode () (:documentation "Returns the current video mode.")) (defun closest-video-mode (current-mode modes-list dwidth dheight &optional ddepth drate) "Try to find the closest video mode matching desired parameters within modes-list. Returns NIL if no match is found." (unless drate (setf drate (video-mode-rate current-mode))) (unless ddepth (setf ddepth (video-mode-depth current-mode))) (loop with best-match = nil with best-dist = most-positive-fixnum for mode in (remove-if (lambda (it) (or (/= (video-mode-rate it) drate) (/= (video-mode-depth it) ddepth))) modes-list) for current-dist = (+ (* (- dwidth (video-mode-width mode)) (- dwidth (video-mode-width mode))) (* (- dheight (video-mode-height mode)) (- dheight (video-mode-height mode)))) when (< current-dist best-dist) do (setf best-dist current-dist best-match mode) finally (return best-match))) (defgeneric create-gl-context (window &key make-current major minor forward-compat debug profile) (:documentation "Creates a new OpenGL context of the specified version for the provided window and optionally make it current (default). If major and minor are NIL old style context creation is used. Otherwise a context compatible with minimum major.minor version is created. If you request a specific context version, you may use the additional arguments to setup context options. The foward-compat argument specify whether to disallow legacy functionalities (only for GL version >= 3.0). The debug argument specify whether a debug context should be created. You may request a specific context profile by specifiying either :core or :compat as the profile argument value.")) (defgeneric destroy-gl-context (ctx) (:documentation "Detach and release the provided OpenGL context.")) (defgeneric attach-gl-context (window ctx) (:documentation "Makes CTX the current OpenGL context and attach it to WINDOW.")) (defgeneric detach-gl-context (ctx) (:documentation "Make the provided OpenGL context no longer current.")) (defgeneric open-window (window title width height &key x y rgba double-buffer stereo red-size green-size blue-size alpha-size depth-size accum-buffer accum-red-size accum-green-size accum-blue-size stencil-buffer stencil-size) (:documentation "Creates a new window *without* any GL context.")) (defgeneric close-window (window) (:documentation "Closes the provided window *without* releasing any attached GL context.")) (defgeneric %init-swap-interval (window) (:method (w) (setf (swap-interval-function w) :unsupported))) (defun create-window (title width height &key (x 0) (y 0) major minor fullscreen (win-class 'window) (double-buffer t) stereo (red-size 4) (green-size 4) (blue-size 4) (alpha-size 4) (depth-size 16) accum-buffer (accum-red-size 0) (accum-green-size 0) (accum-blue-size 0) stencil-buffer (stencil-size 0) profile (gl t)) "Creates a new window with an attached GL context using the provided visual attributes. Major and minor arguments specify the context version to use. When NIL (default value) old style gl context creation is used. Some combinations of platforms and drivers may require :PROFILE :CORE to use versions newer than 2.1, while others will use newest version even if version is not specified. The created window will be of the WINDOW class, you can override this by specifying your own class using :WIN-CLASS." (let ((win (make-instance win-class))) (open-window win title width height :x x :y y :double-buffer double-buffer :stereo stereo :red-size red-size :green-size green-size :blue-size blue-size :alpha-size alpha-size :depth-size depth-size :accum-buffer accum-buffer :accum-red-size accum-red-size :accum-green-size accum-green-size :accum-blue-size accum-blue-size :stencil-buffer stencil-buffer :stencil-size stencil-size) (if gl (create-gl-context win :major major :minor minor :make-current t :profile profile) (setf (window-gl-context win) nil)) (show-window win) (set-fullscreen win fullscreen) win)) (defun destroy-window (window) "Destroy the provided window and any attached GL context." (set-fullscreen window nil) (when (window-gl-context window) (destroy-gl-context (window-gl-context window))) (close-window window)) (defgeneric set-fullscreen (window &optional state) (:documentation "Set window to fullscreen state.")) ( defmethod set - fullscreen : around ( window & optional state ) ( setf ( window - fullscreen window ) state ) ) ) (defun toggle-fullscreen (window) "Attempt to change display mode to the mode closest to geometry and set window fullscreen state." (cond ((and (window-previous-video-mode window) (window-fullscreen window)) (progn (set-fullscreen window nil) (set-video-mode (window-previous-video-mode window)) (setf (window-previous-video-mode window) nil))) ((not (window-fullscreen window)) (progn (setf (window-previous-video-mode window) (current-video-mode)) (set-video-mode (closest-video-mode (current-video-mode) (list-video-modes) (window-width window) (window-height window))) (set-fullscreen window t))))) (defgeneric set-geometry (window x y width height) (:documentation "Configure window geometry.")) (defmethod (setf window-x) (x (win window)) (set-geometry win x (window-y win) (window-width win) (window-height win))) (defmethod (setf window-y) (y (win window)) (set-geometry win (window-x win) y (window-width win) (window-height win))) (defmethod (setf window-width) (width (win window)) (set-geometry win (window-x win) (window-y win) width (window-height win))) (defmethod (setf window-height) (height (win window)) (set-geometry win (window-x win) (window-y win) (window-width win) height)) (defgeneric show-window (window) (:documentation "Make WINDOW visible. (may need to be called twice when window is shown for the first time on Windows.)")) (defgeneric hide-window (window) (:documentation "Make WINDOW not visible.")) (defgeneric set-window-title (window title) (:documentation "Set WINDOW title to TITLE.")) (defgeneric swap-buffers (window) (:documentation "Swaps GL buffers.")) (defgeneric swap-interval (window interval) (:documentation "Specify number of vsync intervals to wait before swap-buffers takes effect. Use 0 for no vsync, 1 for normal vsync, 2 for 1/2 monitor refresh rate, etc. If INTERVAL is negativem the absolute value is used, and when supported swap won't wait for vsync if specified interval has already elapsed. May be ignored or only partially supported depending on platform and user settings.") windows : only supports 0/1 when dwm is enabled ( always on win8 + i think ? ) ( possibly could support > 1 with dwm , but hard to detect if some vsync a normal SwapInterval call with N-1 and a dwmFlush ? ) linux : todo ( depends on GLX_EXT_swap_control , GLX_EXT_swap_control_tear osx : todo (:method (w i) (declare (ignore w i)))) (defgeneric show-cursor (window) (:documentation "Enable cursor display for WINDOW")) (defgeneric hide-cursor (window) (:documentation "Disable cursor display for WINDOW")) (defgeneric maximize-window (window) (:documentation "'Maximize' a window to fill screen, without changing screen mode or window decoractions.")) (defgeneric restore-window (window) (:documentation "Undo the effects of MAXIMIZE-WINDOW")) (defgeneric remove-window-decorations (window) (:documentation "Remove window border, title, etc. if possible.")) (defgeneric restore-window-decorations (window) (:documentation "Restore window border, title, etc.")) (defmacro define-simple-print-object (type &rest attribs) `(defmethod print-object ((event ,type) stream) (with-slots ,attribs event (format stream ,(format nil "#<~~s~{ ~s ~~s~}>" attribs) (type-of event) ,@attribs)))) (defclass event () () (:documentation "Common ancestor for all events.")) (defclass key-event (event) ((keycode :initarg :keycode :reader keycode) (keysym :initarg :keysym :reader keysym) (text :initarg :text :reader text) (pressed :initarg :pressed :reader pressed)) (:documentation "Keyboard key press or release.")) (define-simple-print-object key-event keycode keysym text pressed) (defclass key-press-event (key-event) () (:default-initargs :pressed t) (:documentation "Keyboard key press.")) (defclass key-release-event (key-event) () (:default-initargs :pressed nil) (:documentation "Keyboard key release.")) (defclass button-event (event) ((button :initarg :button :reader button) (pressed :initarg :pressed :reader pressed)) (:documentation "Mouse button press or release.")) (define-simple-print-object button-event button pressed) (defclass button-press-event (button-event) () (:default-initargs :pressed t) (:documentation "Mouse button press.")) (defclass button-release-event (button-event) () (:default-initargs :pressed nil) (:documentation "Mouse button release.")) (defclass mouse-motion-event (event) ((x :initarg :x :reader x) (y :initarg :y :reader y) (dx :initarg :dx :reader dx) (dy :initarg :dy :reader dy)) (:documentation "Mouse motion.")) (define-simple-print-object mouse-motion-event x y dx dy) (defclass expose-event (event) ((width :initarg :width :reader width) (height :initarg :height :reader height)) (:documentation "Window expose.")) (define-simple-print-object expose-event width height) (defclass resize-event (event) ((width :initarg :width :reader width) (height :initarg :height :reader height)) (:documentation "Window resized.")) (define-simple-print-object resize-event width height) (defclass close-event (event) () (:documentation "Window closed.")) (defclass visibility-event (event) ((visible :initarg :visible :reader visible)) (:documentation "Window visibility changed.")) (define-simple-print-object visibility-event visible) (defclass visibility-obscured-event (visibility-event) () (:default-initargs :visible nil) (:documentation "Window was fully obscured.")) (defclass visibility-unobscured-event (visibility-event) () (:default-initargs :visible t) (:documentation "Window was unobscured.")) (defclass focus-event (event) ((focused :initarg :focused :reader focused)) (:documentation "Window focus state changed.")) (define-simple-print-object focus-event focused) (defclass focus-in-event (focus-event) () (:default-initargs :focused t) (:documentation "Window received focus.")) (defclass focus-out-event (focus-event) () (:default-initargs :focused nil) (:documentation "Window lost focus.")) (defclass child-event (event) ((child :initarg :child :reader child)) (:documentation "Status of child window changed.")) (defclass child-created-event (child-event) ((parent :initarg :parent :reader parent) (x :initarg :x :reader x) (y :initarg :y :reader y) (width :initarg :width :reader width) (height :initarg :height :reader height))) (define-simple-print-object child-created-event x y width height) (defclass child-destroyed-event (child-event) ((parent :initarg :parent :reader parent))) (define-simple-print-object child-destroyed-event parent child) (defclass child-reparent-event (child-event) ((parent :initarg :parent :reader parent) (x :initarg :x :reader x) (y :initarg :y :reader y))) (define-simple-print-object child-reparent-event x y) (defclass child-visibility-event (child-event) ((visible :initarg :visible :reader visible)) (:documentation "Child window visibility changed.")) (define-simple-print-object child-visibility-event visible) (defclass child-visibility-obscured-event (child-visibility-event) () (:default-initargs :visible nil) (:documentation "Child window was fully obscured.")) (defclass child-visibility-unobscured-event (child-visibility-event) () (:default-initargs :visible t) (:documentation "Child window was unobscured.")) (defclass child-resize-event (child-event) ((width :initarg :width :reader width) (height :initarg :height :reader height)) (:documentation "Child window resized.")) (define-simple-print-object child-resize-event width height) (defun push-event (window evt) "Push an artificial event into the event processing system. Note that this has no effect on the underlying window system." (setf (window-pushed-event window) evt)) (defun push-close-event (window) "Push an artificial :close event into the event processing system." (push-event window (make-instance 'close-event))) (defgeneric next-event (window &key blocking) (:documentation "Returns next available event for manual processing. If :blocking is true, wait for an event.")) (defmethod next-event ((win window) &key blocking) (let ((pushed-evt (window-pushed-event win))) (if pushed-evt (progn (setf (window-pushed-event win) nil) pushed-evt) (%next-event win :blocking blocking)))) (defdfun %next-event (window &key blocking) "Real next-event implementation." (declare (ignore window blocking)) (error 'not-implemented)) (defmacro dispatch-events (window &key blocking (on-foo t)) "Process all pending system events and call corresponding methods. When :blocking is non-nil calls event handling func that will block until an event occurs. Returns NIL on :CLOSE event, T otherwise." (let ((evt (gensym))) `(block dispatch-events (loop for ,evt = (next-event ,window :blocking ,blocking) while ,evt do ,(if on-foo `(typecase ,evt (key-press-event (on-key ,window t (keycode ,evt) (keysym ,evt) (text ,evt))) (key-release-event (on-key ,window nil (keycode ,evt) (keysym ,evt) (text ,evt))) (button-press-event (on-button ,window t (button ,evt))) (button-release-event (on-button ,window nil (button ,evt))) (mouse-motion-event (on-mouse-motion ,window (x ,evt) (y ,evt) (dx ,evt) (dy ,evt))) (resize-event (on-resize ,window (width ,evt) (height ,evt))) (expose-event (on-resize ,window (width ,evt) (height ,evt)) (on-draw ,window)) (visibility-event (on-visibility ,window (visible ,evt))) (focus-event (on-focus ,window (focused ,evt))) (close-event (on-close ,window) (return-from dispatch-events nil)) (t (format t "Unhandled event type: ~S~%" (type-of ,evt)))) `(progn (on-event ,window ,evt) (when (eql (type-of ,evt) 'close-event) (return-from dispatch-events nil)))) finally (return t))))) (defgeneric on-event (window event)) (defmethod on-event (window event) (declare (ignore window)) (format t "Unhandled event: ~S~%" event)) (defgeneric on-key (window pressed keycode keysym string)) (defgeneric on-button (window pressed button)) (defgeneric on-mouse-motion (window x y dx dy)) (defgeneric on-resize (window w h)) (defgeneric on-draw (window)) (defgeneric on-close (window)) (defgeneric on-visibility (window visible)) (defgeneric on-focus (window focused)) (defmethod on-visibility (window visible) (declare (ignore window visible))) (defmethod on-focus (window focused-p) (declare (ignore window focused-p))) (defmacro with-idle-forms (window &body idle-forms) (let ((blocking (unless idle-forms t)) (res (gensym))) `(loop with ,res = (dispatch-events ,window :blocking ,blocking) while ,res do ,(if idle-forms `(progn ,@idle-forms) t)))) (defmacro with-window ((win-sym title width height &rest attribs) &body body) "Creates a window and binds it to WIN-SYM. The window is detroyed when body exits." `(let ((,win-sym (create-window ,title ,width ,height ,@attribs))) (when ,win-sym (unwind-protect (progn ,@body) (destroy-window ,win-sym))))) (defun set-gl-window (window) "Make WINDOW current for GL rendering." (attach-gl-context window (window-gl-context window)))
e775d42400a1fe806e3b124bd29ecd0ddd14a7897221e4a2448707ecc78884f0
facebookarchive/pfff
class_basic.ml
class foo = object(self) method foo = 1 end
null
https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/tests/ml/parsing/class_basic.ml
ocaml
class foo = object(self) method foo = 1 end
ae77817b857556e97b3aa2fe73a63a881e43c4853ee990ccdd55cb0e9965ec76
databrary/databrary
Service.hs
{-# LANGUAGE OverloadedStrings #-} module EZID.Service ( EZID(..) , initEZID ) where import Control.Monad (unless, forM) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Network.HTTP.Client as HC import Network.HTTP.Types (hContentType) import qualified Store.Config as C data EZID = EZID { ezidRequest :: !HC.Request , ezidNS :: !BS.ByteString } initEZID :: C.Config -> IO (Maybe EZID) initEZID conf = conf C.! "ns" `forM` \ns -> do unless ("doi:10." `BSC.isPrefixOf` ns) $ fail "ezid.ns must be for DOIs" req <- HC.parseRequest ":3000" return $ EZID { ezidRequest = HC.applyBasicAuth (conf C.! "user") (conf C.! "pass") req { HC.requestHeaders = (hContentType, "text/plain") : HC.requestHeaders req , HC.responseTimeout = HC.responseTimeoutMicro 100000000 , HC.redirectCount = 1 } , ezidNS = ns }
null
https://raw.githubusercontent.com/databrary/databrary/c5a03129c6c113a12fc649b2852a972325bfcdb9/src/EZID/Service.hs
haskell
# LANGUAGE OverloadedStrings #
module EZID.Service ( EZID(..) , initEZID ) where import Control.Monad (unless, forM) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Network.HTTP.Client as HC import Network.HTTP.Types (hContentType) import qualified Store.Config as C data EZID = EZID { ezidRequest :: !HC.Request , ezidNS :: !BS.ByteString } initEZID :: C.Config -> IO (Maybe EZID) initEZID conf = conf C.! "ns" `forM` \ns -> do unless ("doi:10." `BSC.isPrefixOf` ns) $ fail "ezid.ns must be for DOIs" req <- HC.parseRequest ":3000" return $ EZID { ezidRequest = HC.applyBasicAuth (conf C.! "user") (conf C.! "pass") req { HC.requestHeaders = (hContentType, "text/plain") : HC.requestHeaders req , HC.responseTimeout = HC.responseTimeoutMicro 100000000 , HC.redirectCount = 1 } , ezidNS = ns }
913bc0d6202b9e3735edfc6b1a33a77151cfba72937da7fbd1fc6000f1765a32
theodormoroianu/SecondYearCourses
LambdaChurch_20210415164346.hs
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) -- alpha-equivalence aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) -- subst u x t defines [u/x]t, i.e., substituting u for x in t for example [ 3 / x](x + x ) = = 3 + 3 -- This substitution avoids variable captures so it is safe to be used when -- reducing terms with free variables (e.g., if evaluating inside lambda abstractions) subst :: Term -- ^ substitution term -> Variable -- ^ variable to be substitutes -> Term -- ^ term in which the substitution occurs -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV -- Normal order reduction -- - like call by name -- - but also reduce under lambda abstractions if no application is possible -- - guarantees reaching a normal form if it exists normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce -- alpha-beta equivalence (for strongly normalizing terms) is obtained by -- fully evaluating the terms using beta-reduction, then checking their -- alpha-equivalence. abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s -- Church Encodings in Lambda churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church0 = lams ["s", "z"] (v "z") -- note that it's the same as churchFalse church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") cPair :: a -> b -> CPair a b cPair = \x y -> CPair $ \action -> action x y churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) cFst :: CPair a b -> a cFst = \p -> (cOn p $ \x y -> x) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) cSnd :: CPair a b -> b cSnd = \p -> (cOn p $ \x y -> y) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) cFactorial :: CNat -> CNat cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) cFibonacci :: CNat -> CNat cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m) newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } instance Foldable CList where foldr agg init xs = cFoldR xs agg init churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
null
https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415164346.hs
haskell
alpha-equivalence subst u x t defines [u/x]t, i.e., substituting u for x in t This substitution avoids variable captures so it is safe to be used when reducing terms with free variables (e.g., if evaluating inside lambda abstractions) ^ substitution term ^ variable to be substitutes ^ term in which the substitution occurs Normal order reduction - like call by name - but also reduce under lambda abstractions if no application is possible - guarantees reaching a normal form if it exists alpha-beta equivalence (for strongly normalizing terms) is obtained by fully evaluating the terms using beta-reduction, then checking their alpha-equivalence. Church Encodings in Lambda note that it's the same as churchFalse
module LambdaChurch where import Data.Char (isLetter) import Data.List ( nub ) class ShowNice a where showNice :: a -> String class ReadNice a where readNice :: String -> (a, String) data Variable = Variable { name :: String , count :: Int } deriving (Show, Eq, Ord) var :: String -> Variable var x = Variable x 0 instance ShowNice Variable where showNice (Variable x 0) = x showNice (Variable x cnt) = x <> "_" <> show cnt instance ReadNice Variable where readNice s | null x = error $ "expected variable but found " <> s | otherwise = (var x, s') where (x, s') = span isLetter s freshVariable :: Variable -> [Variable] -> Variable freshVariable var vars = Variable x (cnt + 1) where x = name var varsWithName = filter ((== x) . name) vars Variable _ cnt = maximum (var : varsWithName) data Term = V Variable | App Term Term | Lam Variable Term deriving (Show) aEq :: Term -> Term -> Bool aEq (V x) (V x') = x == x' aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2' aEq (Lam x t) (Lam x' t') | x == x' = aEq t t' | otherwise = aEq (subst (V y) x t) (subst (V y) x' t') where fvT = freeVars t fvT' = freeVars t' allFV = nub ([x, x'] ++ fvT ++ fvT') y = freshVariable x allFV aEq _ _ = False v :: String -> Term v x = V (var x) lam :: String -> Term -> Term lam x = Lam (var x) lams :: [String] -> Term -> Term lams xs t = foldr lam t xs ($$) :: Term -> Term -> Term ($$) = App infixl 9 $$ instance ShowNice Term where showNice (V var) = showNice var showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")" showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")" instance ReadNice Term where readNice [] = error "Nothing to read" readNice ('(' : '\\' : s) = (Lam var t, s'') where (var, '.' : s') = readNice s (t, ')' : s'') = readNice s' readNice ('(' : s) = (App t1 t2, s'') where (t1, ' ' : s') = readNice s (t2, ')' : s'') = readNice s' readNice s = (V var, s') where (var, s') = readNice s freeVars :: Term -> [Variable] freeVars (V var) = [var] freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2 freeVars (Lam var t) = filter (/= var) (freeVars t) for example [ 3 / x](x + x ) = = 3 + 3 subst -> Term subst u x (V y) | x == y = u | otherwise = V y subst u x (App t1 t2) = App (subst u x t1) (subst u x t2) subst u x (Lam y t) | x == y = Lam y t | y `notElem` fvU = Lam y (subst u x t) | x `notElem` fvT = Lam y t | otherwise = Lam y' (subst u x (subst (V y') y t)) where fvT = freeVars t fvU = freeVars u allFV = nub ([x] ++ fvU ++ fvT) y' = freshVariable y allFV normalReduceStep :: Term -> Maybe Term normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t normalReduceStep (App t1 t2) | Just t1' <- normalReduceStep t1 = Just $ App t1' t2 | Just t2' <- normalReduceStep t2 = Just $ App t1 t2' normalReduceStep (Lam x t) | Just t' <- normalReduceStep t = Just $ Lam x t' normalReduceStep _ = Nothing normalReduce :: Term -> Term normalReduce t | Just t' <- normalReduceStep t = normalReduce t' | otherwise = t reduce :: Term -> Term reduce = normalReduce abEq :: Term -> Term -> Bool abEq t1 t2 = aEq (reduce t1) (reduce t2) evaluate :: String -> String evaluate s = showNice (reduce t) where (t, "") = readNice s churchTrue :: Term churchTrue = lams ["t", "f"] (v "t") churchFalse :: Term churchFalse = lams ["t", "f"] (v "f") churchIf :: Term churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else") churchNot :: Term churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue) churchAnd :: Term churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse) churchOr :: Term churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2") church0 :: Term church1 :: Term church1 = lams ["s", "z"] (v "s" $$ v "z") church2 :: Term church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z")) churchS :: Term churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z")) churchNat :: Integer -> Term churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z")) churchPlus :: Term churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z")) churchPlus' :: Term churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m") churchMul :: Term churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s")) churchMul' :: Term churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0) churchPow :: Term churchPow = lams ["m", "n"] (v "n" $$ v "m") churchPow' :: Term churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1) churchIs0 :: Term churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue) churchS' :: Term churchS' = lam "n" (v "n" $$ churchS $$ church1) churchS'Rev0 :: Term churchS'Rev0 = lams ["s","z"] church0 churchPred :: Term churchPred = lam "n" (churchIf $$ (churchIs0 $$ v "n") $$ church0 $$ (v "n" $$ churchS' $$ churchS'Rev0)) churchSub :: Term churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m") churchLte :: Term churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n")) churchGte :: Term churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m") churchLt :: Term churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n")) churchGt :: Term churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m") churchEq :: Term churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m")) churchPair :: Term churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s") cPair :: a -> b -> CPair a b cPair = \x y -> CPair $ \action -> action x y churchFst :: Term churchFst = lam "pair" (v "pair" $$ churchTrue) cFst :: CPair a b -> a cFst = \p -> (cOn p $ \x y -> x) churchSnd :: Term churchSnd = lam "pair" (v "pair" $$ churchFalse) cSnd :: CPair a b -> b cSnd = \p -> (cOn p $ \x y -> y) churchPred' :: Term churchPred' = lam "n" (churchFst $$ (v "n" $$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ church0 $$ church0) )) cPred :: CNat -> CNat cPred = \n -> cFst $ cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0) churchFactorial :: Term churchFactorial = lam "n" (churchSnd $$ (v "n" $$ lam "p" (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church1 $$ church1) )) cFactorial :: CNat -> CNat cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1) churchFibonacci :: Term churchFibonacci = lam "n" (churchFst $$ (v "n" $$ lam "p" (churchPair $$ (churchSnd $$ v "p") $$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p")) ) $$ (churchPair $$ church0 $$ church1) )) cFibonacci :: CNat -> CNat cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1) churchDivMod :: Term churchDivMod = lams ["m", "n"] (v "m" $$ lam "pair" (churchIf $$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair")) $$ (churchPair $$ (churchS $$ (churchFst $$ v "pair")) $$ (churchSub $$ (churchSnd $$ v "pair") $$ v "n" ) ) $$ v "pair" ) $$ (churchPair $$ church0 $$ v "m") ) cDivMod :: CNat -> CNat -> CPair CNat CNat cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m) newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b } instance Foldable CList where foldr agg init xs = cFoldR xs agg init churchNil :: Term churchNil = lams ["agg", "init"] (v "init") cNil :: CList a cNil = CList $ \agg init -> init churchCons :: Term churchCons = lams ["x","l","agg", "init"] (v "agg" $$ v "x" $$ (v "l" $$ v "agg" $$ v "init") ) (.:) :: a -> CList a -> CList a (.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init) churchList :: [Term] -> Term churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil cList :: [a] -> CList a cList = foldr (.:) cNil churchNatList :: [Integer] -> Term churchNatList = churchList . map churchNat cNatList :: [Integer] -> CList CNat cNatList = cList . map cNat churchSum :: Term churchSum = lam "l" (v "l" $$ churchPlus $$ church0) cSum :: CList CNat -> CNat since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0 churchIsNil :: Term churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue) cIsNil :: CList a -> CBool cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue churchHead :: Term churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default") cHead :: CList a -> a -> a cHead = \l d -> cFoldR l (\x _ -> x) d churchTail :: Term churchTail = lam "l" (churchFst $$ (v "l" $$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t")) $$ (churchSnd $$ v "p")) $$ (churchPair $$ churchNil $$ churchNil) )) cTail :: CList a -> CList a cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil) cLength :: CList a -> CNat cLength = \l -> cFoldR l (\_ n -> cS n) 0 fix :: Term fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x"))) divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b) divmod m n = divmod' (0, 0) where divmod' (x, y) | x' <= m = divmod' (x', succ y) | otherwise = (y, m - x) where x' = x + n divmod' m n = if n == 0 then (0, m) else Function.fix (\f p -> (\x' -> if x' > 0 then f ((,) (succ (fst p)) x') else if (<=) n (snd p) then ((,) (succ (fst p)) 0) else p) ((-) (snd p) n)) (0, m) churchDivMod' :: Term churchDivMod' = lams ["m", "n"] (churchIs0 $$ v "n" $$ (churchPair $$ church0 $$ v "m") $$ (fix $$ lams ["f", "p"] (lam "x" (churchIs0 $$ v "x" $$ (churchLte $$ v "n" $$ (churchSnd $$ v "p") $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0) $$ v "p" ) $$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x")) ) $$ (churchSub $$ (churchSnd $$ v "p") $$ v "n") ) $$ (churchPair $$ church0 $$ v "m") ) ) churchSudan :: Term churchSudan = fix $$ lam "f" (lams ["n", "x", "y"] (churchIs0 $$ v "n" $$ (churchPlus $$ v "x" $$ v "y") $$ (churchIs0 $$ v "y" $$ v "x" $$ (lam "fnpy" (v "f" $$ (churchPred $$ v "n") $$ v "fnpy" $$ (churchPlus $$ v "fnpy" $$ v "y") ) $$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y")) ) ) )) churchAckermann :: Term churchAckermann = fix $$ lam "A" (lams ["m", "n"] (churchIs0 $$ v "m" $$ (churchS $$ v "n") $$ (churchIs0 $$ v "n" $$ (v "A" $$ (churchPred $$ v "m") $$ church1) $$ (v "A" $$ (churchPred $$ v "m") $$ (v "A" $$ v "m" $$ (churchPred $$ v "n"))) ) ) )
ab5e7a9a8149e69e7810ffa29fa26bc0656782519c9e74f9065b01cdc37e6522
tek/ribosome
Response.hs
module Ribosome.Host.Data.Response where import Data.MessagePack (Object) import Exon (exon) import Ribosome.Host.Data.Request (RequestId (RequestId)) data Response = Success Object | Error Text deriving stock (Eq, Show) formatResponse :: Response -> Text formatResponse = \case Success o -> show o Error e -> [exon|error: #{e}|] data TrackedResponse = TrackedResponse { id :: RequestId, payload :: Response } deriving stock (Eq, Show) formatTrackedResponse :: TrackedResponse -> Text formatTrackedResponse (TrackedResponse (RequestId i) payload) = [exon|<#{show i}> #{formatResponse payload}|]
null
https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/host/lib/Ribosome/Host/Data/Response.hs
haskell
module Ribosome.Host.Data.Response where import Data.MessagePack (Object) import Exon (exon) import Ribosome.Host.Data.Request (RequestId (RequestId)) data Response = Success Object | Error Text deriving stock (Eq, Show) formatResponse :: Response -> Text formatResponse = \case Success o -> show o Error e -> [exon|error: #{e}|] data TrackedResponse = TrackedResponse { id :: RequestId, payload :: Response } deriving stock (Eq, Show) formatTrackedResponse :: TrackedResponse -> Text formatTrackedResponse (TrackedResponse (RequestId i) payload) = [exon|<#{show i}> #{formatResponse payload}|]
5d977a71bb8ee961f0da196847d17e0aeb1dc3f7c05b227b99aae52e2ce118b5
bazurbat/chicken-scheme
posix.import.scm
;;;; posix.import.scm - import library for "posix" module ; Copyright ( c ) 2008 - 2016 , The CHICKEN Team ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following ; conditions are met: ; ; Redistributions of source code must retain the above copyright notice, this list of conditions and the following ; disclaimer. ; 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. ; Neither the name of the author nor the names of its contributors may be used to endorse or promote ; products derived from this software without specific prior written permission. ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS ; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY ; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. (##sys#register-primitive-module 'posix '(_exit call-with-input-pipe call-with-output-pipe change-directory change-directory* change-file-mode change-file-owner close-input-pipe close-output-pipe create-directory create-fifo create-pipe create-session create-symbolic-link current-directory current-effective-group-id current-effective-user-id current-effective-user-name get-environment-variables current-group-id current-process-id current-user-id current-user-name delete-directory directory directory? duplicate-fileno errno/2big errno/acces errno/again errno/badf errno/busy errno/child errno/deadlk errno/dom errno/exist errno/fault errno/fbig errno/ilseq errno/intr errno/inval errno/io errno/isdir errno/mfile errno/mlink errno/nametoolong errno/nfile errno/nodev errno/noent errno/noexec errno/nolck errno/nomem errno/nospc errno/nosys errno/notdir errno/notempty errno/notty errno/nxio errno/perm errno/pipe errno/range errno/rofs errno/spipe errno/srch errno/wouldblock errno/xdev fcntl/dupfd fcntl/getfd fcntl/getfl fcntl/setfd fcntl/setfl fifo? file-access-time file-change-time file-creation-mode file-close file-control file-execute-access? file-link file-lock file-lock/blocking file-mkstemp file-modification-time file-open file-owner file-permissions file-position set-file-position! file-read file-read-access? file-select file-size file-stat file-test-lock file-truncate file-type file-unlock file-write file-write-access? fileno/stderr fileno/stdin fileno/stdout find-files get-groups get-host-name glob group-information initialize-groups local-time->seconds local-timezone-abbreviation map-file-to-memory map/anonymous map/file map/fixed map/private map/shared memory-mapped-file-pointer memory-mapped-file? open-input-file* open-input-pipe open-output-file* open-output-pipe open/append open/binary open/creat open/excl open/fsync open/noctty open/nonblock open/rdonly open/rdwr open/read open/sync open/text open/trunc open/write open/wronly parent-process-id perm/irgrp perm/iroth perm/irusr perm/irwxg perm/irwxo perm/irwxu perm/isgid perm/isuid perm/isvtx perm/iwgrp perm/iwoth perm/iwusr perm/ixgrp perm/ixoth perm/ixusr pipe/buf port->fileno process process* process-execute process-fork process-group-id process-run process-signal process-wait prot/exec prot/none prot/read prot/write read-symbolic-link regular-file? seconds->local-time seconds->string seconds->utc-time seek/cur seek/end seek/set set-alarm! set-buffering-mode! set-groups! set-root-directory! set-signal-handler! set-signal-mask! setenv signal-handler signal-mask signal-mask! signal-masked? signal-unmask! signal/abrt signal/alrm signal/break signal/chld signal/cont signal/fpe signal/bus signal/hup signal/ill signal/int signal/io signal/kill signal/pipe signal/prof signal/quit signal/segv signal/stop signal/term signal/trap signal/tstp signal/urg signal/usr1 signal/usr2 signal/vtalrm signal/winch signal/xcpu signal/xfsz signals-list sleep block-device? character-device? fifo? socket? string->time symbolic-link? system-information terminal-name terminal-port? terminal-size time->string unmap-file-from-memory unsetenv user-information utc-time->seconds with-input-from-pipe with-output-to-pipe))
null
https://raw.githubusercontent.com/bazurbat/chicken-scheme/f0c9d1fd8b68eb322e320e65ec40b0bf7d1b41dc/posix.import.scm
scheme
posix.import.scm - import library for "posix" module All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 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. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 HOLDERS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright ( c ) 2008 - 2016 , The CHICKEN Team THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR (##sys#register-primitive-module 'posix '(_exit call-with-input-pipe call-with-output-pipe change-directory change-directory* change-file-mode change-file-owner close-input-pipe close-output-pipe create-directory create-fifo create-pipe create-session create-symbolic-link current-directory current-effective-group-id current-effective-user-id current-effective-user-name get-environment-variables current-group-id current-process-id current-user-id current-user-name delete-directory directory directory? duplicate-fileno errno/2big errno/acces errno/again errno/badf errno/busy errno/child errno/deadlk errno/dom errno/exist errno/fault errno/fbig errno/ilseq errno/intr errno/inval errno/io errno/isdir errno/mfile errno/mlink errno/nametoolong errno/nfile errno/nodev errno/noent errno/noexec errno/nolck errno/nomem errno/nospc errno/nosys errno/notdir errno/notempty errno/notty errno/nxio errno/perm errno/pipe errno/range errno/rofs errno/spipe errno/srch errno/wouldblock errno/xdev fcntl/dupfd fcntl/getfd fcntl/getfl fcntl/setfd fcntl/setfl fifo? file-access-time file-change-time file-creation-mode file-close file-control file-execute-access? file-link file-lock file-lock/blocking file-mkstemp file-modification-time file-open file-owner file-permissions file-position set-file-position! file-read file-read-access? file-select file-size file-stat file-test-lock file-truncate file-type file-unlock file-write file-write-access? fileno/stderr fileno/stdin fileno/stdout find-files get-groups get-host-name glob group-information initialize-groups local-time->seconds local-timezone-abbreviation map-file-to-memory map/anonymous map/file map/fixed map/private map/shared memory-mapped-file-pointer memory-mapped-file? open-input-file* open-input-pipe open-output-file* open-output-pipe open/append open/binary open/creat open/excl open/fsync open/noctty open/nonblock open/rdonly open/rdwr open/read open/sync open/text open/trunc open/write open/wronly parent-process-id perm/irgrp perm/iroth perm/irusr perm/irwxg perm/irwxo perm/irwxu perm/isgid perm/isuid perm/isvtx perm/iwgrp perm/iwoth perm/iwusr perm/ixgrp perm/ixoth perm/ixusr pipe/buf port->fileno process process* process-execute process-fork process-group-id process-run process-signal process-wait prot/exec prot/none prot/read prot/write read-symbolic-link regular-file? seconds->local-time seconds->string seconds->utc-time seek/cur seek/end seek/set set-alarm! set-buffering-mode! set-groups! set-root-directory! set-signal-handler! set-signal-mask! setenv signal-handler signal-mask signal-mask! signal-masked? signal-unmask! signal/abrt signal/alrm signal/break signal/chld signal/cont signal/fpe signal/bus signal/hup signal/ill signal/int signal/io signal/kill signal/pipe signal/prof signal/quit signal/segv signal/stop signal/term signal/trap signal/tstp signal/urg signal/usr1 signal/usr2 signal/vtalrm signal/winch signal/xcpu signal/xfsz signals-list sleep block-device? character-device? fifo? socket? string->time symbolic-link? system-information terminal-name terminal-port? terminal-size time->string unmap-file-from-memory unsetenv user-information utc-time->seconds with-input-from-pipe with-output-to-pipe))
60992e263be195ccef87aca02d147874d441dbdbea13c6fd02c1a201671d0aaf
exoscale/ex
auspex_test.clj
(ns exoscale.ex.test.auspex-test (:use clojure.test) (:require [exoscale.ex :as ex] [exoscale.ex.auspex :as c] [qbits.auspex :as a] [clojure.spec.test.alpha])) (clojure.spec.test.alpha/instrument) (deftest test-auspex (let [ex (ex-info "bar" {::ex/type ::bar1 :bar :baz})] (is (= ::boom @(-> (a/error-future ex) (c/catch ::bar1 (fn [d] ::boom))))) (ex/derive ::bar1 ::baz1) (is (= ::boom @(-> (a/error-future ex) (c/catch ::baz1 (fn [d] ::boom))))) (ex/underive ::bar1 ::baz1) (is (= ex @(-> (a/error-future ex) (c/catch ::bak1 (fn [d] ::boom)) (a/catch clojure.lang.ExceptionInfo (fn [e] e))))) (is (= :foo @(-> (a/success-future :foo) (c/catch ::bak1 (fn [d] ::boom)))))))
null
https://raw.githubusercontent.com/exoscale/ex/a2172c271014dff3238f6a05b465af273252e87c/modules/ex-auspex/test/exoscale/ex/test/auspex_test.clj
clojure
(ns exoscale.ex.test.auspex-test (:use clojure.test) (:require [exoscale.ex :as ex] [exoscale.ex.auspex :as c] [qbits.auspex :as a] [clojure.spec.test.alpha])) (clojure.spec.test.alpha/instrument) (deftest test-auspex (let [ex (ex-info "bar" {::ex/type ::bar1 :bar :baz})] (is (= ::boom @(-> (a/error-future ex) (c/catch ::bar1 (fn [d] ::boom))))) (ex/derive ::bar1 ::baz1) (is (= ::boom @(-> (a/error-future ex) (c/catch ::baz1 (fn [d] ::boom))))) (ex/underive ::bar1 ::baz1) (is (= ex @(-> (a/error-future ex) (c/catch ::bak1 (fn [d] ::boom)) (a/catch clojure.lang.ExceptionInfo (fn [e] e))))) (is (= :foo @(-> (a/success-future :foo) (c/catch ::bak1 (fn [d] ::boom)))))))
9604a260c685041763d8bccdc987cfde192ea4f574b232eb55775feb9123b6e2
geneweb/geneweb
gwdb_driver.ml
Copyright ( c ) 1998 - 2007 INRIA open Dbdisk type istr = int type ifam = int type iper = int let string_of_iper = string_of_int let string_of_ifam = string_of_int let string_of_istr = string_of_int let iper_of_string = int_of_string let ifam_of_string = int_of_string let istr_of_string = int_of_string let dummy_iper = -1 let dummy_ifam = -1 let empty_string = 0 let quest_string = 1 let eq_istr i1 i2 = i1 = i2 let eq_ifam i1 i2 = i1 = i2 let eq_iper i1 i2 = i1 = i2 let is_empty_string istr = istr = 0 let is_quest_string istr = istr = 1 type string_person_index = Dbdisk.string_person_index let spi_find spi = spi.find let spi_first spi = spi.cursor let spi_next (spi : string_person_index) istr = spi.next istr type base = dsk_base let open_base bname : base = Database.opendb bname let close_base base = base.func.cleanup () let sou base i = base.data.strings.get i let bname base = Filename.(remove_extension @@ basename base.data.bdir) let nb_of_persons base = base.data.persons.len let nb_of_real_persons base = base.func.nb_of_real_persons () let nb_of_families base = base.data.families.len let insert_string base s = base.func.Dbdisk.insert_string @@ Mutil.normalize_utf_8 s let commit_patches base = base.func.Dbdisk.commit_patches () let commit_notes base s = base.func.Dbdisk.commit_notes s let person_of_key base = base.func.Dbdisk.person_of_key let persons_of_name base = base.func.Dbdisk.persons_of_name let persons_of_first_name base = base.func.Dbdisk.persons_of_first_name let persons_of_surname base = base.func.Dbdisk.persons_of_surname let base_particles base = Lazy.force base.data.particles let base_strings_of_first_name base s = base.func.strings_of_fname s let base_strings_of_surname base s = base.func.strings_of_sname s let load_ascends_array base = base.data.ascends.load_array () let load_unions_array base = base.data.unions.load_array () let load_couples_array base = base.data.couples.load_array () let load_descends_array base = base.data.descends.load_array () let load_strings_array base = base.data.strings.load_array () let load_persons_array base = base.data.persons.load_array () let load_families_array base = base.data.families.load_array () let clear_ascends_array base = base.data.ascends.clear_array () let clear_unions_array base = base.data.unions.clear_array () let clear_couples_array base = base.data.couples.clear_array () let clear_descends_array base = base.data.descends.clear_array () let clear_strings_array base = base.data.strings.clear_array () let clear_persons_array base = base.data.persons.clear_array () let clear_families_array base = base.data.families.clear_array () let date_of_last_change base = let s = let bdir = base.data.bdir in try Unix.stat (Filename.concat bdir "patches") with Unix.Unix_error (_, _, _) -> Unix.stat (Filename.concat bdir "base") in s.Unix.st_mtime let gen_gen_person_misc_names = Dutil.dsk_person_misc_names let patch_misc_names base ip (p : (iper, iper, istr) Def.gen_person) = let p = { p with Def.key_index = ip } in List.iter (fun s -> base.func.Dbdisk.patch_name s ip) (gen_gen_person_misc_names base p (fun p -> p.Def.titles)) let patch_person base ip (p : (iper, iper, istr) Def.gen_person) = base.func.Dbdisk.patch_person ip p; let s = sou base p.first_name ^ " " ^ sou base p.surname in base.func.Dbdisk.patch_name s ip; patch_misc_names base ip p; Array.iter (fun i -> let cpl = base.data.couples.get i in let m = Adef.mother cpl in let f = Adef.father cpl in patch_misc_names base m (base.data.persons.get m); patch_misc_names base f (base.data.persons.get f); Array.iter (fun i -> patch_misc_names base i (base.data.persons.get i)) (base.data.descends.get i).children) (base.data.unions.get ip).family let patch_ascend base ip a = base.func.Dbdisk.patch_ascend ip a let patch_union base ip u = base.func.Dbdisk.patch_union ip u let patch_family base ifam f = base.func.Dbdisk.patch_family ifam f let patch_couple base ifam c = base.func.Dbdisk.patch_couple ifam c let patch_descend base ifam d = base.func.Dbdisk.patch_descend ifam d let insert_person = patch_person let insert_ascend = patch_ascend let insert_union = patch_union let insert_family = patch_family let insert_couple = patch_couple let insert_descend = patch_descend let delete_person base ip = patch_person base ip { first_name = quest_string; surname = quest_string; occ = 0; image = empty_string; first_names_aliases = []; surnames_aliases = []; public_name = empty_string; qualifiers = []; titles = []; rparents = []; related = []; aliases = []; occupation = empty_string; sex = Neuter; access = Private; birth = Date.cdate_None; birth_place = empty_string; birth_note = empty_string; birth_src = empty_string; baptism = Date.cdate_None; baptism_place = empty_string; baptism_note = empty_string; baptism_src = empty_string; death = DontKnowIfDead; death_place = empty_string; death_note = empty_string; death_src = empty_string; burial = UnknownBurial; burial_place = empty_string; burial_note = empty_string; burial_src = empty_string; pevents = []; notes = empty_string; psources = empty_string; key_index = ip; } let delete_ascend base ip = patch_ascend base ip { parents = None; consang = Adef.no_consang } let delete_union base ip = patch_union base ip { family = [||] } let delete_family base ifam = patch_family base ifam { marriage = Date.cdate_None; marriage_place = empty_string; marriage_note = empty_string; marriage_src = empty_string; relation = Married; divorce = NotDivorced; fevents = []; witnesses = [||]; comment = empty_string; origin_file = empty_string; fsources = empty_string; fam_index = dummy_ifam; } let delete_couple base ifam = patch_couple base ifam (Adef.couple dummy_iper dummy_iper) let delete_descend base ifam = patch_descend base ifam { children = [||] } let new_iper base = base.data.persons.len let new_ifam base = base.data.families.len (* FIXME: lock *) let sync ?(scratch = false) base = if base.data.perm = RDONLY && not scratch then raise Def.(HttpExn (Forbidden, __LOC__)) else Outbase.output base let make bname particles arrays : Dbdisk.dsk_base = sync ~scratch:true (Database.make bname particles arrays); open_base bname let bfname base fname = Filename.concat base.data.bdir fname module NLDB = struct let magic = "GWNL0010" let read base = let fname = bfname base "notes_links" in match try Some (open_in_bin fname) with Sys_error _ -> None with | Some ic -> let r = if Mutil.check_magic magic ic then (input_value ic : (iper, iper) Def.NLDB.t) else failwith "unsupported nldb format" in close_in ic; r | None -> [] let write base db = if base.data.perm = RDONLY then raise Def.(HttpExn (Forbidden, __LOC__)) else let fname_tmp = bfname base "1notes_links" in let fname_def = bfname base "notes_links" in let fname_back = bfname base "notes_links~" in let oc = open_out_bin fname_tmp in output_string oc magic; output_value oc (db : (iper, ifam) Def.NLDB.t); close_out oc; Mutil.rm fname_back; Mutil.mv fname_def fname_back; Sys.rename fname_tmp fname_def end let read_nldb = NLDB.read let write_nldb = NLDB.write let base_notes_origin_file base = base.data.bnotes.Def.norigin_file let base_notes_dir _base = "notes_d" let base_wiznotes_dir _base = "wiznotes" let base_notes_read_aux base fnotes mode = let fname = if fnotes = "" then "notes" else Filename.concat "notes_d" (fnotes ^ ".txt") in try let ic = Secure.open_in @@ Filename.concat base.data.bdir fname in let str = match mode with | Def.RnDeg -> if in_channel_length ic = 0 then "" else " " | Def.Rn1Ln -> ( try input_line ic with End_of_file -> "") | Def.RnAll -> Mutil.input_file_ic ic in close_in ic; str with Sys_error _ -> "" let base_notes_read base fnotes = base_notes_read_aux base fnotes Def.RnAll let base_notes_read_first_line base fnotes = base_notes_read_aux base fnotes Def.Rn1Ln let base_notes_are_empty base fnotes = base_notes_read_aux base fnotes Def.RnDeg = "" type relation = (iper, istr) Def.gen_relation type title = istr Def.gen_title type pers_event = (iper, istr) Def.gen_pers_event type fam_event = (iper, istr) Def.gen_fam_event let cache f a get set x = match get x with | Some v -> v | None -> let v = f a in set x (Some v); v (** Persons *) type person = { base : base; iper : iper; mutable p : (iper, iper, istr) gen_person option; mutable a : ifam gen_ascend option; mutable u : ifam gen_union option; } let cache_per f ({ base; iper; _ } as p) = f (cache base.data.persons.get iper (fun p -> p.p) (fun p v -> p.p <- v) p) let cache_asc f ({ base; iper; _ } as p) = f (cache base.data.ascends.get iper (fun p -> p.a) (fun p v -> p.a <- v) p) let cache_uni f ({ base; iper; _ } as p) = f (cache base.data.unions.get iper (fun p -> p.u) (fun p v -> p.u <- v) p) let gen_person_of_person = cache_per (fun p -> p) let gen_ascend_of_person = cache_asc (fun p -> p) let gen_union_of_person = cache_uni (fun p -> p) let get_access = cache_per (fun p -> p.Def.access) let get_aliases = cache_per (fun p -> p.Def.aliases) let get_baptism = cache_per (fun p -> p.Def.baptism) let get_baptism_note = cache_per (fun p -> p.Def.baptism_note) let get_baptism_place = cache_per (fun p -> p.Def.baptism_place) let get_baptism_src = cache_per (fun p -> p.Def.baptism_src) let get_birth = cache_per (fun p -> p.Def.birth) let get_birth_note = cache_per (fun p -> p.Def.birth_note) let get_birth_place = cache_per (fun p -> p.Def.birth_place) let get_birth_src = cache_per (fun p -> p.Def.birth_src) let get_burial = cache_per (fun p -> p.Def.burial) let get_burial_note = cache_per (fun p -> p.Def.burial_note) let get_burial_place = cache_per (fun p -> p.Def.burial_place) let get_burial_src = cache_per (fun p -> p.Def.burial_src) let get_consang = cache_asc (fun a -> a.Def.consang) let get_death = cache_per (fun p -> p.Def.death) let get_death_note = cache_per (fun p -> p.Def.death_note) let get_death_place = cache_per (fun p -> p.Def.death_place) let get_death_src = cache_per (fun p -> p.Def.death_src) let get_family = cache_uni (fun u -> u.Def.family) let get_first_name = cache_per (fun p -> p.Def.first_name) let get_first_names_aliases = cache_per (fun p -> p.Def.first_names_aliases) let get_image = cache_per (fun p -> p.Def.image) let get_iper = cache_per (fun p -> p.Def.key_index) let get_notes = cache_per (fun p -> p.Def.notes) let get_occ = cache_per (fun p -> p.Def.occ) let get_occupation = cache_per (fun p -> p.Def.occupation) let get_parents = cache_asc (fun a -> a.Def.parents) let get_pevents = cache_per (fun p -> p.Def.pevents) let get_psources = cache_per (fun p -> p.Def.psources) let get_public_name = cache_per (fun p -> p.Def.public_name) let get_qualifiers = cache_per (fun p -> p.Def.qualifiers) let get_related = cache_per (fun p -> p.Def.related) let get_rparents = cache_per (fun p -> p.Def.rparents) let get_sex = cache_per (fun p -> p.Def.sex) let get_surname = cache_per (fun p -> p.Def.surname) let get_surnames_aliases = cache_per (fun p -> p.Def.surnames_aliases) let get_titles = cache_per (fun p -> p.Def.titles) (** Families *) type family = { base : base; ifam : ifam; mutable f : (iper, ifam, istr) gen_family option; mutable c : iper gen_couple option; mutable d : iper gen_descend option; } let cache_fam f ({ base; ifam; _ } as fam) = f (cache base.data.families.get ifam (fun f -> f.f) (fun f v -> f.f <- v) fam) let cache_cpl f ({ base; ifam; _ } as fam) = f (cache base.data.couples.get ifam (fun f -> f.c) (fun f v -> f.c <- v) fam) let cache_des f ({ base; ifam; _ } as fam) = f (cache base.data.descends.get ifam (fun f -> f.d) (fun f v -> f.d <- v) fam) let gen_couple_of_family = cache_cpl (fun c -> c) let gen_descend_of_family = cache_des (fun d -> d) let gen_family_of_family = cache_fam (fun f -> f) let get_children = cache_des (fun d -> d.Def.children) let get_comment = cache_fam (fun f -> f.Def.comment) let get_ifam = cache_fam (fun f -> f.Def.fam_index) let get_divorce = cache_fam (fun f -> f.Def.divorce) let get_father = cache_cpl (fun c -> Adef.father c) let get_fevents = cache_fam (fun f -> f.Def.fevents) let get_fsources = cache_fam (fun f -> f.Def.fsources) let get_marriage = cache_fam (fun f -> f.Def.marriage) let get_marriage_note = cache_fam (fun f -> f.Def.marriage_note) let get_marriage_place = cache_fam (fun f -> f.Def.marriage_place) let get_marriage_src = cache_fam (fun f -> f.Def.marriage_src) let get_mother = cache_cpl (fun c -> Adef.mother c) let get_origin_file = cache_fam (fun f -> f.Def.origin_file) let get_parent_array = cache_cpl (fun c -> Adef.parent_array c) let get_relation = cache_fam (fun f -> f.Def.relation) let get_witnesses = cache_fam (fun f -> f.Def.witnesses) let no_person ip = { (Mutil.empty_person empty_string empty_string) with key_index = ip } let no_ascend = { parents = None; consang = Adef.no_consang } let no_union = { family = [||] } let empty_person base iper = { base; iper; p = Some (no_person iper); a = Some no_ascend; u = Some no_union; } [@ocaml.warning "-42"] let person_of_gen_person base (p, a, u) = { base; iper = p.key_index; p = Some p; a = Some a; u = Some u } [@ocaml.warning "-42"] let family_of_gen_family base (f, c, d) = { base; ifam = f.fam_index; f = Some f; c = Some c; d = Some d } [@ocaml.warning "-42"] let iper_exists base = base.func.iper_exists let ifam_exists base = base.func.ifam_exists let poi base iper = if iper = dummy_iper then empty_person base iper else { base; iper; p = None; a = None; u = None } [@ocaml.warning "-42"] let no_family ifam = { (Mutil.empty_family empty_string) with fam_index = ifam } let no_couple = Adef.couple dummy_iper dummy_iper let no_descend = { Def.children = [||] } let empty_family base ifam = { base; ifam; f = Some (no_family ifam); c = Some no_couple; d = Some no_descend; } let foi base ifam = if ifam = dummy_ifam then empty_family base ifam else { base; ifam; f = None; c = None; d = None } module Collection = struct type 'a t = { length : int; get : int -> 'a option } let map (fn : 'a -> 'b) c = { length = c.length; get = (fun i -> match c.get i with Some x -> Some (fn x) | None -> None); } let length { length; _ } = length let iter fn { get; length } = for i = 0 to length - 1 do match get i with Some x -> fn x | None -> () done let iteri fn { get; length } = for i = 0 to length - 1 do match get i with Some x -> fn i x | None -> () done let fold ?from ?until fn acc { get; length } = let from = match from with Some x -> x | None -> 0 in let until = match until with Some x -> x + 1 | None -> length in let rec loop acc i = if i = until then acc else loop (match get i with Some x -> fn acc x | None -> acc) (i + 1) in loop acc from let fold_until continue fn acc { get; length } = let rec loop acc i = if (not (continue acc)) || i = length then acc else loop (match get i with Some x -> fn acc x | None -> acc) (i + 1) in loop acc 0 let iterator { get; length } = let cursor = ref 0 in let rec next () = if !cursor < length then ( match get !cursor with | None -> incr cursor; next () | v -> incr cursor; v) else None in next end module Marker = struct type ('k, 'v) t = { get : 'k -> 'v; set : 'k -> 'v -> unit } let make (k : 'a -> int) (c : 'a Collection.t) (i : 'v) : ('a, 'v) t = let a = Array.make c.Collection.length i in { get = (fun x -> Array.get a (k x)); set = (fun x v -> Array.set a (k x) v); } let get ({ get; _ } : _ t) k = get k let set ({ set; _ } : _ t) k = set k end let persons base = { Collection.length = nb_of_persons base; get = (fun i -> Some (poi base i)) } let ipers base = { Collection.length = nb_of_persons base; get = (fun i -> Some i) } let iper_marker c i = Marker.make (fun i -> i) c i let ifams ?(select = fun _ -> true) base = { Collection.length = nb_of_families base; get = (fun i -> if select i then if get_ifam (foi base i) = dummy_ifam then None else Some i else None); } let families ?(select = fun _ -> true) base = { Collection.length = nb_of_families base; get = (fun i -> let f = foi base i in if get_ifam f <> dummy_ifam && select f then Some f else None); } let dummy_collection _ = { Collection.length = -1; get = (fun _ -> None) } let ifam_marker c i = Marker.make (fun i -> i) c i let dummy_marker (_ : 'a) (v : 'b) : ('a, 'b) Marker.t = { Marker.get = (fun _ -> v); set = (fun _ _ -> ()) } (* Restrict file *) (* FIXME: these values should not be global *) let visible_ref : (iper, bool) Hashtbl.t option ref = ref None let read_or_create_visible base = let fname = Filename.concat base.data.bdir "restrict" in let visible = if Sys.file_exists fname then ( let ic = Secure.open_in fname in let visible = if Mutil.check_magic Mutil.executable_magic ic then input_value ic else Hashtbl.create (nb_of_persons base) in close_in ic; visible) else Hashtbl.create (nb_of_persons base) in visible_ref := Some visible; visible let base_visible_write base = if base.data.perm = RDONLY then raise Def.(HttpExn (Forbidden, __LOC__)) else let fname = Filename.concat base.data.bdir "restrict" in match !visible_ref with | Some visible -> let oc = Secure.open_out fname in output_string oc Mutil.executable_magic; output_value oc visible; close_out oc | None -> () let base_visible_get base fct i = let visible = match !visible_ref with | Some visible -> visible | None -> read_or_create_visible base in match Hashtbl.find_opt visible i with | None -> let status = fct (poi base i) in Hashtbl.add visible i status; visible_ref := Some visible; status | Some b -> b
null
https://raw.githubusercontent.com/geneweb/geneweb/7b71f8f2f75e0e847818f821a0267938f38c9cf5/lib/gwdb-legacy/gwdb_driver.ml
ocaml
FIXME: lock * Persons * Families Restrict file FIXME: these values should not be global
Copyright ( c ) 1998 - 2007 INRIA open Dbdisk type istr = int type ifam = int type iper = int let string_of_iper = string_of_int let string_of_ifam = string_of_int let string_of_istr = string_of_int let iper_of_string = int_of_string let ifam_of_string = int_of_string let istr_of_string = int_of_string let dummy_iper = -1 let dummy_ifam = -1 let empty_string = 0 let quest_string = 1 let eq_istr i1 i2 = i1 = i2 let eq_ifam i1 i2 = i1 = i2 let eq_iper i1 i2 = i1 = i2 let is_empty_string istr = istr = 0 let is_quest_string istr = istr = 1 type string_person_index = Dbdisk.string_person_index let spi_find spi = spi.find let spi_first spi = spi.cursor let spi_next (spi : string_person_index) istr = spi.next istr type base = dsk_base let open_base bname : base = Database.opendb bname let close_base base = base.func.cleanup () let sou base i = base.data.strings.get i let bname base = Filename.(remove_extension @@ basename base.data.bdir) let nb_of_persons base = base.data.persons.len let nb_of_real_persons base = base.func.nb_of_real_persons () let nb_of_families base = base.data.families.len let insert_string base s = base.func.Dbdisk.insert_string @@ Mutil.normalize_utf_8 s let commit_patches base = base.func.Dbdisk.commit_patches () let commit_notes base s = base.func.Dbdisk.commit_notes s let person_of_key base = base.func.Dbdisk.person_of_key let persons_of_name base = base.func.Dbdisk.persons_of_name let persons_of_first_name base = base.func.Dbdisk.persons_of_first_name let persons_of_surname base = base.func.Dbdisk.persons_of_surname let base_particles base = Lazy.force base.data.particles let base_strings_of_first_name base s = base.func.strings_of_fname s let base_strings_of_surname base s = base.func.strings_of_sname s let load_ascends_array base = base.data.ascends.load_array () let load_unions_array base = base.data.unions.load_array () let load_couples_array base = base.data.couples.load_array () let load_descends_array base = base.data.descends.load_array () let load_strings_array base = base.data.strings.load_array () let load_persons_array base = base.data.persons.load_array () let load_families_array base = base.data.families.load_array () let clear_ascends_array base = base.data.ascends.clear_array () let clear_unions_array base = base.data.unions.clear_array () let clear_couples_array base = base.data.couples.clear_array () let clear_descends_array base = base.data.descends.clear_array () let clear_strings_array base = base.data.strings.clear_array () let clear_persons_array base = base.data.persons.clear_array () let clear_families_array base = base.data.families.clear_array () let date_of_last_change base = let s = let bdir = base.data.bdir in try Unix.stat (Filename.concat bdir "patches") with Unix.Unix_error (_, _, _) -> Unix.stat (Filename.concat bdir "base") in s.Unix.st_mtime let gen_gen_person_misc_names = Dutil.dsk_person_misc_names let patch_misc_names base ip (p : (iper, iper, istr) Def.gen_person) = let p = { p with Def.key_index = ip } in List.iter (fun s -> base.func.Dbdisk.patch_name s ip) (gen_gen_person_misc_names base p (fun p -> p.Def.titles)) let patch_person base ip (p : (iper, iper, istr) Def.gen_person) = base.func.Dbdisk.patch_person ip p; let s = sou base p.first_name ^ " " ^ sou base p.surname in base.func.Dbdisk.patch_name s ip; patch_misc_names base ip p; Array.iter (fun i -> let cpl = base.data.couples.get i in let m = Adef.mother cpl in let f = Adef.father cpl in patch_misc_names base m (base.data.persons.get m); patch_misc_names base f (base.data.persons.get f); Array.iter (fun i -> patch_misc_names base i (base.data.persons.get i)) (base.data.descends.get i).children) (base.data.unions.get ip).family let patch_ascend base ip a = base.func.Dbdisk.patch_ascend ip a let patch_union base ip u = base.func.Dbdisk.patch_union ip u let patch_family base ifam f = base.func.Dbdisk.patch_family ifam f let patch_couple base ifam c = base.func.Dbdisk.patch_couple ifam c let patch_descend base ifam d = base.func.Dbdisk.patch_descend ifam d let insert_person = patch_person let insert_ascend = patch_ascend let insert_union = patch_union let insert_family = patch_family let insert_couple = patch_couple let insert_descend = patch_descend let delete_person base ip = patch_person base ip { first_name = quest_string; surname = quest_string; occ = 0; image = empty_string; first_names_aliases = []; surnames_aliases = []; public_name = empty_string; qualifiers = []; titles = []; rparents = []; related = []; aliases = []; occupation = empty_string; sex = Neuter; access = Private; birth = Date.cdate_None; birth_place = empty_string; birth_note = empty_string; birth_src = empty_string; baptism = Date.cdate_None; baptism_place = empty_string; baptism_note = empty_string; baptism_src = empty_string; death = DontKnowIfDead; death_place = empty_string; death_note = empty_string; death_src = empty_string; burial = UnknownBurial; burial_place = empty_string; burial_note = empty_string; burial_src = empty_string; pevents = []; notes = empty_string; psources = empty_string; key_index = ip; } let delete_ascend base ip = patch_ascend base ip { parents = None; consang = Adef.no_consang } let delete_union base ip = patch_union base ip { family = [||] } let delete_family base ifam = patch_family base ifam { marriage = Date.cdate_None; marriage_place = empty_string; marriage_note = empty_string; marriage_src = empty_string; relation = Married; divorce = NotDivorced; fevents = []; witnesses = [||]; comment = empty_string; origin_file = empty_string; fsources = empty_string; fam_index = dummy_ifam; } let delete_couple base ifam = patch_couple base ifam (Adef.couple dummy_iper dummy_iper) let delete_descend base ifam = patch_descend base ifam { children = [||] } let new_iper base = base.data.persons.len let new_ifam base = base.data.families.len let sync ?(scratch = false) base = if base.data.perm = RDONLY && not scratch then raise Def.(HttpExn (Forbidden, __LOC__)) else Outbase.output base let make bname particles arrays : Dbdisk.dsk_base = sync ~scratch:true (Database.make bname particles arrays); open_base bname let bfname base fname = Filename.concat base.data.bdir fname module NLDB = struct let magic = "GWNL0010" let read base = let fname = bfname base "notes_links" in match try Some (open_in_bin fname) with Sys_error _ -> None with | Some ic -> let r = if Mutil.check_magic magic ic then (input_value ic : (iper, iper) Def.NLDB.t) else failwith "unsupported nldb format" in close_in ic; r | None -> [] let write base db = if base.data.perm = RDONLY then raise Def.(HttpExn (Forbidden, __LOC__)) else let fname_tmp = bfname base "1notes_links" in let fname_def = bfname base "notes_links" in let fname_back = bfname base "notes_links~" in let oc = open_out_bin fname_tmp in output_string oc magic; output_value oc (db : (iper, ifam) Def.NLDB.t); close_out oc; Mutil.rm fname_back; Mutil.mv fname_def fname_back; Sys.rename fname_tmp fname_def end let read_nldb = NLDB.read let write_nldb = NLDB.write let base_notes_origin_file base = base.data.bnotes.Def.norigin_file let base_notes_dir _base = "notes_d" let base_wiznotes_dir _base = "wiznotes" let base_notes_read_aux base fnotes mode = let fname = if fnotes = "" then "notes" else Filename.concat "notes_d" (fnotes ^ ".txt") in try let ic = Secure.open_in @@ Filename.concat base.data.bdir fname in let str = match mode with | Def.RnDeg -> if in_channel_length ic = 0 then "" else " " | Def.Rn1Ln -> ( try input_line ic with End_of_file -> "") | Def.RnAll -> Mutil.input_file_ic ic in close_in ic; str with Sys_error _ -> "" let base_notes_read base fnotes = base_notes_read_aux base fnotes Def.RnAll let base_notes_read_first_line base fnotes = base_notes_read_aux base fnotes Def.Rn1Ln let base_notes_are_empty base fnotes = base_notes_read_aux base fnotes Def.RnDeg = "" type relation = (iper, istr) Def.gen_relation type title = istr Def.gen_title type pers_event = (iper, istr) Def.gen_pers_event type fam_event = (iper, istr) Def.gen_fam_event let cache f a get set x = match get x with | Some v -> v | None -> let v = f a in set x (Some v); v type person = { base : base; iper : iper; mutable p : (iper, iper, istr) gen_person option; mutable a : ifam gen_ascend option; mutable u : ifam gen_union option; } let cache_per f ({ base; iper; _ } as p) = f (cache base.data.persons.get iper (fun p -> p.p) (fun p v -> p.p <- v) p) let cache_asc f ({ base; iper; _ } as p) = f (cache base.data.ascends.get iper (fun p -> p.a) (fun p v -> p.a <- v) p) let cache_uni f ({ base; iper; _ } as p) = f (cache base.data.unions.get iper (fun p -> p.u) (fun p v -> p.u <- v) p) let gen_person_of_person = cache_per (fun p -> p) let gen_ascend_of_person = cache_asc (fun p -> p) let gen_union_of_person = cache_uni (fun p -> p) let get_access = cache_per (fun p -> p.Def.access) let get_aliases = cache_per (fun p -> p.Def.aliases) let get_baptism = cache_per (fun p -> p.Def.baptism) let get_baptism_note = cache_per (fun p -> p.Def.baptism_note) let get_baptism_place = cache_per (fun p -> p.Def.baptism_place) let get_baptism_src = cache_per (fun p -> p.Def.baptism_src) let get_birth = cache_per (fun p -> p.Def.birth) let get_birth_note = cache_per (fun p -> p.Def.birth_note) let get_birth_place = cache_per (fun p -> p.Def.birth_place) let get_birth_src = cache_per (fun p -> p.Def.birth_src) let get_burial = cache_per (fun p -> p.Def.burial) let get_burial_note = cache_per (fun p -> p.Def.burial_note) let get_burial_place = cache_per (fun p -> p.Def.burial_place) let get_burial_src = cache_per (fun p -> p.Def.burial_src) let get_consang = cache_asc (fun a -> a.Def.consang) let get_death = cache_per (fun p -> p.Def.death) let get_death_note = cache_per (fun p -> p.Def.death_note) let get_death_place = cache_per (fun p -> p.Def.death_place) let get_death_src = cache_per (fun p -> p.Def.death_src) let get_family = cache_uni (fun u -> u.Def.family) let get_first_name = cache_per (fun p -> p.Def.first_name) let get_first_names_aliases = cache_per (fun p -> p.Def.first_names_aliases) let get_image = cache_per (fun p -> p.Def.image) let get_iper = cache_per (fun p -> p.Def.key_index) let get_notes = cache_per (fun p -> p.Def.notes) let get_occ = cache_per (fun p -> p.Def.occ) let get_occupation = cache_per (fun p -> p.Def.occupation) let get_parents = cache_asc (fun a -> a.Def.parents) let get_pevents = cache_per (fun p -> p.Def.pevents) let get_psources = cache_per (fun p -> p.Def.psources) let get_public_name = cache_per (fun p -> p.Def.public_name) let get_qualifiers = cache_per (fun p -> p.Def.qualifiers) let get_related = cache_per (fun p -> p.Def.related) let get_rparents = cache_per (fun p -> p.Def.rparents) let get_sex = cache_per (fun p -> p.Def.sex) let get_surname = cache_per (fun p -> p.Def.surname) let get_surnames_aliases = cache_per (fun p -> p.Def.surnames_aliases) let get_titles = cache_per (fun p -> p.Def.titles) type family = { base : base; ifam : ifam; mutable f : (iper, ifam, istr) gen_family option; mutable c : iper gen_couple option; mutable d : iper gen_descend option; } let cache_fam f ({ base; ifam; _ } as fam) = f (cache base.data.families.get ifam (fun f -> f.f) (fun f v -> f.f <- v) fam) let cache_cpl f ({ base; ifam; _ } as fam) = f (cache base.data.couples.get ifam (fun f -> f.c) (fun f v -> f.c <- v) fam) let cache_des f ({ base; ifam; _ } as fam) = f (cache base.data.descends.get ifam (fun f -> f.d) (fun f v -> f.d <- v) fam) let gen_couple_of_family = cache_cpl (fun c -> c) let gen_descend_of_family = cache_des (fun d -> d) let gen_family_of_family = cache_fam (fun f -> f) let get_children = cache_des (fun d -> d.Def.children) let get_comment = cache_fam (fun f -> f.Def.comment) let get_ifam = cache_fam (fun f -> f.Def.fam_index) let get_divorce = cache_fam (fun f -> f.Def.divorce) let get_father = cache_cpl (fun c -> Adef.father c) let get_fevents = cache_fam (fun f -> f.Def.fevents) let get_fsources = cache_fam (fun f -> f.Def.fsources) let get_marriage = cache_fam (fun f -> f.Def.marriage) let get_marriage_note = cache_fam (fun f -> f.Def.marriage_note) let get_marriage_place = cache_fam (fun f -> f.Def.marriage_place) let get_marriage_src = cache_fam (fun f -> f.Def.marriage_src) let get_mother = cache_cpl (fun c -> Adef.mother c) let get_origin_file = cache_fam (fun f -> f.Def.origin_file) let get_parent_array = cache_cpl (fun c -> Adef.parent_array c) let get_relation = cache_fam (fun f -> f.Def.relation) let get_witnesses = cache_fam (fun f -> f.Def.witnesses) let no_person ip = { (Mutil.empty_person empty_string empty_string) with key_index = ip } let no_ascend = { parents = None; consang = Adef.no_consang } let no_union = { family = [||] } let empty_person base iper = { base; iper; p = Some (no_person iper); a = Some no_ascend; u = Some no_union; } [@ocaml.warning "-42"] let person_of_gen_person base (p, a, u) = { base; iper = p.key_index; p = Some p; a = Some a; u = Some u } [@ocaml.warning "-42"] let family_of_gen_family base (f, c, d) = { base; ifam = f.fam_index; f = Some f; c = Some c; d = Some d } [@ocaml.warning "-42"] let iper_exists base = base.func.iper_exists let ifam_exists base = base.func.ifam_exists let poi base iper = if iper = dummy_iper then empty_person base iper else { base; iper; p = None; a = None; u = None } [@ocaml.warning "-42"] let no_family ifam = { (Mutil.empty_family empty_string) with fam_index = ifam } let no_couple = Adef.couple dummy_iper dummy_iper let no_descend = { Def.children = [||] } let empty_family base ifam = { base; ifam; f = Some (no_family ifam); c = Some no_couple; d = Some no_descend; } let foi base ifam = if ifam = dummy_ifam then empty_family base ifam else { base; ifam; f = None; c = None; d = None } module Collection = struct type 'a t = { length : int; get : int -> 'a option } let map (fn : 'a -> 'b) c = { length = c.length; get = (fun i -> match c.get i with Some x -> Some (fn x) | None -> None); } let length { length; _ } = length let iter fn { get; length } = for i = 0 to length - 1 do match get i with Some x -> fn x | None -> () done let iteri fn { get; length } = for i = 0 to length - 1 do match get i with Some x -> fn i x | None -> () done let fold ?from ?until fn acc { get; length } = let from = match from with Some x -> x | None -> 0 in let until = match until with Some x -> x + 1 | None -> length in let rec loop acc i = if i = until then acc else loop (match get i with Some x -> fn acc x | None -> acc) (i + 1) in loop acc from let fold_until continue fn acc { get; length } = let rec loop acc i = if (not (continue acc)) || i = length then acc else loop (match get i with Some x -> fn acc x | None -> acc) (i + 1) in loop acc 0 let iterator { get; length } = let cursor = ref 0 in let rec next () = if !cursor < length then ( match get !cursor with | None -> incr cursor; next () | v -> incr cursor; v) else None in next end module Marker = struct type ('k, 'v) t = { get : 'k -> 'v; set : 'k -> 'v -> unit } let make (k : 'a -> int) (c : 'a Collection.t) (i : 'v) : ('a, 'v) t = let a = Array.make c.Collection.length i in { get = (fun x -> Array.get a (k x)); set = (fun x v -> Array.set a (k x) v); } let get ({ get; _ } : _ t) k = get k let set ({ set; _ } : _ t) k = set k end let persons base = { Collection.length = nb_of_persons base; get = (fun i -> Some (poi base i)) } let ipers base = { Collection.length = nb_of_persons base; get = (fun i -> Some i) } let iper_marker c i = Marker.make (fun i -> i) c i let ifams ?(select = fun _ -> true) base = { Collection.length = nb_of_families base; get = (fun i -> if select i then if get_ifam (foi base i) = dummy_ifam then None else Some i else None); } let families ?(select = fun _ -> true) base = { Collection.length = nb_of_families base; get = (fun i -> let f = foi base i in if get_ifam f <> dummy_ifam && select f then Some f else None); } let dummy_collection _ = { Collection.length = -1; get = (fun _ -> None) } let ifam_marker c i = Marker.make (fun i -> i) c i let dummy_marker (_ : 'a) (v : 'b) : ('a, 'b) Marker.t = { Marker.get = (fun _ -> v); set = (fun _ _ -> ()) } let visible_ref : (iper, bool) Hashtbl.t option ref = ref None let read_or_create_visible base = let fname = Filename.concat base.data.bdir "restrict" in let visible = if Sys.file_exists fname then ( let ic = Secure.open_in fname in let visible = if Mutil.check_magic Mutil.executable_magic ic then input_value ic else Hashtbl.create (nb_of_persons base) in close_in ic; visible) else Hashtbl.create (nb_of_persons base) in visible_ref := Some visible; visible let base_visible_write base = if base.data.perm = RDONLY then raise Def.(HttpExn (Forbidden, __LOC__)) else let fname = Filename.concat base.data.bdir "restrict" in match !visible_ref with | Some visible -> let oc = Secure.open_out fname in output_string oc Mutil.executable_magic; output_value oc visible; close_out oc | None -> () let base_visible_get base fct i = let visible = match !visible_ref with | Some visible -> visible | None -> read_or_create_visible base in match Hashtbl.find_opt visible i with | None -> let status = fct (poi base i) in Hashtbl.add visible i status; visible_ref := Some visible; status | Some b -> b
353b9d07d289d8ffa0c2c471414528d4cc976a1e601f960499b08585bbfa1e18
backtracking/ocaml-bazaar
idd.ml
(**************************************************************************) (* *) Copyright ( C ) (* *) (* This software is free software; you can redistribute it and/or *) modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking (* described in file LICENSE. *) (* *) (* This software 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. *) (* *) (**************************************************************************) (* Integer Dichotomy Diagrams *) type idd = { u: int; (* unique *) lo: idd; p: idd; hi: idd; } * this is lo + x(p ) * hi invariant max(lo , hi ) < ) , 0 < hi invariant max(lo,hi) < x(p), 0 < hi *) let rec zero = { u = 0; lo = zero; p = zero; hi = zero } let rec one = { u = 1; lo = one ; p = zero; hi = zero } (* hash-consing *) module Hidd = struct type t = idd let hash n = (19 * (19 * n.lo.u + n.p.u) + n.hi.u) land max_int let equal n1 n2 = n1.lo == n2.lo && n1.p == n2.p && n1.hi == n2.hi end module Widd = Weak.Make(Hidd) let nodes = Widd.create 200323 let unique = ref 2 let create lo p hi = if hi == zero then lo else let n0 = { u = !unique; lo = lo; p = p; hi = hi } in let n = Widd.merge nodes n0 in if n == n0 then incr unique; n (* memoization *) module H1 = Hashtbl.Make(struct type t = idd let hash n = n.u let equal = (==) end) let memo1 h f x = try H1.find h x with Not_found -> let y = f x in H1.add h x y; y let memo_rec1 f = let h = H1.create 16 in let rec g x = try H1.find h x with Not_found -> let y = f g x in H1.add h x y; y in g module H2 = Hashtbl.Make(struct type t = idd * idd let hash (n1, n2) = (19 * n1.u + n2.u) land max_int let equal (x1, x2) (y1, y2) = x1 == y1 && x2 == y2 end) let memo2 h f x1 x2 = let x = x1, x2 in try H2.find h x with Not_found -> let y = f x1 x2 in H2.add h x y; y let memo_rec2 f = let h = H2.create 16 in let rec g x1 x2 = let x = x1, x2 in try H2.find h x with Not_found -> let y = f g x1 x2 in H2.add h x y; y in g (* operations *) let hash i = i.u let equal = (==) let rec compare n m = if n == m then 0 else if m == zero then 1 else if n == zero then -1 else if n.p != m.p then compare n.p m.p else if n.hi != m.hi then compare n.hi m.hi else compare n.lo m.lo x(p ) = 2^(2^p ) let x p = create zero p one 2 = 2^(2 ^ 0 ) 4 = 2^(2 ^ 1 ) x'(q ) = x(q)-1 = 2^(2^q)-1 let rec x' q = if q == zero then one else let q = d q in let x = x' q in create x q x (* decrement d(n) = n-1 for n>0 *) and d n = assert (n != zero); if n == one then zero else if n.lo != zero then create (d n.lo) n.p n.hi else if n.hi == one then x' n.p else create (x' n.p) n.p (d n.hi) let pred = d (* increment i(n) = n+1 *) let rec i n = if n == zero then one else if n == one then two else if n.lo != x' n.p then create (i n.lo) n.p n.hi else if n.hi != x' n.p then create zero n.p (i n.hi) else create zero (i n.p) one let succ = i let ll n = succ n.p let three = succ two let five = succ four TODO ? memo x ' d i let htwice = H1.create 8192 let haddm = H2.create 8192 lo + x(p ) * hi , with no constraint let rec c lo p hi = let cmp_p_lop = compare p lo.p in if cmp_p_lop > 0 then c1 lo p hi else if cmp_p_lop = 0 then c1 lo.lo p (add hi lo.hi) else c (c lo.lo p hi) lo.p lo.hi lo + x(p ) * hi , with the constraint lo < ) and c1 lo p hi = let cmp_p_hip = compare p hi.p in if cmp_p_hip > 0 then create lo p hi else if cmp_p_hip = 0 then create (create lo p hi.lo) (i p) hi.hi else c (c1 lo p hi.lo) hi.p (c zero p hi.hi) add(a , b ) = a+b and add a b = if a == zero then b else if a == one then i b else let cmp = compare a b in if cmp = 0 then twice a else if cmp > 0 then add b a else if compare a.p b.p < 0 then c (add a b.lo) b.p b.hi else addm a b add(a , b ) when a < b and a.p = and addm a b = memo2 haddm compute_addm a b and compute_addm a b = assert (a.p == b.p); c (add a.lo b.lo) a.p (add a.hi b.hi) and twice a = memo1 htwice compute_twice a and compute_twice a = if a == zero then zero else if a == one then two else c (twice a.lo) a.p (twice a.hi) let hlogandm = H2.create 8192 let hlogorm = H2.create 8192 let hlogxorm = H2.create 8192 let rec logand a b = if a == zero then zero else if a == b then a else if compare a b > 0 then logand b a else if compare a.p b.p < 0 then logand a b.lo else logandm a b and logandm a b = memo2 hlogandm compute_logandm a b and compute_logandm a b = create (logand a.lo b.lo) a.p (logand a.hi b.hi) let rec logor a b = if a == zero then b else if a == b then a else if compare a b > 0 then logor b a else if compare a.p b.p < 0 then create (logor a b.lo) b.p b.hi else logorm a b and logorm a b = memo2 hlogorm compute_logorm a b and compute_logorm a b = create (logor a.lo b.lo) a.p (logor a.hi b.hi) let rec logxor a b = if a == zero then b else if a == b then zero else if compare a b > 0 then logxor b a else if compare a.p b.p < 0 then create (logxor a b.lo) b.p b.hi else logxorm a b and logxorm a b = memo2 hlogxorm compute_logxorm a b and compute_logxorm a b = create (logxor a.lo b.lo) a.p (logxor a.hi b.hi) (* subtract *) let oc ( fun oc ( n , p ) - > assert ( compare ) ; ( * FIXME let oc = memo_rec2 (fun oc (n, p) -> assert (compare p n.p > 0); (* FIXME *) if n == zero then x' p else let q = pred p in if n.p == q then create (oc (n.lo, q)) q (oc (n.hi, q)) else create (oc (n, q)) q (x' q)) *) let xor1 = memo_rec1 (fun xor1 n -> if n == zero then one else if n == one then zero else c (xor1 n.lo) n.p n.hi ) n xor 2^(2^p)-1 let nt = memo_rec2 (fun nt n p -> if n == zero then x' p else if n == one then xor1 (x' p) else let q = pred p in let cmp = compare q n.p in if cmp < 0 then invalid_arg "nt"; if cmp = 0 then c (nt n.lo q) q (nt n.hi q) else c (nt n q) q (x' q) ) let sub a b = let cmp = compare a b in if cmp < 0 then invalid_arg "sub"; if cmp = 0 then zero else if b == zero then a else if b == one then pred a else (succ (add a (nt b (succ a.p)))).lo remove MSB : rmsb(n ) = ( n - 2^i , i = l(n ) - 1 ) for n > 0 let rec rmsb n = if n == zero then invalid_arg "rmsb"; if n == one then zero, zero else let e, l = rmsb n.hi in create n.lo n.p e, imsb l n.p insert MSB : imsb(m , i ) = m + 2^i for m < 2^i and imsb m i = if i == zero then (assert (m == zero); one) else if i == one then if m == zero then two else (assert (m == one); three) else let e, l = rmsb i in if compare l m.p > 0 then create m l (imsb zero e) else create m.lo l (imsb m.hi e) (* binary length l(n) *) let l n = if n == zero then zero else let _, i = rmsb n in succ i 2^i let pop = memo_rec1 (fun pop n -> if n == zero then zero else if n == one then one else add (pop n.lo) (pop n.hi)) (* product *) let mul = memo_rec2 (fun mul a b -> if a == zero then zero else if a == one then b else if compare a b > 0 then mul b a else c (mul a b.lo) b.p (mul a b.hi)) (* huge numbers *) let rec h n = if n = 0 then one else let x = h (n - 1) in create x x x let dfs vzero vone vnode n = let visited = H1.create 16 in H1.add visited zero vzero; H1.add visited one vone; let rec visit n = try H1.find visited n with Not_found -> let lo = visit n.lo and p = visit n.p and hi = visit n.hi in let v = vnode lo p hi in H1.add visited n v; v in visit n let size n = let res = ref 0 in dfs () () (fun _ _ _ -> incr res) n; !res let tree_size n = dfs 0 0 (fun x y z -> x+y+z+1) n (* conversions *) let pmax_of_int = if Sys.word_size = 32 then 4 else 5 let rec of_small_int p = assert (p <= pmax_of_int); if p = 0 then zero else if p = 1 then one else succ (of_small_int (p-1)) let of_int n = if n < 0 then invalid_arg "of_int"; let rec of_int n p = if p < 0 then begin assert (n < 2); if n = 0 then zero else one end else let x = 1 lsl (1 lsl p) in create (of_int (n land (x-1)) (p-1)) (of_small_int p) (of_int (n lsr (1 lsl p)) (p-1)) in of_int n pmax_of_int let idd_max_int = of_int max_int let rec to_int n = if compare n idd_max_int > 0 then invalid_arg "to_int"; if n == zero then 0 else if n == one then 1 else to_int n.lo lor (to_int n.hi lsl (1 lsl to_int n.p)) TODO : to / of Int32 Int64 printing / parsing using the following format 2 = ( 0 , 0 , 1 ) 3 = ( 1 , 0 , 1 ) 4 = ( 2 , 2 , 3 ) 5 = ( 4 , 3 , 3 ) 2 = (0, 0, 1) 3 = (1, 0, 1) 4 = (2, 2, 3) 5 = (4, 3, 3) *) open Format let print fmt n = if n == zero || n == one then invalid_arg "print"; let idx = ref 1 in let visit lo p hi = if !idx > 1 then fprintf fmt "@\n"; let r = incr idx; string_of_int !idx in fprintf fmt "%s = (%s, %s, %s)" r lo p hi; r in ignore (dfs "0" "1" visit n) let parse sl = let nodes = Hashtbl.create 17 in Hashtbl.add nodes 0 zero; Hashtbl.add nodes 1 one; let parse s = Scanf.sscanf s "%d = (%d, %d, %d)" (fun r lo p hi -> let lo = Hashtbl.find nodes lo and p = Hashtbl.find nodes p and hi = Hashtbl.find nodes hi in let n = create lo p hi in Hashtbl.add nodes r n; n) in let rec iter = function | [] -> raise Not_found | [s] -> parse s | s :: l -> ignore (parse s); iter l in try iter sl with Not_found -> invalid_arg "parse" let printer fmt n = let p fmt n = try fprintf fmt "%d" (to_int n) with _ -> fprintf fmt "<too big>" in fprintf fmt "%a = @[%a@]" p n print n let print2 ~max_digits fmt n = if compare (l n) (of_int max_digits) > 0 then invalid_arg "print2"; let rec print d n = assert (d >= 1); if n == zero then fprintf fmt "%s0" (String.make (d-1) '0') else if n == one then fprintf fmt "%s1" (String.make (d-1) '0') else ( let dlo = 1 lsl (to_int n.p) in print (d - dlo) n.hi; print dlo n.lo ) in if n == zero then fprintf fmt "0" else print (to_int (l n)) n (* TODO - to_float ? - of/to_z *)
null
https://raw.githubusercontent.com/backtracking/ocaml-bazaar/e8cb0a4549512e5369154579eaec9dcef04a8379/idd.ml
ocaml
************************************************************************ This software is free software; you can redistribute it and/or described in file LICENSE. This software 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. ************************************************************************ Integer Dichotomy Diagrams unique hash-consing memoization operations decrement d(n) = n-1 for n>0 increment i(n) = n+1 subtract FIXME binary length l(n) product huge numbers conversions TODO - to_float ? - of/to_z
Copyright ( C ) modify it under the terms of the GNU Library General Public License version 2.1 , with the special exception on linking type idd = { lo: idd; p: idd; hi: idd; } * this is lo + x(p ) * hi invariant max(lo , hi ) < ) , 0 < hi invariant max(lo,hi) < x(p), 0 < hi *) let rec zero = { u = 0; lo = zero; p = zero; hi = zero } let rec one = { u = 1; lo = one ; p = zero; hi = zero } module Hidd = struct type t = idd let hash n = (19 * (19 * n.lo.u + n.p.u) + n.hi.u) land max_int let equal n1 n2 = n1.lo == n2.lo && n1.p == n2.p && n1.hi == n2.hi end module Widd = Weak.Make(Hidd) let nodes = Widd.create 200323 let unique = ref 2 let create lo p hi = if hi == zero then lo else let n0 = { u = !unique; lo = lo; p = p; hi = hi } in let n = Widd.merge nodes n0 in if n == n0 then incr unique; n module H1 = Hashtbl.Make(struct type t = idd let hash n = n.u let equal = (==) end) let memo1 h f x = try H1.find h x with Not_found -> let y = f x in H1.add h x y; y let memo_rec1 f = let h = H1.create 16 in let rec g x = try H1.find h x with Not_found -> let y = f g x in H1.add h x y; y in g module H2 = Hashtbl.Make(struct type t = idd * idd let hash (n1, n2) = (19 * n1.u + n2.u) land max_int let equal (x1, x2) (y1, y2) = x1 == y1 && x2 == y2 end) let memo2 h f x1 x2 = let x = x1, x2 in try H2.find h x with Not_found -> let y = f x1 x2 in H2.add h x y; y let memo_rec2 f = let h = H2.create 16 in let rec g x1 x2 = let x = x1, x2 in try H2.find h x with Not_found -> let y = f g x1 x2 in H2.add h x y; y in g let hash i = i.u let equal = (==) let rec compare n m = if n == m then 0 else if m == zero then 1 else if n == zero then -1 else if n.p != m.p then compare n.p m.p else if n.hi != m.hi then compare n.hi m.hi else compare n.lo m.lo x(p ) = 2^(2^p ) let x p = create zero p one 2 = 2^(2 ^ 0 ) 4 = 2^(2 ^ 1 ) x'(q ) = x(q)-1 = 2^(2^q)-1 let rec x' q = if q == zero then one else let q = d q in let x = x' q in create x q x and d n = assert (n != zero); if n == one then zero else if n.lo != zero then create (d n.lo) n.p n.hi else if n.hi == one then x' n.p else create (x' n.p) n.p (d n.hi) let pred = d let rec i n = if n == zero then one else if n == one then two else if n.lo != x' n.p then create (i n.lo) n.p n.hi else if n.hi != x' n.p then create zero n.p (i n.hi) else create zero (i n.p) one let succ = i let ll n = succ n.p let three = succ two let five = succ four TODO ? memo x ' d i let htwice = H1.create 8192 let haddm = H2.create 8192 lo + x(p ) * hi , with no constraint let rec c lo p hi = let cmp_p_lop = compare p lo.p in if cmp_p_lop > 0 then c1 lo p hi else if cmp_p_lop = 0 then c1 lo.lo p (add hi lo.hi) else c (c lo.lo p hi) lo.p lo.hi lo + x(p ) * hi , with the constraint lo < ) and c1 lo p hi = let cmp_p_hip = compare p hi.p in if cmp_p_hip > 0 then create lo p hi else if cmp_p_hip = 0 then create (create lo p hi.lo) (i p) hi.hi else c (c1 lo p hi.lo) hi.p (c zero p hi.hi) add(a , b ) = a+b and add a b = if a == zero then b else if a == one then i b else let cmp = compare a b in if cmp = 0 then twice a else if cmp > 0 then add b a else if compare a.p b.p < 0 then c (add a b.lo) b.p b.hi else addm a b add(a , b ) when a < b and a.p = and addm a b = memo2 haddm compute_addm a b and compute_addm a b = assert (a.p == b.p); c (add a.lo b.lo) a.p (add a.hi b.hi) and twice a = memo1 htwice compute_twice a and compute_twice a = if a == zero then zero else if a == one then two else c (twice a.lo) a.p (twice a.hi) let hlogandm = H2.create 8192 let hlogorm = H2.create 8192 let hlogxorm = H2.create 8192 let rec logand a b = if a == zero then zero else if a == b then a else if compare a b > 0 then logand b a else if compare a.p b.p < 0 then logand a b.lo else logandm a b and logandm a b = memo2 hlogandm compute_logandm a b and compute_logandm a b = create (logand a.lo b.lo) a.p (logand a.hi b.hi) let rec logor a b = if a == zero then b else if a == b then a else if compare a b > 0 then logor b a else if compare a.p b.p < 0 then create (logor a b.lo) b.p b.hi else logorm a b and logorm a b = memo2 hlogorm compute_logorm a b and compute_logorm a b = create (logor a.lo b.lo) a.p (logor a.hi b.hi) let rec logxor a b = if a == zero then b else if a == b then zero else if compare a b > 0 then logxor b a else if compare a.p b.p < 0 then create (logxor a b.lo) b.p b.hi else logxorm a b and logxorm a b = memo2 hlogxorm compute_logxorm a b and compute_logxorm a b = create (logxor a.lo b.lo) a.p (logxor a.hi b.hi) let oc ( fun oc ( n , p ) - > assert ( compare ) ; ( * FIXME let oc = memo_rec2 (fun oc (n, p) -> if n == zero then x' p else let q = pred p in if n.p == q then create (oc (n.lo, q)) q (oc (n.hi, q)) else create (oc (n, q)) q (x' q)) *) let xor1 = memo_rec1 (fun xor1 n -> if n == zero then one else if n == one then zero else c (xor1 n.lo) n.p n.hi ) n xor 2^(2^p)-1 let nt = memo_rec2 (fun nt n p -> if n == zero then x' p else if n == one then xor1 (x' p) else let q = pred p in let cmp = compare q n.p in if cmp < 0 then invalid_arg "nt"; if cmp = 0 then c (nt n.lo q) q (nt n.hi q) else c (nt n q) q (x' q) ) let sub a b = let cmp = compare a b in if cmp < 0 then invalid_arg "sub"; if cmp = 0 then zero else if b == zero then a else if b == one then pred a else (succ (add a (nt b (succ a.p)))).lo remove MSB : rmsb(n ) = ( n - 2^i , i = l(n ) - 1 ) for n > 0 let rec rmsb n = if n == zero then invalid_arg "rmsb"; if n == one then zero, zero else let e, l = rmsb n.hi in create n.lo n.p e, imsb l n.p insert MSB : imsb(m , i ) = m + 2^i for m < 2^i and imsb m i = if i == zero then (assert (m == zero); one) else if i == one then if m == zero then two else (assert (m == one); three) else let e, l = rmsb i in if compare l m.p > 0 then create m l (imsb zero e) else create m.lo l (imsb m.hi e) let l n = if n == zero then zero else let _, i = rmsb n in succ i 2^i let pop = memo_rec1 (fun pop n -> if n == zero then zero else if n == one then one else add (pop n.lo) (pop n.hi)) let mul = memo_rec2 (fun mul a b -> if a == zero then zero else if a == one then b else if compare a b > 0 then mul b a else c (mul a b.lo) b.p (mul a b.hi)) let rec h n = if n = 0 then one else let x = h (n - 1) in create x x x let dfs vzero vone vnode n = let visited = H1.create 16 in H1.add visited zero vzero; H1.add visited one vone; let rec visit n = try H1.find visited n with Not_found -> let lo = visit n.lo and p = visit n.p and hi = visit n.hi in let v = vnode lo p hi in H1.add visited n v; v in visit n let size n = let res = ref 0 in dfs () () (fun _ _ _ -> incr res) n; !res let tree_size n = dfs 0 0 (fun x y z -> x+y+z+1) n let pmax_of_int = if Sys.word_size = 32 then 4 else 5 let rec of_small_int p = assert (p <= pmax_of_int); if p = 0 then zero else if p = 1 then one else succ (of_small_int (p-1)) let of_int n = if n < 0 then invalid_arg "of_int"; let rec of_int n p = if p < 0 then begin assert (n < 2); if n = 0 then zero else one end else let x = 1 lsl (1 lsl p) in create (of_int (n land (x-1)) (p-1)) (of_small_int p) (of_int (n lsr (1 lsl p)) (p-1)) in of_int n pmax_of_int let idd_max_int = of_int max_int let rec to_int n = if compare n idd_max_int > 0 then invalid_arg "to_int"; if n == zero then 0 else if n == one then 1 else to_int n.lo lor (to_int n.hi lsl (1 lsl to_int n.p)) TODO : to / of Int32 Int64 printing / parsing using the following format 2 = ( 0 , 0 , 1 ) 3 = ( 1 , 0 , 1 ) 4 = ( 2 , 2 , 3 ) 5 = ( 4 , 3 , 3 ) 2 = (0, 0, 1) 3 = (1, 0, 1) 4 = (2, 2, 3) 5 = (4, 3, 3) *) open Format let print fmt n = if n == zero || n == one then invalid_arg "print"; let idx = ref 1 in let visit lo p hi = if !idx > 1 then fprintf fmt "@\n"; let r = incr idx; string_of_int !idx in fprintf fmt "%s = (%s, %s, %s)" r lo p hi; r in ignore (dfs "0" "1" visit n) let parse sl = let nodes = Hashtbl.create 17 in Hashtbl.add nodes 0 zero; Hashtbl.add nodes 1 one; let parse s = Scanf.sscanf s "%d = (%d, %d, %d)" (fun r lo p hi -> let lo = Hashtbl.find nodes lo and p = Hashtbl.find nodes p and hi = Hashtbl.find nodes hi in let n = create lo p hi in Hashtbl.add nodes r n; n) in let rec iter = function | [] -> raise Not_found | [s] -> parse s | s :: l -> ignore (parse s); iter l in try iter sl with Not_found -> invalid_arg "parse" let printer fmt n = let p fmt n = try fprintf fmt "%d" (to_int n) with _ -> fprintf fmt "<too big>" in fprintf fmt "%a = @[%a@]" p n print n let print2 ~max_digits fmt n = if compare (l n) (of_int max_digits) > 0 then invalid_arg "print2"; let rec print d n = assert (d >= 1); if n == zero then fprintf fmt "%s0" (String.make (d-1) '0') else if n == one then fprintf fmt "%s1" (String.make (d-1) '0') else ( let dlo = 1 lsl (to_int n.p) in print (d - dlo) n.hi; print dlo n.lo ) in if n == zero then fprintf fmt "0" else print (to_int (l n)) n
456834cd9758668403fc35cb62ae7b950de4796dae94d8cd67cb494c80eac1bf
jfeser/castor
value.ml
open Core open Collections module T = struct type t = | Int of int | Date of Date.t | String of string | Bool of bool | Fixed of Fixed_point.t | Null [@@deriving compare, equal, hash, sexp, variants] end include T module C = Comparable.Make (T) module O : Comparable.Infix with type t := t = C let of_pred = function | `Int x -> Int x | `String x -> String x | `Bool x -> Bool x | `Fixed x -> Fixed x | `Null _ -> Null | `Date x -> Date x | _ -> failwith "Not a value." let to_sql = function | Int x -> Int.to_string x | Fixed x -> Fixed_point.to_string x | Date x -> sprintf "date('%s')" (Date.to_string x) | Bool true -> "true" | Bool false -> "false" | String s -> sprintf "'%s'" s | Null -> "null" let to_param = function | Int x -> Int.to_string x | Fixed x -> Fixed_point.to_string x | Date x -> Date.to_string x | Bool true -> "true" | Bool false -> "false" | String s -> s | Null -> "null" let pp fmt v = Format.fprintf fmt "%s" (to_sql v) let to_int = function Int x -> Some x | _ -> None let to_date = function Date x -> Some x | _ -> None let to_bool = function Bool x -> Some x | _ -> None let to_string = function String x -> Some x | _ -> None let type_error expected v = Error.create (sprintf "Expected a %s." expected) v [%sexp_of: t] |> Error.raise let to_int_exn = function Int x -> x | v -> type_error "int" v let to_date_exn = function Date x -> x | v -> type_error "date" v let to_bool_exn = function Bool x -> x | v -> type_error "bool" v let to_string_exn = function String x -> x | v -> type_error "string" v let to_pred = let module A = Ast in function | Int x -> `Int x | String x -> `String x | Bool x -> `Bool x | Fixed x -> `Fixed x | Null -> `Null None | Date x -> `Date x let ( + ) x y = match (x, y) with | Int a, Int b -> Int (a + b) | Fixed a, Fixed b -> Fixed Fixed_point.(a + b) | Int a, Fixed b | Fixed b, Int a -> Fixed Fixed_point.(b + of_int a) | Date a, Int b -> Date (Date.add_days a b) | _ -> Error.create "Cannot +" (x, y) [%sexp_of: t * t] |> Error.raise let neg = function | Int a -> Int (Int.neg a) | Fixed a -> Fixed Fixed_point.(-a) | Date _ | String _ | Bool _ | Null -> failwith "Cannot neg" let ( - ) x y = x + neg y let ( * ) x y = match (x, y) with | Int a, Int b -> Int (a * b) | Fixed a, Fixed b -> Fixed Fixed_point.(a * b) | Int a, Fixed b | Fixed b, Int a -> Fixed Fixed_point.(b * of_int a) | _ -> failwith "Cannot *" let ( / ) x y = match (x, y) with | Int a, Int b -> Fixed (Fixed_point.of_float Float.(of_int a / of_int b)) | Fixed a, Fixed b -> Fixed Fixed_point.(a / b) | Fixed a, Int b -> Fixed Fixed_point.(a / of_int b) | Int a, Fixed b -> Fixed Fixed_point.(of_int a / b) | _ -> Error.create "Cannot /" (x, y) [%sexp_of: t * t] |> Error.raise let ( % ) x y = to_int_exn x % to_int_exn y |> int
null
https://raw.githubusercontent.com/jfeser/castor/432ba569fb36f0a79883e647336b9a4700ebdf38/lib/value.ml
ocaml
open Core open Collections module T = struct type t = | Int of int | Date of Date.t | String of string | Bool of bool | Fixed of Fixed_point.t | Null [@@deriving compare, equal, hash, sexp, variants] end include T module C = Comparable.Make (T) module O : Comparable.Infix with type t := t = C let of_pred = function | `Int x -> Int x | `String x -> String x | `Bool x -> Bool x | `Fixed x -> Fixed x | `Null _ -> Null | `Date x -> Date x | _ -> failwith "Not a value." let to_sql = function | Int x -> Int.to_string x | Fixed x -> Fixed_point.to_string x | Date x -> sprintf "date('%s')" (Date.to_string x) | Bool true -> "true" | Bool false -> "false" | String s -> sprintf "'%s'" s | Null -> "null" let to_param = function | Int x -> Int.to_string x | Fixed x -> Fixed_point.to_string x | Date x -> Date.to_string x | Bool true -> "true" | Bool false -> "false" | String s -> s | Null -> "null" let pp fmt v = Format.fprintf fmt "%s" (to_sql v) let to_int = function Int x -> Some x | _ -> None let to_date = function Date x -> Some x | _ -> None let to_bool = function Bool x -> Some x | _ -> None let to_string = function String x -> Some x | _ -> None let type_error expected v = Error.create (sprintf "Expected a %s." expected) v [%sexp_of: t] |> Error.raise let to_int_exn = function Int x -> x | v -> type_error "int" v let to_date_exn = function Date x -> x | v -> type_error "date" v let to_bool_exn = function Bool x -> x | v -> type_error "bool" v let to_string_exn = function String x -> x | v -> type_error "string" v let to_pred = let module A = Ast in function | Int x -> `Int x | String x -> `String x | Bool x -> `Bool x | Fixed x -> `Fixed x | Null -> `Null None | Date x -> `Date x let ( + ) x y = match (x, y) with | Int a, Int b -> Int (a + b) | Fixed a, Fixed b -> Fixed Fixed_point.(a + b) | Int a, Fixed b | Fixed b, Int a -> Fixed Fixed_point.(b + of_int a) | Date a, Int b -> Date (Date.add_days a b) | _ -> Error.create "Cannot +" (x, y) [%sexp_of: t * t] |> Error.raise let neg = function | Int a -> Int (Int.neg a) | Fixed a -> Fixed Fixed_point.(-a) | Date _ | String _ | Bool _ | Null -> failwith "Cannot neg" let ( - ) x y = x + neg y let ( * ) x y = match (x, y) with | Int a, Int b -> Int (a * b) | Fixed a, Fixed b -> Fixed Fixed_point.(a * b) | Int a, Fixed b | Fixed b, Int a -> Fixed Fixed_point.(b * of_int a) | _ -> failwith "Cannot *" let ( / ) x y = match (x, y) with | Int a, Int b -> Fixed (Fixed_point.of_float Float.(of_int a / of_int b)) | Fixed a, Fixed b -> Fixed Fixed_point.(a / b) | Fixed a, Int b -> Fixed Fixed_point.(a / of_int b) | Int a, Fixed b -> Fixed Fixed_point.(of_int a / b) | _ -> Error.create "Cannot /" (x, y) [%sexp_of: t * t] |> Error.raise let ( % ) x y = to_int_exn x % to_int_exn y |> int
ff6200ee509d72e0d0dec0e73290edd4846ffdbcc1f9dfa30fb89ec9f0dfefca
noinia/hgeometry
MST.hs
# LANGUAGE ScopedTypeVariables # -------------------------------------------------------------------------------- -- | -- Module : Algorithms.Graph.MST Copyright : ( C ) -- License : see the LICENSE file Maintainer : -------------------------------------------------------------------------------- module Algorithms.Graph.MST( mst , mstEdges , makeTree ) where import Algorithms.Graph.DFS (AdjacencyLists, dfs') import Control.Monad (forM_, when, filterM) import Control.Monad.ST (ST,runST) import qualified Data.List as L import Data.PlanarGraph import Data.Tree import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import qualified Data.Vector.Unboxed.Mutable as UMV -------------------------------------------------------------------------------- -- | Minimum spanning tree of the edges. The result is a rooted tree, in which -- the nodes are the vertices in the planar graph together with the edge weight of the edge to their parent . The root 's weight is zero . -- The algorithm used is 's . -- -- running time: \(O(n \log n)\) mst :: Ord e => PlanarGraph s w v e f -> Tree (VertexId s w) mst g = makeTree g $ mstEdges g -- TODO: Add edges/darts to the output somehow. -- | Computes the set of edges in the Minimum spanning tree -- -- running time: \(O(n \log n)\) mstEdges :: Ord e => PlanarGraph s w v e f -> [Dart s] mstEdges g = runST $ do uf <- new (numVertices g) filterM (\e -> union uf (headOf e g) (tailOf e g)) edges'' where edges'' = map fst . L.sortOn snd . V.toList $ edges g -- | Given an underlying planar graph, and a set of edges that form a tree, -- create the actual tree. -- pre : the planar graph has at least one vertex . makeTree :: forall s w v e f. PlanarGraph s w v e f -> [Dart s] -> Tree (VertexId s w) makeTree g = flip dfs' start . mkAdjacencyLists where n = numVertices g start = V.head $ vertices' g append :: MV.MVector s' [a] -> VertexId s w -> a -> ST s' () append v (VertexId i) x = MV.read v i >>= MV.write v i . (x:) mkAdjacencyLists :: [Dart s] -> AdjacencyLists s w mkAdjacencyLists edges'' = V.create $ do vs <- MV.replicate n [] forM_ edges'' $ \e -> do let u = headOf e g v = tailOf e g append vs u v append vs v u pure vs -------------------------------------------------------------------------------- -- | Union find DS newtype UF s a = UF { _unUF :: UMV.MVector s (Int,Int) } new :: Int -> ST s (UF s a) new n = do v <- UMV.new n forM_ [0..n-1] $ \i -> UMV.write v i (i,0) pure $ UF v | Union the components containing x and y. Returns weather or not the two -- components were already in the same component or not. union :: (Enum a, Eq a) => UF s a -> a -> a -> ST s Bool union uf@(UF v) x y = do (rx,rrx) <- find' uf x (ry,rry) <- find' uf y let b = rx /= ry rx' = fromEnum rx ry' = fromEnum ry when b $ case rrx `compare` rry of LT -> UMV.write v rx' (ry',rrx) GT -> UMV.write v ry' (rx',rry) EQ -> do UMV.write v ry' (rx',rry) UMV.write v rx' (rx',rrx+1) pure b -- | Get the representative of the component containing x find : : ( a , a ) = > UF s a - > a - > ST s a -- find uf = fmap fst . find' uf -- | get the representative (and its rank) of the component containing x find' :: (Enum a, Eq a) => UF s a -> a -> ST s (a,Int) find' uf@(UF v) x = do (p,r) <- UMV.read v (fromEnum x) -- get my parent if toEnum p == x then pure (x,r) -- I am a root else do rt@(j,_) <- find' uf (toEnum p) -- get the root of my parent UMV.write v (fromEnum x) (fromEnum j,r) -- path compression pure rt -------------------------------------------------------------------------------- partial implementation of Prims -- mst g = undefined -- | runs MST with a given root mstFrom : : ( e , Monoid e ) = > > PlanarGraph s w v e f - > Tree ( , e ) mstFrom r g = prims initialQ ( Node ( r , ) [ ] ) -- where update ' k p q = Q.adjust ( const p ) k q -- initial Q has the value of the root set to the zero element , and has no -- -- parent. The others are all set to Top (and have no parent yet) initialQ = update ' r ( ValT ( , Nothing ) ) . GV.foldr ( \v q - > v ( Top , Nothing ) q ) Q.empty $ vertices g -- prims qq t = case Q.minView qq of -- Nothing -> t Just ( v Q.:- > ( w , p ) , q ) - > prims $ -------------------------------------------------------------------------------- -- Testing Stuff -- testG = planarGraph' [ [ (Dart aA Negative, "a-") , ( Dart aC Positive , " c+ " ) , ( Dart aB Positive , " " ) -- , (Dart aA Positive, "a+") -- ] , [ ( Dart aE Negative , " e- " ) -- , (Dart aB Negative, "b-") , ( Dart aD Negative , " d- " ) , ( Dart aG Positive , " g+ " ) -- ] , [ ( Dart aE Positive , " e+ " ) , ( Dart aD Positive , " d+ " ) -- , (Dart aC Negative, "c-") -- ] -- , [ (Dart aG Negative, "g-") -- ] -- ] -- where ( aA : aB : aC : aD : aE : aG : _ ) = take 6 [ Arc 0 .. ]
null
https://raw.githubusercontent.com/noinia/hgeometry/a6abecb1ce4a7fd96b25cc1a5c65cd4257ecde7a/hgeometry-combinatorial/src/Algorithms/Graph/MST.hs
haskell
------------------------------------------------------------------------------ | Module : Algorithms.Graph.MST License : see the LICENSE file ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | Minimum spanning tree of the edges. The result is a rooted tree, in which the nodes are the vertices in the planar graph together with the edge weight running time: \(O(n \log n)\) TODO: Add edges/darts to the output somehow. | Computes the set of edges in the Minimum spanning tree running time: \(O(n \log n)\) | Given an underlying planar graph, and a set of edges that form a tree, create the actual tree. ------------------------------------------------------------------------------ | Union find DS components were already in the same component or not. | Get the representative of the component containing x find uf = fmap fst . find' uf | get the representative (and its rank) of the component containing x get my parent I am a root get the root of my parent path compression ------------------------------------------------------------------------------ mst g = undefined | runs MST with a given root where initial Q has the value of the root set to the zero element , and has no -- parent. The others are all set to Top (and have no parent yet) prims qq t = case Q.minView qq of Nothing -> t ------------------------------------------------------------------------------ Testing Stuff testG = planarGraph' [ [ (Dart aA Negative, "a-") , (Dart aA Positive, "a+") ] , (Dart aB Negative, "b-") ] , (Dart aC Negative, "c-") ] , [ (Dart aG Negative, "g-") ] ] where
# LANGUAGE ScopedTypeVariables # Copyright : ( C ) Maintainer : module Algorithms.Graph.MST( mst , mstEdges , makeTree ) where import Algorithms.Graph.DFS (AdjacencyLists, dfs') import Control.Monad (forM_, when, filterM) import Control.Monad.ST (ST,runST) import qualified Data.List as L import Data.PlanarGraph import Data.Tree import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import qualified Data.Vector.Unboxed.Mutable as UMV of the edge to their parent . The root 's weight is zero . The algorithm used is 's . mst :: Ord e => PlanarGraph s w v e f -> Tree (VertexId s w) mst g = makeTree g $ mstEdges g mstEdges :: Ord e => PlanarGraph s w v e f -> [Dart s] mstEdges g = runST $ do uf <- new (numVertices g) filterM (\e -> union uf (headOf e g) (tailOf e g)) edges'' where edges'' = map fst . L.sortOn snd . V.toList $ edges g pre : the planar graph has at least one vertex . makeTree :: forall s w v e f. PlanarGraph s w v e f -> [Dart s] -> Tree (VertexId s w) makeTree g = flip dfs' start . mkAdjacencyLists where n = numVertices g start = V.head $ vertices' g append :: MV.MVector s' [a] -> VertexId s w -> a -> ST s' () append v (VertexId i) x = MV.read v i >>= MV.write v i . (x:) mkAdjacencyLists :: [Dart s] -> AdjacencyLists s w mkAdjacencyLists edges'' = V.create $ do vs <- MV.replicate n [] forM_ edges'' $ \e -> do let u = headOf e g v = tailOf e g append vs u v append vs v u pure vs newtype UF s a = UF { _unUF :: UMV.MVector s (Int,Int) } new :: Int -> ST s (UF s a) new n = do v <- UMV.new n forM_ [0..n-1] $ \i -> UMV.write v i (i,0) pure $ UF v | Union the components containing x and y. Returns weather or not the two union :: (Enum a, Eq a) => UF s a -> a -> a -> ST s Bool union uf@(UF v) x y = do (rx,rrx) <- find' uf x (ry,rry) <- find' uf y let b = rx /= ry rx' = fromEnum rx ry' = fromEnum ry when b $ case rrx `compare` rry of LT -> UMV.write v rx' (ry',rrx) GT -> UMV.write v ry' (rx',rry) EQ -> do UMV.write v ry' (rx',rry) UMV.write v rx' (rx',rrx+1) pure b find : : ( a , a ) = > UF s a - > a - > ST s a find' :: (Enum a, Eq a) => UF s a -> a -> ST s (a,Int) find' uf@(UF v) x = do if toEnum p == x then else do pure rt partial implementation of Prims mstFrom : : ( e , Monoid e ) = > > PlanarGraph s w v e f - > Tree ( , e ) mstFrom r g = prims initialQ ( Node ( r , ) [ ] ) update ' k p q = Q.adjust ( const p ) k q initialQ = update ' r ( ValT ( , Nothing ) ) . GV.foldr ( \v q - > v ( Top , Nothing ) q ) Q.empty $ vertices g Just ( v Q.:- > ( w , p ) , q ) - > prims $ , ( Dart aC Positive , " c+ " ) , ( Dart aB Positive , " " ) , [ ( Dart aE Negative , " e- " ) , ( Dart aD Negative , " d- " ) , ( Dart aG Positive , " g+ " ) , [ ( Dart aE Positive , " e+ " ) , ( Dart aD Positive , " d+ " ) ( aA : aB : aC : aD : aE : aG : _ ) = take 6 [ Arc 0 .. ]
fb6654544aef936eb51f213601e7145856d35ef1d15410597a765f1f74227938
qfpl/applied-fp-course
File.hs
module Level07.Conf.File where import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as LBS import Data.Text (pack) import Data.Bifunctor (first) import Waargonaut.Attoparsec (pureDecodeAttoparsecByteString) import Control.Exception (try) import Level07.Types (ConfigError (..), PartialConf, partialConfDecoder) Doctest setup section -- $setup -- >>> :set -XOverloadedStrings -- | Update these tests when you've completed this function. -- -- | readConfFile > > > readConfFile " badFileName.no " -- Left (ConfigFileReadError badFileName.no: openBinaryFile: does not exist (No such file or directory)) -- >>> readConfFile "files/test.json" -- Right "{\"foo\":33}\n" -- readConfFile :: FilePath -> IO ( Either ConfigError ByteString ) readConfFile fp = first ConfigFileReadError <$> try (LBS.readFile fp) | Construct the function that will take a ` ` FilePath ` ` , read it in , decode it , -- and construct our ``PartialConf``. parseJSONConfigFile :: FilePath -> IO ( Either ConfigError PartialConf ) parseJSONConfigFile fp = (first BadConfFile . runDecode =<<) <$> readConfFile fp where runDecode = pureDecodeAttoparsecByteString partialConfDecoder
null
https://raw.githubusercontent.com/qfpl/applied-fp-course/d5a94a9dcee677bc95a5184c2ed13329c9f07559/src/Level07/Conf/File.hs
haskell
$setup >>> :set -XOverloadedStrings | Update these tests when you've completed this function. | readConfFile Left (ConfigFileReadError badFileName.no: openBinaryFile: does not exist (No such file or directory)) >>> readConfFile "files/test.json" Right "{\"foo\":33}\n" and construct our ``PartialConf``.
module Level07.Conf.File where import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as LBS import Data.Text (pack) import Data.Bifunctor (first) import Waargonaut.Attoparsec (pureDecodeAttoparsecByteString) import Control.Exception (try) import Level07.Types (ConfigError (..), PartialConf, partialConfDecoder) Doctest setup section > > > readConfFile " badFileName.no " readConfFile :: FilePath -> IO ( Either ConfigError ByteString ) readConfFile fp = first ConfigFileReadError <$> try (LBS.readFile fp) | Construct the function that will take a ` ` FilePath ` ` , read it in , decode it , parseJSONConfigFile :: FilePath -> IO ( Either ConfigError PartialConf ) parseJSONConfigFile fp = (first BadConfFile . runDecode =<<) <$> readConfFile fp where runDecode = pureDecodeAttoparsecByteString partialConfDecoder
22f15d896a681cfde61c74cd1e3b1bfb34649e16b8bddf4cb83b94a82c22ca02
ryanpbrewster/haskell
CoinJam.hs
module Main where import Data.Maybe import Data.List data JamCoin = JamCoin String [Integer] deriving (Show) validateJamCoin :: Integer -> Maybe JamCoin validateJamCoin n = let bitstr = bitString n interpretations = [ interpret b bitstr | b <- [2..10] ] evidence = map nonTrivialDivisor interpretations in if all isJust evidence then Just (JamCoin bitstr $ catMaybes evidence) else Nothing bitString :: Integer -> String bitString 0 = "0" bitString n = reverse (build n) where build 0 = "" build n = (if odd n then '1' else '0') : build (n `div` 2) interpret :: Integer -> String -> Integer interpret b xs = foldl build 0 xs where build acc x = b * acc + (if x == '1' then 1 else 0) primes :: [Integer] primes = 2 : filter isPrime [3,5..] isPrime :: Integer -> Bool isPrime = isNothing . nonTrivialDivisor nonTrivialDivisor :: Integer -> Maybe Integer nonTrivialDivisor n = find (\p -> n `mod` p == 0) $ takeWhile (\p -> p*p <= n) primes
null
https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/GoogleCodeJam/CoinJam/CoinJam.hs
haskell
module Main where import Data.Maybe import Data.List data JamCoin = JamCoin String [Integer] deriving (Show) validateJamCoin :: Integer -> Maybe JamCoin validateJamCoin n = let bitstr = bitString n interpretations = [ interpret b bitstr | b <- [2..10] ] evidence = map nonTrivialDivisor interpretations in if all isJust evidence then Just (JamCoin bitstr $ catMaybes evidence) else Nothing bitString :: Integer -> String bitString 0 = "0" bitString n = reverse (build n) where build 0 = "" build n = (if odd n then '1' else '0') : build (n `div` 2) interpret :: Integer -> String -> Integer interpret b xs = foldl build 0 xs where build acc x = b * acc + (if x == '1' then 1 else 0) primes :: [Integer] primes = 2 : filter isPrime [3,5..] isPrime :: Integer -> Bool isPrime = isNothing . nonTrivialDivisor nonTrivialDivisor :: Integer -> Maybe Integer nonTrivialDivisor n = find (\p -> n `mod` p == 0) $ takeWhile (\p -> p*p <= n) primes
cc58c0ea2bf3588fc19e34b7b98c01b61ab8cfd73fa74a51a595c250fa7fff1d
Innf107/cobble-compiler
Parser.hs
module Cobble.Prelude.Parser ( module Exports , many, sepBy, sepBy1 ) where import Cobble.Prelude as Exports hiding (optional, noneOf, try, many) import Text.Parsec qualified as P import Text.Parsec as Exports hiding ( (<|>), State, Empty, uncons , many, sepBy, sepBy1 ) import Text.Parsec.Pos as Exports many :: ParsecT s u m a -> ParsecT s u m (Seq a) many = fmap fromList . P.many sepBy :: Stream s m t => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m (Seq a) sepBy p s = fromList <$> P.sepBy p s sepBy1 :: Stream s m t => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m (Seq a) sepBy1 p s = fromList <$> P.sepBy1 p s
null
https://raw.githubusercontent.com/Innf107/cobble-compiler/d6b0b65dad0fd6f1d593f7f859b1cc832e01e21f/src/Cobble/Prelude/Parser.hs
haskell
module Cobble.Prelude.Parser ( module Exports , many, sepBy, sepBy1 ) where import Cobble.Prelude as Exports hiding (optional, noneOf, try, many) import Text.Parsec qualified as P import Text.Parsec as Exports hiding ( (<|>), State, Empty, uncons , many, sepBy, sepBy1 ) import Text.Parsec.Pos as Exports many :: ParsecT s u m a -> ParsecT s u m (Seq a) many = fmap fromList . P.many sepBy :: Stream s m t => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m (Seq a) sepBy p s = fromList <$> P.sepBy p s sepBy1 :: Stream s m t => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m (Seq a) sepBy1 p s = fromList <$> P.sepBy1 p s
c4546387596ccc17f9e8cf8d74bf76412634da96162dac2ada0557d57c891c25
haskell/cabal
Library.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # module Distribution.Types.Library ( Library(..), emptyLibrary, explicitLibModules, libModulesAutogen, ) where import Distribution.Compat.Prelude import Prelude () import Distribution.ModuleName import Distribution.Types.BuildInfo import Distribution.Types.LibraryVisibility import Distribution.Types.ModuleReexport import Distribution.Types.LibraryName import qualified Distribution.Types.BuildInfo.Lens as L data Library = Library { libName :: LibraryName , exposedModules :: [ModuleName] , reexportedModules :: [ModuleReexport] , signatures :: [ModuleName] -- ^ What sigs need implementations? , libExposed :: Bool -- ^ Is the lib to be exposed by default? (i.e. whether its modules available in GHCi for example) , libVisibility :: LibraryVisibility -- ^ Whether this multilib can be used as a dependency for other packages. , libBuildInfo :: BuildInfo } deriving (Generic, Show, Eq, Ord, Read, Typeable, Data) instance L.HasBuildInfo Library where buildInfo f l = (\x -> l { libBuildInfo = x }) <$> f (libBuildInfo l) instance Binary Library instance Structured Library instance NFData Library where rnf = genericRnf emptyLibrary :: Library emptyLibrary = Library { libName = LMainLibName , exposedModules = mempty , reexportedModules = mempty , signatures = mempty , libExposed = True , libVisibility = mempty , libBuildInfo = mempty } -- | This instance is not good. -- -- We need it for 'PackageDescription.Configuration.addBuildableCondition'. -- More correct method would be some kind of "create empty clone". -- -- More concretely, 'addBuildableCondition' will make `libVisibility = False` -- libraries when `buildable: false`. This may cause problems. -- instance Monoid Library where mempty = emptyLibrary mappend = (<>) instance Semigroup Library where a <> b = Library { libName = combineLibraryName (libName a) (libName b) , exposedModules = combine exposedModules , reexportedModules = combine reexportedModules , signatures = combine signatures , libExposed = libExposed a && libExposed b -- so False propagates , libVisibility = combine libVisibility , libBuildInfo = combine libBuildInfo } where combine field = field a `mappend` field b -- | Get all the module names from the library (exposed and internal modules) -- which are explicitly listed in the package description which would -- need to be compiled. (This does not include reexports, which -- do not need to be compiled.) This may not include all modules for which GHC generated interface files ( i.e. , implicit modules . ) explicitLibModules :: Library -> [ModuleName] explicitLibModules lib = exposedModules lib ++ otherModules (libBuildInfo lib) ++ signatures lib -- | Get all the auto generated module names from the library, exposed or not. -- This are a subset of 'libModules'. libModulesAutogen :: Library -> [ModuleName] libModulesAutogen lib = autogenModules (libBuildInfo lib) -- | Combine 'LibraryName'. in parsing we prefer value coming -- from munged @name@ field over the @lib-name@. -- -- /Should/ be irrelevant. combineLibraryName :: LibraryName -> LibraryName -> LibraryName combineLibraryName l@(LSubLibName _) _ = l combineLibraryName _ l = l
null
https://raw.githubusercontent.com/haskell/cabal/53c5dc9f9b19d01284e2b07d43e010b732ac91a8/Cabal-syntax/src/Distribution/Types/Library.hs
haskell
# LANGUAGE DeriveDataTypeable # ^ What sigs need implementations? ^ Is the lib to be exposed by default? (i.e. whether its modules available in GHCi for example) ^ Whether this multilib can be used as a dependency for other packages. | This instance is not good. We need it for 'PackageDescription.Configuration.addBuildableCondition'. More correct method would be some kind of "create empty clone". More concretely, 'addBuildableCondition' will make `libVisibility = False` libraries when `buildable: false`. This may cause problems. so False propagates | Get all the module names from the library (exposed and internal modules) which are explicitly listed in the package description which would need to be compiled. (This does not include reexports, which do not need to be compiled.) This may not include all modules for which | Get all the auto generated module names from the library, exposed or not. This are a subset of 'libModules'. | Combine 'LibraryName'. in parsing we prefer value coming from munged @name@ field over the @lib-name@. /Should/ be irrelevant.
# LANGUAGE DeriveGeneric # module Distribution.Types.Library ( Library(..), emptyLibrary, explicitLibModules, libModulesAutogen, ) where import Distribution.Compat.Prelude import Prelude () import Distribution.ModuleName import Distribution.Types.BuildInfo import Distribution.Types.LibraryVisibility import Distribution.Types.ModuleReexport import Distribution.Types.LibraryName import qualified Distribution.Types.BuildInfo.Lens as L data Library = Library { libName :: LibraryName , exposedModules :: [ModuleName] , reexportedModules :: [ModuleReexport] , libBuildInfo :: BuildInfo } deriving (Generic, Show, Eq, Ord, Read, Typeable, Data) instance L.HasBuildInfo Library where buildInfo f l = (\x -> l { libBuildInfo = x }) <$> f (libBuildInfo l) instance Binary Library instance Structured Library instance NFData Library where rnf = genericRnf emptyLibrary :: Library emptyLibrary = Library { libName = LMainLibName , exposedModules = mempty , reexportedModules = mempty , signatures = mempty , libExposed = True , libVisibility = mempty , libBuildInfo = mempty } instance Monoid Library where mempty = emptyLibrary mappend = (<>) instance Semigroup Library where a <> b = Library { libName = combineLibraryName (libName a) (libName b) , exposedModules = combine exposedModules , reexportedModules = combine reexportedModules , signatures = combine signatures , libVisibility = combine libVisibility , libBuildInfo = combine libBuildInfo } where combine field = field a `mappend` field b GHC generated interface files ( i.e. , implicit modules . ) explicitLibModules :: Library -> [ModuleName] explicitLibModules lib = exposedModules lib ++ otherModules (libBuildInfo lib) ++ signatures lib libModulesAutogen :: Library -> [ModuleName] libModulesAutogen lib = autogenModules (libBuildInfo lib) combineLibraryName :: LibraryName -> LibraryName -> LibraryName combineLibraryName l@(LSubLibName _) _ = l combineLibraryName _ l = l
bbc394c326ccb00947b15c72791d8ce1893d7d217ac636e7b9188c45f60c45fa
CloudI/CloudI
tcp_echo_app.erl
%% Feel free to use, reuse and abuse the code in this file. @private -module(tcp_echo_app). -behaviour(application). %% API. -export([start/2]). -export([stop/1]). %% API. start(_Type, _Args) -> {ok, _} = ranch1:start_listener(tcp_echo, 1, ranch1_tcp, [{port, 5555}], echo_protocol, []), tcp_echo_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/cloudi_x_ranch1/examples/tcp_echo/src/tcp_echo_app.erl
erlang
Feel free to use, reuse and abuse the code in this file. API. API.
@private -module(tcp_echo_app). -behaviour(application). -export([start/2]). -export([stop/1]). start(_Type, _Args) -> {ok, _} = ranch1:start_listener(tcp_echo, 1, ranch1_tcp, [{port, 5555}], echo_protocol, []), tcp_echo_sup:start_link(). stop(_State) -> ok.
3c40d6dce0a7b3aab8e4dc13fe5831794b01ed6b9f0bf8c01f3aa2c4b7b01c89
AlfrescoLabs/technical-validation
project.clj
; Copyright © 2013,2014 ( ) ; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; -2.0 ; ; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ; This file is part of an unsupported extension to Alfresco . ; (defproject org.alfrescolabs.alfresco-technical-validation "0.7.0-SNAPSHOT" :description "Performs technical validation of an Alfresco extension." :url "" :license {:name "Apache License, Version 2.0" :url "-2.0"} :min-lein-version "2.4.0" :javac-target "1.7" :dependencies [ [org.clojure/clojure "1.6.0"] [org.clojure/tools.cli "0.3.1"] [org.clojure/tools.logging "0.3.1"] [clojurewerkz/neocons "3.0.0"] [ch.qos.logback/logback-classic "1.1.3"] [me.raynes/conch "0.7.0"] [jansi-clj "0.1.0"] [io.aviso/pretty "0.1.18"] [org.clojars.pmonks/depends "0.3.0"] [org.clojars.pmonks/multigrep "0.2.0"] [org.clojars.pmonks/bookmark-writer "0.1.0"] [org.clojars.pmonks/spinner "0.3.0"] [enlive "1.1.6"] ] :plugins [[lein2-eclipse "2.0.0"]] :profiles {:uberjar {:aot :all}} :source-paths ["src/clojure"] :java-source-paths ["src/java"] :main alfresco-technical-validation.main : jvm - opts [ " -server " " -agentpath:/Applications / YourKit / bin / mac / libyjpagent.jnilib " ] ; To allow YourKit profiling :jvm-opts ["-server"] :bin {:name "atv"})
null
https://raw.githubusercontent.com/AlfrescoLabs/technical-validation/bd1b4b83f6a5e9dd150eedbeebecd30970d3b4aa/project.clj
clojure
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. To allow YourKit profiling
Copyright © 2013,2014 ( ) distributed under the License is distributed on an " AS IS " BASIS , This file is part of an unsupported extension to Alfresco . (defproject org.alfrescolabs.alfresco-technical-validation "0.7.0-SNAPSHOT" :description "Performs technical validation of an Alfresco extension." :url "" :license {:name "Apache License, Version 2.0" :url "-2.0"} :min-lein-version "2.4.0" :javac-target "1.7" :dependencies [ [org.clojure/clojure "1.6.0"] [org.clojure/tools.cli "0.3.1"] [org.clojure/tools.logging "0.3.1"] [clojurewerkz/neocons "3.0.0"] [ch.qos.logback/logback-classic "1.1.3"] [me.raynes/conch "0.7.0"] [jansi-clj "0.1.0"] [io.aviso/pretty "0.1.18"] [org.clojars.pmonks/depends "0.3.0"] [org.clojars.pmonks/multigrep "0.2.0"] [org.clojars.pmonks/bookmark-writer "0.1.0"] [org.clojars.pmonks/spinner "0.3.0"] [enlive "1.1.6"] ] :plugins [[lein2-eclipse "2.0.0"]] :profiles {:uberjar {:aot :all}} :source-paths ["src/clojure"] :java-source-paths ["src/java"] :main alfresco-technical-validation.main :jvm-opts ["-server"] :bin {:name "atv"})
355dbf5e349a47d4af22e940c3bb905b61d5eb6d3cc364e29fe5d8c38a62016a
schemedoc/implementation-metadata
stalingrad.scm
(title "Stalin∇") (tagline "brutally optimizing compiler for VLAD, a pure Scheme with first-class automatic differentiation operators") (github "Functional-AutoDiff/STALINGRAD")
null
https://raw.githubusercontent.com/schemedoc/implementation-metadata/6280d9c4c73833dc5bd1c9bef9b45be6ea5beb68/schemes/stalingrad.scm
scheme
(title "Stalin∇") (tagline "brutally optimizing compiler for VLAD, a pure Scheme with first-class automatic differentiation operators") (github "Functional-AutoDiff/STALINGRAD")
6850db9c7fb890b6d41d6144619be341e5b3aa8f244cbada81859bf81e8d08fb
coast-framework/coast
migrations.clj
(ns coast.migrations (:require [coast.migrations.sql :as migrations.sql] [coast.migrations.edn :as migrations.edn] [coast.db.migrations] [coast.db.connection :refer [connection]] [coast.db.schema :as schema] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [clojure.set :as set]) (:import (java.io File))) (defn migrations-dir [] (.mkdirs (File. "db/migrations")) "db/migrations") (defn migration-files [] (->> (migrations-dir) (io/file) (file-seq) (filter #(.isFile %)) (map #(.getName %)) (filter #(or (.endsWith % ".sql") (.endsWith % ".edn") (.endsWith % ".clj"))))) (defn create-table [] (jdbc/db-do-commands (connection) (jdbc/create-table-ddl :coast_schema_migrations [[:version "text" :primary :key]] {:conditional? true}))) (defn completed-migrations [] (create-table) (->> (jdbc/query (connection) ["select version from coast_schema_migrations order by version"] {:keywordize? true}) (map :version))) (defn version [filename] (first (string/split filename #"_"))) (defn migration-filename [version] (when (some? version) (let [filenames (migration-files)] (first (filter #(string/starts-with? % (str version)) filenames))))) (defn pending [] (let [filenames (migration-files) all (set (map version filenames)) completed (set (completed-migrations)) versions (sort (set/difference all completed))] (mapv migration-filename versions))) (defn statements [filename] (let [migration-type (last (string/split filename #"\.")) filename-with-path (str (migrations-dir) "/" filename) contents (slurp filename-with-path)] (condp = migration-type "sql" {:sql (migrations.sql/up contents) :filename filename} "edn" {:sql (migrations.edn/migrate contents) :raw contents :filename filename} (let [f (load-file filename-with-path) ;; the last var defined {:syms [up change]} (-> f meta :ns .getName ns-publics) output ((or up change (constantly nil)))] {:sql (string/join "" output) :vec output :filename filename})))) (defn migrate [] (let [migrations (pending)] (reset! coast.db.migrations/rollback? false) (doseq [migration migrations] (let [statements (statements migration) friendly-name (string/replace migration #"\.edn|\.sql|\.clj" "")] (if (string/blank? (:sql statements)) (throw (Exception. (format "%s is empty" migration))) (do (println "") (println "-- Migrating: " friendly-name "---------------------") (println "") (println (or (:raw statements) (:sql statements))) (println "") (println "--" friendly-name "---------------------") (println "") (jdbc/db-do-commands (connection) (or (:vec statements) (:sql statements))) (jdbc/insert! (connection) :coast_schema_migrations {:version (version migration)}) (when (.endsWith migration ".edn") (schema/save (:raw statements))) (println friendly-name "migrated successfully"))))))) (defn rollback-statements [filename] (let [migration-type (last (string/split filename #"\.")) filename-with-path (str (migrations-dir) "/" filename) contents (slurp filename-with-path)] (condp = migration-type "sql" {:sql (migrations.sql/down contents) :filename filename} "edn" {:sql (migrations.edn/rollback contents) :raw contents :filename filename} (let [f (load-file filename-with-path) ;; Figure out what the migration's given us... {:syms [down change]} (-> f meta :ns .getName ns-publics) output (cond down (do (reset! coast.db.migrations/rollback? false) ;; don't auto-undo anything, (down) ;; because we're gonna run 'down' exactly as provided; (reset! coast.db.migrations/rollback? true)) ;; and then put it back. change (change) :else nil)] {:sql (string/join "" output) :vec output :filename filename})))) (defn rollback [] (let [migration (migration-filename (last (completed-migrations))) _ (reset! coast.db.migrations/rollback? true)] (when (some? migration) (let [statements (rollback-statements migration) friendly-name (string/replace migration #"\.edn|\.sql|\.clj" "")] (if (string/blank? (:sql statements)) (throw (Exception. (format "%s is empty" migration))) (do (println "") (println "-- Rolling back:" friendly-name "---------------------") (println "") (println (or (:raw statements) (:sql statements))) (println "") (println "--" friendly-name "---------------------") (println "") (jdbc/db-do-commands (connection) (or (:vec statements) (:sql statements))) (jdbc/delete! (connection) :coast_schema_migrations ["version = ?" (version migration)]) (when (.endsWith migration ".edn") (schema/save (:raw statements))) (println friendly-name "rolled back successfully"))))))) (defn -main [action] (case action "migrate" (migrate) "rollback" (rollback) ""))
null
https://raw.githubusercontent.com/coast-framework/coast/5d4a6db4cd87ed9a6d0e3015fdaec0ba0e1b6012/src/coast/migrations.clj
clojure
the last var defined Figure out what the migration's given us... don't auto-undo anything, because we're gonna run 'down' exactly as provided; and then put it back.
(ns coast.migrations (:require [coast.migrations.sql :as migrations.sql] [coast.migrations.edn :as migrations.edn] [coast.db.migrations] [coast.db.connection :refer [connection]] [coast.db.schema :as schema] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.string :as string] [clojure.set :as set]) (:import (java.io File))) (defn migrations-dir [] (.mkdirs (File. "db/migrations")) "db/migrations") (defn migration-files [] (->> (migrations-dir) (io/file) (file-seq) (filter #(.isFile %)) (map #(.getName %)) (filter #(or (.endsWith % ".sql") (.endsWith % ".edn") (.endsWith % ".clj"))))) (defn create-table [] (jdbc/db-do-commands (connection) (jdbc/create-table-ddl :coast_schema_migrations [[:version "text" :primary :key]] {:conditional? true}))) (defn completed-migrations [] (create-table) (->> (jdbc/query (connection) ["select version from coast_schema_migrations order by version"] {:keywordize? true}) (map :version))) (defn version [filename] (first (string/split filename #"_"))) (defn migration-filename [version] (when (some? version) (let [filenames (migration-files)] (first (filter #(string/starts-with? % (str version)) filenames))))) (defn pending [] (let [filenames (migration-files) all (set (map version filenames)) completed (set (completed-migrations)) versions (sort (set/difference all completed))] (mapv migration-filename versions))) (defn statements [filename] (let [migration-type (last (string/split filename #"\.")) filename-with-path (str (migrations-dir) "/" filename) contents (slurp filename-with-path)] (condp = migration-type "sql" {:sql (migrations.sql/up contents) :filename filename} "edn" {:sql (migrations.edn/migrate contents) :raw contents :filename filename} {:syms [up change]} (-> f meta :ns .getName ns-publics) output ((or up change (constantly nil)))] {:sql (string/join "" output) :vec output :filename filename})))) (defn migrate [] (let [migrations (pending)] (reset! coast.db.migrations/rollback? false) (doseq [migration migrations] (let [statements (statements migration) friendly-name (string/replace migration #"\.edn|\.sql|\.clj" "")] (if (string/blank? (:sql statements)) (throw (Exception. (format "%s is empty" migration))) (do (println "") (println "-- Migrating: " friendly-name "---------------------") (println "") (println (or (:raw statements) (:sql statements))) (println "") (println "--" friendly-name "---------------------") (println "") (jdbc/db-do-commands (connection) (or (:vec statements) (:sql statements))) (jdbc/insert! (connection) :coast_schema_migrations {:version (version migration)}) (when (.endsWith migration ".edn") (schema/save (:raw statements))) (println friendly-name "migrated successfully"))))))) (defn rollback-statements [filename] (let [migration-type (last (string/split filename #"\.")) filename-with-path (str (migrations-dir) "/" filename) contents (slurp filename-with-path)] (condp = migration-type "sql" {:sql (migrations.sql/down contents) :filename filename} "edn" {:sql (migrations.edn/rollback contents) :raw contents :filename filename} (let [f (load-file filename-with-path) {:syms [down change]} (-> f meta :ns .getName ns-publics) output (cond down (do change (change) :else nil)] {:sql (string/join "" output) :vec output :filename filename})))) (defn rollback [] (let [migration (migration-filename (last (completed-migrations))) _ (reset! coast.db.migrations/rollback? true)] (when (some? migration) (let [statements (rollback-statements migration) friendly-name (string/replace migration #"\.edn|\.sql|\.clj" "")] (if (string/blank? (:sql statements)) (throw (Exception. (format "%s is empty" migration))) (do (println "") (println "-- Rolling back:" friendly-name "---------------------") (println "") (println (or (:raw statements) (:sql statements))) (println "") (println "--" friendly-name "---------------------") (println "") (jdbc/db-do-commands (connection) (or (:vec statements) (:sql statements))) (jdbc/delete! (connection) :coast_schema_migrations ["version = ?" (version migration)]) (when (.endsWith migration ".edn") (schema/save (:raw statements))) (println friendly-name "rolled back successfully"))))))) (defn -main [action] (case action "migrate" (migrate) "rollback" (rollback) ""))
2cea94395a700e25e2fd647fc0c4c9df1d4c4379e526696483b5a84bf625dfe6
jpmonettas/clograms
build.clj
(ns build (:require [clojure.tools.build.api :as b] [clojure.string :as str])) (def class-dir "target/classes") (defn clean [_] (b/delete {:path "target"})) (defn jar [_] (clean nil) (let [lib 'com.github.jpmonettas/clograms version (format "0.1.%s" (b/git-count-revs nil)) basis (b/create-basis {:project "deps.edn" :aliases []}) jar-file (format "target/%s.jar" (name lib)) src-dirs ["src/clj" "src/clj-styles" "src/cljs"]] (b/write-pom {:class-dir class-dir :lib lib :version version :basis basis :src-dirs src-dirs}) (b/copy-dir {:src-dirs (into src-dirs ["resources"]) :target-dir class-dir}) (b/jar {:class-dir class-dir :jar-file jar-file})))
null
https://raw.githubusercontent.com/jpmonettas/clograms/79a09e35f294b8b52af15a91a26487c0a90ea005/build.clj
clojure
(ns build (:require [clojure.tools.build.api :as b] [clojure.string :as str])) (def class-dir "target/classes") (defn clean [_] (b/delete {:path "target"})) (defn jar [_] (clean nil) (let [lib 'com.github.jpmonettas/clograms version (format "0.1.%s" (b/git-count-revs nil)) basis (b/create-basis {:project "deps.edn" :aliases []}) jar-file (format "target/%s.jar" (name lib)) src-dirs ["src/clj" "src/clj-styles" "src/cljs"]] (b/write-pom {:class-dir class-dir :lib lib :version version :basis basis :src-dirs src-dirs}) (b/copy-dir {:src-dirs (into src-dirs ["resources"]) :target-dir class-dir}) (b/jar {:class-dir class-dir :jar-file jar-file})))
0751cb1be15d6a424f24189fd8a39bf1e200c99ede9d3c310ad65d5ecd6f10b1
vii/dysfunkycom
bitmap-font.lisp
(in-package :lispbuilder-sdl) (defclass bitmap-font (font) ((characters :reader characters :initform (make-hash-table :test 'equal))) (:default-initargs :font-definition *font-8x8*)) (defmethod char-width ((self bitmap-font)) (char-width (font-definition self))) (defmethod char-height ((self bitmap-font)) (char-height (font-definition self))) (defmethod char-pitch ((self bitmap-font)) (char-pitch (font-definition self))) (defmethod char-size ((self bitmap-font)) (char-size (font-definition self))) (defmethod font-data ((self bitmap-font)) (data (font-definition self))) (defclass sdl-bitmap-font (bitmap-font) () (:documentation "The `SDL-BITMAP-FONT` object manages the resources for a bitmap font. Prior to the first call to a `RENDER-STRING*` function, the cached [SURFACE](#surface) is `NIL`. The cached surface is created by a call to any of the RENDER-STRING* functions. Use [DRAW-FONT](#draw-font), [DRAW-FONT-AT](#draw-font-at) or [DRAW-FONT-AT-*](#draw-font-at-*) to draw the cached surface. Free using [FREE](#free)")) (defmethod set-default-font ((font bitmap-font)) (setf *default-font* font) font) (defmethod initialise-font ((self bitmap-font-definition)) (make-instance 'sdl-bitmap-font :font-definition self)) (defun initialise-default-font (&optional (font-definition *font-8x8*)) "Returns a new [SDL-BITMAP-FONT](#sdl-bitmap-font) initialized from `FONT-DEFINITION` data, or `NIL` if the font cannot be created. `FONT-DEFINITION` is set to `\*font-8x8\*` if unspecified. Binds the symbol `\*DEFAULT-FONT\*` to the new font to be used as the default for subsequent font rendering or drawing operations. ##### Packages * Aslo supported in _LISPBUILDER-SDL-GFX_" (set-default-font (initialise-font font-definition))) (defstruct glyph surface fg-color bg-color) (defun glyph (char font) (gethash char (characters font))) (defun get-character (char fg-color bg-color &key (font *default-font*)) "Returns the [SURFACE](#surface) asociated with `CHAR`. Returns a new [SURFACE](#surface) if either of the foreground or background colors `FG-COLOR` or `BG-COLOR` are different than specified for the existing surface." (check-type char character) (check-type fg-color color) (if bg-color (check-type bg-color color)) (check-type font bitmap-font) (let ((redraw? nil) (glyph (glyph char font))) ;; Create a surface for the character, if one does not already exist. (unless glyph (let ((g (make-glyph :surface (create-surface (char-width font) (char-height font) :alpha 0 :pixel-alpha t :type :hw) :fg-color fg-color :bg-color bg-color))) (setf (gethash char (characters font)) g) (setf glyph g) (setf redraw? t))) Foreground color must match or font will be redrawn . (unless (color= (glyph-fg-color glyph) fg-color) (setf (glyph-fg-color glyph) fg-color) (setf redraw? t)) ;; If bg-color must match or font will be redrawn. (when (and bg-color (glyph-bg-color glyph)) (unless (color= (glyph-bg-color glyph) bg-color) (setf (glyph-bg-color glyph) bg-color) (setf redraw? t))) (when (or (and bg-color (not (glyph-bg-color glyph))) (and (not bg-color) (glyph-bg-color glyph))) (setf (glyph-bg-color glyph) bg-color) (setf redraw? t)) ;; Redraw the chracter if fg- or bg-color mismatch or ;; a surface was created. (when redraw? (let ((fg-col (map-color (glyph-fg-color glyph) (glyph-surface glyph))) (bg-col (if bg-color (map-color (glyph-bg-color glyph) (glyph-surface glyph)) 0))) (sdl-base::with-pixel (pix (fp (glyph-surface glyph))) (let ((char-pos (* (char-code char) (char-size font))) (patt 0) (mask #x00)) (dotimes (iy (char-height font)) (setf mask #x00) (dotimes (ix (char-width font)) (setf mask (ash mask -1)) (when (eq mask 0) (setf patt (aref (font-data font) char-pos) mask #x80) (incf char-pos)) (if (> (logand patt mask) 0) (sdl-base::write-pixel pix ix iy fg-col) (sdl-base::write-pixel pix ix iy bg-col)))))))) (glyph-surface glyph))) (defun draw-character (c p1 fg-color bg-color &key (font *default-font*) (surface *default-surface*)) "See [draw-character-shaded-*](#draw-character-shaded-*). ##### Parameters * `P1` is the `X` and `Y` coordinates to render the text onto `SURFACE`, of type POINT." (check-type p1 point) (draw-character-* c (x p1) (y p1) fg-color bg-color :font font :surface surface)) (defun draw-character-* (c x y fg-color bg-color &key (font *default-font*) (surface *default-surface*)) "Draw the character `C` at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. If `BG-COLOR` is `NIL`, then the glyph is rendered using the `SOLID` mode. If `BG-COLOR` is NOT `NIL`, then the glyph is rendered using the `SHADED` mode. ##### Parameters * `C` is the character to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE. ##### For example: \(DRAW-CHARACTER-SHADED-* \"Hello World!\" 0 0 F-COLOR B-COLOR :SURFACE A-SURFACE\)" (check-type c character) (check-type fg-color color) (if bg-color (check-type bg-color color)) (check-type font bitmap-font) (check-type surface sdl-surface) (draw-surface-at-* (get-character c fg-color bg-color :font font) x y :surface surface) surface) (defun draw-string-left-justify-* (str x y fg-color bg-color &key (surface *default-surface*) (font *default-font*)) "Draw the text in the string `STR` *starting* at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. ##### Parameters * `STR` is the text to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE." (loop for c across str do (draw-character-* c x y fg-color bg-color :font font :surface surface) (incf x (char-width font))) surface) (defun draw-string-right-justify-* (str x y fg-color bg-color &key (surface *default-surface*) (font *default-font*)) "Draw the text in the string `STR` *ending* at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. ##### Parameters * `STR` is the text to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE." (let ((right-x (- x (char-width font))) (rev-str (reverse str))) (loop for c across rev-str do (draw-character-* c right-x y fg-color bg-color :font font :surface surface) (decf right-x (char-width font)))) surface) (defun draw-string-centered-* (str x y fg-color bg-color &key (surface *default-surface*) (font *default-font*)) "Draw the text in the string `STR` *with midpoint centered* at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. ##### Parameters * `STR` is the text to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE." (let* ((width (* (length str) (char-width font))) (left-x (- x (/ width 2)))) (loop for c across str do (draw-character-* c left-x y fg-color bg-color :font font :surface surface) (incf left-x (char-width font)))) surface) (defmethod _get-Font-Size_ ((font bitmap-font) text size) (cond ((eq size :w) (* (length text) (char-width font))) ((eq size :h) (char-width font)) (t (error "ERROR in GET-FONT-SIZE: :SIZE must be one of :W or :H")))) (defmethod _get-Font-Height_ ((font bitmap-font)) (char-height font)) (defmethod _is-font-face-fixed-width_ ((font bitmap-font)) t) ;; (defun load-font (file-name font-width font-height &optional (path-name "")) ;; "Load and initialise a simple font using a bmp with a strip of fixed width characters mapped by the char-map-string" ;; (let ((font-surface (load-image bmp-file-name bmp-path-name :key-color key-color))) ;; (if font-surface ;; (make-instance 'font ;; :font-surface font-surface ;; :font-width font-width ;; :font-height font-height ;; :char-map (make-char-map char-map-string) ;; :key-color key-color) ( error " LOAD - FONT : can not be initialised . " ) ) ) ) ;; (defmacro with-open-font ((font-name char-width char-height key-color &optional (font-path "")) ;; &body body) ;; `(let ((*default-font* (load-font ,font-image-name ,font-path ;; ,char-width ,font-height ,char-map-string ,key-color))) ;; (if *default-font* ( progn ;; ,@body ;; (free-font *default-font*)))))
null
https://raw.githubusercontent.com/vii/dysfunkycom/a493fa72662b79e7c4e70361ad0ea3c7235b6166/addons/lispbuilder-sdl/sdl/bitmap-font.lisp
lisp
Create a surface for the character, if one does not already exist. If bg-color must match or font will be redrawn. Redraw the chracter if fg- or bg-color mismatch or a surface was created. (defun load-font (file-name font-width font-height &optional (path-name "")) "Load and initialise a simple font using a bmp with a strip of fixed width characters mapped by the char-map-string" (let ((font-surface (load-image bmp-file-name bmp-path-name :key-color key-color))) (if font-surface (make-instance 'font :font-surface font-surface :font-width font-width :font-height font-height :char-map (make-char-map char-map-string) :key-color key-color) (defmacro with-open-font ((font-name char-width char-height key-color &optional (font-path "")) &body body) `(let ((*default-font* (load-font ,font-image-name ,font-path ,char-width ,font-height ,char-map-string ,key-color))) (if *default-font* ,@body (free-font *default-font*)))))
(in-package :lispbuilder-sdl) (defclass bitmap-font (font) ((characters :reader characters :initform (make-hash-table :test 'equal))) (:default-initargs :font-definition *font-8x8*)) (defmethod char-width ((self bitmap-font)) (char-width (font-definition self))) (defmethod char-height ((self bitmap-font)) (char-height (font-definition self))) (defmethod char-pitch ((self bitmap-font)) (char-pitch (font-definition self))) (defmethod char-size ((self bitmap-font)) (char-size (font-definition self))) (defmethod font-data ((self bitmap-font)) (data (font-definition self))) (defclass sdl-bitmap-font (bitmap-font) () (:documentation "The `SDL-BITMAP-FONT` object manages the resources for a bitmap font. Prior to the first call to a `RENDER-STRING*` function, the cached [SURFACE](#surface) is `NIL`. The cached surface is created by a call to any of the RENDER-STRING* functions. Use [DRAW-FONT](#draw-font), [DRAW-FONT-AT](#draw-font-at) or [DRAW-FONT-AT-*](#draw-font-at-*) to draw the cached surface. Free using [FREE](#free)")) (defmethod set-default-font ((font bitmap-font)) (setf *default-font* font) font) (defmethod initialise-font ((self bitmap-font-definition)) (make-instance 'sdl-bitmap-font :font-definition self)) (defun initialise-default-font (&optional (font-definition *font-8x8*)) "Returns a new [SDL-BITMAP-FONT](#sdl-bitmap-font) initialized from `FONT-DEFINITION` data, or `NIL` if the font cannot be created. `FONT-DEFINITION` is set to `\*font-8x8\*` if unspecified. Binds the symbol `\*DEFAULT-FONT\*` to the new font to be used as the default for subsequent font rendering or drawing operations. ##### Packages * Aslo supported in _LISPBUILDER-SDL-GFX_" (set-default-font (initialise-font font-definition))) (defstruct glyph surface fg-color bg-color) (defun glyph (char font) (gethash char (characters font))) (defun get-character (char fg-color bg-color &key (font *default-font*)) "Returns the [SURFACE](#surface) asociated with `CHAR`. Returns a new [SURFACE](#surface) if either of the foreground or background colors `FG-COLOR` or `BG-COLOR` are different than specified for the existing surface." (check-type char character) (check-type fg-color color) (if bg-color (check-type bg-color color)) (check-type font bitmap-font) (let ((redraw? nil) (glyph (glyph char font))) (unless glyph (let ((g (make-glyph :surface (create-surface (char-width font) (char-height font) :alpha 0 :pixel-alpha t :type :hw) :fg-color fg-color :bg-color bg-color))) (setf (gethash char (characters font)) g) (setf glyph g) (setf redraw? t))) Foreground color must match or font will be redrawn . (unless (color= (glyph-fg-color glyph) fg-color) (setf (glyph-fg-color glyph) fg-color) (setf redraw? t)) (when (and bg-color (glyph-bg-color glyph)) (unless (color= (glyph-bg-color glyph) bg-color) (setf (glyph-bg-color glyph) bg-color) (setf redraw? t))) (when (or (and bg-color (not (glyph-bg-color glyph))) (and (not bg-color) (glyph-bg-color glyph))) (setf (glyph-bg-color glyph) bg-color) (setf redraw? t)) (when redraw? (let ((fg-col (map-color (glyph-fg-color glyph) (glyph-surface glyph))) (bg-col (if bg-color (map-color (glyph-bg-color glyph) (glyph-surface glyph)) 0))) (sdl-base::with-pixel (pix (fp (glyph-surface glyph))) (let ((char-pos (* (char-code char) (char-size font))) (patt 0) (mask #x00)) (dotimes (iy (char-height font)) (setf mask #x00) (dotimes (ix (char-width font)) (setf mask (ash mask -1)) (when (eq mask 0) (setf patt (aref (font-data font) char-pos) mask #x80) (incf char-pos)) (if (> (logand patt mask) 0) (sdl-base::write-pixel pix ix iy fg-col) (sdl-base::write-pixel pix ix iy bg-col)))))))) (glyph-surface glyph))) (defun draw-character (c p1 fg-color bg-color &key (font *default-font*) (surface *default-surface*)) "See [draw-character-shaded-*](#draw-character-shaded-*). ##### Parameters * `P1` is the `X` and `Y` coordinates to render the text onto `SURFACE`, of type POINT." (check-type p1 point) (draw-character-* c (x p1) (y p1) fg-color bg-color :font font :surface surface)) (defun draw-character-* (c x y fg-color bg-color &key (font *default-font*) (surface *default-surface*)) "Draw the character `C` at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. If `BG-COLOR` is `NIL`, then the glyph is rendered using the `SOLID` mode. If `BG-COLOR` is NOT `NIL`, then the glyph is rendered using the `SHADED` mode. ##### Parameters * `C` is the character to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE. ##### For example: \(DRAW-CHARACTER-SHADED-* \"Hello World!\" 0 0 F-COLOR B-COLOR :SURFACE A-SURFACE\)" (check-type c character) (check-type fg-color color) (if bg-color (check-type bg-color color)) (check-type font bitmap-font) (check-type surface sdl-surface) (draw-surface-at-* (get-character c fg-color bg-color :font font) x y :surface surface) surface) (defun draw-string-left-justify-* (str x y fg-color bg-color &key (surface *default-surface*) (font *default-font*)) "Draw the text in the string `STR` *starting* at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. ##### Parameters * `STR` is the text to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE." (loop for c across str do (draw-character-* c x y fg-color bg-color :font font :surface surface) (incf x (char-width font))) surface) (defun draw-string-right-justify-* (str x y fg-color bg-color &key (surface *default-surface*) (font *default-font*)) "Draw the text in the string `STR` *ending* at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. ##### Parameters * `STR` is the text to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE." (let ((right-x (- x (char-width font))) (rev-str (reverse str))) (loop for c across rev-str do (draw-character-* c right-x y fg-color bg-color :font font :surface surface) (decf right-x (char-width font)))) surface) (defun draw-string-centered-* (str x y fg-color bg-color &key (surface *default-surface*) (font *default-font*)) "Draw the text in the string `STR` *with midpoint centered* at location `X` and `Y` using font `FONT` with foreground and background colors `FG-COLOR` and `BG-COLOR` onto surface `SURFACE`. ##### Parameters * `STR` is the text to render. * `X` and `Y` are the X and Y position coordinates, as `INTEGERS`. * `FG-COLOR` is the foreground color used to render text, of type `COLOR` * `BG-COLOR` is the background color used to render text, of type `COLOR` * `FONT` is the bitmap font used to render the character. Bound to `\*DEFAULT-FONT\*` if unspecified. * `SURFACE` is the target surface, of type `SDL-SURFACE`. Bound to `\*DEFAULT-SURFACE\*` if unspecified. ##### Returns * Returns the surface SURFACE." (let* ((width (* (length str) (char-width font))) (left-x (- x (/ width 2)))) (loop for c across str do (draw-character-* c left-x y fg-color bg-color :font font :surface surface) (incf left-x (char-width font)))) surface) (defmethod _get-Font-Size_ ((font bitmap-font) text size) (cond ((eq size :w) (* (length text) (char-width font))) ((eq size :h) (char-width font)) (t (error "ERROR in GET-FONT-SIZE: :SIZE must be one of :W or :H")))) (defmethod _get-Font-Height_ ((font bitmap-font)) (char-height font)) (defmethod _is-font-face-fixed-width_ ((font bitmap-font)) t) ( error " LOAD - FONT : can not be initialised . " ) ) ) ) ( progn
6938a13224349ab2b59df11d25ca92154731238161e049951458ce194c16a375
replikativ/superv.async
dev_server.clj
(ns superv.dev-server (:require [ring.util.response :as resp]) (:gen-class)) (defn handle-index [handler] (fn [request] (if (= [:get "/"] ((juxt :request-method :uri) request)) (resp/response "<!DOCTYPE html> <html> <body> <script src=\"js/client.js\"></script> </body> </html>") (handler request)))) (def main-handler (-> {} handle-index))
null
https://raw.githubusercontent.com/replikativ/superv.async/f9f4f51c2b51ac2fd90dd5ad18a053722882390f/src/superv/dev_server.clj
clojure
(ns superv.dev-server (:require [ring.util.response :as resp]) (:gen-class)) (defn handle-index [handler] (fn [request] (if (= [:get "/"] ((juxt :request-method :uri) request)) (resp/response "<!DOCTYPE html> <html> <body> <script src=\"js/client.js\"></script> </body> </html>") (handler request)))) (def main-handler (-> {} handle-index))
87406bbcd36e354663f10f16f55175ecf00a1fd513d4dc63e7b9592785452ffb
plapadoo/matrix-bot
Http.hs
{-# LANGUAGE DeriveFunctor #-} # LANGUAGE FlexibleInstances # # LANGUAGE TemplateHaskell # module Plpd.Http ( HttpMethod(..) , HttpRequest(..) , HttpResponse(..) , loggingHttp , jsonHttpRequest , hrUrl , hrMethod , hrContentType , hrContent , hresStatusCode , hresContent , JsonParseError , jpeOriginal , jpeError ) where import Control.Applicative (pure) import Control.Lens (makeLenses, (&), (?~), (^.)) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Aeson (FromJSON (..), ToJSON (..), eitherDecode, encode) import Data.Bifunctor (first) import Data.ByteString.Lazy (ByteString) import Data.Either (Either) import Data.Function (($), (.)) import Data.Functor (Functor, (<$>)) import Data.Int (Int) import Data.Monoid ((<>)) import Data.String (String) import qualified Data.Text as Text import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Encoding (decodeUtf8) import Data.UUID (toText) import Network.Wreq (checkResponse, defaults, postWith, putWith, responseBody, responseStatus, statusCode) import Network.Wreq.Types (ResponseChecker) import Plpd.MonadLog (LogMode (LogStdout), defaultLog) import Plpd.Util (textShow) import System.IO (IO) import System.Random (randomIO) import Text.Show (Show, show) -- HTTP API abstraction data HttpMethod = HttpMethodPost | HttpMethodPut instance Show HttpMethod where show HttpMethodPost = "POST" show HttpMethodPut = "PUT" data HttpRequest a = HttpRequest { _hrUrl :: Text.Text , _hrMethod :: HttpMethod , _hrContentType :: Text.Text , _hrContent :: a } deriving (Functor) makeLenses ''HttpRequest data HttpResponse a = HttpResponse { _hresStatusCode :: Int , _hresContent :: a } deriving (Functor) trivialStatusChecker :: ResponseChecker trivialStatusChecker _ _ = pure () makeLenses ''HttpResponse -- eitherDecode returns an error, but keeping the original reply is even better. data JsonParseError = JsonParseError { _jpeOriginal :: ByteString , _jpeError :: String } makeLenses ''JsonParseError eitherDecodeKeep :: FromJSON a => ByteString -> Either JsonParseError a eitherDecodeKeep original = first (JsonParseError original) (eitherDecode original) jsonHttpRequest :: (ToJSON input, FromJSON output, MonadIO m) => HttpRequest input -> m (HttpResponse (Either JsonParseError output)) jsonHttpRequest request = (eitherDecodeKeep <$>) <$> httpRequest (encode <$> request) loggingHttp :: HttpRequest ByteString -> IO (HttpResponse ByteString) loggingHttp request = do uuid <- toText <$> randomIO defaultLog LogStdout $ uuid <> ": HTTP " <> textShow (request ^. hrMethod) <> " request to " <> (request ^. hrUrl) <> ", content type " <> (request ^. hrContentType) <> ", content: " <> (toStrict . decodeUtf8) (request ^. hrContent) response <- (httpRequest request) defaultLog LogStdout $ uuid <> ": response code " <> textShow (response ^. hresStatusCode) <> ", content: " <> (toStrict . decodeUtf8) (response ^. hresContent) pure response httpRequest :: MonadIO m => HttpRequest ByteString -> m (HttpResponse ByteString) httpRequest request = do let opts = defaults & checkResponse ?~ trivialStatusChecker let method = case request ^. hrMethod of HttpMethodPost -> postWith HttpMethodPut -> putWith response <- liftIO $ method opts (Text.unpack (request ^. hrUrl)) (request ^. hrContent) let responseCode = response ^. responseStatus . statusCode pure (HttpResponse responseCode (response ^. responseBody))
null
https://raw.githubusercontent.com/plapadoo/matrix-bot/01ea062116200d407632b93743ef0dbc11a63715/src/Plpd/Http.hs
haskell
# LANGUAGE DeriveFunctor # HTTP API abstraction eitherDecode returns an error, but keeping the original reply is even better.
# LANGUAGE FlexibleInstances # # LANGUAGE TemplateHaskell # module Plpd.Http ( HttpMethod(..) , HttpRequest(..) , HttpResponse(..) , loggingHttp , jsonHttpRequest , hrUrl , hrMethod , hrContentType , hrContent , hresStatusCode , hresContent , JsonParseError , jpeOriginal , jpeError ) where import Control.Applicative (pure) import Control.Lens (makeLenses, (&), (?~), (^.)) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Aeson (FromJSON (..), ToJSON (..), eitherDecode, encode) import Data.Bifunctor (first) import Data.ByteString.Lazy (ByteString) import Data.Either (Either) import Data.Function (($), (.)) import Data.Functor (Functor, (<$>)) import Data.Int (Int) import Data.Monoid ((<>)) import Data.String (String) import qualified Data.Text as Text import Data.Text.Lazy (toStrict) import Data.Text.Lazy.Encoding (decodeUtf8) import Data.UUID (toText) import Network.Wreq (checkResponse, defaults, postWith, putWith, responseBody, responseStatus, statusCode) import Network.Wreq.Types (ResponseChecker) import Plpd.MonadLog (LogMode (LogStdout), defaultLog) import Plpd.Util (textShow) import System.IO (IO) import System.Random (randomIO) import Text.Show (Show, show) data HttpMethod = HttpMethodPost | HttpMethodPut instance Show HttpMethod where show HttpMethodPost = "POST" show HttpMethodPut = "PUT" data HttpRequest a = HttpRequest { _hrUrl :: Text.Text , _hrMethod :: HttpMethod , _hrContentType :: Text.Text , _hrContent :: a } deriving (Functor) makeLenses ''HttpRequest data HttpResponse a = HttpResponse { _hresStatusCode :: Int , _hresContent :: a } deriving (Functor) trivialStatusChecker :: ResponseChecker trivialStatusChecker _ _ = pure () makeLenses ''HttpResponse data JsonParseError = JsonParseError { _jpeOriginal :: ByteString , _jpeError :: String } makeLenses ''JsonParseError eitherDecodeKeep :: FromJSON a => ByteString -> Either JsonParseError a eitherDecodeKeep original = first (JsonParseError original) (eitherDecode original) jsonHttpRequest :: (ToJSON input, FromJSON output, MonadIO m) => HttpRequest input -> m (HttpResponse (Either JsonParseError output)) jsonHttpRequest request = (eitherDecodeKeep <$>) <$> httpRequest (encode <$> request) loggingHttp :: HttpRequest ByteString -> IO (HttpResponse ByteString) loggingHttp request = do uuid <- toText <$> randomIO defaultLog LogStdout $ uuid <> ": HTTP " <> textShow (request ^. hrMethod) <> " request to " <> (request ^. hrUrl) <> ", content type " <> (request ^. hrContentType) <> ", content: " <> (toStrict . decodeUtf8) (request ^. hrContent) response <- (httpRequest request) defaultLog LogStdout $ uuid <> ": response code " <> textShow (response ^. hresStatusCode) <> ", content: " <> (toStrict . decodeUtf8) (response ^. hresContent) pure response httpRequest :: MonadIO m => HttpRequest ByteString -> m (HttpResponse ByteString) httpRequest request = do let opts = defaults & checkResponse ?~ trivialStatusChecker let method = case request ^. hrMethod of HttpMethodPost -> postWith HttpMethodPut -> putWith response <- liftIO $ method opts (Text.unpack (request ^. hrUrl)) (request ^. hrContent) let responseCode = response ^. responseStatus . statusCode pure (HttpResponse responseCode (response ^. responseBody))
07d48fae914a1ced0fa0704d3f51ef6165a8e5f1ad5a9e93b9de9aed95f75812
jakubfijalkowski/hlibsass
Main.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE CPP # import Bindings.Libsass import Foreign import Foreign.C import Test.Hspec simpleCompile :: String -> IO String simpleCompile str = do cstr <- newCString str ctx <- sass_make_data_context cstr status <- sass_compile_data_context ctx if status /= 0 then do sass_delete_data_context ctx return "" else do cres <- sass_context_get_output_string (castPtr ctx) !res <- peekCString cres sass_delete_data_context ctx return res sampleInput :: String sampleInput = "foo { margin: 21px * 2; }" sampleOutput :: String sampleOutput = "foo {\n margin: 42px; }\n" main :: IO () main = hspec $ describe "Libsass" $ do it "should correctly compile simple expression" $ simpleCompile sampleInput `shouldReturn` sampleOutput #ifndef EXTERNAL_LIBSASS it "should report correct version" $ do str <- peekCString libsass_version str `shouldBe` "3.6.4" #endif it "should support quoted strings" $ withCString "sample" $ \cstr -> do str <- sass_make_qstring cstr sass_string_is_quoted str `shouldReturn` True it "should correctly combine two SassValues" $ withCString "" $ \unit -> do val1 <- sass_make_number 1.0 unit val2 <- sass_make_number 2.0 unit val3 <- sass_value_op (fromIntegral $ fromEnum SassAdd) val1 val2 result <- sass_number_get_value val3 sass_delete_value val1 sass_delete_value val2 sass_delete_value val3 result `shouldBe` 3.0
null
https://raw.githubusercontent.com/jakubfijalkowski/hlibsass/aac28a320f4b7435dbb91af11413762679631f0f/tests/Main.hs
haskell
# LANGUAGE BangPatterns #
# LANGUAGE CPP # import Bindings.Libsass import Foreign import Foreign.C import Test.Hspec simpleCompile :: String -> IO String simpleCompile str = do cstr <- newCString str ctx <- sass_make_data_context cstr status <- sass_compile_data_context ctx if status /= 0 then do sass_delete_data_context ctx return "" else do cres <- sass_context_get_output_string (castPtr ctx) !res <- peekCString cres sass_delete_data_context ctx return res sampleInput :: String sampleInput = "foo { margin: 21px * 2; }" sampleOutput :: String sampleOutput = "foo {\n margin: 42px; }\n" main :: IO () main = hspec $ describe "Libsass" $ do it "should correctly compile simple expression" $ simpleCompile sampleInput `shouldReturn` sampleOutput #ifndef EXTERNAL_LIBSASS it "should report correct version" $ do str <- peekCString libsass_version str `shouldBe` "3.6.4" #endif it "should support quoted strings" $ withCString "sample" $ \cstr -> do str <- sass_make_qstring cstr sass_string_is_quoted str `shouldReturn` True it "should correctly combine two SassValues" $ withCString "" $ \unit -> do val1 <- sass_make_number 1.0 unit val2 <- sass_make_number 2.0 unit val3 <- sass_value_op (fromIntegral $ fromEnum SassAdd) val1 val2 result <- sass_number_get_value val3 sass_delete_value val1 sass_delete_value val2 sass_delete_value val3 result `shouldBe` 3.0
4ea2a2ed7fa1328d43b408503bc1a9ed53009f68d2fe36fe7fabbc0f34e1a5cd
moby/vpnkit
connect.ml
let src = let src = Logs.Src.create "port forward" ~doc:"forward local ports to the VM" in Logs.Src.set_level src (Some Logs.Info); src module Log = (val Logs.src_log src : Logs.LOG) open Lwt.Infix let ( >>*= ) m f = m >>= function | Error (`Msg m) -> Lwt.fail_with m | Ok x -> f x let (/) = Filename.concat let home = try Sys.getenv "HOME" with Not_found -> "/Users/root" let vsock_port = 62373l module Unix = struct let vsock_path = ref (home / "Library/Containers/com.docker.docker/Data/@connect") include Host.Sockets.Stream.Unix let connect () = connect (!vsock_path) >>*= fun flow -> let address = Cstruct.of_string (Printf.sprintf "00000003.%08lx\n" vsock_port) in write flow address >>= function | Ok () -> Lwt.return flow | Error `Closed -> Log.err (fun f -> f "vsock connect write got Eof"); close flow >>= fun () -> Lwt.fail End_of_file | Error e -> Log.err (fun f -> f "vsock connect write got %a" pp_write_error e); close flow >>= fun () -> Fmt.kstr Lwt.fail_with "%a" pp_write_error e end module Hvsock = struct (* Avoid using `detach` because we don't want to exhaust the thread pool since this will block the main TCP/IP stack. *) module F = Hvsock_lwt.Flow_shutdown.Make(Host.Time) (Hvsock_lwt.In_main_thread.Make(Host.Main)) (Hvsock.Af_hyperv) type flow = { idx: int; flow: F.flow; } type address = unit let hvsockaddr = ref None let set_port_forward_addr x = hvsockaddr := Some x let close flow = Connection_limit.deregister flow.idx; F.close flow.flow let connect () = match !hvsockaddr with | None -> Log.err (fun f -> f "Please set a Hyper-V socket address for port forwarding"); failwith "Hyper-V socket forwarding not initialised" | Some sockaddr -> let description = "hvsock" in (Lwt.return @@ Connection_limit.register description) >>*= fun idx -> let fd = F.Socket.create () in F.Socket.connect fd sockaddr >|= fun () -> let flow = F.connect fd in { idx; flow } let read_into t = F.read_into t.flow let read t = F.read t.flow let write t = F.write t.flow let writev t = F.writev t.flow let shutdown_read t = F.shutdown_read t.flow let shutdown_write t = F.shutdown_write t.flow let pp_error = F.pp_error let pp_write_error = F.pp_write_error type error = F.error type write_error = F.write_error end
null
https://raw.githubusercontent.com/moby/vpnkit/6039eac025e0740e530f2ff11f57d6d990d1c4a1/src/bin/connect.ml
ocaml
Avoid using `detach` because we don't want to exhaust the thread pool since this will block the main TCP/IP stack.
let src = let src = Logs.Src.create "port forward" ~doc:"forward local ports to the VM" in Logs.Src.set_level src (Some Logs.Info); src module Log = (val Logs.src_log src : Logs.LOG) open Lwt.Infix let ( >>*= ) m f = m >>= function | Error (`Msg m) -> Lwt.fail_with m | Ok x -> f x let (/) = Filename.concat let home = try Sys.getenv "HOME" with Not_found -> "/Users/root" let vsock_port = 62373l module Unix = struct let vsock_path = ref (home / "Library/Containers/com.docker.docker/Data/@connect") include Host.Sockets.Stream.Unix let connect () = connect (!vsock_path) >>*= fun flow -> let address = Cstruct.of_string (Printf.sprintf "00000003.%08lx\n" vsock_port) in write flow address >>= function | Ok () -> Lwt.return flow | Error `Closed -> Log.err (fun f -> f "vsock connect write got Eof"); close flow >>= fun () -> Lwt.fail End_of_file | Error e -> Log.err (fun f -> f "vsock connect write got %a" pp_write_error e); close flow >>= fun () -> Fmt.kstr Lwt.fail_with "%a" pp_write_error e end module Hvsock = struct module F = Hvsock_lwt.Flow_shutdown.Make(Host.Time) (Hvsock_lwt.In_main_thread.Make(Host.Main)) (Hvsock.Af_hyperv) type flow = { idx: int; flow: F.flow; } type address = unit let hvsockaddr = ref None let set_port_forward_addr x = hvsockaddr := Some x let close flow = Connection_limit.deregister flow.idx; F.close flow.flow let connect () = match !hvsockaddr with | None -> Log.err (fun f -> f "Please set a Hyper-V socket address for port forwarding"); failwith "Hyper-V socket forwarding not initialised" | Some sockaddr -> let description = "hvsock" in (Lwt.return @@ Connection_limit.register description) >>*= fun idx -> let fd = F.Socket.create () in F.Socket.connect fd sockaddr >|= fun () -> let flow = F.connect fd in { idx; flow } let read_into t = F.read_into t.flow let read t = F.read t.flow let write t = F.write t.flow let writev t = F.writev t.flow let shutdown_read t = F.shutdown_read t.flow let shutdown_write t = F.shutdown_write t.flow let pp_error = F.pp_error let pp_write_error = F.pp_write_error type error = F.error type write_error = F.write_error end
0fae61229c9b385beb752bbcccf4ca8a3247bb28e6950fa6204d9fdb1f70be97
ddmcdonald/sparser
note on multi-pass sentence control structure.lisp
SEE note on bio control structure.lisp
null
https://raw.githubusercontent.com/ddmcdonald/sparser/304bd02d0cf7337ca25c8f1d44b1d7912759460f/Sparser/documentation/notes/note%20on%20multi-pass%20sentence%20control%20structure.lisp
lisp
SEE note on bio control structure.lisp
021a89f23429c97f04baa47845a525e23e3ab4534beba8daaceb4642cbb06c9b
batterseapower/openshake
Shakefile.hs
import Development.Shake import Development.Shake.System import System.FilePath main :: IO () main = shake $ do ("subdirectory" </> "foo") *> \x -> do system' $ ["touch",x] want ["subdirectory/foo"]
null
https://raw.githubusercontent.com/batterseapower/openshake/4d590c6c4191d5970f2d88f45d9425421d4f64af/tests/creates-directory-implicitly/Shakefile.hs
haskell
import Development.Shake import Development.Shake.System import System.FilePath main :: IO () main = shake $ do ("subdirectory" </> "foo") *> \x -> do system' $ ["touch",x] want ["subdirectory/foo"]