_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
7e9a788d91526b045d0699a523c408787c71b794df1acfaf18d48f0d842c4d26
sky-big/RabbitMQ
rabbit_mgmt_wm_node.erl
The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in %% compliance with the License. You may obtain a copy of the License at %% / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the %% License for the specific language governing rights and limitations %% under the License. %% The Original Code is RabbitMQ Management Console . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2010 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_mgmt_wm_node). -export([init/1, to_json/2, content_types_provided/2, is_authorized/2]). -export([resource_exists/2]). -include("rabbit_mgmt.hrl"). -include("webmachine.hrl"). -include("rabbit.hrl"). %%-------------------------------------------------------------------- init(_Config) -> {ok, #context{}}. content_types_provided(ReqData, Context) -> {[{"application/json", to_json}], ReqData, Context}. resource_exists(ReqData, Context) -> {case node0(ReqData) of not_found -> false; _ -> true end, ReqData, Context}. to_json(ReqData, Context) -> rabbit_mgmt_util:reply(node0(ReqData), ReqData, Context). is_authorized(ReqData, Context) -> rabbit_mgmt_util:is_authorized_monitor(ReqData, Context). %%-------------------------------------------------------------------- node0(ReqData) -> Node = list_to_atom(binary_to_list(rabbit_mgmt_util:id(node, ReqData))), case [N || N <- rabbit_mgmt_wm_nodes:all_nodes(ReqData), proplists:get_value(name, N) == Node] of [] -> not_found; [Data] -> augment(ReqData, Node, Data) end. augment(ReqData, Node, Data) -> lists:foldl(fun (Key, DataN) -> augment(Key, ReqData, Node, DataN) end, Data, [memory, binary]). augment(Key, ReqData, Node, Data) -> case wrq:get_qs_value(atom_to_list(Key), ReqData) of "true" -> Res = case rpc:call(Node, rabbit_vm, Key, [], infinity) of {badrpc, _} -> not_available; Result -> Result end, [{Key, Res} | Data]; _ -> Data end.
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-management/src/rabbit_mgmt_wm_node.erl
erlang
compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. -------------------------------------------------------------------- --------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Version 1.1 ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ Management Console . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2010 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_mgmt_wm_node). -export([init/1, to_json/2, content_types_provided/2, is_authorized/2]). -export([resource_exists/2]). -include("rabbit_mgmt.hrl"). -include("webmachine.hrl"). -include("rabbit.hrl"). init(_Config) -> {ok, #context{}}. content_types_provided(ReqData, Context) -> {[{"application/json", to_json}], ReqData, Context}. resource_exists(ReqData, Context) -> {case node0(ReqData) of not_found -> false; _ -> true end, ReqData, Context}. to_json(ReqData, Context) -> rabbit_mgmt_util:reply(node0(ReqData), ReqData, Context). is_authorized(ReqData, Context) -> rabbit_mgmt_util:is_authorized_monitor(ReqData, Context). node0(ReqData) -> Node = list_to_atom(binary_to_list(rabbit_mgmt_util:id(node, ReqData))), case [N || N <- rabbit_mgmt_wm_nodes:all_nodes(ReqData), proplists:get_value(name, N) == Node] of [] -> not_found; [Data] -> augment(ReqData, Node, Data) end. augment(ReqData, Node, Data) -> lists:foldl(fun (Key, DataN) -> augment(Key, ReqData, Node, DataN) end, Data, [memory, binary]). augment(Key, ReqData, Node, Data) -> case wrq:get_qs_value(atom_to_list(Key), ReqData) of "true" -> Res = case rpc:call(Node, rabbit_vm, Key, [], infinity) of {badrpc, _} -> not_available; Result -> Result end, [{Key, Res} | Data]; _ -> Data end.
782022cfb93d42e891a1d287484f025e42477a932594117403da54852ac1022c
jqueiroz/lojban.io
Main.hs
{-# LANGUAGE OverloadedStrings #-} module Server.Website.Main ( handleRoot ) where import Core import Serializer (personalizedExerciseToJSON, validateExerciseAnswer) import qualified Study.Courses.English.Grammar.Introduction.Course import qualified Study.Courses.English.Grammar.Crash.Course import qualified Study.Courses.English.Vocabulary.Attitudinals.Course import qualified Study.Courses.English.Vocabulary.Brivla.Course import qualified Study.Decks.English.ContextualizedBrivla import qualified Study.Decks.Eberban.English.Roots import Server.Core import Server.Util (forceSlash, getBody) import Server.Authentication.Utils (retrieveRequestHeaderRefererIfAllowed) import Server.Website.Views.Core import Server.Website.Views.Home (displayHome) import Server.Website.Views.Courses (displayCoursesHome) import Server.Website.Views.Decks (displayDecksHome) import Server.Website.Views.Deck (displayDeckHome, displayDeckExercise) import Server.Website.Views.Resources (displayResourcesHome) import Server.Website.Views.Login (displayLoginHome) import Server.Website.Views.Offline (displayOfflineHome) import Server.Website.Views.NotFound (displayNotFoundHome) import Server.Website.Views.Course (displayCourseHome) import Server.Website.Views.Lesson (displayLessonHome, displayLessonExercise) import Control.Monad (msum, guard) import Control.Monad.IO.Class (liftIO) import System.Random (newStdGen, mkStdGen) import Data.ByteString.Builder (toLazyByteString) import qualified Server.Authentication.Main as Authentication import qualified Data.Aeson as A import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.ByteString.Lazy as BS import qualified Network.HTTP.Types.URI as URI import qualified Data.UUID.V4 as UUIDv4 import Happstack.Server -- TODO: consider adding breadcrumbs (/) -- * Handlers handleRoot :: ServerConfiguration -> ServerResources -> ServerPart Response handleRoot serverConfiguration serverResources = do userIdentityMaybe <- Authentication.readUserIdentityFromCookies serverConfiguration serverResources msum [ forceSlash $ handleHome serverConfiguration userIdentityMaybe , dir "courses" $ handleCourses serverConfiguration userIdentityMaybe , dir "decks" $ handleDecks serverConfiguration serverResources userIdentityMaybe , dir "resources" $ handleResources serverConfiguration userIdentityMaybe , dir "login" $ handleLogin serverConfiguration userIdentityMaybe , dir "offline" $ handleOffline serverConfiguration userIdentityMaybe , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleHome :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleHome serverConfiguration userIdentityMaybe = ok . toResponse $ displayHome serverConfiguration userIdentityMaybe handleCourses :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleCourses serverConfiguration userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayCoursesHome serverConfiguration userIdentityMaybe , dir "introduction" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Grammar.Introduction.Course.course , dir "crash" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Grammar.Crash.Course.course , dir "attitudinals" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Vocabulary.Attitudinals.Course.course , dir "brivla" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Vocabulary.Brivla.Course.course , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleDecks :: ServerConfiguration -> ServerResources -> Maybe UserIdentity -> ServerPart Response handleDecks serverConfiguration serverResources userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayDecksHome serverConfiguration userIdentityMaybe , dir "contextualized-brivla" $ handleDeck serverConfiguration serverResources userIdentityMaybe Study.Decks.English.ContextualizedBrivla.deck , dir "eberban-roots" $ handleDeck serverConfiguration serverResources userIdentityMaybe Study.Decks.Eberban.English.Roots.deck , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleResources :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleResources serverConfiguration userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayResourcesHome serverConfiguration userIdentityMaybe , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleLogin :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleLogin serverConfiguration userIdentityMaybe = msum [ handleLogin' , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] where handleLogin' = forceSlash $ case userIdentityMaybe of Nothing -> do TODO : from cookie OR request header ( if there is an error , and /authentication/(register|login ) redirects back to /login ) uuid <- liftIO $ UUIDv4.nextRandom ok . toResponse $ displayLoginHome serverConfiguration userIdentityMaybe refererMaybe uuid _ -> tempRedirect ("/" :: T.Text) . toResponse $ ("You are already signed in." :: T.Text) handleOffline :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleOffline serverConfiguration userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayOfflineHome serverConfiguration userIdentityMaybe , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleNotFound :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleNotFound serverConfiguration userIdentityMaybe = msum [ forceSlash . notFound . toResponse $ displayNotFoundHome serverConfiguration userIdentityMaybe ] handleCourse :: ServerConfiguration -> Maybe UserIdentity -> TopbarCategory -> Course -> ServerPart Response handleCourse serverConfiguration userIdentityMaybe topbarCategory course = let lessons = courseLessons course in msum [ forceSlash . ok . toResponse . displayCourseHome serverConfiguration userIdentityMaybe topbarCategory $ course , path $ \n -> (guard $ 1 <= n && n <= (length lessons)) >> (handleLesson serverConfiguration userIdentityMaybe topbarCategory course n) , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleDeck :: ServerConfiguration -> ServerResources -> Maybe UserIdentity -> Deck -> ServerPart Response handleDeck serverConfiguration serverResources userIdentityMaybe deck = msum [ forceSlash . ok . toResponse $ displayDeckHome serverConfiguration userIdentityMaybe deck , dir "exercises" $ do identityMaybe <- Authentication.readUserIdentityFromCookies serverConfiguration serverResources case identityMaybe of Nothing -> do ( " ./ " : : T.Text ) . toResponse $ ( " You must be signed in . " : : T.Text ) ok . toResponse $ includeInlineScript ("alert('To practice with decks, you need to sign in.'); window.location.href='./';" :: T.Text) Just identity -> ok . toResponse $ displayDeckExercise serverConfiguration userIdentityMaybe deck , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleLesson :: ServerConfiguration -> Maybe UserIdentity -> TopbarCategory -> Course -> Int -> ServerPart Response handleLesson serverConfiguration userIdentityMaybe topbarCategory course lessonNumber = msum [ forceSlash . ok . toResponse $ displayLessonHome serverConfiguration userIdentityMaybe topbarCategory course lessonNumber , dir "report" $ handleLessonReport course lessonNumber , dir "exercises" $ msum [ forceSlash . ok . toResponse $ displayLessonExercise serverConfiguration userIdentityMaybe topbarCategory course lessonNumber , path $ \n -> let lesson = (courseLessons course) !! (lessonNumber - 1) exercise = lessonExercises lesson (mkStdGen n) shouldDisplayHint = False personalizedExercise = PersonalizedExercise exercise shouldDisplayHint in msum [ dir "get" $ (liftIO $ newStdGen) >>= ok . toResponse . A.encode . personalizedExerciseToJSON personalizedExercise , dir "submit" $ getBody >>= \body -> ok . toResponse . A.encode . A.object $ case validateExerciseAnswer exercise body of Nothing -> [("success", A.Bool False)] Just data' -> [("success", A.Bool True), ("data", data')] ] ] , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleLessonReport :: Course -> Int -> ServerPart Response handleLessonReport course lessonNumber = The only reason for using ` tempRedirect ` is that we may want to change the target url in the future forceSlash . tempRedirect url . toResponse $ ("To report an issue, please visit our GitHub repository." :: T.Text) where lesson :: Lesson lesson = (courseLessons course) !! (lessonNumber - 1) url :: T.Text url = "" `T.append` queryString queryString :: T.Text queryString = TE.decodeUtf8 . BS.toStrict . toLazyByteString $ URI.renderQueryText True [ ("labels", Just "reported-lesson") , ("title", Just $ "Feedback regarding lesson: " `T.append` (lessonTitle lesson)) , ("body", Just $ "Please provide your feedback here...\n\n### Context\nFor context, this feedback refers to the lesson \"" `T.append` (lessonTitle lesson) `T.append` "\" in the course \"" `T.append` (courseTitle course) `T.append` "\".") ]
null
https://raw.githubusercontent.com/jqueiroz/lojban.io/68c3e919f92ea1294f32ee7772662ab5667ecef6/haskell/src/Server/Website/Main.hs
haskell
# LANGUAGE OverloadedStrings # TODO: consider adding breadcrumbs (/) * Handlers
module Server.Website.Main ( handleRoot ) where import Core import Serializer (personalizedExerciseToJSON, validateExerciseAnswer) import qualified Study.Courses.English.Grammar.Introduction.Course import qualified Study.Courses.English.Grammar.Crash.Course import qualified Study.Courses.English.Vocabulary.Attitudinals.Course import qualified Study.Courses.English.Vocabulary.Brivla.Course import qualified Study.Decks.English.ContextualizedBrivla import qualified Study.Decks.Eberban.English.Roots import Server.Core import Server.Util (forceSlash, getBody) import Server.Authentication.Utils (retrieveRequestHeaderRefererIfAllowed) import Server.Website.Views.Core import Server.Website.Views.Home (displayHome) import Server.Website.Views.Courses (displayCoursesHome) import Server.Website.Views.Decks (displayDecksHome) import Server.Website.Views.Deck (displayDeckHome, displayDeckExercise) import Server.Website.Views.Resources (displayResourcesHome) import Server.Website.Views.Login (displayLoginHome) import Server.Website.Views.Offline (displayOfflineHome) import Server.Website.Views.NotFound (displayNotFoundHome) import Server.Website.Views.Course (displayCourseHome) import Server.Website.Views.Lesson (displayLessonHome, displayLessonExercise) import Control.Monad (msum, guard) import Control.Monad.IO.Class (liftIO) import System.Random (newStdGen, mkStdGen) import Data.ByteString.Builder (toLazyByteString) import qualified Server.Authentication.Main as Authentication import qualified Data.Aeson as A import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.ByteString.Lazy as BS import qualified Network.HTTP.Types.URI as URI import qualified Data.UUID.V4 as UUIDv4 import Happstack.Server handleRoot :: ServerConfiguration -> ServerResources -> ServerPart Response handleRoot serverConfiguration serverResources = do userIdentityMaybe <- Authentication.readUserIdentityFromCookies serverConfiguration serverResources msum [ forceSlash $ handleHome serverConfiguration userIdentityMaybe , dir "courses" $ handleCourses serverConfiguration userIdentityMaybe , dir "decks" $ handleDecks serverConfiguration serverResources userIdentityMaybe , dir "resources" $ handleResources serverConfiguration userIdentityMaybe , dir "login" $ handleLogin serverConfiguration userIdentityMaybe , dir "offline" $ handleOffline serverConfiguration userIdentityMaybe , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleHome :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleHome serverConfiguration userIdentityMaybe = ok . toResponse $ displayHome serverConfiguration userIdentityMaybe handleCourses :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleCourses serverConfiguration userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayCoursesHome serverConfiguration userIdentityMaybe , dir "introduction" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Grammar.Introduction.Course.course , dir "crash" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Grammar.Crash.Course.course , dir "attitudinals" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Vocabulary.Attitudinals.Course.course , dir "brivla" $ handleCourse serverConfiguration userIdentityMaybe TopbarCourses Study.Courses.English.Vocabulary.Brivla.Course.course , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleDecks :: ServerConfiguration -> ServerResources -> Maybe UserIdentity -> ServerPart Response handleDecks serverConfiguration serverResources userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayDecksHome serverConfiguration userIdentityMaybe , dir "contextualized-brivla" $ handleDeck serverConfiguration serverResources userIdentityMaybe Study.Decks.English.ContextualizedBrivla.deck , dir "eberban-roots" $ handleDeck serverConfiguration serverResources userIdentityMaybe Study.Decks.Eberban.English.Roots.deck , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleResources :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleResources serverConfiguration userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayResourcesHome serverConfiguration userIdentityMaybe , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleLogin :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleLogin serverConfiguration userIdentityMaybe = msum [ handleLogin' , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] where handleLogin' = forceSlash $ case userIdentityMaybe of Nothing -> do TODO : from cookie OR request header ( if there is an error , and /authentication/(register|login ) redirects back to /login ) uuid <- liftIO $ UUIDv4.nextRandom ok . toResponse $ displayLoginHome serverConfiguration userIdentityMaybe refererMaybe uuid _ -> tempRedirect ("/" :: T.Text) . toResponse $ ("You are already signed in." :: T.Text) handleOffline :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleOffline serverConfiguration userIdentityMaybe = msum [ forceSlash . ok . toResponse $ displayOfflineHome serverConfiguration userIdentityMaybe , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleNotFound :: ServerConfiguration -> Maybe UserIdentity -> ServerPart Response handleNotFound serverConfiguration userIdentityMaybe = msum [ forceSlash . notFound . toResponse $ displayNotFoundHome serverConfiguration userIdentityMaybe ] handleCourse :: ServerConfiguration -> Maybe UserIdentity -> TopbarCategory -> Course -> ServerPart Response handleCourse serverConfiguration userIdentityMaybe topbarCategory course = let lessons = courseLessons course in msum [ forceSlash . ok . toResponse . displayCourseHome serverConfiguration userIdentityMaybe topbarCategory $ course , path $ \n -> (guard $ 1 <= n && n <= (length lessons)) >> (handleLesson serverConfiguration userIdentityMaybe topbarCategory course n) , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleDeck :: ServerConfiguration -> ServerResources -> Maybe UserIdentity -> Deck -> ServerPart Response handleDeck serverConfiguration serverResources userIdentityMaybe deck = msum [ forceSlash . ok . toResponse $ displayDeckHome serverConfiguration userIdentityMaybe deck , dir "exercises" $ do identityMaybe <- Authentication.readUserIdentityFromCookies serverConfiguration serverResources case identityMaybe of Nothing -> do ( " ./ " : : T.Text ) . toResponse $ ( " You must be signed in . " : : T.Text ) ok . toResponse $ includeInlineScript ("alert('To practice with decks, you need to sign in.'); window.location.href='./';" :: T.Text) Just identity -> ok . toResponse $ displayDeckExercise serverConfiguration userIdentityMaybe deck , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleLesson :: ServerConfiguration -> Maybe UserIdentity -> TopbarCategory -> Course -> Int -> ServerPart Response handleLesson serverConfiguration userIdentityMaybe topbarCategory course lessonNumber = msum [ forceSlash . ok . toResponse $ displayLessonHome serverConfiguration userIdentityMaybe topbarCategory course lessonNumber , dir "report" $ handleLessonReport course lessonNumber , dir "exercises" $ msum [ forceSlash . ok . toResponse $ displayLessonExercise serverConfiguration userIdentityMaybe topbarCategory course lessonNumber , path $ \n -> let lesson = (courseLessons course) !! (lessonNumber - 1) exercise = lessonExercises lesson (mkStdGen n) shouldDisplayHint = False personalizedExercise = PersonalizedExercise exercise shouldDisplayHint in msum [ dir "get" $ (liftIO $ newStdGen) >>= ok . toResponse . A.encode . personalizedExerciseToJSON personalizedExercise , dir "submit" $ getBody >>= \body -> ok . toResponse . A.encode . A.object $ case validateExerciseAnswer exercise body of Nothing -> [("success", A.Bool False)] Just data' -> [("success", A.Bool True), ("data", data')] ] ] , anyPath $ handleNotFound serverConfiguration userIdentityMaybe ] handleLessonReport :: Course -> Int -> ServerPart Response handleLessonReport course lessonNumber = The only reason for using ` tempRedirect ` is that we may want to change the target url in the future forceSlash . tempRedirect url . toResponse $ ("To report an issue, please visit our GitHub repository." :: T.Text) where lesson :: Lesson lesson = (courseLessons course) !! (lessonNumber - 1) url :: T.Text url = "" `T.append` queryString queryString :: T.Text queryString = TE.decodeUtf8 . BS.toStrict . toLazyByteString $ URI.renderQueryText True [ ("labels", Just "reported-lesson") , ("title", Just $ "Feedback regarding lesson: " `T.append` (lessonTitle lesson)) , ("body", Just $ "Please provide your feedback here...\n\n### Context\nFor context, this feedback refers to the lesson \"" `T.append` (lessonTitle lesson) `T.append` "\" in the course \"" `T.append` (courseTitle course) `T.append` "\".") ]
16769ee90dfe01fada030708fd03217d068c0ade9e0f0b147998db2e82e69c47
KULeuven-CS/CPL
1.21.rkt
#lang eopl (require rackunit) ex 1.21 (define product (lambda (sos1 sos2) (if (null? sos1) '() (append (subproduct (car sos1) sos2) (product (cdr sos1) sos2))))) (define subproduct (lambda (s sos2) (if (null? sos2) '() (cons (list s (car sos2)) (subproduct s (cdr sos2)))))) (check-equal? (product '(a b c) '(x y)) '((a x) (a y) (b x) (b y) (c x) (c y)))
null
https://raw.githubusercontent.com/KULeuven-CS/CPL/0c62cca832edc43218ac63c4e8233e3c3f05d20a/chapter1/1.21.rkt
racket
#lang eopl (require rackunit) ex 1.21 (define product (lambda (sos1 sos2) (if (null? sos1) '() (append (subproduct (car sos1) sos2) (product (cdr sos1) sos2))))) (define subproduct (lambda (s sos2) (if (null? sos2) '() (cons (list s (car sos2)) (subproduct s (cdr sos2)))))) (check-equal? (product '(a b c) '(x y)) '((a x) (a y) (b x) (b y) (c x) (c y)))
6d96e05b49795013dea0b016d07488b27cc76c32daa3e5c88ed297ee6ed0720c
Gabriella439/nix-diff
Utils.hs
# LANGUAGE RecordWildCards # {-# LANGUAGE OverloadedStrings #-} module Golden.Utils where import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.Set import qualified Control.Monad.Reader import qualified Control.Monad.State import Control.Monad (unless) import Control.Exception ( throwIO, ErrorCall(ErrorCall) ) import System.Process.Typed import Nix.Diff ( diff, Diff(unDiff), DiffContext, Status(Status) ) import Nix.Diff.Types ( DerivationDiff ) data TestableDerivations = TestableDerivations { oldDerivation :: FilePath , newDerivation :: FilePath } deriving Show initSimpleDerivations :: IO TestableDerivations initSimpleDerivations = do (oExit, o) <- readProcessStdout (nixInstantiate "./golden-tests/derivations/simple/old/drv.nix") (nExit, n) <- readProcessStdout (nixInstantiate "./golden-tests/derivations/simple/new/drv.nix") unless (oExit == ExitSuccess || nExit == ExitSuccess) (throwIO (ErrorCall "Can't instantiate simple derivations")) pure (TestableDerivations (toFilePath o) (toFilePath n)) where toFilePath = BS.unpack . BS.init -- drop new-line char initComplexDerivations :: IO TestableDerivations initComplexDerivations = do (oExit, o) <- readProcessStdout (nixPathInfo "./golden-tests/derivations/complex/old/") (nExit, n) <- readProcessStdout (nixPathInfo "./golden-tests/derivations/complex/new/") unless (oExit == ExitSuccess || nExit == ExitSuccess) (throwIO (ErrorCall "Can't instantiate complex derivations")) pure (TestableDerivations (toFilePath o) (toFilePath n)) where toFilePath = BS.unpack . BS.init -- drop new-line char nixInstantiate :: FilePath -> ProcessConfig () () () nixInstantiate fp = shell ("nix-instantiate " <> fp) nixPathInfo :: FilePath -> ProcessConfig () () () nixPathInfo fp = shell ("nix path-info --experimental-features 'nix-command flakes' --derivation " <> fp) makeDiffTree :: TestableDerivations -> DiffContext -> IO DerivationDiff makeDiffTree TestableDerivations{..} diffContext = do let status = Status Data.Set.empty let action = diff True oldDerivation (Data.Set.singleton "out") newDerivation (Data.Set.singleton "out") Control.Monad.State.evalStateT (Control.Monad.Reader.runReaderT (unDiff action) diffContext) status
null
https://raw.githubusercontent.com/Gabriella439/nix-diff/8d365e5e8fe9d86add59aab07f79d05ca51d6ade/test/Golden/Utils.hs
haskell
# LANGUAGE OverloadedStrings # drop new-line char drop new-line char
# LANGUAGE RecordWildCards # module Golden.Utils where import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.Set import qualified Control.Monad.Reader import qualified Control.Monad.State import Control.Monad (unless) import Control.Exception ( throwIO, ErrorCall(ErrorCall) ) import System.Process.Typed import Nix.Diff ( diff, Diff(unDiff), DiffContext, Status(Status) ) import Nix.Diff.Types ( DerivationDiff ) data TestableDerivations = TestableDerivations { oldDerivation :: FilePath , newDerivation :: FilePath } deriving Show initSimpleDerivations :: IO TestableDerivations initSimpleDerivations = do (oExit, o) <- readProcessStdout (nixInstantiate "./golden-tests/derivations/simple/old/drv.nix") (nExit, n) <- readProcessStdout (nixInstantiate "./golden-tests/derivations/simple/new/drv.nix") unless (oExit == ExitSuccess || nExit == ExitSuccess) (throwIO (ErrorCall "Can't instantiate simple derivations")) pure (TestableDerivations (toFilePath o) (toFilePath n)) where initComplexDerivations :: IO TestableDerivations initComplexDerivations = do (oExit, o) <- readProcessStdout (nixPathInfo "./golden-tests/derivations/complex/old/") (nExit, n) <- readProcessStdout (nixPathInfo "./golden-tests/derivations/complex/new/") unless (oExit == ExitSuccess || nExit == ExitSuccess) (throwIO (ErrorCall "Can't instantiate complex derivations")) pure (TestableDerivations (toFilePath o) (toFilePath n)) where nixInstantiate :: FilePath -> ProcessConfig () () () nixInstantiate fp = shell ("nix-instantiate " <> fp) nixPathInfo :: FilePath -> ProcessConfig () () () nixPathInfo fp = shell ("nix path-info --experimental-features 'nix-command flakes' --derivation " <> fp) makeDiffTree :: TestableDerivations -> DiffContext -> IO DerivationDiff makeDiffTree TestableDerivations{..} diffContext = do let status = Status Data.Set.empty let action = diff True oldDerivation (Data.Set.singleton "out") newDerivation (Data.Set.singleton "out") Control.Monad.State.evalStateT (Control.Monad.Reader.runReaderT (unDiff action) diffContext) status
9951f927d6faaf6f30287b7aae3967a5d51a755255d345d3dff5afcfc7e3d272
hiroshi-unno/coar
constDatatype.ml
open Core open LogicOld let name_of_sel cons_name i = sprintf "%s#%d" cons_name i let unit_dt = let dt = Datatype.create "unit" [Datatype.mk_dt "unit" []] Datatype.FDt in Datatype.add_cons dt (Datatype.mk_cons "()") let option_dt = let param = Sort.mk_fresh_svar () in let dt = Datatype.create "option" [Datatype.mk_dt "option" [param]] Datatype.FDt in let dt = Datatype.add_cons dt (Datatype.mk_cons "None") in Datatype.add_cons dt (Datatype.mk_cons "Some" ~sels:[Datatype.mk_sel (name_of_sel "Some" 0) param]) let list_dt = let param = Sort.mk_fresh_svar () in let dt = Datatype.create "list" [Datatype.mk_dt "list" [param]] Datatype.FDt in let dt = Datatype.add_cons dt @@ Datatype.mk_cons "[]" in Datatype.add_cons dt @@ Datatype.mk_cons "::" ~sels:[Datatype.mk_sel (name_of_sel "::" 0) param; Datatype.mk_insel (name_of_sel "::" 1) "list" [param]] let exn_dt = Datatype.create "exn" [Datatype.mk_dt "exn" []] Datatype.Undef let _ = LogicOld.update_ref_dtenv (DTEnv.mk_empty () |> Map.Poly.add_exn ~key:"unit" ~data:unit_dt |> Map.Poly.add_exn ~key:"option" ~data:option_dt (* |> Map.Poly.add_exn ~key:"exn" ~data:exn_dt *) |> Map.Poly.add_exn ~key:"list" ~data:list_dt) let init_dtenv () = Atomic.get LogicOld.ref_dtenv let is_unit = function | T_dt.SDT dt -> Stdlib.(dt = unit_dt) | _ -> false
null
https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/ast/constDatatype.ml
ocaml
|> Map.Poly.add_exn ~key:"exn" ~data:exn_dt
open Core open LogicOld let name_of_sel cons_name i = sprintf "%s#%d" cons_name i let unit_dt = let dt = Datatype.create "unit" [Datatype.mk_dt "unit" []] Datatype.FDt in Datatype.add_cons dt (Datatype.mk_cons "()") let option_dt = let param = Sort.mk_fresh_svar () in let dt = Datatype.create "option" [Datatype.mk_dt "option" [param]] Datatype.FDt in let dt = Datatype.add_cons dt (Datatype.mk_cons "None") in Datatype.add_cons dt (Datatype.mk_cons "Some" ~sels:[Datatype.mk_sel (name_of_sel "Some" 0) param]) let list_dt = let param = Sort.mk_fresh_svar () in let dt = Datatype.create "list" [Datatype.mk_dt "list" [param]] Datatype.FDt in let dt = Datatype.add_cons dt @@ Datatype.mk_cons "[]" in Datatype.add_cons dt @@ Datatype.mk_cons "::" ~sels:[Datatype.mk_sel (name_of_sel "::" 0) param; Datatype.mk_insel (name_of_sel "::" 1) "list" [param]] let exn_dt = Datatype.create "exn" [Datatype.mk_dt "exn" []] Datatype.Undef let _ = LogicOld.update_ref_dtenv (DTEnv.mk_empty () |> Map.Poly.add_exn ~key:"unit" ~data:unit_dt |> Map.Poly.add_exn ~key:"option" ~data:option_dt |> Map.Poly.add_exn ~key:"list" ~data:list_dt) let init_dtenv () = Atomic.get LogicOld.ref_dtenv let is_unit = function | T_dt.SDT dt -> Stdlib.(dt = unit_dt) | _ -> false
40b46fcd1f2ae85a65061b07411be596d40c16f448a588323ac5ebd57762cd83
xvw/preface
arrow_choice.ml
open QCheck2 module Suite (R : Model.PROFUNCTORIAL) (P : Preface_specs.ARROW_CHOICE with type ('a, 'b) t = ('a, 'b) R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) = struct module Arrow = Arrow.Suite (R) (P) (A) (B) (C) (D) module Laws = Preface_laws.Arrow_choice.For (P) let arrow_choice_1 count = let generator = fun1 A.observable B.generator and input = R.input (Util.gen_either A.generator C.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_1 (fun lhs rhs (f, x) -> let f = Fn.apply f in let left = lhs f and right = rhs f in R.run_equality x (R.equal (Util.equal_either B.equal C.equal)) left right ) ;; let arrow_choice_2 count = let generator = Gen.tup2 (R.generator A.observable B.generator) (R.generator B.observable C.generator) and input = R.input (Util.gen_either A.generator D.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_2 (fun lhs rhs ((p1, p2), x) -> let pro1 = R.lift p1 and pro2 = R.lift p2 in let left = lhs pro1 pro2 and right = rhs pro1 pro2 in R.run_equality x (R.equal (Util.equal_either C.equal D.equal)) left right ) ;; let arrow_choice_3 count = let generator = R.generator A.observable B.generator and input = R.input A.generator in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_3 (fun lhs rhs (p, x) -> let pro = R.lift p in let left = lhs pro and right = rhs pro in R.run_equality x (R.equal (Util.equal_either B.equal C.equal)) left right ) ;; let arrow_choice_4 count = let generator = Gen.tup2 (R.generator A.observable B.generator) (fun1 C.observable D.generator) and input = R.input (Util.gen_either A.generator C.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_4 (fun lhs rhs ((p, f), x) -> let pro = R.lift p and f = Fn.apply f in let left = lhs pro f and right = rhs pro f in R.run_equality x (R.equal (Util.equal_either B.equal D.equal)) left right ) ;; let arrow_choice_5 count = let generator = R.generator A.observable B.generator and input = R.input (Util.gen_either (Util.gen_either A.generator C.generator) D.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_5 (fun lhs rhs (p, x) -> let pro = R.lift p in let left = lhs pro and right = rhs pro in R.run_equality x (R.equal (Util.equal_either B.equal (Util.equal_either C.equal D.equal)) ) left right ) ;; let tests ~count = Arrow.tests ~count @ [ arrow_choice_1 count ; arrow_choice_2 count ; arrow_choice_3 count ; arrow_choice_4 count ; arrow_choice_5 count ] ;; end
null
https://raw.githubusercontent.com/xvw/preface/84a297e1ee2967ad4341dca875da8d2dc6d7638c/lib/preface_qcheck/arrow_choice.ml
ocaml
open QCheck2 module Suite (R : Model.PROFUNCTORIAL) (P : Preface_specs.ARROW_CHOICE with type ('a, 'b) t = ('a, 'b) R.t) (A : Model.T0) (B : Model.T0) (C : Model.T0) (D : Model.T0) = struct module Arrow = Arrow.Suite (R) (P) (A) (B) (C) (D) module Laws = Preface_laws.Arrow_choice.For (P) let arrow_choice_1 count = let generator = fun1 A.observable B.generator and input = R.input (Util.gen_either A.generator C.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_1 (fun lhs rhs (f, x) -> let f = Fn.apply f in let left = lhs f and right = rhs f in R.run_equality x (R.equal (Util.equal_either B.equal C.equal)) left right ) ;; let arrow_choice_2 count = let generator = Gen.tup2 (R.generator A.observable B.generator) (R.generator B.observable C.generator) and input = R.input (Util.gen_either A.generator D.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_2 (fun lhs rhs ((p1, p2), x) -> let pro1 = R.lift p1 and pro2 = R.lift p2 in let left = lhs pro1 pro2 and right = rhs pro1 pro2 in R.run_equality x (R.equal (Util.equal_either C.equal D.equal)) left right ) ;; let arrow_choice_3 count = let generator = R.generator A.observable B.generator and input = R.input A.generator in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_3 (fun lhs rhs (p, x) -> let pro = R.lift p in let left = lhs pro and right = rhs pro in R.run_equality x (R.equal (Util.equal_either B.equal C.equal)) left right ) ;; let arrow_choice_4 count = let generator = Gen.tup2 (R.generator A.observable B.generator) (fun1 C.observable D.generator) and input = R.input (Util.gen_either A.generator C.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_4 (fun lhs rhs ((p, f), x) -> let pro = R.lift p and f = Fn.apply f in let left = lhs pro f and right = rhs pro f in R.run_equality x (R.equal (Util.equal_either B.equal D.equal)) left right ) ;; let arrow_choice_5 count = let generator = R.generator A.observable B.generator and input = R.input (Util.gen_either (Util.gen_either A.generator C.generator) D.generator) in Util.test ~count (Gen.tup2 generator input) Laws.arrow_choice_5 (fun lhs rhs (p, x) -> let pro = R.lift p in let left = lhs pro and right = rhs pro in R.run_equality x (R.equal (Util.equal_either B.equal (Util.equal_either C.equal D.equal)) ) left right ) ;; let tests ~count = Arrow.tests ~count @ [ arrow_choice_1 count ; arrow_choice_2 count ; arrow_choice_3 count ; arrow_choice_4 count ; arrow_choice_5 count ] ;; end
9eddc1df69d892a10b68a6d1753feea17eeb95bc652e6d75bbc501e7bbe26a54
WhatsApp/erlt
str3.erl
-file("dev/src/str3.erlt", 1). -module(str3). -eqwalizer_unchecked([{mk_str2, 0}, {mk_str3, 0}]). -export_type([str3/0]). -export([mk_str2/0, mk_str3/0]). -type str3() :: {'$#str3:str3', str2:str2()}. mk_str2() -> {'$#str2:str2', {'$#str1:str1', 0}}. mk_str3() -> {'$#str3:str3', {'$#str2:str2', {'$#str1:str1', 0}}}.
null
https://raw.githubusercontent.com/WhatsApp/erlt/616a4adc628ca8754112e659701e57f1cd7fecd1/tests/dev/ir-spec/str3.erl
erlang
-file("dev/src/str3.erlt", 1). -module(str3). -eqwalizer_unchecked([{mk_str2, 0}, {mk_str3, 0}]). -export_type([str3/0]). -export([mk_str2/0, mk_str3/0]). -type str3() :: {'$#str3:str3', str2:str2()}. mk_str2() -> {'$#str2:str2', {'$#str1:str1', 0}}. mk_str3() -> {'$#str3:str3', {'$#str2:str2', {'$#str1:str1', 0}}}.
19a0e700ae9ab734e04033a169f8babe9c5cabd8a6fb2db2b32e33361f6de9f0
realworldocaml/book
virtual_rules.ml
open Import module Pp_spec : sig type t val make : Preprocess.Without_instrumentation.t Preprocess.t Module_name.Per_item.t -> Ocaml.Version.t -> t val pped_module : t -> Module.t -> Module.t end = struct type t = (Module.t -> Module.t) Module_name.Per_item.t let make preprocess v = Module_name.Per_item.map preprocess ~f:(fun pp -> match Preprocess.remove_future_syntax ~for_:Compiler pp v with | No_preprocessing -> Module.ml_source | Action (_, _) -> fun m -> Module.ml_source (Module.pped m) | Pps { loc = _; pps = _; flags = _; staged } -> if staged then Module.ml_source else fun m -> Module.pped (Module.ml_source m)) let pped_module (t : t) m = Module_name.Per_item.get t (Module.name m) m end let setup_copy_rules_for_impl ~sctx ~dir vimpl = let ctx = Super_context.context sctx in let vlib = Vimpl.vlib vimpl in let impl = Vimpl.impl vimpl in let impl_obj_dir = Dune_file.Library.obj_dir ~dir impl in let vlib_obj_dir = Lib.info vlib |> Lib_info.obj_dir in let add_rule = Super_context.add_rule sctx ~dir in let copy_to_obj_dir ~src ~dst = add_rule ~loc:(Loc.of_pos __POS__) (Action_builder.symlink ~src ~dst) in let { Lib_config.has_native; ext_obj; _ } = ctx.lib_config in let { Mode.Dict.byte; native } = Dune_file.Mode_conf.Set.eval impl.modes ~has_native in let copy_obj_file m kind = let src = Obj_dir.Module.cm_file_exn vlib_obj_dir m ~kind in let dst = Obj_dir.Module.cm_file_exn impl_obj_dir m ~kind in copy_to_obj_dir ~src ~dst in let open Memo.O in let copy_objs src = copy_obj_file src Cmi >>> Memo.when_ (Module.visibility src = Public && Obj_dir.need_dedicated_public_dir impl_obj_dir) (fun () -> let dst = Obj_dir.Module.cm_public_file_exn impl_obj_dir src ~kind:Cmi in let src = Obj_dir.Module.cm_public_file_exn vlib_obj_dir src ~kind:Cmi in copy_to_obj_dir ~src ~dst) >>> Memo.when_ (Module.has src ~ml_kind:Impl) (fun () -> Memo.when_ byte (fun () -> copy_obj_file src Cmo) >>> Memo.when_ native (fun () -> copy_obj_file src Cmx >>> let object_file dir = Obj_dir.Module.o_file_exn dir src ~ext_obj in copy_to_obj_dir ~src:(object_file vlib_obj_dir) ~dst:(object_file impl_obj_dir))) in let vlib_modules = Vimpl.vlib_modules vimpl in Modules.fold_no_vlib vlib_modules ~init:(Memo.return ()) ~f:(fun m acc -> acc >>> copy_objs m) let impl sctx ~(lib : Dune_file.Library.t) ~scope = let open Memo.O in match lib.implements with | None -> Memo.return None | Some (loc, implements) -> ( Lib.DB.find (Scope.libs scope) implements >>= function | None -> User_error.raise ~loc [ Pp.textf "Cannot implement %s as that library isn't available" (Lib_name.to_string implements) ] | Some vlib -> let info = Lib.info vlib in let virtual_ = let virtual_ = Lib_info.virtual_ info in match virtual_ with | None -> User_error.raise ~loc:lib.buildable.loc [ Pp.textf "Library %s isn't virtual and cannot be implemented" (Lib_name.to_string implements) ] | Some v -> v in let+ vlib_modules, vlib_foreign_objects = let foreign_objects = Lib_info.foreign_objects info in match (virtual_, foreign_objects) with | External _, Local | Local, External _ -> assert false | External modules, External fa -> Memo.return (modules, fa) | Local, Local -> let name = Lib.name vlib in let vlib = Lib.Local.of_lib_exn vlib in let* dir_contents = let info = Lib.Local.info vlib in let dir = Lib_info.src_dir info in Dir_contents.get sctx ~dir in let* preprocess = Resolve.Memo.read_memo (Preprocess.Per_module.with_instrumentation lib.buildable.preprocess ~instrumentation_backend: (Lib.DB.instrumentation_backend (Scope.libs scope))) in let* modules = let pp_spec = Pp_spec.make preprocess (Super_context.context sctx).version in Dir_contents.ocaml dir_contents >>| Ml_sources.modules ~for_:(Library name) >>= Modules.map_user_written ~f:(fun m -> Memo.return (Pp_spec.pped_module pp_spec m)) in let+ foreign_objects = let ext_obj = (Super_context.context sctx).lib_config.ext_obj in let dir = Obj_dir.obj_dir (Lib.Local.obj_dir vlib) in let+ foreign_sources = Dir_contents.foreign_sources dir_contents in foreign_sources |> Foreign_sources.for_lib ~name |> Foreign.Sources.object_files ~ext_obj ~dir |> List.map ~f:Path.build in (modules, foreign_objects) in Some (Vimpl.make ~impl:lib ~vlib ~vlib_modules ~vlib_foreign_objects))
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/virtual_rules.ml
ocaml
open Import module Pp_spec : sig type t val make : Preprocess.Without_instrumentation.t Preprocess.t Module_name.Per_item.t -> Ocaml.Version.t -> t val pped_module : t -> Module.t -> Module.t end = struct type t = (Module.t -> Module.t) Module_name.Per_item.t let make preprocess v = Module_name.Per_item.map preprocess ~f:(fun pp -> match Preprocess.remove_future_syntax ~for_:Compiler pp v with | No_preprocessing -> Module.ml_source | Action (_, _) -> fun m -> Module.ml_source (Module.pped m) | Pps { loc = _; pps = _; flags = _; staged } -> if staged then Module.ml_source else fun m -> Module.pped (Module.ml_source m)) let pped_module (t : t) m = Module_name.Per_item.get t (Module.name m) m end let setup_copy_rules_for_impl ~sctx ~dir vimpl = let ctx = Super_context.context sctx in let vlib = Vimpl.vlib vimpl in let impl = Vimpl.impl vimpl in let impl_obj_dir = Dune_file.Library.obj_dir ~dir impl in let vlib_obj_dir = Lib.info vlib |> Lib_info.obj_dir in let add_rule = Super_context.add_rule sctx ~dir in let copy_to_obj_dir ~src ~dst = add_rule ~loc:(Loc.of_pos __POS__) (Action_builder.symlink ~src ~dst) in let { Lib_config.has_native; ext_obj; _ } = ctx.lib_config in let { Mode.Dict.byte; native } = Dune_file.Mode_conf.Set.eval impl.modes ~has_native in let copy_obj_file m kind = let src = Obj_dir.Module.cm_file_exn vlib_obj_dir m ~kind in let dst = Obj_dir.Module.cm_file_exn impl_obj_dir m ~kind in copy_to_obj_dir ~src ~dst in let open Memo.O in let copy_objs src = copy_obj_file src Cmi >>> Memo.when_ (Module.visibility src = Public && Obj_dir.need_dedicated_public_dir impl_obj_dir) (fun () -> let dst = Obj_dir.Module.cm_public_file_exn impl_obj_dir src ~kind:Cmi in let src = Obj_dir.Module.cm_public_file_exn vlib_obj_dir src ~kind:Cmi in copy_to_obj_dir ~src ~dst) >>> Memo.when_ (Module.has src ~ml_kind:Impl) (fun () -> Memo.when_ byte (fun () -> copy_obj_file src Cmo) >>> Memo.when_ native (fun () -> copy_obj_file src Cmx >>> let object_file dir = Obj_dir.Module.o_file_exn dir src ~ext_obj in copy_to_obj_dir ~src:(object_file vlib_obj_dir) ~dst:(object_file impl_obj_dir))) in let vlib_modules = Vimpl.vlib_modules vimpl in Modules.fold_no_vlib vlib_modules ~init:(Memo.return ()) ~f:(fun m acc -> acc >>> copy_objs m) let impl sctx ~(lib : Dune_file.Library.t) ~scope = let open Memo.O in match lib.implements with | None -> Memo.return None | Some (loc, implements) -> ( Lib.DB.find (Scope.libs scope) implements >>= function | None -> User_error.raise ~loc [ Pp.textf "Cannot implement %s as that library isn't available" (Lib_name.to_string implements) ] | Some vlib -> let info = Lib.info vlib in let virtual_ = let virtual_ = Lib_info.virtual_ info in match virtual_ with | None -> User_error.raise ~loc:lib.buildable.loc [ Pp.textf "Library %s isn't virtual and cannot be implemented" (Lib_name.to_string implements) ] | Some v -> v in let+ vlib_modules, vlib_foreign_objects = let foreign_objects = Lib_info.foreign_objects info in match (virtual_, foreign_objects) with | External _, Local | Local, External _ -> assert false | External modules, External fa -> Memo.return (modules, fa) | Local, Local -> let name = Lib.name vlib in let vlib = Lib.Local.of_lib_exn vlib in let* dir_contents = let info = Lib.Local.info vlib in let dir = Lib_info.src_dir info in Dir_contents.get sctx ~dir in let* preprocess = Resolve.Memo.read_memo (Preprocess.Per_module.with_instrumentation lib.buildable.preprocess ~instrumentation_backend: (Lib.DB.instrumentation_backend (Scope.libs scope))) in let* modules = let pp_spec = Pp_spec.make preprocess (Super_context.context sctx).version in Dir_contents.ocaml dir_contents >>| Ml_sources.modules ~for_:(Library name) >>= Modules.map_user_written ~f:(fun m -> Memo.return (Pp_spec.pped_module pp_spec m)) in let+ foreign_objects = let ext_obj = (Super_context.context sctx).lib_config.ext_obj in let dir = Obj_dir.obj_dir (Lib.Local.obj_dir vlib) in let+ foreign_sources = Dir_contents.foreign_sources dir_contents in foreign_sources |> Foreign_sources.for_lib ~name |> Foreign.Sources.object_files ~ext_obj ~dir |> List.map ~f:Path.build in (modules, foreign_objects) in Some (Vimpl.make ~impl:lib ~vlib ~vlib_modules ~vlib_foreign_objects))
2d35e1ce23cfd96b8eed0d7ecfa2d46e3ccb656e67120290a766650d6bdca50f
futurice/haskell-mega-repo
Classes.hs
-- | Copyright : ( c ) 2015 Futurice Oy -- License : BSD3 Maintainer : < > -- -- Various classes, and re-exports of often used ones. module PlanMill.Classes ( HasPlanMillCfg (..), MonadCRandom(..), ContainsCryptoGenError, CRandT, evalCRandT, MonadTime(..), ) where import PlanMill.Internal.Prelude import Futurice.CryptoRandom (CRandT, ContainsCryptoGenError, MonadCRandom (..), evalCRandT) import PlanMill.Types class HasPlanMillCfg a where planmillCfg :: Lens' a Cfg planmillCfgUserId :: Lens' a UserId planmillCfgUserId = planmillCfg . lens cfgUserId (\c x -> c { cfgUserId = x }) planmillCfgApiKey :: Lens' a ApiKey planmillCfgApiKey = planmillCfg . lens cfgApiKey (\c x -> c { cfgApiKey = x }) planmillCfgBaseUrl :: Lens' a String planmillCfgBaseUrl = planmillCfg . lens cfgBaseUrl (\c x -> c { cfgBaseUrl = x }) instance HasPlanMillCfg Cfg where planmillCfg = id
null
https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/planmill-client/src/PlanMill/Classes.hs
haskell
| License : BSD3 Various classes, and re-exports of often used ones.
Copyright : ( c ) 2015 Futurice Oy Maintainer : < > module PlanMill.Classes ( HasPlanMillCfg (..), MonadCRandom(..), ContainsCryptoGenError, CRandT, evalCRandT, MonadTime(..), ) where import PlanMill.Internal.Prelude import Futurice.CryptoRandom (CRandT, ContainsCryptoGenError, MonadCRandom (..), evalCRandT) import PlanMill.Types class HasPlanMillCfg a where planmillCfg :: Lens' a Cfg planmillCfgUserId :: Lens' a UserId planmillCfgUserId = planmillCfg . lens cfgUserId (\c x -> c { cfgUserId = x }) planmillCfgApiKey :: Lens' a ApiKey planmillCfgApiKey = planmillCfg . lens cfgApiKey (\c x -> c { cfgApiKey = x }) planmillCfgBaseUrl :: Lens' a String planmillCfgBaseUrl = planmillCfg . lens cfgBaseUrl (\c x -> c { cfgBaseUrl = x }) instance HasPlanMillCfg Cfg where planmillCfg = id
a978fc9c53ee7539f2f097bb851dc00bbd849dfd5a2732a4de85c97c3bcdc376
shiguredo/swidden
swidden_interceptor.erl
-module(swidden_interceptor). 引数なし API の事前処理 -callback preprocess(module(), function(), swidden:json_object()) -> {continue, swidden:json_object()} | {stop, ok} | {stop, {ok, swidden:json_object()}} | {stop, {redirect, binary()}} | {stop, {error, binary()}} | {stop, {error, binary(), map()}}. %% 引数あり API の事前処理 -callback preprocess(module(), function()) -> continue | {stop, ok} | {stop, {ok, swidden:json_object()}} | {stop, {redirect, binary()}} | {stop, {error, binary()}} | {stop, {error, binary(), map()}}. %% 事後処理 -callback postprocess(module(), function(), ok | {ok, swidden:json_object()} | {ok, {redirect, binary()}} | {error, binary()} | {error, binary(), map()}) -> ok | {ok, swidden:json_object()} | {ok, {redirect, binary()}} | {error, binary()} | {error, binary(), map()}.
null
https://raw.githubusercontent.com/shiguredo/swidden/0ac3c2e3e8618d9f3bb853a7689844e6e1ecd6fd/src/swidden_interceptor.erl
erlang
引数あり API の事前処理 事後処理
-module(swidden_interceptor). 引数なし API の事前処理 -callback preprocess(module(), function(), swidden:json_object()) -> {continue, swidden:json_object()} | {stop, ok} | {stop, {ok, swidden:json_object()}} | {stop, {redirect, binary()}} | {stop, {error, binary()}} | {stop, {error, binary(), map()}}. -callback preprocess(module(), function()) -> continue | {stop, ok} | {stop, {ok, swidden:json_object()}} | {stop, {redirect, binary()}} | {stop, {error, binary()}} | {stop, {error, binary(), map()}}. -callback postprocess(module(), function(), ok | {ok, swidden:json_object()} | {ok, {redirect, binary()}} | {error, binary()} | {error, binary(), map()}) -> ok | {ok, swidden:json_object()} | {ok, {redirect, binary()}} | {error, binary()} | {error, binary(), map()}.
a607a5058187f37bb3dcb06854fcae45e776502af7bf42100ac5edf2ef0cbd9c
criticic/llpp
glTex.mli
$ I d : glTex.mli , v 1.8 2012 - 03 - 06 03:31:02 garrigue Exp $ open Gl val coord : s:float -> ?t:float -> ?r:float -> ?q:float -> unit -> unit val coord2 : float * float -> unit val coord3 : float * float * float -> unit val coord4 : float * float * float * float -> unit type env_param = [ `mode of [`modulate|`decal|`blend|`replace] | `color of rgba] val env : env_param -> unit type coord = [`s|`t|`r|`q] type gen_param = [ `mode of [`object_linear|`eye_linear|`sphere_map] | `object_plane of point4 | `eye_plane of point4 ] val gen : coord:coord -> gen_param -> unit type format = [`color_index|`red|`green|`blue|`alpha|`rgb|`bgr|`rgba|`bgra |`luminance|`luminance_alpha] val image1d : ?proxy:bool -> ?level:int -> ?internal:int -> ?border:bool -> ([< format], [< kind]) GlPix.t -> unit val image2d : ?proxy:bool -> ?level:int -> ?internal:int -> ?border:bool -> ([< format], [< kind]) GlPix.t -> unit type filter = [`nearest|`linear|`nearest_mipmap_nearest|`linear_mipmap_nearest |`nearest_mipmap_linear|`linear_mipmap_linear] type wrap = [`clamp|`repeat] type parameter = [ `min_filter of filter | `mag_filter of [`nearest|`linear] | `wrap_s of wrap | `wrap_t of wrap | `border_color of rgba | `priority of clampf | `generate_mipmap of bool ] val parameter : target:[`texture_1d|`texture_2d] -> parameter -> unit type texture_id val gen_texture : unit -> texture_id val gen_textures : len:int -> texture_id array val bind_texture : target:[`texture_1d|`texture_2d] -> texture_id -> unit val delete_texture : texture_id -> unit val delete_textures : texture_id array -> unit
null
https://raw.githubusercontent.com/criticic/llpp/04431d79a40dcc0215f87a2ad577f126a85c1e61/lablGL/glTex.mli
ocaml
$ I d : glTex.mli , v 1.8 2012 - 03 - 06 03:31:02 garrigue Exp $ open Gl val coord : s:float -> ?t:float -> ?r:float -> ?q:float -> unit -> unit val coord2 : float * float -> unit val coord3 : float * float * float -> unit val coord4 : float * float * float * float -> unit type env_param = [ `mode of [`modulate|`decal|`blend|`replace] | `color of rgba] val env : env_param -> unit type coord = [`s|`t|`r|`q] type gen_param = [ `mode of [`object_linear|`eye_linear|`sphere_map] | `object_plane of point4 | `eye_plane of point4 ] val gen : coord:coord -> gen_param -> unit type format = [`color_index|`red|`green|`blue|`alpha|`rgb|`bgr|`rgba|`bgra |`luminance|`luminance_alpha] val image1d : ?proxy:bool -> ?level:int -> ?internal:int -> ?border:bool -> ([< format], [< kind]) GlPix.t -> unit val image2d : ?proxy:bool -> ?level:int -> ?internal:int -> ?border:bool -> ([< format], [< kind]) GlPix.t -> unit type filter = [`nearest|`linear|`nearest_mipmap_nearest|`linear_mipmap_nearest |`nearest_mipmap_linear|`linear_mipmap_linear] type wrap = [`clamp|`repeat] type parameter = [ `min_filter of filter | `mag_filter of [`nearest|`linear] | `wrap_s of wrap | `wrap_t of wrap | `border_color of rgba | `priority of clampf | `generate_mipmap of bool ] val parameter : target:[`texture_1d|`texture_2d] -> parameter -> unit type texture_id val gen_texture : unit -> texture_id val gen_textures : len:int -> texture_id array val bind_texture : target:[`texture_1d|`texture_2d] -> texture_id -> unit val delete_texture : texture_id -> unit val delete_textures : texture_id array -> unit
280b5d0f846e1a0d64b8eedae4451da265caa3598099c5a6f43cd7c4ecd1fe6d
dalaing/little-languages
Pretty.hs
module Components.Type.Bool.Pretty where import Control.Lens (preview) import Text.PrettyPrint.ANSI.Leijen import Common.Recursion import Common.Type.Pretty import Components.Type.Bool.Data prettyTyBool :: WithBoolType ty => ty -> Maybe Doc prettyTyBool = fmap (const . text $ "Bool") . preview _TyBool prettyTypeInput :: WithBoolType ty => PrettyTypeInput ty prettyTypeInput = PrettyTypeInput [ MSBase prettyTyBool ]
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/multityped/nb-modular/src/Components/Type/Bool/Pretty.hs
haskell
module Components.Type.Bool.Pretty where import Control.Lens (preview) import Text.PrettyPrint.ANSI.Leijen import Common.Recursion import Common.Type.Pretty import Components.Type.Bool.Data prettyTyBool :: WithBoolType ty => ty -> Maybe Doc prettyTyBool = fmap (const . text $ "Bool") . preview _TyBool prettyTypeInput :: WithBoolType ty => PrettyTypeInput ty prettyTypeInput = PrettyTypeInput [ MSBase prettyTyBool ]
40989d1260f9ed2ee41980b375603eef2f28a47b4245063a3b9d60e2736210ef
imrehg/ypsilon
paint.scm
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gtk paint) (export gtk_paint_arrow gtk_paint_box gtk_paint_box_gap gtk_paint_check gtk_paint_diamond gtk_paint_expander gtk_paint_extension gtk_paint_flat_box gtk_paint_focus gtk_paint_handle gtk_paint_hline gtk_paint_layout gtk_paint_option gtk_paint_polygon gtk_paint_resize_grip gtk_paint_shadow gtk_paint_shadow_gap gtk_paint_slider gtk_paint_tab gtk_paint_vline) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgtk-x11-2.0.so.0") (on-sunos "libgtk-x11-2.0.so.0") (on-freebsd "libgtk-x11-2.0.so.0") (on-openbsd "libgtk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgtk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GTK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) (define-syntax define-function/va_list (syntax-rules () ((_ ret name args) (define name (lambda x (assertion-violation 'name "va_list argument not supported")))))) void gtk_paint_arrow ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , GtkArrowType arrow_type , , , gint y , , ) (define-function void gtk_paint_arrow (void* void* int int void* void* char* int int int int int int)) void gtk_paint_box ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_box (void* void* int int void* void* char* int int int int)) void gtk_paint_box_gap ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , , , ) (define-function void gtk_paint_box_gap (void* void* int int void* void* char* int int int int int int int)) void gtk_paint_check ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_check (void* void* int int void* void* char* int int int int)) void gtk_paint_diamond ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_diamond (void* void* int int void* void* char* int int int int)) void gtk_paint_expander ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , GtkExpanderStyle expander_style ) (define-function void gtk_paint_expander (void* void* int void* void* char* int int int)) void gtk_paint_extension ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , ) (define-function void gtk_paint_extension (void* void* int int void* void* char* int int int int int)) void gtk_paint_flat_box ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_flat_box (void* void* int int void* void* char* int int int int)) void gtk_paint_focus ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_focus (void* void* int void* void* char* int int int int)) void gtk_paint_handle ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , GtkOrientation orientation ) (define-function void gtk_paint_handle (void* void* int int void* void* char* int int int int int)) void gtk_paint_hline ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , gint x1 , gint x2 , ) (define-function void gtk_paint_hline (void* void* int void* void* char* int int int)) void gtk_paint_layout ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , use_text , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , PangoLayout * layout ) (define-function void gtk_paint_layout (void* void* int int void* void* char* int int void*)) void gtk_paint_option ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_option (void* void* int int void* void* char* int int int int)) void gtk_paint_polygon ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , const GdkPoint * points , , ) (define-function void gtk_paint_polygon (void* void* int int void* void* char* void* int int)) void gtk_paint_resize_grip ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , GdkWindowEdge edge , , gint y , , ) (define-function void gtk_paint_resize_grip (void* void* int void* void* char* int int int int int)) void gtk_paint_shadow ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_shadow (void* void* int int void* void* char* int int int int)) void gtk_paint_shadow_gap ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , , , ) (define-function void gtk_paint_shadow_gap (void* void* int int void* void* char* int int int int int int int)) void gtk_paint_slider ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , GtkOrientation orientation ) (define-function void gtk_paint_slider (void* void* int int void* void* char* int int int int int)) void gtk_paint_tab ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_tab (void* void* int int void* void* char* int int int int)) void gtk_paint_vline ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , gint y1 _ , , ) (define-function void gtk_paint_vline (void* void* int void* void* char* int int int)) ) ;[end]
null
https://raw.githubusercontent.com/imrehg/ypsilon/e57a06ef5c66c1a88905b2be2fa791fa29848514/sitelib/ypsilon/gtk/paint.scm
scheme
[end]
#!nobacktrace Ypsilon Scheme System Copyright ( c ) 2004 - 2009 Y.FUJITA / LittleWing Company Limited . See license.txt for terms and conditions of use . (library (ypsilon gtk paint) (export gtk_paint_arrow gtk_paint_box gtk_paint_box_gap gtk_paint_check gtk_paint_diamond gtk_paint_expander gtk_paint_extension gtk_paint_flat_box gtk_paint_focus gtk_paint_handle gtk_paint_hline gtk_paint_layout gtk_paint_option gtk_paint_polygon gtk_paint_resize_grip gtk_paint_shadow gtk_paint_shadow_gap gtk_paint_slider gtk_paint_tab gtk_paint_vline) (import (rnrs) (ypsilon ffi)) (define lib-name (cond (on-linux "libgtk-x11-2.0.so.0") (on-sunos "libgtk-x11-2.0.so.0") (on-freebsd "libgtk-x11-2.0.so.0") (on-openbsd "libgtk-x11-2.0.so.0") (on-darwin "Gtk.framework/Gtk") (on-windows "libgtk-win32-2.0-0.dll") (else (assertion-violation #f "can not locate GTK library, unknown operating system")))) (define lib (load-shared-object lib-name)) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (c-function lib lib-name ret name args))))) (define-syntax define-function/va_list (syntax-rules () ((_ ret name args) (define name (lambda x (assertion-violation 'name "va_list argument not supported")))))) void gtk_paint_arrow ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , GtkArrowType arrow_type , , , gint y , , ) (define-function void gtk_paint_arrow (void* void* int int void* void* char* int int int int int int)) void gtk_paint_box ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_box (void* void* int int void* void* char* int int int int)) void gtk_paint_box_gap ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , , , ) (define-function void gtk_paint_box_gap (void* void* int int void* void* char* int int int int int int int)) void gtk_paint_check ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_check (void* void* int int void* void* char* int int int int)) void gtk_paint_diamond ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_diamond (void* void* int int void* void* char* int int int int)) void gtk_paint_expander ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , GtkExpanderStyle expander_style ) (define-function void gtk_paint_expander (void* void* int void* void* char* int int int)) void gtk_paint_extension ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , ) (define-function void gtk_paint_extension (void* void* int int void* void* char* int int int int int)) void gtk_paint_flat_box ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_flat_box (void* void* int int void* void* char* int int int int)) void gtk_paint_focus ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_focus (void* void* int void* void* char* int int int int)) void gtk_paint_handle ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , GtkOrientation orientation ) (define-function void gtk_paint_handle (void* void* int int void* void* char* int int int int int)) void gtk_paint_hline ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , gint x1 , gint x2 , ) (define-function void gtk_paint_hline (void* void* int void* void* char* int int int)) void gtk_paint_layout ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , use_text , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , PangoLayout * layout ) (define-function void gtk_paint_layout (void* void* int int void* void* char* int int void*)) void gtk_paint_option ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_option (void* void* int int void* void* char* int int int int)) void gtk_paint_polygon ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , const GdkPoint * points , , ) (define-function void gtk_paint_polygon (void* void* int int void* void* char* void* int int)) void gtk_paint_resize_grip ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , GdkWindowEdge edge , , gint y , , ) (define-function void gtk_paint_resize_grip (void* void* int void* void* char* int int int int int)) void gtk_paint_shadow ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_shadow (void* void* int int void* void* char* int int int int)) void gtk_paint_shadow_gap ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , , , ) (define-function void gtk_paint_shadow_gap (void* void* int int void* void* char* int int int int int int int)) void gtk_paint_slider ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , , GtkOrientation orientation ) (define-function void gtk_paint_slider (void* void* int int void* void* char* int int int int int)) void gtk_paint_tab ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , GtkShadowType shadow_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , , gint y , , ) (define-function void gtk_paint_tab (void* void* int int void* void* char* int int int int)) void gtk_paint_vline ( GtkStyle * style , GdkWindow * window , GtkStateType state_type , const GdkRectangle * area , GtkWidget * widget , const gchar * detail , gint y1 _ , , ) (define-function void gtk_paint_vline (void* void* int void* void* char* int int int))
2a6fed408e852120631536a1cb4bc286c7edee89d2f3ab937c40e4bf4ff1a71a
Engelberg/ubergraph
alg.clj
(ns ubergraph.alg "Contains algorithms that operate on Ubergraphs, and all the functions associated with paths" (:require [ubergraph.core :as uber] [ubergraph.protocols :as prots] [potemkin :refer [import-vars]] [clojure.core.reducers :as r] [loom.graph :as lg] [loom.attr :as la] loom.alg) (:import java.util.PriorityQueue java.util.HashMap java.util.LinkedList java.util.HashSet java.util.Collections java.util.Map)) ;; Various searches for shortest paths For speed , on Java , use mutable queues and hash maps Consider using Clojure data structures for better portability to Clojurescript (import-vars [ubergraph.protocols ;; Path protocols edges-in-path nodes-in-path cost-of-path start-of-path end-of-path last-edge-of-path path-to all-destinations] ;; path-between Reserved for future use in all-paths algorithms [loom.alg ;; Curated loom algorithms connected-components connected? pre-traverse pre-span post-traverse topsort bf-traverse bf-span dag? scc strongly-connected? connect coloring? greedy-coloring degeneracy-ordering maximal-cliques]) ;; TBD - Looking for volunteer to analyze flow and minimum spanning tree algos ;; from loom and ensure correctness for graphs with parallel edges. (declare find-path) (defrecord Path [list-of-edges cost end last-edge] ubergraph.protocols/IPath (edges-in-path [this] @list-of-edges) (nodes-in-path [this] (when (seq @list-of-edges) (cons (uber/src (first @list-of-edges)) (map uber/dest @list-of-edges)))) (cost-of-path [this] cost) (end-of-path [this] end) (start-of-path [this] (first (nodes-in-path this))) (last-edge-of-path [this] (when (not (identical? last-edge ())) last-edge))) (defrecord AllPathsFromSource [^Map backlinks ^Map least-costs] ubergraph.protocols/IAllPathsFromSource (path-to [this dest] (when-let [last-edge (.get backlinks dest)] (->Path (delay (find-path dest backlinks)) (.get least-costs dest) dest last-edge))) (all-destinations [this] (keys backlinks))) (defrecord AllBFSPathsFromSource [^Map backlinks ^Map depths] ubergraph.protocols/IAllPathsFromSource (path-to [this dest] (when-let [last-edge (.get backlinks dest)] (->Path (delay (find-path dest backlinks)) (.get depths dest) dest last-edge))) (all-destinations [this] (keys backlinks))) (alter-meta! #'->Path assoc :no-doc true) (alter-meta! #'->AllPathsFromSource assoc :no-doc true) (alter-meta! #'->AllBFSPathsFromSource assoc :no-doc true) (alter-meta! #'map->Path assoc :no-doc true) (alter-meta! #'map->AllPathsFromSource assoc :no-doc true) (alter-meta! #'map->AllBFSPathsFromSource assoc :no-doc true) (extend-type nil ubergraph.protocols/IPath (edges-in-path [this] nil) (nodes-in-path [this] nil) (cost-of-path [this] nil) (start-of-path [this] nil) (end-of-path [this] nil) ubergraph.protocols/IAllPathsFromSource (path-to [this dest] nil)) (def ^:private no-goal (with-meta #{} {:no-goal true})) ; Used to search all possibilities (defn- edge-attrs "Figure out edge attributes if no graph specified" [edge] (cond (vector? edge) (nth edge 2) (meta edge) (uber/attrs (meta edge) edge) :else {})) (defn pprint-path "Prints a path's edges along with the edges' attribute maps. (pprint-path g p) will print the attribute maps currently stored in graph g for each edge in p. (pprint-path p) will print the attribute maps associated with each edge in p at the time the path was generated." ([p] (println "Total Cost:" (cost-of-path p)) (doseq [edge (edges-in-path p)] (println (uber/src edge) "->" (uber/dest edge) (let [a (edge-attrs edge)] (if (seq a) a ""))))) ([g p] (println "Total Cost:" (cost-of-path p)) (doseq [edge (edges-in-path p)] (println (uber/src edge) "->" (uber/dest edge) (let [a (uber/attrs g edge)] (if (seq a) a "")))))) (defn- find-path "Work backwards from the destination to reconstruct the path" ([to backlinks] (find-path to backlinks ())) ([to ^Map backlinks path] (let [prev-edge (.get backlinks to)] (if (= prev-edge ()) path (recur (uber/src prev-edge) backlinks (cons prev-edge path)))))) (defn- least-edges-path-helper "Find the path with the least number of edges" [g goal? ^LinkedList queue ^HashMap backlinks ^HashMap depths node-filter edge-filter] (loop [] (if-let [node (.poll queue)] (let [depth (.get depths node)] (if (goal? node) (->Path (delay (find-path node backlinks)) depth node (.get backlinks node)) (do (doseq [edge (uber/out-edges g node) :when (edge-filter edge)] (let [dst (uber/dest edge) inc-depth (inc depth)] (when (and (node-filter dst) (not (.get backlinks dst))) (.add queue dst) (.put depths dst inc-depth) (.put backlinks dst edge)))) (recur)))) (if (identical? no-goal goal?) (->AllBFSPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap depths)) nil)))) (defn- least-edges-path-seq-helper "Variation that produces a seq of paths produced during the traversal" [g goal? ^LinkedList queue ^HashMap backlinks ^HashMap depths node-filter edge-filter min-cost max-cost] (let [explore-node (fn [node depth] (doseq [edge (uber/out-edges g node) :when (edge-filter edge)] (let [dst (uber/dest edge) inc-depth (inc depth)] (when (and (node-filter dst) (not (.get backlinks dst))) (.add queue dst) (.put depths dst inc-depth) (.put backlinks dst edge))))) stepfn (fn stepfn [] (when-let [node (.poll queue)] (let [depth (.get depths node)] (if (<= min-cost depth max-cost) (cons (->Path (delay (find-path node backlinks)) depth node (.get backlinks node)) (lazy-seq (if (goal? node) nil (do (explore-node node depth) (stepfn))))) (if (goal? node) nil (do (explore-node node depth) (recur)))))))] (stepfn))) (defn- least-edges-path "Takes a graph g, a collection of starting nodes, and a goal? predicate. Returns a path that gets you from one of the starting nodes to a node that satisfies the goal? predicate using the fewest possible edges." [g starting-nodes goal? node-filter edge-filter traverse? min-cost max-cost] (let [queue (LinkedList.), backlinks (HashMap.) depths (HashMap.)] (doseq [node starting-nodes :when (and (uber/has-node? g node) (node-filter node))] (.add queue node) (.put depths node 0) (.put backlinks node ())) (if traverse? (least-edges-path-seq-helper g goal? queue backlinks depths node-filter edge-filter min-cost max-cost) (least-edges-path-helper g goal? queue backlinks depths node-filter edge-filter)))) (defn- least-cost-path-helper "Find the shortest path with respect to the cost-fn applied to edges" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn node-filter edge-filter] (loop [] (if-let [[cost-from-start-to-node node] (.poll queue)] (cond (goal? node) (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (> cost-from-start-to-node (.get least-costs node)) (recur) :else (do (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :let [dst (uber/dest edge)] :when (node-filter dst)] (let [cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [cost-from-start-to-dst dst]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge)))) (recur))) (if (identical? no-goal goal?) (->AllPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap least-costs)) nil)))) (defn- least-cost-path-seq-helper "Variation that produces a seq of paths produced during the traversal" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn node-filter edge-filter min-cost max-cost] (let [explore-node (fn [node cost-from-start-to-node] (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :let [dst (uber/dest edge)] :when (node-filter dst)] (let [cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [cost-from-start-to-dst dst]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge))))), stepfn (fn stepfn [] (loop [] (when-let [[cost-from-start-to-node node] (.poll queue)] (cond (or (< cost-from-start-to-node min-cost) (< max-cost cost-from-start-to-node)) (do (explore-node node cost-from-start-to-node) (recur)), (goal? node) [(->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node))], (> cost-from-start-to-node (.get least-costs node)) (recur) :else (cons (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (lazy-seq (do (explore-node node cost-from-start-to-node) (stepfn))))))))] (stepfn))) (defn- least-cost-path "Takes a graph g, a collection of starting nodes, a goal? predicate, and optionally a cost function (defaults to weight). Returns a list of edges that form a path with the least cost from one of the starting nodes to a node that satisfies the goal? predicate." [g starting-nodes goal? cost-fn node-filter edge-filter traverse? min-cost max-cost] (let [least-costs (HashMap.), backlinks (HashMap.) queue (PriorityQueue. (fn [x y] (compare (x 0) (y 0))))] (doseq [node starting-nodes :when (and (uber/has-node? g node) (node-filter node))] (.put least-costs node 0) (.put backlinks node ()) (.add queue [0 node])) (if traverse? (least-cost-path-seq-helper g goal? queue least-costs backlinks cost-fn node-filter edge-filter min-cost max-cost) (least-cost-path-helper g goal? queue least-costs backlinks cost-fn node-filter edge-filter)))) (defn- least-cost-path-with-heuristic-helper "AKA A* search" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn heuristic-fn node-filter edge-filter] (loop [] (if-let [[estimated-total-cost-through-node [cost-from-start-to-node node]] (.poll queue)] (cond (goal? node) (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (> cost-from-start-to-node (.get least-costs node)) (recur) :else (do (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :when (node-filter (uber/dest edge))] (let [dst (uber/dest edge), cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [(+ cost-from-start-to-dst (heuristic-fn dst)) [cost-from-start-to-dst dst]]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge)))) (recur))) (if (identical? no-goal goal?) (->AllPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap least-costs)) nil)))) (defn- least-cost-path-with-heuristic-seq-helper "Variation that produces seq of paths traversed" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn heuristic-fn node-filter edge-filter min-cost max-cost] (let [explore-node (fn [node cost-from-start-to-node] (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :when (node-filter (uber/dest edge))] (let [dst (uber/dest edge), cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [(+ cost-from-start-to-dst (heuristic-fn dst)) [cost-from-start-to-dst dst]]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge))))), stepfn (fn stepfn [] (when-let [[estimated-total-cost-through-node [cost-from-start-to-node node]] (.poll queue)] (cond (or (< cost-from-start-to-node min-cost) (< max-cost cost-from-start-to-node)) (do (explore-node node cost-from-start-to-node) (recur)), (goal? node) [(->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node))] (> cost-from-start-to-node (.get least-costs node)) (recur) :else (cons (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (lazy-seq (do (explore-node node cost-from-start-to-node) (stepfn)))))))] (stepfn))) (defn- least-cost-path-with-heuristic "Heuristic function must take a single node as an input, and return a lower bound of the cost from that node to a goal node" [g starting-nodes goal? cost-fn heuristic-fn node-filter edge-filter traverse? min-cost max-cost] (let [least-costs (HashMap.), backlinks (HashMap.) queue (PriorityQueue. (fn [x y] (compare (x 0) (y 0))))] (doseq [node starting-nodes :when (and (uber/has-node? g node) (node-filter node))] (.put least-costs node 0) (.put backlinks node ()) (.add queue [(heuristic-fn node) [0 node]])) (if traverse? (least-cost-path-with-heuristic-seq-helper g goal? queue least-costs backlinks cost-fn heuristic-fn node-filter edge-filter min-cost max-cost) (least-cost-path-with-heuristic-helper g goal? queue least-costs backlinks cost-fn heuristic-fn node-filter edge-filter)))) (declare bellman-ford) (def ^:dynamic ^{:doc "Bind this dynamic variable to false if you prefer for shortest-path to throw an error, if negative cost edge is found."} *auto-bellman-ford* true) (defn- out-edges-fn->graph "Implements the protocols necessary to do a search" [out-edges-fn] (reify lg/Graph (has-node? [g node] true) (out-edges [g node] (for [{:keys [dest] :as edge} (out-edges-fn node)] [node dest (dissoc edge :dest)])) la/AttrGraph (attrs [g edge] (let [attrs (nth edge 2)] (cond (map? attrs) attrs (number? attrs) {:weight attrs} :else {:weight 1}))) (attr [g edge k] (get (la/attrs g edge) k)))) (defn shortest-path "Finds the shortest path in g, where g is either an ubergraph or a transition function that implies a graph. A transition function takes the form: (fn [node] [{:dest successor1, ...} {:dest successor2, ...} ...]) You must specify a start node or a collection of start nodes from which to begin the search, however specifying an end node is optional. If an end node condition is specified, this function will return an implementation of the IPath protocol, representing the shortest path. Otherwise, it will search out as far as it can go, and return an implementation of the IAllPathsFromSource protocol, which contains all the data needed to quickly find the shortest path to a given destination (using IAllPathsFromSource's `path-to` protocol function). If :traverse is set to true, then the function will instead return a lazy sequence of the shortest paths from the start node(s) to each node in the graph in the order the nodes are encountered by the search process. Takes a search-specification map which must contain: Either :start-node (single node) or :start-nodes (collection) Map may contain the following entries: Either :end-node (single node) or :end-nodes (collection) or :end-node? (predicate function) :cost-fn - A function that takes an edge as an input and returns a cost (defaults to every edge having a cost of 1, i.e., breadth-first search if no cost-fn given) :cost-attr - Alternatively, can specify an edge attribute to use as the cost :heuristic-fn - A function that takes a node as an input and returns a lower-bound on the distance to a goal node, used to guide the search and make it more efficient. :node-filter - A predicate function that takes a node and returns true or false. If specified, only nodes that pass this node-filter test will be considered in the search. :edge-filter - A predicate function that takes an edge and returns true or false. If specified, only edges that pass this edge-filter test will be considered in the search. Map may contain the following additional entries if a traversal sequence is desired: :traverse true - Changes output to be a sequence of paths in order encountered. :min-cost - Filters traversal sequence, only applies if :traverse is set to true :max-cost - Filters traversal sequence, only applies if :traverse is set to true shortest-path has specific arities for the two most common combinations: (shortest-path g start-node end-node) (shortest-path g start-node end-node cost-attr) " ([g start-node end-node] (shortest-path g {:start-node start-node, :end-node end-node})) ([g start-node end-node cost-attr] (shortest-path g {:start-node start-node, :end-node end-node, :cost-attr cost-attr})) ([g search-specification] (assert (map? search-specification) "Second input must be a map, see docstring for options") (assert (not (and (get search-specification :start-node) (get search-specification :start-nodes))) "Can't specify both :start-node and :start-nodes") (assert (<= 2 (count (filter nil? (map search-specification [:end-node :end-nodes :end-node?])))) "Pick only one of :end-node, :end-nodes, or :end-node?") (assert (not (and (get search-specification :cost-fn) (get search-specification :cost-attr))) "Can't specify both a :cost-fn and a :cost-attr") (let [g (if-not (fn? g) g (out-edges-fn->graph g)) cost-attr (get search-specification :cost-attr) cost-fn (if cost-attr #(uber/attr g % cost-attr) (get search-specification :cost-fn)) cost-fn (when cost-fn (fn [edge] (let [cost (cost-fn edge)] (if (neg? cost) (throw (IllegalStateException. "Negative edge, retry with Bellman-Ford alg")) cost)))) heuristic-fn (get search-specification :heuristic-fn) node-filter (get search-specification :node-filter (constantly true)) edge-filter (get search-specification :edge-filter (constantly true)) starting-nodes (if-let [start-node (:start-node search-specification)] [start-node] (:start-nodes search-specification)) traversal? (:traverse search-specification) goal? (cond (:end-node search-specification) #{(:end-node search-specification)} (:end-nodes search-specification) (set (:end-nodes search-specification)) (:end-node? search-specification) (:end-node? search-specification) :else no-goal) min-cost (get search-specification :min-cost java.lang.Double/NEGATIVE_INFINITY) max-cost (get search-specification :max-cost java.lang.Double/POSITIVE_INFINITY)] (assert (<= min-cost max-cost) ":min-cost must be less-than-or-equal to :max-cost") (assert (or (not (or (:min-cost search-specification) (:max-cost search-specification))) traversal?) ":min-cost and :max-cost have no effect unless you set :traverse to true") (try (cond (and (nil? cost-fn) (nil? cost-attr) (nil? heuristic-fn)) (least-edges-path g starting-nodes goal? node-filter edge-filter traversal? min-cost max-cost), heuristic-fn (least-cost-path-with-heuristic g starting-nodes goal? (if cost-fn cost-fn (constantly 1)) heuristic-fn node-filter edge-filter traversal? min-cost max-cost), :else (least-cost-path g starting-nodes goal? cost-fn node-filter edge-filter traversal? min-cost max-cost)) (catch IllegalStateException e (if *auto-bellman-ford* (bellman-ford g search-specification) (throw (IllegalStateException. "Found edge with negative cost. Use bellman-ford.")))))))) (defn paths->graph "Takes output of shortest-path and returns the graph of directed edges implied by the search process" [paths] (cond (satisfies? ubergraph.protocols/IAllPathsFromSource paths) (let [^Map backlinks (:backlinks paths)] (apply uber/digraph (for [[node edge] (seq backlinks) init (if (= edge ()) [[node {:cost-of-path (cost-of-path (path-to paths node))}]] [[node {:cost-of-path (cost-of-path (path-to paths node))}] ^:edge [(uber/src (.get backlinks node)) node (edge-attrs edge)]])] init))) (satisfies? ubergraph.protocols/IPath paths) (apply uber/digraph [(end-of-path paths) {:cost-of-path (cost-of-path paths)}] (for [edge (edges-in-path paths)] ^:edge [(uber/src edge) (uber/dest edge) (edge-attrs edge)])) :else (apply uber/digraph (for [path paths :let [edge (last-edge-of-path path)] init (if-not edge [[(end-of-path path) {:cost-of-path (cost-of-path path)}]] [[(end-of-path path) {:cost-of-path (cost-of-path path)}] ^:edge [(uber/src edge) (uber/dest edge) (edge-attrs edge)]])] init)))) Algorithms similar to those in , adapted for (defn loners "Return nodes with no connections to other nodes (i.e., isolated nodes)" [g] (for [node (uber/nodes g) :when (and (zero? (uber/in-degree g node)) (zero? (uber/out-degree g node)))] node)) (defn distinct-edges "Distinct edges of g." [g] (if (uber/ubergraph? g) (for [edge (uber/edges g) :when (not (uber/mirror-edge? edge))] edge) (loom.alg/distinct-edges g))) (defn longest-shortest-path "The longest shortest-path starting from start" [g start] (last (shortest-path g {:start-node start, :traverse true}))) Bellman - Ford , adapted from Loom (defn- can-relax-edge? "Test for whether we can improve the shortest path to v found so far by going through u." [[u v :as edge] cost costs] (let [vd (get costs v) ud (get costs u) sum (+ ud cost)] (> vd sum))) (defn- relax-edge "If there's a shorter path from s to v via u, update our map of estimated path costs and map of paths from source to vertex v" [[u v :as edge] cost [costs backlinks :as estimates]] (let [ud (get costs u) sum (+ ud cost)] (if (can-relax-edge? edge cost costs) [(assoc costs v sum) (assoc backlinks v edge)] estimates))) (defn- relax-edges "Performs edge relaxation on all edges in weighted directed graph" [edges estimates cost-fn] (let [new-estimates (->> (edges) (reduce (fn [estimates edge] (relax-edge edge (cost-fn edge) estimates)) estimates))] (if (identical? estimates new-estimates) ; If no edge relaxed in this pass, we know for sure we're done (reduced (with-meta new-estimates {:bellman-ford-complete true})) new-estimates))) (defn- init-estimates "Initializes path cost estimates and paths from source to all vertices, for Bellman-Ford algorithm" [graph starting-nodes node-filter] (let [starting-node-set (set starting-nodes) nodes (for [node (uber/nodes graph) :when (and (node-filter node) (not (starting-node-set node)))] node) path-costs (into {} (for [node starting-nodes] [node 0])) backlinks (into {} (for [node starting-nodes] [node ()])) infinities (repeat Double/POSITIVE_INFINITY) nils (repeat ()) init-costs (interleave nodes infinities) init-backlinks (interleave nodes nils)] [(apply assoc path-costs init-costs) (apply assoc backlinks init-backlinks)])) (defn bellman-ford "Given an ubergraph g, and one or more start nodes, the Bellman-Ford algorithm produces an implementation of the IAllPathsFromSource protocol if no negative-weight cycle that is reachable from the source exits, and false otherwise, indicating that no solution exists. bellman-ford is very similar to shortest-path. It is less efficient, but it correctly handles graphs with negative edges. If you know you have edges with negative costs, use bellman-ford. If you are unsure whether your graph has negative costs, or don't understand when and why you'd want to use bellman-ford, just use shortest-path and it will make the decision for you, calling this function if necessary. Takes a search-specification map which must contain: Either :start-node (single node) or :start-nodes (collection) Map may contain the following entries: Either :end-node (single node) or :end-nodes (collection) or :end-node? (predicate function) :cost-fn - A function that takes an edge as an input and returns a cost (defaults to weight, or 1 if no weight is present) :cost-attr - Alternatively, can specify an edge attribute to use as the cost :node-filter - A predicate function that takes a node and returns true or false. If specified, only nodes that pass this node-filter test will be considered in the search. :edge-filter - A predicate function that takes an edge and returns true or false. If specified, only edges that pass this edge-filter test will be considered in the search. Map may contain the following additional entries if a traversal sequence is desired: :traverse true - Changes output to be a sequence of paths in order encountered. :min-cost - Filters traversal sequence, only applies if :traverse is set to true :max-cost - Filters traversal sequence, only applies if :traverse is set to true bellman-ford has specific arity for the most common combination: (bellman-ford g start-node cost-attr) " ([g start-node cost-attr] (bellman-ford g {:start-node start-node :cost-attr cost-attr})) ([g search-specification] (assert (map? search-specification) "Second input must be a map, see docstring for options") (assert (not (and (get search-specification :start-node) (get search-specification :start-nodes))) "Can't specify both :start-node and :start-nodes") (assert (<= 2 (count (filter nil? (map search-specification [:end-node :end-nodes :end-node?])))) "Pick only one of :end-node, :end-nodes, or :end-node?") (assert (not (and (get search-specification :cost-fn) (get search-specification :cost-attr))) "Can't specify both a :cost-fn and a :cost-attr") (let [cost-attr (get search-specification :cost-attr) cost-fn (if cost-attr #(uber/attr g % cost-attr) (get search-specification :cost-fn)) node-filter (get search-specification :node-filter (constantly true)) edge-filter (get search-specification :edge-filter (constantly true)) starting-nodes (if-let [start-node (:start-node search-specification)] [start-node] (:start-nodes search-specification)) starting-nodes (filter #(and (uber/has-node? g %) (node-filter %)) starting-nodes) valid-nodes (filter node-filter (uber/nodes g)) end-nodes (cond (:end-node search-specification) [(:end-node search-specification)] (:end-nodes search-specification) (:end-nodes search-specification) (:end-node? search-specification) (filter (:end-node? search-specification) valid-nodes) :else nil) goal? (set end-nodes) traversal? (:traverse search-specification) min-cost (get search-specification :min-cost java.lang.Double/NEGATIVE_INFINITY) max-cost (get search-specification :max-cost java.lang.Double/POSITIVE_INFINITY)] (assert (<= min-cost max-cost) ":min-cost must be less-than-or-equal to :max-cost") (assert (or (not (or (:min-cost search-specification) (:max-cost search-specification))) traversal?) ":min-cost and :max-cost have no effect unless you set :traverse to true") (when (seq starting-nodes) (let [initial-estimates (init-estimates g starting-nodes node-filter) edges (fn [] (for [n (shuffle valid-nodes) ;shuffling nodes improves running time :when (node-filter n) e (uber/out-edges g n) :when (and (edge-filter e) (node-filter (uber/dest e)))] e)) relax - edges is calculated for all edges V-1 times [costs backlinks :as answer] (reduce (fn [estimates _] (relax-edges edges estimates cost-fn)) initial-estimates (range (dec (count valid-nodes))))] (if (and (not (:bellman-ford-complete (meta answer))) (some (fn [edge] (can-relax-edge? edge (cost-fn edge) costs)) (edges))) false (let [backlinks (reduce (fn [links node] (if (= Double/POSITIVE_INFINITY (get costs node)) (dissoc links node) links)) backlinks valid-nodes) all-paths-from-source (->AllPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap costs))] (cond traversal? (->> (vec valid-nodes) (r/map #(path-to all-paths-from-source %)) (r/filter #(<= min-cost (cost-of-path %) max-cost)) r/foldcat sort), end-nodes (->> (vec end-nodes) (r/map #(path-to all-paths-from-source %)) r/foldcat (apply min-key cost-of-path)) :else all-paths-from-source)))))))) ;; Some things from Loom that don't quite work as-is ;; Loom's bipartite has a bug where it only calls successors to get neighbors, ;; which doesn't work for directed edges. (defn bipartite-color "Attempts a two-coloring of graph g. When successful, returns a map of nodes to colors (1 or 0). Otherwise, returns nil." [g] (letfn [(color-component [coloring start] (loop [coloring (assoc coloring start 1) queue (conj clojure.lang.PersistentQueue/EMPTY start)] (if (empty? queue) coloring (let [v (peek queue) color (- 1 (coloring v)) nbrs (uber/neighbors g v)] (if (some #(and (coloring %) (= (coloring v) (coloring %))) nbrs) nil ; graph is not bipartite (let [nbrs (remove coloring nbrs)] (recur (into coloring (for [nbr nbrs] [nbr color])) (into (pop queue) nbrs))))))))] (loop [[node & nodes] (seq (uber/nodes g)) coloring {}] (when coloring (if (nil? node) coloring (if (coloring node) (recur nodes coloring) (recur nodes (color-component coloring node)))))))) (defn bipartite? "Returns true if g is bipartite" [g] (boolean (bipartite-color g))) (defn bipartite-sets "Returns two sets of nodes, one for each color of the bipartite coloring, or nil if g is not bipartite" [g] (when-let [coloring (bipartite-color g)] (reduce (fn [[s1 s2] [node color]] (if (zero? color) [(conj s1 node) s2] [s1 (conj s2 node)])) [#{} #{}] coloring)))
null
https://raw.githubusercontent.com/Engelberg/ubergraph/1a6b326135995a44c4c7dc337602024e9a91edf6/src/ubergraph/alg.clj
clojure
Various searches for shortest paths Path protocols path-between Reserved for future use in all-paths algorithms Curated loom algorithms TBD - Looking for volunteer to analyze flow and minimum spanning tree algos from loom and ensure correctness for graphs with parallel edges. Used to search all possibilities If no edge relaxed in this pass, we know for sure we're done shuffling nodes improves running time Some things from Loom that don't quite work as-is Loom's bipartite has a bug where it only calls successors to get neighbors, which doesn't work for directed edges. graph is not bipartite
(ns ubergraph.alg "Contains algorithms that operate on Ubergraphs, and all the functions associated with paths" (:require [ubergraph.core :as uber] [ubergraph.protocols :as prots] [potemkin :refer [import-vars]] [clojure.core.reducers :as r] [loom.graph :as lg] [loom.attr :as la] loom.alg) (:import java.util.PriorityQueue java.util.HashMap java.util.LinkedList java.util.HashSet java.util.Collections java.util.Map)) For speed , on Java , use mutable queues and hash maps Consider using Clojure data structures for better portability to Clojurescript (import-vars [ubergraph.protocols edges-in-path nodes-in-path cost-of-path start-of-path end-of-path last-edge-of-path path-to all-destinations] [loom.alg connected-components connected? pre-traverse pre-span post-traverse topsort bf-traverse bf-span dag? scc strongly-connected? connect coloring? greedy-coloring degeneracy-ordering maximal-cliques]) (declare find-path) (defrecord Path [list-of-edges cost end last-edge] ubergraph.protocols/IPath (edges-in-path [this] @list-of-edges) (nodes-in-path [this] (when (seq @list-of-edges) (cons (uber/src (first @list-of-edges)) (map uber/dest @list-of-edges)))) (cost-of-path [this] cost) (end-of-path [this] end) (start-of-path [this] (first (nodes-in-path this))) (last-edge-of-path [this] (when (not (identical? last-edge ())) last-edge))) (defrecord AllPathsFromSource [^Map backlinks ^Map least-costs] ubergraph.protocols/IAllPathsFromSource (path-to [this dest] (when-let [last-edge (.get backlinks dest)] (->Path (delay (find-path dest backlinks)) (.get least-costs dest) dest last-edge))) (all-destinations [this] (keys backlinks))) (defrecord AllBFSPathsFromSource [^Map backlinks ^Map depths] ubergraph.protocols/IAllPathsFromSource (path-to [this dest] (when-let [last-edge (.get backlinks dest)] (->Path (delay (find-path dest backlinks)) (.get depths dest) dest last-edge))) (all-destinations [this] (keys backlinks))) (alter-meta! #'->Path assoc :no-doc true) (alter-meta! #'->AllPathsFromSource assoc :no-doc true) (alter-meta! #'->AllBFSPathsFromSource assoc :no-doc true) (alter-meta! #'map->Path assoc :no-doc true) (alter-meta! #'map->AllPathsFromSource assoc :no-doc true) (alter-meta! #'map->AllBFSPathsFromSource assoc :no-doc true) (extend-type nil ubergraph.protocols/IPath (edges-in-path [this] nil) (nodes-in-path [this] nil) (cost-of-path [this] nil) (start-of-path [this] nil) (end-of-path [this] nil) ubergraph.protocols/IAllPathsFromSource (path-to [this dest] nil)) (defn- edge-attrs "Figure out edge attributes if no graph specified" [edge] (cond (vector? edge) (nth edge 2) (meta edge) (uber/attrs (meta edge) edge) :else {})) (defn pprint-path "Prints a path's edges along with the edges' attribute maps. (pprint-path g p) will print the attribute maps currently stored in graph g for each edge in p. (pprint-path p) will print the attribute maps associated with each edge in p at the time the path was generated." ([p] (println "Total Cost:" (cost-of-path p)) (doseq [edge (edges-in-path p)] (println (uber/src edge) "->" (uber/dest edge) (let [a (edge-attrs edge)] (if (seq a) a ""))))) ([g p] (println "Total Cost:" (cost-of-path p)) (doseq [edge (edges-in-path p)] (println (uber/src edge) "->" (uber/dest edge) (let [a (uber/attrs g edge)] (if (seq a) a "")))))) (defn- find-path "Work backwards from the destination to reconstruct the path" ([to backlinks] (find-path to backlinks ())) ([to ^Map backlinks path] (let [prev-edge (.get backlinks to)] (if (= prev-edge ()) path (recur (uber/src prev-edge) backlinks (cons prev-edge path)))))) (defn- least-edges-path-helper "Find the path with the least number of edges" [g goal? ^LinkedList queue ^HashMap backlinks ^HashMap depths node-filter edge-filter] (loop [] (if-let [node (.poll queue)] (let [depth (.get depths node)] (if (goal? node) (->Path (delay (find-path node backlinks)) depth node (.get backlinks node)) (do (doseq [edge (uber/out-edges g node) :when (edge-filter edge)] (let [dst (uber/dest edge) inc-depth (inc depth)] (when (and (node-filter dst) (not (.get backlinks dst))) (.add queue dst) (.put depths dst inc-depth) (.put backlinks dst edge)))) (recur)))) (if (identical? no-goal goal?) (->AllBFSPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap depths)) nil)))) (defn- least-edges-path-seq-helper "Variation that produces a seq of paths produced during the traversal" [g goal? ^LinkedList queue ^HashMap backlinks ^HashMap depths node-filter edge-filter min-cost max-cost] (let [explore-node (fn [node depth] (doseq [edge (uber/out-edges g node) :when (edge-filter edge)] (let [dst (uber/dest edge) inc-depth (inc depth)] (when (and (node-filter dst) (not (.get backlinks dst))) (.add queue dst) (.put depths dst inc-depth) (.put backlinks dst edge))))) stepfn (fn stepfn [] (when-let [node (.poll queue)] (let [depth (.get depths node)] (if (<= min-cost depth max-cost) (cons (->Path (delay (find-path node backlinks)) depth node (.get backlinks node)) (lazy-seq (if (goal? node) nil (do (explore-node node depth) (stepfn))))) (if (goal? node) nil (do (explore-node node depth) (recur)))))))] (stepfn))) (defn- least-edges-path "Takes a graph g, a collection of starting nodes, and a goal? predicate. Returns a path that gets you from one of the starting nodes to a node that satisfies the goal? predicate using the fewest possible edges." [g starting-nodes goal? node-filter edge-filter traverse? min-cost max-cost] (let [queue (LinkedList.), backlinks (HashMap.) depths (HashMap.)] (doseq [node starting-nodes :when (and (uber/has-node? g node) (node-filter node))] (.add queue node) (.put depths node 0) (.put backlinks node ())) (if traverse? (least-edges-path-seq-helper g goal? queue backlinks depths node-filter edge-filter min-cost max-cost) (least-edges-path-helper g goal? queue backlinks depths node-filter edge-filter)))) (defn- least-cost-path-helper "Find the shortest path with respect to the cost-fn applied to edges" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn node-filter edge-filter] (loop [] (if-let [[cost-from-start-to-node node] (.poll queue)] (cond (goal? node) (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (> cost-from-start-to-node (.get least-costs node)) (recur) :else (do (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :let [dst (uber/dest edge)] :when (node-filter dst)] (let [cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [cost-from-start-to-dst dst]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge)))) (recur))) (if (identical? no-goal goal?) (->AllPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap least-costs)) nil)))) (defn- least-cost-path-seq-helper "Variation that produces a seq of paths produced during the traversal" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn node-filter edge-filter min-cost max-cost] (let [explore-node (fn [node cost-from-start-to-node] (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :let [dst (uber/dest edge)] :when (node-filter dst)] (let [cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [cost-from-start-to-dst dst]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge))))), stepfn (fn stepfn [] (loop [] (when-let [[cost-from-start-to-node node] (.poll queue)] (cond (or (< cost-from-start-to-node min-cost) (< max-cost cost-from-start-to-node)) (do (explore-node node cost-from-start-to-node) (recur)), (goal? node) [(->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node))], (> cost-from-start-to-node (.get least-costs node)) (recur) :else (cons (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (lazy-seq (do (explore-node node cost-from-start-to-node) (stepfn))))))))] (stepfn))) (defn- least-cost-path "Takes a graph g, a collection of starting nodes, a goal? predicate, and optionally a cost function (defaults to weight). Returns a list of edges that form a path with the least cost from one of the starting nodes to a node that satisfies the goal? predicate." [g starting-nodes goal? cost-fn node-filter edge-filter traverse? min-cost max-cost] (let [least-costs (HashMap.), backlinks (HashMap.) queue (PriorityQueue. (fn [x y] (compare (x 0) (y 0))))] (doseq [node starting-nodes :when (and (uber/has-node? g node) (node-filter node))] (.put least-costs node 0) (.put backlinks node ()) (.add queue [0 node])) (if traverse? (least-cost-path-seq-helper g goal? queue least-costs backlinks cost-fn node-filter edge-filter min-cost max-cost) (least-cost-path-helper g goal? queue least-costs backlinks cost-fn node-filter edge-filter)))) (defn- least-cost-path-with-heuristic-helper "AKA A* search" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn heuristic-fn node-filter edge-filter] (loop [] (if-let [[estimated-total-cost-through-node [cost-from-start-to-node node]] (.poll queue)] (cond (goal? node) (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (> cost-from-start-to-node (.get least-costs node)) (recur) :else (do (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :when (node-filter (uber/dest edge))] (let [dst (uber/dest edge), cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [(+ cost-from-start-to-dst (heuristic-fn dst)) [cost-from-start-to-dst dst]]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge)))) (recur))) (if (identical? no-goal goal?) (->AllPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap least-costs)) nil)))) (defn- least-cost-path-with-heuristic-seq-helper "Variation that produces seq of paths traversed" [g goal? ^PriorityQueue queue ^HashMap least-costs ^HashMap backlinks cost-fn heuristic-fn node-filter edge-filter min-cost max-cost] (let [explore-node (fn [node cost-from-start-to-node] (doseq [edge (uber/out-edges g node) :when (edge-filter edge) :when (node-filter (uber/dest edge))] (let [dst (uber/dest edge), cost-from-node-to-dst (cost-fn edge), cost-from-start-to-dst (+ cost-from-start-to-node cost-from-node-to-dst) least-cost-found-so-far-from-start-to-dst (.get least-costs dst)] (when (or (not least-cost-found-so-far-from-start-to-dst) (< cost-from-start-to-dst least-cost-found-so-far-from-start-to-dst)) (.add queue [(+ cost-from-start-to-dst (heuristic-fn dst)) [cost-from-start-to-dst dst]]) (.put least-costs dst cost-from-start-to-dst) (.put backlinks dst edge))))), stepfn (fn stepfn [] (when-let [[estimated-total-cost-through-node [cost-from-start-to-node node]] (.poll queue)] (cond (or (< cost-from-start-to-node min-cost) (< max-cost cost-from-start-to-node)) (do (explore-node node cost-from-start-to-node) (recur)), (goal? node) [(->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node))] (> cost-from-start-to-node (.get least-costs node)) (recur) :else (cons (->Path (delay (find-path node backlinks)) (.get least-costs node) node (.get backlinks node)) (lazy-seq (do (explore-node node cost-from-start-to-node) (stepfn)))))))] (stepfn))) (defn- least-cost-path-with-heuristic "Heuristic function must take a single node as an input, and return a lower bound of the cost from that node to a goal node" [g starting-nodes goal? cost-fn heuristic-fn node-filter edge-filter traverse? min-cost max-cost] (let [least-costs (HashMap.), backlinks (HashMap.) queue (PriorityQueue. (fn [x y] (compare (x 0) (y 0))))] (doseq [node starting-nodes :when (and (uber/has-node? g node) (node-filter node))] (.put least-costs node 0) (.put backlinks node ()) (.add queue [(heuristic-fn node) [0 node]])) (if traverse? (least-cost-path-with-heuristic-seq-helper g goal? queue least-costs backlinks cost-fn heuristic-fn node-filter edge-filter min-cost max-cost) (least-cost-path-with-heuristic-helper g goal? queue least-costs backlinks cost-fn heuristic-fn node-filter edge-filter)))) (declare bellman-ford) (def ^:dynamic ^{:doc "Bind this dynamic variable to false if you prefer for shortest-path to throw an error, if negative cost edge is found."} *auto-bellman-ford* true) (defn- out-edges-fn->graph "Implements the protocols necessary to do a search" [out-edges-fn] (reify lg/Graph (has-node? [g node] true) (out-edges [g node] (for [{:keys [dest] :as edge} (out-edges-fn node)] [node dest (dissoc edge :dest)])) la/AttrGraph (attrs [g edge] (let [attrs (nth edge 2)] (cond (map? attrs) attrs (number? attrs) {:weight attrs} :else {:weight 1}))) (attr [g edge k] (get (la/attrs g edge) k)))) (defn shortest-path "Finds the shortest path in g, where g is either an ubergraph or a transition function that implies a graph. A transition function takes the form: (fn [node] [{:dest successor1, ...} {:dest successor2, ...} ...]) You must specify a start node or a collection of start nodes from which to begin the search, however specifying an end node is optional. If an end node condition is specified, this function will return an implementation of the IPath protocol, representing the shortest path. Otherwise, it will search out as far as it can go, and return an implementation of the IAllPathsFromSource protocol, which contains all the data needed to quickly find the shortest path to a given destination (using IAllPathsFromSource's `path-to` protocol function). If :traverse is set to true, then the function will instead return a lazy sequence of the shortest paths from the start node(s) to each node in the graph in the order the nodes are encountered by the search process. Takes a search-specification map which must contain: Either :start-node (single node) or :start-nodes (collection) Map may contain the following entries: Either :end-node (single node) or :end-nodes (collection) or :end-node? (predicate function) :cost-fn - A function that takes an edge as an input and returns a cost (defaults to every edge having a cost of 1, i.e., breadth-first search if no cost-fn given) :cost-attr - Alternatively, can specify an edge attribute to use as the cost :heuristic-fn - A function that takes a node as an input and returns a lower-bound on the distance to a goal node, used to guide the search and make it more efficient. :node-filter - A predicate function that takes a node and returns true or false. If specified, only nodes that pass this node-filter test will be considered in the search. :edge-filter - A predicate function that takes an edge and returns true or false. If specified, only edges that pass this edge-filter test will be considered in the search. Map may contain the following additional entries if a traversal sequence is desired: :traverse true - Changes output to be a sequence of paths in order encountered. :min-cost - Filters traversal sequence, only applies if :traverse is set to true :max-cost - Filters traversal sequence, only applies if :traverse is set to true shortest-path has specific arities for the two most common combinations: (shortest-path g start-node end-node) (shortest-path g start-node end-node cost-attr) " ([g start-node end-node] (shortest-path g {:start-node start-node, :end-node end-node})) ([g start-node end-node cost-attr] (shortest-path g {:start-node start-node, :end-node end-node, :cost-attr cost-attr})) ([g search-specification] (assert (map? search-specification) "Second input must be a map, see docstring for options") (assert (not (and (get search-specification :start-node) (get search-specification :start-nodes))) "Can't specify both :start-node and :start-nodes") (assert (<= 2 (count (filter nil? (map search-specification [:end-node :end-nodes :end-node?])))) "Pick only one of :end-node, :end-nodes, or :end-node?") (assert (not (and (get search-specification :cost-fn) (get search-specification :cost-attr))) "Can't specify both a :cost-fn and a :cost-attr") (let [g (if-not (fn? g) g (out-edges-fn->graph g)) cost-attr (get search-specification :cost-attr) cost-fn (if cost-attr #(uber/attr g % cost-attr) (get search-specification :cost-fn)) cost-fn (when cost-fn (fn [edge] (let [cost (cost-fn edge)] (if (neg? cost) (throw (IllegalStateException. "Negative edge, retry with Bellman-Ford alg")) cost)))) heuristic-fn (get search-specification :heuristic-fn) node-filter (get search-specification :node-filter (constantly true)) edge-filter (get search-specification :edge-filter (constantly true)) starting-nodes (if-let [start-node (:start-node search-specification)] [start-node] (:start-nodes search-specification)) traversal? (:traverse search-specification) goal? (cond (:end-node search-specification) #{(:end-node search-specification)} (:end-nodes search-specification) (set (:end-nodes search-specification)) (:end-node? search-specification) (:end-node? search-specification) :else no-goal) min-cost (get search-specification :min-cost java.lang.Double/NEGATIVE_INFINITY) max-cost (get search-specification :max-cost java.lang.Double/POSITIVE_INFINITY)] (assert (<= min-cost max-cost) ":min-cost must be less-than-or-equal to :max-cost") (assert (or (not (or (:min-cost search-specification) (:max-cost search-specification))) traversal?) ":min-cost and :max-cost have no effect unless you set :traverse to true") (try (cond (and (nil? cost-fn) (nil? cost-attr) (nil? heuristic-fn)) (least-edges-path g starting-nodes goal? node-filter edge-filter traversal? min-cost max-cost), heuristic-fn (least-cost-path-with-heuristic g starting-nodes goal? (if cost-fn cost-fn (constantly 1)) heuristic-fn node-filter edge-filter traversal? min-cost max-cost), :else (least-cost-path g starting-nodes goal? cost-fn node-filter edge-filter traversal? min-cost max-cost)) (catch IllegalStateException e (if *auto-bellman-ford* (bellman-ford g search-specification) (throw (IllegalStateException. "Found edge with negative cost. Use bellman-ford.")))))))) (defn paths->graph "Takes output of shortest-path and returns the graph of directed edges implied by the search process" [paths] (cond (satisfies? ubergraph.protocols/IAllPathsFromSource paths) (let [^Map backlinks (:backlinks paths)] (apply uber/digraph (for [[node edge] (seq backlinks) init (if (= edge ()) [[node {:cost-of-path (cost-of-path (path-to paths node))}]] [[node {:cost-of-path (cost-of-path (path-to paths node))}] ^:edge [(uber/src (.get backlinks node)) node (edge-attrs edge)]])] init))) (satisfies? ubergraph.protocols/IPath paths) (apply uber/digraph [(end-of-path paths) {:cost-of-path (cost-of-path paths)}] (for [edge (edges-in-path paths)] ^:edge [(uber/src edge) (uber/dest edge) (edge-attrs edge)])) :else (apply uber/digraph (for [path paths :let [edge (last-edge-of-path path)] init (if-not edge [[(end-of-path path) {:cost-of-path (cost-of-path path)}]] [[(end-of-path path) {:cost-of-path (cost-of-path path)}] ^:edge [(uber/src edge) (uber/dest edge) (edge-attrs edge)]])] init)))) Algorithms similar to those in , adapted for (defn loners "Return nodes with no connections to other nodes (i.e., isolated nodes)" [g] (for [node (uber/nodes g) :when (and (zero? (uber/in-degree g node)) (zero? (uber/out-degree g node)))] node)) (defn distinct-edges "Distinct edges of g." [g] (if (uber/ubergraph? g) (for [edge (uber/edges g) :when (not (uber/mirror-edge? edge))] edge) (loom.alg/distinct-edges g))) (defn longest-shortest-path "The longest shortest-path starting from start" [g start] (last (shortest-path g {:start-node start, :traverse true}))) Bellman - Ford , adapted from Loom (defn- can-relax-edge? "Test for whether we can improve the shortest path to v found so far by going through u." [[u v :as edge] cost costs] (let [vd (get costs v) ud (get costs u) sum (+ ud cost)] (> vd sum))) (defn- relax-edge "If there's a shorter path from s to v via u, update our map of estimated path costs and map of paths from source to vertex v" [[u v :as edge] cost [costs backlinks :as estimates]] (let [ud (get costs u) sum (+ ud cost)] (if (can-relax-edge? edge cost costs) [(assoc costs v sum) (assoc backlinks v edge)] estimates))) (defn- relax-edges "Performs edge relaxation on all edges in weighted directed graph" [edges estimates cost-fn] (let [new-estimates (->> (edges) (reduce (fn [estimates edge] (relax-edge edge (cost-fn edge) estimates)) estimates))] (if (identical? estimates new-estimates) (reduced (with-meta new-estimates {:bellman-ford-complete true})) new-estimates))) (defn- init-estimates "Initializes path cost estimates and paths from source to all vertices, for Bellman-Ford algorithm" [graph starting-nodes node-filter] (let [starting-node-set (set starting-nodes) nodes (for [node (uber/nodes graph) :when (and (node-filter node) (not (starting-node-set node)))] node) path-costs (into {} (for [node starting-nodes] [node 0])) backlinks (into {} (for [node starting-nodes] [node ()])) infinities (repeat Double/POSITIVE_INFINITY) nils (repeat ()) init-costs (interleave nodes infinities) init-backlinks (interleave nodes nils)] [(apply assoc path-costs init-costs) (apply assoc backlinks init-backlinks)])) (defn bellman-ford "Given an ubergraph g, and one or more start nodes, the Bellman-Ford algorithm produces an implementation of the IAllPathsFromSource protocol if no negative-weight cycle that is reachable from the source exits, and false otherwise, indicating that no solution exists. bellman-ford is very similar to shortest-path. It is less efficient, but it correctly handles graphs with negative edges. If you know you have edges with negative costs, use bellman-ford. If you are unsure whether your graph has negative costs, or don't understand when and why you'd want to use bellman-ford, just use shortest-path and it will make the decision for you, calling this function if necessary. Takes a search-specification map which must contain: Either :start-node (single node) or :start-nodes (collection) Map may contain the following entries: Either :end-node (single node) or :end-nodes (collection) or :end-node? (predicate function) :cost-fn - A function that takes an edge as an input and returns a cost (defaults to weight, or 1 if no weight is present) :cost-attr - Alternatively, can specify an edge attribute to use as the cost :node-filter - A predicate function that takes a node and returns true or false. If specified, only nodes that pass this node-filter test will be considered in the search. :edge-filter - A predicate function that takes an edge and returns true or false. If specified, only edges that pass this edge-filter test will be considered in the search. Map may contain the following additional entries if a traversal sequence is desired: :traverse true - Changes output to be a sequence of paths in order encountered. :min-cost - Filters traversal sequence, only applies if :traverse is set to true :max-cost - Filters traversal sequence, only applies if :traverse is set to true bellman-ford has specific arity for the most common combination: (bellman-ford g start-node cost-attr) " ([g start-node cost-attr] (bellman-ford g {:start-node start-node :cost-attr cost-attr})) ([g search-specification] (assert (map? search-specification) "Second input must be a map, see docstring for options") (assert (not (and (get search-specification :start-node) (get search-specification :start-nodes))) "Can't specify both :start-node and :start-nodes") (assert (<= 2 (count (filter nil? (map search-specification [:end-node :end-nodes :end-node?])))) "Pick only one of :end-node, :end-nodes, or :end-node?") (assert (not (and (get search-specification :cost-fn) (get search-specification :cost-attr))) "Can't specify both a :cost-fn and a :cost-attr") (let [cost-attr (get search-specification :cost-attr) cost-fn (if cost-attr #(uber/attr g % cost-attr) (get search-specification :cost-fn)) node-filter (get search-specification :node-filter (constantly true)) edge-filter (get search-specification :edge-filter (constantly true)) starting-nodes (if-let [start-node (:start-node search-specification)] [start-node] (:start-nodes search-specification)) starting-nodes (filter #(and (uber/has-node? g %) (node-filter %)) starting-nodes) valid-nodes (filter node-filter (uber/nodes g)) end-nodes (cond (:end-node search-specification) [(:end-node search-specification)] (:end-nodes search-specification) (:end-nodes search-specification) (:end-node? search-specification) (filter (:end-node? search-specification) valid-nodes) :else nil) goal? (set end-nodes) traversal? (:traverse search-specification) min-cost (get search-specification :min-cost java.lang.Double/NEGATIVE_INFINITY) max-cost (get search-specification :max-cost java.lang.Double/POSITIVE_INFINITY)] (assert (<= min-cost max-cost) ":min-cost must be less-than-or-equal to :max-cost") (assert (or (not (or (:min-cost search-specification) (:max-cost search-specification))) traversal?) ":min-cost and :max-cost have no effect unless you set :traverse to true") (when (seq starting-nodes) (let [initial-estimates (init-estimates g starting-nodes node-filter) :when (node-filter n) e (uber/out-edges g n) :when (and (edge-filter e) (node-filter (uber/dest e)))] e)) relax - edges is calculated for all edges V-1 times [costs backlinks :as answer] (reduce (fn [estimates _] (relax-edges edges estimates cost-fn)) initial-estimates (range (dec (count valid-nodes))))] (if (and (not (:bellman-ford-complete (meta answer))) (some (fn [edge] (can-relax-edge? edge (cost-fn edge) costs)) (edges))) false (let [backlinks (reduce (fn [links node] (if (= Double/POSITIVE_INFINITY (get costs node)) (dissoc links node) links)) backlinks valid-nodes) all-paths-from-source (->AllPathsFromSource (Collections/unmodifiableMap backlinks) (Collections/unmodifiableMap costs))] (cond traversal? (->> (vec valid-nodes) (r/map #(path-to all-paths-from-source %)) (r/filter #(<= min-cost (cost-of-path %) max-cost)) r/foldcat sort), end-nodes (->> (vec end-nodes) (r/map #(path-to all-paths-from-source %)) r/foldcat (apply min-key cost-of-path)) :else all-paths-from-source)))))))) (defn bipartite-color "Attempts a two-coloring of graph g. When successful, returns a map of nodes to colors (1 or 0). Otherwise, returns nil." [g] (letfn [(color-component [coloring start] (loop [coloring (assoc coloring start 1) queue (conj clojure.lang.PersistentQueue/EMPTY start)] (if (empty? queue) coloring (let [v (peek queue) color (- 1 (coloring v)) nbrs (uber/neighbors g v)] (if (some #(and (coloring %) (= (coloring v) (coloring %))) nbrs) (let [nbrs (remove coloring nbrs)] (recur (into coloring (for [nbr nbrs] [nbr color])) (into (pop queue) nbrs))))))))] (loop [[node & nodes] (seq (uber/nodes g)) coloring {}] (when coloring (if (nil? node) coloring (if (coloring node) (recur nodes coloring) (recur nodes (color-component coloring node)))))))) (defn bipartite? "Returns true if g is bipartite" [g] (boolean (bipartite-color g))) (defn bipartite-sets "Returns two sets of nodes, one for each color of the bipartite coloring, or nil if g is not bipartite" [g] (when-let [coloring (bipartite-color g)] (reduce (fn [[s1 s2] [node color]] (if (zero? color) [(conj s1 node) s2] [s1 (conj s2 node)])) [#{} #{}] coloring)))
b9c0a9daa7e7acc554039c5837833d4966ef977ba001bfdf55c45a6eac5b635c
mdippery/stackim
db.clj
(ns stackim.db (:require [clojure.java.jdbc :as jdbc]) (:import [java.io File] [java.net URI] [java.sql BatchUpdateException])) (def cwd (.getCanonicalPath (File. "."))) (def default-database-url (str "postgres:stackim@localhost/stackim")) (def database-url (or (System/getenv "DATABASE_URL") default-database-url)) (def database-uri (URI. database-url)) (def db database-url)
null
https://raw.githubusercontent.com/mdippery/stackim/619724836908e6127a770b404304425ad62c5660/src/stackim/db.clj
clojure
(ns stackim.db (:require [clojure.java.jdbc :as jdbc]) (:import [java.io File] [java.net URI] [java.sql BatchUpdateException])) (def cwd (.getCanonicalPath (File. "."))) (def default-database-url (str "postgres:stackim@localhost/stackim")) (def database-url (or (System/getenv "DATABASE_URL") default-database-url)) (def database-uri (URI. database-url)) (def db database-url)
abcbbd71551e64b60a5a53974786030fcd2ce584dfce39dbf26d51f3d2226878
cmoid/erlbutt
ssb_feed.erl
SPDX - License - Identifier : GPL-2.0 - only %% Copyright ( C ) 2018 Dionne Associates , LLC . -module(ssb_feed). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -include("ssb.hrl"). -behaviour(gen_server). %% API -export([start_link/1]). -export([whoami/1, post_content/2, store_msg/2, fetch_msg/2, fetch_last_msg/1, store_ref/2, references/3, foldl/3]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -import(utils, [load_term/1]). -define(SERVER, ?MODULE). -record(state, {id, last_msg = null, last_seq = 0, feed, profile, refs, msg_cache}). %%%=================================================================== %%% API %%%=================================================================== start_link(FeedId) -> gen_server:start_link(?MODULE, [FeedId], []). whoami(FeedPid) -> gen_server:call(FeedPid, whoami). post_content(FeedPid, Content) -> gen_server:call(FeedPid, {post, Content}, infinity). store_msg(FeedPid, Msg) -> gen_server:call(FeedPid, {store, Msg}, infinity). fetch_msg(FeedPid, Key) -> gen_server:call(FeedPid, {fetch, Key}). fetch_last_msg(FeedPid) -> gen_server:call(FeedPid, {fetch_last_msg}). store_ref(FeedPid, Arrow) -> gen_server:call(FeedPid, {store_ref, Arrow}, infinity). references(FeedPid, MsgId, RootId) -> gen_server:call(FeedPid, {refs, MsgId, RootId}, infinity). foldl(FeedPid, Fun, Acc) -> gen_server:call(FeedPid, {foldl, Fun, Acc}, infinity). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== init([FeedId]) -> process_flag(trap_exit, true), DecodeId = utils:decode_id(FeedId), {Feed, Profile, Refs} = init_directories(DecodeId), State = #state{id = FeedId, feed = Feed, profile = Profile, refs = Refs, msg_cache = ets:new(messages, [])}, {ok, check_owner_feed(State)}. handle_call(whoami, _From, #state{id = Id} = State) -> {reply, Id, State}; handle_call({post, Content}, _From, #state{id = Id} = State) -> %% A given peer can only post to the feed it owns CanPost = Id == keys:pub_key_disp(), if CanPost -> NewState = post(Content, State), {reply, ok, NewState}; true -> {reply, no_post, State} end; handle_call({store, Msg}, _From, State) -> NewState = store(Msg, State), {reply, ok, NewState}; handle_call({store_ref, Arrow}, _From, #state{refs = Refs} = State) -> write_msg(Arrow, Refs), {reply, ok, State}; handle_call({fetch, Key}, _From, #state{feed = Feed, msg_cache = Messages} = State) -> Val = ets:lookup(Messages, Key), {Pos, Msg} = feed_get(Feed, Val, Key), case Val of [] -> ets:insert(Messages, {Key, Pos}); _Else -> nop end, {reply, message:decode(Msg, false), State}; handle_call({fetch_last_msg}, _From, #state{feed = Feed, msg_cache = Messages} = State) -> Resp = feed_get_last(Feed), case Resp of {Pos, Msg, Key} -> ets:insert(Messages, {Key, Pos}), {reply, message:decode(Msg, false), State}; Else -> {reply, Else, State} end; handle_call({refs, MsgId, TangleId}, _From, #state{refs = Refs} = State) -> Fun = fun(Data, Acc) -> IsArc = has_target(Data, MsgId, TangleId), case IsArc of false -> Acc; Targets -> [Targets | Acc] end end, Result = case file:open(Refs, [read, binary]) of {ok, IoDev} -> int_foldr(Fun, [], IoDev); {error, enoent} -> ?info("Ill formed tangle arcs file ~n",[]), done end, {reply, Result, State}; handle_call({foldl, Fun, Acc}, _From, #state{feed = Feed} = State) -> Result = case file:open(Feed, [read, binary]) of {ok, IoDev} -> int_foldr(Fun, Acc, IoDev); {error, enoent} -> ?info("Ill formed feed ~p ~n",[Feed]), Acc end, {reply, Result, State}. handle_cast(_Request, State) -> {noreply, State}. %% info handle_info(Info, State) -> ?info("WTF: ~p ~n",[Info]), {noreply, State}. %% terminate(Reason, _State) -> ?info("Closed gen_server: ~p ~n",[Reason]), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%=================================================================== Internal functions %%%=================================================================== post(Content, #state{id = FeedId, last_msg = Prev, last_seq = Seq} = State) -> #message{id = Id} = Msg = message:new_msg(Prev, Seq + 1, Content, {FeedId, keys:priv_key()}), NewState = store(Msg, State), NewState#state{last_msg = Id, last_seq = Seq + 1}. store(#message{id = Id, author = Auth} = Msg, #state{feed = Feed, profile = Profile} = State) -> mess_auth:put(Id, Auth), write_msg(Msg, Feed), utils:update_refs(Msg), IsAbout = message:is_about(Msg), case IsAbout of true -> write_msg(Msg, Profile), State; _Else -> State end. write_msg(#message{} = DecMsg, Store) -> Msg = message:encode(DecMsg), write_msg(Msg, Store); write_msg(Msg, Store) -> DataSiz = size(Msg), O = open_file(Store), ok = file:write(O, <<DataSiz:32, Msg/binary, DataSiz:32>>), FileSize = filelib:file_size(Store) + 4, ok = file:write(O, <<FileSize:32>>), close_file(O). init_directories(AuthDir) -> Location = config:feed_store_loc(), Author is already decoded as hex , use first two chars for directory <<Dir:2/binary,RestAuth/binary>> = AuthDir, FeedDir = <<Location/binary,Dir/binary,<<"/">>/binary,RestAuth/binary>>, Feed = <<FeedDir/binary,<<"/">>/binary,<<"log.offset">>/binary>>, Profile = <<FeedDir/binary,<<"/">>/binary,<<"profile">>/binary>>, Refs = <<FeedDir/binary,<<"/">>/binary,<<"references">>/binary>>, filelib:ensure_dir(Feed), filelib:ensure_dir(Profile), filelib:ensure_dir(Refs), {Feed, Profile, Refs}. %% Only feed corresponding to the owner of the peer can post. %% All the other feeds are only meant to be read check_owner_feed(#state{id = FeedId, feed = Feed, msg_cache = Messages} = State) -> IsOwner = FeedId == keys:pub_key_disp(), if IsOwner -> Resp = feed_get_last(Feed), case Resp of no_file -> State; done -> State; {Pos, Msg, Key} -> ets:insert(Messages, {Key, Pos}), #message{sequence = Seq} = message:decode(Msg, true), State#state{last_msg = Key, last_seq = Seq} end; true -> State end. feed_get(Feed, [], Key) -> feed_get(Feed, [{Key, 0}], Key); feed_get(Feed, [{Key, Pos}], Key) -> case file:open(Feed, [read, binary]) of {ok, IoDev} -> file:position(IoDev, Pos), scan(IoDev, Pos, Key); {error, enoent} -> ?info("Probably bad input ~n",[]), done end. feed_get_last(Feed) -> case filelib:is_file(Feed) of true -> case file:open(Feed, [read, binary]) of {ok, IoDev} -> Beg = filelib:file_size(Feed) - 8, file:position(IoDev, Beg), case file:read(IoDev, 4) of {ok, <<TermLenInt:32/integer>>} -> file:position(IoDev, Beg - (TermLenInt + 4)), {ok, Data} = load_term(IoDev), file:close(IoDev), Key = extract_key(Data), {Beg - (TermLenInt + 4), Data, Key}; _Else -> file:close(IoDev), done end; {error, Error} -> ?info("Probably bad input ~p ~n",[{Error, Feed}]), done end; false -> no_file end. extract_key(Data) -> {DataProps} = jiffy:decode(Data), ?pgv(<<"key">>, DataProps). scan(IoDev, Pos, Key) -> case load_term(IoDev) of {ok, Data} -> KeyVal = extract_key(Data), if KeyVal == Key -> {Pos, Data}; true -> {ok, <<NextPos:32/integer>>} = file:read(IoDev, 4), scan(IoDev, NextPos, Key) end; {error, eof} -> ?info("Key not found: ~p ~n",[Key]), not_found; {error, Error} -> ?info("Error ~p scanning for key: ~p ~n",[Error, Key]) end. int_foldr(Fun, Acc, IoDev) -> case load_term(IoDev) of {ok, Data} -> file:read(IoDev, 4), int_foldr(Fun, Fun(Data, Acc), IoDev); {error, _Error} -> file:close(IoDev), Acc end. has_target(Msg, Id, RootId) -> {DecProps} = jiffy:decode(Msg), Root = ?pgv(<<"root">>, DecProps), IsRootId = RootId == Root, [Src, _AuthId] = ?pgv(<<"src">>, DecProps), case IsRootId of true -> if Src == Id -> ?pgv(<<"tar">>, DecProps); true -> false end; false -> false end. open_file(File) -> Open = file:open(File, [append, sync]), case Open of {ok, F} -> F; Else -> ?info("Tried to open failed: ~p ~n",[Else]), nil end. close_file(File) -> ok = file:close(File). -ifdef(TEST). instance_feed_test() -> keys:start_link(), config:start_link("test/ssb.cfg"), mess_auth:start_link(), {ok, F1} = ssb_feed:start_link(keys:pub_key_disp()), ok = ssb_feed:post_content(F1, <<"foo">>). -endif.
null
https://raw.githubusercontent.com/cmoid/erlbutt/9e15ace3e9009c8bce6cf3251cf16e1f8611e16a/apps/ssb/src/ssb_feed.erl
erlang
API gen_server callbacks =================================================================== API =================================================================== =================================================================== gen_server callbacks =================================================================== A given peer can only post to the feed it owns info =================================================================== =================================================================== Only feed corresponding to the owner of the peer can post. All the other feeds are only meant to be read
SPDX - License - Identifier : GPL-2.0 - only Copyright ( C ) 2018 Dionne Associates , LLC . -module(ssb_feed). -ifdef(TEST). -include_lib("eunit/include/eunit.hrl"). -endif. -include("ssb.hrl"). -behaviour(gen_server). -export([start_link/1]). -export([whoami/1, post_content/2, store_msg/2, fetch_msg/2, fetch_last_msg/1, store_ref/2, references/3, foldl/3]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -import(utils, [load_term/1]). -define(SERVER, ?MODULE). -record(state, {id, last_msg = null, last_seq = 0, feed, profile, refs, msg_cache}). start_link(FeedId) -> gen_server:start_link(?MODULE, [FeedId], []). whoami(FeedPid) -> gen_server:call(FeedPid, whoami). post_content(FeedPid, Content) -> gen_server:call(FeedPid, {post, Content}, infinity). store_msg(FeedPid, Msg) -> gen_server:call(FeedPid, {store, Msg}, infinity). fetch_msg(FeedPid, Key) -> gen_server:call(FeedPid, {fetch, Key}). fetch_last_msg(FeedPid) -> gen_server:call(FeedPid, {fetch_last_msg}). store_ref(FeedPid, Arrow) -> gen_server:call(FeedPid, {store_ref, Arrow}, infinity). references(FeedPid, MsgId, RootId) -> gen_server:call(FeedPid, {refs, MsgId, RootId}, infinity). foldl(FeedPid, Fun, Acc) -> gen_server:call(FeedPid, {foldl, Fun, Acc}, infinity). init([FeedId]) -> process_flag(trap_exit, true), DecodeId = utils:decode_id(FeedId), {Feed, Profile, Refs} = init_directories(DecodeId), State = #state{id = FeedId, feed = Feed, profile = Profile, refs = Refs, msg_cache = ets:new(messages, [])}, {ok, check_owner_feed(State)}. handle_call(whoami, _From, #state{id = Id} = State) -> {reply, Id, State}; handle_call({post, Content}, _From, #state{id = Id} = State) -> CanPost = Id == keys:pub_key_disp(), if CanPost -> NewState = post(Content, State), {reply, ok, NewState}; true -> {reply, no_post, State} end; handle_call({store, Msg}, _From, State) -> NewState = store(Msg, State), {reply, ok, NewState}; handle_call({store_ref, Arrow}, _From, #state{refs = Refs} = State) -> write_msg(Arrow, Refs), {reply, ok, State}; handle_call({fetch, Key}, _From, #state{feed = Feed, msg_cache = Messages} = State) -> Val = ets:lookup(Messages, Key), {Pos, Msg} = feed_get(Feed, Val, Key), case Val of [] -> ets:insert(Messages, {Key, Pos}); _Else -> nop end, {reply, message:decode(Msg, false), State}; handle_call({fetch_last_msg}, _From, #state{feed = Feed, msg_cache = Messages} = State) -> Resp = feed_get_last(Feed), case Resp of {Pos, Msg, Key} -> ets:insert(Messages, {Key, Pos}), {reply, message:decode(Msg, false), State}; Else -> {reply, Else, State} end; handle_call({refs, MsgId, TangleId}, _From, #state{refs = Refs} = State) -> Fun = fun(Data, Acc) -> IsArc = has_target(Data, MsgId, TangleId), case IsArc of false -> Acc; Targets -> [Targets | Acc] end end, Result = case file:open(Refs, [read, binary]) of {ok, IoDev} -> int_foldr(Fun, [], IoDev); {error, enoent} -> ?info("Ill formed tangle arcs file ~n",[]), done end, {reply, Result, State}; handle_call({foldl, Fun, Acc}, _From, #state{feed = Feed} = State) -> Result = case file:open(Feed, [read, binary]) of {ok, IoDev} -> int_foldr(Fun, Acc, IoDev); {error, enoent} -> ?info("Ill formed feed ~p ~n",[Feed]), Acc end, {reply, Result, State}. handle_cast(_Request, State) -> {noreply, State}. handle_info(Info, State) -> ?info("WTF: ~p ~n",[Info]), {noreply, State}. terminate(Reason, _State) -> ?info("Closed gen_server: ~p ~n",[Reason]), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions post(Content, #state{id = FeedId, last_msg = Prev, last_seq = Seq} = State) -> #message{id = Id} = Msg = message:new_msg(Prev, Seq + 1, Content, {FeedId, keys:priv_key()}), NewState = store(Msg, State), NewState#state{last_msg = Id, last_seq = Seq + 1}. store(#message{id = Id, author = Auth} = Msg, #state{feed = Feed, profile = Profile} = State) -> mess_auth:put(Id, Auth), write_msg(Msg, Feed), utils:update_refs(Msg), IsAbout = message:is_about(Msg), case IsAbout of true -> write_msg(Msg, Profile), State; _Else -> State end. write_msg(#message{} = DecMsg, Store) -> Msg = message:encode(DecMsg), write_msg(Msg, Store); write_msg(Msg, Store) -> DataSiz = size(Msg), O = open_file(Store), ok = file:write(O, <<DataSiz:32, Msg/binary, DataSiz:32>>), FileSize = filelib:file_size(Store) + 4, ok = file:write(O, <<FileSize:32>>), close_file(O). init_directories(AuthDir) -> Location = config:feed_store_loc(), Author is already decoded as hex , use first two chars for directory <<Dir:2/binary,RestAuth/binary>> = AuthDir, FeedDir = <<Location/binary,Dir/binary,<<"/">>/binary,RestAuth/binary>>, Feed = <<FeedDir/binary,<<"/">>/binary,<<"log.offset">>/binary>>, Profile = <<FeedDir/binary,<<"/">>/binary,<<"profile">>/binary>>, Refs = <<FeedDir/binary,<<"/">>/binary,<<"references">>/binary>>, filelib:ensure_dir(Feed), filelib:ensure_dir(Profile), filelib:ensure_dir(Refs), {Feed, Profile, Refs}. check_owner_feed(#state{id = FeedId, feed = Feed, msg_cache = Messages} = State) -> IsOwner = FeedId == keys:pub_key_disp(), if IsOwner -> Resp = feed_get_last(Feed), case Resp of no_file -> State; done -> State; {Pos, Msg, Key} -> ets:insert(Messages, {Key, Pos}), #message{sequence = Seq} = message:decode(Msg, true), State#state{last_msg = Key, last_seq = Seq} end; true -> State end. feed_get(Feed, [], Key) -> feed_get(Feed, [{Key, 0}], Key); feed_get(Feed, [{Key, Pos}], Key) -> case file:open(Feed, [read, binary]) of {ok, IoDev} -> file:position(IoDev, Pos), scan(IoDev, Pos, Key); {error, enoent} -> ?info("Probably bad input ~n",[]), done end. feed_get_last(Feed) -> case filelib:is_file(Feed) of true -> case file:open(Feed, [read, binary]) of {ok, IoDev} -> Beg = filelib:file_size(Feed) - 8, file:position(IoDev, Beg), case file:read(IoDev, 4) of {ok, <<TermLenInt:32/integer>>} -> file:position(IoDev, Beg - (TermLenInt + 4)), {ok, Data} = load_term(IoDev), file:close(IoDev), Key = extract_key(Data), {Beg - (TermLenInt + 4), Data, Key}; _Else -> file:close(IoDev), done end; {error, Error} -> ?info("Probably bad input ~p ~n",[{Error, Feed}]), done end; false -> no_file end. extract_key(Data) -> {DataProps} = jiffy:decode(Data), ?pgv(<<"key">>, DataProps). scan(IoDev, Pos, Key) -> case load_term(IoDev) of {ok, Data} -> KeyVal = extract_key(Data), if KeyVal == Key -> {Pos, Data}; true -> {ok, <<NextPos:32/integer>>} = file:read(IoDev, 4), scan(IoDev, NextPos, Key) end; {error, eof} -> ?info("Key not found: ~p ~n",[Key]), not_found; {error, Error} -> ?info("Error ~p scanning for key: ~p ~n",[Error, Key]) end. int_foldr(Fun, Acc, IoDev) -> case load_term(IoDev) of {ok, Data} -> file:read(IoDev, 4), int_foldr(Fun, Fun(Data, Acc), IoDev); {error, _Error} -> file:close(IoDev), Acc end. has_target(Msg, Id, RootId) -> {DecProps} = jiffy:decode(Msg), Root = ?pgv(<<"root">>, DecProps), IsRootId = RootId == Root, [Src, _AuthId] = ?pgv(<<"src">>, DecProps), case IsRootId of true -> if Src == Id -> ?pgv(<<"tar">>, DecProps); true -> false end; false -> false end. open_file(File) -> Open = file:open(File, [append, sync]), case Open of {ok, F} -> F; Else -> ?info("Tried to open failed: ~p ~n",[Else]), nil end. close_file(File) -> ok = file:close(File). -ifdef(TEST). instance_feed_test() -> keys:start_link(), config:start_link("test/ssb.cfg"), mess_auth:start_link(), {ok, F1} = ssb_feed:start_link(keys:pub_key_disp()), ok = ssb_feed:post_content(F1, <<"foo">>). -endif.
629fa1ba4a365bd19358569881db5fa36e5bc55f99174560ac42f7118b205715
mishadoff/evolville
spawn.clj
(ns evolville.spawn (:require [evolville.config :as config] [evolville.creature :as creature] [evolville.world :as w])) (defn spawn [world [id creature]] (let [now (System/currentTimeMillis) last-spawn-ts (some-> creature :spawn :ts)] (cond ;; initially make creature aware about spawning (nil? last-spawn-ts) (assoc-in world [:creatures id :spawn :ts] now) ;; if time has passed creature can spawn (< (+ last-spawn-ts config/spawn-rate) now) (let [[child-name child-creature] (creature/random world)] (-> world (assoc-in [:creatures child-name] child-creature) (assoc-in [:creatures child-name :loc] (:loc creature)) (assoc-in [:creatures id :spawn :ts] now))) ;; nothing changes, leave the world as is :else world))) (defn spawn-creatures [world] (w/for-each-creature world spawn))
null
https://raw.githubusercontent.com/mishadoff/evolville/f37e7478ae6373a3b431741bd1ecaac42ea5d9f0/src/evolville/spawn.clj
clojure
initially make creature aware about spawning if time has passed creature can spawn nothing changes, leave the world as is
(ns evolville.spawn (:require [evolville.config :as config] [evolville.creature :as creature] [evolville.world :as w])) (defn spawn [world [id creature]] (let [now (System/currentTimeMillis) last-spawn-ts (some-> creature :spawn :ts)] (cond (nil? last-spawn-ts) (assoc-in world [:creatures id :spawn :ts] now) (< (+ last-spawn-ts config/spawn-rate) now) (let [[child-name child-creature] (creature/random world)] (-> world (assoc-in [:creatures child-name] child-creature) (assoc-in [:creatures child-name :loc] (:loc creature)) (assoc-in [:creatures id :spawn :ts] now))) :else world))) (defn spawn-creatures [world] (w/for-each-creature world spawn))
fbd24df0b6b1c1411a40851e486f05512bdde4a4b4580a6fd0352d9ce47ce83c
ntoronto/drbayes
random-bool-set.rkt
#lang typed/racket/base (require drbayes/private/set) (provide (all-defined-out)) (: random-bool-set (-> Bool-Set)) (define (random-bool-set) (booleans->bool-set ((random) . < . 0.5) ((random) . < . 0.5))) (: random-bool (Bool-Set -> Boolean)) (define (random-bool A) (cond [(empty-bool-set? A) (raise-argument-error 'random-bool "Nonempty-Bool-Set" A)] [(bools? A) ((random) . < . 0.5)] [else (trues? A)]))
null
https://raw.githubusercontent.com/ntoronto/drbayes/e59eb7c7867118bf4c77ca903e133c7530e612a3/drbayes/tests/random-sets/random-bool-set.rkt
racket
#lang typed/racket/base (require drbayes/private/set) (provide (all-defined-out)) (: random-bool-set (-> Bool-Set)) (define (random-bool-set) (booleans->bool-set ((random) . < . 0.5) ((random) . < . 0.5))) (: random-bool (Bool-Set -> Boolean)) (define (random-bool A) (cond [(empty-bool-set? A) (raise-argument-error 'random-bool "Nonempty-Bool-Set" A)] [(bools? A) ((random) . < . 0.5)] [else (trues? A)]))
552c2190c27e1305c4e243494094f36463023e9307a7ab6ae047af806dc6ee9f
Workiva/eva
nodes.clj
Copyright 2015 - 2019 Workiva Inc. ;; ;; Licensed under the Eclipse Public License 1.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -1.0.php ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns eva.datastructures.test-version.logic.nodes (:require [eva.datastructures.test-version.logic.state :as state] [eva.datastructures.test-version.logic.protocols :as protocols :refer :all] [eva.datastructures.protocols :as dsp :refer [interval-overlaps? restrict interval-contains? intersect]] [eva.datastructures.test-version.logic.buffer :as buffer] [eva.datastructures.test-version.logic.message :as message] [eva.v2.datastructures.bbtree.storage :refer [uuid get-nodes get-node put-nodes node-pointer? node?]] [eva.datastructures.versioning :refer [ensure-version]] [eva.datastructures.utils.interval :as interval] [eva.datastructures.utils.comparators :as comparison :refer [UPPER LOWER]] [eva.datastructures.utils.core :refer [fast-last overlaps?]] [utiliva.control :refer [?-> ?->>]] [utiliva.core :refer [piecewise-map partition-map zip-from]] [utiliva.comparator :refer [min max]] [utiliva.alpha :refer [mreduce]] [eva.error :refer [insist]] [plumbing.core :refer [?>]] [clojure.data.avl :as avl] [clojure.core.memoize :as memo] [clojure.math.numeric-tower :refer [ceil floor]]) (:import [clojure.data.avl AVLMap] [clojure.lang RT MapEntry] [eva.v2.datastructures.bbtree.storage NodeStorageInfo] [java.util UUID]) (:refer-clojure :exclude [min max])) ;; Important Legal Note. ;; In our implementation of the btree structure , we do n't exactly use pivot keys . ;; In the standard implementation, if a node has n children, it has n-1 pivots, ;; interposed. But in our implementation, we use "cap" keys. With n children, we ;; have n caps. These are arranged such that all caps to the "left" of a given ;; cap C correspond to children whose subdictionaries contain only keys strictly ;; less than C. ;; ;; The important legal bit: Before changing the organization scheme for the internal ;; keys (e.g., to more closely match the canonical B-tree as described in literature, such as using standard ' pivots ' ) , please contact . (set! *warn-on-reflection* true) (defn new-node-id "Nodes within a tree are identified uniquely by a combination of id and version. Whenever a brand-new node is added to the tree, a new node id is generated sequentially. That's what this method does." [] (insist (some? state/*node-id-counter*) "Cannot create new node id with unbound *node-id-counter*") (swap! state/*node-id-counter* inc)) ;; The following record is never used as anything other than a map. My understanding ;; is that the defined fields will have faster access times. That's all. (defrecord NodeProperties [leaf? root? min-rec max-rec order buffer-size comparator]) ;; universal properties for nodes ;; other properties sometimes used: ;; * ROOT ONLY: :semantics, :node-counter ;; * POINTER ONLY: :node-size (defn empty-properties "Selects from properties the keys #{:comparator :order :leaf? :buffer-size} then merges {:root? false} and returns the result." [props] (map->NodeProperties (assoc (select-keys props [:comparator :order :leaf? :buffer-size]) :root? false))) ;; each new node that is created is assigned a node-id, which persists through node modifications. ;; tx indicates during which sequential operation on the tree the node was last modified. ;; uuid (Maybe String) combines the above with a unique string for safe storage. ;; vvv key-vals should be an AVLMap (currently). (defrecord BufferedBTreeNode properties : { : order o , : root ? # t , : leaf ? # f , : min - rec m , : etc etc } dsp/Versioned (get-version [_] VERSION) NodeStorageInfo (uuid [this] uuid) (uuid [this s] (assoc this :uuid s)) ;; TODO: safety checks (node? [_] true) (node-pointer? [_] false) protocols/IBufferedBTreeNode (node-id [this] node-id) (node-id [this x] (assoc this :node-id x)) ;; TODO: safety checks (new-node-from [this] (assoc (node-empty this) :node-id (new-node-id) :tx state/*transaction-id* :uuid nil)) (node-empty [this] ;; TODO: documentation does NOT match implementation. (BufferedBTreeNode. nil node-id tx (empty buffer) (empty key-vals) (empty-properties properties))) (node-conj [this kv] (insist (not (nil? (val kv)))) (node-assoc this (key kv) (val kv))) (node-assoc [this k v] (insist (not (nil? v))) (let [tmp (BufferedBTreeNode. nil node-id tx buffer (assoc key-vals k v) properties)] (-> tmp (min-rec (partial min (node-comparator this)) (if (leaf-node? tmp) k (min-rec v))) (max-rec (partial max (node-comparator this)) (if (leaf-node? tmp) k (max-rec v)))))) (node-dissoc [this k] (BufferedBTreeNode. nil node-id tx buffer (dissoc key-vals k) properties)) (node-get [this k] (get key-vals k)) (buffer-dissoc [this k] (BufferedBTreeNode. nil node-id tx (dissoc buffer k) key-vals properties)) (children [this] key-vals) (children [this m] (BufferedBTreeNode. nil node-id tx buffer m properties)) (children [this f v] (BufferedBTreeNode. nil node-id tx buffer (f key-vals v) properties)) (messages [this] buffer) (messages [this messages] (BufferedBTreeNode. nil node-id tx messages key-vals properties)) (messages [this f v] (BufferedBTreeNode. nil node-id tx (f buffer v) key-vals properties)) (node-key-for [this k] (if (leaf-node? this) k (if-let [above-thing (avl/nearest key-vals > k)] (key above-thing) (key (fast-last key-vals))))) (leaf-node? [this] (get properties :leaf?)) (mark-leaf [this b] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :leaf? (boolean b)))) (inner-node? [this] (not (leaf-node? this))) (root-node? [this] (get properties :root?)) (mark-root [this b] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :root? (boolean b)))) (properties [this] properties) (node-comparator [this] (get properties :comparator)) (node-order [this] (get properties :order)) (buffer-size [this] (get properties :buffer-size)) (node-size [this] (count key-vals));; constant-time: (= true (counted? key-vals)) (max-rec [this] (get properties :max-rec)) (max-rec [this v] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :max-rec v))) (max-rec [this f v] (BufferedBTreeNode. nil node-id tx buffer key-vals (update properties :max-rec (fnil f LOWER) v))) (min-rec [this] (get properties :min-rec)) (min-rec [this v] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :min-rec v))) (min-rec [this f v] (BufferedBTreeNode. nil node-id tx buffer key-vals (update properties :min-rec (fnil f UPPER) v))) (transaction-id [this] tx) (transaction-id [this v] (BufferedBTreeNode. nil node-id v buffer key-vals properties))) (defrecord BufferedBTreePointer [uuid node-id tx properties] dsp/Versioned (get-version [_] VERSION) NodeStorageInfo (uuid [this] uuid) (uuid [this k] (throw (IllegalArgumentException. "Cannot modify the uuid of a node pointer."))) (node? [_] false) (node-pointer? [_] true) protocols/IBufferedBTreeNode ;; unsupported: (node-empty [this] (throw (IllegalArgumentException. "Cannot empty a node pointer."))) (node-assoc [this k v] (throw (IllegalArgumentException. "Cannot assoc to a node pointer."))) (node-dissoc [this k] (throw (IllegalArgumentException. "Cannot dissoc from a node pointer."))) (node-get [this k] (throw (IllegalArgumentException. "Cannot query a node pointer."))) (buffer-dissoc [this k] (throw (IllegalArgumentException. "Cannot dissoc from the buffer of a node pointer."))) (children [this] (throw (IllegalArgumentException. "Cannot get the children of a node pointer."))) (children [this m] (throw (IllegalArgumentException. "Cannot set the children of a node pointer."))) (children [this f v] (throw (IllegalArgumentException. "Cannot update the children of a node pointer."))) (messages [this] (throw (IllegalArgumentException. "Cannot get the buffer of a node pointer."))) (messages [this messages] (throw (IllegalArgumentException. "Cannot set the buffer of a node pointer."))) (messages [this f v] (throw (IllegalArgumentException. "Cannot update the buffer of a node pointer."))) (node-key-for [this k] (throw (IllegalArgumentException. "Cannot examine keys for a node pointer."))) (mark-leaf [this b] (throw (IllegalArgumentException. "Cannot change properties of a node pointer."))) (mark-root [this b] (throw (IllegalArgumentException. "Cannot change properties of a node pointer."))) (node-order [this] (throw (IllegalArgumentException. "Cannot read node order from the pointer."))) (max-rec [this v] (throw (IllegalArgumentException. "Cannot set the max-recursive key of a node pointer."))) (max-rec [this f v] (throw (IllegalArgumentException. "Cannot update the max-recursive key of a node pointer."))) (node-id [this k] (throw (IllegalArgumentException. "Cannot modify the node-id of a node pointer."))) (transaction-id [this k] (throw (IllegalArgumentException. "Cannot modify the transaction-id of a node pointer."))) ;; supported: (node-id [this] node-id) (transaction-id [this] tx) (min-rec [this v] (BufferedBTreePointer. uuid node-id tx (assoc properties :min-rec v))) (min-rec [this f v] (BufferedBTreePointer. uuid node-id tx (update properties :min-rec (fnil f UPPER) v))) (properties [this] (get this :properties)) (node-comparator [this] (get-in this [:properties :comparator])) (leaf-node? [this] (get-in this [:properties :leaf?])) (inner-node? [this] (not (leaf-node? this))) (root-node? [this] (get-in this [:properties :root?])) (node-size [this] (get-in this [:properties :node-size])) (max-rec [this] (get-in this [:properties :max-rec])) (min-rec [this] (get-in this [:properties :min-rec]))) (defn ensure-uuid "Expects, but does not enforce, that maybe-uuid is either nil or a string of (format \"%s-%s-%s\" id tx (UUID/randomUUID)). If maybe-uuid is nil, this returns a new string of that format." [maybe-uuid id tx] (or maybe-uuid (format "%s-%s-%s" id tx (UUID/randomUUID)))) (defn node->pointer [node] (let [property-keys (if (root-node? node) [:leaf? :root? :max-rec :order :min-rec :node-counter :semantics :comparator] [:leaf? :root? :max-rec :order :min-rec :node-counter])] (->BufferedBTreePointer (ensure-uuid (uuid node) (:node-id node) (transaction-id node)) (:node-id node) (transaction-id node) (assoc (select-keys (properties node) property-keys) :node-size (node-size node))))) (defn nodes->pointers [nodes] (map node->pointer nodes)) (defn pointers->nodes [pointers] (insist (some? state/*store*) "pointers->nodes called when *store* is nil.") (->> (get-nodes state/*store* pointers) (map (partial ensure-version VERSION)))) ;; <== ensuring the version of the requested nodes. (defn pointer->node [pointer] (insist (some? state/*store*) "pointer->node called when *store* is nil.") (first (pointers->nodes [pointer]))) TODO : This is a hack and should be ashamed . Edit : This has become even hackier , and should be utterly mortified . "Takes either a pointer or a node id. Returns either that pointer or a minimal implementation of Pointer and Node that will give its uuid." [pointer-thing] (cond (node-pointer? pointer-thing) pointer-thing (satisfies? protocols/IBufferedBTreeNode pointer-thing) (node->pointer pointer-thing) :else (do (insist (string? pointer-thing)) ;; TODO: uuid? predicate (reify NodeStorageInfo (uuid [_] pointer-thing) (node? [_] false) (node-pointer? [_] true) dsp/Versioned (get-version [_] VERSION))))) (defn min-node-size "Minimum size the node can be before considered 'too small'." [node] (ceil (/ (node-order node) 2))) (defn overflowed? [node] (if (leaf-node? node) (> (node-size node) (+ (node-order node) (buffer-size node))) ;; <-- fat leaves optimization happens here (> (node-size node) (node-order node)))) (defn buffer-overflowing? [node] (buffer/overflowing? (messages node))) (defn node-valid-size? [node] (<= (min-node-size node) (node-size node) (node-order node))) (defn underflowed? [node] (and (not (node-pointer? node)) ;; why are node-pointers not underflowed? I suppose because then their underflowediness would have been caught. (or (and (root-node? node) ;; if it's a root but not a leaf and it has a single child, that child should be made root. (not (leaf-node? node)) (= (node-size node) 1)) (and (not (root-node? node)) ;; If it's not a root, check the min-node-size! (< (node-size node) (min-node-size node)))))) (defn node-overlaps? "Does this node overlap with this range? Optionally accepts comparator." ([node range] (node-overlaps? (node-comparator node) node range)) ([cmp node [y1 y2]] (overlaps? cmp [(min-rec node) (max-rec node)] [y1 y2]))) (defn node-minrec-above "Takes an internal node and a dictionary key. Returns the min-rec of the next node 'above' that key. Useful for establishing cap keys or sorting messages." ([this k] (node-minrec-above this k true)) ([this k buffer-aware?] (insist (inner-node? this)) (if-let [above-thing (avl/nearest (children this) > k)] (if-not buffer-aware? (min-rec (val above-thing)) (if-let [min-msg (seq (filter (complement ranged?) (get (messages this) (key above-thing))))] (min (node-comparator this) (apply min (node-comparator this) (map recip min-msg)) (min-rec (val above-thing))) (min-rec (val above-thing)))) UPPER))) (defn node-minrec-above-buffer-unaware [this k] (node-minrec-above this k false)) (defn left-most-key? [node k] (= k (key (first (children node))))) (defn right-most-key? [node k] (= k (key (last (children node))))) (defn update-min-max [node] (if (leaf-node? node) (-> node (min-rec (key (first (children node)))) (max-rec (key (fast-last (children node))))) ;; if internal node, must also check messages queues: (if (empty? (children node)) node (let [min-rec-child (-> node children first val min-rec) max-rec-child (-> node children fast-last val max-rec) TODO : clunky ! ! ! min / max-rec-msg (buffer/max-recip (partial max (node-comparator node)) (messages node))] (-> node (min-rec (if min-rec-msg (min (node-comparator node) min-rec-child min-rec-msg) min-rec-child)) (max-rec (if max-rec-msg (max (node-comparator node) max-rec-child max-rec-msg) max-rec-child))))))) (defn apply-messages "Applies message operations. Valid ops and their implementations are defined in the message namespace." [node msgs] (insist (leaf-node? node)) (as-> (transaction-id node state/*transaction-id*) node (children node (reduce #(apply-message %2 (node-comparator node) %) (children node) msgs)) (if (pos? (node-size node)) (-> node (min-rec (key (first (children node)))) (max-rec (key (last (children node))))) node))) (defn min-rec-buffer-aware "Finds the min-rec of the child, taking into account messages currently sitting in the buffer to be delivered to that child." [node k child] (if-let [msgs (seq (remove ranged? (get (messages node) k)))] (let [min (partial min (node-comparator node))] (min (apply min (map recip msgs)) (min-rec child))) (min-rec child))) (defn make-child->msgs [node messages] (let [kids (children node)] (persistent! (reduce (fn [child-map message] (if (ranged? message) (let [selection (avl/subrange kids >= (node-key-for node (dsp/low (recip message))) <= (node-key-for node (dsp/high (recip message))))] (reduce #(assoc! % %2 (conj (get % %2 []) message)) child-map (vals selection))) (let [k (node-key-for node (recip message)) child (get kids k)] (assoc! child-map child (conj (get child-map child []) message))))) (transient {}) messages)))) (defn- simply-add-ranged-message* [node msg] (let [slice (avl/subrange (children node) >= (node-key-for node (dsp/low (recip msg))) <= (node-key-for node (dsp/high (recip msg))))] (reduce (fn [node [key msg]] (messages node (buffer/insert (messages node) key msg))) node (for [[k child] slice :let [min-rec* (min-rec child)] :when (interval-overlaps? (recip msg) (node-comparator node) min-rec* k)] [k (assoc msg :target (intersect (recip msg) (node-comparator node) (interval/interval min-rec* k false true)))])))) (defn add-ranged-message "Adds a ranged message to all appropriate message buffers in the node. No updates are made to min- or max-rec." [node msg] (simply-add-ranged-message* node msg)) (defn add-simple-message "Add a single message to a node's message buffer. Updates min- and max-rec accordingly." [node msg] (let [k (node-key-for node (recip msg)) node (-> node (messages (buffer/insert ^buffer/BTreeBuffer (messages node) k msg)) (min-rec (partial min (node-comparator node)) (recip msg)) (max-rec (partial max (node-comparator node)) (recip msg)))] (if (= :upsert (op msg)) (children node (fn [kvs target] ;; TODO: move next child under? (update kvs k min-rec (partial min (node-comparator node)) target)) (recip msg)) node))) (defn add-messages "Adds many messages to a node's message buffer. Updates min- and max-rec accordingly." [node msgs] (if (leaf-node? node) (apply-messages node msgs) (let [node (transaction-id node state/*transaction-id*) add-fn (fn [node msg] (if (ranged? msg) (add-ranged-message node msg) (add-simple-message node msg)))] (reduce add-fn node msgs)))) (defn transfer-messages "Adds messages to the buffer of a node when you already know which keys the messages should correspond to. Does nothing to the node's min-rec or max-rec values." [node ks->msgs] (messages node (fn [buffer ks->msgs] (reduce (fn [buffer [k msgs]] (reduce #(buffer/insert % k %2) buffer msgs)) buffer ks->msgs)) ks->msgs)) (defn add-child "Adds a child to an internal node. Meant to be used when creating a node or when 'swapping' children. You should always add children in reverse sorted order. The flag 'buffer-aware?' indicates whether to take the message buffers into account when assigning local cap keys for the child." ([node child] (add-child node child true)) ([node child buffer-aware?] (insist (inner-node? node)) (let [k (node-minrec-above node (max-rec child) buffer-aware?) node (node-assoc node k child)] (?-> node (left-most-key? k) (min-rec (min-rec child)) (right-most-key? k) (max-rec (max-rec child)))))) (defn add-child-buffer-unaware [node child] (add-child node child false)) (defn add-children "Takes a node and a map nodes->msgs to add. Ensures min- and max-rec are up-to-date." [node adopted->msgs] (let [kids (vals (children node)) kids->msgs (sequence (comp (map #(get (messages node) %)) (zip-from kids)) (keys (children node))) nodes->msgs (sort-by (comp min-rec key) (node-comparator node) (concat adopted->msgs kids->msgs)) ks (conj (vec (rest (map min-rec (keys nodes->msgs)))) UPPER)] (as-> (node-empty node) node (reduce node-conj node (zipmap ks (keys nodes->msgs))) (transfer-messages node (zipmap ks (vals nodes->msgs))) (update-min-max node)))) (defn remove-children "Takes an inner node and a simple sequence of keys. Removes children bound to those keys, along with any messages intended for those children. Updates min- and max-rec accordingly." [node ks] (insist (inner-node? node)) (let [kids (vals (for [kv (children node) :when (every? #(not= (key kv) %) ks)] kv)) new-ks (conj (vec (rest (map min-rec kids))) UPPER) msgs (buffer/get-all (reduce #(dissoc % %2) (messages node) ks))] (as-> (node-empty node) node (reduce node-conj node (zipmap new-ks kids)) (add-messages node msgs) (update-min-max node)))) (defn remove-values "Takes a leaf node and a simple sequence of keys. Removes the values stored by those keys. Once it is finished, it updates the min-rec and max-rec properties of the node." [node ks] (insist (leaf-node? node)) (update-min-max (reduce node-dissoc node ks))) (defn reset-messages ;; TODO: This could be done much more efficiently. "Removes all of the messages from the node's buffer and re-adds them. To be used when the node's internal cap keys have been altered to keep the message buffers in sync." [node] (let [buffer (messages node) msgs (mapcat val buffer)] (add-messages (messages node (empty buffer)) msgs)))
null
https://raw.githubusercontent.com/Workiva/eva/b7b8a6a5215cccb507a92aa67e0168dc777ffeac/dev/src/eva/datastructures/test_version/logic/nodes.clj
clojure
Licensed under the Eclipse Public License 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at -1.0.php 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. Important Legal Note. In the standard implementation, if a node has n children, it has n-1 pivots, interposed. But in our implementation, we use "cap" keys. With n children, we have n caps. These are arranged such that all caps to the "left" of a given cap C correspond to children whose subdictionaries contain only keys strictly less than C. The important legal bit: Before changing the organization scheme for the internal keys (e.g., to more closely match the canonical B-tree as described in literature, The following record is never used as anything other than a map. My understanding is that the defined fields will have faster access times. That's all. universal properties for nodes other properties sometimes used: * ROOT ONLY: :semantics, :node-counter * POINTER ONLY: :node-size each new node that is created is assigned a node-id, which persists through node modifications. tx indicates during which sequential operation on the tree the node was last modified. uuid (Maybe String) combines the above with a unique string for safe storage. vvv key-vals should be an AVLMap (currently). TODO: safety checks TODO: safety checks TODO: documentation does NOT match implementation. constant-time: (= true (counted? key-vals)) unsupported: supported: <== ensuring the version of the requested nodes. TODO: uuid? predicate <-- fat leaves optimization happens here why are node-pointers not underflowed? I suppose because then their underflowediness would have been caught. if it's a root but not a leaf and it has a single child, that child should be made root. If it's not a root, check the min-node-size! if internal node, must also check messages queues: TODO: move next child under? TODO: This could be done much more efficiently.
Copyright 2015 - 2019 Workiva Inc. distributed under the License is distributed on an " AS IS " BASIS , (ns eva.datastructures.test-version.logic.nodes (:require [eva.datastructures.test-version.logic.state :as state] [eva.datastructures.test-version.logic.protocols :as protocols :refer :all] [eva.datastructures.protocols :as dsp :refer [interval-overlaps? restrict interval-contains? intersect]] [eva.datastructures.test-version.logic.buffer :as buffer] [eva.datastructures.test-version.logic.message :as message] [eva.v2.datastructures.bbtree.storage :refer [uuid get-nodes get-node put-nodes node-pointer? node?]] [eva.datastructures.versioning :refer [ensure-version]] [eva.datastructures.utils.interval :as interval] [eva.datastructures.utils.comparators :as comparison :refer [UPPER LOWER]] [eva.datastructures.utils.core :refer [fast-last overlaps?]] [utiliva.control :refer [?-> ?->>]] [utiliva.core :refer [piecewise-map partition-map zip-from]] [utiliva.comparator :refer [min max]] [utiliva.alpha :refer [mreduce]] [eva.error :refer [insist]] [plumbing.core :refer [?>]] [clojure.data.avl :as avl] [clojure.core.memoize :as memo] [clojure.math.numeric-tower :refer [ceil floor]]) (:import [clojure.data.avl AVLMap] [clojure.lang RT MapEntry] [eva.v2.datastructures.bbtree.storage NodeStorageInfo] [java.util UUID]) (:refer-clojure :exclude [min max])) In our implementation of the btree structure , we do n't exactly use pivot keys . such as using standard ' pivots ' ) , please contact . (set! *warn-on-reflection* true) (defn new-node-id "Nodes within a tree are identified uniquely by a combination of id and version. Whenever a brand-new node is added to the tree, a new node id is generated sequentially. That's what this method does." [] (insist (some? state/*node-id-counter*) "Cannot create new node id with unbound *node-id-counter*") (swap! state/*node-id-counter* inc)) (defrecord NodeProperties (defn empty-properties "Selects from properties the keys #{:comparator :order :leaf? :buffer-size} then merges {:root? false} and returns the result." [props] (map->NodeProperties (assoc (select-keys props [:comparator :order :leaf? :buffer-size]) :root? false))) (defrecord BufferedBTreeNode properties : { : order o , : root ? # t , : leaf ? # f , : min - rec m , : etc etc } dsp/Versioned (get-version [_] VERSION) NodeStorageInfo (uuid [this] uuid) (node? [_] true) (node-pointer? [_] false) protocols/IBufferedBTreeNode (node-id [this] node-id) (new-node-from [this] (assoc (node-empty this) :node-id (new-node-id) :tx state/*transaction-id* :uuid nil)) (BufferedBTreeNode. nil node-id tx (empty buffer) (empty key-vals) (empty-properties properties))) (node-conj [this kv] (insist (not (nil? (val kv)))) (node-assoc this (key kv) (val kv))) (node-assoc [this k v] (insist (not (nil? v))) (let [tmp (BufferedBTreeNode. nil node-id tx buffer (assoc key-vals k v) properties)] (-> tmp (min-rec (partial min (node-comparator this)) (if (leaf-node? tmp) k (min-rec v))) (max-rec (partial max (node-comparator this)) (if (leaf-node? tmp) k (max-rec v)))))) (node-dissoc [this k] (BufferedBTreeNode. nil node-id tx buffer (dissoc key-vals k) properties)) (node-get [this k] (get key-vals k)) (buffer-dissoc [this k] (BufferedBTreeNode. nil node-id tx (dissoc buffer k) key-vals properties)) (children [this] key-vals) (children [this m] (BufferedBTreeNode. nil node-id tx buffer m properties)) (children [this f v] (BufferedBTreeNode. nil node-id tx buffer (f key-vals v) properties)) (messages [this] buffer) (messages [this messages] (BufferedBTreeNode. nil node-id tx messages key-vals properties)) (messages [this f v] (BufferedBTreeNode. nil node-id tx (f buffer v) key-vals properties)) (node-key-for [this k] (if (leaf-node? this) k (if-let [above-thing (avl/nearest key-vals > k)] (key above-thing) (key (fast-last key-vals))))) (leaf-node? [this] (get properties :leaf?)) (mark-leaf [this b] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :leaf? (boolean b)))) (inner-node? [this] (not (leaf-node? this))) (root-node? [this] (get properties :root?)) (mark-root [this b] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :root? (boolean b)))) (properties [this] properties) (node-comparator [this] (get properties :comparator)) (node-order [this] (get properties :order)) (buffer-size [this] (get properties :buffer-size)) (max-rec [this] (get properties :max-rec)) (max-rec [this v] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :max-rec v))) (max-rec [this f v] (BufferedBTreeNode. nil node-id tx buffer key-vals (update properties :max-rec (fnil f LOWER) v))) (min-rec [this] (get properties :min-rec)) (min-rec [this v] (BufferedBTreeNode. nil node-id tx buffer key-vals (assoc properties :min-rec v))) (min-rec [this f v] (BufferedBTreeNode. nil node-id tx buffer key-vals (update properties :min-rec (fnil f UPPER) v))) (transaction-id [this] tx) (transaction-id [this v] (BufferedBTreeNode. nil node-id v buffer key-vals properties))) (defrecord BufferedBTreePointer [uuid node-id tx properties] dsp/Versioned (get-version [_] VERSION) NodeStorageInfo (uuid [this] uuid) (uuid [this k] (throw (IllegalArgumentException. "Cannot modify the uuid of a node pointer."))) (node? [_] false) (node-pointer? [_] true) protocols/IBufferedBTreeNode (node-empty [this] (throw (IllegalArgumentException. "Cannot empty a node pointer."))) (node-assoc [this k v] (throw (IllegalArgumentException. "Cannot assoc to a node pointer."))) (node-dissoc [this k] (throw (IllegalArgumentException. "Cannot dissoc from a node pointer."))) (node-get [this k] (throw (IllegalArgumentException. "Cannot query a node pointer."))) (buffer-dissoc [this k] (throw (IllegalArgumentException. "Cannot dissoc from the buffer of a node pointer."))) (children [this] (throw (IllegalArgumentException. "Cannot get the children of a node pointer."))) (children [this m] (throw (IllegalArgumentException. "Cannot set the children of a node pointer."))) (children [this f v] (throw (IllegalArgumentException. "Cannot update the children of a node pointer."))) (messages [this] (throw (IllegalArgumentException. "Cannot get the buffer of a node pointer."))) (messages [this messages] (throw (IllegalArgumentException. "Cannot set the buffer of a node pointer."))) (messages [this f v] (throw (IllegalArgumentException. "Cannot update the buffer of a node pointer."))) (node-key-for [this k] (throw (IllegalArgumentException. "Cannot examine keys for a node pointer."))) (mark-leaf [this b] (throw (IllegalArgumentException. "Cannot change properties of a node pointer."))) (mark-root [this b] (throw (IllegalArgumentException. "Cannot change properties of a node pointer."))) (node-order [this] (throw (IllegalArgumentException. "Cannot read node order from the pointer."))) (max-rec [this v] (throw (IllegalArgumentException. "Cannot set the max-recursive key of a node pointer."))) (max-rec [this f v] (throw (IllegalArgumentException. "Cannot update the max-recursive key of a node pointer."))) (node-id [this k] (throw (IllegalArgumentException. "Cannot modify the node-id of a node pointer."))) (transaction-id [this k] (throw (IllegalArgumentException. "Cannot modify the transaction-id of a node pointer."))) (node-id [this] node-id) (transaction-id [this] tx) (min-rec [this v] (BufferedBTreePointer. uuid node-id tx (assoc properties :min-rec v))) (min-rec [this f v] (BufferedBTreePointer. uuid node-id tx (update properties :min-rec (fnil f UPPER) v))) (properties [this] (get this :properties)) (node-comparator [this] (get-in this [:properties :comparator])) (leaf-node? [this] (get-in this [:properties :leaf?])) (inner-node? [this] (not (leaf-node? this))) (root-node? [this] (get-in this [:properties :root?])) (node-size [this] (get-in this [:properties :node-size])) (max-rec [this] (get-in this [:properties :max-rec])) (min-rec [this] (get-in this [:properties :min-rec]))) (defn ensure-uuid "Expects, but does not enforce, that maybe-uuid is either nil or a string of (format \"%s-%s-%s\" id tx (UUID/randomUUID)). If maybe-uuid is nil, this returns a new string of that format." [maybe-uuid id tx] (or maybe-uuid (format "%s-%s-%s" id tx (UUID/randomUUID)))) (defn node->pointer [node] (let [property-keys (if (root-node? node) [:leaf? :root? :max-rec :order :min-rec :node-counter :semantics :comparator] [:leaf? :root? :max-rec :order :min-rec :node-counter])] (->BufferedBTreePointer (ensure-uuid (uuid node) (:node-id node) (transaction-id node)) (:node-id node) (transaction-id node) (assoc (select-keys (properties node) property-keys) :node-size (node-size node))))) (defn nodes->pointers [nodes] (map node->pointer nodes)) (defn pointers->nodes [pointers] (insist (some? state/*store*) "pointers->nodes called when *store* is nil.") (->> (get-nodes state/*store* pointers) (defn pointer->node [pointer] (insist (some? state/*store*) "pointer->node called when *store* is nil.") (first (pointers->nodes [pointer]))) TODO : This is a hack and should be ashamed . Edit : This has become even hackier , and should be utterly mortified . "Takes either a pointer or a node id. Returns either that pointer or a minimal implementation of Pointer and Node that will give its uuid." [pointer-thing] (cond (node-pointer? pointer-thing) pointer-thing (satisfies? protocols/IBufferedBTreeNode pointer-thing) (node->pointer pointer-thing) :else (reify NodeStorageInfo (uuid [_] pointer-thing) (node? [_] false) (node-pointer? [_] true) dsp/Versioned (get-version [_] VERSION))))) (defn min-node-size "Minimum size the node can be before considered 'too small'." [node] (ceil (/ (node-order node) 2))) (defn overflowed? [node] (if (leaf-node? node) (> (node-size node) (node-order node)))) (defn buffer-overflowing? [node] (buffer/overflowing? (messages node))) (defn node-valid-size? [node] (<= (min-node-size node) (node-size node) (node-order node))) (defn underflowed? [node] (not (leaf-node? node)) (= (node-size node) 1)) (< (node-size node) (min-node-size node)))))) (defn node-overlaps? "Does this node overlap with this range? Optionally accepts comparator." ([node range] (node-overlaps? (node-comparator node) node range)) ([cmp node [y1 y2]] (overlaps? cmp [(min-rec node) (max-rec node)] [y1 y2]))) (defn node-minrec-above "Takes an internal node and a dictionary key. Returns the min-rec of the next node 'above' that key. Useful for establishing cap keys or sorting messages." ([this k] (node-minrec-above this k true)) ([this k buffer-aware?] (insist (inner-node? this)) (if-let [above-thing (avl/nearest (children this) > k)] (if-not buffer-aware? (min-rec (val above-thing)) (if-let [min-msg (seq (filter (complement ranged?) (get (messages this) (key above-thing))))] (min (node-comparator this) (apply min (node-comparator this) (map recip min-msg)) (min-rec (val above-thing))) (min-rec (val above-thing)))) UPPER))) (defn node-minrec-above-buffer-unaware [this k] (node-minrec-above this k false)) (defn left-most-key? [node k] (= k (key (first (children node))))) (defn right-most-key? [node k] (= k (key (last (children node))))) (defn update-min-max [node] (if (leaf-node? node) (-> node (min-rec (key (first (children node)))) (max-rec (key (fast-last (children node))))) (if (empty? (children node)) node (let [min-rec-child (-> node children first val min-rec) max-rec-child (-> node children fast-last val max-rec) TODO : clunky ! ! ! min / max-rec-msg (buffer/max-recip (partial max (node-comparator node)) (messages node))] (-> node (min-rec (if min-rec-msg (min (node-comparator node) min-rec-child min-rec-msg) min-rec-child)) (max-rec (if max-rec-msg (max (node-comparator node) max-rec-child max-rec-msg) max-rec-child))))))) (defn apply-messages "Applies message operations. Valid ops and their implementations are defined in the message namespace." [node msgs] (insist (leaf-node? node)) (as-> (transaction-id node state/*transaction-id*) node (children node (reduce #(apply-message %2 (node-comparator node) %) (children node) msgs)) (if (pos? (node-size node)) (-> node (min-rec (key (first (children node)))) (max-rec (key (last (children node))))) node))) (defn min-rec-buffer-aware "Finds the min-rec of the child, taking into account messages currently sitting in the buffer to be delivered to that child." [node k child] (if-let [msgs (seq (remove ranged? (get (messages node) k)))] (let [min (partial min (node-comparator node))] (min (apply min (map recip msgs)) (min-rec child))) (min-rec child))) (defn make-child->msgs [node messages] (let [kids (children node)] (persistent! (reduce (fn [child-map message] (if (ranged? message) (let [selection (avl/subrange kids >= (node-key-for node (dsp/low (recip message))) <= (node-key-for node (dsp/high (recip message))))] (reduce #(assoc! % %2 (conj (get % %2 []) message)) child-map (vals selection))) (let [k (node-key-for node (recip message)) child (get kids k)] (assoc! child-map child (conj (get child-map child []) message))))) (transient {}) messages)))) (defn- simply-add-ranged-message* [node msg] (let [slice (avl/subrange (children node) >= (node-key-for node (dsp/low (recip msg))) <= (node-key-for node (dsp/high (recip msg))))] (reduce (fn [node [key msg]] (messages node (buffer/insert (messages node) key msg))) node (for [[k child] slice :let [min-rec* (min-rec child)] :when (interval-overlaps? (recip msg) (node-comparator node) min-rec* k)] [k (assoc msg :target (intersect (recip msg) (node-comparator node) (interval/interval min-rec* k false true)))])))) (defn add-ranged-message "Adds a ranged message to all appropriate message buffers in the node. No updates are made to min- or max-rec." [node msg] (simply-add-ranged-message* node msg)) (defn add-simple-message "Add a single message to a node's message buffer. Updates min- and max-rec accordingly." [node msg] (let [k (node-key-for node (recip msg)) node (-> node (messages (buffer/insert ^buffer/BTreeBuffer (messages node) k msg)) (min-rec (partial min (node-comparator node)) (recip msg)) (max-rec (partial max (node-comparator node)) (recip msg)))] (if (= :upsert (op msg)) (children node (update kvs k min-rec (partial min (node-comparator node)) target)) (recip msg)) node))) (defn add-messages "Adds many messages to a node's message buffer. Updates min- and max-rec accordingly." [node msgs] (if (leaf-node? node) (apply-messages node msgs) (let [node (transaction-id node state/*transaction-id*) add-fn (fn [node msg] (if (ranged? msg) (add-ranged-message node msg) (add-simple-message node msg)))] (reduce add-fn node msgs)))) (defn transfer-messages "Adds messages to the buffer of a node when you already know which keys the messages should correspond to. Does nothing to the node's min-rec or max-rec values." [node ks->msgs] (messages node (fn [buffer ks->msgs] (reduce (fn [buffer [k msgs]] (reduce #(buffer/insert % k %2) buffer msgs)) buffer ks->msgs)) ks->msgs)) (defn add-child "Adds a child to an internal node. Meant to be used when creating a node or when 'swapping' children. You should always add children in reverse sorted order. The flag 'buffer-aware?' indicates whether to take the message buffers into account when assigning local cap keys for the child." ([node child] (add-child node child true)) ([node child buffer-aware?] (insist (inner-node? node)) (let [k (node-minrec-above node (max-rec child) buffer-aware?) node (node-assoc node k child)] (?-> node (left-most-key? k) (min-rec (min-rec child)) (right-most-key? k) (max-rec (max-rec child)))))) (defn add-child-buffer-unaware [node child] (add-child node child false)) (defn add-children "Takes a node and a map nodes->msgs to add. Ensures min- and max-rec are up-to-date." [node adopted->msgs] (let [kids (vals (children node)) kids->msgs (sequence (comp (map #(get (messages node) %)) (zip-from kids)) (keys (children node))) nodes->msgs (sort-by (comp min-rec key) (node-comparator node) (concat adopted->msgs kids->msgs)) ks (conj (vec (rest (map min-rec (keys nodes->msgs)))) UPPER)] (as-> (node-empty node) node (reduce node-conj node (zipmap ks (keys nodes->msgs))) (transfer-messages node (zipmap ks (vals nodes->msgs))) (update-min-max node)))) (defn remove-children "Takes an inner node and a simple sequence of keys. Removes children bound to those keys, along with any messages intended for those children. Updates min- and max-rec accordingly." [node ks] (insist (inner-node? node)) (let [kids (vals (for [kv (children node) :when (every? #(not= (key kv) %) ks)] kv)) new-ks (conj (vec (rest (map min-rec kids))) UPPER) msgs (buffer/get-all (reduce #(dissoc % %2) (messages node) ks))] (as-> (node-empty node) node (reduce node-conj node (zipmap new-ks kids)) (add-messages node msgs) (update-min-max node)))) (defn remove-values "Takes a leaf node and a simple sequence of keys. Removes the values stored by those keys. Once it is finished, it updates the min-rec and max-rec properties of the node." [node ks] (insist (leaf-node? node)) (update-min-max (reduce node-dissoc node ks))) "Removes all of the messages from the node's buffer and re-adds them. To be used when the node's internal cap keys have been altered to keep the message buffers in sync." [node] (let [buffer (messages node) msgs (mapcat val buffer)] (add-messages (messages node (empty buffer)) msgs)))
29fd73167bb5902a9a0d8d88e4e1ad06004f8dd6c846b88f4a4a7cc0bfaa49de
clojure-interop/aws-api
core.clj
(ns core (:refer-clojure :only [require comment defn ->]) (:import )) (require '[com.amazonaws.services.servermigration.core])
null
https://raw.githubusercontent.com/clojure-interop/aws-api/59249b43d3bfaff0a79f5f4f8b7bc22518a3bf14/com.amazonaws.services.servermigration/src/core.clj
clojure
(ns core (:refer-clojure :only [require comment defn ->]) (:import )) (require '[com.amazonaws.services.servermigration.core])
7aadae359cb685823bc5e4a86e7074ef1f76bc81aee07d812b37eaa8468b2aee
silkapp/girella
HLint.hs
module HLint.HLint where import "hint" HLint.Default import "hint" HLint.Builtin.All import "hint" HLint.Dollar import " hint " HLint . warn = return ==> pure warn = (>>) ==> (*>) warn = liftIO . atomically ==> atomicallyIO
null
https://raw.githubusercontent.com/silkapp/girella/f2fbbaaa2536f1afc5bc1a493d02f92cec81da18/HLint.hs
haskell
module HLint.HLint where import "hint" HLint.Default import "hint" HLint.Builtin.All import "hint" HLint.Dollar import " hint " HLint . warn = return ==> pure warn = (>>) ==> (*>) warn = liftIO . atomically ==> atomicallyIO
93e25948f21053b9aacb793bed2aff9841e5f8f19ddadad7f510443426ec5c81
vincenthz/hs-asn1
Tests.hs
import Test.QuickCheck import Test.Framework(defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2(testProperty) import Text.Printf import Data.Serialize.Put (runPut) import Data.ASN1.Get (runGet, Result(..)) import Data.ASN1.BitArray import Data.ASN1.Stream (ASN1(..), ASN1ConstructionType(..)) import Data.ASN1.Prim import Data.ASN1.Serialize import Data.ASN1.BinaryEncoding.Parse import Data.ASN1.BinaryEncoding.Writer import Data.ASN1.BinaryEncoding import Data.ASN1.Encoding import Data.ASN1.Types import Data.Word import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.Text.Lazy as T import Control.Monad import Control.Monad.Identity import System.IO instance Arbitrary ASN1Class where arbitrary = elements [ Universal, Application, Context, Private ] instance Arbitrary ASN1Length where arbitrary = do c <- choose (0,2) :: Gen Int case c of 0 -> liftM LenShort (choose (0,0x79)) 1 -> do nb <- choose (0x80,0x1000) return $ mkSmallestLength nb _ -> return LenIndefinite where nbBytes nb = if nb > 255 then 1 + nbBytes (nb `div` 256) else 1 arbitraryDefiniteLength :: Gen ASN1Length arbitraryDefiniteLength = arbitrary `suchThat` (\l -> l /= LenIndefinite) arbitraryTag :: Gen ASN1Tag arbitraryTag = choose(1,10000) instance Arbitrary ASN1Header where arbitrary = liftM4 ASN1Header arbitrary arbitraryTag arbitrary arbitrary arbitraryEvents :: Gen ASN1Events arbitraryEvents = do hdr@(ASN1Header _ _ _ len) <- liftM4 ASN1Header arbitrary arbitraryTag (return False) arbitraryDefiniteLength let blen = case len of LenLong _ x -> x LenShort x -> x _ -> 0 pr <- liftM Primitive (arbitraryBSsized blen) return (ASN1Events [Header hdr, pr]) newtype ASN1Events = ASN1Events [ASN1Event] instance Show ASN1Events where show (ASN1Events x) = show x instance Arbitrary ASN1Events where arbitrary = arbitraryEvents arbitraryOID :: Gen [Integer] arbitraryOID = do i1 <- choose (0,2) :: Gen Integer i2 <- choose (0,39) :: Gen Integer ran <- choose (0,30) :: Gen Int l <- replicateM ran (suchThat arbitrary (\i -> i > 0)) return (i1:i2:l) arbitraryBSsized :: Int -> Gen B.ByteString arbitraryBSsized len = do ws <- replicateM len (choose (0, 255) :: Gen Int) return $ B.pack $ map fromIntegral ws instance Arbitrary B.ByteString where arbitrary = do len <- choose (0, 529) :: Gen Int arbitraryBSsized len instance Arbitrary L.ByteString where arbitrary = do len <- choose (0, 529) :: Gen Int ws <- replicateM len (choose (0, 255) :: Gen Int) return $ L.pack $ map fromIntegral ws instance Arbitrary T.Text where arbitrary = do len <- choose (0, 529) :: Gen Int ws <- replicateM len arbitrary return $ T.pack ws instance Arbitrary BitArray where arbitrary = do bs <- arbitrary w < - choose ( 0,7 ) : : Gen Int return $ toBitArray bs 0 arbitraryTime = do y <- choose (1951, 2050) m <- choose (0, 11) d <- choose (0, 31) h <- choose (0, 23) mi <- choose (0, 59) se <- choose (0, 59) z <- arbitrary return (y,m,d,h,mi,se,z) arbitraryPrintString = do let printableString = (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ " ()+,-./:=?") x <- replicateM 21 (elements printableString) return $ x arbitraryIA5String = do x <- replicateM 21 (elements $ map toEnum [0..127]) return $ x instance Arbitrary ASN1 where arbitrary = oneof [ liftM Boolean arbitrary , liftM IntVal arbitrary , liftM BitString arbitrary , liftM OctetString arbitrary , return Null , liftM OID arbitraryOID --, Real Double -- , return Enumerated , liftM UTF8String arbitrary , liftM NumericString arbitrary , liftM PrintableString arbitraryPrintString , liftM T61String arbitraryIA5String , liftM VideoTexString arbitrary , liftM IA5String arbitraryIA5String , liftM UTCTime arbitraryTime , liftM GeneralizedTime arbitraryTime , liftM GraphicString arbitrary , liftM VisibleString arbitrary , liftM GeneralString arbitrary , liftM BMPString arbitrary , liftM UniversalString arbitrary ] newtype ASN1s = ASN1s [ASN1] instance Show ASN1s where show (ASN1s x) = show x instance Arbitrary ASN1s where arbitrary = do x <- choose (0,5) :: Gen Int z <- case x of 4 -> makeList Sequence 3 -> makeList Set _ -> resize 2 $ listOf1 arbitrary return $ ASN1s z where makeList str = do (ASN1s l) <- arbitrary return ([Start str] ++ l ++ [End str]) prop_header_marshalling_id :: ASN1Header -> Bool prop_header_marshalling_id v = (ofDone $ runGet getHeader $ runPut (putHeader v)) == Right v where ofDone (Done r _ _) = Right r ofDone _ = Left "not done" prop_event_marshalling_id :: ASN1Events -> Bool prop_event_marshalling_id (ASN1Events e) = (parseLBS $ toLazyByteString e) == Right e prop_asn1_der_marshalling_id v = (decodeASN1 DER . encodeASN1 DER) v == Right v marshallingTests = testGroup "Marshalling" [ testProperty "Header" prop_header_marshalling_id , testProperty "Event" prop_event_marshalling_id , testProperty "DER" prop_asn1_der_marshalling_id ] main = defaultMain [marshallingTests]
null
https://raw.githubusercontent.com/vincenthz/hs-asn1/c017c03b0f71a3b45165468a1d1028a0ed7502c0/data/Tests.hs
haskell
, Real Double , return Enumerated
import Test.QuickCheck import Test.Framework(defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2(testProperty) import Text.Printf import Data.Serialize.Put (runPut) import Data.ASN1.Get (runGet, Result(..)) import Data.ASN1.BitArray import Data.ASN1.Stream (ASN1(..), ASN1ConstructionType(..)) import Data.ASN1.Prim import Data.ASN1.Serialize import Data.ASN1.BinaryEncoding.Parse import Data.ASN1.BinaryEncoding.Writer import Data.ASN1.BinaryEncoding import Data.ASN1.Encoding import Data.ASN1.Types import Data.Word import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.Text.Lazy as T import Control.Monad import Control.Monad.Identity import System.IO instance Arbitrary ASN1Class where arbitrary = elements [ Universal, Application, Context, Private ] instance Arbitrary ASN1Length where arbitrary = do c <- choose (0,2) :: Gen Int case c of 0 -> liftM LenShort (choose (0,0x79)) 1 -> do nb <- choose (0x80,0x1000) return $ mkSmallestLength nb _ -> return LenIndefinite where nbBytes nb = if nb > 255 then 1 + nbBytes (nb `div` 256) else 1 arbitraryDefiniteLength :: Gen ASN1Length arbitraryDefiniteLength = arbitrary `suchThat` (\l -> l /= LenIndefinite) arbitraryTag :: Gen ASN1Tag arbitraryTag = choose(1,10000) instance Arbitrary ASN1Header where arbitrary = liftM4 ASN1Header arbitrary arbitraryTag arbitrary arbitrary arbitraryEvents :: Gen ASN1Events arbitraryEvents = do hdr@(ASN1Header _ _ _ len) <- liftM4 ASN1Header arbitrary arbitraryTag (return False) arbitraryDefiniteLength let blen = case len of LenLong _ x -> x LenShort x -> x _ -> 0 pr <- liftM Primitive (arbitraryBSsized blen) return (ASN1Events [Header hdr, pr]) newtype ASN1Events = ASN1Events [ASN1Event] instance Show ASN1Events where show (ASN1Events x) = show x instance Arbitrary ASN1Events where arbitrary = arbitraryEvents arbitraryOID :: Gen [Integer] arbitraryOID = do i1 <- choose (0,2) :: Gen Integer i2 <- choose (0,39) :: Gen Integer ran <- choose (0,30) :: Gen Int l <- replicateM ran (suchThat arbitrary (\i -> i > 0)) return (i1:i2:l) arbitraryBSsized :: Int -> Gen B.ByteString arbitraryBSsized len = do ws <- replicateM len (choose (0, 255) :: Gen Int) return $ B.pack $ map fromIntegral ws instance Arbitrary B.ByteString where arbitrary = do len <- choose (0, 529) :: Gen Int arbitraryBSsized len instance Arbitrary L.ByteString where arbitrary = do len <- choose (0, 529) :: Gen Int ws <- replicateM len (choose (0, 255) :: Gen Int) return $ L.pack $ map fromIntegral ws instance Arbitrary T.Text where arbitrary = do len <- choose (0, 529) :: Gen Int ws <- replicateM len arbitrary return $ T.pack ws instance Arbitrary BitArray where arbitrary = do bs <- arbitrary w < - choose ( 0,7 ) : : Gen Int return $ toBitArray bs 0 arbitraryTime = do y <- choose (1951, 2050) m <- choose (0, 11) d <- choose (0, 31) h <- choose (0, 23) mi <- choose (0, 59) se <- choose (0, 59) z <- arbitrary return (y,m,d,h,mi,se,z) arbitraryPrintString = do let printableString = (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ " ()+,-./:=?") x <- replicateM 21 (elements printableString) return $ x arbitraryIA5String = do x <- replicateM 21 (elements $ map toEnum [0..127]) return $ x instance Arbitrary ASN1 where arbitrary = oneof [ liftM Boolean arbitrary , liftM IntVal arbitrary , liftM BitString arbitrary , liftM OctetString arbitrary , return Null , liftM OID arbitraryOID , liftM UTF8String arbitrary , liftM NumericString arbitrary , liftM PrintableString arbitraryPrintString , liftM T61String arbitraryIA5String , liftM VideoTexString arbitrary , liftM IA5String arbitraryIA5String , liftM UTCTime arbitraryTime , liftM GeneralizedTime arbitraryTime , liftM GraphicString arbitrary , liftM VisibleString arbitrary , liftM GeneralString arbitrary , liftM BMPString arbitrary , liftM UniversalString arbitrary ] newtype ASN1s = ASN1s [ASN1] instance Show ASN1s where show (ASN1s x) = show x instance Arbitrary ASN1s where arbitrary = do x <- choose (0,5) :: Gen Int z <- case x of 4 -> makeList Sequence 3 -> makeList Set _ -> resize 2 $ listOf1 arbitrary return $ ASN1s z where makeList str = do (ASN1s l) <- arbitrary return ([Start str] ++ l ++ [End str]) prop_header_marshalling_id :: ASN1Header -> Bool prop_header_marshalling_id v = (ofDone $ runGet getHeader $ runPut (putHeader v)) == Right v where ofDone (Done r _ _) = Right r ofDone _ = Left "not done" prop_event_marshalling_id :: ASN1Events -> Bool prop_event_marshalling_id (ASN1Events e) = (parseLBS $ toLazyByteString e) == Right e prop_asn1_der_marshalling_id v = (decodeASN1 DER . encodeASN1 DER) v == Right v marshallingTests = testGroup "Marshalling" [ testProperty "Header" prop_header_marshalling_id , testProperty "Event" prop_event_marshalling_id , testProperty "DER" prop_asn1_der_marshalling_id ] main = defaultMain [marshallingTests]
56a986f43903c824d80940edabcdcf57d0148bae58fa62a96106fd76d802d723
evolutics/haskell-formatter
Input.hs
commented = commented -- ^ comment
null
https://raw.githubusercontent.com/evolutics/haskell-formatter/3919428e312db62b305de4dd1c84887e6cfa9478/testsuite/resources/source/comments/empty_lines/between_declaration_and_comment/after/2/Input.hs
haskell
^ comment
commented = commented
4a6e0b9e70a9a87c6fac0c0de56f987799522d68428373f1acf1c2c5174a82bc
herd/herdtools7
StringSet.ml
(****************************************************************************) (* the diy toolsuite *) (* *) , University College London , UK . , INRIA Paris - Rocquencourt , France . (* *) Copyright 2015 - present Institut National de Recherche en Informatique et (* en Automatique and the authors. All rights reserved. *) (* *) This software is governed by the CeCILL - B license under French law and (* abiding by the rules of distribution of free software. You can use, *) modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . (****************************************************************************) include MySet.Make(String) let pp_id sep t = pp_str sep Misc.identity t
null
https://raw.githubusercontent.com/herd/herdtools7/b86aec8db64f8812e19468893deb1cdf5bbcfb83/lib/StringSet.ml
ocaml
************************************************************************** the diy toolsuite en Automatique and the authors. All rights reserved. abiding by the rules of distribution of free software. You can use, **************************************************************************
, University College London , UK . , INRIA Paris - Rocquencourt , France . Copyright 2015 - present Institut National de Recherche en Informatique et This software is governed by the CeCILL - B license under French law and modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . include MySet.Make(String) let pp_id sep t = pp_str sep Misc.identity t
962b37807453ab8a84663c4cb96067ab7bf81afb3d0bacb8c99c1ff57204a449
patricoferris/ocaml-multicore-monorepo
baijiu_keccak_256.ml
module By = Digestif_by module Bi = Digestif_bi module type S = sig type ctx type kind = [ `SHA3_256 ] val init : unit -> ctx val unsafe_feed_bytes : ctx -> By.t -> int -> int -> unit val unsafe_feed_bigstring : ctx -> Bi.t -> int -> int -> unit val unsafe_get : ctx -> By.t val dup : ctx -> ctx end module Unsafe : S = struct type kind = [ `SHA3_256 ] module U = Baijiu_sha3.Unsafe (struct let padding = Baijiu_sha3.keccak_padding end) open U type nonrec ctx = ctx let init () = U.init 32 let unsafe_get = unsafe_get let dup = dup let unsafe_feed_bytes = unsafe_feed_bytes let unsafe_feed_bigstring = unsafe_feed_bigstring end
null
https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/digestif/src-ocaml/baijiu_keccak_256.ml
ocaml
module By = Digestif_by module Bi = Digestif_bi module type S = sig type ctx type kind = [ `SHA3_256 ] val init : unit -> ctx val unsafe_feed_bytes : ctx -> By.t -> int -> int -> unit val unsafe_feed_bigstring : ctx -> Bi.t -> int -> int -> unit val unsafe_get : ctx -> By.t val dup : ctx -> ctx end module Unsafe : S = struct type kind = [ `SHA3_256 ] module U = Baijiu_sha3.Unsafe (struct let padding = Baijiu_sha3.keccak_padding end) open U type nonrec ctx = ctx let init () = U.init 32 let unsafe_get = unsafe_get let dup = dup let unsafe_feed_bytes = unsafe_feed_bytes let unsafe_feed_bigstring = unsafe_feed_bigstring end
9a18b52458cf9fe8589b8f0ab96ad8654c026941d16bb8817990f8ab42a6470d
airalab/hs-web3
Compact.hs
-- | -- Module : Codec.Scale.Compact Copyright : 2016 - 2021 -- License : Apache-2.0 -- -- Maintainer : -- Stability : experimental -- Portability : noportable -- -- Efficient general integer codec. -- module Codec.Scale.Compact (Compact(..)) where import Control.Monad (replicateM) import Data.Bits (shiftL, shiftR, (.&.), (.|.)) import Data.List (unfoldr) import Data.Serialize.Get (getWord16le, getWord32le, getWord8, lookAhead) import Data.Serialize.Put (putWord16le, putWord32le, putWord8) import Codec.Scale.Class (Decode (..), Encode (..)) -- | A "compact" or general integer encoding is sufficient for encoding large integers ( up to 2**536 ) and is more efficient at encoding most -- values than the fixed-width version. newtype Compact a = Compact { unCompact :: a } deriving (Eq, Ord) instance Show a => Show (Compact a) where show = ("Compact " ++) . show . unCompact instance Integral a => Encode (Compact a) where put (Compact x) | n < 0 = error "negatives not supported by compact codec" | n < 64 = singleByteMode | n < 2^14 = twoByteMode | n < 2^30 = fourByteMode | n < 2^536 = bigIntegerMode | otherwise = error $ "unable to encode " ++ show n ++ " as compact" where n = toInteger x singleByteMode = putWord8 (fromIntegral x `shiftL` 2) twoByteMode = putWord16le (fromIntegral x `shiftL` 2 .|. 1) fourByteMode = putWord32le (fromIntegral x `shiftL` 2 .|. 2) bigIntegerMode = do let step 0 = Nothing step i = Just (fromIntegral i, i `shiftR` 8) unroll = unfoldr step n putWord8 (fromIntegral (length unroll - 4) `shiftL` 2 .|. 3) mapM_ putWord8 unroll instance Integral a => Decode (Compact a) where get = do mode <- lookAhead ((3 .&.) <$> getWord8) Compact <$> case mode of 0 -> fromIntegral <$> singleByteMode 1 -> fromIntegral <$> twoByteMode 2 -> fromIntegral <$> fourByteMode 3 -> bigIntegerMode _ -> fail "unexpected prefix decoding compact number" where singleByteMode = flip shiftR 2 <$> getWord8 twoByteMode = flip shiftR 2 <$> getWord16le fourByteMode = flip shiftR 2 <$> getWord32le bigIntegerMode = do let unstep b a = a `shiftL` 8 .|. fromIntegral b roll = fromInteger . foldr unstep 0 len <- ((+4) . flip shiftR 2) <$> getWord8 roll <$> replicateM (fromIntegral len) getWord8
null
https://raw.githubusercontent.com/airalab/hs-web3/01926d3db4f4c83ecd9fc15bc4ce5bfa5c656c02/packages/scale/src/Codec/Scale/Compact.hs
haskell
| Module : Codec.Scale.Compact License : Apache-2.0 Maintainer : Stability : experimental Portability : noportable Efficient general integer codec. | A "compact" or general integer encoding is sufficient for encoding values than the fixed-width version.
Copyright : 2016 - 2021 module Codec.Scale.Compact (Compact(..)) where import Control.Monad (replicateM) import Data.Bits (shiftL, shiftR, (.&.), (.|.)) import Data.List (unfoldr) import Data.Serialize.Get (getWord16le, getWord32le, getWord8, lookAhead) import Data.Serialize.Put (putWord16le, putWord32le, putWord8) import Codec.Scale.Class (Decode (..), Encode (..)) large integers ( up to 2**536 ) and is more efficient at encoding most newtype Compact a = Compact { unCompact :: a } deriving (Eq, Ord) instance Show a => Show (Compact a) where show = ("Compact " ++) . show . unCompact instance Integral a => Encode (Compact a) where put (Compact x) | n < 0 = error "negatives not supported by compact codec" | n < 64 = singleByteMode | n < 2^14 = twoByteMode | n < 2^30 = fourByteMode | n < 2^536 = bigIntegerMode | otherwise = error $ "unable to encode " ++ show n ++ " as compact" where n = toInteger x singleByteMode = putWord8 (fromIntegral x `shiftL` 2) twoByteMode = putWord16le (fromIntegral x `shiftL` 2 .|. 1) fourByteMode = putWord32le (fromIntegral x `shiftL` 2 .|. 2) bigIntegerMode = do let step 0 = Nothing step i = Just (fromIntegral i, i `shiftR` 8) unroll = unfoldr step n putWord8 (fromIntegral (length unroll - 4) `shiftL` 2 .|. 3) mapM_ putWord8 unroll instance Integral a => Decode (Compact a) where get = do mode <- lookAhead ((3 .&.) <$> getWord8) Compact <$> case mode of 0 -> fromIntegral <$> singleByteMode 1 -> fromIntegral <$> twoByteMode 2 -> fromIntegral <$> fourByteMode 3 -> bigIntegerMode _ -> fail "unexpected prefix decoding compact number" where singleByteMode = flip shiftR 2 <$> getWord8 twoByteMode = flip shiftR 2 <$> getWord16le fourByteMode = flip shiftR 2 <$> getWord32le bigIntegerMode = do let unstep b a = a `shiftL` 8 .|. fromIntegral b roll = fromInteger . foldr unstep 0 len <- ((+4) . flip shiftR 2) <$> getWord8 roll <$> replicateM (fromIntegral len) getWord8
56b9c4697631ecfed5cd64ddc340b8a428c0c025ca32d3992431c42eca6a7563
kahua/Gauche-dbd-pg
pg.scm
;;; dbd.pg - PostgreSQL driver ;;; Copyright ( c ) 2003 - 2005 Scheme Arts , L.L.C. , All rights reserved . Copyright ( c ) 2003 - 2005 Time Intermedia Corporation , All rights reserved . ;;; See COPYING for terms and conditions of using this software ;;; (define-module dbd.pg (use dbi) (use gauche.mop.singleton) (use gauche.sequence) (use scheme.list) (export <pg-driver> <pg-connection> <pg-result-set> <pg-row> ;; low-level stuff <pg-conn> <pg-result> pg-connection-handle pq-connectdb pq-finish pq-reset pq-db pq-user pq-pass pq-host pq-port pq-tty pq-options pq-status pq-error-message pq-backend-pid pq-exec pq-result-status pq-res-status pq-result-error-message pq-ntuples pq-nfields pq-fname pq-fnumber pq-ftype pq-fsize pq-fmod pq-binary-tuples pq-getvalue pq-getisnull pq-cmd-status pq-cmd-tuples pq-oid-status pq-clear pq-trace pq-untrace pq-set-notice-processor pq-finished? pq-cleared? pq-escape-string PGRES_EMPTY_QUERY PGRES_COMMAND_OK PGRES_TUPLES_OK PGRES_COPY_OUT PGRES_COPY_IN PGRES_COPY_IN PGRES_NONFATAL_ERROR PGRES_FATAL_ERROR PGRES_COPY_BOTH PGRES_SINGLE_TUPLE pq-send-query pq-set-single-row-mode pq-get-result pq-get-cancel pq-cancel )) (select-module dbd.pg) ;; Loads extension (dynamic-load "dbd--pg") (define-class <pg-driver> (<dbi-driver> <singleton-mixin>) ()) (define-class <pg-connection> (<dbi-connection>) ((%handle :init-keyword :handle :init-value #f))) (define (pg-connection-handle conn) ;public accessor (assume-type conn <pg-connection>) (~ conn'%handle)) (define-class <pg-result-set> (<relation> <sequence>) ((%pg-result :init-keyword :pg-result) (%status :init-keyword :status) (%error :init-keyword :error) (%num-rows :init-keyword :num-rows) (%columns :init-value #f) (num-cols :getter dbi-column-count :init-keyword :num-cols) )) (define-class <pg-row> (<sequence>) ((%result-set :init-keyword :result-set) (%row-id :init-keyword :row-id))) ;; (define-method dbi-make-connection ((d <pg-driver>) (options <string>) (option-alist <list>) . args) (define (build-option-string) (string-join (map (lambda (p) (format "~a='~a'" (car p) (regexp-replace-all #/'/ (cdr p) "\\'"))) (all-options)))) (define (all-options) (append (cond-list ((get-keyword :username args #f) => (cut cons 'user <>)) ((get-keyword :password args #f) => (cut cons 'password <>))) option-alist)) (let* ((conn (make <pg-connection> :driver-name d :open #t :handle (pq-connectdb (build-option-string)))) (status (pq-status (ref conn '%handle)))) (when (eq? status CONNECTION_BAD) (error <dbi-error> "PostgreSQL connect Error:" (pq-error-message (ref conn '%handle)))) conn)) (define (pg-connection-check c) (when (pq-finished? (slot-ref c '%handle)) (error <dbi-error> "closed connection:" c))) ;; Postgres has prepared statement feature. Eventually we're going to use it , but for now , we use Gauche 's default preparation routine . (define-method dbi-execute-using-connection ((c <pg-connection>) (q <dbi-query>) params) (pg-connection-check c) (let* ((h (slot-ref c '%handle)) (prepared (slot-ref q 'prepared)) (result (pq-exec h (apply prepared params))) (status (pq-result-status result))) (when (memv status `(,PGRES_NONFATAL_ERROR ,PGRES_FATAL_ERROR)) (error <dbi-error> (pq-result-error-message result))) (make <pg-result-set> :pg-result result :status status :error error :num-rows (pq-ntuples result) :num-cols (pq-nfields result)))) (define (pg-result-set-check r) (when (pq-cleared? (slot-ref r '%pg-result)) (error <dbi-error> "closed result set:" r))) (define-method dbi-escape-sql ((c <pg-connection>) str) (pq-escape-string str)) ;; ;; Relation API ;; (define-method relation-column-names ((r <pg-result-set>)) (pg-result-set-check r) (or (ref r '%columns) (let1 columns (map (cut pq-fname (slot-ref r '%pg-result) <>) (iota (slot-ref r 'num-cols))) (set! (slot-ref r '%columns) columns) columns))) (define-method relation-accessor ((r <pg-result-set>)) (pg-result-set-check r) (let1 column-names (relation-column-names r) (lambda (row column . maybe-default) (cond ((find-index (cut equal? column <>) column-names) => (lambda (i) (pq-getvalue (slot-ref (slot-ref row '%result-set) '%pg-result) (slot-ref row '%row-id) i))) ((pair? maybe-default) (car maybe-default)) (else (error "pg-result-set: invalid column name:" column)))))) (define-method relation-rows ((r <pg-result-set>)) (coerce-to <list> r)) ;; use call-with-iterator (define-method referencer ((r <pg-result-set>)) (lambda (row ind . fallback) (if (or (< ind 0) (<= (slot-ref r '%num-rows) ind)) (get-optional fallback (error "index out of range:" ind)) (make <pg-row> :result-set r :row-id ind)))) (define-method call-with-iterator ((r <pg-result-set>) proc . option) (pg-result-set-check r) (let ((row-id -1)) (define (end?) (>= (+ row-id 1) (slot-ref r '%num-rows))) (define (next) (inc! row-id) (make <pg-row> :result-set r :row-id row-id)) (proc end? next))) (define-method call-with-iterator ((row <pg-row>) proc . option) (let* ((result (slot-ref row '%result-set)) (num-cols (slot-ref result 'num-cols)) (col-id -1)) (proc (lambda () (>= (+ col-id 1) num-cols)) (lambda () (inc! col-id) (pq-getvalue (slot-ref result '%pg-result) (slot-ref row '%row-id) col-id))))) (define-method referencer ((row <pg-row>)) dbi-get-value) (define-method dbi-get-value ((row <pg-row>) index) (pg-result-set-check (slot-ref row '%result-set)) (pq-getvalue (slot-ref (slot-ref row '%result-set) '%pg-result) (slot-ref row '%row-id) index)) (define-method dbi-open? ((result-set <pg-result-set>)) (not (pq-cleared? (ref result-set '%pg-result)))) (define-method dbi-close ((result-set <pg-result-set>)) (unless (pq-cleared? (ref result-set '%pg-result)) (pq-clear (ref result-set '%pg-result)))) (define-method dbi-open? ((connection <pg-connection>)) (not (pq-finished? (slot-ref connection '%handle)))) (define-method dbi-close ((connection <pg-connection>)) (unless (pq-finished? (slot-ref connection '%handle)) (pq-finish (slot-ref connection '%handle))))
null
https://raw.githubusercontent.com/kahua/Gauche-dbd-pg/2c73feaff511157beeb8a4963be843efb2c60f9f/dbd/pg.scm
scheme
dbd.pg - PostgreSQL driver See COPYING for terms and conditions of using this software low-level stuff Loads extension public accessor Postgres has prepared statement feature. Eventually we're going Relation API use call-with-iterator
Copyright ( c ) 2003 - 2005 Scheme Arts , L.L.C. , All rights reserved . Copyright ( c ) 2003 - 2005 Time Intermedia Corporation , All rights reserved . (define-module dbd.pg (use dbi) (use gauche.mop.singleton) (use gauche.sequence) (use scheme.list) (export <pg-driver> <pg-connection> <pg-result-set> <pg-row> <pg-conn> <pg-result> pg-connection-handle pq-connectdb pq-finish pq-reset pq-db pq-user pq-pass pq-host pq-port pq-tty pq-options pq-status pq-error-message pq-backend-pid pq-exec pq-result-status pq-res-status pq-result-error-message pq-ntuples pq-nfields pq-fname pq-fnumber pq-ftype pq-fsize pq-fmod pq-binary-tuples pq-getvalue pq-getisnull pq-cmd-status pq-cmd-tuples pq-oid-status pq-clear pq-trace pq-untrace pq-set-notice-processor pq-finished? pq-cleared? pq-escape-string PGRES_EMPTY_QUERY PGRES_COMMAND_OK PGRES_TUPLES_OK PGRES_COPY_OUT PGRES_COPY_IN PGRES_COPY_IN PGRES_NONFATAL_ERROR PGRES_FATAL_ERROR PGRES_COPY_BOTH PGRES_SINGLE_TUPLE pq-send-query pq-set-single-row-mode pq-get-result pq-get-cancel pq-cancel )) (select-module dbd.pg) (dynamic-load "dbd--pg") (define-class <pg-driver> (<dbi-driver> <singleton-mixin>) ()) (define-class <pg-connection> (<dbi-connection>) ((%handle :init-keyword :handle :init-value #f))) (assume-type conn <pg-connection>) (~ conn'%handle)) (define-class <pg-result-set> (<relation> <sequence>) ((%pg-result :init-keyword :pg-result) (%status :init-keyword :status) (%error :init-keyword :error) (%num-rows :init-keyword :num-rows) (%columns :init-value #f) (num-cols :getter dbi-column-count :init-keyword :num-cols) )) (define-class <pg-row> (<sequence>) ((%result-set :init-keyword :result-set) (%row-id :init-keyword :row-id))) (define-method dbi-make-connection ((d <pg-driver>) (options <string>) (option-alist <list>) . args) (define (build-option-string) (string-join (map (lambda (p) (format "~a='~a'" (car p) (regexp-replace-all #/'/ (cdr p) "\\'"))) (all-options)))) (define (all-options) (append (cond-list ((get-keyword :username args #f) => (cut cons 'user <>)) ((get-keyword :password args #f) => (cut cons 'password <>))) option-alist)) (let* ((conn (make <pg-connection> :driver-name d :open #t :handle (pq-connectdb (build-option-string)))) (status (pq-status (ref conn '%handle)))) (when (eq? status CONNECTION_BAD) (error <dbi-error> "PostgreSQL connect Error:" (pq-error-message (ref conn '%handle)))) conn)) (define (pg-connection-check c) (when (pq-finished? (slot-ref c '%handle)) (error <dbi-error> "closed connection:" c))) to use it , but for now , we use Gauche 's default preparation routine . (define-method dbi-execute-using-connection ((c <pg-connection>) (q <dbi-query>) params) (pg-connection-check c) (let* ((h (slot-ref c '%handle)) (prepared (slot-ref q 'prepared)) (result (pq-exec h (apply prepared params))) (status (pq-result-status result))) (when (memv status `(,PGRES_NONFATAL_ERROR ,PGRES_FATAL_ERROR)) (error <dbi-error> (pq-result-error-message result))) (make <pg-result-set> :pg-result result :status status :error error :num-rows (pq-ntuples result) :num-cols (pq-nfields result)))) (define (pg-result-set-check r) (when (pq-cleared? (slot-ref r '%pg-result)) (error <dbi-error> "closed result set:" r))) (define-method dbi-escape-sql ((c <pg-connection>) str) (pq-escape-string str)) (define-method relation-column-names ((r <pg-result-set>)) (pg-result-set-check r) (or (ref r '%columns) (let1 columns (map (cut pq-fname (slot-ref r '%pg-result) <>) (iota (slot-ref r 'num-cols))) (set! (slot-ref r '%columns) columns) columns))) (define-method relation-accessor ((r <pg-result-set>)) (pg-result-set-check r) (let1 column-names (relation-column-names r) (lambda (row column . maybe-default) (cond ((find-index (cut equal? column <>) column-names) => (lambda (i) (pq-getvalue (slot-ref (slot-ref row '%result-set) '%pg-result) (slot-ref row '%row-id) i))) ((pair? maybe-default) (car maybe-default)) (else (error "pg-result-set: invalid column name:" column)))))) (define-method relation-rows ((r <pg-result-set>)) (define-method referencer ((r <pg-result-set>)) (lambda (row ind . fallback) (if (or (< ind 0) (<= (slot-ref r '%num-rows) ind)) (get-optional fallback (error "index out of range:" ind)) (make <pg-row> :result-set r :row-id ind)))) (define-method call-with-iterator ((r <pg-result-set>) proc . option) (pg-result-set-check r) (let ((row-id -1)) (define (end?) (>= (+ row-id 1) (slot-ref r '%num-rows))) (define (next) (inc! row-id) (make <pg-row> :result-set r :row-id row-id)) (proc end? next))) (define-method call-with-iterator ((row <pg-row>) proc . option) (let* ((result (slot-ref row '%result-set)) (num-cols (slot-ref result 'num-cols)) (col-id -1)) (proc (lambda () (>= (+ col-id 1) num-cols)) (lambda () (inc! col-id) (pq-getvalue (slot-ref result '%pg-result) (slot-ref row '%row-id) col-id))))) (define-method referencer ((row <pg-row>)) dbi-get-value) (define-method dbi-get-value ((row <pg-row>) index) (pg-result-set-check (slot-ref row '%result-set)) (pq-getvalue (slot-ref (slot-ref row '%result-set) '%pg-result) (slot-ref row '%row-id) index)) (define-method dbi-open? ((result-set <pg-result-set>)) (not (pq-cleared? (ref result-set '%pg-result)))) (define-method dbi-close ((result-set <pg-result-set>)) (unless (pq-cleared? (ref result-set '%pg-result)) (pq-clear (ref result-set '%pg-result)))) (define-method dbi-open? ((connection <pg-connection>)) (not (pq-finished? (slot-ref connection '%handle)))) (define-method dbi-close ((connection <pg-connection>)) (unless (pq-finished? (slot-ref connection '%handle)) (pq-finish (slot-ref connection '%handle))))
829ce903e4735e0b8962660356e4d339058ed56381b76da09ce22d303866db35
sky-big/RabbitMQ
rabbit_federation_link_util.erl
The contents of this file are subject to the Mozilla Public License %% Version 1.1 (the "License"); you may not use this file except in %% compliance with the License. You may obtain a copy of the License %% at / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% The Original Code is RabbitMQ Federation . %% The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . %% -module(rabbit_federation_link_util). -include("amqp_client.hrl"). -include("rabbit_federation.hrl"). %% real -export([start_conn_ch/5, disposable_channel_call/2, disposable_channel_call/3, disposable_connection_call/3, ensure_connection_closed/1, log_terminate/4, unacked_new/0, ack/3, nack/3, forward/9, handle_down/6]). %% temp -export([connection_error/6]). -import(rabbit_misc, [pget/2]). -define(MAX_CONNECTION_CLOSE_TIMEOUT, 10000). %%---------------------------------------------------------------------------- start_conn_ch(Fun, Upstream, UParams, XorQName = #resource{virtual_host = DownVHost}, State) -> case open_monitor(#amqp_params_direct{virtual_host = DownVHost}) of {ok, DConn, DCh} -> case Upstream#upstream.ack_mode of 'on-confirm' -> #'confirm.select_ok'{} = amqp_channel:call(DCh, #'confirm.select'{}), amqp_channel:register_confirm_handler(DCh, self()); _ -> ok end, case open_monitor(UParams#upstream_params.params) of {ok, Conn, Ch} -> %% Don't trap exits until we have established %% connections so that if we try to delete %% federation upstreams while waiting for a %% connection to be established then we don't %% block process_flag(trap_exit, true), try R = Fun(Conn, Ch, DConn, DCh), log_info( XorQName, "connected to ~s~n", [rabbit_federation_upstream:params_to_string( UParams)]), Name = pget(name, amqp_connection:info(DConn, [name])), rabbit_federation_status:report( Upstream, UParams, XorQName, {running, Name}), R catch exit:E -> %% terminate/2 will not get this, as we %% have not put them in our state yet ensure_connection_closed(DConn), ensure_connection_closed(Conn), connection_error(remote_start, E, Upstream, UParams, XorQName, State) end; E -> ensure_connection_closed(DConn), connection_error(remote_start, E, Upstream, UParams, XorQName, State) end; E -> connection_error(local_start, E, Upstream, UParams, XorQName, State) end. open_monitor(Params) -> case open(Params) of {ok, Conn, Ch} -> erlang:monitor(process, Ch), {ok, Conn, Ch}; E -> E end. open(Params) -> case amqp_connection:start(Params) of {ok, Conn} -> case amqp_connection:open_channel(Conn) of {ok, Ch} -> {ok, Conn, Ch}; E -> catch amqp_connection:close(Conn), E end; E -> E end. ensure_channel_closed(Ch) -> catch amqp_channel:close(Ch). ensure_connection_closed(Conn) -> catch amqp_connection:close(Conn, ?MAX_CONNECTION_CLOSE_TIMEOUT). connection_error(remote_start, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), log_warning(XorQName, "did not connect to ~s~n~p~n", [rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(remote, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), log_info(XorQName, "disconnected from ~s~n~p~n", [rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(local, basic_cancel, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, {error, basic_cancel}), log_info(XorQName, "received 'basic.cancel'~n", []), {stop, {shutdown, restart}, State}; connection_error(local_start, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), log_warning(XorQName, "did not connect locally~n~p~n", [E]), {stop, {shutdown, restart}, State}. %% If we terminate due to a gen_server call exploding (almost %% certainly due to an amqp_channel:call() exploding) then we do not %% want to report the gen_server call in our status. clean_reason({E = {shutdown, _}, _}) -> E; clean_reason(E) -> E. local / disconnected never gets invoked , see handle_info({'DOWN ' , ... %%---------------------------------------------------------------------------- unacked_new() -> gb_trees:empty(). ack(#'basic.ack'{delivery_tag = Seq, multiple = Multiple}, Ch, Unack) -> amqp_channel:cast(Ch, #'basic.ack'{delivery_tag = gb_trees:get(Seq, Unack), multiple = Multiple}), remove_delivery_tags(Seq, Multiple, Unack). %% Note: at time of writing the broker will never send requeue=false. And it's %% hard to imagine why it would. But we may as well handle it. nack(#'basic.nack'{delivery_tag = Seq, multiple = Multiple, requeue = Requeue}, Ch, Unack) -> amqp_channel:cast(Ch, #'basic.nack'{delivery_tag = gb_trees:get(Seq, Unack), multiple = Multiple, requeue = Requeue}), remove_delivery_tags(Seq, Multiple, Unack). remove_delivery_tags(Seq, false, Unacked) -> gb_trees:delete(Seq, Unacked); remove_delivery_tags(Seq, true, Unacked) -> case gb_trees:is_empty(Unacked) of true -> Unacked; false -> {Smallest, _Val, Unacked1} = gb_trees:take_smallest(Unacked), case Smallest > Seq of true -> Unacked; false -> remove_delivery_tags(Seq, true, Unacked1) end end. forward(#upstream{ack_mode = AckMode, trust_user_id = Trust}, #'basic.deliver'{delivery_tag = DT}, Ch, DCh, PublishMethod, HeadersFun, ForwardFun, Msg, Unacked) -> Headers = extract_headers(Msg), case ForwardFun(Headers) of true -> Msg1 = maybe_clear_user_id( Trust, update_headers(HeadersFun(Headers), Msg)), Seq = case AckMode of 'on-confirm' -> amqp_channel:next_publish_seqno(DCh); _ -> ignore end, amqp_channel:cast(DCh, PublishMethod, Msg1), case AckMode of 'on-confirm' -> gb_trees:insert(Seq, DT, Unacked); 'on-publish' -> amqp_channel:cast(Ch, #'basic.ack'{delivery_tag = DT}), Unacked; 'no-ack' -> Unacked end; false -> amqp_channel:cast(Ch, #'basic.ack'{delivery_tag = DT}), %% Drop it, but acknowledge it! Unacked end. maybe_clear_user_id(false, Msg = #amqp_msg{props = Props}) -> Msg#amqp_msg{props = Props#'P_basic'{user_id = undefined}}; maybe_clear_user_id(true, Msg) -> Msg. extract_headers(#amqp_msg{props = #'P_basic'{headers = Headers}}) -> Headers. update_headers(Headers, Msg = #amqp_msg{props = Props}) -> Msg#amqp_msg{props = Props#'P_basic'{headers = Headers}}. %%---------------------------------------------------------------------------- %% If the downstream channel shuts down cleanly, we can just ignore it %% - we're the same node, we're presumably about to go down too. handle_down(DCh, shutdown, _Ch, DCh, _Args, State) -> {noreply, State}; %% If the upstream channel goes down for an intelligible reason, just %% log it and die quietly. handle_down(Ch, {shutdown, Reason}, Ch, _DCh, {Upstream, UParams, XName}, State) -> rabbit_federation_link_util:connection_error( remote, {upstream_channel_down, Reason}, Upstream, UParams, XName, State); handle_down(Ch, Reason, Ch, _DCh, _Args, State) -> {stop, {upstream_channel_down, Reason}, State}; handle_down(DCh, Reason, _Ch, DCh, _Args, State) -> {stop, {downstream_channel_down, Reason}, State}. %%---------------------------------------------------------------------------- log_terminate({shutdown, restart}, _Upstream, _UParams, _XorQName) -> %% We've already logged this before munging the reason ok; log_terminate(shutdown, Upstream, UParams, XorQName) -> %% The supervisor is shutting us down; we are probably restarting %% the link because configuration has changed. So try to shut down %% nicely so that we do not cause unacked messages to be %% redelivered. log_info(XorQName, "disconnecting from ~s~n", [rabbit_federation_upstream:params_to_string(UParams)]), rabbit_federation_status:remove(Upstream, XorQName); log_terminate(Reason, Upstream, UParams, XorQName) -> Unexpected death . will log it , but we should update %% rabbit_federation_status. rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(Reason)). log_info (XorQName, Fmt, Args) -> log(info, XorQName, Fmt, Args). log_warning(XorQName, Fmt, Args) -> log(warning, XorQName, Fmt, Args). log(Level, XorQName, Fmt, Args) -> rabbit_log:log(federation, Level, "Federation ~s " ++ Fmt, [rabbit_misc:rs(XorQName) | Args]). %%---------------------------------------------------------------------------- disposable_channel_call(Conn, Method) -> disposable_channel_call(Conn, Method, fun(_, _) -> ok end). disposable_channel_call(Conn, Method, ErrFun) -> {ok, Ch} = amqp_connection:open_channel(Conn), try amqp_channel:call(Ch, Method) catch exit:{{shutdown, {server_initiated_close, Code, Text}}, _} -> ErrFun(Code, Text) after ensure_channel_closed(Ch) end. disposable_connection_call(Params, Method, ErrFun) -> case open(Params) of {ok, Conn, Ch} -> try amqp_channel:call(Ch, Method) catch exit:{{shutdown, {connection_closing, {server_initiated_close, Code, Txt}}}, _} -> ErrFun(Code, Txt) after ensure_connection_closed(Conn) end; E -> E end.
null
https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-federation/src/rabbit_federation_link_util.erl
erlang
Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. real temp ---------------------------------------------------------------------------- Don't trap exits until we have established connections so that if we try to delete federation upstreams while waiting for a connection to be established then we don't block terminate/2 will not get this, as we have not put them in our state yet If we terminate due to a gen_server call exploding (almost certainly due to an amqp_channel:call() exploding) then we do not want to report the gen_server call in our status. ---------------------------------------------------------------------------- Note: at time of writing the broker will never send requeue=false. And it's hard to imagine why it would. But we may as well handle it. Drop it, but acknowledge it! ---------------------------------------------------------------------------- If the downstream channel shuts down cleanly, we can just ignore it - we're the same node, we're presumably about to go down too. If the upstream channel goes down for an intelligible reason, just log it and die quietly. ---------------------------------------------------------------------------- We've already logged this before munging the reason The supervisor is shutting us down; we are probably restarting the link because configuration has changed. So try to shut down nicely so that we do not cause unacked messages to be redelivered. rabbit_federation_status. ----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is RabbitMQ Federation . The Initial Developer of the Original Code is GoPivotal , Inc. Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved . -module(rabbit_federation_link_util). -include("amqp_client.hrl"). -include("rabbit_federation.hrl"). -export([start_conn_ch/5, disposable_channel_call/2, disposable_channel_call/3, disposable_connection_call/3, ensure_connection_closed/1, log_terminate/4, unacked_new/0, ack/3, nack/3, forward/9, handle_down/6]). -export([connection_error/6]). -import(rabbit_misc, [pget/2]). -define(MAX_CONNECTION_CLOSE_TIMEOUT, 10000). start_conn_ch(Fun, Upstream, UParams, XorQName = #resource{virtual_host = DownVHost}, State) -> case open_monitor(#amqp_params_direct{virtual_host = DownVHost}) of {ok, DConn, DCh} -> case Upstream#upstream.ack_mode of 'on-confirm' -> #'confirm.select_ok'{} = amqp_channel:call(DCh, #'confirm.select'{}), amqp_channel:register_confirm_handler(DCh, self()); _ -> ok end, case open_monitor(UParams#upstream_params.params) of {ok, Conn, Ch} -> process_flag(trap_exit, true), try R = Fun(Conn, Ch, DConn, DCh), log_info( XorQName, "connected to ~s~n", [rabbit_federation_upstream:params_to_string( UParams)]), Name = pget(name, amqp_connection:info(DConn, [name])), rabbit_federation_status:report( Upstream, UParams, XorQName, {running, Name}), R catch exit:E -> ensure_connection_closed(DConn), ensure_connection_closed(Conn), connection_error(remote_start, E, Upstream, UParams, XorQName, State) end; E -> ensure_connection_closed(DConn), connection_error(remote_start, E, Upstream, UParams, XorQName, State) end; E -> connection_error(local_start, E, Upstream, UParams, XorQName, State) end. open_monitor(Params) -> case open(Params) of {ok, Conn, Ch} -> erlang:monitor(process, Ch), {ok, Conn, Ch}; E -> E end. open(Params) -> case amqp_connection:start(Params) of {ok, Conn} -> case amqp_connection:open_channel(Conn) of {ok, Ch} -> {ok, Conn, Ch}; E -> catch amqp_connection:close(Conn), E end; E -> E end. ensure_channel_closed(Ch) -> catch amqp_channel:close(Ch). ensure_connection_closed(Conn) -> catch amqp_connection:close(Conn, ?MAX_CONNECTION_CLOSE_TIMEOUT). connection_error(remote_start, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), log_warning(XorQName, "did not connect to ~s~n~p~n", [rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(remote, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), log_info(XorQName, "disconnected from ~s~n~p~n", [rabbit_federation_upstream:params_to_string(UParams), E]), {stop, {shutdown, restart}, State}; connection_error(local, basic_cancel, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, {error, basic_cancel}), log_info(XorQName, "received 'basic.cancel'~n", []), {stop, {shutdown, restart}, State}; connection_error(local_start, E, Upstream, UParams, XorQName, State) -> rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(E)), log_warning(XorQName, "did not connect locally~n~p~n", [E]), {stop, {shutdown, restart}, State}. clean_reason({E = {shutdown, _}, _}) -> E; clean_reason(E) -> E. local / disconnected never gets invoked , see handle_info({'DOWN ' , ... unacked_new() -> gb_trees:empty(). ack(#'basic.ack'{delivery_tag = Seq, multiple = Multiple}, Ch, Unack) -> amqp_channel:cast(Ch, #'basic.ack'{delivery_tag = gb_trees:get(Seq, Unack), multiple = Multiple}), remove_delivery_tags(Seq, Multiple, Unack). nack(#'basic.nack'{delivery_tag = Seq, multiple = Multiple, requeue = Requeue}, Ch, Unack) -> amqp_channel:cast(Ch, #'basic.nack'{delivery_tag = gb_trees:get(Seq, Unack), multiple = Multiple, requeue = Requeue}), remove_delivery_tags(Seq, Multiple, Unack). remove_delivery_tags(Seq, false, Unacked) -> gb_trees:delete(Seq, Unacked); remove_delivery_tags(Seq, true, Unacked) -> case gb_trees:is_empty(Unacked) of true -> Unacked; false -> {Smallest, _Val, Unacked1} = gb_trees:take_smallest(Unacked), case Smallest > Seq of true -> Unacked; false -> remove_delivery_tags(Seq, true, Unacked1) end end. forward(#upstream{ack_mode = AckMode, trust_user_id = Trust}, #'basic.deliver'{delivery_tag = DT}, Ch, DCh, PublishMethod, HeadersFun, ForwardFun, Msg, Unacked) -> Headers = extract_headers(Msg), case ForwardFun(Headers) of true -> Msg1 = maybe_clear_user_id( Trust, update_headers(HeadersFun(Headers), Msg)), Seq = case AckMode of 'on-confirm' -> amqp_channel:next_publish_seqno(DCh); _ -> ignore end, amqp_channel:cast(DCh, PublishMethod, Msg1), case AckMode of 'on-confirm' -> gb_trees:insert(Seq, DT, Unacked); 'on-publish' -> amqp_channel:cast(Ch, #'basic.ack'{delivery_tag = DT}), Unacked; 'no-ack' -> Unacked end; false -> amqp_channel:cast(Ch, #'basic.ack'{delivery_tag = DT}), Unacked end. maybe_clear_user_id(false, Msg = #amqp_msg{props = Props}) -> Msg#amqp_msg{props = Props#'P_basic'{user_id = undefined}}; maybe_clear_user_id(true, Msg) -> Msg. extract_headers(#amqp_msg{props = #'P_basic'{headers = Headers}}) -> Headers. update_headers(Headers, Msg = #amqp_msg{props = Props}) -> Msg#amqp_msg{props = Props#'P_basic'{headers = Headers}}. handle_down(DCh, shutdown, _Ch, DCh, _Args, State) -> {noreply, State}; handle_down(Ch, {shutdown, Reason}, Ch, _DCh, {Upstream, UParams, XName}, State) -> rabbit_federation_link_util:connection_error( remote, {upstream_channel_down, Reason}, Upstream, UParams, XName, State); handle_down(Ch, Reason, Ch, _DCh, _Args, State) -> {stop, {upstream_channel_down, Reason}, State}; handle_down(DCh, Reason, _Ch, DCh, _Args, State) -> {stop, {downstream_channel_down, Reason}, State}. log_terminate({shutdown, restart}, _Upstream, _UParams, _XorQName) -> ok; log_terminate(shutdown, Upstream, UParams, XorQName) -> log_info(XorQName, "disconnecting from ~s~n", [rabbit_federation_upstream:params_to_string(UParams)]), rabbit_federation_status:remove(Upstream, XorQName); log_terminate(Reason, Upstream, UParams, XorQName) -> Unexpected death . will log it , but we should update rabbit_federation_status:report( Upstream, UParams, XorQName, clean_reason(Reason)). log_info (XorQName, Fmt, Args) -> log(info, XorQName, Fmt, Args). log_warning(XorQName, Fmt, Args) -> log(warning, XorQName, Fmt, Args). log(Level, XorQName, Fmt, Args) -> rabbit_log:log(federation, Level, "Federation ~s " ++ Fmt, [rabbit_misc:rs(XorQName) | Args]). disposable_channel_call(Conn, Method) -> disposable_channel_call(Conn, Method, fun(_, _) -> ok end). disposable_channel_call(Conn, Method, ErrFun) -> {ok, Ch} = amqp_connection:open_channel(Conn), try amqp_channel:call(Ch, Method) catch exit:{{shutdown, {server_initiated_close, Code, Text}}, _} -> ErrFun(Code, Text) after ensure_channel_closed(Ch) end. disposable_connection_call(Params, Method, ErrFun) -> case open(Params) of {ok, Conn, Ch} -> try amqp_channel:call(Ch, Method) catch exit:{{shutdown, {connection_closing, {server_initiated_close, Code, Txt}}}, _} -> ErrFun(Code, Txt) after ensure_connection_closed(Conn) end; E -> E end.
6f6cbc54f2c5e58610ae325983ac8f95f4e58b32e76f1c5d4f88a3a5a70a3bab
klutometis/clrs
13.3-6.scm
(load "red-black-tree.scm") (use red-black-tree test) (let* ((root nil) (root (insert/parents! root (make-node key: 41))) (root (insert/parents! root (make-node key: 38))) (root (insert/parents! root (make-node key: 31))) (root (insert/parents! root (make-node key: 12))) (root (insert/parents! root (make-node key: 19))) (root (insert/parents! root (make-node key: 8)))) (test "insertion of successive keys with a parent stack" '((38 . black) ((19 . red) ((12 . black) ((8 . red) (#f . black) (#f . black)) (#f . black)) ((31 . black) (#f . black) (#f . black))) ((41 . black) (#f . black) (#f . black))) (tree->pre-order-key-color-list root)))
null
https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/13/13.3-6.scm
scheme
(load "red-black-tree.scm") (use red-black-tree test) (let* ((root nil) (root (insert/parents! root (make-node key: 41))) (root (insert/parents! root (make-node key: 38))) (root (insert/parents! root (make-node key: 31))) (root (insert/parents! root (make-node key: 12))) (root (insert/parents! root (make-node key: 19))) (root (insert/parents! root (make-node key: 8)))) (test "insertion of successive keys with a parent stack" '((38 . black) ((19 . red) ((12 . black) ((8 . red) (#f . black) (#f . black)) (#f . black)) ((31 . black) (#f . black) (#f . black))) ((41 . black) (#f . black) (#f . black))) (tree->pre-order-key-color-list root)))
b7a1a385bdf3911fccef5b7aa14cad9d7ef5c029dadaf4758478b6b2aea460c8
lk-geimfari/secrets.clj
core_test.clj
(ns secrets.core-test (:require [clojure.test :refer [deftest testing is are]] [clojure.string :as str] [secrets.core :as core])) (deftest token-hex-test (testing "Generate a random hex string" (assert (= (count (core/token-hex)) 64)) (assert (= (count (core/token-hex 64)) 128)))) (deftest token-bytes-test (testing "Generate the random bytes" (are [char] (false? (str/includes? (core/token-bytes) char)) "+" "/" "=") (are [nbytes] (= (count (core/token-bytes nbytes)) nbytes) 8 64 256 1024))) (deftest token-urlsafe-test (testing "Generate a url-safe random string" (are [nbytes result] (= (count (core/token-urlsafe nbytes)) result) 32 43 64 86 16 22))) (deftest randbits-test (testing "Generate a random integer with k random bits" (are [k] (>= (core/randbits k) 0) 8 16 32 64 128 256 512) (assert (= (core/randbits 0) 0)) (assert (instance? BigInteger (core/randbits 32))))) (deftest randbelow-test (testing "Generate a random int in the range [0, n)" (let [number (core/randbelow 100)] (assert (and (> number 0) (< number 100)))))) (deftest choice-test (testing "Choice a random element of coll" (let [chosen (core/choice [8 16 32 64 128])] (assert (and (>= chosen 8) (<= chosen 128))) (is (thrown? AssertionError (core/choice [])))))) (deftest choices-test (testing "Choices a random elements of the collection" (let [k 3 chosen (core/choices [8 16 32 64 128] k)] (assert (= (count chosen) k))) (assert (is (thrown? AssertionError (core/choices [] 1)))) (assert (is (thrown? AssertionError (core/choices [] 0)))) (assert (is (thrown? AssertionError (core/choices ["a" "b" "c"] 0)))) (assert (is (thrown? AssertionError (core/choices ["a" "b" "c"] -1))))))
null
https://raw.githubusercontent.com/lk-geimfari/secrets.clj/4dc7223242766b15c02ebc131885b707ccb4b8dc/test/secrets/core_test.clj
clojure
(ns secrets.core-test (:require [clojure.test :refer [deftest testing is are]] [clojure.string :as str] [secrets.core :as core])) (deftest token-hex-test (testing "Generate a random hex string" (assert (= (count (core/token-hex)) 64)) (assert (= (count (core/token-hex 64)) 128)))) (deftest token-bytes-test (testing "Generate the random bytes" (are [char] (false? (str/includes? (core/token-bytes) char)) "+" "/" "=") (are [nbytes] (= (count (core/token-bytes nbytes)) nbytes) 8 64 256 1024))) (deftest token-urlsafe-test (testing "Generate a url-safe random string" (are [nbytes result] (= (count (core/token-urlsafe nbytes)) result) 32 43 64 86 16 22))) (deftest randbits-test (testing "Generate a random integer with k random bits" (are [k] (>= (core/randbits k) 0) 8 16 32 64 128 256 512) (assert (= (core/randbits 0) 0)) (assert (instance? BigInteger (core/randbits 32))))) (deftest randbelow-test (testing "Generate a random int in the range [0, n)" (let [number (core/randbelow 100)] (assert (and (> number 0) (< number 100)))))) (deftest choice-test (testing "Choice a random element of coll" (let [chosen (core/choice [8 16 32 64 128])] (assert (and (>= chosen 8) (<= chosen 128))) (is (thrown? AssertionError (core/choice [])))))) (deftest choices-test (testing "Choices a random elements of the collection" (let [k 3 chosen (core/choices [8 16 32 64 128] k)] (assert (= (count chosen) k))) (assert (is (thrown? AssertionError (core/choices [] 1)))) (assert (is (thrown? AssertionError (core/choices [] 0)))) (assert (is (thrown? AssertionError (core/choices ["a" "b" "c"] 0)))) (assert (is (thrown? AssertionError (core/choices ["a" "b" "c"] -1))))))
21c29e93eabf17efd6a92c0213f2c1425e0a1f712b374a2fdb36f8ac61dfa910
Olical/propel
util.clj
(ns propel.util "Useful things that don't conceptually belong to one namespace." (:require [clojure.main :as clojure] [clojure.pprint :as pprint]) (:import [java.net ServerSocket])) (defn log [& msg] (apply println "[Propel]" msg)) (defn error [err & msg] (binding [*out* *err*] (apply log "Error:" msg) (-> err (cond-> (not (map? err)) (Throwable->map)) (doto (pprint/pprint)) (clojure/ex-triage) (clojure/ex-str) (println)))) (defn die [& msg] (binding [*out* *err*] (log "Error:" (apply str msg))) (System/exit 1)) (def ^:private alias->ns '{exp expound.alpha cljs cljs.repl fig figwheel.main.api lfig figwheel-sidecar.repl-api node cljs.server.node browser cljs.server.browser}) (defn lapply "Require the namespace of the symbol then apply the var with the args." [sym & args] (let [ns-sym (as-> (symbol (namespace sym)) ns-sym (get alias->ns ns-sym ns-sym))] (require ns-sym) (apply (resolve (symbol (name ns-sym) (name sym))) args))) (defn ^:dynamic free-port "Find a free port we can bind to." [] (let [socket (ServerSocket. 0)] (.close socket) (.getLocalPort socket))) (defn ^:dynamic unique-name "Generates a unique prefixed name string with a label." [label] (str (gensym (str "propel-" label "-")))) (defmacro thread "Useful helper to run code in a thread but ensure errors are caught and logged correctly." [use-case & body] `(future (try ~@body (catch Throwable t# (error t# "From thread" (str "'" ~use-case "'")))))) (defn write "Write the full data to the stream and then flush the stream." [stream data] (doto stream (.write data 0 (count data)) (.flush)))
null
https://raw.githubusercontent.com/Olical/propel/407ccf1ae507876e9a879239fac96380f2c1de2b/src/propel/util.clj
clojure
(ns propel.util "Useful things that don't conceptually belong to one namespace." (:require [clojure.main :as clojure] [clojure.pprint :as pprint]) (:import [java.net ServerSocket])) (defn log [& msg] (apply println "[Propel]" msg)) (defn error [err & msg] (binding [*out* *err*] (apply log "Error:" msg) (-> err (cond-> (not (map? err)) (Throwable->map)) (doto (pprint/pprint)) (clojure/ex-triage) (clojure/ex-str) (println)))) (defn die [& msg] (binding [*out* *err*] (log "Error:" (apply str msg))) (System/exit 1)) (def ^:private alias->ns '{exp expound.alpha cljs cljs.repl fig figwheel.main.api lfig figwheel-sidecar.repl-api node cljs.server.node browser cljs.server.browser}) (defn lapply "Require the namespace of the symbol then apply the var with the args." [sym & args] (let [ns-sym (as-> (symbol (namespace sym)) ns-sym (get alias->ns ns-sym ns-sym))] (require ns-sym) (apply (resolve (symbol (name ns-sym) (name sym))) args))) (defn ^:dynamic free-port "Find a free port we can bind to." [] (let [socket (ServerSocket. 0)] (.close socket) (.getLocalPort socket))) (defn ^:dynamic unique-name "Generates a unique prefixed name string with a label." [label] (str (gensym (str "propel-" label "-")))) (defmacro thread "Useful helper to run code in a thread but ensure errors are caught and logged correctly." [use-case & body] `(future (try ~@body (catch Throwable t# (error t# "From thread" (str "'" ~use-case "'")))))) (defn write "Write the full data to the stream and then flush the stream." [stream data] (doto stream (.write data 0 (count data)) (.flush)))
8a1a1f3429da3c6d51cab7b457aac413a38cc9e872ed561d0b8a38788e834261
incoherentsoftware/defect-process
Item.hs
module Level.Room.Item ( module Level.Room.Item.Types , mkRoomItem ) where import Data.Dynamic (fromDynamic) import Data.Typeable (Typeable) import qualified Data.Set as S import Collision.Hitbox import Level.Room.Item.Types import Msg import Util mkRoomItem :: Typeable d => RoomItemType -> d -> MsgId -> Hitbox -> RoomItem d mkRoomItem itemType itemData msgId hitbox = RoomItem { _type = itemType , _data = itemData , _msgId = msgId , _hitbox = hitbox , _vel = zeroVel2 , _isAttackable = False , _hitByHashedIds = S.empty , _think = const $ return [] , _update = return . id , _updateDynamic = updateDynamic , _draw = const $ return () , _playerCollision = \_ _ -> [] } updateDynamic :: Typeable d => RoomItemUpdateDynamic d updateDynamic dyn item = case fromDynamic dyn of Just update -> update item Nothing -> item
null
https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Level/Room/Item.hs
haskell
module Level.Room.Item ( module Level.Room.Item.Types , mkRoomItem ) where import Data.Dynamic (fromDynamic) import Data.Typeable (Typeable) import qualified Data.Set as S import Collision.Hitbox import Level.Room.Item.Types import Msg import Util mkRoomItem :: Typeable d => RoomItemType -> d -> MsgId -> Hitbox -> RoomItem d mkRoomItem itemType itemData msgId hitbox = RoomItem { _type = itemType , _data = itemData , _msgId = msgId , _hitbox = hitbox , _vel = zeroVel2 , _isAttackable = False , _hitByHashedIds = S.empty , _think = const $ return [] , _update = return . id , _updateDynamic = updateDynamic , _draw = const $ return () , _playerCollision = \_ _ -> [] } updateDynamic :: Typeable d => RoomItemUpdateDynamic d updateDynamic dyn item = case fromDynamic dyn of Just update -> update item Nothing -> item
05aee3a46b3b66c833c25dfb2f20b0d062cc69857dd1b0e005b92712e260c3e0
abailly/xxi-century-typed
ParserSpec.hs
module Minilang.ParserSpec where import qualified Data.Text as Text import Minilang.Parser import Test.Hspec import Text.Parsec.Error import Text.Parsec.Pos spec :: Spec spec = parallel $ describe "Minilang Parser" $ do describe "Parsing Terms and Expressions" $ do it "parse Number" $ do parseProgram False "12" `shouldBe` I 12 parseProgram False "12.4" `shouldBe` D 12.4 parseProgram False "-12" `shouldBe` I (-12) parseProgram False "-42.3" `shouldBe` D (-42.3) it "parse String" $ parseProgram False "\"123\"" `shouldBe` S "123" it "parse Variable" $ do parseProgram False "abc" `shouldBe` Var "abc" parseProgram False "+" `shouldBe` Var "+" parseProgram False "-" `shouldBe` Var "-" parseProgram False "*" `shouldBe` Var "*" parseProgram False "/" `shouldBe` Var "/" parseProgram False "%" `shouldBe` Var "%" parseProgram False "^" `shouldBe` Var "^" parseProgram False "^?!<~#@&=" `shouldBe` Var "^?!<~#@&=" it "parse Universe" $ do parseProgram False "U" `shouldBe` U 0 parseProgram False "U2" `shouldBe` U 2 parseProgram False "Uabc" `shouldBe` Var "Uabc" it "parse Unit" $ parseProgram False "()" `shouldBe` Unit it "parse One" $ parseProgram False "[]" `shouldBe` One it "parse Application" $ parseProgram False "abc fge" `shouldBe` Ap (Var "abc") (Var "fge") it "run application parser" $ doParse application "C (S abc)" `shouldBe` Ap (Var "C") (Ap (Var "S") (Var "abc")) it "parse application as left-associative" $ do parseProgram False "abc fge 12" `shouldBe` Ap (Ap (Var "abc") (Var "fge")) (I 12) parseProgram False "abc fge 12 k" `shouldBe` parseProgram False "((abc fge) 12) k" parseProgram False "abc fge 12 k bool" `shouldBe` parseProgram False "(((abc fge) 12) k) bool" parseProgram False "abc (fge 12)" `shouldBe` Ap (Var "abc") (Ap (Var "fge") (I 12)) parseProgram False "(g n1) (natrec C a g n1)" `shouldBe` Ap (Ap (Var "g") (Var "n1")) (Ap (Ap (Ap (Ap (Var "natrec") (Var "C")) (Var "a")) (Var "g")) (Var "n1")) it "parse Abstraction" $ do parseProgram False "λ abc . abc" `shouldBe` Abs (B "abc") (Var "abc") parseProgram False "λ abc . abc ghe" `shouldBe` Abs (B "abc") (Ap (Var "abc") (Var "ghe")) parseProgram False "λ _ . abc" `shouldBe` Abs Wildcard (Var "abc") it "parse Dependent Product" $ do parseProgram False "Π abc : U . abc" `shouldBe` Pi (B "abc") (U 0) (Var "abc") parseProgram False "Πabc:U.abc" `shouldBe` Pi (B "abc") (U 0) (Var "abc") parseProgram True "Π a : A . C (S a)" `shouldBe` Pi (B "a") (Var "A") (Ap (Var "C") (Ap (Var "S") (Var "a"))) it "parse Function type" $ do parseProgram False "() -> []" `shouldBe` Pi Wildcard Unit One parseProgram False "(A : U) -> A" `shouldBe` Pi (B "A") (U 0) (Var "A") parseProgram False "(A : U) → (b : A) → ()" `shouldBe` Pi (B "A") (U 0) (Pi (B "b") (Var "A") Unit) parseProgram False "(_ : A) -> B" `shouldBe` parseProgram False "A -> B" parseProgram False "(a : A) -> C (S a)" `shouldBe` Pi (B "a") (Var "A") (Ap (Var "C") (Ap (Var "S") (Var "a"))) it "parse Dependent Sum" $ do parseProgram False "Σ abc : U . abc" `shouldBe` Sigma (B "abc") (U 0) (Var "abc") parseProgram False "Σabc: U. abc" `shouldBe` Sigma (B "abc") (U 0) (Var "abc") parseProgram False "Σ x : V . T x → V" `shouldBe` Sigma (B "x") (Var "V") (Pi Wildcard (Ap (Var "T") (Var "x")) (Var "V")) it "parse Projections" $ do parseProgram False "π1.abc" `shouldBe` P1 (Var "abc") parseProgram False "π2.abc" `shouldBe` P2 (Var "abc") it "parse Pairing" $ parseProgram False "(abc,12)" `shouldBe` Pair (Var "abc") (I 12) it "parses Constructor w/ Pairing" $ parseProgram False "foo (abc,12)" `shouldBe` Ap (Var "foo") (Pair (Var "abc") (I 12)) it "parses Labelled Sum" $ do parseProgram False "Sum(foo [] | bar Nat)" `shouldBe` Sum [Choice "foo" (Just One), Choice "bar" (Just $ Var "Nat")] parseProgram False "Sum(foo[] | bar (Nat, Bool))" `shouldBe` Sum [Choice "foo" (Just One), Choice "bar" (Just $ Pair (Var "Nat") (Var "Bool"))] parseProgram False "Sum(foo | bar)" `shouldBe` Sum [Choice "foo" Nothing, Choice "bar" Nothing] parseProgram False "Sum ( foo | bar )" `shouldBe` Sum [Choice "foo" Nothing, Choice "bar" Nothing] it "parses Case choices" $ do parseProgram False "case (foo 12 -> h1 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs (C $ I 12) (Var "h1")), Clause "bar" (Abs (B "x") (Var "h2"))] parseProgram False "case (foo -> 12 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs Wildcard (I 12)), Clause "bar" (Abs (B "x") (Var "h2"))] it "parses Pattern" $ do parseProgram False "λ (abc, xyz) . abc" `shouldBe` Abs (Pat (B "abc") (B "xyz")) (Var "abc") parseProgram False "Π (abc, xyz): U . abc" `shouldBe` Pi (Pat (B "abc") (B "xyz")) (U 0) (Var "abc") it "parses single-line comments after an expression" $ do parseProgram False "() -- this is a comment" `shouldBe` Unit parseProgram False "[] -- this is a comment" `shouldBe` One parseProgram False "-- this is a comment\n()" `shouldBe` Unit parseProgram False "λ -- this is a comment\n(abc, xyz) . abc" `shouldBe` Abs (Pat (B "abc") (B "xyz")) (Var "abc") parseProgram False "case -- a comment\n (foo -- a comment \n-> 12 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs Wildcard (I 12)), Clause "bar" (Abs (B "x") (Var "h2"))] it "parses multiline comments" $ do parseProgram False "case {- this is a multiline \n comment -} (foo -- a comment \n-> 12 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs Wildcard (I 12)), Clause "bar" (Abs (B "x") (Var "h2"))] parseProgram False "{- this is a multiline comment -}\nlet x : Unit -> [] = case (tt -> ())" `shouldBe` Let (Decl (B "x") (Pi Wildcard (Var "Unit") One) (Case [Clause "tt" (Abs Wildcard Unit)])) Unit it "parses holes" $ do pending parseProgram False "λ x . ?hole" `shouldBe` Abs (Pat (B "abc") (B "xyz")) (Hole "hole") describe "Declarations" $ do it "parses generic id function" $ parseDecl "id : Π A : U . Π _ : A . A = λ A . λ x . x" `shouldBe` Decl (B "id") (Pi (B "A") (U 0) (Pi Wildcard (Var "A") (Var "A"))) (Abs (B "A") (Abs (B "x") (Var "x"))) it "parses Bool declaration" $ do parseDecl "Bool : U = Sum (true | false)" `shouldBe` Decl (B "Bool") (U 0) (Sum [Choice "true" Nothing, Choice "false" Nothing]) parseDecl "Bool : U = Sum(true| false)" `shouldBe` Decl (B "Bool") (U 0) (Sum [Choice "true" Nothing, Choice "false" Nothing]) it "parses some declaration" $ parseProgram False "let x : Unit -> [] = case (tt -> ());()" `shouldBe` Let ( Decl (B "x") (Pi Wildcard (Var "Unit") One) (Case [Clause "tt" (Abs Wildcard Unit)]) ) Unit it "parses Bool elimination" $ parseDecl "elimBool : Π C : Bool → U . C false → C true → Π b : Bool . C b = λ C . λ h0 . λ h1 . case (true → h1 | false → h0)" `shouldBe` Decl (B "elimBool") ( Pi (B "C") (Pi Wildcard (Var "Bool") (U 0)) ( Pi Wildcard (Ap (Var "C") (Var "false")) ( Pi Wildcard (Ap (Var "C") (Var "true")) ( Pi (B "b") (Var "Bool") (Ap (Var "C") (Var "b")) ) ) ) ) ( Abs (B "C") ( Abs (B "h0") ( Abs (B "h1") ( Case [ Clause "true" (Abs Wildcard (Var "h1")) , Clause "false" (Abs Wildcard (Var "h0")) ] ) ) ) ) it "parses Nat declaration" $ parseDecl "rec Nat : U = Sum (zero | succ Nat)" `shouldBe` RDecl (B "Nat") (U 0) (Sum [Choice "zero" Nothing, Choice "succ" (Just $ Var "Nat")]) it "parses recursive-inductive universe let" $ parseDecl "rec (V,T) : ΣX:U.X -> U = (Sum(nat | pi (Σ x : V . T x → V)) , case (nat → Nat | pi (x, f ) → Π y : T x . T (f y)))" `shouldBe` RDecl (Pat (B "V") (B "T")) ( Sigma (B "X") (U 0) (Pi Wildcard (Var "X") (U 0)) ) ( Pair ( Sum [ Choice "nat" Nothing , Choice "pi" ( Just $ Sigma (B "x") (Var "V") ( Pi Wildcard (Ap (Var "T") (Var "x")) (Var "V") ) ) ] ) ( Case [ Clause "nat" (Abs Wildcard (Var "Nat")) , Clause "pi" ( Abs (Pat (B "x") (B "f")) ( Pi (B "y") (Ap (Var "T") (Var "x")) ( Ap (Var "T") (Ap (Var "f") (Var "y")) ) ) ) ] ) ) it "parses natRec " $ parseProgram False "let rec natrec : Π C : Nat → U . C zero → (Π n : Nat.C n → C (succ n)) → Π n : Nat . C n = λ C . λ a . λ g . case (zero → a | succ n1 → (g n1) ((((natrec C) a) g) n1)); ()" `shouldBe` Let ( RDecl (B "natrec") ( Pi (B "C") (Pi Wildcard (Var "Nat") (U 0)) ( Pi Wildcard (Ap (Var "C") (Var "zero")) ( Pi Wildcard ( Pi (B "n") (Var "Nat") ( Pi Wildcard (Ap (Var "C") (Var "n")) ( Ap (Var "C") (Ap (Var "succ") (Var "n")) ) ) ) ( Pi (B "n") (Var "Nat") (Ap (Var "C") (Var "n")) ) ) ) ) ( Abs (B "C") ( Abs (B "a") ( Abs (B "g") ( Case [ Clause "zero" (Abs Wildcard (Var "a")) , Clause "succ" ( Abs (B "n1") ( Ap (Ap (Var "g") (Var "n1")) ( Ap ( Ap ( Ap ( Ap (Var "natrec") (Var "C") ) (Var "a") ) (Var "g") ) (Var "n1") ) ) ) ] ) ) ) ) ) Unit it "parses a program" $ parseProgram False ("let rec Nat : U = Sum (zero | succ Nat) ;\n" <> "let id : Π A : U . Π _ : A . A = λ A . λ x . x; ()") `shouldBe` Let (RDecl (B "Nat") (U 0) (Sum [Choice "zero" Nothing, Choice "succ" (Just $ Var "Nat")])) ( Let ( Decl (B "id") (Pi (B "A") (U 0) (Pi Wildcard (Var "A") (Var "A"))) (Abs (B "A") (Abs (B "x") (Var "x"))) ) Unit ) it "parses another program" $ parseProgram False "let Unit : U = Sum (tt); let elimUnit : Π C : Unit -> U. C tt -> Π x:Unit. C x = λ C . λ h . case (tt -> h); ()" `shouldBe` Let ( Decl (B "Unit") (U 0) (Sum [Choice "tt" Nothing]) ) ( Let ( Decl (B "elimUnit") ( Pi (B "C") (Pi Wildcard (Var "Unit") (U 0)) ( Pi Wildcard (Ap (Var "C") (Var "tt")) (Pi (B "x") (Var "Unit") (Ap (Var "C") (Var "x"))) ) ) (Abs (B "C") (Abs (B "h") (Case [Clause "tt" (Abs Wildcard (Var "h"))]))) ) Unit ) it "parses a multiline program" $ parseProgram False ( Text.unlines [ "let rec NEList : Π A : U . U = λ A . Sum(S A | C (Σ a : A . NEList A));" , "let elimNEList : Π A : U . Π C : NEList A -> U . (Π a : A . C (S a)) -> (Π a : (Σ _ : A . NEList A) . C (C a)) -> Π b : NEList A . C b " , " = λ A . λ C . λ h0 . λ h1 . case (S a -> h0 a | C a -> h1 a);" , "let select : NEList Bool -> U = case (S _ -> Unit | C _ -> Unit);" , "()" ] ) `shouldBe` Let (RDecl (B "NEList") (Pi (B "A") (U 0) (U 0)) (Abs (B "A") (Sum [Choice "S" (Just (Var "A")), Choice "C" (Just (Sigma (B "a") (Var "A") (Ap (Var "NEList") (Var "A"))))]))) (Let (Decl (B "elimNEList") (Pi (B "A") (U 0) (Pi (B "C") (Pi Wildcard (Ap (Var "NEList") (Var "A")) (U 0)) (Pi Wildcard (Pi (B "a") (Var "A") (Ap (Var "C") (Ap (Var "S") (Var "a")))) (Pi Wildcard (Pi (B "a") (Sigma Wildcard (Var "A") (Ap (Var "NEList") (Var "A"))) (Ap (Var "C") (Ap (Var "C") (Var "a")))) (Pi (B "b") (Ap (Var "NEList") (Var "A")) (Ap (Var "C") (Var "b"))))))) (Abs (B "A") (Abs (B "C") (Abs (B "h0") (Abs (B "h1") (Case [Clause "S" (Abs (B "a") (Ap (Var "h0") (Var "a"))), Clause "C" (Abs (B "a") (Ap (Var "h1") (Var "a")))])))))) (Let (Decl (B "select") (Pi Wildcard (Ap (Var "NEList") (Var "Bool")) (U 0)) (Case [Clause "S" (Abs Wildcard (Var "Unit")), Clause "C" (Abs Wildcard (Var "Unit"))])) Unit)) describe "Error handling" $ do describe "skipErrorTo" $ it "consumes tokens until some parser succeeds then yields an Error" $ do let fragment = do a <- skipErrorTo [scolon] b <- scolon *> term pure $ Ap a b doParse fragment "fooo ; bar" `shouldBe` Ap (Err $ newErrorMessage (Message "found 'fooo ' between (1,1) and (1,6)") (newPos "" 1 6)) (Var "bar") it "inserts an Err node in AST on error in let" $ do let errorNode = Err $ newErrorMessage (Message "found 'case (tt -> ()' between (1,22) and (1,36)") (newPos "" 1 36) parseProgram False "let x : Unit -> [] = case (tt -> ();()" `shouldBe` Let ( Decl (B "x") (Pi Wildcard (Var "Unit") One) errorNode ) Unit it "inserts an Err node in AST on error in case clause" $ do let errorNode = Err $ newErrorMessage (Message "found '-> ' between (1,31) and (1,34)") (newPos "" 1 34) parseProgram False "let x : Unit -> [] = case (tt -> | ff -> ());()" `shouldBe` Let ( Decl (B "x") (Pi Wildcard (Var "Unit") One) ( Case [ Clause "tt" errorNode , Clause "ff" (Abs Wildcard Unit) ] ) ) Unit
null
https://raw.githubusercontent.com/abailly/xxi-century-typed/89df5eab3747ddb0ea37030ddb1947fb8c14265b/minilang/test/Minilang/ParserSpec.hs
haskell
module Minilang.ParserSpec where import qualified Data.Text as Text import Minilang.Parser import Test.Hspec import Text.Parsec.Error import Text.Parsec.Pos spec :: Spec spec = parallel $ describe "Minilang Parser" $ do describe "Parsing Terms and Expressions" $ do it "parse Number" $ do parseProgram False "12" `shouldBe` I 12 parseProgram False "12.4" `shouldBe` D 12.4 parseProgram False "-12" `shouldBe` I (-12) parseProgram False "-42.3" `shouldBe` D (-42.3) it "parse String" $ parseProgram False "\"123\"" `shouldBe` S "123" it "parse Variable" $ do parseProgram False "abc" `shouldBe` Var "abc" parseProgram False "+" `shouldBe` Var "+" parseProgram False "-" `shouldBe` Var "-" parseProgram False "*" `shouldBe` Var "*" parseProgram False "/" `shouldBe` Var "/" parseProgram False "%" `shouldBe` Var "%" parseProgram False "^" `shouldBe` Var "^" parseProgram False "^?!<~#@&=" `shouldBe` Var "^?!<~#@&=" it "parse Universe" $ do parseProgram False "U" `shouldBe` U 0 parseProgram False "U2" `shouldBe` U 2 parseProgram False "Uabc" `shouldBe` Var "Uabc" it "parse Unit" $ parseProgram False "()" `shouldBe` Unit it "parse One" $ parseProgram False "[]" `shouldBe` One it "parse Application" $ parseProgram False "abc fge" `shouldBe` Ap (Var "abc") (Var "fge") it "run application parser" $ doParse application "C (S abc)" `shouldBe` Ap (Var "C") (Ap (Var "S") (Var "abc")) it "parse application as left-associative" $ do parseProgram False "abc fge 12" `shouldBe` Ap (Ap (Var "abc") (Var "fge")) (I 12) parseProgram False "abc fge 12 k" `shouldBe` parseProgram False "((abc fge) 12) k" parseProgram False "abc fge 12 k bool" `shouldBe` parseProgram False "(((abc fge) 12) k) bool" parseProgram False "abc (fge 12)" `shouldBe` Ap (Var "abc") (Ap (Var "fge") (I 12)) parseProgram False "(g n1) (natrec C a g n1)" `shouldBe` Ap (Ap (Var "g") (Var "n1")) (Ap (Ap (Ap (Ap (Var "natrec") (Var "C")) (Var "a")) (Var "g")) (Var "n1")) it "parse Abstraction" $ do parseProgram False "λ abc . abc" `shouldBe` Abs (B "abc") (Var "abc") parseProgram False "λ abc . abc ghe" `shouldBe` Abs (B "abc") (Ap (Var "abc") (Var "ghe")) parseProgram False "λ _ . abc" `shouldBe` Abs Wildcard (Var "abc") it "parse Dependent Product" $ do parseProgram False "Π abc : U . abc" `shouldBe` Pi (B "abc") (U 0) (Var "abc") parseProgram False "Πabc:U.abc" `shouldBe` Pi (B "abc") (U 0) (Var "abc") parseProgram True "Π a : A . C (S a)" `shouldBe` Pi (B "a") (Var "A") (Ap (Var "C") (Ap (Var "S") (Var "a"))) it "parse Function type" $ do parseProgram False "() -> []" `shouldBe` Pi Wildcard Unit One parseProgram False "(A : U) -> A" `shouldBe` Pi (B "A") (U 0) (Var "A") parseProgram False "(A : U) → (b : A) → ()" `shouldBe` Pi (B "A") (U 0) (Pi (B "b") (Var "A") Unit) parseProgram False "(_ : A) -> B" `shouldBe` parseProgram False "A -> B" parseProgram False "(a : A) -> C (S a)" `shouldBe` Pi (B "a") (Var "A") (Ap (Var "C") (Ap (Var "S") (Var "a"))) it "parse Dependent Sum" $ do parseProgram False "Σ abc : U . abc" `shouldBe` Sigma (B "abc") (U 0) (Var "abc") parseProgram False "Σabc: U. abc" `shouldBe` Sigma (B "abc") (U 0) (Var "abc") parseProgram False "Σ x : V . T x → V" `shouldBe` Sigma (B "x") (Var "V") (Pi Wildcard (Ap (Var "T") (Var "x")) (Var "V")) it "parse Projections" $ do parseProgram False "π1.abc" `shouldBe` P1 (Var "abc") parseProgram False "π2.abc" `shouldBe` P2 (Var "abc") it "parse Pairing" $ parseProgram False "(abc,12)" `shouldBe` Pair (Var "abc") (I 12) it "parses Constructor w/ Pairing" $ parseProgram False "foo (abc,12)" `shouldBe` Ap (Var "foo") (Pair (Var "abc") (I 12)) it "parses Labelled Sum" $ do parseProgram False "Sum(foo [] | bar Nat)" `shouldBe` Sum [Choice "foo" (Just One), Choice "bar" (Just $ Var "Nat")] parseProgram False "Sum(foo[] | bar (Nat, Bool))" `shouldBe` Sum [Choice "foo" (Just One), Choice "bar" (Just $ Pair (Var "Nat") (Var "Bool"))] parseProgram False "Sum(foo | bar)" `shouldBe` Sum [Choice "foo" Nothing, Choice "bar" Nothing] parseProgram False "Sum ( foo | bar )" `shouldBe` Sum [Choice "foo" Nothing, Choice "bar" Nothing] it "parses Case choices" $ do parseProgram False "case (foo 12 -> h1 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs (C $ I 12) (Var "h1")), Clause "bar" (Abs (B "x") (Var "h2"))] parseProgram False "case (foo -> 12 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs Wildcard (I 12)), Clause "bar" (Abs (B "x") (Var "h2"))] it "parses Pattern" $ do parseProgram False "λ (abc, xyz) . abc" `shouldBe` Abs (Pat (B "abc") (B "xyz")) (Var "abc") parseProgram False "Π (abc, xyz): U . abc" `shouldBe` Pi (Pat (B "abc") (B "xyz")) (U 0) (Var "abc") it "parses single-line comments after an expression" $ do parseProgram False "() -- this is a comment" `shouldBe` Unit parseProgram False "[] -- this is a comment" `shouldBe` One parseProgram False "-- this is a comment\n()" `shouldBe` Unit parseProgram False "λ -- this is a comment\n(abc, xyz) . abc" `shouldBe` Abs (Pat (B "abc") (B "xyz")) (Var "abc") parseProgram False "case -- a comment\n (foo -- a comment \n-> 12 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs Wildcard (I 12)), Clause "bar" (Abs (B "x") (Var "h2"))] it "parses multiline comments" $ do parseProgram False "case {- this is a multiline \n comment -} (foo -- a comment \n-> 12 | bar x -> h2)" `shouldBe` Case [Clause "foo" (Abs Wildcard (I 12)), Clause "bar" (Abs (B "x") (Var "h2"))] parseProgram False "{- this is a multiline comment -}\nlet x : Unit -> [] = case (tt -> ())" `shouldBe` Let (Decl (B "x") (Pi Wildcard (Var "Unit") One) (Case [Clause "tt" (Abs Wildcard Unit)])) Unit it "parses holes" $ do pending parseProgram False "λ x . ?hole" `shouldBe` Abs (Pat (B "abc") (B "xyz")) (Hole "hole") describe "Declarations" $ do it "parses generic id function" $ parseDecl "id : Π A : U . Π _ : A . A = λ A . λ x . x" `shouldBe` Decl (B "id") (Pi (B "A") (U 0) (Pi Wildcard (Var "A") (Var "A"))) (Abs (B "A") (Abs (B "x") (Var "x"))) it "parses Bool declaration" $ do parseDecl "Bool : U = Sum (true | false)" `shouldBe` Decl (B "Bool") (U 0) (Sum [Choice "true" Nothing, Choice "false" Nothing]) parseDecl "Bool : U = Sum(true| false)" `shouldBe` Decl (B "Bool") (U 0) (Sum [Choice "true" Nothing, Choice "false" Nothing]) it "parses some declaration" $ parseProgram False "let x : Unit -> [] = case (tt -> ());()" `shouldBe` Let ( Decl (B "x") (Pi Wildcard (Var "Unit") One) (Case [Clause "tt" (Abs Wildcard Unit)]) ) Unit it "parses Bool elimination" $ parseDecl "elimBool : Π C : Bool → U . C false → C true → Π b : Bool . C b = λ C . λ h0 . λ h1 . case (true → h1 | false → h0)" `shouldBe` Decl (B "elimBool") ( Pi (B "C") (Pi Wildcard (Var "Bool") (U 0)) ( Pi Wildcard (Ap (Var "C") (Var "false")) ( Pi Wildcard (Ap (Var "C") (Var "true")) ( Pi (B "b") (Var "Bool") (Ap (Var "C") (Var "b")) ) ) ) ) ( Abs (B "C") ( Abs (B "h0") ( Abs (B "h1") ( Case [ Clause "true" (Abs Wildcard (Var "h1")) , Clause "false" (Abs Wildcard (Var "h0")) ] ) ) ) ) it "parses Nat declaration" $ parseDecl "rec Nat : U = Sum (zero | succ Nat)" `shouldBe` RDecl (B "Nat") (U 0) (Sum [Choice "zero" Nothing, Choice "succ" (Just $ Var "Nat")]) it "parses recursive-inductive universe let" $ parseDecl "rec (V,T) : ΣX:U.X -> U = (Sum(nat | pi (Σ x : V . T x → V)) , case (nat → Nat | pi (x, f ) → Π y : T x . T (f y)))" `shouldBe` RDecl (Pat (B "V") (B "T")) ( Sigma (B "X") (U 0) (Pi Wildcard (Var "X") (U 0)) ) ( Pair ( Sum [ Choice "nat" Nothing , Choice "pi" ( Just $ Sigma (B "x") (Var "V") ( Pi Wildcard (Ap (Var "T") (Var "x")) (Var "V") ) ) ] ) ( Case [ Clause "nat" (Abs Wildcard (Var "Nat")) , Clause "pi" ( Abs (Pat (B "x") (B "f")) ( Pi (B "y") (Ap (Var "T") (Var "x")) ( Ap (Var "T") (Ap (Var "f") (Var "y")) ) ) ) ] ) ) it "parses natRec " $ parseProgram False "let rec natrec : Π C : Nat → U . C zero → (Π n : Nat.C n → C (succ n)) → Π n : Nat . C n = λ C . λ a . λ g . case (zero → a | succ n1 → (g n1) ((((natrec C) a) g) n1)); ()" `shouldBe` Let ( RDecl (B "natrec") ( Pi (B "C") (Pi Wildcard (Var "Nat") (U 0)) ( Pi Wildcard (Ap (Var "C") (Var "zero")) ( Pi Wildcard ( Pi (B "n") (Var "Nat") ( Pi Wildcard (Ap (Var "C") (Var "n")) ( Ap (Var "C") (Ap (Var "succ") (Var "n")) ) ) ) ( Pi (B "n") (Var "Nat") (Ap (Var "C") (Var "n")) ) ) ) ) ( Abs (B "C") ( Abs (B "a") ( Abs (B "g") ( Case [ Clause "zero" (Abs Wildcard (Var "a")) , Clause "succ" ( Abs (B "n1") ( Ap (Ap (Var "g") (Var "n1")) ( Ap ( Ap ( Ap ( Ap (Var "natrec") (Var "C") ) (Var "a") ) (Var "g") ) (Var "n1") ) ) ) ] ) ) ) ) ) Unit it "parses a program" $ parseProgram False ("let rec Nat : U = Sum (zero | succ Nat) ;\n" <> "let id : Π A : U . Π _ : A . A = λ A . λ x . x; ()") `shouldBe` Let (RDecl (B "Nat") (U 0) (Sum [Choice "zero" Nothing, Choice "succ" (Just $ Var "Nat")])) ( Let ( Decl (B "id") (Pi (B "A") (U 0) (Pi Wildcard (Var "A") (Var "A"))) (Abs (B "A") (Abs (B "x") (Var "x"))) ) Unit ) it "parses another program" $ parseProgram False "let Unit : U = Sum (tt); let elimUnit : Π C : Unit -> U. C tt -> Π x:Unit. C x = λ C . λ h . case (tt -> h); ()" `shouldBe` Let ( Decl (B "Unit") (U 0) (Sum [Choice "tt" Nothing]) ) ( Let ( Decl (B "elimUnit") ( Pi (B "C") (Pi Wildcard (Var "Unit") (U 0)) ( Pi Wildcard (Ap (Var "C") (Var "tt")) (Pi (B "x") (Var "Unit") (Ap (Var "C") (Var "x"))) ) ) (Abs (B "C") (Abs (B "h") (Case [Clause "tt" (Abs Wildcard (Var "h"))]))) ) Unit ) it "parses a multiline program" $ parseProgram False ( Text.unlines [ "let rec NEList : Π A : U . U = λ A . Sum(S A | C (Σ a : A . NEList A));" , "let elimNEList : Π A : U . Π C : NEList A -> U . (Π a : A . C (S a)) -> (Π a : (Σ _ : A . NEList A) . C (C a)) -> Π b : NEList A . C b " , " = λ A . λ C . λ h0 . λ h1 . case (S a -> h0 a | C a -> h1 a);" , "let select : NEList Bool -> U = case (S _ -> Unit | C _ -> Unit);" , "()" ] ) `shouldBe` Let (RDecl (B "NEList") (Pi (B "A") (U 0) (U 0)) (Abs (B "A") (Sum [Choice "S" (Just (Var "A")), Choice "C" (Just (Sigma (B "a") (Var "A") (Ap (Var "NEList") (Var "A"))))]))) (Let (Decl (B "elimNEList") (Pi (B "A") (U 0) (Pi (B "C") (Pi Wildcard (Ap (Var "NEList") (Var "A")) (U 0)) (Pi Wildcard (Pi (B "a") (Var "A") (Ap (Var "C") (Ap (Var "S") (Var "a")))) (Pi Wildcard (Pi (B "a") (Sigma Wildcard (Var "A") (Ap (Var "NEList") (Var "A"))) (Ap (Var "C") (Ap (Var "C") (Var "a")))) (Pi (B "b") (Ap (Var "NEList") (Var "A")) (Ap (Var "C") (Var "b"))))))) (Abs (B "A") (Abs (B "C") (Abs (B "h0") (Abs (B "h1") (Case [Clause "S" (Abs (B "a") (Ap (Var "h0") (Var "a"))), Clause "C" (Abs (B "a") (Ap (Var "h1") (Var "a")))])))))) (Let (Decl (B "select") (Pi Wildcard (Ap (Var "NEList") (Var "Bool")) (U 0)) (Case [Clause "S" (Abs Wildcard (Var "Unit")), Clause "C" (Abs Wildcard (Var "Unit"))])) Unit)) describe "Error handling" $ do describe "skipErrorTo" $ it "consumes tokens until some parser succeeds then yields an Error" $ do let fragment = do a <- skipErrorTo [scolon] b <- scolon *> term pure $ Ap a b doParse fragment "fooo ; bar" `shouldBe` Ap (Err $ newErrorMessage (Message "found 'fooo ' between (1,1) and (1,6)") (newPos "" 1 6)) (Var "bar") it "inserts an Err node in AST on error in let" $ do let errorNode = Err $ newErrorMessage (Message "found 'case (tt -> ()' between (1,22) and (1,36)") (newPos "" 1 36) parseProgram False "let x : Unit -> [] = case (tt -> ();()" `shouldBe` Let ( Decl (B "x") (Pi Wildcard (Var "Unit") One) errorNode ) Unit it "inserts an Err node in AST on error in case clause" $ do let errorNode = Err $ newErrorMessage (Message "found '-> ' between (1,31) and (1,34)") (newPos "" 1 34) parseProgram False "let x : Unit -> [] = case (tt -> | ff -> ());()" `shouldBe` Let ( Decl (B "x") (Pi Wildcard (Var "Unit") One) ( Case [ Clause "tt" errorNode , Clause "ff" (Abs Wildcard Unit) ] ) ) Unit
19f7d155eef11cbf56980d07ce13f96b299d5184fdd8c46c44f939f97ffc21a6
oriansj/mes-m2
firstclassops.scm
GNU --- Maxwell Equations of Software Copyright ( C ) 2008 Kragen ;;; This file is part of GNU . ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; GNU is distributed in the hope that it will be useful , but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > ;; Setup output file (set-current-output-port (open-output-file "test/results/test063.answer")) (define (newline) (display #\newline)) (define (for-each f l) (if (null? l) *unspecified* (begin (f (car l)) (for-each f (cdr l))))) Test that + and - are first - class values . At first they were n't ! (define (map2 op a b) ; only necessary because Ur-Scheme map is binary (cond ((and (null? a) (null? b)) '()) ((null? a) (error "mismatched list lengths in map2")) (else (cons (op (car a) (car b)) (map2 op (cdr a) (cdr b)))))) (define (pr num) (display (number->string num)) (newline)) (for-each pr (map2 + '(0 1 3 5 70) '(1 2 3 4 5))) (for-each pr (map2 - '(0 1 3 5 70) '(1 2 3 4 5))) (exit 0)
null
https://raw.githubusercontent.com/oriansj/mes-m2/b44fbc976ae334252de4eb82a57c361a195f2194/test/test063/firstclassops.scm
scheme
you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Setup output file only necessary because Ur-Scheme map is binary
GNU --- Maxwell Equations of Software Copyright ( C ) 2008 Kragen This file is part of GNU . under the terms of the GNU General Public License as published by GNU is distributed in the hope that it will be useful , but You should have received a copy of the GNU General Public License along with GNU . If not , see < / > (set-current-output-port (open-output-file "test/results/test063.answer")) (define (newline) (display #\newline)) (define (for-each f l) (if (null? l) *unspecified* (begin (f (car l)) (for-each f (cdr l))))) Test that + and - are first - class values . At first they were n't ! (cond ((and (null? a) (null? b)) '()) ((null? a) (error "mismatched list lengths in map2")) (else (cons (op (car a) (car b)) (map2 op (cdr a) (cdr b)))))) (define (pr num) (display (number->string num)) (newline)) (for-each pr (map2 + '(0 1 3 5 70) '(1 2 3 4 5))) (for-each pr (map2 - '(0 1 3 5 70) '(1 2 3 4 5))) (exit 0)
59aa6fa828db0283eaabb2c73252bc70ea46e0f4f2159dee1048e7dacacc2697
janestreet/bonsai
bonsai_experimental_animation.ml
open! Core open Bonsai.Let_syntax open Bonsai.For_open module _ = struct type t = float * float [@@deriving sexp, equal] end module Callback = struct type t = unit Effect.t let sexp_of_t = sexp_of_opaque let t_of_sexp _ = failwith "stop using tangle" let equal = phys_equal end module Interpolator = struct type t = | Linear | Ease_in_quad | Ease_out_quad | Ease_in_out_quad | Ease_in_cubic | Ease_out_cubic | Ease_in_out_cubic | Ease_in_quart | Ease_out_quart | Ease_in_out_quart | Ease_in_quint | Ease_out_quint | Ease_in_out_quint | Ease_in_sin | Ease_out_sin | Ease_in_out_sin | Ease_in_exp | Ease_out_exp | Ease_in_out_exp | Ease_in_circ | Ease_out_circ | Ease_in_out_circ | Ease_in_back | Ease_out_back | Ease_in_out_back [@@deriving sexp, equal, enumerate, compare] let to_f = let open Float in function | Linear -> fun t -> t | Ease_in_quad -> fun t -> t * t | Ease_out_quad -> fun t -> t * (2.0 - t) | Ease_in_out_quad -> (function | t when t < 0.5 -> 2.0 * t * t | t -> -1.0 + ((4.0 - (2.0 * t)) * t)) | Ease_in_cubic -> fun t -> t * t * t | Ease_out_cubic -> fun t -> let t = t - 1.0 in (-t * t * t) + 1.0 | Ease_in_out_cubic -> (function | t when t < 0.5 -> 4.0 * t * t * t | t -> ((t - 1.0) * ((2.0 * t) - 2.0) * ((2.0 * t) - 2.0)) + 1.0) | Ease_in_quart -> fun t -> t * t * t * t | Ease_out_quart -> fun t -> let t = t - 1.0 in 1.0 - (t * t * t * t) | Ease_in_out_quart -> (function | t when t < 0.5 -> 8.0 * t * t * t * t | t -> let t = t - 1.0 in 1.0 - (8.0 * t * t * t * t)) | Ease_in_quint -> fun t -> t * t * t * t * t | Ease_out_quint -> fun t -> let t = t - 1.0 in 1.0 + (t * t * t * t * t) | Ease_in_out_quint -> (function | t when t < 0.5 -> 16.0 * t * t * t * t * t | t -> let t = t - 1.0 in 1.0 + (16.0 * t * t * t * t * t)) | Ease_in_sin -> fun t -> 1.0 - cos (t * pi / 2.0) | Ease_out_sin -> fun t -> sin (t * pi / 2.0) | Ease_in_out_sin -> fun t -> -(cos (pi * t) - 1.0) / 2.0 | Ease_in_exp -> (function | 0.0 -> 0.0 | t -> 2.0 ** ((10.0 * t) - 10.0)) | Ease_out_exp -> (function | 1.0 -> 1.0 | t -> 1.0 - (2.0 ** (-10.0 * t))) | Ease_in_out_exp -> (function | 0.0 -> 0.0 | 1.0 -> 1.0 | t when t < 0.5 -> (2.0 ** ((20.0 * t) - 10.0)) / 2.0 | t -> 2.0 - ((2.0 ** ((-20.0 * t) + 10.0)) / 2.0)) | Ease_in_circ -> fun t -> 1.0 - sqrt (1.0 - (t ** 2.0)) | Ease_out_circ -> fun t -> sqrt (1.0 - ((t - 1.0) ** 2.0)) | Ease_in_out_circ -> (function | t when t < 0.5 -> (1.0 - sqrt (1.0 - ((2.0 * t) ** 2.0))) / 2.0 | t -> (sqrt (1.0 - (((-2.0 * t) + 2.0) ** 2.0)) + 1.0) / 2.0) | Ease_in_back -> let c1 = 1.70158 in let c3 = c1 + 1.0 in fun t -> (c3 * t * t * t) - (c1 * t * t) | Ease_out_back -> let c1 = 1.70158 in let c3 = c1 + 1.0 in fun t -> 1.0 + (c3 * ((t - 1.0) ** 3.0)) + (c1 * ((t - 1.0) ** 2.0)) | Ease_in_out_back -> let c1 = 1.70158 in let c2 = c1 * 1.525 in (function | t when t < 0.5 -> ((2.0 * t) ** 2.0) * (((c2 + 1.0) * 2.0 * t) - c2) / 2.0 | t -> (((((2.0 * t) - 2.0) ** 2.0) * (((c2 + 1.0) * ((t * 2.0) - 2.0)) + c2)) + 2.0) / 2.0) ;; end type 'a t = { value : 'a ; animate : ?after_finished:Callback.t -> ?with_:Interpolator.t -> [ `End_at of Time_ns.t | `For of Time_ns.Span.t | `Now ] -> 'a -> unit Effect.t } let curtime = Effect.of_sync_fun (fun () -> Ui_incr.Clock.now Ui_incr.clock) () module Interpolatable = struct type 'a t = 'a -> 'a -> float -> 'a let float low high percent_float = (low *. (1.0 -. percent_float)) +. (high *. percent_float) ;; let int low high percent_float = float (Int.to_float low) (Int.to_float high) percent_float |> Float.round_nearest_half_to_even |> Float.to_int ;; end let make : type a. fallback:a Value.t -> interpolate:(a -> a -> float -> a) -> a t Computation.t = fun ~fallback ~interpolate -> let module A_star_a = struct type t = a * a let sexp_of_t = sexp_of_opaque let t_of_sexp _ = assert false let equal (a, b) (c, d) = phys_equal a c && phys_equal b d end in let%sub start_time, set_start = Bonsai.state_opt (module Time_ns.Alternate_sexp) in let%sub interpolator, set_interpolator = Bonsai.state (module Interpolator) ~default_model:Interpolator.Linear in let%sub end_time, set_end = Bonsai.state_opt (module Time_ns.Alternate_sexp) in let%sub callback, set_callback = Bonsai.state_opt (module Callback) in let%sub range, set_range = Bonsai.state_opt (module A_star_a) in let%sub percent_float = match%sub Value.both start_time end_time with | None, _ | _, None -> Bonsai.const 0.0 | Some start_time, Some end_time -> let%sub before_or_after = Bonsai.Clock.at end_time in let%sub () = match%sub callback with | None -> Bonsai.const () | Some callback -> let callback = let%map callback = callback and set_callback = set_callback in fun prev new_ -> let remove_callback = set_callback None in match prev, new_ with | ( Some Bonsai.Clock.Before_or_after.Before , Bonsai.Clock.Before_or_after.After ) -> Effect.Many [ remove_callback; callback ] | _ -> Effect.Ignore in Bonsai.Edge.on_change' (module Bonsai.Clock.Before_or_after) before_or_after ~callback in (match%sub before_or_after with | After -> Bonsai.const 1.0 | Before -> let%sub cur_time = Bonsai.Clock.now in let%arr start_time = start_time and end_time = end_time and cur_time = cur_time in let range_delta = Time_ns.abs_diff end_time start_time in let cur_delta = Time_ns.abs_diff cur_time start_time in Time_ns.Span.to_ms cur_delta /. Time_ns.Span.to_ms range_delta) in let interpolator = Value.map interpolator ~f:Interpolator.to_f in let%sub value = let%arr fallback = fallback and percent_float = percent_float and interpolator = interpolator and range = range in let percent_float = interpolator percent_float in match range with | None -> fallback | Some (low, high) -> interpolate low high percent_float in let%sub get_value = Bonsai.yoink value in let%sub animate = let%arr set_start = set_start and set_end = set_end and set_callback = set_callback and set_interpolator = set_interpolator and set_range = set_range and get_value = get_value in fun ?after_finished ?with_ time target -> let%bind.Effect now = curtime in let%bind.Effect value = match%bind.Effect get_value with | Active value -> Effect.return value | Inactive -> Effect.never in let target_time = match time with | `End_at time -> time | `For delta -> Time_ns.add now delta | `Now -> now in let effects = [ set_start (Some now) ; set_end (Some target_time) ; set_range (Some (value, target)) ] in let effects = match after_finished with | None -> effects | Some callback -> set_callback (Some callback) :: effects in let effects = match with_ with | None -> effects | Some interpolator -> set_interpolator interpolator :: effects in Effect.Many effects in let%arr value = value and animate = animate in { value; animate } ;; let smooth m ?(with_ = Interpolator.Linear) ~duration ~interpolate v = let%sub { value; animate } = make ~fallback:v ~interpolate in let%sub () = let callback = let%map animate = animate and duration = duration in fun new_ -> animate (`For duration) ~with_ new_ in Bonsai.Edge.on_change m v ~callback in return value ;; module Advanced = struct type nonrec 'a t = 'a t = { value : 'a ; animate : ?after_finished:Callback.t -> ?with_:Interpolator.t -> [ `End_at of Time_ns.t | `For of Time_ns.Span.t | `Now ] -> 'a -> unit Effect.t } let make = make end
null
https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/experimental/animation/src/bonsai_experimental_animation.ml
ocaml
open! Core open Bonsai.Let_syntax open Bonsai.For_open module _ = struct type t = float * float [@@deriving sexp, equal] end module Callback = struct type t = unit Effect.t let sexp_of_t = sexp_of_opaque let t_of_sexp _ = failwith "stop using tangle" let equal = phys_equal end module Interpolator = struct type t = | Linear | Ease_in_quad | Ease_out_quad | Ease_in_out_quad | Ease_in_cubic | Ease_out_cubic | Ease_in_out_cubic | Ease_in_quart | Ease_out_quart | Ease_in_out_quart | Ease_in_quint | Ease_out_quint | Ease_in_out_quint | Ease_in_sin | Ease_out_sin | Ease_in_out_sin | Ease_in_exp | Ease_out_exp | Ease_in_out_exp | Ease_in_circ | Ease_out_circ | Ease_in_out_circ | Ease_in_back | Ease_out_back | Ease_in_out_back [@@deriving sexp, equal, enumerate, compare] let to_f = let open Float in function | Linear -> fun t -> t | Ease_in_quad -> fun t -> t * t | Ease_out_quad -> fun t -> t * (2.0 - t) | Ease_in_out_quad -> (function | t when t < 0.5 -> 2.0 * t * t | t -> -1.0 + ((4.0 - (2.0 * t)) * t)) | Ease_in_cubic -> fun t -> t * t * t | Ease_out_cubic -> fun t -> let t = t - 1.0 in (-t * t * t) + 1.0 | Ease_in_out_cubic -> (function | t when t < 0.5 -> 4.0 * t * t * t | t -> ((t - 1.0) * ((2.0 * t) - 2.0) * ((2.0 * t) - 2.0)) + 1.0) | Ease_in_quart -> fun t -> t * t * t * t | Ease_out_quart -> fun t -> let t = t - 1.0 in 1.0 - (t * t * t * t) | Ease_in_out_quart -> (function | t when t < 0.5 -> 8.0 * t * t * t * t | t -> let t = t - 1.0 in 1.0 - (8.0 * t * t * t * t)) | Ease_in_quint -> fun t -> t * t * t * t * t | Ease_out_quint -> fun t -> let t = t - 1.0 in 1.0 + (t * t * t * t * t) | Ease_in_out_quint -> (function | t when t < 0.5 -> 16.0 * t * t * t * t * t | t -> let t = t - 1.0 in 1.0 + (16.0 * t * t * t * t * t)) | Ease_in_sin -> fun t -> 1.0 - cos (t * pi / 2.0) | Ease_out_sin -> fun t -> sin (t * pi / 2.0) | Ease_in_out_sin -> fun t -> -(cos (pi * t) - 1.0) / 2.0 | Ease_in_exp -> (function | 0.0 -> 0.0 | t -> 2.0 ** ((10.0 * t) - 10.0)) | Ease_out_exp -> (function | 1.0 -> 1.0 | t -> 1.0 - (2.0 ** (-10.0 * t))) | Ease_in_out_exp -> (function | 0.0 -> 0.0 | 1.0 -> 1.0 | t when t < 0.5 -> (2.0 ** ((20.0 * t) - 10.0)) / 2.0 | t -> 2.0 - ((2.0 ** ((-20.0 * t) + 10.0)) / 2.0)) | Ease_in_circ -> fun t -> 1.0 - sqrt (1.0 - (t ** 2.0)) | Ease_out_circ -> fun t -> sqrt (1.0 - ((t - 1.0) ** 2.0)) | Ease_in_out_circ -> (function | t when t < 0.5 -> (1.0 - sqrt (1.0 - ((2.0 * t) ** 2.0))) / 2.0 | t -> (sqrt (1.0 - (((-2.0 * t) + 2.0) ** 2.0)) + 1.0) / 2.0) | Ease_in_back -> let c1 = 1.70158 in let c3 = c1 + 1.0 in fun t -> (c3 * t * t * t) - (c1 * t * t) | Ease_out_back -> let c1 = 1.70158 in let c3 = c1 + 1.0 in fun t -> 1.0 + (c3 * ((t - 1.0) ** 3.0)) + (c1 * ((t - 1.0) ** 2.0)) | Ease_in_out_back -> let c1 = 1.70158 in let c2 = c1 * 1.525 in (function | t when t < 0.5 -> ((2.0 * t) ** 2.0) * (((c2 + 1.0) * 2.0 * t) - c2) / 2.0 | t -> (((((2.0 * t) - 2.0) ** 2.0) * (((c2 + 1.0) * ((t * 2.0) - 2.0)) + c2)) + 2.0) / 2.0) ;; end type 'a t = { value : 'a ; animate : ?after_finished:Callback.t -> ?with_:Interpolator.t -> [ `End_at of Time_ns.t | `For of Time_ns.Span.t | `Now ] -> 'a -> unit Effect.t } let curtime = Effect.of_sync_fun (fun () -> Ui_incr.Clock.now Ui_incr.clock) () module Interpolatable = struct type 'a t = 'a -> 'a -> float -> 'a let float low high percent_float = (low *. (1.0 -. percent_float)) +. (high *. percent_float) ;; let int low high percent_float = float (Int.to_float low) (Int.to_float high) percent_float |> Float.round_nearest_half_to_even |> Float.to_int ;; end let make : type a. fallback:a Value.t -> interpolate:(a -> a -> float -> a) -> a t Computation.t = fun ~fallback ~interpolate -> let module A_star_a = struct type t = a * a let sexp_of_t = sexp_of_opaque let t_of_sexp _ = assert false let equal (a, b) (c, d) = phys_equal a c && phys_equal b d end in let%sub start_time, set_start = Bonsai.state_opt (module Time_ns.Alternate_sexp) in let%sub interpolator, set_interpolator = Bonsai.state (module Interpolator) ~default_model:Interpolator.Linear in let%sub end_time, set_end = Bonsai.state_opt (module Time_ns.Alternate_sexp) in let%sub callback, set_callback = Bonsai.state_opt (module Callback) in let%sub range, set_range = Bonsai.state_opt (module A_star_a) in let%sub percent_float = match%sub Value.both start_time end_time with | None, _ | _, None -> Bonsai.const 0.0 | Some start_time, Some end_time -> let%sub before_or_after = Bonsai.Clock.at end_time in let%sub () = match%sub callback with | None -> Bonsai.const () | Some callback -> let callback = let%map callback = callback and set_callback = set_callback in fun prev new_ -> let remove_callback = set_callback None in match prev, new_ with | ( Some Bonsai.Clock.Before_or_after.Before , Bonsai.Clock.Before_or_after.After ) -> Effect.Many [ remove_callback; callback ] | _ -> Effect.Ignore in Bonsai.Edge.on_change' (module Bonsai.Clock.Before_or_after) before_or_after ~callback in (match%sub before_or_after with | After -> Bonsai.const 1.0 | Before -> let%sub cur_time = Bonsai.Clock.now in let%arr start_time = start_time and end_time = end_time and cur_time = cur_time in let range_delta = Time_ns.abs_diff end_time start_time in let cur_delta = Time_ns.abs_diff cur_time start_time in Time_ns.Span.to_ms cur_delta /. Time_ns.Span.to_ms range_delta) in let interpolator = Value.map interpolator ~f:Interpolator.to_f in let%sub value = let%arr fallback = fallback and percent_float = percent_float and interpolator = interpolator and range = range in let percent_float = interpolator percent_float in match range with | None -> fallback | Some (low, high) -> interpolate low high percent_float in let%sub get_value = Bonsai.yoink value in let%sub animate = let%arr set_start = set_start and set_end = set_end and set_callback = set_callback and set_interpolator = set_interpolator and set_range = set_range and get_value = get_value in fun ?after_finished ?with_ time target -> let%bind.Effect now = curtime in let%bind.Effect value = match%bind.Effect get_value with | Active value -> Effect.return value | Inactive -> Effect.never in let target_time = match time with | `End_at time -> time | `For delta -> Time_ns.add now delta | `Now -> now in let effects = [ set_start (Some now) ; set_end (Some target_time) ; set_range (Some (value, target)) ] in let effects = match after_finished with | None -> effects | Some callback -> set_callback (Some callback) :: effects in let effects = match with_ with | None -> effects | Some interpolator -> set_interpolator interpolator :: effects in Effect.Many effects in let%arr value = value and animate = animate in { value; animate } ;; let smooth m ?(with_ = Interpolator.Linear) ~duration ~interpolate v = let%sub { value; animate } = make ~fallback:v ~interpolate in let%sub () = let callback = let%map animate = animate and duration = duration in fun new_ -> animate (`For duration) ~with_ new_ in Bonsai.Edge.on_change m v ~callback in return value ;; module Advanced = struct type nonrec 'a t = 'a t = { value : 'a ; animate : ?after_finished:Callback.t -> ?with_:Interpolator.t -> [ `End_at of Time_ns.t | `For of Time_ns.Span.t | `Now ] -> 'a -> unit Effect.t } let make = make end
8969e378c45c44c04f1dac5f64a61b1336abdbfff71b15100418e0f9bae5fecc
grin-compiler/ghc-wpc-sample-programs
Treeless.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE PatternSynonyms # -- | The treeless syntax is intended to be used as input for the compiler backends. It is more low - level than Internal syntax and is not used for type checking . -- -- Some of the features of treeless syntax are: -- - case expressions instead of case trees -- - no instantiated datatypes / constructors module Agda.Syntax.Treeless ( module Agda.Syntax.Abstract.Name , module Agda.Syntax.Treeless ) where import Control.Arrow (first, second) import Data.Data (Data) import Data.Word import Agda.Syntax.Position import Agda.Syntax.Literal import Agda.Syntax.Abstract.Name data Compiled = Compiled { cTreeless :: TTerm , cArgUsage :: [Bool] } deriving (Data, Show, Eq, Ord) -- | The treeless compiler can behave differently depending on the target -- language evaluation strategy. For instance, more aggressive erasure for -- lazy targets. data EvaluationStrategy = LazyEvaluation | EagerEvaluation deriving (Eq, Show) type Args = [TTerm] this currently assumes that TApp is translated in a lazy / cbn fashion . The AST should also support strict translation . -- All local variables are using de Bruijn indices . data TTerm = TVar Int | TPrim TPrim | TDef QName | TApp TTerm Args | TLam TTerm | TLit Literal | TCon QName | TLet TTerm TTerm -- ^ introduces a new local binding. The bound term -- MUST only be evaluated if it is used inside the body. -- Sharing may happen, but is optional. -- It is also perfectly valid to just inline the bound term in the body. | TCase Int CaseInfo TTerm [TAlt] -- ^ Case scrutinee (always variable), case type, default value, alternatives First , all TACon alternatives are tried ; then all TAGuard alternatives -- in top to bottom order. -- TACon alternatives must not overlap. | TUnit -- used for levels right now | TSort | TErased ^ Used by the GHC backend | TError TError -- ^ A runtime error, something bad has happened. deriving (Data, Show, Eq, Ord) -- | Compiler-related primitives. This are NOT the same thing as primitives in Agda 's surface or internal syntax ! -- Some of the primitives have a suffix indicating which type of arguments they take, -- using the following naming convention: -- Char | Type -- C | Character -- F | Float -- I | Integer -- Q | QName -- S | String data TPrim = PAdd | PAdd64 | PSub | PSub64 | PMul | PMul64 | PQuot | PQuot64 | PRem | PRem64 | PGeq | PLt | PLt64 | PEqI | PEq64 | PEqF | PEqS | PEqC | PEqQ | PIf | PSeq | PITo64 | P64ToI deriving (Data, Show, Eq, Ord) isPrimEq :: TPrim -> Bool isPrimEq p = p `elem` [PEqI, PEqF, PEqS, PEqC, PEqQ, PEq64] -- | Strip leading coercions and indicate whether there were some. coerceView :: TTerm -> (Bool, TTerm) coerceView = \case TCoerce t -> (True,) $ snd $ coerceView t t -> (False, t) mkTApp :: TTerm -> Args -> TTerm mkTApp x [] = x mkTApp (TApp x as) bs = TApp x (as ++ bs) mkTApp x as = TApp x as tAppView :: TTerm -> (TTerm, [TTerm]) tAppView = \case TApp a bs -> second (++ bs) $ tAppView a t -> (t, []) | Expose the format @coerce f args@. -- -- We fuse coercions, even if interleaving with applications. -- We assume that coercion is powerful enough to satisfy -- @ -- coerce (coerce f a) b = coerce f a b -- @ coerceAppView :: TTerm -> ((Bool, TTerm), [TTerm]) coerceAppView = \case TCoerce t -> first ((True,) . snd) $ coerceAppView t TApp a bs -> second (++ bs) $ coerceAppView a t -> ((False, t), []) tLetView :: TTerm -> ([TTerm], TTerm) tLetView (TLet e b) = first (e :) $ tLetView b tLetView e = ([], e) tLamView :: TTerm -> (Int, TTerm) tLamView = go 0 where go n (TLam b) = go (n + 1) b go n t = (n, t) mkTLam :: Int -> TTerm -> TTerm mkTLam n b = foldr ($) b $ replicate n TLam -- | Introduces a new binding mkLet :: TTerm -> TTerm -> TTerm mkLet x body = TLet x body tInt :: Integer -> TTerm tInt = TLit . LitNat noRange intView :: TTerm -> Maybe Integer intView (TLit (LitNat _ x)) = Just x intView _ = Nothing word64View :: TTerm -> Maybe Word64 word64View (TLit (LitWord64 _ x)) = Just x word64View _ = Nothing tPlusK :: Integer -> TTerm -> TTerm tPlusK 0 n = n tPlusK k n | k < 0 = tOp PSub n (tInt (-k)) tPlusK k n = tOp PAdd (tInt k) n -- -(k + n) tNegPlusK :: Integer -> TTerm -> TTerm tNegPlusK k n = tOp PSub (tInt (-k)) n plusKView :: TTerm -> Maybe (Integer, TTerm) plusKView (TApp (TPrim PAdd) [k, n]) | Just k <- intView k = Just (k, n) plusKView (TApp (TPrim PSub) [n, k]) | Just k <- intView k = Just (-k, n) plusKView _ = Nothing negPlusKView :: TTerm -> Maybe (Integer, TTerm) negPlusKView (TApp (TPrim PSub) [k, n]) | Just k <- intView k = Just (-k, n) negPlusKView _ = Nothing tOp :: TPrim -> TTerm -> TTerm -> TTerm tOp op a b = TPOp op a b pattern TPOp :: TPrim -> TTerm -> TTerm -> TTerm pattern TPOp op a b = TApp (TPrim op) [a, b] pattern TPFn :: TPrim -> TTerm -> TTerm pattern TPFn op a = TApp (TPrim op) [a] tUnreachable :: TTerm tUnreachable = TError TUnreachable tIfThenElse :: TTerm -> TTerm -> TTerm -> TTerm tIfThenElse c i e = TApp (TPrim PIf) [c, i, e] data CaseType = CTData QName -- case on datatype | CTNat | CTInt | CTChar | CTString | CTFloat | CTQName deriving (Data, Show, Eq, Ord) data CaseInfo = CaseInfo { caseLazy :: Bool , caseType :: CaseType } deriving (Data, Show, Eq, Ord) data TAlt = TACon { aCon :: QName, aArity :: Int, aBody :: TTerm } -- ^ Matches on the given constructor. If the match succeeds, -- the pattern variables are prepended to the current environment -- (pushes all existing variables aArity steps further away) | TAGuard { aGuard :: TTerm, aBody :: TTerm } -- ^ Binds no variables | TALit { aLit :: Literal, aBody:: TTerm } deriving (Data, Show, Eq, Ord) data TError = TUnreachable -- ^ Code which is unreachable. E.g. absurd branches or missing case defaults. -- Runtime behaviour of unreachable code is undefined, but preferably -- the program will exit with an error message. The compiler is free -- to assume that this code is unreachable and to remove it. deriving (Data, Show, Eq, Ord) class Unreachable a where -- | Checks if the given expression is unreachable or not. isUnreachable :: a -> Bool instance Unreachable TAlt where isUnreachable = isUnreachable . aBody instance Unreachable TTerm where isUnreachable (TError TUnreachable{}) = True isUnreachable (TLet _ b) = isUnreachable b isUnreachable _ = False instance KillRange Compiled where killRange c = c -- bogus, but not used anyway
null
https://raw.githubusercontent.com/grin-compiler/ghc-wpc-sample-programs/0e3a9b8b7cc3fa0da7c77fb7588dd4830fb087f7/Agda-2.6.1/src/full/Agda/Syntax/Treeless.hs
haskell
# LANGUAGE DeriveDataTypeable # | The treeless syntax is intended to be used as input for the compiler backends. Some of the features of treeless syntax are: - case expressions instead of case trees - no instantiated datatypes / constructors | The treeless compiler can behave differently depending on the target language evaluation strategy. For instance, more aggressive erasure for lazy targets. ^ introduces a new local binding. The bound term MUST only be evaluated if it is used inside the body. Sharing may happen, but is optional. It is also perfectly valid to just inline the bound term in the body. ^ Case scrutinee (always variable), case type, default value, alternatives in top to bottom order. TACon alternatives must not overlap. used for levels right now ^ A runtime error, something bad has happened. | Compiler-related primitives. This are NOT the same thing as primitives Some of the primitives have a suffix indicating which type of arguments they take, using the following naming convention: Char | Type C | Character F | Float I | Integer Q | QName S | String | Strip leading coercions and indicate whether there were some. We fuse coercions, even if interleaving with applications. We assume that coercion is powerful enough to satisfy @ coerce (coerce f a) b = coerce f a b @ | Introduces a new binding -(k + n) case on datatype ^ Matches on the given constructor. If the match succeeds, the pattern variables are prepended to the current environment (pushes all existing variables aArity steps further away) ^ Binds no variables ^ Code which is unreachable. E.g. absurd branches or missing case defaults. Runtime behaviour of unreachable code is undefined, but preferably the program will exit with an error message. The compiler is free to assume that this code is unreachable and to remove it. | Checks if the given expression is unreachable or not. bogus, but not used anyway
# LANGUAGE PatternSynonyms # It is more low - level than Internal syntax and is not used for type checking . module Agda.Syntax.Treeless ( module Agda.Syntax.Abstract.Name , module Agda.Syntax.Treeless ) where import Control.Arrow (first, second) import Data.Data (Data) import Data.Word import Agda.Syntax.Position import Agda.Syntax.Literal import Agda.Syntax.Abstract.Name data Compiled = Compiled { cTreeless :: TTerm , cArgUsage :: [Bool] } deriving (Data, Show, Eq, Ord) data EvaluationStrategy = LazyEvaluation | EagerEvaluation deriving (Eq, Show) type Args = [TTerm] this currently assumes that TApp is translated in a lazy / cbn fashion . The AST should also support strict translation . All local variables are using de Bruijn indices . data TTerm = TVar Int | TPrim TPrim | TDef QName | TApp TTerm Args | TLam TTerm | TLit Literal | TCon QName | TLet TTerm TTerm | TCase Int CaseInfo TTerm [TAlt] First , all TACon alternatives are tried ; then all TAGuard alternatives | TSort | TErased ^ Used by the GHC backend | TError TError deriving (Data, Show, Eq, Ord) in Agda 's surface or internal syntax ! data TPrim = PAdd | PAdd64 | PSub | PSub64 | PMul | PMul64 | PQuot | PQuot64 | PRem | PRem64 | PGeq | PLt | PLt64 | PEqI | PEq64 | PEqF | PEqS | PEqC | PEqQ | PIf | PSeq | PITo64 | P64ToI deriving (Data, Show, Eq, Ord) isPrimEq :: TPrim -> Bool isPrimEq p = p `elem` [PEqI, PEqF, PEqS, PEqC, PEqQ, PEq64] coerceView :: TTerm -> (Bool, TTerm) coerceView = \case TCoerce t -> (True,) $ snd $ coerceView t t -> (False, t) mkTApp :: TTerm -> Args -> TTerm mkTApp x [] = x mkTApp (TApp x as) bs = TApp x (as ++ bs) mkTApp x as = TApp x as tAppView :: TTerm -> (TTerm, [TTerm]) tAppView = \case TApp a bs -> second (++ bs) $ tAppView a t -> (t, []) | Expose the format @coerce f args@. coerceAppView :: TTerm -> ((Bool, TTerm), [TTerm]) coerceAppView = \case TCoerce t -> first ((True,) . snd) $ coerceAppView t TApp a bs -> second (++ bs) $ coerceAppView a t -> ((False, t), []) tLetView :: TTerm -> ([TTerm], TTerm) tLetView (TLet e b) = first (e :) $ tLetView b tLetView e = ([], e) tLamView :: TTerm -> (Int, TTerm) tLamView = go 0 where go n (TLam b) = go (n + 1) b go n t = (n, t) mkTLam :: Int -> TTerm -> TTerm mkTLam n b = foldr ($) b $ replicate n TLam mkLet :: TTerm -> TTerm -> TTerm mkLet x body = TLet x body tInt :: Integer -> TTerm tInt = TLit . LitNat noRange intView :: TTerm -> Maybe Integer intView (TLit (LitNat _ x)) = Just x intView _ = Nothing word64View :: TTerm -> Maybe Word64 word64View (TLit (LitWord64 _ x)) = Just x word64View _ = Nothing tPlusK :: Integer -> TTerm -> TTerm tPlusK 0 n = n tPlusK k n | k < 0 = tOp PSub n (tInt (-k)) tPlusK k n = tOp PAdd (tInt k) n tNegPlusK :: Integer -> TTerm -> TTerm tNegPlusK k n = tOp PSub (tInt (-k)) n plusKView :: TTerm -> Maybe (Integer, TTerm) plusKView (TApp (TPrim PAdd) [k, n]) | Just k <- intView k = Just (k, n) plusKView (TApp (TPrim PSub) [n, k]) | Just k <- intView k = Just (-k, n) plusKView _ = Nothing negPlusKView :: TTerm -> Maybe (Integer, TTerm) negPlusKView (TApp (TPrim PSub) [k, n]) | Just k <- intView k = Just (-k, n) negPlusKView _ = Nothing tOp :: TPrim -> TTerm -> TTerm -> TTerm tOp op a b = TPOp op a b pattern TPOp :: TPrim -> TTerm -> TTerm -> TTerm pattern TPOp op a b = TApp (TPrim op) [a, b] pattern TPFn :: TPrim -> TTerm -> TTerm pattern TPFn op a = TApp (TPrim op) [a] tUnreachable :: TTerm tUnreachable = TError TUnreachable tIfThenElse :: TTerm -> TTerm -> TTerm -> TTerm tIfThenElse c i e = TApp (TPrim PIf) [c, i, e] data CaseType | CTNat | CTInt | CTChar | CTString | CTFloat | CTQName deriving (Data, Show, Eq, Ord) data CaseInfo = CaseInfo { caseLazy :: Bool , caseType :: CaseType } deriving (Data, Show, Eq, Ord) data TAlt = TACon { aCon :: QName, aArity :: Int, aBody :: TTerm } | TAGuard { aGuard :: TTerm, aBody :: TTerm } | TALit { aLit :: Literal, aBody:: TTerm } deriving (Data, Show, Eq, Ord) data TError = TUnreachable deriving (Data, Show, Eq, Ord) class Unreachable a where isUnreachable :: a -> Bool instance Unreachable TAlt where isUnreachable = isUnreachable . aBody instance Unreachable TTerm where isUnreachable (TError TUnreachable{}) = True isUnreachable (TLet _ b) = isUnreachable b isUnreachable _ = False instance KillRange Compiled where
74f5358242a461e0d2d8e86706fa02205101d21a51a3e7fc252787ac629144b0
owickstrom/pandoc-emphasize-code
ChunkingTest.hs
{-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -fno - warn - missing - signatures # module Text.Pandoc.Filter.EmphasizeCode.ChunkingTest where import Test.Tasty.Hspec import Text.Pandoc.Filter.EmphasizeCode.Chunking import Text.Pandoc.Filter.EmphasizeCode.Range import Text.Pandoc.Filter.EmphasizeCode.Testing.Ranges spec_emphasizeRanges = do it "emphasizes a single line range" $ do rs <- splitRanges <$> mkPosRanges' [((1, 1), (1, 7))] emphasizeRanges rs "hello world" `shouldBe` [[Emphasized Inline "hello w", Literal "orld"]] it "emphasizes multiple line ranges on a single line" $ do rs <- splitRanges <$> mkPosRanges' [((1, 1), (1, 3)), ((1, 5), (1, 8))] emphasizeRanges rs "hello world" `shouldBe` [ [ Emphasized Inline "hel" , Literal "l" , Emphasized Inline "o wo" , Literal "rld" ] ] it "emphasizes multiple line ranges on multiple lines" $ do rs <- splitRanges <$> mkPosRanges' [((1, 1), (1, 5)), ((1, 7), (2, 3)), ((4, 5), (4, 10))] emphasizeRanges rs "hello world\nhej världen\nhallo welt\nhei verden" `shouldBe` [ [Emphasized Inline "hello", Literal " ", Emphasized Inline "world"] , [Emphasized Inline "hej", Literal " världen"] , [Literal "hallo welt"] , [Literal "hei ", Emphasized Inline "verden"] ] # ANN module ( " HLint : ignore Use camelCase " : : String ) #
null
https://raw.githubusercontent.com/owickstrom/pandoc-emphasize-code/8f2de8fd78206eb6583bb5a6beca492f250cc25e/test/Text/Pandoc/Filter/EmphasizeCode/ChunkingTest.hs
haskell
# LANGUAGE OverloadedStrings #
# OPTIONS_GHC -fno - warn - missing - signatures # module Text.Pandoc.Filter.EmphasizeCode.ChunkingTest where import Test.Tasty.Hspec import Text.Pandoc.Filter.EmphasizeCode.Chunking import Text.Pandoc.Filter.EmphasizeCode.Range import Text.Pandoc.Filter.EmphasizeCode.Testing.Ranges spec_emphasizeRanges = do it "emphasizes a single line range" $ do rs <- splitRanges <$> mkPosRanges' [((1, 1), (1, 7))] emphasizeRanges rs "hello world" `shouldBe` [[Emphasized Inline "hello w", Literal "orld"]] it "emphasizes multiple line ranges on a single line" $ do rs <- splitRanges <$> mkPosRanges' [((1, 1), (1, 3)), ((1, 5), (1, 8))] emphasizeRanges rs "hello world" `shouldBe` [ [ Emphasized Inline "hel" , Literal "l" , Emphasized Inline "o wo" , Literal "rld" ] ] it "emphasizes multiple line ranges on multiple lines" $ do rs <- splitRanges <$> mkPosRanges' [((1, 1), (1, 5)), ((1, 7), (2, 3)), ((4, 5), (4, 10))] emphasizeRanges rs "hello world\nhej världen\nhallo welt\nhei verden" `shouldBe` [ [Emphasized Inline "hello", Literal " ", Emphasized Inline "world"] , [Emphasized Inline "hej", Literal " världen"] , [Literal "hallo welt"] , [Literal "hei ", Emphasized Inline "verden"] ] # ANN module ( " HLint : ignore Use camelCase " : : String ) #
caeae0652a28104d751975e30a80edacec986b0ef98ea6deb065fbd16520e1fe
lsrcz/grisette
EvaluateSymTests.hs
# LANGUAGE FlexibleContexts # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Grisette.Core.Data.Class.EvaluateSymTests where import Control.Monad.Except import Control.Monad.Identity import Control.Monad.Trans.Maybe import qualified Control.Monad.Writer.Lazy as WriterLazy import qualified Control.Monad.Writer.Strict as WriterStrict import qualified Data.ByteString as B import Data.Functor.Sum import qualified Data.HashMap.Strict as M import Data.Int import Data.Word import Grisette.Core.Data.Class.Evaluate import Grisette.TestUtils.Evaluate import Grisette.TestUtils.SBool import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck gevaluateSymTests :: TestTree gevaluateSymTests = testGroup "GEvaluateSymTests" [ testGroup "GEvaluateSym for common types" [ testGroup "SBool" [ let model = M.empty :: M.HashMap Symbol Bool in testGroup "Empty model / no fill default" [ testCase "CBool" $ gevaluateSym False model (CBool True) @=? CBool True, testCase "SSBool" $ gevaluateSym False model (SSBool "a") @=? SSBool "a", testCase "ISBool" $ gevaluateSym False model (ISBool "a" 1) @=? ISBool "a" 1, testCase "Or" $ gevaluateSym False model (Or (SSBool "a") (SSBool "b")) @=? Or (SSBool "a") (SSBool "b"), testCase "And" $ gevaluateSym False model (And (SSBool "a") (SSBool "b")) @=? And (SSBool "a") (SSBool "b"), testCase "Equal" $ gevaluateSym False model (Equal (SSBool "a") (SSBool "b")) @=? Equal (SSBool "a") (SSBool "b"), testCase "Not" $ gevaluateSym False model (Not (SSBool "a")) @=? Not (SSBool "a"), testCase "ITE" $ gevaluateSym False model (ITE (SSBool "a") (SSBool "b") (SSBool "c")) @=? ITE (SSBool "a") (SSBool "b") (SSBool "c") ], let model = M.empty :: M.HashMap Symbol Bool in testGroup "Empty model / with fill default" [ testCase "CBool" $ gevaluateSym True model (CBool True) @=? CBool True, testCase "SSBool" $ gevaluateSym True model (SSBool "a") @=? CBool False, testCase "ISBool" $ gevaluateSym True model (ISBool "a" 1) @=? CBool False, testCase "Or" $ gevaluateSym True model (Or (SSBool "a") (SSBool "b")) @=? CBool False, testCase "And" $ gevaluateSym True model (And (SSBool "a") (SSBool "b")) @=? CBool False, testCase "Equal" $ gevaluateSym True model (Equal (SSBool "a") (SSBool "b")) @=? CBool True, testCase "Not" $ gevaluateSym True model (Not (SSBool "a")) @=? CBool True, testCase "ITE" $ gevaluateSym True model (ITE (SSBool "a") (SSBool "b") (SSBool "c")) @=? CBool False ], let model = M.fromList [ (SSymbol "a", True), (ISymbol "a" 1, False), (SSymbol "b", False), (SSymbol "c", True) ] :: M.HashMap Symbol Bool in testGroup "Some model" [ testCase "CBool" $ gevaluateSym True model (CBool True) @=? CBool True, testCase "SSBool" $ gevaluateSym True model (SSBool "a") @=? CBool True, testCase "ISBool" $ gevaluateSym True model (ISBool "a" 1) @=? CBool False, testCase "Or" $ gevaluateSym True model (Or (SSBool "a") (SSBool "b")) @=? CBool True, testCase "And" $ gevaluateSym True model (And (SSBool "a") (SSBool "b")) @=? CBool False, testCase "Equal" $ gevaluateSym True model (Equal (SSBool "a") (SSBool "b")) @=? CBool False, testCase "Not" $ gevaluateSym True model (Not (SSBool "a")) @=? CBool False, testCase "ITE" $ gevaluateSym True model (ITE (SSBool "a") (SSBool "b") (SSBool "c")) @=? CBool False ] ], testProperty "Bool" (ioProperty . concreteGEvaluateSymOkProp @Bool), testProperty "Integer" (ioProperty . concreteGEvaluateSymOkProp @Integer), testProperty "Char" (ioProperty . concreteGEvaluateSymOkProp @Char), testProperty "Int" (ioProperty . concreteGEvaluateSymOkProp @Int), testProperty "Int8" (ioProperty . concreteGEvaluateSymOkProp @Int8), testProperty "Int16" (ioProperty . concreteGEvaluateSymOkProp @Int16), testProperty "Int32" (ioProperty . concreteGEvaluateSymOkProp @Int32), testProperty "Int64" (ioProperty . concreteGEvaluateSymOkProp @Int64), testProperty "Word" (ioProperty . concreteGEvaluateSymOkProp @Word), testProperty "Word8" (ioProperty . concreteGEvaluateSymOkProp @Word8), testProperty "Word16" (ioProperty . concreteGEvaluateSymOkProp @Word16), testProperty "Word32" (ioProperty . concreteGEvaluateSymOkProp @Word32), testProperty "Word64" (ioProperty . concreteGEvaluateSymOkProp @Word64), testGroup "List" [ testProperty "[Integer]" (ioProperty . concreteGEvaluateSymOkProp @[Integer]), let model = M.fromList [ (SSymbol "a", True), (SSymbol "b", False) ] :: M.HashMap Symbol Bool in testGroup "[SymBool]" [ testGroup "No fill default" [ testCase "Empty list" $ gevaluateSym False model ([] :: [SBool]) @=? [], testCase "Non-empty list" $ gevaluateSym False model [SSBool "a", SSBool "b", SSBool "c"] @=? [CBool True, CBool False, SSBool "c"] ], testGroup "Fill default" [ testCase "Empty list" $ gevaluateSym True model ([] :: [SBool]) @=? [], testCase "Non-empty list" $ gevaluateSym True model [SSBool "a", SSBool "b", SSBool "c"] @=? [CBool True, CBool False, CBool False] ] ] ], testGroup "Maybe" [ testProperty "Maybe Integer" (ioProperty . concreteGEvaluateSymOkProp @(Maybe Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Maybe SymBool" [ testGroup "No fill default" [ testCase "Nothing" $ gevaluateSym False model (Nothing :: Maybe SBool) @=? Nothing, testCase "Just v when v is in the model" $ gevaluateSym False model (Just (SSBool "a")) @=? Just (CBool True), testCase "Just v when v is not in the model" $ gevaluateSym False model (Just (SSBool "b")) @=? Just (SSBool "b") ], testGroup "Fill default" [ testCase "Nothing" $ gevaluateSym True model (Nothing :: Maybe SBool) @=? Nothing, testCase "Just v when v is in the model" $ gevaluateSym True model (Just (SSBool "a")) @=? Just (CBool True), testCase "Just v when v is not in the model" $ gevaluateSym True model (Just (SSBool "b")) @=? Just (CBool False) ] ] ], testGroup "Either" [ testProperty "Either Integer Integer" (ioProperty . concreteGEvaluateSymOkProp @(Either Integer Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Either SBool SBool" [ testGroup "No fill default" [ testCase "Left v when v is in the model" $ gevaluateSym False model (Left (SSBool "a") :: Either SBool SBool) @=? Left (CBool True), testCase "Left v when v is not in the model" $ gevaluateSym False model (Left (SSBool "b") :: Either SBool SBool) @=? Left (SSBool "b"), testCase "Right v when v is in the model" $ gevaluateSym False model (Right (SSBool "a") :: Either SBool SBool) @=? Right (CBool True), testCase "Right v when v is not in the model" $ gevaluateSym False model (Right (SSBool "b") :: Either SBool SBool) @=? Right (SSBool "b") ], testGroup "Fill default" [ testCase "Left v when v is in the model" $ gevaluateSym True model (Left (SSBool "a") :: Either SBool SBool) @=? Left (CBool True), testCase "Left v when v is not in the model" $ gevaluateSym True model (Left (SSBool "b") :: Either SBool SBool) @=? Left (CBool False), testCase "Right v when v is in the model" $ gevaluateSym True model (Right (SSBool "a") :: Either SBool SBool) @=? Right (CBool True), testCase "Right v when v is not in the model" $ gevaluateSym True model (Right (SSBool "b") :: Either SBool SBool) @=? Right (CBool False) ] ] ], testGroup "MaybeT" [ testProperty "MaybeT Maybe Integer" (ioProperty . concreteGEvaluateSymOkProp @(MaybeT Maybe Integer) . MaybeT), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "MaybeT should work" [ testGroup "No fill default" [ testCase "MaybeT Nothing" $ gevaluateSym False model (MaybeT Nothing :: MaybeT Maybe SBool) @=? MaybeT Nothing, testCase "MaybeT (Just Nothing)" $ gevaluateSym False model (MaybeT $ Just Nothing :: MaybeT Maybe SBool) @=? MaybeT (Just Nothing), testCase "MaybeT (Just v) when v is in the model" $ gevaluateSym False model (MaybeT $ Just $ Just $ SSBool "a") @=? MaybeT (Just (Just (CBool True))), testCase "MaybeT (Just v) when v is not in the model" $ gevaluateSym False model (MaybeT $ Just $ Just $ SSBool "b") @=? MaybeT (Just (Just (SSBool "b"))) ], testGroup "Fill default" [ testCase "MaybeT Nothing" $ gevaluateSym True model (MaybeT Nothing :: MaybeT Maybe SBool) @=? MaybeT Nothing, testCase "MaybeT (Just Nothing)" $ gevaluateSym True model (MaybeT $ Just Nothing :: MaybeT Maybe SBool) @=? MaybeT (Just Nothing), testCase "MaybeT (Just v) when v is in the model" $ gevaluateSym True model (MaybeT $ Just $ Just $ SSBool "a") @=? MaybeT (Just (Just (CBool True))), testCase "MaybeT (Just v) when v is not in the model" $ gevaluateSym True model (MaybeT $ Just $ Just $ SSBool "b") @=? MaybeT (Just (Just (CBool False))) ] ] ], testGroup "ExceptT" [ testProperty "ExceptT Integer Maybe Integer" (ioProperty . concreteGEvaluateSymOkProp @(ExceptT Integer Maybe Integer) . ExceptT), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "ExceptT SBool Maybe SBool" [ testGroup "No fill default" [ testCase "ExceptT Nothing" $ gevaluateSym False model (ExceptT Nothing :: ExceptT SBool Maybe SBool) @=? ExceptT Nothing, testCase "ExceptT (Just (Left v)) when v is in the model" $ gevaluateSym False model (ExceptT $ Just $ Left $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ CBool True), testCase "ExceptT (Just (Left v)) when v is not in the model" $ gevaluateSym False model (ExceptT $ Just $ Left $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ SSBool "b"), testCase "ExceptT (Just (Right v)) when v is in the model" $ gevaluateSym False model (ExceptT $ Just $ Right $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ CBool True), testCase "ExceptT (Just (Right v)) when v is not in the model" $ gevaluateSym False model (ExceptT $ Just $ Right $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ SSBool "b") ], testGroup "Fill default" [ testCase "ExceptT Nothing" $ gevaluateSym True model (ExceptT Nothing :: ExceptT SBool Maybe SBool) @=? ExceptT Nothing, testCase "ExceptT (Just (Left v)) when v is in the model" $ gevaluateSym True model (ExceptT $ Just $ Left $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ CBool True), testCase "ExceptT (Just (Left v)) when v is not in the model" $ gevaluateSym True model (ExceptT $ Just $ Left $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ CBool False), testCase "ExceptT (Just (Right v)) when v is in the model" $ gevaluateSym True model (ExceptT $ Just $ Right $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ CBool True), testCase "ExceptT (Just (Right v)) when v is not in the model" $ gevaluateSym True model (ExceptT $ Just $ Right $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ CBool False) ] ] ], testProperty "()" (ioProperty . concreteGEvaluateSymOkProp @()), testGroup "(,)" [ testProperty "(Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b") @=? (CBool True, SSBool "b"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b") @=? (CBool True, CBool False) ] ], testGroup "(,,)" [ testProperty "(Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c") @=? (CBool True, SSBool "b", SSBool "c"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c") @=? (CBool True, CBool False, CBool False) ] ], testGroup "(,,,)" [ testProperty "(Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d") @=? (CBool True, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e") @=? (CBool True, CBool False, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f") @=? (CBool True, CBool False, CBool False, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "h") @=? (CBool True, CBool False, CBool False, CBool False, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool, SBool, SBool, SBool) should work" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g", SSBool "h") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g", SSBool "h"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "h", SSBool "h") @=? (CBool True, CBool False, CBool False, CBool False, CBool False, CBool False, CBool False, CBool False) ] ], let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "ByteString should work" [ testGroup "No fill default" [ testCase "\"\"" $ gevaluateSym False model ("" :: B.ByteString) @=? "", testCase "\"a\"" $ gevaluateSym False model ("a" :: B.ByteString) @=? "a" ], testGroup "Fill default" [ testCase "\"\"" $ gevaluateSym True model ("" :: B.ByteString) @=? "", testCase "\"a\"" $ gevaluateSym True model ("a" :: B.ByteString) @=? "a" ] ], testGroup "Sum" [ testProperty "Sum Maybe Maybe Integer" ( ioProperty . \(x :: Either (Maybe Integer) (Maybe Integer)) -> case x of Left val -> concreteGEvaluateSymOkProp @(Sum Maybe Maybe Integer) $ InL val Right val -> concreteGEvaluateSymOkProp @(Sum Maybe Maybe Integer) $ InR val ), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Sum Maybe Maybe SBool" [ testGroup "No fill default" [ testCase "InL Nothing" $ gevaluateSym False model (InL Nothing :: Sum Maybe Maybe SBool) @=? InL Nothing, testCase "InR Nothing" $ gevaluateSym False model (InR Nothing :: Sum Maybe Maybe SBool) @=? InR Nothing, testCase "InL (Just v) when v is in the model" $ gevaluateSym False model (InL (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InL (Just $ CBool True), testCase "InL (Just v) when v is not in the model" $ gevaluateSym False model (InL (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InL (Just $ SSBool "b"), testCase "InR (Just v) when v is in the model" $ gevaluateSym False model (InR (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InR (Just $ CBool True), testCase "InR (Just v) when v is not in the model" $ gevaluateSym False model (InR (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InR (Just $ SSBool "b") ], testGroup "Fill default" [ testCase "InL Nothing" $ gevaluateSym True model (InL Nothing :: Sum Maybe Maybe SBool) @=? InL Nothing, testCase "InR Nothing" $ gevaluateSym True model (InR Nothing :: Sum Maybe Maybe SBool) @=? InR Nothing, testCase "InL (Just v) when v is in the model" $ gevaluateSym True model (InL (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InL (Just $ CBool True), testCase "InL (Just v) when v is not in the model" $ gevaluateSym True model (InL (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InL (Just $ CBool False), testCase "InR (Just v) when v is in the model" $ gevaluateSym True model (InR (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InR (Just $ CBool True), testCase "InR (Just v) when v is not in the model" $ gevaluateSym True model (InR (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InR (Just $ CBool False) ] ] ], testGroup "WriterT" [ testGroup "Lazy" [ testProperty "WriterT Integer (Either Integer) Integer" (ioProperty . \(x :: Either Integer (Integer, Integer)) -> concreteGEvaluateSymOkProp (WriterLazy.WriterT x)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "WriterT SBool (Either SBool) SBool" [ testGroup "No fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym False model (WriterLazy.WriterT $ Left $ SSBool "a" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym False model (WriterLazy.WriterT $ Left $ SSBool "b" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ SSBool "b"), testCase "WriterT (Right (v1, v2))" $ gevaluateSym False model (WriterLazy.WriterT $ Right (SSBool "a", SSBool "b") :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Right (CBool True, SSBool "b")) ], testGroup "Fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym True model (WriterLazy.WriterT $ Left $ SSBool "a" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym True model (WriterLazy.WriterT $ Left $ SSBool "b" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ CBool False), testCase "WriterT (Right (v1, v2))" $ gevaluateSym True model (WriterLazy.WriterT $ Right (SSBool "a", SSBool "b") :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Right (CBool True, CBool False)) ] ] ], testGroup "Strict" [ testProperty "WriterT Integer (Either Integer) Integer" (ioProperty . \(x :: Either Integer (Integer, Integer)) -> concreteGEvaluateSymOkProp (WriterStrict.WriterT x)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "WriterT SBool (Either SBool) SBool" [ testGroup "No fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym False model (WriterStrict.WriterT $ Left $ SSBool "a" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym False model (WriterStrict.WriterT $ Left $ SSBool "b" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ SSBool "b"), testCase "WriterT (Right (v1, v2))" $ gevaluateSym False model (WriterStrict.WriterT $ Right (SSBool "a", SSBool "b") :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Right (CBool True, SSBool "b")) ], testGroup "Fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym True model (WriterStrict.WriterT $ Left $ SSBool "a" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym True model (WriterStrict.WriterT $ Left $ SSBool "b" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ CBool False), testCase "WriterT (Right (v1, v2))" $ gevaluateSym True model (WriterStrict.WriterT $ Right (SSBool "a", SSBool "b") :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Right (CBool True, CBool False)) ] ] ] ], testGroup "Identity" [ testProperty "Identity Integer" (ioProperty . \(x :: Integer) -> concreteGEvaluateSymOkProp $ Identity x), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Identity SBool" [ testGroup "No fill default" [ testCase "Identity v when v is in the model" $ gevaluateSym False model (Identity $ SSBool "a") @=? Identity (CBool True), testCase "Identity v when v is not in the model" $ gevaluateSym False model (Identity $ SSBool "b") @=? Identity (SSBool "b") ], testGroup "Fill default" [ testCase "Identity v when v is in the model" $ gevaluateSym True model (Identity $ SSBool "a") @=? Identity (CBool True), testCase "Identity v when v is not in the model" $ gevaluateSym True model (Identity $ SSBool "b") @=? Identity (CBool False) ] ] ], testGroup "IdentityT" [ testProperty "IdentityT (Either Integer) Integer" (ioProperty . \(x :: Either Integer Integer) -> concreteGEvaluateSymOkProp $ IdentityT x), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "IdentityT (Either SBool) SBool" [ testGroup "No fill default" [ testCase "IdentityT (Left v) when v is in the model" $ gevaluateSym False model (IdentityT $ Left $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ CBool True), testCase "IdentityT (Left v) when v is not in the model" $ gevaluateSym False model (IdentityT $ Left $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ SSBool "b"), testCase "IdentityT (Right v) when v is in the model" $ gevaluateSym False model (IdentityT $ Right $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ CBool True), testCase "IdentityT (Right v) when v is not in the model" $ gevaluateSym False model (IdentityT $ Right $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ SSBool "b") ], testGroup "Fill default" [ testCase "IdentityT (Left v) when v is in the model" $ gevaluateSym True model (IdentityT $ Left $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ CBool True), testCase "IdentityT (Left v) when v is not in the model" $ gevaluateSym True model (IdentityT $ Left $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ CBool False), testCase "IdentityT (Right v) when v is in the model" $ gevaluateSym True model (IdentityT $ Right $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ CBool True), testCase "IdentityT (Right v) when v is not in the model" $ gevaluateSym True model (IdentityT $ Right $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ CBool False) ] ] ] ] ]
null
https://raw.githubusercontent.com/lsrcz/grisette/51d492f60fb37b74a626b591ec4c7ed128fa6217/test/Grisette/.Core/Data/Class/EvaluateSymTests.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Grisette.Core.Data.Class.EvaluateSymTests where import Control.Monad.Except import Control.Monad.Identity import Control.Monad.Trans.Maybe import qualified Control.Monad.Writer.Lazy as WriterLazy import qualified Control.Monad.Writer.Strict as WriterStrict import qualified Data.ByteString as B import Data.Functor.Sum import qualified Data.HashMap.Strict as M import Data.Int import Data.Word import Grisette.Core.Data.Class.Evaluate import Grisette.TestUtils.Evaluate import Grisette.TestUtils.SBool import Test.Tasty import Test.Tasty.HUnit import Test.Tasty.QuickCheck gevaluateSymTests :: TestTree gevaluateSymTests = testGroup "GEvaluateSymTests" [ testGroup "GEvaluateSym for common types" [ testGroup "SBool" [ let model = M.empty :: M.HashMap Symbol Bool in testGroup "Empty model / no fill default" [ testCase "CBool" $ gevaluateSym False model (CBool True) @=? CBool True, testCase "SSBool" $ gevaluateSym False model (SSBool "a") @=? SSBool "a", testCase "ISBool" $ gevaluateSym False model (ISBool "a" 1) @=? ISBool "a" 1, testCase "Or" $ gevaluateSym False model (Or (SSBool "a") (SSBool "b")) @=? Or (SSBool "a") (SSBool "b"), testCase "And" $ gevaluateSym False model (And (SSBool "a") (SSBool "b")) @=? And (SSBool "a") (SSBool "b"), testCase "Equal" $ gevaluateSym False model (Equal (SSBool "a") (SSBool "b")) @=? Equal (SSBool "a") (SSBool "b"), testCase "Not" $ gevaluateSym False model (Not (SSBool "a")) @=? Not (SSBool "a"), testCase "ITE" $ gevaluateSym False model (ITE (SSBool "a") (SSBool "b") (SSBool "c")) @=? ITE (SSBool "a") (SSBool "b") (SSBool "c") ], let model = M.empty :: M.HashMap Symbol Bool in testGroup "Empty model / with fill default" [ testCase "CBool" $ gevaluateSym True model (CBool True) @=? CBool True, testCase "SSBool" $ gevaluateSym True model (SSBool "a") @=? CBool False, testCase "ISBool" $ gevaluateSym True model (ISBool "a" 1) @=? CBool False, testCase "Or" $ gevaluateSym True model (Or (SSBool "a") (SSBool "b")) @=? CBool False, testCase "And" $ gevaluateSym True model (And (SSBool "a") (SSBool "b")) @=? CBool False, testCase "Equal" $ gevaluateSym True model (Equal (SSBool "a") (SSBool "b")) @=? CBool True, testCase "Not" $ gevaluateSym True model (Not (SSBool "a")) @=? CBool True, testCase "ITE" $ gevaluateSym True model (ITE (SSBool "a") (SSBool "b") (SSBool "c")) @=? CBool False ], let model = M.fromList [ (SSymbol "a", True), (ISymbol "a" 1, False), (SSymbol "b", False), (SSymbol "c", True) ] :: M.HashMap Symbol Bool in testGroup "Some model" [ testCase "CBool" $ gevaluateSym True model (CBool True) @=? CBool True, testCase "SSBool" $ gevaluateSym True model (SSBool "a") @=? CBool True, testCase "ISBool" $ gevaluateSym True model (ISBool "a" 1) @=? CBool False, testCase "Or" $ gevaluateSym True model (Or (SSBool "a") (SSBool "b")) @=? CBool True, testCase "And" $ gevaluateSym True model (And (SSBool "a") (SSBool "b")) @=? CBool False, testCase "Equal" $ gevaluateSym True model (Equal (SSBool "a") (SSBool "b")) @=? CBool False, testCase "Not" $ gevaluateSym True model (Not (SSBool "a")) @=? CBool False, testCase "ITE" $ gevaluateSym True model (ITE (SSBool "a") (SSBool "b") (SSBool "c")) @=? CBool False ] ], testProperty "Bool" (ioProperty . concreteGEvaluateSymOkProp @Bool), testProperty "Integer" (ioProperty . concreteGEvaluateSymOkProp @Integer), testProperty "Char" (ioProperty . concreteGEvaluateSymOkProp @Char), testProperty "Int" (ioProperty . concreteGEvaluateSymOkProp @Int), testProperty "Int8" (ioProperty . concreteGEvaluateSymOkProp @Int8), testProperty "Int16" (ioProperty . concreteGEvaluateSymOkProp @Int16), testProperty "Int32" (ioProperty . concreteGEvaluateSymOkProp @Int32), testProperty "Int64" (ioProperty . concreteGEvaluateSymOkProp @Int64), testProperty "Word" (ioProperty . concreteGEvaluateSymOkProp @Word), testProperty "Word8" (ioProperty . concreteGEvaluateSymOkProp @Word8), testProperty "Word16" (ioProperty . concreteGEvaluateSymOkProp @Word16), testProperty "Word32" (ioProperty . concreteGEvaluateSymOkProp @Word32), testProperty "Word64" (ioProperty . concreteGEvaluateSymOkProp @Word64), testGroup "List" [ testProperty "[Integer]" (ioProperty . concreteGEvaluateSymOkProp @[Integer]), let model = M.fromList [ (SSymbol "a", True), (SSymbol "b", False) ] :: M.HashMap Symbol Bool in testGroup "[SymBool]" [ testGroup "No fill default" [ testCase "Empty list" $ gevaluateSym False model ([] :: [SBool]) @=? [], testCase "Non-empty list" $ gevaluateSym False model [SSBool "a", SSBool "b", SSBool "c"] @=? [CBool True, CBool False, SSBool "c"] ], testGroup "Fill default" [ testCase "Empty list" $ gevaluateSym True model ([] :: [SBool]) @=? [], testCase "Non-empty list" $ gevaluateSym True model [SSBool "a", SSBool "b", SSBool "c"] @=? [CBool True, CBool False, CBool False] ] ] ], testGroup "Maybe" [ testProperty "Maybe Integer" (ioProperty . concreteGEvaluateSymOkProp @(Maybe Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Maybe SymBool" [ testGroup "No fill default" [ testCase "Nothing" $ gevaluateSym False model (Nothing :: Maybe SBool) @=? Nothing, testCase "Just v when v is in the model" $ gevaluateSym False model (Just (SSBool "a")) @=? Just (CBool True), testCase "Just v when v is not in the model" $ gevaluateSym False model (Just (SSBool "b")) @=? Just (SSBool "b") ], testGroup "Fill default" [ testCase "Nothing" $ gevaluateSym True model (Nothing :: Maybe SBool) @=? Nothing, testCase "Just v when v is in the model" $ gevaluateSym True model (Just (SSBool "a")) @=? Just (CBool True), testCase "Just v when v is not in the model" $ gevaluateSym True model (Just (SSBool "b")) @=? Just (CBool False) ] ] ], testGroup "Either" [ testProperty "Either Integer Integer" (ioProperty . concreteGEvaluateSymOkProp @(Either Integer Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Either SBool SBool" [ testGroup "No fill default" [ testCase "Left v when v is in the model" $ gevaluateSym False model (Left (SSBool "a") :: Either SBool SBool) @=? Left (CBool True), testCase "Left v when v is not in the model" $ gevaluateSym False model (Left (SSBool "b") :: Either SBool SBool) @=? Left (SSBool "b"), testCase "Right v when v is in the model" $ gevaluateSym False model (Right (SSBool "a") :: Either SBool SBool) @=? Right (CBool True), testCase "Right v when v is not in the model" $ gevaluateSym False model (Right (SSBool "b") :: Either SBool SBool) @=? Right (SSBool "b") ], testGroup "Fill default" [ testCase "Left v when v is in the model" $ gevaluateSym True model (Left (SSBool "a") :: Either SBool SBool) @=? Left (CBool True), testCase "Left v when v is not in the model" $ gevaluateSym True model (Left (SSBool "b") :: Either SBool SBool) @=? Left (CBool False), testCase "Right v when v is in the model" $ gevaluateSym True model (Right (SSBool "a") :: Either SBool SBool) @=? Right (CBool True), testCase "Right v when v is not in the model" $ gevaluateSym True model (Right (SSBool "b") :: Either SBool SBool) @=? Right (CBool False) ] ] ], testGroup "MaybeT" [ testProperty "MaybeT Maybe Integer" (ioProperty . concreteGEvaluateSymOkProp @(MaybeT Maybe Integer) . MaybeT), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "MaybeT should work" [ testGroup "No fill default" [ testCase "MaybeT Nothing" $ gevaluateSym False model (MaybeT Nothing :: MaybeT Maybe SBool) @=? MaybeT Nothing, testCase "MaybeT (Just Nothing)" $ gevaluateSym False model (MaybeT $ Just Nothing :: MaybeT Maybe SBool) @=? MaybeT (Just Nothing), testCase "MaybeT (Just v) when v is in the model" $ gevaluateSym False model (MaybeT $ Just $ Just $ SSBool "a") @=? MaybeT (Just (Just (CBool True))), testCase "MaybeT (Just v) when v is not in the model" $ gevaluateSym False model (MaybeT $ Just $ Just $ SSBool "b") @=? MaybeT (Just (Just (SSBool "b"))) ], testGroup "Fill default" [ testCase "MaybeT Nothing" $ gevaluateSym True model (MaybeT Nothing :: MaybeT Maybe SBool) @=? MaybeT Nothing, testCase "MaybeT (Just Nothing)" $ gevaluateSym True model (MaybeT $ Just Nothing :: MaybeT Maybe SBool) @=? MaybeT (Just Nothing), testCase "MaybeT (Just v) when v is in the model" $ gevaluateSym True model (MaybeT $ Just $ Just $ SSBool "a") @=? MaybeT (Just (Just (CBool True))), testCase "MaybeT (Just v) when v is not in the model" $ gevaluateSym True model (MaybeT $ Just $ Just $ SSBool "b") @=? MaybeT (Just (Just (CBool False))) ] ] ], testGroup "ExceptT" [ testProperty "ExceptT Integer Maybe Integer" (ioProperty . concreteGEvaluateSymOkProp @(ExceptT Integer Maybe Integer) . ExceptT), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "ExceptT SBool Maybe SBool" [ testGroup "No fill default" [ testCase "ExceptT Nothing" $ gevaluateSym False model (ExceptT Nothing :: ExceptT SBool Maybe SBool) @=? ExceptT Nothing, testCase "ExceptT (Just (Left v)) when v is in the model" $ gevaluateSym False model (ExceptT $ Just $ Left $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ CBool True), testCase "ExceptT (Just (Left v)) when v is not in the model" $ gevaluateSym False model (ExceptT $ Just $ Left $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ SSBool "b"), testCase "ExceptT (Just (Right v)) when v is in the model" $ gevaluateSym False model (ExceptT $ Just $ Right $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ CBool True), testCase "ExceptT (Just (Right v)) when v is not in the model" $ gevaluateSym False model (ExceptT $ Just $ Right $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ SSBool "b") ], testGroup "Fill default" [ testCase "ExceptT Nothing" $ gevaluateSym True model (ExceptT Nothing :: ExceptT SBool Maybe SBool) @=? ExceptT Nothing, testCase "ExceptT (Just (Left v)) when v is in the model" $ gevaluateSym True model (ExceptT $ Just $ Left $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ CBool True), testCase "ExceptT (Just (Left v)) when v is not in the model" $ gevaluateSym True model (ExceptT $ Just $ Left $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Left $ CBool False), testCase "ExceptT (Just (Right v)) when v is in the model" $ gevaluateSym True model (ExceptT $ Just $ Right $ SSBool "a" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ CBool True), testCase "ExceptT (Just (Right v)) when v is not in the model" $ gevaluateSym True model (ExceptT $ Just $ Right $ SSBool "b" :: ExceptT SBool Maybe SBool) @=? ExceptT (Just $ Right $ CBool False) ] ] ], testProperty "()" (ioProperty . concreteGEvaluateSymOkProp @()), testGroup "(,)" [ testProperty "(Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b") @=? (CBool True, SSBool "b"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b") @=? (CBool True, CBool False) ] ], testGroup "(,,)" [ testProperty "(Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c") @=? (CBool True, SSBool "b", SSBool "c"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c") @=? (CBool True, CBool False, CBool False) ] ], testGroup "(,,,)" [ testProperty "(Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d") @=? (CBool True, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e") @=? (CBool True, CBool False, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f") @=? (CBool True, CBool False, CBool False, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool, SBool, SBool)" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "h") @=? (CBool True, CBool False, CBool False, CBool False, CBool False, CBool False, CBool False) ] ], testGroup "(,,,,,,,)" [ testProperty "(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)" (ioProperty . concreteGEvaluateSymOkProp @(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "(SBool, SBool, SBool, SBool, SBool, SBool, SBool, SBool) should work" [ testCase "No fill default" $ gevaluateSym False model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g", SSBool "h") @=? (CBool True, SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "g", SSBool "h"), testCase "Fill default" $ gevaluateSym True model (SSBool "a", SSBool "b", SSBool "c", SSBool "d", SSBool "e", SSBool "f", SSBool "h", SSBool "h") @=? (CBool True, CBool False, CBool False, CBool False, CBool False, CBool False, CBool False, CBool False) ] ], let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "ByteString should work" [ testGroup "No fill default" [ testCase "\"\"" $ gevaluateSym False model ("" :: B.ByteString) @=? "", testCase "\"a\"" $ gevaluateSym False model ("a" :: B.ByteString) @=? "a" ], testGroup "Fill default" [ testCase "\"\"" $ gevaluateSym True model ("" :: B.ByteString) @=? "", testCase "\"a\"" $ gevaluateSym True model ("a" :: B.ByteString) @=? "a" ] ], testGroup "Sum" [ testProperty "Sum Maybe Maybe Integer" ( ioProperty . \(x :: Either (Maybe Integer) (Maybe Integer)) -> case x of Left val -> concreteGEvaluateSymOkProp @(Sum Maybe Maybe Integer) $ InL val Right val -> concreteGEvaluateSymOkProp @(Sum Maybe Maybe Integer) $ InR val ), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Sum Maybe Maybe SBool" [ testGroup "No fill default" [ testCase "InL Nothing" $ gevaluateSym False model (InL Nothing :: Sum Maybe Maybe SBool) @=? InL Nothing, testCase "InR Nothing" $ gevaluateSym False model (InR Nothing :: Sum Maybe Maybe SBool) @=? InR Nothing, testCase "InL (Just v) when v is in the model" $ gevaluateSym False model (InL (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InL (Just $ CBool True), testCase "InL (Just v) when v is not in the model" $ gevaluateSym False model (InL (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InL (Just $ SSBool "b"), testCase "InR (Just v) when v is in the model" $ gevaluateSym False model (InR (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InR (Just $ CBool True), testCase "InR (Just v) when v is not in the model" $ gevaluateSym False model (InR (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InR (Just $ SSBool "b") ], testGroup "Fill default" [ testCase "InL Nothing" $ gevaluateSym True model (InL Nothing :: Sum Maybe Maybe SBool) @=? InL Nothing, testCase "InR Nothing" $ gevaluateSym True model (InR Nothing :: Sum Maybe Maybe SBool) @=? InR Nothing, testCase "InL (Just v) when v is in the model" $ gevaluateSym True model (InL (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InL (Just $ CBool True), testCase "InL (Just v) when v is not in the model" $ gevaluateSym True model (InL (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InL (Just $ CBool False), testCase "InR (Just v) when v is in the model" $ gevaluateSym True model (InR (Just $ SSBool "a") :: Sum Maybe Maybe SBool) @=? InR (Just $ CBool True), testCase "InR (Just v) when v is not in the model" $ gevaluateSym True model (InR (Just $ SSBool "b") :: Sum Maybe Maybe SBool) @=? InR (Just $ CBool False) ] ] ], testGroup "WriterT" [ testGroup "Lazy" [ testProperty "WriterT Integer (Either Integer) Integer" (ioProperty . \(x :: Either Integer (Integer, Integer)) -> concreteGEvaluateSymOkProp (WriterLazy.WriterT x)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "WriterT SBool (Either SBool) SBool" [ testGroup "No fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym False model (WriterLazy.WriterT $ Left $ SSBool "a" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym False model (WriterLazy.WriterT $ Left $ SSBool "b" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ SSBool "b"), testCase "WriterT (Right (v1, v2))" $ gevaluateSym False model (WriterLazy.WriterT $ Right (SSBool "a", SSBool "b") :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Right (CBool True, SSBool "b")) ], testGroup "Fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym True model (WriterLazy.WriterT $ Left $ SSBool "a" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym True model (WriterLazy.WriterT $ Left $ SSBool "b" :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Left $ CBool False), testCase "WriterT (Right (v1, v2))" $ gevaluateSym True model (WriterLazy.WriterT $ Right (SSBool "a", SSBool "b") :: WriterLazy.WriterT SBool (Either SBool) SBool) @=? WriterLazy.WriterT (Right (CBool True, CBool False)) ] ] ], testGroup "Strict" [ testProperty "WriterT Integer (Either Integer) Integer" (ioProperty . \(x :: Either Integer (Integer, Integer)) -> concreteGEvaluateSymOkProp (WriterStrict.WriterT x)), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "WriterT SBool (Either SBool) SBool" [ testGroup "No fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym False model (WriterStrict.WriterT $ Left $ SSBool "a" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym False model (WriterStrict.WriterT $ Left $ SSBool "b" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ SSBool "b"), testCase "WriterT (Right (v1, v2))" $ gevaluateSym False model (WriterStrict.WriterT $ Right (SSBool "a", SSBool "b") :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Right (CBool True, SSBool "b")) ], testGroup "Fill default" [ testCase "WriterT (Left v) when v is in the model" $ gevaluateSym True model (WriterStrict.WriterT $ Left $ SSBool "a" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ CBool True), testCase "WriterT (Left v) when v is not in the model" $ gevaluateSym True model (WriterStrict.WriterT $ Left $ SSBool "b" :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Left $ CBool False), testCase "WriterT (Right (v1, v2))" $ gevaluateSym True model (WriterStrict.WriterT $ Right (SSBool "a", SSBool "b") :: WriterStrict.WriterT SBool (Either SBool) SBool) @=? WriterStrict.WriterT (Right (CBool True, CBool False)) ] ] ] ], testGroup "Identity" [ testProperty "Identity Integer" (ioProperty . \(x :: Integer) -> concreteGEvaluateSymOkProp $ Identity x), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "Identity SBool" [ testGroup "No fill default" [ testCase "Identity v when v is in the model" $ gevaluateSym False model (Identity $ SSBool "a") @=? Identity (CBool True), testCase "Identity v when v is not in the model" $ gevaluateSym False model (Identity $ SSBool "b") @=? Identity (SSBool "b") ], testGroup "Fill default" [ testCase "Identity v when v is in the model" $ gevaluateSym True model (Identity $ SSBool "a") @=? Identity (CBool True), testCase "Identity v when v is not in the model" $ gevaluateSym True model (Identity $ SSBool "b") @=? Identity (CBool False) ] ] ], testGroup "IdentityT" [ testProperty "IdentityT (Either Integer) Integer" (ioProperty . \(x :: Either Integer Integer) -> concreteGEvaluateSymOkProp $ IdentityT x), let model = M.fromList [(SSymbol "a", True)] :: M.HashMap Symbol Bool in testGroup "IdentityT (Either SBool) SBool" [ testGroup "No fill default" [ testCase "IdentityT (Left v) when v is in the model" $ gevaluateSym False model (IdentityT $ Left $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ CBool True), testCase "IdentityT (Left v) when v is not in the model" $ gevaluateSym False model (IdentityT $ Left $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ SSBool "b"), testCase "IdentityT (Right v) when v is in the model" $ gevaluateSym False model (IdentityT $ Right $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ CBool True), testCase "IdentityT (Right v) when v is not in the model" $ gevaluateSym False model (IdentityT $ Right $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ SSBool "b") ], testGroup "Fill default" [ testCase "IdentityT (Left v) when v is in the model" $ gevaluateSym True model (IdentityT $ Left $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ CBool True), testCase "IdentityT (Left v) when v is not in the model" $ gevaluateSym True model (IdentityT $ Left $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Left $ CBool False), testCase "IdentityT (Right v) when v is in the model" $ gevaluateSym True model (IdentityT $ Right $ SSBool "a" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ CBool True), testCase "IdentityT (Right v) when v is not in the model" $ gevaluateSym True model (IdentityT $ Right $ SSBool "b" :: IdentityT (Either SBool) SBool) @=? IdentityT (Right $ CBool False) ] ] ] ] ]
64f56b2b3c2fa34f3c81410e5a78cc408140744a788e4ebfe656c67882c66589
google/btls
Result.hs
Copyright 2018 Google LLC -- Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not -- use this file except in compliance with the License. You may obtain a copy of -- the License at -- -- -2.0 -- -- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations under -- the License. module BTLS.Result ( alwaysSucceeds, requireSuccess , Result, Error, file, line, errorData, errorDataIsHumanReadable , check, check' ) where import Control.Concurrent (rtsSupportsBoundThreads, runInBoundThread) import Control.Exception (assert) import Control.Monad (guard, unless, when) import Control.Monad.Loops (unfoldM) import Control.Monad.Trans.Except (ExceptT(ExceptT)) import Data.Bits ((.&.)) import Data.ByteString (ByteString) import Foreign (allocaArray) import Foreign.C.String (peekCString) import Foreign.C.Types import Foreign.Marshal.Unsafe (unsafeLocalState) import BTLS.BoringSSL.Err alwaysSucceeds :: CInt -> IO () alwaysSucceeds r = assert (r == 1) (return ()) requireSuccess :: CInt -> IO () requireSuccess r = when (r /= 1) $ ioError (userError "BoringSSL failure") type Result = Either [Error] -- | An error which occurred during processing. data Error = Error { err :: Err , file :: FilePath , line :: Int , errorData :: Maybe ByteString , flags :: CInt } errorDataIsHumanReadable :: Error -> Bool errorDataIsHumanReadable e = flags e .&. errFlagString == 1 instance Show Error where show e = let len = 120 in unsafeLocalState $ allocaArray len $ \pOut -> do errErrorStringN (err e) pOut len peekCString pOut errorFromTuple :: (Err, FilePath, Int, Maybe ByteString, CInt) -> Error errorFromTuple = uncurry5 Error dequeueError :: IO (Maybe Error) dequeueError = do e@((Err code), _file, _line, _extra, _flags) <- errGetErrorLineData guard (code /= 0) return (Just (errorFromTuple e)) check :: IO Int -> ExceptT [Error] IO () check = ExceptT . check' check' :: IO Int -> IO (Either [Error] ()) check' f = do unless rtsSupportsBoundThreads $ error "btls requires the threaded runtime. Please recompile with -threaded." runInBoundThread $ do -- TODO(bbaren): Assert that the error queue is clear r <- f if r == 1 then Right <$> return () else Left <$> unfoldM dequeueError uncurry5 :: (a -> b -> c -> d -> e -> z) -> (a, b, c, d, e) -> z uncurry5 f (a, b, c, d, e) = f a b c d e
null
https://raw.githubusercontent.com/google/btls/6de13194f15468b186fe62d089b3a7189795c704/src/BTLS/Result.hs
haskell
use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | An error which occurred during processing. TODO(bbaren): Assert that the error queue is clear
Copyright 2018 Google LLC Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not distributed under the License is distributed on an " AS IS " BASIS , WITHOUT module BTLS.Result ( alwaysSucceeds, requireSuccess , Result, Error, file, line, errorData, errorDataIsHumanReadable , check, check' ) where import Control.Concurrent (rtsSupportsBoundThreads, runInBoundThread) import Control.Exception (assert) import Control.Monad (guard, unless, when) import Control.Monad.Loops (unfoldM) import Control.Monad.Trans.Except (ExceptT(ExceptT)) import Data.Bits ((.&.)) import Data.ByteString (ByteString) import Foreign (allocaArray) import Foreign.C.String (peekCString) import Foreign.C.Types import Foreign.Marshal.Unsafe (unsafeLocalState) import BTLS.BoringSSL.Err alwaysSucceeds :: CInt -> IO () alwaysSucceeds r = assert (r == 1) (return ()) requireSuccess :: CInt -> IO () requireSuccess r = when (r /= 1) $ ioError (userError "BoringSSL failure") type Result = Either [Error] data Error = Error { err :: Err , file :: FilePath , line :: Int , errorData :: Maybe ByteString , flags :: CInt } errorDataIsHumanReadable :: Error -> Bool errorDataIsHumanReadable e = flags e .&. errFlagString == 1 instance Show Error where show e = let len = 120 in unsafeLocalState $ allocaArray len $ \pOut -> do errErrorStringN (err e) pOut len peekCString pOut errorFromTuple :: (Err, FilePath, Int, Maybe ByteString, CInt) -> Error errorFromTuple = uncurry5 Error dequeueError :: IO (Maybe Error) dequeueError = do e@((Err code), _file, _line, _extra, _flags) <- errGetErrorLineData guard (code /= 0) return (Just (errorFromTuple e)) check :: IO Int -> ExceptT [Error] IO () check = ExceptT . check' check' :: IO Int -> IO (Either [Error] ()) check' f = do unless rtsSupportsBoundThreads $ error "btls requires the threaded runtime. Please recompile with -threaded." runInBoundThread $ do r <- f if r == 1 then Right <$> return () else Left <$> unfoldM dequeueError uncurry5 :: (a -> b -> c -> d -> e -> z) -> (a, b, c, d, e) -> z uncurry5 f (a, b, c, d, e) = f a b c d e
ea656992c366a77944a0f778b2adca9ef4d5853b2c913e62fab011f36e1f4ae9
ice1000/learn
playing-with-laziness.hs
module Laziness where import Control.Arrow type Matrix = [[Bool]] mx = 100 myFind :: Matrix -> Int -> Int -> (Int, Int) myFind m x y |m !! x !! y = (x, y) |x == mx = myFind m 0 $ y + 1 |otherwise = myFind m (x + 1) y --- findTrue :: Matrix -> (Int, Int) findTrue m = myFind (take mx <$> (take mx <$> m)) 0 0
null
https://raw.githubusercontent.com/ice1000/learn/4ce5ea1897c97f7b5b3aee46ccd994e3613a58dd/Haskell/CW-Kata/playing-with-laziness.hs
haskell
-
module Laziness where import Control.Arrow type Matrix = [[Bool]] mx = 100 myFind :: Matrix -> Int -> Int -> (Int, Int) myFind m x y |m !! x !! y = (x, y) |x == mx = myFind m 0 $ y + 1 |otherwise = myFind m (x + 1) y findTrue :: Matrix -> (Int, Int) findTrue m = myFind (take mx <$> (take mx <$> m)) 0 0
78a5a653928e1ba95c213cae36518d38bedd586ea955e7e778edc372842b904b
rescript-lang/rescript-compiler
ext_bytes.ml
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) external unsafe_blit_string : string -> int -> bytes -> int -> int -> unit = "caml_blit_string" [@@noalloc]
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/e60482c6f6a69994907b9bd56e58ce87052e3659/jscomp/ext/ext_bytes.ml
ocaml
Copyright ( C ) 2015 - 2016 Bloomberg Finance L.P. * * This program is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * In addition to the permissions granted to you by the LGPL , you may combine * or link a " work that uses the Library " with a publicly distributed version * of this file to produce a combined library or application , then distribute * that combined work under the terms of your choosing , with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 ( or the corresponding section of a later version of the LGPL * should you choose to use a later version ) . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition to the permissions granted to you by the LGPL, you may combine * or link a "work that uses the Library" with a publicly distributed version * of this file to produce a combined library or application, then distribute * that combined work under the terms of your choosing, with no requirement * to comply with the obligations normally placed on you by section 4 of the * LGPL version 3 (or the corresponding section of a later version of the LGPL * should you choose to use a later version). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) external unsafe_blit_string : string -> int -> bytes -> int -> int -> unit = "caml_blit_string" [@@noalloc]
dbcca00191027691e0eda7fc151a761056812069679bb6faf3a91efdb38e4c80
ferd/lrw
lrw_prop.erl
-module(lrw_prop). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(PROPMOD, proper). -define(PROP(A), {timeout, 45, ?_assert(?PROPMOD:quickcheck(A(), [10000]))}). proper_test_() -> {"Run all property-based tests", [?PROP(prop_all_ip), ?PROP(prop_all), ?PROP(prop_top_ip), ?PROP(prop_top)]}. prop_all_ip() -> ?FORALL({Key,IPs}, {term(), nonempty_list(inet:ip4_address())}, begin Res = lrw:all_ip(Key, IPs), Res = lrw:all_ip(Key, lists:reverse(IPs)), % order is okay Res--[hd(IPs)] =:= lrw:all_ip(Key, tl(IPs)) % losing nodes is okay end). prop_all() -> we 're using an ip address to include IPv4 and IPv6 , but any %% term should work. This just speeds up the test. ?FORALL({Key,Nodes}, {term(), nonempty_list(inet:ip_address())}, begin Res = lrw:all(Key, Nodes), Res = lrw:all(Key, lists:reverse(Nodes)), % order is okay Res--[hd(Nodes)] =:= lrw:all(Key, tl(Nodes)) % losing nodes is okay end). prop_top_ip() -> ?FORALL({Key,IPs, N}, {term(), nonempty_list(inet:ip4_address()), pos_integer()}, begin All = lrw:all_ip(Key, IPs), Top = lrw:top_ip(Key, IPs, N), asking for 4 out of 2 yields 2 . andalso lists:prefix(Top, All) % same order end). prop_top() -> we 're using an ip address to include IPv4 and IPv6 , but any %% term should work. This just speeds up the test. ?FORALL({Key,Nodes, N}, {term(), nonempty_list(inet:ip_address()), pos_integer()}, begin All = lrw:all(Key, Nodes), Top = lrw:top(Key, Nodes, N), asking for 4 out of 2 yields 2 . andalso lists:prefix(Top, All) % same order end).
null
https://raw.githubusercontent.com/ferd/lrw/91761be19efcc46a4d10ea50df93183e0dea7dbb/test/lrw_prop.erl
erlang
order is okay losing nodes is okay term should work. This just speeds up the test. order is okay losing nodes is okay same order term should work. This just speeds up the test. same order
-module(lrw_prop). -include_lib("proper/include/proper.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(PROPMOD, proper). -define(PROP(A), {timeout, 45, ?_assert(?PROPMOD:quickcheck(A(), [10000]))}). proper_test_() -> {"Run all property-based tests", [?PROP(prop_all_ip), ?PROP(prop_all), ?PROP(prop_top_ip), ?PROP(prop_top)]}. prop_all_ip() -> ?FORALL({Key,IPs}, {term(), nonempty_list(inet:ip4_address())}, begin Res = lrw:all_ip(Key, IPs), end). prop_all() -> we 're using an ip address to include IPv4 and IPv6 , but any ?FORALL({Key,Nodes}, {term(), nonempty_list(inet:ip_address())}, begin Res = lrw:all(Key, Nodes), end). prop_top_ip() -> ?FORALL({Key,IPs, N}, {term(), nonempty_list(inet:ip4_address()), pos_integer()}, begin All = lrw:all_ip(Key, IPs), Top = lrw:top_ip(Key, IPs, N), asking for 4 out of 2 yields 2 . andalso end). prop_top() -> we 're using an ip address to include IPv4 and IPv6 , but any ?FORALL({Key,Nodes, N}, {term(), nonempty_list(inet:ip_address()), pos_integer()}, begin All = lrw:all(Key, Nodes), Top = lrw:top(Key, Nodes, N), asking for 4 out of 2 yields 2 . andalso end).
42a999ffba698209f90eb0e8ba26b6d1ac0d67140cb6523adde321368523b51f
schibsted/spid-tech-docs
apis.clj
(ns spid-docs.cultivate.apis "Process data in resources/apis.edn into a map of endpoints, where the two-level category is key and a map with description and related endpoints are the values." (:require [spid-docs.formatting :refer [to-id-str]] [spid-docs.homeless :refer [update-vals in?]] [spid-docs.routes :refer [article-path]])) (defn- api-tuple [endpoint] [(-> endpoint :category :section) (-> endpoint :category :api)]) (defn- ->api [endpoints articles] (let [api-name (-> endpoints first :category :api) article (str "/" (to-id-str api-name) ".md") api {:endpoints endpoints :category (-> endpoints first :category :section) :api api-name}] (if (in? (vec (keys articles)) article) (assoc api :url (article-path article)) api))) (defn cultivate-apis "Sort the endpoints under their respective API categories." [endpoints articles] (update-vals (group-by api-tuple endpoints) #(->api % articles)))
null
https://raw.githubusercontent.com/schibsted/spid-tech-docs/ee6a4394e9732572e97fc3a55506b2d6b9a9fe2b/src/spid_docs/cultivate/apis.clj
clojure
(ns spid-docs.cultivate.apis "Process data in resources/apis.edn into a map of endpoints, where the two-level category is key and a map with description and related endpoints are the values." (:require [spid-docs.formatting :refer [to-id-str]] [spid-docs.homeless :refer [update-vals in?]] [spid-docs.routes :refer [article-path]])) (defn- api-tuple [endpoint] [(-> endpoint :category :section) (-> endpoint :category :api)]) (defn- ->api [endpoints articles] (let [api-name (-> endpoints first :category :api) article (str "/" (to-id-str api-name) ".md") api {:endpoints endpoints :category (-> endpoints first :category :section) :api api-name}] (if (in? (vec (keys articles)) article) (assoc api :url (article-path article)) api))) (defn cultivate-apis "Sort the endpoints under their respective API categories." [endpoints articles] (update-vals (group-by api-tuple endpoints) #(->api % articles)))
eb185525c268bb4de9062a6d9fb2e8e753a044648c4ffbafb43c203da61c3d01
naveensundarg/prover
dpll-system.lisp
;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: common-lisp-user -*- ;;; File: dpll-system.lisp The contents of this file are subject to the Mozilla Public License ;;; Version 1.1 (the "License"); you may not use this file except in ;;; compliance with the License. You may obtain a copy of the License at ;;; / ;;; Software distributed under the License is distributed on an " AS IS " ;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the ;;; License for the specific language governing rights and limitations ;;; under the License. ;;; The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2010 . All Rights Reserved . ;;; Contributor(s ): < > . (in-package :common-lisp-user) (defpackage :snark-dpll (:use :common-lisp :snark-lisp) (:export #:dp-prover #:dp-version #:dp-tracing #:dp-tracing-state #:dp-tracing-models #:dp-tracing-choices #:dp-satisfiable-p #:dp-satisfiable-file-p #:make-dp-clause-set #:dp-insert #:dp-insert-sorted #:dp-insert-wff #:dp-insert-file #:dp-count #:dp-clauses #:dp-output-clauses-to-file #:wff-clauses #:dp-horn-clause-set-p #:checkpoint-dp-clause-set #:restore-dp-clause-set #:uncheckpoint-dp-clause-set #:choose-an-atom-of-a-shortest-clause #:choose-an-atom-of-a-shortest-clause-randomly #:choose-an-atom-of-a-shortest-clause-with-most-occurrences #:choose-an-atom-of-a-shortest-clause-with-most-occurrences-randomly #:choose-an-atom-of-a-shortest-positive-clause #:choose-an-atom-of-a-shortest-positive-clause-randomly #:choose-an-atom-of-a-shortest-positive-clause-with-most-occurrences #:choose-an-atom-of-a-shortest-positive-clause-with-most-occurrences-randomly #:lookahead-true #:lookahead-false #:lookahead-true-false #:lookahead-false-true )) (loads "davis-putnam3") dpll-system.lisp EOF
null
https://raw.githubusercontent.com/naveensundarg/prover/812baf098d8bf77e4d634cef4d12de94dcd1e113/snark-20120808r02/src/dpll-system.lisp
lisp
-*- Mode: Lisp; Syntax: Common-Lisp; Package: common-lisp-user -*- File: dpll-system.lisp Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License.
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is SNARK . The Initial Developer of the Original Code is SRI International . Portions created by the Initial Developer are Copyright ( C ) 1981 - 2010 . All Rights Reserved . Contributor(s ): < > . (in-package :common-lisp-user) (defpackage :snark-dpll (:use :common-lisp :snark-lisp) (:export #:dp-prover #:dp-version #:dp-tracing #:dp-tracing-state #:dp-tracing-models #:dp-tracing-choices #:dp-satisfiable-p #:dp-satisfiable-file-p #:make-dp-clause-set #:dp-insert #:dp-insert-sorted #:dp-insert-wff #:dp-insert-file #:dp-count #:dp-clauses #:dp-output-clauses-to-file #:wff-clauses #:dp-horn-clause-set-p #:checkpoint-dp-clause-set #:restore-dp-clause-set #:uncheckpoint-dp-clause-set #:choose-an-atom-of-a-shortest-clause #:choose-an-atom-of-a-shortest-clause-randomly #:choose-an-atom-of-a-shortest-clause-with-most-occurrences #:choose-an-atom-of-a-shortest-clause-with-most-occurrences-randomly #:choose-an-atom-of-a-shortest-positive-clause #:choose-an-atom-of-a-shortest-positive-clause-randomly #:choose-an-atom-of-a-shortest-positive-clause-with-most-occurrences #:choose-an-atom-of-a-shortest-positive-clause-with-most-occurrences-randomly #:lookahead-true #:lookahead-false #:lookahead-true-false #:lookahead-false-true )) (loads "davis-putnam3") dpll-system.lisp EOF
d1813e2d6b5c9e03e1848f097c393170ae5a0e5603670472b0d517686fdee62e
thierry-martinez/refl
deep_variables.ml
type ('a, 'b) t = | A of 'a | B of 'b option [@@deriving refl] type 'a u = ('a, int) t [@@deriving refl]
null
https://raw.githubusercontent.com/thierry-martinez/refl/64e7c86f25c47c29aeeaa581a751ef37e138a42f/tests/deep_variables/deep_variables.ml
ocaml
type ('a, 'b) t = | A of 'a | B of 'b option [@@deriving refl] type 'a u = ('a, int) t [@@deriving refl]
6dd38f7eb660d4f3a4f08d18b6adc30c46f4c14aff3b541bb176ac982409744e
candera/vmt
wind.cljs
(ns weathergen.wind "Library for rendering iconography associated with wind." (:require [goog.string :as gstring] [goog.string.format] [hoplon.svg :as svg] [weathergen.math :as math])) (defn barb [speed] (let [pennants (-> speed (/ 50) long) speed' (-> speed (- (* 50 pennants))) ticks (math/clamp (if (zero? pennants) 1 0) 100 (int (/ speed' 5))) full-tails (int (/ ticks 2)) half-tail? (odd? ticks) Handle the case of a single half - tail by offsetting it ;; from the beginning of the barb single-half-tail? (and half-tail? (zero? full-tails) (zero? pennants)) starts-with-tail? (and (zero? pennants) (pos? full-tails)) scale 1 offset 0.1 tail-step 0.16 tail-slant 0.15 tail-width (* 0.25 1.5) pennant-base 0.2 pennant-step 0.25 pennant-offset (* pennant-step pennants)] (svg/g ;; TODO: Refactor this so it uses paths everywhere rather ;; than a mixture of lines and paths (if starts-with-tail? (svg/path :attr {:class "wind-vector" :fill "none"} :d (gstring/format "M%f,%f L%f,%f L%f,%f" tail-width, -0.50 0, (+ -0.5 tail-slant) 0, (- 0.5 tail-slant))) (svg/line :attr {:class "wind-vector"} :x1 0 :x2 0 :y1 (- 0.5 tail-slant) :y2 (+ -0.5 tail-slant))) Pennants (svg/g :attr {:class "wind-vector pennant"} (for [n (range pennants)] (svg/path :attr {:fill "black"} :d (gstring/format "M%f,%f L%f,%f L%f,%f Z" 0 (+ -0.5 (* pennant-step n)) tail-width (+ -0.50 (* pennant-step n)) 0 (+ -0.5 (* pennant-step n) pennant-base))))) ;; Full tails (svg/g :attr {:class "wind-vector full-tail"} (for [n (range (if starts-with-tail? 1 0) full-tails)] (svg/line :x1 0 :y1 (+ -0.5 tail-slant pennant-offset (* tail-step n)) :x2 tail-width :y2 (+ -0.5 pennant-offset (* tail-step n))))) Half tails (when half-tail? (let [length 0.6] (svg/line :attr {:class "wind-vector half-tail"} :x1 0 :y1 (+ -0.50 tail-slant pennant-offset (* tail-step (+ full-tails (if single-half-tail? 1.5 0)))) :x2 (* tail-width length) :y2 (+ -0.50 (* tail-slant (- 1 length)) pennant-offset (* tail-step (+ full-tails (if single-half-tail? 1.5 0))))))))))
null
https://raw.githubusercontent.com/candera/vmt/8cf450e6c34af87d748152afd7f547b92ae9b38e/src/weathergen/wind.cljs
clojure
from the beginning of the barb TODO: Refactor this so it uses paths everywhere rather than a mixture of lines and paths Full tails
(ns weathergen.wind "Library for rendering iconography associated with wind." (:require [goog.string :as gstring] [goog.string.format] [hoplon.svg :as svg] [weathergen.math :as math])) (defn barb [speed] (let [pennants (-> speed (/ 50) long) speed' (-> speed (- (* 50 pennants))) ticks (math/clamp (if (zero? pennants) 1 0) 100 (int (/ speed' 5))) full-tails (int (/ ticks 2)) half-tail? (odd? ticks) Handle the case of a single half - tail by offsetting it single-half-tail? (and half-tail? (zero? full-tails) (zero? pennants)) starts-with-tail? (and (zero? pennants) (pos? full-tails)) scale 1 offset 0.1 tail-step 0.16 tail-slant 0.15 tail-width (* 0.25 1.5) pennant-base 0.2 pennant-step 0.25 pennant-offset (* pennant-step pennants)] (svg/g (if starts-with-tail? (svg/path :attr {:class "wind-vector" :fill "none"} :d (gstring/format "M%f,%f L%f,%f L%f,%f" tail-width, -0.50 0, (+ -0.5 tail-slant) 0, (- 0.5 tail-slant))) (svg/line :attr {:class "wind-vector"} :x1 0 :x2 0 :y1 (- 0.5 tail-slant) :y2 (+ -0.5 tail-slant))) Pennants (svg/g :attr {:class "wind-vector pennant"} (for [n (range pennants)] (svg/path :attr {:fill "black"} :d (gstring/format "M%f,%f L%f,%f L%f,%f Z" 0 (+ -0.5 (* pennant-step n)) tail-width (+ -0.50 (* pennant-step n)) 0 (+ -0.5 (* pennant-step n) pennant-base))))) (svg/g :attr {:class "wind-vector full-tail"} (for [n (range (if starts-with-tail? 1 0) full-tails)] (svg/line :x1 0 :y1 (+ -0.5 tail-slant pennant-offset (* tail-step n)) :x2 tail-width :y2 (+ -0.5 pennant-offset (* tail-step n))))) Half tails (when half-tail? (let [length 0.6] (svg/line :attr {:class "wind-vector half-tail"} :x1 0 :y1 (+ -0.50 tail-slant pennant-offset (* tail-step (+ full-tails (if single-half-tail? 1.5 0)))) :x2 (* tail-width length) :y2 (+ -0.50 (* tail-slant (- 1 length)) pennant-offset (* tail-step (+ full-tails (if single-half-tail? 1.5 0))))))))))
b55f68c90680bb3366bad968e25f4fc994cfc32fe5f361abe59a96fa4f5056df
ovotech/kafka-avro-confluent
specs.clj
(ns kafka-avro-confluent.v2.specs (:require [clojure.spec.alpha :as s] [clojure.string :as string] [clojure.walk :as w])) (s/def ::non-blank-string (s/and string? (complement string/blank?))) (s/def :schema-registry/base-url ::non-blank-string) (s/def :schema-registry/username ::non-blank-string) (s/def :schema-registry/password ::non-blank-string) (s/def :kafka.serde/config (s/and (s/conformer #(try (->> % (into {}) w/keywordize-keys) (catch Exception ex :clojure.spec.alpha/invalid))) (s/keys :req [:schema-registry/base-url] :opt [:schema-registry/username :schema-registry/password]))) (s/def :avro-record/schema any?) (s/def :avro-record/value any?) (s/def ::avro-record (s/keys :req-un [:avro-record/schema :avro-record/value]))
null
https://raw.githubusercontent.com/ovotech/kafka-avro-confluent/b014de61d2bc217ab5c8962c2a3d3f61f3553dd5/src/kafka_avro_confluent/v2/specs.clj
clojure
(ns kafka-avro-confluent.v2.specs (:require [clojure.spec.alpha :as s] [clojure.string :as string] [clojure.walk :as w])) (s/def ::non-blank-string (s/and string? (complement string/blank?))) (s/def :schema-registry/base-url ::non-blank-string) (s/def :schema-registry/username ::non-blank-string) (s/def :schema-registry/password ::non-blank-string) (s/def :kafka.serde/config (s/and (s/conformer #(try (->> % (into {}) w/keywordize-keys) (catch Exception ex :clojure.spec.alpha/invalid))) (s/keys :req [:schema-registry/base-url] :opt [:schema-registry/username :schema-registry/password]))) (s/def :avro-record/schema any?) (s/def :avro-record/value any?) (s/def ::avro-record (s/keys :req-un [:avro-record/schema :avro-record/value]))
1392790e812022404c35c45a13ae3bde5b4a0ddfed2db67f1776a672e53a43f1
yetanalytics/dl4clj
listeners.clj
(ns ^{:doc "listener creation namespace. composes the listeners package from dl4j see: -summary.html"} dl4clj.optimize.listeners (:import [org.deeplearning4j.optimize.listeners ParamAndGradientIterationListener ComposableIterationListener ScoreIterationListener PerformanceListener PerformanceListener$Builder CollectScoresIterationListener] [org.deeplearning4j.optimize.api IterationListener]) (:require [dl4clj.utils :refer [contains-many? generic-dispatching-fn array-of obj-or-code? builder-fn]])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; multi method that sets up the constructor/builder ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti listeners generic-dispatching-fn) (defmethod listeners :param-and-gradient [opts] (let [conf (:param-and-gradient opts) {iterations :iterations print-header? :print-header? print-mean? :print-mean? print-min-max? :print-min-max? print-mean-abs-value? :print-mean-abs-value? output-to-console? :output-to-console? output-to-file? :output-to-file? output-to-logger? :output-to-logger? file :file delim :delim} conf] (if (contains-many? conf :iterations :print-header? :print-mean? :print-min-max? :print-mean-abs-value? :output-to-console? :output-to-file? :output-to-logger? :file :delim) `(ParamAndGradientIterationListener. ~iterations ~print-header? ~print-mean? ~print-min-max? ~print-mean-abs-value? ~output-to-console? ~output-to-file? ~output-to-logger? ~file ~delim) `(ParamAndGradientIterationListener.)))) (defmethod listeners :collection-scores [opts] (let [conf (:collection-scores opts) frequency (:frequency conf)] (if frequency `(CollectScoresIterationListener. ~frequency) `(CollectScoresIterationListener.)))) (defmethod listeners :composable [opts] (let [conf (:composable opts) listeners (:coll-of-listeners conf)] `(ComposableIterationListener. ~listeners))) (defmethod listeners :score-iteration [opts] (let [conf (:score-iteration opts) print-every-n (:print-every-n conf)] (if print-every-n `(ScoreIterationListener. ~print-every-n) `(ScoreIterationListener.)))) (defmethod listeners :performance [opts] (let [conf (:performance opts) {report-batch? :report-batch? report-iteration? :report-iteration? report-sample? :report-sample? report-score? :report-score? report-time? :report-time? freq :frequency build? :build?} conf method-map {:report-batch? '.reportBatch :report-iteration? '.reportIteration :report-sample? '.reportSample :report-score? '.reportScore :report-time? '.reportTime :frequency '.setFrequency} code (builder-fn `(PerformanceListener$Builder.) method-map (dissoc conf :as-code?))] (if build? `(.build ~code) code))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; user facing fns that specify args for making listeners ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn new-performance-iteration-listener "Simple IterationListener that tracks time spend on training per iteration. :report-batch (boolean), if batches/sec should be reported together with other data - defaults to true :report-iteration? (boolean), if iteration number should be reported together with other data - defaults to true :report-sample? (boolean), if samples/sec should be reported together with other data - defaults to true :report-score? (boolean), if score should be reported together with other data - defaults to true :report-time? (boolean), if time per iteration should be reported together with other data - defaults to true :frequency (int), Desired IterationListener activation frequency - defaults to 1 :build? (boolean), if you want to build the builder - defaults to true :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false defaults are only used if no kw args are supplied" [& {:keys [report-batch? report-iteration? report-sample? report-score? report-time? build? frequency array? as-code?] :or {array? false as-code? true} :as opts}] (let [conf (if (nil? opts) {:build? true :report-batch? true :report-iteration? true :report-sample? true :report-score? true :report-time? true :frequency 1} opts) data (listeners {:performance conf}) code-or-obj (if as-code? data (eval data))] (if (and (true? array?) (false? as-code?)) (array-of :data code-or-obj :java-type IterationListener) code-or-obj))) (defn new-score-iteration-listener "Score iteration listener :print-every-n (int), print every n iterations - defaults to 10 :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it" [& {:keys [print-every-n array? as-code?] :or {array? false as-code? true} :as opts}] (let [conf (if opts opts {:print-every-n 10}) code (if (true? array?) `(array-of :data ~(listeners {:score-iteration conf}) :java-type IterationListener) (listeners {:score-iteration conf}))] (obj-or-code? as-code? code))) (defn new-composable-iteration-listener "A group of listeners listeners (collection or array) multiple listeners to compose together :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it" [& {:keys [coll-of-listeners array? as-code?] :or {array? false as-code? true} :as opts}] (let [code (if (true? array?) `(array-of :data ~(listeners {:composable opts}) :java-type IterationListener) (listeners {:composable opts}))] (obj-or-code? as-code? code))) (defn new-collection-scores-iteration-listener "CollectScoresIterationListener simply stores the model scores internally (along with the iteration) every 1 or N iterations (this is configurable). These scores can then be obtained or exported. :frequency (int), how often scores are stored - defaults to 1 :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it" [& {:keys [frequency array? as-code?] :or {array? false as-code? true} :as opts}] (let [conf (if opts opts {:frequency 1}) code (if (true? array?) `(array-of :data ~(listeners {:collection-scores conf}) :java-type IterationListener) (listeners {:collection-scores conf}))] (obj-or-code? as-code? code))) (defn new-param-and-gradient-iteration-listener "An iteration listener that provides details on parameters and gradients at each iteration during traning. Attempts to provide much of the same information as the UI histogram iteration listener, but in a text-based format (for example, when learning on a system accessed via SSH etc). i.e., is intended to aid network tuning and debugging This iteration listener is set up to calculate mean, min, max, and mean absolute value of each type of parameter and gradient in the network at each iteration. :iterations (int), frequency to calculate and report values - defaults to 1 :print-header? (boolean), Whether to output a header row (i.e., names for each column) - defaults to true :print-mean? (boolean), Calculate and display the mean of parameters and gradients - defaults to true :print-min-max? (boolean), Calculate and display the min/max of the parameters and gradients - defaults to true :print-mean-abs-value? (boolean), Calculate and display the mean absolute value - defaults to true :output-to-console? (boolean), If true, display the values to the console - defaults to true :output-to-file? (boolean), If true, write the values to a file, one per line - defaults to false :output-to-logger? (boolean), If true, log the values - defaults to true :file (java.io.File), File to write values to. May be null - not used if :output-to-file? = false - defaults to nil :delimiter (str), the delimiter for the output file. - defaults to , :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it defaults are only used if no kw args are supplied" [& {:keys [iterations print-header? print-mean? print-min-max? print-mean-abs-value? output-to-console? output-to-file? output-to-logger? file delimiter array? as-code?] :or {array? false} :as opts}] (let [conf (if opts opts {:iterations 1 :print-header? true :print-mean? true :print-min-max? true :print-mean-abs-value? true :output-to-console? true :output-to-file? false :output-to-logger? true :file nil :delimiter ","}) code (if (true? array?) `(array-of :data ~(listeners {:param-and-gradient conf}) :java-type IterationListener) (listeners {:param-and-gradient conf}))] (obj-or-code? as-code? code)))
null
https://raw.githubusercontent.com/yetanalytics/dl4clj/9ef055b2a460f1a6246733713136b981fd322510/src/dl4clj/optimize/listeners.clj
clojure
multi method that sets up the constructor/builder
(ns ^{:doc "listener creation namespace. composes the listeners package from dl4j see: -summary.html"} dl4clj.optimize.listeners (:import [org.deeplearning4j.optimize.listeners ParamAndGradientIterationListener ComposableIterationListener ScoreIterationListener PerformanceListener PerformanceListener$Builder CollectScoresIterationListener] [org.deeplearning4j.optimize.api IterationListener]) (:require [dl4clj.utils :refer [contains-many? generic-dispatching-fn array-of obj-or-code? builder-fn]])) (defmulti listeners generic-dispatching-fn) (defmethod listeners :param-and-gradient [opts] (let [conf (:param-and-gradient opts) {iterations :iterations print-header? :print-header? print-mean? :print-mean? print-min-max? :print-min-max? print-mean-abs-value? :print-mean-abs-value? output-to-console? :output-to-console? output-to-file? :output-to-file? output-to-logger? :output-to-logger? file :file delim :delim} conf] (if (contains-many? conf :iterations :print-header? :print-mean? :print-min-max? :print-mean-abs-value? :output-to-console? :output-to-file? :output-to-logger? :file :delim) `(ParamAndGradientIterationListener. ~iterations ~print-header? ~print-mean? ~print-min-max? ~print-mean-abs-value? ~output-to-console? ~output-to-file? ~output-to-logger? ~file ~delim) `(ParamAndGradientIterationListener.)))) (defmethod listeners :collection-scores [opts] (let [conf (:collection-scores opts) frequency (:frequency conf)] (if frequency `(CollectScoresIterationListener. ~frequency) `(CollectScoresIterationListener.)))) (defmethod listeners :composable [opts] (let [conf (:composable opts) listeners (:coll-of-listeners conf)] `(ComposableIterationListener. ~listeners))) (defmethod listeners :score-iteration [opts] (let [conf (:score-iteration opts) print-every-n (:print-every-n conf)] (if print-every-n `(ScoreIterationListener. ~print-every-n) `(ScoreIterationListener.)))) (defmethod listeners :performance [opts] (let [conf (:performance opts) {report-batch? :report-batch? report-iteration? :report-iteration? report-sample? :report-sample? report-score? :report-score? report-time? :report-time? freq :frequency build? :build?} conf method-map {:report-batch? '.reportBatch :report-iteration? '.reportIteration :report-sample? '.reportSample :report-score? '.reportScore :report-time? '.reportTime :frequency '.setFrequency} code (builder-fn `(PerformanceListener$Builder.) method-map (dissoc conf :as-code?))] (if build? `(.build ~code) code))) user facing fns that specify args for making listeners (defn new-performance-iteration-listener "Simple IterationListener that tracks time spend on training per iteration. :report-batch (boolean), if batches/sec should be reported together with other data - defaults to true :report-iteration? (boolean), if iteration number should be reported together with other data - defaults to true :report-sample? (boolean), if samples/sec should be reported together with other data - defaults to true :report-score? (boolean), if score should be reported together with other data - defaults to true :report-time? (boolean), if time per iteration should be reported together with other data - defaults to true :frequency (int), Desired IterationListener activation frequency - defaults to 1 :build? (boolean), if you want to build the builder - defaults to true :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false defaults are only used if no kw args are supplied" [& {:keys [report-batch? report-iteration? report-sample? report-score? report-time? build? frequency array? as-code?] :or {array? false as-code? true} :as opts}] (let [conf (if (nil? opts) {:build? true :report-batch? true :report-iteration? true :report-sample? true :report-score? true :report-time? true :frequency 1} opts) data (listeners {:performance conf}) code-or-obj (if as-code? data (eval data))] (if (and (true? array?) (false? as-code?)) (array-of :data code-or-obj :java-type IterationListener) code-or-obj))) (defn new-score-iteration-listener "Score iteration listener :print-every-n (int), print every n iterations - defaults to 10 :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it" [& {:keys [print-every-n array? as-code?] :or {array? false as-code? true} :as opts}] (let [conf (if opts opts {:print-every-n 10}) code (if (true? array?) `(array-of :data ~(listeners {:score-iteration conf}) :java-type IterationListener) (listeners {:score-iteration conf}))] (obj-or-code? as-code? code))) (defn new-composable-iteration-listener "A group of listeners listeners (collection or array) multiple listeners to compose together :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it" [& {:keys [coll-of-listeners array? as-code?] :or {array? false as-code? true} :as opts}] (let [code (if (true? array?) `(array-of :data ~(listeners {:composable opts}) :java-type IterationListener) (listeners {:composable opts}))] (obj-or-code? as-code? code))) (defn new-collection-scores-iteration-listener "CollectScoresIterationListener simply stores the model scores internally (along with the iteration) every 1 or N iterations (this is configurable). These scores can then be obtained or exported. :frequency (int), how often scores are stored - defaults to 1 :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it" [& {:keys [frequency array? as-code?] :or {array? false as-code? true} :as opts}] (let [conf (if opts opts {:frequency 1}) code (if (true? array?) `(array-of :data ~(listeners {:collection-scores conf}) :java-type IterationListener) (listeners {:collection-scores conf}))] (obj-or-code? as-code? code))) (defn new-param-and-gradient-iteration-listener "An iteration listener that provides details on parameters and gradients at each iteration during traning. Attempts to provide much of the same information as the UI histogram iteration listener, but in a text-based format (for example, when learning on a system accessed via SSH etc). i.e., is intended to aid network tuning and debugging This iteration listener is set up to calculate mean, min, max, and mean absolute value of each type of parameter and gradient in the network at each iteration. :iterations (int), frequency to calculate and report values - defaults to 1 :print-header? (boolean), Whether to output a header row (i.e., names for each column) - defaults to true :print-mean? (boolean), Calculate and display the mean of parameters and gradients - defaults to true :print-min-max? (boolean), Calculate and display the min/max of the parameters and gradients - defaults to true :print-mean-abs-value? (boolean), Calculate and display the mean absolute value - defaults to true :output-to-console? (boolean), If true, display the values to the console - defaults to true :output-to-file? (boolean), If true, write the values to a file, one per line - defaults to false :output-to-logger? (boolean), If true, log the values - defaults to true :file (java.io.File), File to write values to. May be null - not used if :output-to-file? = false - defaults to nil :delimiter (str), the delimiter for the output file. - defaults to , :array? (boolean), if you want to return the object in an array of type IterationListener - defaults to false :as-code? (boolean), return the java object or the code for creating it defaults are only used if no kw args are supplied" [& {:keys [iterations print-header? print-mean? print-min-max? print-mean-abs-value? output-to-console? output-to-file? output-to-logger? file delimiter array? as-code?] :or {array? false} :as opts}] (let [conf (if opts opts {:iterations 1 :print-header? true :print-mean? true :print-min-max? true :print-mean-abs-value? true :output-to-console? true :output-to-file? false :output-to-logger? true :file nil :delimiter ","}) code (if (true? array?) `(array-of :data ~(listeners {:param-and-gradient conf}) :java-type IterationListener) (listeners {:param-and-gradient conf}))] (obj-or-code? as-code? code)))
921a71d11a731cc8126392292632b096b968d4638b7db6b00c079134aadd74a5
kana/sicp
ex-3.25.scm
Exercise 3.25 . Generalizing one- and two - dimensional tables , show how to ;;; implement a table in which values are stored under an arbitrary number of ;;; keys and different values may be stored under different numbers of keys. ;;; The lookup and insert! procedures should take as input a list of keys used ;;; to access the table. ; Let's consider the following interaction: ; ; (define t (make-table)) ; (insert! '(a) 'v1) ; (insert! '(a b c) 'v2) ; If t was a one - dimensional table , we could assume that each key is paired with a value . If t was a two - dimensional table , we could assume that each ; key is paired with a list of records, and the pairs can be treated as one - dimensional tables . But t is not . A key might have both a value and ; a subtable, as above. ; ; So that I chose the following represenation: ; ; * Each key is paired with a subtable ; * The car of that subtable points the value for the key ; * The car of each table points #f by default ; ; t ; | ; v ; [o][o]-->[o][/] ; | | ; v v ; #f [o][o]-->[o][o]-->[o][/] ; | | | ; v v v ; a v1 [o][o]-->[o][o]-->[o][/] ; | | | ; v v v ; b #f [o][o]-->[o][/] ; | | ; v v ; c v2 (define (make-table) (list #f)) (define (lookup keys table) (define (go keys table) (if (null? keys) (car table) (let ([pair (assoc (car keys) (cdr table))]) (if pair (go (cdr keys) (cdr pair)) #f)))) (go keys table)) (define (insert! keys value table) (define (go keys table) (if (null? keys) (set-car! table value) (let ([pair (assoc (car keys) (cdr table))]) (cond [pair (go (cdr keys) (cdr pair))] [else (let ([subtable (make-table)]) (set-cdr! table (list (cons (car keys) subtable) (cdr table))) (go (cdr keys) subtable))])))) (go keys table) 'ok) (define t (make-table)) #?=t #?=(lookup '(a) t) (insert! '(a) 'v1 t) #?=t #?=(lookup '(a) t) #?=(lookup '(a b c) t) (insert! '(a b c) 'v2 t) #?=t #?=(lookup '(a b c) t) #?=(lookup '(a b) t) #?=(lookup '(z) t)
null
https://raw.githubusercontent.com/kana/sicp/912bda4276995492ffc2ec971618316701e196f6/ex-3.25.scm
scheme
implement a table in which values are stored under an arbitrary number of keys and different values may be stored under different numbers of keys. The lookup and insert! procedures should take as input a list of keys used to access the table. Let's consider the following interaction: (define t (make-table)) (insert! '(a) 'v1) (insert! '(a b c) 'v2) key is paired with a list of records, and the pairs can be treated as a subtable, as above. So that I chose the following represenation: * Each key is paired with a subtable * The car of that subtable points the value for the key * The car of each table points #f by default t | v [o][o]-->[o][/] | | v v #f [o][o]-->[o][o]-->[o][/] | | | v v v a v1 [o][o]-->[o][o]-->[o][/] | | | v v v b #f [o][o]-->[o][/] | | v v c v2
Exercise 3.25 . Generalizing one- and two - dimensional tables , show how to If t was a one - dimensional table , we could assume that each key is paired with a value . If t was a two - dimensional table , we could assume that each one - dimensional tables . But t is not . A key might have both a value and (define (make-table) (list #f)) (define (lookup keys table) (define (go keys table) (if (null? keys) (car table) (let ([pair (assoc (car keys) (cdr table))]) (if pair (go (cdr keys) (cdr pair)) #f)))) (go keys table)) (define (insert! keys value table) (define (go keys table) (if (null? keys) (set-car! table value) (let ([pair (assoc (car keys) (cdr table))]) (cond [pair (go (cdr keys) (cdr pair))] [else (let ([subtable (make-table)]) (set-cdr! table (list (cons (car keys) subtable) (cdr table))) (go (cdr keys) subtable))])))) (go keys table) 'ok) (define t (make-table)) #?=t #?=(lookup '(a) t) (insert! '(a) 'v1 t) #?=t #?=(lookup '(a) t) #?=(lookup '(a b c) t) (insert! '(a b c) 'v2 t) #?=t #?=(lookup '(a b c) t) #?=(lookup '(a b) t) #?=(lookup '(z) t)
a8528da48a34a7c5416f5d0be7b27bf52e546715d48a6d98a520285a2ce14871
ocaml-ppx/ppxlib
context_free.mli
(** Context free rewriting, to define local rewriting rules that will all be applied at once by the driver. *) open! Import (** Local rewriting rules. This module lets you define local rewriting rules, such as extension point expanders. It is not completely generic and you cannot define any kind of rewriting, it currently focuses on what is commonly used. New scheme can be added on demand. We have some ideas to make this fully generic, but this hasn't been a priority so far. *) module Rule : sig type t val extension : Extension.t -> t (** Rewrite an extension point *) val special_function : string -> (expression -> expression option) -> t * [ special_function i d expand ] is a rule to rewrite a function call at parsing time . [ i d ] is the identifier to match on and [ expand ] is used to expand the full function application ( it gets the Pexp_apply node ) . If the function is found in the tree without being applied , [ expand ] gets only the identifier ( Pexp_ident node ) so you should handle both cases . If [ i d ] is an operator identifier and contains dots , it should be parenthesized ( e.g. [ " ( + .+ ) " ] ) . [ expand ] must decide whether the expression it receive can be rewritten or not . Especially ppxlib makes the assumption that [ expand ] is idempotent . It will loop if it is not . parsing time. [id] is the identifier to match on and [expand] is used to expand the full function application (it gets the Pexp_apply node). If the function is found in the tree without being applied, [expand] gets only the identifier (Pexp_ident node) so you should handle both cases. If [id] is an operator identifier and contains dots, it should be parenthesized (e.g. ["(+.+)"]). [expand] must decide whether the expression it receive can be rewritten or not. Especially ppxlib makes the assumption that [expand] is idempotent. It will loop if it is not. *) (** Used for the [constant] function. *) module Constant_kind : sig type t = Float | Integer end val constant : Constant_kind.t -> char -> (Location.t -> string -> Parsetree.expression) -> t (** [constant kind suffix expander] Registers an extension for transforming constants literals, based on the suffix character. *) (** The rest of this API is for rewriting rules that apply when a certain attribute is present. The API is not complete and is currently only enough to implement deriving. *) type ('a, 'b, 'c) attr_group_inline = ('b, 'c) Attribute.t -> (ctxt:Expansion_context.Deriver.t -> Asttypes.rec_flag -> 'b list -> 'c option list -> 'a list) -> t * Match the attribute on a group of items , such as a group of recursive type definitions ( Pstr_type , Psig_type ) . The expander will be triggered if any of the item has the attribute . The expander is called as follow : [ expand ~loc ~path rec_flag items values ] where [ values ] is the list of values associated to the attribute for each item in [ items ] . [ expand ] must return a list of element to add after the group . For instance a list of structure item to add after a group of type definitions . definitions (Pstr_type, Psig_type). The expander will be triggered if any of the item has the attribute. The expander is called as follow: [expand ~loc ~path rec_flag items values] where [values] is the list of values associated to the attribute for each item in [items]. [expand] must return a list of element to add after the group. For instance a list of structure item to add after a group of type definitions. *) val attr_str_type_decl : (structure_item, type_declaration, _) attr_group_inline val attr_sig_type_decl : (signature_item, type_declaration, _) attr_group_inline val attr_str_type_decl_expect : (structure_item, type_declaration, _) attr_group_inline (** The _expect variants are for producing code that is compared to what the user wrote in the source code. *) val attr_sig_type_decl_expect : (signature_item, type_declaration, _) attr_group_inline type ('a, 'b, 'c) attr_inline = ('b, 'c) Attribute.t -> (ctxt:Expansion_context.Deriver.t -> 'b -> 'c -> 'a list) -> t (** Same as [attr_group_inline] but for elements that are not part of a group, such as exceptions and type extensions *) val attr_str_module_type_decl : (structure_item, module_type_declaration, _) attr_inline val attr_sig_module_type_decl : (signature_item, module_type_declaration, _) attr_inline val attr_str_module_type_decl_expect : (structure_item, module_type_declaration, _) attr_inline val attr_sig_module_type_decl_expect : (signature_item, module_type_declaration, _) attr_inline val attr_str_type_ext : (structure_item, type_extension, _) attr_inline val attr_sig_type_ext : (signature_item, type_extension, _) attr_inline val attr_str_type_ext_expect : (structure_item, type_extension, _) attr_inline val attr_sig_type_ext_expect : (signature_item, type_extension, _) attr_inline val attr_str_exception : (structure_item, type_exception, _) attr_inline val attr_sig_exception : (signature_item, type_exception, _) attr_inline val attr_str_exception_expect : (structure_item, type_exception, _) attr_inline val attr_sig_exception_expect : (signature_item, type_exception, _) attr_inline end (**/**) (*_ This API is not stable *) module Generated_code_hook : sig type 'a single_or_many = Single of 'a | Many of 'a list (*_ Hook called whenever we generate code some *) type t = { f : 'a. 'a Extension.Context.t -> Location.t -> 'a single_or_many -> unit; } val nop : t end module Expect_mismatch_handler : sig type t = { f : 'a. 'a Attribute.Floating.Context.t -> Location.t -> 'a list -> unit; } val nop : t end (**/**) (* TODO: a simple comment here is fine, while we would expect only docstring or (*_ *) comments to be accepted. On the contrary, docstrings are *not* accepted. This means was not complete and indeed the parser should be fixed. *) class map_top_down : ?expect_mismatch_handler: Expect_mismatch_handler.t (* default: Expect_mismatch_handler.nop *) -> ?generated_code_hook: Generated_code_hook.t (* default: Generated_code_hook.nop *) -> Rule.t list -> object inherit Ast_traverse.map_with_expansion_context_and_errors end
null
https://raw.githubusercontent.com/ocaml-ppx/ppxlib/1110af2ea18f351cc3f2ccbee8444bb2a4b257b7/src/context_free.mli
ocaml
* Context free rewriting, to define local rewriting rules that will all be applied at once by the driver. * Local rewriting rules. This module lets you define local rewriting rules, such as extension point expanders. It is not completely generic and you cannot define any kind of rewriting, it currently focuses on what is commonly used. New scheme can be added on demand. We have some ideas to make this fully generic, but this hasn't been a priority so far. * Rewrite an extension point * Used for the [constant] function. * [constant kind suffix expander] Registers an extension for transforming constants literals, based on the suffix character. * The rest of this API is for rewriting rules that apply when a certain attribute is present. The API is not complete and is currently only enough to implement deriving. * The _expect variants are for producing code that is compared to what the user wrote in the source code. * Same as [attr_group_inline] but for elements that are not part of a group, such as exceptions and type extensions */* _ This API is not stable _ Hook called whenever we generate code some */* TODO: a simple comment here is fine, while we would expect only docstring or (*_ default: Expect_mismatch_handler.nop default: Generated_code_hook.nop
open! Import module Rule : sig type t val extension : Extension.t -> t val special_function : string -> (expression -> expression option) -> t * [ special_function i d expand ] is a rule to rewrite a function call at parsing time . [ i d ] is the identifier to match on and [ expand ] is used to expand the full function application ( it gets the Pexp_apply node ) . If the function is found in the tree without being applied , [ expand ] gets only the identifier ( Pexp_ident node ) so you should handle both cases . If [ i d ] is an operator identifier and contains dots , it should be parenthesized ( e.g. [ " ( + .+ ) " ] ) . [ expand ] must decide whether the expression it receive can be rewritten or not . Especially ppxlib makes the assumption that [ expand ] is idempotent . It will loop if it is not . parsing time. [id] is the identifier to match on and [expand] is used to expand the full function application (it gets the Pexp_apply node). If the function is found in the tree without being applied, [expand] gets only the identifier (Pexp_ident node) so you should handle both cases. If [id] is an operator identifier and contains dots, it should be parenthesized (e.g. ["(+.+)"]). [expand] must decide whether the expression it receive can be rewritten or not. Especially ppxlib makes the assumption that [expand] is idempotent. It will loop if it is not. *) module Constant_kind : sig type t = Float | Integer end val constant : Constant_kind.t -> char -> (Location.t -> string -> Parsetree.expression) -> t type ('a, 'b, 'c) attr_group_inline = ('b, 'c) Attribute.t -> (ctxt:Expansion_context.Deriver.t -> Asttypes.rec_flag -> 'b list -> 'c option list -> 'a list) -> t * Match the attribute on a group of items , such as a group of recursive type definitions ( Pstr_type , Psig_type ) . The expander will be triggered if any of the item has the attribute . The expander is called as follow : [ expand ~loc ~path rec_flag items values ] where [ values ] is the list of values associated to the attribute for each item in [ items ] . [ expand ] must return a list of element to add after the group . For instance a list of structure item to add after a group of type definitions . definitions (Pstr_type, Psig_type). The expander will be triggered if any of the item has the attribute. The expander is called as follow: [expand ~loc ~path rec_flag items values] where [values] is the list of values associated to the attribute for each item in [items]. [expand] must return a list of element to add after the group. For instance a list of structure item to add after a group of type definitions. *) val attr_str_type_decl : (structure_item, type_declaration, _) attr_group_inline val attr_sig_type_decl : (signature_item, type_declaration, _) attr_group_inline val attr_str_type_decl_expect : (structure_item, type_declaration, _) attr_group_inline val attr_sig_type_decl_expect : (signature_item, type_declaration, _) attr_group_inline type ('a, 'b, 'c) attr_inline = ('b, 'c) Attribute.t -> (ctxt:Expansion_context.Deriver.t -> 'b -> 'c -> 'a list) -> t val attr_str_module_type_decl : (structure_item, module_type_declaration, _) attr_inline val attr_sig_module_type_decl : (signature_item, module_type_declaration, _) attr_inline val attr_str_module_type_decl_expect : (structure_item, module_type_declaration, _) attr_inline val attr_sig_module_type_decl_expect : (signature_item, module_type_declaration, _) attr_inline val attr_str_type_ext : (structure_item, type_extension, _) attr_inline val attr_sig_type_ext : (signature_item, type_extension, _) attr_inline val attr_str_type_ext_expect : (structure_item, type_extension, _) attr_inline val attr_sig_type_ext_expect : (signature_item, type_extension, _) attr_inline val attr_str_exception : (structure_item, type_exception, _) attr_inline val attr_sig_exception : (signature_item, type_exception, _) attr_inline val attr_str_exception_expect : (structure_item, type_exception, _) attr_inline val attr_sig_exception_expect : (signature_item, type_exception, _) attr_inline end module Generated_code_hook : sig type 'a single_or_many = Single of 'a | Many of 'a list type t = { f : 'a. 'a Extension.Context.t -> Location.t -> 'a single_or_many -> unit; } val nop : t end module Expect_mismatch_handler : sig type t = { f : 'a. 'a Attribute.Floating.Context.t -> Location.t -> 'a list -> unit; } val nop : t end comments to be accepted. On the contrary, docstrings are *not* accepted. This means was not complete and indeed the parser should be fixed. *) class map_top_down : ?expect_mismatch_handler: -> ?generated_code_hook: -> Rule.t list -> object inherit Ast_traverse.map_with_expansion_context_and_errors end
7aaa2b4ea78432bbd72ad4864e435b37da7da8a1d915a0854b0c5c0be29d4514
carl-eastlund/dracula
random.rkt
#lang racket (require racket/require (path-up "self/require.rkt") (for-syntax (cce-in syntax)) (cce-in function) (prefix-in raw- (combine-in (random-in random) srfi/27))) (provide/contract [prob/c (case-> (-> flat-contract?) (-> (one-of/c 0 1) flat-contract?) (-> (one-of/c 0) (one-of/c 1) flat-contract?))]) prob / c : [ 0 1 ] - > FlatContract Accepts real numbers in ( 0,1 ) , inclusive of 0 and/or 1 if supplied . (define prob/c (match-lambda* [(list) (and/c (real-in 0 1) (>/c 0) (</c 1))] [(list 0) (and/c (real-in 0 1) (</c 1))] [(list 1) (and/c (real-in 0 1) (>/c 0))] [(list 0 1) (real-in 0 1)])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; SETUP ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (source) (current-pseudo-random-generator)) (define (schematics-random-integer k) ((raw-random-source-make-integers (source)) k)) (define (schematics-random-real) ((raw-random-source-make-reals (source)))) (define (schematics-random-binomial n p) ((raw-random-source-make-binomials (source)) n p)) (define (schematics-random-geometric p) ((raw-random-source-make-geometrics (source)) p)) (define (schematics-random-poisson r) ((raw-random-source-make-poissons (source)) r)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BOOLEAN DISTRIBUTIONS ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-boolean (->* [] [(prob/c 0 1)] boolean?)] [random-boolean/fair (-> boolean?)] [random-boolean/bernoulli (-> (prob/c 0 1) boolean?)]) random - boolean / : Prob - > ( Random Boolean ) (define (random-boolean/bernoulli p) (if (exact? p) (let* ([n (numerator p)] [d (denominator p)]) (< (schematics-random-integer d) n)) (< (schematics-random-real) p))) ;; random-boolean/fair : (Random Boolean) (define (random-boolean/fair) (random-boolean/bernoulli 1/2)) ;; random-boolean : [Prob] -> (Random Boolean) (define (random-boolean [p 1/2]) (random-boolean/bernoulli p)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BOUNDED INTEGER DISTRIBUTIONS ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-natural/binomial (->d ([n natural-number/c] [p (prob/c 0 1)]) () [_ (integer-in 0 n)])] [random-integer/uniform (->d ([lo exact-integer?] [hi (and/c exact-integer? (>=/c lo))]) () [_ (integer-in lo hi)])]) random - natural / binomial : ( ) (define (random-natural/binomial n p) (inexact->exact (schematics-random-binomial n p))) random - integer / uniform : Int Int - > ( Random Int ) The second argument must not be less than the first . (define (random-integer/uniform lo hi) (+ lo (schematics-random-integer (+ hi 1 (- lo))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; UNBOUNDED INTEGER DISTRIBUTIONS ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Make these depend on their optional arguments once I learn how. (provide/contract [random-natural/geometric (-> (prob/c) (one-of/c 0 1) natural-number/c)] [random-natural/pascal (-> exact-positive-integer? (prob/c) natural-number/c)] [random-natural/poisson (-> (and/c rational? positive?) natural-number/c)] [random-integer/skellam (->* [(and/c rational? positive?)] [(and/c rational? positive?)] exact-integer?)]) random - natural / geometric : Prob ( Or 0 1 ) - > ( ) (define (random-natural/geometric p base) (+ base (inexact->exact (schematics-random-geometric p)) -1)) random - natural / pascal : Pos Prob - > ( ) (define (random-natural/pascal n p) (for/fold ([sum 0]) ([i (in-range 1 n)]) (+ sum (random-natural/geometric p 0)))) random - natural / poisson : PosRat - > ( ) (define (random-natural/poisson rate) (inexact->exact (schematics-random-poisson rate))) random - integer / : PosRat [ PosRat ] - > ( Random Int ) (define (random-integer/skellam pos-rate [neg-rate pos-rate]) (- (random-natural/poisson pos-rate) (random-natural/poisson neg-rate))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BOUNDED REAL DISTRIBUTIONS ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-real/uniform (->d ([lo real?] [hi (and/c real? (>=/c lo))]) () [_ (real-in lo hi)])]) ;; random-real/uniform : Real Real>=lo -> Real in [lo,hi] (define (random-real/uniform lo hi) (+ lo (* (- hi lo) (schematics-random-real)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; RANDOM CHOICE ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-choice (->* [any/c] [] #:rest (listof any/c) any/c)] [random-choice-weighted (-> (listof (cons/c (>/c 0) any/c)) any/c)]) (define (random-choice . args) (list-ref args (random-integer/uniform 0 (- (length args) 1)))) (define (random-choice-weighted alist) (let* ([weights (map inexact->exact (map car alist))] [values (map cdr alist)] [total (apply + weights)] [choice (random-real/uniform 0 1)]) (let loop ([ws weights] [vs values] [cumulative 0]) (if (null? ws) (error 'random-choice-weighted "no choices given") (let* ([accum (+ cumulative (/ (car ws) total))]) (if (<= choice accum) (car vs) (loop (cdr ws) (cdr vs) accum))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; RANDOM DISPATCH ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide random-case) (define-for-syntax (expand-random-case/weighted-args stx) (syntax-case stx () [() stx] [(expr #:weight wt . rest) (quasisyntax/loc stx ([expr wt] #,@(expand-random-case/weighted-args #'rest)))] [(expr . rest) (quasisyntax/loc stx ([expr 1] #,@(expand-random-case/weighted-args #'rest)))] [_ (syntax-error stx "expected a sequence of expressions with optional #:weight keywords")])) (define-syntax (random-case stx) (parameterize ([current-syntax stx]) (syntax-case stx () [(_ arg ...) (with-syntax ([([expr wt] ...) (expand-random-case/weighted-args #'(arg ...))]) (syntax/loc stx (call (random-choice-weighted (list (cons wt (lambda () expr)) ...)))))]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; DEFAULT NUMBER DISTRIBUTIONS ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-natural (-> natural-number/c)] [random-integer (-> exact-integer?)] [random-rational (-> (and/c rational? exact?))] [random-exact (-> (and/c number? exact?))] [random-positive-real (-> (and/c inexact-real? (>/c 0)))] [random-real (-> inexact-real?)] [random-inexact (-> (and/c number? inexact?))] [random-number (-> number?)]) ;; Primitive constructors (define (random-nonnegative-integer) (random-natural/geometric 1/1000 0)) (define (random-positive-integer) (random-natural/geometric 1/1000 1)) (define (random-signed-integer) (random-case (random-nonnegative-integer) (- (random-nonnegative-integer)))) (define (random-nonnegative-ratio) (/ (random-nonnegative-integer) (random-positive-integer))) (define (random-signed-ratio) (random-case (random-nonnegative-ratio) (- (random-nonnegative-ratio)))) (define (random-exact-complex) (make-rectangular (random-signed-ratio) (random-signed-ratio))) (define (random-unitary-real) (random-real/uniform 0 1)) (define (random-positive-real) (/ (random-unitary-real) (random-unitary-real))) (define (random-signed-real) (random-case (random-positive-real) (- (random-positive-real)))) (define (random-inexact-complex) (make-rectangular (random-signed-real) (random-signed-real))) ;; Exported constructors (define (random-natural) (random-nonnegative-integer)) (define (random-integer) (random-signed-integer)) (define (random-rational) (random-case (random-signed-integer) (random-signed-ratio))) (define (random-exact) (random-case (random-signed-integer) (random-signed-ratio) (random-exact-complex))) (define (random-real) (random-signed-real)) (define (random-inexact) (random-case (random-signed-real) (random-inexact-complex))) (define (random-number) (random-case (random-signed-integer) (random-signed-ratio) (random-exact-complex) (random-signed-real) (random-inexact-complex))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; LIST DISTRIBUTIONS ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-list (->* [(-> any/c)] [#:len natural-number/c] list?)]) (define (random-list make-elem #:len [len (random-natural/poisson 4)]) (build-list len (thunk* (make-elem)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; TEXT DISTRIBUTIONS ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-char (-> char?)] [random-string (->* [] [#:char (-> char?) #:len natural-number/c] string?)] [random-symbol (->* [] [#:string string?] symbol?)] [random-keyword (->* [] [#:string string?] keyword?)]) (define (random-char) (string-ref "abcdefghijklmnopqrstuvwxyz" (random-integer/uniform 0 25))) (define (random-string #:char [make-char random-char] #:len [len (random-natural/poisson 4)]) (apply string (random-list make-char #:len len))) (define (random-symbol #:string [string (random-string)]) (string->symbol string)) (define (random-keyword #:string [string (random-string)]) (string->keyword string)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (provide/contract [random-atom (-> (not/c cons?))] [random-sexp (->* [] [#:atom (-> (not/c cons?)) #:improper boolean? #:size exact-nonnegative-integer?] any/c)]) (define (random-atom) (random-case empty (random-boolean) (random-symbol) (random-char) (random-number) (random-string))) (define (random-sexp #:atom [make-atom random-atom] #:improper [improper? #f] #:size [size (random-natural/poisson 4)]) (if improper? (random-improper-sexp? make-atom size) (random-proper-sexp? make-atom size))) (define (random-improper-sexp? make-atom size) (if (= size 0) (make-atom) (let* ([left-size (random-integer/uniform 0 (- size 1))] [right-size (- size left-size 1)]) (cons (random-improper-sexp? make-atom left-size) (random-improper-sexp? make-atom right-size))))) (define (random-proper-sexp? make-atom size) (if (= size 0) (make-atom) (let* ([len (random-integer/uniform 1 size)] [sub (- size len)] [subsizes (random-split-count sub len)]) (map (lambda (subsize) (random-proper-sexp? make-atom subsize)) subsizes)))) (define (random-split-count count len) (let* ([vec (make-vector len 0)]) (for ([i (in-range count)]) (let* ([j (random-integer/uniform 0 (- len 1))]) (vector-set! vec j (+ (vector-ref vec j) 1)))) (vector->list vec)))
null
https://raw.githubusercontent.com/carl-eastlund/dracula/a937f4b40463779246e3544e4021c53744a33847/private/fasttest/random.rkt
racket
SETUP random-boolean/fair : (Random Boolean) random-boolean : [Prob] -> (Random Boolean) Make these depend on their optional arguments once I learn how. random-real/uniform : Real Real>=lo -> Real in [lo,hi] DEFAULT NUMBER DISTRIBUTIONS Primitive constructors Exported constructors LIST DISTRIBUTIONS
#lang racket (require racket/require (path-up "self/require.rkt") (for-syntax (cce-in syntax)) (cce-in function) (prefix-in raw- (combine-in (random-in random) srfi/27))) (provide/contract [prob/c (case-> (-> flat-contract?) (-> (one-of/c 0 1) flat-contract?) (-> (one-of/c 0) (one-of/c 1) flat-contract?))]) prob / c : [ 0 1 ] - > FlatContract Accepts real numbers in ( 0,1 ) , inclusive of 0 and/or 1 if supplied . (define prob/c (match-lambda* [(list) (and/c (real-in 0 1) (>/c 0) (</c 1))] [(list 0) (and/c (real-in 0 1) (</c 1))] [(list 1) (and/c (real-in 0 1) (>/c 0))] [(list 0 1) (real-in 0 1)])) (define (source) (current-pseudo-random-generator)) (define (schematics-random-integer k) ((raw-random-source-make-integers (source)) k)) (define (schematics-random-real) ((raw-random-source-make-reals (source)))) (define (schematics-random-binomial n p) ((raw-random-source-make-binomials (source)) n p)) (define (schematics-random-geometric p) ((raw-random-source-make-geometrics (source)) p)) (define (schematics-random-poisson r) ((raw-random-source-make-poissons (source)) r)) BOOLEAN DISTRIBUTIONS (provide/contract [random-boolean (->* [] [(prob/c 0 1)] boolean?)] [random-boolean/fair (-> boolean?)] [random-boolean/bernoulli (-> (prob/c 0 1) boolean?)]) random - boolean / : Prob - > ( Random Boolean ) (define (random-boolean/bernoulli p) (if (exact? p) (let* ([n (numerator p)] [d (denominator p)]) (< (schematics-random-integer d) n)) (< (schematics-random-real) p))) (define (random-boolean/fair) (random-boolean/bernoulli 1/2)) (define (random-boolean [p 1/2]) (random-boolean/bernoulli p)) BOUNDED INTEGER DISTRIBUTIONS (provide/contract [random-natural/binomial (->d ([n natural-number/c] [p (prob/c 0 1)]) () [_ (integer-in 0 n)])] [random-integer/uniform (->d ([lo exact-integer?] [hi (and/c exact-integer? (>=/c lo))]) () [_ (integer-in lo hi)])]) random - natural / binomial : ( ) (define (random-natural/binomial n p) (inexact->exact (schematics-random-binomial n p))) random - integer / uniform : Int Int - > ( Random Int ) The second argument must not be less than the first . (define (random-integer/uniform lo hi) (+ lo (schematics-random-integer (+ hi 1 (- lo))))) UNBOUNDED INTEGER DISTRIBUTIONS (provide/contract [random-natural/geometric (-> (prob/c) (one-of/c 0 1) natural-number/c)] [random-natural/pascal (-> exact-positive-integer? (prob/c) natural-number/c)] [random-natural/poisson (-> (and/c rational? positive?) natural-number/c)] [random-integer/skellam (->* [(and/c rational? positive?)] [(and/c rational? positive?)] exact-integer?)]) random - natural / geometric : Prob ( Or 0 1 ) - > ( ) (define (random-natural/geometric p base) (+ base (inexact->exact (schematics-random-geometric p)) -1)) random - natural / pascal : Pos Prob - > ( ) (define (random-natural/pascal n p) (for/fold ([sum 0]) ([i (in-range 1 n)]) (+ sum (random-natural/geometric p 0)))) random - natural / poisson : PosRat - > ( ) (define (random-natural/poisson rate) (inexact->exact (schematics-random-poisson rate))) random - integer / : PosRat [ PosRat ] - > ( Random Int ) (define (random-integer/skellam pos-rate [neg-rate pos-rate]) (- (random-natural/poisson pos-rate) (random-natural/poisson neg-rate))) BOUNDED REAL DISTRIBUTIONS (provide/contract [random-real/uniform (->d ([lo real?] [hi (and/c real? (>=/c lo))]) () [_ (real-in lo hi)])]) (define (random-real/uniform lo hi) (+ lo (* (- hi lo) (schematics-random-real)))) RANDOM CHOICE (provide/contract [random-choice (->* [any/c] [] #:rest (listof any/c) any/c)] [random-choice-weighted (-> (listof (cons/c (>/c 0) any/c)) any/c)]) (define (random-choice . args) (list-ref args (random-integer/uniform 0 (- (length args) 1)))) (define (random-choice-weighted alist) (let* ([weights (map inexact->exact (map car alist))] [values (map cdr alist)] [total (apply + weights)] [choice (random-real/uniform 0 1)]) (let loop ([ws weights] [vs values] [cumulative 0]) (if (null? ws) (error 'random-choice-weighted "no choices given") (let* ([accum (+ cumulative (/ (car ws) total))]) (if (<= choice accum) (car vs) (loop (cdr ws) (cdr vs) accum))))))) RANDOM DISPATCH (provide random-case) (define-for-syntax (expand-random-case/weighted-args stx) (syntax-case stx () [() stx] [(expr #:weight wt . rest) (quasisyntax/loc stx ([expr wt] #,@(expand-random-case/weighted-args #'rest)))] [(expr . rest) (quasisyntax/loc stx ([expr 1] #,@(expand-random-case/weighted-args #'rest)))] [_ (syntax-error stx "expected a sequence of expressions with optional #:weight keywords")])) (define-syntax (random-case stx) (parameterize ([current-syntax stx]) (syntax-case stx () [(_ arg ...) (with-syntax ([([expr wt] ...) (expand-random-case/weighted-args #'(arg ...))]) (syntax/loc stx (call (random-choice-weighted (list (cons wt (lambda () expr)) ...)))))]))) (provide/contract [random-natural (-> natural-number/c)] [random-integer (-> exact-integer?)] [random-rational (-> (and/c rational? exact?))] [random-exact (-> (and/c number? exact?))] [random-positive-real (-> (and/c inexact-real? (>/c 0)))] [random-real (-> inexact-real?)] [random-inexact (-> (and/c number? inexact?))] [random-number (-> number?)]) (define (random-nonnegative-integer) (random-natural/geometric 1/1000 0)) (define (random-positive-integer) (random-natural/geometric 1/1000 1)) (define (random-signed-integer) (random-case (random-nonnegative-integer) (- (random-nonnegative-integer)))) (define (random-nonnegative-ratio) (/ (random-nonnegative-integer) (random-positive-integer))) (define (random-signed-ratio) (random-case (random-nonnegative-ratio) (- (random-nonnegative-ratio)))) (define (random-exact-complex) (make-rectangular (random-signed-ratio) (random-signed-ratio))) (define (random-unitary-real) (random-real/uniform 0 1)) (define (random-positive-real) (/ (random-unitary-real) (random-unitary-real))) (define (random-signed-real) (random-case (random-positive-real) (- (random-positive-real)))) (define (random-inexact-complex) (make-rectangular (random-signed-real) (random-signed-real))) (define (random-natural) (random-nonnegative-integer)) (define (random-integer) (random-signed-integer)) (define (random-rational) (random-case (random-signed-integer) (random-signed-ratio))) (define (random-exact) (random-case (random-signed-integer) (random-signed-ratio) (random-exact-complex))) (define (random-real) (random-signed-real)) (define (random-inexact) (random-case (random-signed-real) (random-inexact-complex))) (define (random-number) (random-case (random-signed-integer) (random-signed-ratio) (random-exact-complex) (random-signed-real) (random-inexact-complex))) (provide/contract [random-list (->* [(-> any/c)] [#:len natural-number/c] list?)]) (define (random-list make-elem #:len [len (random-natural/poisson 4)]) (build-list len (thunk* (make-elem)))) TEXT DISTRIBUTIONS (provide/contract [random-char (-> char?)] [random-string (->* [] [#:char (-> char?) #:len natural-number/c] string?)] [random-symbol (->* [] [#:string string?] symbol?)] [random-keyword (->* [] [#:string string?] keyword?)]) (define (random-char) (string-ref "abcdefghijklmnopqrstuvwxyz" (random-integer/uniform 0 25))) (define (random-string #:char [make-char random-char] #:len [len (random-natural/poisson 4)]) (apply string (random-list make-char #:len len))) (define (random-symbol #:string [string (random-string)]) (string->symbol string)) (define (random-keyword #:string [string (random-string)]) (string->keyword string)) (provide/contract [random-atom (-> (not/c cons?))] [random-sexp (->* [] [#:atom (-> (not/c cons?)) #:improper boolean? #:size exact-nonnegative-integer?] any/c)]) (define (random-atom) (random-case empty (random-boolean) (random-symbol) (random-char) (random-number) (random-string))) (define (random-sexp #:atom [make-atom random-atom] #:improper [improper? #f] #:size [size (random-natural/poisson 4)]) (if improper? (random-improper-sexp? make-atom size) (random-proper-sexp? make-atom size))) (define (random-improper-sexp? make-atom size) (if (= size 0) (make-atom) (let* ([left-size (random-integer/uniform 0 (- size 1))] [right-size (- size left-size 1)]) (cons (random-improper-sexp? make-atom left-size) (random-improper-sexp? make-atom right-size))))) (define (random-proper-sexp? make-atom size) (if (= size 0) (make-atom) (let* ([len (random-integer/uniform 1 size)] [sub (- size len)] [subsizes (random-split-count sub len)]) (map (lambda (subsize) (random-proper-sexp? make-atom subsize)) subsizes)))) (define (random-split-count count len) (let* ([vec (make-vector len 0)]) (for ([i (in-range count)]) (let* ([j (random-integer/uniform 0 (- len 1))]) (vector-set! vec j (+ (vector-ref vec j) 1)))) (vector->list vec)))
21413bd017713e123693da06cf8fc837e2445bab61d401724cd528f60cf9c802
ocurrent/ocurrent-deployer
aws.ml
(* Compose configuration for a AWS ECS *) type t = { name: string; branch: string; vcpu: float; memory: int; storage: int option; replicas: int; command: string option; port: int; certificate: string; } let command_colon = function | None -> "" | Some cmd -> " command: " ^ cmd ^ "\n" let storage_colon n gb = match gb with | None -> "" | Some gb -> Fmt.str {| %sTaskDefinition: Properties: EphemeralStorage: SizeInGiB: %i |} n gb let compose s = let capitalized_branch = String.capitalize_ascii s.branch in let service = Fmt.str {| version: "3.4" services: %s: image: $IMAGE_HASH %s ports: - target: %i x-aws-protocol: http deploy: replicas: %i resources: limits: cpus: '%f' memory: %iM x-aws-logs_retention: 90 x-aws-cloudformation: Resources: %sService: Properties: DeploymentConfiguration: MaximumPercent: 100 MinimumHealthyPercent: 50 %s Default%iIngress: Properties: FromPort: 443 Description: %s:443/tcp on default network ToPort: 443 %s%iListener: Properties: Certificates: - CertificateArn: "%s" Protocol: HTTPS Port: 443 HttpToHttpsListener: Properties: DefaultActions: - Type: redirect RedirectConfig: Port: 443 Protocol: HTTPS StatusCode: HTTP_301 LoadBalancerArn: Ref: LoadBalancer Port: 80 Protocol: HTTP Type: AWS::ElasticLoadBalancingV2::Listener |} s.branch (* service *) (command_colon s.command) (* command: something *) s.port (* ports: - n where n is the container port the service is running on *) s.replicas (* Number of instances to create *) vcpu : is a factional value 0.5 = > 512 out of 1024 cpu units container RAM in MB capitalized_branch EC2 instance storage space - default 20 GB Ingress description update and set overwrite port with 443 capitalized_branch s.port s.certificate (* xxxTCPyyListerner set the SSL certificate to use *) in service Replace $ IMAGE_HASH in the compose file with the fixed ( hash ) image i d let replace_hash_var ~hash contents = Re.Str.(global_replace (regexp_string "$IMAGE_HASH") hash contents)
null
https://raw.githubusercontent.com/ocurrent/ocurrent-deployer/ec01824b1abd9ad77cea7d058316293515b11f68/src/aws.ml
ocaml
Compose configuration for a AWS ECS service command: something ports: - n where n is the container port the service is running on Number of instances to create xxxTCPyyListerner set the SSL certificate to use
type t = { name: string; branch: string; vcpu: float; memory: int; storage: int option; replicas: int; command: string option; port: int; certificate: string; } let command_colon = function | None -> "" | Some cmd -> " command: " ^ cmd ^ "\n" let storage_colon n gb = match gb with | None -> "" | Some gb -> Fmt.str {| %sTaskDefinition: Properties: EphemeralStorage: SizeInGiB: %i |} n gb let compose s = let capitalized_branch = String.capitalize_ascii s.branch in let service = Fmt.str {| version: "3.4" services: %s: image: $IMAGE_HASH %s ports: - target: %i x-aws-protocol: http deploy: replicas: %i resources: limits: cpus: '%f' memory: %iM x-aws-logs_retention: 90 x-aws-cloudformation: Resources: %sService: Properties: DeploymentConfiguration: MaximumPercent: 100 MinimumHealthyPercent: 50 %s Default%iIngress: Properties: FromPort: 443 Description: %s:443/tcp on default network ToPort: 443 %s%iListener: Properties: Certificates: - CertificateArn: "%s" Protocol: HTTPS Port: 443 HttpToHttpsListener: Properties: DefaultActions: - Type: redirect RedirectConfig: Port: 443 Protocol: HTTPS StatusCode: HTTP_301 LoadBalancerArn: Ref: LoadBalancer Port: 80 Protocol: HTTP Type: AWS::ElasticLoadBalancingV2::Listener vcpu : is a factional value 0.5 = > 512 out of 1024 cpu units container RAM in MB capitalized_branch EC2 instance storage space - default 20 GB Ingress description update and set overwrite port with 443 in service Replace $ IMAGE_HASH in the compose file with the fixed ( hash ) image i d let replace_hash_var ~hash contents = Re.Str.(global_replace (regexp_string "$IMAGE_HASH") hash contents)
49450309c26e7b525de4e5f09eb31aaa59395ea38083e2ab3572848663744f16
solomon-b/monoidal-functors
Monoidal.hs
module Data.Bifunctor.Monoidal ( -- * Semigroupal Semigroupal (..), * Unital Unital (..), -- * Monoidal Monoidal, ) where -------------------------------------------------------------------------------- import Control.Applicative (Alternative (..), Applicative (..), pure, (<$>)) import Control.Arrow (Kleisli (..)) import Control.Category (Category (..)) import Control.Category.Cartesian (Cocartesian (..), Semicartesian (..)) import Control.Category.Tensor (Associative, Iso (..), Tensor (..)) import Control.Monad (Functor (..), Monad) import Data.Biapplicative (Biapplicative (..), Bifunctor (..)) import Data.Bifunctor.Clown (Clown) import Data.Bifunctor.Joker (Joker (..)) import Data.Either (Either, either) import Data.Function (const, ($)) import Data.Profunctor (Forget (..), Profunctor (..), Star (..), Strong (..)) import Data.Semigroupoid (Semigroupoid (..)) import Data.These (These (..), these) import Data.Tuple (fst, snd, uncurry) import Data.Void (Void, absurd) import Prelude (Either (..)) -------------------------------------------------------------------------------- | Given monoidal categories \((\mathcal{C } , \otimes , I_{\mathcal{C}})\ ) and \((\mathcal{D } , \bullet , I_{\mathcal{D}})\ ) . A bifunctor \(F : \mathcal{C_1 } \times \mathcal{C_2 } \to \mathcal{D}\ ) is ' Semigroupal ' if it supports a natural transformation \(\phi_{AB , CD } : F\ A\ B \bullet F\ C\ D \to F\ ( A \otimes ( B \otimes D)\ ) , which we call ' combine ' . -- -- === Laws -- -- __Associativity:__ -- -- \[ -- \require{AMScd} -- \begin{CD} -- (F A B \bullet F C D) \bullet F X Y @>>{\alpha_{\mathcal{D}}}> F A B \bullet (F C D \bullet F X Y) \\ -- @VV{\phi_{AB,CD} \bullet 1}V @VV{1 \bullet \phi_{CD,FY}}V \\ -- F (A \otimes C) (B \otimes D) \bullet F X Y @. F A B \bullet (F (C \otimes X) (D \otimes Y) \\ @VV{\phi_{(A \otimes C)(B \otimes D),XY}}V @VV{\phi_{AB,(C \otimes X)(D \otimes Y)}}V \\ F ( ( A \otimes C ) \otimes X ) ( ( B \otimes D ) \otimes Y ) @>>{F \alpha_{\mathcal{C_1 } } } \alpha_{\mathcal{C_2 } } > F ( A \otimes ( C \otimes X ) ) ( B \otimes ( D \otimes Y ) ) \\ -- \end{CD} -- \] -- -- @ ' combine ' ' Control . Category .. ' ' Control.Category.Tensor.grmap ' ' combine ' ' Control . Category .. ' ' bwd ' ' Control.Category.Tensor.assoc ' ≡ ' fmap ' ( ' bwd ' ' Control.Category.Tensor.assoc ' ) ' Control . Category .. ' ' combine ' ' Control . Category .. ' ' Control.Category.Tensor.glmap ' ' combine ' -- @ class (Associative cat t1, Associative cat t2, Associative cat to) => Semigroupal cat t1 t2 to f where | A natural transformation \(\phi_{AB , CD } : F\ A\ B \bullet F\ C\ D \to F\ ( A \otimes ( B \otimes D)\ ) . -- -- ==== __Examples__ -- > > > : t combine > ) @ ( , ) @ ( , ) @ ( , ) @ ( , ) combine @(- > ) @ ( , ) @ ( , ) @ ( , ) @ ( , ) : : ( ( x , y ) , ( x ' , y ' ) ) - > ( ( x , x ' ) , ( y , y ' ) ) -- > > > combine @(- > ) @ ( , ) @ ( , ) @ ( , ) @ ( , ) ( ( True , " Hello " ) , ( ( ) , " World " ) ) -- ((True,()),("Hello","World")) -- > > > combine @(- > ) @ ( , ) @ ( , ) @ ( , ) > ) ( show , ( > 10 ) ) ( True , 11 ) -- ("True",True) combine :: cat (to (f x y) (f x' y')) (f (t1 x x') (t2 y y')) instance Profunctor p => Semigroupal (->) (,) Either Either p where combine :: Either (p x y) (p x' y') -> p (x, x') (Either y y') combine = either (dimap fst Left) (dimap snd Right) instance Semigroupal (->) (,) (,) (,) (,) where combine :: ((x, y), (x', y')) -> ((x, x'), (y, y')) combine ((x, y), (x', y')) = ((x, x'), (y, y')) -- NOTE: This version could be used for a more general abstraction -- of products in a category: -- combine = -- let fwd' = fwd assoc bwd ' = bwd assoc in second swap . swap . fwd ' . swap . first ( bwd ' . first swap ) . fwd ' instance Semigroupal (->) Either Either Either (,) where combine :: Either (x, y) (x', y') -> (Either x x', Either y y') combine = either (bimap Left Left) (bimap Right Right) instance Semigroupal (->) Either Either Either Either where combine :: Either (Either x y) (Either x' y') -> Either (Either x x') (Either y y') combine = either (bimap Left Left) (bimap Right Right) instance Semigroupal (->) Either (,) (,) Either where combine :: (Either x y, Either x' y') -> Either (Either x x') (y, y') combine = \case (Left x, Left _) -> Left $ Left x (Left x, Right _) -> Left $ Left x (Right _, Left x') -> Left $ Right x' (Right y, Right y') -> Right (y, y') instance Semigroupal (->) These (,) (,) Either where combine :: (Either x y, Either x' y') -> Either (These x x') (y, y') combine = \case (Left x, Left x') -> Left $ These x x' (Left x, Right _) -> Left $ This x (Right _, Left x') -> Left $ That x' (Right y, Right y') -> Right (y, y') instance Semigroupal (->) (,) (,) (,) (->) where combine :: (x -> y, x' -> y') -> (x, x') -> (y, y') combine = uncurry bimap instance Semigroupal (->) Either Either (,) (->) where combine :: (x -> y, x' -> y') -> Either x x' -> Either y y' combine fs = either (Left . fst fs) (Right . snd fs) instance Applicative f => Semigroupal (->) (,) (,) (,) (Joker f) where combine :: (Joker f x y, Joker f x' y') -> Joker f (x, x') (y, y') combine = uncurry $ biliftA2 (,) (,) instance Alternative f => Semigroupal (->) Either Either (,) (Joker f) where combine :: (Joker f x y, Joker f x' y') -> Joker f (Either x x') (Either y y') combine = uncurry $ biliftA2 (\_ x' -> Right x') (\_ y' -> Right y') instance Functor f => Semigroupal (->) Either Either Either (Joker f) where combine :: Either (Joker f x y) (Joker f x' y') -> Joker f (Either x x') (Either y y') combine = either (Joker . fmap Left . runJoker) (Joker . fmap Right . runJoker) instance Applicative f => Semigroupal (->) (,) (,) (,) (Clown f) where combine :: (Clown f x y, Clown f x' y') -> Clown f (x, x') (y, y') combine = uncurry $ biliftA2 (,) (,) instance Alternative f => Semigroupal (->) Either Either (,) (Clown f) where combine :: (Clown f x y, Clown f x' y') -> Clown f (Either x x') (Either y y') combine = uncurry $ biliftA2 (\_ x' -> Right x') (\_ y' -> Right y') instance Applicative f => Semigroupal (->) (,) (,) (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (x, x') (y, y') combine (Star fxy, Star fxy') = Star $ \(x, x') -> liftA2 (,) (fxy x) (fxy' x') instance Functor f => Semigroupal (->) Either Either (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (Either x x') (Either y y') combine (Star fxy, Star fxy') = Star $ either (fmap Left . fxy) (fmap Right . fxy') instance Applicative f => Semigroupal (->) These These (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (These x x') (These y y') combine (Star fxy, Star fxy') = Star $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) These These These (Star f) where combine :: Applicative f => These (Star f x y) (Star f x' y') -> Star f (These x x') (These y y') combine = \case This (Star fxy) -> Star $ these (fmap This . fxy) (const empty) (\x _ -> This <$> fxy x) That (Star fxy') -> Star $ these (const empty) (fmap That . fxy') (\_ x' -> That <$> fxy' x') These (Star fxy) (Star fxy') -> Star $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) Either Either Either (Star f) where combine :: Either (Star f x y) (Star f x' y') -> Star f (Either x x') (Either y y') combine = \case Left (Star fxy) -> Star $ either (fmap Left . fxy) (const empty) Right (Star fxy') -> Star $ either (const empty) (fmap Right . fxy') instance Alternative f => Semigroupal (->) (,) Either (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (x, x') (Either y y') combine (Star f, Star g) = Star $ \(x, x') -> (Left <$> f x) <|> (Right <$> g x') instance Applicative f => Semigroupal (->) (,) (,) (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (x, x') (y, y') combine (Kleisli fxy, Kleisli fxy') = Kleisli $ \(x, x') -> liftA2 (,) (fxy x) (fxy' x') instance Functor f => Semigroupal (->) Either Either (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (Either x x') (Either y y') combine (Kleisli fxy, Kleisli fxy') = Kleisli $ either (fmap Left . fxy) (fmap Right . fxy') instance Applicative f => Semigroupal (->) These These (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (These x x') (These y y') combine (Kleisli fxy, Kleisli fxy') = Kleisli $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) These These These (Kleisli f) where combine :: Applicative f => These (Kleisli f x y) (Kleisli f x' y') -> Kleisli f (These x x') (These y y') combine = \case This (Kleisli fxy) -> Kleisli $ these (fmap This . fxy) (const empty) (\x _ -> This <$> fxy x) That (Kleisli fxy') -> Kleisli $ these (const empty) (fmap That . fxy') (\_ x' -> That <$> fxy' x') These (Kleisli fxy) (Kleisli fxy') -> Kleisli $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) Either Either Either (Kleisli f) where combine :: Either (Kleisli f x y) (Kleisli f x' y') -> Kleisli f (Either x x') (Either y y') combine = \case Left (Kleisli fxy) -> Kleisli $ either (fmap Left . fxy) (const empty) Right (Kleisli fxy') -> Kleisli $ either (const empty) (fmap Right . fxy') instance Alternative f => Semigroupal (->) (,) Either (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (x, x') (Either y y') combine (Kleisli f, Kleisli g) = Kleisli $ \(x, x') -> (Left <$> f x) <|> (Right <$> g x') instance Alternative f => Semigroupal (->) (,) (,) (,) (Forget (f r)) where combine :: (Forget (f r) x y, Forget (f r) x' y') -> Forget (f r) (x, x') (y, y') combine (Forget f, Forget g) = Forget $ \(x, x') -> f x <|> g x' instance Semigroupal (->) Either Either (,) (Forget (f r)) where combine :: (Forget (f r) x y, Forget (f r) x' y') -> Forget (f r) (Either x x') (Either y y') combine (Forget f, Forget g) = Forget $ either f g instance Alternative f => Semigroupal (->) Either Either Either (Forget (f r)) where combine :: Either (Forget (f r) x y) (Forget (f r) x' y') -> Forget (f r) (Either x x') (Either y y') combine = \case Left (Forget f) -> Forget $ either f (const empty) Right (Forget g) -> Forget $ either (const empty) g instance Alternative f => Semigroupal (->) (,) Either (,) (Forget (f r)) where combine :: (Forget (f r) x y, Forget (f r) x' y') -> Forget (f r) (x, x') (Either y y') combine (Forget f, Forget g) = Forget $ \(x, x') -> f x <|> g x' -------------------------------------------------------------------------------- | Given monoidal categories \((\mathcal{C } , \otimes , I_{\mathcal{C}})\ ) and \((\mathcal{D } , \bullet , I_{\mathcal{D}})\ ) . A bifunctor \(F : \mathcal{C_1 } \times \mathcal{C_2 } \to \mathcal{D}\ ) is ' Unital ' if it supports a morphism -- \(\phi : I_{\mathcal{D}} \to F\ I_{\mathcal{C_1}}\ I_{\mathcal{C_2}}\), which we call 'introduce'. class Unital cat i1 i2 io f where -- | @introduce@ maps from the identity in \(\mathcal{C_1} \times \mathcal{C_2}\) to the identity in \(\mathcal{D}\ ) . -- -- ==== __Examples__ -- > > > introduce > ) @ ( ) @ ( ) @ ( ) @ ( , ) ( ) -- ((),()) -- > > > : t introduce > ) @Void @ ( ) @ ( ) introduce > ) @Void @ ( ) @ ( ) : : ( ) - > Either Void ( ) -- > > > introduce > ) @Void @ ( ) @ ( ) ( ) -- Right () introduce :: cat io (f i1 i2) instance (Profunctor p, Category p) => Unital (->) () () () (StrongCategory p) where introduce :: () -> StrongCategory p () () introduce () = StrongCategory id instance Unital (->) () () () (,) where introduce :: () -> ((), ()) introduce = split instance Unital (->) Void Void Void (,) where introduce :: Void -> (Void, Void) introduce = spawn instance Unital (->) Void Void Void Either where introduce :: Void -> Either Void Void introduce = bwd unitr instance Unital (->) Void () () Either where introduce :: () -> Either Void () introduce = Right instance Unital (->) () () () (->) where introduce :: () -> () -> () introduce () () = () instance Unital (->) Void Void Void (->) where introduce :: Void -> Void -> Void introduce = absurd instance (Unital (->) Void Void () (->)) where introduce :: () -> Void -> Void introduce () = absurd instance Applicative f => Unital (->) () () () (Joker f) where introduce :: () -> Joker f () () introduce = Joker . pure instance Alternative f => Unital (->) Void Void () (Joker f) where introduce :: () -> Joker f Void Void introduce () = Joker empty instance Unital (->) Void Void Void (Joker f) where introduce :: Void -> Joker f Void Void introduce = absurd instance Applicative f => Unital (->) () () () (Star f) where introduce :: () -> Star f () () introduce () = Star pure instance Unital (->) Void Void () (Star f) where introduce :: () -> Star f Void Void introduce () = Star absurd instance Alternative f => Unital (->) Void Void Void (Star f) where introduce :: Void -> Star f Void Void introduce = absurd instance Alternative f => Unital (->) () Void () (Star f) where introduce :: () -> Star f () Void introduce () = Star $ const empty instance Applicative f => Unital (->) () () () (Kleisli f) where introduce :: () -> Kleisli f () () introduce () = Kleisli pure instance Unital (->) Void Void () (Kleisli f) where introduce :: () -> Kleisli f Void Void introduce () = Kleisli absurd instance Alternative f => Unital (->) Void Void Void (Kleisli f) where introduce :: Void -> Kleisli f Void Void introduce = absurd instance Alternative f => Unital (->) () Void () (Kleisli f) where introduce :: () -> Kleisli f () Void introduce () = Kleisli $ const empty -------------------------------------------------------------------------------- -- Monoidal | Given monoidal categories \((\mathcal{C } , \otimes , I_{\mathcal{C}})\ ) and \((\mathcal{D } , \bullet , I_{\mathcal{D}})\ ) . A bifunctor \(F : \mathcal{C_1 } \times \mathcal{C_2 } \to \mathcal{D}\ ) is ' Monoidal ' if it maps between \(\mathcal{C_1 } \times \mathcal{C_2}\ ) and \(\mathcal{D}\ ) while preserving their monoidal structure . Eg . , a homomorphism of monoidal categories . -- See for more details . -- -- === Laws -- -- __Right Unitality:__ -- -- \[ -- \require{AMScd} -- \begin{CD} F A B \bullet I_{\mathcal{D } } @>{1 \bullet } > > F A B \bullet F I_{\mathcal{C_{1 } } } I_{\mathcal{C_{2}}}\\ @VV{\rho_{\mathcal{D}}}V @VV{\phi AB , I_{\mathcal{C_{1}}}I_{\mathcal{C_{2}}}}V \\ F A B @<<{F \rho_{\mathcal{C_{1 } } } \rho_{\mathcal{C_{2 } } } } < F ( A \otimes } } } ) ( B \otimes I_{\mathcal{C_{2 } } } ) -- \end{CD} -- \] -- -- @ -- 'combine' 'Control.Category..' 'Control.Category.Tensor.grmap' 'introduce' ≡ 'bwd' 'unitr' 'Control.Category..' 'fwd' 'unitr' -- @ -- -- __ Left Unitality__: -- -- \[ -- \begin{CD} I_{\mathcal{D } } \bullet F A B @>{\phi \bullet 1 } > > F I_{\mathcal{C_{1 } } } I_{\mathcal{C_{2 } } } \bullet F A B\\ -- @VV{\lambda_{\mathcal{D}}}V @VV{I_{\mathcal{C_{1}}}I_{\mathcal{C_{2}}},\phi AB}V \\ F A B @<<{F \lambda_{\mathcal{C_{1 } } } \lambda_{\mathcal{C_{2 } } } } < F ( I_{\mathcal{C_{1 } } } \otimes A ) ( I_{\mathcal{C_{2 } } } \otimes B ) -- \end{CD} -- \] -- -- @ -- 'combine' 'Control.Category..' 'Control.Category.Tensor.glmap' 'introduce' ≡ 'fmap' ('bwd' 'unitl') 'Control.Category..' 'fwd' 'unitl' -- @ class ( Tensor cat t1 i1, Tensor cat t2 i2, Tensor cat to io, Semigroupal cat t1 t2 to f, Unital cat i1 i2 io f ) => Monoidal cat t1 i1 t2 i2 to io f instance (Strong p, Semigroupoid p, Category p) => Monoidal (->) (,) () (,) () (,) () (StrongCategory p) instance Monoidal (->) (,) () (,) () (,) () (,) instance Monoidal (->) Either Void Either Void Either Void (,) instance Monoidal (->) Either Void Either Void Either Void Either instance Monoidal (->) Either Void (,) () (,) () Either instance Monoidal (->) These Void (,) () (,) () Either instance Monoidal (->) (,) () (,) () (,) () (->) instance Monoidal (->) Either Void Either Void (,) () (->) instance Applicative f => Monoidal (->) (,) () (,) () (,) () (Joker f) instance Alternative f => Monoidal (->) Either Void Either Void (,) () (Joker f) instance Functor f => Monoidal (->) Either Void Either Void Either Void (Joker f) instance Applicative f => Monoidal (->) (,) () (,) () (,) () (Star f) instance Functor f => Monoidal (->) Either Void Either Void (,) () (Star f) instance Applicative f => Monoidal (->) These Void These Void (,) () (Star f) instance Alternative f => Monoidal (->) Either Void Either Void Either Void (Star f) instance Alternative f => Monoidal (->) These Void These Void These Void (Star f) instance Alternative f => Monoidal (->) (,) () Either Void (,) () (Star f) instance Applicative f => Monoidal (->) (,) () (,) () (,) () (Kleisli f) instance Functor f => Monoidal (->) Either Void Either Void (,) () (Kleisli f) instance Applicative f => Monoidal (->) These Void These Void (,) () (Kleisli f) instance Alternative f => Monoidal (->) Either Void Either Void Either Void (Kleisli f) instance Alternative f => Monoidal (->) These Void These Void These Void (Kleisli f) instance Alternative f => Monoidal (->) (,) () Either Void (,) () (Kleisli f) newtype StrongCategory p a b = StrongCategory (p a b) deriving (Functor, Applicative, Monad, Profunctor, Category) instance Semigroupoid p => Semigroupoid (StrongCategory p) where o :: StrongCategory p b c -> StrongCategory p a b -> StrongCategory p a c o (StrongCategory f) (StrongCategory g) = StrongCategory (f `o` g) instance (Strong p, Semigroupoid p) => Semigroupal (->) (,) (,) (,) (StrongCategory p) where combine :: (StrongCategory p x y, StrongCategory p x' y') -> StrongCategory p (x, x') (y, y') combine (StrongCategory pxy, StrongCategory pxy') = StrongCategory $ first' pxy `o` second' pxy'
null
https://raw.githubusercontent.com/solomon-b/monoidal-functors/4caa75b76bb9b0cf1d09f33f21becc400c1b45bb/src/Data/Bifunctor/Monoidal.hs
haskell
* Semigroupal * Monoidal ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ === Laws __Associativity:__ \[ \require{AMScd} \begin{CD} (F A B \bullet F C D) \bullet F X Y @>>{\alpha_{\mathcal{D}}}> F A B \bullet (F C D \bullet F X Y) \\ @VV{\phi_{AB,CD} \bullet 1}V @VV{1 \bullet \phi_{CD,FY}}V \\ F (A \otimes C) (B \otimes D) \bullet F X Y @. F A B \bullet (F (C \otimes X) (D \otimes Y) \\ \end{CD} \] @ @ ==== __Examples__ ((True,()),("Hello","World")) ("True",True) NOTE: This version could be used for a more general abstraction of products in a category: combine = let fwd' = fwd assoc ------------------------------------------------------------------------------ \(\phi : I_{\mathcal{D}} \to F\ I_{\mathcal{C_1}}\ I_{\mathcal{C_2}}\), which we call 'introduce'. | @introduce@ maps from the identity in \(\mathcal{C_1} \times \mathcal{C_2}\) to the ==== __Examples__ ((),()) Right () ------------------------------------------------------------------------------ Monoidal === Laws __Right Unitality:__ \[ \require{AMScd} \begin{CD} \end{CD} \] @ 'combine' 'Control.Category..' 'Control.Category.Tensor.grmap' 'introduce' ≡ 'bwd' 'unitr' 'Control.Category..' 'fwd' 'unitr' @ __ Left Unitality__: \[ \begin{CD} @VV{\lambda_{\mathcal{D}}}V @VV{I_{\mathcal{C_{1}}}I_{\mathcal{C_{2}}},\phi AB}V \\ \end{CD} \] @ 'combine' 'Control.Category..' 'Control.Category.Tensor.glmap' 'introduce' ≡ 'fmap' ('bwd' 'unitl') 'Control.Category..' 'fwd' 'unitl' @
module Data.Bifunctor.Monoidal Semigroupal (..), * Unital Unital (..), Monoidal, ) where import Control.Applicative (Alternative (..), Applicative (..), pure, (<$>)) import Control.Arrow (Kleisli (..)) import Control.Category (Category (..)) import Control.Category.Cartesian (Cocartesian (..), Semicartesian (..)) import Control.Category.Tensor (Associative, Iso (..), Tensor (..)) import Control.Monad (Functor (..), Monad) import Data.Biapplicative (Biapplicative (..), Bifunctor (..)) import Data.Bifunctor.Clown (Clown) import Data.Bifunctor.Joker (Joker (..)) import Data.Either (Either, either) import Data.Function (const, ($)) import Data.Profunctor (Forget (..), Profunctor (..), Star (..), Strong (..)) import Data.Semigroupoid (Semigroupoid (..)) import Data.These (These (..), these) import Data.Tuple (fst, snd, uncurry) import Data.Void (Void, absurd) import Prelude (Either (..)) | Given monoidal categories \((\mathcal{C } , \otimes , I_{\mathcal{C}})\ ) and \((\mathcal{D } , \bullet , I_{\mathcal{D}})\ ) . A bifunctor \(F : \mathcal{C_1 } \times \mathcal{C_2 } \to \mathcal{D}\ ) is ' Semigroupal ' if it supports a natural transformation \(\phi_{AB , CD } : F\ A\ B \bullet F\ C\ D \to F\ ( A \otimes ( B \otimes D)\ ) , which we call ' combine ' . @VV{\phi_{(A \otimes C)(B \otimes D),XY}}V @VV{\phi_{AB,(C \otimes X)(D \otimes Y)}}V \\ F ( ( A \otimes C ) \otimes X ) ( ( B \otimes D ) \otimes Y ) @>>{F \alpha_{\mathcal{C_1 } } } \alpha_{\mathcal{C_2 } } > F ( A \otimes ( C \otimes X ) ) ( B \otimes ( D \otimes Y ) ) \\ ' combine ' ' Control . Category .. ' ' Control.Category.Tensor.grmap ' ' combine ' ' Control . Category .. ' ' bwd ' ' Control.Category.Tensor.assoc ' ≡ ' fmap ' ( ' bwd ' ' Control.Category.Tensor.assoc ' ) ' Control . Category .. ' ' combine ' ' Control . Category .. ' ' Control.Category.Tensor.glmap ' ' combine ' class (Associative cat t1, Associative cat t2, Associative cat to) => Semigroupal cat t1 t2 to f where | A natural transformation \(\phi_{AB , CD } : F\ A\ B \bullet F\ C\ D \to F\ ( A \otimes ( B \otimes D)\ ) . > > > : t combine > ) @ ( , ) @ ( , ) @ ( , ) @ ( , ) combine @(- > ) @ ( , ) @ ( , ) @ ( , ) @ ( , ) : : ( ( x , y ) , ( x ' , y ' ) ) - > ( ( x , x ' ) , ( y , y ' ) ) > > > combine @(- > ) @ ( , ) @ ( , ) @ ( , ) @ ( , ) ( ( True , " Hello " ) , ( ( ) , " World " ) ) > > > combine @(- > ) @ ( , ) @ ( , ) @ ( , ) > ) ( show , ( > 10 ) ) ( True , 11 ) combine :: cat (to (f x y) (f x' y')) (f (t1 x x') (t2 y y')) instance Profunctor p => Semigroupal (->) (,) Either Either p where combine :: Either (p x y) (p x' y') -> p (x, x') (Either y y') combine = either (dimap fst Left) (dimap snd Right) instance Semigroupal (->) (,) (,) (,) (,) where combine :: ((x, y), (x', y')) -> ((x, x'), (y, y')) combine ((x, y), (x', y')) = ((x, x'), (y, y')) bwd ' = bwd assoc in second swap . swap . fwd ' . swap . first ( bwd ' . first swap ) . fwd ' instance Semigroupal (->) Either Either Either (,) where combine :: Either (x, y) (x', y') -> (Either x x', Either y y') combine = either (bimap Left Left) (bimap Right Right) instance Semigroupal (->) Either Either Either Either where combine :: Either (Either x y) (Either x' y') -> Either (Either x x') (Either y y') combine = either (bimap Left Left) (bimap Right Right) instance Semigroupal (->) Either (,) (,) Either where combine :: (Either x y, Either x' y') -> Either (Either x x') (y, y') combine = \case (Left x, Left _) -> Left $ Left x (Left x, Right _) -> Left $ Left x (Right _, Left x') -> Left $ Right x' (Right y, Right y') -> Right (y, y') instance Semigroupal (->) These (,) (,) Either where combine :: (Either x y, Either x' y') -> Either (These x x') (y, y') combine = \case (Left x, Left x') -> Left $ These x x' (Left x, Right _) -> Left $ This x (Right _, Left x') -> Left $ That x' (Right y, Right y') -> Right (y, y') instance Semigroupal (->) (,) (,) (,) (->) where combine :: (x -> y, x' -> y') -> (x, x') -> (y, y') combine = uncurry bimap instance Semigroupal (->) Either Either (,) (->) where combine :: (x -> y, x' -> y') -> Either x x' -> Either y y' combine fs = either (Left . fst fs) (Right . snd fs) instance Applicative f => Semigroupal (->) (,) (,) (,) (Joker f) where combine :: (Joker f x y, Joker f x' y') -> Joker f (x, x') (y, y') combine = uncurry $ biliftA2 (,) (,) instance Alternative f => Semigroupal (->) Either Either (,) (Joker f) where combine :: (Joker f x y, Joker f x' y') -> Joker f (Either x x') (Either y y') combine = uncurry $ biliftA2 (\_ x' -> Right x') (\_ y' -> Right y') instance Functor f => Semigroupal (->) Either Either Either (Joker f) where combine :: Either (Joker f x y) (Joker f x' y') -> Joker f (Either x x') (Either y y') combine = either (Joker . fmap Left . runJoker) (Joker . fmap Right . runJoker) instance Applicative f => Semigroupal (->) (,) (,) (,) (Clown f) where combine :: (Clown f x y, Clown f x' y') -> Clown f (x, x') (y, y') combine = uncurry $ biliftA2 (,) (,) instance Alternative f => Semigroupal (->) Either Either (,) (Clown f) where combine :: (Clown f x y, Clown f x' y') -> Clown f (Either x x') (Either y y') combine = uncurry $ biliftA2 (\_ x' -> Right x') (\_ y' -> Right y') instance Applicative f => Semigroupal (->) (,) (,) (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (x, x') (y, y') combine (Star fxy, Star fxy') = Star $ \(x, x') -> liftA2 (,) (fxy x) (fxy' x') instance Functor f => Semigroupal (->) Either Either (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (Either x x') (Either y y') combine (Star fxy, Star fxy') = Star $ either (fmap Left . fxy) (fmap Right . fxy') instance Applicative f => Semigroupal (->) These These (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (These x x') (These y y') combine (Star fxy, Star fxy') = Star $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) These These These (Star f) where combine :: Applicative f => These (Star f x y) (Star f x' y') -> Star f (These x x') (These y y') combine = \case This (Star fxy) -> Star $ these (fmap This . fxy) (const empty) (\x _ -> This <$> fxy x) That (Star fxy') -> Star $ these (const empty) (fmap That . fxy') (\_ x' -> That <$> fxy' x') These (Star fxy) (Star fxy') -> Star $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) Either Either Either (Star f) where combine :: Either (Star f x y) (Star f x' y') -> Star f (Either x x') (Either y y') combine = \case Left (Star fxy) -> Star $ either (fmap Left . fxy) (const empty) Right (Star fxy') -> Star $ either (const empty) (fmap Right . fxy') instance Alternative f => Semigroupal (->) (,) Either (,) (Star f) where combine :: (Star f x y, Star f x' y') -> Star f (x, x') (Either y y') combine (Star f, Star g) = Star $ \(x, x') -> (Left <$> f x) <|> (Right <$> g x') instance Applicative f => Semigroupal (->) (,) (,) (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (x, x') (y, y') combine (Kleisli fxy, Kleisli fxy') = Kleisli $ \(x, x') -> liftA2 (,) (fxy x) (fxy' x') instance Functor f => Semigroupal (->) Either Either (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (Either x x') (Either y y') combine (Kleisli fxy, Kleisli fxy') = Kleisli $ either (fmap Left . fxy) (fmap Right . fxy') instance Applicative f => Semigroupal (->) These These (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (These x x') (These y y') combine (Kleisli fxy, Kleisli fxy') = Kleisli $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) These These These (Kleisli f) where combine :: Applicative f => These (Kleisli f x y) (Kleisli f x' y') -> Kleisli f (These x x') (These y y') combine = \case This (Kleisli fxy) -> Kleisli $ these (fmap This . fxy) (const empty) (\x _ -> This <$> fxy x) That (Kleisli fxy') -> Kleisli $ these (const empty) (fmap That . fxy') (\_ x' -> That <$> fxy' x') These (Kleisli fxy) (Kleisli fxy') -> Kleisli $ these (fmap This . fxy) (fmap That . fxy') (\x x' -> liftA2 These (fxy x) (fxy' x')) instance Alternative f => Semigroupal (->) Either Either Either (Kleisli f) where combine :: Either (Kleisli f x y) (Kleisli f x' y') -> Kleisli f (Either x x') (Either y y') combine = \case Left (Kleisli fxy) -> Kleisli $ either (fmap Left . fxy) (const empty) Right (Kleisli fxy') -> Kleisli $ either (const empty) (fmap Right . fxy') instance Alternative f => Semigroupal (->) (,) Either (,) (Kleisli f) where combine :: (Kleisli f x y, Kleisli f x' y') -> Kleisli f (x, x') (Either y y') combine (Kleisli f, Kleisli g) = Kleisli $ \(x, x') -> (Left <$> f x) <|> (Right <$> g x') instance Alternative f => Semigroupal (->) (,) (,) (,) (Forget (f r)) where combine :: (Forget (f r) x y, Forget (f r) x' y') -> Forget (f r) (x, x') (y, y') combine (Forget f, Forget g) = Forget $ \(x, x') -> f x <|> g x' instance Semigroupal (->) Either Either (,) (Forget (f r)) where combine :: (Forget (f r) x y, Forget (f r) x' y') -> Forget (f r) (Either x x') (Either y y') combine (Forget f, Forget g) = Forget $ either f g instance Alternative f => Semigroupal (->) Either Either Either (Forget (f r)) where combine :: Either (Forget (f r) x y) (Forget (f r) x' y') -> Forget (f r) (Either x x') (Either y y') combine = \case Left (Forget f) -> Forget $ either f (const empty) Right (Forget g) -> Forget $ either (const empty) g instance Alternative f => Semigroupal (->) (,) Either (,) (Forget (f r)) where combine :: (Forget (f r) x y, Forget (f r) x' y') -> Forget (f r) (x, x') (Either y y') combine (Forget f, Forget g) = Forget $ \(x, x') -> f x <|> g x' | Given monoidal categories \((\mathcal{C } , \otimes , I_{\mathcal{C}})\ ) and \((\mathcal{D } , \bullet , I_{\mathcal{D}})\ ) . A bifunctor \(F : \mathcal{C_1 } \times \mathcal{C_2 } \to \mathcal{D}\ ) is ' Unital ' if it supports a morphism class Unital cat i1 i2 io f where identity in \(\mathcal{D}\ ) . > > > introduce > ) @ ( ) @ ( ) @ ( ) @ ( , ) ( ) > > > : t introduce > ) @Void @ ( ) @ ( ) introduce > ) @Void @ ( ) @ ( ) : : ( ) - > Either Void ( ) > > > introduce > ) @Void @ ( ) @ ( ) ( ) introduce :: cat io (f i1 i2) instance (Profunctor p, Category p) => Unital (->) () () () (StrongCategory p) where introduce :: () -> StrongCategory p () () introduce () = StrongCategory id instance Unital (->) () () () (,) where introduce :: () -> ((), ()) introduce = split instance Unital (->) Void Void Void (,) where introduce :: Void -> (Void, Void) introduce = spawn instance Unital (->) Void Void Void Either where introduce :: Void -> Either Void Void introduce = bwd unitr instance Unital (->) Void () () Either where introduce :: () -> Either Void () introduce = Right instance Unital (->) () () () (->) where introduce :: () -> () -> () introduce () () = () instance Unital (->) Void Void Void (->) where introduce :: Void -> Void -> Void introduce = absurd instance (Unital (->) Void Void () (->)) where introduce :: () -> Void -> Void introduce () = absurd instance Applicative f => Unital (->) () () () (Joker f) where introduce :: () -> Joker f () () introduce = Joker . pure instance Alternative f => Unital (->) Void Void () (Joker f) where introduce :: () -> Joker f Void Void introduce () = Joker empty instance Unital (->) Void Void Void (Joker f) where introduce :: Void -> Joker f Void Void introduce = absurd instance Applicative f => Unital (->) () () () (Star f) where introduce :: () -> Star f () () introduce () = Star pure instance Unital (->) Void Void () (Star f) where introduce :: () -> Star f Void Void introduce () = Star absurd instance Alternative f => Unital (->) Void Void Void (Star f) where introduce :: Void -> Star f Void Void introduce = absurd instance Alternative f => Unital (->) () Void () (Star f) where introduce :: () -> Star f () Void introduce () = Star $ const empty instance Applicative f => Unital (->) () () () (Kleisli f) where introduce :: () -> Kleisli f () () introduce () = Kleisli pure instance Unital (->) Void Void () (Kleisli f) where introduce :: () -> Kleisli f Void Void introduce () = Kleisli absurd instance Alternative f => Unital (->) Void Void Void (Kleisli f) where introduce :: Void -> Kleisli f Void Void introduce = absurd instance Alternative f => Unital (->) () Void () (Kleisli f) where introduce :: () -> Kleisli f () Void introduce () = Kleisli $ const empty | Given monoidal categories \((\mathcal{C } , \otimes , I_{\mathcal{C}})\ ) and \((\mathcal{D } , \bullet , I_{\mathcal{D}})\ ) . A bifunctor \(F : \mathcal{C_1 } \times \mathcal{C_2 } \to \mathcal{D}\ ) is ' Monoidal ' if it maps between \(\mathcal{C_1 } \times \mathcal{C_2}\ ) and \(\mathcal{D}\ ) while preserving their monoidal structure . Eg . , a homomorphism of monoidal categories . See for more details . F A B \bullet I_{\mathcal{D } } @>{1 \bullet } > > F A B \bullet F I_{\mathcal{C_{1 } } } I_{\mathcal{C_{2}}}\\ @VV{\rho_{\mathcal{D}}}V @VV{\phi AB , I_{\mathcal{C_{1}}}I_{\mathcal{C_{2}}}}V \\ F A B @<<{F \rho_{\mathcal{C_{1 } } } \rho_{\mathcal{C_{2 } } } } < F ( A \otimes } } } ) ( B \otimes I_{\mathcal{C_{2 } } } ) I_{\mathcal{D } } \bullet F A B @>{\phi \bullet 1 } > > F I_{\mathcal{C_{1 } } } I_{\mathcal{C_{2 } } } \bullet F A B\\ F A B @<<{F \lambda_{\mathcal{C_{1 } } } \lambda_{\mathcal{C_{2 } } } } < F ( I_{\mathcal{C_{1 } } } \otimes A ) ( I_{\mathcal{C_{2 } } } \otimes B ) class ( Tensor cat t1 i1, Tensor cat t2 i2, Tensor cat to io, Semigroupal cat t1 t2 to f, Unital cat i1 i2 io f ) => Monoidal cat t1 i1 t2 i2 to io f instance (Strong p, Semigroupoid p, Category p) => Monoidal (->) (,) () (,) () (,) () (StrongCategory p) instance Monoidal (->) (,) () (,) () (,) () (,) instance Monoidal (->) Either Void Either Void Either Void (,) instance Monoidal (->) Either Void Either Void Either Void Either instance Monoidal (->) Either Void (,) () (,) () Either instance Monoidal (->) These Void (,) () (,) () Either instance Monoidal (->) (,) () (,) () (,) () (->) instance Monoidal (->) Either Void Either Void (,) () (->) instance Applicative f => Monoidal (->) (,) () (,) () (,) () (Joker f) instance Alternative f => Monoidal (->) Either Void Either Void (,) () (Joker f) instance Functor f => Monoidal (->) Either Void Either Void Either Void (Joker f) instance Applicative f => Monoidal (->) (,) () (,) () (,) () (Star f) instance Functor f => Monoidal (->) Either Void Either Void (,) () (Star f) instance Applicative f => Monoidal (->) These Void These Void (,) () (Star f) instance Alternative f => Monoidal (->) Either Void Either Void Either Void (Star f) instance Alternative f => Monoidal (->) These Void These Void These Void (Star f) instance Alternative f => Monoidal (->) (,) () Either Void (,) () (Star f) instance Applicative f => Monoidal (->) (,) () (,) () (,) () (Kleisli f) instance Functor f => Monoidal (->) Either Void Either Void (,) () (Kleisli f) instance Applicative f => Monoidal (->) These Void These Void (,) () (Kleisli f) instance Alternative f => Monoidal (->) Either Void Either Void Either Void (Kleisli f) instance Alternative f => Monoidal (->) These Void These Void These Void (Kleisli f) instance Alternative f => Monoidal (->) (,) () Either Void (,) () (Kleisli f) newtype StrongCategory p a b = StrongCategory (p a b) deriving (Functor, Applicative, Monad, Profunctor, Category) instance Semigroupoid p => Semigroupoid (StrongCategory p) where o :: StrongCategory p b c -> StrongCategory p a b -> StrongCategory p a c o (StrongCategory f) (StrongCategory g) = StrongCategory (f `o` g) instance (Strong p, Semigroupoid p) => Semigroupal (->) (,) (,) (,) (StrongCategory p) where combine :: (StrongCategory p x y, StrongCategory p x' y') -> StrongCategory p (x, x') (y, y') combine (StrongCategory pxy, StrongCategory pxy') = StrongCategory $ first' pxy `o` second' pxy'
aa1b2fe135d37db251f920cf36488dd6266440086839b480cc40933ca4cdd83f
malyn/mondrian
macros.clj
(ns mondrian.macros (use [dommy.macros :only [sel1]])) (defmacro defmondrian "Defines a mondrian animation function given the initial state and a pair of functions that drive the the animation. The resulting function takes a reference to a mondrian DOM element, which must include a canvas element upon which the animation will be rendered." [fname init-state update-pipeline render-stack] `(def ~(with-meta fname {:export true}) (fn [drawing#] (let [canvas# (sel1 drawing# :canvas) ctx# (monet.canvas/get-context canvas# "2d") [w# h#] (mondrian.ui/setup-canvas canvas# ctx# 1.0) fixed-state# {:drawing drawing# :ctx ctx# :w w# :h h#}] (anim/start ~init-state #(-> (merge % fixed-state#) ~update-pipeline) #(~render-stack %) #(-> ctx# (monet.canvas/fill-style "red") (monet.canvas/font-style "sans-serif") (monet.canvas/text {:text % :x 0 :y 20})))))))
null
https://raw.githubusercontent.com/malyn/mondrian/4ba922d7c4190fbfef92348dfd1c9b8873c27a13/src/clj/mondrian/macros.clj
clojure
(ns mondrian.macros (use [dommy.macros :only [sel1]])) (defmacro defmondrian "Defines a mondrian animation function given the initial state and a pair of functions that drive the the animation. The resulting function takes a reference to a mondrian DOM element, which must include a canvas element upon which the animation will be rendered." [fname init-state update-pipeline render-stack] `(def ~(with-meta fname {:export true}) (fn [drawing#] (let [canvas# (sel1 drawing# :canvas) ctx# (monet.canvas/get-context canvas# "2d") [w# h#] (mondrian.ui/setup-canvas canvas# ctx# 1.0) fixed-state# {:drawing drawing# :ctx ctx# :w w# :h h#}] (anim/start ~init-state #(-> (merge % fixed-state#) ~update-pipeline) #(~render-stack %) #(-> ctx# (monet.canvas/fill-style "red") (monet.canvas/font-style "sans-serif") (monet.canvas/text {:text % :x 0 :y 20})))))))
f30e89478c0de65f57608da29bc7f061df740f8a36889db15aeaa3919f94d9c8
xapi-project/message-switch
gpumon_interface_test.ml
open Idl_test_common module GenPath = struct let test_data_path = "gpu_gen" end module OldPath = struct let test_data_path = "test_data/gpumon" end module C = Gpumon_interface.RPC_API (GenTestData (GenPath) (TJsonrpc)) module T = Gpumon_interface.RPC_API (TestOldRpcs (OldPath) (TJsonrpc)) let tests = !C.implementation @ !T.implementation
null
https://raw.githubusercontent.com/xapi-project/message-switch/1d0d1aa45c01eba144ac2826d0d88bb663e33101/xapi-idl/lib_test/gpumon_interface_test.ml
ocaml
open Idl_test_common module GenPath = struct let test_data_path = "gpu_gen" end module OldPath = struct let test_data_path = "test_data/gpumon" end module C = Gpumon_interface.RPC_API (GenTestData (GenPath) (TJsonrpc)) module T = Gpumon_interface.RPC_API (TestOldRpcs (OldPath) (TJsonrpc)) let tests = !C.implementation @ !T.implementation
260376a729f73fd429ef4a628ceb5a7fabd39d4563cc4f00afcb6ef3e38e744d
jarohen/yoyo
om.cljs
(ns {{name}}.ui.app (:require [clojure.string :as s] [om.core :as om] [om.dom :as dom] [nrepl.embed :refer [connect-brepl!]])) (enable-console-print!) (connect-brepl!) (defn hello-world [] (om/component (dom/p nil "Hello world!"))) (set! (.-onload js/window) (fn [] (om/root hello-world {} {:target js/document.body}))) ;; ------------------------------------------------------------ ;; Below this line is only required for the Yo-yo welcome page, feel ;; free to just delete all of it when you want to get cracking on your ;; own project! (defn code [s] (dom/strong #js {:style #js {:font-family "'Courier New', 'monospace'"}} s)) (defn demo-component [] (om/component (dom/div #js {:className "container"} (dom/h2 #js {:style #js {:margin-top "1em"}} "Hello from Yo-yo!") (dom/h3 nil "Things to try:") (dom/ul nil (dom/li nil (dom/p nil "In your Clojure REPL, run " (code "(yoyo/reload!)") " to completely reload the webapp without restarting the JVM.")) (dom/li nil (dom/p nil "Start making your webapp!") (dom/ul nil (dom/li nil (dom/p nil "The CLJS entry point is in " (code "ui-src/{{sanitized}}/ui/app.cljs"))) (dom/li nil (dom/p nil "The Clojure system entry point is in " (code "src/{{sanitized}}/service/system.clj"))) (dom/li nil (dom/p nil "The Clojure Ring handler is in " (code "src/{{sanitized}}/service/handler.clj"))))) (dom/li nil (dom/p nil "Connect to the CLJS browser REPL") (dom/ol nil (dom/li nil "Connect to the normal server-side REPL (port 7888, by default)") (dom/li nil "Evaluate: " (code "(nrepl.embed/->brepl)")) (dom/li nil "Refresh this page") (dom/li nil "When you get a " (code "cljs.user =>") " prompt, you can test it with:" (dom/ul nil (dom/li nil (code "(+ 1 1)")) (dom/li nil (code "(js/window.alert \"Hello world!\")")) (dom/li nil (code "(set! (.-backgroundColor js/document.body.style) \"green\")")))))) (dom/li nil (dom/p nil "Any trouble, let me know - either through GitHub or on Twitter at " (dom/a #js {:href ""} "@jarohen"))) (dom/li nil (dom/p nil "Good luck!"))) (dom/div #js {:style #js {:text-align "right" :font-weight "bold"}} (dom/p nil (dom/span #js {:style #js {:font-size "1.3em"}} "James Henderson") (dom/br nil) "Twitter: " (dom/a #js {:href ""} "@jarohen") (dom/br nil) "GitHub: " (dom/a #js {:href "-henderson"} "james-henderson")))))) (set! (.-onload js/window) (fn [] (om/root demo-component {} {:target js/document.body})))
null
https://raw.githubusercontent.com/jarohen/yoyo/b579d21becd06b5330dee9f5963708db03ce1e25/templates/yoyo-webapp/src/leiningen/new/yoyo_webapp/cljs/om.cljs
clojure
------------------------------------------------------------ Below this line is only required for the Yo-yo welcome page, feel free to just delete all of it when you want to get cracking on your own project!
(ns {{name}}.ui.app (:require [clojure.string :as s] [om.core :as om] [om.dom :as dom] [nrepl.embed :refer [connect-brepl!]])) (enable-console-print!) (connect-brepl!) (defn hello-world [] (om/component (dom/p nil "Hello world!"))) (set! (.-onload js/window) (fn [] (om/root hello-world {} {:target js/document.body}))) (defn code [s] (dom/strong #js {:style #js {:font-family "'Courier New', 'monospace'"}} s)) (defn demo-component [] (om/component (dom/div #js {:className "container"} (dom/h2 #js {:style #js {:margin-top "1em"}} "Hello from Yo-yo!") (dom/h3 nil "Things to try:") (dom/ul nil (dom/li nil (dom/p nil "In your Clojure REPL, run " (code "(yoyo/reload!)") " to completely reload the webapp without restarting the JVM.")) (dom/li nil (dom/p nil "Start making your webapp!") (dom/ul nil (dom/li nil (dom/p nil "The CLJS entry point is in " (code "ui-src/{{sanitized}}/ui/app.cljs"))) (dom/li nil (dom/p nil "The Clojure system entry point is in " (code "src/{{sanitized}}/service/system.clj"))) (dom/li nil (dom/p nil "The Clojure Ring handler is in " (code "src/{{sanitized}}/service/handler.clj"))))) (dom/li nil (dom/p nil "Connect to the CLJS browser REPL") (dom/ol nil (dom/li nil "Connect to the normal server-side REPL (port 7888, by default)") (dom/li nil "Evaluate: " (code "(nrepl.embed/->brepl)")) (dom/li nil "Refresh this page") (dom/li nil "When you get a " (code "cljs.user =>") " prompt, you can test it with:" (dom/ul nil (dom/li nil (code "(+ 1 1)")) (dom/li nil (code "(js/window.alert \"Hello world!\")")) (dom/li nil (code "(set! (.-backgroundColor js/document.body.style) \"green\")")))))) (dom/li nil (dom/p nil "Any trouble, let me know - either through GitHub or on Twitter at " (dom/a #js {:href ""} "@jarohen"))) (dom/li nil (dom/p nil "Good luck!"))) (dom/div #js {:style #js {:text-align "right" :font-weight "bold"}} (dom/p nil (dom/span #js {:style #js {:font-size "1.3em"}} "James Henderson") (dom/br nil) "Twitter: " (dom/a #js {:href ""} "@jarohen") (dom/br nil) "GitHub: " (dom/a #js {:href "-henderson"} "james-henderson")))))) (set! (.-onload js/window) (fn [] (om/root demo-component {} {:target js/document.body})))
36e34a1bdfb8741dcda6f8315505d4c01d059c41cf646f36c16c8cf74c076a48
c4-project/c4f
delitmus.mli
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) (** Command for act's C/Litmus delitmusifier. *) val command : Core.Command.t (** [command] is the top-level 'act-c delitmus' command. *)
null
https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/cmd_c/src/delitmus.mli
ocaml
* Command for act's C/Litmus delitmusifier. * [command] is the top-level 'act-c delitmus' command.
This file is part of c4f . Copyright ( c ) 2018 - 2022 C4 Project c4 t itself is licensed under the MIT License . See the LICENSE file in the project root for more information . Parts of c4 t are based on code from the Herdtools7 project ( ) : see the LICENSE.herd file in the project root for more information . Copyright (c) 2018-2022 C4 Project c4t itself is licensed under the MIT License. See the LICENSE file in the project root for more information. Parts of c4t are based on code from the Herdtools7 project () : see the LICENSE.herd file in the project root for more information. *) val command : Core.Command.t
bf47e9d6d22213909ab90549a50fe50d4ecc1b20e1b272f37ebc4fac72e36294
sshine/hs-jq
Expr.hs
module Jq.Expr where import Data.Scientific (Scientific) import Data.Text (Text) The jq grammar : A derived BNF : -language-grammar.md Initially , only look at expressions and skip jq modules , function defs and imperative constructs . You know , I did n't even know that jq had support for modules until now . I 'm learning ! Note : ' as ' is only available in subsequent expressions : $ jq -n ' [ 1 as $ answer | 2 ] | $ answer ' # fails TODO : Catch this in type - checking phase . The jq grammar: A derived BNF: -language-grammar.md Initially, only look at expressions and skip jq modules, function defs and imperative constructs. You know, I didn't even know that jq had support for modules until now. I'm learning! Note: 'as' is only available in subsequent expressions: $ jq -n '[ 1 as $answer | 2 ] | $answer' # fails TODO: Catch this in type-checking phase. -} type Ident = Text type Expr = AbstractExpr Scientific data AbstractExpr n -- Function definitions = FuncDef !Ident ![Param] !Expr !Expr -- Control structures | As !Expr !Pattern | Reduce !Expr !Pattern !Expr !Expr | Foreach !Expr !Pattern !Expr !Expr !(Maybe Expr) | If ![(Expr, Expr)] !Expr | TryCatch !Expr !(Maybe Expr) | Label !Ident | Break Ident -- 'break' $ IDENT (JBOL Term) Operators | Assign !Expr !Expr -- '=' | Or !Expr !Expr -- 'or' | And !Expr !Expr -- 'and' | Alt !Expr !Expr -- '//' | AltDestruct !Expr !Expr -- '?//' | AltAssign !Expr !Expr -- '//=' | UpdateAssign !Expr !Expr -- '|=' | Pipe !Expr !Expr -- '|' | Comma !Expr !Expr -- ',' | Plus !Expr !Expr -- '+' | PlusAssign !Expr !Expr -- '+=' | Minus !Expr !Expr -- '-' | MinusAssign !Expr !Expr -- '-=' | Mult !Expr !Expr -- '*' | MultAssign !Expr !Expr -- '*=' | Div !Expr !Expr -- '/' | DivAssign !Expr !Expr -- '/=' | Mod !Expr !Expr -- '%' | ModAssign !Expr !Expr -- '%=' | Eq !Expr !Expr -- '==' | Neq !Expr !Expr -- '!=' | Lt !Expr !Expr -- '<' | Gt !Expr !Expr -- '>' | Leq !Expr !Expr -- '<=' | Geq !Expr !Expr -- '>=' -- Prefix/postfix | Optional !Expr -- suffix '?' | Neg !Expr -- prefix '-' -- Begins with '.' | Identity -- '.' | RecursiveDescent -- '..' | DotField !Ident -- '.foo' | DotStr !JqString -- '."foo"' -- Postfix [], postfix indexing with . and [] | ValueIterator !Expr -- '[]' | IndexAfter !Expr !Expr -- 'e[y]' | IndexRangeAfter !Expr !(Maybe Expr) !(Maybe Expr) -- postfix 'e[x:y]', 'e[x:]', 'e[:y]', 'e[:]' | DotFieldAfter !Expr !Ident -- suffix 'e.foo' | DotStrAfter !Expr !JqString -- suffix '."foo"' -- Other terms ' foo ' , ' foo ( ) ' , ' foo(1 ) ' , ' foo(1 ; 2 ) ' | Var Ident -- '$var' ([a-zA-Z_][a-zA-Z_0-9]*::)*[a-zA-Z_][a-zA-Z_0-9]* This is what JBOL 's grammar calls MkDictPair | List ![Expr] | Str !JqString | NanLit | InfLit | NumLit !n | BoolLit !Bool | NullLit -- Explicit parentheses | Paren !Expr | Format !Ident !(Maybe JqString) deriving (Eq, Show) data ObjKey = FieldKey !Ident | FieldExpr !Expr deriving (Eq, Show) data Param = ValueParam !Ident -- '$' ident | FilterParam !Ident -- e.g. 'def foo(f): f | f' deriving (Show, Eq) data Pattern = VarPat !Text -- '... as $var' | ArrayPat ![Pattern] -- '... as [ ... ]' | ObjPat ![(ObjKeyPat, Pattern)] -- '... as { ... }' deriving (Eq, Show) Corresponds to ' ObjPat ' in JBOL grammar data ObjKeyPat = ObjKeyVarPat !Ident -- '$' IDENT | ObjKeyIdentPat !Ident -- IDENT | ObjKeyStrPat !JqString -- "..." | ObjKeyExprPat !Expr -- XXX deriving (Eq, Show) data StrChunk = StrLit !Text | StrEsc !Char | StrInterp !Expr deriving (Eq, Show) type JqString = [StrChunk] mkStrExpr :: Text -> Expr mkStrExpr = Str . mkStrLit mkStrLit :: Text -> JqString mkStrLit = return . StrLit mkStrEscExpr :: Char -> Expr mkStrEscExpr = Str . return . StrEsc
null
https://raw.githubusercontent.com/sshine/hs-jq/157b89a34b1f72581b02302b876785d6074dffa3/src/Jq/Expr.hs
haskell
Function definitions Control structures 'break' $ IDENT (JBOL Term) '=' 'or' 'and' '//' '?//' '//=' '|=' '|' ',' '+' '+=' '-' '-=' '*' '*=' '/' '/=' '%' '%=' '==' '!=' '<' '>' '<=' '>=' Prefix/postfix suffix '?' prefix '-' Begins with '.' '.' '..' '.foo' '."foo"' Postfix [], postfix indexing with . and [] '[]' 'e[y]' postfix 'e[x:y]', 'e[x:]', 'e[:y]', 'e[:]' suffix 'e.foo' suffix '."foo"' Other terms '$var' ([a-zA-Z_][a-zA-Z_0-9]*::)*[a-zA-Z_][a-zA-Z_0-9]* Explicit parentheses '$' ident e.g. 'def foo(f): f | f' '... as $var' '... as [ ... ]' '... as { ... }' '$' IDENT IDENT "..." XXX
module Jq.Expr where import Data.Scientific (Scientific) import Data.Text (Text) The jq grammar : A derived BNF : -language-grammar.md Initially , only look at expressions and skip jq modules , function defs and imperative constructs . You know , I did n't even know that jq had support for modules until now . I 'm learning ! Note : ' as ' is only available in subsequent expressions : $ jq -n ' [ 1 as $ answer | 2 ] | $ answer ' # fails TODO : Catch this in type - checking phase . The jq grammar: A derived BNF: -language-grammar.md Initially, only look at expressions and skip jq modules, function defs and imperative constructs. You know, I didn't even know that jq had support for modules until now. I'm learning! Note: 'as' is only available in subsequent expressions: $ jq -n '[ 1 as $answer | 2 ] | $answer' # fails TODO: Catch this in type-checking phase. -} type Ident = Text type Expr = AbstractExpr Scientific data AbstractExpr n = FuncDef !Ident ![Param] !Expr !Expr | As !Expr !Pattern | Reduce !Expr !Pattern !Expr !Expr | Foreach !Expr !Pattern !Expr !Expr !(Maybe Expr) | If ![(Expr, Expr)] !Expr | TryCatch !Expr !(Maybe Expr) | Label !Ident Operators | IndexRangeAfter !Expr !(Maybe Expr) !(Maybe Expr) ' foo ' , ' foo ( ) ' , ' foo(1 ) ' , ' foo(1 ; 2 ) ' This is what JBOL 's grammar calls MkDictPair | List ![Expr] | Str !JqString | NanLit | InfLit | NumLit !n | BoolLit !Bool | NullLit | Paren !Expr | Format !Ident !(Maybe JqString) deriving (Eq, Show) data ObjKey = FieldKey !Ident | FieldExpr !Expr deriving (Eq, Show) deriving (Show, Eq) deriving (Eq, Show) Corresponds to ' ObjPat ' in JBOL grammar deriving (Eq, Show) data StrChunk = StrLit !Text | StrEsc !Char | StrInterp !Expr deriving (Eq, Show) type JqString = [StrChunk] mkStrExpr :: Text -> Expr mkStrExpr = Str . mkStrLit mkStrLit :: Text -> JqString mkStrLit = return . StrLit mkStrEscExpr :: Char -> Expr mkStrEscExpr = Str . return . StrEsc
82ec071e3e9b00d67deff7663a892cc83170cee492c4eda7a97760e64415bc79
janestreet/memtrace_viewer_with_deps
expect_test_config.ml
module IO_run = struct type 'a t = 'a let return x = x let bind t ~f = f t end module IO_flush = struct include IO_run let to_run t = t end let flush () = () (* the runtime already flushes [stdout] *) let run f = f () let flushed () = true (* the runtime flushed [stdout] before calling this function *) let upon_unreleasable_issue = `CR
null
https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/ppx_expect/config/expect_test_config.ml
ocaml
the runtime already flushes [stdout] the runtime flushed [stdout] before calling this function
module IO_run = struct type 'a t = 'a let return x = x let bind t ~f = f t end module IO_flush = struct include IO_run let to_run t = t end let run f = f () let upon_unreleasable_issue = `CR
13226d2767ccdd42e1505158fda7057ba24e2d7ea1c6408775b58a51ac304bc3
PacktPublishing/Haskell-High-Performance-Programming
fib.hs
import Control.Parallel fib :: Int -> Int fib n | n <= 1 = 1 | n <= 28 = fib (n - 1) + fib (n - 2) | otherwise = let a = fib (n - 1) b = fib (n - 2) in a `par` b `par` a + b -- in a + b main = do let x = fib 37 y = fib 38 z = fib 39 w = fib 40 x `par` y `par` z `par` w `pseq` print (x, y, z, w) -- print (x,y,z,w)
null
https://raw.githubusercontent.com/PacktPublishing/Haskell-High-Performance-Programming/2b1bfdb8102129be41e8d79c7e9caf12100c5556/Chapter05/fib.hs
haskell
in a + b print (x,y,z,w)
import Control.Parallel fib :: Int -> Int fib n | n <= 1 = 1 | n <= 28 = fib (n - 1) + fib (n - 2) | otherwise = let a = fib (n - 1) b = fib (n - 2) in a `par` b `par` a + b main = do let x = fib 37 y = fib 38 z = fib 39 w = fib 40 x `par` y `par` z `par` w `pseq` print (x, y, z, w)
592b7fba16020bb060eda94be245ba914f10129bdd9ab8fa68b5bbeb90df3699
michaelklishin/monger
querying_test.clj
(ns monger.test.querying-test (:refer-clojure :exclude [select find sort]) (:import [com.mongodb WriteResult WriteConcern DBObject ReadPreference] org.bson.types.ObjectId java.util.Date) (:require [monger.core :as mg] [monger.collection :as mc] monger.joda-time [monger.result :as mgres] [clojure.test :refer :all] [monger.conversion :refer :all] [monger.query :refer :all] [monger.operators :refer :all] [clj-time.core :refer [date-time]])) (let [conn (mg/connect) db (mg/get-db conn "monger-test")] (defn purge-collections [f] (mc/remove db "docs") (mc/remove db "things") (mc/remove db "locations") (mc/remove db "querying_docs") (f) (mc/remove db "docs") (mc/remove db "things") (mc/remove db "locations") (mc/remove db "querying_docs")) (use-fixtures :each purge-collections) ;; ;; monger.collection/* finders ("low-level API") ;; by (deftest query-full-document-by-object-id (let [coll "querying_docs" oid (ObjectId.) doc { :_id oid :title "Introducing Monger" }] (mc/insert db coll doc) (is (= doc (mc/find-map-by-id db coll oid))) (is (= doc (mc/find-one-as-map db coll { :_id oid }))))) ;; exact match over string field (deftest query-full-document-using-exact-matching-over-string-field (let [coll "querying_docs" doc { :title "monger" :language "Clojure" :_id (ObjectId.) }] (mc/insert db coll doc) (is (= [doc] (mc/find-maps db coll { :title "monger" }))) (is (= doc (from-db-object (first (mc/find db coll { :title "monger" })) true))))) ;; exact match over string field with limit (deftest query-full-document-using-exact-matching-over-string-with-field-with-limit (let [coll "querying_docs" doc1 { :title "monger" :language "Clojure" :_id (ObjectId.) } doc2 { :title "langohr" :language "Clojure" :_id (ObjectId.) } doc3 { :title "netty" :language "Java" :_id (ObjectId.) } _ (mc/insert-batch db coll [doc1 doc2 doc3]) result (with-collection db coll (find { :title "monger" }) (fields [:title, :language, :_id]) (skip 0) (limit 1))] (is (= 1 (count result))) (is (= [doc1] result)))) (deftest query-full-document-using-exact-matching-over-string-field-with-limit-and-offset (let [coll "querying_docs" doc1 { :title "lucene" :language "Java" :_id (ObjectId.) } doc2 { :title "joda-time" :language "Java" :_id (ObjectId.) } doc3 { :title "netty" :language "Java" :_id (ObjectId.) } _ (mc/insert-batch db coll [doc1 doc2 doc3]) result (with-collection db coll (find { :language "Java" }) (skip 1) (limit 2) (sort { :title 1 }))] (is (= 2 (count result))) (is (= [doc1 doc3] result)))) (deftest query-with-sorting-on-multiple-fields (let [coll "querying_docs" doc1 { :a 1 :b 2 :c 3 :text "Whatever" :_id (ObjectId.) } doc2 { :a 1 :b 1 :c 4 :text "Blah " :_id (ObjectId.) } doc3 { :a 10 :b 3 :c 1 :text "Abc" :_id (ObjectId.) } doc4 { :a 10 :b 3 :c 3 :text "Abc" :_id (ObjectId.) } _ (mc/insert-batch db coll [doc1 doc2 doc3 doc4]) result1 (with-collection db coll (find {}) (limit 2) (fields [:a :b :c :text]) (sort (sorted-map :a 1 :b 1 :text -1))) result2 (with-collection db coll (find {}) (limit 2) (fields [:a :b :c :text]) (sort (array-map :c 1 :text -1))) result3 (with-collection db coll (find {}) (limit 2) (fields [:a :b :c :text]) (sort (array-map :c -1 :text 1)))] (is (= [doc2 doc1] result1)) (is (= [doc3 doc1] result2)) (is (= [doc2 doc4] result3)))) < ( $ lt ) , < = ( $ lte ) , > ( $ gt ) , > = ( ) (deftest query-using-dsl-and-$lt-operator-with-integers (let [coll "querying_docs" doc1 { :language "Clojure" :_id (ObjectId.) :inception_year 2006 } doc2 { :language "Java" :_id (ObjectId.) :inception_year 1992 } doc3 { :language "Scala" :_id (ObjectId.) :inception_year 2003 } _ (mc/insert-batch db coll [doc1 doc2]) lt-result (with-collection db coll (find { :inception_year { $lt 2000 } }) (limit 2))] (is (= [doc2] (vec lt-result))))) (deftest query-using-dsl-and-$lt-operator-with-dates (let [coll "querying_docs" these rely on monger.joda - time being loaded . MK . doc1 { :language "Clojure" :_id (ObjectId.) :inception_year (date-time 2006 1 1) } doc2 { :language "Java" :_id (ObjectId.) :inception_year (date-time 1992 1 2) } doc3 { :language "Scala" :_id (ObjectId.) :inception_year (date-time 2003 3 3) } _ (mc/insert-batch db coll [doc1 doc2]) lt-result (with-collection db coll (find { :inception_year { $lt (date-time 2000 1 2) } }) (limit 2))] (is (= (map :_id [doc2]) (map :_id (vec lt-result)))))) (deftest query-using-both-$lte-and-$gte-operators-with-dates (let [coll "querying_docs" these rely on monger.joda - time being loaded . MK . doc1 { :language "Clojure" :_id (ObjectId.) :inception_year (date-time 2006 1 1) } doc2 { :language "Java" :_id (ObjectId.) :inception_year (date-time 1992 1 2) } doc3 { :language "Scala" :_id (ObjectId.) :inception_year (date-time 2003 3 3) } _ (mc/insert-batch db coll [doc1 doc2 doc3]) lt-result (with-collection db coll (find { :inception_year { $gt (date-time 2000 1 2) $lte (date-time 2007 2 2) } }) (sort { :inception_year 1 }))] (is (= (map :_id [doc3 doc1]) (map :_id (vec lt-result)))))) (deftest query-using-$gt-$lt-$gte-$lte-operators-as-strings (let [coll "querying_docs" doc1 { :language "Clojure" :_id (ObjectId.) :inception_year 2006 } doc2 { :language "Java" :_id (ObjectId.) :inception_year 1992 } doc3 { :language "Scala" :_id (ObjectId.) :inception_year 2003 } _ (mc/insert-batch db coll [doc1 doc2 doc3])] (are [doc, result] (= doc, result) (doc2 (with-collection db coll (find { :inception_year { "$lt" 2000 } }))) (doc2 (with-collection db coll (find { :inception_year { "$lte" 1992 } }))) (doc1 (with-collection db coll (find { :inception_year { "$gt" 2002 } }) (limit 1) (sort { :inception_year -1 }))) (doc1 (with-collection db coll (find { :inception_year { "$gte" 2006 } })))))) (deftest query-using-$gt-$lt-$gte-$lte-operators-using-dsl-composition (let [coll "querying_docs" doc1 { :language "Clojure" :_id (ObjectId.) :inception_year 2006 } doc2 { :language "Java" :_id (ObjectId.) :inception_year 1992 } doc3 { :language "Scala" :_id (ObjectId.) :inception_year 2003 } srt (-> {} (limit 1) (sort { :inception_year -1 })) _ (mc/insert-batch db coll [doc1 doc2 doc3])] (is (= [doc1] (with-collection db coll (find { :inception_year { "$gt" 2002 } }) (merge srt)))))) ;; $all (deftest query-with-using-$all (let [coll "querying_docs" doc1 { :_id (ObjectId.) :title "Clojure" :tags ["functional" "homoiconic" "syntax-oriented" "dsls" "concurrency features" "jvm"] } doc2 { :_id (ObjectId.) :title "Java" :tags ["object-oriented" "jvm"] } doc3 { :_id (ObjectId.) :title "Scala" :tags ["functional" "object-oriented" "dsls" "concurrency features" "jvm"] } - (mc/insert-batch db coll [doc1 doc2 doc3]) result1 (with-collection db coll (find { :tags { "$all" ["functional" "jvm" "homoiconic"] } })) result2 (with-collection db coll (find { :tags { "$all" ["functional" "native" "homoiconic"] } })) result3 (with-collection db coll (find { :tags { "$all" ["functional" "jvm" "dsls"] } }) (sort { :title 1 }))] (is (= [doc1] result1)) (is (empty? result2)) (is (= 2 (count result3))) (is (= doc1 (first result3))))) ;; $exists (deftest query-with-find-one-as-map-using-$exists (let [coll "querying_docs" doc1 { :_id (ObjectId.) :published-by "Jill The Blogger" :draft false :title "X announces another Y" } doc2 { :_id (ObjectId.) :draft true :title "Z announces a Y competitor" } _ (mc/insert-batch db coll [doc1 doc2]) result1 (mc/find-one-as-map db coll { :published-by { "$exists" true } }) result2 (mc/find-one-as-map db coll { :published-by { "$exists" false } })] (is (= doc1 result1)) (is (= doc2 result2)))) ;; $mod (deftest query-with-find-one-as-map-using-$mod (let [coll "querying_docs" doc1 { :_id (ObjectId.) :counter 25 } doc2 { :_id (ObjectId.) :counter 32 } doc3 { :_id (ObjectId.) :counter 63 } _ (mc/insert-batch db coll [doc1 doc2 doc3]) result1 (mc/find-one-as-map db coll { :counter { "$mod" [10, 5] } }) result2 (mc/find-one-as-map db coll { :counter { "$mod" [10, 2] } }) result3 (mc/find-one-as-map db coll { :counter { "$mod" [11, 1] } })] (is (= doc1 result1)) (is (= doc2 result2)) (is (empty? result3)))) ;; $ne (deftest query-with-find-one-as-map-using-$ne (let [coll "querying_docs" doc1 { :_id (ObjectId.) :counter 25 } doc2 { :_id (ObjectId.) :counter 32 } _ (mc/insert-batch db coll [doc1 doc2]) result1 (mc/find-one-as-map db coll { :counter { "$ne" 25 } }) result2 (mc/find-one-as-map db coll { :counter { "$ne" 32 } })] (is (= doc2 result1)) (is (= doc1 result2)))) ;; ;; monger.query DSL features ;; ;; pagination (deftest query-using-pagination-dsl (let [coll "querying_docs" doc1 { :_id (ObjectId.) :title "Clojure" :tags ["functional" "homoiconic" "syntax-oriented" "dsls" "concurrency features" "jvm"] } doc2 { :_id (ObjectId.) :title "Java" :tags ["object-oriented" "jvm"] } doc3 { :_id (ObjectId.) :title "Scala" :tags ["functional" "object-oriented" "dsls" "concurrency features" "jvm"] } doc4 { :_id (ObjectId.) :title "Ruby" :tags ["dynamic" "object-oriented" "dsls" "jvm"] } doc5 { :_id (ObjectId.) :title "Groovy" :tags ["dynamic" "object-oriented" "dsls" "jvm"] } doc6 { :_id (ObjectId.) :title "OCaml" :tags ["functional" "static" "dsls"] } doc7 { :_id (ObjectId.) :title "Haskell" :tags ["functional" "static" "dsls" "concurrency features"] } - (mc/insert-batch db coll [doc1 doc2 doc3 doc4 doc5 doc6 doc7]) result1 (with-collection db coll (find {}) (paginate :page 1 :per-page 3) (sort { :title 1 }) (read-preference (ReadPreference/primary)) (options com.mongodb.Bytes/QUERYOPTION_NOTIMEOUT)) result2 (with-collection db coll (find {}) (paginate :page 2 :per-page 3) (sort { :title 1 })) result3 (with-collection db coll (find {}) (paginate :page 3 :per-page 3) (sort { :title 1 })) result4 (with-collection db coll (find {}) (paginate :page 10 :per-page 3) (sort { :title 1 }))] (is (= [doc1 doc5 doc7] result1)) (is (= [doc2 doc6 doc4] result2)) (is (= [doc3] result3)) (is (empty? result4)))) (deftest combined-querying-dsl-example1 (let [coll "querying_docs" ma-doc { :_id (ObjectId.) :name "Massachusetts" :iso "MA" :population 6547629 :joined_in 1788 :capital "Boston" } de-doc { :_id (ObjectId.) :name "Delaware" :iso "DE" :population 897934 :joined_in 1787 :capital "Dover" } ny-doc { :_id (ObjectId.) :name "New York" :iso "NY" :population 19378102 :joined_in 1788 :capital "Albany" } ca-doc { :_id (ObjectId.) :name "California" :iso "CA" :population 37253956 :joined_in 1850 :capital "Sacramento" } tx-doc { :_id (ObjectId.) :name "Texas" :iso "TX" :population 25145561 :joined_in 1845 :capital "Austin" } top3 (partial-query (limit 3)) by-population-desc (partial-query (sort { :population -1 })) _ (mc/insert-batch db coll [ma-doc de-doc ny-doc ca-doc tx-doc]) result (with-collection db coll (find {}) (merge top3) (merge by-population-desc))] (is (= result [ca-doc tx-doc ny-doc])))) (deftest combined-querying-dsl-example2 (let [coll "querying_docs" ma-doc { :_id (ObjectId.) :name "Massachusetts" :iso "MA" :population 6547629 :joined_in 1788 :capital "Boston" } de-doc { :_id (ObjectId.) :name "Delaware" :iso "DE" :population 897934 :joined_in 1787 :capital "Dover" } ny-doc { :_id (ObjectId.) :name "New York" :iso "NY" :population 19378102 :joined_in 1788 :capital "Albany" } ca-doc { :_id (ObjectId.) :name "California" :iso "CA" :population 37253956 :joined_in 1850 :capital "Sacramento" } tx-doc { :_id (ObjectId.) :name "Texas" :iso "TX" :population 25145561 :joined_in 1845 :capital "Austin" } top3 (partial-query (limit 3)) by-population-desc (partial-query (sort { :population -1 })) _ (mc/insert-batch db coll [ma-doc de-doc ny-doc ca-doc tx-doc]) result (with-collection db coll (find {}) (merge top3) (merge by-population-desc) (keywordize-fields false))] ;; documents have fields as strings, ;; not keywords (is (= (map #(% "name") result) (map #(% :name) [ca-doc tx-doc ny-doc]))))))
null
https://raw.githubusercontent.com/michaelklishin/monger/9f3d192dffb16da011f805355b87ae172c584a69/test/monger/test/querying_test.clj
clojure
monger.collection/* finders ("low-level API") exact match over string field exact match over string field with limit $all $exists $mod $ne monger.query DSL features pagination documents have fields as strings, not keywords
(ns monger.test.querying-test (:refer-clojure :exclude [select find sort]) (:import [com.mongodb WriteResult WriteConcern DBObject ReadPreference] org.bson.types.ObjectId java.util.Date) (:require [monger.core :as mg] [monger.collection :as mc] monger.joda-time [monger.result :as mgres] [clojure.test :refer :all] [monger.conversion :refer :all] [monger.query :refer :all] [monger.operators :refer :all] [clj-time.core :refer [date-time]])) (let [conn (mg/connect) db (mg/get-db conn "monger-test")] (defn purge-collections [f] (mc/remove db "docs") (mc/remove db "things") (mc/remove db "locations") (mc/remove db "querying_docs") (f) (mc/remove db "docs") (mc/remove db "things") (mc/remove db "locations") (mc/remove db "querying_docs")) (use-fixtures :each purge-collections) by (deftest query-full-document-by-object-id (let [coll "querying_docs" oid (ObjectId.) doc { :_id oid :title "Introducing Monger" }] (mc/insert db coll doc) (is (= doc (mc/find-map-by-id db coll oid))) (is (= doc (mc/find-one-as-map db coll { :_id oid }))))) (deftest query-full-document-using-exact-matching-over-string-field (let [coll "querying_docs" doc { :title "monger" :language "Clojure" :_id (ObjectId.) }] (mc/insert db coll doc) (is (= [doc] (mc/find-maps db coll { :title "monger" }))) (is (= doc (from-db-object (first (mc/find db coll { :title "monger" })) true))))) (deftest query-full-document-using-exact-matching-over-string-with-field-with-limit (let [coll "querying_docs" doc1 { :title "monger" :language "Clojure" :_id (ObjectId.) } doc2 { :title "langohr" :language "Clojure" :_id (ObjectId.) } doc3 { :title "netty" :language "Java" :_id (ObjectId.) } _ (mc/insert-batch db coll [doc1 doc2 doc3]) result (with-collection db coll (find { :title "monger" }) (fields [:title, :language, :_id]) (skip 0) (limit 1))] (is (= 1 (count result))) (is (= [doc1] result)))) (deftest query-full-document-using-exact-matching-over-string-field-with-limit-and-offset (let [coll "querying_docs" doc1 { :title "lucene" :language "Java" :_id (ObjectId.) } doc2 { :title "joda-time" :language "Java" :_id (ObjectId.) } doc3 { :title "netty" :language "Java" :_id (ObjectId.) } _ (mc/insert-batch db coll [doc1 doc2 doc3]) result (with-collection db coll (find { :language "Java" }) (skip 1) (limit 2) (sort { :title 1 }))] (is (= 2 (count result))) (is (= [doc1 doc3] result)))) (deftest query-with-sorting-on-multiple-fields (let [coll "querying_docs" doc1 { :a 1 :b 2 :c 3 :text "Whatever" :_id (ObjectId.) } doc2 { :a 1 :b 1 :c 4 :text "Blah " :_id (ObjectId.) } doc3 { :a 10 :b 3 :c 1 :text "Abc" :_id (ObjectId.) } doc4 { :a 10 :b 3 :c 3 :text "Abc" :_id (ObjectId.) } _ (mc/insert-batch db coll [doc1 doc2 doc3 doc4]) result1 (with-collection db coll (find {}) (limit 2) (fields [:a :b :c :text]) (sort (sorted-map :a 1 :b 1 :text -1))) result2 (with-collection db coll (find {}) (limit 2) (fields [:a :b :c :text]) (sort (array-map :c 1 :text -1))) result3 (with-collection db coll (find {}) (limit 2) (fields [:a :b :c :text]) (sort (array-map :c -1 :text 1)))] (is (= [doc2 doc1] result1)) (is (= [doc3 doc1] result2)) (is (= [doc2 doc4] result3)))) < ( $ lt ) , < = ( $ lte ) , > ( $ gt ) , > = ( ) (deftest query-using-dsl-and-$lt-operator-with-integers (let [coll "querying_docs" doc1 { :language "Clojure" :_id (ObjectId.) :inception_year 2006 } doc2 { :language "Java" :_id (ObjectId.) :inception_year 1992 } doc3 { :language "Scala" :_id (ObjectId.) :inception_year 2003 } _ (mc/insert-batch db coll [doc1 doc2]) lt-result (with-collection db coll (find { :inception_year { $lt 2000 } }) (limit 2))] (is (= [doc2] (vec lt-result))))) (deftest query-using-dsl-and-$lt-operator-with-dates (let [coll "querying_docs" these rely on monger.joda - time being loaded . MK . doc1 { :language "Clojure" :_id (ObjectId.) :inception_year (date-time 2006 1 1) } doc2 { :language "Java" :_id (ObjectId.) :inception_year (date-time 1992 1 2) } doc3 { :language "Scala" :_id (ObjectId.) :inception_year (date-time 2003 3 3) } _ (mc/insert-batch db coll [doc1 doc2]) lt-result (with-collection db coll (find { :inception_year { $lt (date-time 2000 1 2) } }) (limit 2))] (is (= (map :_id [doc2]) (map :_id (vec lt-result)))))) (deftest query-using-both-$lte-and-$gte-operators-with-dates (let [coll "querying_docs" these rely on monger.joda - time being loaded . MK . doc1 { :language "Clojure" :_id (ObjectId.) :inception_year (date-time 2006 1 1) } doc2 { :language "Java" :_id (ObjectId.) :inception_year (date-time 1992 1 2) } doc3 { :language "Scala" :_id (ObjectId.) :inception_year (date-time 2003 3 3) } _ (mc/insert-batch db coll [doc1 doc2 doc3]) lt-result (with-collection db coll (find { :inception_year { $gt (date-time 2000 1 2) $lte (date-time 2007 2 2) } }) (sort { :inception_year 1 }))] (is (= (map :_id [doc3 doc1]) (map :_id (vec lt-result)))))) (deftest query-using-$gt-$lt-$gte-$lte-operators-as-strings (let [coll "querying_docs" doc1 { :language "Clojure" :_id (ObjectId.) :inception_year 2006 } doc2 { :language "Java" :_id (ObjectId.) :inception_year 1992 } doc3 { :language "Scala" :_id (ObjectId.) :inception_year 2003 } _ (mc/insert-batch db coll [doc1 doc2 doc3])] (are [doc, result] (= doc, result) (doc2 (with-collection db coll (find { :inception_year { "$lt" 2000 } }))) (doc2 (with-collection db coll (find { :inception_year { "$lte" 1992 } }))) (doc1 (with-collection db coll (find { :inception_year { "$gt" 2002 } }) (limit 1) (sort { :inception_year -1 }))) (doc1 (with-collection db coll (find { :inception_year { "$gte" 2006 } })))))) (deftest query-using-$gt-$lt-$gte-$lte-operators-using-dsl-composition (let [coll "querying_docs" doc1 { :language "Clojure" :_id (ObjectId.) :inception_year 2006 } doc2 { :language "Java" :_id (ObjectId.) :inception_year 1992 } doc3 { :language "Scala" :_id (ObjectId.) :inception_year 2003 } srt (-> {} (limit 1) (sort { :inception_year -1 })) _ (mc/insert-batch db coll [doc1 doc2 doc3])] (is (= [doc1] (with-collection db coll (find { :inception_year { "$gt" 2002 } }) (merge srt)))))) (deftest query-with-using-$all (let [coll "querying_docs" doc1 { :_id (ObjectId.) :title "Clojure" :tags ["functional" "homoiconic" "syntax-oriented" "dsls" "concurrency features" "jvm"] } doc2 { :_id (ObjectId.) :title "Java" :tags ["object-oriented" "jvm"] } doc3 { :_id (ObjectId.) :title "Scala" :tags ["functional" "object-oriented" "dsls" "concurrency features" "jvm"] } - (mc/insert-batch db coll [doc1 doc2 doc3]) result1 (with-collection db coll (find { :tags { "$all" ["functional" "jvm" "homoiconic"] } })) result2 (with-collection db coll (find { :tags { "$all" ["functional" "native" "homoiconic"] } })) result3 (with-collection db coll (find { :tags { "$all" ["functional" "jvm" "dsls"] } }) (sort { :title 1 }))] (is (= [doc1] result1)) (is (empty? result2)) (is (= 2 (count result3))) (is (= doc1 (first result3))))) (deftest query-with-find-one-as-map-using-$exists (let [coll "querying_docs" doc1 { :_id (ObjectId.) :published-by "Jill The Blogger" :draft false :title "X announces another Y" } doc2 { :_id (ObjectId.) :draft true :title "Z announces a Y competitor" } _ (mc/insert-batch db coll [doc1 doc2]) result1 (mc/find-one-as-map db coll { :published-by { "$exists" true } }) result2 (mc/find-one-as-map db coll { :published-by { "$exists" false } })] (is (= doc1 result1)) (is (= doc2 result2)))) (deftest query-with-find-one-as-map-using-$mod (let [coll "querying_docs" doc1 { :_id (ObjectId.) :counter 25 } doc2 { :_id (ObjectId.) :counter 32 } doc3 { :_id (ObjectId.) :counter 63 } _ (mc/insert-batch db coll [doc1 doc2 doc3]) result1 (mc/find-one-as-map db coll { :counter { "$mod" [10, 5] } }) result2 (mc/find-one-as-map db coll { :counter { "$mod" [10, 2] } }) result3 (mc/find-one-as-map db coll { :counter { "$mod" [11, 1] } })] (is (= doc1 result1)) (is (= doc2 result2)) (is (empty? result3)))) (deftest query-with-find-one-as-map-using-$ne (let [coll "querying_docs" doc1 { :_id (ObjectId.) :counter 25 } doc2 { :_id (ObjectId.) :counter 32 } _ (mc/insert-batch db coll [doc1 doc2]) result1 (mc/find-one-as-map db coll { :counter { "$ne" 25 } }) result2 (mc/find-one-as-map db coll { :counter { "$ne" 32 } })] (is (= doc2 result1)) (is (= doc1 result2)))) (deftest query-using-pagination-dsl (let [coll "querying_docs" doc1 { :_id (ObjectId.) :title "Clojure" :tags ["functional" "homoiconic" "syntax-oriented" "dsls" "concurrency features" "jvm"] } doc2 { :_id (ObjectId.) :title "Java" :tags ["object-oriented" "jvm"] } doc3 { :_id (ObjectId.) :title "Scala" :tags ["functional" "object-oriented" "dsls" "concurrency features" "jvm"] } doc4 { :_id (ObjectId.) :title "Ruby" :tags ["dynamic" "object-oriented" "dsls" "jvm"] } doc5 { :_id (ObjectId.) :title "Groovy" :tags ["dynamic" "object-oriented" "dsls" "jvm"] } doc6 { :_id (ObjectId.) :title "OCaml" :tags ["functional" "static" "dsls"] } doc7 { :_id (ObjectId.) :title "Haskell" :tags ["functional" "static" "dsls" "concurrency features"] } - (mc/insert-batch db coll [doc1 doc2 doc3 doc4 doc5 doc6 doc7]) result1 (with-collection db coll (find {}) (paginate :page 1 :per-page 3) (sort { :title 1 }) (read-preference (ReadPreference/primary)) (options com.mongodb.Bytes/QUERYOPTION_NOTIMEOUT)) result2 (with-collection db coll (find {}) (paginate :page 2 :per-page 3) (sort { :title 1 })) result3 (with-collection db coll (find {}) (paginate :page 3 :per-page 3) (sort { :title 1 })) result4 (with-collection db coll (find {}) (paginate :page 10 :per-page 3) (sort { :title 1 }))] (is (= [doc1 doc5 doc7] result1)) (is (= [doc2 doc6 doc4] result2)) (is (= [doc3] result3)) (is (empty? result4)))) (deftest combined-querying-dsl-example1 (let [coll "querying_docs" ma-doc { :_id (ObjectId.) :name "Massachusetts" :iso "MA" :population 6547629 :joined_in 1788 :capital "Boston" } de-doc { :_id (ObjectId.) :name "Delaware" :iso "DE" :population 897934 :joined_in 1787 :capital "Dover" } ny-doc { :_id (ObjectId.) :name "New York" :iso "NY" :population 19378102 :joined_in 1788 :capital "Albany" } ca-doc { :_id (ObjectId.) :name "California" :iso "CA" :population 37253956 :joined_in 1850 :capital "Sacramento" } tx-doc { :_id (ObjectId.) :name "Texas" :iso "TX" :population 25145561 :joined_in 1845 :capital "Austin" } top3 (partial-query (limit 3)) by-population-desc (partial-query (sort { :population -1 })) _ (mc/insert-batch db coll [ma-doc de-doc ny-doc ca-doc tx-doc]) result (with-collection db coll (find {}) (merge top3) (merge by-population-desc))] (is (= result [ca-doc tx-doc ny-doc])))) (deftest combined-querying-dsl-example2 (let [coll "querying_docs" ma-doc { :_id (ObjectId.) :name "Massachusetts" :iso "MA" :population 6547629 :joined_in 1788 :capital "Boston" } de-doc { :_id (ObjectId.) :name "Delaware" :iso "DE" :population 897934 :joined_in 1787 :capital "Dover" } ny-doc { :_id (ObjectId.) :name "New York" :iso "NY" :population 19378102 :joined_in 1788 :capital "Albany" } ca-doc { :_id (ObjectId.) :name "California" :iso "CA" :population 37253956 :joined_in 1850 :capital "Sacramento" } tx-doc { :_id (ObjectId.) :name "Texas" :iso "TX" :population 25145561 :joined_in 1845 :capital "Austin" } top3 (partial-query (limit 3)) by-population-desc (partial-query (sort { :population -1 })) _ (mc/insert-batch db coll [ma-doc de-doc ny-doc ca-doc tx-doc]) result (with-collection db coll (find {}) (merge top3) (merge by-population-desc) (keywordize-fields false))] (is (= (map #(% "name") result) (map #(% :name) [ca-doc tx-doc ny-doc]))))))
282003c6b24c400ed7533c63facac967a0e5eaced4b283c9c4f32c22143fad65
lambdaisland/launchpad
shadow.clj
re - enable lambdaisland.launchpad.shadow (:require [clojure.java.io :as io] [shadow.cljs.devtools.api :as api] [shadow.cljs.devtools.config :as config] [shadow.cljs.devtools.server :as server] [shadow.cljs.devtools.server.runtime :as runtime] [lambdaisland.classpath :as licp]) (:import (java.nio.file Path))) (def process-root "The directory where the JVM is running, as a Path" (.toAbsolutePath (Path/of "" (into-array String [])))) (defn find-shadow-roots "Find all libraries included via :local/root that have a shadow-cljs.edn at their root." [] (cond-> (keep (fn [{:local/keys [root]}] (when (and root (.exists (io/file root "shadow-cljs.edn"))) root)) (vals (:libs (licp/read-basis)))) (.exists (io/file "shadow-cljs.edn")) (conj ""))) (defn read-shadow-config "Slurp in a shadow-cljs.edn, applying normalization and defaults." [file] (-> (config/read-config file) (config/normalize) (->> (merge config/default-config)))) (defn relativize "Given module-path as a relative-path inside module-root, return a relative path based off process-root." [process-root module-root module-path] (-> process-root (.relativize (.resolve module-root module-path)) str) ) (defn update-build-keys "Update `:output-to`/`:output-dir` in a shadow build config, such that is resolved against the process root, rather than the module root." [process-root module-root build] (cond-> build (:output-dir build) (update :output-dir (partial relativize process-root module-root)) (:output-to build) (update :output-to (partial relativize process-root module-root)))) (defn merged-shadow-config "Given multiple locations that contain a shadow-cljs.edn, merge them into a single config, where the path locations have been updated." [module-paths] (-> (apply merge-with (fn [a b] (cond (and (map? a) (map? b)) (merge a b) (and (set? a) (set? b)) (into a b) :else b)) (for [module-path module-paths :let [module-root (.toAbsolutePath (Path/of module-path (into-array String []))) config-file (str (.resolve module-root "shadow-cljs.edn")) module-name (str (.getFileName module-root))]] (-> config-file read-shadow-config (update :builds (fn [builds] (into {} (map (fn [[k v]] (let [build-id k ;; Not sure yet if this is a good idea #_(if (qualified-keyword? k) k (keyword module-name (name k)))] [build-id (assoc (update-build-keys process-root module-root v) :build-id build-id :js-options (if (= "" module-path) {} {:js-package-dirs [(str module-path "/node_modules")]}))]))) builds)))))) (assoc :deps {}) (dissoc :source-paths :dependencies))) (defn merged-config "Return a complete, combined, shadow-cljs config map, that combines all shadow-cljs.edn files found in projects that were references via :local/root." [] (merged-shadow-config (find-shadow-roots))) (defn start-builds! [& build-ids] (when (nil? @runtime/instance-ref) (let [config (merged-config)] (server/start! config) (doseq [build-id build-ids] (-> (get-in config [:builds build-id]) (assoc :build-id build-id) api/watch)) (loop [] (when (nil? @runtime/instance-ref) (Thread/sleep 250) (recur)))))) #_(start-builds :main) #_(require 'shadow.build)
null
https://raw.githubusercontent.com/lambdaisland/launchpad/16137ecfd49d86f7f7dbe7d54e386c82e7720ab6/src/lambdaisland/launchpad/shadow.clj
clojure
Not sure yet if this is a good idea
re - enable lambdaisland.launchpad.shadow (:require [clojure.java.io :as io] [shadow.cljs.devtools.api :as api] [shadow.cljs.devtools.config :as config] [shadow.cljs.devtools.server :as server] [shadow.cljs.devtools.server.runtime :as runtime] [lambdaisland.classpath :as licp]) (:import (java.nio.file Path))) (def process-root "The directory where the JVM is running, as a Path" (.toAbsolutePath (Path/of "" (into-array String [])))) (defn find-shadow-roots "Find all libraries included via :local/root that have a shadow-cljs.edn at their root." [] (cond-> (keep (fn [{:local/keys [root]}] (when (and root (.exists (io/file root "shadow-cljs.edn"))) root)) (vals (:libs (licp/read-basis)))) (.exists (io/file "shadow-cljs.edn")) (conj ""))) (defn read-shadow-config "Slurp in a shadow-cljs.edn, applying normalization and defaults." [file] (-> (config/read-config file) (config/normalize) (->> (merge config/default-config)))) (defn relativize "Given module-path as a relative-path inside module-root, return a relative path based off process-root." [process-root module-root module-path] (-> process-root (.relativize (.resolve module-root module-path)) str) ) (defn update-build-keys "Update `:output-to`/`:output-dir` in a shadow build config, such that is resolved against the process root, rather than the module root." [process-root module-root build] (cond-> build (:output-dir build) (update :output-dir (partial relativize process-root module-root)) (:output-to build) (update :output-to (partial relativize process-root module-root)))) (defn merged-shadow-config "Given multiple locations that contain a shadow-cljs.edn, merge them into a single config, where the path locations have been updated." [module-paths] (-> (apply merge-with (fn [a b] (cond (and (map? a) (map? b)) (merge a b) (and (set? a) (set? b)) (into a b) :else b)) (for [module-path module-paths :let [module-root (.toAbsolutePath (Path/of module-path (into-array String []))) config-file (str (.resolve module-root "shadow-cljs.edn")) module-name (str (.getFileName module-root))]] (-> config-file read-shadow-config (update :builds (fn [builds] (into {} (map (fn [[k v]] (let [build-id k #_(if (qualified-keyword? k) k (keyword module-name (name k)))] [build-id (assoc (update-build-keys process-root module-root v) :build-id build-id :js-options (if (= "" module-path) {} {:js-package-dirs [(str module-path "/node_modules")]}))]))) builds)))))) (assoc :deps {}) (dissoc :source-paths :dependencies))) (defn merged-config "Return a complete, combined, shadow-cljs config map, that combines all shadow-cljs.edn files found in projects that were references via :local/root." [] (merged-shadow-config (find-shadow-roots))) (defn start-builds! [& build-ids] (when (nil? @runtime/instance-ref) (let [config (merged-config)] (server/start! config) (doseq [build-id build-ids] (-> (get-in config [:builds build-id]) (assoc :build-id build-id) api/watch)) (loop [] (when (nil? @runtime/instance-ref) (Thread/sleep 250) (recur)))))) #_(start-builds :main) #_(require 'shadow.build)
d50486ec8e8ff33071de90150e6c8912214d4260f4a687a455c0e0aa825d3217
racket/gui
snip-canvas.rkt
#lang racket/base (require racket/gui/base racket/class) (provide snip-canvas%) (define snip-canvas% (class editor-canvas% (init parent make-snip [style null] [label #f] [horizontal-inset 5] [vertical-inset 5] [enabled #t] [vert-margin 0] [horiz-margin 0] [min-width 0] [min-height 0] [stretchable-width #t] [stretchable-height #t]) (define snip #f) (define text (new read-only-text%)) (send text set-writable #f) (define/public (get-snip) snip) (define/override (on-size w h) (update-snip w h) (super on-size w h)) (define (update-snip w h) (define snip-w (max 0 (- w (* 2 horizontal-inset)))) (define snip-h (max 0 (- h (* 2 vertical-inset)))) (cond [snip (send snip resize snip-w snip-h)] [else (set-snip (make-snip snip-w snip-h))])) (define (set-snip s) (unless (is-a? s snip%) (raise-type-error 'set-snip "snip%" s)) (set! snip s) (send text set-writable #t) (send text begin-edit-sequence #f) (send text erase) (send text insert snip) (send text end-edit-sequence) (send text set-writable #f)) (super-new [parent parent] [editor text] [horizontal-inset horizontal-inset] [vertical-inset vertical-inset] [label label] [enabled enabled] [style (list* 'no-hscroll 'no-vscroll style)] [vert-margin vert-margin] [horiz-margin horiz-margin] [min-width min-width] [min-height min-height] [stretchable-width stretchable-width] [stretchable-height stretchable-height]))) (define read-only-text% (class text% (define writable? #t) (define/public (set-writable w?) (set! writable? w?)) (define/augment (can-change-style? start len) writable?) (define/augment (can-delete? start len) writable?) (define/augment (can-insert? start len) writable?) (define/augment (can-load-file? filename format) writable?) (define/augment (can-save-file? filename format) writable?) (define/override (can-do-edit-operation? op [recursive? #t]) (case op [(copy select-all) #t] [else writable?])) (super-new) (send this hide-caret #t)))
null
https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mrlib/snip-canvas.rkt
racket
#lang racket/base (require racket/gui/base racket/class) (provide snip-canvas%) (define snip-canvas% (class editor-canvas% (init parent make-snip [style null] [label #f] [horizontal-inset 5] [vertical-inset 5] [enabled #t] [vert-margin 0] [horiz-margin 0] [min-width 0] [min-height 0] [stretchable-width #t] [stretchable-height #t]) (define snip #f) (define text (new read-only-text%)) (send text set-writable #f) (define/public (get-snip) snip) (define/override (on-size w h) (update-snip w h) (super on-size w h)) (define (update-snip w h) (define snip-w (max 0 (- w (* 2 horizontal-inset)))) (define snip-h (max 0 (- h (* 2 vertical-inset)))) (cond [snip (send snip resize snip-w snip-h)] [else (set-snip (make-snip snip-w snip-h))])) (define (set-snip s) (unless (is-a? s snip%) (raise-type-error 'set-snip "snip%" s)) (set! snip s) (send text set-writable #t) (send text begin-edit-sequence #f) (send text erase) (send text insert snip) (send text end-edit-sequence) (send text set-writable #f)) (super-new [parent parent] [editor text] [horizontal-inset horizontal-inset] [vertical-inset vertical-inset] [label label] [enabled enabled] [style (list* 'no-hscroll 'no-vscroll style)] [vert-margin vert-margin] [horiz-margin horiz-margin] [min-width min-width] [min-height min-height] [stretchable-width stretchable-width] [stretchable-height stretchable-height]))) (define read-only-text% (class text% (define writable? #t) (define/public (set-writable w?) (set! writable? w?)) (define/augment (can-change-style? start len) writable?) (define/augment (can-delete? start len) writable?) (define/augment (can-insert? start len) writable?) (define/augment (can-load-file? filename format) writable?) (define/augment (can-save-file? filename format) writable?) (define/override (can-do-edit-operation? op [recursive? #t]) (case op [(copy select-all) #t] [else writable?])) (super-new) (send this hide-caret #t)))
e55ffb4f7ff77f5654e76d9ad9bf44dd23d10e7f7c8e699282e89d9c38bcfbab
startalkIM/ejabberd
ejabberd_system_monitor.erl
%%%------------------------------------------------------------------- %%% File : ejabberd_system_monitor.erl Author : < > %%% Description : Ejabberd watchdog Created : 21 Mar 2007 by < > %%% %%% ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne %%% %%% This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the %%% License, or (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU %%% General Public License for more details. %%% You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . %%% %%%------------------------------------------------------------------- -module(ejabberd_system_monitor). -behaviour(ejabberd_config). -author(''). -behaviour(gen_server). %% API -export([start_link/0, process_command/3, register_hook/1, process_remote_command/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, opt_type/1]). -include("ejabberd.hrl"). -include("logger.hrl"). -include("jlib.hrl"). -record(state, {}). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the server %%-------------------------------------------------------------------- start_link() -> LH = ejabberd_config:get_option( watchdog_large_heap, fun(I) when is_integer(I), I > 0 -> I end, 1000000), Opts = [{large_heap, LH}], gen_server:start_link({local, ?MODULE}, ?MODULE, Opts, []). process_command(From, To, Packet) -> case To of #jid{luser = <<"">>, lresource = <<"watchdog">>} -> #xmlel{name = Name} = Packet, case Name of <<"message">> -> LFrom = jid:tolower(jid:remove_resource(From)), case lists:member(LFrom, get_admin_jids()) of true -> Body = fxml:get_path_s(Packet, [{elem, <<"body">>}, cdata]), spawn(fun () -> process_flag(priority, high), process_command1(From, To, Body) end), stop; false -> ok end; _ -> ok end; _ -> ok end. register_hook(Host) -> ejabberd_hooks:add(local_send_to_resource_hook, Host, ?MODULE, process_command, 50). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init(Opts) -> LH = proplists:get_value(large_heap, Opts), process_flag(priority, high), erlang:system_monitor(self(), [{large_heap, LH}]), lists:foreach(fun register_hook/1, ?MYHOSTS), {ok, #state{}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({get, large_heap}, _From, State) -> {reply, get_large_heap(), State}; handle_call({set, large_heap, NewValue}, _From, State) -> MonSettings = erlang:system_monitor(self(), [{large_heap, NewValue}]), OldLH = get_large_heap(MonSettings), NewLH = get_large_heap(), {reply, {lh_changed, OldLH, NewLH}, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. get_large_heap() -> MonSettings = erlang:system_monitor(), get_large_heap(MonSettings). get_large_heap(MonSettings) -> {_MonitorPid, Options} = MonSettings, proplists:get_value(large_heap, Options). %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info({monitor, Pid, large_heap, Info}, State) -> spawn(fun () -> process_flag(priority, high), process_large_heap(Pid, Info) end), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- process_large_heap(Pid, Info) -> Host = (?MYNAME), JIDs = get_admin_jids(), DetailedInfo = detailed_info(Pid), Body = iolist_to_binary( io_lib:format("(~w) The process ~w is consuming too " "much memory:~n~p~n~s", [node(), Pid, Info, DetailedInfo])), From = jid:make(<<"">>, Host, <<"watchdog">>), Hint = [#xmlel{name = <<"no-permanent-store">>, attrs = [{<<"xmlns">>, ?NS_HINTS}]}], lists:foreach(fun (JID) -> send_message(From, jid:make(JID), Body, Hint) end, JIDs). send_message(From, To, Body) -> send_message(From, To, Body, []). send_message(From, To, Body, ExtraEls) -> ejabberd_router:route(From, To, #xmlel{name = <<"message">>, attrs = [{<<"type">>, <<"chat">>}], children = [#xmlel{name = <<"body">>, attrs = [], children = [{xmlcdata, Body}]} | ExtraEls]}). get_admin_jids() -> ejabberd_config:get_option( watchdog_admins, fun(JIDs) -> [jid:tolower( jid:from_string( iolist_to_binary(S))) || S <- JIDs] end, []). detailed_info(Pid) -> case process_info(Pid, dictionary) of {dictionary, Dict} -> case lists:keysearch('$ancestors', 1, Dict) of {value, {'$ancestors', [Sup | _]}} -> case Sup of ejabberd_c2s_sup -> c2s_info(Pid); ejabberd_s2s_out_sup -> s2s_out_info(Pid); ejabberd_service_sup -> service_info(Pid); _ -> detailed_info1(Pid) end; _ -> detailed_info1(Pid) end; _ -> detailed_info1(Pid) end. detailed_info1(Pid) -> io_lib:format("~p", [[process_info(Pid, current_function), process_info(Pid, initial_call), process_info(Pid, message_queue_len), process_info(Pid, links), process_info(Pid, dictionary), process_info(Pid, heap_size), process_info(Pid, stack_size)]]). c2s_info(Pid) -> [<<"Process type: c2s">>, check_send_queue(Pid), <<"\n">>, io_lib:format("Command to kill this process: kill ~s ~w", [iolist_to_binary(atom_to_list(node())), Pid])]. s2s_out_info(Pid) -> FromTo = mnesia:dirty_select(s2s, [{{s2s, '$1', Pid, '_'}, [], ['$1']}]), [<<"Process type: s2s_out">>, case FromTo of [{From, To}] -> <<"\n", (io_lib:format("S2S connection: from ~s to ~s", [From, To]))/binary>>; _ -> <<"">> end, check_send_queue(Pid), <<"\n">>, io_lib:format("Command to kill this process: kill ~s ~w", [iolist_to_binary(atom_to_list(node())), Pid])]. service_info(Pid) -> Routes = mnesia:dirty_select(route, [{{route, '$1', Pid, '_'}, [], ['$1']}]), [<<"Process type: s2s_out">>, case Routes of [Route] -> <<"\nServiced domain: ", Route/binary>>; _ -> <<"">> end, check_send_queue(Pid), <<"\n">>, io_lib:format("Command to kill this process: kill ~s ~w", [iolist_to_binary(atom_to_list(node())), Pid])]. check_send_queue(Pid) -> case {process_info(Pid, current_function), process_info(Pid, message_queue_len)} of {{current_function, MFA}, {message_queue_len, MLen}} -> if MLen > 100 -> case MFA of {prim_inet, send, 2} -> <<"\nPossible reason: the process is blocked " "trying to send data over its TCP connection.">>; {M, F, A} -> [<<"\nPossible reason: the process can't " "process messages faster than they arrive. ">>, io_lib:format("Current function is ~w:~w/~w", [M, F, A])] end; true -> <<"">> end; _ -> <<"">> end. process_command1(From, To, Body) -> process_command2(str:tokens(Body, <<" ">>), From, To). process_command2([<<"kill">>, SNode, SPid], From, To) -> Node = jlib:binary_to_atom(SNode), remote_command(Node, [kill, SPid], From, To); process_command2([<<"showlh">>, SNode], From, To) -> Node = jlib:binary_to_atom(SNode), remote_command(Node, [showlh], From, To); process_command2([<<"setlh">>, SNode, NewValueString], From, To) -> Node = jlib:binary_to_atom(SNode), NewValue = jlib:binary_to_integer(NewValueString), remote_command(Node, [setlh, NewValue], From, To); process_command2([<<"help">>], From, To) -> send_message(To, From, help()); process_command2(_, From, To) -> send_message(To, From, help()). help() -> <<"Commands:\n kill <node> <pid>\n showlh " "<node>\n setlh <node> <integer>">>. remote_command(Node, Args, From, To) -> Message = case ejabberd_cluster:call(Node, ?MODULE, process_remote_command, [Args]) of {badrpc, Reason} -> io_lib:format("Command failed:~n~p", [Reason]); Result -> Result end, send_message(To, From, iolist_to_binary(Message)). process_remote_command([kill, SPid]) -> exit(list_to_pid(SPid), kill), <<"ok">>; process_remote_command([showlh]) -> Res = gen_server:call(ejabberd_system_monitor, {get, large_heap}), io_lib:format("Current large heap: ~p", [Res]); process_remote_command([setlh, NewValue]) -> {lh_changed, OldLH, NewLH} = gen_server:call(ejabberd_system_monitor, {set, large_heap, NewValue}), io_lib:format("Result of set large heap: ~p --> ~p", [OldLH, NewLH]); process_remote_command(_) -> throw(unknown_command). opt_type(watchdog_admins) -> fun (JIDs) -> [jid:tolower(jid:from_string(iolist_to_binary(S))) || S <- JIDs] end; opt_type(watchdog_large_heap) -> fun (I) when is_integer(I), I > 0 -> I end; opt_type(_) -> [watchdog_admins, watchdog_large_heap].
null
https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/src/ejabberd_system_monitor.erl
erlang
------------------------------------------------------------------- File : ejabberd_system_monitor.erl Description : Ejabberd watchdog This program is free software; you can redistribute it and/or License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------- API ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- --------------------------------------------------------------------
Author : < > Created : 21 Mar 2007 by < > ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . -module(ejabberd_system_monitor). -behaviour(ejabberd_config). -author(''). -behaviour(gen_server). -export([start_link/0, process_command/3, register_hook/1, process_remote_command/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, opt_type/1]). -include("ejabberd.hrl"). -include("logger.hrl"). -include("jlib.hrl"). -record(state, {}). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> LH = ejabberd_config:get_option( watchdog_large_heap, fun(I) when is_integer(I), I > 0 -> I end, 1000000), Opts = [{large_heap, LH}], gen_server:start_link({local, ?MODULE}, ?MODULE, Opts, []). process_command(From, To, Packet) -> case To of #jid{luser = <<"">>, lresource = <<"watchdog">>} -> #xmlel{name = Name} = Packet, case Name of <<"message">> -> LFrom = jid:tolower(jid:remove_resource(From)), case lists:member(LFrom, get_admin_jids()) of true -> Body = fxml:get_path_s(Packet, [{elem, <<"body">>}, cdata]), spawn(fun () -> process_flag(priority, high), process_command1(From, To, Body) end), stop; false -> ok end; _ -> ok end; _ -> ok end. register_hook(Host) -> ejabberd_hooks:add(local_send_to_resource_hook, Host, ?MODULE, process_command, 50). { ok , State , Timeout } | init(Opts) -> LH = proplists:get_value(large_heap, Opts), process_flag(priority, high), erlang:system_monitor(self(), [{large_heap, LH}]), lists:foreach(fun register_hook/1, ?MYHOSTS), {ok, #state{}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({get, large_heap}, _From, State) -> {reply, get_large_heap(), State}; handle_call({set, large_heap, NewValue}, _From, State) -> MonSettings = erlang:system_monitor(self(), [{large_heap, NewValue}]), OldLH = get_large_heap(MonSettings), NewLH = get_large_heap(), {reply, {lh_changed, OldLH, NewLH}, State}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State}. get_large_heap() -> MonSettings = erlang:system_monitor(), get_large_heap(MonSettings). get_large_heap(MonSettings) -> {_MonitorPid, Options} = MonSettings, proplists:get_value(large_heap, Options). Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info({monitor, Pid, large_heap, Info}, State) -> spawn(fun () -> process_flag(priority, high), process_large_heap(Pid, Info) end), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions process_large_heap(Pid, Info) -> Host = (?MYNAME), JIDs = get_admin_jids(), DetailedInfo = detailed_info(Pid), Body = iolist_to_binary( io_lib:format("(~w) The process ~w is consuming too " "much memory:~n~p~n~s", [node(), Pid, Info, DetailedInfo])), From = jid:make(<<"">>, Host, <<"watchdog">>), Hint = [#xmlel{name = <<"no-permanent-store">>, attrs = [{<<"xmlns">>, ?NS_HINTS}]}], lists:foreach(fun (JID) -> send_message(From, jid:make(JID), Body, Hint) end, JIDs). send_message(From, To, Body) -> send_message(From, To, Body, []). send_message(From, To, Body, ExtraEls) -> ejabberd_router:route(From, To, #xmlel{name = <<"message">>, attrs = [{<<"type">>, <<"chat">>}], children = [#xmlel{name = <<"body">>, attrs = [], children = [{xmlcdata, Body}]} | ExtraEls]}). get_admin_jids() -> ejabberd_config:get_option( watchdog_admins, fun(JIDs) -> [jid:tolower( jid:from_string( iolist_to_binary(S))) || S <- JIDs] end, []). detailed_info(Pid) -> case process_info(Pid, dictionary) of {dictionary, Dict} -> case lists:keysearch('$ancestors', 1, Dict) of {value, {'$ancestors', [Sup | _]}} -> case Sup of ejabberd_c2s_sup -> c2s_info(Pid); ejabberd_s2s_out_sup -> s2s_out_info(Pid); ejabberd_service_sup -> service_info(Pid); _ -> detailed_info1(Pid) end; _ -> detailed_info1(Pid) end; _ -> detailed_info1(Pid) end. detailed_info1(Pid) -> io_lib:format("~p", [[process_info(Pid, current_function), process_info(Pid, initial_call), process_info(Pid, message_queue_len), process_info(Pid, links), process_info(Pid, dictionary), process_info(Pid, heap_size), process_info(Pid, stack_size)]]). c2s_info(Pid) -> [<<"Process type: c2s">>, check_send_queue(Pid), <<"\n">>, io_lib:format("Command to kill this process: kill ~s ~w", [iolist_to_binary(atom_to_list(node())), Pid])]. s2s_out_info(Pid) -> FromTo = mnesia:dirty_select(s2s, [{{s2s, '$1', Pid, '_'}, [], ['$1']}]), [<<"Process type: s2s_out">>, case FromTo of [{From, To}] -> <<"\n", (io_lib:format("S2S connection: from ~s to ~s", [From, To]))/binary>>; _ -> <<"">> end, check_send_queue(Pid), <<"\n">>, io_lib:format("Command to kill this process: kill ~s ~w", [iolist_to_binary(atom_to_list(node())), Pid])]. service_info(Pid) -> Routes = mnesia:dirty_select(route, [{{route, '$1', Pid, '_'}, [], ['$1']}]), [<<"Process type: s2s_out">>, case Routes of [Route] -> <<"\nServiced domain: ", Route/binary>>; _ -> <<"">> end, check_send_queue(Pid), <<"\n">>, io_lib:format("Command to kill this process: kill ~s ~w", [iolist_to_binary(atom_to_list(node())), Pid])]. check_send_queue(Pid) -> case {process_info(Pid, current_function), process_info(Pid, message_queue_len)} of {{current_function, MFA}, {message_queue_len, MLen}} -> if MLen > 100 -> case MFA of {prim_inet, send, 2} -> <<"\nPossible reason: the process is blocked " "trying to send data over its TCP connection.">>; {M, F, A} -> [<<"\nPossible reason: the process can't " "process messages faster than they arrive. ">>, io_lib:format("Current function is ~w:~w/~w", [M, F, A])] end; true -> <<"">> end; _ -> <<"">> end. process_command1(From, To, Body) -> process_command2(str:tokens(Body, <<" ">>), From, To). process_command2([<<"kill">>, SNode, SPid], From, To) -> Node = jlib:binary_to_atom(SNode), remote_command(Node, [kill, SPid], From, To); process_command2([<<"showlh">>, SNode], From, To) -> Node = jlib:binary_to_atom(SNode), remote_command(Node, [showlh], From, To); process_command2([<<"setlh">>, SNode, NewValueString], From, To) -> Node = jlib:binary_to_atom(SNode), NewValue = jlib:binary_to_integer(NewValueString), remote_command(Node, [setlh, NewValue], From, To); process_command2([<<"help">>], From, To) -> send_message(To, From, help()); process_command2(_, From, To) -> send_message(To, From, help()). help() -> <<"Commands:\n kill <node> <pid>\n showlh " "<node>\n setlh <node> <integer>">>. remote_command(Node, Args, From, To) -> Message = case ejabberd_cluster:call(Node, ?MODULE, process_remote_command, [Args]) of {badrpc, Reason} -> io_lib:format("Command failed:~n~p", [Reason]); Result -> Result end, send_message(To, From, iolist_to_binary(Message)). process_remote_command([kill, SPid]) -> exit(list_to_pid(SPid), kill), <<"ok">>; process_remote_command([showlh]) -> Res = gen_server:call(ejabberd_system_monitor, {get, large_heap}), io_lib:format("Current large heap: ~p", [Res]); process_remote_command([setlh, NewValue]) -> {lh_changed, OldLH, NewLH} = gen_server:call(ejabberd_system_monitor, {set, large_heap, NewValue}), io_lib:format("Result of set large heap: ~p --> ~p", [OldLH, NewLH]); process_remote_command(_) -> throw(unknown_command). opt_type(watchdog_admins) -> fun (JIDs) -> [jid:tolower(jid:from_string(iolist_to_binary(S))) || S <- JIDs] end; opt_type(watchdog_large_heap) -> fun (I) when is_integer(I), I > 0 -> I end; opt_type(_) -> [watchdog_admins, watchdog_large_heap].
91bbc38017fc88bb12038abd80b1c4e65798cce5a63a4c2baee4de264643e6c5
unnohideyuki/bunny
sample334.hs
f x = case x of 0 -> "zero" _ -> "non-zero" main = do putStrLn $ f 1 putStrLn $ f 0 putStrLn $ f (1::Int) putStrLn $ f (0::Integer) putStrLn $ f (1.0::Double) putStrLn $ f (0.0::Float)
null
https://raw.githubusercontent.com/unnohideyuki/bunny/f01735ac55b40f977f1c5055919e16b97aa1bf13/compiler/test/samples/sample334.hs
haskell
f x = case x of 0 -> "zero" _ -> "non-zero" main = do putStrLn $ f 1 putStrLn $ f 0 putStrLn $ f (1::Int) putStrLn $ f (0::Integer) putStrLn $ f (1.0::Double) putStrLn $ f (0.0::Float)
bec4d1c1ef6ebaf546f64c07b487b187c99a3ed9f5a58b326779fb07e4b1a00b
ucsd-progsys/nate
taquin.ml
(***********************************************************************) (* *) MLTk , Tcl / Tk interface of Objective Caml (* *) , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS (* *) Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking (* described in file LICENSE found in the Objective Caml source tree. *) (* *) (***********************************************************************) $ I d : taquin.ml , v 1.2 2002/04/26 12:15:59 furuse Exp $ open Tk;; let découpe_image img nx ny = let l = Imagephoto.width img and h = Imagephoto.height img in let tx = l / nx and ty = h / ny in let pièces = ref [] in for x = 0 to nx - 1 do for y = 0 to ny - 1 do let pièce = Imagephoto.create ~width:tx ~height:ty () in Imagephoto.copy ~src:img ~src_area:(x * tx, y * ty, (x + 1) * tx, (y + 1) * ty) pièce; pièces := pièce :: !pièces done done; (tx, ty, List.tl !pièces);; let remplir_taquin c nx ny tx ty pièces = let trou_x = ref (nx - 1) and trou_y = ref (ny - 1) in let trou = Canvas.create_rectangle ~x1:(!trou_x * tx) ~y1:(!trou_y * ty) ~x2:tx ~y2:ty c in let taquin = Array.make_matrix nx ny trou in let p = ref pièces in for x = 0 to nx - 1 do for y = 0 to ny - 1 do match !p with | [] -> () | pièce :: reste -> taquin.(x).(y) <- Canvas.create_image ~x:(x * tx) ~y:(y * ty) ~image:pièce ~anchor:`Nw ~tags:["pièce"] c; p := reste done done; let déplacer x y = let pièce = taquin.(x).(y) in Canvas.coords_set c pièce ~xys:[!trou_x * tx, !trou_y * ty]; Canvas.coords_set c trou ~xys:[x * tx, y * ty; tx, ty]; taquin.(!trou_x).(!trou_y) <- pièce; taquin.(x).(y) <- trou; trou_x := x; trou_y := y in let jouer ei = let x = ei.ev_MouseX / tx and y = ei.ev_MouseY / ty in if x = !trou_x && (y = !trou_y - 1 || y = !trou_y + 1) || y = !trou_y && (x = !trou_x - 1 || x = !trou_x + 1) then déplacer x y in Canvas.bind ~events:[`ButtonPress] ~fields:[`MouseX; `MouseY] ~action:jouer c (`Tag "pièce");; let rec permutation = function | [] -> [] | l -> let n = Random.int (List.length l) in let (élément, reste) = partage l n in élément :: permutation reste and partage l n = match l with | [] -> failwith "partage" | tête :: reste -> if n = 0 then (tête, reste) else let (élément, reste') = partage reste (n - 1) in (élément, tête :: reste');; let create_filled_text parent lines = let lnum = List.length lines and lwidth = List.fold_right (fun line max -> let l = String.length line in if l > max then l else max) lines 1 in let txtw = Text.create ~width:lwidth ~height:lnum parent in List.iter (fun line -> Text.insert ~index:(`End, []) ~text:line txtw; Text.insert ~index:(`End, []) ~text:"\n" txtw) lines; txtw;; let give_help parent lines () = let help_window = Toplevel.create parent in Wm.title_set help_window "Help"; let help_frame = Frame.create help_window in let help_txtw = create_filled_text help_frame lines in let quit_help () = destroy help_window in let ok_button = Button.create ~text:"Ok" ~command:quit_help help_frame in pack ~side:`Bottom [help_txtw]; pack ~side:`Bottom [ok_button ]; pack [help_frame];; let taquin nom_fichier nx ny = let fp = openTk () in Wm.title_set fp "Taquin"; let img = Imagephoto.create ~file:nom_fichier () in let c = Canvas.create ~background:`Black ~width:(Imagephoto.width img) ~height:(Imagephoto.height img) fp in let (tx, ty, pièces) = découpe_image img nx ny in remplir_taquin c nx ny tx ty (permutation pièces); pack [c]; let quit = Button.create ~text:"Quit" ~command:closeTk fp in let help_lines = ["Pour jouer, cliquer sur une des pièces"; "entourant le trou"; ""; "To play, click on a part around the hole"] in let help = Button.create ~text:"Help" ~command:(give_help fp help_lines) fp in pack ~side:`Left ~fill:`X [quit] ; pack ~side:`Left ~fill:`X [help] ; mainLoop ();; if !Sys.interactive then () else begin taquin "Lambda2.back.gif" 4 4; exit 0 end;;
null
https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/otherlibs/labltk/examples_labltk/taquin.ml
ocaml
********************************************************************* described in file LICENSE found in the Objective Caml source tree. *********************************************************************
MLTk , Tcl / Tk interface of Objective Caml , , and projet Cristal , INRIA Rocquencourt , Kyoto University RIMS Copyright 2002 Institut National de Recherche en Informatique et en Automatique and Kyoto University . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with the special exception on linking $ I d : taquin.ml , v 1.2 2002/04/26 12:15:59 furuse Exp $ open Tk;; let découpe_image img nx ny = let l = Imagephoto.width img and h = Imagephoto.height img in let tx = l / nx and ty = h / ny in let pièces = ref [] in for x = 0 to nx - 1 do for y = 0 to ny - 1 do let pièce = Imagephoto.create ~width:tx ~height:ty () in Imagephoto.copy ~src:img ~src_area:(x * tx, y * ty, (x + 1) * tx, (y + 1) * ty) pièce; pièces := pièce :: !pièces done done; (tx, ty, List.tl !pièces);; let remplir_taquin c nx ny tx ty pièces = let trou_x = ref (nx - 1) and trou_y = ref (ny - 1) in let trou = Canvas.create_rectangle ~x1:(!trou_x * tx) ~y1:(!trou_y * ty) ~x2:tx ~y2:ty c in let taquin = Array.make_matrix nx ny trou in let p = ref pièces in for x = 0 to nx - 1 do for y = 0 to ny - 1 do match !p with | [] -> () | pièce :: reste -> taquin.(x).(y) <- Canvas.create_image ~x:(x * tx) ~y:(y * ty) ~image:pièce ~anchor:`Nw ~tags:["pièce"] c; p := reste done done; let déplacer x y = let pièce = taquin.(x).(y) in Canvas.coords_set c pièce ~xys:[!trou_x * tx, !trou_y * ty]; Canvas.coords_set c trou ~xys:[x * tx, y * ty; tx, ty]; taquin.(!trou_x).(!trou_y) <- pièce; taquin.(x).(y) <- trou; trou_x := x; trou_y := y in let jouer ei = let x = ei.ev_MouseX / tx and y = ei.ev_MouseY / ty in if x = !trou_x && (y = !trou_y - 1 || y = !trou_y + 1) || y = !trou_y && (x = !trou_x - 1 || x = !trou_x + 1) then déplacer x y in Canvas.bind ~events:[`ButtonPress] ~fields:[`MouseX; `MouseY] ~action:jouer c (`Tag "pièce");; let rec permutation = function | [] -> [] | l -> let n = Random.int (List.length l) in let (élément, reste) = partage l n in élément :: permutation reste and partage l n = match l with | [] -> failwith "partage" | tête :: reste -> if n = 0 then (tête, reste) else let (élément, reste') = partage reste (n - 1) in (élément, tête :: reste');; let create_filled_text parent lines = let lnum = List.length lines and lwidth = List.fold_right (fun line max -> let l = String.length line in if l > max then l else max) lines 1 in let txtw = Text.create ~width:lwidth ~height:lnum parent in List.iter (fun line -> Text.insert ~index:(`End, []) ~text:line txtw; Text.insert ~index:(`End, []) ~text:"\n" txtw) lines; txtw;; let give_help parent lines () = let help_window = Toplevel.create parent in Wm.title_set help_window "Help"; let help_frame = Frame.create help_window in let help_txtw = create_filled_text help_frame lines in let quit_help () = destroy help_window in let ok_button = Button.create ~text:"Ok" ~command:quit_help help_frame in pack ~side:`Bottom [help_txtw]; pack ~side:`Bottom [ok_button ]; pack [help_frame];; let taquin nom_fichier nx ny = let fp = openTk () in Wm.title_set fp "Taquin"; let img = Imagephoto.create ~file:nom_fichier () in let c = Canvas.create ~background:`Black ~width:(Imagephoto.width img) ~height:(Imagephoto.height img) fp in let (tx, ty, pièces) = découpe_image img nx ny in remplir_taquin c nx ny tx ty (permutation pièces); pack [c]; let quit = Button.create ~text:"Quit" ~command:closeTk fp in let help_lines = ["Pour jouer, cliquer sur une des pièces"; "entourant le trou"; ""; "To play, click on a part around the hole"] in let help = Button.create ~text:"Help" ~command:(give_help fp help_lines) fp in pack ~side:`Left ~fill:`X [quit] ; pack ~side:`Left ~fill:`X [help] ; mainLoop ();; if !Sys.interactive then () else begin taquin "Lambda2.back.gif" 4 4; exit 0 end;;
7ffeaee4a52452ba948010a7ba89438e7a7f932e87531748fac845d2cb4d2c8c
evturn/programming-in-haskell
13.08-arithmetic-expressions.hs
import Control.Applicative import Data.Char newtype Parser a = P (String -> [(a, String)]) ----------------------------------------------------------------------------- -- expr ::= term (+ expr | ∊) -- term ::= factor (* term | ∊) factor : : = ( expr ) | nat -- nat ::= 0 | 1 | 2 | ... ----------------------------------------------------------------------------- expr :: Parser Int expr = do t <- term do symbol "+" e <- expr return (t + e) <|> return t term :: Parser Int term = do f <- factor do symbol "*" t <- term return (f * t) <|> return f factor :: Parser Int factor = do symbol "(" e <- expr symbol ")" return e <|> natural eval :: String -> Int eval xs = case (parse expr xs) of [(n, [])] -> n [(_, out)] -> error ("Unused input " ++ out) [] -> error "Invalid input" parse :: Parser a -> String -> [(a, String)] parse (P p) inp = p inp item :: Parser Char item = P $ \inp -> case inp of [] -> [] (x:xs) -> [(x, xs)] sat :: (Char -> Bool) -> Parser Char sat p = do x <- item if p x then return x else empty digit :: Parser Char digit = sat isDigit lower :: Parser Char lower = sat isLower upper :: Parser Char upper = sat isUpper letter :: Parser Char letter = sat isAlpha alphanum :: Parser Char alphanum = sat isAlphaNum char :: Char -> Parser Char char x = sat (== x) string :: String -> Parser String string [] = return [] string (x:xs) = do char x string xs return (x:xs) ident :: Parser String ident = do x <- lower xs <- many alphanum return (x:xs) nat :: Parser Int nat = do xs <- some digit return (read xs) space :: Parser () space = do many (sat isSpace) return () int :: Parser Int int = do char '-' n <- nat return (-n) <|> nat token :: Parser a -> Parser a token p = do space v <- p space return v identifier :: Parser String identifier = token ident natural :: Parser Int natural = token nat integer :: Parser Int integer = token int symbol :: String -> Parser String symbol xs = token (string xs) nats :: Parser [Int] nats = do symbol "[" n <- natural ns <- many $ do symbol "," natural symbol "]" return (n:ns) instance Functor Parser where fmap f p = P $ \inp -> case parse p inp of [] -> [] [(v, out)] -> [(f v, out)] instance Applicative Parser where pure v = P $ \inp -> [(v, inp)] pf <*> px = P $ \inp -> case parse pf inp of [] -> [] [(f, out)] -> parse (fmap f px) out instance Monad Parser where p >>= f = P $ \inp -> case parse p inp of [] -> [] [(v, out)] -> parse (f v) out instance Alternative Parser where empty = P $ \inp -> [] p <|> q = P $ \inp -> case parse p inp of [] -> parse q inp [(v, out)] -> [(v, out)]
null
https://raw.githubusercontent.com/evturn/programming-in-haskell/0af2c48c8221b5bcd052492e2be2b79635f6994c/13-monadic-parsing/13.08-arithmetic-expressions.hs
haskell
--------------------------------------------------------------------------- expr ::= term (+ expr | ∊) term ::= factor (* term | ∊) nat ::= 0 | 1 | 2 | ... ---------------------------------------------------------------------------
import Control.Applicative import Data.Char newtype Parser a = P (String -> [(a, String)]) factor : : = ( expr ) | nat expr :: Parser Int expr = do t <- term do symbol "+" e <- expr return (t + e) <|> return t term :: Parser Int term = do f <- factor do symbol "*" t <- term return (f * t) <|> return f factor :: Parser Int factor = do symbol "(" e <- expr symbol ")" return e <|> natural eval :: String -> Int eval xs = case (parse expr xs) of [(n, [])] -> n [(_, out)] -> error ("Unused input " ++ out) [] -> error "Invalid input" parse :: Parser a -> String -> [(a, String)] parse (P p) inp = p inp item :: Parser Char item = P $ \inp -> case inp of [] -> [] (x:xs) -> [(x, xs)] sat :: (Char -> Bool) -> Parser Char sat p = do x <- item if p x then return x else empty digit :: Parser Char digit = sat isDigit lower :: Parser Char lower = sat isLower upper :: Parser Char upper = sat isUpper letter :: Parser Char letter = sat isAlpha alphanum :: Parser Char alphanum = sat isAlphaNum char :: Char -> Parser Char char x = sat (== x) string :: String -> Parser String string [] = return [] string (x:xs) = do char x string xs return (x:xs) ident :: Parser String ident = do x <- lower xs <- many alphanum return (x:xs) nat :: Parser Int nat = do xs <- some digit return (read xs) space :: Parser () space = do many (sat isSpace) return () int :: Parser Int int = do char '-' n <- nat return (-n) <|> nat token :: Parser a -> Parser a token p = do space v <- p space return v identifier :: Parser String identifier = token ident natural :: Parser Int natural = token nat integer :: Parser Int integer = token int symbol :: String -> Parser String symbol xs = token (string xs) nats :: Parser [Int] nats = do symbol "[" n <- natural ns <- many $ do symbol "," natural symbol "]" return (n:ns) instance Functor Parser where fmap f p = P $ \inp -> case parse p inp of [] -> [] [(v, out)] -> [(f v, out)] instance Applicative Parser where pure v = P $ \inp -> [(v, inp)] pf <*> px = P $ \inp -> case parse pf inp of [] -> [] [(f, out)] -> parse (fmap f px) out instance Monad Parser where p >>= f = P $ \inp -> case parse p inp of [] -> [] [(v, out)] -> parse (f v) out instance Alternative Parser where empty = P $ \inp -> [] p <|> q = P $ \inp -> case parse p inp of [] -> parse q inp [(v, out)] -> [(v, out)]
fbbb5dcb9ceb1e5439ae692de93c36ebe37d66b5b2aac45db7907307cd55e663
ledger/ledger4
Setup.hs
import Distribution.Simple main = defaultMain
null
https://raw.githubusercontent.com/ledger/ledger4/0dd4d772dbd6a94ef83398e79e9acab2029a5a3a/commodities/Setup.hs
haskell
import Distribution.Simple main = defaultMain
28ae3ce063811bad28ae6aad168b7b45b5217e61a5d2762ad044bfd27af37b30
Eonblast/Scalaxis
merkle_tree.erl
2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > @doc tree implementation %% with configurable bucketing, branching and hashing. %% Underlaying tree structure is an n-ary tree. %% After calling gen_hashes the tree is ready to use and sealed. %% @end %% @version $Id$ -module(merkle_tree). -include("record_helpers.hrl"). -include("scalaris.hrl"). -export([new/1, new/2, insert/3, empty/0, lookup/2, size/1, size_detail/1, gen_hash/1, iterator/1, next/1, is_empty/1, is_leaf/1, get_bucket/1, is_merkle_tree/1, get_hash/1, get_interval/1, get_childs/1, get_root/1, get_bucket_size/1, get_branch_factor/1, store_to_DOT/1]). -ifdef(with_export_type_support). -export_type([mt_config/0, merkle_tree/0, mt_node/0, mt_node_key/0, mt_size/0]). -export_type([mt_iter/0]). -endif. -define(TRACE(X , Y ) , io : : [ ~p ] " + + X + + " ~n " , [ ? MODULE , self ( ) ] + + Y ) ) . -define(TRACE(X,Y), ok). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Types %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -type mt_node_key() :: binary() | nil. -type mt_interval() :: intervals:interval(). -type mt_bucket() :: orddict:orddict() | nil. -type mt_size() :: {InnerNodes::non_neg_integer(), Leafs::non_neg_integer()}. -type hash_fun() :: fun((binary()) -> mt_node_key()). -type inner_hash_fun() :: fun(([mt_node_key()]) -> mt_node_key()). % INFO: on changes extend build_config function -record(mt_config, { branch_factor = 2 :: pos_integer(), %number of childs per inner node bucket_size = 24 :: pos_integer(), %max items in a leaf leaf_hf = fun crypto:sha/1 :: hash_fun(), %hash function for leaf signature creation inner_hf = get_XOR_fun() :: inner_hash_fun(),%hash function for inner node signature creation - gen_hash_on = value :: value | key %node hash will be generated on value or an key }). -type mt_config() :: #mt_config{}. -type mt_node() :: { Hash :: mt_node_key(), %hash of childs/containing items Count :: non_neg_integer(), %in inner nodes number of subnodes, in leaf nodes number of items in the bucket Bucket :: mt_bucket(), %item storage Interval :: mt_interval(), %represented interval Child_list :: [mt_node()] }. -type mt_iter() :: [mt_node()]. -type merkle_tree() :: {merkle_tree, mt_config(), Root::mt_node()}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_bucket_size(merkle_tree()) -> pos_integer(). get_bucket_size({merkle_tree, Config, _}) -> Config#mt_config.bucket_size. -spec get_branch_factor(merkle_tree()) -> pos_integer(). get_branch_factor({merkle_tree, Config, _}) -> Config#mt_config.branch_factor. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_root(merkle_tree()) -> mt_node() | undefined. get_root({merkle_tree, _, Root}) -> Root; get_root(_) -> undefined. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @doc Insert on an empty tree fail . First operation on an empty tree should be set_interval . % Returns an empty merkle tree ready for work. -spec empty() -> merkle_tree(). empty() -> {merkle_tree, #mt_config{}, {nil, 0, nil, intervals:empty(), []}}. -spec is_empty(merkle_tree()) -> boolean(). is_empty({merkle_tree, _, {nil, 0, nil, I, []}}) -> intervals:is_empty(I); is_empty(_) -> false. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec new(mt_interval()) -> merkle_tree(). new(Interval) -> {merkle_tree, #mt_config{}, {nil, 0, orddict:new(), Interval, []}}. % @doc ConfParams = list of tuples defined by {config field name, value} e.g. [ { branch_factor , 32 } , { bucket_size , 16 } ] -spec new(mt_interval(), [{atom(), term()}]) -> merkle_tree(). new(Interval, ConfParams) -> {merkle_tree, build_config(ConfParams), {nil, 0, orddict:new(), Interval, []}}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec lookup(Interval, TreeObj) -> Node | not_found when is_subtype(Interval, mt_interval()), is_subtype(TreeObj, merkle_tree() | mt_node()), is_subtype(Node, mt_node()). lookup(I, {merkle_tree, _, Root}) -> lookup(I, Root); lookup(I, {_, _, _, I, _} = Node) -> Node; lookup(I, {_, _, _, NodeI, ChildList} = Node) -> case intervals:is_subset(I, NodeI) of true when length(ChildList) =:= 0 -> Node; true -> IChilds = lists:filter(fun({_, _, _, CI, _}) -> intervals:is_subset(I, CI) end, ChildList), case length(IChilds) of 0 -> not_found; 1 -> [IChild] = IChilds, lookup(I, IChild); _ -> error_logger:error_msg("tree interval not correct splitted") end; false -> not_found end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_hash(merkle_tree() | mt_node()) -> mt_node_key(). get_hash({merkle_tree, _, Node}) -> get_hash(Node); get_hash({Hash, _, _, _, _}) -> Hash. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_interval(merkle_tree() | mt_node()) -> intervals:interval(). get_interval({merkle_tree, _, Node}) -> get_interval(Node); get_interval({_, _, _, I, _}) -> I. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_childs(merkle_tree() | mt_node()) -> [mt_node()]. get_childs({merkle_tree, _, Node}) -> get_childs(Node); get_childs({_, _, _, _, Childs}) -> Childs. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec is_leaf(merkle_tree() | mt_node()) -> boolean(). is_leaf({merkle_tree, _, Node}) -> is_leaf(Node); is_leaf({_, _, _, _, []}) -> true; is_leaf(_) -> false. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc Returns true if given term is a merkle tree otherwise false. -spec is_merkle_tree(term()) -> boolean(). is_merkle_tree(Tree) when erlang:is_tuple(Tree) -> erlang:element(1, Tree) =:= merkle_tree; is_merkle_tree(_) -> false. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec get_bucket(merkle_tree() | mt_node()) -> [{Key::term(), Value::term()}]. get_bucket({merkle_tree, _, Root}) -> get_bucket(Root); get_bucket({_, C, Bucket, _, []}) when C > 0 -> orddict:to_list(Bucket); get_bucket(_) -> []. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec insert(Key::term(), Val::term(), merkle_tree()) -> merkle_tree(). insert(Key, Val, {merkle_tree, Config, Root} = Tree) -> case intervals:in(Key, get_interval(Root)) of true -> Changed = insert_to_node(Key, Val, Root, Config), {merkle_tree, Config, Changed}; false -> Tree end. -spec insert_to_node(Key, Val, Node, Config) -> NewNode when is_subtype(Key, term()), is_subtype(Val, term()), is_subtype(Node, mt_node()), is_subtype(Config, mt_config()), is_subtype(NewNode, mt_node()). insert_to_node(Key, Val, {Hash, Count, Bucket, Interval, []} = Node, Config) when Count >= 0 andalso Count < Config#mt_config.bucket_size -> case orddict:is_key(Key, Bucket) of true -> Node; false -> {Hash, Count + 1, orddict:store(Key, Val, Bucket), Interval, []} end; insert_to_node(Key, Val, {_, Count, Bucket, Interval, []}, Config) when Count =:= Config#mt_config.bucket_size -> ChildI = intervals:split(Interval, Config#mt_config.branch_factor), NewLeafs = lists:map(fun(I) -> NewBucket = orddict:filter(fun(K, _) -> intervals:in(K, I) end, Bucket), {nil, orddict:size(NewBucket), NewBucket, I, []} end, ChildI), insert_to_node(Key, Val, {nil, 1 + Config#mt_config.branch_factor, nil, Interval, NewLeafs}, Config); insert_to_node(Key, Val, {Hash, Count, nil, Interval, Childs} = Node, Config) -> {_Dest, Rest} = lists:partition(fun({_, _, _, I, _}) -> intervals:in(Key, I) end, Childs), case length(_Dest) =:= 0 of true -> error_logger:error_msg("InsertFailed: No free slots in Merkle_Tree!"), Node; false -> Dest = hd(_Dest), OldSize = node_size(Dest), NewDest = insert_to_node(Key, Val, Dest, Config), {Hash, Count + (node_size(NewDest) - OldSize), nil, Interval, [NewDest|Rest]} end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -spec gen_hash(merkle_tree()) -> merkle_tree(). gen_hash({merkle_tree, Config, Root}) -> {merkle_tree, Config, gen_hash_node(Root, Config)}. -spec gen_hash_node(Node, Config) -> Node2 when is_subtype(Node, mt_node()), is_subtype(Config, mt_config()), is_subtype(Node2, mt_node()). gen_hash_node({_, Count, Bucket, I, []}, Config = #mt_config{ gen_hash_on = HashProp }) -> LeafHf = Config#mt_config.leaf_hf, Hash = case Count > 0 of true -> ToHash = case HashProp of key -> orddict:fetch_keys(Bucket); value -> lists:map(fun({_, V}) -> V end, orddict:to_list(Bucket)) end, LeafHf(erlang:term_to_binary(ToHash)); _ -> LeafHf(term_to_binary(0)) end, {Hash, Count, Bucket, I, []}; gen_hash_node({_, Count, nil, I, List}, Config) -> NewChilds = lists:map(fun(X) -> gen_hash_node(X, Config) end, List), InnerHf = Config#mt_config.inner_hf, Hash = InnerHf(lists:map(fun({H, _, _, _, _}) -> H end, NewChilds)), {Hash, Count, nil, I, NewChilds}. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc Returns the total number of nodes in a tree or node (inner nodes and leafs) -spec size(merkle_tree() | mt_node()) -> non_neg_integer(). size({merkle_tree, _, Root}) -> node_size(Root); size(Node) -> node_size(Node). -spec node_size(mt_node()) -> non_neg_integer(). node_size({_, _, _, _, []}) -> 1; node_size({_, C, _, _, _}) -> C. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc Returns a tuple with number of inner nodes and leaf nodes. -spec size_detail(merkle_tree()) -> mt_size(). size_detail({merkle_tree, _, Root}) -> size_detail_node(Root, {0, 0}). -spec size_detail_node(mt_node(), mt_size()) -> mt_size(). size_detail_node({_, _, _, _, []}, {Inner, Leafs}) -> {Inner, Leafs + 1}; size_detail_node({_, _, _, _, Childs}, {Inner, Leafs}) -> lists:foldl(fun(Node, {I, L}) -> size_detail_node(Node, {I, L}) end, {Inner + 1, Leafs}, Childs). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % @doc Returns an iterator to visit all tree nodes with next Iterates over all tree nodes from left to right in a deep first manner . -spec iterator(Tree) -> Iter when is_subtype(Tree, merkle_tree()), is_subtype(Iter, mt_iter()). iterator({merkle_tree, _, Root}) -> [Root]. -spec iterator_node(Node, Iter1) -> Iter2 when is_subtype(Node, mt_node()), is_subtype(Iter1, mt_iter()), is_subtype(Iter2, mt_iter()). iterator_node({_, _, _, _, []}, Iter1) -> Iter1; iterator_node({_, _, _, _, Childs}, Iter1) -> lists:flatten([Childs | Iter1]). -spec next(Iter1) -> none | {Node, Iter2} when is_subtype(Iter1, mt_iter()), is_subtype(Node, mt_node()), is_subtype(Iter2, mt_iter()). next([Node | Rest]) -> {Node, iterator_node(Node, Rest)}; next([]) -> none. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @doc Stores the tree graph into a file in DOT language ( for Graphviz or other visualization tools ) . -spec store_to_DOT(merkle_tree()) -> ok. store_to_DOT(MerkleTree) -> erlang:spawn(fun() -> store_to_DOT_p(MerkleTree) end), ok. store_to_DOT_p({merkle_tree, Conf, Root}) -> case file:open("../merkle_tree-graph.dot", [write]) of {ok, Fileid} -> io:fwrite(Fileid, "digraph merkle_tree { ~n", []), io:fwrite(Fileid, " style=filled;~n", []), store_node_to_DOT(Root, Fileid, 1, 2, Conf), io:fwrite(Fileid, "} ~n", []), _ = file:close(Fileid), ok; {_, _} -> io_error end. -spec store_node_to_DOT(mt_node(), pid(), pos_integer(), pos_integer(), mt_config()) -> pos_integer(). store_node_to_DOT({_, C, _, I, []}, Fileid, MyId, NextFreeId, #mt_config{ bucket_size = BuckSize }) -> {LBr, LKey, RKey, RBr} = intervals:get_bounds(I), io:fwrite(Fileid, " ~p [label=\"~s~p,~p~s ; ~p/~p\", shape=box]~n", [MyId, erlang:atom_to_list(LBr), LKey, RKey, erlang:atom_to_list(RBr), C, BuckSize]), NextFreeId; store_node_to_DOT({_, _, _ , I, [_|RChilds] = Childs}, Fileid, MyId, NextFreeId, TConf) -> io:fwrite(Fileid, " ~p -> { ~p", [MyId, NextFreeId]), NNFreeId = lists:foldl(fun(_, Acc) -> io:fwrite(Fileid, ";~p", [Acc]), Acc + 1 end, NextFreeId + 1, RChilds), io:fwrite(Fileid, " }~n", []), {_, NNNFreeId} = lists:foldl(fun(Node, {NodeId, NextFree}) -> {NodeId + 1 , store_node_to_DOT(Node, Fileid, NodeId, NextFree, TConf)} end, {NextFreeId, NNFreeId}, Childs), {LBr, LKey, RKey, RBr} = intervals:get_bounds(I), io:fwrite(Fileid, " ~p [label=\"~s~p,~p~s\"""]", [MyId, erlang:atom_to_list(LBr), LKey, RKey, erlang:atom_to_list(RBr)]), NNNFreeId. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Local Functions -spec build_config([{atom(), term()}]) -> mt_config(). build_config(ParamList) -> lists:foldl(fun({Key, Val}, Conf) -> case Key of branch_factor -> Conf#mt_config{ branch_factor = Val }; bucket_size -> Conf#mt_config{ bucket_size = Val }; leaf_hf -> Conf#mt_config{ leaf_hf = Val }; inner_hf -> Conf#mt_config{ inner_hf = Val }; gen_hash_on -> Conf#mt_config{ gen_hash_on = Val } end end, #mt_config{}, ParamList). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% get_XOR_fun() -> (fun([H|T]) -> lists:foldl(fun(X, Acc) -> binary_xor(X, Acc) end, H, T) end). -spec binary_xor(binary(), binary()) -> binary(). binary_xor(A, B) -> Size = bit_size(A), <<X:Size>> = A, <<Y:Size>> = B, <<(X bxor Y):Size>>.
null
https://raw.githubusercontent.com/Eonblast/Scalaxis/10287d11428e627dca8c41c818745763b9f7e8d4/src/rrepair/merkle_tree.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. with configurable bucketing, branching and hashing. Underlaying tree structure is an n-ary tree. After calling gen_hashes the tree is ready to use and sealed. @end @version $Id$ Types INFO: on changes extend build_config function number of childs per inner node max items in a leaf hash function for leaf signature creation hash function for inner node signature creation - node hash will be generated on value or an key hash of childs/containing items in inner nodes number of subnodes, in leaf nodes number of items in the bucket item storage represented interval Returns an empty merkle tree ready for work. @doc ConfParams = list of tuples defined by {config field name, value} @doc Returns true if given term is a merkle tree otherwise false. @doc Returns the total number of nodes in a tree or node (inner nodes and leafs) @doc Returns a tuple with number of inner nodes and leaf nodes. @doc Returns an iterator to visit all tree nodes with next Local Functions
2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > @doc tree implementation -module(merkle_tree). -include("record_helpers.hrl"). -include("scalaris.hrl"). -export([new/1, new/2, insert/3, empty/0, lookup/2, size/1, size_detail/1, gen_hash/1, iterator/1, next/1, is_empty/1, is_leaf/1, get_bucket/1, is_merkle_tree/1, get_hash/1, get_interval/1, get_childs/1, get_root/1, get_bucket_size/1, get_branch_factor/1, store_to_DOT/1]). -ifdef(with_export_type_support). -export_type([mt_config/0, merkle_tree/0, mt_node/0, mt_node_key/0, mt_size/0]). -export_type([mt_iter/0]). -endif. -define(TRACE(X , Y ) , io : : [ ~p ] " + + X + + " ~n " , [ ? MODULE , self ( ) ] + + Y ) ) . -define(TRACE(X,Y), ok). -type mt_node_key() :: binary() | nil. -type mt_interval() :: intervals:interval(). -type mt_bucket() :: orddict:orddict() | nil. -type mt_size() :: {InnerNodes::non_neg_integer(), Leafs::non_neg_integer()}. -type hash_fun() :: fun((binary()) -> mt_node_key()). -type inner_hash_fun() :: fun(([mt_node_key()]) -> mt_node_key()). -record(mt_config, { }). -type mt_config() :: #mt_config{}. Child_list :: [mt_node()] }. -type mt_iter() :: [mt_node()]. -type merkle_tree() :: {merkle_tree, mt_config(), Root::mt_node()}. -spec get_bucket_size(merkle_tree()) -> pos_integer(). get_bucket_size({merkle_tree, Config, _}) -> Config#mt_config.bucket_size. -spec get_branch_factor(merkle_tree()) -> pos_integer(). get_branch_factor({merkle_tree, Config, _}) -> Config#mt_config.branch_factor. -spec get_root(merkle_tree()) -> mt_node() | undefined. get_root({merkle_tree, _, Root}) -> Root; get_root(_) -> undefined. @doc Insert on an empty tree fail . First operation on an empty tree should be set_interval . -spec empty() -> merkle_tree(). empty() -> {merkle_tree, #mt_config{}, {nil, 0, nil, intervals:empty(), []}}. -spec is_empty(merkle_tree()) -> boolean(). is_empty({merkle_tree, _, {nil, 0, nil, I, []}}) -> intervals:is_empty(I); is_empty(_) -> false. -spec new(mt_interval()) -> merkle_tree(). new(Interval) -> {merkle_tree, #mt_config{}, {nil, 0, orddict:new(), Interval, []}}. e.g. [ { branch_factor , 32 } , { bucket_size , 16 } ] -spec new(mt_interval(), [{atom(), term()}]) -> merkle_tree(). new(Interval, ConfParams) -> {merkle_tree, build_config(ConfParams), {nil, 0, orddict:new(), Interval, []}}. -spec lookup(Interval, TreeObj) -> Node | not_found when is_subtype(Interval, mt_interval()), is_subtype(TreeObj, merkle_tree() | mt_node()), is_subtype(Node, mt_node()). lookup(I, {merkle_tree, _, Root}) -> lookup(I, Root); lookup(I, {_, _, _, I, _} = Node) -> Node; lookup(I, {_, _, _, NodeI, ChildList} = Node) -> case intervals:is_subset(I, NodeI) of true when length(ChildList) =:= 0 -> Node; true -> IChilds = lists:filter(fun({_, _, _, CI, _}) -> intervals:is_subset(I, CI) end, ChildList), case length(IChilds) of 0 -> not_found; 1 -> [IChild] = IChilds, lookup(I, IChild); _ -> error_logger:error_msg("tree interval not correct splitted") end; false -> not_found end. -spec get_hash(merkle_tree() | mt_node()) -> mt_node_key(). get_hash({merkle_tree, _, Node}) -> get_hash(Node); get_hash({Hash, _, _, _, _}) -> Hash. -spec get_interval(merkle_tree() | mt_node()) -> intervals:interval(). get_interval({merkle_tree, _, Node}) -> get_interval(Node); get_interval({_, _, _, I, _}) -> I. -spec get_childs(merkle_tree() | mt_node()) -> [mt_node()]. get_childs({merkle_tree, _, Node}) -> get_childs(Node); get_childs({_, _, _, _, Childs}) -> Childs. -spec is_leaf(merkle_tree() | mt_node()) -> boolean(). is_leaf({merkle_tree, _, Node}) -> is_leaf(Node); is_leaf({_, _, _, _, []}) -> true; is_leaf(_) -> false. -spec is_merkle_tree(term()) -> boolean(). is_merkle_tree(Tree) when erlang:is_tuple(Tree) -> erlang:element(1, Tree) =:= merkle_tree; is_merkle_tree(_) -> false. -spec get_bucket(merkle_tree() | mt_node()) -> [{Key::term(), Value::term()}]. get_bucket({merkle_tree, _, Root}) -> get_bucket(Root); get_bucket({_, C, Bucket, _, []}) when C > 0 -> orddict:to_list(Bucket); get_bucket(_) -> []. -spec insert(Key::term(), Val::term(), merkle_tree()) -> merkle_tree(). insert(Key, Val, {merkle_tree, Config, Root} = Tree) -> case intervals:in(Key, get_interval(Root)) of true -> Changed = insert_to_node(Key, Val, Root, Config), {merkle_tree, Config, Changed}; false -> Tree end. -spec insert_to_node(Key, Val, Node, Config) -> NewNode when is_subtype(Key, term()), is_subtype(Val, term()), is_subtype(Node, mt_node()), is_subtype(Config, mt_config()), is_subtype(NewNode, mt_node()). insert_to_node(Key, Val, {Hash, Count, Bucket, Interval, []} = Node, Config) when Count >= 0 andalso Count < Config#mt_config.bucket_size -> case orddict:is_key(Key, Bucket) of true -> Node; false -> {Hash, Count + 1, orddict:store(Key, Val, Bucket), Interval, []} end; insert_to_node(Key, Val, {_, Count, Bucket, Interval, []}, Config) when Count =:= Config#mt_config.bucket_size -> ChildI = intervals:split(Interval, Config#mt_config.branch_factor), NewLeafs = lists:map(fun(I) -> NewBucket = orddict:filter(fun(K, _) -> intervals:in(K, I) end, Bucket), {nil, orddict:size(NewBucket), NewBucket, I, []} end, ChildI), insert_to_node(Key, Val, {nil, 1 + Config#mt_config.branch_factor, nil, Interval, NewLeafs}, Config); insert_to_node(Key, Val, {Hash, Count, nil, Interval, Childs} = Node, Config) -> {_Dest, Rest} = lists:partition(fun({_, _, _, I, _}) -> intervals:in(Key, I) end, Childs), case length(_Dest) =:= 0 of true -> error_logger:error_msg("InsertFailed: No free slots in Merkle_Tree!"), Node; false -> Dest = hd(_Dest), OldSize = node_size(Dest), NewDest = insert_to_node(Key, Val, Dest, Config), {Hash, Count + (node_size(NewDest) - OldSize), nil, Interval, [NewDest|Rest]} end. -spec gen_hash(merkle_tree()) -> merkle_tree(). gen_hash({merkle_tree, Config, Root}) -> {merkle_tree, Config, gen_hash_node(Root, Config)}. -spec gen_hash_node(Node, Config) -> Node2 when is_subtype(Node, mt_node()), is_subtype(Config, mt_config()), is_subtype(Node2, mt_node()). gen_hash_node({_, Count, Bucket, I, []}, Config = #mt_config{ gen_hash_on = HashProp }) -> LeafHf = Config#mt_config.leaf_hf, Hash = case Count > 0 of true -> ToHash = case HashProp of key -> orddict:fetch_keys(Bucket); value -> lists:map(fun({_, V}) -> V end, orddict:to_list(Bucket)) end, LeafHf(erlang:term_to_binary(ToHash)); _ -> LeafHf(term_to_binary(0)) end, {Hash, Count, Bucket, I, []}; gen_hash_node({_, Count, nil, I, List}, Config) -> NewChilds = lists:map(fun(X) -> gen_hash_node(X, Config) end, List), InnerHf = Config#mt_config.inner_hf, Hash = InnerHf(lists:map(fun({H, _, _, _, _}) -> H end, NewChilds)), {Hash, Count, nil, I, NewChilds}. -spec size(merkle_tree() | mt_node()) -> non_neg_integer(). size({merkle_tree, _, Root}) -> node_size(Root); size(Node) -> node_size(Node). -spec node_size(mt_node()) -> non_neg_integer(). node_size({_, _, _, _, []}) -> 1; node_size({_, C, _, _, _}) -> C. -spec size_detail(merkle_tree()) -> mt_size(). size_detail({merkle_tree, _, Root}) -> size_detail_node(Root, {0, 0}). -spec size_detail_node(mt_node(), mt_size()) -> mt_size(). size_detail_node({_, _, _, _, []}, {Inner, Leafs}) -> {Inner, Leafs + 1}; size_detail_node({_, _, _, _, Childs}, {Inner, Leafs}) -> lists:foldl(fun(Node, {I, L}) -> size_detail_node(Node, {I, L}) end, {Inner + 1, Leafs}, Childs). Iterates over all tree nodes from left to right in a deep first manner . -spec iterator(Tree) -> Iter when is_subtype(Tree, merkle_tree()), is_subtype(Iter, mt_iter()). iterator({merkle_tree, _, Root}) -> [Root]. -spec iterator_node(Node, Iter1) -> Iter2 when is_subtype(Node, mt_node()), is_subtype(Iter1, mt_iter()), is_subtype(Iter2, mt_iter()). iterator_node({_, _, _, _, []}, Iter1) -> Iter1; iterator_node({_, _, _, _, Childs}, Iter1) -> lists:flatten([Childs | Iter1]). -spec next(Iter1) -> none | {Node, Iter2} when is_subtype(Iter1, mt_iter()), is_subtype(Node, mt_node()), is_subtype(Iter2, mt_iter()). next([Node | Rest]) -> {Node, iterator_node(Node, Rest)}; next([]) -> none. @doc Stores the tree graph into a file in DOT language ( for Graphviz or other visualization tools ) . -spec store_to_DOT(merkle_tree()) -> ok. store_to_DOT(MerkleTree) -> erlang:spawn(fun() -> store_to_DOT_p(MerkleTree) end), ok. store_to_DOT_p({merkle_tree, Conf, Root}) -> case file:open("../merkle_tree-graph.dot", [write]) of {ok, Fileid} -> io:fwrite(Fileid, "digraph merkle_tree { ~n", []), io:fwrite(Fileid, " style=filled;~n", []), store_node_to_DOT(Root, Fileid, 1, 2, Conf), io:fwrite(Fileid, "} ~n", []), _ = file:close(Fileid), ok; {_, _} -> io_error end. -spec store_node_to_DOT(mt_node(), pid(), pos_integer(), pos_integer(), mt_config()) -> pos_integer(). store_node_to_DOT({_, C, _, I, []}, Fileid, MyId, NextFreeId, #mt_config{ bucket_size = BuckSize }) -> {LBr, LKey, RKey, RBr} = intervals:get_bounds(I), io:fwrite(Fileid, " ~p [label=\"~s~p,~p~s ; ~p/~p\", shape=box]~n", [MyId, erlang:atom_to_list(LBr), LKey, RKey, erlang:atom_to_list(RBr), C, BuckSize]), NextFreeId; store_node_to_DOT({_, _, _ , I, [_|RChilds] = Childs}, Fileid, MyId, NextFreeId, TConf) -> io:fwrite(Fileid, " ~p -> { ~p", [MyId, NextFreeId]), NNFreeId = lists:foldl(fun(_, Acc) -> io:fwrite(Fileid, ";~p", [Acc]), Acc + 1 end, NextFreeId + 1, RChilds), io:fwrite(Fileid, " }~n", []), {_, NNNFreeId} = lists:foldl(fun(Node, {NodeId, NextFree}) -> {NodeId + 1 , store_node_to_DOT(Node, Fileid, NodeId, NextFree, TConf)} end, {NextFreeId, NNFreeId}, Childs), {LBr, LKey, RKey, RBr} = intervals:get_bounds(I), io:fwrite(Fileid, " ~p [label=\"~s~p,~p~s\"""]", [MyId, erlang:atom_to_list(LBr), LKey, RKey, erlang:atom_to_list(RBr)]), NNNFreeId. -spec build_config([{atom(), term()}]) -> mt_config(). build_config(ParamList) -> lists:foldl(fun({Key, Val}, Conf) -> case Key of branch_factor -> Conf#mt_config{ branch_factor = Val }; bucket_size -> Conf#mt_config{ bucket_size = Val }; leaf_hf -> Conf#mt_config{ leaf_hf = Val }; inner_hf -> Conf#mt_config{ inner_hf = Val }; gen_hash_on -> Conf#mt_config{ gen_hash_on = Val } end end, #mt_config{}, ParamList). get_XOR_fun() -> (fun([H|T]) -> lists:foldl(fun(X, Acc) -> binary_xor(X, Acc) end, H, T) end). -spec binary_xor(binary(), binary()) -> binary(). binary_xor(A, B) -> Size = bit_size(A), <<X:Size>> = A, <<Y:Size>> = B, <<(X bxor Y):Size>>.
b02ef6ee1ecd9aa4008ebac817b9aedd1ffa9e7e1182e5ec53a688c2917090cd
wardle/concierge
nhs_number.clj
(ns com.eldrix.concierge.nhs-number) (defn valid? "Validate an NHS number using the modulus 11 algorithm. An NHS number should be 10 numeric digits with the tenth digit a check digit. The validation occurs thusly: 1. Multiply each of the first nine digits by a weighting factor (digit 1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2) 2. Add the results of each multiplication together 3. Divide total by 11, establish the remainder 4. Subtract the remainder from 11 to give the check digit 5. If result is 11, the check digit is 0 6. If result is 10, NHS number is invalid 7. Check remainder matches the check digit, if it does not NHS number is invalid" [^String nnn] (when (and (= 10 (count nnn)) (every? #(Character/isDigit ^char %) nnn)) (let [cd (- (int (.charAt nnn 9)) (int \0)) ;; the check digit digits (map #(- (int %) (int \0)) nnn) ;; convert string into integers the weights running from 10 down to 2 total (reduce + (map * digits weights)) ;; multiply and total c1 (- 11 (mod total 11)) ;; what we think should be the check digit corrective fix when result is 11 (= cd c2)))) (defn format-nnn "Formats an NHS number for display purposes into 'XXX XXX XXXX'" [^String nnn] (if-not (= 10 (count nnn)) nnn (str (subs nnn 0 3) " " (subs nnn 3 6) " " (subs nnn 6)))) (comment (valid? "1111111111") (use 'criterium.core) (format-nnn "1234567890") (bench (format-nnn "11111111111")))
null
https://raw.githubusercontent.com/wardle/concierge/bb738cbc775b2cfde1c3f6bc526cded1af300978/src/com/eldrix/concierge/nhs_number.clj
clojure
the check digit convert string into integers multiply and total what we think should be the check digit
(ns com.eldrix.concierge.nhs-number) (defn valid? "Validate an NHS number using the modulus 11 algorithm. An NHS number should be 10 numeric digits with the tenth digit a check digit. The validation occurs thusly: 1. Multiply each of the first nine digits by a weighting factor (digit 1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2) 2. Add the results of each multiplication together 3. Divide total by 11, establish the remainder 4. Subtract the remainder from 11 to give the check digit 5. If result is 11, the check digit is 0 6. If result is 10, NHS number is invalid 7. Check remainder matches the check digit, if it does not NHS number is invalid" [^String nnn] (when (and (= 10 (count nnn)) (every? #(Character/isDigit ^char %) nnn)) the weights running from 10 down to 2 corrective fix when result is 11 (= cd c2)))) (defn format-nnn "Formats an NHS number for display purposes into 'XXX XXX XXXX'" [^String nnn] (if-not (= 10 (count nnn)) nnn (str (subs nnn 0 3) " " (subs nnn 3 6) " " (subs nnn 6)))) (comment (valid? "1111111111") (use 'criterium.core) (format-nnn "1234567890") (bench (format-nnn "11111111111")))
8f6563122292130c757026ec34689c5062b6312d2e5b86ecbc694f755e000c78
keera-studios/keera-hails
AppDataBasic.hs
{-# LANGUAGE DeriveDataTypeable #-} -- | -- Copyright : ( C ) Keera Studios Ltd , 2013 -- License : BSD3 Maintainer : module AppDataBasic where import Data.Data import Data.Default import Data . Typeable -- This is the CLI app definition : what we get from the user data AppDataBasic = AppDataBasic { action :: HailsAction , outputDir :: Maybe FilePath , overwrite :: Bool } deriving (Show, Data, Typeable) data HailsAction = HailsInit | HailsClean deriving (Show, Data, Typeable) instance Default HailsAction where def = HailsInit
null
https://raw.githubusercontent.com/keera-studios/keera-hails/bf069e5aafc85a1f55fa119ae45a025a2bd4a3d0/keera-hails/src/AppDataBasic.hs
haskell
# LANGUAGE DeriveDataTypeable # | License : BSD3 This is the CLI app definition : what we get from the user
Copyright : ( C ) Keera Studios Ltd , 2013 Maintainer : module AppDataBasic where import Data.Data import Data.Default import Data . Typeable data AppDataBasic = AppDataBasic { action :: HailsAction , outputDir :: Maybe FilePath , overwrite :: Bool } deriving (Show, Data, Typeable) data HailsAction = HailsInit | HailsClean deriving (Show, Data, Typeable) instance Default HailsAction where def = HailsInit
542e846c9fdb6f62a5d0f9d5bde332a565e16328effd69d5c4008bd35db2c6c8
mariari/Misc-ML-Scripts
shunt.hs
# LANGUAGE DeriveGeneric # -- | - This implements the Shunt Yard algorithm for determining the -- precedence of operations module Shunt where import Data.List.NonEmpty import GHC.Generics hiding (Associativity) import Control.Monad (foldM) data Associativity = Left' | Right' | NonAssoc deriving (Eq, Show, Generic) data Precedence sym = Pred sym Associativity Int deriving (Show, Eq, Generic) data Error sym = Clash (Precedence sym) (Precedence sym) | MoreEles deriving (Show, Eq) -- Not a real ordering, hence not an ord instance predOrd :: Precedence sym -> Precedence sym -> Either (Error sym) Bool predOrd p1@(Pred _ fix iNew) p2@(Pred _ fix' iOld) | iNew == iOld && fix /= fix' = Left (Clash p1 p2) | iNew == iOld && NonAssoc == fix && NonAssoc == fix' = Left (Clash p1 p2) | otherwise = case fix of Left' -> Right (iNew <= iOld) _ -> Right (iNew < iOld) data PredOrEle sym a = Precedence (Precedence sym) | Ele a deriving (Eq, Show) data Application sym a = App sym (Application sym a) (Application sym a) | Single a deriving (Eq, Show) shunt :: NonEmpty (PredOrEle sym a) -> Either (Error sym) (Application sym a) shunt = fmap (combine . popAll) . foldM shuntAcc ([], []) shuntAcc :: ([Application sym a], [Precedence sym]) -> PredOrEle sym a -> Either (Error sym) ([Application sym a], [Precedence sym]) shuntAcc (aps, prec) (Ele a) = Right (Single a : aps, prec) shuntAcc (aps, []) (Precedence p) = Right (aps, [p]) shuntAcc (aps, (pred : preds)) (Precedence p) = case p `predOrd` pred of Right True -> case aps of x1 : x2 : xs -> Right (App (predSymbol pred) x2 x1 : xs, p : preds) [_] -> Left MoreEles [] -> Left MoreEles Right False -> Right (aps, p : pred : preds) Left err -> Left err popAll :: ([Application sym a], [Precedence sym]) -> [Application sym a] popAll (xs, []) = xs popAll (x1 : x2 : xs, op : ops) = popAll (App (predSymbol op) x2 x1 : xs, ops) popAll ([], (_ : _)) = error "More applications than elements!" popAll ([_], (_ : _)) = error "More applications than elements!" This list should be of length 1 after all is said and done , and an -- application given by shunt combine :: [Application sym a] -> Application sym a combine (x : _) = x combine [] = error "precondition failed: Shunt.combine was given an empty list" predSymbol :: Precedence sym -> sym predSymbol (Pred s _ _) = s
null
https://raw.githubusercontent.com/mariari/Misc-ML-Scripts/34e53528f06203766b47464ed53c14ce88096cdd/Haskell/shunt.hs
haskell
| precedence of operations Not a real ordering, hence not an ord instance application given by shunt
# LANGUAGE DeriveGeneric # - This implements the Shunt Yard algorithm for determining the module Shunt where import Data.List.NonEmpty import GHC.Generics hiding (Associativity) import Control.Monad (foldM) data Associativity = Left' | Right' | NonAssoc deriving (Eq, Show, Generic) data Precedence sym = Pred sym Associativity Int deriving (Show, Eq, Generic) data Error sym = Clash (Precedence sym) (Precedence sym) | MoreEles deriving (Show, Eq) predOrd :: Precedence sym -> Precedence sym -> Either (Error sym) Bool predOrd p1@(Pred _ fix iNew) p2@(Pred _ fix' iOld) | iNew == iOld && fix /= fix' = Left (Clash p1 p2) | iNew == iOld && NonAssoc == fix && NonAssoc == fix' = Left (Clash p1 p2) | otherwise = case fix of Left' -> Right (iNew <= iOld) _ -> Right (iNew < iOld) data PredOrEle sym a = Precedence (Precedence sym) | Ele a deriving (Eq, Show) data Application sym a = App sym (Application sym a) (Application sym a) | Single a deriving (Eq, Show) shunt :: NonEmpty (PredOrEle sym a) -> Either (Error sym) (Application sym a) shunt = fmap (combine . popAll) . foldM shuntAcc ([], []) shuntAcc :: ([Application sym a], [Precedence sym]) -> PredOrEle sym a -> Either (Error sym) ([Application sym a], [Precedence sym]) shuntAcc (aps, prec) (Ele a) = Right (Single a : aps, prec) shuntAcc (aps, []) (Precedence p) = Right (aps, [p]) shuntAcc (aps, (pred : preds)) (Precedence p) = case p `predOrd` pred of Right True -> case aps of x1 : x2 : xs -> Right (App (predSymbol pred) x2 x1 : xs, p : preds) [_] -> Left MoreEles [] -> Left MoreEles Right False -> Right (aps, p : pred : preds) Left err -> Left err popAll :: ([Application sym a], [Precedence sym]) -> [Application sym a] popAll (xs, []) = xs popAll (x1 : x2 : xs, op : ops) = popAll (App (predSymbol op) x2 x1 : xs, ops) popAll ([], (_ : _)) = error "More applications than elements!" popAll ([_], (_ : _)) = error "More applications than elements!" This list should be of length 1 after all is said and done , and an combine :: [Application sym a] -> Application sym a combine (x : _) = x combine [] = error "precondition failed: Shunt.combine was given an empty list" predSymbol :: Precedence sym -> sym predSymbol (Pred s _ _) = s
7167446ce2b2e031e6c8e7df25ebaef0336fb81b01ecd6cd96003db9c3847656
metametadata/aide
events.cljs
(ns app.events (:require [app.api :as api] [aide.core :as aide] [aide-history.core :as aide-history] [goog.functions :as goog-functions])) (aide/defevent on-search-success [app [q friends]] (if (= q (:query @(:*model app))) (swap! (:*model app) assoc :friends friends) (println "ignore response for" (pr-str q) "because current query is" (pr-str (:query @(:*model app)))))) (defn -search [app q] (api/search q #(aide/emit app on-search-success [q %]))) (aide/defevent on-enter [app {:keys [token]}] (swap! (:*model app) assoc :query token) (-search app token)) (def -search-on-input (goog-functions/debounce (fn [app q] (aide-history/push-token (:history app) q {:bypass-on-enter-event? true}) (-search app q)) 300)) (aide/defevent on-input [app q] (swap! (:*model app) assoc :query q) (-search-on-input app q))
null
https://raw.githubusercontent.com/metametadata/aide/0828b53503e8c7f54f84e1b140a1d02ad80aff36/examples/friend-list/src/app/events.cljs
clojure
(ns app.events (:require [app.api :as api] [aide.core :as aide] [aide-history.core :as aide-history] [goog.functions :as goog-functions])) (aide/defevent on-search-success [app [q friends]] (if (= q (:query @(:*model app))) (swap! (:*model app) assoc :friends friends) (println "ignore response for" (pr-str q) "because current query is" (pr-str (:query @(:*model app)))))) (defn -search [app q] (api/search q #(aide/emit app on-search-success [q %]))) (aide/defevent on-enter [app {:keys [token]}] (swap! (:*model app) assoc :query token) (-search app token)) (def -search-on-input (goog-functions/debounce (fn [app q] (aide-history/push-token (:history app) q {:bypass-on-enter-event? true}) (-search app q)) 300)) (aide/defevent on-input [app q] (swap! (:*model app) assoc :query q) (-search-on-input app q))
b73dcc49199967f8350c7265c78d43280ad78f3873e169097c1ac944ade53c3e
EFanZh/EOPL-Exercises
exercise-6.27.rkt
#lang eopl Exercise 6.27 [ ★ ★ ] As it stands , cps - of - let - exp will generate a useless let expression . ( Why ? ) Modify this procedure ;; so that the continuation variable is the same as the let variable. Then if exp1 is nonsimple, ;; ( cps - of - exp < < let var1 = exp1 in exp2 > > K ) = ( cps - of - exp exp1 < < proc ( var1 ) ( cps - of - exp exp2 K ) > > CPS - IN grammar . (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("+" "(" (separated-list expression ",") ")") sum-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression ("letrec" (arbno identifier "(" (arbno identifier) ")" "=" expression) "in" expression) letrec-exp] [expression (identifier) var-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("proc" "(" (arbno identifier) ")" expression) proc-exp] [expression ("(" expression (arbno expression) ")") call-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) CPS - OUT grammar . (define cps-out-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define cps-out-grammar '([cps-out-program (tfexp) cps-a-program] [simple-expression (number) cps-const-exp] [simple-expression (identifier) cps-var-exp] [simple-expression ("-" "(" simple-expression "," simple-expression ")") cps-diff-exp] [simple-expression ("zero?" "(" simple-expression ")") cps-zero?-exp] [simple-expression ("+" "(" (separated-list simple-expression ",") ")") cps-sum-exp] [simple-expression ("proc" "(" (arbno identifier) ")" tfexp) cps-proc-exp] [tfexp (simple-expression) simple-exp->exp] [tfexp ("let" identifier "=" simple-expression "in" tfexp) cps-let-exp] [tfexp ("letrec" (arbno identifier "(" (arbno identifier) ")" "=" tfexp) "in" tfexp) cps-letrec-exp] [tfexp ("if" simple-expression "then" tfexp "else" tfexp) cps-if-exp] [tfexp ("(" simple-expression (arbno simple-expression) ")") cps-call-exp])) (sllgen:make-define-datatypes cps-out-lexical-spec cps-out-grammar) ;; Transformer. (define list-set (lambda (lst n val) (cond [(null? lst) (eopl:error 'list-set "ran off end")] [(zero? n) (cons val (cdr lst))] [else (cons (car lst) (list-set (cdr lst) (- n 1) val))]))) (define fresh-identifier (let ([sn 0]) (lambda (identifier) (set! sn (+ sn 1)) (string->symbol (string-append (symbol->string identifier) "%" (number->string sn)))))) (define all-simple? (lambda (exps) (if (null? exps) #t (and (inp-exp-simple? (car exps)) (all-simple? (cdr exps)))))) (define inp-exp-simple? (lambda (exp) (cases expression exp [const-exp (num) #t] [var-exp (var) #t] [diff-exp (exp1 exp2) (and (inp-exp-simple? exp1) (inp-exp-simple? exp2))] [zero?-exp (exp1) (inp-exp-simple? exp1)] [proc-exp (ids exp) #t] [sum-exp (exps) (all-simple? exps)] [else #f]))) (define make-send-to-cont (lambda (cont bexp) (cps-call-exp cont (list bexp)))) (define cps-of-zero?-exp (lambda (exp1 k-exp) (cps-of-exps (list exp1) (lambda (new-rands) (make-send-to-cont k-exp (cps-zero?-exp (car new-rands))))))) (define cps-of-sum-exp (lambda (exps k-exp) (cps-of-exps exps (lambda (new-rands) (make-send-to-cont k-exp (cps-sum-exp new-rands)))))) (define cps-of-diff-exp (lambda (exp1 exp2 k-exp) (cps-of-exps (list exp1 exp2) (lambda (new-rands) (make-send-to-cont k-exp (cps-diff-exp (car new-rands) (cadr new-rands))))))) (define cps-of-if-exp (lambda (exp1 exp2 exp3 k-exp) (cps-of-exps (list exp1) (lambda (new-rands) (cps-if-exp (car new-rands) (cps-of-exp exp2 k-exp) (cps-of-exp exp3 k-exp)))))) (define cps-of-let-exp (lambda (id rhs body k-exp) (cps-of-exp rhs (cps-proc-exp (list id) (cps-of-exp body k-exp))))) (define cps-of-letrec-exp (lambda (proc-names idss proc-bodies body k-exp) (cps-letrec-exp proc-names (map (lambda (ids) (append ids (list 'k%00))) idss) (map (lambda (exp) (cps-of-exp exp (cps-var-exp 'k%00))) proc-bodies) (cps-of-exp body k-exp)))) (define cps-of-call-exp (lambda (rator rands k-exp) (cps-of-exps (cons rator rands) (lambda (new-rands) (cps-call-exp (car new-rands) (append (cdr new-rands) (list k-exp))))))) (define report-invalid-exp-to-cps-of-simple-exp (lambda (exp) (eopl:error 'cps-of-simple-exp "non-simple expression to cps-of-simple-exp: ~s" exp))) (define cps-of-simple-exp (lambda (exp) (cases expression exp [const-exp (num) (cps-const-exp num)] [var-exp (var) (cps-var-exp var)] [diff-exp (exp1 exp2) (cps-diff-exp (cps-of-simple-exp exp1) (cps-of-simple-exp exp2))] [zero?-exp (exp1) (cps-zero?-exp (cps-of-simple-exp exp1))] [proc-exp (ids exp) (cps-proc-exp (append ids (list 'k%00)) (cps-of-exp exp (cps-var-exp 'k%00)))] [sum-exp (exps) (cps-sum-exp (map cps-of-simple-exp exps))] [else (report-invalid-exp-to-cps-of-simple-exp exp)]))) (define cps-of-exp (lambda (exp cont) (cases expression exp [const-exp (num) (make-send-to-cont cont (cps-const-exp num))] [var-exp (var) (make-send-to-cont cont (cps-var-exp var))] [proc-exp (vars body) (make-send-to-cont cont (cps-proc-exp (append vars (list 'k%00)) (cps-of-exp body (cps-var-exp 'k%00))))] [zero?-exp (exp1) (cps-of-zero?-exp exp1 cont)] [diff-exp (exp1 exp2) (cps-of-diff-exp exp1 exp2 cont)] [sum-exp (exps) (cps-of-sum-exp exps cont)] [if-exp (exp1 exp2 exp3) (cps-of-if-exp exp1 exp2 exp3 cont)] [let-exp (var exp1 body) (cps-of-let-exp var exp1 body cont)] [letrec-exp (ids bidss proc-bodies body) (cps-of-letrec-exp ids bidss proc-bodies body cont)] [call-exp (rator rands) (cps-of-call-exp rator rands cont)]))) (define cps-of-exps (lambda (exps builder) (define list-index (lambda (pred lst) (cond [(null? lst) #f] [(pred (car lst)) 0] [(list-index pred (cdr lst)) => (lambda (n) (+ n 1))] [else #f]))) (let cps-of-rest ([exps exps]) (let ([pos (list-index (lambda (exp) (not (inp-exp-simple? exp))) exps)]) (if (not pos) (builder (map cps-of-simple-exp exps)) (let ([var (fresh-identifier 'var)]) (cps-of-exp (list-ref exps pos) (cps-proc-exp (list var) (cps-of-rest (list-set exps pos (var-exp var))))))))))) (define cps-of-program (lambda (pgm) (cases program pgm [a-program (exp1) (cps-a-program (cps-of-exps (list exp1) (lambda (new-args) (simple-exp->exp (car new-args)))))]))) ;; Data structures - expressed values. (define-datatype proc proc? [procedure [vars (list-of symbol?)] [body tfexp?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) ;; Data structures - environment. (define empty-env (lambda () '())) (define extend-env* (lambda (syms vals old-env) (cons (list 'let syms vals) old-env))) (define extend-env-rec** (lambda (p-names b-varss p-bodies saved-env) (cons (list 'letrec p-names b-varss p-bodies) saved-env))) (define environment? (list-of (lambda (p) (and (pair? p) (or (eqv? (car p) 'let) (eqv? (car p) 'letrec)))))) (define apply-env (lambda (env search-sym) (define list-index (lambda (sym los) (let loop ([pos 0] [los los]) (cond [(null? los) #f] [(eqv? sym (car los)) pos] [else (loop (+ pos 1) (cdr los))])))) (if (null? env) (eopl:error 'apply-env "No binding for ~s" search-sym) (let* ([binding (car env)] [saved-env (cdr env)]) (let ([pos (list-index search-sym (cadr binding))]) (if pos (case (car binding) [(let) (list-ref (caddr binding) pos)] [(letrec) (let ([bvars (caddr binding)] [bodies (cadddr binding)]) (proc-val (procedure (list-ref bvars pos) (list-ref bodies pos) env)))]) (apply-env saved-env search-sym))))))) ;; Data structures - continuation. (define-datatype continuation continuation? [end-cont]) ;; Interpreter. (define apply-cont (lambda (cont val) (cases continuation cont [end-cont () val]))) (define apply-procedure/k (lambda (proc1 args cont) (cases proc proc1 [procedure (vars body saved-env) (value-of/k body (extend-env* vars args saved-env) cont)]))) (define value-of-simple-exp (lambda (exp env) (cases simple-expression exp [cps-const-exp (num) (num-val num)] [cps-var-exp (var) (apply-env env var)] [cps-diff-exp (exp1 exp2) (let ([val1 (expval->num (value-of-simple-exp exp1 env))] [val2 (expval->num (value-of-simple-exp exp2 env))]) (num-val (- val1 val2)))] [cps-zero?-exp (exp1) (bool-val (zero? (expval->num (value-of-simple-exp exp1 env))))] [cps-sum-exp (exps) (let ([nums (map (lambda (exp) (expval->num (value-of-simple-exp exp env))) exps)]) (num-val (let sum-loop ([nums nums]) (if (null? nums) 0 (+ (car nums) (sum-loop (cdr nums)))))))] [cps-proc-exp (vars body) (proc-val (procedure vars body env))]))) (define value-of/k (lambda (exp env cont) (cases tfexp exp [simple-exp->exp (simple) (apply-cont cont (value-of-simple-exp simple env))] [cps-let-exp (var rhs body) (let ([val (value-of-simple-exp rhs env)]) (value-of/k body (extend-env* (list var) (list val) env) cont))] [cps-letrec-exp (p-names b-varss p-bodies letrec-body) (value-of/k letrec-body (extend-env-rec** p-names b-varss p-bodies env) cont)] [cps-if-exp (simple1 body1 body2) (if (expval->bool (value-of-simple-exp simple1 env)) (value-of/k body1 env cont) (value-of/k body2 env cont))] [cps-call-exp (rator rands) (let ([rator-proc (expval->proc (value-of-simple-exp rator env))] [rand-vals (map (lambda (simple) (value-of-simple-exp simple env)) rands)]) (apply-procedure/k rator-proc rand-vals cont))]))) (define value-of-program (lambda (pgm) (cases cps-out-program pgm [cps-a-program (exp1) (value-of/k exp1 (empty-env) (end-cont))]))) Interface . (define run (lambda (string) (let ([cpsed-pgm (cps-of-program (scan&parse string))]) (value-of-program cpsed-pgm)))) (provide bool-val num-val run)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-6.27.rkt
racket
so that the continuation variable is the same as the let variable. Then if exp1 is nonsimple, Transformer. Data structures - expressed values. Data structures - environment. Data structures - continuation. Interpreter.
#lang eopl Exercise 6.27 [ ★ ★ ] As it stands , cps - of - let - exp will generate a useless let expression . ( Why ? ) Modify this procedure ( cps - of - exp < < let var1 = exp1 in exp2 > > K ) = ( cps - of - exp exp1 < < proc ( var1 ) ( cps - of - exp exp2 K ) > > CPS - IN grammar . (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("+" "(" (separated-list expression ",") ")") sum-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression ("letrec" (arbno identifier "(" (arbno identifier) ")" "=" expression) "in" expression) letrec-exp] [expression (identifier) var-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("proc" "(" (arbno identifier) ")" expression) proc-exp] [expression ("(" expression (arbno expression) ")") call-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) CPS - OUT grammar . (define cps-out-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define cps-out-grammar '([cps-out-program (tfexp) cps-a-program] [simple-expression (number) cps-const-exp] [simple-expression (identifier) cps-var-exp] [simple-expression ("-" "(" simple-expression "," simple-expression ")") cps-diff-exp] [simple-expression ("zero?" "(" simple-expression ")") cps-zero?-exp] [simple-expression ("+" "(" (separated-list simple-expression ",") ")") cps-sum-exp] [simple-expression ("proc" "(" (arbno identifier) ")" tfexp) cps-proc-exp] [tfexp (simple-expression) simple-exp->exp] [tfexp ("let" identifier "=" simple-expression "in" tfexp) cps-let-exp] [tfexp ("letrec" (arbno identifier "(" (arbno identifier) ")" "=" tfexp) "in" tfexp) cps-letrec-exp] [tfexp ("if" simple-expression "then" tfexp "else" tfexp) cps-if-exp] [tfexp ("(" simple-expression (arbno simple-expression) ")") cps-call-exp])) (sllgen:make-define-datatypes cps-out-lexical-spec cps-out-grammar) (define list-set (lambda (lst n val) (cond [(null? lst) (eopl:error 'list-set "ran off end")] [(zero? n) (cons val (cdr lst))] [else (cons (car lst) (list-set (cdr lst) (- n 1) val))]))) (define fresh-identifier (let ([sn 0]) (lambda (identifier) (set! sn (+ sn 1)) (string->symbol (string-append (symbol->string identifier) "%" (number->string sn)))))) (define all-simple? (lambda (exps) (if (null? exps) #t (and (inp-exp-simple? (car exps)) (all-simple? (cdr exps)))))) (define inp-exp-simple? (lambda (exp) (cases expression exp [const-exp (num) #t] [var-exp (var) #t] [diff-exp (exp1 exp2) (and (inp-exp-simple? exp1) (inp-exp-simple? exp2))] [zero?-exp (exp1) (inp-exp-simple? exp1)] [proc-exp (ids exp) #t] [sum-exp (exps) (all-simple? exps)] [else #f]))) (define make-send-to-cont (lambda (cont bexp) (cps-call-exp cont (list bexp)))) (define cps-of-zero?-exp (lambda (exp1 k-exp) (cps-of-exps (list exp1) (lambda (new-rands) (make-send-to-cont k-exp (cps-zero?-exp (car new-rands))))))) (define cps-of-sum-exp (lambda (exps k-exp) (cps-of-exps exps (lambda (new-rands) (make-send-to-cont k-exp (cps-sum-exp new-rands)))))) (define cps-of-diff-exp (lambda (exp1 exp2 k-exp) (cps-of-exps (list exp1 exp2) (lambda (new-rands) (make-send-to-cont k-exp (cps-diff-exp (car new-rands) (cadr new-rands))))))) (define cps-of-if-exp (lambda (exp1 exp2 exp3 k-exp) (cps-of-exps (list exp1) (lambda (new-rands) (cps-if-exp (car new-rands) (cps-of-exp exp2 k-exp) (cps-of-exp exp3 k-exp)))))) (define cps-of-let-exp (lambda (id rhs body k-exp) (cps-of-exp rhs (cps-proc-exp (list id) (cps-of-exp body k-exp))))) (define cps-of-letrec-exp (lambda (proc-names idss proc-bodies body k-exp) (cps-letrec-exp proc-names (map (lambda (ids) (append ids (list 'k%00))) idss) (map (lambda (exp) (cps-of-exp exp (cps-var-exp 'k%00))) proc-bodies) (cps-of-exp body k-exp)))) (define cps-of-call-exp (lambda (rator rands k-exp) (cps-of-exps (cons rator rands) (lambda (new-rands) (cps-call-exp (car new-rands) (append (cdr new-rands) (list k-exp))))))) (define report-invalid-exp-to-cps-of-simple-exp (lambda (exp) (eopl:error 'cps-of-simple-exp "non-simple expression to cps-of-simple-exp: ~s" exp))) (define cps-of-simple-exp (lambda (exp) (cases expression exp [const-exp (num) (cps-const-exp num)] [var-exp (var) (cps-var-exp var)] [diff-exp (exp1 exp2) (cps-diff-exp (cps-of-simple-exp exp1) (cps-of-simple-exp exp2))] [zero?-exp (exp1) (cps-zero?-exp (cps-of-simple-exp exp1))] [proc-exp (ids exp) (cps-proc-exp (append ids (list 'k%00)) (cps-of-exp exp (cps-var-exp 'k%00)))] [sum-exp (exps) (cps-sum-exp (map cps-of-simple-exp exps))] [else (report-invalid-exp-to-cps-of-simple-exp exp)]))) (define cps-of-exp (lambda (exp cont) (cases expression exp [const-exp (num) (make-send-to-cont cont (cps-const-exp num))] [var-exp (var) (make-send-to-cont cont (cps-var-exp var))] [proc-exp (vars body) (make-send-to-cont cont (cps-proc-exp (append vars (list 'k%00)) (cps-of-exp body (cps-var-exp 'k%00))))] [zero?-exp (exp1) (cps-of-zero?-exp exp1 cont)] [diff-exp (exp1 exp2) (cps-of-diff-exp exp1 exp2 cont)] [sum-exp (exps) (cps-of-sum-exp exps cont)] [if-exp (exp1 exp2 exp3) (cps-of-if-exp exp1 exp2 exp3 cont)] [let-exp (var exp1 body) (cps-of-let-exp var exp1 body cont)] [letrec-exp (ids bidss proc-bodies body) (cps-of-letrec-exp ids bidss proc-bodies body cont)] [call-exp (rator rands) (cps-of-call-exp rator rands cont)]))) (define cps-of-exps (lambda (exps builder) (define list-index (lambda (pred lst) (cond [(null? lst) #f] [(pred (car lst)) 0] [(list-index pred (cdr lst)) => (lambda (n) (+ n 1))] [else #f]))) (let cps-of-rest ([exps exps]) (let ([pos (list-index (lambda (exp) (not (inp-exp-simple? exp))) exps)]) (if (not pos) (builder (map cps-of-simple-exp exps)) (let ([var (fresh-identifier 'var)]) (cps-of-exp (list-ref exps pos) (cps-proc-exp (list var) (cps-of-rest (list-set exps pos (var-exp var))))))))))) (define cps-of-program (lambda (pgm) (cases program pgm [a-program (exp1) (cps-a-program (cps-of-exps (list exp1) (lambda (new-args) (simple-exp->exp (car new-args)))))]))) (define-datatype proc proc? [procedure [vars (list-of symbol?)] [body tfexp?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define empty-env (lambda () '())) (define extend-env* (lambda (syms vals old-env) (cons (list 'let syms vals) old-env))) (define extend-env-rec** (lambda (p-names b-varss p-bodies saved-env) (cons (list 'letrec p-names b-varss p-bodies) saved-env))) (define environment? (list-of (lambda (p) (and (pair? p) (or (eqv? (car p) 'let) (eqv? (car p) 'letrec)))))) (define apply-env (lambda (env search-sym) (define list-index (lambda (sym los) (let loop ([pos 0] [los los]) (cond [(null? los) #f] [(eqv? sym (car los)) pos] [else (loop (+ pos 1) (cdr los))])))) (if (null? env) (eopl:error 'apply-env "No binding for ~s" search-sym) (let* ([binding (car env)] [saved-env (cdr env)]) (let ([pos (list-index search-sym (cadr binding))]) (if pos (case (car binding) [(let) (list-ref (caddr binding) pos)] [(letrec) (let ([bvars (caddr binding)] [bodies (cadddr binding)]) (proc-val (procedure (list-ref bvars pos) (list-ref bodies pos) env)))]) (apply-env saved-env search-sym))))))) (define-datatype continuation continuation? [end-cont]) (define apply-cont (lambda (cont val) (cases continuation cont [end-cont () val]))) (define apply-procedure/k (lambda (proc1 args cont) (cases proc proc1 [procedure (vars body saved-env) (value-of/k body (extend-env* vars args saved-env) cont)]))) (define value-of-simple-exp (lambda (exp env) (cases simple-expression exp [cps-const-exp (num) (num-val num)] [cps-var-exp (var) (apply-env env var)] [cps-diff-exp (exp1 exp2) (let ([val1 (expval->num (value-of-simple-exp exp1 env))] [val2 (expval->num (value-of-simple-exp exp2 env))]) (num-val (- val1 val2)))] [cps-zero?-exp (exp1) (bool-val (zero? (expval->num (value-of-simple-exp exp1 env))))] [cps-sum-exp (exps) (let ([nums (map (lambda (exp) (expval->num (value-of-simple-exp exp env))) exps)]) (num-val (let sum-loop ([nums nums]) (if (null? nums) 0 (+ (car nums) (sum-loop (cdr nums)))))))] [cps-proc-exp (vars body) (proc-val (procedure vars body env))]))) (define value-of/k (lambda (exp env cont) (cases tfexp exp [simple-exp->exp (simple) (apply-cont cont (value-of-simple-exp simple env))] [cps-let-exp (var rhs body) (let ([val (value-of-simple-exp rhs env)]) (value-of/k body (extend-env* (list var) (list val) env) cont))] [cps-letrec-exp (p-names b-varss p-bodies letrec-body) (value-of/k letrec-body (extend-env-rec** p-names b-varss p-bodies env) cont)] [cps-if-exp (simple1 body1 body2) (if (expval->bool (value-of-simple-exp simple1 env)) (value-of/k body1 env cont) (value-of/k body2 env cont))] [cps-call-exp (rator rands) (let ([rator-proc (expval->proc (value-of-simple-exp rator env))] [rand-vals (map (lambda (simple) (value-of-simple-exp simple env)) rands)]) (apply-procedure/k rator-proc rand-vals cont))]))) (define value-of-program (lambda (pgm) (cases cps-out-program pgm [cps-a-program (exp1) (value-of/k exp1 (empty-env) (end-cont))]))) Interface . (define run (lambda (string) (let ([cpsed-pgm (cps-of-program (scan&parse string))]) (value-of-program cpsed-pgm)))) (provide bool-val num-val run)
823744dbfc9aca4fd2c02a1c0f3ecfc1fe7899f55fd9220039895813fa1e3f63
exercism/haskell
Phone.hs
module Phone (number) where import Data.Char (isDigit) number :: String -> Maybe String number input = clean input >>= check check :: String -> Maybe String check ('0':_) = Nothing check ('1':_) = Nothing check (_:_:_:'0':_) = Nothing check (_:_:_:'1':_) = Nothing check s = Just s clean :: String -> Maybe String clean input | len == 10 = Just digits | len == 11 && head digits == '1' = Just $ tail digits | otherwise = Nothing where digits = filter isDigit input len = length digits
null
https://raw.githubusercontent.com/exercism/haskell/ae17e9fc5ca736a228db6dda5e3f3b057fa6f3d0/exercises/practice/phone-number/.meta/examples/success-standard/src/Phone.hs
haskell
module Phone (number) where import Data.Char (isDigit) number :: String -> Maybe String number input = clean input >>= check check :: String -> Maybe String check ('0':_) = Nothing check ('1':_) = Nothing check (_:_:_:'0':_) = Nothing check (_:_:_:'1':_) = Nothing check s = Just s clean :: String -> Maybe String clean input | len == 10 = Just digits | len == 11 && head digits == '1' = Just $ tail digits | otherwise = Nothing where digits = filter isDigit input len = length digits
a0a4ead2b1e8ffe3e6530db9c975ced99cee1bf3983f6bff83503146fea18cd1
layerware/hugsql
project.clj
(defproject com.layerware/hugsql-adapter "0.5.3" :description "hugsql adapter support/protocol" :url "" :license {:name "Apache License, Version 2.0" :url "-2.0.html"} :scm {:dir ".."} :dependencies [[org.clojure/clojure "1.8.0"]])
null
https://raw.githubusercontent.com/layerware/hugsql/ad73d080f84487c3438058ed5203d44f06c46365/hugsql-adapter/project.clj
clojure
(defproject com.layerware/hugsql-adapter "0.5.3" :description "hugsql adapter support/protocol" :url "" :license {:name "Apache License, Version 2.0" :url "-2.0.html"} :scm {:dir ".."} :dependencies [[org.clojure/clojure "1.8.0"]])
68b42061349044050fa02689ee976a47bd8258d2b55bbdf6892ec4e16f79cd7a
weavejester/environ
plugin.clj
(ns lein-environ.plugin (:use [robert.hooke :only (add-hook)]) (:require [clojure.java.io :as io] leiningen.core.main)) (defn- as-edn [& args] (binding [*print-dup* false *print-meta* false *print-length* false *print-level* false] (apply prn-str args))) (defn- map-vals [f m] (reduce-kv #(assoc %1 %2 (f %3)) {} m)) (defn- replace-project-keyword [value project] (if (and (keyword? value) (= (namespace value) "project")) (project (keyword (name value))) value)) (defn read-env [project] (map-vals #(replace-project-keyword % project) (:env project {}))) (defn env-file [project] (io/file (:root project) ".lein-env")) (defn- write-env-to-file [func task-name project args] (spit (env-file project) (as-edn (read-env project))) (func task-name project args)) (defn hooks [] (add-hook #'leiningen.core.main/apply-task #'write-env-to-file))
null
https://raw.githubusercontent.com/weavejester/environ/bd355e6422399703c46abe7c890b54685632ae10/lein-environ/src/lein_environ/plugin.clj
clojure
(ns lein-environ.plugin (:use [robert.hooke :only (add-hook)]) (:require [clojure.java.io :as io] leiningen.core.main)) (defn- as-edn [& args] (binding [*print-dup* false *print-meta* false *print-length* false *print-level* false] (apply prn-str args))) (defn- map-vals [f m] (reduce-kv #(assoc %1 %2 (f %3)) {} m)) (defn- replace-project-keyword [value project] (if (and (keyword? value) (= (namespace value) "project")) (project (keyword (name value))) value)) (defn read-env [project] (map-vals #(replace-project-keyword % project) (:env project {}))) (defn env-file [project] (io/file (:root project) ".lein-env")) (defn- write-env-to-file [func task-name project args] (spit (env-file project) (as-edn (read-env project))) (func task-name project args)) (defn hooks [] (add-hook #'leiningen.core.main/apply-task #'write-env-to-file))
4cbde841a42545f322c8dff8e5b695a78c73767e885a50ed90d74c48b4be15d6
kumarshantanu/lein-clr
project.clj
(defproject lein-clr/parent "0.0.0" :description "Housekeeping project for lein-clr" :url "-clr" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.0.0" :plugins [[lein-sub "0.2.4"]] :sub ["lein-template" "plugin"] :eval-in :leiningen)
null
https://raw.githubusercontent.com/kumarshantanu/lein-clr/de43519353c3c4a8a4e1520faf7f9a576910382e/project.clj
clojure
(defproject lein-clr/parent "0.0.0" :description "Housekeeping project for lein-clr" :url "-clr" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.0.0" :plugins [[lein-sub "0.2.4"]] :sub ["lein-template" "plugin"] :eval-in :leiningen)
87fdf752305fedb81223a1d28bf700594ebf02042b9a7dbdd21f0d8893432588
Clojure2D/clojure2d-examples
ex43_noise_figures.clj
(ns ex43-noise-figures (:require [clojure2d.core :refer :all] [fastmath.random :as r] [fastmath.core :as m] [clojure2d.color :as c] [fastmath.fields :as f] [fastmath.vector :as v])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defn new-pair "Create new noise and field" [] (let [ncfg (assoc (r/random-noise-cfg) :normalize? false :octaves (r/irand 1 5)) fcfg (binding [f/*skip-random-fields* true] (f/random-configuration 2))] [(r/random-noise-fn ncfg) (f/combine fcfg)])) (def sinusoidal (f/field :sinusoidal 0.2)) (defn draw "" [canvas window ^long frame _] (let [z (/ frame 1000.0) [noise-fn field-fn] (get-state window) scale (max 0.2 (* (mouse-x window) 0.001)) hw (/ (width canvas) 2.0) hh (/ (height canvas) 2.0) speed (* z (max 1.0 (m/norm (mouse-y window) hh (height canvas) 1.0 8.0)))] (-> canvas (set-background :black 100) (translate hw hh) (rotate m/QUARTER_PI) (set-color (c/gray 250) 40)) (dotimes [i 100000] (let [xx (r/drand (- scale) scale) yy (r/drand (- scale) scale) fv (sinusoidal (field-fn (v/vec2 xx yy))) xx (+ xx ^double (fv 0)) yy (+ yy ^double (fv 1)) nx (* 250 ^double (noise-fn xx yy speed)) ny (* 250 ^double (noise-fn yy xx speed))] (point canvas nx ny))))) (def window (show-window {:canvas (canvas 800 800) :draw-fn draw :state (new-pair) :window-name "ex43"})) (defmethod mouse-event ["ex43" :mouse-pressed] [_ _] (new-pair))
null
https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/9de82f5ac0737b7e78e07a17cf03ac577d973817/src/ex43_noise_figures.clj
clojure
(ns ex43-noise-figures (:require [clojure2d.core :refer :all] [fastmath.random :as r] [fastmath.core :as m] [clojure2d.color :as c] [fastmath.fields :as f] [fastmath.vector :as v])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (m/use-primitive-operators) (defn new-pair "Create new noise and field" [] (let [ncfg (assoc (r/random-noise-cfg) :normalize? false :octaves (r/irand 1 5)) fcfg (binding [f/*skip-random-fields* true] (f/random-configuration 2))] [(r/random-noise-fn ncfg) (f/combine fcfg)])) (def sinusoidal (f/field :sinusoidal 0.2)) (defn draw "" [canvas window ^long frame _] (let [z (/ frame 1000.0) [noise-fn field-fn] (get-state window) scale (max 0.2 (* (mouse-x window) 0.001)) hw (/ (width canvas) 2.0) hh (/ (height canvas) 2.0) speed (* z (max 1.0 (m/norm (mouse-y window) hh (height canvas) 1.0 8.0)))] (-> canvas (set-background :black 100) (translate hw hh) (rotate m/QUARTER_PI) (set-color (c/gray 250) 40)) (dotimes [i 100000] (let [xx (r/drand (- scale) scale) yy (r/drand (- scale) scale) fv (sinusoidal (field-fn (v/vec2 xx yy))) xx (+ xx ^double (fv 0)) yy (+ yy ^double (fv 1)) nx (* 250 ^double (noise-fn xx yy speed)) ny (* 250 ^double (noise-fn yy xx speed))] (point canvas nx ny))))) (def window (show-window {:canvas (canvas 800 800) :draw-fn draw :state (new-pair) :window-name "ex43"})) (defmethod mouse-event ["ex43" :mouse-pressed] [_ _] (new-pair))
23ee73ef776938b8137a14302b5853c53c027a12e278e4ad21fba455b96ab806
runtimeverification/haskell-backend
AndTerms.hs
| Copyright : ( c ) Runtime Verification , 2018 - 2021 License : BSD-3 - Clause Copyright : (c) Runtime Verification, 2018-2021 License : BSD-3-Clause -} module Kore.Simplify.AndTerms ( termUnification, maybeTermAnd, maybeTermEquals, TermSimplifier, TermTransformationOld, cannotUnifyDistinctDomainValues, functionAnd, matchFunctionAnd, compareForEquals, FunctionAnd (..), ) where import Control.Error ( MaybeT (..), ) import Control.Error qualified as Error import Data.String ( fromString, ) import Data.Text ( Text, ) import Kore.Builtin.Bool qualified as Builtin.Bool import Kore.Builtin.Builtin qualified as Builtin import Kore.Builtin.Endianness qualified as Builtin.Endianness import Kore.Builtin.Int qualified as Builtin.Int import Kore.Builtin.InternalBytes ( matchBytes, unifyBytes, ) import Kore.Builtin.KEqual qualified as Builtin.KEqual import Kore.Builtin.List qualified as Builtin.List import Kore.Builtin.Map qualified as Builtin.Map import Kore.Builtin.Set qualified as Builtin.Set import Kore.Builtin.Signedness qualified as Builtin.Signedness import Kore.Builtin.String qualified as Builtin.String import Kore.Internal.Condition as Condition import Kore.Internal.OrCondition qualified as OrCondition import Kore.Internal.OrPattern qualified as OrPattern import Kore.Internal.Pattern ( Pattern, ) import Kore.Internal.Pattern qualified as Pattern import Kore.Internal.Predicate ( makeEqualsPredicate, makeNotPredicate, pattern PredicateTrue, ) import Kore.Internal.Predicate qualified as Predicate import Kore.Internal.SideCondition ( SideCondition, ) import Kore.Internal.SideCondition qualified as SideCondition ( topTODO, ) import Kore.Internal.Substitution qualified as Substitution import Kore.Internal.Symbol qualified as Symbol import Kore.Internal.TermLike import Kore.Log.DebugUnification ( debugUnificationSolved, debugUnificationUnsolved, whileDebugUnification, ) import Kore.Log.DebugUnifyBottom ( debugUnifyBottom, debugUnifyBottomAndReturnBottom, ) import Kore.Rewrite.RewritingVariable ( RewritingVariableName, ) import Kore.Simplify.Exists qualified as Exists import Kore.Simplify.ExpandAlias import Kore.Simplify.InjSimplifier import Kore.Simplify.NoConfusion import Kore.Simplify.NotSimplifier import Kore.Simplify.Overloading as Overloading import Kore.Simplify.Simplify as Simplifier import Kore.Sort ( sameSort, ) import Kore.Unification.Unify as Unify import Kore.Unparser import Pair import Prelude.Kore import Pretty qualified | Unify two terms without discarding the terms . We want to keep the terms because substitution relies on the result not being @\\bottom@. When a case is not implemented , @termUnification@ will create a @\\ceil@ of the conjunction of the two terms . The comment for ' Kore.Simplify.And.simplify ' describes all the special cases handled by this . We want to keep the terms because substitution relies on the result not being @\\bottom@. When a case is not implemented, @termUnification@ will create a @\\ceil@ of the conjunction of the two terms. The comment for 'Kore.Simplify.And.simplify' describes all the special cases handled by this. -} termUnification :: forall unifier. MonadUnify unifier => NotSimplifier Simplifier => HasCallStack => TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier (Pattern RewritingVariableName) termUnification = \term1 term2 -> whileDebugUnification term1 term2 $ do result <- termUnificationWorker term1 term2 debugUnificationSolved result pure result where termUnificationWorker :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier (Pattern RewritingVariableName) termUnificationWorker term1 term2 = do let maybeTermUnification :: MaybeT unifier (Pattern RewritingVariableName) maybeTermUnification = maybeTermAnd termUnificationWorker term1 term2 Error.maybeT (incompleteUnificationPattern term1 term2) pure maybeTermUnification incompleteUnificationPattern term1 term2 = do debugUnificationUnsolved term1 term2 mkAnd term1 term2 & Pattern.fromTermLike & return maybeTermEquals :: MonadUnify unifier => NotSimplifier Simplifier => HasCallStack => -- | Used to simplify subterm "and". TermSimplifier RewritingVariableName unifier -> TermLike RewritingVariableName -> TermLike RewritingVariableName -> MaybeT unifier (Pattern RewritingVariableName) maybeTermEquals childTransformers first second = do injSimplifier <- Simplifier.askInjSimplifier overloadSimplifier <- Simplifier.askOverloadSimplifier tools <- Simplifier.askMetadataTools worker injSimplifier overloadSimplifier tools where worker injSimplifier overloadSimplifier tools | Just unifyData <- Builtin.Int.matchInt first second = lift $ Builtin.Int.unifyInt unifyData | Just unifyData <- Builtin.Bool.matchBools first second = lift $ Builtin.Bool.unifyBool unifyData | Just unifyData <- Builtin.String.matchString first second = lift $ Builtin.String.unifyString unifyData | Just unifyData <- matchDomainValue first second = lift $ unifyDomainValue unifyData | Just unifyData <- matchStringLiteral first second = lift $ unifyStringLiteral unifyData | Just term <- matchEqualsAndEquals first second = lift $ equalAndEquals term | Just unifyData <- matchBytes first second = lift $ unifyBytes unifyData | Just unifyData <- matchBottomTermEquals first second = lift $ bottomTermEquals (sameSort (termLikeSort first) (termLikeSort second)) SideCondition.topTODO unifyData | Just unifyData <- matchVariableFunctionEquals first second = lift $ variableFunctionEquals unifyData | Just unifyData <- matchEqualInjectiveHeadsAndEquals first second = lift $ equalInjectiveHeadsAndEquals childTransformers unifyData | Just unifyData <- matchInj injSimplifier first second = lift $ unifySortInjection childTransformers unifyData | Just unifyData <- matchConstructorSortInjectionAndEquals first second = lift $ constructorSortInjectionAndEquals unifyData | Just unifyData <- matchDifferentConstructors overloadSimplifier first second = lift $ constructorAndEqualsAssumesDifferentHeads unifyData | Just unifyData <- unifyOverloading overloadSimplifier (Pair first second) = lift $ overloadedConstructorSortInjectionAndEquals childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolAnd first second = lift $ Builtin.Bool.unifyBoolAnd childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolOr first second = lift $ Builtin.Bool.unifyBoolOr childTransformers unifyData | Just boolNotData <- Builtin.Bool.matchUnifyBoolNot first second = lift $ Builtin.Bool.unifyBoolNot childTransformers boolNotData | Just unifyData <- Builtin.Int.matchUnifyIntEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.String.matchUnifyStringEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.KEqual.matchUnifyKequalsEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.Endianness.matchUnifyEqualsEndianness first second = lift $ Builtin.Endianness.unifyEquals unifyData | Just unifyData <- Builtin.Signedness.matchUnifyEqualsSignedness first second = lift $ Builtin.Signedness.unifyEquals unifyData | Just unifyData <- Builtin.Map.matchUnifyEquals tools first second = lift $ Builtin.Map.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.Map.matchUnifyNotInKeys first second = lift $ Builtin.Map.unifyNotInKeys (sameSort (termLikeSort first) (termLikeSort second)) childTransformers unifyData | Just unifyData <- Builtin.Set.matchUnifyEquals tools first second = lift $ Builtin.Set.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.List.matchUnifyEqualsList tools first second = lift $ Builtin.List.unifyEquals childTransformers tools unifyData | Just unifyData <- matchDomainValueAndConstructorErrors first second = lift $ domainValueAndConstructorErrors unifyData | otherwise = empty maybeTermAnd :: MonadUnify unifier => NotSimplifier Simplifier => HasCallStack => -- | Used to simplify subterm "and". TermSimplifier RewritingVariableName unifier -> TermLike RewritingVariableName -> TermLike RewritingVariableName -> MaybeT unifier (Pattern RewritingVariableName) maybeTermAnd childTransformers first second = do injSimplifier <- Simplifier.askInjSimplifier overloadSimplifier <- Simplifier.askOverloadSimplifier tools <- Simplifier.askMetadataTools worker injSimplifier overloadSimplifier tools where worker injSimplifier overloadSimplifier tools | Just unifyData <- matchExpandAlias first second = let UnifyExpandAlias{term1, term2} = unifyData in maybeTermAnd childTransformers term1 term2 | Just unifyData <- matchBoolAnd first second = lift $ boolAnd unifyData | Just unifyData <- Builtin.Int.matchInt first second = lift $ Builtin.Int.unifyInt unifyData | Just unifyData <- Builtin.Bool.matchBools first second = lift $ Builtin.Bool.unifyBool unifyData | Just unifyData <- Builtin.String.matchString first second = lift $ Builtin.String.unifyString unifyData | Just unifyData <- matchDomainValue first second = lift $ unifyDomainValue unifyData | Just unifyData <- matchStringLiteral first second = lift $ unifyStringLiteral unifyData | Just term <- matchEqualsAndEquals first second = lift $ equalAndEquals term | Just unifyData <- matchBytes first second = lift $ unifyBytes unifyData | Just matched <- matchVariables first second = lift $ unifyVariables matched | Just matched <- matchVariableFunction second first = lift $ unifyVariableFunction matched | Just unifyData <- matchEqualInjectiveHeadsAndEquals first second = lift $ equalInjectiveHeadsAndEquals childTransformers unifyData | Just unifyData <- matchInj injSimplifier first second = lift $ unifySortInjection childTransformers unifyData | Just unifyData <- matchConstructorSortInjectionAndEquals first second = lift $ constructorSortInjectionAndEquals unifyData | Just unifyData <- matchDifferentConstructors overloadSimplifier first second = lift $ constructorAndEqualsAssumesDifferentHeads unifyData | Just unifyData <- unifyOverloading overloadSimplifier (Pair first second) = lift $ overloadedConstructorSortInjectionAndEquals childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolAnd first second = lift $ Builtin.Bool.unifyBoolAnd childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolOr first second = lift $ Builtin.Bool.unifyBoolOr childTransformers unifyData | Just boolNotData <- Builtin.Bool.matchUnifyBoolNot first second = lift $ Builtin.Bool.unifyBoolNot childTransformers boolNotData | Just unifyData <- Builtin.KEqual.matchUnifyKequalsEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.Int.matchUnifyIntEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.String.matchUnifyStringEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.KEqual.matchIfThenElse first second = lift $ Builtin.KEqual.unifyIfThenElse childTransformers unifyData | Just unifyData <- Builtin.Endianness.matchUnifyEqualsEndianness first second = lift $ Builtin.Endianness.unifyEquals unifyData | Just unifyData <- Builtin.Signedness.matchUnifyEqualsSignedness first second = lift $ Builtin.Signedness.unifyEquals unifyData | Just unifyData <- Builtin.Map.matchUnifyEquals tools first second = lift $ Builtin.Map.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.Set.matchUnifyEquals tools first second = lift $ Builtin.Set.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.List.matchUnifyEqualsList tools first second = lift $ Builtin.List.unifyEquals childTransformers tools unifyData | Just unifyData <- matchDomainValueAndConstructorErrors first second = lift $ domainValueAndConstructorErrors unifyData | Just unifyData <- matchFunctionAnd first second = return $ functionAnd unifyData | otherwise = empty | Construct the conjunction or unification of two terms . Each @TermTransformationOld@ should represent one unification case and each unification case should be handled by only one @TermTransformationOld@. If the pattern heads do not match the case under consideration , call ' empty ' to allow another case to handle the patterns . If the pattern heads do match the unification case , then use ' lift ' to wrap the implementation of that case . All the @TermTransformationOld@s and similar functions defined in this module call ' empty ' unless given patterns matching their unification case . Each @TermTransformationOld@ should represent one unification case and each unification case should be handled by only one @TermTransformationOld@. If the pattern heads do not match the case under consideration, call 'empty' to allow another case to handle the patterns. If the pattern heads do match the unification case, then use 'lift' to wrap the implementation of that case. All the @TermTransformationOld@s and similar functions defined in this module call 'empty' unless given patterns matching their unification case. -} type TermTransformationOld variable unifier = TermSimplifier variable unifier -> TermLike variable -> TermLike variable -> MaybeT unifier (Pattern variable) data UnifyBoolAnd = UnifyBoolAndBottom !Sort !(TermLike RewritingVariableName) | UnifyBoolAndTop !(TermLike RewritingVariableName) | Matches @ \\and{_}(\\bottom , _ ) @ and @ \\and{_}(\\top , _ ) , @ symmetric in the two arguments . @ \\and{_}(\\bottom, _) @ and @ \\and{_}(\\top, _), @ symmetric in the two arguments. -} matchBoolAnd :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyBoolAnd matchBoolAnd term1 term2 | Pattern.isBottom term1 = let sort = termLikeSort term1 in Just $ UnifyBoolAndBottom sort term2 | Pattern.isTop term1 = Just $ UnifyBoolAndTop term2 | Pattern.isBottom term2 = let sort = termLikeSort term2 in Just $ UnifyBoolAndBottom sort term1 | Pattern.isTop term2 = Just $ UnifyBoolAndTop term1 | otherwise = Nothing # INLINE matchBoolAnd # -- | Simplify the conjunction of terms where one is a predicate. boolAnd :: MonadUnify unifier => UnifyBoolAnd -> unifier (Pattern RewritingVariableName) boolAnd unifyData = case unifyData of UnifyBoolAndBottom sort term -> do explainBoolAndBottom term sort return $ Pattern.fromTermLike $ mkBottom sort UnifyBoolAndTop term -> do return $ Pattern.fromTermLike term explainBoolAndBottom :: MonadUnify unifier => TermLike RewritingVariableName -> Sort -> unifier () explainBoolAndBottom term sort = debugUnifyBottom "Cannot unify bottom." (mkBottom sort) term {- | Matches @ \\equals{_, _}(t, t) @ and @ \\and{_}(t, t) @ -} matchEqualsAndEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe (TermLike RewritingVariableName) matchEqualsAndEquals first second | first == second = Just first | otherwise = Nothing # INLINE matchEqualsAndEquals # -- | Returns the term as a pattern. equalAndEquals :: Monad unifier => TermLike RewritingVariableName -> unifier (Pattern RewritingVariableName) equalAndEquals term = TODO ( thomas.tuegel ): Preserve simplified flags . return (Pattern.fromTermLike term) data BottomTermEquals = BottomTermEquals { sort :: !Sort , term :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( \\bottom , _ ) , @ symmetric in the two arguments . @ \\equals{_, _}(\\bottom, _), @ symmetric in the two arguments. -} matchBottomTermEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe BottomTermEquals matchBottomTermEquals first second | Bottom_ sort <- first = Just BottomTermEquals{sort, term = second} | Bottom_ sort <- second = Just BottomTermEquals{sort, term = first} | otherwise = Nothing # INLINE matchBottomTermEquals # | Unify two patterns where the first is @\\bottom@. bottomTermEquals :: MonadUnify unifier => Sort -> SideCondition RewritingVariableName -> BottomTermEquals -> unifier (Pattern RewritingVariableName) bottomTermEquals resultSort sideCondition unifyData = do MonadUnify secondCeil <- liftSimplifier $ makeEvaluateTermCeil sideCondition term case toList secondCeil of [] -> return (Pattern.topOf resultSort) [Conditional{predicate = PredicateTrue, substitution}] | substitution == mempty -> debugUnifyBottomAndReturnBottom "Cannot unify bottom with non-bottom pattern." (mkBottom sort) term _ -> return Conditional { term = mkTop resultSort , predicate = makeNotPredicate $ OrCondition.toPredicate $ OrPattern.map Condition.toPredicate secondCeil , substitution = mempty } where BottomTermEquals{sort, term} = unifyData data UnifyVariables = UnifyVariables {variable1, variable2 :: !(ElementVariable RewritingVariableName)} | Match the unification of two element variables . matchVariables :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyVariables matchVariables first second = do ElemVar_ variable1 <- pure first ElemVar_ variable2 <- pure second pure UnifyVariables{variable1, variable2} # INLINE matchVariables # unifyVariables :: MonadUnify unifier => UnifyVariables -> unifier (Pattern RewritingVariableName) unifyVariables UnifyVariables{variable1, variable2} = pure $ Pattern.assign (inject variable1) (mkElemVar variable2) data UnifyVariableFunction = UnifyVariableFunction { variable :: !(ElementVariable RewritingVariableName) , term :: !(TermLike RewritingVariableName) } -- | Match the unification of an element variable with a function-like term. matchVariableFunction :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyVariableFunction matchVariableFunction = \first second -> worker first second <|> worker second first where worker first term = do ElemVar_ variable <- pure first guard (isFunctionPattern term) pure UnifyVariableFunction{variable, term} # INLINE matchVariableFunction # unifyVariableFunction :: MonadUnify unifier => UnifyVariableFunction -> unifier (Pattern RewritingVariableName) unifyVariableFunction UnifyVariableFunction{variable, term} = Condition.assign (inject variable) term & Pattern.withCondition term & pure data VariableFunctionEquals = VariableFunctionEquals { var :: !(ElementVariable RewritingVariableName) , term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( x , f ( _ ) ) , @ symmetric in the two arguments . @ \\equals{_, _}(x, f(_)), @ symmetric in the two arguments. -} matchVariableFunctionEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe VariableFunctionEquals matchVariableFunctionEquals first second | ElemVar_ var <- first , isFunctionPattern second = Just VariableFunctionEquals{term1 = first, term2 = second, var} | ElemVar_ var <- second , isFunctionPattern first = Just VariableFunctionEquals{term1 = second, term2 = first, var} | otherwise = Nothing # INLINE matchVariableFunctionEquals # {- | Unify a variable with a function pattern. See also: 'isFunctionPattern' -} variableFunctionEquals :: MonadUnify unifier => VariableFunctionEquals -> unifier (Pattern RewritingVariableName) variableFunctionEquals unifyData = do MonadUnify predicate <- do resultOr <- liftSimplifier $ makeEvaluateTermCeil SideCondition.topTODO term2 case toList resultOr of [] -> debugUnifyBottomAndReturnBottom "Unification of variable and bottom \ \when attempting to simplify equals." term1 term2 resultConditions -> Unify.scatter resultConditions let result = predicate <> Condition.fromSingleSubstitution (Substitution.assign (inject var) term2) return (Pattern.withCondition term2 result) where VariableFunctionEquals{term1, term2, var} = unifyData data UnifyInjData = UnifyInjData { term1, term2 :: !(TermLike RewritingVariableName) , unifyInj :: !(UnifyInj (InjPair RewritingVariableName)) } | Matches @ \\equals { _ , _ } ( inj{sub , super}(children ) , inj{sub ' , super'}(children ' ) ) @ and @ \\and{_}(inj{sub , super}(children ) , inj{sub ' , super'}(children ' ) ) @ when either * @super /= super'@ * @sub = = sub'@ * @sub@ is a subsort of @sub'@ or vice - versa . * @children@ or @children'@ satisfies * the subsorts of @sub , sub'@ are disjoint . @ \\equals{_, _}(inj{sub, super}(children), inj{sub', super'}(children')) @ and @ \\and{_}(inj{sub, super}(children), inj{sub', super'}(children')) @ when either * @super /= super'@ * @sub == sub'@ * @sub@ is a subsort of @sub'@ or vice-versa. * @children@ or @children'@ satisfies @hasConstructorLikeTop@. * the subsorts of @sub, sub'@ are disjoint. -} matchInj :: InjSimplifier -> TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyInjData matchInj injSimplifier first second | Inj_ inj1 <- first , Inj_ inj2 <- second = UnifyInjData first second <$> matchInjs injSimplifier inj1 inj2 | otherwise = Nothing # INLINE matchInj # | Simplify the conjunction of two sort injections . Assumes that the two heads were already tested for equality and were found to be different . This simplifies cases where there is a subsort relation between the injected sorts of the conjoined patterns , such as , @ \inj{src1 , dst}(a ) ∧ \inj{src2 , dst}(b ) = = = \inj{src2 , , ) ∧ b ) @ when @src1@ is a subsort of Assumes that the two heads were already tested for equality and were found to be different. This simplifies cases where there is a subsort relation between the injected sorts of the conjoined patterns, such as, @ \inj{src1, dst}(a) ∧ \inj{src2, dst}(b) === \inj{src2, dst}(\inj{src1, src2}(a) ∧ b) @ when @src1@ is a subsort of @src2@. -} unifySortInjection :: forall unifier. MonadUnify unifier => TermSimplifier RewritingVariableName unifier -> UnifyInjData -> unifier (Pattern RewritingVariableName) unifySortInjection termMerger unifyData = do InjSimplifier{unifyInjs} <- Simplifier.askInjSimplifier unifyInjs unifyInj & maybe distinct merge where distinct = debugUnifyBottomAndReturnBottom "Distinct sort injections" term1 term2 merge inj@Inj{injChild = Pair child1 child2} = do childPattern <- termMerger child1 child2 InjSimplifier{evaluateInj} <- askInjSimplifier let (childTerm, childCondition) = Pattern.splitTerm childPattern inj' = evaluateInj inj{injChild = childTerm} return $ Pattern.withCondition inj' childCondition UnifyInjData{unifyInj, term1, term2} = unifyData data ConstructorSortInjectionAndEquals = ConstructorSortInjectionAndEquals { term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( inj { _ , _ } ( _ ) , c ( _ ) ) @ @ \\equals { _ , _ } ( c ( _ ) , inj { _ , _ } ( _ ) ) @ and @ \\and{_}(inj { _ , _ } ( _ ) , c ( _ ) ) @ @ \\and{_}(c ( _ ) , inj { _ , _ } ( _ ) ) @ when @c@ has the @constructor@ attribute . @ \\equals{_, _}(inj{_,_}(_), c(_)) @ @ \\equals{_, _}(c(_), inj{_,_}(_)) @ and @ \\and{_}(inj{_,_}(_), c(_)) @ @ \\and{_}(c(_), inj{_,_}(_)) @ when @c@ has the @constructor@ attribute. -} matchConstructorSortInjectionAndEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe ConstructorSortInjectionAndEquals matchConstructorSortInjectionAndEquals first second | Inj_ _ <- first , App_ symbol _ <- second , Symbol.isConstructor symbol = Just ConstructorSortInjectionAndEquals{term1 = first, term2 = second} | Inj_ _ <- second , App_ symbol _ <- first , Symbol.isConstructor symbol = Just ConstructorSortInjectionAndEquals{term1 = first, term2 = second} | otherwise = Nothing # INLINE matchConstructorSortInjectionAndEquals # {- | Unify a constructor application pattern with a sort injection pattern. Sort injections clash with constructors, so @constructorSortInjectionAndEquals@ returns @\\bottom@. -} constructorSortInjectionAndEquals :: MonadUnify unifier => ConstructorSortInjectionAndEquals -> unifier a constructorSortInjectionAndEquals unifyData = noConfusionInjectionConstructor term1 term2 where ConstructorSortInjectionAndEquals{term1, term2} = unifyData noConfusionInjectionConstructor :: MonadUnify unifier => TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier a noConfusionInjectionConstructor term1 term2 = debugUnifyBottomAndReturnBottom "No confusion: sort injections and constructors" term1 term2 | If the two constructors form an overload pair , apply the overloading axioms on the terms to make the constructors equal , then retry unification on them . See < -backend/blob/master/docs/2019-08-27-Unification-modulo-overloaded-constructors.md > If the two constructors form an overload pair, apply the overloading axioms on the terms to make the constructors equal, then retry unification on them. See <-backend/blob/master/docs/2019-08-27-Unification-modulo-overloaded-constructors.md> -} overloadedConstructorSortInjectionAndEquals :: MonadUnify unifier => TermSimplifier RewritingVariableName unifier -> OverloadingData -> unifier (Pattern RewritingVariableName) overloadedConstructorSortInjectionAndEquals termMerger unifyData = case matchResult of Resolution (Simple (Pair firstTerm' secondTerm')) -> termMerger firstTerm' secondTerm' Resolution ( WithNarrowing Narrowing { narrowingSubst , narrowingVars , overloadPair = Pair firstTerm' secondTerm' } ) -> do boundPattern <- do merged <- termMerger firstTerm' secondTerm' liftSimplifier $ Exists.makeEvaluate SideCondition.topTODO narrowingVars $ merged `Pattern.andCondition` narrowingSubst case OrPattern.toPatterns boundPattern of [result] -> return result [] -> debugUnifyBottomAndReturnBottom ( "exists simplification for overloaded" <> " constructors returned no pattern" ) term1 term2 _ -> scatter boundPattern ClashResult message -> debugUnifyBottomAndReturnBottom (fromString message) term1 term2 where OverloadingData{term1, term2, matchResult} = unifyData data DVConstrError = DVConstr !(TermLike RewritingVariableName) !(TermLike RewritingVariableName) | ConstrDV !(TermLike RewritingVariableName) !(TermLike RewritingVariableName) | Matches @ \\equals { _ , _ } ( \\dv { _ } ( _ ) , c ( _ ) ) @ @ \\equals { _ , _ } ( c ( _ ) , \\dv { _ } ( _ ) ) @ @ \\and{_}(\\dv { _ } ( _ ) , c ( _ ) ) @ @ \\and{_}(c ( _ ) , \\dv { _ } ( _ ) ) @ when @c@ is a constructor . @ \\equals{_, _}(\\dv{_}(_), c(_)) @ @ \\equals{_, _}(c(_), \\dv{_}(_)) @ @ \\and{_}(\\dv{_}(_), c(_)) @ @ \\and{_}(c(_), \\dv{_}(_)) @ when @c@ is a constructor. -} matchDomainValueAndConstructorErrors :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe DVConstrError matchDomainValueAndConstructorErrors first second | DV_ _ _ <- first , App_ secondHead _ <- second , Symbol.isConstructor secondHead = Just $ DVConstr first second | App_ firstHead _ <- first , Symbol.isConstructor firstHead , DV_ _ _ <- second = Just $ ConstrDV first second | otherwise = Nothing {- | Unifcation or equality for a domain value pattern vs a constructor application. This unification case throws an error because domain values may not occur in a sort with constructors. -} domainValueAndConstructorErrors :: HasCallStack => DVConstrError -> unifier a domainValueAndConstructorErrors unifyData = error $ show ( Pretty.vsep [ cannotHandle , fromString $ unparseToString term1 , fromString $ unparseToString term2 , "" ] ) where (term1, term2, cannotHandle) = case unifyData of DVConstr a b -> (a, b, "Cannot handle DomainValue and Constructor:") ConstrDV a b -> (a, b, "Cannot handle Constructor and DomainValue:") data UnifyDomainValue = UnifyDomainValue { val1, val2 :: !(TermLike RewritingVariableName) , term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( \\dv{s } ( _ ) , \\dv{s } ( _ ) ) @ and @ \\and{_}(\\dv{s } ( _ ) , \\dv{s } ( _ ) ) @ @ \\equals{_, _}(\\dv{s}(_), \\dv{s}(_)) @ and @ \\and{_}(\\dv{s}(_), \\dv{s}(_)) @ -} matchDomainValue :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyDomainValue matchDomainValue term1 term2 | DV_ sort1 val1 <- term1 , DV_ sort2 val2 <- term2 , sort1 == sort2 = Just UnifyDomainValue{val1, val2, term1, term2} | otherwise = Nothing # INLINE matchDomainValue # | Unify two domain values . The two patterns are assumed to be inequal ; therefore this case always return @\\bottom@. See also : ' equalAndEquals ' The two patterns are assumed to be inequal; therefore this case always return @\\bottom@. See also: 'equalAndEquals' -} TODO ( thomas.tuegel ): This unification case assumes that \dv is injective , -- but it is not. unifyDomainValue :: forall unifier. MonadUnify unifier => UnifyDomainValue -> unifier (Pattern RewritingVariableName) unifyDomainValue unifyData | val1 == val2 = return $ Pattern.fromTermLike term1 | otherwise = cannotUnifyDomainValues term1 term2 where UnifyDomainValue{val1, val2, term1, term2} = unifyData cannotUnifyDistinctDomainValues :: Text cannotUnifyDistinctDomainValues = "distinct domain values" cannotUnifyDomainValues :: MonadUnify unifier => TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier a cannotUnifyDomainValues term1 term2 = debugUnifyBottomAndReturnBottom cannotUnifyDistinctDomainValues term1 term2 | @UnifyStringLiteral@ represents unification of two string literals . data UnifyStringLiteral = UnifyStringLiteral { txt1, txt2 :: !Text , term1, term2 :: !(TermLike RewritingVariableName) } -- | Matches the unification problem @"txt1"@ with @"txt2"@. matchStringLiteral :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyStringLiteral matchStringLiteral term1 term2 | StringLiteral_ txt1 <- term1 , StringLiteral_ txt2 <- term2 = Just UnifyStringLiteral{txt1, txt2, term1, term2} | otherwise = Nothing # INLINE matchStringLiteral # -- | Finish solving the 'UnifyStringLiteral' problem. unifyStringLiteral :: forall unifier. MonadUnify unifier => UnifyStringLiteral -> unifier (Pattern RewritingVariableName) unifyStringLiteral unifyData | txt1 == txt2 = return $ Pattern.fromTermLike term1 | otherwise = debugUnifyBottomAndReturnBottom "distinct string literals" term1 term2 where UnifyStringLiteral{txt1, txt2, term1, term2} = unifyData data FunctionAnd = FunctionAnd { term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\and{_}(f ( _ ) , ( _ ) ) @ @ \\and{_}(f(_), g(_)) @ -} matchFunctionAnd :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe FunctionAnd matchFunctionAnd term1 term2 | isFunctionPattern term1 , isFunctionPattern term2 = Just FunctionAnd{term1, term2} | otherwise = Nothing # INLINE matchFunctionAnd # | Unify any two function patterns . The function patterns are unified by creating an @\\equals@ predicate . If either argument is constructor - like , that argument will be the resulting ' term ' ; otherwise , the lesser argument is the resulting ' term ' . The term always appears on the left - hand side of the @\\equals@ predicate , and the other argument appears on the right - hand side . The function patterns are unified by creating an @\\equals@ predicate. If either argument is constructor-like, that argument will be the resulting 'term'; otherwise, the lesser argument is the resulting 'term'. The term always appears on the left-hand side of the @\\equals@ predicate, and the other argument appears on the right-hand side. -} functionAnd :: FunctionAnd -> Pattern RewritingVariableName functionAnd FunctionAnd{term1, term2} = makeEqualsPredicate first' second' & Predicate.markSimplified Ceil predicate not needed since first being -- bottom will make the entire term bottom. However, -- one must be careful to not just drop the term. & Condition.fromPredicate & Pattern.withCondition first' -- different for Equals where (first', second') = minMaxBy compareForEquals term1 term2 {- | Normal ordering for terms in @\equals(_, _)@. The normal ordering is arbitrary, but important to avoid duplication. -} compareForEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Ordering compareForEquals first second | isConstructorLike first = LT | isConstructorLike second = GT | otherwise = compare first second
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/f2c86d14fcc67aaa580b9913f9bccbc56c5281a3/kore/src/Kore/Simplify/AndTerms.hs
haskell
| Used to simplify subterm "and". | Used to simplify subterm "and". | Simplify the conjunction of terms where one is a predicate. | Matches @ \\equals{_, _}(t, t) @ and @ \\and{_}(t, t) @ | Returns the term as a pattern. | Match the unification of an element variable with a function-like term. | Unify a variable with a function pattern. See also: 'isFunctionPattern' | Unify a constructor application pattern with a sort injection pattern. Sort injections clash with constructors, so @constructorSortInjectionAndEquals@ returns @\\bottom@. | Unifcation or equality for a domain value pattern vs a constructor application. This unification case throws an error because domain values may not occur in a sort with constructors. but it is not. | Matches the unification problem @"txt1"@ with @"txt2"@. | Finish solving the 'UnifyStringLiteral' problem. bottom will make the entire term bottom. However, one must be careful to not just drop the term. different for Equals | Normal ordering for terms in @\equals(_, _)@. The normal ordering is arbitrary, but important to avoid duplication.
| Copyright : ( c ) Runtime Verification , 2018 - 2021 License : BSD-3 - Clause Copyright : (c) Runtime Verification, 2018-2021 License : BSD-3-Clause -} module Kore.Simplify.AndTerms ( termUnification, maybeTermAnd, maybeTermEquals, TermSimplifier, TermTransformationOld, cannotUnifyDistinctDomainValues, functionAnd, matchFunctionAnd, compareForEquals, FunctionAnd (..), ) where import Control.Error ( MaybeT (..), ) import Control.Error qualified as Error import Data.String ( fromString, ) import Data.Text ( Text, ) import Kore.Builtin.Bool qualified as Builtin.Bool import Kore.Builtin.Builtin qualified as Builtin import Kore.Builtin.Endianness qualified as Builtin.Endianness import Kore.Builtin.Int qualified as Builtin.Int import Kore.Builtin.InternalBytes ( matchBytes, unifyBytes, ) import Kore.Builtin.KEqual qualified as Builtin.KEqual import Kore.Builtin.List qualified as Builtin.List import Kore.Builtin.Map qualified as Builtin.Map import Kore.Builtin.Set qualified as Builtin.Set import Kore.Builtin.Signedness qualified as Builtin.Signedness import Kore.Builtin.String qualified as Builtin.String import Kore.Internal.Condition as Condition import Kore.Internal.OrCondition qualified as OrCondition import Kore.Internal.OrPattern qualified as OrPattern import Kore.Internal.Pattern ( Pattern, ) import Kore.Internal.Pattern qualified as Pattern import Kore.Internal.Predicate ( makeEqualsPredicate, makeNotPredicate, pattern PredicateTrue, ) import Kore.Internal.Predicate qualified as Predicate import Kore.Internal.SideCondition ( SideCondition, ) import Kore.Internal.SideCondition qualified as SideCondition ( topTODO, ) import Kore.Internal.Substitution qualified as Substitution import Kore.Internal.Symbol qualified as Symbol import Kore.Internal.TermLike import Kore.Log.DebugUnification ( debugUnificationSolved, debugUnificationUnsolved, whileDebugUnification, ) import Kore.Log.DebugUnifyBottom ( debugUnifyBottom, debugUnifyBottomAndReturnBottom, ) import Kore.Rewrite.RewritingVariable ( RewritingVariableName, ) import Kore.Simplify.Exists qualified as Exists import Kore.Simplify.ExpandAlias import Kore.Simplify.InjSimplifier import Kore.Simplify.NoConfusion import Kore.Simplify.NotSimplifier import Kore.Simplify.Overloading as Overloading import Kore.Simplify.Simplify as Simplifier import Kore.Sort ( sameSort, ) import Kore.Unification.Unify as Unify import Kore.Unparser import Pair import Prelude.Kore import Pretty qualified | Unify two terms without discarding the terms . We want to keep the terms because substitution relies on the result not being @\\bottom@. When a case is not implemented , @termUnification@ will create a @\\ceil@ of the conjunction of the two terms . The comment for ' Kore.Simplify.And.simplify ' describes all the special cases handled by this . We want to keep the terms because substitution relies on the result not being @\\bottom@. When a case is not implemented, @termUnification@ will create a @\\ceil@ of the conjunction of the two terms. The comment for 'Kore.Simplify.And.simplify' describes all the special cases handled by this. -} termUnification :: forall unifier. MonadUnify unifier => NotSimplifier Simplifier => HasCallStack => TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier (Pattern RewritingVariableName) termUnification = \term1 term2 -> whileDebugUnification term1 term2 $ do result <- termUnificationWorker term1 term2 debugUnificationSolved result pure result where termUnificationWorker :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier (Pattern RewritingVariableName) termUnificationWorker term1 term2 = do let maybeTermUnification :: MaybeT unifier (Pattern RewritingVariableName) maybeTermUnification = maybeTermAnd termUnificationWorker term1 term2 Error.maybeT (incompleteUnificationPattern term1 term2) pure maybeTermUnification incompleteUnificationPattern term1 term2 = do debugUnificationUnsolved term1 term2 mkAnd term1 term2 & Pattern.fromTermLike & return maybeTermEquals :: MonadUnify unifier => NotSimplifier Simplifier => HasCallStack => TermSimplifier RewritingVariableName unifier -> TermLike RewritingVariableName -> TermLike RewritingVariableName -> MaybeT unifier (Pattern RewritingVariableName) maybeTermEquals childTransformers first second = do injSimplifier <- Simplifier.askInjSimplifier overloadSimplifier <- Simplifier.askOverloadSimplifier tools <- Simplifier.askMetadataTools worker injSimplifier overloadSimplifier tools where worker injSimplifier overloadSimplifier tools | Just unifyData <- Builtin.Int.matchInt first second = lift $ Builtin.Int.unifyInt unifyData | Just unifyData <- Builtin.Bool.matchBools first second = lift $ Builtin.Bool.unifyBool unifyData | Just unifyData <- Builtin.String.matchString first second = lift $ Builtin.String.unifyString unifyData | Just unifyData <- matchDomainValue first second = lift $ unifyDomainValue unifyData | Just unifyData <- matchStringLiteral first second = lift $ unifyStringLiteral unifyData | Just term <- matchEqualsAndEquals first second = lift $ equalAndEquals term | Just unifyData <- matchBytes first second = lift $ unifyBytes unifyData | Just unifyData <- matchBottomTermEquals first second = lift $ bottomTermEquals (sameSort (termLikeSort first) (termLikeSort second)) SideCondition.topTODO unifyData | Just unifyData <- matchVariableFunctionEquals first second = lift $ variableFunctionEquals unifyData | Just unifyData <- matchEqualInjectiveHeadsAndEquals first second = lift $ equalInjectiveHeadsAndEquals childTransformers unifyData | Just unifyData <- matchInj injSimplifier first second = lift $ unifySortInjection childTransformers unifyData | Just unifyData <- matchConstructorSortInjectionAndEquals first second = lift $ constructorSortInjectionAndEquals unifyData | Just unifyData <- matchDifferentConstructors overloadSimplifier first second = lift $ constructorAndEqualsAssumesDifferentHeads unifyData | Just unifyData <- unifyOverloading overloadSimplifier (Pair first second) = lift $ overloadedConstructorSortInjectionAndEquals childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolAnd first second = lift $ Builtin.Bool.unifyBoolAnd childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolOr first second = lift $ Builtin.Bool.unifyBoolOr childTransformers unifyData | Just boolNotData <- Builtin.Bool.matchUnifyBoolNot first second = lift $ Builtin.Bool.unifyBoolNot childTransformers boolNotData | Just unifyData <- Builtin.Int.matchUnifyIntEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.String.matchUnifyStringEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.KEqual.matchUnifyKequalsEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.Endianness.matchUnifyEqualsEndianness first second = lift $ Builtin.Endianness.unifyEquals unifyData | Just unifyData <- Builtin.Signedness.matchUnifyEqualsSignedness first second = lift $ Builtin.Signedness.unifyEquals unifyData | Just unifyData <- Builtin.Map.matchUnifyEquals tools first second = lift $ Builtin.Map.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.Map.matchUnifyNotInKeys first second = lift $ Builtin.Map.unifyNotInKeys (sameSort (termLikeSort first) (termLikeSort second)) childTransformers unifyData | Just unifyData <- Builtin.Set.matchUnifyEquals tools first second = lift $ Builtin.Set.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.List.matchUnifyEqualsList tools first second = lift $ Builtin.List.unifyEquals childTransformers tools unifyData | Just unifyData <- matchDomainValueAndConstructorErrors first second = lift $ domainValueAndConstructorErrors unifyData | otherwise = empty maybeTermAnd :: MonadUnify unifier => NotSimplifier Simplifier => HasCallStack => TermSimplifier RewritingVariableName unifier -> TermLike RewritingVariableName -> TermLike RewritingVariableName -> MaybeT unifier (Pattern RewritingVariableName) maybeTermAnd childTransformers first second = do injSimplifier <- Simplifier.askInjSimplifier overloadSimplifier <- Simplifier.askOverloadSimplifier tools <- Simplifier.askMetadataTools worker injSimplifier overloadSimplifier tools where worker injSimplifier overloadSimplifier tools | Just unifyData <- matchExpandAlias first second = let UnifyExpandAlias{term1, term2} = unifyData in maybeTermAnd childTransformers term1 term2 | Just unifyData <- matchBoolAnd first second = lift $ boolAnd unifyData | Just unifyData <- Builtin.Int.matchInt first second = lift $ Builtin.Int.unifyInt unifyData | Just unifyData <- Builtin.Bool.matchBools first second = lift $ Builtin.Bool.unifyBool unifyData | Just unifyData <- Builtin.String.matchString first second = lift $ Builtin.String.unifyString unifyData | Just unifyData <- matchDomainValue first second = lift $ unifyDomainValue unifyData | Just unifyData <- matchStringLiteral first second = lift $ unifyStringLiteral unifyData | Just term <- matchEqualsAndEquals first second = lift $ equalAndEquals term | Just unifyData <- matchBytes first second = lift $ unifyBytes unifyData | Just matched <- matchVariables first second = lift $ unifyVariables matched | Just matched <- matchVariableFunction second first = lift $ unifyVariableFunction matched | Just unifyData <- matchEqualInjectiveHeadsAndEquals first second = lift $ equalInjectiveHeadsAndEquals childTransformers unifyData | Just unifyData <- matchInj injSimplifier first second = lift $ unifySortInjection childTransformers unifyData | Just unifyData <- matchConstructorSortInjectionAndEquals first second = lift $ constructorSortInjectionAndEquals unifyData | Just unifyData <- matchDifferentConstructors overloadSimplifier first second = lift $ constructorAndEqualsAssumesDifferentHeads unifyData | Just unifyData <- unifyOverloading overloadSimplifier (Pair first second) = lift $ overloadedConstructorSortInjectionAndEquals childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolAnd first second = lift $ Builtin.Bool.unifyBoolAnd childTransformers unifyData | Just unifyData <- Builtin.Bool.matchUnifyBoolOr first second = lift $ Builtin.Bool.unifyBoolOr childTransformers unifyData | Just boolNotData <- Builtin.Bool.matchUnifyBoolNot first second = lift $ Builtin.Bool.unifyBoolNot childTransformers boolNotData | Just unifyData <- Builtin.KEqual.matchUnifyKequalsEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.Int.matchUnifyIntEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.String.matchUnifyStringEq first second = lift $ Builtin.unifyEq childTransformers unifyData | Just unifyData <- Builtin.KEqual.matchIfThenElse first second = lift $ Builtin.KEqual.unifyIfThenElse childTransformers unifyData | Just unifyData <- Builtin.Endianness.matchUnifyEqualsEndianness first second = lift $ Builtin.Endianness.unifyEquals unifyData | Just unifyData <- Builtin.Signedness.matchUnifyEqualsSignedness first second = lift $ Builtin.Signedness.unifyEquals unifyData | Just unifyData <- Builtin.Map.matchUnifyEquals tools first second = lift $ Builtin.Map.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.Set.matchUnifyEquals tools first second = lift $ Builtin.Set.unifyEquals childTransformers tools unifyData | Just unifyData <- Builtin.List.matchUnifyEqualsList tools first second = lift $ Builtin.List.unifyEquals childTransformers tools unifyData | Just unifyData <- matchDomainValueAndConstructorErrors first second = lift $ domainValueAndConstructorErrors unifyData | Just unifyData <- matchFunctionAnd first second = return $ functionAnd unifyData | otherwise = empty | Construct the conjunction or unification of two terms . Each @TermTransformationOld@ should represent one unification case and each unification case should be handled by only one @TermTransformationOld@. If the pattern heads do not match the case under consideration , call ' empty ' to allow another case to handle the patterns . If the pattern heads do match the unification case , then use ' lift ' to wrap the implementation of that case . All the @TermTransformationOld@s and similar functions defined in this module call ' empty ' unless given patterns matching their unification case . Each @TermTransformationOld@ should represent one unification case and each unification case should be handled by only one @TermTransformationOld@. If the pattern heads do not match the case under consideration, call 'empty' to allow another case to handle the patterns. If the pattern heads do match the unification case, then use 'lift' to wrap the implementation of that case. All the @TermTransformationOld@s and similar functions defined in this module call 'empty' unless given patterns matching their unification case. -} type TermTransformationOld variable unifier = TermSimplifier variable unifier -> TermLike variable -> TermLike variable -> MaybeT unifier (Pattern variable) data UnifyBoolAnd = UnifyBoolAndBottom !Sort !(TermLike RewritingVariableName) | UnifyBoolAndTop !(TermLike RewritingVariableName) | Matches @ \\and{_}(\\bottom , _ ) @ and @ \\and{_}(\\top , _ ) , @ symmetric in the two arguments . @ \\and{_}(\\bottom, _) @ and @ \\and{_}(\\top, _), @ symmetric in the two arguments. -} matchBoolAnd :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyBoolAnd matchBoolAnd term1 term2 | Pattern.isBottom term1 = let sort = termLikeSort term1 in Just $ UnifyBoolAndBottom sort term2 | Pattern.isTop term1 = Just $ UnifyBoolAndTop term2 | Pattern.isBottom term2 = let sort = termLikeSort term2 in Just $ UnifyBoolAndBottom sort term1 | Pattern.isTop term2 = Just $ UnifyBoolAndTop term1 | otherwise = Nothing # INLINE matchBoolAnd # boolAnd :: MonadUnify unifier => UnifyBoolAnd -> unifier (Pattern RewritingVariableName) boolAnd unifyData = case unifyData of UnifyBoolAndBottom sort term -> do explainBoolAndBottom term sort return $ Pattern.fromTermLike $ mkBottom sort UnifyBoolAndTop term -> do return $ Pattern.fromTermLike term explainBoolAndBottom :: MonadUnify unifier => TermLike RewritingVariableName -> Sort -> unifier () explainBoolAndBottom term sort = debugUnifyBottom "Cannot unify bottom." (mkBottom sort) term matchEqualsAndEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe (TermLike RewritingVariableName) matchEqualsAndEquals first second | first == second = Just first | otherwise = Nothing # INLINE matchEqualsAndEquals # equalAndEquals :: Monad unifier => TermLike RewritingVariableName -> unifier (Pattern RewritingVariableName) equalAndEquals term = TODO ( thomas.tuegel ): Preserve simplified flags . return (Pattern.fromTermLike term) data BottomTermEquals = BottomTermEquals { sort :: !Sort , term :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( \\bottom , _ ) , @ symmetric in the two arguments . @ \\equals{_, _}(\\bottom, _), @ symmetric in the two arguments. -} matchBottomTermEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe BottomTermEquals matchBottomTermEquals first second | Bottom_ sort <- first = Just BottomTermEquals{sort, term = second} | Bottom_ sort <- second = Just BottomTermEquals{sort, term = first} | otherwise = Nothing # INLINE matchBottomTermEquals # | Unify two patterns where the first is @\\bottom@. bottomTermEquals :: MonadUnify unifier => Sort -> SideCondition RewritingVariableName -> BottomTermEquals -> unifier (Pattern RewritingVariableName) bottomTermEquals resultSort sideCondition unifyData = do MonadUnify secondCeil <- liftSimplifier $ makeEvaluateTermCeil sideCondition term case toList secondCeil of [] -> return (Pattern.topOf resultSort) [Conditional{predicate = PredicateTrue, substitution}] | substitution == mempty -> debugUnifyBottomAndReturnBottom "Cannot unify bottom with non-bottom pattern." (mkBottom sort) term _ -> return Conditional { term = mkTop resultSort , predicate = makeNotPredicate $ OrCondition.toPredicate $ OrPattern.map Condition.toPredicate secondCeil , substitution = mempty } where BottomTermEquals{sort, term} = unifyData data UnifyVariables = UnifyVariables {variable1, variable2 :: !(ElementVariable RewritingVariableName)} | Match the unification of two element variables . matchVariables :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyVariables matchVariables first second = do ElemVar_ variable1 <- pure first ElemVar_ variable2 <- pure second pure UnifyVariables{variable1, variable2} # INLINE matchVariables # unifyVariables :: MonadUnify unifier => UnifyVariables -> unifier (Pattern RewritingVariableName) unifyVariables UnifyVariables{variable1, variable2} = pure $ Pattern.assign (inject variable1) (mkElemVar variable2) data UnifyVariableFunction = UnifyVariableFunction { variable :: !(ElementVariable RewritingVariableName) , term :: !(TermLike RewritingVariableName) } matchVariableFunction :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyVariableFunction matchVariableFunction = \first second -> worker first second <|> worker second first where worker first term = do ElemVar_ variable <- pure first guard (isFunctionPattern term) pure UnifyVariableFunction{variable, term} # INLINE matchVariableFunction # unifyVariableFunction :: MonadUnify unifier => UnifyVariableFunction -> unifier (Pattern RewritingVariableName) unifyVariableFunction UnifyVariableFunction{variable, term} = Condition.assign (inject variable) term & Pattern.withCondition term & pure data VariableFunctionEquals = VariableFunctionEquals { var :: !(ElementVariable RewritingVariableName) , term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( x , f ( _ ) ) , @ symmetric in the two arguments . @ \\equals{_, _}(x, f(_)), @ symmetric in the two arguments. -} matchVariableFunctionEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe VariableFunctionEquals matchVariableFunctionEquals first second | ElemVar_ var <- first , isFunctionPattern second = Just VariableFunctionEquals{term1 = first, term2 = second, var} | ElemVar_ var <- second , isFunctionPattern first = Just VariableFunctionEquals{term1 = second, term2 = first, var} | otherwise = Nothing # INLINE matchVariableFunctionEquals # variableFunctionEquals :: MonadUnify unifier => VariableFunctionEquals -> unifier (Pattern RewritingVariableName) variableFunctionEquals unifyData = do MonadUnify predicate <- do resultOr <- liftSimplifier $ makeEvaluateTermCeil SideCondition.topTODO term2 case toList resultOr of [] -> debugUnifyBottomAndReturnBottom "Unification of variable and bottom \ \when attempting to simplify equals." term1 term2 resultConditions -> Unify.scatter resultConditions let result = predicate <> Condition.fromSingleSubstitution (Substitution.assign (inject var) term2) return (Pattern.withCondition term2 result) where VariableFunctionEquals{term1, term2, var} = unifyData data UnifyInjData = UnifyInjData { term1, term2 :: !(TermLike RewritingVariableName) , unifyInj :: !(UnifyInj (InjPair RewritingVariableName)) } | Matches @ \\equals { _ , _ } ( inj{sub , super}(children ) , inj{sub ' , super'}(children ' ) ) @ and @ \\and{_}(inj{sub , super}(children ) , inj{sub ' , super'}(children ' ) ) @ when either * @super /= super'@ * @sub = = sub'@ * @sub@ is a subsort of @sub'@ or vice - versa . * @children@ or @children'@ satisfies * the subsorts of @sub , sub'@ are disjoint . @ \\equals{_, _}(inj{sub, super}(children), inj{sub', super'}(children')) @ and @ \\and{_}(inj{sub, super}(children), inj{sub', super'}(children')) @ when either * @super /= super'@ * @sub == sub'@ * @sub@ is a subsort of @sub'@ or vice-versa. * @children@ or @children'@ satisfies @hasConstructorLikeTop@. * the subsorts of @sub, sub'@ are disjoint. -} matchInj :: InjSimplifier -> TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyInjData matchInj injSimplifier first second | Inj_ inj1 <- first , Inj_ inj2 <- second = UnifyInjData first second <$> matchInjs injSimplifier inj1 inj2 | otherwise = Nothing # INLINE matchInj # | Simplify the conjunction of two sort injections . Assumes that the two heads were already tested for equality and were found to be different . This simplifies cases where there is a subsort relation between the injected sorts of the conjoined patterns , such as , @ \inj{src1 , dst}(a ) ∧ \inj{src2 , dst}(b ) = = = \inj{src2 , , ) ∧ b ) @ when @src1@ is a subsort of Assumes that the two heads were already tested for equality and were found to be different. This simplifies cases where there is a subsort relation between the injected sorts of the conjoined patterns, such as, @ \inj{src1, dst}(a) ∧ \inj{src2, dst}(b) === \inj{src2, dst}(\inj{src1, src2}(a) ∧ b) @ when @src1@ is a subsort of @src2@. -} unifySortInjection :: forall unifier. MonadUnify unifier => TermSimplifier RewritingVariableName unifier -> UnifyInjData -> unifier (Pattern RewritingVariableName) unifySortInjection termMerger unifyData = do InjSimplifier{unifyInjs} <- Simplifier.askInjSimplifier unifyInjs unifyInj & maybe distinct merge where distinct = debugUnifyBottomAndReturnBottom "Distinct sort injections" term1 term2 merge inj@Inj{injChild = Pair child1 child2} = do childPattern <- termMerger child1 child2 InjSimplifier{evaluateInj} <- askInjSimplifier let (childTerm, childCondition) = Pattern.splitTerm childPattern inj' = evaluateInj inj{injChild = childTerm} return $ Pattern.withCondition inj' childCondition UnifyInjData{unifyInj, term1, term2} = unifyData data ConstructorSortInjectionAndEquals = ConstructorSortInjectionAndEquals { term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( inj { _ , _ } ( _ ) , c ( _ ) ) @ @ \\equals { _ , _ } ( c ( _ ) , inj { _ , _ } ( _ ) ) @ and @ \\and{_}(inj { _ , _ } ( _ ) , c ( _ ) ) @ @ \\and{_}(c ( _ ) , inj { _ , _ } ( _ ) ) @ when @c@ has the @constructor@ attribute . @ \\equals{_, _}(inj{_,_}(_), c(_)) @ @ \\equals{_, _}(c(_), inj{_,_}(_)) @ and @ \\and{_}(inj{_,_}(_), c(_)) @ @ \\and{_}(c(_), inj{_,_}(_)) @ when @c@ has the @constructor@ attribute. -} matchConstructorSortInjectionAndEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe ConstructorSortInjectionAndEquals matchConstructorSortInjectionAndEquals first second | Inj_ _ <- first , App_ symbol _ <- second , Symbol.isConstructor symbol = Just ConstructorSortInjectionAndEquals{term1 = first, term2 = second} | Inj_ _ <- second , App_ symbol _ <- first , Symbol.isConstructor symbol = Just ConstructorSortInjectionAndEquals{term1 = first, term2 = second} | otherwise = Nothing # INLINE matchConstructorSortInjectionAndEquals # constructorSortInjectionAndEquals :: MonadUnify unifier => ConstructorSortInjectionAndEquals -> unifier a constructorSortInjectionAndEquals unifyData = noConfusionInjectionConstructor term1 term2 where ConstructorSortInjectionAndEquals{term1, term2} = unifyData noConfusionInjectionConstructor :: MonadUnify unifier => TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier a noConfusionInjectionConstructor term1 term2 = debugUnifyBottomAndReturnBottom "No confusion: sort injections and constructors" term1 term2 | If the two constructors form an overload pair , apply the overloading axioms on the terms to make the constructors equal , then retry unification on them . See < -backend/blob/master/docs/2019-08-27-Unification-modulo-overloaded-constructors.md > If the two constructors form an overload pair, apply the overloading axioms on the terms to make the constructors equal, then retry unification on them. See <-backend/blob/master/docs/2019-08-27-Unification-modulo-overloaded-constructors.md> -} overloadedConstructorSortInjectionAndEquals :: MonadUnify unifier => TermSimplifier RewritingVariableName unifier -> OverloadingData -> unifier (Pattern RewritingVariableName) overloadedConstructorSortInjectionAndEquals termMerger unifyData = case matchResult of Resolution (Simple (Pair firstTerm' secondTerm')) -> termMerger firstTerm' secondTerm' Resolution ( WithNarrowing Narrowing { narrowingSubst , narrowingVars , overloadPair = Pair firstTerm' secondTerm' } ) -> do boundPattern <- do merged <- termMerger firstTerm' secondTerm' liftSimplifier $ Exists.makeEvaluate SideCondition.topTODO narrowingVars $ merged `Pattern.andCondition` narrowingSubst case OrPattern.toPatterns boundPattern of [result] -> return result [] -> debugUnifyBottomAndReturnBottom ( "exists simplification for overloaded" <> " constructors returned no pattern" ) term1 term2 _ -> scatter boundPattern ClashResult message -> debugUnifyBottomAndReturnBottom (fromString message) term1 term2 where OverloadingData{term1, term2, matchResult} = unifyData data DVConstrError = DVConstr !(TermLike RewritingVariableName) !(TermLike RewritingVariableName) | ConstrDV !(TermLike RewritingVariableName) !(TermLike RewritingVariableName) | Matches @ \\equals { _ , _ } ( \\dv { _ } ( _ ) , c ( _ ) ) @ @ \\equals { _ , _ } ( c ( _ ) , \\dv { _ } ( _ ) ) @ @ \\and{_}(\\dv { _ } ( _ ) , c ( _ ) ) @ @ \\and{_}(c ( _ ) , \\dv { _ } ( _ ) ) @ when @c@ is a constructor . @ \\equals{_, _}(\\dv{_}(_), c(_)) @ @ \\equals{_, _}(c(_), \\dv{_}(_)) @ @ \\and{_}(\\dv{_}(_), c(_)) @ @ \\and{_}(c(_), \\dv{_}(_)) @ when @c@ is a constructor. -} matchDomainValueAndConstructorErrors :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe DVConstrError matchDomainValueAndConstructorErrors first second | DV_ _ _ <- first , App_ secondHead _ <- second , Symbol.isConstructor secondHead = Just $ DVConstr first second | App_ firstHead _ <- first , Symbol.isConstructor firstHead , DV_ _ _ <- second = Just $ ConstrDV first second | otherwise = Nothing domainValueAndConstructorErrors :: HasCallStack => DVConstrError -> unifier a domainValueAndConstructorErrors unifyData = error $ show ( Pretty.vsep [ cannotHandle , fromString $ unparseToString term1 , fromString $ unparseToString term2 , "" ] ) where (term1, term2, cannotHandle) = case unifyData of DVConstr a b -> (a, b, "Cannot handle DomainValue and Constructor:") ConstrDV a b -> (a, b, "Cannot handle Constructor and DomainValue:") data UnifyDomainValue = UnifyDomainValue { val1, val2 :: !(TermLike RewritingVariableName) , term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\equals { _ , _ } ( \\dv{s } ( _ ) , \\dv{s } ( _ ) ) @ and @ \\and{_}(\\dv{s } ( _ ) , \\dv{s } ( _ ) ) @ @ \\equals{_, _}(\\dv{s}(_), \\dv{s}(_)) @ and @ \\and{_}(\\dv{s}(_), \\dv{s}(_)) @ -} matchDomainValue :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyDomainValue matchDomainValue term1 term2 | DV_ sort1 val1 <- term1 , DV_ sort2 val2 <- term2 , sort1 == sort2 = Just UnifyDomainValue{val1, val2, term1, term2} | otherwise = Nothing # INLINE matchDomainValue # | Unify two domain values . The two patterns are assumed to be inequal ; therefore this case always return @\\bottom@. See also : ' equalAndEquals ' The two patterns are assumed to be inequal; therefore this case always return @\\bottom@. See also: 'equalAndEquals' -} TODO ( thomas.tuegel ): This unification case assumes that \dv is injective , unifyDomainValue :: forall unifier. MonadUnify unifier => UnifyDomainValue -> unifier (Pattern RewritingVariableName) unifyDomainValue unifyData | val1 == val2 = return $ Pattern.fromTermLike term1 | otherwise = cannotUnifyDomainValues term1 term2 where UnifyDomainValue{val1, val2, term1, term2} = unifyData cannotUnifyDistinctDomainValues :: Text cannotUnifyDistinctDomainValues = "distinct domain values" cannotUnifyDomainValues :: MonadUnify unifier => TermLike RewritingVariableName -> TermLike RewritingVariableName -> unifier a cannotUnifyDomainValues term1 term2 = debugUnifyBottomAndReturnBottom cannotUnifyDistinctDomainValues term1 term2 | @UnifyStringLiteral@ represents unification of two string literals . data UnifyStringLiteral = UnifyStringLiteral { txt1, txt2 :: !Text , term1, term2 :: !(TermLike RewritingVariableName) } matchStringLiteral :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe UnifyStringLiteral matchStringLiteral term1 term2 | StringLiteral_ txt1 <- term1 , StringLiteral_ txt2 <- term2 = Just UnifyStringLiteral{txt1, txt2, term1, term2} | otherwise = Nothing # INLINE matchStringLiteral # unifyStringLiteral :: forall unifier. MonadUnify unifier => UnifyStringLiteral -> unifier (Pattern RewritingVariableName) unifyStringLiteral unifyData | txt1 == txt2 = return $ Pattern.fromTermLike term1 | otherwise = debugUnifyBottomAndReturnBottom "distinct string literals" term1 term2 where UnifyStringLiteral{txt1, txt2, term1, term2} = unifyData data FunctionAnd = FunctionAnd { term1, term2 :: !(TermLike RewritingVariableName) } | Matches @ \\and{_}(f ( _ ) , ( _ ) ) @ @ \\and{_}(f(_), g(_)) @ -} matchFunctionAnd :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Maybe FunctionAnd matchFunctionAnd term1 term2 | isFunctionPattern term1 , isFunctionPattern term2 = Just FunctionAnd{term1, term2} | otherwise = Nothing # INLINE matchFunctionAnd # | Unify any two function patterns . The function patterns are unified by creating an @\\equals@ predicate . If either argument is constructor - like , that argument will be the resulting ' term ' ; otherwise , the lesser argument is the resulting ' term ' . The term always appears on the left - hand side of the @\\equals@ predicate , and the other argument appears on the right - hand side . The function patterns are unified by creating an @\\equals@ predicate. If either argument is constructor-like, that argument will be the resulting 'term'; otherwise, the lesser argument is the resulting 'term'. The term always appears on the left-hand side of the @\\equals@ predicate, and the other argument appears on the right-hand side. -} functionAnd :: FunctionAnd -> Pattern RewritingVariableName functionAnd FunctionAnd{term1, term2} = makeEqualsPredicate first' second' & Predicate.markSimplified Ceil predicate not needed since first being & Condition.fromPredicate where (first', second') = minMaxBy compareForEquals term1 term2 compareForEquals :: TermLike RewritingVariableName -> TermLike RewritingVariableName -> Ordering compareForEquals first second | isConstructorLike first = LT | isConstructorLike second = GT | otherwise = compare first second
159fc2cdc6ef59950639294d668b5b69909819c3d7377510b8642a126e43a4ba
stevebleazard/ocaml-jsonxt
process.ml
let error msg _json = raise (Failure msg) module Internal = struct module type S = sig type json val null : unit -> json end module type Internal_strict_intf = sig type json val member : string -> [> `Assoc of (string * json) list ] -> json val index : int -> [> `List of json list ] -> json val map : (json -> json) -> [> `List of json list ] -> [> `List of json list ] val to_assoc : [> `Assoc of (string * json) list ] -> (string * json) list val to_bool : [> `Bool of bool ] -> bool val to_float : [> `Float of float ] -> float val to_string : [> `String of string ] -> string val to_string_option : [> `String of string | `Null ] -> string option val to_option : (([> `Null ] as 'a) -> json) -> 'a -> json option val to_list : [> `List of json list ] -> json list val to_bool_option : [> `Bool of bool | `Null ] -> bool option val to_float_option : [> `Float of float | `Null ] -> float option val to_number : [> `Float of float ] -> float val to_number_option : [> `Float of float | `Null ] -> float option val convert_each : (json -> json) -> [> `List of json list ] -> json list val rev_filter_map : ('a -> 'a option) -> 'a list -> 'a list -> 'a list val filter_map : ('a -> 'a option) -> 'a list -> 'a list val rev_flatten : 'a list -> [> `List of 'a list ] list -> 'a list val flatten : [> `List of 'a list ] list -> 'a list val filter_index : int -> [> `List of json list ] list -> json list val filter_list : [> `List of 'a ] list -> 'a list val filter_assoc : [> `Assoc of 'a ] list -> 'a list val filter_bool : [> `Bool of bool ] list -> bool list val filter_float : [> `Float of float ] list -> float list val filter_string : [> `String of string ] list -> string list val filter_member : string -> [> `Assoc of (string * json) list ] list -> json list val filter_number : [> `Float of float ] list -> float list val keys : [> `Assoc of (string * 'a) list ] -> string list val values : [> `Assoc of (string * 'a) list ] -> 'a list val combine : [> `Assoc of 'a list ] -> [> `Assoc of 'a list ] -> [> `Assoc of 'a list ] val sort : ([> `Assoc of (string * 'a) list | `List of 'a list ] as 'a) -> 'a end module Shared = struct let rec rev_filter_map f acc l = match l with | [] -> acc | hd::tl -> match f hd with | None -> rev_filter_map f acc tl | Some v -> rev_filter_map f (v::acc) tl let filter_map f l = List.rev (rev_filter_map f [] l) let rec rev_flatten acc l = match l with | [] -> acc | hd::tl -> match hd with | `List l2 -> rev_flatten (List.rev_append l2 acc) tl | _ -> rev_flatten acc tl let flatten l = List.rev (rev_flatten [] l) end module Strict(M : S) : Internal_strict_intf with type json = M.json = struct type json = M.json let assoc name obj : json = try List.assoc name obj with Not_found -> M.null () let member name v : json = match v with | `Assoc obj -> assoc name obj | json -> error ("Expected `Assoc to find name '" ^ name ^ "' in") json let index i v : json = match v with | `List l -> let len = List.length l in let i' = if i < 0 then len + i else i in if i' < 0 || i' >= len then raise (Invalid_argument (string_of_int i ^ " out of bounds")) else List.nth l i' | json -> error "Can't index none `List type " json let map f v = match v with | `List l -> `List (List.map f l) | json -> error "Can't map over none `List type " json let to_assoc = function | `Assoc obj -> obj | json -> error "Expected `Assoc" json let to_bool = function | `Bool b -> b | json -> error "Expected `Bool" json let to_float = function | `Float f -> f | json -> error "Expected `Float" json let to_string = function | `String s -> s | json -> error "Expected `String" json let to_string_option = function | `String s -> Some s | `Null -> None | json -> error "Expected `String or `Null" json let to_option f v : json option = match v with | `Null -> None | v -> Some (f v) let to_list v : json list = match v with | `List l -> l | json -> error "Expected `List" json let to_float_option = function | `Float f -> Some f | `Null -> None | json -> error "Expected `Float or `Null" json let to_bool_option = function | `Bool b -> Some b | `Null -> None | json -> error "Expected `Bool or `Null" json let to_number = function | `Float f -> f | json -> error "Expected `Float" json let to_number_option = function | `Float f -> Some f | `Null -> None | json -> error "Expected `Float or `Null" json let convert_each f = function | `List l -> List.map f l | json -> error "Expected `List" json let rev_filter_map = Shared.rev_filter_map let filter_map = Shared.filter_map let rev_flatten = Shared.rev_flatten let flatten = Shared.flatten let filter_index i l = filter_map (function | `List l -> (try Some (List.nth l i) with _ -> None) | _ -> None) l let filter_list l = filter_map (function `List l -> Some l | _ -> None) l let filter_assoc l = filter_map (function `Assoc l -> Some l | _ -> None) l let filter_bool l = filter_map (function `Bool b -> Some b | _ -> None) l let filter_float l = filter_map (function `Float f -> Some f | _ -> None) l let filter_string l = filter_map (function `String s -> Some s | _ -> None) l let filter_member k l = filter_map (function `Assoc l -> (try Some (List.assoc k l) with _ -> None) | _ -> None) l let filter_number l = filter_map ( function | `Float f -> Some f | _ -> None ) l let keys o = to_assoc o |> List.map (fun (key, _) -> key) let values o = to_assoc o |> List.map (fun (_, value) -> value) let combine first second = match (first, second) with | (`Assoc a, `Assoc b) -> `Assoc (a @ b) | (_, _) -> raise (Invalid_argument "Expected two objects") let rec sort json = match json with | `Assoc o -> let o = List.rev (List.rev_map (fun (k, v) -> (k, sort v)) o) in `Assoc ((List.stable_sort (fun (k1, _) (k2, _) -> String.compare k1 k2)) o) | `List l -> `List (List.rev (List.rev_map sort l)) | el -> el end module type Internal_basic_intf = sig val to_number : [> `Int of int | `Float of float ] -> float val to_number_option : [> `Int of int | `Float of float | `Null ] -> float option val to_int : [> `Int of int ] -> int val to_int_option : [> `Int of int | `Null ] -> int option val filter_int : [> `Int of int ] list -> int list val filter_number : [> `Int of int | `Float of float ] list -> float list end module Basic(M : S) : Internal_basic_intf = struct let to_number = function | `Int i -> float i | `Float f -> f | json -> error "Expected `Int or `Float" json let to_number_option = function | `Int i -> Some (float i) | `Float f -> Some f | `Null -> None | json -> error "Expected `Int, `Float or `Null" json let to_int = function | `Int i -> i | json -> error "Expected `Int" json let to_int_option = function | `Int i -> Some i | `Null -> None | json -> error "Expected `Int or `Null" json let filter_int l = Shared.filter_map (function `Int i -> Some i | _ -> None) l let filter_number l = Shared.filter_map ( function | `Int i -> Some (float i) | `Float f -> Some f | _ -> None ) l end module type Internal_extended_intf = sig val sort : ([> `Assoc of (string * 'a) list | `List of 'a list | `Tuple of 'a list | `Variant of 'b * 'a option ] as 'a) -> 'a end module Extended(M : S) : Internal_extended_intf = struct let rec sort json = match json with | `Assoc o -> let o = List.rev (List.rev_map (fun (k, v) -> (k, sort v)) o) in `Assoc ((List.stable_sort (fun (k1, _) (k2, _) -> String.compare k1 k2)) o) | `Tuple l | `List l -> `List (List.rev (List.rev_map sort l)) | `Variant (k, Some v) as v1 -> let v' = sort v in if v' == v then v1 else `Variant (k, Some v') | el -> el end end module Strict = struct module M = struct type json = Json.Strict.json let null () = `Null end include Internal.Strict(M) end module Basic = struct module M = struct type json = Json.Basic.json let null () = `Null end include Internal.Strict(M) include Internal.Basic(M) end module Extended = struct module M = struct type json = Json.Extended.json let null () = `Null end include Internal.Strict(M) include Internal.Basic(M) include Internal.Extended(M) end module Yojson_safe = struct module M = struct type json = [ | `Null | `Bool of bool | `Int of int | `Intlit of string | `Float of float | `String of string | `Assoc of (string * json) list | `List of json list | `Tuple of json list | `Variant of (string * json option) ] let null () = `Null end include Internal.Strict(M) include Internal.Basic(M) include Internal.Extended(M) end
null
https://raw.githubusercontent.com/stevebleazard/ocaml-jsonxt/fe982b6087dd76ca003d8fbc19ae9a519f54b828/lib/process.ml
ocaml
let error msg _json = raise (Failure msg) module Internal = struct module type S = sig type json val null : unit -> json end module type Internal_strict_intf = sig type json val member : string -> [> `Assoc of (string * json) list ] -> json val index : int -> [> `List of json list ] -> json val map : (json -> json) -> [> `List of json list ] -> [> `List of json list ] val to_assoc : [> `Assoc of (string * json) list ] -> (string * json) list val to_bool : [> `Bool of bool ] -> bool val to_float : [> `Float of float ] -> float val to_string : [> `String of string ] -> string val to_string_option : [> `String of string | `Null ] -> string option val to_option : (([> `Null ] as 'a) -> json) -> 'a -> json option val to_list : [> `List of json list ] -> json list val to_bool_option : [> `Bool of bool | `Null ] -> bool option val to_float_option : [> `Float of float | `Null ] -> float option val to_number : [> `Float of float ] -> float val to_number_option : [> `Float of float | `Null ] -> float option val convert_each : (json -> json) -> [> `List of json list ] -> json list val rev_filter_map : ('a -> 'a option) -> 'a list -> 'a list -> 'a list val filter_map : ('a -> 'a option) -> 'a list -> 'a list val rev_flatten : 'a list -> [> `List of 'a list ] list -> 'a list val flatten : [> `List of 'a list ] list -> 'a list val filter_index : int -> [> `List of json list ] list -> json list val filter_list : [> `List of 'a ] list -> 'a list val filter_assoc : [> `Assoc of 'a ] list -> 'a list val filter_bool : [> `Bool of bool ] list -> bool list val filter_float : [> `Float of float ] list -> float list val filter_string : [> `String of string ] list -> string list val filter_member : string -> [> `Assoc of (string * json) list ] list -> json list val filter_number : [> `Float of float ] list -> float list val keys : [> `Assoc of (string * 'a) list ] -> string list val values : [> `Assoc of (string * 'a) list ] -> 'a list val combine : [> `Assoc of 'a list ] -> [> `Assoc of 'a list ] -> [> `Assoc of 'a list ] val sort : ([> `Assoc of (string * 'a) list | `List of 'a list ] as 'a) -> 'a end module Shared = struct let rec rev_filter_map f acc l = match l with | [] -> acc | hd::tl -> match f hd with | None -> rev_filter_map f acc tl | Some v -> rev_filter_map f (v::acc) tl let filter_map f l = List.rev (rev_filter_map f [] l) let rec rev_flatten acc l = match l with | [] -> acc | hd::tl -> match hd with | `List l2 -> rev_flatten (List.rev_append l2 acc) tl | _ -> rev_flatten acc tl let flatten l = List.rev (rev_flatten [] l) end module Strict(M : S) : Internal_strict_intf with type json = M.json = struct type json = M.json let assoc name obj : json = try List.assoc name obj with Not_found -> M.null () let member name v : json = match v with | `Assoc obj -> assoc name obj | json -> error ("Expected `Assoc to find name '" ^ name ^ "' in") json let index i v : json = match v with | `List l -> let len = List.length l in let i' = if i < 0 then len + i else i in if i' < 0 || i' >= len then raise (Invalid_argument (string_of_int i ^ " out of bounds")) else List.nth l i' | json -> error "Can't index none `List type " json let map f v = match v with | `List l -> `List (List.map f l) | json -> error "Can't map over none `List type " json let to_assoc = function | `Assoc obj -> obj | json -> error "Expected `Assoc" json let to_bool = function | `Bool b -> b | json -> error "Expected `Bool" json let to_float = function | `Float f -> f | json -> error "Expected `Float" json let to_string = function | `String s -> s | json -> error "Expected `String" json let to_string_option = function | `String s -> Some s | `Null -> None | json -> error "Expected `String or `Null" json let to_option f v : json option = match v with | `Null -> None | v -> Some (f v) let to_list v : json list = match v with | `List l -> l | json -> error "Expected `List" json let to_float_option = function | `Float f -> Some f | `Null -> None | json -> error "Expected `Float or `Null" json let to_bool_option = function | `Bool b -> Some b | `Null -> None | json -> error "Expected `Bool or `Null" json let to_number = function | `Float f -> f | json -> error "Expected `Float" json let to_number_option = function | `Float f -> Some f | `Null -> None | json -> error "Expected `Float or `Null" json let convert_each f = function | `List l -> List.map f l | json -> error "Expected `List" json let rev_filter_map = Shared.rev_filter_map let filter_map = Shared.filter_map let rev_flatten = Shared.rev_flatten let flatten = Shared.flatten let filter_index i l = filter_map (function | `List l -> (try Some (List.nth l i) with _ -> None) | _ -> None) l let filter_list l = filter_map (function `List l -> Some l | _ -> None) l let filter_assoc l = filter_map (function `Assoc l -> Some l | _ -> None) l let filter_bool l = filter_map (function `Bool b -> Some b | _ -> None) l let filter_float l = filter_map (function `Float f -> Some f | _ -> None) l let filter_string l = filter_map (function `String s -> Some s | _ -> None) l let filter_member k l = filter_map (function `Assoc l -> (try Some (List.assoc k l) with _ -> None) | _ -> None) l let filter_number l = filter_map ( function | `Float f -> Some f | _ -> None ) l let keys o = to_assoc o |> List.map (fun (key, _) -> key) let values o = to_assoc o |> List.map (fun (_, value) -> value) let combine first second = match (first, second) with | (`Assoc a, `Assoc b) -> `Assoc (a @ b) | (_, _) -> raise (Invalid_argument "Expected two objects") let rec sort json = match json with | `Assoc o -> let o = List.rev (List.rev_map (fun (k, v) -> (k, sort v)) o) in `Assoc ((List.stable_sort (fun (k1, _) (k2, _) -> String.compare k1 k2)) o) | `List l -> `List (List.rev (List.rev_map sort l)) | el -> el end module type Internal_basic_intf = sig val to_number : [> `Int of int | `Float of float ] -> float val to_number_option : [> `Int of int | `Float of float | `Null ] -> float option val to_int : [> `Int of int ] -> int val to_int_option : [> `Int of int | `Null ] -> int option val filter_int : [> `Int of int ] list -> int list val filter_number : [> `Int of int | `Float of float ] list -> float list end module Basic(M : S) : Internal_basic_intf = struct let to_number = function | `Int i -> float i | `Float f -> f | json -> error "Expected `Int or `Float" json let to_number_option = function | `Int i -> Some (float i) | `Float f -> Some f | `Null -> None | json -> error "Expected `Int, `Float or `Null" json let to_int = function | `Int i -> i | json -> error "Expected `Int" json let to_int_option = function | `Int i -> Some i | `Null -> None | json -> error "Expected `Int or `Null" json let filter_int l = Shared.filter_map (function `Int i -> Some i | _ -> None) l let filter_number l = Shared.filter_map ( function | `Int i -> Some (float i) | `Float f -> Some f | _ -> None ) l end module type Internal_extended_intf = sig val sort : ([> `Assoc of (string * 'a) list | `List of 'a list | `Tuple of 'a list | `Variant of 'b * 'a option ] as 'a) -> 'a end module Extended(M : S) : Internal_extended_intf = struct let rec sort json = match json with | `Assoc o -> let o = List.rev (List.rev_map (fun (k, v) -> (k, sort v)) o) in `Assoc ((List.stable_sort (fun (k1, _) (k2, _) -> String.compare k1 k2)) o) | `Tuple l | `List l -> `List (List.rev (List.rev_map sort l)) | `Variant (k, Some v) as v1 -> let v' = sort v in if v' == v then v1 else `Variant (k, Some v') | el -> el end end module Strict = struct module M = struct type json = Json.Strict.json let null () = `Null end include Internal.Strict(M) end module Basic = struct module M = struct type json = Json.Basic.json let null () = `Null end include Internal.Strict(M) include Internal.Basic(M) end module Extended = struct module M = struct type json = Json.Extended.json let null () = `Null end include Internal.Strict(M) include Internal.Basic(M) include Internal.Extended(M) end module Yojson_safe = struct module M = struct type json = [ | `Null | `Bool of bool | `Int of int | `Intlit of string | `Float of float | `String of string | `Assoc of (string * json) list | `List of json list | `Tuple of json list | `Variant of (string * json option) ] let null () = `Null end include Internal.Strict(M) include Internal.Basic(M) include Internal.Extended(M) end
9b5fed7c6dd8e9955b32a39b3a8cba28e72c80a9646e40ba0a74c8a08d36dad2
xapi-project/xen-api
unixfd.ml
(** file descriptor with location *) type raw = Unix.file_descr * string type t = raw Safe.t let borrow_exn t = Safe.borrow_exn t |> fst let ( ! ) = borrow_exn let release (chan, _) = Unix.close chan Calling functions that may take locks inside a finaliser can lead to deadlocks , see and -project/xcp-idl/pull/288 . This can be worked around by running the finaliser code on a separate thread , however that needs lockless data structures for safety ( Mutex and Event is not safe to use within a finaliser ) . Although I have code for this it is too complex / error - prone to be used for code that is rarely run . Instead have leak tracing only for Unix file descriptors where we print errors to stderr instead of using a logging library . This is similar to what OCaml already provides for channels , see [ Sys.enable_runtime_warnings ] . deadlocks, see and -project/xcp-idl/pull/288. This can be worked around by running the finaliser code on a separate thread, however that needs lockless data structures for safety (Mutex and Event is not safe to use within a finaliser). Although I have code for this it is too complex/error-prone to be used for code that is rarely run. Instead have leak tracing only for Unix file descriptors where we print errors to stderr instead of using a logging library. This is similar to what OCaml already provides for channels, see [Sys.enable_runtime_warnings]. *) let on_finalise_leaked (chan, loc) = let enabled = Sys.runtime_warnings_enabled () in if enabled then Printf.eprintf "[unix_fd]: resource leak detected, allocated at %s\n%!" loc ; try Unix.close chan with e -> if enabled then ( Printexc.print_backtrace stderr ; Printf.eprintf "[unix_fd]: close failed: %s (allocated at %s)\n%!" (Printexc.to_string e) loc ) let within chan ~loc = Safe.within @@ Safe.create ~on_finalise_leaked ~release (chan, loc) let pair (fd1, fd2) ~loc f = within ~loc fd1 (fun fd1 -> within ~loc fd2 (fun fd2 -> f fd1 fd2)) let with_pipe () = pair @@ Unix.pipe () let with_socketpair domain typ proto ~loc f = let fd1, fd2 = Unix.socketpair domain typ proto in within ~loc fd1 (fun fd1 -> within ~loc fd2 (fun fd2 -> f fd1 fd2)) let with_fd alloc = alloc () |> within let with_open_connection addr ~loc f = let open Unix in with_fd ~loc (fun () -> socket ~cloexec:true (domain_of_sockaddr addr) SOCK_STREAM 0 ) @@ fun s -> connect !s addr ; f s let with_ic fd = A file descriptor can not be safely shared between an [ in ] and [ out ] channel . * Unix.open_connection does this but if you close both channels you get EBADF . * Unix.open_connection does this but if you close both channels you get EBADF. *) Safe.within @@ Safe.create ~release:close_in_noerr (Unix.in_channel_of_descr (Unix.dup fd)) let with_oc fd = Safe.within @@ Safe.create ~release:close_out_noerr (Unix.out_channel_of_descr (Unix.dup fd)) let with_channels t f = let fd = !t in with_ic fd @@ fun ic -> with_oc fd @@ fun oc -> (* the channels are using [dup]-ed FDs, close original now *) Safe.safe_release t ; f Safe.(borrow_exn ic, borrow_exn oc) let safe_close = Safe.safe_release
null
https://raw.githubusercontent.com/xapi-project/xen-api/5c9c44c6d40a9930f454722c9cd09c7079ec814e/ocaml/libs/resources/unixfd.ml
ocaml
* file descriptor with location the channels are using [dup]-ed FDs, close original now
type raw = Unix.file_descr * string type t = raw Safe.t let borrow_exn t = Safe.borrow_exn t |> fst let ( ! ) = borrow_exn let release (chan, _) = Unix.close chan Calling functions that may take locks inside a finaliser can lead to deadlocks , see and -project/xcp-idl/pull/288 . This can be worked around by running the finaliser code on a separate thread , however that needs lockless data structures for safety ( Mutex and Event is not safe to use within a finaliser ) . Although I have code for this it is too complex / error - prone to be used for code that is rarely run . Instead have leak tracing only for Unix file descriptors where we print errors to stderr instead of using a logging library . This is similar to what OCaml already provides for channels , see [ Sys.enable_runtime_warnings ] . deadlocks, see and -project/xcp-idl/pull/288. This can be worked around by running the finaliser code on a separate thread, however that needs lockless data structures for safety (Mutex and Event is not safe to use within a finaliser). Although I have code for this it is too complex/error-prone to be used for code that is rarely run. Instead have leak tracing only for Unix file descriptors where we print errors to stderr instead of using a logging library. This is similar to what OCaml already provides for channels, see [Sys.enable_runtime_warnings]. *) let on_finalise_leaked (chan, loc) = let enabled = Sys.runtime_warnings_enabled () in if enabled then Printf.eprintf "[unix_fd]: resource leak detected, allocated at %s\n%!" loc ; try Unix.close chan with e -> if enabled then ( Printexc.print_backtrace stderr ; Printf.eprintf "[unix_fd]: close failed: %s (allocated at %s)\n%!" (Printexc.to_string e) loc ) let within chan ~loc = Safe.within @@ Safe.create ~on_finalise_leaked ~release (chan, loc) let pair (fd1, fd2) ~loc f = within ~loc fd1 (fun fd1 -> within ~loc fd2 (fun fd2 -> f fd1 fd2)) let with_pipe () = pair @@ Unix.pipe () let with_socketpair domain typ proto ~loc f = let fd1, fd2 = Unix.socketpair domain typ proto in within ~loc fd1 (fun fd1 -> within ~loc fd2 (fun fd2 -> f fd1 fd2)) let with_fd alloc = alloc () |> within let with_open_connection addr ~loc f = let open Unix in with_fd ~loc (fun () -> socket ~cloexec:true (domain_of_sockaddr addr) SOCK_STREAM 0 ) @@ fun s -> connect !s addr ; f s let with_ic fd = A file descriptor can not be safely shared between an [ in ] and [ out ] channel . * Unix.open_connection does this but if you close both channels you get EBADF . * Unix.open_connection does this but if you close both channels you get EBADF. *) Safe.within @@ Safe.create ~release:close_in_noerr (Unix.in_channel_of_descr (Unix.dup fd)) let with_oc fd = Safe.within @@ Safe.create ~release:close_out_noerr (Unix.out_channel_of_descr (Unix.dup fd)) let with_channels t f = let fd = !t in with_ic fd @@ fun ic -> with_oc fd @@ fun oc -> Safe.safe_release t ; f Safe.(borrow_exn ic, borrow_exn oc) let safe_close = Safe.safe_release
017987a97ac51e80dbd5a92fc0091b9f7379d3b50578635c44f8546861b539c0
ml-in-barcelona/server-reason-react
jsso-react-pre-ocaml.ml
This is the file that handles turning Reason JSX ' agnostic function call into a jsoo - react - specific function call . , this is a macro , using 's ppx facilities ; -guide-to-extension- points - in - ocaml/ This is the file that handles turning Reason JSX' agnostic function call into a jsoo-react-specific function call. Aka, this is a macro, using OCaml's ppx facilities; -guide-to-extension- points-in-ocaml/ *) The transform : transform ` [ @JSX ] div(~props1 = a , ~props2 = b , ~children=[foo , bar ] , ( ) ) ` into ` ReactDom.createDOMElementVariadic("div " , ReactDom.domProps(~props1=1 , = b ) , [ foo , bar ] ) ` . transform the upper - cased case ` [ @JSX ] Foo.createElement(~key = a , ~ref = b , ~foo = bar , ~children= [ ] , ( ) ) ` into ` React.createElement(Foo.make , Foo.makeProps(~key = a , ~ref = b , ~foo = bar , ( ) ) ) ` transform the upper - cased case ` [ @JSX ] = bar , ~children=[foo , bar ] , ( ) ) ` into ` React.createElementVariadic(Foo.make , Foo.makeProps(~foo = bar , ~children = React.null , ( ) ) , [ foo , bar ] ) ` transform ` [ @JSX ] [ foo ] ` into ` React.createFragment([foo ] ) ` The transform: transform `[@JSX] div(~props1=a, ~props2=b, ~children=[foo, bar], ())` into `ReactDom.createDOMElementVariadic("div", ReactDom.domProps(~props1=1, ~props2=b), [foo, bar])`. transform the upper-cased case `[@JSX] Foo.createElement(~key=a, ~ref=b, ~foo=bar, ~children=[], ())` into `React.createElement(Foo.make, Foo.makeProps(~key=a, ~ref=b, ~foo=bar, ()))` transform the upper-cased case `[@JSX] Foo.createElement(~foo=bar, ~children=[foo, bar], ())` into `React.createElementVariadic(Foo.make, Foo.makeProps(~foo=bar, ~children=React.null, ()), [foo, bar])` transform `[@JSX] [foo]` into `React.createFragment([foo])` *) module Ocaml_location = Location open Ppxlib open Ast_helper let rec find_opt p = function | [] -> None | x :: l -> if p x then Some x else find_opt p l let nolabel = Nolabel let labelled str = Labelled str let optional str = Optional str let isOptional str = match str with Optional _ -> true | _ -> false let isLabelled str = match str with Labelled _ -> true | _ -> false let getLabel str = match str with Optional str | Labelled str -> str | Nolabel -> "" let optionIdent = Lident "option" let argIsKeyRef = function | Labelled ("key" | "ref"), _ | Optional ("key" | "ref"), _ -> true | _ -> false let isUnit expr = match expr.pexp_desc with | Pexp_construct ({ txt = Lident "()"; _ }, _) -> true | _ -> false let constantString ~loc str = Ast_helper.Exp.constant ~loc (Const.string str) let safeTypeFromValue valueStr = let valueStr = getLabel valueStr in match String.sub valueStr 0 1 with "_" -> "T" ^ valueStr | _ -> valueStr let keyType loc = Typ.constr ~loc { loc; txt = optionIdent } [ Typ.constr ~loc { loc; txt = Lident "string" } [] ] let refType loc = [%type: ReactDom.domRef] type 'a children = | ListLiteral of 'a | Exact of 'a type componentConfig = { propsName : string } let revAstList ~loc expr = let rec revAstList_ acc = function | [%expr []] -> acc | [%expr [%e? hd] :: [%e? tl]] -> revAstList_ [%expr [%e hd] :: [%e acc]] tl | expr -> expr in revAstList_ [%expr []] expr (* unlike reason-react ppx, we don't transform to array, just apply mapper to children *) let transformChildrenIfListUpper ~loc ~mapper theList = unlike reason - react ppx , we do n't transform to array as it 'd be incompatible with [ @js.variadic ] gen_js_api attribute , which requires argument to be a list [@js.variadic] gen_js_api attribute, which requires argument to be a list *) let rec transformChildren_ theList accum = not in the sense of converting a list to an array ; convert the AST reprensentation of a list to the AST reprensentation of an array reprensentation of a list to the AST reprensentation of an array *) match theList with | [%expr []] -> ( match accum with | [%expr [ [%e? singleElement] ]] -> Exact singleElement | accum -> ListLiteral (revAstList ~loc accum)) | [%expr [%e? v] :: [%e? acc]] -> transformChildren_ acc [%expr [%e mapper#expression v] :: [%e accum]] | notAList -> Exact (mapper#expression notAList) in transformChildren_ theList [%expr []] (* unlike reason-react ppx, we don't transform to array, just apply mapper to children *) let transformChildrenIfList ~loc ~mapper theList = let rec transformChildren_ theList accum = match theList with | [%expr []] -> revAstList ~loc accum | [%expr [%e? v] :: [%e? acc]] -> transformChildren_ acc [%expr [%e mapper#expression v] :: [%e accum]] | notAList -> mapper#expression notAList in transformChildren_ theList [%expr []] let extractChildren ?(removeLastPositionUnit = false) ~loc propsAndChildren = let rec allButLast_ lst acc = match lst with | [] -> [] | [ (Nolabel, { pexp_desc = Pexp_construct ({ txt = Lident "()" }, None) }) ] -> acc | (Nolabel, _) :: _rest -> raise (Invalid_argument "JSX: found non-labelled argument before the last position") | arg :: rest -> allButLast_ rest (arg :: acc) in let allButLast lst = allButLast_ lst [] |> List.rev in match List.partition (fun (label, _) -> label = labelled "children") propsAndChildren with | [], props -> (* no children provided? Place a placeholder list *) ( Exp.construct ~loc { loc; txt = Lident "[]" } None , if removeLastPositionUnit then allButLast props else props ) | [ (_, childrenExpr) ], props -> (childrenExpr, if removeLastPositionUnit then allButLast props else props) | _ -> raise (Invalid_argument "JSX: somehow there's more than one `children` label") let unerasableIgnore loc = { attr_name = { txt = "warning"; loc } ; attr_payload = PStr [ Str.eval (Exp.constant (Const.string "-16")) ] ; attr_loc = loc } let merlinFocus = { attr_name = { txt = "merlin.focus"; loc = Location.none } ; attr_payload = PStr [] ; attr_loc = Location.none } (* Helper method to look up the [@react.component] attribute *) let hasAttr { attr_name; _ } = attr_name.txt = "react.component" (* Helper method to filter out any attribute that isn't [@react.component] *) let otherAttrsPure { attr_name; _ } = attr_name.txt <> "react.component" (* Iterate over the attributes and try to find the [@react.component] attribute *) let hasAttrOnBinding { pvb_attributes } = find_opt hasAttr pvb_attributes <> None (* Filter the [@react.component] attribute and immutably replace them on the binding *) let filterAttrOnBinding binding = { binding with pvb_attributes = List.filter otherAttrsPure binding.pvb_attributes } (* Finds the name of the variable the binding is assigned to, otherwise raises Invalid_argument *) let getFnName binding = match binding with | { pvb_pat = { ppat_desc = Ppat_var { txt } } } -> txt | _ -> raise (Invalid_argument "react.component calls cannot be destructured.") let makeNewBinding binding expression newName = match binding with | { pvb_pat = { ppat_desc = Ppat_var ppat_var } as pvb_pat } -> { binding with pvb_pat = { pvb_pat with ppat_desc = Ppat_var { ppat_var with txt = newName } } ; pvb_expr = expression ; pvb_attributes = [ merlinFocus ] } | _ -> raise (Invalid_argument "react.component calls cannot be destructured.") (* Lookup the value of `props` otherwise raise Invalid_argument error *) let getPropsNameValue _acc (loc, exp) = match (loc, exp) with | { txt = Lident "props" }, { pexp_desc = Pexp_ident { txt = Lident str } } -> { propsName = str } | { txt }, _ -> raise (Invalid_argument ("react.component only accepts props as an option, given: " ^ Longident.last_exn txt)) (* Lookup the `props` record or string as part of [@react.component] and store the name for use when rewriting *) let getPropsAttr payload = let defaultProps = { propsName = "Props" } in match payload with | Some (PStr ({ pstr_desc = Pstr_eval ({ pexp_desc = Pexp_record (recordFields, None) }, _) } :: _rest)) -> List.fold_left getPropsNameValue defaultProps recordFields | Some (PStr ({ pstr_desc = Pstr_eval ({ pexp_desc = Pexp_ident { txt = Lident "props" } }, _) } :: _rest)) -> { propsName = "props" } | Some (PStr ({ pstr_desc = Pstr_eval (_, _) } :: _rest)) -> raise (Invalid_argument "react.component accepts a record config with props as an options.") | _ -> defaultProps Plucks the label , loc , and type _ from an AST node let pluckLabelDefaultLocType (label, default, _, _, loc, type_) = (label, default, loc, type_) Lookup the filename from the location information on the AST node and turn it into a valid module identifier let filenameFromLoc (pstr_loc : Location.t) = let fileName = match pstr_loc.loc_start.pos_fname with | "" -> !Ocaml_location.input_name | fileName -> fileName in let fileName = try Filename.chop_extension (Filename.basename fileName) with Invalid_argument _ -> fileName in let fileName = String.capitalize_ascii fileName in fileName (* Build a string representation of a module name with segments separated by $ *) let makeModuleName fileName nestedModules fnName = let fullModuleName = match (fileName, nestedModules, fnName) with (* TODO: is this even reachable? It seems like the fileName always exists *) | "", nestedModules, "make" -> nestedModules | "", nestedModules, fnName -> List.rev (fnName :: nestedModules) | fileName, nestedModules, "make" -> fileName :: List.rev nestedModules | fileName, nestedModules, fnName -> fileName :: List.rev (fnName :: nestedModules) in let fullModuleName = String.concat "$" fullModuleName in fullModuleName AST node builders These functions help us build AST nodes that are needed when transforming a [ @react.component ] into a constructor and a ` makeProps ` function AST node builders These functions help us build AST nodes that are needed when transforming a [@react.component] into a constructor and a `makeProps` function *) (* Build an AST node representing all named args for the `makeProps` definition for a component's props *) let rec makeArgsForMakePropsType list args = match list with | (label, default, loc, interiorType) :: tl -> let coreType = match (label, interiorType, default) with (* ~foo=1 *) | label, None, Some _ -> Typ.mk ~loc (Ptyp_var (safeTypeFromValue label)) (* ~foo: int=1 *) | _label, Some type_, Some _ -> type_ (* ~foo: option(int)=? *) | ( label , Some { ptyp_desc = Ptyp_constr ({ txt = Lident "option"; _ }, [ type_ ]) ; _ } , _ ) | ( label , Some { ptyp_desc = Ptyp_constr ({ txt = Ldot (Lident "*predef*", "option"); _ }, [ type_ ]) ; _ } , _ ) ~foo : ? - note this is nt valid . but we want to get a type error | label, Some type_, _ when isOptional label -> type_ (* ~foo=? *) | label, None, _ when isOptional label -> Typ.mk ~loc (Ptyp_var (safeTypeFromValue label)) (* ~foo *) | label, None, _ -> Typ.mk ~loc (Ptyp_var (safeTypeFromValue label)) | _label, Some type_, _ -> type_ in makeArgsForMakePropsType tl (Typ.arrow ~loc label coreType args) | [] -> args Build an AST node for the Js object representing props for a component let makePropsValue fnName loc namedArgListWithKeyAndRef propsType = let propsName = fnName ^ "Props" in Val.mk ~loc { txt = propsName; loc } (makeArgsForMakePropsType namedArgListWithKeyAndRef (Typ.arrow Nolabel { ptyp_desc = Ptyp_constr ({ txt = Lident "unit"; loc }, []) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } propsType)) (* Build an AST node for the signature of the `external` definition *) let makePropsExternalSig fnName loc namedArgListWithKeyAndRef propsType = { psig_loc = loc ; psig_desc = Psig_value (makePropsValue fnName loc namedArgListWithKeyAndRef propsType) } Build an AST node for the props name when converted to a Js.t inside the function signature let makePropsName ~loc name = Pat.mk ~loc (Ppat_var { txt = name; loc }) let makeObjectField loc (str, _attrs, propType) = let type_ = [%type: [%t propType] Js_of_ocaml.Js.readonly_prop] in { pof_desc = Otag ({ loc; txt = str }, { type_ with ptyp_attributes = [] }) ; pof_loc = loc ; pof_attributes = [] } Build an AST node representing a " closed " . object representing a component 's props let makePropsType ~loc namedTypeList = Typ.mk ~loc (Ptyp_constr ( { txt = Ldot (Ldot (Lident "Js_of_ocaml", "Js"), "t"); loc } , [ Typ.mk ~loc (Ptyp_object (List.map (makeObjectField loc) namedTypeList, Closed)) ] )) let rec makeFunsForMakePropsBody list args = match list with | (label, _default, loc, _interiorType) :: tl -> makeFunsForMakePropsBody tl (Exp.fun_ ~loc label None { ppat_desc = Ppat_var { txt = getLabel label; loc } ; ppat_loc = loc ; ppat_attributes = [] ; ppat_loc_stack = [] } args) | [] -> args let makeAttributeValue ~loc (type_ : Html.attributeType) value = match type_ with | String -> [%expr Js_of_ocaml.Js.string ([%e value] : string)] | Int -> [%expr ([%e value] : int)] | Float -> [%expr ([%e value] : float)] | Bool -> [%expr ([%e value] : bool)] | Style -> [%expr ([%e value] : ReactDom.Style.t)] | Ref -> [%expr ([%e value] : ReactDom.domRef)] | InnerHtml -> [%expr ([%e value] : ReactDom.DangerouslySetInnerHTML.t)] let makeEventValue ~loc (type_ : Html.eventType) value = match type_ with | Clipboard -> [%expr ([%e value] : React.Event.Clipboard.t -> unit)] | Composition -> [%expr ([%e value] : React.Event.Composition.t -> unit)] | Keyboard -> [%expr ([%e value] : React.Event.Keyboard.t -> unit)] | Focus -> [%expr ([%e value] : React.Event.Focus.t -> unit)] | Form -> [%expr ([%e value] : React.Event.Form.t -> unit)] | Mouse -> [%expr ([%e value] : React.Event.Mouse.t -> unit)] | Selection -> [%expr ([%e value] : React.Event.Selection.t -> unit)] | Touch -> [%expr ([%e value] : React.Event.Touch.t -> unit)] | UI -> [%expr ([%e value] : React.Event.UI.t -> unit)] | Wheel -> [%expr ([%e value] : React.Event.Wheel.t -> unit)] | Media -> [%expr ([%e value] : React.Event.Media.t -> unit)] | Image -> [%expr ([%e value] : React.Event.Image.t -> unit)] | Animation -> [%expr ([%e value] : React.Event.Animation.t -> unit)] | Transition -> [%expr ([%e value] : React.Event.Transition.t -> unit)] | _ -> [%expr ([%e value] : React.Event.t -> unit)] let makeValue ~loc prop value = match prop with | Html.Attribute attribute -> makeAttributeValue ~loc attribute.type_ value | Html.Event event -> makeEventValue ~loc event.type_ value let makeJsObj ~loc namedArgListWithKeyAndRef = let labelToTuple label = let l = getLabel label in let id = Exp.ident ~loc { txt = Lident l; loc } in let make_tuple raw = match l = "key" with | true -> [%expr [%e Exp.constant ~loc (Const.string l)] , inject (Js_of_ocaml.Js.string [%e raw])] | false -> [%expr [%e Exp.constant ~loc (Const.string l)], inject [%e raw]] in match isOptional label with | true -> [%expr Option.map (fun raw -> [%e make_tuple [%expr raw]]) [%e id]] | false -> [%expr Some [%e make_tuple id]] in [%expr obj ([%e Exp.array ~loc (List.map (fun (label, _, _, _) -> labelToTuple label) namedArgListWithKeyAndRef)] |> Array.to_list |> List.filter_map (fun x -> x) |> Array.of_list)] let makePropsValueBinding fnName loc namedArgListWithKeyAndRef propsType = let core_type = makeArgsForMakePropsType namedArgListWithKeyAndRef [%type: unit -> [%t propsType]] in let propsName = fnName ^ "Props" in Vb.mk ~loc (Pat.mk ~loc (Ppat_constraint ( makePropsName ~loc propsName , { ptyp_desc = Ptyp_poly ([], core_type) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ))) (Exp.mk ~loc (Pexp_constraint ( makeFunsForMakePropsBody namedArgListWithKeyAndRef [%expr fun _ -> let open Js_of_ocaml.Js.Unsafe in [%e makeJsObj ~loc namedArgListWithKeyAndRef]] , core_type ))) (* Returns a structure item for the `makeProps` function *) let makePropsItem fnName loc namedArgListWithKeyAndRef propsType = Str.mk ~loc (Pstr_value ( Nonrecursive , [ makePropsValueBinding fnName loc namedArgListWithKeyAndRef propsType ] )) (* Builds an AST node for the entire `makeProps` function *) let makePropsDecl fnName loc namedArgListWithKeyAndRef namedTypeList = makePropsItem fnName loc (List.map pluckLabelDefaultLocType namedArgListWithKeyAndRef) (makePropsType ~loc namedTypeList) (* TODO: some line number might still be wrong *) let jsxMapper () = let transformUppercaseCall modulePath mapper loc attrs _ callArguments = let children, argsWithLabels = extractChildren ~loc ~removeLastPositionUnit:true callArguments in let argsForMake = argsWithLabels in let childrenExpr = transformChildrenIfListUpper ~loc ~mapper children in let recursivelyTransformedArgsForMake = argsForMake |> List.map (fun (label, expression) -> (label, mapper#expression expression)) in let childrenArg = ref None in let args = recursivelyTransformedArgsForMake @ (match childrenExpr with | Exact children -> [ (labelled "children", children) ] | ListLiteral [%expr []] -> [] | ListLiteral expression -> (* this is a hack to support react components that introspect into their children *) childrenArg := Some expression; [ ( labelled "children" , Exp.ident ~loc { loc; txt = Ldot (Lident "React", "null") } ) ]) @ [ (nolabel, Exp.construct ~loc { loc; txt = Lident "()" } None) ] in let isCap str = let first = String.sub str 0 1 in let capped = String.uppercase_ascii first in first = capped in let ident = match modulePath with | Lident _ -> Ldot (modulePath, "make") | Ldot (_modulePath, value) as fullPath when isCap value -> Ldot (fullPath, "make") | modulePath -> modulePath in let propsIdent = match ident with | Lident path -> Lident (path ^ "Props") | Ldot (ident, path) -> Ldot (ident, path ^ "Props") | _ -> raise (Invalid_argument "JSX name can't be the result of function applications") in let props = Exp.apply ~attrs ~loc (Exp.ident ~loc { loc; txt = propsIdent }) args in (* handle key, ref, children *) (* React.createElement(Component.make, props, ...children) *) match !childrenArg with | None -> Exp.apply ~loc ~attrs (Exp.ident ~loc { loc; txt = Ldot (Lident "React", "createElement") }) [ (nolabel, Exp.ident ~loc { txt = ident; loc }); (nolabel, props) ] | Some children -> Exp.apply ~loc ~attrs (Exp.ident ~loc { loc; txt = Ldot (Lident "React", "createElementVariadic") }) [ (nolabel, Exp.ident ~loc { txt = ident; loc }) ; (nolabel, props) ; (nolabel, children) ] in let transformLowercaseCall mapper loc attrs callArguments id callLoc = let children, nonChildrenProps = extractChildren ~loc callArguments in let componentNameExpr = constantString ~loc id in let childrenExpr = transformChildrenIfList ~loc ~mapper children in let createElementCall = match children with (* [@JSX] div(~children=[a]), coming from <div> a </div> *) | { pexp_desc = ( Pexp_construct ({ txt = Lident "::" }, Some { pexp_desc = Pexp_tuple _ }) | Pexp_construct ({ txt = Lident "[]" }, None) ) } -> "createDOMElementVariadic" (* [@JSX] div(~children= value), coming from <div> ...(value) </div> *) | _ -> raise (Invalid_argument "A spread as a DOM element's children don't make sense written \ together. You can simply remove the spread.") in let args = (* Filtering out last unit *) let isLabeledArg (name, value) = getLabel name != "" && not (isUnit value) in let labeledProps = List.filter isLabeledArg nonChildrenProps in let makePropField (arg_label, _value) = let loc = callLoc in let name = getLabel arg_label in let objectKey = Exp.constant ~loc (Pconst_string (name, loc, None)) in [%expr [%e objectKey], value] in let propsObj = [%expr (Js_of_ocaml.Js.Unsafe.obj [%e Exp.array ~loc (List.map makePropField labeledProps)] : ReactDom.domProps)] in [ (* "div" *) (nolabel, componentNameExpr) ; (* ~props: Js_of_ocaml.Js.Unsafe.obj ... *) (labelled "props", propsObj) ; (* [|moreCreateElementCallsHere|] *) (nolabel, childrenExpr) ] in Exp.apply ~loc (* throw away the [@JSX] attribute and keep the others, if any *) ~attrs (* ReactDom.createElement *) (Exp.ident ~loc { loc; txt = Ldot (Ldot (Lident "React", "Dom"), createElementCall) }) args in let rec recursivelyTransformNamedArgsForMake mapper expr list = let expr = mapper#expression expr in match expr.pexp_desc with (* TODO: make this show up with a loc. *) | Pexp_fun (Labelled "key", _, _, _) | Pexp_fun (Optional "key", _, _, _) -> raise (Invalid_argument "Key cannot be accessed inside of a component. Don't worry - you \ can always key a component from its parent!") | Pexp_fun (Labelled "ref", _, _, _) | Pexp_fun (Optional "ref", _, _, _) -> raise (Invalid_argument "Ref cannot be passed as a normal prop. Please use `forwardRef` \ API instead.") | Pexp_fun (arg, default, pattern, expression) when isOptional arg || isLabelled arg -> let () = match (isOptional arg, pattern, default) with | true, { ppat_desc = Ppat_constraint (_, { ptyp_desc }) }, None -> ( match ptyp_desc with | Ptyp_constr ({ txt = Lident "option" }, [ _ ]) -> () | _ -> let currentType = match ptyp_desc with | Ptyp_constr ({ txt }, []) -> String.concat "." (Longident.flatten_exn txt) | Ptyp_constr ({ txt }, _innerTypeArgs) -> String.concat "." (Longident.flatten_exn txt) ^ "(...)" | _ -> "..." in Location.raise_errorf ~loc:pattern.ppat_loc "jsoo-react: optional argument annotations must have \ explicit `option`. Did you mean `option(%s)=?`?" currentType) | _ -> () in let alias = match pattern with | { ppat_desc = Ppat_alias (_, { txt }) | Ppat_var { txt } } -> txt | { ppat_desc = Ppat_any } -> "_" | _ -> getLabel arg in let type_ = match pattern with | { ppat_desc = Ppat_constraint (_, type_) } -> Some type_ | _ -> None in recursivelyTransformNamedArgsForMake mapper expression ((arg, default, pattern, alias, pattern.ppat_loc, type_) :: list) | Pexp_fun ( Nolabel , _ , { ppat_desc = Ppat_construct ({ txt = Lident "()" }, _) | Ppat_any } , _expression ) -> (list, None) | Pexp_fun ( Nolabel , _ , { ppat_desc = ( Ppat_var { txt } | Ppat_constraint ({ ppat_desc = Ppat_var { txt } }, _) ) } , _expression ) -> (list, Some txt) | Pexp_fun (Nolabel, _, pattern, _expression) -> Location.raise_errorf ~loc:pattern.ppat_loc "jsoo-react: react.component refs only support plain arguments and \ type annotations." | _ -> (list, None) in let argToType types (name, default, _noLabelName, _alias, loc, type_) = match (type_, name, default) with | ( Some { ptyp_desc = Ptyp_constr ({ txt = Lident "option" }, [ type_ ]) } , name , _ ) when isOptional name -> ( getLabel name , [] , { type_ with ptyp_desc = Ptyp_constr ({ loc = type_.ptyp_loc; txt = optionIdent }, [ type_ ]) } ) :: types | Some type_, name, Some _default -> ( getLabel name , [] , { ptyp_desc = Ptyp_constr ({ loc; txt = optionIdent }, [ type_ ]) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ) :: types | Some type_, name, _ -> (getLabel name, [], type_) :: types | None, name, _ when isOptional name -> ( getLabel name , [] , { ptyp_desc = Ptyp_constr ( { loc; txt = optionIdent } , [ { ptyp_desc = Ptyp_var (safeTypeFromValue name) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ] ) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ) :: types | None, name, _ when isLabelled name -> ( getLabel name , [] , { ptyp_desc = Ptyp_var (safeTypeFromValue name) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ) :: types | _ -> types in let argToConcreteType types (name, loc, type_) = match name with | name when isLabelled name -> (getLabel name, [], type_) :: types | name when isOptional name -> (getLabel name, [], Typ.constr ~loc { loc; txt = optionIdent } [ type_ ]) :: types | _ -> types in let nestedModules = ref [] in let transformComponentDefinition mapper structure returnStructures = match structure with (* external *) | { pstr_loc ; pstr_desc = Pstr_primitive ({ pval_name = { txt = fnName }; pval_attributes; pval_type } as value_description) } as pstr -> ( match List.filter hasAttr pval_attributes with | [] -> structure :: returnStructures | [ _ ] -> let rec getPropTypes types ({ ptyp_loc; ptyp_desc } as fullType) = match ptyp_desc with | Ptyp_arrow (name, type_, ({ ptyp_desc = Ptyp_arrow _ } as rest)) when isLabelled name || isOptional name -> getPropTypes ((name, ptyp_loc, type_) :: types) rest | Ptyp_arrow (Nolabel, _type, rest) -> getPropTypes types rest | Ptyp_arrow (name, type_, returnValue) when isLabelled name || isOptional name -> (returnValue, (name, returnValue.ptyp_loc, type_) :: types) | _ -> (fullType, types) in let innerType, propTypes = getPropTypes [] pval_type in let namedTypeList = List.fold_left argToConcreteType [] propTypes in let pluckLabelAndLoc (label, loc, type_) = (label, None (* default *), loc, Some type_) in let retPropsType = makePropsType ~loc:pstr_loc namedTypeList in let externalPropsDecl = makePropsItem fnName pstr_loc ((Optional "key", None, pstr_loc, Some (keyType pstr_loc)) :: List.map pluckLabelAndLoc propTypes) retPropsType in (* can't be an arrow because it will defensively uncurry *) let newExternalType = Ptyp_constr ( { loc = pstr_loc ; txt = Ldot (Lident "React", "componentLike") } , [ retPropsType; innerType ] ) in let newStructure = { pstr with pstr_desc = Pstr_primitive { value_description with pval_type = { pval_type with ptyp_desc = newExternalType } ; pval_attributes = List.filter otherAttrsPure pval_attributes } } in externalPropsDecl :: newStructure :: returnStructures | _ -> raise (Invalid_argument "Only one react.component call can exist on a component at \ one time")) (* let component = ... *) | { pstr_loc; pstr_desc = Pstr_value (recFlag, valueBindings) } -> let fileName = filenameFromLoc pstr_loc in let emptyLoc = Location.in_file fileName in let mapBinding binding = if hasAttrOnBinding binding then let bindingLoc = binding.pvb_loc in let bindingPatLoc = binding.pvb_pat.ppat_loc in let binding = { binding with pvb_pat = { binding.pvb_pat with ppat_loc = emptyLoc } ; pvb_loc = emptyLoc } in let fnName = getFnName binding in let internalFnName = fnName ^ "$Internal" in let fullModuleName = makeModuleName fileName !nestedModules fnName in let modifiedBindingOld binding = let expression = binding.pvb_expr in (* TODO: there is a long-tail of unsupported features inside of blocks - Pexp_letmodule , Pexp_letexception , Pexp_ifthenelse *) let rec spelunkForFunExpression expression = match expression with (* let make = (~prop) => ... *) | { pexp_desc = Pexp_fun _ } -> expression (* let make = {let foo = bar in (~prop) => ...} *) | { pexp_desc = Pexp_let (_recursive, _vbs, returnExpression) } -> (* here's where we spelunk! *) spelunkForFunExpression returnExpression let make = React.forwardRef((~prop ) = > ... ) or let make = React.memoCustomCompareProps((~prop ) = > ... , ( ) ) let make = React.memoCustomCompareProps((~prop) => ..., compareProps()) *) | { pexp_desc = Pexp_apply ( _wrapperExpression , ( [ (Nolabel, innerFunctionExpression) ] | [ (Nolabel, innerFunctionExpression) ; (Nolabel, { pexp_desc = Pexp_fun _ }) ] ) ) } -> spelunkForFunExpression innerFunctionExpression | { pexp_desc = Pexp_sequence (_wrapperExpression, innerFunctionExpression) } -> spelunkForFunExpression innerFunctionExpression | _ -> raise (Invalid_argument "react.component calls can only be on function \ definitions or component wrappers (forwardRef, \ memo).") in spelunkForFunExpression expression in let modifiedBinding binding = let hasApplication = ref false in let wrapExpressionWithBinding expressionFn expression = Vb.mk ~loc:bindingLoc ~attrs:(List.filter otherAttrsPure binding.pvb_attributes) (Pat.var ~loc:bindingPatLoc { loc = bindingPatLoc; txt = fnName }) (expressionFn expression) in let expression = binding.pvb_expr in let unerasableIgnoreExp exp = { exp with pexp_attributes = unerasableIgnore emptyLoc :: exp.pexp_attributes } in (* TODO: there is a long-tail of unsupported features inside of blocks - Pexp_letmodule , Pexp_letexception , Pexp_ifthenelse *) let rec spelunkForFunExpression expression = match expression with (* let make = (~prop) => ... with no final unit *) | { pexp_desc = Pexp_fun ( ((Labelled _ | Optional _) as label) , default , pattern , ({ pexp_desc = Pexp_fun _ } as internalExpression) ) } -> let wrap, hasUnit, exp = spelunkForFunExpression internalExpression in ( wrap , hasUnit , unerasableIgnoreExp { expression with pexp_desc = Pexp_fun (label, default, pattern, exp) } ) (* let make = (()) => ... *) (* let make = (_) => ... *) | { pexp_desc = Pexp_fun ( Nolabel , _default , { ppat_desc = ( Ppat_construct ({ txt = Lident "()" }, _) | Ppat_any ) } , _internalExpression ) } -> ((fun a -> a), true, expression) (* let make = (~prop) => ... *) | { pexp_desc = Pexp_fun ( (Labelled _ | Optional _) , _default , _pattern , _internalExpression ) } -> ((fun a -> a), false, unerasableIgnoreExp expression) (* let make = (prop) => ... *) | { pexp_desc = Pexp_fun (_nolabel, _default, pattern, _internalExpression) } -> if hasApplication.contents then ((fun a -> a), false, unerasableIgnoreExp expression) else Location.raise_errorf ~loc:pattern.ppat_loc "jsoo-react: props need to be labelled arguments.\n\ \ If you are working with refs be sure to wrap with \ React.forwardRef.\n\ \ If your component doesn't have any props use () or \ _ instead of a name." (* let make = {let foo = bar in (~prop) => ...} *) | { pexp_desc = Pexp_let (recursive, vbs, internalExpression) } -> (* here's where we spelunk! *) let wrap, hasUnit, exp = spelunkForFunExpression internalExpression in ( wrap , hasUnit , { expression with pexp_desc = Pexp_let (recursive, vbs, exp) } ) (* let make = React.forwardRef((~prop) => ...) *) | { pexp_desc = Pexp_apply (wrapperExpression, [ (Nolabel, internalExpression) ]) } -> let () = hasApplication := true in let _, hasUnit, exp = spelunkForFunExpression internalExpression in ( (fun exp -> Exp.apply wrapperExpression [ (nolabel, exp) ]) , hasUnit , exp ) (* let make = React.memoCustomCompareProps((~prop) => ..., (prevPros, nextProps) => true) *) | { pexp_desc = Pexp_apply ( wrapperExpression , [ (Nolabel, internalExpression) ; ((Nolabel, { pexp_desc = Pexp_fun _ }) as compareProps) ] ) } -> let () = hasApplication := true in let _, hasUnit, exp = spelunkForFunExpression internalExpression in ( (fun exp -> Exp.apply wrapperExpression [ (nolabel, exp); compareProps ]) , hasUnit , exp ) | { pexp_desc = Pexp_sequence (wrapperExpression, internalExpression) } -> let wrap, hasUnit, exp = spelunkForFunExpression internalExpression in ( wrap , hasUnit , { expression with pexp_desc = Pexp_sequence (wrapperExpression, exp) } ) | e -> ((fun a -> a), false, e) in let wrapExpression, hasUnit, expression = spelunkForFunExpression expression in (wrapExpressionWithBinding wrapExpression, hasUnit, expression) in let bindingWrapper, hasUnit, expression = modifiedBinding binding in let reactComponentAttribute = try Some (List.find hasAttr binding.pvb_attributes) with Not_found -> None in let _attr_loc, payload = match reactComponentAttribute with | Some { attr_loc; attr_payload } -> (attr_loc, Some attr_payload) | None -> (emptyLoc, None) in let props = getPropsAttr payload in (* do stuff here! *) let namedArgList, forwardRef = recursivelyTransformNamedArgsForMake mapper (modifiedBindingOld binding) [] in let namedArgListWithKeyAndRef = ( optional "key" , None , Pat.var { txt = "key"; loc = emptyLoc } , "key" , emptyLoc , Some (keyType emptyLoc) ) :: namedArgList in let namedArgListWithKeyAndRef = match forwardRef with | Some _ -> ( optional "ref" , None , Pat.var { txt = "ref"; loc = emptyLoc } , "ref" , emptyLoc , Some (refType emptyLoc) ) :: namedArgListWithKeyAndRef | None -> namedArgListWithKeyAndRef in let namedArgListWithKeyAndRefForNew = match forwardRef with | Some txt -> namedArgList @ [ ( nolabel , None , Pat.var { txt; loc = emptyLoc } , txt , emptyLoc , None ) ] | None -> namedArgList in let pluckArg (label, _, _, alias, loc, _) = let labelString = match label with | label when isOptional label || isLabelled label -> getLabel label | _ -> "" in ( label , match labelString with | "" -> Exp.ident ~loc { txt = Lident alias; loc } | labelString -> let propsNameId = Exp.ident ~loc { txt = Lident props.propsName; loc } in let labelStringConst = Exp.constant ~loc (Const.string labelString) in let send = Exp.send ~loc (Exp.ident ~loc { txt = Lident "x"; loc }) { txt = labelString; loc } in #L322-L332 [%expr (fun (type res a0) (a0 : a0 Js_of_ocaml.Js.t) (_ : a0 -> < get : res ; .. > Js_of_ocaml.Js.gen_prop) : res -> Js_of_ocaml.Js.Unsafe.get a0 [%e labelStringConst]) ([%e propsNameId] : < .. > Js_of_ocaml.Js.t) (fun x -> [%e send])] ) in let namedTypeList = List.fold_left argToType [] namedArgList in let loc = emptyLoc in let makePropsLet = makePropsDecl fnName loc namedArgListWithKeyAndRef namedTypeList in let innerExpressionArgs = List.map pluckArg namedArgListWithKeyAndRefForNew @ if hasUnit then [ (Nolabel, Exp.construct { loc; txt = Lident "()" } None) ] else [] in let innerExpression = Exp.apply (Exp.ident { loc ; txt = Lident (match recFlag with | Recursive -> internalFnName | Nonrecursive -> fnName) }) innerExpressionArgs in let innerExpressionWithRef = match forwardRef with | Some txt -> { innerExpression with pexp_desc = Pexp_fun ( nolabel , None , { ppat_desc = Ppat_var { txt; loc = emptyLoc } ; ppat_loc = emptyLoc ; ppat_attributes = [] ; ppat_loc_stack = [] } , innerExpression ) } | None -> innerExpression in let fullExpression = Exp.fun_ nolabel None { ppat_desc = Ppat_constraint ( makePropsName ~loc:emptyLoc props.propsName , makePropsType ~loc:emptyLoc namedTypeList ) ; ppat_loc = emptyLoc ; ppat_attributes = [] ; ppat_loc_stack = [] } innerExpressionWithRef in let fullExpression = match fullModuleName with | "" -> fullExpression | txt -> Exp.let_ Nonrecursive [ Vb.mk ~loc:emptyLoc (Pat.var ~loc:emptyLoc { loc = emptyLoc; txt }) fullExpression ] (Exp.ident ~loc:emptyLoc { loc = emptyLoc; txt = Lident txt }) in let bindings, newBinding = match recFlag with | Recursive -> ( [ bindingWrapper (Exp.let_ ~loc:emptyLoc Recursive [ makeNewBinding binding expression internalFnName ; Vb.mk (Pat.var { loc = emptyLoc; txt = fnName }) fullExpression ] (Exp.ident { loc = emptyLoc; txt = Lident fnName })) ] , None ) | Nonrecursive -> ( [ { binding with pvb_expr = expression; pvb_attributes = [] } ] , Some (bindingWrapper fullExpression) ) in (Some makePropsLet, bindings, newBinding) else (None, [ binding ], None) in let structuresAndBinding = List.map mapBinding valueBindings in let otherStructures (extern, binding, newBinding) (externs, bindings, newBindings) = let externs = match extern with | Some extern -> extern :: externs | None -> externs in let newBindings = match newBinding with | Some newBinding -> newBinding :: newBindings | None -> newBindings in (externs, binding @ bindings, newBindings) in let externs, bindings, newBindings = List.fold_right otherStructures structuresAndBinding ([], [], []) in externs @ [ { pstr_loc; pstr_desc = Pstr_value (recFlag, bindings) } ] @ (match newBindings with | [] -> [] | newBindings -> [ { pstr_loc = emptyLoc ; pstr_desc = Pstr_value (recFlag, newBindings) } ]) @ returnStructures | structure -> structure :: returnStructures in let reactComponentTransform mapper structures = List.fold_right (transformComponentDefinition mapper) structures [] in let transformComponentSignature _mapper signature returnSignatures = match signature with | { psig_loc ; psig_desc = Psig_value ({ pval_name = { txt = fnName }; pval_attributes; pval_type } as psig_desc) } as psig -> ( match List.filter hasAttr pval_attributes with | [] -> signature :: returnSignatures | [ _ ] -> let rec getPropTypes types ({ ptyp_loc; ptyp_desc } as fullType) = match ptyp_desc with | Ptyp_arrow (name, type_, ({ ptyp_desc = Ptyp_arrow _ } as rest)) when isOptional name || isLabelled name -> getPropTypes ((name, ptyp_loc, type_) :: types) rest | Ptyp_arrow (Nolabel, _type, rest) -> getPropTypes types rest | Ptyp_arrow (name, type_, returnValue) when isOptional name || isLabelled name -> (returnValue, (name, returnValue.ptyp_loc, type_) :: types) | _ -> (fullType, types) in let innerType, propTypes = getPropTypes [] pval_type in let namedTypeList = List.fold_left argToConcreteType [] propTypes in let pluckLabelAndLoc (label, loc, type_) = (label, None, loc, Some type_) in let retPropsType = makePropsType ~loc:psig_loc namedTypeList in let externalPropsDecl = makePropsExternalSig fnName psig_loc ((optional "key", None, psig_loc, Some (keyType psig_loc)) :: List.map pluckLabelAndLoc propTypes) retPropsType in (* can't be an arrow because it will defensively uncurry *) let newExternalType = Ptyp_constr ( { loc = psig_loc ; txt = Ldot (Lident "React", "componentLike") } , [ retPropsType; innerType ] ) in let newStructure = { psig with psig_desc = Psig_value { psig_desc with pval_type = { pval_type with ptyp_desc = newExternalType } ; pval_attributes = List.filter otherAttrsPure pval_attributes } } in externalPropsDecl :: newStructure :: returnSignatures | _ -> raise (Invalid_argument "Only one react.component call can exist on a component at \ one time")) | signature -> signature :: returnSignatures in let reactComponentSignatureTransform mapper signatures = List.fold_right (transformComponentSignature mapper) signatures [] in let transformJsxCall mapper callExpression callArguments attrs applyLoc = match callExpression.pexp_desc with | Pexp_ident caller -> ( match caller with | { txt = Lident "createElement" } -> raise (Invalid_argument "JSX: `createElement` should be preceeded by a module name.") Foo.createElement(~prop1 = foo , ~prop2 = bar , ~children= [ ] , ( ) ) | { loc; txt = Ldot (modulePath, ("createElement" | "make")) } -> transformUppercaseCall modulePath mapper loc attrs callExpression callArguments div(~prop1 = foo , ~prop2 = bar , ~children=[bla ] , ( ) ) turn that into ReactDom.createElement(~props = ReactDom.props(~props1 = foo , ~props2 = bar , ( ) ) , [ |bla| ] ) ReactDom.createElement(~props=ReactDom.props(~props1=foo, ~props2=bar, ()), [|bla|]) *) | { loc; txt = Lident id } -> transformLowercaseCall mapper loc attrs callArguments id applyLoc | { txt = Ldot (_, anythingNotCreateElementOrMake) } -> raise (Invalid_argument ("JSX: the JSX attribute should be attached to a \ `YourModuleName.createElement` or `YourModuleName.make` \ call. We saw `" ^ anythingNotCreateElementOrMake ^ "` instead")) | { txt = Lapply _ } -> (* don't think there's ever a case where this is reached *) raise (Invalid_argument "JSX: encountered a weird case while processing the code. \ Please report this!")) | _ -> raise (Invalid_argument "JSX: `createElement` should be preceeded by a simple, direct \ module name.") in object (self) inherit Ast_traverse.map as super method! signature signature = super#signature @@ reactComponentSignatureTransform self signature method! structure structure = match structure with | structures -> super#structure @@ reactComponentTransform self structures method! expression expression = match expression with (* Does the function application have the @JSX attribute? *) | { pexp_desc = Pexp_apply (callExpression, callArguments) ; pexp_attributes ; pexp_loc = applyLoc } -> ( let jsxAttribute, nonJSXAttributes = List.partition (fun attribute -> attribute.attr_name.txt = "JSX") pexp_attributes in match (jsxAttribute, nonJSXAttributes) with no JSX attribute | [], _ -> super#expression expression | _, nonJSXAttributes -> transformJsxCall self callExpression callArguments nonJSXAttributes applyLoc) is it a list with jsx attribute ? Reason < > foo</ > to [ @JSX][foo ] | { pexp_desc = ( Pexp_construct ({ txt = Lident "::"; loc }, Some { pexp_desc = Pexp_tuple _ }) | Pexp_construct ({ txt = Lident "[]"; loc }, None) ) ; pexp_attributes } as listItems -> ( let jsxAttribute, nonJSXAttributes = List.partition (fun attribute -> attribute.attr_name.txt = "JSX") pexp_attributes in match (jsxAttribute, nonJSXAttributes) with no JSX attribute | [], _ -> super#expression expression | _, nonJSXAttributes -> let callExpression = [%expr React.Fragment.createElement] in transformJsxCall self callExpression [ (Labelled "children", listItems) ] nonJSXAttributes listItems.pexp_loc) (* Delegate to the default mapper, a deep identity traversal *) | e -> super#expression e method! module_binding module_binding = let _ = match module_binding.pmb_name.txt with | None -> () | Some txt -> nestedModules := txt :: !nestedModules in let mapped = super#module_binding module_binding in let _ = nestedModules := List.tl !nestedModules in mapped end let rewrite_implementation (code : Parsetree.structure) : Parsetree.structure = let mapper = jsxMapper () in mapper#structure code let rewrite_signature (code : Parsetree.signature) : Parsetree.signature = let mapper = jsxMapper () in mapper#signature code let () = Driver.register_transformation "native-react-ppx" ~impl:rewrite_implementation ~intf:rewrite_signature
null
https://raw.githubusercontent.com/ml-in-barcelona/server-reason-react/02950c3028b994efe7291e747b5ec29f0d150d1f/arch/jsso-react-pre-ocaml.ml
ocaml
unlike reason-react ppx, we don't transform to array, just apply mapper to children unlike reason-react ppx, we don't transform to array, just apply mapper to children no children provided? Place a placeholder list Helper method to look up the [@react.component] attribute Helper method to filter out any attribute that isn't [@react.component] Iterate over the attributes and try to find the [@react.component] attribute Filter the [@react.component] attribute and immutably replace them on the binding Finds the name of the variable the binding is assigned to, otherwise raises Invalid_argument Lookup the value of `props` otherwise raise Invalid_argument error Lookup the `props` record or string as part of [@react.component] and store the name for use when rewriting Build a string representation of a module name with segments separated by $ TODO: is this even reachable? It seems like the fileName always exists Build an AST node representing all named args for the `makeProps` definition for a component's props ~foo=1 ~foo: int=1 ~foo: option(int)=? ~foo=? ~foo Build an AST node for the signature of the `external` definition Returns a structure item for the `makeProps` function Builds an AST node for the entire `makeProps` function TODO: some line number might still be wrong this is a hack to support react components that introspect into their children handle key, ref, children React.createElement(Component.make, props, ...children) [@JSX] div(~children=[a]), coming from <div> a </div> [@JSX] div(~children= value), coming from <div> ...(value) </div> Filtering out last unit "div" ~props: Js_of_ocaml.Js.Unsafe.obj ... [|moreCreateElementCallsHere|] throw away the [@JSX] attribute and keep the others, if any ReactDom.createElement TODO: make this show up with a loc. external default can't be an arrow because it will defensively uncurry let component = ... TODO: there is a long-tail of unsupported features inside of blocks - Pexp_letmodule , Pexp_letexception , Pexp_ifthenelse let make = (~prop) => ... let make = {let foo = bar in (~prop) => ...} here's where we spelunk! TODO: there is a long-tail of unsupported features inside of blocks - Pexp_letmodule , Pexp_letexception , Pexp_ifthenelse let make = (~prop) => ... with no final unit let make = (()) => ... let make = (_) => ... let make = (~prop) => ... let make = (prop) => ... let make = {let foo = bar in (~prop) => ...} here's where we spelunk! let make = React.forwardRef((~prop) => ...) let make = React.memoCustomCompareProps((~prop) => ..., (prevPros, nextProps) => true) do stuff here! can't be an arrow because it will defensively uncurry don't think there's ever a case where this is reached Does the function application have the @JSX attribute? Delegate to the default mapper, a deep identity traversal
This is the file that handles turning Reason JSX ' agnostic function call into a jsoo - react - specific function call . , this is a macro , using 's ppx facilities ; -guide-to-extension- points - in - ocaml/ This is the file that handles turning Reason JSX' agnostic function call into a jsoo-react-specific function call. Aka, this is a macro, using OCaml's ppx facilities; -guide-to-extension- points-in-ocaml/ *) The transform : transform ` [ @JSX ] div(~props1 = a , ~props2 = b , ~children=[foo , bar ] , ( ) ) ` into ` ReactDom.createDOMElementVariadic("div " , ReactDom.domProps(~props1=1 , = b ) , [ foo , bar ] ) ` . transform the upper - cased case ` [ @JSX ] Foo.createElement(~key = a , ~ref = b , ~foo = bar , ~children= [ ] , ( ) ) ` into ` React.createElement(Foo.make , Foo.makeProps(~key = a , ~ref = b , ~foo = bar , ( ) ) ) ` transform the upper - cased case ` [ @JSX ] = bar , ~children=[foo , bar ] , ( ) ) ` into ` React.createElementVariadic(Foo.make , Foo.makeProps(~foo = bar , ~children = React.null , ( ) ) , [ foo , bar ] ) ` transform ` [ @JSX ] [ foo ] ` into ` React.createFragment([foo ] ) ` The transform: transform `[@JSX] div(~props1=a, ~props2=b, ~children=[foo, bar], ())` into `ReactDom.createDOMElementVariadic("div", ReactDom.domProps(~props1=1, ~props2=b), [foo, bar])`. transform the upper-cased case `[@JSX] Foo.createElement(~key=a, ~ref=b, ~foo=bar, ~children=[], ())` into `React.createElement(Foo.make, Foo.makeProps(~key=a, ~ref=b, ~foo=bar, ()))` transform the upper-cased case `[@JSX] Foo.createElement(~foo=bar, ~children=[foo, bar], ())` into `React.createElementVariadic(Foo.make, Foo.makeProps(~foo=bar, ~children=React.null, ()), [foo, bar])` transform `[@JSX] [foo]` into `React.createFragment([foo])` *) module Ocaml_location = Location open Ppxlib open Ast_helper let rec find_opt p = function | [] -> None | x :: l -> if p x then Some x else find_opt p l let nolabel = Nolabel let labelled str = Labelled str let optional str = Optional str let isOptional str = match str with Optional _ -> true | _ -> false let isLabelled str = match str with Labelled _ -> true | _ -> false let getLabel str = match str with Optional str | Labelled str -> str | Nolabel -> "" let optionIdent = Lident "option" let argIsKeyRef = function | Labelled ("key" | "ref"), _ | Optional ("key" | "ref"), _ -> true | _ -> false let isUnit expr = match expr.pexp_desc with | Pexp_construct ({ txt = Lident "()"; _ }, _) -> true | _ -> false let constantString ~loc str = Ast_helper.Exp.constant ~loc (Const.string str) let safeTypeFromValue valueStr = let valueStr = getLabel valueStr in match String.sub valueStr 0 1 with "_" -> "T" ^ valueStr | _ -> valueStr let keyType loc = Typ.constr ~loc { loc; txt = optionIdent } [ Typ.constr ~loc { loc; txt = Lident "string" } [] ] let refType loc = [%type: ReactDom.domRef] type 'a children = | ListLiteral of 'a | Exact of 'a type componentConfig = { propsName : string } let revAstList ~loc expr = let rec revAstList_ acc = function | [%expr []] -> acc | [%expr [%e? hd] :: [%e? tl]] -> revAstList_ [%expr [%e hd] :: [%e acc]] tl | expr -> expr in revAstList_ [%expr []] expr let transformChildrenIfListUpper ~loc ~mapper theList = unlike reason - react ppx , we do n't transform to array as it 'd be incompatible with [ @js.variadic ] gen_js_api attribute , which requires argument to be a list [@js.variadic] gen_js_api attribute, which requires argument to be a list *) let rec transformChildren_ theList accum = not in the sense of converting a list to an array ; convert the AST reprensentation of a list to the AST reprensentation of an array reprensentation of a list to the AST reprensentation of an array *) match theList with | [%expr []] -> ( match accum with | [%expr [ [%e? singleElement] ]] -> Exact singleElement | accum -> ListLiteral (revAstList ~loc accum)) | [%expr [%e? v] :: [%e? acc]] -> transformChildren_ acc [%expr [%e mapper#expression v] :: [%e accum]] | notAList -> Exact (mapper#expression notAList) in transformChildren_ theList [%expr []] let transformChildrenIfList ~loc ~mapper theList = let rec transformChildren_ theList accum = match theList with | [%expr []] -> revAstList ~loc accum | [%expr [%e? v] :: [%e? acc]] -> transformChildren_ acc [%expr [%e mapper#expression v] :: [%e accum]] | notAList -> mapper#expression notAList in transformChildren_ theList [%expr []] let extractChildren ?(removeLastPositionUnit = false) ~loc propsAndChildren = let rec allButLast_ lst acc = match lst with | [] -> [] | [ (Nolabel, { pexp_desc = Pexp_construct ({ txt = Lident "()" }, None) }) ] -> acc | (Nolabel, _) :: _rest -> raise (Invalid_argument "JSX: found non-labelled argument before the last position") | arg :: rest -> allButLast_ rest (arg :: acc) in let allButLast lst = allButLast_ lst [] |> List.rev in match List.partition (fun (label, _) -> label = labelled "children") propsAndChildren with | [], props -> ( Exp.construct ~loc { loc; txt = Lident "[]" } None , if removeLastPositionUnit then allButLast props else props ) | [ (_, childrenExpr) ], props -> (childrenExpr, if removeLastPositionUnit then allButLast props else props) | _ -> raise (Invalid_argument "JSX: somehow there's more than one `children` label") let unerasableIgnore loc = { attr_name = { txt = "warning"; loc } ; attr_payload = PStr [ Str.eval (Exp.constant (Const.string "-16")) ] ; attr_loc = loc } let merlinFocus = { attr_name = { txt = "merlin.focus"; loc = Location.none } ; attr_payload = PStr [] ; attr_loc = Location.none } let hasAttr { attr_name; _ } = attr_name.txt = "react.component" let otherAttrsPure { attr_name; _ } = attr_name.txt <> "react.component" let hasAttrOnBinding { pvb_attributes } = find_opt hasAttr pvb_attributes <> None let filterAttrOnBinding binding = { binding with pvb_attributes = List.filter otherAttrsPure binding.pvb_attributes } let getFnName binding = match binding with | { pvb_pat = { ppat_desc = Ppat_var { txt } } } -> txt | _ -> raise (Invalid_argument "react.component calls cannot be destructured.") let makeNewBinding binding expression newName = match binding with | { pvb_pat = { ppat_desc = Ppat_var ppat_var } as pvb_pat } -> { binding with pvb_pat = { pvb_pat with ppat_desc = Ppat_var { ppat_var with txt = newName } } ; pvb_expr = expression ; pvb_attributes = [ merlinFocus ] } | _ -> raise (Invalid_argument "react.component calls cannot be destructured.") let getPropsNameValue _acc (loc, exp) = match (loc, exp) with | { txt = Lident "props" }, { pexp_desc = Pexp_ident { txt = Lident str } } -> { propsName = str } | { txt }, _ -> raise (Invalid_argument ("react.component only accepts props as an option, given: " ^ Longident.last_exn txt)) let getPropsAttr payload = let defaultProps = { propsName = "Props" } in match payload with | Some (PStr ({ pstr_desc = Pstr_eval ({ pexp_desc = Pexp_record (recordFields, None) }, _) } :: _rest)) -> List.fold_left getPropsNameValue defaultProps recordFields | Some (PStr ({ pstr_desc = Pstr_eval ({ pexp_desc = Pexp_ident { txt = Lident "props" } }, _) } :: _rest)) -> { propsName = "props" } | Some (PStr ({ pstr_desc = Pstr_eval (_, _) } :: _rest)) -> raise (Invalid_argument "react.component accepts a record config with props as an options.") | _ -> defaultProps Plucks the label , loc , and type _ from an AST node let pluckLabelDefaultLocType (label, default, _, _, loc, type_) = (label, default, loc, type_) Lookup the filename from the location information on the AST node and turn it into a valid module identifier let filenameFromLoc (pstr_loc : Location.t) = let fileName = match pstr_loc.loc_start.pos_fname with | "" -> !Ocaml_location.input_name | fileName -> fileName in let fileName = try Filename.chop_extension (Filename.basename fileName) with Invalid_argument _ -> fileName in let fileName = String.capitalize_ascii fileName in fileName let makeModuleName fileName nestedModules fnName = let fullModuleName = match (fileName, nestedModules, fnName) with | "", nestedModules, "make" -> nestedModules | "", nestedModules, fnName -> List.rev (fnName :: nestedModules) | fileName, nestedModules, "make" -> fileName :: List.rev nestedModules | fileName, nestedModules, fnName -> fileName :: List.rev (fnName :: nestedModules) in let fullModuleName = String.concat "$" fullModuleName in fullModuleName AST node builders These functions help us build AST nodes that are needed when transforming a [ @react.component ] into a constructor and a ` makeProps ` function AST node builders These functions help us build AST nodes that are needed when transforming a [@react.component] into a constructor and a `makeProps` function *) let rec makeArgsForMakePropsType list args = match list with | (label, default, loc, interiorType) :: tl -> let coreType = match (label, interiorType, default) with | label, None, Some _ -> Typ.mk ~loc (Ptyp_var (safeTypeFromValue label)) | _label, Some type_, Some _ -> type_ | ( label , Some { ptyp_desc = Ptyp_constr ({ txt = Lident "option"; _ }, [ type_ ]) ; _ } , _ ) | ( label , Some { ptyp_desc = Ptyp_constr ({ txt = Ldot (Lident "*predef*", "option"); _ }, [ type_ ]) ; _ } , _ ) ~foo : ? - note this is nt valid . but we want to get a type error | label, Some type_, _ when isOptional label -> type_ | label, None, _ when isOptional label -> Typ.mk ~loc (Ptyp_var (safeTypeFromValue label)) | label, None, _ -> Typ.mk ~loc (Ptyp_var (safeTypeFromValue label)) | _label, Some type_, _ -> type_ in makeArgsForMakePropsType tl (Typ.arrow ~loc label coreType args) | [] -> args Build an AST node for the Js object representing props for a component let makePropsValue fnName loc namedArgListWithKeyAndRef propsType = let propsName = fnName ^ "Props" in Val.mk ~loc { txt = propsName; loc } (makeArgsForMakePropsType namedArgListWithKeyAndRef (Typ.arrow Nolabel { ptyp_desc = Ptyp_constr ({ txt = Lident "unit"; loc }, []) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } propsType)) let makePropsExternalSig fnName loc namedArgListWithKeyAndRef propsType = { psig_loc = loc ; psig_desc = Psig_value (makePropsValue fnName loc namedArgListWithKeyAndRef propsType) } Build an AST node for the props name when converted to a Js.t inside the function signature let makePropsName ~loc name = Pat.mk ~loc (Ppat_var { txt = name; loc }) let makeObjectField loc (str, _attrs, propType) = let type_ = [%type: [%t propType] Js_of_ocaml.Js.readonly_prop] in { pof_desc = Otag ({ loc; txt = str }, { type_ with ptyp_attributes = [] }) ; pof_loc = loc ; pof_attributes = [] } Build an AST node representing a " closed " . object representing a component 's props let makePropsType ~loc namedTypeList = Typ.mk ~loc (Ptyp_constr ( { txt = Ldot (Ldot (Lident "Js_of_ocaml", "Js"), "t"); loc } , [ Typ.mk ~loc (Ptyp_object (List.map (makeObjectField loc) namedTypeList, Closed)) ] )) let rec makeFunsForMakePropsBody list args = match list with | (label, _default, loc, _interiorType) :: tl -> makeFunsForMakePropsBody tl (Exp.fun_ ~loc label None { ppat_desc = Ppat_var { txt = getLabel label; loc } ; ppat_loc = loc ; ppat_attributes = [] ; ppat_loc_stack = [] } args) | [] -> args let makeAttributeValue ~loc (type_ : Html.attributeType) value = match type_ with | String -> [%expr Js_of_ocaml.Js.string ([%e value] : string)] | Int -> [%expr ([%e value] : int)] | Float -> [%expr ([%e value] : float)] | Bool -> [%expr ([%e value] : bool)] | Style -> [%expr ([%e value] : ReactDom.Style.t)] | Ref -> [%expr ([%e value] : ReactDom.domRef)] | InnerHtml -> [%expr ([%e value] : ReactDom.DangerouslySetInnerHTML.t)] let makeEventValue ~loc (type_ : Html.eventType) value = match type_ with | Clipboard -> [%expr ([%e value] : React.Event.Clipboard.t -> unit)] | Composition -> [%expr ([%e value] : React.Event.Composition.t -> unit)] | Keyboard -> [%expr ([%e value] : React.Event.Keyboard.t -> unit)] | Focus -> [%expr ([%e value] : React.Event.Focus.t -> unit)] | Form -> [%expr ([%e value] : React.Event.Form.t -> unit)] | Mouse -> [%expr ([%e value] : React.Event.Mouse.t -> unit)] | Selection -> [%expr ([%e value] : React.Event.Selection.t -> unit)] | Touch -> [%expr ([%e value] : React.Event.Touch.t -> unit)] | UI -> [%expr ([%e value] : React.Event.UI.t -> unit)] | Wheel -> [%expr ([%e value] : React.Event.Wheel.t -> unit)] | Media -> [%expr ([%e value] : React.Event.Media.t -> unit)] | Image -> [%expr ([%e value] : React.Event.Image.t -> unit)] | Animation -> [%expr ([%e value] : React.Event.Animation.t -> unit)] | Transition -> [%expr ([%e value] : React.Event.Transition.t -> unit)] | _ -> [%expr ([%e value] : React.Event.t -> unit)] let makeValue ~loc prop value = match prop with | Html.Attribute attribute -> makeAttributeValue ~loc attribute.type_ value | Html.Event event -> makeEventValue ~loc event.type_ value let makeJsObj ~loc namedArgListWithKeyAndRef = let labelToTuple label = let l = getLabel label in let id = Exp.ident ~loc { txt = Lident l; loc } in let make_tuple raw = match l = "key" with | true -> [%expr [%e Exp.constant ~loc (Const.string l)] , inject (Js_of_ocaml.Js.string [%e raw])] | false -> [%expr [%e Exp.constant ~loc (Const.string l)], inject [%e raw]] in match isOptional label with | true -> [%expr Option.map (fun raw -> [%e make_tuple [%expr raw]]) [%e id]] | false -> [%expr Some [%e make_tuple id]] in [%expr obj ([%e Exp.array ~loc (List.map (fun (label, _, _, _) -> labelToTuple label) namedArgListWithKeyAndRef)] |> Array.to_list |> List.filter_map (fun x -> x) |> Array.of_list)] let makePropsValueBinding fnName loc namedArgListWithKeyAndRef propsType = let core_type = makeArgsForMakePropsType namedArgListWithKeyAndRef [%type: unit -> [%t propsType]] in let propsName = fnName ^ "Props" in Vb.mk ~loc (Pat.mk ~loc (Ppat_constraint ( makePropsName ~loc propsName , { ptyp_desc = Ptyp_poly ([], core_type) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ))) (Exp.mk ~loc (Pexp_constraint ( makeFunsForMakePropsBody namedArgListWithKeyAndRef [%expr fun _ -> let open Js_of_ocaml.Js.Unsafe in [%e makeJsObj ~loc namedArgListWithKeyAndRef]] , core_type ))) let makePropsItem fnName loc namedArgListWithKeyAndRef propsType = Str.mk ~loc (Pstr_value ( Nonrecursive , [ makePropsValueBinding fnName loc namedArgListWithKeyAndRef propsType ] )) let makePropsDecl fnName loc namedArgListWithKeyAndRef namedTypeList = makePropsItem fnName loc (List.map pluckLabelDefaultLocType namedArgListWithKeyAndRef) (makePropsType ~loc namedTypeList) let jsxMapper () = let transformUppercaseCall modulePath mapper loc attrs _ callArguments = let children, argsWithLabels = extractChildren ~loc ~removeLastPositionUnit:true callArguments in let argsForMake = argsWithLabels in let childrenExpr = transformChildrenIfListUpper ~loc ~mapper children in let recursivelyTransformedArgsForMake = argsForMake |> List.map (fun (label, expression) -> (label, mapper#expression expression)) in let childrenArg = ref None in let args = recursivelyTransformedArgsForMake @ (match childrenExpr with | Exact children -> [ (labelled "children", children) ] | ListLiteral [%expr []] -> [] | ListLiteral expression -> childrenArg := Some expression; [ ( labelled "children" , Exp.ident ~loc { loc; txt = Ldot (Lident "React", "null") } ) ]) @ [ (nolabel, Exp.construct ~loc { loc; txt = Lident "()" } None) ] in let isCap str = let first = String.sub str 0 1 in let capped = String.uppercase_ascii first in first = capped in let ident = match modulePath with | Lident _ -> Ldot (modulePath, "make") | Ldot (_modulePath, value) as fullPath when isCap value -> Ldot (fullPath, "make") | modulePath -> modulePath in let propsIdent = match ident with | Lident path -> Lident (path ^ "Props") | Ldot (ident, path) -> Ldot (ident, path ^ "Props") | _ -> raise (Invalid_argument "JSX name can't be the result of function applications") in let props = Exp.apply ~attrs ~loc (Exp.ident ~loc { loc; txt = propsIdent }) args in match !childrenArg with | None -> Exp.apply ~loc ~attrs (Exp.ident ~loc { loc; txt = Ldot (Lident "React", "createElement") }) [ (nolabel, Exp.ident ~loc { txt = ident; loc }); (nolabel, props) ] | Some children -> Exp.apply ~loc ~attrs (Exp.ident ~loc { loc; txt = Ldot (Lident "React", "createElementVariadic") }) [ (nolabel, Exp.ident ~loc { txt = ident; loc }) ; (nolabel, props) ; (nolabel, children) ] in let transformLowercaseCall mapper loc attrs callArguments id callLoc = let children, nonChildrenProps = extractChildren ~loc callArguments in let componentNameExpr = constantString ~loc id in let childrenExpr = transformChildrenIfList ~loc ~mapper children in let createElementCall = match children with | { pexp_desc = ( Pexp_construct ({ txt = Lident "::" }, Some { pexp_desc = Pexp_tuple _ }) | Pexp_construct ({ txt = Lident "[]" }, None) ) } -> "createDOMElementVariadic" | _ -> raise (Invalid_argument "A spread as a DOM element's children don't make sense written \ together. You can simply remove the spread.") in let args = let isLabeledArg (name, value) = getLabel name != "" && not (isUnit value) in let labeledProps = List.filter isLabeledArg nonChildrenProps in let makePropField (arg_label, _value) = let loc = callLoc in let name = getLabel arg_label in let objectKey = Exp.constant ~loc (Pconst_string (name, loc, None)) in [%expr [%e objectKey], value] in let propsObj = [%expr (Js_of_ocaml.Js.Unsafe.obj [%e Exp.array ~loc (List.map makePropField labeledProps)] : ReactDom.domProps)] in (nolabel, componentNameExpr) (labelled "props", propsObj) (nolabel, childrenExpr) ] in Exp.apply ~attrs (Exp.ident ~loc { loc; txt = Ldot (Ldot (Lident "React", "Dom"), createElementCall) }) args in let rec recursivelyTransformNamedArgsForMake mapper expr list = let expr = mapper#expression expr in match expr.pexp_desc with | Pexp_fun (Labelled "key", _, _, _) | Pexp_fun (Optional "key", _, _, _) -> raise (Invalid_argument "Key cannot be accessed inside of a component. Don't worry - you \ can always key a component from its parent!") | Pexp_fun (Labelled "ref", _, _, _) | Pexp_fun (Optional "ref", _, _, _) -> raise (Invalid_argument "Ref cannot be passed as a normal prop. Please use `forwardRef` \ API instead.") | Pexp_fun (arg, default, pattern, expression) when isOptional arg || isLabelled arg -> let () = match (isOptional arg, pattern, default) with | true, { ppat_desc = Ppat_constraint (_, { ptyp_desc }) }, None -> ( match ptyp_desc with | Ptyp_constr ({ txt = Lident "option" }, [ _ ]) -> () | _ -> let currentType = match ptyp_desc with | Ptyp_constr ({ txt }, []) -> String.concat "." (Longident.flatten_exn txt) | Ptyp_constr ({ txt }, _innerTypeArgs) -> String.concat "." (Longident.flatten_exn txt) ^ "(...)" | _ -> "..." in Location.raise_errorf ~loc:pattern.ppat_loc "jsoo-react: optional argument annotations must have \ explicit `option`. Did you mean `option(%s)=?`?" currentType) | _ -> () in let alias = match pattern with | { ppat_desc = Ppat_alias (_, { txt }) | Ppat_var { txt } } -> txt | { ppat_desc = Ppat_any } -> "_" | _ -> getLabel arg in let type_ = match pattern with | { ppat_desc = Ppat_constraint (_, type_) } -> Some type_ | _ -> None in recursivelyTransformNamedArgsForMake mapper expression ((arg, default, pattern, alias, pattern.ppat_loc, type_) :: list) | Pexp_fun ( Nolabel , _ , { ppat_desc = Ppat_construct ({ txt = Lident "()" }, _) | Ppat_any } , _expression ) -> (list, None) | Pexp_fun ( Nolabel , _ , { ppat_desc = ( Ppat_var { txt } | Ppat_constraint ({ ppat_desc = Ppat_var { txt } }, _) ) } , _expression ) -> (list, Some txt) | Pexp_fun (Nolabel, _, pattern, _expression) -> Location.raise_errorf ~loc:pattern.ppat_loc "jsoo-react: react.component refs only support plain arguments and \ type annotations." | _ -> (list, None) in let argToType types (name, default, _noLabelName, _alias, loc, type_) = match (type_, name, default) with | ( Some { ptyp_desc = Ptyp_constr ({ txt = Lident "option" }, [ type_ ]) } , name , _ ) when isOptional name -> ( getLabel name , [] , { type_ with ptyp_desc = Ptyp_constr ({ loc = type_.ptyp_loc; txt = optionIdent }, [ type_ ]) } ) :: types | Some type_, name, Some _default -> ( getLabel name , [] , { ptyp_desc = Ptyp_constr ({ loc; txt = optionIdent }, [ type_ ]) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ) :: types | Some type_, name, _ -> (getLabel name, [], type_) :: types | None, name, _ when isOptional name -> ( getLabel name , [] , { ptyp_desc = Ptyp_constr ( { loc; txt = optionIdent } , [ { ptyp_desc = Ptyp_var (safeTypeFromValue name) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ] ) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ) :: types | None, name, _ when isLabelled name -> ( getLabel name , [] , { ptyp_desc = Ptyp_var (safeTypeFromValue name) ; ptyp_loc = loc ; ptyp_attributes = [] ; ptyp_loc_stack = [] } ) :: types | _ -> types in let argToConcreteType types (name, loc, type_) = match name with | name when isLabelled name -> (getLabel name, [], type_) :: types | name when isOptional name -> (getLabel name, [], Typ.constr ~loc { loc; txt = optionIdent } [ type_ ]) :: types | _ -> types in let nestedModules = ref [] in let transformComponentDefinition mapper structure returnStructures = match structure with | { pstr_loc ; pstr_desc = Pstr_primitive ({ pval_name = { txt = fnName }; pval_attributes; pval_type } as value_description) } as pstr -> ( match List.filter hasAttr pval_attributes with | [] -> structure :: returnStructures | [ _ ] -> let rec getPropTypes types ({ ptyp_loc; ptyp_desc } as fullType) = match ptyp_desc with | Ptyp_arrow (name, type_, ({ ptyp_desc = Ptyp_arrow _ } as rest)) when isLabelled name || isOptional name -> getPropTypes ((name, ptyp_loc, type_) :: types) rest | Ptyp_arrow (Nolabel, _type, rest) -> getPropTypes types rest | Ptyp_arrow (name, type_, returnValue) when isLabelled name || isOptional name -> (returnValue, (name, returnValue.ptyp_loc, type_) :: types) | _ -> (fullType, types) in let innerType, propTypes = getPropTypes [] pval_type in let namedTypeList = List.fold_left argToConcreteType [] propTypes in let pluckLabelAndLoc (label, loc, type_) = in let retPropsType = makePropsType ~loc:pstr_loc namedTypeList in let externalPropsDecl = makePropsItem fnName pstr_loc ((Optional "key", None, pstr_loc, Some (keyType pstr_loc)) :: List.map pluckLabelAndLoc propTypes) retPropsType in let newExternalType = Ptyp_constr ( { loc = pstr_loc ; txt = Ldot (Lident "React", "componentLike") } , [ retPropsType; innerType ] ) in let newStructure = { pstr with pstr_desc = Pstr_primitive { value_description with pval_type = { pval_type with ptyp_desc = newExternalType } ; pval_attributes = List.filter otherAttrsPure pval_attributes } } in externalPropsDecl :: newStructure :: returnStructures | _ -> raise (Invalid_argument "Only one react.component call can exist on a component at \ one time")) | { pstr_loc; pstr_desc = Pstr_value (recFlag, valueBindings) } -> let fileName = filenameFromLoc pstr_loc in let emptyLoc = Location.in_file fileName in let mapBinding binding = if hasAttrOnBinding binding then let bindingLoc = binding.pvb_loc in let bindingPatLoc = binding.pvb_pat.ppat_loc in let binding = { binding with pvb_pat = { binding.pvb_pat with ppat_loc = emptyLoc } ; pvb_loc = emptyLoc } in let fnName = getFnName binding in let internalFnName = fnName ^ "$Internal" in let fullModuleName = makeModuleName fileName !nestedModules fnName in let modifiedBindingOld binding = let expression = binding.pvb_expr in let rec spelunkForFunExpression expression = match expression with | { pexp_desc = Pexp_fun _ } -> expression | { pexp_desc = Pexp_let (_recursive, _vbs, returnExpression) } -> spelunkForFunExpression returnExpression let make = React.forwardRef((~prop ) = > ... ) or let make = React.memoCustomCompareProps((~prop ) = > ... , ( ) ) let make = React.memoCustomCompareProps((~prop) => ..., compareProps()) *) | { pexp_desc = Pexp_apply ( _wrapperExpression , ( [ (Nolabel, innerFunctionExpression) ] | [ (Nolabel, innerFunctionExpression) ; (Nolabel, { pexp_desc = Pexp_fun _ }) ] ) ) } -> spelunkForFunExpression innerFunctionExpression | { pexp_desc = Pexp_sequence (_wrapperExpression, innerFunctionExpression) } -> spelunkForFunExpression innerFunctionExpression | _ -> raise (Invalid_argument "react.component calls can only be on function \ definitions or component wrappers (forwardRef, \ memo).") in spelunkForFunExpression expression in let modifiedBinding binding = let hasApplication = ref false in let wrapExpressionWithBinding expressionFn expression = Vb.mk ~loc:bindingLoc ~attrs:(List.filter otherAttrsPure binding.pvb_attributes) (Pat.var ~loc:bindingPatLoc { loc = bindingPatLoc; txt = fnName }) (expressionFn expression) in let expression = binding.pvb_expr in let unerasableIgnoreExp exp = { exp with pexp_attributes = unerasableIgnore emptyLoc :: exp.pexp_attributes } in let rec spelunkForFunExpression expression = match expression with | { pexp_desc = Pexp_fun ( ((Labelled _ | Optional _) as label) , default , pattern , ({ pexp_desc = Pexp_fun _ } as internalExpression) ) } -> let wrap, hasUnit, exp = spelunkForFunExpression internalExpression in ( wrap , hasUnit , unerasableIgnoreExp { expression with pexp_desc = Pexp_fun (label, default, pattern, exp) } ) | { pexp_desc = Pexp_fun ( Nolabel , _default , { ppat_desc = ( Ppat_construct ({ txt = Lident "()" }, _) | Ppat_any ) } , _internalExpression ) } -> ((fun a -> a), true, expression) | { pexp_desc = Pexp_fun ( (Labelled _ | Optional _) , _default , _pattern , _internalExpression ) } -> ((fun a -> a), false, unerasableIgnoreExp expression) | { pexp_desc = Pexp_fun (_nolabel, _default, pattern, _internalExpression) } -> if hasApplication.contents then ((fun a -> a), false, unerasableIgnoreExp expression) else Location.raise_errorf ~loc:pattern.ppat_loc "jsoo-react: props need to be labelled arguments.\n\ \ If you are working with refs be sure to wrap with \ React.forwardRef.\n\ \ If your component doesn't have any props use () or \ _ instead of a name." | { pexp_desc = Pexp_let (recursive, vbs, internalExpression) } -> let wrap, hasUnit, exp = spelunkForFunExpression internalExpression in ( wrap , hasUnit , { expression with pexp_desc = Pexp_let (recursive, vbs, exp) } ) | { pexp_desc = Pexp_apply (wrapperExpression, [ (Nolabel, internalExpression) ]) } -> let () = hasApplication := true in let _, hasUnit, exp = spelunkForFunExpression internalExpression in ( (fun exp -> Exp.apply wrapperExpression [ (nolabel, exp) ]) , hasUnit , exp ) | { pexp_desc = Pexp_apply ( wrapperExpression , [ (Nolabel, internalExpression) ; ((Nolabel, { pexp_desc = Pexp_fun _ }) as compareProps) ] ) } -> let () = hasApplication := true in let _, hasUnit, exp = spelunkForFunExpression internalExpression in ( (fun exp -> Exp.apply wrapperExpression [ (nolabel, exp); compareProps ]) , hasUnit , exp ) | { pexp_desc = Pexp_sequence (wrapperExpression, internalExpression) } -> let wrap, hasUnit, exp = spelunkForFunExpression internalExpression in ( wrap , hasUnit , { expression with pexp_desc = Pexp_sequence (wrapperExpression, exp) } ) | e -> ((fun a -> a), false, e) in let wrapExpression, hasUnit, expression = spelunkForFunExpression expression in (wrapExpressionWithBinding wrapExpression, hasUnit, expression) in let bindingWrapper, hasUnit, expression = modifiedBinding binding in let reactComponentAttribute = try Some (List.find hasAttr binding.pvb_attributes) with Not_found -> None in let _attr_loc, payload = match reactComponentAttribute with | Some { attr_loc; attr_payload } -> (attr_loc, Some attr_payload) | None -> (emptyLoc, None) in let props = getPropsAttr payload in let namedArgList, forwardRef = recursivelyTransformNamedArgsForMake mapper (modifiedBindingOld binding) [] in let namedArgListWithKeyAndRef = ( optional "key" , None , Pat.var { txt = "key"; loc = emptyLoc } , "key" , emptyLoc , Some (keyType emptyLoc) ) :: namedArgList in let namedArgListWithKeyAndRef = match forwardRef with | Some _ -> ( optional "ref" , None , Pat.var { txt = "ref"; loc = emptyLoc } , "ref" , emptyLoc , Some (refType emptyLoc) ) :: namedArgListWithKeyAndRef | None -> namedArgListWithKeyAndRef in let namedArgListWithKeyAndRefForNew = match forwardRef with | Some txt -> namedArgList @ [ ( nolabel , None , Pat.var { txt; loc = emptyLoc } , txt , emptyLoc , None ) ] | None -> namedArgList in let pluckArg (label, _, _, alias, loc, _) = let labelString = match label with | label when isOptional label || isLabelled label -> getLabel label | _ -> "" in ( label , match labelString with | "" -> Exp.ident ~loc { txt = Lident alias; loc } | labelString -> let propsNameId = Exp.ident ~loc { txt = Lident props.propsName; loc } in let labelStringConst = Exp.constant ~loc (Const.string labelString) in let send = Exp.send ~loc (Exp.ident ~loc { txt = Lident "x"; loc }) { txt = labelString; loc } in #L322-L332 [%expr (fun (type res a0) (a0 : a0 Js_of_ocaml.Js.t) (_ : a0 -> < get : res ; .. > Js_of_ocaml.Js.gen_prop) : res -> Js_of_ocaml.Js.Unsafe.get a0 [%e labelStringConst]) ([%e propsNameId] : < .. > Js_of_ocaml.Js.t) (fun x -> [%e send])] ) in let namedTypeList = List.fold_left argToType [] namedArgList in let loc = emptyLoc in let makePropsLet = makePropsDecl fnName loc namedArgListWithKeyAndRef namedTypeList in let innerExpressionArgs = List.map pluckArg namedArgListWithKeyAndRefForNew @ if hasUnit then [ (Nolabel, Exp.construct { loc; txt = Lident "()" } None) ] else [] in let innerExpression = Exp.apply (Exp.ident { loc ; txt = Lident (match recFlag with | Recursive -> internalFnName | Nonrecursive -> fnName) }) innerExpressionArgs in let innerExpressionWithRef = match forwardRef with | Some txt -> { innerExpression with pexp_desc = Pexp_fun ( nolabel , None , { ppat_desc = Ppat_var { txt; loc = emptyLoc } ; ppat_loc = emptyLoc ; ppat_attributes = [] ; ppat_loc_stack = [] } , innerExpression ) } | None -> innerExpression in let fullExpression = Exp.fun_ nolabel None { ppat_desc = Ppat_constraint ( makePropsName ~loc:emptyLoc props.propsName , makePropsType ~loc:emptyLoc namedTypeList ) ; ppat_loc = emptyLoc ; ppat_attributes = [] ; ppat_loc_stack = [] } innerExpressionWithRef in let fullExpression = match fullModuleName with | "" -> fullExpression | txt -> Exp.let_ Nonrecursive [ Vb.mk ~loc:emptyLoc (Pat.var ~loc:emptyLoc { loc = emptyLoc; txt }) fullExpression ] (Exp.ident ~loc:emptyLoc { loc = emptyLoc; txt = Lident txt }) in let bindings, newBinding = match recFlag with | Recursive -> ( [ bindingWrapper (Exp.let_ ~loc:emptyLoc Recursive [ makeNewBinding binding expression internalFnName ; Vb.mk (Pat.var { loc = emptyLoc; txt = fnName }) fullExpression ] (Exp.ident { loc = emptyLoc; txt = Lident fnName })) ] , None ) | Nonrecursive -> ( [ { binding with pvb_expr = expression; pvb_attributes = [] } ] , Some (bindingWrapper fullExpression) ) in (Some makePropsLet, bindings, newBinding) else (None, [ binding ], None) in let structuresAndBinding = List.map mapBinding valueBindings in let otherStructures (extern, binding, newBinding) (externs, bindings, newBindings) = let externs = match extern with | Some extern -> extern :: externs | None -> externs in let newBindings = match newBinding with | Some newBinding -> newBinding :: newBindings | None -> newBindings in (externs, binding @ bindings, newBindings) in let externs, bindings, newBindings = List.fold_right otherStructures structuresAndBinding ([], [], []) in externs @ [ { pstr_loc; pstr_desc = Pstr_value (recFlag, bindings) } ] @ (match newBindings with | [] -> [] | newBindings -> [ { pstr_loc = emptyLoc ; pstr_desc = Pstr_value (recFlag, newBindings) } ]) @ returnStructures | structure -> structure :: returnStructures in let reactComponentTransform mapper structures = List.fold_right (transformComponentDefinition mapper) structures [] in let transformComponentSignature _mapper signature returnSignatures = match signature with | { psig_loc ; psig_desc = Psig_value ({ pval_name = { txt = fnName }; pval_attributes; pval_type } as psig_desc) } as psig -> ( match List.filter hasAttr pval_attributes with | [] -> signature :: returnSignatures | [ _ ] -> let rec getPropTypes types ({ ptyp_loc; ptyp_desc } as fullType) = match ptyp_desc with | Ptyp_arrow (name, type_, ({ ptyp_desc = Ptyp_arrow _ } as rest)) when isOptional name || isLabelled name -> getPropTypes ((name, ptyp_loc, type_) :: types) rest | Ptyp_arrow (Nolabel, _type, rest) -> getPropTypes types rest | Ptyp_arrow (name, type_, returnValue) when isOptional name || isLabelled name -> (returnValue, (name, returnValue.ptyp_loc, type_) :: types) | _ -> (fullType, types) in let innerType, propTypes = getPropTypes [] pval_type in let namedTypeList = List.fold_left argToConcreteType [] propTypes in let pluckLabelAndLoc (label, loc, type_) = (label, None, loc, Some type_) in let retPropsType = makePropsType ~loc:psig_loc namedTypeList in let externalPropsDecl = makePropsExternalSig fnName psig_loc ((optional "key", None, psig_loc, Some (keyType psig_loc)) :: List.map pluckLabelAndLoc propTypes) retPropsType in let newExternalType = Ptyp_constr ( { loc = psig_loc ; txt = Ldot (Lident "React", "componentLike") } , [ retPropsType; innerType ] ) in let newStructure = { psig with psig_desc = Psig_value { psig_desc with pval_type = { pval_type with ptyp_desc = newExternalType } ; pval_attributes = List.filter otherAttrsPure pval_attributes } } in externalPropsDecl :: newStructure :: returnSignatures | _ -> raise (Invalid_argument "Only one react.component call can exist on a component at \ one time")) | signature -> signature :: returnSignatures in let reactComponentSignatureTransform mapper signatures = List.fold_right (transformComponentSignature mapper) signatures [] in let transformJsxCall mapper callExpression callArguments attrs applyLoc = match callExpression.pexp_desc with | Pexp_ident caller -> ( match caller with | { txt = Lident "createElement" } -> raise (Invalid_argument "JSX: `createElement` should be preceeded by a module name.") Foo.createElement(~prop1 = foo , ~prop2 = bar , ~children= [ ] , ( ) ) | { loc; txt = Ldot (modulePath, ("createElement" | "make")) } -> transformUppercaseCall modulePath mapper loc attrs callExpression callArguments div(~prop1 = foo , ~prop2 = bar , ~children=[bla ] , ( ) ) turn that into ReactDom.createElement(~props = ReactDom.props(~props1 = foo , ~props2 = bar , ( ) ) , [ |bla| ] ) ReactDom.createElement(~props=ReactDom.props(~props1=foo, ~props2=bar, ()), [|bla|]) *) | { loc; txt = Lident id } -> transformLowercaseCall mapper loc attrs callArguments id applyLoc | { txt = Ldot (_, anythingNotCreateElementOrMake) } -> raise (Invalid_argument ("JSX: the JSX attribute should be attached to a \ `YourModuleName.createElement` or `YourModuleName.make` \ call. We saw `" ^ anythingNotCreateElementOrMake ^ "` instead")) | { txt = Lapply _ } -> raise (Invalid_argument "JSX: encountered a weird case while processing the code. \ Please report this!")) | _ -> raise (Invalid_argument "JSX: `createElement` should be preceeded by a simple, direct \ module name.") in object (self) inherit Ast_traverse.map as super method! signature signature = super#signature @@ reactComponentSignatureTransform self signature method! structure structure = match structure with | structures -> super#structure @@ reactComponentTransform self structures method! expression expression = match expression with | { pexp_desc = Pexp_apply (callExpression, callArguments) ; pexp_attributes ; pexp_loc = applyLoc } -> ( let jsxAttribute, nonJSXAttributes = List.partition (fun attribute -> attribute.attr_name.txt = "JSX") pexp_attributes in match (jsxAttribute, nonJSXAttributes) with no JSX attribute | [], _ -> super#expression expression | _, nonJSXAttributes -> transformJsxCall self callExpression callArguments nonJSXAttributes applyLoc) is it a list with jsx attribute ? Reason < > foo</ > to [ @JSX][foo ] | { pexp_desc = ( Pexp_construct ({ txt = Lident "::"; loc }, Some { pexp_desc = Pexp_tuple _ }) | Pexp_construct ({ txt = Lident "[]"; loc }, None) ) ; pexp_attributes } as listItems -> ( let jsxAttribute, nonJSXAttributes = List.partition (fun attribute -> attribute.attr_name.txt = "JSX") pexp_attributes in match (jsxAttribute, nonJSXAttributes) with no JSX attribute | [], _ -> super#expression expression | _, nonJSXAttributes -> let callExpression = [%expr React.Fragment.createElement] in transformJsxCall self callExpression [ (Labelled "children", listItems) ] nonJSXAttributes listItems.pexp_loc) | e -> super#expression e method! module_binding module_binding = let _ = match module_binding.pmb_name.txt with | None -> () | Some txt -> nestedModules := txt :: !nestedModules in let mapped = super#module_binding module_binding in let _ = nestedModules := List.tl !nestedModules in mapped end let rewrite_implementation (code : Parsetree.structure) : Parsetree.structure = let mapper = jsxMapper () in mapper#structure code let rewrite_signature (code : Parsetree.signature) : Parsetree.signature = let mapper = jsxMapper () in mapper#signature code let () = Driver.register_transformation "native-react-ppx" ~impl:rewrite_implementation ~intf:rewrite_signature
a2c17aa3329c67ce95e834b7df1e6ebde25e553ccc74ebb0b3711d2d5f58e894
Eonblast/Scalaxis
hfs_lhsp_md5.erl
2010 - 2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > %% @doc Less hashing, same performance hash function set container %% %% Implementation of a hash function set proposed in 2006 by , " Less Hashing , Same Performance : Building a Better Bloom Filter %% Build k Hash functions of the form g_i(x) = h_1(X) + i * h_2(X) %% %% Used MD5 Hash-Function like in 2000 - L.Fan , . , JA , ZB : " Summary Cache : A Scalable Wide - Area Web Cache Sharing Protocol " ( Counting Bloom Filters Paper ) %% @end %% @version $Id$ -module(hfs_lhsp_md5). % types -behaviour(hfs_beh). -type hf_number() :: integer(). -type hfs_t() :: {hfs_lhsp_md5, hf_number()}. % include -include("hfs_beh.hrl"). % API functions @doc returns a new lhsp hfs new_(_, HFCount) -> new_(HFCount). new_(HFCount) -> {hfs_lhsp_md5, HFCount}. @doc Applies Val to all hash functions in container HC apply_val_({hfs_lhsp_md5, K}, Val) -> ValBin = term_to_binary(Val), HF1 = erlang:adler32(ValBin), <<HF2:128>> = erlang:md5(ValBin), [ HF1 + I * HF2 || I <- lists:seq(0, K-1, 1) ]. % @doc Returns number of hash functions in the container hfs_size_(Hfs) -> {hfs_lhsp_md5, K} = Hfs, K.
null
https://raw.githubusercontent.com/Eonblast/Scalaxis/10287d11428e627dca8c41c818745763b9f7e8d4/src/rrepair/hfs_lhsp_md5.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc Less hashing, same performance hash function set container Implementation of a hash function set proposed in Build k Hash functions of the form g_i(x) = h_1(X) + i * h_2(X) Used MD5 Hash-Function like in @end @version $Id$ types include API functions @doc Returns number of hash functions in the container
2010 - 2011 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > 2006 by , " Less Hashing , Same Performance : Building a Better Bloom Filter 2000 - L.Fan , . , JA , ZB : " Summary Cache : A Scalable Wide - Area Web Cache Sharing Protocol " ( Counting Bloom Filters Paper ) -module(hfs_lhsp_md5). -behaviour(hfs_beh). -type hf_number() :: integer(). -type hfs_t() :: {hfs_lhsp_md5, hf_number()}. -include("hfs_beh.hrl"). @doc returns a new lhsp hfs new_(_, HFCount) -> new_(HFCount). new_(HFCount) -> {hfs_lhsp_md5, HFCount}. @doc Applies Val to all hash functions in container HC apply_val_({hfs_lhsp_md5, K}, Val) -> ValBin = term_to_binary(Val), HF1 = erlang:adler32(ValBin), <<HF2:128>> = erlang:md5(ValBin), [ HF1 + I * HF2 || I <- lists:seq(0, K-1, 1) ]. hfs_size_(Hfs) -> {hfs_lhsp_md5, K} = Hfs, K.
33829c5f33573dcb958648e16a551aca8d322009a8533b7fc01c505480f62c8d
homebaseio/datalog-console
transact_cards.cljs
(ns datalog-console.workspaces.transact-cards)
null
https://raw.githubusercontent.com/homebaseio/datalog-console/af831c85addc345cc5e1af4412821f0cfb80b808/src/dev/datalog_console/workspaces/transact_cards.cljs
clojure
(ns datalog-console.workspaces.transact-cards)
2cc83a80dafc36100a176de3de7ff3ce8f698713ad9b099cff2c54d5d4a9dd5a
dasuxullebt/uxul-world
constants.lisp
Copyright 2009 - 2011 (in-package :uxul-world) (defmacro mydefconst (x y) `(eval-when (:compile-toplevel :load-toplevel) (when (or (not (boundp ',x)) (not (equal ,y (symbol-value ',x)))) (defconstant ,x ,y)))) (mydefconst +screen-width+ 1024) (mydefconst +screen-height+ 768) (mydefconst +class-indices+ '(t uxul-world::animation uxul-world::collision uxul-world::game-object uxul-world::player uxul-world::room uxul-world::stone uxul-world::xy-coordinates uxul-world::bottom uxul-world::moving-enemy uxul-world::standing-enemy uxul-world::moving-item uxul-world::standing-item uxul-world::game-object-with-animation uxul-world::teleporter))
null
https://raw.githubusercontent.com/dasuxullebt/uxul-world/f05e44b099e5976411b3ef1f980ec616bd221425/constants.lisp
lisp
Copyright 2009 - 2011 (in-package :uxul-world) (defmacro mydefconst (x y) `(eval-when (:compile-toplevel :load-toplevel) (when (or (not (boundp ',x)) (not (equal ,y (symbol-value ',x)))) (defconstant ,x ,y)))) (mydefconst +screen-width+ 1024) (mydefconst +screen-height+ 768) (mydefconst +class-indices+ '(t uxul-world::animation uxul-world::collision uxul-world::game-object uxul-world::player uxul-world::room uxul-world::stone uxul-world::xy-coordinates uxul-world::bottom uxul-world::moving-enemy uxul-world::standing-enemy uxul-world::moving-item uxul-world::standing-item uxul-world::game-object-with-animation uxul-world::teleporter))
00dfadf2546e4340ef197235128fbd7d2ac3af328e568fa05f789a8b250b93d1
LambdaHack/LambdaHack
HandleHumanGlobalM.hs
| Semantics of " Game . LambdaHack . Client . UI.HumanCmd " -- client commands that return server requests. -- A couple of them do not take time, the rest does. -- Here prompts and menus are displayed, but any feedback resulting -- from the commands (e.g., from inventory manipulation) is generated later on, -- by the server, for all clients that witness the results of the commands. module Game.LambdaHack.Client.UI.HandleHumanGlobalM * Meta commands byAreaHuman, byAimModeHuman , composeIfLocalHuman, composeUnlessErrorHuman, compose2ndLocalHuman , loopOnNothingHuman, executeIfClearHuman -- * Global commands that usually take time , waitHuman, waitHuman10, yellHuman, moveRunHuman , runOnceAheadHuman, moveOnceToXhairHuman , runOnceToXhairHuman, continueToXhairHuman , moveItemHuman, projectHuman, applyHuman , alterDirHuman, alterWithPointerHuman, closeDirHuman , helpHuman, hintHuman, dashboardHuman, itemMenuHuman, chooseItemMenuHuman , mainMenuHuman, mainMenuAutoOnHuman, mainMenuAutoOffHuman , settingsMenuHuman, challengeMenuHuman, gameDifficultyIncr , gameFishToggle, gameGoodsToggle, gameWolfToggle, gameKeeperToggle , gameScenarioIncr -- * Global commands that never take time , gameExitWithHuman, ExitStrategy(..), gameDropHuman, gameExitHuman , gameSaveHuman, doctrineHuman, automateHuman, automateToggleHuman , automateBackHuman #ifdef EXPOSE_INTERNAL -- * Internal operations , areaToRectangles, meleeAid, displaceAid, moveSearchAlter, alterCommon , goToXhair, goToXhairExplorationMode, goToXhairGoTo , multiActorGoTo, moveOrSelectItem, selectItemsToMove, moveItems , projectItem, applyItem, alterTileAtPos, verifyAlters, processTileActions , verifyEscape, verifyToolEffect, closeTileAtPos, msgAddDone, pickPoint , generateMenu #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Data.Char as Char import Data.Either import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Version import qualified NLP.Miniutter.English as MU import Game.LambdaHack.Client.Bfs import Game.LambdaHack.Client.BfsM import Game.LambdaHack.Client.CommonM import Game.LambdaHack.Client.MonadClient import Game.LambdaHack.Client.Request import Game.LambdaHack.Client.State import Game.LambdaHack.Client.UI.ActorUI import Game.LambdaHack.Client.UI.Content.Input import Game.LambdaHack.Client.UI.Content.Screen import Game.LambdaHack.Client.UI.ContentClientUI import Game.LambdaHack.Client.UI.Frame import Game.LambdaHack.Client.UI.FrameM import Game.LambdaHack.Client.UI.HandleHelperM import Game.LambdaHack.Client.UI.HandleHumanLocalM import Game.LambdaHack.Client.UI.HumanCmd import Game.LambdaHack.Client.UI.InventoryM import Game.LambdaHack.Client.UI.ItemDescription import qualified Game.LambdaHack.Client.UI.Key as K import Game.LambdaHack.Client.UI.KeyBindings import Game.LambdaHack.Client.UI.MonadClientUI import Game.LambdaHack.Client.UI.Msg import Game.LambdaHack.Client.UI.MsgM import Game.LambdaHack.Client.UI.Overlay import Game.LambdaHack.Client.UI.PointUI import Game.LambdaHack.Client.UI.RunM import Game.LambdaHack.Client.UI.SessionUI import Game.LambdaHack.Client.UI.Slideshow import Game.LambdaHack.Client.UI.SlideshowM import Game.LambdaHack.Client.UI.UIOptions import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Area import Game.LambdaHack.Common.ClientOptions import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import qualified Game.LambdaHack.Common.ItemAspect as IA import Game.LambdaHack.Common.Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.Point import Game.LambdaHack.Common.ReqFailure import Game.LambdaHack.Common.State import qualified Game.LambdaHack.Common.Tile as Tile import Game.LambdaHack.Common.Types import Game.LambdaHack.Common.Vector import qualified Game.LambdaHack.Content.FactionKind as FK import qualified Game.LambdaHack.Content.ItemKind as IK import qualified Game.LambdaHack.Content.ModeKind as MK import Game.LambdaHack.Content.RuleKind import qualified Game.LambdaHack.Content.TileKind as TK import qualified Game.LambdaHack.Core.Dice as Dice import Game.LambdaHack.Core.Random import qualified Game.LambdaHack.Definition.Ability as Ability import qualified Game.LambdaHack.Definition.Color as Color import Game.LambdaHack.Definition.Defs import qualified Game.LambdaHack.Definition.DefsInternal as DefsInternal -- * ByArea -- | Pick command depending on area the mouse pointer is in. The first matching area is chosen . If none match , only interrupt . byAreaHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> [(CmdArea, HumanCmd)] -> m (Either MError ReqUI) byAreaHuman cmdSemInCxtOfKM l = do CCUI{coinput=InputContent{brevMap}} <- getsSession sccui pUI <- getsSession spointer let PointSquare px py = uiToSquare pUI abuse of convention : @Point@ , not used -- for the whole UI screen in square font coordinates pointerInArea a = do rs <- areaToRectangles a return $! any (`inside` p) $ catMaybes rs cmds <- filterM (pointerInArea . fst) l case cmds of [] -> do stopPlayBack return $ Left Nothing (_, cmd) : _ -> do let kmFound = case M.lookup cmd brevMap of Just (km : _) -> km _ -> K.escKM cmdSemInCxtOfKM kmFound cmd Many values here are shared with " Game . LambdaHack . Client . UI.DrawM " . areaToRectangles :: MonadClientUI m => CmdArea -> m [Maybe Area] areaToRectangles ca = map toArea <$> do CCUI{coscreen=ScreenContent{rwidth, rheight}} <- getsSession sccui case ca of CaMessage -> return [(0, 0, rwidth - 1, 0)] takes preference over @CaMapParty@ and @CaMap@ mleader <- getsClient sleader case mleader of Nothing -> return [] Just leader -> do b <- getsState $ getActorBody leader let PointSquare x y = mapToSquare $ bpos b return [(x, y, x, y)] takes preference over @CaMap@ lidV <- viewedLevelUI side <- getsClient sside ours <- getsState $ filter (not . bproj) . map snd . actorAssocs (== side) lidV let rectFromB p = let PointSquare x y = mapToSquare p in (x, y, x, y) return $! map (rectFromB . bpos) ours CaMap -> let PointSquare xo yo = mapToSquare originPoint PointSquare xe ye = mapToSquare $ Point (rwidth - 1) (rheight - 4) in return [(xo, yo, xe, ye)] CaLevelNumber -> let y = rheight - 2 in return [(0, y, 1, y)] CaArenaName -> let y = rheight - 2 x = (rwidth - 1) `div` 2 - 11 in return [(3, y, x, y)] CaPercentSeen -> let y = rheight - 2 x = (rwidth - 1) `div` 2 in return [(x - 9, y, x, y)] CaXhairDesc -> let y = rheight - 2 x = (rwidth - 1) `div` 2 + 2 in return [(x, y, rwidth - 1, y)] CaSelected -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(0, y, x - 24, y)] CaCalmGauge -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 22, y, x - 18, y)] CaCalmValue -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 17, y, x - 11, y)] CaHPGauge -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 9, y, x - 6, y)] CaHPValue -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 6, y, x, y)] CaLeaderDesc -> let y = rheight - 1 x = (rwidth - 1) `div` 2 + 2 in return [(x, y, rwidth - 1, y)] -- * ByAimMode byAimModeHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) byAimModeHuman cmdNotAimingM cmdAimingM = do aimMode <- getsSession saimMode if isNothing aimMode then cmdNotAimingM else cmdAimingM * composeIfLocalHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) composeIfLocalHuman c1 c2 = do slideOrCmd1 <- c1 case slideOrCmd1 of Left merr1 -> do slideOrCmd2 <- c2 case slideOrCmd2 of Left merr2 -> return $ Left $ mergeMError merr1 merr2 _ -> return slideOrCmd2 _ -> return slideOrCmd1 * ComposeUnlessError composeUnlessErrorHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) composeUnlessErrorHuman c1 c2 = do slideOrCmd1 <- c1 case slideOrCmd1 of Left Nothing -> c2 _ -> return slideOrCmd1 -- * Compose2ndLocal compose2ndLocalHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) compose2ndLocalHuman c1 c2 = do slideOrCmd1 <- c1 case slideOrCmd1 of Left merr1 -> do slideOrCmd2 <- c2 case slideOrCmd2 of Left merr2 -> return $ Left $ mergeMError merr1 merr2 ignore second request , keep effect req -> do ignore second request , keep effect return req -- * LoopOnNothing loopOnNothingHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) loopOnNothingHuman cmd = do res <- cmd case res of Left Nothing -> loopOnNothingHuman cmd _ -> return res * ExecuteIfClear executeIfClearHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) executeIfClearHuman c1 = do sreportNull <- getsSession sreportNull sreqDelay <- getsSession sreqDelay -- When server query delay is handled, don't complicate things by clearing -- screen instead of running the command. if sreportNull || sreqDelay == ReqDelayHandled then c1 else return $ Left Nothing -- * Wait -- | Leader waits a turn (and blocks, etc.). waitHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) waitHuman leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkWait actorCurAndMaxSk > 0 then do modifySession $ \sess -> sess {swaitTimes = abs (swaitTimes sess) + 1} return $ Right ReqWait else failSer WaitUnskilled -- * Wait10 | Leader waits a 1/10th of a turn ( and does n't block , etc . ) . waitHuman10 :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) waitHuman10 leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkWait actorCurAndMaxSk >= 4 then do modifySession $ \sess -> sess {swaitTimes = abs (swaitTimes sess) + 1} return $ Right ReqWait10 else failSer WaitUnskilled -- * Yell -- | Leader yells or yawns, if sleeping. yellHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) yellHuman leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkWait actorCurAndMaxSk > 0 -- If waiting drained and really, potentially, no other possible action, -- still allow yelling. || Ability.getSk Ability.SkMove actorCurAndMaxSk <= 0 || Ability.getSk Ability.SkDisplace actorCurAndMaxSk <= 0 || Ability.getSk Ability.SkMelee actorCurAndMaxSk <= 0 then return $ Right ReqYell else failSer WaitUnskilled * MoveDir and RunDir moveRunHuman :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> Bool -> Bool -> Vector -> m (FailOrCmd RequestTimed) moveRunHuman leader initialStep finalGoal run runAhead dir = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader arena <- getArenaUI sb <- getsState $ getActorBody leader fact <- getsState $ (EM.! bfid sb) . sfactionD Start running in the given direction . The first turn of running -- succeeds much more often than subsequent turns, because we ignore -- most of the disturbances, since the player is mostly aware of them -- and still explicitly requests a run, knowing how it behaves. sel <- getsSession sselected let runMembers = if runAhead || noRunWithMulti fact then [leader] else ES.elems (ES.delete leader sel) ++ [leader] runParams = RunParams { runLeader = leader , runMembers , runInitial = True , runStopMsg = Nothing , runWaiting = 0 } initRunning = when (initialStep && run) $ do modifySession $ \sess -> sess {srunning = Just runParams} when runAhead $ macroHuman macroRun25 -- When running, the invisible actor is hit (not displaced!), -- so that running in the presence of roving invisible -- actors is equivalent to moving (with visible actors -- this is not a problem, since runnning stops early enough). let tpos = bpos sb `shift` dir -- We start by checking actors at the target position, -- which gives a partial information (actors can be invisible), -- as opposed to accessibility (and items) which are always accurate -- (tiles can't be invisible). tgts <- getsState $ posToAidAssocs tpos arena case tgts of [] -> do -- move or search or alter runStopOrCmd <- moveSearchAlter leader run dir case runStopOrCmd of Left stopMsg -> return $ Left stopMsg Right runCmd -> do Do n't check @initialStep@ and @finalGoal@ -- and don't stop going to target: door opening is mundane enough. initRunning return $ Right runCmd [(target, _)] | run && initialStep && Ability.getSk Ability.SkDisplace actorCurAndMaxSk > 0 -> -- No @stopPlayBack@: initial displace is benign enough. -- Displacing requires accessibility, but it's checked later on. displaceAid leader target _ : _ : _ | run && initialStep && Ability.getSk Ability.SkDisplace actorCurAndMaxSk > 0 -> failSer DisplaceMultiple (target, tb) : _ | not run && initialStep && finalGoal && bfid tb == bfid sb && not (bproj tb) -> do stopPlayBack -- don't ever auto-repeat leader choice -- We always see actors from our own faction. Select one of adjacent actors by bumping into him . Takes no time . success <- pickLeader True target let !_A = assert (success `blame` "bump self" `swith` (leader, target, tb)) () failWith "the pointman switched by bumping" (target, tb) : _ | not run && initialStep && finalGoal && (bfid tb /= bfid sb || bproj tb) -> do stopPlayBack -- don't ever auto-repeat melee if Ability.getSk Ability.SkMelee actorCurAndMaxSk > 0 then -- No problem if there are many projectiles at the spot. We just attack the first one . meleeAid leader target else failSer MeleeUnskilled _ : _ -> failWith "actor in the way" -- | Actor attacks an enemy actor or his own projectile. meleeAid :: (MonadClient m, MonadClientUI m) => ActorId -> ActorId -> m (FailOrCmd RequestTimed) meleeAid leader target = do side <- getsClient sside tb <- getsState $ getActorBody target sfact <- getsState $ (EM.! side) . sfactionD mel <- pickWeaponClient leader target case mel of Nothing -> failWith "nothing to melee with" Just wp -> do let returnCmd = do -- Set personal target to enemy, so that AI, if it takes over -- the actor, is likely to continue the fight even if the foe flees. modifyClient $ updateTarget leader $ const $ Just $ TEnemy target Also set xhair to see the foe 's HP , because it 's automatically -- set to any new spotted actor, so it needs to be reset -- and also it's not useful as permanent ranged target anyway. modifySession $ \sess -> sess {sxhair = Just $ TEnemy target} return $ Right wp res | bproj tb || isFoe side sfact (bfid tb) = returnCmd | isFriend side sfact (bfid tb) = do let !_A = assert (side /= bfid tb) () go1 <- displayYesNo ColorBW "You are bound by an alliance. Really attack?" if not go1 then failWith "attack canceled" else returnCmd | otherwise = do go2 <- displayYesNo ColorBW "This attack will start a war. Are you sure?" if not go2 then failWith "attack canceled" else returnCmd res -- Seeing the actor prevents altering a tile under it, but that -- does not limit the player, he just doesn't waste a turn -- on a failed altering. -- | Actor swaps position with another. displaceAid :: MonadClientUI m => ActorId -> ActorId -> m (FailOrCmd RequestTimed) displaceAid leader target = do COps{coTileSpeedup} <- getsState scops sb <- getsState $ getActorBody leader tb <- getsState $ getActorBody target tfact <- getsState $ (EM.! bfid tb) . sfactionD actorMaxSk <- getsState $ getActorMaxSkills target dEnemy <- getsState $ dispEnemy leader target actorMaxSk let immobile = Ability.getSk Ability.SkMove actorMaxSk <= 0 tpos = bpos tb adj = checkAdjacent sb tb atWar = isFoe (bfid tb) tfact (bfid sb) if | not adj -> failSer DisplaceDistant | not (bproj tb) && atWar && actorDying tb -> -- checked separately for a better message failSer DisplaceDying | not (bproj tb) && atWar && actorWaits tb -> -- checked separately for a better message failSer DisplaceBraced | not (bproj tb) && atWar && immobile -> -- checked separately for a better message failSer DisplaceImmobile | not dEnemy && atWar -> failSer DisplaceSupported | otherwise -> do let lid = blid sb lvl <- getLevel lid -- Displacing requires full access. if Tile.isWalkable coTileSpeedup $ lvl `at` tpos then case posToAidsLvl tpos lvl of [] -> error $ "" `showFailure` (leader, sb, target, tb) [_] -> return $ Right $ ReqDisplace target _ -> failSer DisplaceMultiple else failSer DisplaceAccess -- | Leader moves or searches or alters. No visible actor at the position. moveSearchAlter :: MonadClientUI m => ActorId -> Bool -> Vector -> m (FailOrCmd RequestTimed) moveSearchAlter leader run dir = do COps{coTileSpeedup} <- getsState scops actorCurAndMaxSk <- getsState $ getActorMaxSkills leader sb <- getsState $ getActorBody leader let moveSkill = Ability.getSk Ability.SkMove actorCurAndMaxSk spos = bpos sb -- source position tpos = spos `shift` dir -- target position alterable <- getsState $ tileAlterable (blid sb) tpos lvl <- getLevel $ blid sb let t = lvl `at` tpos runStopOrCmd <- if Tile.isWalkable coTileSpeedup t then -- Movement requires full access. if | moveSkill > 0 -> -- A potential invisible actor is hit. War started without asking. return $ Right $ ReqMove dir | bwatch sb == WSleep -> failSer MoveUnskilledAsleep | otherwise -> failSer MoveUnskilled else do -- Not walkable, so search and/or alter the tile. let sxhair = Just $ TPoint TUnknown (blid sb) tpos Point xhair to see details with ` ~ ` . setXHairFromGUI sxhair if run then do -- Explicit request to examine the terrain. blurb <- lookAtPosition tpos (blid sb) mapM_ (uncurry msgAdd) blurb failWith $ "the terrain is" <+> if | Tile.isModifiable coTileSpeedup t -> "potentially modifiable" | alterable -> "potentially triggerable" | otherwise -> "completely inert" else alterCommon leader True tpos return $! runStopOrCmd alterCommon :: MonadClientUI m => ActorId -> Bool -> Point -> m (FailOrCmd RequestTimed) alterCommon leader bumping tpos = do CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui cops@COps{cotile, coTileSpeedup} <- getsState scops side <- getsClient sside factionD <- getsState sfactionD actorCurAndMaxSk <- getsState $ getActorMaxSkills leader sb <- getsState $ getActorBody leader let alterSkill = Ability.getSk Ability.SkAlter actorCurAndMaxSk spos = bpos sb alterable <- getsState $ tileAlterable (blid sb) tpos lvl <- getLevel $ blid sb localTime <- getsState $ getLocalTime (blid sb) embeds <- getsState $ getEmbedBag (blid sb) tpos itemToF <- getsState $ flip itemToFull getKind <- getsState $ flip getIidKind let t = lvl `at` tpos underFeet = tpos == spos -- if enter and alter, be more permissive modificationFailureHint = msgAdd MsgTutorialHint "Some doors can be opened, stairs unbarred, treasures recovered, only if you find tools that increase your terrain modification ability and act as keys to the puzzle. To gather clues about the keys, listen to what's around you, examine items, inspect terrain, trigger, bump and harass. Once you uncover a likely tool, wield it, return and try to break through again." if | not alterable -> do let name = MU.Text $ TK.tname $ okind cotile t itemLook (iid, kit@(k, _)) = let itemFull = itemToF iid in partItemWsShort rwidth side factionD k localTime itemFull kit embedKindList = map (\(iid, kit) -> (getKind iid, (iid, kit))) (EM.assocs embeds) ilooks = map itemLook $ sortEmbeds cops t embedKindList failWith $ makePhrase $ ["there is no way to activate or modify", MU.AW name] ++ if EM.null embeds then [] else ["with", MU.WWandW ilooks] misclick ? related to AlterNothing but no searching possible ; -- this also rules out activating embeds that only cause -- raw damage, with no chance of altering the tile | Tile.isSuspect coTileSpeedup t && not underFeet && alterSkill <= 1 -> do modificationFailureHint failSer AlterUnskilled | not (Tile.isSuspect coTileSpeedup t) && not underFeet && alterSkill < Tile.alterMinSkill coTileSpeedup t -> do -- Rather rare (requires high skill), so describe the tile. blurb <- lookAtPosition tpos (blid sb) mapM_ (uncurry msgAdd) blurb modificationFailureHint failSer AlterUnwalked | chessDist tpos (bpos sb) > 1 -> -- Checked late to give useful info about distant tiles. failSer AlterDistant | not underFeet && (occupiedBigLvl tpos lvl || occupiedProjLvl tpos lvl) -> -- Don't mislead describing terrain, if other actor is to blame. failSer AlterBlockActor | otherwise -> do -- promising verAlters <- verifyAlters leader bumping tpos case verAlters of Right () -> if bumping then return $ Right $ ReqMove $ vectorToFrom tpos spos else do msgAddDone False leader tpos "modify" return $ Right $ ReqAlter tpos Left err -> return $ Left err -- Even when bumping, we don't use ReqMove, because we don't want -- to hit invisible actors, e.g., hidden in a wall. -- If server performed an attack for free -- on the invisible actor anyway, the player (or AI) -- would be tempted to repeatedly hit random walls -- in hopes of killing a monster residing within. If the action had a cost , misclicks would incur the cost , too . -- Right now the player may repeatedly alter tiles trying to learn -- about invisible pass-wall actors, but when an actor detected, -- it costs a turn and does not harm the invisible actors, -- so it's not so tempting. * runOnceAheadHuman :: MonadClientUI m => ActorId -> m (Either MError RequestTimed) runOnceAheadHuman leader = do side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD keyPressed <- anyKeyPressed srunning <- getsSession srunning -- When running, stop if disturbed. If not running, stop at once. case srunning of Nothing -> do msgAdd MsgRunStopReason "run stop: nothing to do" return $ Left Nothing Just RunParams{runMembers} | noRunWithMulti fact && runMembers /= [leader] -> do msgAdd MsgRunStopReason "run stop: automatic pointman change" return $ Left Nothing Just _runParams | keyPressed -> do discardPressedKey msgAdd MsgRunStopReason "run stop: key pressed" weaveJust <$> failWith "interrupted" Just runParams -> do arena <- getArenaUI runOutcome <- continueRun arena runParams case runOutcome of Left stopMsg -> do msgAdd MsgRunStopReason ("run stop:" <+> stopMsg) return $ Left Nothing Right runCmd -> return $ Right runCmd -- * MoveOnceToXhair moveOnceToXhairHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) moveOnceToXhairHuman leader = goToXhair leader True False goToXhair :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> m (FailOrCmd RequestTimed) goToXhair leader initialStep run = do aimMode <- getsSession saimMode -- Movement is legal only outside aiming mode. if isJust aimMode then failWith "cannot move in aiming mode" else goToXhairExplorationMode leader initialStep run goToXhairExplorationMode :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> m (FailOrCmd RequestTimed) goToXhairExplorationMode leader initialStep run = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader sb <- getsState $ getActorBody leader let moveSkill = Ability.getSk Ability.SkMove actorCurAndMaxSk If skill is too low , no path in @Bfs@ is going to be found , -- but we check the skill (and sleep) to give a more accurate message. if | moveSkill > 0 -> do xhair <- getsSession sxhair xhairGoTo <- getsSession sxhairGoTo mfail <- if isJust xhairGoTo && xhairGoTo /= xhair then failWith "crosshair position changed" else do when (isNothing xhairGoTo) $ -- set it up for next steps modifySession $ \sess -> sess {sxhairGoTo = xhair} goToXhairGoTo leader initialStep run when (isLeft mfail) $ modifySession $ \sess -> sess {sxhairGoTo = Nothing} return mfail | bwatch sb == WSleep -> failSer MoveUnskilledAsleep | otherwise -> failSer MoveUnskilled goToXhairGoTo :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> m (FailOrCmd RequestTimed) goToXhairGoTo leader initialStep run = do b <- getsState $ getActorBody leader mxhairPos <- mxhairToPos case mxhairPos of Nothing -> failWith "crosshair position invalid" Just c -> do running <- getsSession srunning case running of Do n't use running params from previous run or goto - xhair . Just paramOld | not initialStep -> do arena <- getArenaUI runOutcome <- multiActorGoTo arena c paramOld case runOutcome of Left stopMsg -> return $ Left stopMsg Right (finalGoal, dir) -> moveRunHuman leader initialStep finalGoal run False dir _ | c == bpos b -> failWith "position reached" _ -> do let !_A = assert (initialStep || not run) () (bfs, mpath) <- getCacheBfsAndPath leader c xhairMoused <- getsSession sxhairMoused case mpath of _ | xhairMoused && isNothing (accessBfs bfs c) -> failWith "no route to crosshair (press again to go there anyway)" _ | initialStep && adjacent (bpos b) c -> do let dir = towards (bpos b) c moveRunHuman leader initialStep True run False dir Nothing -> failWith "no route to crosshair" Just AndPath{pathList=[]} -> failWith "almost there" Just AndPath{pathList = p1 : _} -> do let finalGoal = p1 == c dir = towards (bpos b) p1 moveRunHuman leader initialStep finalGoal run False dir multiActorGoTo :: (MonadClient m, MonadClientUI m) => LevelId -> Point -> RunParams -> m (FailOrCmd (Bool, Vector)) multiActorGoTo arena c paramOld = case paramOld of RunParams{runMembers = []} -> failWith "selected actors no longer there" RunParams{runMembers = r : rs, runWaiting} -> do onLevel <- getsState $ memActor r arena b <- getsState $ getActorBody r mxhairPos <- mxhairToPos if not onLevel || mxhairPos == Just (bpos b) then do let paramNew = paramOld {runMembers = rs} multiActorGoTo arena c paramNew else do sL <- getState modifyClient $ updateLeader r sL let runMembersNew = rs ++ [r] paramNew = paramOld { runMembers = runMembersNew , runWaiting = 0} (bfs, mpath) <- getCacheBfsAndPath r c xhairMoused <- getsSession sxhairMoused case mpath of _ | xhairMoused && isNothing (accessBfs bfs c) -> failWith "no route to crosshair (press again to go there anyway)" Nothing -> failWith "no route to crosshair" Just AndPath{pathList=[]} -> failWith "almost there" Just AndPath{pathList = p1 : _} -> do let finalGoal = p1 == c dir = towards (bpos b) p1 tgts <- getsState $ posToAids p1 arena case tgts of [] -> do modifySession $ \sess -> sess {srunning = Just paramNew} return $ Right (finalGoal, dir) [target] | target `elem` rs || runWaiting <= length rs -> Let r wait until all others move . it in runWaiting -- to avoid cycles. When all wait for each other, fail. multiActorGoTo arena c paramNew{runWaiting=runWaiting + 1} _ -> failWith "collective running finished" -- usually OK -- * RunOnceToXhair runOnceToXhairHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) runOnceToXhairHuman leader = goToXhair leader True True * ContinueToXhair continueToXhairHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) continueToXhairHuman leader = goToXhair leader False False{-irrelevant-} -- * MoveItem moveItemHuman :: forall m. MonadClientUI m => ActorId -> [CStore] -> CStore -> Maybe Text -> Bool -> m (FailOrCmd RequestTimed) moveItemHuman leader stores destCStore mverb auto = do let !_A = assert (destCStore `notElem` stores) () actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkMoveItem actorCurAndMaxSk > 0 then moveOrSelectItem leader stores destCStore mverb auto else failSer MoveItemUnskilled -- This cannot be structured as projecting or applying, with @ByItemMode@ and @ChooseItemToMove@ , because at least in case of grabbing items , more than one item is chosen , which does n't fit @sitemSel@. Separating -- grabbing of multiple items as a distinct command is too high a price. moveOrSelectItem :: forall m. MonadClientUI m => ActorId -> [CStore] -> CStore -> Maybe Text -> Bool -> m (FailOrCmd RequestTimed) moveOrSelectItem leader storesRaw destCStore mverb auto = do b <- getsState $ getActorBody leader actorCurAndMaxSk <- getsState $ getActorMaxSkills leader mstash <- getsState $ \s -> gstash $ sfactionD s EM.! bfid b let calmE = calmEnough b actorCurAndMaxSk overStash = mstash == Just (blid b, bpos b) stores = case storesRaw of CEqp : rest@(_ : _) | not calmE -> rest ++ [CEqp] CGround : rest@(_ : _) | overStash -> rest ++ [CGround] _ -> storesRaw itemSel <- getsSession sitemSel modifySession $ \sess -> sess {sitemSel = Nothing} -- prevent surprise case itemSel of _ | stores == [CGround] && overStash -> failWith "you can't loot items from your own stash" Just (_, fromCStore@CEqp, _) | fromCStore /= destCStore && fromCStore `elem` stores && not calmE -> failWith "neither the selected item nor any other can be unequipped" Just (_, fromCStore@CGround, _) | fromCStore /= destCStore && fromCStore `elem` stores && overStash -> failWith "you vainly paw through your own hoard" Just (iid, fromCStore, _) | fromCStore /= destCStore && fromCStore `elem` stores -> do bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of Nothing -> -- the case of old selection or selection from another actor moveOrSelectItem leader stores destCStore mverb auto Just (k, it) -> assert (k > 0) $ do let eqpFree = eqpFreeN b kToPick | destCStore == CEqp = min eqpFree k | otherwise = k if | destCStore == CEqp && not calmE -> failSer ItemNotCalm | destCStore == CGround && overStash -> failSer ItemOverStash | kToPick == 0 -> failWith "no more items can be equipped" | otherwise -> do socK <- pickNumber (not auto) kToPick case socK of Left Nothing -> moveOrSelectItem leader stores destCStore mverb auto Left (Just err) -> return $ Left err Right kChosen -> let is = (fromCStore, [(iid, (kChosen, take kChosen it))]) in Right <$> moveItems leader stores is destCStore _ -> do mis <- selectItemsToMove leader stores destCStore mverb auto case mis of Left err -> return $ Left err Right (fromCStore, [(iid, _)]) | stores /= [CGround] -> do modifySession $ \sess -> sess {sitemSel = Just (iid, fromCStore, False)} moveOrSelectItem leader stores destCStore mverb auto Right is@(fromCStore, _) -> if | fromCStore == CEqp && not calmE -> failSer ItemNotCalm | fromCStore == CGround && overStash -> failSer ItemOverStash | otherwise -> Right <$> moveItems leader stores is destCStore selectItemsToMove :: forall m. MonadClientUI m => ActorId -> [CStore] -> CStore -> Maybe Text -> Bool -> m (FailOrCmd (CStore, [(ItemId, ItemQuant)])) selectItemsToMove leader stores destCStore mverb auto = do let verb = fromMaybe (verbCStore destCStore) mverb actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader mstash <- getsState $ \s -> gstash $ sfactionD s EM.! bfid b lastItemMove <- getsSession slastItemMove This calmE is outdated when one of the items increases max Calm -- (e.g., in pickup, which handles many items at once), but this is OK, -- the server accepts item movement based on calm at the start, not end -- or in the middle. -- The calmE is inaccurate also if an item not IDed, but that's intended -- and the server will ignore and warn (and content may avoid that, -- e.g., making all rings identified) let calmE = calmEnough b actorCurAndMaxSk overStash = mstash == Just (blid b, bpos b) if | destCStore == CEqp && not calmE -> failSer ItemNotCalm | destCStore == CGround && overStash -> failSer ItemOverStash | destCStore == CEqp && eqpOverfull b 1 -> failSer EqpOverfull | otherwise -> do let storesLast = case lastItemMove of Just (lastFrom, lastDest) | lastDest == destCStore && lastFrom `elem` stores -> lastFrom : delete lastFrom stores _ -> stores prompt = "What to" promptEqp = "What consumable to" eqpItemsN body = let n = sum $ map fst $ EM.elems $ beqp body in "(" <> makePhrase [MU.CarWs n "item"] ppItemDialogBody body actorSk cCur = case cCur of MStore CEqp | not $ calmEnough body actorSk -> "distractedly paw at" <+> ppItemDialogModeIn cCur MStore CGround | mstash == Just (blid body, bpos body) -> "greedily fondle" <+> ppItemDialogModeIn cCur _ -> case destCStore of CEqp | not $ calmEnough body actorSk -> "distractedly attempt to" <+> verb <+> ppItemDialogModeFrom cCur CEqp | eqpOverfull body 1 -> "attempt to fit into equipment" <+> ppItemDialogModeFrom cCur CGround | mstash == Just (blid body, bpos body) -> "greedily attempt to" <+> verb <+> ppItemDialogModeFrom cCur CEqp -> verb <+> eqpItemsN body <+> "so far)" <+> ppItemDialogModeFrom cCur _ -> verb <+> ppItemDialogModeFrom cCur <+> if cCur == MStore CEqp then eqpItemsN body <+> "now)" else "" (promptGeneric, psuit) = We prune item list only for eqp , because other stores do n't have -- so clear cut heuristics. So when picking up a stash, either grab it to auto - store things , or equip first using the pruning -- and then stash the rest selectively or en masse. if destCStore == CEqp then (promptEqp, return $ SuitsSomething $ \_ itemFull _kit -> IA.goesIntoEqp $ aspectRecordFull itemFull) else (prompt, return SuitsEverything) ggi <- getFull leader psuit (\body _ actorSk cCur _ -> prompt <+> ppItemDialogBody body actorSk cCur) (\body _ actorSk cCur _ -> promptGeneric <+> ppItemDialogBody body actorSk cCur) storesLast (not auto) True case ggi of Right (fromCStore, l) -> do modifySession $ \sess -> sess {slastItemMove = Just (fromCStore, destCStore)} return $ Right (fromCStore, l) Left err -> failWith err moveItems :: forall m. MonadClientUI m => ActorId -> [CStore] -> (CStore, [(ItemId, ItemQuant)]) -> CStore -> m RequestTimed moveItems leader stores (fromCStore, l) destCStore = do let !_A = assert (fromCStore /= destCStore && fromCStore `elem` stores) () actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader discoBenefit <- getsClient sdiscoBenefit let calmE = calmEnough b actorCurAndMaxSk ret4 :: [(ItemId, ItemQuant)] -> Int -> m [(ItemId, Int, CStore, CStore)] ret4 [] _ = return [] ret4 ((iid, (k, _)) : rest) oldN = do let !_A = assert (k > 0) () retRec toCStore = do let n = oldN + if toCStore == CEqp then k else 0 l4 <- ret4 rest n return $ (iid, k, fromCStore, toCStore) : l4 if stores == [CGround] && destCStore == CStash -- normal pickup then -- @CStash@ is the implicit default; refine: if | not $ benInEqp $ discoBenefit EM.! iid -> retRec CStash | eqpOverfull b (oldN + 1) -> do -- Action goes through, but changed, so keep in history. msgAdd MsgActionWarning $ "Warning:" <+> showReqFailure EqpOverfull <> "." retRec CStash | eqpOverfull b (oldN + k) -> do -- If this stack doesn't fit, we don't equip any part of it, -- but we may equip a smaller stack later of other items -- in the same pickup. msgAdd MsgActionWarning $ "Warning:" <+> showReqFailure EqpStackFull <> "." retRec CStash | not calmE -> do msgAdd MsgActionWarning $ "Warning:" <+> showReqFailure ItemNotCalm <> "." retRec CStash | otherwise -> -- Prefer @CEqp@ if all conditions hold: retRec CEqp else case destCStore of -- player forces store, so @benInEqp@ ignored CEqp | eqpOverfull b (oldN + 1) -> do -- Action aborted, so different colour and not in history. msgAdd MsgPromptItems $ "Failure:" <+> showReqFailure EqpOverfull <> "." -- No recursive call here, we exit item manipulation, -- but something is moved or else outer functions would not call us. return [] CEqp | eqpOverfull b (oldN + k) -> do msgAdd MsgPromptItems $ "Failure:" <+> showReqFailure EqpStackFull <> "." return [] _ -> retRec destCStore l4 <- ret4 l 0 if null l4 then error $ "" `showFailure` (stores, fromCStore, l, destCStore) else return $! ReqMoveItems l4 -- * Project projectHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) projectHuman leader = do curChal <- getsClient scurChal actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if | ckeeper curChal -> failSer ProjectFinderKeeper | Ability.getSk Ability.SkProject actorCurAndMaxSk <= 0 -> -- Detailed are check later. failSer ProjectUnskilled | otherwise -> do itemSel <- getsSession sitemSel case itemSel of Just (_, COrgan, _) -> failWith "can't fling an organ" Just (iid, fromCStore, _) -> do b <- getsState $ getActorBody leader bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of Nothing -> failWith "no item to fling" Just _kit -> do itemFull <- getsState $ itemToFull iid let i = (fromCStore, (iid, itemFull)) projectItem leader i Nothing -> failWith "no item to fling" projectItem :: (MonadClient m, MonadClientUI m) => ActorId -> (CStore, (ItemId, ItemFull)) -> m (FailOrCmd RequestTimed) projectItem leader (fromCStore, (iid, itemFull)) = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader let calmE = calmEnough b actorCurAndMaxSk if fromCStore == CEqp && not calmE then failSer ItemNotCalm else do mpsuitReq <- psuitReq leader case mpsuitReq of Left err -> failWith err Right psuitReqFun -> case psuitReqFun itemFull of Left reqFail -> failSer reqFail Right (pos, _) -> do Benefit{benFling} <- getsClient $ (EM.! iid) . sdiscoBenefit go <- if benFling >= 0 then displayYesNo ColorFull "The item may be beneficial. Do you really want to fling it?" else return True if go then do -- Set personal target to enemy, so that AI, if it takes over -- the actor, is likely to continue the fight even if the foe -- flees. Similarly if the crosshair points at position, etc. sxhair <- getsSession sxhair modifyClient $ updateTarget leader (const sxhair) -- Project. eps <- getsClient seps return $ Right $ ReqProject pos eps iid fromCStore else do modifySession $ \sess -> sess {sitemSel = Nothing} failWith "never mind" -- * Apply applyHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) applyHuman leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkApply actorCurAndMaxSk <= 0 then -- detailed check later failSer ApplyUnskilled else do itemSel <- getsSession sitemSel case itemSel of Just (iid, fromCStore, _) -> do b <- getsState $ getActorBody leader bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of Nothing -> failWith "no item to trigger" Just kit -> do itemFull <- getsState $ itemToFull iid applyItem leader (fromCStore, (iid, (itemFull, kit))) Nothing -> failWith "no item to trigger" applyItem :: MonadClientUI m => ActorId -> (CStore, (ItemId, ItemFullKit)) -> m (FailOrCmd RequestTimed) applyItem leader (fromCStore, (iid, (itemFull, kit))) = do COps{corule} <- getsState scops actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader localTime <- getsState $ getLocalTime (blid b) let skill = Ability.getSk Ability.SkApply actorCurAndMaxSk calmE = calmEnough b actorCurAndMaxSk arItem = aspectRecordFull itemFull if fromCStore == CEqp && not calmE then failSer ItemNotCalm else case permittedApply corule localTime skill calmE (Just fromCStore) itemFull kit of Left reqFail -> failSer reqFail Right _ -> do Benefit{benApply} <- getsClient $ (EM.! iid) . sdiscoBenefit go <- if | IA.checkFlag Ability.Periodic arItem && not (IA.checkFlag Ability.Durable arItem) -> -- No warning if item durable, because activation weak, -- but price low, due to no destruction. displayYesNo ColorFull "Triggering this periodic item may not produce all its effects (check item description) and moreover, because it's not durable, will destroy it. Are you sure?" | benApply < 0 -> displayYesNo ColorFull "The item appears harmful. Do you really want to trigger it?" | otherwise -> return True if go then return $ Right $ ReqApply iid fromCStore else do modifySession $ \sess -> sess {sitemSel = Nothing} failWith "never mind" * -- | Ask for a direction and alter a tile, if possible. alterDirHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) alterDirHuman leader = pickPoint leader "modify" >>= \case Just p -> alterTileAtPos leader p Nothing -> failWith "never mind" -- | Try to alter a tile using a feature at the given position. -- -- We don't check if the tile is interesting, e.g., if any embedded -- item can be triggered, because the player explicitely requested -- the action. Consequently, even if all embedded items are recharching, -- the time will be wasted and the server will describe the failure in detail. alterTileAtPos :: MonadClientUI m => ActorId -> Point -> m (FailOrCmd RequestTimed) alterTileAtPos leader pos = do sb <- getsState $ getActorBody leader let sxhair = Just $ TPoint TUnknown (blid sb) pos Point xhair to see details with ` ~ ` . setXHairFromGUI sxhair alterCommon leader False pos -- | Verify that the tile can be transformed or any embedded item effect -- triggered and the player is aware if the effect is dangerous or grave, -- such as ending the game. verifyAlters :: forall m. MonadClientUI m => ActorId -> Bool -> Point -> m (FailOrCmd ()) verifyAlters leader bumping tpos = do COps{cotile, coTileSpeedup} <- getsState scops sb <- getsState $ getActorBody leader arItem <- getsState $ aspectRecordFromIid $ btrunk sb embeds <- getsState $ getEmbedBag (blid sb) tpos lvl <- getLevel $ blid sb getKind <- getsState $ flip getIidKind let embedKindList = if IA.checkFlag Ability.Blast arItem then [] -- prevent embeds triggering each other in a loop else map (\(iid, kit) -> (getKind iid, (iid, kit))) (EM.assocs embeds) underFeet = tpos == bpos sb -- if enter and alter, be more permissive blockedByItem = EM.member tpos (lfloor lvl) tile = lvl `at` tpos feats = TK.tfeature $ okind cotile tile tileActions = mapMaybe (parseTileAction (bproj sb) (underFeet || blockedByItem) -- avoids AlterBlockItem embedKindList) feats if null tileActions && blockedByItem && not underFeet && Tile.isModifiable coTileSpeedup tile then failSer AlterBlockItem else processTileActions leader bumping tpos tileActions processTileActions :: forall m. MonadClientUI m => ActorId -> Bool -> Point -> [TileAction] -> m (FailOrCmd ()) processTileActions leader bumping tpos tas = do COps{coTileSpeedup} <- getsState scops getKind <- getsState $ flip getIidKind sb <- getsState $ getActorBody leader lvl <- getLevel $ blid sb sar <- getsState $ aspectRecordFromIid $ btrunk sb let leaderIsMist = IA.checkFlag Ability.Blast sar && Dice.infDice (IK.idamage $ getKind $ btrunk sb) <= 0 tileMinSkill = Tile.alterMinSkill coTileSpeedup $ lvl `at` tpos processTA :: Maybe Bool -> [TileAction] -> Bool -> m (FailOrCmd (Maybe (Bool, Bool))) processTA museResult [] bumpFailed = do let useResult = fromMaybe False museResult -- No warning will be generated if during explicit modification -- an embed is activated but there is not enough tools -- for a subsequent transformation. This is fine. Bumping would produce the warning and S - dir also displays the tool info . -- We can't rule out the embed is the main feature and the tool -- transformation is not important despite following it. -- We don't want spam in such a case. return $ Right $ if Tile.isSuspect coTileSpeedup (lvl `at` tpos) || useResult && not bumpFailed then Nothing -- success of some kind else Just (useResult, bumpFailed) -- not quite processTA museResult (ta : rest) bumpFailed = case ta of EmbedAction (iid, _) -> do are activated in the order in tile definition -- and never after the tile is changed. -- We assume the item would trigger and we let the player -- take the risk of wasted turn to verify the assumption. -- If the item recharges, the wasted turns let the player wait. let useResult = fromMaybe False museResult if | leaderIsMist || bproj sb && tileMinSkill > 0 -> -- local skill check processTA (Just useResult) rest bumpFailed -- embed won't fire; try others | (not . any IK.isEffEscape) (IK.ieffects $ getKind iid) -> processTA (Just True) rest False -- no escape checking needed, effect found; -- also bumpFailed reset, because must have been -- marginal if an embed was following it | otherwise -> do mfail <- verifyEscape case mfail of Left err -> return $ Left err Right () -> processTA (Just True) rest False -- effect found, bumpFailed reset ToAction{} -> if fromMaybe True museResult && not (bproj sb && tileMinSkill > 0) -- local skill check then return $ Right Nothing -- tile changed, no more activations else processTA museResult rest bumpFailed -- failed, but not due to bumping WithAction tools0 _ -> if not bumping || null tools0 then if fromMaybe True museResult then do -- UI requested, so this is voluntary, so item loss is fine. kitAssG <- getsState $ kitAssocs leader [CGround] kitAssE <- getsState $ kitAssocs leader [CEqp] let kitAss = listToolsToConsume kitAssG kitAssE grps0 = map (\(x, y) -> (False, x, y)) tools0 -- apply if durable (_, iidsToApply, grps) = foldl' subtractIidfromGrps (EM.empty, [], grps0) kitAss if null grps then do let hasEffectOrDmg (_, (_, ItemFull{itemKind})) = IK.idamage itemKind /= 0 || any IK.forApplyEffect (IK.ieffects itemKind) mfail <- case filter hasEffectOrDmg iidsToApply of [] -> return $ Right () (store, (_, itemFull)) : _ -> verifyToolEffect (blid sb) store itemFull case mfail of Left err -> return $ Left err Right () -> return $ Right Nothing -- tile changed, done else processTA museResult rest bumpFailed -- not enough tools else processTA museResult rest bumpFailed -- embeds failed else processTA museResult rest True -- failed due to bumping mfail <- processTA Nothing tas False case mfail of Left err -> return $ Left err Right Nothing -> return $ Right () Right (Just (useResult, bumpFailed)) -> do let !_A = assert (not useResult || bumpFailed) () blurb <- lookAtPosition tpos (blid sb) mapM_ (uncurry msgAdd) blurb if bumpFailed then do revCmd <- revCmdMap let km = revCmd AlterDir msg = "bumping is not enough to transform this terrain; modify with the '" <> T.pack (K.showKM km) <> "' command instead" if useResult then do merr <- failMsg msg msgAdd MsgPromptAction $ showFailError $ fromJust merr return $ Right () -- effect the embed activation, though else failWith msg else failWith "unable to activate nor modify at this time" -- related to, among others, @SfxNoItemsForTile@ on the server verifyEscape :: MonadClientUI m => m (FailOrCmd ()) verifyEscape = do side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD if not (FK.fcanEscape $ gkind fact) then failWith "This is the way out, but where would you go in this alien world?" -- exceptionally a full sentence, because a real question else do (_, total) <- getsState $ calculateTotal side dungeonTotal <- getsState sgold let prompt | dungeonTotal == 0 = "You finally reached your goal. Really leave now?" | total == 0 = "Afraid of the challenge? Leaving so soon and without any treasure? Are you sure?" | total < dungeonTotal = "You've finally found the way out, but you didn't gather all valuables rumoured to be laying around. Really leave already?" | otherwise = "This is the way out and you collected all treasure there is to find. Really leave now?" -- The player can back off, but we never insist, -- because possibly the score formula doesn't reward treasure -- or he is focused on winning only. go <- displayYesNo ColorBW prompt if not go then failWith "here's your chance" else return $ Right () verifyToolEffect :: MonadClientUI m => LevelId -> CStore -> ItemFull -> m (FailOrCmd ()) verifyToolEffect lid store itemFull = do CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui side <- getsClient sside localTime <- getsState $ getLocalTime lid factionD <- getsState sfactionD let (name1, powers) = partItemShort rwidth side factionD localTime itemFull quantSingle objectA = makePhrase [MU.AW name1, powers] -- "Potentially", because an unidentified items on the ground can take -- precedence (perhaps placed there in order to get identified!). prompt = "Do you really want to transform the terrain potentially using" <+> objectA <+> ppCStoreIn store <+> "that may cause substantial side-effects?" objectThe = makePhrase ["the", name1] go <- displayYesNo ColorBW prompt if not go then failWith $ "replace" <+> objectThe <+> "and try again" -- question capitalized and ended with a dot, answer neither else return $ Right () -- * AlterWithPointer -- | Try to alter a tile using a feature under the pointer. alterWithPointerHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) alterWithPointerHuman leader = do COps{corule=RuleContent{rWidthMax, rHeightMax}} <- getsState scops pUI <- getsSession spointer let p = squareToMap $ uiToSquare pUI if insideP (0, 0, rWidthMax - 1, rHeightMax - 1) p then alterTileAtPos leader p else failWith "never mind" -- * CloseDir | Close nearby open tile ; ask for direction , if there is more than one . closeDirHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) closeDirHuman leader = do COps{coTileSpeedup} <- getsState scops b <- getsState $ getActorBody leader lvl <- getLevel $ blid b let vPts = vicinityUnsafe $ bpos b openPts = filter (Tile.isClosable coTileSpeedup . at lvl) vPts case openPts of [] -> failSer CloseNothing [o] -> closeTileAtPos leader o _ -> pickPoint leader "close" >>= \case Nothing -> failWith "never mind" Just p -> closeTileAtPos leader p -- | Close tile at given position. closeTileAtPos :: MonadClientUI m => ActorId -> Point -> m (FailOrCmd RequestTimed) closeTileAtPos leader tpos = do COps{coTileSpeedup} <- getsState scops actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader alterable <- getsState $ tileAlterable (blid b) tpos lvl <- getLevel $ blid b let alterSkill = Ability.getSk Ability.SkAlter actorCurAndMaxSk t = lvl `at` tpos isOpen = Tile.isClosable coTileSpeedup t isClosed = Tile.isOpenable coTileSpeedup t case (alterable, isClosed, isOpen) of (False, _, _) -> failSer CloseNothing (True, False, False) -> failSer CloseNonClosable (True, True, False) -> failSer CloseClosed (True, True, True) -> error "TileKind content validation" (True, False, True) -> if | tpos `chessDist` bpos b > 1 -> failSer CloseDistant | alterSkill <= 1 -> failSer AlterUnskilled | EM.member tpos $ lfloor lvl -> failSer AlterBlockItem | occupiedBigLvl tpos lvl || occupiedProjLvl tpos lvl -> failSer AlterBlockActor | otherwise -> do msgAddDone True leader tpos "close" return $ Right (ReqAlter tpos) -- | Adds message with proper names. msgAddDone :: MonadClientUI m => Bool -> ActorId -> Point -> Text -> m () msgAddDone mentionTile leader p verb = do COps{cotile} <- getsState scops b <- getsState $ getActorBody leader lvl <- getLevel $ blid b let tname = TK.tname $ okind cotile $ lvl `at` p s = case T.words tname of [] -> "thing" ("open" : xs) -> T.unwords xs _ -> tname object | mentionTile = "the" <+> s | otherwise = "" v = p `vectorToFrom` bpos b dir | v == Vector 0 0 = "underneath" | otherwise = compassText v msgAdd MsgActionComplete $ "You" <+> verb <+> object <+> dir <> "." -- | Prompts user to pick a point. pickPoint :: MonadClientUI m => ActorId -> Text -> m (Maybe Point) pickPoint leader verb = do b <- getsState $ getActorBody leader UIOptions{uVi, uLeftHand} <- getsSession sUIOptions let dirKeys = K.dirAllKey uVi uLeftHand keys = K.escKM : K.leftButtonReleaseKM : map (K.KM K.NoModifier) dirKeys msgAdd MsgPromptGeneric $ "Where to" <+> verb <> "? [movement key] [pointer]" slides <- reportToSlideshow [K.escKM] km <- getConfirms ColorFull keys slides case K.key km of K.LeftButtonRelease -> do pUI <- getsSession spointer let p = squareToMap $ uiToSquare pUI return $ Just p _ -> return $ shift (bpos b) <$> K.handleDir dirKeys km -- * Help -- | Display command help. helpHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) helpHuman cmdSemInCxtOfKM = do ccui@CCUI{coinput, coscreen=ScreenContent{rwidth, rheight, rintroScreen}} <- getsSession sccui fontSetup@FontSetup{..} <- getFontSetup gameModeId <- getsState sgameModeId modeOv <- describeMode True gameModeId curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut let displayTutorialHints = fromMaybe curTutorial overrideTut modeH = ( "Press SPACE or PGDN to advance or ESC to see the map again." , (modeOv, []) ) keyH = keyHelp ccui fontSetup -- This takes a list of paragraphs and returns a list of screens. -- Both paragraph and screen is a list of lines. -- -- This would be faster, but less clear, if paragraphs were stored -- reversed in content. Not worth it, until we have huge manuals -- or run on weak mobiles. Even then, precomputation during -- compilation may be better. -- -- Empty lines may appear at the end of pages, but it's fine, -- it means there is a new section on the next page. packIntoScreens :: [[String]] -> [[String]] -> Int -> [[String]] packIntoScreens [] acc _ = [intercalate [""] (reverse acc)] packIntoScreens ([] : ls) [] _ = -- Ignore empty paragraphs at the start of screen. packIntoScreens ls [] 0 packIntoScreens (l : ls) [] h = assert (h == 0) $ -- If a paragraph, even alone, is longer than screen height, it's split. if length l <= rheight - 3 then packIntoScreens ls [l] (length l) else let (screen, rest) = splitAt (rheight - 3) l in screen : packIntoScreens (rest : ls) [] 0 packIntoScreens (l : ls) acc h = The extra @+ 1@ comes from the empty line separating paragraphs , -- as added in @intercalate@. if length l + 1 + h <= rheight - 3 then packIntoScreens ls (l : acc) (length l + 1 + h) else intercalate [""] (reverse acc) : packIntoScreens (l : ls) [] 0 manualScreens = packIntoScreens (snd rintroScreen) [] 0 sideBySide = if isSquareFont monoFont single column , two screens map offsetOverlay $ filter (not . null) [screen1, screen2] two columns , single screen [offsetOverlay screen1 ++ xtranslateOverlay rwidth (offsetOverlay screen2)] listPairs (a : b : rest) = (a, b) : listPairs rest listPairs [a] = [(a, [])] listPairs [] = [] -- Each screen begins with an empty line, to separate the header. manualOvs = map (EM.singleton monoFont) $ concatMap sideBySide $ listPairs $ map ((emptyAttrLine :) . map stringToAL) manualScreens addMnualHeader ov = ( "Showing PLAYING.md (best viewed in the browser)." , (ov, []) ) manualH = map addMnualHeader manualOvs splitHelp (t, okx) = splitOKX fontSetup True rwidth rheight rwidth (textToAS t) [K.spaceKM, K.returnKM, K.escKM] okx sli = toSlideshow fontSetup displayTutorialHints $ concatMap splitHelp $ modeH : keyH ++ manualH -- Thus, the whole help menu corresponds to a single menu of item or lore, -- e.g., shared stash menu. This is especially clear when the shared stash -- menu contains many pages. ekm <- displayChoiceScreen "help" ColorFull True sli [K.spaceKM, K.returnKM, K.escKM] case ekm of Left km | km `elem` [K.escKM, K.spaceKM] -> return $ Left Nothing Left km | km == K.returnKM -> do msgAdd MsgPromptGeneric "Press RET when a command help text is selected to invoke the command." return $ Left Nothing Left km -> case km `M.lookup` bcmdMap coinput of Just (_desc, _cats, cmd) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right _slot -> error $ "" `showFailure` ekm -- * Hint -- | Display hint or, if already displayed, display help. hintHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) hintHuman cmdSemInCxtOfKM = do sreportNull <- getsSession sreportNull if sreportNull then do promptMainKeys return $ Left Nothing else helpHuman cmdSemInCxtOfKM -- * Dashboard -- | Display the dashboard. dashboardHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) dashboardHuman cmdSemInCxtOfKM = do CCUI{coinput, coscreen=ScreenContent{rwidth, rheight}} <- getsSession sccui fontSetup@FontSetup{..} <- getFontSetup curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut let displayTutorialHints = fromMaybe curTutorial overrideTut offsetCol2 = 3 (ov0, kxs0) = okxsN coinput monoFont propFont offsetCol2 (const False) False CmdDashboard ([], [], []) ([], []) al1 = textToAS "Dashboard" splitHelp (al, okx) = splitOKX fontSetup False rwidth (rheight - 2) rwidth al [K.returnKM, K.escKM] okx sli = toSlideshow fontSetup displayTutorialHints $ splitHelp (al1, (ov0, kxs0)) extraKeys = [K.returnKM, K.escKM] ekm <- displayChoiceScreen "dashboard" ColorFull False sli extraKeys case ekm of Left km -> case km `M.lookup` bcmdMap coinput of _ | km == K.escKM -> weaveJust <$> failWith "never mind" _ | km == K.returnKM -> do msgAdd MsgPromptGeneric "Press RET when a menu name is selected to browse the menu." return $ Left Nothing Just (_desc, _cats, cmd) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right _slot -> error $ "" `showFailure` ekm -- * ItemMenu itemMenuHuman :: MonadClientUI m => ActorId -> (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) itemMenuHuman leader cmdSemInCxtOfKM = do COps{corule} <- getsState scops itemSel <- getsSession sitemSel fontSetup@FontSetup{..} <- getFontSetup case itemSel of Just (iid, fromCStore, _) -> do side <- getsClient sside b <- getsState $ getActorBody leader bUI <- getsSession $ getActorUI leader bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of Nothing -> weaveJust <$> failWith "no item to open item menu for" Just kit -> do CCUI{coscreen=ScreenContent{rwidth, rheight}} <- getsSession sccui actorCurAndMaxSk <- getsState $ getActorMaxSkills leader itemFull <- getsState $ itemToFull iid localTime <- getsState $ getLocalTime (blid b) found <- getsState $ findIid leader side iid let !_A = assert (not (null found) || fromCStore == CGround `blame` (iid, leader)) () fAlt (aid, (_, store)) = aid /= leader || store /= fromCStore foundAlt = filter fAlt found markParagraphs = rheight >= 45 meleeSkill = Ability.getSk Ability.SkHurtMelee actorCurAndMaxSk partRawActor aid = getsSession (partActor . getActorUI aid) ppLoc aid store = do parts <- ppContainerWownW partRawActor False (CActor aid store) return $! "[" ++ T.unpack (makePhrase parts) ++ "]" dmode = MStore fromCStore foundTexts <- mapM (\(aid, (_, store)) -> ppLoc aid store) foundAlt (ovLab, ovDesc) <- itemDescOverlays markParagraphs meleeSkill dmode iid kit itemFull rwidth let foundPrefix = textToAS $ if null foundTexts then "" else "The item is also in:" ovPrefix = ytranslateOverlay (length ovDesc) $ offsetOverlay $ splitAttrString rwidth rwidth foundPrefix ystart = length ovDesc + length ovPrefix - 1 xstart = textSize monoFont (Color.spaceAttrW32 : attrLine (snd $ last ovPrefix)) foundKeys = map (K.KM K.NoModifier . K.Fun) starting from 1 ! let ks = zip foundKeys foundTexts width = if isSquareFont monoFont then 2 * rwidth else rwidth (ovFoundRaw, kxsFound) = wrapOKX monoFont ystart xstart width ks ovFound = ovPrefix ++ ovFoundRaw report <- getReportUI True CCUI{coinput} <- getsSession sccui mstash <- getsState $ \s -> gstash $ sfactionD s EM.! side curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut let displayTutorialHints = fromMaybe curTutorial overrideTut calmE = calmEnough b actorCurAndMaxSk greyedOut cmd = not calmE && fromCStore == CEqp || mstash == Just (blid b, bpos b) && fromCStore == CGround || case cmd of ByAimMode AimModeCmd{..} -> greyedOut exploration || greyedOut aiming ComposeIfLocal cmd1 cmd2 -> greyedOut cmd1 || greyedOut cmd2 ComposeUnlessError cmd1 cmd2 -> greyedOut cmd1 || greyedOut cmd2 Compose2ndLocal cmd1 cmd2 -> greyedOut cmd1 || greyedOut cmd2 MoveItem stores destCStore _ _ -> fromCStore `notElem` stores || destCStore == CEqp && (not calmE || eqpOverfull b 1) || destCStore == CGround && mstash == Just (blid b, bpos b) Apply{} -> let skill = Ability.getSk Ability.SkApply actorCurAndMaxSk in not $ fromRight False $ permittedApply corule localTime skill calmE (Just fromCStore) itemFull kit Project{} -> let skill = Ability.getSk Ability.SkProject actorCurAndMaxSk in not $ fromRight False $ permittedProject False skill calmE itemFull _ -> False fmt n k h = " " <> T.justifyLeft n ' ' k <> " " <> h offsetCol2 = 11 keyCaption = fmt offsetCol2 "keys" "command" offset = 1 + maxYofOverlay (ovDesc ++ ovFound) (ov0, kxs0) = xytranslateOKX 0 offset $ okxsN coinput monoFont propFont offsetCol2 greyedOut True CmdItemMenu ([], [], ["", keyCaption]) ([], []) t0 = makeSentence [ MU.SubjectVerbSg (partActor bUI) "choose" , "an item", MU.Text $ ppCStoreIn fromCStore ] alRep = foldr (<+:>) [] $ renderReport True report al1 | null alRep = textToAS t0 | otherwise = alRep ++ stringToAS "\n" ++ textToAS t0 splitHelp (al, okx) = splitOKX fontSetup False rwidth (rheight - 2) rwidth al [K.spaceKM, K.escKM] okx sli = toSlideshow fontSetup displayTutorialHints $ splitHelp ( al1 , ( EM.insertWith (++) squareFont ovLab $ EM.insertWith (++) propFont ovDesc $ EM.insertWith (++) monoFont ovFound ov0 -- mono font, because there are buttons , kxsFound ++ kxs0 )) extraKeys = [K.spaceKM, K.escKM] ++ foundKeys recordHistory -- report shown (e.g., leader switch), save to history ekm <- displayChoiceScreen "item menu" ColorFull False sli extraKeys case ekm of Left km -> case km `M.lookup` bcmdMap coinput of _ | km == K.escKM -> weaveJust <$> failWith "never mind" _ | km == K.spaceKM -> chooseItemMenuHuman leader cmdSemInCxtOfKM dmode _ | km `elem` foundKeys -> case km of K.KM{key=K.Fun n} -> do let (newAid, (bNew, newCStore)) = foundAlt !! (n - 1) fact <- getsState $ (EM.! side) . sfactionD let banned = bannedPointmanSwitchBetweenLevels fact if blid bNew /= blid b && banned then weaveJust <$> failSer NoChangeDunLeader else do -- Verbosity not necessary to notice the switch -- and it's explicitly requested, so no surprise. void $ pickLeader False newAid modifySession $ \sess -> sess {sitemSel = Just (iid, newCStore, False)} itemMenuHuman newAid cmdSemInCxtOfKM _ -> error $ "" `showFailure` km Just (_desc, _cats, cmd) -> do modifySession $ \sess -> sess {sitemSel = Just (iid, fromCStore, True)} cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right _slot -> error $ "" `showFailure` ekm Nothing -> weaveJust <$> failWith "no item to open item menu for" * ChooseItemMenu chooseItemMenuHuman :: MonadClientUI m => ActorId -> (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> ItemDialogMode -> m (Either MError ReqUI) chooseItemMenuHuman leader1 cmdSemInCxtOfKM c1 = do res2 <- chooseItemDialogMode leader1 True c1 case res2 of Right leader2 -> itemMenuHuman leader2 cmdSemInCxtOfKM Left err -> return $ Left $ Just err -- * MainMenu generateMenu :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> FontOverlayMap -> [(Text, HumanCmd, Maybe HumanCmd, Maybe FontOverlayMap)] -> [String] -> String -> m (Either MError ReqUI) generateMenu cmdSemInCxtOfKM blurb kdsRaw gameInfo menuName = do COps{corule} <- getsState scops CCUI{ coinput=InputContent{brevMap} , coscreen=ScreenContent{rheight, rwebAddress} } <- getsSession sccui FontSetup{..} <- getFontSetup let matchKM slot kd@(_, cmd, _, _) = case M.lookup cmd brevMap of Just (km : _) -> (Left km, kd) _ -> (Right slot, kd) kds = zipWith matchKM natSlots kdsRaw bindings = -- key bindings to display let attrCursor = Color.defAttr {Color.bg = Color.HighlightNoneCursor} highAttr ac = ac {Color.acAttr = attrCursor} highW32 = Color.attrCharToW32 . highAttr . Color.attrCharFromW32 markFirst d = markFirstAS $ textToAS d markFirstAS [] = [] markFirstAS (ac : rest) = highW32 ac : rest fmt (ekm, (d, _, _, _)) = (ekm, markFirst d) in map fmt kds generate :: Int -> (KeyOrSlot, AttrString) -> KYX generate y (ekm, binding) = (ekm, (PointUI 0 y, ButtonWidth squareFont (length binding))) okxBindings = ( EM.singleton squareFont $ offsetOverlay $ map (attrStringToAL . snd) bindings , zipWith generate [0..] bindings ) titleLine = rtitle corule ++ " " ++ showVersion (rexeVersion corule) ++ " " titleAndInfo = map stringToAL ([ "" , titleLine ++ "[" ++ rwebAddress ++ "]" , "" ] ++ gameInfo) webButton = ( Left $ K.mkChar '@' -- to start the menu not here , ( PointUI (2 * length titleLine) 1 , ButtonWidth squareFont (2 + length rwebAddress) ) ) okxTitle = ( EM.singleton squareFont $ offsetOverlay titleAndInfo , [webButton] ) okx = xytranslateOKX 2 0 $ sideBySideOKX 2 (length titleAndInfo) okxTitle okxBindings prepareBlurb ovs = let introLen = 1 + maxYofFontOverlayMap ovs start0 = max 0 (rheight - introLen - if isSquareFont propFont then 1 else 2) in EM.map (xytranslateOverlay (-2) (start0 - 2)) ovs subtracting 2 from X and Y to negate the indentation in -- @displayChoiceScreenWithRightPane@ returnDefaultOKS = return (prepareBlurb blurb, []) displayInRightPane ekm = case ekm `lookup` kds of Just (_, _, _, mblurbRight) -> case mblurbRight of Nothing -> returnDefaultOKS Just blurbRight -> return (prepareBlurb blurbRight, []) Nothing | ekm == Left (K.mkChar '@') -> returnDefaultOKS Nothing -> error $ "generateMenu: unexpected key:" `showFailure` ekm keys = [K.leftKM, K.rightKM, K.escKM, K.mkChar '@'] loop = do kmkm <- displayChoiceScreenWithRightPaneKMKM displayInRightPane True menuName ColorFull True (menuToSlideshow okx) keys case kmkm of Left (km@(K.KM {key=K.Left}), ekm) -> case ekm `lookup` kds of Just (_, _, Nothing, _) -> loop Just (_, _, Just cmdReverse, _) -> cmdSemInCxtOfKM km cmdReverse Nothing -> weaveJust <$> failWith "never mind" Left (km@(K.KM {key=K.Right}), ekm) -> case ekm `lookup` kds of Just (_, cmd, _, _) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Left (K.KM {key=K.Char '@'}, _)-> do success <- tryOpenBrowser rwebAddress if success then generateMenu cmdSemInCxtOfKM blurb kdsRaw gameInfo menuName else weaveJust <$> failWith "failed to open web browser" Left (km, _) -> case Left km `lookup` kds of Just (_, cmd, _, _) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right slot -> case Right slot `lookup` kds of Just (_, cmd, _, _) -> cmdSemInCxtOfKM K.escKM cmd Nothing -> weaveJust <$> failWith "never mind" loop -- | Display the main menu. mainMenuHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) mainMenuHuman cmdSemInCxtOfKM = do CCUI{coscreen=ScreenContent{rintroScreen}} <- getsSession sccui FontSetup{propFont} <- getFontSetup gameMode <- getGameMode curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut curChal <- getsClient scurChal let offOn b = if b then "on" else "off" -- Key-description-command tuples. kds = [ ("+ setup and start new game>", ChallengeMenu, Nothing, Nothing) , ("@ save and exit to desktop", GameExit, Nothing, Nothing) , ("+ tweak convenience settings>", SettingsMenu, Nothing, Nothing) , ("@ toggle autoplay", AutomateToggle, Nothing, Nothing) , ("@ see command help", Help, Nothing, Nothing) , ("@ switch to dashboard", Dashboard, Nothing, Nothing) , ("^ back to playing", AutomateBack, Nothing, Nothing) ] gameName = MK.mname gameMode displayTutorialHints = fromMaybe curTutorial overrideTut gameInfo = map T.unpack [ "Now playing:" <+> gameName , "" , " with difficulty:" <+> tshow (cdiff curChal) , " cold fish:" <+> offOn (cfish curChal) , " ready goods:" <+> offOn (cgoods curChal) , " lone wolf:" <+> offOn (cwolf curChal) , " finder keeper:" <+> offOn (ckeeper curChal) , " tutorial hints:" <+> offOn displayTutorialHints , "" ] glueLines (l1 : l2 : rest) = if | null l1 -> l1 : glueLines (l2 : rest) | null l2 -> l1 : l2 : glueLines rest | otherwise -> (l1 ++ l2) : glueLines rest glueLines ll = ll backstory | isSquareFont propFont = fst rintroScreen | otherwise = glueLines $ fst rintroScreen backstoryAL = map (stringToAL . dropWhile (== ' ')) backstory blurb = attrLinesToFontMap [(propFont, backstoryAL)] generateMenu cmdSemInCxtOfKM blurb kds gameInfo "main" * MainMenuAutoOn -- | Display the main menu and set @swasAutomated@. mainMenuAutoOnHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) mainMenuAutoOnHuman cmdSemInCxtOfKM = do modifySession $ \sess -> sess {swasAutomated = True} mainMenuHuman cmdSemInCxtOfKM -- * MainMenuAutoOff -- | Display the main menu and unset @swasAutomated@. mainMenuAutoOffHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) mainMenuAutoOffHuman cmdSemInCxtOfKM = do modifySession $ \sess -> sess {swasAutomated = False} mainMenuHuman cmdSemInCxtOfKM -- * SettingsMenu -- | Display the settings menu. settingsMenuHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) settingsMenuHuman cmdSemInCxtOfKM = do CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui UIOptions{uMsgWrapColumn} <- getsSession sUIOptions FontSetup{..} <- getFontSetup markSuspect <- getsClient smarkSuspect markVision <- getsSession smarkVision markSmell <- getsSession smarkSmell noAnim <- getsClient $ fromMaybe False . snoAnim . soptions side <- getsClient sside factDoctrine <- getsState $ gdoctrine . (EM.! side) . sfactionD overrideTut <- getsSession soverrideTut let offOn b = if b then "on" else "off" offOnAll n = case n of 0 -> "none" 1 -> "untried" 2 -> "all" _ -> error $ "" `showFailure` n neverEver n = case n of 0 -> "never" 1 -> "aiming" 2 -> "always" _ -> error $ "" `showFailure` n offOnUnset mb = case mb of Nothing -> "pass" Just b -> if b then "force on" else "force off" tsuspect = "@ mark suspect terrain:" <+> offOnAll markSuspect tvisible = "@ show visible zone:" <+> neverEver markVision tsmell = "@ display smell clues:" <+> offOn markSmell tanim = "@ play animations:" <+> offOn (not noAnim) tdoctrine = "@ squad doctrine:" <+> Ability.nameDoctrine factDoctrine toverride = "@ override tutorial hints:" <+> offOnUnset overrideTut width = if isSquareFont propFont then rwidth `div` 2 else min uMsgWrapColumn (rwidth - 2) textToBlurb t = Just $ attrLinesToFontMap [ ( propFont , splitAttrString width width $ textToAS t ) ] -- Key-description-command-text tuples. kds = [ ( tsuspect, MarkSuspect 1, Just (MarkSuspect (-1)) , textToBlurb "* mark suspect terrain\nThis setting affects the ongoing and the next games. It determines which suspect terrain is marked in special color on the map: none, untried (not searched nor revealed), all. It correspondingly determines which, if any, suspect tiles are considered for mouse go-to, auto-explore and for the command that marks the nearest unexplored position." ) , ( tvisible, MarkVision 1, Just (MarkVision (-1)) , textToBlurb "* show visible zone\nThis setting affects the ongoing and the next games. It determines the conditions under which the area visible to the party is marked on the map via a gray background: never, when aiming, always." ) , ( tsmell, MarkSmell, Just MarkSmell , textToBlurb "* display smell clues\nThis setting affects the ongoing and the next games. It determines whether the map displays any smell traces (regardless of who left them) detected by a party member that can track via smell (as determined by the smell radius skill; not common among humans)." ) , ( tanim, MarkAnim, Just MarkAnim , textToBlurb "* play animations\nThis setting affects the ongoing and the next games. It determines whether important events, such combat, are highlighted by animations. This overrides the corresponding config file setting." ) , ( tdoctrine, Doctrine, Nothing , textToBlurb "* squad doctrine\nThis setting affects the ongoing game, but does not persist to the next games. It determines the behaviour of henchmen (non-pointman characters) in the party and, in particular, if they are permitted to move autonomously or fire opportunistically (assuming they are able to, usually due to rare equipment). This setting has a poor UI that will be improved in the future." ) , ( toverride, OverrideTut 1, Just (OverrideTut (-1)) , textToBlurb "* override tutorial hints\nThis setting affects the ongoing and the next games. It determines whether tutorial hints are, respectively, not overridden with respect to the default game mode setting, forced to be off, forced to be on. Tutorial hints are rendered as pink messages and can afterwards be re-read from message history." ) , ( "^ back to main menu", MainMenu, Nothing, Just EM.empty ) ] gameInfo = map T.unpack [ "Tweak convenience settings:" , "" ] generateMenu cmdSemInCxtOfKM EM.empty kds gameInfo "settings" -- * ChallengeMenu -- | Display the challenge menu. challengeMenuHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) challengeMenuHuman cmdSemInCxtOfKM = do cops <- getsState scops CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui UIOptions{uMsgWrapColumn} <- getsSession sUIOptions FontSetup{..} <- getFontSetup svictories <- getsSession svictories snxtScenario <- getsSession snxtScenario nxtChal <- getsClient snxtChal let (gameModeId, gameMode) = nxtGameMode cops snxtScenario victories = case EM.lookup gameModeId svictories of Nothing -> 0 Just cm -> fromMaybe 0 (M.lookup nxtChal cm) star t = if victories > 0 then "*" <> t else t tnextScenario = "@ adventure:" <+> star (MK.mname gameMode) offOn b = if b then "on" else "off" tnextDiff = "@ difficulty level:" <+> tshow (cdiff nxtChal) tnextFish = "@ cold fish (rather hard):" <+> offOn (cfish nxtChal) tnextGoods = "@ ready goods (hard):" <+> offOn (cgoods nxtChal) tnextWolf = "@ lone wolf (very hard):" <+> offOn (cwolf nxtChal) tnextKeeper = "@ finder keeper (hard):" <+> offOn (ckeeper nxtChal) width = if isSquareFont propFont then rwidth `div` 2 else min uMsgWrapColumn (rwidth - 2) widthFull = if isSquareFont propFont then rwidth `div` 2 else rwidth - 2 duplicateEOL '\n' = "\n\n" duplicateEOL c = T.singleton c blurb = Just $ attrLinesToFontMap [ ( propFont , splitAttrString width width $ textFgToAS Color.BrBlack $ T.concatMap duplicateEOL (MK.mdesc gameMode) <> "\n\n" ) , ( propFont , splitAttrString widthFull widthFull $ textToAS $ MK.mrules gameMode <> "\n\n" ) , ( propFont , splitAttrString width width $ textToAS $ T.concatMap duplicateEOL (MK.mreason gameMode) ) ] textToBlurb t = Just $ attrLinesToFontMap [ ( propFont , splitAttrString width width -- not widthFull! $ textToAS t ) ] -- Key-description-command-text tuples. kds = [ ( tnextScenario, GameScenarioIncr 1, Just (GameScenarioIncr (-1)) , blurb ) , ( tnextDiff, GameDifficultyIncr 1, Just (GameDifficultyIncr (-1)) , textToBlurb "* difficulty level\nThis determines the difficulty of survival in the next game that's about to be started. Lower numbers result in easier game. In particular, difficulty below 5 multiplies hitpoints of player characters and difficulty over 5 multiplies hitpoints of their enemies. Game score scales with difficulty.") , ( tnextFish, GameFishToggle, Just GameFishToggle , textToBlurb "* cold fish\nThis challenge mode setting will affect the next game that's about to be started. When on, it makes it impossible for player characters to be healed by actors from other factions (this is a significant restriction in the long crawl adventure).") , ( tnextGoods, GameGoodsToggle, Just GameGoodsToggle , textToBlurb "* ready goods\nThis challenge mode setting will affect the next game that's about to be started. When on, it disables crafting for the player, making the selection of equipment, especially melee weapons, very limited, unless the player has the luck to find the rare powerful ready weapons (this applies only if the chosen adventure supports crafting at all).") , ( tnextWolf, GameWolfToggle, Just GameWolfToggle , textToBlurb "* lone wolf\nThis challenge mode setting will affect the next game that's about to be started. When on, it reduces player's starting actors to exactly one, though later on new heroes may join the party. This makes the game very hard in the long run.") , ( tnextKeeper, GameKeeperToggle, Just GameKeeperToggle , textToBlurb "* finder keeper\nThis challenge mode setting will affect the next game that's about to be started. When on, it completely disables flinging projectiles by the player, which affects not only ranged damage dealing, but also throwing of consumables that buff teammates engaged in melee combat, weaken and distract enemies, light dark corners, etc.") , ( "@ start new game", GameRestart, Nothing, blurb ) , ( "^ back to main menu", MainMenu, Nothing, Nothing ) ] gameInfo = map T.unpack [ "Setup and start new game:" , "" ] generateMenu cmdSemInCxtOfKM EM.empty kds gameInfo "challenge" -- * GameDifficultyIncr gameDifficultyIncr :: MonadClient m => Int -> m () gameDifficultyIncr delta = do nxtDiff <- getsClient $ cdiff . snxtChal let d | nxtDiff + delta > difficultyBound = 1 | nxtDiff + delta < 1 = difficultyBound | otherwise = nxtDiff + delta modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cdiff = d} } -- * GameFishToggle gameFishToggle :: MonadClient m => m () gameFishToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cfish = not (cfish (snxtChal cli))} } -- * GameGoodsToggle gameGoodsToggle :: MonadClient m => m () gameGoodsToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cgoods = not (cgoods (snxtChal cli))} } -- * GameWolfToggle gameWolfToggle :: MonadClient m => m () gameWolfToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cwolf = not (cwolf (snxtChal cli))} } * gameKeeperToggle :: MonadClient m => m () gameKeeperToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {ckeeper = not (ckeeper (snxtChal cli))} } -- * GameScenarioIncr gameScenarioIncr :: MonadClientUI m => Int -> m () gameScenarioIncr delta = do cops <- getsState scops oldScenario <- getsSession snxtScenario let snxtScenario = oldScenario + delta snxtTutorial = MK.mtutorial $ snd $ nxtGameMode cops snxtScenario modifySession $ \sess -> sess {snxtScenario, snxtTutorial} * GameRestart & GameQuit data ExitStrategy = Restart | Quit gameExitWithHuman :: MonadClientUI m => ExitStrategy -> m (FailOrCmd ReqUI) gameExitWithHuman exitStrategy = do snxtChal <- getsClient snxtChal cops <- getsState scops noConfirmsGame <- isNoConfirmsGame gameMode <- getGameMode snxtScenario <- getsSession snxtScenario let nxtGameName = MK.mname $ snd $ nxtGameMode cops snxtScenario exitReturn x = return $ Right $ ReqUIGameRestart x snxtChal displayExitMessage diff = displayYesNo ColorBW $ diff <+> "progress of the ongoing" <+> MK.mname gameMode <+> "game will be lost! Are you sure?" ifM (if' noConfirmsGame (return True) -- true case (displayExitMessage $ case exitStrategy of -- false case Restart -> "You just requested a new" <+> nxtGameName <+> "game. The " Quit -> "If you quit, the ")) (exitReturn $ case exitStrategy of -- ifM true case Restart -> let (mainName, _) = T.span (\c -> Char.isAlpha c || c == ' ') nxtGameName in DefsInternal.GroupName $ T.intercalate " " $ take 2 $ T.words mainName Quit -> MK.INSERT_COIN) (rndToActionUI (oneOf -- ifM false case [ "yea, would be a pity to leave them to die" , "yea, a shame to get your team stranded" ]) >>= failWith) ifM :: Monad m => m Bool -> m b -> m b -> m b ifM b t f = do b' <- b; if b' then t else f if' :: Bool -> p -> p -> p if' b t f = if b then t else f -- * GameDrop gameDropHuman :: MonadClientUI m => m ReqUI gameDropHuman = do modifySession $ \sess -> sess {sallNframes = -1} -- hack, but we crash anyway msgAdd MsgPromptGeneric "Interrupt! Trashing the unsaved game. The program exits now." clientPrintUI "Interrupt! Trashing the unsaved game. The program exits now." this is not shown by ANSI frontend , but at least shown by sdl2 one return ReqUIGameDropAndExit -- * GameExit gameExitHuman :: Monad m => m ReqUI gameExitHuman = return ReqUIGameSaveAndExit -- * GameSave gameSaveHuman :: MonadClientUI m => m ReqUI gameSaveHuman = do -- Announce before the saving started, since it can take a while. msgAdd MsgInnerWorkSpam "Saving game backup." return ReqUIGameSave -- * Doctrine -- Note that the difference between seek-target and follow-the-leader doctrine -- can influence even a faction with passive actors. E.g., if a passive actor -- has an extra active skill from equipment, he moves every turn. doctrineHuman :: MonadClientUI m => m (FailOrCmd ReqUI) doctrineHuman = do fid <- getsClient sside fromT <- getsState $ gdoctrine . (EM.! fid) . sfactionD let toT = if fromT == maxBound then minBound else succ fromT go <- displaySpaceEsc ColorFull $ "(Beware, work in progress!)" <+> "Current squad doctrine is '" <> Ability.nameDoctrine fromT <> "'" <+> "(" <> Ability.describeDoctrine fromT <> ")." <+> "Switching doctrine to '" <> Ability.nameDoctrine toT <> "'" <+> "(" <> Ability.describeDoctrine toT <> ")." <+> "This clears targets of all non-pointmen teammates." <+> "New targets will be picked according to new doctrine." if not go then failWith "squad doctrine change canceled" else return $ Right $ ReqUIDoctrine toT -- * Automate automateHuman :: MonadClientUI m => m (FailOrCmd ReqUI) automateHuman = do clearAimMode proceed <- displayYesNo ColorBW "Do you really want to cede control to AI?" if not proceed then failWith "automation canceled" else return $ Right ReqUIAutomate * AutomateToggle automateToggleHuman :: MonadClientUI m => m (FailOrCmd ReqUI) automateToggleHuman = do swasAutomated <- getsSession swasAutomated if swasAutomated then failWith "automation canceled" else automateHuman -- * AutomateBack automateBackHuman :: MonadClientUI m => m (Either MError ReqUI) automateBackHuman = do swasAutomated <- getsSession swasAutomated return $! if swasAutomated then Right ReqUIAutomate else Left Nothing
null
https://raw.githubusercontent.com/LambdaHack/LambdaHack/80d7c24a67224e09673a1d3e80cef9ffb0d91aa4/engine-src/Game/LambdaHack/Client/UI/HandleHumanGlobalM.hs
haskell
client commands that return server requests. A couple of them do not take time, the rest does. Here prompts and menus are displayed, but any feedback resulting from the commands (e.g., from inventory manipulation) is generated later on, by the server, for all clients that witness the results of the commands. * Global commands that usually take time * Global commands that never take time * Internal operations * ByArea | Pick command depending on area the mouse pointer is in. for the whole UI screen in square font coordinates * ByAimMode * Compose2ndLocal * LoopOnNothing When server query delay is handled, don't complicate things by clearing screen instead of running the command. * Wait | Leader waits a turn (and blocks, etc.). * Wait10 * Yell | Leader yells or yawns, if sleeping. If waiting drained and really, potentially, no other possible action, still allow yelling. succeeds much more often than subsequent turns, because we ignore most of the disturbances, since the player is mostly aware of them and still explicitly requests a run, knowing how it behaves. When running, the invisible actor is hit (not displaced!), so that running in the presence of roving invisible actors is equivalent to moving (with visible actors this is not a problem, since runnning stops early enough). We start by checking actors at the target position, which gives a partial information (actors can be invisible), as opposed to accessibility (and items) which are always accurate (tiles can't be invisible). move or search or alter and don't stop going to target: door opening is mundane enough. No @stopPlayBack@: initial displace is benign enough. Displacing requires accessibility, but it's checked later on. don't ever auto-repeat leader choice We always see actors from our own faction. don't ever auto-repeat melee No problem if there are many projectiles at the spot. We just | Actor attacks an enemy actor or his own projectile. Set personal target to enemy, so that AI, if it takes over the actor, is likely to continue the fight even if the foe flees. set to any new spotted actor, so it needs to be reset and also it's not useful as permanent ranged target anyway. Seeing the actor prevents altering a tile under it, but that does not limit the player, he just doesn't waste a turn on a failed altering. | Actor swaps position with another. checked separately for a better message checked separately for a better message checked separately for a better message Displacing requires full access. | Leader moves or searches or alters. No visible actor at the position. source position target position Movement requires full access. A potential invisible actor is hit. War started without asking. Not walkable, so search and/or alter the tile. Explicit request to examine the terrain. if enter and alter, be more permissive this also rules out activating embeds that only cause raw damage, with no chance of altering the tile Rather rare (requires high skill), so describe the tile. Checked late to give useful info about distant tiles. Don't mislead describing terrain, if other actor is to blame. promising Even when bumping, we don't use ReqMove, because we don't want to hit invisible actors, e.g., hidden in a wall. If server performed an attack for free on the invisible actor anyway, the player (or AI) would be tempted to repeatedly hit random walls in hopes of killing a monster residing within. Right now the player may repeatedly alter tiles trying to learn about invisible pass-wall actors, but when an actor detected, it costs a turn and does not harm the invisible actors, so it's not so tempting. When running, stop if disturbed. If not running, stop at once. * MoveOnceToXhair Movement is legal only outside aiming mode. but we check the skill (and sleep) to give a more accurate message. set it up for next steps to avoid cycles. When all wait for each other, fail. usually OK * RunOnceToXhair irrelevant * MoveItem This cannot be structured as projecting or applying, with @ByItemMode@ grabbing of multiple items as a distinct command is too high a price. prevent surprise the case of old selection or selection from another actor (e.g., in pickup, which handles many items at once), but this is OK, the server accepts item movement based on calm at the start, not end or in the middle. The calmE is inaccurate also if an item not IDed, but that's intended and the server will ignore and warn (and content may avoid that, e.g., making all rings identified) so clear cut heuristics. So when picking up a stash, either grab and then stash the rest selectively or en masse. normal pickup @CStash@ is the implicit default; refine: Action goes through, but changed, so keep in history. If this stack doesn't fit, we don't equip any part of it, but we may equip a smaller stack later of other items in the same pickup. Prefer @CEqp@ if all conditions hold: player forces store, so @benInEqp@ ignored Action aborted, so different colour and not in history. No recursive call here, we exit item manipulation, but something is moved or else outer functions would not call us. * Project Detailed are check later. Set personal target to enemy, so that AI, if it takes over the actor, is likely to continue the fight even if the foe flees. Similarly if the crosshair points at position, etc. Project. * Apply detailed check later No warning if item durable, because activation weak, but price low, due to no destruction. | Ask for a direction and alter a tile, if possible. | Try to alter a tile using a feature at the given position. We don't check if the tile is interesting, e.g., if any embedded item can be triggered, because the player explicitely requested the action. Consequently, even if all embedded items are recharching, the time will be wasted and the server will describe the failure in detail. | Verify that the tile can be transformed or any embedded item effect triggered and the player is aware if the effect is dangerous or grave, such as ending the game. prevent embeds triggering each other in a loop if enter and alter, be more permissive avoids AlterBlockItem No warning will be generated if during explicit modification an embed is activated but there is not enough tools for a subsequent transformation. This is fine. Bumping would We can't rule out the embed is the main feature and the tool transformation is not important despite following it. We don't want spam in such a case. success of some kind not quite and never after the tile is changed. We assume the item would trigger and we let the player take the risk of wasted turn to verify the assumption. If the item recharges, the wasted turns let the player wait. local skill check embed won't fire; try others no escape checking needed, effect found; also bumpFailed reset, because must have been marginal if an embed was following it effect found, bumpFailed reset local skill check tile changed, no more activations failed, but not due to bumping UI requested, so this is voluntary, so item loss is fine. apply if durable tile changed, done not enough tools embeds failed failed due to bumping effect the embed activation, though related to, among others, @SfxNoItemsForTile@ on the server exceptionally a full sentence, because a real question The player can back off, but we never insist, because possibly the score formula doesn't reward treasure or he is focused on winning only. "Potentially", because an unidentified items on the ground can take precedence (perhaps placed there in order to get identified!). question capitalized and ended with a dot, answer neither * AlterWithPointer | Try to alter a tile using a feature under the pointer. * CloseDir | Close tile at given position. | Adds message with proper names. | Prompts user to pick a point. * Help | Display command help. This takes a list of paragraphs and returns a list of screens. Both paragraph and screen is a list of lines. This would be faster, but less clear, if paragraphs were stored reversed in content. Not worth it, until we have huge manuals or run on weak mobiles. Even then, precomputation during compilation may be better. Empty lines may appear at the end of pages, but it's fine, it means there is a new section on the next page. Ignore empty paragraphs at the start of screen. If a paragraph, even alone, is longer than screen height, it's split. as added in @intercalate@. Each screen begins with an empty line, to separate the header. Thus, the whole help menu corresponds to a single menu of item or lore, e.g., shared stash menu. This is especially clear when the shared stash menu contains many pages. * Hint | Display hint or, if already displayed, display help. * Dashboard | Display the dashboard. * ItemMenu mono font, because there are buttons report shown (e.g., leader switch), save to history Verbosity not necessary to notice the switch and it's explicitly requested, so no surprise. * MainMenu key bindings to display to start the menu not here @displayChoiceScreenWithRightPane@ | Display the main menu. Key-description-command tuples. | Display the main menu and set @swasAutomated@. * MainMenuAutoOff | Display the main menu and unset @swasAutomated@. * SettingsMenu | Display the settings menu. Key-description-command-text tuples. * ChallengeMenu | Display the challenge menu. not widthFull! Key-description-command-text tuples. * GameDifficultyIncr * GameFishToggle * GameGoodsToggle * GameWolfToggle * GameScenarioIncr true case false case ifM true case ifM false case * GameDrop hack, but we crash anyway * GameExit * GameSave Announce before the saving started, since it can take a while. * Doctrine Note that the difference between seek-target and follow-the-leader doctrine can influence even a faction with passive actors. E.g., if a passive actor has an extra active skill from equipment, he moves every turn. * Automate * AutomateBack
| Semantics of " Game . LambdaHack . Client . UI.HumanCmd " module Game.LambdaHack.Client.UI.HandleHumanGlobalM * Meta commands byAreaHuman, byAimModeHuman , composeIfLocalHuman, composeUnlessErrorHuman, compose2ndLocalHuman , loopOnNothingHuman, executeIfClearHuman , waitHuman, waitHuman10, yellHuman, moveRunHuman , runOnceAheadHuman, moveOnceToXhairHuman , runOnceToXhairHuman, continueToXhairHuman , moveItemHuman, projectHuman, applyHuman , alterDirHuman, alterWithPointerHuman, closeDirHuman , helpHuman, hintHuman, dashboardHuman, itemMenuHuman, chooseItemMenuHuman , mainMenuHuman, mainMenuAutoOnHuman, mainMenuAutoOffHuman , settingsMenuHuman, challengeMenuHuman, gameDifficultyIncr , gameFishToggle, gameGoodsToggle, gameWolfToggle, gameKeeperToggle , gameScenarioIncr , gameExitWithHuman, ExitStrategy(..), gameDropHuman, gameExitHuman , gameSaveHuman, doctrineHuman, automateHuman, automateToggleHuman , automateBackHuman #ifdef EXPOSE_INTERNAL , areaToRectangles, meleeAid, displaceAid, moveSearchAlter, alterCommon , goToXhair, goToXhairExplorationMode, goToXhairGoTo , multiActorGoTo, moveOrSelectItem, selectItemsToMove, moveItems , projectItem, applyItem, alterTileAtPos, verifyAlters, processTileActions , verifyEscape, verifyToolEffect, closeTileAtPos, msgAddDone, pickPoint , generateMenu #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Data.Char as Char import Data.Either import qualified Data.EnumMap.Strict as EM import qualified Data.EnumSet as ES import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Version import qualified NLP.Miniutter.English as MU import Game.LambdaHack.Client.Bfs import Game.LambdaHack.Client.BfsM import Game.LambdaHack.Client.CommonM import Game.LambdaHack.Client.MonadClient import Game.LambdaHack.Client.Request import Game.LambdaHack.Client.State import Game.LambdaHack.Client.UI.ActorUI import Game.LambdaHack.Client.UI.Content.Input import Game.LambdaHack.Client.UI.Content.Screen import Game.LambdaHack.Client.UI.ContentClientUI import Game.LambdaHack.Client.UI.Frame import Game.LambdaHack.Client.UI.FrameM import Game.LambdaHack.Client.UI.HandleHelperM import Game.LambdaHack.Client.UI.HandleHumanLocalM import Game.LambdaHack.Client.UI.HumanCmd import Game.LambdaHack.Client.UI.InventoryM import Game.LambdaHack.Client.UI.ItemDescription import qualified Game.LambdaHack.Client.UI.Key as K import Game.LambdaHack.Client.UI.KeyBindings import Game.LambdaHack.Client.UI.MonadClientUI import Game.LambdaHack.Client.UI.Msg import Game.LambdaHack.Client.UI.MsgM import Game.LambdaHack.Client.UI.Overlay import Game.LambdaHack.Client.UI.PointUI import Game.LambdaHack.Client.UI.RunM import Game.LambdaHack.Client.UI.SessionUI import Game.LambdaHack.Client.UI.Slideshow import Game.LambdaHack.Client.UI.SlideshowM import Game.LambdaHack.Client.UI.UIOptions import Game.LambdaHack.Common.Actor import Game.LambdaHack.Common.ActorState import Game.LambdaHack.Common.Area import Game.LambdaHack.Common.ClientOptions import Game.LambdaHack.Common.Faction import Game.LambdaHack.Common.Item import qualified Game.LambdaHack.Common.ItemAspect as IA import Game.LambdaHack.Common.Kind import Game.LambdaHack.Common.Level import Game.LambdaHack.Common.Misc import Game.LambdaHack.Common.MonadStateRead import Game.LambdaHack.Common.Point import Game.LambdaHack.Common.ReqFailure import Game.LambdaHack.Common.State import qualified Game.LambdaHack.Common.Tile as Tile import Game.LambdaHack.Common.Types import Game.LambdaHack.Common.Vector import qualified Game.LambdaHack.Content.FactionKind as FK import qualified Game.LambdaHack.Content.ItemKind as IK import qualified Game.LambdaHack.Content.ModeKind as MK import Game.LambdaHack.Content.RuleKind import qualified Game.LambdaHack.Content.TileKind as TK import qualified Game.LambdaHack.Core.Dice as Dice import Game.LambdaHack.Core.Random import qualified Game.LambdaHack.Definition.Ability as Ability import qualified Game.LambdaHack.Definition.Color as Color import Game.LambdaHack.Definition.Defs import qualified Game.LambdaHack.Definition.DefsInternal as DefsInternal The first matching area is chosen . If none match , only interrupt . byAreaHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> [(CmdArea, HumanCmd)] -> m (Either MError ReqUI) byAreaHuman cmdSemInCxtOfKM l = do CCUI{coinput=InputContent{brevMap}} <- getsSession sccui pUI <- getsSession spointer let PointSquare px py = uiToSquare pUI abuse of convention : @Point@ , not used pointerInArea a = do rs <- areaToRectangles a return $! any (`inside` p) $ catMaybes rs cmds <- filterM (pointerInArea . fst) l case cmds of [] -> do stopPlayBack return $ Left Nothing (_, cmd) : _ -> do let kmFound = case M.lookup cmd brevMap of Just (km : _) -> km _ -> K.escKM cmdSemInCxtOfKM kmFound cmd Many values here are shared with " Game . LambdaHack . Client . UI.DrawM " . areaToRectangles :: MonadClientUI m => CmdArea -> m [Maybe Area] areaToRectangles ca = map toArea <$> do CCUI{coscreen=ScreenContent{rwidth, rheight}} <- getsSession sccui case ca of CaMessage -> return [(0, 0, rwidth - 1, 0)] takes preference over @CaMapParty@ and @CaMap@ mleader <- getsClient sleader case mleader of Nothing -> return [] Just leader -> do b <- getsState $ getActorBody leader let PointSquare x y = mapToSquare $ bpos b return [(x, y, x, y)] takes preference over @CaMap@ lidV <- viewedLevelUI side <- getsClient sside ours <- getsState $ filter (not . bproj) . map snd . actorAssocs (== side) lidV let rectFromB p = let PointSquare x y = mapToSquare p in (x, y, x, y) return $! map (rectFromB . bpos) ours CaMap -> let PointSquare xo yo = mapToSquare originPoint PointSquare xe ye = mapToSquare $ Point (rwidth - 1) (rheight - 4) in return [(xo, yo, xe, ye)] CaLevelNumber -> let y = rheight - 2 in return [(0, y, 1, y)] CaArenaName -> let y = rheight - 2 x = (rwidth - 1) `div` 2 - 11 in return [(3, y, x, y)] CaPercentSeen -> let y = rheight - 2 x = (rwidth - 1) `div` 2 in return [(x - 9, y, x, y)] CaXhairDesc -> let y = rheight - 2 x = (rwidth - 1) `div` 2 + 2 in return [(x, y, rwidth - 1, y)] CaSelected -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(0, y, x - 24, y)] CaCalmGauge -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 22, y, x - 18, y)] CaCalmValue -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 17, y, x - 11, y)] CaHPGauge -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 9, y, x - 6, y)] CaHPValue -> let y = rheight - 1 x = (rwidth - 1) `div` 2 in return [(x - 6, y, x, y)] CaLeaderDesc -> let y = rheight - 1 x = (rwidth - 1) `div` 2 + 2 in return [(x, y, rwidth - 1, y)] byAimModeHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) byAimModeHuman cmdNotAimingM cmdAimingM = do aimMode <- getsSession saimMode if isNothing aimMode then cmdNotAimingM else cmdAimingM * composeIfLocalHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) composeIfLocalHuman c1 c2 = do slideOrCmd1 <- c1 case slideOrCmd1 of Left merr1 -> do slideOrCmd2 <- c2 case slideOrCmd2 of Left merr2 -> return $ Left $ mergeMError merr1 merr2 _ -> return slideOrCmd2 _ -> return slideOrCmd1 * ComposeUnlessError composeUnlessErrorHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) composeUnlessErrorHuman c1 c2 = do slideOrCmd1 <- c1 case slideOrCmd1 of Left Nothing -> c2 _ -> return slideOrCmd1 compose2ndLocalHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI) compose2ndLocalHuman c1 c2 = do slideOrCmd1 <- c1 case slideOrCmd1 of Left merr1 -> do slideOrCmd2 <- c2 case slideOrCmd2 of Left merr2 -> return $ Left $ mergeMError merr1 merr2 ignore second request , keep effect req -> do ignore second request , keep effect return req loopOnNothingHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) loopOnNothingHuman cmd = do res <- cmd case res of Left Nothing -> loopOnNothingHuman cmd _ -> return res * ExecuteIfClear executeIfClearHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) executeIfClearHuman c1 = do sreportNull <- getsSession sreportNull sreqDelay <- getsSession sreqDelay if sreportNull || sreqDelay == ReqDelayHandled then c1 else return $ Left Nothing waitHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) waitHuman leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkWait actorCurAndMaxSk > 0 then do modifySession $ \sess -> sess {swaitTimes = abs (swaitTimes sess) + 1} return $ Right ReqWait else failSer WaitUnskilled | Leader waits a 1/10th of a turn ( and does n't block , etc . ) . waitHuman10 :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) waitHuman10 leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkWait actorCurAndMaxSk >= 4 then do modifySession $ \sess -> sess {swaitTimes = abs (swaitTimes sess) + 1} return $ Right ReqWait10 else failSer WaitUnskilled yellHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) yellHuman leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkWait actorCurAndMaxSk > 0 || Ability.getSk Ability.SkMove actorCurAndMaxSk <= 0 || Ability.getSk Ability.SkDisplace actorCurAndMaxSk <= 0 || Ability.getSk Ability.SkMelee actorCurAndMaxSk <= 0 then return $ Right ReqYell else failSer WaitUnskilled * MoveDir and RunDir moveRunHuman :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> Bool -> Bool -> Vector -> m (FailOrCmd RequestTimed) moveRunHuman leader initialStep finalGoal run runAhead dir = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader arena <- getArenaUI sb <- getsState $ getActorBody leader fact <- getsState $ (EM.! bfid sb) . sfactionD Start running in the given direction . The first turn of running sel <- getsSession sselected let runMembers = if runAhead || noRunWithMulti fact then [leader] else ES.elems (ES.delete leader sel) ++ [leader] runParams = RunParams { runLeader = leader , runMembers , runInitial = True , runStopMsg = Nothing , runWaiting = 0 } initRunning = when (initialStep && run) $ do modifySession $ \sess -> sess {srunning = Just runParams} when runAhead $ macroHuman macroRun25 let tpos = bpos sb `shift` dir tgts <- getsState $ posToAidAssocs tpos arena case tgts of runStopOrCmd <- moveSearchAlter leader run dir case runStopOrCmd of Left stopMsg -> return $ Left stopMsg Right runCmd -> do Do n't check @initialStep@ and @finalGoal@ initRunning return $ Right runCmd [(target, _)] | run && initialStep && Ability.getSk Ability.SkDisplace actorCurAndMaxSk > 0 -> displaceAid leader target _ : _ : _ | run && initialStep && Ability.getSk Ability.SkDisplace actorCurAndMaxSk > 0 -> failSer DisplaceMultiple (target, tb) : _ | not run && initialStep && finalGoal && bfid tb == bfid sb && not (bproj tb) -> do Select one of adjacent actors by bumping into him . Takes no time . success <- pickLeader True target let !_A = assert (success `blame` "bump self" `swith` (leader, target, tb)) () failWith "the pointman switched by bumping" (target, tb) : _ | not run && initialStep && finalGoal && (bfid tb /= bfid sb || bproj tb) -> do if Ability.getSk Ability.SkMelee actorCurAndMaxSk > 0 attack the first one . meleeAid leader target else failSer MeleeUnskilled _ : _ -> failWith "actor in the way" meleeAid :: (MonadClient m, MonadClientUI m) => ActorId -> ActorId -> m (FailOrCmd RequestTimed) meleeAid leader target = do side <- getsClient sside tb <- getsState $ getActorBody target sfact <- getsState $ (EM.! side) . sfactionD mel <- pickWeaponClient leader target case mel of Nothing -> failWith "nothing to melee with" Just wp -> do let returnCmd = do modifyClient $ updateTarget leader $ const $ Just $ TEnemy target Also set xhair to see the foe 's HP , because it 's automatically modifySession $ \sess -> sess {sxhair = Just $ TEnemy target} return $ Right wp res | bproj tb || isFoe side sfact (bfid tb) = returnCmd | isFriend side sfact (bfid tb) = do let !_A = assert (side /= bfid tb) () go1 <- displayYesNo ColorBW "You are bound by an alliance. Really attack?" if not go1 then failWith "attack canceled" else returnCmd | otherwise = do go2 <- displayYesNo ColorBW "This attack will start a war. Are you sure?" if not go2 then failWith "attack canceled" else returnCmd res displaceAid :: MonadClientUI m => ActorId -> ActorId -> m (FailOrCmd RequestTimed) displaceAid leader target = do COps{coTileSpeedup} <- getsState scops sb <- getsState $ getActorBody leader tb <- getsState $ getActorBody target tfact <- getsState $ (EM.! bfid tb) . sfactionD actorMaxSk <- getsState $ getActorMaxSkills target dEnemy <- getsState $ dispEnemy leader target actorMaxSk let immobile = Ability.getSk Ability.SkMove actorMaxSk <= 0 tpos = bpos tb adj = checkAdjacent sb tb atWar = isFoe (bfid tb) tfact (bfid sb) if | not adj -> failSer DisplaceDistant | not (bproj tb) && atWar failSer DisplaceDying | not (bproj tb) && atWar failSer DisplaceBraced | not (bproj tb) && atWar failSer DisplaceImmobile | not dEnemy && atWar -> failSer DisplaceSupported | otherwise -> do let lid = blid sb lvl <- getLevel lid if Tile.isWalkable coTileSpeedup $ lvl `at` tpos then case posToAidsLvl tpos lvl of [] -> error $ "" `showFailure` (leader, sb, target, tb) [_] -> return $ Right $ ReqDisplace target _ -> failSer DisplaceMultiple else failSer DisplaceAccess moveSearchAlter :: MonadClientUI m => ActorId -> Bool -> Vector -> m (FailOrCmd RequestTimed) moveSearchAlter leader run dir = do COps{coTileSpeedup} <- getsState scops actorCurAndMaxSk <- getsState $ getActorMaxSkills leader sb <- getsState $ getActorBody leader let moveSkill = Ability.getSk Ability.SkMove actorCurAndMaxSk alterable <- getsState $ tileAlterable (blid sb) tpos lvl <- getLevel $ blid sb let t = lvl `at` tpos runStopOrCmd <- if | moveSkill > 0 -> return $ Right $ ReqMove dir | bwatch sb == WSleep -> failSer MoveUnskilledAsleep | otherwise -> failSer MoveUnskilled let sxhair = Just $ TPoint TUnknown (blid sb) tpos Point xhair to see details with ` ~ ` . setXHairFromGUI sxhair if run then do blurb <- lookAtPosition tpos (blid sb) mapM_ (uncurry msgAdd) blurb failWith $ "the terrain is" <+> if | Tile.isModifiable coTileSpeedup t -> "potentially modifiable" | alterable -> "potentially triggerable" | otherwise -> "completely inert" else alterCommon leader True tpos return $! runStopOrCmd alterCommon :: MonadClientUI m => ActorId -> Bool -> Point -> m (FailOrCmd RequestTimed) alterCommon leader bumping tpos = do CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui cops@COps{cotile, coTileSpeedup} <- getsState scops side <- getsClient sside factionD <- getsState sfactionD actorCurAndMaxSk <- getsState $ getActorMaxSkills leader sb <- getsState $ getActorBody leader let alterSkill = Ability.getSk Ability.SkAlter actorCurAndMaxSk spos = bpos sb alterable <- getsState $ tileAlterable (blid sb) tpos lvl <- getLevel $ blid sb localTime <- getsState $ getLocalTime (blid sb) embeds <- getsState $ getEmbedBag (blid sb) tpos itemToF <- getsState $ flip itemToFull getKind <- getsState $ flip getIidKind let t = lvl `at` tpos modificationFailureHint = msgAdd MsgTutorialHint "Some doors can be opened, stairs unbarred, treasures recovered, only if you find tools that increase your terrain modification ability and act as keys to the puzzle. To gather clues about the keys, listen to what's around you, examine items, inspect terrain, trigger, bump and harass. Once you uncover a likely tool, wield it, return and try to break through again." if | not alterable -> do let name = MU.Text $ TK.tname $ okind cotile t itemLook (iid, kit@(k, _)) = let itemFull = itemToF iid in partItemWsShort rwidth side factionD k localTime itemFull kit embedKindList = map (\(iid, kit) -> (getKind iid, (iid, kit))) (EM.assocs embeds) ilooks = map itemLook $ sortEmbeds cops t embedKindList failWith $ makePhrase $ ["there is no way to activate or modify", MU.AW name] ++ if EM.null embeds then [] else ["with", MU.WWandW ilooks] misclick ? related to AlterNothing but no searching possible ; | Tile.isSuspect coTileSpeedup t && not underFeet && alterSkill <= 1 -> do modificationFailureHint failSer AlterUnskilled | not (Tile.isSuspect coTileSpeedup t) && not underFeet && alterSkill < Tile.alterMinSkill coTileSpeedup t -> do blurb <- lookAtPosition tpos (blid sb) mapM_ (uncurry msgAdd) blurb modificationFailureHint failSer AlterUnwalked | chessDist tpos (bpos sb) > 1 -> failSer AlterDistant | not underFeet && (occupiedBigLvl tpos lvl || occupiedProjLvl tpos lvl) -> failSer AlterBlockActor verAlters <- verifyAlters leader bumping tpos case verAlters of Right () -> if bumping then return $ Right $ ReqMove $ vectorToFrom tpos spos else do msgAddDone False leader tpos "modify" return $ Right $ ReqAlter tpos Left err -> return $ Left err If the action had a cost , misclicks would incur the cost , too . * runOnceAheadHuman :: MonadClientUI m => ActorId -> m (Either MError RequestTimed) runOnceAheadHuman leader = do side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD keyPressed <- anyKeyPressed srunning <- getsSession srunning case srunning of Nothing -> do msgAdd MsgRunStopReason "run stop: nothing to do" return $ Left Nothing Just RunParams{runMembers} | noRunWithMulti fact && runMembers /= [leader] -> do msgAdd MsgRunStopReason "run stop: automatic pointman change" return $ Left Nothing Just _runParams | keyPressed -> do discardPressedKey msgAdd MsgRunStopReason "run stop: key pressed" weaveJust <$> failWith "interrupted" Just runParams -> do arena <- getArenaUI runOutcome <- continueRun arena runParams case runOutcome of Left stopMsg -> do msgAdd MsgRunStopReason ("run stop:" <+> stopMsg) return $ Left Nothing Right runCmd -> return $ Right runCmd moveOnceToXhairHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) moveOnceToXhairHuman leader = goToXhair leader True False goToXhair :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> m (FailOrCmd RequestTimed) goToXhair leader initialStep run = do aimMode <- getsSession saimMode if isJust aimMode then failWith "cannot move in aiming mode" else goToXhairExplorationMode leader initialStep run goToXhairExplorationMode :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> m (FailOrCmd RequestTimed) goToXhairExplorationMode leader initialStep run = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader sb <- getsState $ getActorBody leader let moveSkill = Ability.getSk Ability.SkMove actorCurAndMaxSk If skill is too low , no path in @Bfs@ is going to be found , if | moveSkill > 0 -> do xhair <- getsSession sxhair xhairGoTo <- getsSession sxhairGoTo mfail <- if isJust xhairGoTo && xhairGoTo /= xhair then failWith "crosshair position changed" else do modifySession $ \sess -> sess {sxhairGoTo = xhair} goToXhairGoTo leader initialStep run when (isLeft mfail) $ modifySession $ \sess -> sess {sxhairGoTo = Nothing} return mfail | bwatch sb == WSleep -> failSer MoveUnskilledAsleep | otherwise -> failSer MoveUnskilled goToXhairGoTo :: (MonadClient m, MonadClientUI m) => ActorId -> Bool -> Bool -> m (FailOrCmd RequestTimed) goToXhairGoTo leader initialStep run = do b <- getsState $ getActorBody leader mxhairPos <- mxhairToPos case mxhairPos of Nothing -> failWith "crosshair position invalid" Just c -> do running <- getsSession srunning case running of Do n't use running params from previous run or goto - xhair . Just paramOld | not initialStep -> do arena <- getArenaUI runOutcome <- multiActorGoTo arena c paramOld case runOutcome of Left stopMsg -> return $ Left stopMsg Right (finalGoal, dir) -> moveRunHuman leader initialStep finalGoal run False dir _ | c == bpos b -> failWith "position reached" _ -> do let !_A = assert (initialStep || not run) () (bfs, mpath) <- getCacheBfsAndPath leader c xhairMoused <- getsSession sxhairMoused case mpath of _ | xhairMoused && isNothing (accessBfs bfs c) -> failWith "no route to crosshair (press again to go there anyway)" _ | initialStep && adjacent (bpos b) c -> do let dir = towards (bpos b) c moveRunHuman leader initialStep True run False dir Nothing -> failWith "no route to crosshair" Just AndPath{pathList=[]} -> failWith "almost there" Just AndPath{pathList = p1 : _} -> do let finalGoal = p1 == c dir = towards (bpos b) p1 moveRunHuman leader initialStep finalGoal run False dir multiActorGoTo :: (MonadClient m, MonadClientUI m) => LevelId -> Point -> RunParams -> m (FailOrCmd (Bool, Vector)) multiActorGoTo arena c paramOld = case paramOld of RunParams{runMembers = []} -> failWith "selected actors no longer there" RunParams{runMembers = r : rs, runWaiting} -> do onLevel <- getsState $ memActor r arena b <- getsState $ getActorBody r mxhairPos <- mxhairToPos if not onLevel || mxhairPos == Just (bpos b) then do let paramNew = paramOld {runMembers = rs} multiActorGoTo arena c paramNew else do sL <- getState modifyClient $ updateLeader r sL let runMembersNew = rs ++ [r] paramNew = paramOld { runMembers = runMembersNew , runWaiting = 0} (bfs, mpath) <- getCacheBfsAndPath r c xhairMoused <- getsSession sxhairMoused case mpath of _ | xhairMoused && isNothing (accessBfs bfs c) -> failWith "no route to crosshair (press again to go there anyway)" Nothing -> failWith "no route to crosshair" Just AndPath{pathList=[]} -> failWith "almost there" Just AndPath{pathList = p1 : _} -> do let finalGoal = p1 == c dir = towards (bpos b) p1 tgts <- getsState $ posToAids p1 arena case tgts of [] -> do modifySession $ \sess -> sess {srunning = Just paramNew} return $ Right (finalGoal, dir) [target] | target `elem` rs || runWaiting <= length rs -> Let r wait until all others move . it in runWaiting multiActorGoTo arena c paramNew{runWaiting=runWaiting + 1} _ -> runOnceToXhairHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) runOnceToXhairHuman leader = goToXhair leader True True * ContinueToXhair continueToXhairHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) moveItemHuman :: forall m. MonadClientUI m => ActorId -> [CStore] -> CStore -> Maybe Text -> Bool -> m (FailOrCmd RequestTimed) moveItemHuman leader stores destCStore mverb auto = do let !_A = assert (destCStore `notElem` stores) () actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkMoveItem actorCurAndMaxSk > 0 then moveOrSelectItem leader stores destCStore mverb auto else failSer MoveItemUnskilled and @ChooseItemToMove@ , because at least in case of grabbing items , more than one item is chosen , which does n't fit @sitemSel@. Separating moveOrSelectItem :: forall m. MonadClientUI m => ActorId -> [CStore] -> CStore -> Maybe Text -> Bool -> m (FailOrCmd RequestTimed) moveOrSelectItem leader storesRaw destCStore mverb auto = do b <- getsState $ getActorBody leader actorCurAndMaxSk <- getsState $ getActorMaxSkills leader mstash <- getsState $ \s -> gstash $ sfactionD s EM.! bfid b let calmE = calmEnough b actorCurAndMaxSk overStash = mstash == Just (blid b, bpos b) stores = case storesRaw of CEqp : rest@(_ : _) | not calmE -> rest ++ [CEqp] CGround : rest@(_ : _) | overStash -> rest ++ [CGround] _ -> storesRaw itemSel <- getsSession sitemSel case itemSel of _ | stores == [CGround] && overStash -> failWith "you can't loot items from your own stash" Just (_, fromCStore@CEqp, _) | fromCStore /= destCStore && fromCStore `elem` stores && not calmE -> failWith "neither the selected item nor any other can be unequipped" Just (_, fromCStore@CGround, _) | fromCStore /= destCStore && fromCStore `elem` stores && overStash -> failWith "you vainly paw through your own hoard" Just (iid, fromCStore, _) | fromCStore /= destCStore && fromCStore `elem` stores -> do bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of moveOrSelectItem leader stores destCStore mverb auto Just (k, it) -> assert (k > 0) $ do let eqpFree = eqpFreeN b kToPick | destCStore == CEqp = min eqpFree k | otherwise = k if | destCStore == CEqp && not calmE -> failSer ItemNotCalm | destCStore == CGround && overStash -> failSer ItemOverStash | kToPick == 0 -> failWith "no more items can be equipped" | otherwise -> do socK <- pickNumber (not auto) kToPick case socK of Left Nothing -> moveOrSelectItem leader stores destCStore mverb auto Left (Just err) -> return $ Left err Right kChosen -> let is = (fromCStore, [(iid, (kChosen, take kChosen it))]) in Right <$> moveItems leader stores is destCStore _ -> do mis <- selectItemsToMove leader stores destCStore mverb auto case mis of Left err -> return $ Left err Right (fromCStore, [(iid, _)]) | stores /= [CGround] -> do modifySession $ \sess -> sess {sitemSel = Just (iid, fromCStore, False)} moveOrSelectItem leader stores destCStore mverb auto Right is@(fromCStore, _) -> if | fromCStore == CEqp && not calmE -> failSer ItemNotCalm | fromCStore == CGround && overStash -> failSer ItemOverStash | otherwise -> Right <$> moveItems leader stores is destCStore selectItemsToMove :: forall m. MonadClientUI m => ActorId -> [CStore] -> CStore -> Maybe Text -> Bool -> m (FailOrCmd (CStore, [(ItemId, ItemQuant)])) selectItemsToMove leader stores destCStore mverb auto = do let verb = fromMaybe (verbCStore destCStore) mverb actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader mstash <- getsState $ \s -> gstash $ sfactionD s EM.! bfid b lastItemMove <- getsSession slastItemMove This calmE is outdated when one of the items increases max Calm let calmE = calmEnough b actorCurAndMaxSk overStash = mstash == Just (blid b, bpos b) if | destCStore == CEqp && not calmE -> failSer ItemNotCalm | destCStore == CGround && overStash -> failSer ItemOverStash | destCStore == CEqp && eqpOverfull b 1 -> failSer EqpOverfull | otherwise -> do let storesLast = case lastItemMove of Just (lastFrom, lastDest) | lastDest == destCStore && lastFrom `elem` stores -> lastFrom : delete lastFrom stores _ -> stores prompt = "What to" promptEqp = "What consumable to" eqpItemsN body = let n = sum $ map fst $ EM.elems $ beqp body in "(" <> makePhrase [MU.CarWs n "item"] ppItemDialogBody body actorSk cCur = case cCur of MStore CEqp | not $ calmEnough body actorSk -> "distractedly paw at" <+> ppItemDialogModeIn cCur MStore CGround | mstash == Just (blid body, bpos body) -> "greedily fondle" <+> ppItemDialogModeIn cCur _ -> case destCStore of CEqp | not $ calmEnough body actorSk -> "distractedly attempt to" <+> verb <+> ppItemDialogModeFrom cCur CEqp | eqpOverfull body 1 -> "attempt to fit into equipment" <+> ppItemDialogModeFrom cCur CGround | mstash == Just (blid body, bpos body) -> "greedily attempt to" <+> verb <+> ppItemDialogModeFrom cCur CEqp -> verb <+> eqpItemsN body <+> "so far)" <+> ppItemDialogModeFrom cCur _ -> verb <+> ppItemDialogModeFrom cCur <+> if cCur == MStore CEqp then eqpItemsN body <+> "now)" else "" (promptGeneric, psuit) = We prune item list only for eqp , because other stores do n't have it to auto - store things , or equip first using the pruning if destCStore == CEqp then (promptEqp, return $ SuitsSomething $ \_ itemFull _kit -> IA.goesIntoEqp $ aspectRecordFull itemFull) else (prompt, return SuitsEverything) ggi <- getFull leader psuit (\body _ actorSk cCur _ -> prompt <+> ppItemDialogBody body actorSk cCur) (\body _ actorSk cCur _ -> promptGeneric <+> ppItemDialogBody body actorSk cCur) storesLast (not auto) True case ggi of Right (fromCStore, l) -> do modifySession $ \sess -> sess {slastItemMove = Just (fromCStore, destCStore)} return $ Right (fromCStore, l) Left err -> failWith err moveItems :: forall m. MonadClientUI m => ActorId -> [CStore] -> (CStore, [(ItemId, ItemQuant)]) -> CStore -> m RequestTimed moveItems leader stores (fromCStore, l) destCStore = do let !_A = assert (fromCStore /= destCStore && fromCStore `elem` stores) () actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader discoBenefit <- getsClient sdiscoBenefit let calmE = calmEnough b actorCurAndMaxSk ret4 :: [(ItemId, ItemQuant)] -> Int -> m [(ItemId, Int, CStore, CStore)] ret4 [] _ = return [] ret4 ((iid, (k, _)) : rest) oldN = do let !_A = assert (k > 0) () retRec toCStore = do let n = oldN + if toCStore == CEqp then k else 0 l4 <- ret4 rest n return $ (iid, k, fromCStore, toCStore) : l4 if | not $ benInEqp $ discoBenefit EM.! iid -> retRec CStash | eqpOverfull b (oldN + 1) -> do msgAdd MsgActionWarning $ "Warning:" <+> showReqFailure EqpOverfull <> "." retRec CStash | eqpOverfull b (oldN + k) -> do msgAdd MsgActionWarning $ "Warning:" <+> showReqFailure EqpStackFull <> "." retRec CStash | not calmE -> do msgAdd MsgActionWarning $ "Warning:" <+> showReqFailure ItemNotCalm <> "." retRec CStash | otherwise -> retRec CEqp CEqp | eqpOverfull b (oldN + 1) -> do msgAdd MsgPromptItems $ "Failure:" <+> showReqFailure EqpOverfull <> "." return [] CEqp | eqpOverfull b (oldN + k) -> do msgAdd MsgPromptItems $ "Failure:" <+> showReqFailure EqpStackFull <> "." return [] _ -> retRec destCStore l4 <- ret4 l 0 if null l4 then error $ "" `showFailure` (stores, fromCStore, l, destCStore) else return $! ReqMoveItems l4 projectHuman :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed) projectHuman leader = do curChal <- getsClient scurChal actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if | ckeeper curChal -> failSer ProjectFinderKeeper | Ability.getSk Ability.SkProject actorCurAndMaxSk <= 0 -> failSer ProjectUnskilled | otherwise -> do itemSel <- getsSession sitemSel case itemSel of Just (_, COrgan, _) -> failWith "can't fling an organ" Just (iid, fromCStore, _) -> do b <- getsState $ getActorBody leader bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of Nothing -> failWith "no item to fling" Just _kit -> do itemFull <- getsState $ itemToFull iid let i = (fromCStore, (iid, itemFull)) projectItem leader i Nothing -> failWith "no item to fling" projectItem :: (MonadClient m, MonadClientUI m) => ActorId -> (CStore, (ItemId, ItemFull)) -> m (FailOrCmd RequestTimed) projectItem leader (fromCStore, (iid, itemFull)) = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader let calmE = calmEnough b actorCurAndMaxSk if fromCStore == CEqp && not calmE then failSer ItemNotCalm else do mpsuitReq <- psuitReq leader case mpsuitReq of Left err -> failWith err Right psuitReqFun -> case psuitReqFun itemFull of Left reqFail -> failSer reqFail Right (pos, _) -> do Benefit{benFling} <- getsClient $ (EM.! iid) . sdiscoBenefit go <- if benFling >= 0 then displayYesNo ColorFull "The item may be beneficial. Do you really want to fling it?" else return True if go then do sxhair <- getsSession sxhair modifyClient $ updateTarget leader (const sxhair) eps <- getsClient seps return $ Right $ ReqProject pos eps iid fromCStore else do modifySession $ \sess -> sess {sitemSel = Nothing} failWith "never mind" applyHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) applyHuman leader = do actorCurAndMaxSk <- getsState $ getActorMaxSkills leader if Ability.getSk Ability.SkApply failSer ApplyUnskilled else do itemSel <- getsSession sitemSel case itemSel of Just (iid, fromCStore, _) -> do b <- getsState $ getActorBody leader bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of Nothing -> failWith "no item to trigger" Just kit -> do itemFull <- getsState $ itemToFull iid applyItem leader (fromCStore, (iid, (itemFull, kit))) Nothing -> failWith "no item to trigger" applyItem :: MonadClientUI m => ActorId -> (CStore, (ItemId, ItemFullKit)) -> m (FailOrCmd RequestTimed) applyItem leader (fromCStore, (iid, (itemFull, kit))) = do COps{corule} <- getsState scops actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader localTime <- getsState $ getLocalTime (blid b) let skill = Ability.getSk Ability.SkApply actorCurAndMaxSk calmE = calmEnough b actorCurAndMaxSk arItem = aspectRecordFull itemFull if fromCStore == CEqp && not calmE then failSer ItemNotCalm else case permittedApply corule localTime skill calmE (Just fromCStore) itemFull kit of Left reqFail -> failSer reqFail Right _ -> do Benefit{benApply} <- getsClient $ (EM.! iid) . sdiscoBenefit go <- if | IA.checkFlag Ability.Periodic arItem && not (IA.checkFlag Ability.Durable arItem) -> displayYesNo ColorFull "Triggering this periodic item may not produce all its effects (check item description) and moreover, because it's not durable, will destroy it. Are you sure?" | benApply < 0 -> displayYesNo ColorFull "The item appears harmful. Do you really want to trigger it?" | otherwise -> return True if go then return $ Right $ ReqApply iid fromCStore else do modifySession $ \sess -> sess {sitemSel = Nothing} failWith "never mind" * alterDirHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) alterDirHuman leader = pickPoint leader "modify" >>= \case Just p -> alterTileAtPos leader p Nothing -> failWith "never mind" alterTileAtPos :: MonadClientUI m => ActorId -> Point -> m (FailOrCmd RequestTimed) alterTileAtPos leader pos = do sb <- getsState $ getActorBody leader let sxhair = Just $ TPoint TUnknown (blid sb) pos Point xhair to see details with ` ~ ` . setXHairFromGUI sxhair alterCommon leader False pos verifyAlters :: forall m. MonadClientUI m => ActorId -> Bool -> Point -> m (FailOrCmd ()) verifyAlters leader bumping tpos = do COps{cotile, coTileSpeedup} <- getsState scops sb <- getsState $ getActorBody leader arItem <- getsState $ aspectRecordFromIid $ btrunk sb embeds <- getsState $ getEmbedBag (blid sb) tpos lvl <- getLevel $ blid sb getKind <- getsState $ flip getIidKind let embedKindList = if IA.checkFlag Ability.Blast arItem else map (\(iid, kit) -> (getKind iid, (iid, kit))) (EM.assocs embeds) blockedByItem = EM.member tpos (lfloor lvl) tile = lvl `at` tpos feats = TK.tfeature $ okind cotile tile tileActions = mapMaybe (parseTileAction (bproj sb) embedKindList) feats if null tileActions && blockedByItem && not underFeet && Tile.isModifiable coTileSpeedup tile then failSer AlterBlockItem else processTileActions leader bumping tpos tileActions processTileActions :: forall m. MonadClientUI m => ActorId -> Bool -> Point -> [TileAction] -> m (FailOrCmd ()) processTileActions leader bumping tpos tas = do COps{coTileSpeedup} <- getsState scops getKind <- getsState $ flip getIidKind sb <- getsState $ getActorBody leader lvl <- getLevel $ blid sb sar <- getsState $ aspectRecordFromIid $ btrunk sb let leaderIsMist = IA.checkFlag Ability.Blast sar && Dice.infDice (IK.idamage $ getKind $ btrunk sb) <= 0 tileMinSkill = Tile.alterMinSkill coTileSpeedup $ lvl `at` tpos processTA :: Maybe Bool -> [TileAction] -> Bool -> m (FailOrCmd (Maybe (Bool, Bool))) processTA museResult [] bumpFailed = do let useResult = fromMaybe False museResult produce the warning and S - dir also displays the tool info . return $ Right $ if Tile.isSuspect coTileSpeedup (lvl `at` tpos) || useResult && not bumpFailed processTA museResult (ta : rest) bumpFailed = case ta of EmbedAction (iid, _) -> do are activated in the order in tile definition let useResult = fromMaybe False museResult if | leaderIsMist processTA (Just useResult) rest bumpFailed | (not . any IK.isEffEscape) (IK.ieffects $ getKind iid) -> processTA (Just True) rest False | otherwise -> do mfail <- verifyEscape case mfail of Left err -> return $ Left err Right () -> processTA (Just True) rest False ToAction{} -> if fromMaybe True museResult else processTA museResult rest bumpFailed WithAction tools0 _ -> if not bumping || null tools0 then if fromMaybe True museResult then do kitAssG <- getsState $ kitAssocs leader [CGround] kitAssE <- getsState $ kitAssocs leader [CEqp] let kitAss = listToolsToConsume kitAssG kitAssE grps0 = map (\(x, y) -> (False, x, y)) tools0 (_, iidsToApply, grps) = foldl' subtractIidfromGrps (EM.empty, [], grps0) kitAss if null grps then do let hasEffectOrDmg (_, (_, ItemFull{itemKind})) = IK.idamage itemKind /= 0 || any IK.forApplyEffect (IK.ieffects itemKind) mfail <- case filter hasEffectOrDmg iidsToApply of [] -> return $ Right () (store, (_, itemFull)) : _ -> verifyToolEffect (blid sb) store itemFull case mfail of Left err -> return $ Left err mfail <- processTA Nothing tas False case mfail of Left err -> return $ Left err Right Nothing -> return $ Right () Right (Just (useResult, bumpFailed)) -> do let !_A = assert (not useResult || bumpFailed) () blurb <- lookAtPosition tpos (blid sb) mapM_ (uncurry msgAdd) blurb if bumpFailed then do revCmd <- revCmdMap let km = revCmd AlterDir msg = "bumping is not enough to transform this terrain; modify with the '" <> T.pack (K.showKM km) <> "' command instead" if useResult then do merr <- failMsg msg msgAdd MsgPromptAction $ showFailError $ fromJust merr else failWith msg else failWith "unable to activate nor modify at this time" verifyEscape :: MonadClientUI m => m (FailOrCmd ()) verifyEscape = do side <- getsClient sside fact <- getsState $ (EM.! side) . sfactionD if not (FK.fcanEscape $ gkind fact) then failWith "This is the way out, but where would you go in this alien world?" else do (_, total) <- getsState $ calculateTotal side dungeonTotal <- getsState sgold let prompt | dungeonTotal == 0 = "You finally reached your goal. Really leave now?" | total == 0 = "Afraid of the challenge? Leaving so soon and without any treasure? Are you sure?" | total < dungeonTotal = "You've finally found the way out, but you didn't gather all valuables rumoured to be laying around. Really leave already?" | otherwise = "This is the way out and you collected all treasure there is to find. Really leave now?" go <- displayYesNo ColorBW prompt if not go then failWith "here's your chance" else return $ Right () verifyToolEffect :: MonadClientUI m => LevelId -> CStore -> ItemFull -> m (FailOrCmd ()) verifyToolEffect lid store itemFull = do CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui side <- getsClient sside localTime <- getsState $ getLocalTime lid factionD <- getsState sfactionD let (name1, powers) = partItemShort rwidth side factionD localTime itemFull quantSingle objectA = makePhrase [MU.AW name1, powers] prompt = "Do you really want to transform the terrain potentially using" <+> objectA <+> ppCStoreIn store <+> "that may cause substantial side-effects?" objectThe = makePhrase ["the", name1] go <- displayYesNo ColorBW prompt if not go then failWith $ "replace" <+> objectThe <+> "and try again" else return $ Right () alterWithPointerHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) alterWithPointerHuman leader = do COps{corule=RuleContent{rWidthMax, rHeightMax}} <- getsState scops pUI <- getsSession spointer let p = squareToMap $ uiToSquare pUI if insideP (0, 0, rWidthMax - 1, rHeightMax - 1) p then alterTileAtPos leader p else failWith "never mind" | Close nearby open tile ; ask for direction , if there is more than one . closeDirHuman :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed) closeDirHuman leader = do COps{coTileSpeedup} <- getsState scops b <- getsState $ getActorBody leader lvl <- getLevel $ blid b let vPts = vicinityUnsafe $ bpos b openPts = filter (Tile.isClosable coTileSpeedup . at lvl) vPts case openPts of [] -> failSer CloseNothing [o] -> closeTileAtPos leader o _ -> pickPoint leader "close" >>= \case Nothing -> failWith "never mind" Just p -> closeTileAtPos leader p closeTileAtPos :: MonadClientUI m => ActorId -> Point -> m (FailOrCmd RequestTimed) closeTileAtPos leader tpos = do COps{coTileSpeedup} <- getsState scops actorCurAndMaxSk <- getsState $ getActorMaxSkills leader b <- getsState $ getActorBody leader alterable <- getsState $ tileAlterable (blid b) tpos lvl <- getLevel $ blid b let alterSkill = Ability.getSk Ability.SkAlter actorCurAndMaxSk t = lvl `at` tpos isOpen = Tile.isClosable coTileSpeedup t isClosed = Tile.isOpenable coTileSpeedup t case (alterable, isClosed, isOpen) of (False, _, _) -> failSer CloseNothing (True, False, False) -> failSer CloseNonClosable (True, True, False) -> failSer CloseClosed (True, True, True) -> error "TileKind content validation" (True, False, True) -> if | tpos `chessDist` bpos b > 1 -> failSer CloseDistant | alterSkill <= 1 -> failSer AlterUnskilled | EM.member tpos $ lfloor lvl -> failSer AlterBlockItem | occupiedBigLvl tpos lvl || occupiedProjLvl tpos lvl -> failSer AlterBlockActor | otherwise -> do msgAddDone True leader tpos "close" return $ Right (ReqAlter tpos) msgAddDone :: MonadClientUI m => Bool -> ActorId -> Point -> Text -> m () msgAddDone mentionTile leader p verb = do COps{cotile} <- getsState scops b <- getsState $ getActorBody leader lvl <- getLevel $ blid b let tname = TK.tname $ okind cotile $ lvl `at` p s = case T.words tname of [] -> "thing" ("open" : xs) -> T.unwords xs _ -> tname object | mentionTile = "the" <+> s | otherwise = "" v = p `vectorToFrom` bpos b dir | v == Vector 0 0 = "underneath" | otherwise = compassText v msgAdd MsgActionComplete $ "You" <+> verb <+> object <+> dir <> "." pickPoint :: MonadClientUI m => ActorId -> Text -> m (Maybe Point) pickPoint leader verb = do b <- getsState $ getActorBody leader UIOptions{uVi, uLeftHand} <- getsSession sUIOptions let dirKeys = K.dirAllKey uVi uLeftHand keys = K.escKM : K.leftButtonReleaseKM : map (K.KM K.NoModifier) dirKeys msgAdd MsgPromptGeneric $ "Where to" <+> verb <> "? [movement key] [pointer]" slides <- reportToSlideshow [K.escKM] km <- getConfirms ColorFull keys slides case K.key km of K.LeftButtonRelease -> do pUI <- getsSession spointer let p = squareToMap $ uiToSquare pUI return $ Just p _ -> return $ shift (bpos b) <$> K.handleDir dirKeys km helpHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) helpHuman cmdSemInCxtOfKM = do ccui@CCUI{coinput, coscreen=ScreenContent{rwidth, rheight, rintroScreen}} <- getsSession sccui fontSetup@FontSetup{..} <- getFontSetup gameModeId <- getsState sgameModeId modeOv <- describeMode True gameModeId curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut let displayTutorialHints = fromMaybe curTutorial overrideTut modeH = ( "Press SPACE or PGDN to advance or ESC to see the map again." , (modeOv, []) ) keyH = keyHelp ccui fontSetup packIntoScreens :: [[String]] -> [[String]] -> Int -> [[String]] packIntoScreens [] acc _ = [intercalate [""] (reverse acc)] packIntoScreens ([] : ls) [] _ = packIntoScreens ls [] 0 packIntoScreens (l : ls) [] h = assert (h == 0) $ if length l <= rheight - 3 then packIntoScreens ls [l] (length l) else let (screen, rest) = splitAt (rheight - 3) l in screen : packIntoScreens (rest : ls) [] 0 packIntoScreens (l : ls) acc h = The extra @+ 1@ comes from the empty line separating paragraphs , if length l + 1 + h <= rheight - 3 then packIntoScreens ls (l : acc) (length l + 1 + h) else intercalate [""] (reverse acc) : packIntoScreens (l : ls) [] 0 manualScreens = packIntoScreens (snd rintroScreen) [] 0 sideBySide = if isSquareFont monoFont single column , two screens map offsetOverlay $ filter (not . null) [screen1, screen2] two columns , single screen [offsetOverlay screen1 ++ xtranslateOverlay rwidth (offsetOverlay screen2)] listPairs (a : b : rest) = (a, b) : listPairs rest listPairs [a] = [(a, [])] listPairs [] = [] manualOvs = map (EM.singleton monoFont) $ concatMap sideBySide $ listPairs $ map ((emptyAttrLine :) . map stringToAL) manualScreens addMnualHeader ov = ( "Showing PLAYING.md (best viewed in the browser)." , (ov, []) ) manualH = map addMnualHeader manualOvs splitHelp (t, okx) = splitOKX fontSetup True rwidth rheight rwidth (textToAS t) [K.spaceKM, K.returnKM, K.escKM] okx sli = toSlideshow fontSetup displayTutorialHints $ concatMap splitHelp $ modeH : keyH ++ manualH ekm <- displayChoiceScreen "help" ColorFull True sli [K.spaceKM, K.returnKM, K.escKM] case ekm of Left km | km `elem` [K.escKM, K.spaceKM] -> return $ Left Nothing Left km | km == K.returnKM -> do msgAdd MsgPromptGeneric "Press RET when a command help text is selected to invoke the command." return $ Left Nothing Left km -> case km `M.lookup` bcmdMap coinput of Just (_desc, _cats, cmd) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right _slot -> error $ "" `showFailure` ekm hintHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) hintHuman cmdSemInCxtOfKM = do sreportNull <- getsSession sreportNull if sreportNull then do promptMainKeys return $ Left Nothing else helpHuman cmdSemInCxtOfKM dashboardHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) dashboardHuman cmdSemInCxtOfKM = do CCUI{coinput, coscreen=ScreenContent{rwidth, rheight}} <- getsSession sccui fontSetup@FontSetup{..} <- getFontSetup curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut let displayTutorialHints = fromMaybe curTutorial overrideTut offsetCol2 = 3 (ov0, kxs0) = okxsN coinput monoFont propFont offsetCol2 (const False) False CmdDashboard ([], [], []) ([], []) al1 = textToAS "Dashboard" splitHelp (al, okx) = splitOKX fontSetup False rwidth (rheight - 2) rwidth al [K.returnKM, K.escKM] okx sli = toSlideshow fontSetup displayTutorialHints $ splitHelp (al1, (ov0, kxs0)) extraKeys = [K.returnKM, K.escKM] ekm <- displayChoiceScreen "dashboard" ColorFull False sli extraKeys case ekm of Left km -> case km `M.lookup` bcmdMap coinput of _ | km == K.escKM -> weaveJust <$> failWith "never mind" _ | km == K.returnKM -> do msgAdd MsgPromptGeneric "Press RET when a menu name is selected to browse the menu." return $ Left Nothing Just (_desc, _cats, cmd) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right _slot -> error $ "" `showFailure` ekm itemMenuHuman :: MonadClientUI m => ActorId -> (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) itemMenuHuman leader cmdSemInCxtOfKM = do COps{corule} <- getsState scops itemSel <- getsSession sitemSel fontSetup@FontSetup{..} <- getFontSetup case itemSel of Just (iid, fromCStore, _) -> do side <- getsClient sside b <- getsState $ getActorBody leader bUI <- getsSession $ getActorUI leader bag <- getsState $ getBodyStoreBag b fromCStore case iid `EM.lookup` bag of Nothing -> weaveJust <$> failWith "no item to open item menu for" Just kit -> do CCUI{coscreen=ScreenContent{rwidth, rheight}} <- getsSession sccui actorCurAndMaxSk <- getsState $ getActorMaxSkills leader itemFull <- getsState $ itemToFull iid localTime <- getsState $ getLocalTime (blid b) found <- getsState $ findIid leader side iid let !_A = assert (not (null found) || fromCStore == CGround `blame` (iid, leader)) () fAlt (aid, (_, store)) = aid /= leader || store /= fromCStore foundAlt = filter fAlt found markParagraphs = rheight >= 45 meleeSkill = Ability.getSk Ability.SkHurtMelee actorCurAndMaxSk partRawActor aid = getsSession (partActor . getActorUI aid) ppLoc aid store = do parts <- ppContainerWownW partRawActor False (CActor aid store) return $! "[" ++ T.unpack (makePhrase parts) ++ "]" dmode = MStore fromCStore foundTexts <- mapM (\(aid, (_, store)) -> ppLoc aid store) foundAlt (ovLab, ovDesc) <- itemDescOverlays markParagraphs meleeSkill dmode iid kit itemFull rwidth let foundPrefix = textToAS $ if null foundTexts then "" else "The item is also in:" ovPrefix = ytranslateOverlay (length ovDesc) $ offsetOverlay $ splitAttrString rwidth rwidth foundPrefix ystart = length ovDesc + length ovPrefix - 1 xstart = textSize monoFont (Color.spaceAttrW32 : attrLine (snd $ last ovPrefix)) foundKeys = map (K.KM K.NoModifier . K.Fun) starting from 1 ! let ks = zip foundKeys foundTexts width = if isSquareFont monoFont then 2 * rwidth else rwidth (ovFoundRaw, kxsFound) = wrapOKX monoFont ystart xstart width ks ovFound = ovPrefix ++ ovFoundRaw report <- getReportUI True CCUI{coinput} <- getsSession sccui mstash <- getsState $ \s -> gstash $ sfactionD s EM.! side curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut let displayTutorialHints = fromMaybe curTutorial overrideTut calmE = calmEnough b actorCurAndMaxSk greyedOut cmd = not calmE && fromCStore == CEqp || mstash == Just (blid b, bpos b) && fromCStore == CGround || case cmd of ByAimMode AimModeCmd{..} -> greyedOut exploration || greyedOut aiming ComposeIfLocal cmd1 cmd2 -> greyedOut cmd1 || greyedOut cmd2 ComposeUnlessError cmd1 cmd2 -> greyedOut cmd1 || greyedOut cmd2 Compose2ndLocal cmd1 cmd2 -> greyedOut cmd1 || greyedOut cmd2 MoveItem stores destCStore _ _ -> fromCStore `notElem` stores || destCStore == CEqp && (not calmE || eqpOverfull b 1) || destCStore == CGround && mstash == Just (blid b, bpos b) Apply{} -> let skill = Ability.getSk Ability.SkApply actorCurAndMaxSk in not $ fromRight False $ permittedApply corule localTime skill calmE (Just fromCStore) itemFull kit Project{} -> let skill = Ability.getSk Ability.SkProject actorCurAndMaxSk in not $ fromRight False $ permittedProject False skill calmE itemFull _ -> False fmt n k h = " " <> T.justifyLeft n ' ' k <> " " <> h offsetCol2 = 11 keyCaption = fmt offsetCol2 "keys" "command" offset = 1 + maxYofOverlay (ovDesc ++ ovFound) (ov0, kxs0) = xytranslateOKX 0 offset $ okxsN coinput monoFont propFont offsetCol2 greyedOut True CmdItemMenu ([], [], ["", keyCaption]) ([], []) t0 = makeSentence [ MU.SubjectVerbSg (partActor bUI) "choose" , "an item", MU.Text $ ppCStoreIn fromCStore ] alRep = foldr (<+:>) [] $ renderReport True report al1 | null alRep = textToAS t0 | otherwise = alRep ++ stringToAS "\n" ++ textToAS t0 splitHelp (al, okx) = splitOKX fontSetup False rwidth (rheight - 2) rwidth al [K.spaceKM, K.escKM] okx sli = toSlideshow fontSetup displayTutorialHints $ splitHelp ( al1 , ( EM.insertWith (++) squareFont ovLab $ EM.insertWith (++) propFont ovDesc $ EM.insertWith (++) monoFont ovFound ov0 , kxsFound ++ kxs0 )) extraKeys = [K.spaceKM, K.escKM] ++ foundKeys ekm <- displayChoiceScreen "item menu" ColorFull False sli extraKeys case ekm of Left km -> case km `M.lookup` bcmdMap coinput of _ | km == K.escKM -> weaveJust <$> failWith "never mind" _ | km == K.spaceKM -> chooseItemMenuHuman leader cmdSemInCxtOfKM dmode _ | km `elem` foundKeys -> case km of K.KM{key=K.Fun n} -> do let (newAid, (bNew, newCStore)) = foundAlt !! (n - 1) fact <- getsState $ (EM.! side) . sfactionD let banned = bannedPointmanSwitchBetweenLevels fact if blid bNew /= blid b && banned then weaveJust <$> failSer NoChangeDunLeader else do void $ pickLeader False newAid modifySession $ \sess -> sess {sitemSel = Just (iid, newCStore, False)} itemMenuHuman newAid cmdSemInCxtOfKM _ -> error $ "" `showFailure` km Just (_desc, _cats, cmd) -> do modifySession $ \sess -> sess {sitemSel = Just (iid, fromCStore, True)} cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right _slot -> error $ "" `showFailure` ekm Nothing -> weaveJust <$> failWith "no item to open item menu for" * ChooseItemMenu chooseItemMenuHuman :: MonadClientUI m => ActorId -> (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> ItemDialogMode -> m (Either MError ReqUI) chooseItemMenuHuman leader1 cmdSemInCxtOfKM c1 = do res2 <- chooseItemDialogMode leader1 True c1 case res2 of Right leader2 -> itemMenuHuman leader2 cmdSemInCxtOfKM Left err -> return $ Left $ Just err generateMenu :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> FontOverlayMap -> [(Text, HumanCmd, Maybe HumanCmd, Maybe FontOverlayMap)] -> [String] -> String -> m (Either MError ReqUI) generateMenu cmdSemInCxtOfKM blurb kdsRaw gameInfo menuName = do COps{corule} <- getsState scops CCUI{ coinput=InputContent{brevMap} , coscreen=ScreenContent{rheight, rwebAddress} } <- getsSession sccui FontSetup{..} <- getFontSetup let matchKM slot kd@(_, cmd, _, _) = case M.lookup cmd brevMap of Just (km : _) -> (Left km, kd) _ -> (Right slot, kd) kds = zipWith matchKM natSlots kdsRaw let attrCursor = Color.defAttr {Color.bg = Color.HighlightNoneCursor} highAttr ac = ac {Color.acAttr = attrCursor} highW32 = Color.attrCharToW32 . highAttr . Color.attrCharFromW32 markFirst d = markFirstAS $ textToAS d markFirstAS [] = [] markFirstAS (ac : rest) = highW32 ac : rest fmt (ekm, (d, _, _, _)) = (ekm, markFirst d) in map fmt kds generate :: Int -> (KeyOrSlot, AttrString) -> KYX generate y (ekm, binding) = (ekm, (PointUI 0 y, ButtonWidth squareFont (length binding))) okxBindings = ( EM.singleton squareFont $ offsetOverlay $ map (attrStringToAL . snd) bindings , zipWith generate [0..] bindings ) titleLine = rtitle corule ++ " " ++ showVersion (rexeVersion corule) ++ " " titleAndInfo = map stringToAL ([ "" , titleLine ++ "[" ++ rwebAddress ++ "]" , "" ] ++ gameInfo) , ( PointUI (2 * length titleLine) 1 , ButtonWidth squareFont (2 + length rwebAddress) ) ) okxTitle = ( EM.singleton squareFont $ offsetOverlay titleAndInfo , [webButton] ) okx = xytranslateOKX 2 0 $ sideBySideOKX 2 (length titleAndInfo) okxTitle okxBindings prepareBlurb ovs = let introLen = 1 + maxYofFontOverlayMap ovs start0 = max 0 (rheight - introLen - if isSquareFont propFont then 1 else 2) in EM.map (xytranslateOverlay (-2) (start0 - 2)) ovs subtracting 2 from X and Y to negate the indentation in returnDefaultOKS = return (prepareBlurb blurb, []) displayInRightPane ekm = case ekm `lookup` kds of Just (_, _, _, mblurbRight) -> case mblurbRight of Nothing -> returnDefaultOKS Just blurbRight -> return (prepareBlurb blurbRight, []) Nothing | ekm == Left (K.mkChar '@') -> returnDefaultOKS Nothing -> error $ "generateMenu: unexpected key:" `showFailure` ekm keys = [K.leftKM, K.rightKM, K.escKM, K.mkChar '@'] loop = do kmkm <- displayChoiceScreenWithRightPaneKMKM displayInRightPane True menuName ColorFull True (menuToSlideshow okx) keys case kmkm of Left (km@(K.KM {key=K.Left}), ekm) -> case ekm `lookup` kds of Just (_, _, Nothing, _) -> loop Just (_, _, Just cmdReverse, _) -> cmdSemInCxtOfKM km cmdReverse Nothing -> weaveJust <$> failWith "never mind" Left (km@(K.KM {key=K.Right}), ekm) -> case ekm `lookup` kds of Just (_, cmd, _, _) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Left (K.KM {key=K.Char '@'}, _)-> do success <- tryOpenBrowser rwebAddress if success then generateMenu cmdSemInCxtOfKM blurb kdsRaw gameInfo menuName else weaveJust <$> failWith "failed to open web browser" Left (km, _) -> case Left km `lookup` kds of Just (_, cmd, _, _) -> cmdSemInCxtOfKM km cmd Nothing -> weaveJust <$> failWith "never mind" Right slot -> case Right slot `lookup` kds of Just (_, cmd, _, _) -> cmdSemInCxtOfKM K.escKM cmd Nothing -> weaveJust <$> failWith "never mind" loop mainMenuHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) mainMenuHuman cmdSemInCxtOfKM = do CCUI{coscreen=ScreenContent{rintroScreen}} <- getsSession sccui FontSetup{propFont} <- getFontSetup gameMode <- getGameMode curTutorial <- getsSession scurTutorial overrideTut <- getsSession soverrideTut curChal <- getsClient scurChal let offOn b = if b then "on" else "off" kds = [ ("+ setup and start new game>", ChallengeMenu, Nothing, Nothing) , ("@ save and exit to desktop", GameExit, Nothing, Nothing) , ("+ tweak convenience settings>", SettingsMenu, Nothing, Nothing) , ("@ toggle autoplay", AutomateToggle, Nothing, Nothing) , ("@ see command help", Help, Nothing, Nothing) , ("@ switch to dashboard", Dashboard, Nothing, Nothing) , ("^ back to playing", AutomateBack, Nothing, Nothing) ] gameName = MK.mname gameMode displayTutorialHints = fromMaybe curTutorial overrideTut gameInfo = map T.unpack [ "Now playing:" <+> gameName , "" , " with difficulty:" <+> tshow (cdiff curChal) , " cold fish:" <+> offOn (cfish curChal) , " ready goods:" <+> offOn (cgoods curChal) , " lone wolf:" <+> offOn (cwolf curChal) , " finder keeper:" <+> offOn (ckeeper curChal) , " tutorial hints:" <+> offOn displayTutorialHints , "" ] glueLines (l1 : l2 : rest) = if | null l1 -> l1 : glueLines (l2 : rest) | null l2 -> l1 : l2 : glueLines rest | otherwise -> (l1 ++ l2) : glueLines rest glueLines ll = ll backstory | isSquareFont propFont = fst rintroScreen | otherwise = glueLines $ fst rintroScreen backstoryAL = map (stringToAL . dropWhile (== ' ')) backstory blurb = attrLinesToFontMap [(propFont, backstoryAL)] generateMenu cmdSemInCxtOfKM blurb kds gameInfo "main" * MainMenuAutoOn mainMenuAutoOnHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) mainMenuAutoOnHuman cmdSemInCxtOfKM = do modifySession $ \sess -> sess {swasAutomated = True} mainMenuHuman cmdSemInCxtOfKM mainMenuAutoOffHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) mainMenuAutoOffHuman cmdSemInCxtOfKM = do modifySession $ \sess -> sess {swasAutomated = False} mainMenuHuman cmdSemInCxtOfKM settingsMenuHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) settingsMenuHuman cmdSemInCxtOfKM = do CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui UIOptions{uMsgWrapColumn} <- getsSession sUIOptions FontSetup{..} <- getFontSetup markSuspect <- getsClient smarkSuspect markVision <- getsSession smarkVision markSmell <- getsSession smarkSmell noAnim <- getsClient $ fromMaybe False . snoAnim . soptions side <- getsClient sside factDoctrine <- getsState $ gdoctrine . (EM.! side) . sfactionD overrideTut <- getsSession soverrideTut let offOn b = if b then "on" else "off" offOnAll n = case n of 0 -> "none" 1 -> "untried" 2 -> "all" _ -> error $ "" `showFailure` n neverEver n = case n of 0 -> "never" 1 -> "aiming" 2 -> "always" _ -> error $ "" `showFailure` n offOnUnset mb = case mb of Nothing -> "pass" Just b -> if b then "force on" else "force off" tsuspect = "@ mark suspect terrain:" <+> offOnAll markSuspect tvisible = "@ show visible zone:" <+> neverEver markVision tsmell = "@ display smell clues:" <+> offOn markSmell tanim = "@ play animations:" <+> offOn (not noAnim) tdoctrine = "@ squad doctrine:" <+> Ability.nameDoctrine factDoctrine toverride = "@ override tutorial hints:" <+> offOnUnset overrideTut width = if isSquareFont propFont then rwidth `div` 2 else min uMsgWrapColumn (rwidth - 2) textToBlurb t = Just $ attrLinesToFontMap [ ( propFont , splitAttrString width width $ textToAS t ) ] kds = [ ( tsuspect, MarkSuspect 1, Just (MarkSuspect (-1)) , textToBlurb "* mark suspect terrain\nThis setting affects the ongoing and the next games. It determines which suspect terrain is marked in special color on the map: none, untried (not searched nor revealed), all. It correspondingly determines which, if any, suspect tiles are considered for mouse go-to, auto-explore and for the command that marks the nearest unexplored position." ) , ( tvisible, MarkVision 1, Just (MarkVision (-1)) , textToBlurb "* show visible zone\nThis setting affects the ongoing and the next games. It determines the conditions under which the area visible to the party is marked on the map via a gray background: never, when aiming, always." ) , ( tsmell, MarkSmell, Just MarkSmell , textToBlurb "* display smell clues\nThis setting affects the ongoing and the next games. It determines whether the map displays any smell traces (regardless of who left them) detected by a party member that can track via smell (as determined by the smell radius skill; not common among humans)." ) , ( tanim, MarkAnim, Just MarkAnim , textToBlurb "* play animations\nThis setting affects the ongoing and the next games. It determines whether important events, such combat, are highlighted by animations. This overrides the corresponding config file setting." ) , ( tdoctrine, Doctrine, Nothing , textToBlurb "* squad doctrine\nThis setting affects the ongoing game, but does not persist to the next games. It determines the behaviour of henchmen (non-pointman characters) in the party and, in particular, if they are permitted to move autonomously or fire opportunistically (assuming they are able to, usually due to rare equipment). This setting has a poor UI that will be improved in the future." ) , ( toverride, OverrideTut 1, Just (OverrideTut (-1)) , textToBlurb "* override tutorial hints\nThis setting affects the ongoing and the next games. It determines whether tutorial hints are, respectively, not overridden with respect to the default game mode setting, forced to be off, forced to be on. Tutorial hints are rendered as pink messages and can afterwards be re-read from message history." ) , ( "^ back to main menu", MainMenu, Nothing, Just EM.empty ) ] gameInfo = map T.unpack [ "Tweak convenience settings:" , "" ] generateMenu cmdSemInCxtOfKM EM.empty kds gameInfo "settings" challengeMenuHuman :: MonadClientUI m => (K.KM -> HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI) challengeMenuHuman cmdSemInCxtOfKM = do cops <- getsState scops CCUI{coscreen=ScreenContent{rwidth}} <- getsSession sccui UIOptions{uMsgWrapColumn} <- getsSession sUIOptions FontSetup{..} <- getFontSetup svictories <- getsSession svictories snxtScenario <- getsSession snxtScenario nxtChal <- getsClient snxtChal let (gameModeId, gameMode) = nxtGameMode cops snxtScenario victories = case EM.lookup gameModeId svictories of Nothing -> 0 Just cm -> fromMaybe 0 (M.lookup nxtChal cm) star t = if victories > 0 then "*" <> t else t tnextScenario = "@ adventure:" <+> star (MK.mname gameMode) offOn b = if b then "on" else "off" tnextDiff = "@ difficulty level:" <+> tshow (cdiff nxtChal) tnextFish = "@ cold fish (rather hard):" <+> offOn (cfish nxtChal) tnextGoods = "@ ready goods (hard):" <+> offOn (cgoods nxtChal) tnextWolf = "@ lone wolf (very hard):" <+> offOn (cwolf nxtChal) tnextKeeper = "@ finder keeper (hard):" <+> offOn (ckeeper nxtChal) width = if isSquareFont propFont then rwidth `div` 2 else min uMsgWrapColumn (rwidth - 2) widthFull = if isSquareFont propFont then rwidth `div` 2 else rwidth - 2 duplicateEOL '\n' = "\n\n" duplicateEOL c = T.singleton c blurb = Just $ attrLinesToFontMap [ ( propFont , splitAttrString width width $ textFgToAS Color.BrBlack $ T.concatMap duplicateEOL (MK.mdesc gameMode) <> "\n\n" ) , ( propFont , splitAttrString widthFull widthFull $ textToAS $ MK.mrules gameMode <> "\n\n" ) , ( propFont , splitAttrString width width $ textToAS $ T.concatMap duplicateEOL (MK.mreason gameMode) ) ] textToBlurb t = Just $ attrLinesToFontMap [ ( propFont $ textToAS t ) ] kds = [ ( tnextScenario, GameScenarioIncr 1, Just (GameScenarioIncr (-1)) , blurb ) , ( tnextDiff, GameDifficultyIncr 1, Just (GameDifficultyIncr (-1)) , textToBlurb "* difficulty level\nThis determines the difficulty of survival in the next game that's about to be started. Lower numbers result in easier game. In particular, difficulty below 5 multiplies hitpoints of player characters and difficulty over 5 multiplies hitpoints of their enemies. Game score scales with difficulty.") , ( tnextFish, GameFishToggle, Just GameFishToggle , textToBlurb "* cold fish\nThis challenge mode setting will affect the next game that's about to be started. When on, it makes it impossible for player characters to be healed by actors from other factions (this is a significant restriction in the long crawl adventure).") , ( tnextGoods, GameGoodsToggle, Just GameGoodsToggle , textToBlurb "* ready goods\nThis challenge mode setting will affect the next game that's about to be started. When on, it disables crafting for the player, making the selection of equipment, especially melee weapons, very limited, unless the player has the luck to find the rare powerful ready weapons (this applies only if the chosen adventure supports crafting at all).") , ( tnextWolf, GameWolfToggle, Just GameWolfToggle , textToBlurb "* lone wolf\nThis challenge mode setting will affect the next game that's about to be started. When on, it reduces player's starting actors to exactly one, though later on new heroes may join the party. This makes the game very hard in the long run.") , ( tnextKeeper, GameKeeperToggle, Just GameKeeperToggle , textToBlurb "* finder keeper\nThis challenge mode setting will affect the next game that's about to be started. When on, it completely disables flinging projectiles by the player, which affects not only ranged damage dealing, but also throwing of consumables that buff teammates engaged in melee combat, weaken and distract enemies, light dark corners, etc.") , ( "@ start new game", GameRestart, Nothing, blurb ) , ( "^ back to main menu", MainMenu, Nothing, Nothing ) ] gameInfo = map T.unpack [ "Setup and start new game:" , "" ] generateMenu cmdSemInCxtOfKM EM.empty kds gameInfo "challenge" gameDifficultyIncr :: MonadClient m => Int -> m () gameDifficultyIncr delta = do nxtDiff <- getsClient $ cdiff . snxtChal let d | nxtDiff + delta > difficultyBound = 1 | nxtDiff + delta < 1 = difficultyBound | otherwise = nxtDiff + delta modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cdiff = d} } gameFishToggle :: MonadClient m => m () gameFishToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cfish = not (cfish (snxtChal cli))} } gameGoodsToggle :: MonadClient m => m () gameGoodsToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cgoods = not (cgoods (snxtChal cli))} } gameWolfToggle :: MonadClient m => m () gameWolfToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {cwolf = not (cwolf (snxtChal cli))} } * gameKeeperToggle :: MonadClient m => m () gameKeeperToggle = modifyClient $ \cli -> cli {snxtChal = (snxtChal cli) {ckeeper = not (ckeeper (snxtChal cli))} } gameScenarioIncr :: MonadClientUI m => Int -> m () gameScenarioIncr delta = do cops <- getsState scops oldScenario <- getsSession snxtScenario let snxtScenario = oldScenario + delta snxtTutorial = MK.mtutorial $ snd $ nxtGameMode cops snxtScenario modifySession $ \sess -> sess {snxtScenario, snxtTutorial} * GameRestart & GameQuit data ExitStrategy = Restart | Quit gameExitWithHuman :: MonadClientUI m => ExitStrategy -> m (FailOrCmd ReqUI) gameExitWithHuman exitStrategy = do snxtChal <- getsClient snxtChal cops <- getsState scops noConfirmsGame <- isNoConfirmsGame gameMode <- getGameMode snxtScenario <- getsSession snxtScenario let nxtGameName = MK.mname $ snd $ nxtGameMode cops snxtScenario exitReturn x = return $ Right $ ReqUIGameRestart x snxtChal displayExitMessage diff = displayYesNo ColorBW $ diff <+> "progress of the ongoing" <+> MK.mname gameMode <+> "game will be lost! Are you sure?" ifM (if' noConfirmsGame Restart -> "You just requested a new" <+> nxtGameName <+> "game. The " Quit -> "If you quit, the ")) Restart -> let (mainName, _) = T.span (\c -> Char.isAlpha c || c == ' ') nxtGameName in DefsInternal.GroupName $ T.intercalate " " $ take 2 $ T.words mainName Quit -> MK.INSERT_COIN) [ "yea, would be a pity to leave them to die" , "yea, a shame to get your team stranded" ]) >>= failWith) ifM :: Monad m => m Bool -> m b -> m b -> m b ifM b t f = do b' <- b; if b' then t else f if' :: Bool -> p -> p -> p if' b t f = if b then t else f gameDropHuman :: MonadClientUI m => m ReqUI gameDropHuman = do msgAdd MsgPromptGeneric "Interrupt! Trashing the unsaved game. The program exits now." clientPrintUI "Interrupt! Trashing the unsaved game. The program exits now." this is not shown by ANSI frontend , but at least shown by sdl2 one return ReqUIGameDropAndExit gameExitHuman :: Monad m => m ReqUI gameExitHuman = return ReqUIGameSaveAndExit gameSaveHuman :: MonadClientUI m => m ReqUI gameSaveHuman = do msgAdd MsgInnerWorkSpam "Saving game backup." return ReqUIGameSave doctrineHuman :: MonadClientUI m => m (FailOrCmd ReqUI) doctrineHuman = do fid <- getsClient sside fromT <- getsState $ gdoctrine . (EM.! fid) . sfactionD let toT = if fromT == maxBound then minBound else succ fromT go <- displaySpaceEsc ColorFull $ "(Beware, work in progress!)" <+> "Current squad doctrine is '" <> Ability.nameDoctrine fromT <> "'" <+> "(" <> Ability.describeDoctrine fromT <> ")." <+> "Switching doctrine to '" <> Ability.nameDoctrine toT <> "'" <+> "(" <> Ability.describeDoctrine toT <> ")." <+> "This clears targets of all non-pointmen teammates." <+> "New targets will be picked according to new doctrine." if not go then failWith "squad doctrine change canceled" else return $ Right $ ReqUIDoctrine toT automateHuman :: MonadClientUI m => m (FailOrCmd ReqUI) automateHuman = do clearAimMode proceed <- displayYesNo ColorBW "Do you really want to cede control to AI?" if not proceed then failWith "automation canceled" else return $ Right ReqUIAutomate * AutomateToggle automateToggleHuman :: MonadClientUI m => m (FailOrCmd ReqUI) automateToggleHuman = do swasAutomated <- getsSession swasAutomated if swasAutomated then failWith "automation canceled" else automateHuman automateBackHuman :: MonadClientUI m => m (Either MError ReqUI) automateBackHuman = do swasAutomated <- getsSession swasAutomated return $! if swasAutomated then Right ReqUIAutomate else Left Nothing
e77042183fe7b6065368d3447c3a554705efd4a3f291c305545e941b5d3d05d2
angelhof/flumina
configuration.erl
-module(configuration). -export([create/4, create/5, get_mailbox_name_node/1, get_children/1, get_children_mbox_pids/1, get_children_node_names/1, find_node/2, find_children/2, find_children_mbox_pids/2, find_children_node_pids/2, find_children_preds/2, find_children_spec_preds/2, find_descendant_preds/2, find_node_mailbox_pid_pairs/1, find_node_mailbox_father_pid_pairs/1, get_relevant_predicates/2, pretty_print_configuration/2]). -include("type_definitions.hrl"). -include("config.hrl"). %% %% This function creates the configuration %% from a tree specification. %% - It spawns and creates the nodes %% - It initializes the router %% -spec create(temp_setup_tree(), dependencies(), mailbox(), impl_tags()) -> configuration(). create(Tree, Dependencies, OutputPid, ImplTags) -> Options = conf_gen:default_options(), create(Tree, Dependencies, Options, OutputPid, ImplTags). -spec create(temp_setup_tree(), dependencies(), conf_gen_options_rec(), mailbox(), impl_tags()) -> configuration(). create(Tree, Dependencies, OptionsRec, OutputPid, ImplTags) -> %% Register this node as the master node true = register(master, self()), %% Spawns the nodes NameSeed = make_name_seed(), {PidsTree, _NewNameSeed} = spawn_nodes(Tree, NameSeed, OptionsRec, Dependencies, OutputPid, 0, ImplTags), %% Create the configuration tree ConfTree = prepare_configuration_tree(PidsTree, Tree), io:format("Configuration:~n~p~n", [ConfTree]), %% Send the configuration tree to all nodes' mailboxes send_conf_tree(ConfTree, PidsTree), ConfTree. %% Spawns the nodes based on the tree configuration -spec spawn_nodes(temp_setup_tree(), name_seed(), conf_gen_options_rec(), dependencies(), mailbox(), integer(), impl_tags()) -> {pid_tree(), name_seed()}. spawn_nodes({State, Node, {_SpecPred, Pred}, Funs, Children}, NameSeed, OptionsRec, Dependencies, OutputPid, Depth, ImplTags) -> {ChildrenPidTrees, NewNameSeed} = lists:foldr( fun(C, {AccTrees, NameSeed0}) -> {CTree, NameSeed1} = spawn_nodes(C, NameSeed0, OptionsRec, Dependencies, OutputPid, Depth + 1, ImplTags), {[CTree|AccTrees], NameSeed1} end, {[], NameSeed}, Children), _ChildrenPids = [MP || {{_NP, MP}, _} <- ChildrenPidTrees], {NodeName, AlmostFinalNameSeed} = gen_proc_name(NewNameSeed), {MailboxName, FinalNameSeed} = gen_proc_name(AlmostFinalNameSeed), {NodePid, NodeAndMailboxNames} = node:init(State, {NodeName, MailboxName, Node}, Pred, Funs, OptionsRec, Dependencies, OutputPid, Depth, ImplTags), {{{NodePid, NodeAndMailboxNames}, ChildrenPidTrees}, FinalNameSeed}. -spec make_name_seed() -> name_seed(). make_name_seed() -> make_name_seed(0). -spec make_name_seed(name_seed()) -> name_seed(). make_name_seed(0) -> 0. -spec gen_proc_name(name_seed()) -> {atom(), name_seed()}. gen_proc_name(Seed) -> {list_to_atom("proc_" ++ integer_to_list(Seed)), Seed + 1}. %% Prepares the router tree -spec prepare_configuration_tree(pid_tree(), temp_setup_tree()) -> configuration(). prepare_configuration_tree({{NodePid, {NodeName, MboxName, Node}}, ChildrenPids}, {_State, Node, {SpecPred, Pred}, _Funs, Children}) -> ChildrenTrees = [prepare_configuration_tree(P, N) || {P, N} <- lists:zip(ChildrenPids, Children)], {node, NodePid, {NodeName, Node}, {MboxName, Node}, {SpecPred, Pred}, ChildrenTrees}. Sends the conf tree to all children in a Pid tree -spec send_conf_tree(configuration(), pid_tree()) -> ok. send_conf_tree(ConfTree, {{_NodePid, {_NodeName, MailboxName, Node}}, ChildrenPids}) -> {MailboxName, Node} ! {configuration, ConfTree}, [send_conf_tree(ConfTree, CP) || CP <- ChildrenPids], ok. %% %% Functions to use the configuration tree %% WARNING: They are implemented in a naive way %% searching again and again top down %% in the tree. %% %% %% Getters %% -spec get_mailbox_name_node(configuration()) -> mailbox(). get_mailbox_name_node({node, _Pid, _NNN, MboxNameNode, _Preds, _Children}) -> MboxNameNode. %% This function returns the children of some node in the pid tree -spec get_children(configuration()) -> [configuration()]. get_children({node, _Pid, _NNN, _MboxNN, _Preds, Children}) -> Children. %% This function returns the pids of the children nodes of a node in the tree -spec get_children_mbox_pids(configuration()) -> [mailbox()]. get_children_mbox_pids(ConfNode) -> [MPNodeName || {node, _, _NNN, MPNodeName, _, _} <- get_children(ConfNode)]. %% This function returns the names and nodes of the children nodes of a node in the tree -spec get_children_node_names(configuration()) -> [mailbox()]. get_children_node_names(ConfNode) -> [NodeNameNode || {node, _, NodeNameNode, _MPNodeName, _, _} <- get_children(ConfNode)]. %% This function finds a node in the configuration tree -spec find_node(pid(), configuration()) -> configuration(). find_node(Pid, ConfTree) -> [Node] = find_node0(Pid, ConfTree), Node. -spec find_node0(pid(), configuration()) -> [configuration()]. find_node0(Pid, {node, Pid, _NNN, _MboxNN, _Preds, _Children} = Node) -> [Node]; find_node0(Pid, {node, _Pid, _NNN, _MboxNN, _Preds, Children}) -> lists:flatten([find_node0(Pid, CN) || CN <- Children]). %% This function returns the children of some node in the pid tree -spec find_children(pid(), configuration()) -> [configuration()]. find_children(Pid, ConfTree) -> ConfNode = find_node(Pid, ConfTree), get_children(ConfNode). %% This function returns the pids of the children nodes of a node in the tree -spec find_children_mbox_pids(pid(), configuration()) -> [mailbox()]. find_children_mbox_pids(Pid, ConfTree) -> ConfNode = find_node(Pid, ConfTree), get_children_mbox_pids(ConfNode). -spec find_children_node_pids(pid(), configuration()) -> [pid()]. find_children_node_pids(Pid, ConfTree) -> [NPid || {node, NPid, _NNN, _, _, _} <- find_children(Pid, ConfTree)]. %% This function returns the predicates of the pids of the children nodes -spec find_children_preds(pid(), configuration()) -> [impl_message_predicate()]. find_children_preds(Pid, ConfTree) -> [ImplPred || {node, _, _, _, {_,ImplPred}, _} <- find_children(Pid, ConfTree)]. -spec find_children_spec_preds(pid(), configuration()) -> [message_predicate()]. find_children_spec_preds(Pid, ConfTree) -> [SpecPred || {node, _, _, _, {SpecPred,_}, _} <- find_children(Pid, ConfTree)]. %% This function returns the predicates of the pids of all the descendant nodes -spec find_descendant_preds(pid(), configuration()) -> [impl_message_predicate()]. find_descendant_preds(Pid, ConfTree) -> ChildrenDescendants = lists:flatten( [find_descendant_preds(CPid, ConfTree) || CPid <- find_children_node_pids(Pid, ConfTree)]), ChildrenPreds = find_children_preds(Pid, ConfTree), ChildrenPreds ++ ChildrenDescendants. %% Returns a list with all the pairs of node and mailbox pids -spec find_node_mailbox_pid_pairs(configuration()) -> [{pid(), mailbox()}]. find_node_mailbox_pid_pairs({node, NPid, _NNN, MboxNodeName, _Pred, Children}) -> ChildrenPairs = lists:flatten([find_node_mailbox_pid_pairs(C) || C <- Children]), [{NPid, MboxNodeName}|ChildrenPairs]. -spec union_children_preds([configuration()]) -> impl_message_predicate(). union_children_preds(Children) -> fun(Msg) -> lists:any( fun({node, _N, _NNN, _MNN, {_SP, Pred}, _C}) -> Pred(Msg) end, Children) end. -spec is_acc({'acc' | 'rest', message_predicate()}) -> boolean(). is_acc({acc, _}) -> true; is_acc(_) -> false. -spec get_relevant_predicates(pid(), configuration()) -> {'ok', impl_message_predicate()}. get_relevant_predicates(Attachee, ConfTree) -> [{acc, RelevantPred}] = lists:filter(fun is_acc/1, get_relevant_predicates0(Attachee, ConfTree)), {ok, RelevantPred}. -spec get_relevant_predicates0(pid(), configuration()) -> [{'acc' | 'rest', impl_message_predicate()}]. get_relevant_predicates0(Attachee, {node, Attachee, _NNN, _MNN, {_SpecPred, Pred}, Children}) -> ChildrenPred = union_children_preds(Children), ReturnPred = fun(Msg) -> Pred(Msg) andalso not ChildrenPred(Msg) end, [{acc, ReturnPred}, {rest, Pred}]; get_relevant_predicates0(Attachee, {node, _NotAttachee, _NNN, _MNN, {_SpecPrec, Pred}, Children}) -> ChildrenPredicates = lists:flatten([get_relevant_predicates0(Attachee, C) || C <- Children]), case lists:partition(fun(C) -> is_acc(C) end, ChildrenPredicates) of {[], _} -> No child matches the Attachee pid in this subtree [{rest, Pred}]; {[{acc, ChildPred}], Rest} -> One child matches pid ReturnPred = fun(Msg) -> %% My child's pred, or my predicate without the other children predicates ChildPred(Msg) orelse (Pred(Msg) andalso not lists:any(fun({rest, Pr}) -> Pr(Msg) end, Rest)) end, [{acc, ReturnPred}, {rest, Pred}] end. %% It returns the pairs of mailbox and father ids -spec find_node_mailbox_father_pid_pairs(configuration()) -> {{mailbox(), 'root'}, [{mailbox(), mailbox()}]}. find_node_mailbox_father_pid_pairs({node, _NPid, NodeNameNode, MboxNameNode, _Preds, Children}) -> ChildrenPairs = lists:map( fun(C) -> {Root, Rest} = find_node_mailbox_father_pid_pairs(C), [Root|Rest] end, Children), FlatChildrenPairs = lists:flatten(ChildrenPairs), {{MboxNameNode, root}, [add_father_if_undef(ChildPair, NodeNameNode) || ChildPair <- FlatChildrenPairs]}. -spec add_father_if_undef({mailbox(), mailbox() | 'root'}, mailbox()) -> {mailbox(), mailbox()}. add_father_if_undef({ChildMPid, root}, Father) -> {ChildMPid, Father}; add_father_if_undef(ChildPair, _Father) -> ChildPair. %% Pretty Print configuration tree -spec pretty_print_configuration([tag()], configuration()) -> 'ok'. pretty_print_configuration(Tags, Configuration) -> pretty_print_configuration(Tags, Configuration, 0). -spec pretty_print_configuration([tag()], configuration(), integer()) -> 'ok'. pretty_print_configuration(SpecTags, {node, _NPid, _NNN, _MNN, {TagPred, _MsgPred}, Children}, Indent) -> RelevantTags = [Tag || Tag <- SpecTags, TagPred(Tag)], IndentString = lists:flatten(lists:duplicate(Indent, " ")), io:format("~s|-~p~n", [IndentString, RelevantTags]), lists:foreach( fun(Child) -> pretty_print_configuration(SpecTags, Child, Indent+1) end, Children). %% lists:duplicate(5, xx).
null
https://raw.githubusercontent.com/angelhof/flumina/9602454b845cddf8e3dff8c54089c7f970ee08e1/src/configuration.erl
erlang
This function creates the configuration from a tree specification. - It spawns and creates the nodes - It initializes the router Register this node as the master node Spawns the nodes Create the configuration tree Send the configuration tree to all nodes' mailboxes Spawns the nodes based on the tree configuration Prepares the router tree Functions to use the configuration tree WARNING: They are implemented in a naive way searching again and again top down in the tree. Getters This function returns the children of some node in the pid tree This function returns the pids of the children nodes of a node in the tree This function returns the names and nodes of the children nodes of a node in the tree This function finds a node in the configuration tree This function returns the children of some node in the pid tree This function returns the pids of the children nodes of a node in the tree This function returns the predicates of the pids of the children nodes This function returns the predicates of the pids of all the descendant nodes Returns a list with all the pairs of node and mailbox pids My child's pred, or my predicate without the other children predicates It returns the pairs of mailbox and father ids Pretty Print configuration tree lists:duplicate(5, xx).
-module(configuration). -export([create/4, create/5, get_mailbox_name_node/1, get_children/1, get_children_mbox_pids/1, get_children_node_names/1, find_node/2, find_children/2, find_children_mbox_pids/2, find_children_node_pids/2, find_children_preds/2, find_children_spec_preds/2, find_descendant_preds/2, find_node_mailbox_pid_pairs/1, find_node_mailbox_father_pid_pairs/1, get_relevant_predicates/2, pretty_print_configuration/2]). -include("type_definitions.hrl"). -include("config.hrl"). -spec create(temp_setup_tree(), dependencies(), mailbox(), impl_tags()) -> configuration(). create(Tree, Dependencies, OutputPid, ImplTags) -> Options = conf_gen:default_options(), create(Tree, Dependencies, Options, OutputPid, ImplTags). -spec create(temp_setup_tree(), dependencies(), conf_gen_options_rec(), mailbox(), impl_tags()) -> configuration(). create(Tree, Dependencies, OptionsRec, OutputPid, ImplTags) -> true = register(master, self()), NameSeed = make_name_seed(), {PidsTree, _NewNameSeed} = spawn_nodes(Tree, NameSeed, OptionsRec, Dependencies, OutputPid, 0, ImplTags), ConfTree = prepare_configuration_tree(PidsTree, Tree), io:format("Configuration:~n~p~n", [ConfTree]), send_conf_tree(ConfTree, PidsTree), ConfTree. -spec spawn_nodes(temp_setup_tree(), name_seed(), conf_gen_options_rec(), dependencies(), mailbox(), integer(), impl_tags()) -> {pid_tree(), name_seed()}. spawn_nodes({State, Node, {_SpecPred, Pred}, Funs, Children}, NameSeed, OptionsRec, Dependencies, OutputPid, Depth, ImplTags) -> {ChildrenPidTrees, NewNameSeed} = lists:foldr( fun(C, {AccTrees, NameSeed0}) -> {CTree, NameSeed1} = spawn_nodes(C, NameSeed0, OptionsRec, Dependencies, OutputPid, Depth + 1, ImplTags), {[CTree|AccTrees], NameSeed1} end, {[], NameSeed}, Children), _ChildrenPids = [MP || {{_NP, MP}, _} <- ChildrenPidTrees], {NodeName, AlmostFinalNameSeed} = gen_proc_name(NewNameSeed), {MailboxName, FinalNameSeed} = gen_proc_name(AlmostFinalNameSeed), {NodePid, NodeAndMailboxNames} = node:init(State, {NodeName, MailboxName, Node}, Pred, Funs, OptionsRec, Dependencies, OutputPid, Depth, ImplTags), {{{NodePid, NodeAndMailboxNames}, ChildrenPidTrees}, FinalNameSeed}. -spec make_name_seed() -> name_seed(). make_name_seed() -> make_name_seed(0). -spec make_name_seed(name_seed()) -> name_seed(). make_name_seed(0) -> 0. -spec gen_proc_name(name_seed()) -> {atom(), name_seed()}. gen_proc_name(Seed) -> {list_to_atom("proc_" ++ integer_to_list(Seed)), Seed + 1}. -spec prepare_configuration_tree(pid_tree(), temp_setup_tree()) -> configuration(). prepare_configuration_tree({{NodePid, {NodeName, MboxName, Node}}, ChildrenPids}, {_State, Node, {SpecPred, Pred}, _Funs, Children}) -> ChildrenTrees = [prepare_configuration_tree(P, N) || {P, N} <- lists:zip(ChildrenPids, Children)], {node, NodePid, {NodeName, Node}, {MboxName, Node}, {SpecPred, Pred}, ChildrenTrees}. Sends the conf tree to all children in a Pid tree -spec send_conf_tree(configuration(), pid_tree()) -> ok. send_conf_tree(ConfTree, {{_NodePid, {_NodeName, MailboxName, Node}}, ChildrenPids}) -> {MailboxName, Node} ! {configuration, ConfTree}, [send_conf_tree(ConfTree, CP) || CP <- ChildrenPids], ok. -spec get_mailbox_name_node(configuration()) -> mailbox(). get_mailbox_name_node({node, _Pid, _NNN, MboxNameNode, _Preds, _Children}) -> MboxNameNode. -spec get_children(configuration()) -> [configuration()]. get_children({node, _Pid, _NNN, _MboxNN, _Preds, Children}) -> Children. -spec get_children_mbox_pids(configuration()) -> [mailbox()]. get_children_mbox_pids(ConfNode) -> [MPNodeName || {node, _, _NNN, MPNodeName, _, _} <- get_children(ConfNode)]. -spec get_children_node_names(configuration()) -> [mailbox()]. get_children_node_names(ConfNode) -> [NodeNameNode || {node, _, NodeNameNode, _MPNodeName, _, _} <- get_children(ConfNode)]. -spec find_node(pid(), configuration()) -> configuration(). find_node(Pid, ConfTree) -> [Node] = find_node0(Pid, ConfTree), Node. -spec find_node0(pid(), configuration()) -> [configuration()]. find_node0(Pid, {node, Pid, _NNN, _MboxNN, _Preds, _Children} = Node) -> [Node]; find_node0(Pid, {node, _Pid, _NNN, _MboxNN, _Preds, Children}) -> lists:flatten([find_node0(Pid, CN) || CN <- Children]). -spec find_children(pid(), configuration()) -> [configuration()]. find_children(Pid, ConfTree) -> ConfNode = find_node(Pid, ConfTree), get_children(ConfNode). -spec find_children_mbox_pids(pid(), configuration()) -> [mailbox()]. find_children_mbox_pids(Pid, ConfTree) -> ConfNode = find_node(Pid, ConfTree), get_children_mbox_pids(ConfNode). -spec find_children_node_pids(pid(), configuration()) -> [pid()]. find_children_node_pids(Pid, ConfTree) -> [NPid || {node, NPid, _NNN, _, _, _} <- find_children(Pid, ConfTree)]. -spec find_children_preds(pid(), configuration()) -> [impl_message_predicate()]. find_children_preds(Pid, ConfTree) -> [ImplPred || {node, _, _, _, {_,ImplPred}, _} <- find_children(Pid, ConfTree)]. -spec find_children_spec_preds(pid(), configuration()) -> [message_predicate()]. find_children_spec_preds(Pid, ConfTree) -> [SpecPred || {node, _, _, _, {SpecPred,_}, _} <- find_children(Pid, ConfTree)]. -spec find_descendant_preds(pid(), configuration()) -> [impl_message_predicate()]. find_descendant_preds(Pid, ConfTree) -> ChildrenDescendants = lists:flatten( [find_descendant_preds(CPid, ConfTree) || CPid <- find_children_node_pids(Pid, ConfTree)]), ChildrenPreds = find_children_preds(Pid, ConfTree), ChildrenPreds ++ ChildrenDescendants. -spec find_node_mailbox_pid_pairs(configuration()) -> [{pid(), mailbox()}]. find_node_mailbox_pid_pairs({node, NPid, _NNN, MboxNodeName, _Pred, Children}) -> ChildrenPairs = lists:flatten([find_node_mailbox_pid_pairs(C) || C <- Children]), [{NPid, MboxNodeName}|ChildrenPairs]. -spec union_children_preds([configuration()]) -> impl_message_predicate(). union_children_preds(Children) -> fun(Msg) -> lists:any( fun({node, _N, _NNN, _MNN, {_SP, Pred}, _C}) -> Pred(Msg) end, Children) end. -spec is_acc({'acc' | 'rest', message_predicate()}) -> boolean(). is_acc({acc, _}) -> true; is_acc(_) -> false. -spec get_relevant_predicates(pid(), configuration()) -> {'ok', impl_message_predicate()}. get_relevant_predicates(Attachee, ConfTree) -> [{acc, RelevantPred}] = lists:filter(fun is_acc/1, get_relevant_predicates0(Attachee, ConfTree)), {ok, RelevantPred}. -spec get_relevant_predicates0(pid(), configuration()) -> [{'acc' | 'rest', impl_message_predicate()}]. get_relevant_predicates0(Attachee, {node, Attachee, _NNN, _MNN, {_SpecPred, Pred}, Children}) -> ChildrenPred = union_children_preds(Children), ReturnPred = fun(Msg) -> Pred(Msg) andalso not ChildrenPred(Msg) end, [{acc, ReturnPred}, {rest, Pred}]; get_relevant_predicates0(Attachee, {node, _NotAttachee, _NNN, _MNN, {_SpecPrec, Pred}, Children}) -> ChildrenPredicates = lists:flatten([get_relevant_predicates0(Attachee, C) || C <- Children]), case lists:partition(fun(C) -> is_acc(C) end, ChildrenPredicates) of {[], _} -> No child matches the Attachee pid in this subtree [{rest, Pred}]; {[{acc, ChildPred}], Rest} -> One child matches pid ReturnPred = fun(Msg) -> ChildPred(Msg) orelse (Pred(Msg) andalso not lists:any(fun({rest, Pr}) -> Pr(Msg) end, Rest)) end, [{acc, ReturnPred}, {rest, Pred}] end. -spec find_node_mailbox_father_pid_pairs(configuration()) -> {{mailbox(), 'root'}, [{mailbox(), mailbox()}]}. find_node_mailbox_father_pid_pairs({node, _NPid, NodeNameNode, MboxNameNode, _Preds, Children}) -> ChildrenPairs = lists:map( fun(C) -> {Root, Rest} = find_node_mailbox_father_pid_pairs(C), [Root|Rest] end, Children), FlatChildrenPairs = lists:flatten(ChildrenPairs), {{MboxNameNode, root}, [add_father_if_undef(ChildPair, NodeNameNode) || ChildPair <- FlatChildrenPairs]}. -spec add_father_if_undef({mailbox(), mailbox() | 'root'}, mailbox()) -> {mailbox(), mailbox()}. add_father_if_undef({ChildMPid, root}, Father) -> {ChildMPid, Father}; add_father_if_undef(ChildPair, _Father) -> ChildPair. -spec pretty_print_configuration([tag()], configuration()) -> 'ok'. pretty_print_configuration(Tags, Configuration) -> pretty_print_configuration(Tags, Configuration, 0). -spec pretty_print_configuration([tag()], configuration(), integer()) -> 'ok'. pretty_print_configuration(SpecTags, {node, _NPid, _NNN, _MNN, {TagPred, _MsgPred}, Children}, Indent) -> RelevantTags = [Tag || Tag <- SpecTags, TagPred(Tag)], IndentString = lists:flatten(lists:duplicate(Indent, " ")), io:format("~s|-~p~n", [IndentString, RelevantTags]), lists:foreach( fun(Child) -> pretty_print_configuration(SpecTags, Child, Indent+1) end, Children).
38da7710ae90af9e2202dff6bd3f1f96f5f668bafce4aaab251fff74ab1fba6d
astrada/ocaml-extjs
ext_Loader.mli
* Ext . Loader is the heart of the new dynamic depende ... { % < p><a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . is the heart of the new dynamic dependency loading capability in Ext JS 4 + . It is most commonly used via the < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > shorthand . < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . Loader</a > supports both asynchronous and synchronous loading approaches , and leverage their advantages for the best development flow . We 'll discuss about the pros and cons of each approach:</p > < h1 > Asynchronous Loading</h1 > < ul > < li><p > Advantages:</p > < ul > < li > Cross - domain</li > < li > No web server needed : you can run the application via the file system protocol ( i.e : < code > file / to / your / index .html</code>)</li > < li > Best possible debugging experience : error messages come with the exact file name and line number</li > < /ul > < /li > < li><p > Disadvantages:</p > < ul > < li > Dependencies need to be specified before - hand</li > < /ul > < /li > < /ul > < h3 > Method 1 : Explicitly include what you need:</h3 > < pre><code>// Syntax < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>(\{String / Array\ } expressions ) ; // Example : Single alias < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('widget.window ' ) ; // Example : Single class name < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ) ; // Example : Multiple aliases / class names mix < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>(['widget.window ' , ' layout.border ' , ' < a href="#!/api / Ext.data . Connection " rel="Ext.data . Connection " class="docClass">Ext.data . Connection</a > ' ] ) ; // Wildcards < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>(['widget . * ' , ' layout . * ' , ' Ext.data . * ' ] ) ; < /code></pre > < h3 > Method 2 : Explicitly exclude what you do n't need:</h3 > < pre><code>// Syntax : Note that it must be in this chaining format . < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>(\{String / Array\ } expressions ) .require(\{String / Array\ } expressions ) ; // Include everything except Ext.data . * < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('Ext.data.*').require ( ' * ' ) ; // Include all widgets except widget.checkbox * , // which will match widget.checkbox , widget.checkboxfield , widget.checkboxgroup , etc . < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('widget.checkbox*').require('widget . * ' ) ; < /code></pre > < h1 > Synchronous Loading on Demand</h1 > < ul > < li><p > Advantages:</p > < ul > < li > There 's no need to specify dependencies before - hand , which is always the convenience of including ext-all.js before</li > < /ul > < /li > < li><p > Disadvantages:</p > < ul > < li > Not as good debugging experience since file name wo n't be shown ( except in Firebug at the moment)</li > < li > Must be from the same domain due to XHR restriction</li > < li > Need a web server , same reason as above</li > < /ul > < /li > < /ul > < p > There 's one simple rule to follow : Instantiate everything with < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a > instead of the < code > new</code > < pre><code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('widget.window ' , \ { ... \ } ) ; // Instead of new < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a>(\{ ... \ } ) ; < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' , \{\ } ) ; // Same as above , using full class name instead of alias < a href="#!/api / Ext - method - widget " rel="Ext - method - widget " class="docClass">Ext.widget</a>('window ' , \{\ } ) ; // Same as above , all you need is the traditional ` xtype ` < /code></pre > < p > Behind the scene , < a href="#!/api / Ext . ClassManager " rel="Ext . ClassManager " class="docClass">Ext . will automatically check whether the given class name / alias has already existed on the page . If it 's not , < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . will immediately switch itself to synchronous mode and automatic load the given class and all its dependencies.</p > < h1 > Hybrid Loading - The Best of Both Worlds</h1 > < p > It has all the advantages combined from asynchronous and synchronous loading . The development flow is simple:</p > < h3 > Step 1 : Start writing your application using synchronous approach.</h3 > < p><a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . will automatically fetch all dependencies on demand as they 're needed during run - time . For example:</p > < pre><code><a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function()\ { var window = < a href="#!/api / Ext - method - widget " rel="Ext - method - widget " class="docClass">Ext.widget</a>('window ' , \ { width : 500 , height : 300 , layout : \ { type : ' border ' , padding : 5 \ } , title : ' Hello Dialog ' , items : [ \ { title : ' Navigation ' , collapsible : true , region : ' west ' , width : 200 , html : ' Hello ' , split : true \ } , \ { title : ' TabPanel ' , region : ' center ' \ } ] \ } ) ; window.show ( ) ; \ } ) < /code></pre > < h3 > Step 2 : Along the way , when you need better debugging ability , watch the console for warnings like these:</h3 > < pre><code>[<a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . ] Synchronously loading ' < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ; consider adding < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ) before your application 's code ClassManager.js:432 [ < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . ] Synchronously loading ' < a href="#!/api / Ext.layout.container . Border " . Border " class="docClass">Ext.layout.container . > ' ; consider adding < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.layout.container . Border " . Border " class="docClass">Ext.layout.container . > ' ) before your application 's code < /code></pre > < p > Simply copy and paste the suggested code above < code><a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a></code > , i.e:</p > < pre><code><a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ) ; < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.layout.container . Border " . Border " class="docClass">Ext.layout.container . > ' ) ; < a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " > ( ... ) ; < /code></pre > < p > Everything should now load via asynchronous mode.</p > < h1 > Deployment</h1 > < p > It 's important to note that dynamic loading should only be used during development on your local machines . During production , all dependencies should be combined into one single JavaScript file . < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . makes the whole process of transitioning from / to between development / maintenance and production as easy as possible . Internally < a href="#!/api / Ext . Loader - property - history " rel="Ext . Loader - property - history " class="docClass">Ext . Loader.history</a > maintains the list of all dependencies your application needs in the exact loading sequence . It 's as simple as concatenating all files in this array into one , then include it on top of your application.</p > < p > This process will be automated with Sencha Command , to be released and documented towards Ext JS 4 Final.</p > % } {% <p><a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used via the <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a> shorthand. <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> supports both asynchronous and synchronous loading approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:</p> <h1>Asynchronous Loading</h1> <ul> <li><p>Advantages:</p> <ul> <li>Cross-domain</li> <li>No web server needed: you can run the application via the file system protocol (i.e: <code>file .html</code>)</li> <li>Best possible debugging experience: error messages come with the exact file name and line number</li> </ul> </li> <li><p>Disadvantages:</p> <ul> <li>Dependencies need to be specified before-hand</li> </ul> </li> </ul> <h3>Method 1: Explicitly include what you need:</h3> <pre><code>// Syntax <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(\{String/Array\} expressions); // Example: Single alias <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('widget.window'); // Example: Single class name <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>'); // Example: Multiple aliases / class names mix <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(['widget.window', 'layout.border', '<a href="#!/api/Ext.data.Connection" rel="Ext.data.Connection" class="docClass">Ext.data.Connection</a>']); // Wildcards <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(['widget.*', 'layout.*', 'Ext.data.*']); </code></pre> <h3>Method 2: Explicitly exclude what you don't need:</h3> <pre><code>// Syntax: Note that it must be in this chaining format. <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>(\{String/Array\} expressions) .require(\{String/Array\} expressions); // Include everything except Ext.data.* <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('Ext.data.*').require('*'); // Include all widgets except widget.checkbox*, // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc. <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('widget.checkbox*').require('widget.*'); </code></pre> <h1>Synchronous Loading on Demand</h1> <ul> <li><p>Advantages:</p> <ul> <li>There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js before</li> </ul> </li> <li><p>Disadvantages:</p> <ul> <li>Not as good debugging experience since file name won't be shown (except in Firebug at the moment)</li> <li>Must be from the same domain due to XHR restriction</li> <li>Need a web server, same reason as above</li> </ul> </li> </ul> <p>There's one simple rule to follow: Instantiate everything with <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a> instead of the <code>new</code> keyword</p> <pre><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('widget.window', \{ ... \}); // Instead of new <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>(\{...\}); <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>', \{\}); // Same as above, using full class name instead of alias <a href="#!/api/Ext-method-widget" rel="Ext-method-widget" class="docClass">Ext.widget</a>('window', \{\}); // Same as above, all you need is the traditional `xtype` </code></pre> <p>Behind the scene, <a href="#!/api/Ext.ClassManager" rel="Ext.ClassManager" class="docClass">Ext.ClassManager</a> will automatically check whether the given class name / alias has already existed on the page. If it's not, <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> will immediately switch itself to synchronous mode and automatic load the given class and all its dependencies.</p> <h1>Hybrid Loading - The Best of Both Worlds</h1> <p>It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:</p> <h3>Step 1: Start writing your application using synchronous approach.</h3> <p><a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> will automatically fetch all dependencies on demand as they're needed during run-time. For example:</p> <pre><code><a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function()\{ var window = <a href="#!/api/Ext-method-widget" rel="Ext-method-widget" class="docClass">Ext.widget</a>('window', \{ width: 500, height: 300, layout: \{ type: 'border', padding: 5 \}, title: 'Hello Dialog', items: [\{ title: 'Navigation', collapsible: true, region: 'west', width: 200, html: 'Hello', split: true \}, \{ title: 'TabPanel', region: 'center' \}] \}); window.show(); \}) </code></pre> <h3>Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these:</h3> <pre><code>[<a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a>] Synchronously loading '<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>'; consider adding <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>') before your application's code ClassManager.js:432 [<a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a>] Synchronously loading '<a href="#!/api/Ext.layout.container.Border" rel="Ext.layout.container.Border" class="docClass">Ext.layout.container.Border</a>'; consider adding <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.layout.container.Border" rel="Ext.layout.container.Border" class="docClass">Ext.layout.container.Border</a>') before your application's code </code></pre> <p>Simply copy and paste the suggested code above <code><a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a></code>, i.e:</p> <pre><code><a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>'); <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.layout.container.Border" rel="Ext.layout.container.Border" class="docClass">Ext.layout.container.Border</a>'); <a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(...); </code></pre> <p>Everything should now load via asynchronous mode.</p> <h1>Deployment</h1> <p>It's important to note that dynamic loading should only be used during development on your local machines. During production, all dependencies should be combined into one single JavaScript file. <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> makes the whole process of transitioning from / to between development / maintenance and production as easy as possible. Internally <a href="#!/api/Ext.Loader-property-history" rel="Ext.Loader-property-history" class="docClass">Ext.Loader.history</a> maintains the list of all dependencies your application needs in the exact loading sequence. It's as simple as concatenating all files in this array into one, then include it on top of your application.</p> <p>This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.</p> %} *) class type t = object('self) method history : _ Js.js_array Js.t Js.prop (** {% <p>An array of class names to keep track of the dependency loading order. This is not guaranteed to be the same everytime due to the asynchronous nature of the Loader.</p> %} *) method addClassPathMappings : _ Js.t -> 'self Js.t Js.meth * { % < p > Sets a batch of path entries</p > % } { b Parameters } : { ul { - paths : [ _ Js.t ] { % < p > a set of className : path mappings</p > % } } } { b Returns } : { ul { - [ Ext_Loader.t Js.t ] { % < p > this</p > % } } } {b Parameters}: {ul {- paths: [_ Js.t] {% <p>a set of className: path mappings</p> %} } } {b Returns}: {ul {- [Ext_Loader.t Js.t] {% <p>this</p> %} } } *) method exclude : _ Js.js_array Js.t -> _ Js.t Js.meth * { % < p > Explicitly exclude files from being loaded . Useful when used in conjunction with a broad include expression . Can be chained with more < code > require</code > and < code > exclude</code > methods , eg:</p > < pre><code><a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('Ext.data.*').require ( ' * ' ) ; < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('widget.button*').require('widget . * ' ) ; < /code></pre > < p><a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a > is alias for < a href="#!/api / Ext . Loader - method - exclude " rel="Ext . Loader - method - exclude " class="docClass">exclude</a>.</p > % } { b Parameters } : { ul { - excludes : [ _ Js.js_array Js.t ] } } { b Returns } : { ul { - [ _ Js.t ] { % < p > object contains < code > require</code > method for chaining</p > % } } } Can be chained with more <code>require</code> and <code>exclude</code> methods, eg:</p> <pre><code><a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('Ext.data.*').require('*'); <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('widget.button*').require('widget.*'); </code></pre> <p><a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a> is alias for <a href="#!/api/Ext.Loader-method-exclude" rel="Ext.Loader-method-exclude" class="docClass">exclude</a>.</p> %} {b Parameters}: {ul {- excludes: [_ Js.js_array Js.t] } } {b Returns}: {ul {- [_ Js.t] {% <p>object contains <code>require</code> method for chaining</p> %} } } *) method getConfig : Js.js_string Js.t -> _ Js.t Js.meth * { % < p > Get the config value corresponding to the specified name . If no name is given , will return the config object</p > % } { b Parameters } : { ul { - name : [ Js.js_string Js.t ] { % < p > The config property name</p > % } } } {b Parameters}: {ul {- name: [Js.js_string Js.t] {% <p>The config property name</p> %} } } *) method getPath : Js.js_string Js.t -> Js.js_string Js.t Js.meth * { % < p > Translates a className to a file path by adding the the proper prefix and converting the . 's to / 's . For example:</p > < pre><code><a href="#!/api / Ext . Loader - method - setPath " rel="Ext . Loader - method - setPath " class="docClass">Ext . Loader.setPath</a>('My ' , ' /path / to / My ' ) ; alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.awesome . Class ' ) ) ; // alerts ' /path / to / My / awesome / Class.js ' < /code></pre > < p > Note that the deeper namespace levels , if explicitly set , are always resolved first . For example:</p > < pre><code><a href="#!/api / Ext . Loader - method - setPath " rel="Ext . Loader - method - setPath " class="docClass">Ext . Loader.setPath</a>(\ { ' My ' : ' /path / to / lib ' , ' ' : ' /other / path / for / awesome / stuff ' , ' My.awesome.more ' : ' /more / awesome / path ' \ } ) ; alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.awesome . Class ' ) ) ; // alerts ' /other / path / for / awesome / stuff / Class.js ' alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.awesome.more . Class ' ) ) ; // alerts ' /more / awesome / path / Class.js ' alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.cool . Class ' ) ) ; // alerts ' /path / to / lib / cool / Class.js ' alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('Unknown.strange . Stuff ' ) ) ; // alerts ' Unknown / strange / Stuff.js ' < /code></pre > % } { b Parameters } : { ul { - className : [ Js.js_string Js.t ] } } { b Returns } : { ul { - [ Js.js_string Js.t ] { % < p > path</p > % } } } the proper prefix and converting the .'s to /'s. For example:</p> <pre><code><a href="#!/api/Ext.Loader-method-setPath" rel="Ext.Loader-method-setPath" class="docClass">Ext.Loader.setPath</a>('My', '/path/to/My'); alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js' </code></pre> <p>Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:</p> <pre><code><a href="#!/api/Ext.Loader-method-setPath" rel="Ext.Loader-method-setPath" class="docClass">Ext.Loader.setPath</a>(\{ 'My': '/path/to/lib', 'My.awesome': '/other/path/for/awesome/stuff', 'My.awesome.more': '/more/awesome/path' \}); alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js' alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js' alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js' alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js' </code></pre> %} {b Parameters}: {ul {- className: [Js.js_string Js.t] } } {b Returns}: {ul {- [Js.js_string Js.t] {% <p>path</p> %} } } *) method loadScript : _ Js.t -> unit Js.meth * { % < p > Loads the specified script URL and calls the supplied callbacks . If this method is called before < a href="#!/api / Ext - property - isReady " rel="Ext - property - isReady " class="docClass">Ext.isReady</a > , the script 's load will delay the transition to ready . This can be used to load arbitrary scripts that may contain further < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > calls.</p > % } { b Parameters } : { ul { - options : [ _ Js.t ] { % < p > The options object or simply the URL to load.</p > % } } } is called before <a href="#!/api/Ext-property-isReady" rel="Ext-property-isReady" class="docClass">Ext.isReady</a>, the script's load will delay the transition to ready. This can be used to load arbitrary scripts that may contain further <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a> calls.</p> %} {b Parameters}: {ul {- options: [_ Js.t] {% <p>The options object or simply the URL to load.</p> %} } } *) method onReady : _ Js.callback -> _ Js.t -> bool Js.t -> unit Js.meth * { % < p > Add a new listener to be executed when all required scripts are fully loaded</p > % } { b Parameters } : { ul { - fn : [ _ Js.callback ] { % < p > The function callback to be executed</p > % } } { - scope : [ _ Js.t ] { % < p > The execution scope ( < code > this</code > ) of the callback function</p > % } } { - withDomReady : [ bool Js.t ] { % < p > Whether or not to wait for document dom ready as > % } } } {b Parameters}: {ul {- fn: [_ Js.callback] {% <p>The function callback to be executed</p> %} } {- scope: [_ Js.t] {% <p>The execution scope (<code>this</code>) of the callback function</p> %} } {- withDomReady: [bool Js.t] {% <p>Whether or not to wait for document dom ready as well</p> %} } } *) method require : _ Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> unit Js.meth * { % < p > Loads all classes by the given names and all their direct dependencies ; optionally executes the given callback function when finishes , within the optional scope.</p > < p><a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > is alias for < a href="#!/api / Ext . Loader - method - require " rel="Ext . Loader - method - require " class="docClass">require</a>.</p > % } { b Parameters } : { ul { - expressions : [ _ Js.t ] { % < p > Can either be a string or an array of string</p > % } } { - fn : [ _ Js.callback ] ( optional ) { % < p > The callback function</p > % } } { - scope : [ _ ] ( optional ) { % < p > The execution scope ( < code > this</code > ) of the callback function</p > % } } { - excludes : [ _ ] ( optional ) { % < p > Classes to be excluded , useful when being used with expressions</p > % } } } the given callback function when finishes, within the optional scope.</p> <p><a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a> is alias for <a href="#!/api/Ext.Loader-method-require" rel="Ext.Loader-method-require" class="docClass">require</a>.</p> %} {b Parameters}: {ul {- expressions: [_ Js.t] {% <p>Can either be a string or an array of string</p> %} } {- fn: [_ Js.callback] (optional) {% <p>The callback function</p> %} } {- scope: [_ Js.t] (optional) {% <p>The execution scope (<code>this</code>) of the callback function</p> %} } {- excludes: [_ Js.t] (optional) {% <p>Classes to be excluded, useful when being used with expressions</p> %} } } *) method setConfig : _ Js.t -> 'self Js.t Js.meth * { % < p > Set the configuration for the loader . This should be called right after is included in the page , and before < a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " > . > < pre><code>&lt;script type="text / javascript " src="ext - core - debug.js"&gt;&lt;/script&gt ; & lt;script type="text / javascript"&gt ; < a href="#!/api / Ext . Loader - method - setConfig " rel="Ext . Loader - method - setConfig " class="docClass">Ext . { enabled : true , paths : \ { ' My ' : ' my_own_path ' \ } \ } ) ; & lt;/script&gt ; & lt;script type="text / javascript"&gt ; < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > ( ... ) ; < a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function ( ) \ { // application code here \ } ) ; & lt;/script&gt ; < /code></pre > < p > Refer to config options of < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . for the list of possible properties</p > % } { b Parameters } : { ul { - config : [ _ Js.t ] { % < p > The config object to override the default values</p > % } } } { b Returns } : { ul { - [ Ext_Loader.t Js.t ] { % < p > this</p > % } } } is included in the page, and before <a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>. i.e:</p> <pre><code>&lt;script type="text/javascript" src="ext-core-debug.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; <a href="#!/api/Ext.Loader-method-setConfig" rel="Ext.Loader-method-setConfig" class="docClass">Ext.Loader.setConfig</a>(\{ enabled: true, paths: \{ 'My': 'my_own_path' \} \}); &lt;/script&gt; &lt;script type="text/javascript"&gt; <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(...); <a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function() \{ // application code here \}); &lt;/script&gt; </code></pre> <p>Refer to config options of <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> for the list of possible properties</p> %} {b Parameters}: {ul {- config: [_ Js.t] {% <p>The config object to override the default values</p> %} } } {b Returns}: {ul {- [Ext_Loader.t Js.t] {% <p>this</p> %} } } *) method setPath : _ Js.t -> Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth * { % < p > Sets the path of a namespace . For > < pre><code><a href="#!/api / Ext . Loader - method - setPath " rel="Ext . Loader - method - setPath " class="docClass">Ext . Loader.setPath</a>('Ext ' , ' . ' ) ; < /code></pre > % } { b Parameters } : { ul { - name : [ _ Js.t ] { % < p > See < a href="#!/api / Ext . Function - method - flexSetter " rel="Ext . Function - method - flexSetter " class="docClass">flexSetter</a></p > % } } { - path : [ Js.js_string Js.t ] ( optional ) { % < p > See < a href="#!/api / Ext . Function - method - flexSetter " rel="Ext . Function - method - flexSetter " class="docClass">flexSetter</a></p > % } } } { b Returns } : { ul { - [ Ext_Loader.t Js.t ] { % < p > this</p > % } } } For Example:</p> <pre><code><a href="#!/api/Ext.Loader-method-setPath" rel="Ext.Loader-method-setPath" class="docClass">Ext.Loader.setPath</a>('Ext', '.'); </code></pre> %} {b Parameters}: {ul {- name: [_ Js.t] {% <p>See <a href="#!/api/Ext.Function-method-flexSetter" rel="Ext.Function-method-flexSetter" class="docClass">flexSetter</a></p> %} } {- path: [Js.js_string Js.t] (optional) {% <p>See <a href="#!/api/Ext.Function-method-flexSetter" rel="Ext.Function-method-flexSetter" class="docClass">flexSetter</a></p> %} } } {b Returns}: {ul {- [Ext_Loader.t Js.t] {% <p>this</p> %} } } *) method syncRequire : _ Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> unit Js.meth * { % < p > Synchronously loads all classes by the given names and all their direct dependencies ; optionally executes the given callback function when finishes , within the optional scope.</p > < p><a href="#!/api / Ext - method - syncRequire " rel="Ext - method - syncRequire " class="docClass">Ext.syncRequire</a > is alias for < a href="#!/api / Ext . Loader - method - syncRequire " rel="Ext . Loader - method - syncRequire " class="docClass">syncRequire</a>.</p > % } { b Parameters } : { ul { - expressions : [ _ Js.t ] { % < p > Can either be a string or an array of string</p > % } } { - fn : [ _ Js.callback ] ( optional ) { % < p > The callback function</p > % } } { - scope : [ _ ] ( optional ) { % < p > The execution scope ( < code > this</code > ) of the callback function</p > % } } { - excludes : [ _ ] ( optional ) { % < p > Classes to be excluded , useful when being used with expressions</p > % } } } executes the given callback function when finishes, within the optional scope.</p> <p><a href="#!/api/Ext-method-syncRequire" rel="Ext-method-syncRequire" class="docClass">Ext.syncRequire</a> is alias for <a href="#!/api/Ext.Loader-method-syncRequire" rel="Ext.Loader-method-syncRequire" class="docClass">syncRequire</a>.</p> %} {b Parameters}: {ul {- expressions: [_ Js.t] {% <p>Can either be a string or an array of string</p> %} } {- fn: [_ Js.callback] (optional) {% <p>The callback function</p> %} } {- scope: [_ Js.t] (optional) {% <p>The execution scope (<code>this</code>) of the callback function</p> %} } {- excludes: [_ Js.t] (optional) {% <p>Classes to be excluded, useful when being used with expressions</p> %} } } *) end class type configs = object('self) method disableCaching : bool Js.t Js.prop * { % < p > Appends current timestamp to script files to prevent caching.</p > % } Defaults to : [ true ] Defaults to: [true] *) method disableCachingParam : Js.js_string Js.t Js.prop (** {% <p>The get parameter name for the cache buster's timestamp.</p> %} Defaults to: ['_dc'] *) method enabled : bool Js.t Js.prop (** {% <p>Whether or not to enable the dynamic dependency loading feature.</p> %} Defaults to: [false] *) method garbageCollect : bool Js.t Js.prop * { % < p > True to prepare an asynchronous script tag for garbage collection ( effective only if < a href="#!/api / Ext . Loader - cfg - preserveScripts " rel="Ext . " class="docClass">preserveScripts</a > is false)</p > % } Defaults to : [ false ] if <a href="#!/api/Ext.Loader-cfg-preserveScripts" rel="Ext.Loader-cfg-preserveScripts" class="docClass">preserveScripts</a> is false)</p> %} Defaults to: [false] *) method paths : _ Js.t Js.prop * { % < p > The mapping from namespaces to file paths</p > < pre><code>\ { ' Ext ' : ' . ' , // This is set by default , < a href="#!/api / Ext.layout.container . Container " rel="Ext.layout.container . Container " class="docClass">Ext.layout.container . Container</a > will be // loaded from ./layout / Container.js ' My ' : ' ./src / my_own_folder ' // My.layout . Container will be loaded from // ./src / my_own_folder / layout / Container.js \ } < /code></pre > < p > Note that all relative paths are relative to the current HTML document . If not being specified , for example , < code > Other.awesome . Class</code > will simply be loaded from < code>./Other / awesome / Class.js</code></p > % } Defaults to : [ \{'Ext ' : ' .'\ } ] <pre><code>\{ 'Ext': '.', // This is set by default, <a href="#!/api/Ext.layout.container.Container" rel="Ext.layout.container.Container" class="docClass">Ext.layout.container.Container</a> will be // loaded from ./layout/Container.js 'My': './src/my_own_folder' // My.layout.Container will be loaded from // ./src/my_own_folder/layout/Container.js \} </code></pre> <p>Note that all relative paths are relative to the current HTML document. If not being specified, for example, <code>Other.awesome.Class</code> will simply be loaded from <code>./Other/awesome/Class.js</code></p> %} Defaults to: [\{'Ext': '.'\}] *) method preserveScripts : bool Js.t Js.prop * { % < p > False to remove and optionally < a href="#!/api / Ext . Loader - cfg - garbageCollect " rel="Ext . " class="docClass">garbage - collect</a > asynchronously loaded scripts , True to retain script element for browser debugger compatibility and improved load performance.</p > % } Defaults to : [ true ] True to retain script element for browser debugger compatibility and improved load performance.</p> %} Defaults to: [true] *) method scriptChainDelay : bool Js.t Js.prop * { % < p > millisecond delay between asynchronous script injection ( prevents stack overflow on some user agents ) ' false ' disables delay but potentially increases stack load.</p > % } Defaults to : [ false ] 'false' disables delay but potentially increases stack load.</p> %} Defaults to: [false] *) method scriptCharset : Js.js_string Js.t Js.prop * { % < p > Optional charset to specify encoding of dynamic script content.</p > % } *) end class type events = object end class type statics = object end val get_instance : unit -> t Js.t (** Singleton instance for lazy-loaded modules. *) val instance : t Js.t * instance . val of_configs : configs Js.t -> t Js.t (** [of_configs c] casts a config object [c] to an instance of class [t] *) val to_configs : t Js.t -> configs Js.t (** [to_configs o] casts instance [o] of class [t] to a config object *)
null
https://raw.githubusercontent.com/astrada/ocaml-extjs/77df630a75fb84667ee953f218c9ce375b3e7484/lib/ext_Loader.mli
ocaml
* {% <p>An array of class names to keep track of the dependency loading order. This is not guaranteed to be the same everytime due to the asynchronous nature of the Loader.</p> %} * {% <p>The get parameter name for the cache buster's timestamp.</p> %} Defaults to: ['_dc'] * {% <p>Whether or not to enable the dynamic dependency loading feature.</p> %} Defaults to: [false] * Singleton instance for lazy-loaded modules. * [of_configs c] casts a config object [c] to an instance of class [t] * [to_configs o] casts instance [o] of class [t] to a config object
* Ext . Loader is the heart of the new dynamic depende ... { % < p><a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . is the heart of the new dynamic dependency loading capability in Ext JS 4 + . It is most commonly used via the < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > shorthand . < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . Loader</a > supports both asynchronous and synchronous loading approaches , and leverage their advantages for the best development flow . We 'll discuss about the pros and cons of each approach:</p > < h1 > Asynchronous Loading</h1 > < ul > < li><p > Advantages:</p > < ul > < li > Cross - domain</li > < li > No web server needed : you can run the application via the file system protocol ( i.e : < code > file / to / your / index .html</code>)</li > < li > Best possible debugging experience : error messages come with the exact file name and line number</li > < /ul > < /li > < li><p > Disadvantages:</p > < ul > < li > Dependencies need to be specified before - hand</li > < /ul > < /li > < /ul > < h3 > Method 1 : Explicitly include what you need:</h3 > < pre><code>// Syntax < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>(\{String / Array\ } expressions ) ; // Example : Single alias < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('widget.window ' ) ; // Example : Single class name < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ) ; // Example : Multiple aliases / class names mix < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>(['widget.window ' , ' layout.border ' , ' < a href="#!/api / Ext.data . Connection " rel="Ext.data . Connection " class="docClass">Ext.data . Connection</a > ' ] ) ; // Wildcards < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>(['widget . * ' , ' layout . * ' , ' Ext.data . * ' ] ) ; < /code></pre > < h3 > Method 2 : Explicitly exclude what you do n't need:</h3 > < pre><code>// Syntax : Note that it must be in this chaining format . < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>(\{String / Array\ } expressions ) .require(\{String / Array\ } expressions ) ; // Include everything except Ext.data . * < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('Ext.data.*').require ( ' * ' ) ; // Include all widgets except widget.checkbox * , // which will match widget.checkbox , widget.checkboxfield , widget.checkboxgroup , etc . < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('widget.checkbox*').require('widget . * ' ) ; < /code></pre > < h1 > Synchronous Loading on Demand</h1 > < ul > < li><p > Advantages:</p > < ul > < li > There 's no need to specify dependencies before - hand , which is always the convenience of including ext-all.js before</li > < /ul > < /li > < li><p > Disadvantages:</p > < ul > < li > Not as good debugging experience since file name wo n't be shown ( except in Firebug at the moment)</li > < li > Must be from the same domain due to XHR restriction</li > < li > Need a web server , same reason as above</li > < /ul > < /li > < /ul > < p > There 's one simple rule to follow : Instantiate everything with < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a > instead of the < code > new</code > < pre><code><a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('widget.window ' , \ { ... \ } ) ; // Instead of new < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a>(\{ ... \ } ) ; < a href="#!/api / Ext - method - create " rel="Ext - method - create " class="docClass">Ext.create</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' , \{\ } ) ; // Same as above , using full class name instead of alias < a href="#!/api / Ext - method - widget " rel="Ext - method - widget " class="docClass">Ext.widget</a>('window ' , \{\ } ) ; // Same as above , all you need is the traditional ` xtype ` < /code></pre > < p > Behind the scene , < a href="#!/api / Ext . ClassManager " rel="Ext . ClassManager " class="docClass">Ext . will automatically check whether the given class name / alias has already existed on the page . If it 's not , < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . will immediately switch itself to synchronous mode and automatic load the given class and all its dependencies.</p > < h1 > Hybrid Loading - The Best of Both Worlds</h1 > < p > It has all the advantages combined from asynchronous and synchronous loading . The development flow is simple:</p > < h3 > Step 1 : Start writing your application using synchronous approach.</h3 > < p><a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . will automatically fetch all dependencies on demand as they 're needed during run - time . For example:</p > < pre><code><a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function()\ { var window = < a href="#!/api / Ext - method - widget " rel="Ext - method - widget " class="docClass">Ext.widget</a>('window ' , \ { width : 500 , height : 300 , layout : \ { type : ' border ' , padding : 5 \ } , title : ' Hello Dialog ' , items : [ \ { title : ' Navigation ' , collapsible : true , region : ' west ' , width : 200 , html : ' Hello ' , split : true \ } , \ { title : ' TabPanel ' , region : ' center ' \ } ] \ } ) ; window.show ( ) ; \ } ) < /code></pre > < h3 > Step 2 : Along the way , when you need better debugging ability , watch the console for warnings like these:</h3 > < pre><code>[<a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . ] Synchronously loading ' < a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ; consider adding < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ) before your application 's code ClassManager.js:432 [ < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . ] Synchronously loading ' < a href="#!/api / Ext.layout.container . Border " . Border " class="docClass">Ext.layout.container . > ' ; consider adding < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.layout.container . Border " . Border " class="docClass">Ext.layout.container . > ' ) before your application 's code < /code></pre > < p > Simply copy and paste the suggested code above < code><a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a></code > , i.e:</p > < pre><code><a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.window . Window " rel="Ext.window . Window " class="docClass">Ext.window . Window</a > ' ) ; < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a>('<a href="#!/api / Ext.layout.container . Border " . Border " class="docClass">Ext.layout.container . > ' ) ; < a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " > ( ... ) ; < /code></pre > < p > Everything should now load via asynchronous mode.</p > < h1 > Deployment</h1 > < p > It 's important to note that dynamic loading should only be used during development on your local machines . During production , all dependencies should be combined into one single JavaScript file . < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . makes the whole process of transitioning from / to between development / maintenance and production as easy as possible . Internally < a href="#!/api / Ext . Loader - property - history " rel="Ext . Loader - property - history " class="docClass">Ext . Loader.history</a > maintains the list of all dependencies your application needs in the exact loading sequence . It 's as simple as concatenating all files in this array into one , then include it on top of your application.</p > < p > This process will be automated with Sencha Command , to be released and documented towards Ext JS 4 Final.</p > % } {% <p><a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> is the heart of the new dynamic dependency loading capability in Ext JS 4+. It is most commonly used via the <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a> shorthand. <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> supports both asynchronous and synchronous loading approaches, and leverage their advantages for the best development flow. We'll discuss about the pros and cons of each approach:</p> <h1>Asynchronous Loading</h1> <ul> <li><p>Advantages:</p> <ul> <li>Cross-domain</li> <li>No web server needed: you can run the application via the file system protocol (i.e: <code>file .html</code>)</li> <li>Best possible debugging experience: error messages come with the exact file name and line number</li> </ul> </li> <li><p>Disadvantages:</p> <ul> <li>Dependencies need to be specified before-hand</li> </ul> </li> </ul> <h3>Method 1: Explicitly include what you need:</h3> <pre><code>// Syntax <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(\{String/Array\} expressions); // Example: Single alias <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('widget.window'); // Example: Single class name <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>'); // Example: Multiple aliases / class names mix <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(['widget.window', 'layout.border', '<a href="#!/api/Ext.data.Connection" rel="Ext.data.Connection" class="docClass">Ext.data.Connection</a>']); // Wildcards <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(['widget.*', 'layout.*', 'Ext.data.*']); </code></pre> <h3>Method 2: Explicitly exclude what you don't need:</h3> <pre><code>// Syntax: Note that it must be in this chaining format. <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>(\{String/Array\} expressions) .require(\{String/Array\} expressions); // Include everything except Ext.data.* <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('Ext.data.*').require('*'); // Include all widgets except widget.checkbox*, // which will match widget.checkbox, widget.checkboxfield, widget.checkboxgroup, etc. <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('widget.checkbox*').require('widget.*'); </code></pre> <h1>Synchronous Loading on Demand</h1> <ul> <li><p>Advantages:</p> <ul> <li>There's no need to specify dependencies before-hand, which is always the convenience of including ext-all.js before</li> </ul> </li> <li><p>Disadvantages:</p> <ul> <li>Not as good debugging experience since file name won't be shown (except in Firebug at the moment)</li> <li>Must be from the same domain due to XHR restriction</li> <li>Need a web server, same reason as above</li> </ul> </li> </ul> <p>There's one simple rule to follow: Instantiate everything with <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a> instead of the <code>new</code> keyword</p> <pre><code><a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('widget.window', \{ ... \}); // Instead of new <a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>(\{...\}); <a href="#!/api/Ext-method-create" rel="Ext-method-create" class="docClass">Ext.create</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>', \{\}); // Same as above, using full class name instead of alias <a href="#!/api/Ext-method-widget" rel="Ext-method-widget" class="docClass">Ext.widget</a>('window', \{\}); // Same as above, all you need is the traditional `xtype` </code></pre> <p>Behind the scene, <a href="#!/api/Ext.ClassManager" rel="Ext.ClassManager" class="docClass">Ext.ClassManager</a> will automatically check whether the given class name / alias has already existed on the page. If it's not, <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> will immediately switch itself to synchronous mode and automatic load the given class and all its dependencies.</p> <h1>Hybrid Loading - The Best of Both Worlds</h1> <p>It has all the advantages combined from asynchronous and synchronous loading. The development flow is simple:</p> <h3>Step 1: Start writing your application using synchronous approach.</h3> <p><a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> will automatically fetch all dependencies on demand as they're needed during run-time. For example:</p> <pre><code><a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function()\{ var window = <a href="#!/api/Ext-method-widget" rel="Ext-method-widget" class="docClass">Ext.widget</a>('window', \{ width: 500, height: 300, layout: \{ type: 'border', padding: 5 \}, title: 'Hello Dialog', items: [\{ title: 'Navigation', collapsible: true, region: 'west', width: 200, html: 'Hello', split: true \}, \{ title: 'TabPanel', region: 'center' \}] \}); window.show(); \}) </code></pre> <h3>Step 2: Along the way, when you need better debugging ability, watch the console for warnings like these:</h3> <pre><code>[<a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a>] Synchronously loading '<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>'; consider adding <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>') before your application's code ClassManager.js:432 [<a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a>] Synchronously loading '<a href="#!/api/Ext.layout.container.Border" rel="Ext.layout.container.Border" class="docClass">Ext.layout.container.Border</a>'; consider adding <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.layout.container.Border" rel="Ext.layout.container.Border" class="docClass">Ext.layout.container.Border</a>') before your application's code </code></pre> <p>Simply copy and paste the suggested code above <code><a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a></code>, i.e:</p> <pre><code><a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.window.Window" rel="Ext.window.Window" class="docClass">Ext.window.Window</a>'); <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>('<a href="#!/api/Ext.layout.container.Border" rel="Ext.layout.container.Border" class="docClass">Ext.layout.container.Border</a>'); <a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(...); </code></pre> <p>Everything should now load via asynchronous mode.</p> <h1>Deployment</h1> <p>It's important to note that dynamic loading should only be used during development on your local machines. During production, all dependencies should be combined into one single JavaScript file. <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> makes the whole process of transitioning from / to between development / maintenance and production as easy as possible. Internally <a href="#!/api/Ext.Loader-property-history" rel="Ext.Loader-property-history" class="docClass">Ext.Loader.history</a> maintains the list of all dependencies your application needs in the exact loading sequence. It's as simple as concatenating all files in this array into one, then include it on top of your application.</p> <p>This process will be automated with Sencha Command, to be released and documented towards Ext JS 4 Final.</p> %} *) class type t = object('self) method history : _ Js.js_array Js.t Js.prop method addClassPathMappings : _ Js.t -> 'self Js.t Js.meth * { % < p > Sets a batch of path entries</p > % } { b Parameters } : { ul { - paths : [ _ Js.t ] { % < p > a set of className : path mappings</p > % } } } { b Returns } : { ul { - [ Ext_Loader.t Js.t ] { % < p > this</p > % } } } {b Parameters}: {ul {- paths: [_ Js.t] {% <p>a set of className: path mappings</p> %} } } {b Returns}: {ul {- [Ext_Loader.t Js.t] {% <p>this</p> %} } } *) method exclude : _ Js.js_array Js.t -> _ Js.t Js.meth * { % < p > Explicitly exclude files from being loaded . Useful when used in conjunction with a broad include expression . Can be chained with more < code > require</code > and < code > exclude</code > methods , eg:</p > < pre><code><a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('Ext.data.*').require ( ' * ' ) ; < a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a>('widget.button*').require('widget . * ' ) ; < /code></pre > < p><a href="#!/api / Ext - method - exclude " rel="Ext - method - exclude " class="docClass">Ext.exclude</a > is alias for < a href="#!/api / Ext . Loader - method - exclude " rel="Ext . Loader - method - exclude " class="docClass">exclude</a>.</p > % } { b Parameters } : { ul { - excludes : [ _ Js.js_array Js.t ] } } { b Returns } : { ul { - [ _ Js.t ] { % < p > object contains < code > require</code > method for chaining</p > % } } } Can be chained with more <code>require</code> and <code>exclude</code> methods, eg:</p> <pre><code><a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('Ext.data.*').require('*'); <a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a>('widget.button*').require('widget.*'); </code></pre> <p><a href="#!/api/Ext-method-exclude" rel="Ext-method-exclude" class="docClass">Ext.exclude</a> is alias for <a href="#!/api/Ext.Loader-method-exclude" rel="Ext.Loader-method-exclude" class="docClass">exclude</a>.</p> %} {b Parameters}: {ul {- excludes: [_ Js.js_array Js.t] } } {b Returns}: {ul {- [_ Js.t] {% <p>object contains <code>require</code> method for chaining</p> %} } } *) method getConfig : Js.js_string Js.t -> _ Js.t Js.meth * { % < p > Get the config value corresponding to the specified name . If no name is given , will return the config object</p > % } { b Parameters } : { ul { - name : [ Js.js_string Js.t ] { % < p > The config property name</p > % } } } {b Parameters}: {ul {- name: [Js.js_string Js.t] {% <p>The config property name</p> %} } } *) method getPath : Js.js_string Js.t -> Js.js_string Js.t Js.meth * { % < p > Translates a className to a file path by adding the the proper prefix and converting the . 's to / 's . For example:</p > < pre><code><a href="#!/api / Ext . Loader - method - setPath " rel="Ext . Loader - method - setPath " class="docClass">Ext . Loader.setPath</a>('My ' , ' /path / to / My ' ) ; alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.awesome . Class ' ) ) ; // alerts ' /path / to / My / awesome / Class.js ' < /code></pre > < p > Note that the deeper namespace levels , if explicitly set , are always resolved first . For example:</p > < pre><code><a href="#!/api / Ext . Loader - method - setPath " rel="Ext . Loader - method - setPath " class="docClass">Ext . Loader.setPath</a>(\ { ' My ' : ' /path / to / lib ' , ' ' : ' /other / path / for / awesome / stuff ' , ' My.awesome.more ' : ' /more / awesome / path ' \ } ) ; alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.awesome . Class ' ) ) ; // alerts ' /other / path / for / awesome / stuff / Class.js ' alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.awesome.more . Class ' ) ) ; // alerts ' /more / awesome / path / Class.js ' alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('My.cool . Class ' ) ) ; // alerts ' /path / to / lib / cool / Class.js ' alert(<a href="#!/api / Ext . Loader - method - getPath " rel="Ext . Loader - method - getPath " class="docClass">Ext . Loader.getPath</a>('Unknown.strange . Stuff ' ) ) ; // alerts ' Unknown / strange / Stuff.js ' < /code></pre > % } { b Parameters } : { ul { - className : [ Js.js_string Js.t ] } } { b Returns } : { ul { - [ Js.js_string Js.t ] { % < p > path</p > % } } } the proper prefix and converting the .'s to /'s. For example:</p> <pre><code><a href="#!/api/Ext.Loader-method-setPath" rel="Ext.Loader-method-setPath" class="docClass">Ext.Loader.setPath</a>('My', '/path/to/My'); alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.awesome.Class')); // alerts '/path/to/My/awesome/Class.js' </code></pre> <p>Note that the deeper namespace levels, if explicitly set, are always resolved first. For example:</p> <pre><code><a href="#!/api/Ext.Loader-method-setPath" rel="Ext.Loader-method-setPath" class="docClass">Ext.Loader.setPath</a>(\{ 'My': '/path/to/lib', 'My.awesome': '/other/path/for/awesome/stuff', 'My.awesome.more': '/more/awesome/path' \}); alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.awesome.Class')); // alerts '/other/path/for/awesome/stuff/Class.js' alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.awesome.more.Class')); // alerts '/more/awesome/path/Class.js' alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('My.cool.Class')); // alerts '/path/to/lib/cool/Class.js' alert(<a href="#!/api/Ext.Loader-method-getPath" rel="Ext.Loader-method-getPath" class="docClass">Ext.Loader.getPath</a>('Unknown.strange.Stuff')); // alerts 'Unknown/strange/Stuff.js' </code></pre> %} {b Parameters}: {ul {- className: [Js.js_string Js.t] } } {b Returns}: {ul {- [Js.js_string Js.t] {% <p>path</p> %} } } *) method loadScript : _ Js.t -> unit Js.meth * { % < p > Loads the specified script URL and calls the supplied callbacks . If this method is called before < a href="#!/api / Ext - property - isReady " rel="Ext - property - isReady " class="docClass">Ext.isReady</a > , the script 's load will delay the transition to ready . This can be used to load arbitrary scripts that may contain further < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > calls.</p > % } { b Parameters } : { ul { - options : [ _ Js.t ] { % < p > The options object or simply the URL to load.</p > % } } } is called before <a href="#!/api/Ext-property-isReady" rel="Ext-property-isReady" class="docClass">Ext.isReady</a>, the script's load will delay the transition to ready. This can be used to load arbitrary scripts that may contain further <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a> calls.</p> %} {b Parameters}: {ul {- options: [_ Js.t] {% <p>The options object or simply the URL to load.</p> %} } } *) method onReady : _ Js.callback -> _ Js.t -> bool Js.t -> unit Js.meth * { % < p > Add a new listener to be executed when all required scripts are fully loaded</p > % } { b Parameters } : { ul { - fn : [ _ Js.callback ] { % < p > The function callback to be executed</p > % } } { - scope : [ _ Js.t ] { % < p > The execution scope ( < code > this</code > ) of the callback function</p > % } } { - withDomReady : [ bool Js.t ] { % < p > Whether or not to wait for document dom ready as > % } } } {b Parameters}: {ul {- fn: [_ Js.callback] {% <p>The function callback to be executed</p> %} } {- scope: [_ Js.t] {% <p>The execution scope (<code>this</code>) of the callback function</p> %} } {- withDomReady: [bool Js.t] {% <p>Whether or not to wait for document dom ready as well</p> %} } } *) method require : _ Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> unit Js.meth * { % < p > Loads all classes by the given names and all their direct dependencies ; optionally executes the given callback function when finishes , within the optional scope.</p > < p><a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > is alias for < a href="#!/api / Ext . Loader - method - require " rel="Ext . Loader - method - require " class="docClass">require</a>.</p > % } { b Parameters } : { ul { - expressions : [ _ Js.t ] { % < p > Can either be a string or an array of string</p > % } } { - fn : [ _ Js.callback ] ( optional ) { % < p > The callback function</p > % } } { - scope : [ _ ] ( optional ) { % < p > The execution scope ( < code > this</code > ) of the callback function</p > % } } { - excludes : [ _ ] ( optional ) { % < p > Classes to be excluded , useful when being used with expressions</p > % } } } the given callback function when finishes, within the optional scope.</p> <p><a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a> is alias for <a href="#!/api/Ext.Loader-method-require" rel="Ext.Loader-method-require" class="docClass">require</a>.</p> %} {b Parameters}: {ul {- expressions: [_ Js.t] {% <p>Can either be a string or an array of string</p> %} } {- fn: [_ Js.callback] (optional) {% <p>The callback function</p> %} } {- scope: [_ Js.t] (optional) {% <p>The execution scope (<code>this</code>) of the callback function</p> %} } {- excludes: [_ Js.t] (optional) {% <p>Classes to be excluded, useful when being used with expressions</p> %} } } *) method setConfig : _ Js.t -> 'self Js.t Js.meth * { % < p > Set the configuration for the loader . This should be called right after is included in the page , and before < a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " > . > < pre><code>&lt;script type="text / javascript " src="ext - core - debug.js"&gt;&lt;/script&gt ; & lt;script type="text / javascript"&gt ; < a href="#!/api / Ext . Loader - method - setConfig " rel="Ext . Loader - method - setConfig " class="docClass">Ext . { enabled : true , paths : \ { ' My ' : ' my_own_path ' \ } \ } ) ; & lt;/script&gt ; & lt;script type="text / javascript"&gt ; < a href="#!/api / Ext - method - require " rel="Ext - method - require " class="docClass">Ext.require</a > ( ... ) ; < a href="#!/api / Ext - method - onReady " rel="Ext - method - onReady " class="docClass">Ext.onReady</a>(function ( ) \ { // application code here \ } ) ; & lt;/script&gt ; < /code></pre > < p > Refer to config options of < a href="#!/api / Ext . Loader " rel="Ext . Loader " class="docClass">Ext . for the list of possible properties</p > % } { b Parameters } : { ul { - config : [ _ Js.t ] { % < p > The config object to override the default values</p > % } } } { b Returns } : { ul { - [ Ext_Loader.t Js.t ] { % < p > this</p > % } } } is included in the page, and before <a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>. i.e:</p> <pre><code>&lt;script type="text/javascript" src="ext-core-debug.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; <a href="#!/api/Ext.Loader-method-setConfig" rel="Ext.Loader-method-setConfig" class="docClass">Ext.Loader.setConfig</a>(\{ enabled: true, paths: \{ 'My': 'my_own_path' \} \}); &lt;/script&gt; &lt;script type="text/javascript"&gt; <a href="#!/api/Ext-method-require" rel="Ext-method-require" class="docClass">Ext.require</a>(...); <a href="#!/api/Ext-method-onReady" rel="Ext-method-onReady" class="docClass">Ext.onReady</a>(function() \{ // application code here \}); &lt;/script&gt; </code></pre> <p>Refer to config options of <a href="#!/api/Ext.Loader" rel="Ext.Loader" class="docClass">Ext.Loader</a> for the list of possible properties</p> %} {b Parameters}: {ul {- config: [_ Js.t] {% <p>The config object to override the default values</p> %} } } {b Returns}: {ul {- [Ext_Loader.t Js.t] {% <p>this</p> %} } } *) method setPath : _ Js.t -> Js.js_string Js.t Js.optdef -> 'self Js.t Js.meth * { % < p > Sets the path of a namespace . For > < pre><code><a href="#!/api / Ext . Loader - method - setPath " rel="Ext . Loader - method - setPath " class="docClass">Ext . Loader.setPath</a>('Ext ' , ' . ' ) ; < /code></pre > % } { b Parameters } : { ul { - name : [ _ Js.t ] { % < p > See < a href="#!/api / Ext . Function - method - flexSetter " rel="Ext . Function - method - flexSetter " class="docClass">flexSetter</a></p > % } } { - path : [ Js.js_string Js.t ] ( optional ) { % < p > See < a href="#!/api / Ext . Function - method - flexSetter " rel="Ext . Function - method - flexSetter " class="docClass">flexSetter</a></p > % } } } { b Returns } : { ul { - [ Ext_Loader.t Js.t ] { % < p > this</p > % } } } For Example:</p> <pre><code><a href="#!/api/Ext.Loader-method-setPath" rel="Ext.Loader-method-setPath" class="docClass">Ext.Loader.setPath</a>('Ext', '.'); </code></pre> %} {b Parameters}: {ul {- name: [_ Js.t] {% <p>See <a href="#!/api/Ext.Function-method-flexSetter" rel="Ext.Function-method-flexSetter" class="docClass">flexSetter</a></p> %} } {- path: [Js.js_string Js.t] (optional) {% <p>See <a href="#!/api/Ext.Function-method-flexSetter" rel="Ext.Function-method-flexSetter" class="docClass">flexSetter</a></p> %} } } {b Returns}: {ul {- [Ext_Loader.t Js.t] {% <p>this</p> %} } } *) method syncRequire : _ Js.t -> _ Js.callback Js.optdef -> _ Js.t Js.optdef -> _ Js.t Js.optdef -> unit Js.meth * { % < p > Synchronously loads all classes by the given names and all their direct dependencies ; optionally executes the given callback function when finishes , within the optional scope.</p > < p><a href="#!/api / Ext - method - syncRequire " rel="Ext - method - syncRequire " class="docClass">Ext.syncRequire</a > is alias for < a href="#!/api / Ext . Loader - method - syncRequire " rel="Ext . Loader - method - syncRequire " class="docClass">syncRequire</a>.</p > % } { b Parameters } : { ul { - expressions : [ _ Js.t ] { % < p > Can either be a string or an array of string</p > % } } { - fn : [ _ Js.callback ] ( optional ) { % < p > The callback function</p > % } } { - scope : [ _ ] ( optional ) { % < p > The execution scope ( < code > this</code > ) of the callback function</p > % } } { - excludes : [ _ ] ( optional ) { % < p > Classes to be excluded , useful when being used with expressions</p > % } } } executes the given callback function when finishes, within the optional scope.</p> <p><a href="#!/api/Ext-method-syncRequire" rel="Ext-method-syncRequire" class="docClass">Ext.syncRequire</a> is alias for <a href="#!/api/Ext.Loader-method-syncRequire" rel="Ext.Loader-method-syncRequire" class="docClass">syncRequire</a>.</p> %} {b Parameters}: {ul {- expressions: [_ Js.t] {% <p>Can either be a string or an array of string</p> %} } {- fn: [_ Js.callback] (optional) {% <p>The callback function</p> %} } {- scope: [_ Js.t] (optional) {% <p>The execution scope (<code>this</code>) of the callback function</p> %} } {- excludes: [_ Js.t] (optional) {% <p>Classes to be excluded, useful when being used with expressions</p> %} } } *) end class type configs = object('self) method disableCaching : bool Js.t Js.prop * { % < p > Appends current timestamp to script files to prevent caching.</p > % } Defaults to : [ true ] Defaults to: [true] *) method disableCachingParam : Js.js_string Js.t Js.prop method enabled : bool Js.t Js.prop method garbageCollect : bool Js.t Js.prop * { % < p > True to prepare an asynchronous script tag for garbage collection ( effective only if < a href="#!/api / Ext . Loader - cfg - preserveScripts " rel="Ext . " class="docClass">preserveScripts</a > is false)</p > % } Defaults to : [ false ] if <a href="#!/api/Ext.Loader-cfg-preserveScripts" rel="Ext.Loader-cfg-preserveScripts" class="docClass">preserveScripts</a> is false)</p> %} Defaults to: [false] *) method paths : _ Js.t Js.prop * { % < p > The mapping from namespaces to file paths</p > < pre><code>\ { ' Ext ' : ' . ' , // This is set by default , < a href="#!/api / Ext.layout.container . Container " rel="Ext.layout.container . Container " class="docClass">Ext.layout.container . Container</a > will be // loaded from ./layout / Container.js ' My ' : ' ./src / my_own_folder ' // My.layout . Container will be loaded from // ./src / my_own_folder / layout / Container.js \ } < /code></pre > < p > Note that all relative paths are relative to the current HTML document . If not being specified , for example , < code > Other.awesome . Class</code > will simply be loaded from < code>./Other / awesome / Class.js</code></p > % } Defaults to : [ \{'Ext ' : ' .'\ } ] <pre><code>\{ 'Ext': '.', // This is set by default, <a href="#!/api/Ext.layout.container.Container" rel="Ext.layout.container.Container" class="docClass">Ext.layout.container.Container</a> will be // loaded from ./layout/Container.js 'My': './src/my_own_folder' // My.layout.Container will be loaded from // ./src/my_own_folder/layout/Container.js \} </code></pre> <p>Note that all relative paths are relative to the current HTML document. If not being specified, for example, <code>Other.awesome.Class</code> will simply be loaded from <code>./Other/awesome/Class.js</code></p> %} Defaults to: [\{'Ext': '.'\}] *) method preserveScripts : bool Js.t Js.prop * { % < p > False to remove and optionally < a href="#!/api / Ext . Loader - cfg - garbageCollect " rel="Ext . " class="docClass">garbage - collect</a > asynchronously loaded scripts , True to retain script element for browser debugger compatibility and improved load performance.</p > % } Defaults to : [ true ] True to retain script element for browser debugger compatibility and improved load performance.</p> %} Defaults to: [true] *) method scriptChainDelay : bool Js.t Js.prop * { % < p > millisecond delay between asynchronous script injection ( prevents stack overflow on some user agents ) ' false ' disables delay but potentially increases stack load.</p > % } Defaults to : [ false ] 'false' disables delay but potentially increases stack load.</p> %} Defaults to: [false] *) method scriptCharset : Js.js_string Js.t Js.prop * { % < p > Optional charset to specify encoding of dynamic script content.</p > % } *) end class type events = object end class type statics = object end val get_instance : unit -> t Js.t val instance : t Js.t * instance . val of_configs : configs Js.t -> t Js.t val to_configs : t Js.t -> configs Js.t
51e7dd297901c422a8e8c5c75aa56512ca436e572af1a636c49113463eccd53b
metabase/metabase
subscription_test.clj
(ns ^:mb/once metabase-enterprise.advanced-permissions.api.subscription-test "Permisisons tests for API that needs to be enforced by Application Permissions to create and edit alerts/subscriptions." (:require [clojure.test :refer :all] [metabase.api.alert :as api.alert] [metabase.api.alert-test :as alert-test] [metabase.models :refer [Card Collection Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as perms-group] [metabase.models.pulse :as pulse] [metabase.public-settings.premium-features-test :as premium-features-test] [metabase.pulse-test :as pulse-test] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db])) (defmacro ^:private with-subscription-disabled-for-all-users "Temporarily remove `subscription` permission for group `All Users`, execute `body` then re-grant it. Use it when we need to isolate a user's permissions during tests." [& body] `(try (perms/revoke-application-permissions! (perms-group/all-users) :subscription) ~@body (finally (perms/grant-application-permissions! (perms-group/all-users) :subscription)))) (deftest pulse-permissions-test (testing "/api/pulse/*" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp* [Card [card] Pulse [pulse {:creator_id (u/the-id user)}]] (let [pulse-default {:name "A Pulse" :cards [{:id (:id card) :include_csv true :include_xls false}] :channels [{:enabled true :channel_type "email" :schedule_type "daily" :schedule_hour 12 :recipients []}]} create-pulse (fn [status] (testing "create pulse" (mt/user-http-request user :post status "pulse" pulse-default))) update-pulse (fn [status] (testing "update pulse" (mt/user-http-request user :put status (format "pulse/%d" (:id pulse)) (merge pulse-default {:name "New Name"})))) get-form (fn [status] (testing "get form input" (mt/user-http-request user :get status "pulse/form_input")))] (testing "user's group has no subscription permissions" (perms/revoke-application-permissions! group :subscription) (testing "should succeed if `advanced-permissions` is disabled" (premium-features-test/with-premium-features #{} (create-pulse 200) (update-pulse 200) (get-form 200))) (testing "should fail if `advanced-permissions` is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (create-pulse 403) (update-pulse 403) (get-form 403)))) (testing "User's group with subscription permission" (perms/grant-application-permissions! group :subscription) (premium-features-test/with-premium-features #{:advanced-permissions} (testing "should succeed if `advanced-permissions` is enabled" (create-pulse 200) (update-pulse 200) (get-form 200))))))))) (testing "PUT /api/pulse/:id" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp* [Card [{card-id :id}]] (letfn [(add-pulse-recipient [req-user status] (pulse-test/with-pulse-for-card [the-pulse {:card card-id :pulse {:creator_id (u/the-id user)} :channel :email}] (let [the-pulse (pulse/retrieve-pulse (:id the-pulse)) channel (api.alert/email-channel the-pulse) new-channel (assoc channel :recipients (conj (:recipients channel) (mt/fetch-user :lucky))) new-pulse (assoc the-pulse :channels [new-channel])] (testing (format "- add pulse's recipients with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "pulse/%d" (:id the-pulse)) new-pulse))))) (remove-pulse-recipient [req-user status] (pulse-test/with-pulse-for-card [the-pulse {:card card-id :pulse {:creator_id (u/the-id user)} :channel :email}] ;; manually add another user as recipient (mt/with-temp PulseChannelRecipient [_ {:user_id (:id user) :pulse_channel_id (db/select-one-id PulseChannel :channel_type "email" :pulse_id (:id the-pulse))}] (let [the-pulse (pulse/retrieve-pulse (:id the-pulse)) channel (api.alert/email-channel the-pulse) new-channel (update channel :recipients rest) new-pulse (assoc the-pulse :channels [new-channel])] (testing (format "- remove pulse's recipients with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "pulse/%d" (:id the-pulse)) new-pulse))))))] (testing "anyone could add/remove pulse's recipients if advanced-permissions is disabled" (premium-features-test/with-premium-features #{} (add-pulse-recipient user 200) (remove-pulse-recipient user 200) (add-pulse-recipient :crowberto 200) (remove-pulse-recipient :crowberto 200))) (testing "non-admin can't modify recipients if advanced-permissions is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (add-pulse-recipient user 403) (remove-pulse-recipient user 403) (testing "what if they have monitoring permissions?" (perms/grant-application-permissions! group :monitoring) (testing "they can remove recipients" (remove-pulse-recipient user 200)) (testing "they can't add recipients" (add-pulse-recipient user 403))) (testing "unless subscription permissions" (perms/grant-application-permissions! group :subscription) (add-pulse-recipient user 200)))))))))) (deftest alert-permissions-test (testing "/api/alert/*" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp* [Card [card {:creator_id (:id user)}] Collection [_collection]] (let [alert-default {:card {:id (:id card) :include_csv true :include_xls false :dashboard_card_id nil} :alert_condition "rows" :alert_first_only true :channels [{:enabled true :channel_type "email" :schedule_type "daily" :schedule_hour 12 :recipients []}]} create-alert (fn [status] (testing "create alert" (mt/user-http-request user :post status "alert" alert-default))) user-alert (premium-features-test/with-premium-features #{:advanced-permissions} (perms/grant-application-permissions! group :subscription) (u/prog1 (create-alert 200) (perms/revoke-application-permissions! group :subscription))) update-alert (fn [status] (testing "update alert" (mt/user-http-request user :put status (format "alert/%d" (:id user-alert)) (dissoc (merge alert-default {:alert_condition "goal"}) :channels))))] (testing "user's group has no subscription permissions" (perms/revoke-application-permissions! group :subscription) (testing "should succeed if `advanced-permissions` is disabled" (premium-features-test/with-premium-features #{} (create-alert 200) (update-alert 200))) (testing "should fail if `advanced-permissions` is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (create-alert 403) (update-alert 403)))) (testing "User's group with subscription permission" (perms/grant-application-permissions! group :subscription) (premium-features-test/with-premium-features #{:advanced-permissions} (testing "should succeed if `advanced-permissions` is enabled" (create-alert 200) (update-alert 200))))))))) (testing "PUT /api/alert/:id" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp Card [_] (letfn [(add-alert-recipient [req-user status] (mt/with-temp* [Pulse [alert (alert-test/basic-alert)] Card [card] PulseCard [_ (alert-test/pulse-card alert card)] PulseChannel [pc (alert-test/pulse-channel alert)]] (testing (format "- add alert's recipient with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "alert/%d" (:id alert)) (alert-test/default-alert-req card pc))))) (archive-alert-recipient [req-user status] (mt/with-temp* [Pulse [alert (alert-test/basic-alert)] Card [card] PulseCard [_ (alert-test/pulse-card alert card)] PulseChannel [pc (alert-test/pulse-channel alert)]] (testing (format "- archive alert with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "alert/%d" (:id alert)) (-> (alert-test/default-alert-req card pc) (assoc :archive true) (assoc-in [:channels 0 :recipients] [])))))) (remove-alert-recipient [req-user status] (mt/with-temp* [Pulse [alert (alert-test/basic-alert)] Card [card] PulseCard [_ (alert-test/pulse-card alert card)] PulseChannel [pc (alert-test/pulse-channel alert)] PulseChannelRecipient [_ (alert-test/recipient pc :rasta)]] (testing (format "- remove alert's recipient with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "alert/%d" (:id alert)) (assoc-in (alert-test/default-alert-req card pc) [:channels 0 :recipients] [])))))] (testing "only admin add/remove recipients and archive" (premium-features-test/with-premium-features #{} (add-alert-recipient user 403) (archive-alert-recipient user 403) (remove-alert-recipient user 403) (add-alert-recipient :crowberto 200) (archive-alert-recipient :crowberto 200) (remove-alert-recipient :crowberto 200))) (testing "non-admins can't modify recipients if advanced-permissions is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (add-alert-recipient user 403) (archive-alert-recipient user 403) (remove-alert-recipient user 403) (testing "what if they have monitoring permissions?" (perms/grant-application-permissions! group :monitoring) (testing "they can remove or archive recipients" (archive-alert-recipient user 200) (remove-alert-recipient user 200)) (testing "they can't add recipients" (add-alert-recipient user 403))) (testing "unless have subscription permissions" (perms/grant-application-permissions! group :subscription) (add-alert-recipient user 200))))))))))
null
https://raw.githubusercontent.com/metabase/metabase/0288adb5e4ed8ded2798c03c65c7c54a786903ab/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/subscription_test.clj
clojure
manually add another user as recipient
(ns ^:mb/once metabase-enterprise.advanced-permissions.api.subscription-test "Permisisons tests for API that needs to be enforced by Application Permissions to create and edit alerts/subscriptions." (:require [clojure.test :refer :all] [metabase.api.alert :as api.alert] [metabase.api.alert-test :as alert-test] [metabase.models :refer [Card Collection Pulse PulseCard PulseChannel PulseChannelRecipient]] [metabase.models.permissions :as perms] [metabase.models.permissions-group :as perms-group] [metabase.models.pulse :as pulse] [metabase.public-settings.premium-features-test :as premium-features-test] [metabase.pulse-test :as pulse-test] [metabase.test :as mt] [metabase.util :as u] [toucan.db :as db])) (defmacro ^:private with-subscription-disabled-for-all-users "Temporarily remove `subscription` permission for group `All Users`, execute `body` then re-grant it. Use it when we need to isolate a user's permissions during tests." [& body] `(try (perms/revoke-application-permissions! (perms-group/all-users) :subscription) ~@body (finally (perms/grant-application-permissions! (perms-group/all-users) :subscription)))) (deftest pulse-permissions-test (testing "/api/pulse/*" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp* [Card [card] Pulse [pulse {:creator_id (u/the-id user)}]] (let [pulse-default {:name "A Pulse" :cards [{:id (:id card) :include_csv true :include_xls false}] :channels [{:enabled true :channel_type "email" :schedule_type "daily" :schedule_hour 12 :recipients []}]} create-pulse (fn [status] (testing "create pulse" (mt/user-http-request user :post status "pulse" pulse-default))) update-pulse (fn [status] (testing "update pulse" (mt/user-http-request user :put status (format "pulse/%d" (:id pulse)) (merge pulse-default {:name "New Name"})))) get-form (fn [status] (testing "get form input" (mt/user-http-request user :get status "pulse/form_input")))] (testing "user's group has no subscription permissions" (perms/revoke-application-permissions! group :subscription) (testing "should succeed if `advanced-permissions` is disabled" (premium-features-test/with-premium-features #{} (create-pulse 200) (update-pulse 200) (get-form 200))) (testing "should fail if `advanced-permissions` is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (create-pulse 403) (update-pulse 403) (get-form 403)))) (testing "User's group with subscription permission" (perms/grant-application-permissions! group :subscription) (premium-features-test/with-premium-features #{:advanced-permissions} (testing "should succeed if `advanced-permissions` is enabled" (create-pulse 200) (update-pulse 200) (get-form 200))))))))) (testing "PUT /api/pulse/:id" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp* [Card [{card-id :id}]] (letfn [(add-pulse-recipient [req-user status] (pulse-test/with-pulse-for-card [the-pulse {:card card-id :pulse {:creator_id (u/the-id user)} :channel :email}] (let [the-pulse (pulse/retrieve-pulse (:id the-pulse)) channel (api.alert/email-channel the-pulse) new-channel (assoc channel :recipients (conj (:recipients channel) (mt/fetch-user :lucky))) new-pulse (assoc the-pulse :channels [new-channel])] (testing (format "- add pulse's recipients with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "pulse/%d" (:id the-pulse)) new-pulse))))) (remove-pulse-recipient [req-user status] (pulse-test/with-pulse-for-card [the-pulse {:card card-id :pulse {:creator_id (u/the-id user)} :channel :email}] (mt/with-temp PulseChannelRecipient [_ {:user_id (:id user) :pulse_channel_id (db/select-one-id PulseChannel :channel_type "email" :pulse_id (:id the-pulse))}] (let [the-pulse (pulse/retrieve-pulse (:id the-pulse)) channel (api.alert/email-channel the-pulse) new-channel (update channel :recipients rest) new-pulse (assoc the-pulse :channels [new-channel])] (testing (format "- remove pulse's recipients with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "pulse/%d" (:id the-pulse)) new-pulse))))))] (testing "anyone could add/remove pulse's recipients if advanced-permissions is disabled" (premium-features-test/with-premium-features #{} (add-pulse-recipient user 200) (remove-pulse-recipient user 200) (add-pulse-recipient :crowberto 200) (remove-pulse-recipient :crowberto 200))) (testing "non-admin can't modify recipients if advanced-permissions is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (add-pulse-recipient user 403) (remove-pulse-recipient user 403) (testing "what if they have monitoring permissions?" (perms/grant-application-permissions! group :monitoring) (testing "they can remove recipients" (remove-pulse-recipient user 200)) (testing "they can't add recipients" (add-pulse-recipient user 403))) (testing "unless subscription permissions" (perms/grant-application-permissions! group :subscription) (add-pulse-recipient user 200)))))))))) (deftest alert-permissions-test (testing "/api/alert/*" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp* [Card [card {:creator_id (:id user)}] Collection [_collection]] (let [alert-default {:card {:id (:id card) :include_csv true :include_xls false :dashboard_card_id nil} :alert_condition "rows" :alert_first_only true :channels [{:enabled true :channel_type "email" :schedule_type "daily" :schedule_hour 12 :recipients []}]} create-alert (fn [status] (testing "create alert" (mt/user-http-request user :post status "alert" alert-default))) user-alert (premium-features-test/with-premium-features #{:advanced-permissions} (perms/grant-application-permissions! group :subscription) (u/prog1 (create-alert 200) (perms/revoke-application-permissions! group :subscription))) update-alert (fn [status] (testing "update alert" (mt/user-http-request user :put status (format "alert/%d" (:id user-alert)) (dissoc (merge alert-default {:alert_condition "goal"}) :channels))))] (testing "user's group has no subscription permissions" (perms/revoke-application-permissions! group :subscription) (testing "should succeed if `advanced-permissions` is disabled" (premium-features-test/with-premium-features #{} (create-alert 200) (update-alert 200))) (testing "should fail if `advanced-permissions` is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (create-alert 403) (update-alert 403)))) (testing "User's group with subscription permission" (perms/grant-application-permissions! group :subscription) (premium-features-test/with-premium-features #{:advanced-permissions} (testing "should succeed if `advanced-permissions` is enabled" (create-alert 200) (update-alert 200))))))))) (testing "PUT /api/alert/:id" (with-subscription-disabled-for-all-users (mt/with-user-in-groups [group {:name "New Group"} user [group]] (mt/with-temp Card [_] (letfn [(add-alert-recipient [req-user status] (mt/with-temp* [Pulse [alert (alert-test/basic-alert)] Card [card] PulseCard [_ (alert-test/pulse-card alert card)] PulseChannel [pc (alert-test/pulse-channel alert)]] (testing (format "- add alert's recipient with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "alert/%d" (:id alert)) (alert-test/default-alert-req card pc))))) (archive-alert-recipient [req-user status] (mt/with-temp* [Pulse [alert (alert-test/basic-alert)] Card [card] PulseCard [_ (alert-test/pulse-card alert card)] PulseChannel [pc (alert-test/pulse-channel alert)]] (testing (format "- archive alert with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "alert/%d" (:id alert)) (-> (alert-test/default-alert-req card pc) (assoc :archive true) (assoc-in [:channels 0 :recipients] [])))))) (remove-alert-recipient [req-user status] (mt/with-temp* [Pulse [alert (alert-test/basic-alert)] Card [card] PulseCard [_ (alert-test/pulse-card alert card)] PulseChannel [pc (alert-test/pulse-channel alert)] PulseChannelRecipient [_ (alert-test/recipient pc :rasta)]] (testing (format "- remove alert's recipient with %s user" (mt/user-descriptor req-user)) (mt/user-http-request req-user :put status (format "alert/%d" (:id alert)) (assoc-in (alert-test/default-alert-req card pc) [:channels 0 :recipients] [])))))] (testing "only admin add/remove recipients and archive" (premium-features-test/with-premium-features #{} (add-alert-recipient user 403) (archive-alert-recipient user 403) (remove-alert-recipient user 403) (add-alert-recipient :crowberto 200) (archive-alert-recipient :crowberto 200) (remove-alert-recipient :crowberto 200))) (testing "non-admins can't modify recipients if advanced-permissions is enabled" (premium-features-test/with-premium-features #{:advanced-permissions} (add-alert-recipient user 403) (archive-alert-recipient user 403) (remove-alert-recipient user 403) (testing "what if they have monitoring permissions?" (perms/grant-application-permissions! group :monitoring) (testing "they can remove or archive recipients" (archive-alert-recipient user 200) (remove-alert-recipient user 200)) (testing "they can't add recipients" (add-alert-recipient user 403))) (testing "unless have subscription permissions" (perms/grant-application-permissions! group :subscription) (add-alert-recipient user 200))))))))))
43e3a81056cea5405ef3eeea2c42fd7b2e737ec0062304f748d1adc0d8fa898d
basho/riak_test
ensemble_vnode_crash.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2013 - 2014 Basho Technologies , Inc. %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(ensemble_vnode_crash). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -compile({parse_transform, rt_intercept_pt}). -define(M, riak_kv_ensemble_backend_orig). confirm() -> NumNodes = 5, NVal = 5, Config = ensemble_util:fast_config(NVal), lager:info("Building cluster and waiting for ensemble to stablize"), Nodes = ensemble_util:build_cluster(NumNodes, Config, NVal), vnode_util:load(Nodes), Node = hd(Nodes), ensemble_util:wait_until_stable(Node, NVal), lager:info("Creating/activating 'strong' bucket type"), rt:create_and_activate_bucket_type(Node, <<"strong">>, [{consistent, true}, {n_val, NVal}]), ensemble_util:wait_until_stable(Node, NVal), Bucket = {<<"strong">>, <<"test">>}, Keys = [<<N:64/integer>> || N <- lists:seq(1,1000)], Key1 = hd(Keys), DocIdx = rpc:call(Node, riak_core_util, chash_std_keyfun, [{Bucket, Key1}]), PL = rpc:call(Node, riak_core_apl, get_primary_apl, [DocIdx, NVal, riak_kv]), {{Key1Idx, Key1Node}, _} = hd(PL), PBC = rt:pbc(Node), lager:info("Writing ~p consistent keys", [1000]), [ok = rt:pbc_write(PBC, Bucket, Key, Key) || Key <- Keys], lager:info("Read keys to verify they exist"), [rt:pbc_read(PBC, Bucket, Key) || Key <- Keys], %% Setting up intercept to ensure that %% riak_kv_ensemble_backend:handle_down/4 gets called when a vnode or vnode %% proxy crashes for a given key lager:info("Adding Intercept for riak_kv_ensemble_backend:handle_down/4"), Self = self(), rt_intercept:add(Node, {riak_kv_ensemble_backend, [{{handle_down, 4}, {[Self], fun(Ref, Pid, Reason, State) -> Self ! {handle_down, Reason}, ?M:maybe_async_update_orig(Ref, Pid, Reason, State) end}}]}), {ok, VnodePid} =rpc:call(Key1Node, riak_core_vnode_manager, get_vnode_pid, [Key1Idx, riak_kv_vnode]), lager:info("Killing Vnode ~p for Key1 {~p, ~p}", [VnodePid, Key1Node, Key1Idx]), true = rpc:call(Key1Node, erlang, exit, [VnodePid, testkill]), lager:info("Waiting to receive msg indicating downed vnode"), Count = wait_for_all_handle_downs(0), ?assert(Count > 0), lager:info("Wait for stable ensembles"), ensemble_util:wait_until_stable(Node, NVal), lager:info("Re-reading keys"), [rt:pbc_read(PBC, Bucket, Key) || Key <- Keys], lager:info("Killing Vnode Proxy for Key1"), Proxy = rpc:call(Key1Node, riak_core_vnode_proxy, reg_name, [riak_kv_vnode, Key1Idx]), ProxyPid = rpc:call(Key1Node, erlang, whereis, [Proxy]), lager:info("Killing Vnode Proxy ~p", [Proxy]), true = rpc:call(Key1Node, erlang, exit, [ProxyPid, testkill]), lager:info("Waiting to receive msg indicating downed vnode proxy:"), Count2 = wait_for_all_handle_downs(0), ?assert(Count2 > 0), lager:info("Wait for stable ensembles"), ensemble_util:wait_until_stable(Node, NVal), lager:info("Re-reading keys"), [rt:pbc_read(PBC, Bucket, Key) || Key <- Keys], pass. wait_for_all_handle_downs(Count) -> receive {handle_down, _} -> wait_for_all_handle_downs(Count+1) after 5000 -> Count end.
null
https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/ensemble_vnode_crash.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- Setting up intercept to ensure that riak_kv_ensemble_backend:handle_down/4 gets called when a vnode or vnode proxy crashes for a given key
Copyright ( c ) 2013 - 2014 Basho Technologies , Inc. This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(ensemble_vnode_crash). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -compile({parse_transform, rt_intercept_pt}). -define(M, riak_kv_ensemble_backend_orig). confirm() -> NumNodes = 5, NVal = 5, Config = ensemble_util:fast_config(NVal), lager:info("Building cluster and waiting for ensemble to stablize"), Nodes = ensemble_util:build_cluster(NumNodes, Config, NVal), vnode_util:load(Nodes), Node = hd(Nodes), ensemble_util:wait_until_stable(Node, NVal), lager:info("Creating/activating 'strong' bucket type"), rt:create_and_activate_bucket_type(Node, <<"strong">>, [{consistent, true}, {n_val, NVal}]), ensemble_util:wait_until_stable(Node, NVal), Bucket = {<<"strong">>, <<"test">>}, Keys = [<<N:64/integer>> || N <- lists:seq(1,1000)], Key1 = hd(Keys), DocIdx = rpc:call(Node, riak_core_util, chash_std_keyfun, [{Bucket, Key1}]), PL = rpc:call(Node, riak_core_apl, get_primary_apl, [DocIdx, NVal, riak_kv]), {{Key1Idx, Key1Node}, _} = hd(PL), PBC = rt:pbc(Node), lager:info("Writing ~p consistent keys", [1000]), [ok = rt:pbc_write(PBC, Bucket, Key, Key) || Key <- Keys], lager:info("Read keys to verify they exist"), [rt:pbc_read(PBC, Bucket, Key) || Key <- Keys], lager:info("Adding Intercept for riak_kv_ensemble_backend:handle_down/4"), Self = self(), rt_intercept:add(Node, {riak_kv_ensemble_backend, [{{handle_down, 4}, {[Self], fun(Ref, Pid, Reason, State) -> Self ! {handle_down, Reason}, ?M:maybe_async_update_orig(Ref, Pid, Reason, State) end}}]}), {ok, VnodePid} =rpc:call(Key1Node, riak_core_vnode_manager, get_vnode_pid, [Key1Idx, riak_kv_vnode]), lager:info("Killing Vnode ~p for Key1 {~p, ~p}", [VnodePid, Key1Node, Key1Idx]), true = rpc:call(Key1Node, erlang, exit, [VnodePid, testkill]), lager:info("Waiting to receive msg indicating downed vnode"), Count = wait_for_all_handle_downs(0), ?assert(Count > 0), lager:info("Wait for stable ensembles"), ensemble_util:wait_until_stable(Node, NVal), lager:info("Re-reading keys"), [rt:pbc_read(PBC, Bucket, Key) || Key <- Keys], lager:info("Killing Vnode Proxy for Key1"), Proxy = rpc:call(Key1Node, riak_core_vnode_proxy, reg_name, [riak_kv_vnode, Key1Idx]), ProxyPid = rpc:call(Key1Node, erlang, whereis, [Proxy]), lager:info("Killing Vnode Proxy ~p", [Proxy]), true = rpc:call(Key1Node, erlang, exit, [ProxyPid, testkill]), lager:info("Waiting to receive msg indicating downed vnode proxy:"), Count2 = wait_for_all_handle_downs(0), ?assert(Count2 > 0), lager:info("Wait for stable ensembles"), ensemble_util:wait_until_stable(Node, NVal), lager:info("Re-reading keys"), [rt:pbc_read(PBC, Bucket, Key) || Key <- Keys], pass. wait_for_all_handle_downs(Count) -> receive {handle_down, _} -> wait_for_all_handle_downs(Count+1) after 5000 -> Count end.
428d4736b81b7b913c211b7527163942801bcc6dca1f8290b8c8b7a0b2b45b5b
ivankocienski/lspec
00-basic-examples.lisp
(in-package :cl-user) (defpackage :lspec-example (:use :cl :lspec)) (in-package :lspec-example) (specify "A group of tests" (around-each ;; do some set up (yield) ;; cleanup ) (context "a way of nesting and segmenting tests" (it "is okay" (let ((zero 0)) (expect zero :to-be-zero))) (it "will fail" (let ((not-zero 1)) (expect not-zero :to-be-zero))) (it "should find things" (let ((true t)) (expect true :to-be-true))))) (specify "tests with callback blocks" (around-each ;; set up (format t "around 0 set up~%") (yield) ;; tear down (format t "around 0 tear down~%")) (around-each ;; set up (format t "around 1 set up~%") (yield) ;; tear down (format t "around 1 tear down~%")) (it "should only run above blocks~%" (format t " in C1 spec~%")) (it "should be pending") (it "is also pending" (pending)) (it "is pending with a nice message" (pending "FIXME")) (context "this is a sub context" (around-each ;; set up (format t "around 2 set up~%") (yield) ;; tear down (format t "around 2 tear down~%") ) (it "should run before blocks!" (format t " in spec~%"))) (it "should only be here" (format t " in C1 spec~%")))
null
https://raw.githubusercontent.com/ivankocienski/lspec/489346b7f53692f2ff9c86748a14ebea89eedfd6/examples/00-basic-examples.lisp
lisp
do some set up cleanup set up tear down set up tear down set up tear down
(in-package :cl-user) (defpackage :lspec-example (:use :cl :lspec)) (in-package :lspec-example) (specify "A group of tests" (around-each (yield) ) (context "a way of nesting and segmenting tests" (it "is okay" (let ((zero 0)) (expect zero :to-be-zero))) (it "will fail" (let ((not-zero 1)) (expect not-zero :to-be-zero))) (it "should find things" (let ((true t)) (expect true :to-be-true))))) (specify "tests with callback blocks" (around-each (format t "around 0 set up~%") (yield) (format t "around 0 tear down~%")) (around-each (format t "around 1 set up~%") (yield) (format t "around 1 tear down~%")) (it "should only run above blocks~%" (format t " in C1 spec~%")) (it "should be pending") (it "is also pending" (pending)) (it "is pending with a nice message" (pending "FIXME")) (context "this is a sub context" (around-each (format t "around 2 set up~%") (yield) (format t "around 2 tear down~%") ) (it "should run before blocks!" (format t " in spec~%"))) (it "should only be here" (format t " in C1 spec~%")))
2b785f894be65c4505c873a54561747332e5e78929462460a6aa0bca7d4f988b
ghcjs/ghcjs-dom
SQLTransactionErrorCallback.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.SQLTransactionErrorCallback (newSQLTransactionErrorCallback, newSQLTransactionErrorCallbackSync, newSQLTransactionErrorCallbackAsync, SQLTransactionErrorCallback) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums | < -US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation > newSQLTransactionErrorCallback :: (MonadIO m) => (SQLError -> IO ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallback callback = liftIO (SQLTransactionErrorCallback <$> syncCallback1 ThrowWouldBlock (\ error -> fromJSValUnchecked error >>= \ error' -> callback error')) | < -US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation > newSQLTransactionErrorCallbackSync :: (MonadIO m) => (SQLError -> IO ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallbackSync callback = liftIO (SQLTransactionErrorCallback <$> syncCallback1 ContinueAsync (\ error -> fromJSValUnchecked error >>= \ error' -> callback error')) | < -US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation > newSQLTransactionErrorCallbackAsync :: (MonadIO m) => (SQLError -> IO ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallbackAsync callback = liftIO (SQLTransactionErrorCallback <$> asyncCallback1 (\ error -> fromJSValUnchecked error >>= \ error' -> callback error'))
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SQLTransactionErrorCallback.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.SQLTransactionErrorCallback (newSQLTransactionErrorCallback, newSQLTransactionErrorCallbackSync, newSQLTransactionErrorCallbackAsync, SQLTransactionErrorCallback) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums | < -US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation > newSQLTransactionErrorCallback :: (MonadIO m) => (SQLError -> IO ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallback callback = liftIO (SQLTransactionErrorCallback <$> syncCallback1 ThrowWouldBlock (\ error -> fromJSValUnchecked error >>= \ error' -> callback error')) | < -US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation > newSQLTransactionErrorCallbackSync :: (MonadIO m) => (SQLError -> IO ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallbackSync callback = liftIO (SQLTransactionErrorCallback <$> syncCallback1 ContinueAsync (\ error -> fromJSValUnchecked error >>= \ error' -> callback error')) | < -US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation > newSQLTransactionErrorCallbackAsync :: (MonadIO m) => (SQLError -> IO ()) -> m SQLTransactionErrorCallback newSQLTransactionErrorCallbackAsync callback = liftIO (SQLTransactionErrorCallback <$> asyncCallback1 (\ error -> fromJSValUnchecked error >>= \ error' -> callback error'))
d99c57df673717aad2302638cb2d8047a5088b39b535c1a49f0212a12e9eec49
ghc/packages-Cabal
CabalLanguage.hs
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -freduction-depth=0 #-} #else {-# OPTIONS_GHC -fcontext-stack=151 #-} #endif # OPTIONS_GHC -fno - warn - orphans # module Data.TreeDiff.Instances.CabalLanguage () where import Data.TreeDiff import Language.Haskell.Extension (Extension, KnownExtension, Language) -- These are big enums, so they are in separate file. -- instance ToExpr Extension instance ToExpr KnownExtension instance ToExpr Language
null
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Cabal-tree-diff/src/Data/TreeDiff/Instances/CabalLanguage.hs
haskell
# OPTIONS_GHC -freduction-depth=0 # # OPTIONS_GHC -fcontext-stack=151 # These are big enums, so they are in separate file.
# LANGUAGE CPP # #if __GLASGOW_HASKELL__ >= 800 #else #endif # OPTIONS_GHC -fno - warn - orphans # module Data.TreeDiff.Instances.CabalLanguage () where import Data.TreeDiff import Language.Haskell.Extension (Extension, KnownExtension, Language) instance ToExpr Extension instance ToExpr KnownExtension instance ToExpr Language
11d9deb1164f2c90095ae756d99a357ab418a1be34ce2fecd5c8d59b2b646509
glondu/belenios
group.ml
(**************************************************************************) (* BELENIOS *) (* *) Copyright © 2012 - 2023 (* *) (* This program is free software: you can redistribute it and/or modify *) it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the (* License, or (at your option) any later version, with the additional *) exemption that compiling , linking , and/or using OpenSSL is allowed . (* *) (* This program is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) (* Affero General Public License for more details. *) (* *) You should have received a copy of the GNU Affero General Public (* License along with this program. If not, see *) (* </>. *) (**************************************************************************) open Belenios_platform open Platform open Belenios_core open Serializable_j open Signatures let get_ff_params = function | "BELENIOS-2048" -> { g = Z.of_string "2402352677501852209227687703532399932712287657378364916510075318787663274146353219320285676155269678799694668298749389095083896573425601900601068477164491735474137283104610458681314511781646755400527402889846139864532661215055797097162016168270312886432456663834863635782106154918419982534315189740658186868651151358576410138882215396016043228843603930989333662772848406593138406010231675095763777982665103606822406635076697764025346253773085133173495194248967754052573659049492477631475991575198775177711481490920456600205478127054728238140972518639858334115700568353695553423781475582491896050296680037745308460627"; p = Z.of_string "20694785691422546401013643657505008064922989295751104097100884787057374219242717401922237254497684338129066633138078958404960054389636289796393038773905722803605973749427671376777618898589872735865049081167099310535867780980030790491654063777173764198678527273474476341835600035698305193144284561701911000786737307333564123971732897913240474578834468260652327974647951137672658693582180046317922073668860052627186363386088796882120769432366149491002923444346373222145884100586421050242120365433561201320481118852408731077014151666200162313177169372189248078507711827842317498073276598828825169183103125680162072880719"; q = Z.of_string "78571733251071885079927659812671450121821421258408794611510081919805623223441"; embedding = None; } | "RFC-3526-2048" -> { g = Z.of_string "2"; p = Z.of_string "32317006071311007300338913926423828248817941241140239112842009751400741706634354222619689417363569347117901737909704191754605873209195028853758986185622153212175412514901774520270235796078236248884246189477587641105928646099411723245426622522193230540919037680524235519125679715870117001058055877651038861847280257976054903569732561526167081339361799541336476559160368317896729073178384589680639671900977202194168647225871031411336429319536193471636533209717077448227988588565369208645296636077250268955505928362751121174096972998068410554359584866583291642136218231078990999448652468262416972035911852507045361090559"; q = Z.of_string "16158503035655503650169456963211914124408970620570119556421004875700370853317177111309844708681784673558950868954852095877302936604597514426879493092811076606087706257450887260135117898039118124442123094738793820552964323049705861622713311261096615270459518840262117759562839857935058500529027938825519430923640128988027451784866280763083540669680899770668238279580184158948364536589192294840319835950488601097084323612935515705668214659768096735818266604858538724113994294282684604322648318038625134477752964181375560587048486499034205277179792433291645821068109115539495499724326234131208486017955926253522680545279"; embedding = Some {padding = 8; bits_per_int = 8}; } | _ -> raise Not_found let ed25519 () : (module GROUP) = match libsodium_stubs () with | None -> (module Ed25519_pure) | Some stubs -> let module S = (val stubs) in let module G = Ed25519_libsodium.Make (S) in (module G) let of_string x = match get_ff_params x with | params -> let module G = (val Group_field.make x params : Group_field.GROUP) in (module G : GROUP) | exception Not_found -> match x with | "Ed25519" -> ed25519 () | _ -> Printf.ksprintf failwith "unknown group: %s" x
null
https://raw.githubusercontent.com/glondu/belenios/5306402c15c6a76438b13b8b9da0f45d02a0563d/src/lib/v1/group.ml
ocaml
************************************************************************ BELENIOS This program is free software: you can redistribute it and/or modify License, or (at your option) any later version, with the additional This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. License along with this program. If not, see </>. ************************************************************************
Copyright © 2012 - 2023 it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the exemption that compiling , linking , and/or using OpenSSL is allowed . You should have received a copy of the GNU Affero General Public open Belenios_platform open Platform open Belenios_core open Serializable_j open Signatures let get_ff_params = function | "BELENIOS-2048" -> { g = Z.of_string "2402352677501852209227687703532399932712287657378364916510075318787663274146353219320285676155269678799694668298749389095083896573425601900601068477164491735474137283104610458681314511781646755400527402889846139864532661215055797097162016168270312886432456663834863635782106154918419982534315189740658186868651151358576410138882215396016043228843603930989333662772848406593138406010231675095763777982665103606822406635076697764025346253773085133173495194248967754052573659049492477631475991575198775177711481490920456600205478127054728238140972518639858334115700568353695553423781475582491896050296680037745308460627"; p = Z.of_string "20694785691422546401013643657505008064922989295751104097100884787057374219242717401922237254497684338129066633138078958404960054389636289796393038773905722803605973749427671376777618898589872735865049081167099310535867780980030790491654063777173764198678527273474476341835600035698305193144284561701911000786737307333564123971732897913240474578834468260652327974647951137672658693582180046317922073668860052627186363386088796882120769432366149491002923444346373222145884100586421050242120365433561201320481118852408731077014151666200162313177169372189248078507711827842317498073276598828825169183103125680162072880719"; q = Z.of_string "78571733251071885079927659812671450121821421258408794611510081919805623223441"; embedding = None; } | "RFC-3526-2048" -> { g = Z.of_string "2"; p = Z.of_string "32317006071311007300338913926423828248817941241140239112842009751400741706634354222619689417363569347117901737909704191754605873209195028853758986185622153212175412514901774520270235796078236248884246189477587641105928646099411723245426622522193230540919037680524235519125679715870117001058055877651038861847280257976054903569732561526167081339361799541336476559160368317896729073178384589680639671900977202194168647225871031411336429319536193471636533209717077448227988588565369208645296636077250268955505928362751121174096972998068410554359584866583291642136218231078990999448652468262416972035911852507045361090559"; q = Z.of_string "16158503035655503650169456963211914124408970620570119556421004875700370853317177111309844708681784673558950868954852095877302936604597514426879493092811076606087706257450887260135117898039118124442123094738793820552964323049705861622713311261096615270459518840262117759562839857935058500529027938825519430923640128988027451784866280763083540669680899770668238279580184158948364536589192294840319835950488601097084323612935515705668214659768096735818266604858538724113994294282684604322648318038625134477752964181375560587048486499034205277179792433291645821068109115539495499724326234131208486017955926253522680545279"; embedding = Some {padding = 8; bits_per_int = 8}; } | _ -> raise Not_found let ed25519 () : (module GROUP) = match libsodium_stubs () with | None -> (module Ed25519_pure) | Some stubs -> let module S = (val stubs) in let module G = Ed25519_libsodium.Make (S) in (module G) let of_string x = match get_ff_params x with | params -> let module G = (val Group_field.make x params : Group_field.GROUP) in (module G : GROUP) | exception Not_found -> match x with | "Ed25519" -> ed25519 () | _ -> Printf.ksprintf failwith "unknown group: %s" x
aa0e63050f4063fd9df7051d582b8313a2a8ef20c1ed54f9bb7aad1f635653a0
adamschoenemann/clofrp
RecSpec.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE OverloadedLists # # LANGUAGE QuasiQuotes # {-# LANGUAGE RankNTypes #-} module CloFRP.Check.RecSpec where import Test.Tasty.Hspec import CloFRP.Check.TestUtils import CloFRP.TestUtils import CloFRP.QuasiQuoter import CloFRP.Check.Prog import CloFRP.Check.TypingM import CloFRP.Pretty import CloFRP.AST.Name recSpec :: Spec recSpec = do -- let errs e x = fst x `shouldBe` e describe "recursive types" $ do it "works in very simple cases (Nat)" $ do let Right prog = pprog [text| data NatF a = Z | S a deriving Functor. type Nat = Fix NatF. foldNat' : NatF (Fix NatF) -> Fix NatF. foldNat' = \m -> fold m. foldNat : NatF Nat -> Nat. foldNat = \m -> fold m. foldNatPF : NatF Nat -> Nat. foldNatPF = fold. unfoldNat' : Fix NatF -> NatF (Fix NatF). unfoldNat' = \m -> unfold m. unfoldNat : Nat -> NatF Nat. unfoldNat = \m -> unfold m. unfoldNatPF : Nat -> NatF Nat. unfoldNatPF = unfold. zero : Nat. zero = fold Z. one : Nat. one = fold (S (fold Z)). |] runCheckProg mempty prog `shouldYield` () it "works in slightly more complex case (Nat)" $ do let Right prog = pprog [text| data NatF a = Z | S a. type Nat = Fix NatF. unfoldFold : Nat -> Nat. unfoldFold = \m -> fold (unfold m). foldUnfold : NatF Nat -> NatF Nat. foldUnfold = \m -> unfold (fold m). |] runCheckProg mempty prog `shouldYield` () it "works with some pattern matching (Nat)" $ do let Right prog = pprog [text| data NatF a = Z | S a. type Nat = Fix NatF. pred : Nat -> Nat. pred = \m -> case unfold m of | Z -> fold Z | S m' -> m' end. pred2 : Nat -> Nat. pred2 = \m -> case unfold m of | S m' -> case unfold m' of | Z -> fold Z | S m'' -> m'' end | Z -> fold Z end. succ : Nat -> Nat. succ = \x -> fold (S x). plus2 : Nat -> Nat. plus2 = \x -> fold (S (fold (S x))). |] runCheckProg mempty prog `shouldYield` () it "works in very simple cases (List)" $ do let Right prog = pprog [text| data ListF a f = Nil | Cons a f. type List a = Fix (ListF a). foldList' : forall a. ListF a (Fix (ListF a)) -> Fix (ListF a). foldList' = \m -> fold m. foldList : forall a. ListF a (List a) -> List a. foldList = \m -> fold m. unfoldList' : forall a. (Fix (ListF a)) -> ListF a (Fix (ListF a)). unfoldList' = \m -> unfold m. unfoldList : forall a. List a -> ListF a (List a). unfoldList = \m -> unfold m. nil : forall a. List a. nil = fold Nil. cons : forall a. a -> List a -> List a. cons = \x xs -> fold (Cons x xs). |] runCheckProg mempty prog `shouldYield` () it "works with some pattern matching (List)" $ do let Right prog = pprog [text| data ListF a f = Nil | Cons a f. type List a = Fix (ListF a). data Maybe a = Nothing | Just a. foldList : forall a. ListF a (List a) -> List a. foldList = \x -> fold x. head : forall a. List a -> Maybe a. head = \xs -> case unfold xs of | Nil -> Nothing | Cons x xs' -> Just x end. singleton : forall a. a -> List a. singleton = \x -> fold (Cons x (fold Nil)). singleton' : forall a. a -> List a. singleton' = \x -> foldList (Cons x (foldList Nil)). |] runCheckProg mempty prog `shouldYield` () it "works with Trees" $ do let Right prog = pprog [text| data TreeF a f = Empty | Branch a f f. type Tree a = Fix (TreeF a). data NatF a = Z | S a. type Nat = Fix NatF. data Maybe a = Nothing | Just a. data Triple a b c = Triple a b c. empty : forall a. Tree a. empty = fold Empty. branch : forall a. a -> Tree a -> Tree a -> Tree a. branch = \x l r -> fold (Branch x l r). treeMatch : forall a. Tree a -> Maybe (Triple a (Tree a) (Tree a)). treeMatch = \t -> case unfold t of | Empty -> Nothing | Branch x l r -> Just (Triple x l r) end. nonsense : forall a. Tree a -> Nat. nonsense = \t -> case unfold t of | Empty -> fold Z | Branch x l r -> fold (S (fold Z)) end. |] runCheckProg mempty prog `shouldYield` () specify "primRec with Nat" $ do let Right prog = pprog [text| data NatF a = Z | S a deriving Functor. type Nat = Fix NatF. plusRec : Nat -> NatF (Nat, Nat) -> Nat. plusRec = \n x -> case x of | Z -> n | S (m', r) -> fold (S r) end. -- without annotations :O plus : Nat -> Nat -> Nat. plus = \m n -> let body = \x -> case x of | Z -> n | S (m', r) -> fold (S r) end in primRec {NatF} body m. multRec : Nat -> NatF (Nat, Nat) -> Nat. multRec = \n x -> case x of | Z -> fold Z | S (m', r) -> plus n r end. mult : Nat -> Nat -> Nat. mult = \m n -> primRec {NatF} (multRec n) m. -- without annotations :O mult' : Nat -> Nat -> Nat. mult' = \m n -> let body = \x -> case x of | Z -> fold Z | S (m', r) -> plus n r end in primRec {NatF} body m. |] runCheckProg mempty prog `shouldYield` () specify "primRec with List" $ do let Right prog = pprog [text| data ListF a f = Nil | Cons a f deriving Functor. type List a = Fix (ListF a). mapRec : forall a b. (a -> b) -> ListF a (List a, List b) -> List b. mapRec = \f l-> case l of | Nil -> fold Nil | Cons x (xs, ys) -> fold (Cons (f x) ys) end. map : forall a b. (a -> b) -> List a -> List b. map = \f xs -> primRec {ListF a} (mapRec f) xs. -- without annotations :O map' : forall a b. (a -> b) -> List a -> List b. map' = \f xs -> let body = \x -> case x of | Nil -> fold Nil | Cons x (xs, ys) -> fold (Cons (f x) ys) end in primRec {ListF a} body xs. type Fmap (f : * -> *) = forall a b. (a -> b) -> f a -> f b. data Functor (f : * -> *) = Functor (Fmap f). -- we have to wrap it in a "newtype" to make it a functor data ListW a = ListW (Fix (ListF a)). listf : forall a. Functor ListW. listf = Functor (\f l -> case l of | ListW ls -> ListW (map f ls) end ). |] runCheckProg mempty prog `shouldYield` () specify "primRec with Tree" $ do let Right prog = pprog [text| data TreeF a f = Empty | Branch a f f deriving Functor. type Tree a = Fix (TreeF a). mapRec : forall a b. (a -> b) -> TreeF a (Tree a, Tree b) -> Tree b. mapRec = \f t -> case t of | Empty -> fold Empty | Branch x (l, lrec) (r, rrec) -> fold (Branch (f x) lrec rrec) end. map : forall a b. (a -> b) -> Tree a -> Tree b. map = \f xs -> primRec {TreeF a} (mapRec f) xs. -- -- without annotations :O map' : forall a b. (a -> b) -> Tree a -> Tree b. map' = \f xs -> let body = \t -> case t of | Empty -> fold Empty | Branch x (l, lrec) (r, rrec) -> fold (Branch (f x) lrec rrec) end in primRec {TreeF a} body xs. |] runCheckProg mempty prog `shouldYield` ()
null
https://raw.githubusercontent.com/adamschoenemann/clofrp/c26f86aec2cdb8fa7fd317acd13f7d77af984bd3/test-suite/CloFRP/Check/RecSpec.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # let errs e x = fst x `shouldBe` e without annotations :O without annotations :O without annotations :O we have to wrap it in a "newtype" to make it a functor -- without annotations :O
# LANGUAGE OverloadedLists # # LANGUAGE QuasiQuotes # module CloFRP.Check.RecSpec where import Test.Tasty.Hspec import CloFRP.Check.TestUtils import CloFRP.TestUtils import CloFRP.QuasiQuoter import CloFRP.Check.Prog import CloFRP.Check.TypingM import CloFRP.Pretty import CloFRP.AST.Name recSpec :: Spec recSpec = do describe "recursive types" $ do it "works in very simple cases (Nat)" $ do let Right prog = pprog [text| data NatF a = Z | S a deriving Functor. type Nat = Fix NatF. foldNat' : NatF (Fix NatF) -> Fix NatF. foldNat' = \m -> fold m. foldNat : NatF Nat -> Nat. foldNat = \m -> fold m. foldNatPF : NatF Nat -> Nat. foldNatPF = fold. unfoldNat' : Fix NatF -> NatF (Fix NatF). unfoldNat' = \m -> unfold m. unfoldNat : Nat -> NatF Nat. unfoldNat = \m -> unfold m. unfoldNatPF : Nat -> NatF Nat. unfoldNatPF = unfold. zero : Nat. zero = fold Z. one : Nat. one = fold (S (fold Z)). |] runCheckProg mempty prog `shouldYield` () it "works in slightly more complex case (Nat)" $ do let Right prog = pprog [text| data NatF a = Z | S a. type Nat = Fix NatF. unfoldFold : Nat -> Nat. unfoldFold = \m -> fold (unfold m). foldUnfold : NatF Nat -> NatF Nat. foldUnfold = \m -> unfold (fold m). |] runCheckProg mempty prog `shouldYield` () it "works with some pattern matching (Nat)" $ do let Right prog = pprog [text| data NatF a = Z | S a. type Nat = Fix NatF. pred : Nat -> Nat. pred = \m -> case unfold m of | Z -> fold Z | S m' -> m' end. pred2 : Nat -> Nat. pred2 = \m -> case unfold m of | S m' -> case unfold m' of | Z -> fold Z | S m'' -> m'' end | Z -> fold Z end. succ : Nat -> Nat. succ = \x -> fold (S x). plus2 : Nat -> Nat. plus2 = \x -> fold (S (fold (S x))). |] runCheckProg mempty prog `shouldYield` () it "works in very simple cases (List)" $ do let Right prog = pprog [text| data ListF a f = Nil | Cons a f. type List a = Fix (ListF a). foldList' : forall a. ListF a (Fix (ListF a)) -> Fix (ListF a). foldList' = \m -> fold m. foldList : forall a. ListF a (List a) -> List a. foldList = \m -> fold m. unfoldList' : forall a. (Fix (ListF a)) -> ListF a (Fix (ListF a)). unfoldList' = \m -> unfold m. unfoldList : forall a. List a -> ListF a (List a). unfoldList = \m -> unfold m. nil : forall a. List a. nil = fold Nil. cons : forall a. a -> List a -> List a. cons = \x xs -> fold (Cons x xs). |] runCheckProg mempty prog `shouldYield` () it "works with some pattern matching (List)" $ do let Right prog = pprog [text| data ListF a f = Nil | Cons a f. type List a = Fix (ListF a). data Maybe a = Nothing | Just a. foldList : forall a. ListF a (List a) -> List a. foldList = \x -> fold x. head : forall a. List a -> Maybe a. head = \xs -> case unfold xs of | Nil -> Nothing | Cons x xs' -> Just x end. singleton : forall a. a -> List a. singleton = \x -> fold (Cons x (fold Nil)). singleton' : forall a. a -> List a. singleton' = \x -> foldList (Cons x (foldList Nil)). |] runCheckProg mempty prog `shouldYield` () it "works with Trees" $ do let Right prog = pprog [text| data TreeF a f = Empty | Branch a f f. type Tree a = Fix (TreeF a). data NatF a = Z | S a. type Nat = Fix NatF. data Maybe a = Nothing | Just a. data Triple a b c = Triple a b c. empty : forall a. Tree a. empty = fold Empty. branch : forall a. a -> Tree a -> Tree a -> Tree a. branch = \x l r -> fold (Branch x l r). treeMatch : forall a. Tree a -> Maybe (Triple a (Tree a) (Tree a)). treeMatch = \t -> case unfold t of | Empty -> Nothing | Branch x l r -> Just (Triple x l r) end. nonsense : forall a. Tree a -> Nat. nonsense = \t -> case unfold t of | Empty -> fold Z | Branch x l r -> fold (S (fold Z)) end. |] runCheckProg mempty prog `shouldYield` () specify "primRec with Nat" $ do let Right prog = pprog [text| data NatF a = Z | S a deriving Functor. type Nat = Fix NatF. plusRec : Nat -> NatF (Nat, Nat) -> Nat. plusRec = \n x -> case x of | Z -> n | S (m', r) -> fold (S r) end. plus : Nat -> Nat -> Nat. plus = \m n -> let body = \x -> case x of | Z -> n | S (m', r) -> fold (S r) end in primRec {NatF} body m. multRec : Nat -> NatF (Nat, Nat) -> Nat. multRec = \n x -> case x of | Z -> fold Z | S (m', r) -> plus n r end. mult : Nat -> Nat -> Nat. mult = \m n -> primRec {NatF} (multRec n) m. mult' : Nat -> Nat -> Nat. mult' = \m n -> let body = \x -> case x of | Z -> fold Z | S (m', r) -> plus n r end in primRec {NatF} body m. |] runCheckProg mempty prog `shouldYield` () specify "primRec with List" $ do let Right prog = pprog [text| data ListF a f = Nil | Cons a f deriving Functor. type List a = Fix (ListF a). mapRec : forall a b. (a -> b) -> ListF a (List a, List b) -> List b. mapRec = \f l-> case l of | Nil -> fold Nil | Cons x (xs, ys) -> fold (Cons (f x) ys) end. map : forall a b. (a -> b) -> List a -> List b. map = \f xs -> primRec {ListF a} (mapRec f) xs. map' : forall a b. (a -> b) -> List a -> List b. map' = \f xs -> let body = \x -> case x of | Nil -> fold Nil | Cons x (xs, ys) -> fold (Cons (f x) ys) end in primRec {ListF a} body xs. type Fmap (f : * -> *) = forall a b. (a -> b) -> f a -> f b. data Functor (f : * -> *) = Functor (Fmap f). data ListW a = ListW (Fix (ListF a)). listf : forall a. Functor ListW. listf = Functor (\f l -> case l of | ListW ls -> ListW (map f ls) end ). |] runCheckProg mempty prog `shouldYield` () specify "primRec with Tree" $ do let Right prog = pprog [text| data TreeF a f = Empty | Branch a f f deriving Functor. type Tree a = Fix (TreeF a). mapRec : forall a b. (a -> b) -> TreeF a (Tree a, Tree b) -> Tree b. mapRec = \f t -> case t of | Empty -> fold Empty | Branch x (l, lrec) (r, rrec) -> fold (Branch (f x) lrec rrec) end. map : forall a b. (a -> b) -> Tree a -> Tree b. map = \f xs -> primRec {TreeF a} (mapRec f) xs. map' : forall a b. (a -> b) -> Tree a -> Tree b. map' = \f xs -> let body = \t -> case t of | Empty -> fold Empty | Branch x (l, lrec) (r, rrec) -> fold (Branch (f x) lrec rrec) end in primRec {TreeF a} body xs. |] runCheckProg mempty prog `shouldYield` ()
2d93ffb3e03dc478d3d0696b589b3d5973b163b4ee4086643f31a19ec20aba0b
np/ling
Fmt.hs
module Ling.Fmt where import System.Environment (getArgs) import System.Exit (exitFailure) import System.IO import Ling.ErrM import Ling.Fmt.Albert.Abs as A import Ling.Fmt.Albert.Layout as A import Ling.Fmt.Albert.Migrate as A import Ling.Fmt.Albert.Par as A import Ling.Fmt.Benjamin.Abs as B import Ling.Fmt.Benjamin.Layout as B import Ling.Fmt.Benjamin.Migrate as B import Ling.Fmt.Benjamin.Par as B import Ling.Print import Ling.Prelude runFile :: FilePath -> IO () runFile f = hPutStrLn stderr f >> readFile f >>= run parseA :: String -> Err A.Program parseA = A.pProgram . A.resolveLayout True . A.myLexer parseB :: String -> Err B.Program parseB = B.pProgram . B.resolveLayout True . B.myLexer (<<|>>) :: Err a -> Err a -> Err a Ok tree <<|>> _ = Ok tree _ <<|>> Ok tree = Ok tree Bad err0 <<|>> Bad err1 = Bad (err0 <> "\n\n" <> err1) run :: String -> IO () run s = case (B.transProgram <$> parseB s) <<|>> (B.transProgram . A.transProgram <$> parseA s) of Bad err -> do putStrLn "\nParse Failed...\n" putStrLn err exitFailure Ok tree -> putStrLn . pretty $ tree usage :: IO () usage = do putStrLn $ unlines [ "usage: Call with one of the following argument combinations:" , " --help Display this help message." , " (no arguments) Parse stdin." , " (files) Parse content of files." ] exitFailure main :: IO () main = do args <- getArgs case args of ["--help"] -> usage [] -> getContents >>= run "-s":fs -> for_ fs runFile fs -> for_ fs runFile
null
https://raw.githubusercontent.com/np/ling/ca942db83ac927420d1ae5e24b4da164394ddbbe/Ling/Fmt.hs
haskell
module Ling.Fmt where import System.Environment (getArgs) import System.Exit (exitFailure) import System.IO import Ling.ErrM import Ling.Fmt.Albert.Abs as A import Ling.Fmt.Albert.Layout as A import Ling.Fmt.Albert.Migrate as A import Ling.Fmt.Albert.Par as A import Ling.Fmt.Benjamin.Abs as B import Ling.Fmt.Benjamin.Layout as B import Ling.Fmt.Benjamin.Migrate as B import Ling.Fmt.Benjamin.Par as B import Ling.Print import Ling.Prelude runFile :: FilePath -> IO () runFile f = hPutStrLn stderr f >> readFile f >>= run parseA :: String -> Err A.Program parseA = A.pProgram . A.resolveLayout True . A.myLexer parseB :: String -> Err B.Program parseB = B.pProgram . B.resolveLayout True . B.myLexer (<<|>>) :: Err a -> Err a -> Err a Ok tree <<|>> _ = Ok tree _ <<|>> Ok tree = Ok tree Bad err0 <<|>> Bad err1 = Bad (err0 <> "\n\n" <> err1) run :: String -> IO () run s = case (B.transProgram <$> parseB s) <<|>> (B.transProgram . A.transProgram <$> parseA s) of Bad err -> do putStrLn "\nParse Failed...\n" putStrLn err exitFailure Ok tree -> putStrLn . pretty $ tree usage :: IO () usage = do putStrLn $ unlines [ "usage: Call with one of the following argument combinations:" , " --help Display this help message." , " (no arguments) Parse stdin." , " (files) Parse content of files." ] exitFailure main :: IO () main = do args <- getArgs case args of ["--help"] -> usage [] -> getContents >>= run "-s":fs -> for_ fs runFile fs -> for_ fs runFile
2b204a79231e9b8a321c7b484ca7ce7d0231fe96f261f2586e5eca8badbe6bf4
kelamg/HtDP2e-workthrough
ex35.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 ex35) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) ; String -> 1String ; extracts the last character from a non-empty string ; given: ; "Datboi" for str ; expected: ; "i" (define (string-last str) (if (> (string-length str) 0) (string-ith str (- (string-length str) 1)) "supplied an empty string")) (string-last "Datboi")
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Fixed-size-Data/ex35.rkt
racket
about the language level of this file in a form that our tools can easily process. String -> 1String extracts the last character from a non-empty string given: "Datboi" for str expected: "i"
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex35) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (define (string-last str) (if (> (string-length str) 0) (string-ith str (- (string-length str) 1)) "supplied an empty string")) (string-last "Datboi")
ce228cdeb15c63b88009340dc6f3ebeca54bdff927da7af44a2e0eceb982a1f1
schemeway/lalr-scm
calc.scm
;;; ;;;; Simple calculator in Scheme ;;; ;; ;; This program illustrates the use of the lalr-scm parser generator ;; for Scheme. It is NOT robust, since calling a function with ;; the wrong number of arguments may generate an error that will ;; cause the calculator to crash. ;;; ;;;; The LALR(1) parser ;;; (define calc-parser (lalr-parser ;; --- Options ;; output a parser, called calc-parser, in a separate file - calc.yy.scm, (output: calc-parser "calc.yy.scm") output the LALR table to calc.out (out-table: "calc.out") ;; there should be no conflict (expect: 5) ;; --- token definitions (ID NUM = LPAREN RPAREN NEWLINE COMMA (left: + -) (left: * /) (nonassoc: uminus)) (lines (lines line) : (display-result $2) (line) : (display-result $1)) ;; --- rules (line (assign NEWLINE) : $1 (expr NEWLINE) : $1 (NEWLINE) : #f (error NEWLINE) : #f) (assign (ID = expr) : (add-binding $1 $3)) (expr (expr + expr) : (+ $1 $3) (expr - expr) : (- $1 $3) (expr * expr) : (* $1 $3) (expr / expr) : (/ $1 $3) (- expr (prec: uminus)) : (- $2) (ID) : (get-binding $1) (ID LPAREN args RPAREN) : (invoke-proc $1 $3) (NUM) : $1 (LPAREN expr RPAREN) : $2) (args () : '() (expr arg-rest) : (cons $1 $2)) (arg-rest (COMMA expr arg-rest) : (cons $2 $3) () : '()))) ;;; ;;;; The lexer ;;; (cond-expand (gambit (define port-line input-port-line) (define port-column input-port-column)) (chicken (define (force-output) #f) (define (port-line port) (let-values (((line _) (port-position port))) line)) (define (port-column port) (let-values (((_ column) (port-position port))) column))) (guile (define (port-line port) '??) (define (port-column port) '??)) (else (define (force-output) #f) (define (port-line port) '??) (define (port-column port) '??))) (define (make-lexer errorp) (lambda () (letrec ((skip-spaces (lambda () (let loop ((c (peek-char))) (if (and (not (eof-object? c)) (or (char=? c #\space) (char=? c #\tab))) (begin (read-char) (loop (peek-char))))))) (read-number (lambda (l) (let ((c (peek-char))) (if (char-numeric? c) (read-number (cons (read-char) l)) (string->number (apply string (reverse l))))))) (read-id (lambda (l) (let ((c (peek-char))) (if (char-alphabetic? c) (read-id (cons (read-char) l)) (string->symbol (apply string (reverse l)))))))) ;; -- skip spaces (skip-spaces) ;; -- read the next token (let loop () (let* ((location (make-source-location "*stdin*" (port-line (current-input-port)) (port-column (current-input-port)) -1 -1)) (c (read-char))) (cond ((eof-object? c) '*eoi*) ((char=? c #\newline) (make-lexical-token 'NEWLINE location #f)) ((char=? c #\+) (make-lexical-token '+ location #f)) ((char=? c #\-) (make-lexical-token '- location #f)) ((char=? c #\*) (make-lexical-token '* location #f)) ((char=? c #\/) (make-lexical-token '/ location #f)) ((char=? c #\=) (make-lexical-token '= location #f)) ((char=? c #\,) (make-lexical-token 'COMMA location #f)) ((char=? c #\() (make-lexical-token 'LPAREN location #f)) ((char=? c #\)) (make-lexical-token 'RPAREN location #f)) ((char-numeric? c) (make-lexical-token 'NUM location (read-number (list c)))) ((char-alphabetic? c) (make-lexical-token 'ID location (read-id (list c)))) (else (errorp "PARSE ERROR : illegal character: " c) (skip-spaces) (loop)))))))) ;;; ;;;; Environment management ;;; (define *env* (list (cons '$$ 0))) (define (init-bindings) (set-cdr! *env* '()) (add-binding 'cos cos) (add-binding 'sin sin) (add-binding 'tan tan) (add-binding 'expt expt) (add-binding 'sqrt sqrt)) (define (add-binding var val) (set! *env* (cons (cons var val) *env*)) val) (define (get-binding var) (let ((p (assq var *env*))) (if p (cdr p) 0))) (define (invoke-proc proc-name args) (let ((proc (get-binding proc-name))) (if (procedure? proc) (apply proc args) (begin (display "ERROR: invalid procedure:") (display proc-name) (newline) 0)))) ;;; ;;;; The main program ;;; (define (display-result v) (if v (begin (display v) (newline))) (display-prompt)) (define (display-prompt) (display "[calculator]> ") (force-output)) (define calc (lambda () (call-with-current-continuation (lambda (k) (display "********************************") (newline) (display "* Mini calculator in Scheme *") (newline) (display "* *") (newline) (display "* Enter expressions followed *") (newline) (display "* by [RETURN] or 'quit()' to *") (newline) (display "* exit. *") (newline) (display "********************************") (newline) (init-bindings) (add-binding 'quit (lambda () (k #t))) (letrec ((errorp (lambda (message . args) (display message) (if (and (pair? args) (lexical-token? (car args))) (let ((token (car args))) (display (or (lexical-token-value token) (lexical-token-category token))) (let ((source (lexical-token-source token))) (if (source-location? source) (let ((line (source-location-line source)) (column (source-location-column source))) (if (and (number? line) (number? column)) (begin (display " (at line ") (display line) (display ", column ") (display (+ 1 column)) (display ")"))))))) (for-each display args)) (newline))) (start (lambda () (calc-parser (make-lexer errorp) errorp)))) (display-prompt) (start)))))) (calc)
null
https://raw.githubusercontent.com/schemeway/lalr-scm/e3048fae5809b2869c654bb301e92f6d84d5b0be/calc.scm
scheme
Simple calculator in Scheme This program illustrates the use of the lalr-scm parser generator for Scheme. It is NOT robust, since calling a function with the wrong number of arguments may generate an error that will cause the calculator to crash. The LALR(1) parser --- Options output a parser, called calc-parser, in a separate file - calc.yy.scm, there should be no conflict --- token definitions --- rules The lexer -- skip spaces -- read the next token Environment management The main program
(define calc-parser (lalr-parser (output: calc-parser "calc.yy.scm") output the LALR table to calc.out (out-table: "calc.out") (expect: 5) (ID NUM = LPAREN RPAREN NEWLINE COMMA (left: + -) (left: * /) (nonassoc: uminus)) (lines (lines line) : (display-result $2) (line) : (display-result $1)) (line (assign NEWLINE) : $1 (expr NEWLINE) : $1 (NEWLINE) : #f (error NEWLINE) : #f) (assign (ID = expr) : (add-binding $1 $3)) (expr (expr + expr) : (+ $1 $3) (expr - expr) : (- $1 $3) (expr * expr) : (* $1 $3) (expr / expr) : (/ $1 $3) (- expr (prec: uminus)) : (- $2) (ID) : (get-binding $1) (ID LPAREN args RPAREN) : (invoke-proc $1 $3) (NUM) : $1 (LPAREN expr RPAREN) : $2) (args () : '() (expr arg-rest) : (cons $1 $2)) (arg-rest (COMMA expr arg-rest) : (cons $2 $3) () : '()))) (cond-expand (gambit (define port-line input-port-line) (define port-column input-port-column)) (chicken (define (force-output) #f) (define (port-line port) (let-values (((line _) (port-position port))) line)) (define (port-column port) (let-values (((_ column) (port-position port))) column))) (guile (define (port-line port) '??) (define (port-column port) '??)) (else (define (force-output) #f) (define (port-line port) '??) (define (port-column port) '??))) (define (make-lexer errorp) (lambda () (letrec ((skip-spaces (lambda () (let loop ((c (peek-char))) (if (and (not (eof-object? c)) (or (char=? c #\space) (char=? c #\tab))) (begin (read-char) (loop (peek-char))))))) (read-number (lambda (l) (let ((c (peek-char))) (if (char-numeric? c) (read-number (cons (read-char) l)) (string->number (apply string (reverse l))))))) (read-id (lambda (l) (let ((c (peek-char))) (if (char-alphabetic? c) (read-id (cons (read-char) l)) (string->symbol (apply string (reverse l)))))))) (skip-spaces) (let loop () (let* ((location (make-source-location "*stdin*" (port-line (current-input-port)) (port-column (current-input-port)) -1 -1)) (c (read-char))) (cond ((eof-object? c) '*eoi*) ((char=? c #\newline) (make-lexical-token 'NEWLINE location #f)) ((char=? c #\+) (make-lexical-token '+ location #f)) ((char=? c #\-) (make-lexical-token '- location #f)) ((char=? c #\*) (make-lexical-token '* location #f)) ((char=? c #\/) (make-lexical-token '/ location #f)) ((char=? c #\=) (make-lexical-token '= location #f)) ((char=? c #\,) (make-lexical-token 'COMMA location #f)) ((char=? c #\() (make-lexical-token 'LPAREN location #f)) ((char=? c #\)) (make-lexical-token 'RPAREN location #f)) ((char-numeric? c) (make-lexical-token 'NUM location (read-number (list c)))) ((char-alphabetic? c) (make-lexical-token 'ID location (read-id (list c)))) (else (errorp "PARSE ERROR : illegal character: " c) (skip-spaces) (loop)))))))) (define *env* (list (cons '$$ 0))) (define (init-bindings) (set-cdr! *env* '()) (add-binding 'cos cos) (add-binding 'sin sin) (add-binding 'tan tan) (add-binding 'expt expt) (add-binding 'sqrt sqrt)) (define (add-binding var val) (set! *env* (cons (cons var val) *env*)) val) (define (get-binding var) (let ((p (assq var *env*))) (if p (cdr p) 0))) (define (invoke-proc proc-name args) (let ((proc (get-binding proc-name))) (if (procedure? proc) (apply proc args) (begin (display "ERROR: invalid procedure:") (display proc-name) (newline) 0)))) (define (display-result v) (if v (begin (display v) (newline))) (display-prompt)) (define (display-prompt) (display "[calculator]> ") (force-output)) (define calc (lambda () (call-with-current-continuation (lambda (k) (display "********************************") (newline) (display "* Mini calculator in Scheme *") (newline) (display "* *") (newline) (display "* Enter expressions followed *") (newline) (display "* by [RETURN] or 'quit()' to *") (newline) (display "* exit. *") (newline) (display "********************************") (newline) (init-bindings) (add-binding 'quit (lambda () (k #t))) (letrec ((errorp (lambda (message . args) (display message) (if (and (pair? args) (lexical-token? (car args))) (let ((token (car args))) (display (or (lexical-token-value token) (lexical-token-category token))) (let ((source (lexical-token-source token))) (if (source-location? source) (let ((line (source-location-line source)) (column (source-location-column source))) (if (and (number? line) (number? column)) (begin (display " (at line ") (display line) (display ", column ") (display (+ 1 column)) (display ")"))))))) (for-each display args)) (newline))) (start (lambda () (calc-parser (make-lexer errorp) errorp)))) (display-prompt) (start)))))) (calc)
5d6f3d10f5e6648f3b65459189ff9facf3e3c39fce2da04b2fc3b6626a57df2e
lambe-lang/nethra
t03_product.ml
open Common open Nethra.Toy.Compiler open Preface_stdlib.Result.Functor (struct type t = Nethra.Syntax.Source.Region.t Pass.error end) let compile_basic_product () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, unit) ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "basic product type" expected (string_of_error result) let compile_basic_product_fails () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, 1) ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok false in Alcotest.(check (result bool string)) "basic product type fails" expected (string_of_error result) let compile_basic_product_first () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, unit) sig first : type val first = fst pair ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "basic product first" expected (string_of_error result) let compile_basic_product_second () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, unit) sig second : Unit val second = snd pair ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "basic product second" expected (string_of_error result) let compile_trait_denotation () = let result = Pass.run {toy| -{ trait Monoid { sig t : type sig empty : t sig compose : t -> t -> t } }- sig Monoid : type val Monoid = (t:type) * (t * (t -> t -> t)) sig Empty : type val Empty = (t:type) * t sig Compose : type val Compose = (t:type) * (t -> t -> t) sig empty : Monoid -> Empty val empty = (x).(fst x, fst (snd x)) sig compose : Monoid -> Compose val compose = (x).(fst x, snd (snd x)) |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "trait denotation" expected (string_of_error result) let compile_trait_implementation () = let result = Pass.run {toy| -{ trait Monoid { sig empty : self sig compose : self -> self -> self } }- sig Monoid : type val Monoid = (t:type) * (t * (t -> t -> t)) sig Empty : type val Empty = (t:type) * t sig Compose : type val Compose = (t:type) * (t -> t -> t) sig empty : Monoid -> Empty val empty = (x).(fst x, fst (snd x)) sig compose : Monoid -> Compose val compose = (x).(fst x, snd (snd x)) ------------ -{ impl Monoid for int { val empty = 0 val compose = add } }- sig int : type sig add : int -> int -> int sig Monoid_for_Int : Monoid val Monoid_for_Int = (int, 0, add) |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "trait implementation" expected (string_of_error result) let cases = let open Alcotest in ( "Product Compiler" , [ test_case "basic product type" `Quick compile_basic_product ; test_case "basic product type fails" `Quick compile_basic_product_fails ; test_case "basic product first" `Quick compile_basic_product_first ; test_case "basic product second" `Quick compile_basic_product_second ; test_case "trait denotation" `Quick compile_trait_denotation ; test_case "trait implementation" `Quick compile_trait_implementation ] )
null
https://raw.githubusercontent.com/lambe-lang/nethra/892b84deb9475021b95bfa6274dc8b70cb3e44ea/test/nethra/toy/s00_compiler/t03_product.ml
ocaml
open Common open Nethra.Toy.Compiler open Preface_stdlib.Result.Functor (struct type t = Nethra.Syntax.Source.Region.t Pass.error end) let compile_basic_product () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, unit) ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "basic product type" expected (string_of_error result) let compile_basic_product_fails () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, 1) ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok false in Alcotest.(check (result bool string)) "basic product type fails" expected (string_of_error result) let compile_basic_product_first () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, unit) sig first : type val first = fst pair ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "basic product first" expected (string_of_error result) let compile_basic_product_second () = let result = Pass.run {toy| sig Unit : type sig unit : Unit ------------ sig pair : (X:type) * X val pair = (Unit, unit) sig second : Unit val second = snd pair ------------ |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "basic product second" expected (string_of_error result) let compile_trait_denotation () = let result = Pass.run {toy| -{ trait Monoid { sig t : type sig empty : t sig compose : t -> t -> t } }- sig Monoid : type val Monoid = (t:type) * (t * (t -> t -> t)) sig Empty : type val Empty = (t:type) * t sig Compose : type val Compose = (t:type) * (t -> t -> t) sig empty : Monoid -> Empty val empty = (x).(fst x, fst (snd x)) sig compose : Monoid -> Compose val compose = (x).(fst x, snd (snd x)) |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "trait denotation" expected (string_of_error result) let compile_trait_implementation () = let result = Pass.run {toy| -{ trait Monoid { sig empty : self sig compose : self -> self -> self } }- sig Monoid : type val Monoid = (t:type) * (t * (t -> t -> t)) sig Empty : type val Empty = (t:type) * t sig Compose : type val Compose = (t:type) * (t -> t -> t) sig empty : Monoid -> Empty val empty = (x).(fst x, fst (snd x)) sig compose : Monoid -> Compose val compose = (x).(fst x, snd (snd x)) ------------ -{ impl Monoid for int { val empty = 0 val compose = add } }- sig int : type sig add : int -> int -> int sig Monoid_for_Int : Monoid val Monoid_for_Int = (int, 0, add) |toy} <&> fun (_, l) -> check l and expected = Result.Ok true in Alcotest.(check (result bool string)) "trait implementation" expected (string_of_error result) let cases = let open Alcotest in ( "Product Compiler" , [ test_case "basic product type" `Quick compile_basic_product ; test_case "basic product type fails" `Quick compile_basic_product_fails ; test_case "basic product first" `Quick compile_basic_product_first ; test_case "basic product second" `Quick compile_basic_product_second ; test_case "trait denotation" `Quick compile_trait_denotation ; test_case "trait implementation" `Quick compile_trait_implementation ] )