_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 |
|---|---|---|---|---|---|---|---|---|
63cedee57034838f149370bc64f3ff69a4b46668f38240078c730c8538ee9cc2 | nvim-treesitter/nvim-treesitter | locals.scm | ; Scopes
[
(function_call)
(code_block)
(function_block)
(control_structure)
] @scope
; Definitions
(argument
name: (identifier) @definition.parameter
(#set! "definition.var.scope" "local")
)
(variable_definition
name: (variable (local_var (identifier) @definition.var
)))
(variable_definition
name: (variable (environment_var (identifier) @definition.var))
(#set! "definition.var.scope" "global"))
(function_definition name: (variable) @definition.var
(#set! "definition.var.scope" "parent")
)
(identifier) @reference
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/56634f49ab3d8122153c8c5582c581fb6a6af075/queries/supercollider/locals.scm | scheme | Scopes
Definitions | [
(function_call)
(code_block)
(function_block)
(control_structure)
] @scope
(argument
name: (identifier) @definition.parameter
(#set! "definition.var.scope" "local")
)
(variable_definition
name: (variable (local_var (identifier) @definition.var
)))
(variable_definition
name: (variable (environment_var (identifier) @definition.var))
(#set! "definition.var.scope" "global"))
(function_definition name: (variable) @definition.var
(#set! "definition.var.scope" "parent")
)
(identifier) @reference
|
b10034261cbd8eec881045be242d49f43ce90893fb556bc3e8489257c87352ce | bmeurer/ocamljit2 | arrayLabels.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
(* Module [ArrayLabels]: labelled Array module *)
include Array
| null | https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/stdlib/arrayLabels.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
Module [ArrayLabels]: labelled Array module | , Kyoto University RIMS
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
include Array
|
2a1e6d162037f8b579f3cbe68e84d9e91f42d17e128c05eb54e796eed0cc7879 | jbracker/supermonad | PreludeWithoutMonad.hs |
-- | A verson of the standard prelude that does not export anything that
-- involves standard monads.
module Control.Super.Monad.PreludeWithoutMonad
( -- * Prelude
-- ** Standard types, classes and related functions
-- *** Basic data types
P.Bool(..)
, (P.&&), (P.||), P.not, P.otherwise
, P.Maybe(..)
, P.maybe
, P.Either(..)
, P.either
, P.Ordering(..)
, P.Char, P.String
* * * * Tuples
, P.fst, P.snd, P.curry, P.uncurry
-- *** Basic type classes
, P.Eq(..), P.Ord(..), P.Enum(..), P.Bounded(..)
-- *** Numbers
-- **** Numeric types
, P.Int, P.Integer, P.Float, P.Double, P.Rational, P.Word
-- **** Numeric type classes
, P.Num(..), P.Real(..), P.Integral(..)
, P.Fractional(..), P.Floating(..)
, P.RealFrac(..), P.RealFloat(..)
-- **** Numeric functions
, P.subtract, P.even, P.odd, P.gcd, P.lcm
, (P.^), (P.^^)
, P.fromIntegral, P.realToFrac
* * *
, P.Monoid(..)
-- *** (Monads and) functors
, P.Functor(..), (P.<$>)
-- , P.Applicative(..) -- Nope not this one!
, P.Monad ( .. ) -- Nope not this one !
-- *** Folds and traversals
, P.Foldable(..)
, P.Traversable(traverse, sequenceA) -- Only export the non-monad functions.
-- *** Miscellaneous functions
, P.id, P.const, P.flip, P.until, P.asTypeOf, P.error, P.undefined, P.seq
, (P..), (P.$), (P.$!)
-- ** List operations
, P.map, P.filter, P.head, P.last, P.tail, P.init, P.reverse
, (P.++), (P.!!)
-- *** Special folds
, P.and, P.or, P.any, P.all
, P.concat, P.concatMap
-- *** Building lists
-- **** Scans
, P.scanl, P.scanl1, P.scanr, P.scanr1
-- **** Infinite lists
, P.iterate, P.repeat, P.replicate, P.cycle
-- *** Sublists
, P.take, P.drop, P.splitAt, P.takeWhile, P.dropWhile, P.span, P.break
-- *** Searching lists
, P.notElem, P.lookup
-- *** Zipping and unzipping lists
, P.zip, P.zip3, P.zipWith, P.zipWith3, P.unzip, P.unzip3
-- *** Functions on strings
, P.lines, P.words, P.unlines, P.unwords
-- ** Converting from and to @String@
-- *** Converting to @String@
, P.ShowS, P.Show(..)
, P.shows, P.showChar, P.showString, P.showParen
-- *** Converting from @String@
, P.ReadS, P.Read(..)
, P.reads, P.readParen, P.read, P.lex
-- ** Basic input and output
, P.IO
-- *** Simple I/O operations
-- **** Output functions
, P.putChar, P.putStr, P.putStrLn, P.print
-- **** Input functions
, P.getChar, P.getLine, P.getContents, P.interact
-- **** Files
, P.FilePath
, P.readFile, P.writeFile, P.appendFile, P.readIO, P.readLn
-- *** Exception handing in the I/O monad
, P.IOError
, P.ioError, P.userError
) where
import qualified Prelude as P | null | https://raw.githubusercontent.com/jbracker/supermonad/2595396a225a65b1dce6ed9a1ce59960f392a55b/src/Control/Super/Monad/PreludeWithoutMonad.hs | haskell | | A verson of the standard prelude that does not export anything that
involves standard monads.
* Prelude
** Standard types, classes and related functions
*** Basic data types
*** Basic type classes
*** Numbers
**** Numeric types
**** Numeric type classes
**** Numeric functions
*** (Monads and) functors
, P.Applicative(..) -- Nope not this one!
Nope not this one !
*** Folds and traversals
Only export the non-monad functions.
*** Miscellaneous functions
** List operations
*** Special folds
*** Building lists
**** Scans
**** Infinite lists
*** Sublists
*** Searching lists
*** Zipping and unzipping lists
*** Functions on strings
** Converting from and to @String@
*** Converting to @String@
*** Converting from @String@
** Basic input and output
*** Simple I/O operations
**** Output functions
**** Input functions
**** Files
*** Exception handing in the I/O monad |
module Control.Super.Monad.PreludeWithoutMonad
P.Bool(..)
, (P.&&), (P.||), P.not, P.otherwise
, P.Maybe(..)
, P.maybe
, P.Either(..)
, P.either
, P.Ordering(..)
, P.Char, P.String
* * * * Tuples
, P.fst, P.snd, P.curry, P.uncurry
, P.Eq(..), P.Ord(..), P.Enum(..), P.Bounded(..)
, P.Int, P.Integer, P.Float, P.Double, P.Rational, P.Word
, P.Num(..), P.Real(..), P.Integral(..)
, P.Fractional(..), P.Floating(..)
, P.RealFrac(..), P.RealFloat(..)
, P.subtract, P.even, P.odd, P.gcd, P.lcm
, (P.^), (P.^^)
, P.fromIntegral, P.realToFrac
* * *
, P.Monoid(..)
, P.Functor(..), (P.<$>)
, P.Foldable(..)
, P.id, P.const, P.flip, P.until, P.asTypeOf, P.error, P.undefined, P.seq
, (P..), (P.$), (P.$!)
, P.map, P.filter, P.head, P.last, P.tail, P.init, P.reverse
, (P.++), (P.!!)
, P.and, P.or, P.any, P.all
, P.concat, P.concatMap
, P.scanl, P.scanl1, P.scanr, P.scanr1
, P.iterate, P.repeat, P.replicate, P.cycle
, P.take, P.drop, P.splitAt, P.takeWhile, P.dropWhile, P.span, P.break
, P.notElem, P.lookup
, P.zip, P.zip3, P.zipWith, P.zipWith3, P.unzip, P.unzip3
, P.lines, P.words, P.unlines, P.unwords
, P.ShowS, P.Show(..)
, P.shows, P.showChar, P.showString, P.showParen
, P.ReadS, P.Read(..)
, P.reads, P.readParen, P.read, P.lex
, P.IO
, P.putChar, P.putStr, P.putStrLn, P.print
, P.getChar, P.getLine, P.getContents, P.interact
, P.FilePath
, P.readFile, P.writeFile, P.appendFile, P.readIO, P.readLn
, P.IOError
, P.ioError, P.userError
) where
import qualified Prelude as P |
211f7e8806b3ee7d18a8aaf6fb94693760e4a302cedcc7465f8d537daccc42df | cxxxr/apispec | parameter.lisp | (defpackage #:apispec/tests/classes/parameter
(:use #:cl
#:rove
#:apispec/classes/parameter)
(:import-from #:apispec/classes/schema
#:object
#:schema)
(:import-from #:assoc-utils
#:alist-hash))
(in-package #:apispec/tests/classes/parameter)
(deftest parse-query-string-tests
(ok (equalp (parse-query-string "id=abc&id=opq&id=xyz"
(list
(make-instance 'parameter
:name "id"
:in "query"
:description "ID of the object to fetch"
:required nil
:schema (schema (array :items 'string))
:style "form"
:explode t)))
'(("id" . #("abc" "opq" "xyz")))))
(ok (equalp (parse-query-string "id=abc,opq,xyz"
(list
(make-instance 'parameter
:name "id"
:in "query"
:description "ID of the object to fetch"
:required nil
:schema (schema (array :items 'string))
:style "form"
:explode nil)))
'(("id" . #("abc" "opq" "xyz")))))
(ok (equalp (parse-query-string nil
(list
(make-instance 'parameter
:name "name"
:in "query"
:description "ID of the object to fetch"
:required nil
:schema (schema (array :items 'string))
:style "form"
:explode nil)))
'(("name"))))
(ok (signals (parse-query-string "id=abc,opq,xyz" (list))
'parameter-validation-failed))
(ok (signals (parse-query-string nil
(list
(make-instance 'parameter
:name "name"
:in "query"
:description "ID of the object to fetch"
:required t
:schema (schema (array :items 'string))
:style "form"
:expldoe nil)))
'parameter-validation-failed)))
(deftest parse-headers-tests
(ok (equalp (parse-headers
(alist-hash
'(("token" . "123,456")))
(list (make-instance 'parameter
:name "token"
:in "header"
:description "token to be passed to a header"
:required t
:schema (schema (array :items 'integer))
:style "simple")))
'(("token" . #(123 456)))))
(ok (signals (parse-headers
(make-hash-table)
(list (make-instance 'parameter
:name "token"
:in "header"
:description "token to be passed to a header"
:required t
:schema (schema (array :items 'integer))
:style "simple")))
'parameter-validation-failed)))
(deftest parse-cookie-parameter
(ok (equalp (parse-cookie-string
"id=5"
(list (make-instance 'parameter
:name "id"
:in "cookie"
:required t
:schema (schema integer)
:style "form")))
'(("id" . 5))))
(ok (equalp (parse-cookie-string
"id=3,4,5"
(list (make-instance 'parameter
:name "id"
:in "cookie"
:required t
:schema (schema (array :items 'integer))
:style "form"
:explode nil)))
'(("id" . #(3 4 5)))))
(ok (equalp (parse-cookie-string
"id=role,admin,firstName,Alex"
(list (make-instance 'parameter
:name "id"
:in "cookie"
:required t
:schema (schema (object (("role" string) ("firstName" string))))
:style "form"
:explode nil)))
'(("id" . (("role" . "admin")
("firstName" . "Alex")))))))
| null | https://raw.githubusercontent.com/cxxxr/apispec/4bdd238f6b5effed305d284e0e6b7cef214e94a2/tests/classes/parameter.lisp | lisp | (defpackage #:apispec/tests/classes/parameter
(:use #:cl
#:rove
#:apispec/classes/parameter)
(:import-from #:apispec/classes/schema
#:object
#:schema)
(:import-from #:assoc-utils
#:alist-hash))
(in-package #:apispec/tests/classes/parameter)
(deftest parse-query-string-tests
(ok (equalp (parse-query-string "id=abc&id=opq&id=xyz"
(list
(make-instance 'parameter
:name "id"
:in "query"
:description "ID of the object to fetch"
:required nil
:schema (schema (array :items 'string))
:style "form"
:explode t)))
'(("id" . #("abc" "opq" "xyz")))))
(ok (equalp (parse-query-string "id=abc,opq,xyz"
(list
(make-instance 'parameter
:name "id"
:in "query"
:description "ID of the object to fetch"
:required nil
:schema (schema (array :items 'string))
:style "form"
:explode nil)))
'(("id" . #("abc" "opq" "xyz")))))
(ok (equalp (parse-query-string nil
(list
(make-instance 'parameter
:name "name"
:in "query"
:description "ID of the object to fetch"
:required nil
:schema (schema (array :items 'string))
:style "form"
:explode nil)))
'(("name"))))
(ok (signals (parse-query-string "id=abc,opq,xyz" (list))
'parameter-validation-failed))
(ok (signals (parse-query-string nil
(list
(make-instance 'parameter
:name "name"
:in "query"
:description "ID of the object to fetch"
:required t
:schema (schema (array :items 'string))
:style "form"
:expldoe nil)))
'parameter-validation-failed)))
(deftest parse-headers-tests
(ok (equalp (parse-headers
(alist-hash
'(("token" . "123,456")))
(list (make-instance 'parameter
:name "token"
:in "header"
:description "token to be passed to a header"
:required t
:schema (schema (array :items 'integer))
:style "simple")))
'(("token" . #(123 456)))))
(ok (signals (parse-headers
(make-hash-table)
(list (make-instance 'parameter
:name "token"
:in "header"
:description "token to be passed to a header"
:required t
:schema (schema (array :items 'integer))
:style "simple")))
'parameter-validation-failed)))
(deftest parse-cookie-parameter
(ok (equalp (parse-cookie-string
"id=5"
(list (make-instance 'parameter
:name "id"
:in "cookie"
:required t
:schema (schema integer)
:style "form")))
'(("id" . 5))))
(ok (equalp (parse-cookie-string
"id=3,4,5"
(list (make-instance 'parameter
:name "id"
:in "cookie"
:required t
:schema (schema (array :items 'integer))
:style "form"
:explode nil)))
'(("id" . #(3 4 5)))))
(ok (equalp (parse-cookie-string
"id=role,admin,firstName,Alex"
(list (make-instance 'parameter
:name "id"
:in "cookie"
:required t
:schema (schema (object (("role" string) ("firstName" string))))
:style "form"
:explode nil)))
'(("id" . (("role" . "admin")
("firstName" . "Alex")))))))
| |
6158bd3759908a65abfcab600e9c86e756c545580c42d2c92689b59986fda147 | privet-kitty/cl-competitive | 2cc.lisp | (defpackage :cp/test/2cc
(:use :cl :fiveam :cp/2cc :cp/set-equal)
(:import-from :cp/test/base #:base-suite))
(in-package :cp/test/2cc)
(in-suite base-suite)
(test 2cc
;; Graph example is from
(let* ((graph #(() (2 5) (1 3) (2 4 5) (3) (1 3 7 8) (8) (5 8) (5 6 7 9) (8)))
(2cc (make-2cc graph))
(comps (2cc-components 2cc))
(sizes (2cc-sizes 2cc))
(bridges (2cc-bridges 2cc)))
(is (set-equal '((3 . 4) (6 . 8) (8 . 9)) bridges :test #'equal))
(is (= (aref comps 1)
(aref comps 2)
(aref comps 3)
(aref comps 5)
(aref comps 7)
(aref comps 8)))
(is (/= (aref comps 0) (aref comps 1) (aref comps 4) (aref comps 6) (aref comps 9)))
(is (= 6 (aref sizes (aref comps 1))))
(is (= 1 (aref sizes (aref comps 0))))
(is (= 1 (aref sizes (aref comps 4))))
(is (= 1 (aref sizes (aref comps 6))))
(is (= 1 (aref sizes (aref comps 9))))
(is (= (2cc-count 2cc) (length (make-bridge-tree 2cc)))))
;; empty graph
(finishes (make-2cc #())))
| null | https://raw.githubusercontent.com/privet-kitty/cl-competitive/a1e3077015824b53272e2c5c9c30639a9192cf86/module/test/2cc.lisp | lisp | Graph example is from
empty graph | (defpackage :cp/test/2cc
(:use :cl :fiveam :cp/2cc :cp/set-equal)
(:import-from :cp/test/base #:base-suite))
(in-package :cp/test/2cc)
(in-suite base-suite)
(test 2cc
(let* ((graph #(() (2 5) (1 3) (2 4 5) (3) (1 3 7 8) (8) (5 8) (5 6 7 9) (8)))
(2cc (make-2cc graph))
(comps (2cc-components 2cc))
(sizes (2cc-sizes 2cc))
(bridges (2cc-bridges 2cc)))
(is (set-equal '((3 . 4) (6 . 8) (8 . 9)) bridges :test #'equal))
(is (= (aref comps 1)
(aref comps 2)
(aref comps 3)
(aref comps 5)
(aref comps 7)
(aref comps 8)))
(is (/= (aref comps 0) (aref comps 1) (aref comps 4) (aref comps 6) (aref comps 9)))
(is (= 6 (aref sizes (aref comps 1))))
(is (= 1 (aref sizes (aref comps 0))))
(is (= 1 (aref sizes (aref comps 4))))
(is (= 1 (aref sizes (aref comps 6))))
(is (= 1 (aref sizes (aref comps 9))))
(is (= (2cc-count 2cc) (length (make-bridge-tree 2cc)))))
(finishes (make-2cc #())))
|
f758ea46c1f0a07d72ced447e7eea58be1ff461b377ab4e7b50cd8b71cfe8fac | schell/odin | Evented.hs | # LANGUAGE LambdaCase #
module Control.Monad.Evented where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
newtype EventT m b = EventT { runEventT :: m (Either b (EventT m b)) }
--------------------------------------------------------------------------------
-- Constructors
--------------------------------------------------------------------------------
done :: Monad m => a -> EventT m a
done = EventT . return . Left
next :: Monad m => EventT m a -> EventT m a
next = EventT . return . Right
--------------------------------------------------------------------------------
-- Combinators
--------------------------------------------------------------------------------
-- | Waits a number of frames.
wait :: Monad m => Int -> EventT m ()
wait 0 = done ()
wait n = next $ wait $ n - 1
-- | Runs both evented computations (left and then right) each frame and returns
the first computation that completes .
withEither :: Monad m => EventT m a -> EventT m b -> EventT m (Either a b)
withEither ea eb =
lift ((,) <$> runEventT ea <*> runEventT eb) >>= \case
(Left a,_) -> done $ Left a
(_,Left b) -> done $ Right b
(Right a, Right b) -> next $ withEither a b
-- | Runs all evented computations (left to right) on each frame and returns
the first computation that completes .
withAny :: Monad m => [EventT m a] -> EventT m a
withAny ts0 = do
es <- lift $ mapM runEventT ts0
case foldl f (Right []) es of
Right ts -> next $ withAny ts
Left a -> done a
where f (Left a) _ = Left a
f (Right ts) (Right t) = Right $ ts ++ [t]
f _ (Left a) = Left a
--------------------------------------------------------------------------------
-- Instances
--------------------------------------------------------------------------------
instance Monad m => Functor (EventT m) where
fmap f (EventT g) = EventT $
g >>= \case
Right ev -> return $ Right $ fmap f ev
Left c -> return $ Left $ f c
instance Monad m => Applicative (EventT m) where
pure = done
ef <*> ex = do
f <- ef
x <- ex
return $ f x
instance Monad m => Monad (EventT m) where
(EventT g) >>= fev = EventT $ g >>= \case
Right ev -> return $ Right $ ev >>= fev
Left c -> runEventT $ fev c
return = done
instance MonadTrans EventT where
lift f = EventT $ f >>= return . Left
instance MonadIO m => MonadIO (EventT m) where
liftIO = lift . liftIO
| null | https://raw.githubusercontent.com/schell/odin/97ae1610a7abd19aa150bc7dfc132082d88ca9ea/src/Control/Monad/Evented.hs | haskell | ------------------------------------------------------------------------------
Constructors
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Combinators
------------------------------------------------------------------------------
| Waits a number of frames.
| Runs both evented computations (left and then right) each frame and returns
| Runs all evented computations (left to right) on each frame and returns
------------------------------------------------------------------------------
Instances
------------------------------------------------------------------------------ | # LANGUAGE LambdaCase #
module Control.Monad.Evented where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
newtype EventT m b = EventT { runEventT :: m (Either b (EventT m b)) }
done :: Monad m => a -> EventT m a
done = EventT . return . Left
next :: Monad m => EventT m a -> EventT m a
next = EventT . return . Right
wait :: Monad m => Int -> EventT m ()
wait 0 = done ()
wait n = next $ wait $ n - 1
the first computation that completes .
withEither :: Monad m => EventT m a -> EventT m b -> EventT m (Either a b)
withEither ea eb =
lift ((,) <$> runEventT ea <*> runEventT eb) >>= \case
(Left a,_) -> done $ Left a
(_,Left b) -> done $ Right b
(Right a, Right b) -> next $ withEither a b
the first computation that completes .
withAny :: Monad m => [EventT m a] -> EventT m a
withAny ts0 = do
es <- lift $ mapM runEventT ts0
case foldl f (Right []) es of
Right ts -> next $ withAny ts
Left a -> done a
where f (Left a) _ = Left a
f (Right ts) (Right t) = Right $ ts ++ [t]
f _ (Left a) = Left a
instance Monad m => Functor (EventT m) where
fmap f (EventT g) = EventT $
g >>= \case
Right ev -> return $ Right $ fmap f ev
Left c -> return $ Left $ f c
instance Monad m => Applicative (EventT m) where
pure = done
ef <*> ex = do
f <- ef
x <- ex
return $ f x
instance Monad m => Monad (EventT m) where
(EventT g) >>= fev = EventT $ g >>= \case
Right ev -> return $ Right $ ev >>= fev
Left c -> runEventT $ fev c
return = done
instance MonadTrans EventT where
lift f = EventT $ f >>= return . Left
instance MonadIO m => MonadIO (EventT m) where
liftIO = lift . liftIO
|
9bd998869095b25c564f1512ad11609324d2284632c4fa95dd875054cd54fa44 | tsloughter/kuberl | kuberl_v1beta2_stateful_set_spec.erl | -module(kuberl_v1beta2_stateful_set_spec).
-export([encode/1]).
-export_type([kuberl_v1beta2_stateful_set_spec/0]).
-type kuberl_v1beta2_stateful_set_spec() ::
#{ 'podManagementPolicy' => binary(),
'replicas' => integer(),
'revisionHistoryLimit' => integer(),
'selector' := kuberl_v1_label_selector:kuberl_v1_label_selector(),
'serviceName' := binary(),
'template' := kuberl_v1_pod_template_spec:kuberl_v1_pod_template_spec(),
'updateStrategy' => kuberl_v1beta2_stateful_set_update_strategy:kuberl_v1beta2_stateful_set_update_strategy(),
'volumeClaimTemplates' => list()
}.
encode(#{ 'podManagementPolicy' := PodManagementPolicy,
'replicas' := Replicas,
'revisionHistoryLimit' := RevisionHistoryLimit,
'selector' := Selector,
'serviceName' := ServiceName,
'template' := Template,
'updateStrategy' := UpdateStrategy,
'volumeClaimTemplates' := VolumeClaimTemplates
}) ->
#{ 'podManagementPolicy' => PodManagementPolicy,
'replicas' => Replicas,
'revisionHistoryLimit' => RevisionHistoryLimit,
'selector' => Selector,
'serviceName' => ServiceName,
'template' => Template,
'updateStrategy' => UpdateStrategy,
'volumeClaimTemplates' => VolumeClaimTemplates
}.
| null | https://raw.githubusercontent.com/tsloughter/kuberl/f02ae6680d6ea5db6e8b6c7acbee8c4f9df482e2/gen/kuberl_v1beta2_stateful_set_spec.erl | erlang | -module(kuberl_v1beta2_stateful_set_spec).
-export([encode/1]).
-export_type([kuberl_v1beta2_stateful_set_spec/0]).
-type kuberl_v1beta2_stateful_set_spec() ::
#{ 'podManagementPolicy' => binary(),
'replicas' => integer(),
'revisionHistoryLimit' => integer(),
'selector' := kuberl_v1_label_selector:kuberl_v1_label_selector(),
'serviceName' := binary(),
'template' := kuberl_v1_pod_template_spec:kuberl_v1_pod_template_spec(),
'updateStrategy' => kuberl_v1beta2_stateful_set_update_strategy:kuberl_v1beta2_stateful_set_update_strategy(),
'volumeClaimTemplates' => list()
}.
encode(#{ 'podManagementPolicy' := PodManagementPolicy,
'replicas' := Replicas,
'revisionHistoryLimit' := RevisionHistoryLimit,
'selector' := Selector,
'serviceName' := ServiceName,
'template' := Template,
'updateStrategy' := UpdateStrategy,
'volumeClaimTemplates' := VolumeClaimTemplates
}) ->
#{ 'podManagementPolicy' => PodManagementPolicy,
'replicas' => Replicas,
'revisionHistoryLimit' => RevisionHistoryLimit,
'selector' => Selector,
'serviceName' => ServiceName,
'template' => Template,
'updateStrategy' => UpdateStrategy,
'volumeClaimTemplates' => VolumeClaimTemplates
}.
| |
a317250406501fbce846907bc722cfba82caca07b33773a1afc8d2ead21a264d | dlowe-net/local-time | local-time.lisp | (in-package #:local-time)
;;; Types
(defclass timestamp ()
((day :accessor day-of :initarg :day :initform 0 :type integer)
(sec :accessor sec-of :initarg :sec :initform 0 :type integer)
(nsec :accessor nsec-of :initarg :nsec :initform 0 :type (integer 0 999999999))))
(defstruct subzone
(abbrev nil)
(offset nil)
(daylight-p nil))
(defstruct timezone
(transitions #(0) :type simple-vector)
(indexes #(0) :type simple-vector)
(subzones #() :type simple-vector)
(leap-seconds nil :type list)
(path nil)
(name "anonymous" :type string)
(loaded nil :type boolean))
(deftype timezone-offset ()
'(integer -43200 50400))
(defun %valid-time-of-day? (timestamp)
(zerop (day-of timestamp)))
(deftype time-of-day ()
'(and timestamp
(satisfies %valid-time-of-day?)))
(defun %valid-date? (timestamp)
(and (zerop (sec-of timestamp))
(zerop (nsec-of timestamp))))
(deftype date ()
'(and timestamp
(satisfies %valid-date?)))
(defun zone-name (zone)
(timezone-name zone))
(define-condition invalid-timezone-file (error)
((path :accessor path-of :initarg :path))
(:report (lambda (condition stream)
(format stream "The file at ~a is not a timezone file."
(path-of condition)))))
(define-condition invalid-time-specification (error)
()
(:report "The time specification is invalid"))
(define-condition invalid-timestring (error)
((timestring :accessor timestring-of :initarg :timestring)
(failure :accessor failure-of :initarg :failure))
(:report (lambda (condition stream)
(format stream "Failed to parse ~S as an rfc3339 time: ~S"
(timestring-of condition)
(failure-of condition)))))
(defmethod make-load-form ((self timestamp) &optional environment)
(make-load-form-saving-slots self :environment environment))
Declaims
(declaim (inline now format-timestring %get-current-time
format-rfc3339-timestring to-rfc3339-timestring
format-rfc1123-timestring to-rfc1123-timestring)
(ftype (function (&rest t) string) format-rfc3339-timestring)
(ftype (function (&rest t) string) format-timestring)
(ftype (function (&rest t) fixnum) local-timezone)
(ftype (function (&rest t) (values
timezone-offset
boolean
string)) timestamp-subzone)
(ftype (function (timestamp &key (:timezone timezone) (:offset (or null integer)))
(values (integer 0 999999999)
(integer 0 59)
(integer 0 59)
(integer 0 23)
(integer 1 31)
(integer 1 12)
(integer -1000000 1000000)
(integer 0 6)
t
timezone-offset
simple-string))
decode-timestamp))
;;; Variables
(defvar *default-timezone*)
(defparameter *default-timezone-repository-path*
(flet ((try (project-home-directory)
(when project-home-directory
(ignore-errors
(truename
(merge-pathnames "zoneinfo/"
(make-pathname :directory (pathname-directory project-home-directory))))))))
(or (when (find-package "ASDF")
(let ((path (eval (read-from-string
"(let ((system (asdf:find-system :local-time nil)))
(when system
(asdf:component-pathname system)))"))))
(try path)))
(let ((path (or #.*compile-file-truename*
*load-truename*)))
(when path
(try (merge-pathnames "../" path)))))))
;;; Month information
(defparameter +month-names+
#("" "January" "February" "March" "April" "May" "June" "July" "August"
"September" "October" "November" "December"))
(defparameter +short-month-names+
#("" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov"
"Dec"))
(defparameter +day-names+
#("Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"))
(defparameter +day-names-as-keywords+
#(:sunday :monday :tuesday :wednesday :thursday :friday :saturday))
(defparameter +short-day-names+
#("Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"))
(defparameter +minimal-day-names+
#("Su" "Mo" "Tu" "We" "Th" "Fr" "Sa"))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant +months-per-year+ 12)
(defconstant +days-per-week+ 7)
(defconstant +hours-per-day+ 24)
(defconstant +minutes-per-day+ 1440)
(defconstant +minutes-per-hour+ 60)
(defconstant +seconds-per-day+ 86400)
(defconstant +seconds-per-hour+ 3600)
(defconstant +seconds-per-minute+ 60)
(defconstant +usecs-per-day+ 86400000000))
(defparameter +iso-8601-date-format+
'((:year 4) #\- (:month 2) #\- (:day 2)))
(defparameter +iso-8601-time-format+
'((:hour 2) #\: (:min 2) #\: (:sec 2) #\. (:usec 6)))
(defparameter +iso-8601-format+
2008 - 11 - 18T02:32:00.586931 + 01:00
(append +iso-8601-date-format+ (list #\T) +iso-8601-time-format+ (list :gmt-offset-or-z)))
(defparameter +rfc3339-format+ +iso-8601-format+)
(defparameter +rfc3339-format/date-only+
'((:year 4) #\- (:month 2) #\- (:day 2)))
(defparameter +asctime-format+
'(:short-weekday #\space :short-month #\space (:day 2 #\space) #\space
(:hour 2) #\: (:min 2) #\: (:sec 2) #\space
(:year 4)))
(defparameter +rfc-1123-format+
Sun , 06 Nov 1994 08:49:37 GMT
'(:short-weekday ", " (:day 2) #\space :short-month #\space (:year 4) #\space
(:hour 2) #\: (:min 2) #\: (:sec 2) #\space :gmt-offset-hhmm)
"See the RFC 1123 for the details about the possible values of the timezone field.")
(defparameter +iso-week-date-format+
2009 - W53 - 5
'((:iso-week-year 4) #\- #\W (:iso-week-number 2) #\- (:iso-week-day 1)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +rotated-month-days-without-leap-day+
#.(coerce #(31 30 31 30 31 31 30 31 30 31 31 28)
'(simple-array fixnum (*))))
(defparameter +rotated-month-offsets-without-leap-day+
(coerce
(cons 0
(loop with sum = 0
for days :across +rotated-month-days-without-leap-day+
collect (incf sum days)))
'(simple-array fixnum (*)))))
The astronomical julian date offset is the number of days between
;; the current date and -4713-01-01T00:00:00+00:00
(defparameter +astronomical-julian-date-offset+ -2451605)
The modified julian date is the number of days between the current
date and 1858 - 11 - 17T12:00:00 + 00:00 . TODO : For the sake of simplicity ,
;; we currently just do the date arithmetic and don't adjust for the
;; time of day.
(defparameter +modified-julian-date-offset+ -51604)
(defun %subzone-as-of (timezone unix-time)
(let* ((as-of-time unix-time)
(index-length (length (timezone-indexes timezone)))
(transition-idx (cond ((zerop index-length) nil)
(as-of-time (transition-position as-of-time
(timezone-transitions timezone)))
(t (1- index-length))))
(subzone-idx (if transition-idx
(elt (timezone-indexes timezone) transition-idx)
0)))
(values (elt (timezone-subzones timezone) subzone-idx)
transition-idx)))
(defun %guess-offset (seconds days &optional timezone)
;; try converting the local time to a timestamp using each available
;; subtimezone, until we find one where the offset matches the offset that
;; applies at that time (according to the transition table).
;;
;; Consequence for ambiguous cases:
Whichever subtimezone is listed first in the tzinfo database will be
;; the one that we pick to resolve ambiguous local time representations.
(let* ((zone (%realize-timezone (or timezone *default-timezone*)))
(unix-time (timestamp-values-to-unix seconds days))
(subzone (%subzone-as-of zone unix-time)))
(subzone-offset subzone)))
(defun %read-binary-integer (stream byte-count &optional (signed nil))
"Read BYTE-COUNT bytes from the binary stream STREAM, and return an integer which is its representation in network byte order (MSB). If SIGNED is true, interprets the most significant bit as a sign indicator."
(loop
:with result = 0
:for offset :from (* (1- byte-count) 8) :downto 0 :by 8
:do (setf (ldb (byte 8 offset) result) (read-byte stream))
:finally (if signed
(let ((high-bit (* byte-count 8)))
(if (logbitp (1- high-bit) result)
(return (- result (ash 1 high-bit)))
(return result)))
(return result))))
(defun %string-from-unsigned-byte-vector (vector offset)
"Returns a string created from the vector of unsigned bytes VECTOR starting at OFFSET which is terminated by a 0."
(declare (type (vector (unsigned-byte 8)) vector))
(let* ((null-pos (or (position 0 vector :start offset) (length vector)))
(result (make-string (- null-pos offset))))
(loop for input-index :from offset :upto (1- null-pos)
for output-index :upfrom 0
do (setf (aref result output-index) (code-char (aref vector input-index))))
result))
(defun %find-first-std-offset (timezone-indexes timestamp-info)
(let ((subzone-idx (find-if 'subzone-daylight-p
timezone-indexes
:key (lambda (x) (aref timestamp-info x)))))
(subzone-offset (aref timestamp-info (or subzone-idx 0)))))
(defun %tz-verify-magic-number (inf zone)
;; read and verify magic number
(let ((magic-buf (make-array 4 :element-type 'unsigned-byte)))
(read-sequence magic-buf inf :start 0 :end 4)
(when (string/= (map 'string #'code-char magic-buf) "TZif" :end1 4)
(error 'invalid-timezone-file :path (timezone-path zone))))
skip 16 bytes for " future use "
(let ((ignore-buf (make-array 16 :element-type 'unsigned-byte)))
(read-sequence ignore-buf inf :start 0 :end 16)))
(defun %tz-read-header (inf)
`(:utc-count ,(%read-binary-integer inf 4)
:wall-count ,(%read-binary-integer inf 4)
:leap-count ,(%read-binary-integer inf 4)
:transition-count ,(%read-binary-integer inf 4)
:type-count ,(%read-binary-integer inf 4)
:abbrev-length ,(%read-binary-integer inf 4)))
(defun %tz-read-transitions (inf count)
(make-array count
:initial-contents
(loop for idx from 1 upto count
collect (%read-binary-integer inf 4 t))))
(defun %tz-read-indexes (inf count)
(make-array count
:initial-contents
(loop for idx from 1 upto count
collect (%read-binary-integer inf 1))))
(defun %tz-read-subzone (inf count)
(loop for idx from 1 upto count
collect (list (%read-binary-integer inf 4 t)
(%read-binary-integer inf 1)
(%read-binary-integer inf 1))))
(defun leap-seconds-sec (leap-seconds)
(car leap-seconds))
(defun leap-seconds-adjustment (leap-seconds)
(cdr leap-seconds))
(defun %tz-read-leap-seconds (inf count)
(when (plusp count)
(loop for idx from 1 upto count
collect (%read-binary-integer inf 4) into sec
collect (%read-binary-integer inf 4) into adjustment
finally (return (cons (make-array count :initial-contents sec)
(make-array count :initial-contents adjustment))))))
(defun %tz-read-abbrevs (inf length)
(let ((a (make-array length :element-type '(unsigned-byte 8))))
(read-sequence a inf
:start 0
:end length)
a))
(defun %tz-read-indicators (inf length)
;; read standard/wall indicators
(let ((buf (make-array length :element-type '(unsigned-byte 8))))
(read-sequence buf inf
:start 0
:end length)
(make-array length
:element-type 'bit
:initial-contents buf)))
(defun %tz-make-subzones (raw-info abbrevs gmt-indicators std-indicators)
(declare (ignore gmt-indicators std-indicators))
TODO : handle TZ environment variables , which use the gmt and std
;; indicators
(make-array (length raw-info)
:element-type 'subzone
:initial-contents
(loop for info in raw-info collect
(make-subzone
:offset (first info)
:daylight-p (/= (second info) 0)
:abbrev (%string-from-unsigned-byte-vector abbrevs (third info))))))
(defun %realize-timezone (zone &optional reload)
"If timezone has not already been loaded or RELOAD is non-NIL, loads the timezone information from its associated unix file. If the file is not a valid timezone file, the condition INVALID-TIMEZONE-FILE will be signaled."
(when (or reload (not (timezone-loaded zone)))
(with-open-file (inf (timezone-path zone)
:direction :input
:element-type 'unsigned-byte)
(%tz-verify-magic-number inf zone)
;; read header values
(let* ((header (%tz-read-header inf))
(timezone-transitions (%tz-read-transitions inf (getf header :transition-count)))
(subzone-indexes (%tz-read-indexes inf (getf header :transition-count)))
(subzone-raw-info (%tz-read-subzone inf (getf header :type-count)))
(abbreviation-buf (%tz-read-abbrevs inf (getf header :abbrev-length)))
(leap-second-info (%tz-read-leap-seconds inf (getf header :leap-count)))
(std-indicators (%tz-read-indicators inf (getf header :wall-count)))
(gmt-indicators (%tz-read-indicators inf (getf header :utc-count)))
(subzone-info (%tz-make-subzones subzone-raw-info
abbreviation-buf
gmt-indicators
std-indicators)))
(setf (timezone-transitions zone) timezone-transitions)
(setf (timezone-indexes zone) subzone-indexes)
(setf (timezone-subzones zone) subzone-info)
(setf (timezone-leap-seconds zone) leap-second-info))
(setf (timezone-loaded zone) t)))
zone)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %make-simple-timezone (name abbrev offset)
(let ((subzone (local-time::make-subzone :offset offset
:daylight-p nil
:abbrev abbrev)))
(local-time::make-timezone
:subzones (make-array 1 :initial-contents (list subzone))
:path nil
:name name
:loaded t)))
to be used as # + # .(local - time::package - with - symbol ? " SB - EXT " " GET - TIME - OF - DAY " )
(defun package-with-symbol? (package name)
(if (and (find-package package)
(find-symbol name package))
'(:and)
'(:or))))
(defparameter +utc-zone+ (%make-simple-timezone "Coordinated Universal Time" "UTC" 0))
(defparameter +gmt-zone+ (%make-simple-timezone "Greenwich Mean Time" "GMT" 0))
(defparameter +none-zone+ (%make-simple-timezone "Explicit Offset Given" "NONE" 0))
(defparameter *location-name->timezone* (make-hash-table :test 'equal)
"A hashtable with entries like \"Europe/Budapest\" -> timezone-instance")
(defparameter *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal)
"A hashtable of \"CEST\" -> list of timezones with \"CEST\" subzone")
(defmacro define-timezone (zone-name zone-file &key (load nil))
"Define zone-name (a symbol or a string) as a new timezone,
lazy-loaded from zone-file (a pathname designator relative to the
zoneinfo directory on this system. If load is true, load immediately."
(declare (type (or string symbol) zone-name))
(let ((zone-sym (if (symbolp zone-name)
zone-name
(intern zone-name))))
`(prog1
(defparameter ,zone-sym
(make-timezone :path ,zone-file
:name ,(if (symbolp zone-name)
(string-downcase (symbol-name zone-name))
zone-name)))
,@(when load
`((let ((timezone (%realize-timezone ,zone-sym)))
(setf (gethash (timezone-name timezone)
*location-name->timezone*)
timezone)
(loop for subzone across (timezone-subzones timezone)
do
(push timezone
(gethash (subzone-abbrev subzone)
*abbreviated-subzone-name->timezone-list*)))))))))
(eval-when (:load-toplevel :execute)
(let ((default-timezone-file #p"/etc/localtime"))
(handler-case
(define-timezone *default-timezone* default-timezone-file :load t)
(t ()
(setf *default-timezone* +utc-zone+)))))
(defun find-timezone-by-location-name (name)
(when (zerop (hash-table-count *location-name->timezone*))
(error "Seems like the timezone repository has not yet been loaded. Hint: see REREAD-TIMEZONE-REPOSITORY."))
(gethash name *location-name->timezone*))
(defun timezones-matching-subzone (abbreviated-name timestamp)
"Returns list of lists of active timezone, matched subzone and last transition time
for timezones that have subzone matching specified ABBREVIATED-NAME as of TIMESTAMP moment if provided. "
(loop for zone in (gethash abbreviated-name *abbreviated-subzone-name->timezone-list*)
;; get the subzone and the latest transition index
for (subzone transition-idx) = (multiple-value-list (%subzone-as-of zone (timestamp-to-unix timestamp)))
if (equal abbreviated-name (subzone-abbrev subzone))
collect (list zone subzone (when transition-idx (elt (timezone-transitions zone) transition-idx)))))
(defun all-timezones-matching-subzone (abbreviated-name)
"Returns list of lists of timezone, matched subzone and last transition time
for timezones that have subzone matching specified ABBREVIATED-NAME. Includes both active and historical timezones."
(loop for zone in (gethash abbreviated-name *abbreviated-subzone-name->timezone-list*)
for (subzone transition-idx) = (multiple-value-list (%subzone-as-of zone nil))
if (equal abbreviated-name (subzone-abbrev subzone))
collect (list zone subzone (when transition-idx (elt (timezone-transitions zone) transition-idx)))
else
when transition-idx
nconc (loop for subzone-idx from 0 below (length (timezone-subzones zone))
for sz = (elt (timezone-subzones zone) subzone-idx)
for tix = (position subzone-idx (timezone-indexes zone) :from-end t)
when (and tix (equal abbreviated-name (subzone-abbrev sz)))
collect (list zone sz (elt (timezone-transitions zone) tix)))))
(defun timezone= (timezone-1 timezone-2)
"Return two values indicating the relationship between timezone-1 and timezone-2. The first value is whether the two timezones are equal and the second value indicates whether it is sure or not.
In other words:
\(values t t) means timezone-1 and timezone-2 are definitely equal.
\(values nil t) means timezone-1 and timezone-2 are definitely different.
\(values nil nil) means that it couldn't be determined."
(if (or (eq timezone-1 timezone-2)
(equalp timezone-1 timezone-2))
(values t t)
(values nil nil)))
(defun reread-timezone-repository (&key (timezone-repository *default-timezone-repository-path*))
(check-type timezone-repository (or pathname string))
(let ((root-directory (uiop:directory-exists-p timezone-repository)))
(unless root-directory
(error "REREAD-TIMEZONE-REPOSITORY was called with invalid PROJECT-DIRECTORY (~A)."
timezone-repository))
(let ((cutoff-position (length (princ-to-string root-directory))))
(flet ((visitor (file)
(handler-case
(let* ((full-name (subseq (princ-to-string file) cutoff-position))
(timezone (%realize-timezone (make-timezone :path file :name full-name))))
(setf (gethash full-name *location-name->timezone*) timezone)
(map nil (lambda (subzone)
(push timezone (gethash (subzone-abbrev subzone)
*abbreviated-subzone-name->timezone-list*)))
(timezone-subzones timezone)))
(invalid-timezone-file () nil))))
(setf *location-name->timezone* (make-hash-table :test 'equal))
(setf *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal))
(uiop:collect-sub*directories root-directory
(constantly t)
(constantly t)
(lambda (dir)
(dolist (file (uiop:directory-files dir))
(when (not (find "Etc" (pathname-directory file)
:test #'string=))
(visitor file)))))
(uiop:collect-sub*directories (merge-pathnames "Etc/" root-directory)
(constantly t)
(constantly t)
(lambda (dir)
(dolist (file (uiop:directory-files dir))
(visitor file))))))))
(defmacro make-timestamp (&rest args)
`(make-instance 'timestamp ,@args))
(defun clone-timestamp (timestamp)
(make-instance 'timestamp
:nsec (nsec-of timestamp)
:sec (sec-of timestamp)
:day (day-of timestamp)))
(defun transition-position (needle haystack)
(declare (type integer needle)
(type (simple-array integer (*)) haystack))
(loop
with start = 0
with end = (1- (length haystack))
for middle = (floor (+ end start) 2)
while (and (< start end)
(/= needle (elt haystack middle)))
do (cond
((> needle (elt haystack middle))
(setf start (1+ middle)))
(t
(setf end (1- middle))))
finally
(return (max 0 (cond
((minusp end)
0)
((= needle (elt haystack middle))
middle)
((>= needle (elt haystack end))
end)
(t
(1- end)))))))
(defun timestamp-subtimezone (timestamp timezone)
"Return as multiple values the time zone as the number of seconds east of UTC, a boolean daylight-saving-p, and the customary abbreviation of the timezone."
(declare (type timestamp timestamp)
(type (or null timezone) timezone))
(let* ((zone (%realize-timezone (or timezone *default-timezone*)))
(unix-time (timestamp-to-unix timestamp))
(subzone-idx (if (zerop (length (timezone-indexes zone)))
0
(elt (timezone-indexes zone)
(transition-position unix-time
(timezone-transitions zone)))))
(subzone (elt (timezone-subzones zone) subzone-idx)))
(values
(subzone-offset subzone)
(subzone-daylight-p subzone)
(subzone-abbrev subzone))))
(defun %adjust-to-offset (sec day offset)
"Returns two values, the values of new DAY and SEC slots of the timestamp adjusted to the given timezone."
(declare (type integer sec day offset))
(multiple-value-bind (offset-day offset-sec)
(truncate offset +seconds-per-day+)
(let* ((new-sec (+ sec offset-sec))
(new-day (+ day offset-day)))
(cond ((minusp new-sec)
(incf new-sec +seconds-per-day+)
(decf new-day))
((>= new-sec +seconds-per-day+)
(incf new-day)
(decf new-sec +seconds-per-day+)))
(values new-sec new-day))))
(defun %adjust-to-timezone (source timezone &optional offset)
(%adjust-to-offset (sec-of source)
(day-of source)
(or offset
(timestamp-subtimezone source timezone))))
(defun timestamp-minimize-part (timestamp part &key
(timezone *default-timezone*)
into)
(let* ((timestamp-parts '(:nsec :sec :min :hour :day :month))
(part-count (position part timestamp-parts)))
(assert part-count nil
"timestamp-minimize-part called with invalid part ~a (expected one of ~a)"
part
timestamp-parts)
(multiple-value-bind (nsec sec min hour day month year day-of-week daylight-saving-time-p offset)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore nsec day-of-week daylight-saving-time-p))
(encode-timestamp 0
(if (> part-count 0) 0 sec)
(if (> part-count 1) 0 min)
(if (> part-count 2) 0 hour)
(if (> part-count 3) 1 day)
(if (> part-count 4) 1 month)
year
:offset (if timezone nil offset)
:timezone timezone
:into into))))
(defun timestamp-maximize-part (timestamp part &key
(timezone *default-timezone*)
into)
(let* ((timestamp-parts '(:nsec :sec :min :hour :day :month))
(part-count (position part timestamp-parts)))
(assert part-count nil
"timestamp-maximize-part called with invalid part ~a (expected one of ~a)"
part
timestamp-parts)
(multiple-value-bind (nsec sec min hour day month year day-of-week daylight-saving-time-p offset)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore nsec day-of-week daylight-saving-time-p))
(let ((month (if (> part-count 4) 12 month)))
(encode-timestamp 999999999
(if (> part-count 0) 59 sec)
(if (> part-count 1) 59 min)
(if (> part-count 2) 23 hour)
(if (> part-count 3) (days-in-month month year) day)
month
year
:offset (if timezone nil offset)
:timezone timezone
:into into)))))
(defmacro with-decoded-timestamp ((&key nsec sec minute hour day month year day-of-week daylight-p timezone offset)
timestamp &body forms)
"This macro binds variables to the decoded elements of TIMESTAMP. The TIMEZONE argument is used for decoding the timestamp, and is not bound by the macro. The value of DAY-OF-WEEK starts from 0 which means Sunday."
(let ((ignores)
(types)
(variables))
(macrolet ((initialize (&rest vars)
`(progn
,@(loop
:for var :in vars
:collect `(progn
(unless ,var
(setf ,var (gensym))
(push ,var ignores))
(push ,var variables)))
(setf ignores (nreverse ignores))
(setf variables (nreverse variables))))
(declare-fixnum-type (&rest vars)
`(progn
,@(loop
:for var :in vars
:collect `(when ,var
(push `(type fixnum ,,var) types)))
(setf types (nreverse types)))))
(when nsec
(push `(type (integer 0 999999999) ,nsec) types))
(declare-fixnum-type sec minute hour day month year)
(initialize nsec sec minute hour day month year day-of-week daylight-p))
`(multiple-value-bind (,@variables)
(decode-timestamp ,timestamp :timezone ,(or timezone '*default-timezone*) :offset ,offset)
(declare (ignore ,@ignores) ,@types)
,@forms)))
(defun %normalize-month-year-pair (month year)
"Normalizes the month/year pair: in case month is < 1 or > 12 the month and year are corrected to handle the overflow."
(multiple-value-bind (year-offset month-minus-one)
(floor (1- month) 12)
(values (1+ month-minus-one)
(+ year year-offset))))
(defun days-in-month (month year)
"Returns the number of days in the given month of the specified year."
(let ((normal-days (aref +rotated-month-days-without-leap-day+
(mod (+ month 9) 12))))
(if (and (= month 2)
(or (and (zerop (mod year 4))
(plusp (mod year 100)))
(zerop (mod year 400))))
February on a leap year
normal-days)))
TODO scan all uses of FIX - OVERFLOW - IN - DAYS and decide where it 's ok to silently fix and where should be and error reported
(defun %fix-overflow-in-days (day month year)
"In case the day number is higher than the maximal possible for the given month/year pair, returns the last day of the month."
(let ((max-day (days-in-month month year)))
(if (> day max-day)
max-day
day)))
(eval-when (:compile-toplevel :load-toplevel)
(defun %list-length= (num list)
"Tests for a list of length NUM without traversing the entire list to get the length."
(let ((c (nthcdr (1- num) list)))
(and c (endp (cdr c)))))
(defun %expand-adjust-timestamp-changes (timestamp changes visitor)
(loop
:with params = ()
:with functions = ()
:for change in changes
:do
(progn
(assert (or
(%list-length= 3 change)
(and (%list-length= 2 change)
(symbolp (first change))
(or (string= (first change) :timezone)
(string= (first change) :utc-offset)))
(and (%list-length= 4 change)
(symbolp (third change))
(or (string= (third change) :to)
(string= (third change) :by))))
nil "Syntax error in expression ~S" change)
(let ((operation (first change))
(part (second change))
(value (if (%list-length= 3 change)
(third change)
(fourth change))))
(cond
((string= operation :set)
(push `(%set-timestamp-part ,part ,value) functions))
((string= operation :offset)
(push `(%offset-timestamp-part ,part ,value) functions))
((string= operation :utc-offset)
(push part params)
(push :utc-offset params))
((string= operation :timezone)
(push part params)
(push :timezone params))
(t (error "Unexpected operation ~S" operation)))))
:finally
(loop
:for (function part value) in functions
:do
(funcall visitor `(,function ,timestamp ,part ,value ,@params)))))
(defun %expand-adjust-timestamp (timestamp changes &key functional)
(let* ((old (gensym "OLD"))
(new (if functional
(gensym "NEW")
old))
(forms (list)))
(%expand-adjust-timestamp-changes old changes
(lambda (change)
(push
`(progn
(multiple-value-bind (nsec sec day)
,change
(setf (nsec-of ,new) nsec)
(setf (sec-of ,new) sec)
(setf (day-of ,new) day))
,@(when functional
`((setf ,old ,new))))
forms)))
(setf forms (nreverse forms))
`(let* ((,old ,timestamp)
,@(when functional
`((,new (clone-timestamp ,old)))))
,@forms
,old)))
) ; eval-when
(defmacro adjust-timestamp (timestamp &body changes)
(%expand-adjust-timestamp timestamp changes :functional t))
(defmacro adjust-timestamp! (timestamp &body changes)
(%expand-adjust-timestamp timestamp changes :functional nil))
(defun %set-timestamp-part (time part new-value &key (timezone *default-timezone*) utc-offset)
;; TODO think about error signalling. when, how to disable if it makes sense, ...
(case part
((:nsec :sec-of-day :day)
(let ((nsec (nsec-of time))
(sec (sec-of time))
(day (day-of time)))
(case part
(:nsec (setf nsec (coerce new-value '(integer 0 999999999))))
(:sec-of-day (setf sec (coerce new-value `(integer 0 ,+seconds-per-day+))))
(:day (setf day new-value)))
(values nsec sec day)))
(otherwise
(with-decoded-timestamp (:nsec nsec :sec sec :minute minute :hour hour
:day day :month month :year year :timezone timezone :offset utc-offset)
time
(ecase part
(:sec (setf sec new-value))
(:minute (setf minute new-value))
(:hour (setf hour new-value))
(:day-of-month (setf day new-value))
(:month (setf month new-value)
(setf day (%fix-overflow-in-days day month year)))
(:year (setf year new-value)
(setf day (%fix-overflow-in-days day month year))))
(encode-timestamp-into-values nsec sec minute hour day month year :timezone timezone :offset utc-offset)))))
(defun %offset-timestamp-part (time part offset &key (timezone *default-timezone*) utc-offset)
"Returns a time adjusted by the specified OFFSET. Takes care of
different kinds of overflows. The setting :day-of-week is possible
using a keyword symbol name of a week-day (see
+DAY-NAMES-AS-KEYWORDS+) as value. In that case point the result to
day given by OFFSET in the week that contains TIME."
(labels ((direct-adjust (part offset nsec sec day)
(cond ((eq part :day-of-week)
(with-decoded-timestamp (:day-of-week day-of-week
:nsec nsec :sec sec :minute minute :hour hour
:day day :month month :year year
:timezone timezone :offset utc-offset)
time
(let ((position (position offset +day-names-as-keywords+ :test #'eq)))
(assert position (position) "~S is not a valid day name" offset)
(let ((offset (+ (- (if (zerop day-of-week)
7
day-of-week))
position)))
(incf day offset)
(cond
((< day 1)
(decf month)
(when (< month 1)
(setf month 12)
(decf year))
(setf day (+ (days-in-month month year) day)))
((let ((days-in-month (days-in-month month year)))
(when (< days-in-month day)
(incf month)
(when (= month 13)
(setf month 1)
(incf year))
(decf day days-in-month)))))
(encode-timestamp-into-values nsec sec minute hour day month year
:timezone timezone :offset utc-offset)))))
((zerop offset)
The offset is zero , so just return the parts of the timestamp object
(values nsec sec day))
(t
(let ((old-utc-offset (or utc-offset
(timestamp-subtimezone time timezone)))
new-utc-offset)
(tagbody
top
(ecase part
(:nsec
(multiple-value-bind (sec-offset new-nsec)
(floor (+ offset nsec) 1000000000)
;; the time might need to be adjusted a bit more if q != 0
(setf part :sec
offset sec-offset
nsec new-nsec)
(go top)))
((:sec :minute :hour)
(multiple-value-bind (days-offset new-sec)
(floor (+ sec (* offset (ecase part
(:sec 1)
(:minute +seconds-per-minute+)
(:hour +seconds-per-hour+))))
+seconds-per-day+)
(return-from direct-adjust (values nsec new-sec (+ day days-offset)))))
(:day
(incf day offset)
(setf new-utc-offset (or utc-offset
(timestamp-subtimezone (make-timestamp :nsec nsec :sec sec :day day)
timezone)))
(when (not (= old-utc-offset
new-utc-offset))
;; We hit the DST boundary. We need to restart again
with : sec , but this time we know both old and new
;; UTC offset will be the same, so it's safe to do
(setf part :sec
offset (- old-utc-offset
new-utc-offset)
old-utc-offset new-utc-offset)
(go top))
(return-from direct-adjust (values nsec sec day)))))))))
(safe-adjust (part offset time)
(with-decoded-timestamp (:nsec nsec :sec sec :minute minute :hour hour :day day
:month month :year year :timezone timezone :offset utc-offset)
time
(multiple-value-bind (month-new year-new)
(%normalize-month-year-pair
(+ (ecase part
(:month offset)
(:year (* 12 offset)))
month)
year)
;; Almost there. However, it is necessary to check for
overflows first
(encode-timestamp-into-values nsec sec minute hour
(%fix-overflow-in-days day month-new year-new)
month-new year-new
:timezone timezone :offset utc-offset)))))
(ecase part
((:nsec :sec :minute :hour :day :day-of-week)
(direct-adjust part offset
(nsec-of time)
(sec-of time)
(day-of time)))
((:month :year) (safe-adjust part offset time)))))
TODO merge this functionality into timestamp - difference
(defun timestamp-whole-year-difference (time-a time-b)
"Returns the number of whole years elapsed between time-a and time-b (hint: anniversaries)."
(declare (type timestamp time-b time-a))
(multiple-value-bind (nsec-b sec-b minute-b hour-b day-b month-b year-b day-of-week-b daylight-p-b offset-b)
(decode-timestamp time-b)
(declare (ignore day-of-week-b daylight-p-b))
(multiple-value-bind (nsec-a sec-a minute-a hour-a day-a month-a year-a)
(decode-timestamp time-a)
(declare (ignore nsec-a sec-a minute-a hour-a day-a month-a))
(let ((year-difference (- year-a year-b)))
(if (timestamp<= (encode-timestamp nsec-b sec-b minute-b hour-b
(if (= month-b 2)
(min 28 day-b)
day-b)
month-b
(+ year-difference year-b)
:offset offset-b)
time-a)
year-difference
(1- year-difference))))))
(defun timestamp-difference (time-a time-b)
"Returns the difference between TIME-A and TIME-B in seconds"
(let ((nsec (- (nsec-of time-a) (nsec-of time-b)))
(second (- (sec-of time-a) (sec-of time-b)))
(day (- (day-of time-a) (day-of time-b))))
(when (minusp nsec)
(decf second)
(incf nsec 1000000000))
(when (minusp second)
(decf day)
(incf second +seconds-per-day+))
(let ((result (+ (* day +seconds-per-day+)
second)))
(unless (zerop nsec)
this incf turns the result into a float , so only do this when necessary
(incf result (/ nsec 1000000000d0)))
result)))
(defun timestamp+ (time amount unit &optional (timezone *default-timezone*) offset)
(multiple-value-bind (nsec sec day)
(%offset-timestamp-part time unit amount :timezone timezone :utc-offset offset)
(make-timestamp :nsec nsec
:sec sec
:day day)))
(defun timestamp- (time amount unit &optional (timezone *default-timezone*) offset)
(timestamp+ time (- amount) unit timezone offset))
(defun timestamp-day-of-week (timestamp &key (timezone *default-timezone*) offset)
(mod (+ 3 (nth-value 1 (%adjust-to-timezone timestamp timezone offset))) 7))
TODO read
;;
;; (or something else, sorry :) this scheme only works back until
1582 , the start of the gregorian calendar . see also
;; DECODE-TIMESTAMP when fixing if fixing is desired at all.
(defun valid-timestamp-p (nsec sec minute hour day month year)
"Returns T if the time values refer to a valid time, otherwise returns NIL."
(and (<= 0 nsec 999999999)
(<= 0 sec 59)
(<= 0 minute 59)
(<= 0 hour 23)
(<= 1 month 12)
(<= 1 day (days-in-month month year))
(/= year 0)))
(defun encode-timestamp-into-values (nsec sec minute hour day month year
&key (timezone *default-timezone*) offset)
"Returns (VALUES NSEC SEC DAY ZONE) ready to be used for
instantiating a new timestamp object. If the specified time is
invalid, the condition INVALID-TIME-SPECIFICATION is raised."
;; If the user provided an explicit offset, we use that. Otherwise,
(declare (type integer nsec sec minute hour day month year)
(type (or integer null) offset))
(unless (valid-timestamp-p nsec sec minute hour day month year)
(error 'invalid-time-specification))
(let* ((0-based-rotated-month (if (>= month 3)
(- month 3)
(+ month 9)))
(internal-year (if (< month 3)
(- year 2001)
(- year 2000)))
(years-as-days (years-to-days internal-year))
(sec (+ (* hour +seconds-per-hour+)
(* minute +seconds-per-minute+)
sec))
(days-from-zero-point (+ years-as-days
(aref +rotated-month-offsets-without-leap-day+ 0-based-rotated-month)
(1- day)))
(used-offset (or offset
(%guess-offset sec
days-from-zero-point
timezone))))
(multiple-value-bind (utc-sec utc-day)
(%adjust-to-offset sec days-from-zero-point (- used-offset))
(values nsec utc-sec utc-day))))
(defun encode-timestamp (nsec sec minute hour day month year
&key (timezone *default-timezone*) offset into)
"Return a new TIMESTAMP instance corresponding to the specified time
elements."
(declare (type integer nsec sec minute hour day month year))
(multiple-value-bind (nsec sec day)
(encode-timestamp-into-values nsec sec minute hour day month year
:timezone timezone :offset offset)
(if into
(progn
(setf (nsec-of into) nsec)
(setf (sec-of into) sec)
(setf (day-of into) day)
into)
(make-timestamp
:nsec nsec
:sec sec
:day day))))
(defun universal-to-timestamp (universal &key (nsec 0))
"Returns a timestamp corresponding to the given universal time."
universal time is seconds from 1900 - 01 - 01T00:00:00Z.
(let ((adjusted-universal (- universal #.(encode-universal-time 0 0 0 1 3 2000 0))))
(multiple-value-bind (day second)
(floor adjusted-universal +seconds-per-day+)
(make-timestamp :day day :sec second :nsec nsec))))
(defun timestamp-to-universal (timestamp)
"Return the UNIVERSAL-TIME corresponding to the TIMESTAMP"
universal time is seconds from 1900 - 01 - 01T00:00:00Z
(+ (* (day-of timestamp) +seconds-per-day+)
(sec-of timestamp)
#.(encode-universal-time 0 0 0 1 3 2000 0)))
(defun unix-to-timestamp (unix &key (nsec 0))
"Return a TIMESTAMP corresponding to UNIX, which is the number of seconds since the unix epoch, 1970-01-01T00:00:00Z."
(multiple-value-bind (days secs)
(floor unix +seconds-per-day+)
(make-timestamp :day (- days 11017) :sec secs :nsec nsec)))
(defun timestamp-values-to-unix (seconds day)
"Return the Unix time correspondint to the values used to encode a TIMESTAMP"
(+ (* (+ day 11017) +seconds-per-day+) seconds))
(defun timestamp-to-unix (timestamp)
"Return the Unix time corresponding to the TIMESTAMP"
(declare (type timestamp timestamp))
(timestamp-values-to-unix (sec-of timestamp) (day-of timestamp)))
#+(and allegro (not os-windows))
(eval-when (:compile-toplevel :load-toplevel :execute)
Allegro common lisp requires some toplevel hoops through which to
;; jump in order to call unix's gettimeofday properly.
(ff:def-foreign-type timeval
(:struct (tv_sec :long)
(tv_usec :long)))
(ff:def-foreign-call
(allegro-ffi-gettimeofday "gettimeofday")
((timeval (* timeval))
;; and do this to allow a 0 for NULL
(timezone :foreign-address))
:returning (:int fixnum)))
#+(and allegro os-windows)
(eval-when (:compile-toplevel :load-toplevel :execute)
Allegro common lisp requires some toplevel hoops through which to
;; jump in order to call unix's gettimeofday properly.
(ff:def-foreign-type filetime
(:struct (|dwLowDateTime| :int)
(|dwHighDateTime| :int)))
(ff:def-foreign-call
(allegro-ffi-get-system-time-as-file-time "GetSystemTimeAsFileTime")
((filetime (* filetime)))
:returning :void))
#+(or (and allegro os-windows)
(and ccl windows))
(defun filetime-to-current-time (low high)
"Convert a Windows time into (values sec nano-sec)."
(let* ((unix-epoch-filetime 116444736000000000)
(filetime (logior low (ash high 32)))
(filetime (- filetime unix-epoch-filetime)))
(multiple-value-bind (secs 100ns-periods)
(floor filetime #.(round 1e7))
(values secs (* 100ns-periods 100)))))
#+(and lispworks (or linux darwin))
(progn
(fli:define-c-typedef time-t :long)
(fli:define-c-typedef suseconds-t #+linux :long
#+darwin :int)
(fli:define-c-struct timeval
(tv-sec time-t)
(tv-usec suseconds-t))
(fli:define-foreign-function (gettimeofday/ffi "gettimeofday")
((tv (:pointer (:struct timeval)))
(tz :pointer))
:result-type :int)
(defun lispworks-gettimeofday ()
(declare (optimize speed (safety 1)))
(fli:with-dynamic-foreign-objects ((tv (:struct timeval)))
(let ((ret (gettimeofday/ffi tv fli:*null-pointer*)))
(assert (zerop ret) nil "gettimeofday failed")
(let ((secs
(fli:foreign-slot-value tv 'tv-sec
:type 'time-t
:object-type '(:struct timeval)))
(usecs
(fli:foreign-slot-value tv 'tv-usec
:type 'suseconds-t
:object-type '(:struct timeval))))
(values secs (* 1000 usecs)))))))
(defun %get-current-time ()
"Cross-implementation abstraction to get the current time measured from the unix epoch (1/1/1970). Should return (values sec nano-sec)."
#+(and allegro (not os-windows))
(flet ((allegro-gettimeofday ()
(let ((tv (ff:allocate-fobject 'timeval :c)))
(allegro-ffi-gettimeofday tv 0)
(let ((sec (ff:fslot-value-typed 'timeval :c tv 'tv_sec))
(usec (ff:fslot-value-typed 'timeval :c tv 'tv_usec)))
(ff:free-fobject tv)
(values sec usec)))))
(multiple-value-bind (sec usec) (allegro-gettimeofday)
(values sec (* 1000 usec))))
#+(and allegro os-windows)
(let* ((ft (ff:allocate-fobject 'filetime :c)))
(allegro-ffi-get-system-time-as-file-time ft)
(let* ((low (ff:fslot-value-typed 'filetime :c ft '|dwLowDateTime|))
(high (ff:fslot-value-typed 'filetime :c ft '|dwHighDateTime|)))
(filetime-to-current-time low high)))
#+cmu
(multiple-value-bind (success? sec usec) (unix:unix-gettimeofday)
(assert success? () "unix:unix-gettimeofday reported failure?!")
(values sec (* 1000 usec)))
#+sbcl
(progn
available from sbcl 1.0.28.66
(multiple-value-bind (sec nsec) (sb-ext:get-time-of-day)
(values sec (* 1000 nsec)))
obsolete , scheduled to be deleted at the end of 2009
(multiple-value-bind (success? sec nsec) (sb-unix:unix-gettimeofday)
(assert success? () "sb-unix:unix-gettimeofday reported failure?!")
(values sec (* 1000 nsec))))
#+(and ccl (not windows))
(ccl:rlet ((tv :timeval))
(let ((err (ccl:external-call "gettimeofday" :address tv :address (ccl:%null-ptr) :int)))
(assert (zerop err) nil "gettimeofday failed")
(values (ccl:pref tv :timeval.tv_sec) (* 1000 (ccl:pref tv :timeval.tv_usec)))))
#+(and ccl windows)
(ccl:rlet ((time :<lpfiletime>))
(ccl:external-call "GetSystemTimeAsFileTime" :<lpfiletime> time :void)
(let* ((low (ccl:%get-unsigned-long time (/ 0 8)))
(high (ccl:%get-unsigned-long time (/ 32 8))))
(filetime-to-current-time low high)))
#+abcl
(multiple-value-bind (sec millis)
(truncate (java:jstatic "currentTimeMillis" "java.lang.System") 1000)
(values sec (* millis 1000000)))
#+(and lispworks (or linux darwin))
(lispworks-gettimeofday)
#-(or allegro cmu sbcl abcl ccl (and lispworks (or linux darwin)))
(values (- (get-universal-time)
CL 's get - universal - time uses an epoch of 1/1/1900 , so adjust the result to the Unix epoch
#.(encode-universal-time 0 0 0 1 1 1970 0))
0))
(defvar *clock* t
"Use the `*clock*' special variable if you need to define your own idea of the current time.
The value of this variable should have the methods `local-time::clock-now', and
`local-time::clock-today'. The currently supported values in local-time are:
t - use the standard clock
local-time:leap-second-adjusted - use a clock which adjusts for leap seconds using the information in *default-timezone*.")
(defun now ()
"Returns a timestamp representing the present moment."
(clock-now *clock*))
(defun today ()
"Returns a timestamp representing the present day."
(clock-today *clock*))
(defgeneric clock-now (clock)
(:documentation "Returns a timestamp for the current time given a clock."))
(defgeneric clock-today (clock)
(:documentation "Returns a timestamp for the current date given a
clock. The date is encoded by convention as a timestamp with the
time set to 00:00:00UTC."))
(defun %leap-seconds-offset (leap-seconds sec)
"Find the latest leap second adjustment effective at SEC system time."
(elt (leap-seconds-adjustment leap-seconds)
(transition-position sec (leap-seconds-sec leap-seconds))))
(defun %adjust-sec-for-leap-seconds (sec)
"Ajdust SEC from system time to Unix time (on systems those clock does not jump back over leap seconds)."
(let ((leap-seconds (timezone-leap-seconds (%realize-timezone *default-timezone*))))
(when leap-seconds
(decf sec (%leap-seconds-offset leap-seconds sec))))
sec)
(defmethod clock-now ((clock (eql 'leap-second-adjusted)))
(multiple-value-bind (sec nsec) (%get-current-time)
(unix-to-timestamp (%adjust-sec-for-leap-seconds sec)
:nsec nsec)))
(defmethod clock-now (clock)
(declare (ignore clock))
(multiple-value-bind (sec nsec) (%get-current-time)
(unix-to-timestamp sec :nsec nsec)))
(defmethod clock-today (clock)
(declare (ignore clock))
TODO should return a date value , anyhow we will decide to represent it eventually
(let ((result (now)))
(setf (sec-of result) 0)
(setf (nsec-of result) 0)
result))
(defmacro %defcomparator (name &body body)
(let ((pair-comparator-name (intern (concatenate 'string "%" (string name)))))
`(progn
(declaim (inline ,pair-comparator-name))
(defun ,pair-comparator-name (time-a time-b)
(assert (typep time-a 'timestamp)
nil
'type-error
:datum time-a
:expected-type 'timestamp)
(assert (typep time-b 'timestamp)
nil
'type-error
:datum time-b
:expected-type 'timestamp)
,@body)
(defun ,name (&rest times)
(declare (dynamic-extent times))
(loop for head on times
while (cdr head)
always (,pair-comparator-name (first head) (second head))))
(define-compiler-macro ,name (&rest times)
(let ((vars (loop
:for i :upfrom 0 :below (length times)
:collect (gensym (concatenate 'string "TIME-" (princ-to-string i) "-")))))
`(let (,@(loop
:for var :in vars
:for time :in times
:collect (list var time)))
;; we could evaluate comparisons of timestamp literals here
(and ,@(loop
:for (time-a time-b) :on vars
:while time-b
:collect `(,',pair-comparator-name ,time-a ,time-b)))))))))
(defun %timestamp-compare (time-a time-b)
"Returns the symbols <, >, or =, describing the relationship between TIME-A and TIME-b."
(declare (type timestamp time-a time-b))
(cond
((< (day-of time-a) (day-of time-b)) '<)
((> (day-of time-a) (day-of time-b)) '>)
((< (sec-of time-a) (sec-of time-b)) '<)
((> (sec-of time-a) (sec-of time-b)) '>)
((< (nsec-of time-a) (nsec-of time-b)) '<)
((> (nsec-of time-a) (nsec-of time-b)) '>)
(t '=)))
(%defcomparator timestamp<
(eql (%timestamp-compare time-a time-b) '<))
(%defcomparator timestamp<=
(not (null (member (%timestamp-compare time-a time-b) '(< =)))))
(%defcomparator timestamp>
(eql (%timestamp-compare time-a time-b) '>))
(%defcomparator timestamp>=
(not (null (member (%timestamp-compare time-a time-b) '(> =)))))
(%defcomparator timestamp=
(eql (%timestamp-compare time-a time-b) '=))
(defun timestamp/= (&rest timestamps)
"Returns T if no pair of timestamps is equal. Otherwise return NIL."
(declare (dynamic-extent timestamps))
(loop for ts-head on timestamps do
(loop for ts in (rest ts-head) do
(when (timestamp= (car ts-head) ts)
(return-from timestamp/= nil))))
t)
(defun contest (test list)
"Applies TEST to pairs of elements in list, keeping the element which last tested T. Returns the winning element."
(reduce (lambda (a b) (if (funcall test a b) a b)) list))
(defun timestamp-minimum (time &rest times)
"Returns the earliest timestamp"
(contest #'timestamp< (cons time times)))
(defun timestamp-maximum (time &rest times)
"Returns the latest timestamp"
(contest #'timestamp> (cons time times)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun years-to-days (years)
"Given a number of years, returns the number of days in those years."
(let* ((days (* years 365))
(l1 (floor years 4))
(l2 (floor years 100))
(l3 (floor years 400)))
(+ days l1 (- l2) l3))))
(defun days-to-years (days)
"Given a number of days, returns the number of years and the remaining days in that year."
(let ((remaining-days days))
(multiple-value-bind (400-years remaining-days)
(floor remaining-days #.(years-to-days 400))
(let* ((100-years (min (floor remaining-days #.(years-to-days 100)) 3))
(remaining-days (- remaining-days
(* 100-years #.(years-to-days 100)))))
(multiple-value-bind (4-years remaining-days)
(floor remaining-days #.(years-to-days 4))
(let ((years (min 3 (floor remaining-days #.(years-to-days 1)))))
(values (+ (* 400-years 400)
(* 100-years 100)
(* 4-years 4)
years)
(- remaining-days (* years 365))))))))
the above is the macroexpansion of the following . uses , but kept for clarity because the expansion is unreadable .
#+nil
(bind ((remaining-days days)
((values 400-years remaining-days) (floor remaining-days #.(years-to-days 400)))
(100-years (min (floor remaining-days #.(years-to-days 100))
3))
(remaining-days (- remaining-days
(* 100-years
#.(years-to-days 100))))
((values 4-years remaining-days) (floor remaining-days #.(years-to-days 4)))
(years (min (floor remaining-days 365)
3)))
(values (+ (* 400-years 400)
(* 100-years 100)
(* 4-years 4)
years)
(- remaining-days (* years 365)))))
(defun %timestamp-decode-date (days)
"Returns the year, month, and day, given the number of days from the epoch."
(declare (type integer days))
(multiple-value-bind (years remaining-days)
(days-to-years days)
(let* ((leap-day-p (= remaining-days 365))
(rotated-1-based-month (if leap-day-p
march is the first month and february is the last
(position remaining-days +rotated-month-offsets-without-leap-day+ :test #'<)))
(1-based-month (if (>= rotated-1-based-month 11)
(- rotated-1-based-month 10)
(+ rotated-1-based-month 2)))
(1-based-day (if leap-day-p
29
(1+ (- remaining-days (aref +rotated-month-offsets-without-leap-day+
(1- rotated-1-based-month)))))))
(values
(+ years
january is in the next year
2001
2000))
1-based-month
1-based-day))))
(defun %timestamp-decode-iso-week (timestamp)
"Returns the year, week number, and day of week components of an ISO week date."
Algorithm from :ISO_week_date#Algorithms
(let* ((dn (timestamp-day-of-week timestamp))
ISO weekdays are Monday=1 and Sunday=7
(nearest-thursday (timestamp+ timestamp (- 4 day-of-week) :day))
(year (timestamp-year nearest-thursday))
(month (timestamp-month nearest-thursday))
(day (timestamp-day nearest-thursday))
(ordinal-day (- (day-of (encode-timestamp 0 0 0 0 day month year :timezone +utc-zone+))
(day-of (encode-timestamp 0 0 0 0 1 1 year :timezone +utc-zone+)))))
(values year
(1+ (floor ordinal-day 7))
day-of-week)))
(defun %timestamp-decode-time (seconds)
"Returns the hours, minutes, and seconds, given the number of seconds since midnight."
(declare (type integer seconds))
(multiple-value-bind (hours hour-remainder)
(floor seconds +seconds-per-hour+)
(multiple-value-bind (minutes seconds)
(floor hour-remainder +seconds-per-minute+)
(values
hours
minutes
seconds))))
(defun decode-timestamp (timestamp &key (timezone *default-timezone*) offset)
"Returns the decoded time as multiple values: nsec, ss, mm, hh, day, month, year, day-of-week"
(declare (type timestamp timestamp))
(let ((timezone (if offset (the timezone +none-zone+) timezone)))
(multiple-value-bind (offset* daylight-p abbreviation)
(timestamp-subtimezone timestamp timezone)
(multiple-value-bind (adjusted-secs adjusted-days)
(%adjust-to-timezone timestamp timezone offset)
(multiple-value-bind (hours minutes seconds)
(%timestamp-decode-time adjusted-secs)
(multiple-value-bind (year month day)
(%timestamp-decode-date adjusted-days)
(values
(nsec-of timestamp)
seconds minutes hours
day month year
(timestamp-day-of-week timestamp :timezone timezone :offset offset)
daylight-p
(or offset offset*)
abbreviation)))))))
(defun timestamp-year (timestamp &key (timezone *default-timezone*))
"Returns the cardinal year upon which the timestamp falls."
(nth-value 0
(%timestamp-decode-date
(nth-value 1 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-century (timestamp &key (timezone *default-timezone*))
"Returns the ordinal century upon which the timestamp falls."
(let* ((year (timestamp-year timestamp :timezone timezone))
(sign (signum year)))
(+ sign
(* sign
(truncate (1- (abs year)) 100)))))
(defun timestamp-millennium (timestamp &key (timezone *default-timezone*))
"Returns the ordinal millennium upon which the timestamp falls."
(let* ((year (timestamp-year timestamp :timezone timezone))
(sign (signum year)))
(+ sign
(* sign
(truncate (1- (abs year)) 1000)))))
(defun timestamp-decade (timestamp &key (timezone *default-timezone*))
"Returns the cardinal decade upon which the timestamp falls."
(truncate (timestamp-year timestamp :timezone timezone) 10))
(defun timestamp-month (timestamp &key (timezone *default-timezone*))
"Returns the month upon which the timestamp falls."
(nth-value 1
(%timestamp-decode-date
(nth-value 1 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-day (timestamp &key (timezone *default-timezone*))
"Returns the day of the month upon which the timestamp falls."
(nth-value 2
(%timestamp-decode-date
(nth-value 1 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-hour (timestamp &key (timezone *default-timezone*))
(nth-value 0
(%timestamp-decode-time
(nth-value 0 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-minute (timestamp &key (timezone *default-timezone*))
(nth-value 1
(%timestamp-decode-time
(nth-value 0 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-second (timestamp &key (timezone *default-timezone*))
(nth-value 2
(%timestamp-decode-time
(nth-value 0 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-microsecond (timestamp)
(floor (nsec-of timestamp) 1000))
(defun timestamp-millisecond (timestamp)
(floor (nsec-of timestamp) 1000000))
(defun split-timestring (str &rest args)
(declare (inline))
(apply #'%split-timestring (coerce str 'simple-string) args))
(defun %split-timestring (time-string &key
(start 0)
(end (length time-string))
(fail-on-error t) (time-separator #\:)
(date-separator #\-)
(date-time-separator #\T)
(fract-time-separators '(#\. #\,))
(allow-missing-elements t)
(allow-missing-date-part allow-missing-elements)
(allow-missing-time-part allow-missing-elements)
(allow-missing-timezone-part allow-missing-time-part))
"Based on including the function names used. Returns (values year month day hour minute second nsec offset-hour offset-minute). On parsing failure, signals INVALID-TIMESTRING if FAIL-ON-ERROR is NIL, otherwise returns NIL."
(declare (type character date-time-separator time-separator date-separator)
(type simple-string time-string)
(optimize (speed 3)))
(the list
(let (year month day hour minute second nsec offset-hour offset-minute)
(declare (type (or null fixnum) start end year month day hour minute second offset-hour offset-minute)
(type (or null (signed-byte 32)) nsec))
(macrolet ((passert (expression)
`(unless ,expression
(parse-error ',expression)))
(parse-integer-into (start-end place &optional low-limit high-limit)
(let ((entry (gensym "ENTRY"))
(value (gensym "VALUE"))
(pos (gensym "POS"))
(start (gensym "START"))
(end (gensym "END")))
`(let ((,entry ,start-end))
(if ,entry
(let ((,start (car ,entry))
(,end (cdr ,entry)))
(multiple-value-bind (,value ,pos) (parse-integer time-string :start ,start :end ,end :junk-allowed t)
(passert (= ,pos ,end))
(setf ,place ,value)
,(if (and low-limit high-limit)
`(passert (<= ,low-limit ,place ,high-limit))
(values))
(values)))
(progn
(passert allow-missing-elements)
(values))))))
(with-parts-and-count ((start end split-chars) &body body)
`(multiple-value-bind (parts count) (split ,start ,end ,split-chars)
(declare (ignorable count) (type fixnum count)
( type # 1=(cons ( cons fixnum fixnum ) ( or null # 1 # ) ) parts )
(type list parts))
,@body)))
(labels ((split (start end chars)
(declare (type fixnum start end))
(unless (consp chars)
(setf chars (list chars)))
(loop with last-match = start
with match-count of-type (integer 0 #.most-positive-fixnum) = 0
for index of-type fixnum upfrom start
while (< index end)
when (member (aref time-string index) chars :test #'char-equal)
collect (prog1 (if (< last-match index)
(cons last-match index)
nil)
(incf match-count)
(setf last-match (1+ index)))
into result
finally (return (values (if (zerop (- index last-match))
result
(prog1
(nconc result (list (cons last-match index)))
(incf match-count)))
match-count))))
(parse ()
(with-parts-and-count (start end date-time-separator)
(cond ((= count 2)
(if (first parts)
(full-date (first parts))
(passert allow-missing-date-part))
(if (second parts)
(full-time (second parts))
(passert allow-missing-time-part))
(done))
((and (= count 1)
allow-missing-date-part
(find time-separator time-string
:start (car (first parts))
:end (cdr (first parts))))
(full-time (first parts))
(done))
((and (= count 1)
allow-missing-time-part
(find date-separator time-string
:start (car (first parts))
:end (cdr (first parts))))
(full-date (first parts))
(done)))
(parse-error nil)))
(full-date (start-end)
(let ((parts (split (car start-end) (cdr start-end) date-separator)))
(passert (%list-length= 3 parts))
(date-fullyear (first parts))
(date-month (second parts))
(date-mday (third parts))))
(date-fullyear (start-end)
(parse-integer-into start-end year))
(date-month (start-end)
(parse-integer-into start-end month 1 12))
(date-mday (start-end)
(parse-integer-into start-end day 1 31))
(full-time (start-end)
(let ((start (car start-end))
(end (cdr start-end)))
(with-parts-and-count (start end (list #\Z #\- #\+))
(let* ((zulup (find #\Z time-string :test #'char-equal :start start :end end))
(sign (unless zulup
(if (find #\+ time-string :test #'char-equal :start start :end end)
1
-1))))
(passert (<= 1 count 2))
(unless (and (eq (first parts) nil)
(not (rest parts)))
;; not a single #\Z
(partial-time (first parts)))
(when zulup
(setf offset-hour 0
offset-minute 0))
(if (= count 1)
(passert (or zulup allow-missing-timezone-part))
(let* ((entry (second parts))
(start (car entry))
(end (cdr entry)))
(declare (type fixnum start end))
(passert (or zulup
(not (zerop (- end start)))))
(unless zulup
(time-offset (second parts) sign))))))))
(partial-time (start-end)
(with-parts-and-count ((car start-end) (cdr start-end) time-separator)
(passert (eql count 3))
(time-hour (first parts))
(time-minute (second parts))
(time-second (third parts))))
(time-hour (start-end)
(parse-integer-into start-end hour 0 23))
(time-minute (start-end)
(parse-integer-into start-end minute 0 59))
(time-second (start-end)
(with-parts-and-count ((car start-end) (cdr start-end) fract-time-separators)
(passert (<= 1 count 2))
(let ((*read-eval* nil))
(parse-integer-into (first parts) second 0 59)
(if (> count 1)
(let* ((start (car (second parts)))
(end (cdr (second parts))))
(declare (type (integer 0 #.array-dimension-limit) start end))
(passert (<= (- end start) 9))
(let ((new-end (position #\0 time-string
:test-not #'eql
:start start
:end end
:from-end t)))
(when new-end
(setf end (min (1+ new-end)))))
(setf nsec (* (the (integer 0 999999999) (parse-integer time-string :start start :end end))
(aref #.(coerce #(1000000000 100000000 10000000
1000000 100000 10000 1000 100 10 1)
'(simple-array (signed-byte 32) (10)))
(- end start)))))
(setf nsec 0)))))
(time-offset (start-end sign)
(with-parts-and-count ((car start-end) (cdr start-end) time-separator)
(passert (or (and allow-missing-timezone-part (zerop count))
(= count 1)
(= count 2)))
(cond
((= count 2)
hh : offset
(parse-integer-into (first parts) offset-hour 0 23)
(parse-integer-into (second parts) offset-minute 0 59))
((= (- (cdar parts) (caar parts)) 4)
;; hhmm offset
(parse-integer-into (cons (caar parts)
(+ (caar parts) 2))
offset-hour 0 23)
(parse-integer-into (cons (+ (caar parts) 2)
(+ (caar parts) 4))
offset-minute 0 59))
((= (- (cdar parts) (caar parts)) 2)
;; hh offset
(parse-integer-into (cons (caar parts)
(+ (caar parts) 2))
offset-hour 0 23)
(setf offset-minute 0)))
(setf offset-hour (* offset-hour sign)
offset-minute (* offset-minute sign))))
(parse-error (failure)
(if fail-on-error
(error 'invalid-timestring :timestring time-string :failure failure)
(return-from %split-timestring nil)))
(done ()
(return-from %split-timestring (list year month day hour minute second nsec offset-hour offset-minute))))
(parse))))))
(defun parse-rfc3339-timestring (timestring &key (fail-on-error t)
(allow-missing-time-part nil))
(parse-timestring timestring :fail-on-error fail-on-error
:allow-missing-timezone-part nil
:allow-missing-time-part allow-missing-time-part
:allow-missing-date-part nil
:fract-time-separators #\.))
(defun parse-timestring (timestring &key
start
end
(fail-on-error t)
(time-separator #\:)
(date-separator #\-)
(date-time-separator #\T)
(fract-time-separators '(#\. #\,))
(allow-missing-elements t)
(allow-missing-date-part allow-missing-elements)
(allow-missing-time-part allow-missing-elements)
(allow-missing-timezone-part allow-missing-elements)
(offset 0))
"Parse a timestring and return the corresponding TIMESTAMP.
See split-timestring for details. Unspecified fields in the
timestring are initialized to their lowest possible value,
and timezone offset is 0 (UTC) unless explicitly specified
in the input string."
(let ((parts (%split-timestring (coerce timestring 'simple-string)
:start (or start 0)
:end (or end (length timestring))
:fail-on-error fail-on-error
:time-separator time-separator
:date-separator date-separator
:date-time-separator date-time-separator
:fract-time-separators fract-time-separators
:allow-missing-elements allow-missing-elements
:allow-missing-date-part allow-missing-date-part
:allow-missing-time-part allow-missing-time-part
:allow-missing-timezone-part allow-missing-timezone-part)))
(when parts
(destructuring-bind (year month day hour minute second nsec offset-hour offset-minute)
parts
(encode-timestamp
(or nsec 0)
(or second 0)
(or minute 0)
(or hour 0)
(or day 1)
(or month 3)
(or year 2000)
:offset (if offset-hour
(+ (* offset-hour 3600)
(* (or offset-minute 0) 60))
offset))))))
(defun ordinalize (day)
"Return an ordinal string representing the position
of DAY in a sequence (1st, 2nd, 3rd, 4th, etc)."
(declare (type (integer 1 31) day))
(format nil "~d~a" day
(if (<= 11 day 13)
"th"
(case (mod day 10)
(1 "st")
(2 "nd")
(3 "rd")
(t "th")))))
(defun %construct-timestring (timestamp format timezone)
"Constructs a string representing TIMESTAMP given the FORMAT
of the string and the TIMEZONE.
See the documentation of FORMAT-TIMESTRING for the structure of FORMAT."
(declare (type timestamp timestamp)
(optimize (speed 3)))
(multiple-value-bind (nsec sec minute hour day month year weekday daylight-p offset abbrev)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore daylight-p))
(multiple-value-bind (iso-year iso-week iso-weekday)
(%timestamp-decode-iso-week timestamp)
(let ((*print-pretty* nil)
(*print-circle* nil))
(with-output-to-string (result nil)
(dolist (fmt format)
(cond
((member fmt '(:gmt-offset :gmt-offset-or-z :gmt-offset-hhmm))
(multiple-value-bind (offset-hours offset-secs)
(floor offset +seconds-per-hour+)
(declare (fixnum offset-hours offset-secs))
(if (and (eql fmt :gmt-offset-or-z) (zerop offset))
(princ #\Z result)
(format result "~c~2,'0d~:[:~;~]~2,'0d"
(if (minusp offset-hours) #\- #\+)
(abs offset-hours)
(eql fmt :gmt-offset-hhmm)
(truncate (abs offset-secs)
+seconds-per-minute+)))))
((eql fmt :short-year)
(princ (mod year 100) result))
((eql fmt :long-month)
(princ (aref +month-names+ month) result))
((eql fmt :short-month)
(princ (aref +short-month-names+ month) result))
((eql fmt :long-weekday)
(princ (aref +day-names+ weekday) result))
((eql fmt :short-weekday)
(princ (aref +short-day-names+ weekday) result))
((eql fmt :minimal-weekday)
(princ (aref +minimal-day-names+ weekday) result))
((eql fmt :timezone)
(princ abbrev result))
((eql fmt :ampm)
(princ (if (< hour 12) "am" "pm") result))
((eql fmt :ordinal-day)
(princ (ordinalize day) result))
((or (stringp fmt) (characterp fmt))
(princ fmt result))
(t
(let ((val (ecase (if (consp fmt) (car fmt) fmt)
(:nsec nsec)
(:usec (floor nsec 1000))
(:msec (floor nsec 1000000))
(:sec sec)
(:min minute)
(:hour hour)
(:hour12 (1+ (mod (1- hour) 12)))
(:day day)
(:weekday weekday)
(:month month)
(:year year)
(:iso-week-year iso-year)
(:iso-week-number iso-week)
(:iso-week-day iso-weekday))))
(cond
((atom fmt)
(princ val result))
((minusp val)
(format result "-~v,vd"
(second fmt)
(or (third fmt) #\0)
(abs val)))
(t
(format result "~v,vd"
(second fmt)
(or (third fmt) #\0)
val))))))))))))
(defun format-timestring (destination timestamp &key
(format +iso-8601-format+)
(timezone *default-timezone*))
"Constructs a string representation of TIMESTAMP according
to FORMAT and returns it.
If destination is T, the string is written to *standard-output*.
If destination is a stream, the string is written to the stream.
FORMAT is a list containing one or more of strings, characters,
and keywords. Strings and characters are output literally,
while keywords are replaced by the values here:
:YEAR *year
:MONTH *numeric month
:DAY *day of month
:HOUR *hour
:MIN *minutes
:SEC *seconds
:WEEKDAY *numeric day of week starting from index 0, which means Sunday
:MSEC *milliseconds
:USEC *microseconds
:NSEC *nanoseconds
:ISO-WEEK-YEAR *year for ISO week date (can be different from regular calendar year)
:ISO-WEEK-NUMBER *ISO week number (i.e. 1 through 53)
:ISO-WEEK-DAY *ISO compatible weekday number (monday=1, sunday=7)
:LONG-WEEKDAY long form of weekday (e.g. Sunday, Monday)
:SHORT-WEEKDAY short form of weekday (e.g. Sun, Mon)
:MINIMAL-WEEKDAY minimal form of weekday (e.g. Su, Mo)
:SHORT-YEAR short form of year (last 2 digits, e.g. 41, 42 instead of 2041, 2042)
:LONG-MONTH long form of month (e.g. January, February)
:SHORT-MONTH short form of month (e.g. Jan, Feb)
:HOUR12 *hour on a 12-hour clock
:AMPM am/pm marker in lowercase
:GMT-OFFSET the gmt-offset of the time, in +00:00 form
:GMT-OFFSET-OR-Z like :GMT-OFFSET, but is Z when UTC
:GMT-OFFSET-HHMM like :GMT-OFFSET, but in +0000 form
:TIMEZONE timezone abbrevation for the time
Elements marked by * can be placed in a list in the form
\(:keyword padding &optional \(padchar #\\0))
The string representation of the value will be padded with the padchar.
You can see examples in +ISO-8601-FORMAT+, +ASCTIME-FORMAT+, and +RFC-1123-FORMAT+."
(declare (type (or boolean stream) destination))
(let ((result (%construct-timestring timestamp format timezone)))
(when destination
(write-string result (if (eq t destination) *standard-output* destination)))
result))
(defun format-rfc1123-timestring (destination timestamp &key
(timezone *default-timezone*))
(format-timestring destination timestamp
:format +rfc-1123-format+
:timezone timezone))
(defun to-rfc1123-timestring (timestamp)
(format-rfc1123-timestring nil timestamp))
(defun format-rfc3339-timestring (destination timestamp &key
omit-date-part
omit-time-part
(omit-timezone-part omit-time-part)
(use-zulu t)
(timezone *default-timezone*))
"Formats a timestring in the RFC 3339 format, a restricted form of the ISO-8601 timestring specification for Internet timestamps."
(let ((rfc3339-format
(if (and use-zulu
(not omit-date-part)
(not omit-time-part)
(not omit-timezone-part))
+rfc3339-format+ ; micro optimization
(append
(unless omit-date-part
'((:year 4) #\-
(:month 2) #\-
(:day 2)))
(unless (or omit-date-part
omit-time-part)
'(#\T))
(unless omit-time-part
'((:hour 2) #\:
(:min 2) #\:
(:sec 2) #\.
(:usec 6)))
(unless omit-timezone-part
(if use-zulu
'(:gmt-offset-or-z)
'(:gmt-offset)))))))
(format-timestring destination timestamp :format rfc3339-format :timezone timezone)))
(defun to-rfc3339-timestring (timestamp)
(format-rfc3339-timestring nil timestamp))
(defun %read-timestring (stream char)
(declare (ignore char))
(parse-timestring
(with-output-to-string (str)
(loop for c = (read-char stream nil)
while (and c (or (digit-char-p c) (member c '(#\: #\T #\t #\: #\- #\+ #\Z #\.))))
do (princ c str)
finally (when c (unread-char c stream))))
:allow-missing-elements t))
(defun %read-universal-time (stream char arg)
(declare (ignore char arg))
(universal-to-timestamp
(parse-integer
(with-output-to-string (str)
(loop for c = (read-char stream nil)
while (and c (digit-char-p c))
do (princ c str)
finally (when c (unread-char c stream)))))))
(defun enable-read-macros ()
"Enables the local-time reader macros for literal timestamps and universal time."
(set-macro-character #\@ '%read-timestring)
(set-dispatch-macro-character #\# #\@ '%read-universal-time)
(values))
(defvar *debug-timestamp* nil)
(defmethod print-object ((object timestamp) stream)
"Print the TIMESTAMP object using the standard reader notation"
(cond
(*debug-timestamp*
(print-unreadable-object (object stream :type t)
(format stream "~d/~d/~d"
(day-of object)
(sec-of object)
(nsec-of object))))
(t
(when *print-escape*
(write-char #\@ stream))
(format-rfc3339-timestring stream object))))
(defmethod print-object ((object timezone) stream)
"Print the TIMEZONE object in a reader-rejected manner."
(print-unreadable-object (object stream :type t)
(format stream "~:[UNLOADED~;~{~a~^ ~}~]"
(timezone-loaded object)
(map 'list #'subzone-abbrev (timezone-subzones object)))))
(defun astronomical-julian-date (timestamp)
"Returns the astronomical julian date referred to by the timestamp."
(- (day-of timestamp) +astronomical-julian-date-offset+))
(defun modified-julian-date (timestamp)
"Returns the modified julian date referred to by the timestamp."
(- (day-of timestamp) +modified-julian-date-offset+))
(declaim (notinline format-timestring))
| null | https://raw.githubusercontent.com/dlowe-net/local-time/a177eb911c0e8116e2bfceb79049265a884b701b/src/local-time.lisp | lisp | Types
Variables
Month information
the current date and -4713-01-01T00:00:00+00:00
we currently just do the date arithmetic and don't adjust for the
time of day.
try converting the local time to a timestamp using each available
subtimezone, until we find one where the offset matches the offset that
applies at that time (according to the transition table).
Consequence for ambiguous cases:
the one that we pick to resolve ambiguous local time representations.
read and verify magic number
read standard/wall indicators
indicators
read header values
get the subzone and the latest transition index
eval-when
TODO think about error signalling. when, how to disable if it makes sense, ...
the time might need to be adjusted a bit more if q != 0
We hit the DST boundary. We need to restart again
UTC offset will be the same, so it's safe to do
Almost there. However, it is necessary to check for
(or something else, sorry :) this scheme only works back until
DECODE-TIMESTAMP when fixing if fixing is desired at all.
If the user provided an explicit offset, we use that. Otherwise,
jump in order to call unix's gettimeofday properly.
and do this to allow a 0 for NULL
jump in order to call unix's gettimeofday properly.
we could evaluate comparisons of timestamp literals here
not a single #\Z
hhmm offset
hh offset
micro optimization | (in-package #:local-time)
(defclass timestamp ()
((day :accessor day-of :initarg :day :initform 0 :type integer)
(sec :accessor sec-of :initarg :sec :initform 0 :type integer)
(nsec :accessor nsec-of :initarg :nsec :initform 0 :type (integer 0 999999999))))
(defstruct subzone
(abbrev nil)
(offset nil)
(daylight-p nil))
(defstruct timezone
(transitions #(0) :type simple-vector)
(indexes #(0) :type simple-vector)
(subzones #() :type simple-vector)
(leap-seconds nil :type list)
(path nil)
(name "anonymous" :type string)
(loaded nil :type boolean))
(deftype timezone-offset ()
'(integer -43200 50400))
(defun %valid-time-of-day? (timestamp)
(zerop (day-of timestamp)))
(deftype time-of-day ()
'(and timestamp
(satisfies %valid-time-of-day?)))
(defun %valid-date? (timestamp)
(and (zerop (sec-of timestamp))
(zerop (nsec-of timestamp))))
(deftype date ()
'(and timestamp
(satisfies %valid-date?)))
(defun zone-name (zone)
(timezone-name zone))
(define-condition invalid-timezone-file (error)
((path :accessor path-of :initarg :path))
(:report (lambda (condition stream)
(format stream "The file at ~a is not a timezone file."
(path-of condition)))))
(define-condition invalid-time-specification (error)
()
(:report "The time specification is invalid"))
(define-condition invalid-timestring (error)
((timestring :accessor timestring-of :initarg :timestring)
(failure :accessor failure-of :initarg :failure))
(:report (lambda (condition stream)
(format stream "Failed to parse ~S as an rfc3339 time: ~S"
(timestring-of condition)
(failure-of condition)))))
(defmethod make-load-form ((self timestamp) &optional environment)
(make-load-form-saving-slots self :environment environment))
Declaims
(declaim (inline now format-timestring %get-current-time
format-rfc3339-timestring to-rfc3339-timestring
format-rfc1123-timestring to-rfc1123-timestring)
(ftype (function (&rest t) string) format-rfc3339-timestring)
(ftype (function (&rest t) string) format-timestring)
(ftype (function (&rest t) fixnum) local-timezone)
(ftype (function (&rest t) (values
timezone-offset
boolean
string)) timestamp-subzone)
(ftype (function (timestamp &key (:timezone timezone) (:offset (or null integer)))
(values (integer 0 999999999)
(integer 0 59)
(integer 0 59)
(integer 0 23)
(integer 1 31)
(integer 1 12)
(integer -1000000 1000000)
(integer 0 6)
t
timezone-offset
simple-string))
decode-timestamp))
(defvar *default-timezone*)
(defparameter *default-timezone-repository-path*
(flet ((try (project-home-directory)
(when project-home-directory
(ignore-errors
(truename
(merge-pathnames "zoneinfo/"
(make-pathname :directory (pathname-directory project-home-directory))))))))
(or (when (find-package "ASDF")
(let ((path (eval (read-from-string
"(let ((system (asdf:find-system :local-time nil)))
(when system
(asdf:component-pathname system)))"))))
(try path)))
(let ((path (or #.*compile-file-truename*
*load-truename*)))
(when path
(try (merge-pathnames "../" path)))))))
(defparameter +month-names+
#("" "January" "February" "March" "April" "May" "June" "July" "August"
"September" "October" "November" "December"))
(defparameter +short-month-names+
#("" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov"
"Dec"))
(defparameter +day-names+
#("Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"))
(defparameter +day-names-as-keywords+
#(:sunday :monday :tuesday :wednesday :thursday :friday :saturday))
(defparameter +short-day-names+
#("Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"))
(defparameter +minimal-day-names+
#("Su" "Mo" "Tu" "We" "Th" "Fr" "Sa"))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant +months-per-year+ 12)
(defconstant +days-per-week+ 7)
(defconstant +hours-per-day+ 24)
(defconstant +minutes-per-day+ 1440)
(defconstant +minutes-per-hour+ 60)
(defconstant +seconds-per-day+ 86400)
(defconstant +seconds-per-hour+ 3600)
(defconstant +seconds-per-minute+ 60)
(defconstant +usecs-per-day+ 86400000000))
(defparameter +iso-8601-date-format+
'((:year 4) #\- (:month 2) #\- (:day 2)))
(defparameter +iso-8601-time-format+
'((:hour 2) #\: (:min 2) #\: (:sec 2) #\. (:usec 6)))
(defparameter +iso-8601-format+
2008 - 11 - 18T02:32:00.586931 + 01:00
(append +iso-8601-date-format+ (list #\T) +iso-8601-time-format+ (list :gmt-offset-or-z)))
(defparameter +rfc3339-format+ +iso-8601-format+)
(defparameter +rfc3339-format/date-only+
'((:year 4) #\- (:month 2) #\- (:day 2)))
(defparameter +asctime-format+
'(:short-weekday #\space :short-month #\space (:day 2 #\space) #\space
(:hour 2) #\: (:min 2) #\: (:sec 2) #\space
(:year 4)))
(defparameter +rfc-1123-format+
Sun , 06 Nov 1994 08:49:37 GMT
'(:short-weekday ", " (:day 2) #\space :short-month #\space (:year 4) #\space
(:hour 2) #\: (:min 2) #\: (:sec 2) #\space :gmt-offset-hhmm)
"See the RFC 1123 for the details about the possible values of the timezone field.")
(defparameter +iso-week-date-format+
2009 - W53 - 5
'((:iso-week-year 4) #\- #\W (:iso-week-number 2) #\- (:iso-week-day 1)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +rotated-month-days-without-leap-day+
#.(coerce #(31 30 31 30 31 31 30 31 30 31 31 28)
'(simple-array fixnum (*))))
(defparameter +rotated-month-offsets-without-leap-day+
(coerce
(cons 0
(loop with sum = 0
for days :across +rotated-month-days-without-leap-day+
collect (incf sum days)))
'(simple-array fixnum (*)))))
The astronomical julian date offset is the number of days between
(defparameter +astronomical-julian-date-offset+ -2451605)
The modified julian date is the number of days between the current
date and 1858 - 11 - 17T12:00:00 + 00:00 . TODO : For the sake of simplicity ,
(defparameter +modified-julian-date-offset+ -51604)
(defun %subzone-as-of (timezone unix-time)
(let* ((as-of-time unix-time)
(index-length (length (timezone-indexes timezone)))
(transition-idx (cond ((zerop index-length) nil)
(as-of-time (transition-position as-of-time
(timezone-transitions timezone)))
(t (1- index-length))))
(subzone-idx (if transition-idx
(elt (timezone-indexes timezone) transition-idx)
0)))
(values (elt (timezone-subzones timezone) subzone-idx)
transition-idx)))
(defun %guess-offset (seconds days &optional timezone)
Whichever subtimezone is listed first in the tzinfo database will be
(let* ((zone (%realize-timezone (or timezone *default-timezone*)))
(unix-time (timestamp-values-to-unix seconds days))
(subzone (%subzone-as-of zone unix-time)))
(subzone-offset subzone)))
(defun %read-binary-integer (stream byte-count &optional (signed nil))
"Read BYTE-COUNT bytes from the binary stream STREAM, and return an integer which is its representation in network byte order (MSB). If SIGNED is true, interprets the most significant bit as a sign indicator."
(loop
:with result = 0
:for offset :from (* (1- byte-count) 8) :downto 0 :by 8
:do (setf (ldb (byte 8 offset) result) (read-byte stream))
:finally (if signed
(let ((high-bit (* byte-count 8)))
(if (logbitp (1- high-bit) result)
(return (- result (ash 1 high-bit)))
(return result)))
(return result))))
(defun %string-from-unsigned-byte-vector (vector offset)
"Returns a string created from the vector of unsigned bytes VECTOR starting at OFFSET which is terminated by a 0."
(declare (type (vector (unsigned-byte 8)) vector))
(let* ((null-pos (or (position 0 vector :start offset) (length vector)))
(result (make-string (- null-pos offset))))
(loop for input-index :from offset :upto (1- null-pos)
for output-index :upfrom 0
do (setf (aref result output-index) (code-char (aref vector input-index))))
result))
(defun %find-first-std-offset (timezone-indexes timestamp-info)
(let ((subzone-idx (find-if 'subzone-daylight-p
timezone-indexes
:key (lambda (x) (aref timestamp-info x)))))
(subzone-offset (aref timestamp-info (or subzone-idx 0)))))
(defun %tz-verify-magic-number (inf zone)
(let ((magic-buf (make-array 4 :element-type 'unsigned-byte)))
(read-sequence magic-buf inf :start 0 :end 4)
(when (string/= (map 'string #'code-char magic-buf) "TZif" :end1 4)
(error 'invalid-timezone-file :path (timezone-path zone))))
skip 16 bytes for " future use "
(let ((ignore-buf (make-array 16 :element-type 'unsigned-byte)))
(read-sequence ignore-buf inf :start 0 :end 16)))
(defun %tz-read-header (inf)
`(:utc-count ,(%read-binary-integer inf 4)
:wall-count ,(%read-binary-integer inf 4)
:leap-count ,(%read-binary-integer inf 4)
:transition-count ,(%read-binary-integer inf 4)
:type-count ,(%read-binary-integer inf 4)
:abbrev-length ,(%read-binary-integer inf 4)))
(defun %tz-read-transitions (inf count)
(make-array count
:initial-contents
(loop for idx from 1 upto count
collect (%read-binary-integer inf 4 t))))
(defun %tz-read-indexes (inf count)
(make-array count
:initial-contents
(loop for idx from 1 upto count
collect (%read-binary-integer inf 1))))
(defun %tz-read-subzone (inf count)
(loop for idx from 1 upto count
collect (list (%read-binary-integer inf 4 t)
(%read-binary-integer inf 1)
(%read-binary-integer inf 1))))
(defun leap-seconds-sec (leap-seconds)
(car leap-seconds))
(defun leap-seconds-adjustment (leap-seconds)
(cdr leap-seconds))
(defun %tz-read-leap-seconds (inf count)
(when (plusp count)
(loop for idx from 1 upto count
collect (%read-binary-integer inf 4) into sec
collect (%read-binary-integer inf 4) into adjustment
finally (return (cons (make-array count :initial-contents sec)
(make-array count :initial-contents adjustment))))))
(defun %tz-read-abbrevs (inf length)
(let ((a (make-array length :element-type '(unsigned-byte 8))))
(read-sequence a inf
:start 0
:end length)
a))
(defun %tz-read-indicators (inf length)
(let ((buf (make-array length :element-type '(unsigned-byte 8))))
(read-sequence buf inf
:start 0
:end length)
(make-array length
:element-type 'bit
:initial-contents buf)))
(defun %tz-make-subzones (raw-info abbrevs gmt-indicators std-indicators)
(declare (ignore gmt-indicators std-indicators))
TODO : handle TZ environment variables , which use the gmt and std
(make-array (length raw-info)
:element-type 'subzone
:initial-contents
(loop for info in raw-info collect
(make-subzone
:offset (first info)
:daylight-p (/= (second info) 0)
:abbrev (%string-from-unsigned-byte-vector abbrevs (third info))))))
(defun %realize-timezone (zone &optional reload)
"If timezone has not already been loaded or RELOAD is non-NIL, loads the timezone information from its associated unix file. If the file is not a valid timezone file, the condition INVALID-TIMEZONE-FILE will be signaled."
(when (or reload (not (timezone-loaded zone)))
(with-open-file (inf (timezone-path zone)
:direction :input
:element-type 'unsigned-byte)
(%tz-verify-magic-number inf zone)
(let* ((header (%tz-read-header inf))
(timezone-transitions (%tz-read-transitions inf (getf header :transition-count)))
(subzone-indexes (%tz-read-indexes inf (getf header :transition-count)))
(subzone-raw-info (%tz-read-subzone inf (getf header :type-count)))
(abbreviation-buf (%tz-read-abbrevs inf (getf header :abbrev-length)))
(leap-second-info (%tz-read-leap-seconds inf (getf header :leap-count)))
(std-indicators (%tz-read-indicators inf (getf header :wall-count)))
(gmt-indicators (%tz-read-indicators inf (getf header :utc-count)))
(subzone-info (%tz-make-subzones subzone-raw-info
abbreviation-buf
gmt-indicators
std-indicators)))
(setf (timezone-transitions zone) timezone-transitions)
(setf (timezone-indexes zone) subzone-indexes)
(setf (timezone-subzones zone) subzone-info)
(setf (timezone-leap-seconds zone) leap-second-info))
(setf (timezone-loaded zone) t)))
zone)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %make-simple-timezone (name abbrev offset)
(let ((subzone (local-time::make-subzone :offset offset
:daylight-p nil
:abbrev abbrev)))
(local-time::make-timezone
:subzones (make-array 1 :initial-contents (list subzone))
:path nil
:name name
:loaded t)))
to be used as # + # .(local - time::package - with - symbol ? " SB - EXT " " GET - TIME - OF - DAY " )
(defun package-with-symbol? (package name)
(if (and (find-package package)
(find-symbol name package))
'(:and)
'(:or))))
(defparameter +utc-zone+ (%make-simple-timezone "Coordinated Universal Time" "UTC" 0))
(defparameter +gmt-zone+ (%make-simple-timezone "Greenwich Mean Time" "GMT" 0))
(defparameter +none-zone+ (%make-simple-timezone "Explicit Offset Given" "NONE" 0))
(defparameter *location-name->timezone* (make-hash-table :test 'equal)
"A hashtable with entries like \"Europe/Budapest\" -> timezone-instance")
(defparameter *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal)
"A hashtable of \"CEST\" -> list of timezones with \"CEST\" subzone")
(defmacro define-timezone (zone-name zone-file &key (load nil))
"Define zone-name (a symbol or a string) as a new timezone,
lazy-loaded from zone-file (a pathname designator relative to the
zoneinfo directory on this system. If load is true, load immediately."
(declare (type (or string symbol) zone-name))
(let ((zone-sym (if (symbolp zone-name)
zone-name
(intern zone-name))))
`(prog1
(defparameter ,zone-sym
(make-timezone :path ,zone-file
:name ,(if (symbolp zone-name)
(string-downcase (symbol-name zone-name))
zone-name)))
,@(when load
`((let ((timezone (%realize-timezone ,zone-sym)))
(setf (gethash (timezone-name timezone)
*location-name->timezone*)
timezone)
(loop for subzone across (timezone-subzones timezone)
do
(push timezone
(gethash (subzone-abbrev subzone)
*abbreviated-subzone-name->timezone-list*)))))))))
(eval-when (:load-toplevel :execute)
(let ((default-timezone-file #p"/etc/localtime"))
(handler-case
(define-timezone *default-timezone* default-timezone-file :load t)
(t ()
(setf *default-timezone* +utc-zone+)))))
(defun find-timezone-by-location-name (name)
(when (zerop (hash-table-count *location-name->timezone*))
(error "Seems like the timezone repository has not yet been loaded. Hint: see REREAD-TIMEZONE-REPOSITORY."))
(gethash name *location-name->timezone*))
(defun timezones-matching-subzone (abbreviated-name timestamp)
"Returns list of lists of active timezone, matched subzone and last transition time
for timezones that have subzone matching specified ABBREVIATED-NAME as of TIMESTAMP moment if provided. "
(loop for zone in (gethash abbreviated-name *abbreviated-subzone-name->timezone-list*)
for (subzone transition-idx) = (multiple-value-list (%subzone-as-of zone (timestamp-to-unix timestamp)))
if (equal abbreviated-name (subzone-abbrev subzone))
collect (list zone subzone (when transition-idx (elt (timezone-transitions zone) transition-idx)))))
(defun all-timezones-matching-subzone (abbreviated-name)
"Returns list of lists of timezone, matched subzone and last transition time
for timezones that have subzone matching specified ABBREVIATED-NAME. Includes both active and historical timezones."
(loop for zone in (gethash abbreviated-name *abbreviated-subzone-name->timezone-list*)
for (subzone transition-idx) = (multiple-value-list (%subzone-as-of zone nil))
if (equal abbreviated-name (subzone-abbrev subzone))
collect (list zone subzone (when transition-idx (elt (timezone-transitions zone) transition-idx)))
else
when transition-idx
nconc (loop for subzone-idx from 0 below (length (timezone-subzones zone))
for sz = (elt (timezone-subzones zone) subzone-idx)
for tix = (position subzone-idx (timezone-indexes zone) :from-end t)
when (and tix (equal abbreviated-name (subzone-abbrev sz)))
collect (list zone sz (elt (timezone-transitions zone) tix)))))
(defun timezone= (timezone-1 timezone-2)
"Return two values indicating the relationship between timezone-1 and timezone-2. The first value is whether the two timezones are equal and the second value indicates whether it is sure or not.
In other words:
\(values t t) means timezone-1 and timezone-2 are definitely equal.
\(values nil t) means timezone-1 and timezone-2 are definitely different.
\(values nil nil) means that it couldn't be determined."
(if (or (eq timezone-1 timezone-2)
(equalp timezone-1 timezone-2))
(values t t)
(values nil nil)))
(defun reread-timezone-repository (&key (timezone-repository *default-timezone-repository-path*))
(check-type timezone-repository (or pathname string))
(let ((root-directory (uiop:directory-exists-p timezone-repository)))
(unless root-directory
(error "REREAD-TIMEZONE-REPOSITORY was called with invalid PROJECT-DIRECTORY (~A)."
timezone-repository))
(let ((cutoff-position (length (princ-to-string root-directory))))
(flet ((visitor (file)
(handler-case
(let* ((full-name (subseq (princ-to-string file) cutoff-position))
(timezone (%realize-timezone (make-timezone :path file :name full-name))))
(setf (gethash full-name *location-name->timezone*) timezone)
(map nil (lambda (subzone)
(push timezone (gethash (subzone-abbrev subzone)
*abbreviated-subzone-name->timezone-list*)))
(timezone-subzones timezone)))
(invalid-timezone-file () nil))))
(setf *location-name->timezone* (make-hash-table :test 'equal))
(setf *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal))
(uiop:collect-sub*directories root-directory
(constantly t)
(constantly t)
(lambda (dir)
(dolist (file (uiop:directory-files dir))
(when (not (find "Etc" (pathname-directory file)
:test #'string=))
(visitor file)))))
(uiop:collect-sub*directories (merge-pathnames "Etc/" root-directory)
(constantly t)
(constantly t)
(lambda (dir)
(dolist (file (uiop:directory-files dir))
(visitor file))))))))
(defmacro make-timestamp (&rest args)
`(make-instance 'timestamp ,@args))
(defun clone-timestamp (timestamp)
(make-instance 'timestamp
:nsec (nsec-of timestamp)
:sec (sec-of timestamp)
:day (day-of timestamp)))
(defun transition-position (needle haystack)
(declare (type integer needle)
(type (simple-array integer (*)) haystack))
(loop
with start = 0
with end = (1- (length haystack))
for middle = (floor (+ end start) 2)
while (and (< start end)
(/= needle (elt haystack middle)))
do (cond
((> needle (elt haystack middle))
(setf start (1+ middle)))
(t
(setf end (1- middle))))
finally
(return (max 0 (cond
((minusp end)
0)
((= needle (elt haystack middle))
middle)
((>= needle (elt haystack end))
end)
(t
(1- end)))))))
(defun timestamp-subtimezone (timestamp timezone)
"Return as multiple values the time zone as the number of seconds east of UTC, a boolean daylight-saving-p, and the customary abbreviation of the timezone."
(declare (type timestamp timestamp)
(type (or null timezone) timezone))
(let* ((zone (%realize-timezone (or timezone *default-timezone*)))
(unix-time (timestamp-to-unix timestamp))
(subzone-idx (if (zerop (length (timezone-indexes zone)))
0
(elt (timezone-indexes zone)
(transition-position unix-time
(timezone-transitions zone)))))
(subzone (elt (timezone-subzones zone) subzone-idx)))
(values
(subzone-offset subzone)
(subzone-daylight-p subzone)
(subzone-abbrev subzone))))
(defun %adjust-to-offset (sec day offset)
"Returns two values, the values of new DAY and SEC slots of the timestamp adjusted to the given timezone."
(declare (type integer sec day offset))
(multiple-value-bind (offset-day offset-sec)
(truncate offset +seconds-per-day+)
(let* ((new-sec (+ sec offset-sec))
(new-day (+ day offset-day)))
(cond ((minusp new-sec)
(incf new-sec +seconds-per-day+)
(decf new-day))
((>= new-sec +seconds-per-day+)
(incf new-day)
(decf new-sec +seconds-per-day+)))
(values new-sec new-day))))
(defun %adjust-to-timezone (source timezone &optional offset)
(%adjust-to-offset (sec-of source)
(day-of source)
(or offset
(timestamp-subtimezone source timezone))))
(defun timestamp-minimize-part (timestamp part &key
(timezone *default-timezone*)
into)
(let* ((timestamp-parts '(:nsec :sec :min :hour :day :month))
(part-count (position part timestamp-parts)))
(assert part-count nil
"timestamp-minimize-part called with invalid part ~a (expected one of ~a)"
part
timestamp-parts)
(multiple-value-bind (nsec sec min hour day month year day-of-week daylight-saving-time-p offset)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore nsec day-of-week daylight-saving-time-p))
(encode-timestamp 0
(if (> part-count 0) 0 sec)
(if (> part-count 1) 0 min)
(if (> part-count 2) 0 hour)
(if (> part-count 3) 1 day)
(if (> part-count 4) 1 month)
year
:offset (if timezone nil offset)
:timezone timezone
:into into))))
(defun timestamp-maximize-part (timestamp part &key
(timezone *default-timezone*)
into)
(let* ((timestamp-parts '(:nsec :sec :min :hour :day :month))
(part-count (position part timestamp-parts)))
(assert part-count nil
"timestamp-maximize-part called with invalid part ~a (expected one of ~a)"
part
timestamp-parts)
(multiple-value-bind (nsec sec min hour day month year day-of-week daylight-saving-time-p offset)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore nsec day-of-week daylight-saving-time-p))
(let ((month (if (> part-count 4) 12 month)))
(encode-timestamp 999999999
(if (> part-count 0) 59 sec)
(if (> part-count 1) 59 min)
(if (> part-count 2) 23 hour)
(if (> part-count 3) (days-in-month month year) day)
month
year
:offset (if timezone nil offset)
:timezone timezone
:into into)))))
(defmacro with-decoded-timestamp ((&key nsec sec minute hour day month year day-of-week daylight-p timezone offset)
timestamp &body forms)
"This macro binds variables to the decoded elements of TIMESTAMP. The TIMEZONE argument is used for decoding the timestamp, and is not bound by the macro. The value of DAY-OF-WEEK starts from 0 which means Sunday."
(let ((ignores)
(types)
(variables))
(macrolet ((initialize (&rest vars)
`(progn
,@(loop
:for var :in vars
:collect `(progn
(unless ,var
(setf ,var (gensym))
(push ,var ignores))
(push ,var variables)))
(setf ignores (nreverse ignores))
(setf variables (nreverse variables))))
(declare-fixnum-type (&rest vars)
`(progn
,@(loop
:for var :in vars
:collect `(when ,var
(push `(type fixnum ,,var) types)))
(setf types (nreverse types)))))
(when nsec
(push `(type (integer 0 999999999) ,nsec) types))
(declare-fixnum-type sec minute hour day month year)
(initialize nsec sec minute hour day month year day-of-week daylight-p))
`(multiple-value-bind (,@variables)
(decode-timestamp ,timestamp :timezone ,(or timezone '*default-timezone*) :offset ,offset)
(declare (ignore ,@ignores) ,@types)
,@forms)))
(defun %normalize-month-year-pair (month year)
"Normalizes the month/year pair: in case month is < 1 or > 12 the month and year are corrected to handle the overflow."
(multiple-value-bind (year-offset month-minus-one)
(floor (1- month) 12)
(values (1+ month-minus-one)
(+ year year-offset))))
(defun days-in-month (month year)
"Returns the number of days in the given month of the specified year."
(let ((normal-days (aref +rotated-month-days-without-leap-day+
(mod (+ month 9) 12))))
(if (and (= month 2)
(or (and (zerop (mod year 4))
(plusp (mod year 100)))
(zerop (mod year 400))))
February on a leap year
normal-days)))
TODO scan all uses of FIX - OVERFLOW - IN - DAYS and decide where it 's ok to silently fix and where should be and error reported
(defun %fix-overflow-in-days (day month year)
"In case the day number is higher than the maximal possible for the given month/year pair, returns the last day of the month."
(let ((max-day (days-in-month month year)))
(if (> day max-day)
max-day
day)))
(eval-when (:compile-toplevel :load-toplevel)
(defun %list-length= (num list)
"Tests for a list of length NUM without traversing the entire list to get the length."
(let ((c (nthcdr (1- num) list)))
(and c (endp (cdr c)))))
(defun %expand-adjust-timestamp-changes (timestamp changes visitor)
(loop
:with params = ()
:with functions = ()
:for change in changes
:do
(progn
(assert (or
(%list-length= 3 change)
(and (%list-length= 2 change)
(symbolp (first change))
(or (string= (first change) :timezone)
(string= (first change) :utc-offset)))
(and (%list-length= 4 change)
(symbolp (third change))
(or (string= (third change) :to)
(string= (third change) :by))))
nil "Syntax error in expression ~S" change)
(let ((operation (first change))
(part (second change))
(value (if (%list-length= 3 change)
(third change)
(fourth change))))
(cond
((string= operation :set)
(push `(%set-timestamp-part ,part ,value) functions))
((string= operation :offset)
(push `(%offset-timestamp-part ,part ,value) functions))
((string= operation :utc-offset)
(push part params)
(push :utc-offset params))
((string= operation :timezone)
(push part params)
(push :timezone params))
(t (error "Unexpected operation ~S" operation)))))
:finally
(loop
:for (function part value) in functions
:do
(funcall visitor `(,function ,timestamp ,part ,value ,@params)))))
(defun %expand-adjust-timestamp (timestamp changes &key functional)
(let* ((old (gensym "OLD"))
(new (if functional
(gensym "NEW")
old))
(forms (list)))
(%expand-adjust-timestamp-changes old changes
(lambda (change)
(push
`(progn
(multiple-value-bind (nsec sec day)
,change
(setf (nsec-of ,new) nsec)
(setf (sec-of ,new) sec)
(setf (day-of ,new) day))
,@(when functional
`((setf ,old ,new))))
forms)))
(setf forms (nreverse forms))
`(let* ((,old ,timestamp)
,@(when functional
`((,new (clone-timestamp ,old)))))
,@forms
,old)))
(defmacro adjust-timestamp (timestamp &body changes)
(%expand-adjust-timestamp timestamp changes :functional t))
(defmacro adjust-timestamp! (timestamp &body changes)
(%expand-adjust-timestamp timestamp changes :functional nil))
(defun %set-timestamp-part (time part new-value &key (timezone *default-timezone*) utc-offset)
(case part
((:nsec :sec-of-day :day)
(let ((nsec (nsec-of time))
(sec (sec-of time))
(day (day-of time)))
(case part
(:nsec (setf nsec (coerce new-value '(integer 0 999999999))))
(:sec-of-day (setf sec (coerce new-value `(integer 0 ,+seconds-per-day+))))
(:day (setf day new-value)))
(values nsec sec day)))
(otherwise
(with-decoded-timestamp (:nsec nsec :sec sec :minute minute :hour hour
:day day :month month :year year :timezone timezone :offset utc-offset)
time
(ecase part
(:sec (setf sec new-value))
(:minute (setf minute new-value))
(:hour (setf hour new-value))
(:day-of-month (setf day new-value))
(:month (setf month new-value)
(setf day (%fix-overflow-in-days day month year)))
(:year (setf year new-value)
(setf day (%fix-overflow-in-days day month year))))
(encode-timestamp-into-values nsec sec minute hour day month year :timezone timezone :offset utc-offset)))))
(defun %offset-timestamp-part (time part offset &key (timezone *default-timezone*) utc-offset)
"Returns a time adjusted by the specified OFFSET. Takes care of
different kinds of overflows. The setting :day-of-week is possible
using a keyword symbol name of a week-day (see
+DAY-NAMES-AS-KEYWORDS+) as value. In that case point the result to
day given by OFFSET in the week that contains TIME."
(labels ((direct-adjust (part offset nsec sec day)
(cond ((eq part :day-of-week)
(with-decoded-timestamp (:day-of-week day-of-week
:nsec nsec :sec sec :minute minute :hour hour
:day day :month month :year year
:timezone timezone :offset utc-offset)
time
(let ((position (position offset +day-names-as-keywords+ :test #'eq)))
(assert position (position) "~S is not a valid day name" offset)
(let ((offset (+ (- (if (zerop day-of-week)
7
day-of-week))
position)))
(incf day offset)
(cond
((< day 1)
(decf month)
(when (< month 1)
(setf month 12)
(decf year))
(setf day (+ (days-in-month month year) day)))
((let ((days-in-month (days-in-month month year)))
(when (< days-in-month day)
(incf month)
(when (= month 13)
(setf month 1)
(incf year))
(decf day days-in-month)))))
(encode-timestamp-into-values nsec sec minute hour day month year
:timezone timezone :offset utc-offset)))))
((zerop offset)
The offset is zero , so just return the parts of the timestamp object
(values nsec sec day))
(t
(let ((old-utc-offset (or utc-offset
(timestamp-subtimezone time timezone)))
new-utc-offset)
(tagbody
top
(ecase part
(:nsec
(multiple-value-bind (sec-offset new-nsec)
(floor (+ offset nsec) 1000000000)
(setf part :sec
offset sec-offset
nsec new-nsec)
(go top)))
((:sec :minute :hour)
(multiple-value-bind (days-offset new-sec)
(floor (+ sec (* offset (ecase part
(:sec 1)
(:minute +seconds-per-minute+)
(:hour +seconds-per-hour+))))
+seconds-per-day+)
(return-from direct-adjust (values nsec new-sec (+ day days-offset)))))
(:day
(incf day offset)
(setf new-utc-offset (or utc-offset
(timestamp-subtimezone (make-timestamp :nsec nsec :sec sec :day day)
timezone)))
(when (not (= old-utc-offset
new-utc-offset))
with : sec , but this time we know both old and new
(setf part :sec
offset (- old-utc-offset
new-utc-offset)
old-utc-offset new-utc-offset)
(go top))
(return-from direct-adjust (values nsec sec day)))))))))
(safe-adjust (part offset time)
(with-decoded-timestamp (:nsec nsec :sec sec :minute minute :hour hour :day day
:month month :year year :timezone timezone :offset utc-offset)
time
(multiple-value-bind (month-new year-new)
(%normalize-month-year-pair
(+ (ecase part
(:month offset)
(:year (* 12 offset)))
month)
year)
overflows first
(encode-timestamp-into-values nsec sec minute hour
(%fix-overflow-in-days day month-new year-new)
month-new year-new
:timezone timezone :offset utc-offset)))))
(ecase part
((:nsec :sec :minute :hour :day :day-of-week)
(direct-adjust part offset
(nsec-of time)
(sec-of time)
(day-of time)))
((:month :year) (safe-adjust part offset time)))))
TODO merge this functionality into timestamp - difference
(defun timestamp-whole-year-difference (time-a time-b)
"Returns the number of whole years elapsed between time-a and time-b (hint: anniversaries)."
(declare (type timestamp time-b time-a))
(multiple-value-bind (nsec-b sec-b minute-b hour-b day-b month-b year-b day-of-week-b daylight-p-b offset-b)
(decode-timestamp time-b)
(declare (ignore day-of-week-b daylight-p-b))
(multiple-value-bind (nsec-a sec-a minute-a hour-a day-a month-a year-a)
(decode-timestamp time-a)
(declare (ignore nsec-a sec-a minute-a hour-a day-a month-a))
(let ((year-difference (- year-a year-b)))
(if (timestamp<= (encode-timestamp nsec-b sec-b minute-b hour-b
(if (= month-b 2)
(min 28 day-b)
day-b)
month-b
(+ year-difference year-b)
:offset offset-b)
time-a)
year-difference
(1- year-difference))))))
(defun timestamp-difference (time-a time-b)
"Returns the difference between TIME-A and TIME-B in seconds"
(let ((nsec (- (nsec-of time-a) (nsec-of time-b)))
(second (- (sec-of time-a) (sec-of time-b)))
(day (- (day-of time-a) (day-of time-b))))
(when (minusp nsec)
(decf second)
(incf nsec 1000000000))
(when (minusp second)
(decf day)
(incf second +seconds-per-day+))
(let ((result (+ (* day +seconds-per-day+)
second)))
(unless (zerop nsec)
this incf turns the result into a float , so only do this when necessary
(incf result (/ nsec 1000000000d0)))
result)))
(defun timestamp+ (time amount unit &optional (timezone *default-timezone*) offset)
(multiple-value-bind (nsec sec day)
(%offset-timestamp-part time unit amount :timezone timezone :utc-offset offset)
(make-timestamp :nsec nsec
:sec sec
:day day)))
(defun timestamp- (time amount unit &optional (timezone *default-timezone*) offset)
(timestamp+ time (- amount) unit timezone offset))
(defun timestamp-day-of-week (timestamp &key (timezone *default-timezone*) offset)
(mod (+ 3 (nth-value 1 (%adjust-to-timezone timestamp timezone offset))) 7))
TODO read
1582 , the start of the gregorian calendar . see also
(defun valid-timestamp-p (nsec sec minute hour day month year)
"Returns T if the time values refer to a valid time, otherwise returns NIL."
(and (<= 0 nsec 999999999)
(<= 0 sec 59)
(<= 0 minute 59)
(<= 0 hour 23)
(<= 1 month 12)
(<= 1 day (days-in-month month year))
(/= year 0)))
(defun encode-timestamp-into-values (nsec sec minute hour day month year
&key (timezone *default-timezone*) offset)
"Returns (VALUES NSEC SEC DAY ZONE) ready to be used for
instantiating a new timestamp object. If the specified time is
invalid, the condition INVALID-TIME-SPECIFICATION is raised."
(declare (type integer nsec sec minute hour day month year)
(type (or integer null) offset))
(unless (valid-timestamp-p nsec sec minute hour day month year)
(error 'invalid-time-specification))
(let* ((0-based-rotated-month (if (>= month 3)
(- month 3)
(+ month 9)))
(internal-year (if (< month 3)
(- year 2001)
(- year 2000)))
(years-as-days (years-to-days internal-year))
(sec (+ (* hour +seconds-per-hour+)
(* minute +seconds-per-minute+)
sec))
(days-from-zero-point (+ years-as-days
(aref +rotated-month-offsets-without-leap-day+ 0-based-rotated-month)
(1- day)))
(used-offset (or offset
(%guess-offset sec
days-from-zero-point
timezone))))
(multiple-value-bind (utc-sec utc-day)
(%adjust-to-offset sec days-from-zero-point (- used-offset))
(values nsec utc-sec utc-day))))
(defun encode-timestamp (nsec sec minute hour day month year
&key (timezone *default-timezone*) offset into)
"Return a new TIMESTAMP instance corresponding to the specified time
elements."
(declare (type integer nsec sec minute hour day month year))
(multiple-value-bind (nsec sec day)
(encode-timestamp-into-values nsec sec minute hour day month year
:timezone timezone :offset offset)
(if into
(progn
(setf (nsec-of into) nsec)
(setf (sec-of into) sec)
(setf (day-of into) day)
into)
(make-timestamp
:nsec nsec
:sec sec
:day day))))
(defun universal-to-timestamp (universal &key (nsec 0))
"Returns a timestamp corresponding to the given universal time."
universal time is seconds from 1900 - 01 - 01T00:00:00Z.
(let ((adjusted-universal (- universal #.(encode-universal-time 0 0 0 1 3 2000 0))))
(multiple-value-bind (day second)
(floor adjusted-universal +seconds-per-day+)
(make-timestamp :day day :sec second :nsec nsec))))
(defun timestamp-to-universal (timestamp)
"Return the UNIVERSAL-TIME corresponding to the TIMESTAMP"
universal time is seconds from 1900 - 01 - 01T00:00:00Z
(+ (* (day-of timestamp) +seconds-per-day+)
(sec-of timestamp)
#.(encode-universal-time 0 0 0 1 3 2000 0)))
(defun unix-to-timestamp (unix &key (nsec 0))
"Return a TIMESTAMP corresponding to UNIX, which is the number of seconds since the unix epoch, 1970-01-01T00:00:00Z."
(multiple-value-bind (days secs)
(floor unix +seconds-per-day+)
(make-timestamp :day (- days 11017) :sec secs :nsec nsec)))
(defun timestamp-values-to-unix (seconds day)
"Return the Unix time correspondint to the values used to encode a TIMESTAMP"
(+ (* (+ day 11017) +seconds-per-day+) seconds))
(defun timestamp-to-unix (timestamp)
"Return the Unix time corresponding to the TIMESTAMP"
(declare (type timestamp timestamp))
(timestamp-values-to-unix (sec-of timestamp) (day-of timestamp)))
#+(and allegro (not os-windows))
(eval-when (:compile-toplevel :load-toplevel :execute)
Allegro common lisp requires some toplevel hoops through which to
(ff:def-foreign-type timeval
(:struct (tv_sec :long)
(tv_usec :long)))
(ff:def-foreign-call
(allegro-ffi-gettimeofday "gettimeofday")
((timeval (* timeval))
(timezone :foreign-address))
:returning (:int fixnum)))
#+(and allegro os-windows)
(eval-when (:compile-toplevel :load-toplevel :execute)
Allegro common lisp requires some toplevel hoops through which to
(ff:def-foreign-type filetime
(:struct (|dwLowDateTime| :int)
(|dwHighDateTime| :int)))
(ff:def-foreign-call
(allegro-ffi-get-system-time-as-file-time "GetSystemTimeAsFileTime")
((filetime (* filetime)))
:returning :void))
#+(or (and allegro os-windows)
(and ccl windows))
(defun filetime-to-current-time (low high)
"Convert a Windows time into (values sec nano-sec)."
(let* ((unix-epoch-filetime 116444736000000000)
(filetime (logior low (ash high 32)))
(filetime (- filetime unix-epoch-filetime)))
(multiple-value-bind (secs 100ns-periods)
(floor filetime #.(round 1e7))
(values secs (* 100ns-periods 100)))))
#+(and lispworks (or linux darwin))
(progn
(fli:define-c-typedef time-t :long)
(fli:define-c-typedef suseconds-t #+linux :long
#+darwin :int)
(fli:define-c-struct timeval
(tv-sec time-t)
(tv-usec suseconds-t))
(fli:define-foreign-function (gettimeofday/ffi "gettimeofday")
((tv (:pointer (:struct timeval)))
(tz :pointer))
:result-type :int)
(defun lispworks-gettimeofday ()
(declare (optimize speed (safety 1)))
(fli:with-dynamic-foreign-objects ((tv (:struct timeval)))
(let ((ret (gettimeofday/ffi tv fli:*null-pointer*)))
(assert (zerop ret) nil "gettimeofday failed")
(let ((secs
(fli:foreign-slot-value tv 'tv-sec
:type 'time-t
:object-type '(:struct timeval)))
(usecs
(fli:foreign-slot-value tv 'tv-usec
:type 'suseconds-t
:object-type '(:struct timeval))))
(values secs (* 1000 usecs)))))))
(defun %get-current-time ()
"Cross-implementation abstraction to get the current time measured from the unix epoch (1/1/1970). Should return (values sec nano-sec)."
#+(and allegro (not os-windows))
(flet ((allegro-gettimeofday ()
(let ((tv (ff:allocate-fobject 'timeval :c)))
(allegro-ffi-gettimeofday tv 0)
(let ((sec (ff:fslot-value-typed 'timeval :c tv 'tv_sec))
(usec (ff:fslot-value-typed 'timeval :c tv 'tv_usec)))
(ff:free-fobject tv)
(values sec usec)))))
(multiple-value-bind (sec usec) (allegro-gettimeofday)
(values sec (* 1000 usec))))
#+(and allegro os-windows)
(let* ((ft (ff:allocate-fobject 'filetime :c)))
(allegro-ffi-get-system-time-as-file-time ft)
(let* ((low (ff:fslot-value-typed 'filetime :c ft '|dwLowDateTime|))
(high (ff:fslot-value-typed 'filetime :c ft '|dwHighDateTime|)))
(filetime-to-current-time low high)))
#+cmu
(multiple-value-bind (success? sec usec) (unix:unix-gettimeofday)
(assert success? () "unix:unix-gettimeofday reported failure?!")
(values sec (* 1000 usec)))
#+sbcl
(progn
available from sbcl 1.0.28.66
(multiple-value-bind (sec nsec) (sb-ext:get-time-of-day)
(values sec (* 1000 nsec)))
obsolete , scheduled to be deleted at the end of 2009
(multiple-value-bind (success? sec nsec) (sb-unix:unix-gettimeofday)
(assert success? () "sb-unix:unix-gettimeofday reported failure?!")
(values sec (* 1000 nsec))))
#+(and ccl (not windows))
(ccl:rlet ((tv :timeval))
(let ((err (ccl:external-call "gettimeofday" :address tv :address (ccl:%null-ptr) :int)))
(assert (zerop err) nil "gettimeofday failed")
(values (ccl:pref tv :timeval.tv_sec) (* 1000 (ccl:pref tv :timeval.tv_usec)))))
#+(and ccl windows)
(ccl:rlet ((time :<lpfiletime>))
(ccl:external-call "GetSystemTimeAsFileTime" :<lpfiletime> time :void)
(let* ((low (ccl:%get-unsigned-long time (/ 0 8)))
(high (ccl:%get-unsigned-long time (/ 32 8))))
(filetime-to-current-time low high)))
#+abcl
(multiple-value-bind (sec millis)
(truncate (java:jstatic "currentTimeMillis" "java.lang.System") 1000)
(values sec (* millis 1000000)))
#+(and lispworks (or linux darwin))
(lispworks-gettimeofday)
#-(or allegro cmu sbcl abcl ccl (and lispworks (or linux darwin)))
(values (- (get-universal-time)
CL 's get - universal - time uses an epoch of 1/1/1900 , so adjust the result to the Unix epoch
#.(encode-universal-time 0 0 0 1 1 1970 0))
0))
(defvar *clock* t
"Use the `*clock*' special variable if you need to define your own idea of the current time.
The value of this variable should have the methods `local-time::clock-now', and
`local-time::clock-today'. The currently supported values in local-time are:
t - use the standard clock
local-time:leap-second-adjusted - use a clock which adjusts for leap seconds using the information in *default-timezone*.")
(defun now ()
"Returns a timestamp representing the present moment."
(clock-now *clock*))
(defun today ()
"Returns a timestamp representing the present day."
(clock-today *clock*))
(defgeneric clock-now (clock)
(:documentation "Returns a timestamp for the current time given a clock."))
(defgeneric clock-today (clock)
(:documentation "Returns a timestamp for the current date given a
clock. The date is encoded by convention as a timestamp with the
time set to 00:00:00UTC."))
(defun %leap-seconds-offset (leap-seconds sec)
"Find the latest leap second adjustment effective at SEC system time."
(elt (leap-seconds-adjustment leap-seconds)
(transition-position sec (leap-seconds-sec leap-seconds))))
(defun %adjust-sec-for-leap-seconds (sec)
"Ajdust SEC from system time to Unix time (on systems those clock does not jump back over leap seconds)."
(let ((leap-seconds (timezone-leap-seconds (%realize-timezone *default-timezone*))))
(when leap-seconds
(decf sec (%leap-seconds-offset leap-seconds sec))))
sec)
(defmethod clock-now ((clock (eql 'leap-second-adjusted)))
(multiple-value-bind (sec nsec) (%get-current-time)
(unix-to-timestamp (%adjust-sec-for-leap-seconds sec)
:nsec nsec)))
(defmethod clock-now (clock)
(declare (ignore clock))
(multiple-value-bind (sec nsec) (%get-current-time)
(unix-to-timestamp sec :nsec nsec)))
(defmethod clock-today (clock)
(declare (ignore clock))
TODO should return a date value , anyhow we will decide to represent it eventually
(let ((result (now)))
(setf (sec-of result) 0)
(setf (nsec-of result) 0)
result))
(defmacro %defcomparator (name &body body)
(let ((pair-comparator-name (intern (concatenate 'string "%" (string name)))))
`(progn
(declaim (inline ,pair-comparator-name))
(defun ,pair-comparator-name (time-a time-b)
(assert (typep time-a 'timestamp)
nil
'type-error
:datum time-a
:expected-type 'timestamp)
(assert (typep time-b 'timestamp)
nil
'type-error
:datum time-b
:expected-type 'timestamp)
,@body)
(defun ,name (&rest times)
(declare (dynamic-extent times))
(loop for head on times
while (cdr head)
always (,pair-comparator-name (first head) (second head))))
(define-compiler-macro ,name (&rest times)
(let ((vars (loop
:for i :upfrom 0 :below (length times)
:collect (gensym (concatenate 'string "TIME-" (princ-to-string i) "-")))))
`(let (,@(loop
:for var :in vars
:for time :in times
:collect (list var time)))
(and ,@(loop
:for (time-a time-b) :on vars
:while time-b
:collect `(,',pair-comparator-name ,time-a ,time-b)))))))))
(defun %timestamp-compare (time-a time-b)
"Returns the symbols <, >, or =, describing the relationship between TIME-A and TIME-b."
(declare (type timestamp time-a time-b))
(cond
((< (day-of time-a) (day-of time-b)) '<)
((> (day-of time-a) (day-of time-b)) '>)
((< (sec-of time-a) (sec-of time-b)) '<)
((> (sec-of time-a) (sec-of time-b)) '>)
((< (nsec-of time-a) (nsec-of time-b)) '<)
((> (nsec-of time-a) (nsec-of time-b)) '>)
(t '=)))
(%defcomparator timestamp<
(eql (%timestamp-compare time-a time-b) '<))
(%defcomparator timestamp<=
(not (null (member (%timestamp-compare time-a time-b) '(< =)))))
(%defcomparator timestamp>
(eql (%timestamp-compare time-a time-b) '>))
(%defcomparator timestamp>=
(not (null (member (%timestamp-compare time-a time-b) '(> =)))))
(%defcomparator timestamp=
(eql (%timestamp-compare time-a time-b) '=))
(defun timestamp/= (&rest timestamps)
"Returns T if no pair of timestamps is equal. Otherwise return NIL."
(declare (dynamic-extent timestamps))
(loop for ts-head on timestamps do
(loop for ts in (rest ts-head) do
(when (timestamp= (car ts-head) ts)
(return-from timestamp/= nil))))
t)
(defun contest (test list)
"Applies TEST to pairs of elements in list, keeping the element which last tested T. Returns the winning element."
(reduce (lambda (a b) (if (funcall test a b) a b)) list))
(defun timestamp-minimum (time &rest times)
"Returns the earliest timestamp"
(contest #'timestamp< (cons time times)))
(defun timestamp-maximum (time &rest times)
"Returns the latest timestamp"
(contest #'timestamp> (cons time times)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun years-to-days (years)
"Given a number of years, returns the number of days in those years."
(let* ((days (* years 365))
(l1 (floor years 4))
(l2 (floor years 100))
(l3 (floor years 400)))
(+ days l1 (- l2) l3))))
(defun days-to-years (days)
"Given a number of days, returns the number of years and the remaining days in that year."
(let ((remaining-days days))
(multiple-value-bind (400-years remaining-days)
(floor remaining-days #.(years-to-days 400))
(let* ((100-years (min (floor remaining-days #.(years-to-days 100)) 3))
(remaining-days (- remaining-days
(* 100-years #.(years-to-days 100)))))
(multiple-value-bind (4-years remaining-days)
(floor remaining-days #.(years-to-days 4))
(let ((years (min 3 (floor remaining-days #.(years-to-days 1)))))
(values (+ (* 400-years 400)
(* 100-years 100)
(* 4-years 4)
years)
(- remaining-days (* years 365))))))))
the above is the macroexpansion of the following . uses , but kept for clarity because the expansion is unreadable .
#+nil
(bind ((remaining-days days)
((values 400-years remaining-days) (floor remaining-days #.(years-to-days 400)))
(100-years (min (floor remaining-days #.(years-to-days 100))
3))
(remaining-days (- remaining-days
(* 100-years
#.(years-to-days 100))))
((values 4-years remaining-days) (floor remaining-days #.(years-to-days 4)))
(years (min (floor remaining-days 365)
3)))
(values (+ (* 400-years 400)
(* 100-years 100)
(* 4-years 4)
years)
(- remaining-days (* years 365)))))
(defun %timestamp-decode-date (days)
"Returns the year, month, and day, given the number of days from the epoch."
(declare (type integer days))
(multiple-value-bind (years remaining-days)
(days-to-years days)
(let* ((leap-day-p (= remaining-days 365))
(rotated-1-based-month (if leap-day-p
march is the first month and february is the last
(position remaining-days +rotated-month-offsets-without-leap-day+ :test #'<)))
(1-based-month (if (>= rotated-1-based-month 11)
(- rotated-1-based-month 10)
(+ rotated-1-based-month 2)))
(1-based-day (if leap-day-p
29
(1+ (- remaining-days (aref +rotated-month-offsets-without-leap-day+
(1- rotated-1-based-month)))))))
(values
(+ years
january is in the next year
2001
2000))
1-based-month
1-based-day))))
(defun %timestamp-decode-iso-week (timestamp)
"Returns the year, week number, and day of week components of an ISO week date."
Algorithm from :ISO_week_date#Algorithms
(let* ((dn (timestamp-day-of-week timestamp))
ISO weekdays are Monday=1 and Sunday=7
(nearest-thursday (timestamp+ timestamp (- 4 day-of-week) :day))
(year (timestamp-year nearest-thursday))
(month (timestamp-month nearest-thursday))
(day (timestamp-day nearest-thursday))
(ordinal-day (- (day-of (encode-timestamp 0 0 0 0 day month year :timezone +utc-zone+))
(day-of (encode-timestamp 0 0 0 0 1 1 year :timezone +utc-zone+)))))
(values year
(1+ (floor ordinal-day 7))
day-of-week)))
(defun %timestamp-decode-time (seconds)
"Returns the hours, minutes, and seconds, given the number of seconds since midnight."
(declare (type integer seconds))
(multiple-value-bind (hours hour-remainder)
(floor seconds +seconds-per-hour+)
(multiple-value-bind (minutes seconds)
(floor hour-remainder +seconds-per-minute+)
(values
hours
minutes
seconds))))
(defun decode-timestamp (timestamp &key (timezone *default-timezone*) offset)
"Returns the decoded time as multiple values: nsec, ss, mm, hh, day, month, year, day-of-week"
(declare (type timestamp timestamp))
(let ((timezone (if offset (the timezone +none-zone+) timezone)))
(multiple-value-bind (offset* daylight-p abbreviation)
(timestamp-subtimezone timestamp timezone)
(multiple-value-bind (adjusted-secs adjusted-days)
(%adjust-to-timezone timestamp timezone offset)
(multiple-value-bind (hours minutes seconds)
(%timestamp-decode-time adjusted-secs)
(multiple-value-bind (year month day)
(%timestamp-decode-date adjusted-days)
(values
(nsec-of timestamp)
seconds minutes hours
day month year
(timestamp-day-of-week timestamp :timezone timezone :offset offset)
daylight-p
(or offset offset*)
abbreviation)))))))
(defun timestamp-year (timestamp &key (timezone *default-timezone*))
"Returns the cardinal year upon which the timestamp falls."
(nth-value 0
(%timestamp-decode-date
(nth-value 1 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-century (timestamp &key (timezone *default-timezone*))
"Returns the ordinal century upon which the timestamp falls."
(let* ((year (timestamp-year timestamp :timezone timezone))
(sign (signum year)))
(+ sign
(* sign
(truncate (1- (abs year)) 100)))))
(defun timestamp-millennium (timestamp &key (timezone *default-timezone*))
"Returns the ordinal millennium upon which the timestamp falls."
(let* ((year (timestamp-year timestamp :timezone timezone))
(sign (signum year)))
(+ sign
(* sign
(truncate (1- (abs year)) 1000)))))
(defun timestamp-decade (timestamp &key (timezone *default-timezone*))
"Returns the cardinal decade upon which the timestamp falls."
(truncate (timestamp-year timestamp :timezone timezone) 10))
(defun timestamp-month (timestamp &key (timezone *default-timezone*))
"Returns the month upon which the timestamp falls."
(nth-value 1
(%timestamp-decode-date
(nth-value 1 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-day (timestamp &key (timezone *default-timezone*))
"Returns the day of the month upon which the timestamp falls."
(nth-value 2
(%timestamp-decode-date
(nth-value 1 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-hour (timestamp &key (timezone *default-timezone*))
(nth-value 0
(%timestamp-decode-time
(nth-value 0 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-minute (timestamp &key (timezone *default-timezone*))
(nth-value 1
(%timestamp-decode-time
(nth-value 0 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-second (timestamp &key (timezone *default-timezone*))
(nth-value 2
(%timestamp-decode-time
(nth-value 0 (%adjust-to-timezone timestamp timezone)))))
(defun timestamp-microsecond (timestamp)
(floor (nsec-of timestamp) 1000))
(defun timestamp-millisecond (timestamp)
(floor (nsec-of timestamp) 1000000))
(defun split-timestring (str &rest args)
(declare (inline))
(apply #'%split-timestring (coerce str 'simple-string) args))
(defun %split-timestring (time-string &key
(start 0)
(end (length time-string))
(fail-on-error t) (time-separator #\:)
(date-separator #\-)
(date-time-separator #\T)
(fract-time-separators '(#\. #\,))
(allow-missing-elements t)
(allow-missing-date-part allow-missing-elements)
(allow-missing-time-part allow-missing-elements)
(allow-missing-timezone-part allow-missing-time-part))
"Based on including the function names used. Returns (values year month day hour minute second nsec offset-hour offset-minute). On parsing failure, signals INVALID-TIMESTRING if FAIL-ON-ERROR is NIL, otherwise returns NIL."
(declare (type character date-time-separator time-separator date-separator)
(type simple-string time-string)
(optimize (speed 3)))
(the list
(let (year month day hour minute second nsec offset-hour offset-minute)
(declare (type (or null fixnum) start end year month day hour minute second offset-hour offset-minute)
(type (or null (signed-byte 32)) nsec))
(macrolet ((passert (expression)
`(unless ,expression
(parse-error ',expression)))
(parse-integer-into (start-end place &optional low-limit high-limit)
(let ((entry (gensym "ENTRY"))
(value (gensym "VALUE"))
(pos (gensym "POS"))
(start (gensym "START"))
(end (gensym "END")))
`(let ((,entry ,start-end))
(if ,entry
(let ((,start (car ,entry))
(,end (cdr ,entry)))
(multiple-value-bind (,value ,pos) (parse-integer time-string :start ,start :end ,end :junk-allowed t)
(passert (= ,pos ,end))
(setf ,place ,value)
,(if (and low-limit high-limit)
`(passert (<= ,low-limit ,place ,high-limit))
(values))
(values)))
(progn
(passert allow-missing-elements)
(values))))))
(with-parts-and-count ((start end split-chars) &body body)
`(multiple-value-bind (parts count) (split ,start ,end ,split-chars)
(declare (ignorable count) (type fixnum count)
( type # 1=(cons ( cons fixnum fixnum ) ( or null # 1 # ) ) parts )
(type list parts))
,@body)))
(labels ((split (start end chars)
(declare (type fixnum start end))
(unless (consp chars)
(setf chars (list chars)))
(loop with last-match = start
with match-count of-type (integer 0 #.most-positive-fixnum) = 0
for index of-type fixnum upfrom start
while (< index end)
when (member (aref time-string index) chars :test #'char-equal)
collect (prog1 (if (< last-match index)
(cons last-match index)
nil)
(incf match-count)
(setf last-match (1+ index)))
into result
finally (return (values (if (zerop (- index last-match))
result
(prog1
(nconc result (list (cons last-match index)))
(incf match-count)))
match-count))))
(parse ()
(with-parts-and-count (start end date-time-separator)
(cond ((= count 2)
(if (first parts)
(full-date (first parts))
(passert allow-missing-date-part))
(if (second parts)
(full-time (second parts))
(passert allow-missing-time-part))
(done))
((and (= count 1)
allow-missing-date-part
(find time-separator time-string
:start (car (first parts))
:end (cdr (first parts))))
(full-time (first parts))
(done))
((and (= count 1)
allow-missing-time-part
(find date-separator time-string
:start (car (first parts))
:end (cdr (first parts))))
(full-date (first parts))
(done)))
(parse-error nil)))
(full-date (start-end)
(let ((parts (split (car start-end) (cdr start-end) date-separator)))
(passert (%list-length= 3 parts))
(date-fullyear (first parts))
(date-month (second parts))
(date-mday (third parts))))
(date-fullyear (start-end)
(parse-integer-into start-end year))
(date-month (start-end)
(parse-integer-into start-end month 1 12))
(date-mday (start-end)
(parse-integer-into start-end day 1 31))
(full-time (start-end)
(let ((start (car start-end))
(end (cdr start-end)))
(with-parts-and-count (start end (list #\Z #\- #\+))
(let* ((zulup (find #\Z time-string :test #'char-equal :start start :end end))
(sign (unless zulup
(if (find #\+ time-string :test #'char-equal :start start :end end)
1
-1))))
(passert (<= 1 count 2))
(unless (and (eq (first parts) nil)
(not (rest parts)))
(partial-time (first parts)))
(when zulup
(setf offset-hour 0
offset-minute 0))
(if (= count 1)
(passert (or zulup allow-missing-timezone-part))
(let* ((entry (second parts))
(start (car entry))
(end (cdr entry)))
(declare (type fixnum start end))
(passert (or zulup
(not (zerop (- end start)))))
(unless zulup
(time-offset (second parts) sign))))))))
(partial-time (start-end)
(with-parts-and-count ((car start-end) (cdr start-end) time-separator)
(passert (eql count 3))
(time-hour (first parts))
(time-minute (second parts))
(time-second (third parts))))
(time-hour (start-end)
(parse-integer-into start-end hour 0 23))
(time-minute (start-end)
(parse-integer-into start-end minute 0 59))
(time-second (start-end)
(with-parts-and-count ((car start-end) (cdr start-end) fract-time-separators)
(passert (<= 1 count 2))
(let ((*read-eval* nil))
(parse-integer-into (first parts) second 0 59)
(if (> count 1)
(let* ((start (car (second parts)))
(end (cdr (second parts))))
(declare (type (integer 0 #.array-dimension-limit) start end))
(passert (<= (- end start) 9))
(let ((new-end (position #\0 time-string
:test-not #'eql
:start start
:end end
:from-end t)))
(when new-end
(setf end (min (1+ new-end)))))
(setf nsec (* (the (integer 0 999999999) (parse-integer time-string :start start :end end))
(aref #.(coerce #(1000000000 100000000 10000000
1000000 100000 10000 1000 100 10 1)
'(simple-array (signed-byte 32) (10)))
(- end start)))))
(setf nsec 0)))))
(time-offset (start-end sign)
(with-parts-and-count ((car start-end) (cdr start-end) time-separator)
(passert (or (and allow-missing-timezone-part (zerop count))
(= count 1)
(= count 2)))
(cond
((= count 2)
hh : offset
(parse-integer-into (first parts) offset-hour 0 23)
(parse-integer-into (second parts) offset-minute 0 59))
((= (- (cdar parts) (caar parts)) 4)
(parse-integer-into (cons (caar parts)
(+ (caar parts) 2))
offset-hour 0 23)
(parse-integer-into (cons (+ (caar parts) 2)
(+ (caar parts) 4))
offset-minute 0 59))
((= (- (cdar parts) (caar parts)) 2)
(parse-integer-into (cons (caar parts)
(+ (caar parts) 2))
offset-hour 0 23)
(setf offset-minute 0)))
(setf offset-hour (* offset-hour sign)
offset-minute (* offset-minute sign))))
(parse-error (failure)
(if fail-on-error
(error 'invalid-timestring :timestring time-string :failure failure)
(return-from %split-timestring nil)))
(done ()
(return-from %split-timestring (list year month day hour minute second nsec offset-hour offset-minute))))
(parse))))))
(defun parse-rfc3339-timestring (timestring &key (fail-on-error t)
(allow-missing-time-part nil))
(parse-timestring timestring :fail-on-error fail-on-error
:allow-missing-timezone-part nil
:allow-missing-time-part allow-missing-time-part
:allow-missing-date-part nil
:fract-time-separators #\.))
(defun parse-timestring (timestring &key
start
end
(fail-on-error t)
(time-separator #\:)
(date-separator #\-)
(date-time-separator #\T)
(fract-time-separators '(#\. #\,))
(allow-missing-elements t)
(allow-missing-date-part allow-missing-elements)
(allow-missing-time-part allow-missing-elements)
(allow-missing-timezone-part allow-missing-elements)
(offset 0))
"Parse a timestring and return the corresponding TIMESTAMP.
See split-timestring for details. Unspecified fields in the
timestring are initialized to their lowest possible value,
and timezone offset is 0 (UTC) unless explicitly specified
in the input string."
(let ((parts (%split-timestring (coerce timestring 'simple-string)
:start (or start 0)
:end (or end (length timestring))
:fail-on-error fail-on-error
:time-separator time-separator
:date-separator date-separator
:date-time-separator date-time-separator
:fract-time-separators fract-time-separators
:allow-missing-elements allow-missing-elements
:allow-missing-date-part allow-missing-date-part
:allow-missing-time-part allow-missing-time-part
:allow-missing-timezone-part allow-missing-timezone-part)))
(when parts
(destructuring-bind (year month day hour minute second nsec offset-hour offset-minute)
parts
(encode-timestamp
(or nsec 0)
(or second 0)
(or minute 0)
(or hour 0)
(or day 1)
(or month 3)
(or year 2000)
:offset (if offset-hour
(+ (* offset-hour 3600)
(* (or offset-minute 0) 60))
offset))))))
(defun ordinalize (day)
"Return an ordinal string representing the position
of DAY in a sequence (1st, 2nd, 3rd, 4th, etc)."
(declare (type (integer 1 31) day))
(format nil "~d~a" day
(if (<= 11 day 13)
"th"
(case (mod day 10)
(1 "st")
(2 "nd")
(3 "rd")
(t "th")))))
(defun %construct-timestring (timestamp format timezone)
"Constructs a string representing TIMESTAMP given the FORMAT
of the string and the TIMEZONE.
See the documentation of FORMAT-TIMESTRING for the structure of FORMAT."
(declare (type timestamp timestamp)
(optimize (speed 3)))
(multiple-value-bind (nsec sec minute hour day month year weekday daylight-p offset abbrev)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore daylight-p))
(multiple-value-bind (iso-year iso-week iso-weekday)
(%timestamp-decode-iso-week timestamp)
(let ((*print-pretty* nil)
(*print-circle* nil))
(with-output-to-string (result nil)
(dolist (fmt format)
(cond
((member fmt '(:gmt-offset :gmt-offset-or-z :gmt-offset-hhmm))
(multiple-value-bind (offset-hours offset-secs)
(floor offset +seconds-per-hour+)
(declare (fixnum offset-hours offset-secs))
(if (and (eql fmt :gmt-offset-or-z) (zerop offset))
(princ #\Z result)
(format result "~c~2,'0d~:[:~;~]~2,'0d"
(if (minusp offset-hours) #\- #\+)
(abs offset-hours)
(eql fmt :gmt-offset-hhmm)
(truncate (abs offset-secs)
+seconds-per-minute+)))))
((eql fmt :short-year)
(princ (mod year 100) result))
((eql fmt :long-month)
(princ (aref +month-names+ month) result))
((eql fmt :short-month)
(princ (aref +short-month-names+ month) result))
((eql fmt :long-weekday)
(princ (aref +day-names+ weekday) result))
((eql fmt :short-weekday)
(princ (aref +short-day-names+ weekday) result))
((eql fmt :minimal-weekday)
(princ (aref +minimal-day-names+ weekday) result))
((eql fmt :timezone)
(princ abbrev result))
((eql fmt :ampm)
(princ (if (< hour 12) "am" "pm") result))
((eql fmt :ordinal-day)
(princ (ordinalize day) result))
((or (stringp fmt) (characterp fmt))
(princ fmt result))
(t
(let ((val (ecase (if (consp fmt) (car fmt) fmt)
(:nsec nsec)
(:usec (floor nsec 1000))
(:msec (floor nsec 1000000))
(:sec sec)
(:min minute)
(:hour hour)
(:hour12 (1+ (mod (1- hour) 12)))
(:day day)
(:weekday weekday)
(:month month)
(:year year)
(:iso-week-year iso-year)
(:iso-week-number iso-week)
(:iso-week-day iso-weekday))))
(cond
((atom fmt)
(princ val result))
((minusp val)
(format result "-~v,vd"
(second fmt)
(or (third fmt) #\0)
(abs val)))
(t
(format result "~v,vd"
(second fmt)
(or (third fmt) #\0)
val))))))))))))
(defun format-timestring (destination timestamp &key
(format +iso-8601-format+)
(timezone *default-timezone*))
"Constructs a string representation of TIMESTAMP according
to FORMAT and returns it.
If destination is T, the string is written to *standard-output*.
If destination is a stream, the string is written to the stream.
FORMAT is a list containing one or more of strings, characters,
and keywords. Strings and characters are output literally,
while keywords are replaced by the values here:
:YEAR *year
:MONTH *numeric month
:DAY *day of month
:HOUR *hour
:MIN *minutes
:SEC *seconds
:WEEKDAY *numeric day of week starting from index 0, which means Sunday
:MSEC *milliseconds
:USEC *microseconds
:NSEC *nanoseconds
:ISO-WEEK-YEAR *year for ISO week date (can be different from regular calendar year)
:ISO-WEEK-NUMBER *ISO week number (i.e. 1 through 53)
:ISO-WEEK-DAY *ISO compatible weekday number (monday=1, sunday=7)
:LONG-WEEKDAY long form of weekday (e.g. Sunday, Monday)
:SHORT-WEEKDAY short form of weekday (e.g. Sun, Mon)
:MINIMAL-WEEKDAY minimal form of weekday (e.g. Su, Mo)
:SHORT-YEAR short form of year (last 2 digits, e.g. 41, 42 instead of 2041, 2042)
:LONG-MONTH long form of month (e.g. January, February)
:SHORT-MONTH short form of month (e.g. Jan, Feb)
:HOUR12 *hour on a 12-hour clock
:AMPM am/pm marker in lowercase
:GMT-OFFSET the gmt-offset of the time, in +00:00 form
:GMT-OFFSET-OR-Z like :GMT-OFFSET, but is Z when UTC
:GMT-OFFSET-HHMM like :GMT-OFFSET, but in +0000 form
:TIMEZONE timezone abbrevation for the time
Elements marked by * can be placed in a list in the form
\(:keyword padding &optional \(padchar #\\0))
The string representation of the value will be padded with the padchar.
You can see examples in +ISO-8601-FORMAT+, +ASCTIME-FORMAT+, and +RFC-1123-FORMAT+."
(declare (type (or boolean stream) destination))
(let ((result (%construct-timestring timestamp format timezone)))
(when destination
(write-string result (if (eq t destination) *standard-output* destination)))
result))
(defun format-rfc1123-timestring (destination timestamp &key
(timezone *default-timezone*))
(format-timestring destination timestamp
:format +rfc-1123-format+
:timezone timezone))
(defun to-rfc1123-timestring (timestamp)
(format-rfc1123-timestring nil timestamp))
(defun format-rfc3339-timestring (destination timestamp &key
omit-date-part
omit-time-part
(omit-timezone-part omit-time-part)
(use-zulu t)
(timezone *default-timezone*))
"Formats a timestring in the RFC 3339 format, a restricted form of the ISO-8601 timestring specification for Internet timestamps."
(let ((rfc3339-format
(if (and use-zulu
(not omit-date-part)
(not omit-time-part)
(not omit-timezone-part))
(append
(unless omit-date-part
'((:year 4) #\-
(:month 2) #\-
(:day 2)))
(unless (or omit-date-part
omit-time-part)
'(#\T))
(unless omit-time-part
'((:hour 2) #\:
(:min 2) #\:
(:sec 2) #\.
(:usec 6)))
(unless omit-timezone-part
(if use-zulu
'(:gmt-offset-or-z)
'(:gmt-offset)))))))
(format-timestring destination timestamp :format rfc3339-format :timezone timezone)))
(defun to-rfc3339-timestring (timestamp)
(format-rfc3339-timestring nil timestamp))
(defun %read-timestring (stream char)
(declare (ignore char))
(parse-timestring
(with-output-to-string (str)
(loop for c = (read-char stream nil)
while (and c (or (digit-char-p c) (member c '(#\: #\T #\t #\: #\- #\+ #\Z #\.))))
do (princ c str)
finally (when c (unread-char c stream))))
:allow-missing-elements t))
(defun %read-universal-time (stream char arg)
(declare (ignore char arg))
(universal-to-timestamp
(parse-integer
(with-output-to-string (str)
(loop for c = (read-char stream nil)
while (and c (digit-char-p c))
do (princ c str)
finally (when c (unread-char c stream)))))))
(defun enable-read-macros ()
"Enables the local-time reader macros for literal timestamps and universal time."
(set-macro-character #\@ '%read-timestring)
(set-dispatch-macro-character #\# #\@ '%read-universal-time)
(values))
(defvar *debug-timestamp* nil)
(defmethod print-object ((object timestamp) stream)
"Print the TIMESTAMP object using the standard reader notation"
(cond
(*debug-timestamp*
(print-unreadable-object (object stream :type t)
(format stream "~d/~d/~d"
(day-of object)
(sec-of object)
(nsec-of object))))
(t
(when *print-escape*
(write-char #\@ stream))
(format-rfc3339-timestring stream object))))
(defmethod print-object ((object timezone) stream)
"Print the TIMEZONE object in a reader-rejected manner."
(print-unreadable-object (object stream :type t)
(format stream "~:[UNLOADED~;~{~a~^ ~}~]"
(timezone-loaded object)
(map 'list #'subzone-abbrev (timezone-subzones object)))))
(defun astronomical-julian-date (timestamp)
"Returns the astronomical julian date referred to by the timestamp."
(- (day-of timestamp) +astronomical-julian-date-offset+))
(defun modified-julian-date (timestamp)
"Returns the modified julian date referred to by the timestamp."
(- (day-of timestamp) +modified-julian-date-offset+))
(declaim (notinline format-timestring))
|
33dc4933b89782c187dcd9854420b0f74ad63a8b0ebc8a044de8586824795b34 | cram2/cram | matrix-product-hermitian.lisp | Regression test MATRIX - PRODUCT - HERMITIAN for GSLL , automatically generated
;;
Copyright 2009 , 2010 , 2014
Distributed under the terms of the GNU General Public License
;;
;; 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 3 of the License , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST MATRIX-PRODUCT-HERMITIAN
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(161635.16f0 -134299.77f0) #C(93510.016f0 -191870.72f0)
#C(55739.336f0 13621.439f0))
(#C(-68526.41f0 125188.29f0) #C(46318.242f0 59787.605f0)
#C(-28142.984f0 5816.9385f0))
(#C(-139503.38f0 55690.902f0) #C(2898.8164f0 49116.78f0)
#C(-57882.3f0 -176350.63f0))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5 8.24) #C(3.29 -8.93) #C(34.12 -6.15))
(#C(-8.93 34.12) #C(-6.15 49.27) #C(-13.49 32.5))
(#C(49.27 -13.49) #C(32.5 42.73) #C(-17.24 43.31)))))
(M2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(42.73 -17.24) #C(43.31 -16.12) #C(-8.25 21.44))
(#C(-16.12 -8.25) #C(21.44 -49.08) #C(-39.66 -49.46))
(#C(-49.08 -39.66) #C(-49.46 19.68) #C(-5.55 -8.82)))))
(M3
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(19.68 -5.55) #C(-8.82 25.37) #C(-30.58 31.67))
(#C(25.37 -30.58) #C(31.67 29.36) #C(-33.24 -27.03))
(#C(29.36 -33.24) #C(-27.03 -41.67) #C(42.0 -20.81)))))
(S1 #C(-41.67f0 42.0f0))
(S2 #C(42.0f0 -20.81f0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 M2 M3 S1 S2) 'array '(complex single-float)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(161635.17690299999d0 -134299.761873d0)
#C(93510.01525000001d0 -191870.723694d0)
#C(55739.340844000006d0 13621.441385000013d0))
(#C(-68526.41140699999d0 125188.28846599998d0)
#C(46318.25349699999d0 59787.61715899999d0)
#C(-28142.984856000003d0 5816.936996999999d0))
(#C(-139503.391422d0 55690.900627999996d0)
#C(2898.816300000017d0 49116.78897299998d0)
#C(-57882.29909799999d0 -176350.62442500002d0))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5d0 8.24d0) #C(3.29d0 -8.93d0) #C(34.12d0 -6.15d0))
(#C(-8.93d0 34.12d0) #C(-6.15d0 49.27d0) #C(-13.49d0 32.5d0))
(#C(49.27d0 -13.49d0) #C(32.5d0 42.73d0) #C(-17.24d0 43.31d0)))))
(M2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(42.73d0 -17.24d0) #C(43.31d0 -16.12d0) #C(-8.25d0 21.44d0))
(#C(-16.12d0 -8.25d0) #C(21.44d0 -49.08d0) #C(-39.66d0 -49.46d0))
(#C(-49.08d0 -39.66d0) #C(-49.46d0 19.68d0) #C(-5.55d0 -8.82d0)))))
(M3
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(19.68d0 -5.55d0) #C(-8.82d0 25.37d0) #C(-30.58d0 31.67d0))
(#C(25.37d0 -30.58d0) #C(31.67d0 29.36d0) #C(-33.24d0 -27.03d0))
(#C(29.36d0 -33.24d0) #C(-27.03d0 -41.67d0) #C(42.0d0 -20.81d0)))))
(S1 #C(-41.67d0 42.0d0))
(S2 #C(42.0d0 -20.81d0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 M2 M3 S1 S2) 'array '(complex double-float)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#(#C(117171.67f0 19582.54f0) #C(18787.117f0 29534.742f0)
#C(-104992.03f0 72729.13f0)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5 8.24) #C(3.29 -8.93) #C(34.12 -6.15))
(#C(-8.93 34.12) #C(-6.15 49.27) #C(-13.49 32.5))
(#C(49.27 -13.49) #C(32.5 42.73) #C(-17.24 43.31)))))
(V1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'(#C(42.73 -17.24) #C(43.31 -16.12) #C(-8.25 21.44))))
(V2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'(#C(-16.12 -8.25) #C(21.44 -49.08) #C(-39.66 -49.46))))
(S1 #C(-49.08f0 -39.66f0))
(S2 #C(-39.66f0 -49.46f0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 V1 V2 S1 S2) 'array '(complex single-float)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#(#C(117171.67150799997d0 19582.539385999997d0)
#C(18787.113150000005d0 29534.74247000001d0)
#C(-104992.03586199998d0 72729.12516600001d0)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5d0 8.24d0) #C(3.29d0 -8.93d0) #C(34.12d0 -6.15d0))
(#C(-8.93d0 34.12d0) #C(-6.15d0 49.27d0) #C(-13.49d0 32.5d0))
(#C(49.27d0 -13.49d0) #C(32.5d0 42.73d0) #C(-17.24d0 43.31d0)))))
(V1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'(#C(42.73d0 -17.24d0) #C(43.31d0 -16.12d0) #C(-8.25d0 21.44d0))))
(V2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'(#C(-16.12d0 -8.25d0) #C(21.44d0 -49.08d0) #C(-39.66d0 -49.46d0))))
(S1 #C(-49.08d0 -39.66d0))
(S2 #C(-39.66d0 -49.46d0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 V1 V2 S1 S2) 'array '(complex double-float))))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/tests/matrix-product-hermitian.lisp | lisp |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | Regression test MATRIX - PRODUCT - HERMITIAN for GSLL , automatically generated
Copyright 2009 , 2010 , 2014
Distributed under the terms of the GNU General Public License
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST MATRIX-PRODUCT-HERMITIAN
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(161635.16f0 -134299.77f0) #C(93510.016f0 -191870.72f0)
#C(55739.336f0 13621.439f0))
(#C(-68526.41f0 125188.29f0) #C(46318.242f0 59787.605f0)
#C(-28142.984f0 5816.9385f0))
(#C(-139503.38f0 55690.902f0) #C(2898.8164f0 49116.78f0)
#C(-57882.3f0 -176350.63f0))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5 8.24) #C(3.29 -8.93) #C(34.12 -6.15))
(#C(-8.93 34.12) #C(-6.15 49.27) #C(-13.49 32.5))
(#C(49.27 -13.49) #C(32.5 42.73) #C(-17.24 43.31)))))
(M2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(42.73 -17.24) #C(43.31 -16.12) #C(-8.25 21.44))
(#C(-16.12 -8.25) #C(21.44 -49.08) #C(-39.66 -49.46))
(#C(-49.08 -39.66) #C(-49.46 19.68) #C(-5.55 -8.82)))))
(M3
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(19.68 -5.55) #C(-8.82 25.37) #C(-30.58 31.67))
(#C(25.37 -30.58) #C(31.67 29.36) #C(-33.24 -27.03))
(#C(29.36 -33.24) #C(-27.03 -41.67) #C(42.0 -20.81)))))
(S1 #C(-41.67f0 42.0f0))
(S2 #C(42.0f0 -20.81f0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 M2 M3 S1 S2) 'array '(complex single-float)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#2A((#C(161635.17690299999d0 -134299.761873d0)
#C(93510.01525000001d0 -191870.723694d0)
#C(55739.340844000006d0 13621.441385000013d0))
(#C(-68526.41140699999d0 125188.28846599998d0)
#C(46318.25349699999d0 59787.61715899999d0)
#C(-28142.984856000003d0 5816.936996999999d0))
(#C(-139503.391422d0 55690.900627999996d0)
#C(2898.816300000017d0 49116.78897299998d0)
#C(-57882.29909799999d0 -176350.62442500002d0))))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5d0 8.24d0) #C(3.29d0 -8.93d0) #C(34.12d0 -6.15d0))
(#C(-8.93d0 34.12d0) #C(-6.15d0 49.27d0) #C(-13.49d0 32.5d0))
(#C(49.27d0 -13.49d0) #C(32.5d0 42.73d0) #C(-17.24d0 43.31d0)))))
(M2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(42.73d0 -17.24d0) #C(43.31d0 -16.12d0) #C(-8.25d0 21.44d0))
(#C(-16.12d0 -8.25d0) #C(21.44d0 -49.08d0) #C(-39.66d0 -49.46d0))
(#C(-49.08d0 -39.66d0) #C(-49.46d0 19.68d0) #C(-5.55d0 -8.82d0)))))
(M3
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(19.68d0 -5.55d0) #C(-8.82d0 25.37d0) #C(-30.58d0 31.67d0))
(#C(25.37d0 -30.58d0) #C(31.67d0 29.36d0) #C(-33.24d0 -27.03d0))
(#C(29.36d0 -33.24d0) #C(-27.03d0 -41.67d0) #C(42.0d0 -20.81d0)))))
(S1 #C(-41.67d0 42.0d0))
(S2 #C(42.0d0 -20.81d0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 M2 M3 S1 S2) 'array '(complex double-float)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#(#C(117171.67f0 19582.54f0) #C(18787.117f0 29534.742f0)
#C(-104992.03f0 72729.13f0)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5 8.24) #C(3.29 -8.93) #C(34.12 -6.15))
(#C(-8.93 34.12) #C(-6.15 49.27) #C(-13.49 32.5))
(#C(49.27 -13.49) #C(32.5 42.73) #C(-17.24 43.31)))))
(V1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'(#C(42.73 -17.24) #C(43.31 -16.12) #C(-8.25 21.44))))
(V2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX SINGLE-FLOAT)
:INITIAL-CONTENTS
'(#C(-16.12 -8.25) #C(21.44 -49.08) #C(-39.66 -49.46))))
(S1 #C(-49.08f0 -39.66f0))
(S2 #C(-39.66f0 -49.46f0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 V1 V2 S1 S2) 'array '(complex single-float)))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST
#(#C(117171.67150799997d0 19582.539385999997d0)
#C(18787.113150000005d0 29534.74247000001d0)
#C(-104992.03586199998d0 72729.12516600001d0)))
(MULTIPLE-VALUE-LIST
(LET ((M1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'((#C(-34.5d0 8.24d0) #C(3.29d0 -8.93d0) #C(34.12d0 -6.15d0))
(#C(-8.93d0 34.12d0) #C(-6.15d0 49.27d0) #C(-13.49d0 32.5d0))
(#C(49.27d0 -13.49d0) #C(32.5d0 42.73d0) #C(-17.24d0 43.31d0)))))
(V1
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'(#C(42.73d0 -17.24d0) #C(43.31d0 -16.12d0) #C(-8.25d0 21.44d0))))
(V2
(GRID:MAKE-FOREIGN-ARRAY
'(COMPLEX DOUBLE-FLOAT)
:INITIAL-CONTENTS
'(#C(-16.12d0 -8.25d0) #C(21.44d0 -49.08d0) #C(-39.66d0 -49.46d0))))
(S1 #C(-49.08d0 -39.66d0))
(S2 #C(-39.66d0 -49.46d0)))
(GRID:COPY-TO
(MATRIX-PRODUCT-HERMITIAN M1 V1 V2 S1 S2) 'array '(complex double-float))))))
|
5eda460c1131cdb8f080e1db4a69e72f92fd66e84930b4f5ad399523a63784e5 | clojure/core.typed | recur_utils.clj | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^:skip-wiki clojure.core.typed.checker.check.recur-utils
(:require [clojure.core.typed.checker.utils :as u]
[clojure.core.typed.checker.type-rep :as r]))
(u/def-type RecurTarget [dom rest drest kws]
"A target for recur"
[(every? r/Type? dom)
((some-fn nil? r/Type?) rest)
((some-fn nil? r/DottedPretype?) drest)
TODO
(defmacro ^:private set-validator-doc! [var val-fn]
`(set-validator! ~var (fn [a#] (assert (~val-fn a#)
(str "Invalid reference state: " ~var
" with value: "
(pr-str a#)))
true)))
(defonce ^:dynamic *recur-target* nil)
(set-validator-doc! #'*recur-target* (some-fn nil? RecurTarget?))
(defmacro with-recur-target [tgt & body]
`(binding [*recur-target* ~tgt]
~@body))
(defonce ^:dynamic *loop-bnd-anns* nil)
(set-validator! #'*loop-bnd-anns* #(or (nil? %)
(every? r/Type? %)))
| null | https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/check/recur_utils.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , contributors .
(ns ^:skip-wiki clojure.core.typed.checker.check.recur-utils
(:require [clojure.core.typed.checker.utils :as u]
[clojure.core.typed.checker.type-rep :as r]))
(u/def-type RecurTarget [dom rest drest kws]
"A target for recur"
[(every? r/Type? dom)
((some-fn nil? r/Type?) rest)
((some-fn nil? r/DottedPretype?) drest)
TODO
(defmacro ^:private set-validator-doc! [var val-fn]
`(set-validator! ~var (fn [a#] (assert (~val-fn a#)
(str "Invalid reference state: " ~var
" with value: "
(pr-str a#)))
true)))
(defonce ^:dynamic *recur-target* nil)
(set-validator-doc! #'*recur-target* (some-fn nil? RecurTarget?))
(defmacro with-recur-target [tgt & body]
`(binding [*recur-target* ~tgt]
~@body))
(defonce ^:dynamic *loop-bnd-anns* nil)
(set-validator! #'*loop-bnd-anns* #(or (nil? %)
(every? r/Type? %)))
|
afd8a6b387c6f764c893393ea7745b74ec356a9d7a14ea34507c09294abd5611 | arcadia-unity/ArcadiaGodot | def.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.test-clojure.def
(:use clojure.test clojure.test-helper
clojure.test-clojure.protocols))
(deftest defn-error-messages
(testing "multiarity syntax invalid parameter declaration"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn foo (arg1 arg2))))))
(testing "multiarity syntax invalid signature"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn foo
([a] 1)
[a b])))))
(testing "assume single arity syntax"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn foo a)))))
(testing "bad name"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn "bad docstring" testname [arg1 arg2])))))
(testing "missing parameter/signature"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn testname)))))
(testing "allow trailing map"
(is (eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b}))))
(testing "don't allow interleaved map"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b} ([] 1)))))))
(deftest non-dynamic-warnings
(testing "no warning for **"
(is (empty? (with-err-print-writer
(eval-in-temp-ns (defn ** ([a b] (Math/pow (double a) (double b)))))))))
(testing "warning for *hello*"
(is (not (empty? (with-err-print-writer
(eval-in-temp-ns (def *hello* "hi"))))))))
(deftest dynamic-redefinition
;; too many contextual things for this kind of caching to work...
(testing "classes are never cached, even if their bodies are the same"
(is (= :b
(eval
'(do
(defmacro my-macro [] :a)
(defn do-macro [] (my-macro))
(defmacro my-macro [] :b)
(defn do-macro [] (my-macro))
(do-macro)))))))
(deftest nested-dynamic-declaration
(testing "vars :dynamic meta data is applied immediately to vars declared anywhere"
(is (= 10
(eval
'(do
(list
(declare ^:dynamic p)
(defn q [] @p))
(binding [p (atom 10)]
(q))))))))
| null | https://raw.githubusercontent.com/arcadia-unity/ArcadiaGodot/d9881c8132c46f21efde4eb4eb9a534d808cdb20/Clojure/clojure/test_clojure/def.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
too many contextual things for this kind of caching to work... | Copyright ( c ) . All rights reserved .
(ns clojure.test-clojure.def
(:use clojure.test clojure.test-helper
clojure.test-clojure.protocols))
(deftest defn-error-messages
(testing "multiarity syntax invalid parameter declaration"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn foo (arg1 arg2))))))
(testing "multiarity syntax invalid signature"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn foo
([a] 1)
[a b])))))
(testing "assume single arity syntax"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn foo a)))))
(testing "bad name"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn "bad docstring" testname [arg1 arg2])))))
(testing "missing parameter/signature"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn testname)))))
(testing "allow trailing map"
(is (eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b}))))
(testing "don't allow interleaved map"
(is (fails-with-cause?
clojure.lang.ExceptionInfo
#"Call to clojure.core/defn did not conform to spec"
(eval-in-temp-ns (defn a "asdf" ([a] 1) {:a :b} ([] 1)))))))
(deftest non-dynamic-warnings
(testing "no warning for **"
(is (empty? (with-err-print-writer
(eval-in-temp-ns (defn ** ([a b] (Math/pow (double a) (double b)))))))))
(testing "warning for *hello*"
(is (not (empty? (with-err-print-writer
(eval-in-temp-ns (def *hello* "hi"))))))))
(deftest dynamic-redefinition
(testing "classes are never cached, even if their bodies are the same"
(is (= :b
(eval
'(do
(defmacro my-macro [] :a)
(defn do-macro [] (my-macro))
(defmacro my-macro [] :b)
(defn do-macro [] (my-macro))
(do-macro)))))))
(deftest nested-dynamic-declaration
(testing "vars :dynamic meta data is applied immediately to vars declared anywhere"
(is (= 10
(eval
'(do
(list
(declare ^:dynamic p)
(defn q [] @p))
(binding [p (atom 10)]
(q))))))))
|
67346d60950823ab853bf7e903d6a95929dd8edc25a2c7da482c1fbec6418abd | Mesabloo/HaSM | Mmap.hs | # LANGUAGE CPP , ForeignFunctionInterface #
module System.Mmap
( mmap, munmap
, module System.Mmap.Flags
, module System.Mmap.Exception ) where
import Foreign.Ptr
import Foreign.C.Types
import System.Mmap.Flags
import System.Mmap.Exception
import Control.Exception (throwIO)
import Control.Monad (when)
import Data.Word
import System.Posix.Types
#ifndef mingw32_HOST_OS
foreign import ccall unsafe "sys/mman.h mmap"
#else
foreign import ccall unsafe "./MMap/windows-mmap.h mmap"
#endif
c_mmap :: Ptr () -> CSize -> ProtOption -> MmapOption -> Fd -> COff -> IO (Ptr a)
#ifndef mingw32_HOST_OS
foreign import ccall unsafe "sys/mman.h munmap"
#else
foreign import ccall unsafe "./MMap/windows-mmap.h munmap"
#endif
c_munmap :: Ptr a -> CSize -> IO Int
-- | The 'mmap' function is used to allocate pages.
mmap :: Ptr () -> CSize -> ProtOption -> MmapOption -> Fd -> COff -> IO (Ptr Word8)
mmap addr len prot flags fd offset = do
ptr <- c_mmap addr len prot flags fd offset
when (ptr == intPtrToPtr (-1)) $ throwIO MmapException
pure ptr
-- | The 'munmap' function is used to free pages.
munmap :: Ptr a -> CSize -> IO Int
munmap addr len = do
ret <- c_munmap addr len
when (ret == -1) $ throwIO MmapException
pure ret | null | https://raw.githubusercontent.com/Mesabloo/HaSM/7d75f0a81055d1e9c9dd0d351f3e9b9c00c7dadd/src/System/Mmap.hs | haskell | | The 'mmap' function is used to allocate pages.
| The 'munmap' function is used to free pages. | # LANGUAGE CPP , ForeignFunctionInterface #
module System.Mmap
( mmap, munmap
, module System.Mmap.Flags
, module System.Mmap.Exception ) where
import Foreign.Ptr
import Foreign.C.Types
import System.Mmap.Flags
import System.Mmap.Exception
import Control.Exception (throwIO)
import Control.Monad (when)
import Data.Word
import System.Posix.Types
#ifndef mingw32_HOST_OS
foreign import ccall unsafe "sys/mman.h mmap"
#else
foreign import ccall unsafe "./MMap/windows-mmap.h mmap"
#endif
c_mmap :: Ptr () -> CSize -> ProtOption -> MmapOption -> Fd -> COff -> IO (Ptr a)
#ifndef mingw32_HOST_OS
foreign import ccall unsafe "sys/mman.h munmap"
#else
foreign import ccall unsafe "./MMap/windows-mmap.h munmap"
#endif
c_munmap :: Ptr a -> CSize -> IO Int
mmap :: Ptr () -> CSize -> ProtOption -> MmapOption -> Fd -> COff -> IO (Ptr Word8)
mmap addr len prot flags fd offset = do
ptr <- c_mmap addr len prot flags fd offset
when (ptr == intPtrToPtr (-1)) $ throwIO MmapException
pure ptr
munmap :: Ptr a -> CSize -> IO Int
munmap addr len = do
ret <- c_munmap addr len
when (ret == -1) $ throwIO MmapException
pure ret |
1639703c085df05c5c3d0d9912cd19795a65cd01205be57e3a29efe5079f9cc4 | kazzmir/master-of-magic | exmouse.ml | Example program for the Allegro library , by .
*
* This program demonstrates how to get mouse input . The
* first part of the test retrieves the raw mouse input data
* and displays it on the screen without using any mouse
* cursor . When you press a key the standard arrow - like mouse
* cursor appears . You are not restricted to this shape ,
* and a second key press modifies the cursor to be several
* concentric colored circles . They are not joined together ,
* so you can still see bits of what 's behind when you move the
* cursor over the printed text message .
*
* This program demonstrates how to get mouse input. The
* first part of the test retrieves the raw mouse input data
* and displays it on the screen without using any mouse
* cursor. When you press a key the standard arrow-like mouse
* cursor appears. You are not restricted to this shape,
* and a second key press modifies the cursor to be several
* concentric colored circles. They are not joined together,
* so you can still see bits of what's behind when you move the
* cursor over the printed text message.
*)
open Allegro ;;
let print_all_buttons() =
let screen, font = get_screen(), get_font() in
let fc = makecol 0 0 0 in
let bc = makecol 255 255 255 in
textprintf_right_ex screen font 320 50 fc bc "buttons";
for i = 0 to pred 8 do
let x = 320 in
let y = 60 + i * 10 in
if ((get_mouse_b()) land (1 lsl i)) <> 0
then textout_right_ex screen font (string_of_int(1 + i)) x y fc bc
else textout_right_ex screen font " " x y fc bc;
done;
;;
let () =
allegro_init();
install_keyboard();
install_timer();
begin
try set_gfx_mode GFX_AUTODETECT_WINDOWED 320 200 0 0
with _ ->
try set_gfx_mode GFX_SAFE 320 200 0 0
with _ ->
set_gfx_mode GFX_TEXT 0 0 0 0;
allegro_message("Unable to set any graphic mode\n"^ (get_allegro_error()) ^"\n");
exit 1;
end;
let screen, font = get_screen(), get_font() in
let screen_w = get_screen_width()
and screen_h = get_screen_height() in
set_palette(get_desktop_palette());
clear_to_color screen (makecol 255 255 255);
(* Detect mouse presence *)
let _ =
try install_mouse()
with _ ->
textout_centre_ex screen font "No mouse detected, but you need one!"
(screen_w/2) (screen_h/2) (makecol 0 0 0) (makecol 255 255 255);
ignore(readkey());
exit 0;
in
textprintf_centre_ex screen font (screen_w/2) 8 (makecol 0 0 0)
(makecol 255 255 255)
"Driver: %s" (mouse_driver_name());
let c = ref 0 in
let mickeyx = ref 0 in
let mickeyy = ref 0 in
while not(keypressed()) do
(* On most platforms (eg. DOS) things will still work correctly
* without this call, but it is a good idea to include it in any
* programs that you want to be portable, because on some platforms
* you may not be able to get any mouse input without it.
*)
poll_mouse();
acquire_screen();
let black, white = (makecol 0 0 0), (makecol 255 255 255) in
(* the mouse position is stored in the variables mouse_x and mouse_y *)
textprintf_ex screen font 16 48 black white "mouse_x = %-5d" (get_mouse_x());
textprintf_ex screen font 16 64 black white "mouse_y = %-5d" (get_mouse_y());
or you can use this function to measure the speed of movement .
* Note that we only call it every fourth time round the loop :
* there 's no need for that other than to slow the numbers down
* a bit so that you will have time to read them ...
* Note that we only call it every fourth time round the loop:
* there's no need for that other than to slow the numbers down
* a bit so that you will have time to read them...
*)
incr c;
if ((!c land 3) = 0) then
begin
let _mickeyx, _mickeyy = get_mouse_mickeys() in
mickeyx := _mickeyx;
mickeyy := _mickeyy;
end;
textprintf_ex screen font 16 88 black white "mickey_x = %-7d" !mickeyx;
textprintf_ex screen font 16 104 black white "mickey_y = %-7d" !mickeyy;
(* the mouse button state is stored in the variable mouse_b *)
if left_button_pressed()
then textout_ex screen font "left button is pressed " 16 128 black white
else textout_ex screen font "left button not pressed" 16 128 black white;
if right_button_pressed()
then textout_ex screen font "right button is pressed " 16 144 black white
else textout_ex screen font "right button not pressed" 16 144 black white;
if middle_button_pressed()
then textout_ex screen font "middle button is pressed " 16 160 black white
else textout_ex screen font "middle button not pressed" 16 160 black white;
(* the wheel position is stored in the variable mouse_z *)
textprintf_ex screen font 16 184 black white "mouse_z = %-5d" (get_mouse_z());
print_all_buttons();
release_screen();
vsync();
done;
clear_keybuf();
To display a mouse pointer , call show_mouse ( ) . There are several
* things you should be aware of before you do this , though . For one ,
* it wo n't work unless you call install_timer ( ) first . For another ,
* you must never draw anything onto the screen while the mouse
* pointer is visible . So before you draw anything , be sure to turn
* the mouse off with show_mouse(NULL ) , and turn it back on again when
* you are done .
* things you should be aware of before you do this, though. For one,
* it won't work unless you call install_timer() first. For another,
* you must never draw anything onto the screen while the mouse
* pointer is visible. So before you draw anything, be sure to turn
* the mouse off with show_mouse(NULL), and turn it back on again when
* you are done.
*)
clear_to_color screen (makecol 255 255 255);
textout_centre_ex screen font "Press a key to change cursor"
(screen_w/2) (screen_h/2) (makecol 0 0 0)
(makecol 255 255 255);
show_mouse screen;
ignore(readkey());
hide_mouse();
(* create a custom mouse cursor bitmap... *)
let custom_cursor = create_bitmap 32 32 in
clear_to_color custom_cursor (bitmap_mask_color screen);
for c=0 to pred 8 do
circle custom_cursor 16 16 (c*2) (palette_color c);
done;
(* select the custom cursor and set the focus point to the middle of it *)
set_mouse_sprite custom_cursor;
set_mouse_sprite_focus 16 16;
clear_to_color screen (makecol 255 255 255);
textout_centre_ex screen font "Press a key to quit" (screen_w/2)
(screen_h/2) (makecol 0 0 0) (makecol 255 255 255);
show_mouse screen;
ignore(readkey());
hide_mouse();
destroy_bitmap custom_cursor;
;;
| null | https://raw.githubusercontent.com/kazzmir/master-of-magic/830bfd1c549a5ac7370fa6a72bb06be5d3435fa0/lib/ocaml-allegro-20080222/ml_examples/exmouse.ml | ocaml | Detect mouse presence
On most platforms (eg. DOS) things will still work correctly
* without this call, but it is a good idea to include it in any
* programs that you want to be portable, because on some platforms
* you may not be able to get any mouse input without it.
the mouse position is stored in the variables mouse_x and mouse_y
the mouse button state is stored in the variable mouse_b
the wheel position is stored in the variable mouse_z
create a custom mouse cursor bitmap...
select the custom cursor and set the focus point to the middle of it | Example program for the Allegro library , by .
*
* This program demonstrates how to get mouse input . The
* first part of the test retrieves the raw mouse input data
* and displays it on the screen without using any mouse
* cursor . When you press a key the standard arrow - like mouse
* cursor appears . You are not restricted to this shape ,
* and a second key press modifies the cursor to be several
* concentric colored circles . They are not joined together ,
* so you can still see bits of what 's behind when you move the
* cursor over the printed text message .
*
* This program demonstrates how to get mouse input. The
* first part of the test retrieves the raw mouse input data
* and displays it on the screen without using any mouse
* cursor. When you press a key the standard arrow-like mouse
* cursor appears. You are not restricted to this shape,
* and a second key press modifies the cursor to be several
* concentric colored circles. They are not joined together,
* so you can still see bits of what's behind when you move the
* cursor over the printed text message.
*)
open Allegro ;;
let print_all_buttons() =
let screen, font = get_screen(), get_font() in
let fc = makecol 0 0 0 in
let bc = makecol 255 255 255 in
textprintf_right_ex screen font 320 50 fc bc "buttons";
for i = 0 to pred 8 do
let x = 320 in
let y = 60 + i * 10 in
if ((get_mouse_b()) land (1 lsl i)) <> 0
then textout_right_ex screen font (string_of_int(1 + i)) x y fc bc
else textout_right_ex screen font " " x y fc bc;
done;
;;
let () =
allegro_init();
install_keyboard();
install_timer();
begin
try set_gfx_mode GFX_AUTODETECT_WINDOWED 320 200 0 0
with _ ->
try set_gfx_mode GFX_SAFE 320 200 0 0
with _ ->
set_gfx_mode GFX_TEXT 0 0 0 0;
allegro_message("Unable to set any graphic mode\n"^ (get_allegro_error()) ^"\n");
exit 1;
end;
let screen, font = get_screen(), get_font() in
let screen_w = get_screen_width()
and screen_h = get_screen_height() in
set_palette(get_desktop_palette());
clear_to_color screen (makecol 255 255 255);
let _ =
try install_mouse()
with _ ->
textout_centre_ex screen font "No mouse detected, but you need one!"
(screen_w/2) (screen_h/2) (makecol 0 0 0) (makecol 255 255 255);
ignore(readkey());
exit 0;
in
textprintf_centre_ex screen font (screen_w/2) 8 (makecol 0 0 0)
(makecol 255 255 255)
"Driver: %s" (mouse_driver_name());
let c = ref 0 in
let mickeyx = ref 0 in
let mickeyy = ref 0 in
while not(keypressed()) do
poll_mouse();
acquire_screen();
let black, white = (makecol 0 0 0), (makecol 255 255 255) in
textprintf_ex screen font 16 48 black white "mouse_x = %-5d" (get_mouse_x());
textprintf_ex screen font 16 64 black white "mouse_y = %-5d" (get_mouse_y());
or you can use this function to measure the speed of movement .
* Note that we only call it every fourth time round the loop :
* there 's no need for that other than to slow the numbers down
* a bit so that you will have time to read them ...
* Note that we only call it every fourth time round the loop:
* there's no need for that other than to slow the numbers down
* a bit so that you will have time to read them...
*)
incr c;
if ((!c land 3) = 0) then
begin
let _mickeyx, _mickeyy = get_mouse_mickeys() in
mickeyx := _mickeyx;
mickeyy := _mickeyy;
end;
textprintf_ex screen font 16 88 black white "mickey_x = %-7d" !mickeyx;
textprintf_ex screen font 16 104 black white "mickey_y = %-7d" !mickeyy;
if left_button_pressed()
then textout_ex screen font "left button is pressed " 16 128 black white
else textout_ex screen font "left button not pressed" 16 128 black white;
if right_button_pressed()
then textout_ex screen font "right button is pressed " 16 144 black white
else textout_ex screen font "right button not pressed" 16 144 black white;
if middle_button_pressed()
then textout_ex screen font "middle button is pressed " 16 160 black white
else textout_ex screen font "middle button not pressed" 16 160 black white;
textprintf_ex screen font 16 184 black white "mouse_z = %-5d" (get_mouse_z());
print_all_buttons();
release_screen();
vsync();
done;
clear_keybuf();
To display a mouse pointer , call show_mouse ( ) . There are several
* things you should be aware of before you do this , though . For one ,
* it wo n't work unless you call install_timer ( ) first . For another ,
* you must never draw anything onto the screen while the mouse
* pointer is visible . So before you draw anything , be sure to turn
* the mouse off with show_mouse(NULL ) , and turn it back on again when
* you are done .
* things you should be aware of before you do this, though. For one,
* it won't work unless you call install_timer() first. For another,
* you must never draw anything onto the screen while the mouse
* pointer is visible. So before you draw anything, be sure to turn
* the mouse off with show_mouse(NULL), and turn it back on again when
* you are done.
*)
clear_to_color screen (makecol 255 255 255);
textout_centre_ex screen font "Press a key to change cursor"
(screen_w/2) (screen_h/2) (makecol 0 0 0)
(makecol 255 255 255);
show_mouse screen;
ignore(readkey());
hide_mouse();
let custom_cursor = create_bitmap 32 32 in
clear_to_color custom_cursor (bitmap_mask_color screen);
for c=0 to pred 8 do
circle custom_cursor 16 16 (c*2) (palette_color c);
done;
set_mouse_sprite custom_cursor;
set_mouse_sprite_focus 16 16;
clear_to_color screen (makecol 255 255 255);
textout_centre_ex screen font "Press a key to quit" (screen_w/2)
(screen_h/2) (makecol 0 0 0) (makecol 255 255 255);
show_mouse screen;
ignore(readkey());
hide_mouse();
destroy_bitmap custom_cursor;
;;
|
376924bceb3f2871e995024082049ea5ce1732c6d77aa91a9307a89e7caab4d3 | shayan-najd/NativeMetaprogramming | FailDueToGivenOverlapping.hs | # LANGUAGE FlexibleContexts #
module FailDueToGivenOverlapping where
class C a where
class D a where
dop :: a -> ()
instance C a => D [a]
-- should succeed since we can't learn anything more for 'a'
foo :: (C a, D [Int]) => a -> ()
foo x = dop [x]
class E a where
eop :: a -> ()
instance E [a] where
eop = undefined
-- should fail since we can never be sure that we learnt
-- everything about the free unification variable.
bar :: E [Int] => () -> ()
bar _ = eop [undefined]
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/should_fail/FailDueToGivenOverlapping.hs | haskell | should succeed since we can't learn anything more for 'a'
should fail since we can never be sure that we learnt
everything about the free unification variable. | # LANGUAGE FlexibleContexts #
module FailDueToGivenOverlapping where
class C a where
class D a where
dop :: a -> ()
instance C a => D [a]
foo :: (C a, D [Int]) => a -> ()
foo x = dop [x]
class E a where
eop :: a -> ()
instance E [a] where
eop = undefined
bar :: E [Int] => () -> ()
bar _ = eop [undefined]
|
0d995c47f342382eb952f3b6a61502c8a5f219a7a5b56a35a763f9a4633e249a | hasktorch/ffi-experimental | Generator.hs |
# LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
module ATen.Unmanaged.Type.Generator where
import qualified Language.C.Inline.Cpp as C
import qualified Language.C.Inline.Cpp.Exceptions as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import qualified Data.Map as Map
import Foreign.C.String
import Foreign.C.Types
import Foreign hiding (newForeignPtr)
import Foreign.Concurrent
import ATen.Type
import ATen.Class
C.context $ C.cppCtx <> mempty { C.ctxTypesTable = typeTable }
C.include "<ATen/ATen.h>"
C.include "<vector>"
deleteGenerator :: Ptr Generator -> IO ()
deleteGenerator object = [C.throwBlock| void { delete $(at::Generator* object);}|]
instance CppObject Generator where
fromPtr ptr = newForeignPtr ptr (deleteGenerator ptr)
| null | https://raw.githubusercontent.com/hasktorch/ffi-experimental/54192297742221c4d50398586ba8d187451f9ee0/ffi/src/ATen/Unmanaged/Type/Generator.hs | haskell | # LANGUAGE OverloadedStrings # |
# LANGUAGE DataKinds #
# LANGUAGE PolyKinds #
# LANGUAGE TemplateHaskell #
# LANGUAGE QuasiQuotes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
module ATen.Unmanaged.Type.Generator where
import qualified Language.C.Inline.Cpp as C
import qualified Language.C.Inline.Cpp.Exceptions as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import qualified Data.Map as Map
import Foreign.C.String
import Foreign.C.Types
import Foreign hiding (newForeignPtr)
import Foreign.Concurrent
import ATen.Type
import ATen.Class
C.context $ C.cppCtx <> mempty { C.ctxTypesTable = typeTable }
C.include "<ATen/ATen.h>"
C.include "<vector>"
deleteGenerator :: Ptr Generator -> IO ()
deleteGenerator object = [C.throwBlock| void { delete $(at::Generator* object);}|]
instance CppObject Generator where
fromPtr ptr = newForeignPtr ptr (deleteGenerator ptr)
|
ac2637a2a3e199aff32e041f4a7a0520f0b17600bf10eb6aac0483b8575c78d2 | haskell-gi/gi-gtk-examples | ProgressThreadedRTS.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
Example of concurrent and Gtk .
--
This demo uses GHC 's support for OS level threads . It has to be
-- linked using the ghc -threaded flag.
--
Because Gtk+ is single threaded we have to be very careful to call
-- Gtk+ only from the main GUI thread. So while it's ok to forkIO,
-- any GUI actions in that thread have to be 'posted' to the main GUI
thread as in the example here .
import Control.Applicative
import Prelude
import Control.Concurrent
import qualified GI.Gtk as GI (init)
import GI.Gtk
(progressBarPulse, ProgressBar, dialogRun, widgetShowAll,
boxPackStart, progressBarNew, dialogGetContentArea,
dialogAddButton, dialogNew)
import GI.Gtk.Enums (ResponseType(..))
import GI.GLib (pattern PRIORITY_DEFAULT, idleAdd)
main :: IO ()
main = do
GI.init Nothing
dia <- dialogNew
dialogAddButton dia "_Close" (fromIntegral $ fromEnum ResponseTypeClose)
contain <- dialogGetContentArea dia
pb <- progressBarNew
boxPackStart contain pb False False 0
widgetShowAll dia
forkIO (doTask pb)
dialogRun dia
return ()
doTask :: ProgressBar -> IO ()
doTask pb = do
idleAdd PRIORITY_DEFAULT $ progressBarPulse pb >> return False
threadDelay 100000
doTask pb
| null | https://raw.githubusercontent.com/haskell-gi/gi-gtk-examples/38c7c0c4bfa68efc04165d55ba53e1a2acc1dcef/concurrent/ProgressThreadedRTS.hs | haskell | # LANGUAGE OverloadedStrings #
linked using the ghc -threaded flag.
Gtk+ only from the main GUI thread. So while it's ok to forkIO,
any GUI actions in that thread have to be 'posted' to the main GUI | # LANGUAGE PatternSynonyms #
Example of concurrent and Gtk .
This demo uses GHC 's support for OS level threads . It has to be
Because Gtk+ is single threaded we have to be very careful to call
thread as in the example here .
import Control.Applicative
import Prelude
import Control.Concurrent
import qualified GI.Gtk as GI (init)
import GI.Gtk
(progressBarPulse, ProgressBar, dialogRun, widgetShowAll,
boxPackStart, progressBarNew, dialogGetContentArea,
dialogAddButton, dialogNew)
import GI.Gtk.Enums (ResponseType(..))
import GI.GLib (pattern PRIORITY_DEFAULT, idleAdd)
main :: IO ()
main = do
GI.init Nothing
dia <- dialogNew
dialogAddButton dia "_Close" (fromIntegral $ fromEnum ResponseTypeClose)
contain <- dialogGetContentArea dia
pb <- progressBarNew
boxPackStart contain pb False False 0
widgetShowAll dia
forkIO (doTask pb)
dialogRun dia
return ()
doTask :: ProgressBar -> IO ()
doTask pb = do
idleAdd PRIORITY_DEFAULT $ progressBarPulse pb >> return False
threadDelay 100000
doTask pb
|
c253f0da44411c7ccbeb05bfc27ed5a6188857c54c537aec52065e292e81a073 | trez/LazyNES | Helpers.hs | module Helpers
(
-- * Bit
bitBool
, boolBit
*
, (<+>)
, whenM
, unlessM
-- * Addresses.
, toAddr
, mkAddr
, (<#>)
-- * Type conversions.
, signed
, signed16
, unsigned
, unsigned8
) where
import Control.Monad (liftM2, when, unless)
import CPU.Types
| Set bit @n@ of bits according to @b@.
bitBool :: Bits a => Int -> Bool -> a -> a
bitBool n b = if b then (`setBit` n) else (`clearBit` n)
-- | Return a bits representation of bool.
boolBit :: (Num a, Bits a) => Bool -> a
boolBit True = 1
boolBit False = 0
| Monadic adding .
(<+>) :: (Num a, Monad m) => m a -> m a -> m a
(<+>) = liftM2 (+)
-- | Monadic when.
whenM :: Monad m => m Bool -> m () -> m ()
whenM bm m = do
b <- bm
when b m
-- | Monadic unless.
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM bm m = do
b <- bm
unless b m
-- | Transforms an operand into a Address.
toAddr :: Operand -> Address
toAddr = fromIntegral
| Build a 16 - bit address from low and high components .
mkAddr :: Operand -> Operand -> Address
mkAddr low high = toAddr high `shiftL` 8 + toAddr low
| Builds a 16 - bit address .
(<#>) :: Monad m => m Operand -> m Operand -> m Address
(<#>) = liftM2 mkAddr
| Transform a unsigned integer to a 8 bit signed integer .
signed :: Word8 -> Int8
signed = fromIntegral
| Transform a signed integer to a unsigned 8bit integer .
unsigned :: Int8 -> Word8
unsigned = fromIntegral
| Transform a unsigned integer to a 16 bit signed integer without sign promotion .
signed16 :: Word8 -> Int16
signed16 = fromIntegral . (fromIntegral :: Word8 -> Word16)
| Transform a 16bit signed integer to a unsigned 8bit integer .
unsigned8 :: Int16 -> Word8
unsigned8 = fromIntegral . (0x00FF .&.)
| null | https://raw.githubusercontent.com/trez/LazyNES/8f2572e6bb60d1c0ab2c94c584144220ff9e05d1/src/Helpers.hs | haskell | * Bit
* Addresses.
* Type conversions.
| Return a bits representation of bool.
| Monadic when.
| Monadic unless.
| Transforms an operand into a Address. | module Helpers
(
bitBool
, boolBit
*
, (<+>)
, whenM
, unlessM
, toAddr
, mkAddr
, (<#>)
, signed
, signed16
, unsigned
, unsigned8
) where
import Control.Monad (liftM2, when, unless)
import CPU.Types
| Set bit @n@ of bits according to @b@.
bitBool :: Bits a => Int -> Bool -> a -> a
bitBool n b = if b then (`setBit` n) else (`clearBit` n)
boolBit :: (Num a, Bits a) => Bool -> a
boolBit True = 1
boolBit False = 0
| Monadic adding .
(<+>) :: (Num a, Monad m) => m a -> m a -> m a
(<+>) = liftM2 (+)
whenM :: Monad m => m Bool -> m () -> m ()
whenM bm m = do
b <- bm
when b m
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM bm m = do
b <- bm
unless b m
toAddr :: Operand -> Address
toAddr = fromIntegral
| Build a 16 - bit address from low and high components .
mkAddr :: Operand -> Operand -> Address
mkAddr low high = toAddr high `shiftL` 8 + toAddr low
| Builds a 16 - bit address .
(<#>) :: Monad m => m Operand -> m Operand -> m Address
(<#>) = liftM2 mkAddr
| Transform a unsigned integer to a 8 bit signed integer .
signed :: Word8 -> Int8
signed = fromIntegral
| Transform a signed integer to a unsigned 8bit integer .
unsigned :: Int8 -> Word8
unsigned = fromIntegral
| Transform a unsigned integer to a 16 bit signed integer without sign promotion .
signed16 :: Word8 -> Int16
signed16 = fromIntegral . (fromIntegral :: Word8 -> Word16)
| Transform a 16bit signed integer to a unsigned 8bit integer .
unsigned8 :: Int16 -> Word8
unsigned8 = fromIntegral . (0x00FF .&.)
|
1440aa8ebc47891408b60e8a178ffdbc0c368391e2fb0f52a21d4b9ca9694841 | stamourv/racket-benchmark | types.rkt | #lang racket
(provide (struct-out benchmark-result) benchmark-logger)
;;;;;;;;;;;;;;;;;;;;;;;;; Benchmark Results ;;;;;;;;;;;;;;;;;;;;;;;;;
(struct benchmark-result
(name ;; any/c
( listof any / c )
( listof number ? )
)
#:prefab
)
(define benchmark-logger (make-logger 'benchmark (current-logger)))
| null | https://raw.githubusercontent.com/stamourv/racket-benchmark/de7e84539de23834508dba42e07859cf13bde20c/benchmark/types.rkt | racket | Benchmark Results ;;;;;;;;;;;;;;;;;;;;;;;;;
any/c | #lang racket
(provide (struct-out benchmark-result) benchmark-logger)
(struct benchmark-result
( listof any / c )
( listof number ? )
)
#:prefab
)
(define benchmark-logger (make-logger 'benchmark (current-logger)))
|
649180d68fc0d92669ca38a6c108fb190ddab8ba4d78148d4cc79d74577196c7 | tomahawkins/atom | ValidData.hs | -- |
-- Module: ValidData
-- Description: Capturing data that can either be valid or invalid
Copyright : ( c ) 2013 Lee Pike
--
-- Capturing data that can either be valid or invalid.
module Language.Atom.Common.ValidData
( ValidData
, validData
, getValidData
, whenValid
, whenInvalid
) where
import Language.Atom.Expressions
import Language.Atom.Language
-- | 'ValidData' captures the data and its validity condition.
-- 'ValidData' is abstract to prevent rules from using invalid data.
data ValidData a = ValidData a (E Bool)
-- | Create 'ValidData' given the data and validity condition.
validData :: a -> E Bool -> ValidData a
validData = ValidData
-- | Get a valid data. Action is disabled if data is invalid.
getValidData :: ValidData a -> Atom a
getValidData (ValidData a v) = cond v >> return a
-- | Action enabled if 'ValidData' is valid.
whenValid :: ValidData a -> Atom ()
whenValid (ValidData _ v) = cond v
-- | Action enabled if 'ValidData' is not valid.
whenInvalid :: ValidData a -> Atom ()
whenInvalid (ValidData _ v) = cond $ not_ v
| null | https://raw.githubusercontent.com/tomahawkins/atom/e552e18859c6d249af4b293e9d2197878c0fd4fd/Language/Atom/Common/ValidData.hs | haskell | |
Module: ValidData
Description: Capturing data that can either be valid or invalid
Capturing data that can either be valid or invalid.
| 'ValidData' captures the data and its validity condition.
'ValidData' is abstract to prevent rules from using invalid data.
| Create 'ValidData' given the data and validity condition.
| Get a valid data. Action is disabled if data is invalid.
| Action enabled if 'ValidData' is valid.
| Action enabled if 'ValidData' is not valid. | Copyright : ( c ) 2013 Lee Pike
module Language.Atom.Common.ValidData
( ValidData
, validData
, getValidData
, whenValid
, whenInvalid
) where
import Language.Atom.Expressions
import Language.Atom.Language
data ValidData a = ValidData a (E Bool)
validData :: a -> E Bool -> ValidData a
validData = ValidData
getValidData :: ValidData a -> Atom a
getValidData (ValidData a v) = cond v >> return a
whenValid :: ValidData a -> Atom ()
whenValid (ValidData _ v) = cond v
whenInvalid :: ValidData a -> Atom ()
whenInvalid (ValidData _ v) = cond $ not_ v
|
d222d75c78046d05c57fbfe8ef70d345a7508ae58881a1b56bdac7ddba92682c | OCamlPro/opam-bin | commandPull.ml | (**************************************************************************)
(* *)
Copyright 2020 OCamlPro & Origin Labs
(* *)
(* All rights reserved. This file is distributed under the terms of the *)
GNU Lesser General Public License version 2.1 , with the special
(* exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Ezcmd.TYPES
open EzConfig.OP
open Ez_file.V1
open EzFile.OP
let cmd_name = "pull"
let action () =
match !!Config.rsync_url with
| None ->
Printf.eprintf
"Error: you must define the remote url with `%s config --rsync-url`\n%!"
Globals.command ;
exit 2
| Some rsync_url ->
let args = [ "rsync"; "-auv" ; "--progress" ] in
let args = args @ [
rsync_url // ".";
Globals.opambin_store_dir // "." ;
] in
Printf.eprintf "Calling '%s'\n%!"
(String.concat " " args);
Misc.call ~nvo:None (Array.of_list args);
Printf.eprintf "Done.\n%!";
()
let cmd =
{
cmd_name ;
cmd_action = (fun () -> action () ) ;
cmd_args = [] ;
cmd_man = [];
cmd_doc = "pull binary packages from the remote server";
}
| null | https://raw.githubusercontent.com/OCamlPro/opam-bin/322e46827280af0fdf6a24ac65893b67d3b9f269/src/opam_bin_lib/commandPull.ml | ocaml | ************************************************************************
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************ | Copyright 2020 OCamlPro & Origin Labs
GNU Lesser General Public License version 2.1 , with the special
open Ezcmd.TYPES
open EzConfig.OP
open Ez_file.V1
open EzFile.OP
let cmd_name = "pull"
let action () =
match !!Config.rsync_url with
| None ->
Printf.eprintf
"Error: you must define the remote url with `%s config --rsync-url`\n%!"
Globals.command ;
exit 2
| Some rsync_url ->
let args = [ "rsync"; "-auv" ; "--progress" ] in
let args = args @ [
rsync_url // ".";
Globals.opambin_store_dir // "." ;
] in
Printf.eprintf "Calling '%s'\n%!"
(String.concat " " args);
Misc.call ~nvo:None (Array.of_list args);
Printf.eprintf "Done.\n%!";
()
let cmd =
{
cmd_name ;
cmd_action = (fun () -> action () ) ;
cmd_args = [] ;
cmd_man = [];
cmd_doc = "pull binary packages from the remote server";
}
|
b5fdd4e56e31819824d979b62d507c5186f1a1ede0af95c5ed27a458be008d6a | PrincetonUniversity/lucid | addDefaultBranches.ml | (* make sure every match statement
has an explicit default case. *)
open CoreSyntax
module CL = Caml.List
let is_default_pats pats =
let is_wild pat =
match pat with
| PWild -> true
| _ -> false
in
CL.map is_wild pats |> CL.fold_left ( & ) true
;;
let new_default_branch exps : branch = CL.map (fun _ -> PWild) exps, snoop
let add_default_branches ds =
let v =
object
inherit [_] s_map as super
method! visit_statement ctx statement =
let new_stmt = super#visit_statement ctx statement in
match new_stmt.s with
| SMatch (exps, branches) ->
(match is_default_pats (CL.rev branches |> CL.hd |> fst) with
| true -> new_stmt
| false ->
let branches = branches @ [new_default_branch exps] in
{ new_stmt with s = SMatch (exps, branches) })
| _ -> new_stmt
end
in
v#visit_decls () ds
;;
| null | https://raw.githubusercontent.com/PrincetonUniversity/lucid/d7f41caa00654bc01eb2e6c0307d93800cbc749b/src/lib/midend/transformations/addDefaultBranches.ml | ocaml | make sure every match statement
has an explicit default case. | open CoreSyntax
module CL = Caml.List
let is_default_pats pats =
let is_wild pat =
match pat with
| PWild -> true
| _ -> false
in
CL.map is_wild pats |> CL.fold_left ( & ) true
;;
let new_default_branch exps : branch = CL.map (fun _ -> PWild) exps, snoop
let add_default_branches ds =
let v =
object
inherit [_] s_map as super
method! visit_statement ctx statement =
let new_stmt = super#visit_statement ctx statement in
match new_stmt.s with
| SMatch (exps, branches) ->
(match is_default_pats (CL.rev branches |> CL.hd |> fst) with
| true -> new_stmt
| false ->
let branches = branches @ [new_default_branch exps] in
{ new_stmt with s = SMatch (exps, branches) })
| _ -> new_stmt
end
in
v#visit_decls () ds
;;
|
370b349c85c949084293fb4cb5c8cdbdd3040cac874a6bf457c8be743b623f8f | paulcadman/the-little-typer | chapter-15-Absurd.rkt | #lang pie
Exercises on Absurd from Chapter 15 of The Little Typer
(claim +
(-> Nat Nat
Nat))
(define +
(λ (a b)
(rec-Nat a
b
(λ (_ b+a-k)
(add1 b+a-k)))))
(claim double
(-> Nat
Nat))
(define double
(λ (n)
(rec-Nat n
0
(λ (_ n+n-2)
(+ 2 n+n-2)))))
(claim Even
(-> Nat
U))
(define Even
(λ (n)
(Σ ([half Nat])
(= Nat n (double half)))))
(claim Odd
(-> Nat
U))
(define Odd
(λ (n)
(Σ ([haf Nat])
(= Nat n (add1 (double haf))))))
(claim <=
(-> Nat Nat
U))
(define <=
(λ (a b)
(Σ ([k Nat])
(= Nat (+ k a) b))))
;; The following is not required for the statement of exercises
;; but will be required in some solutions.
(claim =consequence
(-> Nat Nat
U))
(define =consequence
(λ (n j)
(which-Nat n
(which-Nat j
Trivial
(λ (j-1)
Absurd))
(λ (n-1)
(which-Nat j
Absurd
(λ (j-1)
(= Nat n-1 j-1)))))))
(claim =consequence-same
(Π ([n Nat])
(=consequence n n)))
(define =consequence-same
(λ (n)
(ind-Nat n
(λ (k)
(=consequence k k))
sole
(λ (n-1 =consequence-n-1)
(same n-1)))))
(claim use-Nat=
(Π ([n Nat]
[j Nat])
(-> (= Nat n j)
(=consequence n j))))
(define use-Nat=
(λ (n j)
(λ (n=j)
(replace n=j
(λ (k)
(=consequence n k))
(=consequence-same n)))))
(claim zero-not-add1
(Π ([n Nat])
(-> (= Nat zero (add1 n))
Absurd)))
(define zero-not-add1
(λ (n)
(use-Nat= zero (add1 n))))
Exercise 15.1
;;
State and prove that 3 is not less than 1 .
(claim not-3<=1
(-> (<= 3 1)
Absurd))
Exercise 15.2
;;
State and prove that any natural number is not equal to its successor .
(claim n<>Sn
(Π ([n Nat])
(-> (= Nat n (add1 n))
Absurd)))
Exercise 15.3
;;
State and prove that for every Nat n , the successor of n is not less
;; than or equal to n.
(claim Sn-not<=-n
(Π ([n Nat])
(-> (<= (add1 n) n)
Absurd)))
Exercise 15.4
;;
State and prove that 1 is not Even .
(claim one-not-Even
(-> (Even 1)
Absurd))
| null | https://raw.githubusercontent.com/paulcadman/the-little-typer/0a5c6877a902f26fc7f100de593f44f6a986624c/exercises/chapter-15-Absurd.rkt | racket | The following is not required for the statement of exercises
but will be required in some solutions.
than or equal to n.
| #lang pie
Exercises on Absurd from Chapter 15 of The Little Typer
(claim +
(-> Nat Nat
Nat))
(define +
(λ (a b)
(rec-Nat a
b
(λ (_ b+a-k)
(add1 b+a-k)))))
(claim double
(-> Nat
Nat))
(define double
(λ (n)
(rec-Nat n
0
(λ (_ n+n-2)
(+ 2 n+n-2)))))
(claim Even
(-> Nat
U))
(define Even
(λ (n)
(Σ ([half Nat])
(= Nat n (double half)))))
(claim Odd
(-> Nat
U))
(define Odd
(λ (n)
(Σ ([haf Nat])
(= Nat n (add1 (double haf))))))
(claim <=
(-> Nat Nat
U))
(define <=
(λ (a b)
(Σ ([k Nat])
(= Nat (+ k a) b))))
(claim =consequence
(-> Nat Nat
U))
(define =consequence
(λ (n j)
(which-Nat n
(which-Nat j
Trivial
(λ (j-1)
Absurd))
(λ (n-1)
(which-Nat j
Absurd
(λ (j-1)
(= Nat n-1 j-1)))))))
(claim =consequence-same
(Π ([n Nat])
(=consequence n n)))
(define =consequence-same
(λ (n)
(ind-Nat n
(λ (k)
(=consequence k k))
sole
(λ (n-1 =consequence-n-1)
(same n-1)))))
(claim use-Nat=
(Π ([n Nat]
[j Nat])
(-> (= Nat n j)
(=consequence n j))))
(define use-Nat=
(λ (n j)
(λ (n=j)
(replace n=j
(λ (k)
(=consequence n k))
(=consequence-same n)))))
(claim zero-not-add1
(Π ([n Nat])
(-> (= Nat zero (add1 n))
Absurd)))
(define zero-not-add1
(λ (n)
(use-Nat= zero (add1 n))))
Exercise 15.1
State and prove that 3 is not less than 1 .
(claim not-3<=1
(-> (<= 3 1)
Absurd))
Exercise 15.2
State and prove that any natural number is not equal to its successor .
(claim n<>Sn
(Π ([n Nat])
(-> (= Nat n (add1 n))
Absurd)))
Exercise 15.3
State and prove that for every Nat n , the successor of n is not less
(claim Sn-not<=-n
(Π ([n Nat])
(-> (<= (add1 n) n)
Absurd)))
Exercise 15.4
State and prove that 1 is not Even .
(claim one-not-Even
(-> (Even 1)
Absurd))
|
8b65c7bf975a4794ad3f8953ac1c84f3b89074f3542f94217853ffef7b7db8c6 | anoma/juvix | Repl.hs | # LANGUAGE QuasiQuotes #
module Commands.Dev.Geb.Repl where
import Commands.Base hiding (command)
import Commands.Dev.Geb.Repl.Format
import Commands.Dev.Geb.Repl.Options
import Control.Exception (throwIO)
import Control.Monad.State.Strict qualified as State
import Data.String.Interpolate (i, __i)
import Juvix.Compiler.Backend.Geb qualified as Geb
import Juvix.Compiler.Backend.Geb.Analysis.TypeChecking.Error
import Juvix.Data.Error.GenericError qualified as Error
import Juvix.Extra.Version
import Juvix.Prelude.Pretty qualified as P
import System.Console.ANSI qualified as Ansi
import System.Console.Haskeline
import System.Console.Repline qualified as Repline
type ReplS = State.StateT ReplState IO
type Repl a = Repline.HaskelineT ReplS a
data ReplState = ReplState
{ _replContextEntryPoint :: Maybe EntryPoint,
_replStateInvokeDir :: Path Abs Dir,
_replStateGlobalOptions :: GlobalOptions
}
makeLenses ''ReplState
replPath :: Path Abs File
replPath = $(mkAbsFile "/repl.geb")
runCommand :: (Members '[Embed IO, App] r) => GebReplOptions -> Sem r ()
runCommand replOpts = do
root <- askPkgDir
buildDir <- askBuildDir
package <- askPackage
invokeDir <- askInvokeDir
globalOptions <- askGlobalOptions
let getReplEntryPoint :: SomeBase File -> Repl EntryPoint
getReplEntryPoint inputFile = do
gopts <- State.gets (^. replStateGlobalOptions)
absInputFile :: Path Abs File <- replMakeAbsolute inputFile
return $
EntryPoint
{ _entryPointRoot = root,
_entryPointBuildDir = buildDir,
_entryPointResolverRoot = root,
_entryPointNoTermination = gopts ^. globalNoTermination,
_entryPointNoPositivity = gopts ^. globalNoPositivity,
_entryPointNoStdlib = gopts ^. globalNoStdlib,
_entryPointPackage = package,
_entryPointModulePaths = pure absInputFile,
_entryPointGenericOptions = project gopts,
_entryPointStdin = Nothing
}
embed
( State.evalStateT
(replAction replOpts getReplEntryPoint)
( ReplState
{ _replContextEntryPoint = Nothing,
_replStateGlobalOptions = globalOptions,
_replStateInvokeDir = invokeDir
}
)
)
loadEntryPoint :: EntryPoint -> Repl ()
loadEntryPoint ep = do
State.modify
( set
replContextEntryPoint
(Just ep)
)
let epPath :: Path Abs File = ep ^. entryPointModulePaths . _head1
liftIO (putStrLn . pack $ "OK loaded " <> toFilePath epPath)
content <- liftIO (readFile (toFilePath epPath))
let evalRes =
Geb.runEval $
Geb.RunEvalArgs
{ _runEvalArgsContent = content,
_runEvalArgsInputFile = epPath,
_runEvalArgsEvaluatorOptions = Geb.defaultEvaluatorOptions
}
printEvalResult evalRes
reloadFile :: String -> Repl ()
reloadFile _ = do
mentryPoint <- State.gets ((^. replContextEntryPoint))
maybe noFileLoadedMsg loadEntryPoint mentryPoint
pSomeFile :: String -> SomeBase File
pSomeFile = someFile . unpack . strip . pack
type ReplEntryPoint = SomeBase File -> Repl EntryPoint
loadFile :: ReplEntryPoint -> SomeBase File -> Repl ()
loadFile getReplEntryPoint f = do
entryPoint <- getReplEntryPoint f
loadEntryPoint entryPoint
inferObject :: String -> Repl ()
inferObject gebMorphism = Repline.dontCrash $ do
case Geb.runParser replPath (pack gebMorphism) of
Left err -> printError (JuvixError err)
Right (Geb.ExpressionMorphism morphism) -> do
case Geb.inferObject' morphism of
Right obj -> renderOut (Geb.ppOut Geb.defaultEvaluatorOptions obj)
Left err -> printError (JuvixError err)
Right (Geb.ExpressionTypedMorphism _) ->
checkTypedMorphism gebMorphism
Right _ -> printError (error "Inference only works on Geb morphisms.")
checkTypedMorphism :: String -> Repl ()
checkTypedMorphism gebMorphism = Repline.dontCrash $ do
case Geb.runParser replPath (pack gebMorphism) of
Left err -> printError (JuvixError err)
Right (Geb.ExpressionTypedMorphism tyMorphism) -> do
case run . runError @CheckingError $ Geb.check' tyMorphism of
Right obj -> renderOut (Geb.ppOut Geb.defaultEvaluatorOptions obj)
Left err -> printError (JuvixError err)
Right _ -> printError (error "Checking only works on typed Geb morphisms.")
runReplCommand :: String -> Repl ()
runReplCommand input =
Repline.dontCrash $
do
let evalRes =
Geb.runEval $
Geb.RunEvalArgs
{ _runEvalArgsContent = pack input,
_runEvalArgsInputFile = replPath,
_runEvalArgsEvaluatorOptions = Geb.defaultEvaluatorOptions
}
printEvalResult evalRes
evalAndOutputMorphism :: String -> Repl ()
evalAndOutputMorphism input =
Repline.dontCrash $ do
let evalRes =
Geb.runEval $
Geb.RunEvalArgs
{ _runEvalArgsContent = pack input,
_runEvalArgsInputFile = replPath,
_runEvalArgsEvaluatorOptions =
Geb.defaultEvaluatorOptions
{ Geb._evaluatorOptionsOutputMorphism = True
}
}
printEvalResult evalRes
options :: ReplEntryPoint -> [(String, String -> Repl ())]
options replEntryPoint =
[ ("help", Repline.dontCrash . helpText),
-- `multiline` is included here for auto-completion purposes only.
-- `repline`'s `multilineCommand` logic overrides this no-op.
(multilineCmd, Repline.dontCrash . \_ -> return ()),
("check", checkTypedMorphism),
("load", Repline.dontCrash . loadFile replEntryPoint . pSomeFile),
("morphism", evalAndOutputMorphism),
("quit", quit),
("reload", Repline.dontCrash . reloadFile),
("root", printRoot),
("type", inferObject),
("version", displayVersion)
]
optsCompleter :: ReplEntryPoint -> Repline.WordCompleter ReplS
optsCompleter replEntryPoint n = do
let names = (":" <>) . fst <$> options replEntryPoint
return (filter (isPrefixOf n) names)
prefix :: Maybe Char
prefix = Just ':'
multilineCommand :: Maybe String
multilineCommand = Just multilineCmd
tabComplete :: ReplEntryPoint -> Repline.CompleterStyle ReplS
tabComplete replEntryPoint =
Repline.Prefix
(Repline.wordCompleter (optsCompleter replEntryPoint))
defaultMatcher
replAction :: GebReplOptions -> ReplEntryPoint -> ReplS ()
replAction replOpts replEntryPoint =
Repline.evalReplOpts
Repline.ReplOpts
{ prefix,
multilineCommand,
initialiser = initSession replOpts,
finaliser = endSession,
command = runReplCommand,
options = options replEntryPoint,
tabComplete = tabComplete replEntryPoint,
banner
}
defaultMatcher :: [(String, CompletionFunc ReplS)]
defaultMatcher = [(":load", Repline.fileCompleter)]
banner :: Repline.MultiLine -> Repl String
banner = \case
Repline.MultiLine -> return "... "
Repline.SingleLine -> replPromptText
noFileLoadedMsg :: Repl ()
noFileLoadedMsg =
renderOut
. ReplMessageDoc
$ P.annotate
ReplError
"No file loaded. Load a file using the `:load FILE` command."
<> P.line
initSession :: GebReplOptions -> Repl ()
initSession replOpts
| replOpts ^. gebReplOptionsSilent = return ()
| otherwise = renderOut welcomeMsg
welcomeMsg :: ReplMessageDoc
welcomeMsg =
ReplMessageDoc $
P.annotate ReplIntro "Welcome to the Juvix Geb REPL!"
<> P.line
<> normal [i|Juvix v#{versionTag}: .|]
<> P.line
<> normal "Type :help for help."
<> P.line
replPromptText :: Repl String
replPromptText = do
r <- replText . ReplMessageDoc $ P.annotate ReplPrompt "geb> "
return (unpack r)
helpText :: String -> Repl ()
helpText _ =
renderOutNormal
[__i|
EXPRESSION Evaluate a Geb morphism
:help Print this help
:load FILE Load a file into the REPL
:reload Reload the currently loaded file
:check EXPRESSION Check the type of a Geb morphism
:type EXPRESSION Infer the type of a Geb morphism
:morphism EXPRESSION Read back after evaluate a Geb morphism
:version Display the Juvix version
:multiline Enter multiline mode
:root Print the root directory of the REPL
:version Display the Juvix version
:quit Exit the REPL
|]
multilineCmd :: String
multilineCmd = "multiline"
quit :: String -> Repl ()
quit _ = liftIO (throwIO Interrupt)
endSession :: Repl Repline.ExitDecision
endSession = return Repline.Exit
printRoot :: String -> Repl ()
printRoot _ = do
r <- State.gets (^. replStateInvokeDir)
renderOutNormal $ pack (toFilePath r)
displayVersion :: String -> Repl ()
displayVersion _ = renderOutNormal versionTag
replMakeAbsolute :: SomeBase b -> Repl (Path Abs b)
replMakeAbsolute = \case
Abs p -> return p
Rel r -> do
invokeDir <- State.gets (^. replStateInvokeDir)
return (invokeDir <//> r)
replText :: (P.HasAnsiBackend a, P.HasTextBackend a) => a -> Repl Text
replText t = do
opts <- State.gets (^. replStateGlobalOptions)
hasAnsi <- liftIO (Ansi.hSupportsANSIColor stdout)
return $ P.toAnsiText (not (opts ^. globalNoColors) && hasAnsi) t
render' :: (P.HasAnsiBackend a, P.HasTextBackend a) => a -> Repl ()
render' t = do
opts <- State.gets (^. replStateGlobalOptions)
hasAnsi <- liftIO (Ansi.hSupportsANSIColor stdout)
liftIO (P.renderIO (not (opts ^. globalNoColors) && hasAnsi) t)
renderOut :: (P.HasAnsiBackend a, P.HasTextBackend a) => a -> Repl ()
renderOut t = render' t >> liftIO (putStrLn "")
renderOutNormal :: Text -> Repl ()
renderOutNormal = renderOut . ReplMessageDoc . normal
printError :: JuvixError -> Repl ()
printError e = do
opts <- State.gets (^. replStateGlobalOptions)
hasAnsi <- liftIO (Ansi.hSupportsANSIColor stderr)
let useAnsi = (not (opts ^. globalNoColors) && hasAnsi)
errorText <-
replText . ReplMessageDoc
$ P.annotate
ReplError
$ pretty
( run
. runReader (project' @GenericOptions opts)
$ Error.render useAnsi False e
)
liftIO $ hPutStrLn stderr errorText
printEvalResult :: Either JuvixError Geb.RunEvalResult -> Repl ()
printEvalResult = \case
Left err -> printError err
Right (Geb.RunEvalResultGebValue v) ->
renderOut (Geb.ppOut Geb.defaultEvaluatorOptions v)
Right (Geb.RunEvalResultMorphism morphism) ->
renderOut (Geb.ppOut Geb.defaultEvaluatorOptions morphism)
| null | https://raw.githubusercontent.com/anoma/juvix/0ef464668da2211e52725a73f36f342c52e37489/app/Commands/Dev/Geb/Repl.hs | haskell | `multiline` is included here for auto-completion purposes only.
`repline`'s `multilineCommand` logic overrides this no-op. | # LANGUAGE QuasiQuotes #
module Commands.Dev.Geb.Repl where
import Commands.Base hiding (command)
import Commands.Dev.Geb.Repl.Format
import Commands.Dev.Geb.Repl.Options
import Control.Exception (throwIO)
import Control.Monad.State.Strict qualified as State
import Data.String.Interpolate (i, __i)
import Juvix.Compiler.Backend.Geb qualified as Geb
import Juvix.Compiler.Backend.Geb.Analysis.TypeChecking.Error
import Juvix.Data.Error.GenericError qualified as Error
import Juvix.Extra.Version
import Juvix.Prelude.Pretty qualified as P
import System.Console.ANSI qualified as Ansi
import System.Console.Haskeline
import System.Console.Repline qualified as Repline
type ReplS = State.StateT ReplState IO
type Repl a = Repline.HaskelineT ReplS a
data ReplState = ReplState
{ _replContextEntryPoint :: Maybe EntryPoint,
_replStateInvokeDir :: Path Abs Dir,
_replStateGlobalOptions :: GlobalOptions
}
makeLenses ''ReplState
replPath :: Path Abs File
replPath = $(mkAbsFile "/repl.geb")
runCommand :: (Members '[Embed IO, App] r) => GebReplOptions -> Sem r ()
runCommand replOpts = do
root <- askPkgDir
buildDir <- askBuildDir
package <- askPackage
invokeDir <- askInvokeDir
globalOptions <- askGlobalOptions
let getReplEntryPoint :: SomeBase File -> Repl EntryPoint
getReplEntryPoint inputFile = do
gopts <- State.gets (^. replStateGlobalOptions)
absInputFile :: Path Abs File <- replMakeAbsolute inputFile
return $
EntryPoint
{ _entryPointRoot = root,
_entryPointBuildDir = buildDir,
_entryPointResolverRoot = root,
_entryPointNoTermination = gopts ^. globalNoTermination,
_entryPointNoPositivity = gopts ^. globalNoPositivity,
_entryPointNoStdlib = gopts ^. globalNoStdlib,
_entryPointPackage = package,
_entryPointModulePaths = pure absInputFile,
_entryPointGenericOptions = project gopts,
_entryPointStdin = Nothing
}
embed
( State.evalStateT
(replAction replOpts getReplEntryPoint)
( ReplState
{ _replContextEntryPoint = Nothing,
_replStateGlobalOptions = globalOptions,
_replStateInvokeDir = invokeDir
}
)
)
loadEntryPoint :: EntryPoint -> Repl ()
loadEntryPoint ep = do
State.modify
( set
replContextEntryPoint
(Just ep)
)
let epPath :: Path Abs File = ep ^. entryPointModulePaths . _head1
liftIO (putStrLn . pack $ "OK loaded " <> toFilePath epPath)
content <- liftIO (readFile (toFilePath epPath))
let evalRes =
Geb.runEval $
Geb.RunEvalArgs
{ _runEvalArgsContent = content,
_runEvalArgsInputFile = epPath,
_runEvalArgsEvaluatorOptions = Geb.defaultEvaluatorOptions
}
printEvalResult evalRes
reloadFile :: String -> Repl ()
reloadFile _ = do
mentryPoint <- State.gets ((^. replContextEntryPoint))
maybe noFileLoadedMsg loadEntryPoint mentryPoint
pSomeFile :: String -> SomeBase File
pSomeFile = someFile . unpack . strip . pack
type ReplEntryPoint = SomeBase File -> Repl EntryPoint
loadFile :: ReplEntryPoint -> SomeBase File -> Repl ()
loadFile getReplEntryPoint f = do
entryPoint <- getReplEntryPoint f
loadEntryPoint entryPoint
inferObject :: String -> Repl ()
inferObject gebMorphism = Repline.dontCrash $ do
case Geb.runParser replPath (pack gebMorphism) of
Left err -> printError (JuvixError err)
Right (Geb.ExpressionMorphism morphism) -> do
case Geb.inferObject' morphism of
Right obj -> renderOut (Geb.ppOut Geb.defaultEvaluatorOptions obj)
Left err -> printError (JuvixError err)
Right (Geb.ExpressionTypedMorphism _) ->
checkTypedMorphism gebMorphism
Right _ -> printError (error "Inference only works on Geb morphisms.")
checkTypedMorphism :: String -> Repl ()
checkTypedMorphism gebMorphism = Repline.dontCrash $ do
case Geb.runParser replPath (pack gebMorphism) of
Left err -> printError (JuvixError err)
Right (Geb.ExpressionTypedMorphism tyMorphism) -> do
case run . runError @CheckingError $ Geb.check' tyMorphism of
Right obj -> renderOut (Geb.ppOut Geb.defaultEvaluatorOptions obj)
Left err -> printError (JuvixError err)
Right _ -> printError (error "Checking only works on typed Geb morphisms.")
runReplCommand :: String -> Repl ()
runReplCommand input =
Repline.dontCrash $
do
let evalRes =
Geb.runEval $
Geb.RunEvalArgs
{ _runEvalArgsContent = pack input,
_runEvalArgsInputFile = replPath,
_runEvalArgsEvaluatorOptions = Geb.defaultEvaluatorOptions
}
printEvalResult evalRes
evalAndOutputMorphism :: String -> Repl ()
evalAndOutputMorphism input =
Repline.dontCrash $ do
let evalRes =
Geb.runEval $
Geb.RunEvalArgs
{ _runEvalArgsContent = pack input,
_runEvalArgsInputFile = replPath,
_runEvalArgsEvaluatorOptions =
Geb.defaultEvaluatorOptions
{ Geb._evaluatorOptionsOutputMorphism = True
}
}
printEvalResult evalRes
options :: ReplEntryPoint -> [(String, String -> Repl ())]
options replEntryPoint =
[ ("help", Repline.dontCrash . helpText),
(multilineCmd, Repline.dontCrash . \_ -> return ()),
("check", checkTypedMorphism),
("load", Repline.dontCrash . loadFile replEntryPoint . pSomeFile),
("morphism", evalAndOutputMorphism),
("quit", quit),
("reload", Repline.dontCrash . reloadFile),
("root", printRoot),
("type", inferObject),
("version", displayVersion)
]
optsCompleter :: ReplEntryPoint -> Repline.WordCompleter ReplS
optsCompleter replEntryPoint n = do
let names = (":" <>) . fst <$> options replEntryPoint
return (filter (isPrefixOf n) names)
prefix :: Maybe Char
prefix = Just ':'
multilineCommand :: Maybe String
multilineCommand = Just multilineCmd
tabComplete :: ReplEntryPoint -> Repline.CompleterStyle ReplS
tabComplete replEntryPoint =
Repline.Prefix
(Repline.wordCompleter (optsCompleter replEntryPoint))
defaultMatcher
replAction :: GebReplOptions -> ReplEntryPoint -> ReplS ()
replAction replOpts replEntryPoint =
Repline.evalReplOpts
Repline.ReplOpts
{ prefix,
multilineCommand,
initialiser = initSession replOpts,
finaliser = endSession,
command = runReplCommand,
options = options replEntryPoint,
tabComplete = tabComplete replEntryPoint,
banner
}
defaultMatcher :: [(String, CompletionFunc ReplS)]
defaultMatcher = [(":load", Repline.fileCompleter)]
banner :: Repline.MultiLine -> Repl String
banner = \case
Repline.MultiLine -> return "... "
Repline.SingleLine -> replPromptText
noFileLoadedMsg :: Repl ()
noFileLoadedMsg =
renderOut
. ReplMessageDoc
$ P.annotate
ReplError
"No file loaded. Load a file using the `:load FILE` command."
<> P.line
initSession :: GebReplOptions -> Repl ()
initSession replOpts
| replOpts ^. gebReplOptionsSilent = return ()
| otherwise = renderOut welcomeMsg
welcomeMsg :: ReplMessageDoc
welcomeMsg =
ReplMessageDoc $
P.annotate ReplIntro "Welcome to the Juvix Geb REPL!"
<> P.line
<> normal [i|Juvix v#{versionTag}: .|]
<> P.line
<> normal "Type :help for help."
<> P.line
replPromptText :: Repl String
replPromptText = do
r <- replText . ReplMessageDoc $ P.annotate ReplPrompt "geb> "
return (unpack r)
helpText :: String -> Repl ()
helpText _ =
renderOutNormal
[__i|
EXPRESSION Evaluate a Geb morphism
:help Print this help
:load FILE Load a file into the REPL
:reload Reload the currently loaded file
:check EXPRESSION Check the type of a Geb morphism
:type EXPRESSION Infer the type of a Geb morphism
:morphism EXPRESSION Read back after evaluate a Geb morphism
:version Display the Juvix version
:multiline Enter multiline mode
:root Print the root directory of the REPL
:version Display the Juvix version
:quit Exit the REPL
|]
multilineCmd :: String
multilineCmd = "multiline"
quit :: String -> Repl ()
quit _ = liftIO (throwIO Interrupt)
endSession :: Repl Repline.ExitDecision
endSession = return Repline.Exit
printRoot :: String -> Repl ()
printRoot _ = do
r <- State.gets (^. replStateInvokeDir)
renderOutNormal $ pack (toFilePath r)
displayVersion :: String -> Repl ()
displayVersion _ = renderOutNormal versionTag
replMakeAbsolute :: SomeBase b -> Repl (Path Abs b)
replMakeAbsolute = \case
Abs p -> return p
Rel r -> do
invokeDir <- State.gets (^. replStateInvokeDir)
return (invokeDir <//> r)
replText :: (P.HasAnsiBackend a, P.HasTextBackend a) => a -> Repl Text
replText t = do
opts <- State.gets (^. replStateGlobalOptions)
hasAnsi <- liftIO (Ansi.hSupportsANSIColor stdout)
return $ P.toAnsiText (not (opts ^. globalNoColors) && hasAnsi) t
render' :: (P.HasAnsiBackend a, P.HasTextBackend a) => a -> Repl ()
render' t = do
opts <- State.gets (^. replStateGlobalOptions)
hasAnsi <- liftIO (Ansi.hSupportsANSIColor stdout)
liftIO (P.renderIO (not (opts ^. globalNoColors) && hasAnsi) t)
renderOut :: (P.HasAnsiBackend a, P.HasTextBackend a) => a -> Repl ()
renderOut t = render' t >> liftIO (putStrLn "")
renderOutNormal :: Text -> Repl ()
renderOutNormal = renderOut . ReplMessageDoc . normal
printError :: JuvixError -> Repl ()
printError e = do
opts <- State.gets (^. replStateGlobalOptions)
hasAnsi <- liftIO (Ansi.hSupportsANSIColor stderr)
let useAnsi = (not (opts ^. globalNoColors) && hasAnsi)
errorText <-
replText . ReplMessageDoc
$ P.annotate
ReplError
$ pretty
( run
. runReader (project' @GenericOptions opts)
$ Error.render useAnsi False e
)
liftIO $ hPutStrLn stderr errorText
printEvalResult :: Either JuvixError Geb.RunEvalResult -> Repl ()
printEvalResult = \case
Left err -> printError err
Right (Geb.RunEvalResultGebValue v) ->
renderOut (Geb.ppOut Geb.defaultEvaluatorOptions v)
Right (Geb.RunEvalResultMorphism morphism) ->
renderOut (Geb.ppOut Geb.defaultEvaluatorOptions morphism)
|
d830d567bbae6afab575bbdd313cfc88b5a48d44c2d3dc9f10cc08c09957c464 | 5HT/ant | Glyph.mli |
open XNum;
open Runtime;
open Substitute;
open FontMetric;
open Box;
value attach_accent : font_metric -> glyph_desc -> font_metric -> glyph_desc -> box;
value vertical_extendable : num -> font_metric ->
glyph_desc -> glyph_desc -> glyph_desc -> glyph_desc -> box;
value horizontal_extendable : num -> font_metric ->
glyph_desc -> glyph_desc -> glyph_desc -> glyph_desc -> box;
| null | https://raw.githubusercontent.com/5HT/ant/6acf51f4c4ebcc06c52c595776e0293cfa2f1da4/Typesetting/Glyph.mli | ocaml |
open XNum;
open Runtime;
open Substitute;
open FontMetric;
open Box;
value attach_accent : font_metric -> glyph_desc -> font_metric -> glyph_desc -> box;
value vertical_extendable : num -> font_metric ->
glyph_desc -> glyph_desc -> glyph_desc -> glyph_desc -> box;
value horizontal_extendable : num -> font_metric ->
glyph_desc -> glyph_desc -> glyph_desc -> glyph_desc -> box;
| |
1ce650531f905ac4fbba463508909428a6a4fff0997c4ccb89fd1abea1f31c2b | input-output-hk/marlowe-cardano | ChainSync.hs | {-# LANGUAGE Arrows #-}
# LANGUAGE DataKinds #
# LANGUAGE DuplicateRecordFields #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StrictData #-}
module Language.Marlowe.Runtime.ChainSync
( ChainSyncDependencies(..)
, chainSync
) where
import Cardano.Api (CardanoEra, CardanoMode, Tx, TxValidationErrorInMode)
import qualified Cardano.Api as Cardano
import Cardano.Api.Shelley (AcquiringFailure)
import Control.Concurrent.Component
import Language.Marlowe.Runtime.ChainSync.Api (ChainSyncCommand, ChainSyncQuery, RuntimeChainSeekServer)
import Language.Marlowe.Runtime.ChainSync.Database (DatabaseQueries(..))
import Language.Marlowe.Runtime.ChainSync.JobServer (ChainSyncJobServerDependencies(..), chainSyncJobServer)
import Language.Marlowe.Runtime.ChainSync.QueryServer (ChainSyncQueryServerDependencies(..), chainSyncQueryServer)
import Language.Marlowe.Runtime.ChainSync.Server (ChainSyncServerDependencies(..), chainSyncServer)
import Network.Protocol.Connection (SomeConnectionSource)
import Network.Protocol.Job.Server (JobServer)
import Network.Protocol.Query.Server (QueryServer)
import Ouroboros.Network.Protocol.LocalTxSubmission.Client (SubmitResult)
data ChainSyncDependencies r = ChainSyncDependencies
{ databaseQueries :: DatabaseQueries IO
, syncSource :: SomeConnectionSource RuntimeChainSeekServer IO
, querySource :: SomeConnectionSource (QueryServer ChainSyncQuery) IO
, jobSource :: SomeConnectionSource (JobServer ChainSyncCommand) IO
, queryLocalNodeState
:: forall result
. Maybe Cardano.ChainPoint
-> Cardano.QueryInMode CardanoMode result
-> IO (Either AcquiringFailure result)
, submitTxToNodeLocal
:: forall era
. CardanoEra era
-> Tx era
-> IO (SubmitResult (TxValidationErrorInMode CardanoMode))
}
chainSync :: Component IO (ChainSyncDependencies r) ()
chainSync = proc ChainSyncDependencies{..} -> do
let DatabaseQueries{..} = databaseQueries
chainSyncServer -< ChainSyncServerDependencies{..}
chainSyncQueryServer -< ChainSyncQueryServerDependencies{..}
chainSyncJobServer -< ChainSyncJobServerDependencies{..}
| null | https://raw.githubusercontent.com/input-output-hk/marlowe-cardano/bc9a0325f13b886e90ea05196ffb70a46c2ab095/marlowe-chain-sync/libchainsync/Language/Marlowe/Runtime/ChainSync.hs | haskell | # LANGUAGE Arrows #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE StrictData # | # LANGUAGE DataKinds #
# LANGUAGE DuplicateRecordFields #
module Language.Marlowe.Runtime.ChainSync
( ChainSyncDependencies(..)
, chainSync
) where
import Cardano.Api (CardanoEra, CardanoMode, Tx, TxValidationErrorInMode)
import qualified Cardano.Api as Cardano
import Cardano.Api.Shelley (AcquiringFailure)
import Control.Concurrent.Component
import Language.Marlowe.Runtime.ChainSync.Api (ChainSyncCommand, ChainSyncQuery, RuntimeChainSeekServer)
import Language.Marlowe.Runtime.ChainSync.Database (DatabaseQueries(..))
import Language.Marlowe.Runtime.ChainSync.JobServer (ChainSyncJobServerDependencies(..), chainSyncJobServer)
import Language.Marlowe.Runtime.ChainSync.QueryServer (ChainSyncQueryServerDependencies(..), chainSyncQueryServer)
import Language.Marlowe.Runtime.ChainSync.Server (ChainSyncServerDependencies(..), chainSyncServer)
import Network.Protocol.Connection (SomeConnectionSource)
import Network.Protocol.Job.Server (JobServer)
import Network.Protocol.Query.Server (QueryServer)
import Ouroboros.Network.Protocol.LocalTxSubmission.Client (SubmitResult)
data ChainSyncDependencies r = ChainSyncDependencies
{ databaseQueries :: DatabaseQueries IO
, syncSource :: SomeConnectionSource RuntimeChainSeekServer IO
, querySource :: SomeConnectionSource (QueryServer ChainSyncQuery) IO
, jobSource :: SomeConnectionSource (JobServer ChainSyncCommand) IO
, queryLocalNodeState
:: forall result
. Maybe Cardano.ChainPoint
-> Cardano.QueryInMode CardanoMode result
-> IO (Either AcquiringFailure result)
, submitTxToNodeLocal
:: forall era
. CardanoEra era
-> Tx era
-> IO (SubmitResult (TxValidationErrorInMode CardanoMode))
}
chainSync :: Component IO (ChainSyncDependencies r) ()
chainSync = proc ChainSyncDependencies{..} -> do
let DatabaseQueries{..} = databaseQueries
chainSyncServer -< ChainSyncServerDependencies{..}
chainSyncQueryServer -< ChainSyncQueryServerDependencies{..}
chainSyncJobServer -< ChainSyncJobServerDependencies{..}
|
f825acc9003a587e20a5e537fe12ec8f7cd69327929aad45c3678436a7936780 | ejgallego/coq-lsp | init.ml | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * INRIA , CNRS and contributors - Copyright 1999 - 2018
(* <O___,, * (see CREDITS file for the list of authors) *)
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(************************************************************************)
(* Coq Language Server Protocol / SerAPI *)
Copyright 2016 - 2019 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 +
Written by :
(************************************************************************)
(**************************************************************************)
Low - level , internal Coq initialization
(**************************************************************************)
type coq_opts =
{ fb_handler : Feedback.feedback -> unit
(** callback to handle async feedback *)
* callback to load cma / cmo files
; load_plugin : Mltop.PluginSpec.t -> unit
* callback to load findlib packages
; debug : bool (** Enable Coq Debug mode *)
}
let coq_init opts =
Core Coq initialization
Lib.init ();
Global.set_impredicative_set false;
Global.set_native_compiler false;
if opts.debug then CDebug.set_flags "backtrace";
(**************************************************************************)
(* Feedback setup *)
(**************************************************************************)
Initialize logging .
ignore (Feedback.add_feeder opts.fb_handler);
(* SerAPI plugins *)
let load_plugin = opts.load_plugin in
let load_module = opts.load_module in
(* Custom toplevel is used for bytecode-to-js dynlink *)
let ser_mltop : Mltop.toplevel =
let open Mltop in
{ load_plugin
; load_module
; add_dir = (fun _ -> ())
; ml_loop = (fun _ -> ())
}
in
Mltop.set_top ser_mltop;
This should go away in Coq itself
Safe_typing.allow_delayed_constants := true;
(**************************************************************************)
(* Add root state!! *)
(**************************************************************************)
Vernacstate.freeze_interp_state ~marshallable:false |> State.of_coq
(* End of core initialization *)
(**************************************************************************)
Per - document , internal Coq initialization
(**************************************************************************)
the context for a document
let doc_init ~root_state ~workspace ~uri () =
(* Lsp.Io.log_error "init" "starting"; *)
Vernacstate.unfreeze_interp_state (State.to_coq root_state);
Set load paths from workspace info . * Important * , this has to happen before
we declare the library below as [ Declaremods / Library ] will infer the module
name by looking at the load path !
we declare the library below as [Declaremods/Library] will infer the module
name by looking at the load path! *)
Workspace.apply ~uri workspace;
(* We return the state at this point! *)
Vernacstate.freeze_interp_state ~marshallable:false |> State.of_coq
let doc_init ~root_state ~workspace ~uri =
Protect.eval ~f:(doc_init ~root_state ~workspace ~uri) ()
| null | https://raw.githubusercontent.com/ejgallego/coq-lsp/70a3d4d41192671ca710775c98adfba4cfd5fae7/coq/init.ml | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
<O___,, * (see CREDITS file for the list of authors)
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
**********************************************************************
Coq Language Server Protocol / SerAPI
**********************************************************************
************************************************************************
************************************************************************
* callback to handle async feedback
* Enable Coq Debug mode
************************************************************************
Feedback setup
************************************************************************
SerAPI plugins
Custom toplevel is used for bytecode-to-js dynlink
************************************************************************
Add root state!!
************************************************************************
End of core initialization
************************************************************************
************************************************************************
Lsp.Io.log_error "init" "starting";
We return the state at this point! | v * INRIA , CNRS and contributors - Copyright 1999 - 2018
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
Copyright 2016 - 2019 MINES ParisTech -- Dual License LGPL 2.1 / GPL3 +
Written by :
Low - level , internal Coq initialization
type coq_opts =
{ fb_handler : Feedback.feedback -> unit
* callback to load cma / cmo files
; load_plugin : Mltop.PluginSpec.t -> unit
* callback to load findlib packages
}
let coq_init opts =
Core Coq initialization
Lib.init ();
Global.set_impredicative_set false;
Global.set_native_compiler false;
if opts.debug then CDebug.set_flags "backtrace";
Initialize logging .
ignore (Feedback.add_feeder opts.fb_handler);
let load_plugin = opts.load_plugin in
let load_module = opts.load_module in
let ser_mltop : Mltop.toplevel =
let open Mltop in
{ load_plugin
; load_module
; add_dir = (fun _ -> ())
; ml_loop = (fun _ -> ())
}
in
Mltop.set_top ser_mltop;
This should go away in Coq itself
Safe_typing.allow_delayed_constants := true;
Vernacstate.freeze_interp_state ~marshallable:false |> State.of_coq
Per - document , internal Coq initialization
the context for a document
let doc_init ~root_state ~workspace ~uri () =
Vernacstate.unfreeze_interp_state (State.to_coq root_state);
Set load paths from workspace info . * Important * , this has to happen before
we declare the library below as [ Declaremods / Library ] will infer the module
name by looking at the load path !
we declare the library below as [Declaremods/Library] will infer the module
name by looking at the load path! *)
Workspace.apply ~uri workspace;
Vernacstate.freeze_interp_state ~marshallable:false |> State.of_coq
let doc_init ~root_state ~workspace ~uri =
Protect.eval ~f:(doc_init ~root_state ~workspace ~uri) ()
|
9f8a8d10c1d36f6b2dd8abfd9abed7aca83e8cc6ecaad005a0cedef967ac2e88 | faylang/fay | emptyMain.hs | module EmptyMain where
main :: Fay ()
main = return ()
| null | https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/tests/emptyMain.hs | haskell | module EmptyMain where
main :: Fay ()
main = return ()
| |
e74350ff6da882c092e3b794360b6e9530294b4e8d53ececc2b1a1df63d4e174 | ChicagoBoss/ChicagoBoss | boss_controller_compiler_test.erl | %%-------------------------------------------------------------------
@author
ChicagoBoss Team and contributors , see file in root directory
%% @end
This file is part of ChicagoBoss project .
See file in root directory
%% for license information, see LICENSE file in root directory
%% @end
%% @doc
%%-------------------------------------------------------------------
-module(boss_controller_compiler_test).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("../src/boss/boss_web.hrl").
-define(TMODULE, boss_controller_compiler).
-compile(export_all).
spec_test_() ->
begin
Tests = [
fun prop_add_routes_to_forms/0,
{add_export_to_forms, 1},
{extract_routes_from_clauses, 2},
{function_for_routes, 1},
{route_from_token_ast, 1}
{ map_syntax_tuples , 1 } ,
% {map_tokens, 1}
],
[case Test of
{Funct, Arity} ->
?_assert(proper:check_spec({?TMODULE, Funct, Arity},
[{to_file, user}, 25]));
F when is_function(F,0) ->
?_assert(proper:quickcheck(F(),
[{to_file, user}]))
end||Test <-Tests]
end.
%-type route_form() :: boss_controller_compiler:route_form().
prop_add_routes_to_forms() ->
?FORALL(ExportAttrs ,
list(boss_controller_compiler:export_attr1()),
?IMPLIES(len_in_range(ExportAttrs,1,20),
begin
Result = boss_controller_compiler:add_routes_to_forms(ExportAttrs
++ [{eof, 1}]),
is_list(Result)
end)).
prop_add_routes_to_forms_function() ->
?FORALL(FctTups,
list(route_form()),
?IMPLIES(len_in_range(FctTups, 1,5),
?TIMEOUT(300,
begin
Result = boss_controller_compiler:add_routes_to_forms(FctTups,[],[]),
is_list(Result)
end))).
len_in_range(List, Min, Max) ->
Len = length(List),
Len =< Max andalso Len >= Min.
| null | https://raw.githubusercontent.com/ChicagoBoss/ChicagoBoss/113bac70c2f835c1e99c757170fd38abf09f5da2/test/boss_controller_compiler_test.erl | erlang | -------------------------------------------------------------------
@end
for license information, see LICENSE file in root directory
@end
@doc
-------------------------------------------------------------------
{map_tokens, 1}
-type route_form() :: boss_controller_compiler:route_form(). | @author
ChicagoBoss Team and contributors , see file in root directory
This file is part of ChicagoBoss project .
See file in root directory
-module(boss_controller_compiler_test).
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("../src/boss/boss_web.hrl").
-define(TMODULE, boss_controller_compiler).
-compile(export_all).
spec_test_() ->
begin
Tests = [
fun prop_add_routes_to_forms/0,
{add_export_to_forms, 1},
{extract_routes_from_clauses, 2},
{function_for_routes, 1},
{route_from_token_ast, 1}
{ map_syntax_tuples , 1 } ,
],
[case Test of
{Funct, Arity} ->
?_assert(proper:check_spec({?TMODULE, Funct, Arity},
[{to_file, user}, 25]));
F when is_function(F,0) ->
?_assert(proper:quickcheck(F(),
[{to_file, user}]))
end||Test <-Tests]
end.
prop_add_routes_to_forms() ->
?FORALL(ExportAttrs ,
list(boss_controller_compiler:export_attr1()),
?IMPLIES(len_in_range(ExportAttrs,1,20),
begin
Result = boss_controller_compiler:add_routes_to_forms(ExportAttrs
++ [{eof, 1}]),
is_list(Result)
end)).
prop_add_routes_to_forms_function() ->
?FORALL(FctTups,
list(route_form()),
?IMPLIES(len_in_range(FctTups, 1,5),
?TIMEOUT(300,
begin
Result = boss_controller_compiler:add_routes_to_forms(FctTups,[],[]),
is_list(Result)
end))).
len_in_range(List, Min, Max) ->
Len = length(List),
Len =< Max andalso Len >= Min.
|
453ea83e2e818271e8b12dcbc6d148883e930f18201bab20709c6404d8f8eee8 | choener/BiobaseXNA | properties.hs |
module Main where
import Control.Monad (join)
import Data.Bits
import Data.Function (on)
import Data.Int (Int16(..))
import Data.List (groupBy,sort,permutations,nub,(\\))
import Data.Maybe (isJust)
import Data.Word (Word)
import Debug.Trace
import qualified Data.Vector.Unboxed as VU
import Test.QuickCheck hiding ((.&.))
import Test.Tasty
import Test.Tasty.QuickCheck (testProperty)
import Test.Tasty.TH
import Biobase.Secondary.Diagrams
import Biobase.Secondary.Basepair (PairIdx)
newtype ArbitrarySSTree = ASST (SSTree PairIdx ())
deriving (Show)
instance Arbitrary ArbitrarySSTree where
arbitrary = ASST <$> sized arbitrarySSTree
where
arbitrarySSTree m = do
Positive c <- arbitrary
cs <- go 0 (c*m)
let k = if null cs then 0 else 1 + maximum [ z | SSTree (_,z) _ _ <- cs ]
return $ SSExtern k () cs
go i j = do
Positive c <- arbitrary
Positive d <- arbitrary
if i+c+d >= j
then return []
else do
cs <- go (i+c+1) (i+c+d)
let h = SSTree (i+c,i+c+d) () cs
ts <- go (i+c+d+1) j
return $ h:ts
shrink ( ASST ( SSExtern k ( ) cs ) )
| null cs = [ ]
| otherwise = [ ASST
shrink (ASST (SSExtern k () cs))
| null cs = []
| otherwise = [ ASST
-}
collectPairs (ASST (SSExtern k _ zs)) = (k, sort $ go zs)
where go [] = []
go (SSTree (i,j) _ cs : ss) = (i,j) : go cs ++ go ss
bld :: Int -> [PairIdx] -> D1Secondary
bld = curry mkD1S
prop_d1Distance a@(ASST _) b@(ASST _) = d1Distance x y == k
where x = mkD1S (lx', x')
y = mkD1S (ly', y')
(lx', x') = collectPairs a
(ly', y') = collectPairs b
k = length $ (x' \\ y') ++ (y' \\ x')
---- | Check if both the memoized version and the population enumeration
---- produce the same multisets, but maybe in different order.
----
---- prop> \(n :: Int16) -> let b = popCount n in memoSorted b == enumSorted b
----
--
prop_PopCountSet ( NonZero ( n ' : : Int16 ) ) = memo = = enum
where b = n
-- memo = memoSorted b
-- enum = enumSorted b
n = n ' ` mod ` 12
--
memoSorted , enumSorted : : Int - > [ [ Int ] ]
--
--memoSorted b = map sort . groupBy ((==) `on` popCount) $ VU.toList $ popCntMemoInt b
enumSorted b = map sort $ [ 0 ] : [ roll ( popPermutation b ) ( Just $ 2^k-1 ) | k < - [ 1 .. b ] ]
-- where roll f (Just k) = k : roll f (f k)
-- roll _ Nothing = []
--
prop_lsb_Int ( x : : Int ) = lsbZ x = = maybe ( -1 ) i d ( maybeLsb x )
--
prop_lsb_Word ( x : : Word ) = lsbZ x = = maybe ( -1 ) i d ( maybeLsb x )
--
prop_OneBits_Int ( x : : Int ) = x = = length abl & & and [ testBit x k | k < - abl ]
-- where abl = activeBitsL x
--
---- Tests if we actually generate all permutations.
--
prop_allPermutations ( a : : Int , b : : Int ) = and ( sort qs ) ( sort $ nub ps )
where nbs = min a ' b ' -- number of 1 bits in set
-- sts = max a' b' -- set size
a ' = a ` mod ` 8 -- finiteBitSize a
b ' = b ` mod ` 8 -- finiteBitSize b
-- ps = permutations $ replicate (sts - nbs) False ++ replicate nbs True
qs = go ( Just $ 2 ^ nbs - 1 )
-- go :: Maybe Int -> [Int]
-- go Nothing = []
-- go (Just k) = k : go (popPermutation sts k)
cmp k as = and [ if a then testBit k c else ( not $ testBit k c ) | ( a , c ) < - zip ( reverse as ) [ 0 .. ] ]
--
---- TODO popComplement
--
prop_popShiftL_popShiftR ( a::Word , ) = s = = l
-- where m = a .|. b
-- s = a .&. b
-- l = popShiftL m r
-- r = popShiftR m s
main :: IO ()
main = $(defaultMainGenerator)
| null | https://raw.githubusercontent.com/choener/BiobaseXNA/ebec70a3906106a50c29cdbbce9a3247d6ebb15f/tests/properties.hs | haskell | -- | Check if both the memoized version and the population enumeration
-- produce the same multisets, but maybe in different order.
--
-- prop> \(n :: Int16) -> let b = popCount n in memoSorted b == enumSorted b
--
memo = memoSorted b
enum = enumSorted b
memoSorted b = map sort . groupBy ((==) `on` popCount) $ VU.toList $ popCntMemoInt b
where roll f (Just k) = k : roll f (f k)
roll _ Nothing = []
where abl = activeBitsL x
-- Tests if we actually generate all permutations.
number of 1 bits in set
sts = max a' b' -- set size
finiteBitSize a
finiteBitSize b
ps = permutations $ replicate (sts - nbs) False ++ replicate nbs True
go :: Maybe Int -> [Int]
go Nothing = []
go (Just k) = k : go (popPermutation sts k)
-- TODO popComplement
where m = a .|. b
s = a .&. b
l = popShiftL m r
r = popShiftR m s |
module Main where
import Control.Monad (join)
import Data.Bits
import Data.Function (on)
import Data.Int (Int16(..))
import Data.List (groupBy,sort,permutations,nub,(\\))
import Data.Maybe (isJust)
import Data.Word (Word)
import Debug.Trace
import qualified Data.Vector.Unboxed as VU
import Test.QuickCheck hiding ((.&.))
import Test.Tasty
import Test.Tasty.QuickCheck (testProperty)
import Test.Tasty.TH
import Biobase.Secondary.Diagrams
import Biobase.Secondary.Basepair (PairIdx)
newtype ArbitrarySSTree = ASST (SSTree PairIdx ())
deriving (Show)
instance Arbitrary ArbitrarySSTree where
arbitrary = ASST <$> sized arbitrarySSTree
where
arbitrarySSTree m = do
Positive c <- arbitrary
cs <- go 0 (c*m)
let k = if null cs then 0 else 1 + maximum [ z | SSTree (_,z) _ _ <- cs ]
return $ SSExtern k () cs
go i j = do
Positive c <- arbitrary
Positive d <- arbitrary
if i+c+d >= j
then return []
else do
cs <- go (i+c+1) (i+c+d)
let h = SSTree (i+c,i+c+d) () cs
ts <- go (i+c+d+1) j
return $ h:ts
shrink ( ASST ( SSExtern k ( ) cs ) )
| null cs = [ ]
| otherwise = [ ASST
shrink (ASST (SSExtern k () cs))
| null cs = []
| otherwise = [ ASST
-}
collectPairs (ASST (SSExtern k _ zs)) = (k, sort $ go zs)
where go [] = []
go (SSTree (i,j) _ cs : ss) = (i,j) : go cs ++ go ss
bld :: Int -> [PairIdx] -> D1Secondary
bld = curry mkD1S
prop_d1Distance a@(ASST _) b@(ASST _) = d1Distance x y == k
where x = mkD1S (lx', x')
y = mkD1S (ly', y')
(lx', x') = collectPairs a
(ly', y') = collectPairs b
k = length $ (x' \\ y') ++ (y' \\ x')
prop_PopCountSet ( NonZero ( n ' : : Int16 ) ) = memo = = enum
where b = n
n = n ' ` mod ` 12
memoSorted , enumSorted : : Int - > [ [ Int ] ]
enumSorted b = map sort $ [ 0 ] : [ roll ( popPermutation b ) ( Just $ 2^k-1 ) | k < - [ 1 .. b ] ]
prop_lsb_Int ( x : : Int ) = lsbZ x = = maybe ( -1 ) i d ( maybeLsb x )
prop_lsb_Word ( x : : Word ) = lsbZ x = = maybe ( -1 ) i d ( maybeLsb x )
prop_OneBits_Int ( x : : Int ) = x = = length abl & & and [ testBit x k | k < - abl ]
prop_allPermutations ( a : : Int , b : : Int ) = and ( sort qs ) ( sort $ nub ps )
qs = go ( Just $ 2 ^ nbs - 1 )
cmp k as = and [ if a then testBit k c else ( not $ testBit k c ) | ( a , c ) < - zip ( reverse as ) [ 0 .. ] ]
prop_popShiftL_popShiftR ( a::Word , ) = s = = l
main :: IO ()
main = $(defaultMainGenerator)
|
06476360202bdebfb9fc156fc40801d47528e954945094fae92f202f9325c705 | zenspider/schemers | exercise.2.25.scm | #lang racket/base
(require "../lib/test.rkt")
Exercise 2.25 .
Give combinations of cars and that will pick 7 from each of
;; the following lists:
;;
( 1 3 ( 5 7 ) 9 )
( ( 7 ) )
( 1 ( 2 ( 3 ( 4 ( 5 ( 6 7 ) ) ) ) ) )
(define a '(1 3 (5 7) 9))
(define b '((7)))
(define c '(1 (2 (3 (4 (5 (6 7)))))))
(assert-equal 7 (car (cdaddr a)))
(assert-equal 7 (caar b))
(assert-equal 7 (cadr (cadr (cadr (cadr (cadr (cadr c)))))))
;; or
(assert-equal 7 (cadadr (cadadr (cadadr c))))
(done)
| null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_2/exercise.2.25.scm | scheme | the following lists:
or | #lang racket/base
(require "../lib/test.rkt")
Exercise 2.25 .
Give combinations of cars and that will pick 7 from each of
( 1 3 ( 5 7 ) 9 )
( ( 7 ) )
( 1 ( 2 ( 3 ( 4 ( 5 ( 6 7 ) ) ) ) ) )
(define a '(1 3 (5 7) 9))
(define b '((7)))
(define c '(1 (2 (3 (4 (5 (6 7)))))))
(assert-equal 7 (car (cdaddr a)))
(assert-equal 7 (caar b))
(assert-equal 7 (cadr (cadr (cadr (cadr (cadr (cadr c)))))))
(assert-equal 7 (cadadr (cadadr (cadadr c))))
(done)
|
0197a889f7ab42b7b3208043640566aadc15fed16175e93e69856aae894a55f2 | emqx/emqx | emqx_authz_api_sources.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_authz_api_sources).
-behaviour(minirest_api).
-include("emqx_authz.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("hocon/include/hoconsc.hrl").
-import(hoconsc, [mk/1, mk/2, ref/2, array/1, enum/1]).
-define(BAD_REQUEST, 'BAD_REQUEST').
-define(NOT_FOUND, 'NOT_FOUND').
-define(API_SCHEMA_MODULE, emqx_authz_api_schema).
-export([
get_raw_sources/0,
get_raw_source/1,
source_status/2,
lookup_from_local_node/1,
lookup_from_all_nodes/1
]).
-export([
api_spec/0,
paths/0,
schema/1,
fields/1
]).
-export([
sources/2,
source/2,
source_move/2,
aggregate_metrics/1
]).
-define(TAGS, [<<"Authorization">>]).
api_spec() ->
emqx_dashboard_swagger:spec(?MODULE, #{check_schema => true}).
paths() ->
[
"/authorization/sources",
"/authorization/sources/:type",
"/authorization/sources/:type/status",
"/authorization/sources/:type/move"
].
fields(sources) ->
[{sources, mk(array(hoconsc:union(authz_sources_type_refs())), #{desc => ?DESC(sources)})}].
%%--------------------------------------------------------------------
Schema for each URI
%%--------------------------------------------------------------------
schema("/authorization/sources") ->
#{
'operationId' => sources,
get =>
#{
description => ?DESC(authorization_sources_get),
tags => ?TAGS,
responses =>
#{
200 => ref(?MODULE, sources)
}
},
post =>
#{
description => ?DESC(authorization_sources_post),
tags => ?TAGS,
'requestBody' => mk(
hoconsc:union(authz_sources_type_refs()),
#{desc => ?DESC(source_config)}
),
responses =>
#{
204 => <<"Authorization source created successfully">>,
400 => emqx_dashboard_swagger:error_codes(
[?BAD_REQUEST],
<<"Bad Request">>
)
}
}
};
schema("/authorization/sources/:type") ->
#{
'operationId' => source,
get =>
#{
description => ?DESC(authorization_sources_type_get),
tags => ?TAGS,
parameters => parameters_field(),
responses =>
#{
200 => mk(
hoconsc:union(authz_sources_type_refs()),
#{desc => ?DESC(source)}
),
404 => emqx_dashboard_swagger:error_codes([?NOT_FOUND], <<"Not Found">>)
}
},
put =>
#{
description => ?DESC(authorization_sources_type_put),
tags => ?TAGS,
parameters => parameters_field(),
'requestBody' => mk(hoconsc:union(authz_sources_type_refs())),
responses =>
#{
204 => <<"Authorization source updated successfully">>,
400 => emqx_dashboard_swagger:error_codes([?BAD_REQUEST], <<"Bad Request">>)
}
},
delete =>
#{
description => ?DESC(authorization_sources_type_delete),
tags => ?TAGS,
parameters => parameters_field(),
responses =>
#{
204 => <<"Deleted successfully">>,
400 => emqx_dashboard_swagger:error_codes([?BAD_REQUEST], <<"Bad Request">>)
}
}
};
schema("/authorization/sources/:type/status") ->
#{
'operationId' => source_status,
get =>
#{
description => ?DESC(authorization_sources_type_status_get),
tags => ?TAGS,
parameters => parameters_field(),
responses =>
#{
200 => emqx_dashboard_swagger:schema_with_examples(
hoconsc:ref(emqx_authz_schema, "metrics_status_fields"),
status_metrics_example()
),
400 => emqx_dashboard_swagger:error_codes(
[?BAD_REQUEST], <<"Bad request">>
),
404 => emqx_dashboard_swagger:error_codes([?NOT_FOUND], <<"Not Found">>)
}
}
};
schema("/authorization/sources/:type/move") ->
#{
'operationId' => source_move,
post =>
#{
description => ?DESC(authorization_sources_type_move_post),
tags => ?TAGS,
parameters => parameters_field(),
'requestBody' =>
emqx_dashboard_swagger:schema_with_examples(
ref(?API_SCHEMA_MODULE, position),
position_example()
),
responses =>
#{
204 => <<"No Content">>,
400 => emqx_dashboard_swagger:error_codes(
[?BAD_REQUEST], <<"Bad Request">>
),
404 => emqx_dashboard_swagger:error_codes([?NOT_FOUND], <<"Not Found">>)
}
}
}.
%%--------------------------------------------------------------------
%% Operation functions
%%--------------------------------------------------------------------
sources(Method, #{bindings := #{type := Type} = Bindings} = Req) when
is_atom(Type)
->
sources(Method, Req#{bindings => Bindings#{type => atom_to_binary(Type, utf8)}});
sources(get, _) ->
Sources = lists:foldl(
fun
(
#{
<<"type">> := <<"file">>,
<<"enable">> := Enable,
<<"path">> := Path
},
AccIn
) ->
case file:read_file(Path) of
{ok, Rules} ->
lists:append(AccIn, [
#{
type => file,
enable => Enable,
rules => Rules
}
]);
{error, _} ->
lists:append(AccIn, [
#{
type => file,
enable => Enable,
rules => <<"">>
}
])
end;
(Source, AccIn) ->
lists:append(AccIn, [Source])
end,
[],
get_raw_sources()
),
{200, #{sources => Sources}};
sources(post, #{body := Body}) ->
update_config(?CMD_PREPEND, Body).
source(Method, #{bindings := #{type := Type} = Bindings} = Req) when
is_atom(Type)
->
source(Method, Req#{bindings => Bindings#{type => atom_to_binary(Type, utf8)}});
source(get, #{bindings := #{type := Type}}) ->
with_source(
Type,
fun
(#{<<"type">> := <<"file">>, <<"enable">> := Enable, <<"path">> := Path}) ->
case file:read_file(Path) of
{ok, Rules} ->
{200, #{
type => file,
enable => Enable,
rules => Rules
}};
{error, Reason} ->
{500, #{
code => <<"INTERNAL_ERROR">>,
message => bin(Reason)
}}
end;
(Source) ->
{200, Source}
end
);
source(put, #{bindings := #{type := Type}, body := #{<<"type">> := Type} = Body}) ->
with_source(
Type,
fun(_) ->
update_config({?CMD_REPLACE, Type}, Body)
end
);
source(put, #{bindings := #{type := Type}, body := #{<<"type">> := _OtherType}}) ->
with_source(
Type,
fun(_) ->
{400, #{code => <<"BAD_REQUEST">>, message => <<"Type mismatch">>}}
end
);
source(delete, #{bindings := #{type := Type}}) ->
with_source(
Type,
fun(_) ->
update_config({?CMD_DELETE, Type}, #{})
end
).
source_status(get, #{bindings := #{type := Type}}) ->
with_source(
atom_to_binary(Type, utf8),
fun(_) -> lookup_from_all_nodes(Type) end
).
source_move(Method, #{bindings := #{type := Type} = Bindings} = Req) when
is_atom(Type)
->
source_move(Method, Req#{bindings => Bindings#{type => atom_to_binary(Type, utf8)}});
source_move(post, #{bindings := #{type := Type}, body := #{<<"position">> := Position}}) ->
with_source(
Type,
fun(_Source) ->
case parse_position(Position) of
{ok, NPosition} ->
try emqx_authz:move(Type, NPosition) of
{ok, _} ->
{204};
{error, {not_found_source, _Type}} ->
{404, #{
code => <<"NOT_FOUND">>,
message => <<"source ", Type/binary, " not found">>
}};
{error, {emqx_conf_schema, _}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => <<"BAD_SCHEMA">>
}};
{error, Reason} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}}
catch
error:{unknown_authz_source_type, Unknown} ->
NUnknown = bin(Unknown),
{400, #{
code => <<"BAD_REQUEST">>,
message => <<"Unknown authz Source Type: ", NUnknown/binary>>
}}
end;
{error, Reason} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}}
end
end
).
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
lookup_from_local_node(Type) ->
NodeId = node(self()),
try emqx_authz:lookup(Type) of
#{annotations := #{id := ResourceId}} ->
Metrics = emqx_metrics_worker:get_metrics(authz_metrics, Type),
case emqx_resource:get_instance(ResourceId) of
{error, not_found} ->
{error, {NodeId, not_found_resource}};
{ok, _, #{status := Status, metrics := ResourceMetrics}} ->
{ok, {NodeId, Status, Metrics, ResourceMetrics}}
end;
_ ->
Metrics = emqx_metrics_worker:get_metrics(authz_metrics, Type),
for authz file /
{ok, {NodeId, connected, Metrics, #{}}}
catch
_:Reason -> {error, {NodeId, list_to_binary(io_lib:format("~p", [Reason]))}}
end.
lookup_from_all_nodes(Type) ->
Nodes = mria_mnesia:running_nodes(),
case is_ok(emqx_authz_proto_v1:lookup_from_all_nodes(Nodes, Type)) of
{ok, ResList} ->
{StatusMap, MetricsMap, ResourceMetricsMap, ErrorMap} = make_result_map(ResList),
AggregateStatus = aggregate_status(maps:values(StatusMap)),
AggregateMetrics = aggregate_metrics(maps:values(MetricsMap)),
AggregateResourceMetrics = aggregate_metrics(maps:values(ResourceMetricsMap)),
Fun = fun(_, V1) -> restructure_map(V1) end,
MKMap = fun(Name) -> fun({Key, Val}) -> #{node => Key, Name => Val} end end,
HelpFun = fun(M, Name) -> lists:map(MKMap(Name), maps:to_list(M)) end,
{200, #{
node_resource_metrics => HelpFun(maps:map(Fun, ResourceMetricsMap), metrics),
resource_metrics =>
case maps:size(AggregateResourceMetrics) of
0 -> #{};
_ -> restructure_map(AggregateResourceMetrics)
end,
node_metrics => HelpFun(maps:map(Fun, MetricsMap), metrics),
metrics => restructure_map(AggregateMetrics),
node_status => HelpFun(StatusMap, status),
status => AggregateStatus,
node_error => HelpFun(maps:map(Fun, ErrorMap), reason)
}};
{error, ErrL} ->
{400, #{
code => <<"INTERNAL_ERROR">>,
message => bin_t(io_lib:format("~p", [ErrL]))
}}
end.
aggregate_status([]) ->
empty_metrics_and_status;
aggregate_status(AllStatus) ->
Head = fun([A | _]) -> A end,
HeadVal = Head(AllStatus),
AllRes = lists:all(fun(Val) -> Val == HeadVal end, AllStatus),
case AllRes of
true -> HeadVal;
false -> inconsistent
end.
aggregate_metrics([]) ->
#{};
aggregate_metrics([HeadMetrics | AllMetrics]) ->
ErrorLogger = fun(Reason) -> ?SLOG(info, #{msg => "bad_metrics_value", error => Reason}) end,
Fun = fun(ElemMap, AccMap) ->
emqx_map_lib:best_effort_recursive_sum(AccMap, ElemMap, ErrorLogger)
end,
lists:foldl(Fun, HeadMetrics, AllMetrics).
make_result_map(ResList) ->
Fun =
fun(Elem, {StatusMap, MetricsMap, ResourceMetricsMap, ErrorMap}) ->
case Elem of
{ok, {NodeId, Status, Metrics, ResourceMetrics}} ->
{
maps:put(NodeId, Status, StatusMap),
maps:put(NodeId, Metrics, MetricsMap),
maps:put(NodeId, ResourceMetrics, ResourceMetricsMap),
ErrorMap
};
{error, {NodeId, Reason}} ->
{StatusMap, MetricsMap, ResourceMetricsMap, maps:put(NodeId, Reason, ErrorMap)}
end
end,
lists:foldl(Fun, {maps:new(), maps:new(), maps:new(), maps:new()}, ResList).
restructure_map(#{
counters := #{deny := Failed, total := Total, allow := Succ, nomatch := Nomatch},
rate := #{total := #{current := Rate, last5m := Rate5m, max := RateMax}}
}) ->
#{
total => Total,
allow => Succ,
deny => Failed,
nomatch => Nomatch,
rate => Rate,
rate_last5m => Rate5m,
rate_max => RateMax
};
restructure_map(#{
counters := #{failed := Failed, matched := Match, success := Succ},
rate := #{matched := #{current := Rate, last5m := Rate5m, max := RateMax}}
}) ->
#{
matched => Match,
success => Succ,
failed => Failed,
rate => Rate,
rate_last5m => Rate5m,
rate_max => RateMax
};
restructure_map(Error) ->
Error.
bin_t(S) when is_list(S) ->
list_to_binary(S).
is_ok(ResL) ->
case
lists:filter(
fun
({ok, _}) -> false;
(_) -> true
end,
ResL
)
of
[] -> {ok, [Res || {ok, Res} <- ResL]};
ErrL -> {error, ErrL}
end.
get_raw_sources() ->
RawSources = emqx:get_raw_config([authorization, sources], []),
Schema = emqx_hocon:make_schema(emqx_authz_schema:authz_fields()),
Conf = #{<<"sources">> => RawSources},
#{<<"sources">> := Sources} = hocon_tconf:make_serializable(Schema, Conf, #{}),
merge_default_headers(Sources).
merge_default_headers(Sources) ->
lists:map(
fun(Source) ->
case maps:find(<<"headers">>, Source) of
{ok, Headers} ->
NewHeaders =
case Source of
#{<<"method">> := <<"get">>} ->
(emqx_authz_schema:headers_no_content_type(converter))(Headers);
#{<<"method">> := <<"post">>} ->
(emqx_authz_schema:headers(converter))(Headers);
_ ->
Headers
end,
Source#{<<"headers">> => NewHeaders};
error ->
Source
end
end,
Sources
).
get_raw_source(Type) ->
lists:filter(
fun(#{<<"type">> := T}) ->
T =:= Type
end,
get_raw_sources()
).
-spec with_source(binary(), fun((map()) -> term())) -> term().
with_source(Type, ContF) ->
case get_raw_source(Type) of
[] ->
{404, #{code => <<"NOT_FOUND">>, message => <<"Not found: ", Type/binary>>}};
[Source] ->
ContF(Source)
end.
update_config(Cmd, Sources) ->
case emqx_authz:update(Cmd, Sources) of
{ok, _} ->
{204};
{error, {pre_config_update, emqx_authz, Reason}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}};
{error, {post_config_update, emqx_authz, Reason}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}};
%% TODO: The `Reason` may cann't be trans to json term. (i.e. ecpool start failed)
{error, {emqx_conf_schema, _}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => <<"BAD_SCHEMA">>
}};
{error, Reason} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}}
end.
parameters_field() ->
[
{type,
mk(
enum(?API_SCHEMA_MODULE:authz_sources_types(simple)),
#{in => path, desc => ?DESC(source_type)}
)}
].
parse_position(<<"front">>) ->
{ok, ?CMD_MOVE_FRONT};
parse_position(<<"rear">>) ->
{ok, ?CMD_MOVE_REAR};
parse_position(<<"before:">>) ->
{error, <<"Invalid parameter. Cannot be placed before an empty target">>};
parse_position(<<"after:">>) ->
{error, <<"Invalid parameter. Cannot be placed after an empty target">>};
parse_position(<<"before:", Before/binary>>) ->
{ok, ?CMD_MOVE_BEFORE(Before)};
parse_position(<<"after:", After/binary>>) ->
{ok, ?CMD_MOVE_AFTER(After)};
parse_position(_) ->
{error, <<"Invalid parameter. Unknow position">>}.
position_example() ->
#{
front =>
#{
summary => <<"front example">>,
value => #{<<"position">> => <<"front">>}
},
rear =>
#{
summary => <<"rear example">>,
value => #{<<"position">> => <<"rear">>}
},
relative_before =>
#{
summary => <<"relative example">>,
value => #{<<"position">> => <<"before:file">>}
},
relative_after =>
#{
summary => <<"relative example">>,
value => #{<<"position">> => <<"after:file">>}
}
}.
authz_sources_type_refs() ->
[
ref(?API_SCHEMA_MODULE, Type)
|| Type <- emqx_authz_api_schema:authz_sources_types(detailed)
].
bin(Term) -> erlang:iolist_to_binary(io_lib:format("~p", [Term])).
status_metrics_example() ->
#{
'metrics_example' => #{
summary => <<"Showing a typical metrics example">>,
value =>
#{
resource_metrics => #{
matched => 0,
success => 0,
failed => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
},
node_resource_metrics => [
#{
node => node(),
metrics => #{
matched => 0,
success => 0,
failed => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
}
}
],
metrics => #{
total => 0,
allow => 0,
deny => 0,
nomatch => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
},
node_metrics => [
#{
node => node(),
metrics => #{
total => 0,
allow => 0,
deny => 0,
nomatch => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
}
}
],
status => connected,
node_status => [
#{
node => node(),
status => connected
}
]
}
}
}.
| null | https://raw.githubusercontent.com/emqx/emqx/609cd01a35859bf079043a933c4edb72ea2ea8e2/apps/emqx_authz/src/emqx_authz_api_sources.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.
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Operation functions
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
TODO: The `Reason` may cann't be trans to json term. (i.e. ecpool start failed) | Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_authz_api_sources).
-behaviour(minirest_api).
-include("emqx_authz.hrl").
-include_lib("emqx/include/logger.hrl").
-include_lib("hocon/include/hoconsc.hrl").
-import(hoconsc, [mk/1, mk/2, ref/2, array/1, enum/1]).
-define(BAD_REQUEST, 'BAD_REQUEST').
-define(NOT_FOUND, 'NOT_FOUND').
-define(API_SCHEMA_MODULE, emqx_authz_api_schema).
-export([
get_raw_sources/0,
get_raw_source/1,
source_status/2,
lookup_from_local_node/1,
lookup_from_all_nodes/1
]).
-export([
api_spec/0,
paths/0,
schema/1,
fields/1
]).
-export([
sources/2,
source/2,
source_move/2,
aggregate_metrics/1
]).
-define(TAGS, [<<"Authorization">>]).
api_spec() ->
emqx_dashboard_swagger:spec(?MODULE, #{check_schema => true}).
paths() ->
[
"/authorization/sources",
"/authorization/sources/:type",
"/authorization/sources/:type/status",
"/authorization/sources/:type/move"
].
fields(sources) ->
[{sources, mk(array(hoconsc:union(authz_sources_type_refs())), #{desc => ?DESC(sources)})}].
Schema for each URI
schema("/authorization/sources") ->
#{
'operationId' => sources,
get =>
#{
description => ?DESC(authorization_sources_get),
tags => ?TAGS,
responses =>
#{
200 => ref(?MODULE, sources)
}
},
post =>
#{
description => ?DESC(authorization_sources_post),
tags => ?TAGS,
'requestBody' => mk(
hoconsc:union(authz_sources_type_refs()),
#{desc => ?DESC(source_config)}
),
responses =>
#{
204 => <<"Authorization source created successfully">>,
400 => emqx_dashboard_swagger:error_codes(
[?BAD_REQUEST],
<<"Bad Request">>
)
}
}
};
schema("/authorization/sources/:type") ->
#{
'operationId' => source,
get =>
#{
description => ?DESC(authorization_sources_type_get),
tags => ?TAGS,
parameters => parameters_field(),
responses =>
#{
200 => mk(
hoconsc:union(authz_sources_type_refs()),
#{desc => ?DESC(source)}
),
404 => emqx_dashboard_swagger:error_codes([?NOT_FOUND], <<"Not Found">>)
}
},
put =>
#{
description => ?DESC(authorization_sources_type_put),
tags => ?TAGS,
parameters => parameters_field(),
'requestBody' => mk(hoconsc:union(authz_sources_type_refs())),
responses =>
#{
204 => <<"Authorization source updated successfully">>,
400 => emqx_dashboard_swagger:error_codes([?BAD_REQUEST], <<"Bad Request">>)
}
},
delete =>
#{
description => ?DESC(authorization_sources_type_delete),
tags => ?TAGS,
parameters => parameters_field(),
responses =>
#{
204 => <<"Deleted successfully">>,
400 => emqx_dashboard_swagger:error_codes([?BAD_REQUEST], <<"Bad Request">>)
}
}
};
schema("/authorization/sources/:type/status") ->
#{
'operationId' => source_status,
get =>
#{
description => ?DESC(authorization_sources_type_status_get),
tags => ?TAGS,
parameters => parameters_field(),
responses =>
#{
200 => emqx_dashboard_swagger:schema_with_examples(
hoconsc:ref(emqx_authz_schema, "metrics_status_fields"),
status_metrics_example()
),
400 => emqx_dashboard_swagger:error_codes(
[?BAD_REQUEST], <<"Bad request">>
),
404 => emqx_dashboard_swagger:error_codes([?NOT_FOUND], <<"Not Found">>)
}
}
};
schema("/authorization/sources/:type/move") ->
#{
'operationId' => source_move,
post =>
#{
description => ?DESC(authorization_sources_type_move_post),
tags => ?TAGS,
parameters => parameters_field(),
'requestBody' =>
emqx_dashboard_swagger:schema_with_examples(
ref(?API_SCHEMA_MODULE, position),
position_example()
),
responses =>
#{
204 => <<"No Content">>,
400 => emqx_dashboard_swagger:error_codes(
[?BAD_REQUEST], <<"Bad Request">>
),
404 => emqx_dashboard_swagger:error_codes([?NOT_FOUND], <<"Not Found">>)
}
}
}.
sources(Method, #{bindings := #{type := Type} = Bindings} = Req) when
is_atom(Type)
->
sources(Method, Req#{bindings => Bindings#{type => atom_to_binary(Type, utf8)}});
sources(get, _) ->
Sources = lists:foldl(
fun
(
#{
<<"type">> := <<"file">>,
<<"enable">> := Enable,
<<"path">> := Path
},
AccIn
) ->
case file:read_file(Path) of
{ok, Rules} ->
lists:append(AccIn, [
#{
type => file,
enable => Enable,
rules => Rules
}
]);
{error, _} ->
lists:append(AccIn, [
#{
type => file,
enable => Enable,
rules => <<"">>
}
])
end;
(Source, AccIn) ->
lists:append(AccIn, [Source])
end,
[],
get_raw_sources()
),
{200, #{sources => Sources}};
sources(post, #{body := Body}) ->
update_config(?CMD_PREPEND, Body).
source(Method, #{bindings := #{type := Type} = Bindings} = Req) when
is_atom(Type)
->
source(Method, Req#{bindings => Bindings#{type => atom_to_binary(Type, utf8)}});
source(get, #{bindings := #{type := Type}}) ->
with_source(
Type,
fun
(#{<<"type">> := <<"file">>, <<"enable">> := Enable, <<"path">> := Path}) ->
case file:read_file(Path) of
{ok, Rules} ->
{200, #{
type => file,
enable => Enable,
rules => Rules
}};
{error, Reason} ->
{500, #{
code => <<"INTERNAL_ERROR">>,
message => bin(Reason)
}}
end;
(Source) ->
{200, Source}
end
);
source(put, #{bindings := #{type := Type}, body := #{<<"type">> := Type} = Body}) ->
with_source(
Type,
fun(_) ->
update_config({?CMD_REPLACE, Type}, Body)
end
);
source(put, #{bindings := #{type := Type}, body := #{<<"type">> := _OtherType}}) ->
with_source(
Type,
fun(_) ->
{400, #{code => <<"BAD_REQUEST">>, message => <<"Type mismatch">>}}
end
);
source(delete, #{bindings := #{type := Type}}) ->
with_source(
Type,
fun(_) ->
update_config({?CMD_DELETE, Type}, #{})
end
).
source_status(get, #{bindings := #{type := Type}}) ->
with_source(
atom_to_binary(Type, utf8),
fun(_) -> lookup_from_all_nodes(Type) end
).
source_move(Method, #{bindings := #{type := Type} = Bindings} = Req) when
is_atom(Type)
->
source_move(Method, Req#{bindings => Bindings#{type => atom_to_binary(Type, utf8)}});
source_move(post, #{bindings := #{type := Type}, body := #{<<"position">> := Position}}) ->
with_source(
Type,
fun(_Source) ->
case parse_position(Position) of
{ok, NPosition} ->
try emqx_authz:move(Type, NPosition) of
{ok, _} ->
{204};
{error, {not_found_source, _Type}} ->
{404, #{
code => <<"NOT_FOUND">>,
message => <<"source ", Type/binary, " not found">>
}};
{error, {emqx_conf_schema, _}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => <<"BAD_SCHEMA">>
}};
{error, Reason} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}}
catch
error:{unknown_authz_source_type, Unknown} ->
NUnknown = bin(Unknown),
{400, #{
code => <<"BAD_REQUEST">>,
message => <<"Unknown authz Source Type: ", NUnknown/binary>>
}}
end;
{error, Reason} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}}
end
end
).
Internal functions
lookup_from_local_node(Type) ->
NodeId = node(self()),
try emqx_authz:lookup(Type) of
#{annotations := #{id := ResourceId}} ->
Metrics = emqx_metrics_worker:get_metrics(authz_metrics, Type),
case emqx_resource:get_instance(ResourceId) of
{error, not_found} ->
{error, {NodeId, not_found_resource}};
{ok, _, #{status := Status, metrics := ResourceMetrics}} ->
{ok, {NodeId, Status, Metrics, ResourceMetrics}}
end;
_ ->
Metrics = emqx_metrics_worker:get_metrics(authz_metrics, Type),
for authz file /
{ok, {NodeId, connected, Metrics, #{}}}
catch
_:Reason -> {error, {NodeId, list_to_binary(io_lib:format("~p", [Reason]))}}
end.
lookup_from_all_nodes(Type) ->
Nodes = mria_mnesia:running_nodes(),
case is_ok(emqx_authz_proto_v1:lookup_from_all_nodes(Nodes, Type)) of
{ok, ResList} ->
{StatusMap, MetricsMap, ResourceMetricsMap, ErrorMap} = make_result_map(ResList),
AggregateStatus = aggregate_status(maps:values(StatusMap)),
AggregateMetrics = aggregate_metrics(maps:values(MetricsMap)),
AggregateResourceMetrics = aggregate_metrics(maps:values(ResourceMetricsMap)),
Fun = fun(_, V1) -> restructure_map(V1) end,
MKMap = fun(Name) -> fun({Key, Val}) -> #{node => Key, Name => Val} end end,
HelpFun = fun(M, Name) -> lists:map(MKMap(Name), maps:to_list(M)) end,
{200, #{
node_resource_metrics => HelpFun(maps:map(Fun, ResourceMetricsMap), metrics),
resource_metrics =>
case maps:size(AggregateResourceMetrics) of
0 -> #{};
_ -> restructure_map(AggregateResourceMetrics)
end,
node_metrics => HelpFun(maps:map(Fun, MetricsMap), metrics),
metrics => restructure_map(AggregateMetrics),
node_status => HelpFun(StatusMap, status),
status => AggregateStatus,
node_error => HelpFun(maps:map(Fun, ErrorMap), reason)
}};
{error, ErrL} ->
{400, #{
code => <<"INTERNAL_ERROR">>,
message => bin_t(io_lib:format("~p", [ErrL]))
}}
end.
aggregate_status([]) ->
empty_metrics_and_status;
aggregate_status(AllStatus) ->
Head = fun([A | _]) -> A end,
HeadVal = Head(AllStatus),
AllRes = lists:all(fun(Val) -> Val == HeadVal end, AllStatus),
case AllRes of
true -> HeadVal;
false -> inconsistent
end.
aggregate_metrics([]) ->
#{};
aggregate_metrics([HeadMetrics | AllMetrics]) ->
ErrorLogger = fun(Reason) -> ?SLOG(info, #{msg => "bad_metrics_value", error => Reason}) end,
Fun = fun(ElemMap, AccMap) ->
emqx_map_lib:best_effort_recursive_sum(AccMap, ElemMap, ErrorLogger)
end,
lists:foldl(Fun, HeadMetrics, AllMetrics).
make_result_map(ResList) ->
Fun =
fun(Elem, {StatusMap, MetricsMap, ResourceMetricsMap, ErrorMap}) ->
case Elem of
{ok, {NodeId, Status, Metrics, ResourceMetrics}} ->
{
maps:put(NodeId, Status, StatusMap),
maps:put(NodeId, Metrics, MetricsMap),
maps:put(NodeId, ResourceMetrics, ResourceMetricsMap),
ErrorMap
};
{error, {NodeId, Reason}} ->
{StatusMap, MetricsMap, ResourceMetricsMap, maps:put(NodeId, Reason, ErrorMap)}
end
end,
lists:foldl(Fun, {maps:new(), maps:new(), maps:new(), maps:new()}, ResList).
restructure_map(#{
counters := #{deny := Failed, total := Total, allow := Succ, nomatch := Nomatch},
rate := #{total := #{current := Rate, last5m := Rate5m, max := RateMax}}
}) ->
#{
total => Total,
allow => Succ,
deny => Failed,
nomatch => Nomatch,
rate => Rate,
rate_last5m => Rate5m,
rate_max => RateMax
};
restructure_map(#{
counters := #{failed := Failed, matched := Match, success := Succ},
rate := #{matched := #{current := Rate, last5m := Rate5m, max := RateMax}}
}) ->
#{
matched => Match,
success => Succ,
failed => Failed,
rate => Rate,
rate_last5m => Rate5m,
rate_max => RateMax
};
restructure_map(Error) ->
Error.
bin_t(S) when is_list(S) ->
list_to_binary(S).
is_ok(ResL) ->
case
lists:filter(
fun
({ok, _}) -> false;
(_) -> true
end,
ResL
)
of
[] -> {ok, [Res || {ok, Res} <- ResL]};
ErrL -> {error, ErrL}
end.
get_raw_sources() ->
RawSources = emqx:get_raw_config([authorization, sources], []),
Schema = emqx_hocon:make_schema(emqx_authz_schema:authz_fields()),
Conf = #{<<"sources">> => RawSources},
#{<<"sources">> := Sources} = hocon_tconf:make_serializable(Schema, Conf, #{}),
merge_default_headers(Sources).
merge_default_headers(Sources) ->
lists:map(
fun(Source) ->
case maps:find(<<"headers">>, Source) of
{ok, Headers} ->
NewHeaders =
case Source of
#{<<"method">> := <<"get">>} ->
(emqx_authz_schema:headers_no_content_type(converter))(Headers);
#{<<"method">> := <<"post">>} ->
(emqx_authz_schema:headers(converter))(Headers);
_ ->
Headers
end,
Source#{<<"headers">> => NewHeaders};
error ->
Source
end
end,
Sources
).
get_raw_source(Type) ->
lists:filter(
fun(#{<<"type">> := T}) ->
T =:= Type
end,
get_raw_sources()
).
-spec with_source(binary(), fun((map()) -> term())) -> term().
with_source(Type, ContF) ->
case get_raw_source(Type) of
[] ->
{404, #{code => <<"NOT_FOUND">>, message => <<"Not found: ", Type/binary>>}};
[Source] ->
ContF(Source)
end.
update_config(Cmd, Sources) ->
case emqx_authz:update(Cmd, Sources) of
{ok, _} ->
{204};
{error, {pre_config_update, emqx_authz, Reason}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}};
{error, {post_config_update, emqx_authz, Reason}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}};
{error, {emqx_conf_schema, _}} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => <<"BAD_SCHEMA">>
}};
{error, Reason} ->
{400, #{
code => <<"BAD_REQUEST">>,
message => bin(Reason)
}}
end.
parameters_field() ->
[
{type,
mk(
enum(?API_SCHEMA_MODULE:authz_sources_types(simple)),
#{in => path, desc => ?DESC(source_type)}
)}
].
parse_position(<<"front">>) ->
{ok, ?CMD_MOVE_FRONT};
parse_position(<<"rear">>) ->
{ok, ?CMD_MOVE_REAR};
parse_position(<<"before:">>) ->
{error, <<"Invalid parameter. Cannot be placed before an empty target">>};
parse_position(<<"after:">>) ->
{error, <<"Invalid parameter. Cannot be placed after an empty target">>};
parse_position(<<"before:", Before/binary>>) ->
{ok, ?CMD_MOVE_BEFORE(Before)};
parse_position(<<"after:", After/binary>>) ->
{ok, ?CMD_MOVE_AFTER(After)};
parse_position(_) ->
{error, <<"Invalid parameter. Unknow position">>}.
position_example() ->
#{
front =>
#{
summary => <<"front example">>,
value => #{<<"position">> => <<"front">>}
},
rear =>
#{
summary => <<"rear example">>,
value => #{<<"position">> => <<"rear">>}
},
relative_before =>
#{
summary => <<"relative example">>,
value => #{<<"position">> => <<"before:file">>}
},
relative_after =>
#{
summary => <<"relative example">>,
value => #{<<"position">> => <<"after:file">>}
}
}.
authz_sources_type_refs() ->
[
ref(?API_SCHEMA_MODULE, Type)
|| Type <- emqx_authz_api_schema:authz_sources_types(detailed)
].
bin(Term) -> erlang:iolist_to_binary(io_lib:format("~p", [Term])).
status_metrics_example() ->
#{
'metrics_example' => #{
summary => <<"Showing a typical metrics example">>,
value =>
#{
resource_metrics => #{
matched => 0,
success => 0,
failed => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
},
node_resource_metrics => [
#{
node => node(),
metrics => #{
matched => 0,
success => 0,
failed => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
}
}
],
metrics => #{
total => 0,
allow => 0,
deny => 0,
nomatch => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
},
node_metrics => [
#{
node => node(),
metrics => #{
total => 0,
allow => 0,
deny => 0,
nomatch => 0,
rate => 0.0,
rate_last5m => 0.0,
rate_max => 0.0
}
}
],
status => connected,
node_status => [
#{
node => node(),
status => connected
}
]
}
}
}.
|
86b27c1d79ea3503bfddc4759989d8c4a51c1eacb3e282c91ea2fdc25a36ce98 | chaoxu/fancy-walks | UnionFind.hs |
import Control.Monad.ST
import Data.Array.ST
type UnionFind s = STUArray s Int Int
buildUF :: (Int, Int) -> ST s (UnionFind s)
buildUF bnds = newArray bnds (-1)
findUF :: UnionFind s -> Int -> ST s Int
findUF uf a = do
fa <- readArray uf a
if fa == -1
then return a
else do
ret <- findUF uf fa
writeArray uf a ret
return ret
mergeUF :: UnionFind s -> Int -> Int -> ST s Bool
mergeUF uf a b = do
fa <- findUF uf a
fb <- findUF uf b
if fa == fb
then return False
else do
writeArray uf fa fb
return True
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/snippets/UnionFind.hs | haskell |
import Control.Monad.ST
import Data.Array.ST
type UnionFind s = STUArray s Int Int
buildUF :: (Int, Int) -> ST s (UnionFind s)
buildUF bnds = newArray bnds (-1)
findUF :: UnionFind s -> Int -> ST s Int
findUF uf a = do
fa <- readArray uf a
if fa == -1
then return a
else do
ret <- findUF uf fa
writeArray uf a ret
return ret
mergeUF :: UnionFind s -> Int -> Int -> ST s Bool
mergeUF uf a b = do
fa <- findUF uf a
fb <- findUF uf b
if fa == fb
then return False
else do
writeArray uf fa fb
return True
| |
a21c85d640bae53492e85b206fd238567296ba92407e0ee0235615916be38fc1 | pablomarx/Thomas | runtime-functions.scm | * Copyright 1992 Digital Equipment Corporation
;* All Rights Reserved
;*
;* Permission to use, copy, and modify this software and its documentation is
;* hereby granted only under the following terms and conditions. Both the
;* above copyright notice and this permission notice must appear in all copies
;* of the software, derivative works or modified versions, and any portions
;* thereof, and both notices must appear in supporting documentation.
;*
;* Users of this software agree to the terms and conditions set forth herein,
* and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free
;* right and license under any changes, enhancements or extensions made to the
;* core functions of the software, including but not limited to those affording
;* compatibility with other hardware or software environments, but excluding
;* applications which incorporate this software. Users further agree to use
* their best efforts to return to Digital any such changes , enhancements or
* extensions that they make and inform Digital of noteworthy uses of this
* software . Correspondence should be provided to Digital at :
;*
* Director , Cambridge Research Lab
* Digital Equipment Corp
* One Kendall Square , Bldg 700
;* Cambridge MA 02139
;*
;* This software may be distributed (but not offered for sale or transferred
* for compensation ) to third parties , provided such third parties agree to
;* abide by the terms and conditions of this notice.
;*
* THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL
;* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
;* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
;* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
;* SOFTWARE.
$ I d : runtime - functions.scm , v 1.25 1992/09/11 21:23:40 jmiller Exp $
;;;; Miscellaneous Dylan Functions
;;;
Specialized MAKE for some built in classes
;;;
(add-method dylan:make
(dylan::function->method
(make-param-list `((CLASS ,(dylan::make-singleton <generic-function>)))
#F #F '(debug-name: required: rest?: key?:))
(lambda (class . rest)
class ; ignored
(let ((name (dylan::find-keyword rest 'debug-name:
(lambda ()
"Anonymous Generic Function")))
(nrequired
(dylan::find-keyword
rest 'required:
(lambda ()
(dylan-call dylan:error "(make (singleton <generic-function>)) -- required: not supplied" class rest))))
(rest? (dylan::find-keyword rest 'rest?: (lambda () #F)))
(keys (dylan::find-keyword rest 'key?: (lambda () #F))))
(dylan::create-generic-function name nrequired keys rest?)))))
(add-method dylan:make
(dylan::function->method
(make-param-list
`((CLASS ,(dylan::make-singleton <singleton>))) #F #F '(object:))
(lambda (class . rest)
class ; ignored
(let ((object (dylan::find-keyword
rest 'object:
(lambda ()
(dylan-call dylan:error "(make (singleton <singleton>)) -- object not supplied" class rest)))))
(dylan::make-singleton object)))))
(add-method dylan:make
(dylan::function->method
(make-param-list `((CLASS ,(dylan::make-singleton <complex>)))
#F #F '(real: imag: magnitude: angle:))
(lambda (class . rest)
class ; Ignored
(let ((real (dylan::find-keyword rest 'real: (lambda () #F)))
(imag (dylan::find-keyword rest 'imag: (lambda () #F)))
(mag (dylan::find-keyword rest 'magnitude: (lambda () #F)))
(angle (dylan::find-keyword rest 'angle: (lambda () #F))))
(cond ((and (not real) (not imag) (not mag) (not angle))
(dylan-call dylan:make-rectangular 0 0))
((and real (not imag) (not mag) (not angle))
(dylan-call dylan:make-rectangular real 0))
((and (not real) imag (not mag) (not angle))
(dylan-call dylan:make-rectangular 0 imag))
((and real imag (not mag) (not angle))
(dylan-call dylan:make-rectangular real imag))
((and (not real) (not imag) mag (not angle))
(dylan-call dylan:make-polar mag 0))
((and (not real) (not imag) (not mag) angle)
(dylan-call dylan:make-polar 0 angle))
((and (not real) (not imag) mag angle)
(dylan-call dylan:make-polar mag angle))
(else
(dylan-call dylan:error "(make (singleton <complex>)) -- invalid keyword combination" class rest)))))))
;;;
;;; Misc Generic Functions
;;;
(define dylan:find-method
(dylan::generic-fn 'find-method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)
(SPECIALIZERS ,<list>)) #F #F #F)
find-method))
(define dylan:generic-function-methods
(dylan::generic-fn 'generic-function-methods
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #F #F)
(lambda (generic-function)
(generic-function.methods generic-function))))
(define dylan:acosh
(dylan::generic-fn 'acosh
one-number
(lambda (z)
(log (+ z (* (+ z 1) (sqrt (/ (- z 1) (+ z 1)))))))))
(define dylan:asinh
(dylan::generic-fn 'asinh
one-number
(lambda (z)
(log (+ z (sqrt (+ 1 (* z z))))))))
(define dylan:atanh
(dylan::generic-fn 'atanh
one-number
(lambda (z)
(log (* (+ 1 z) (sqrt (/ 1 (- 1 (* z z)))))))))
(define dylan:cosh
(dylan::generic-fn 'cosh
one-number
(lambda (z)
(/ (+ (exp z) (exp (- z))) 2))))
(define dylan:sinh
(dylan::generic-fn 'sinh
one-number
(lambda (z)
(/ (- (exp z) (exp (- z))) 2))))
(define dylan:tanh
(dylan::generic-fn 'tanh
one-number
(lambda (z)
(/ (- (exp z) (exp (- z)))
(+ (exp z) (exp (- z)))))))
(define dylan:add-slot
(dylan::generic-fn 'add-slot
(make-param-list `((SLOT-OWNER ,<object>))
#F #F '(getter: setter: type: init-value:
init-function: init-keyword:
required-init-keyword: debug-name:
allocation:))
add-slot))
(define dylan:freeze-methods
(dylan::generic-fn 'freeze-methods
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #T #F)
(lambda (generic-function . specializers)
specializers ; Ignored for now
generic-function)))
(define dylan:function-arguments
(dylan::generic-fn 'function-arguments
(make-param-list `((FN ,<function>)) #F #F #F)
#F))
(begin
(add-method dylan:function-arguments
(dylan::dylan-callable->method
(make-param-list `((METHOD ,<method>)) #F #F #F)
(lambda (multiple-values next-method method)
(dylan-full-call dylan:values multiple-values next-method
(method.nrequired method)
(method.rest? method)
(method.keys method)))))
(add-method dylan:function-arguments
(dylan::dylan-callable->method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #F #F)
(lambda (multiple-values next-method generic-function)
(dylan-full-call dylan:values multiple-values next-method
(generic-function.nrequired generic-function)
(generic-function.rest? generic-function)
(generic-function.keys generic-function))))))
(define dylan:make-polar
(dylan::generic-fn 'make-polar two-reals
(lambda (magnitude angle)
(if (zero? angle)
magnitude
(+ (* magnitude (cos angle))
(* magnitude (sin angle) (get-+i)))))))
(define dylan:make-rectangular
(dylan::generic-fn 'make-rectangular two-reals
(lambda (real imaginary)
(if (zero? imaginary)
real
(+ real (* (get-+i) imaginary))))))
(define dylan:method-specializers
(dylan::generic-fn 'method-specializers
(make-param-list `((METHOD ,<method>)) #F #F #F)
(lambda (method) (method.specializers method))))
(define dylan:singleton
(dylan::generic-fn 'singleton one-object dylan::make-singleton))
(define dylan:sorted-applicable-methods
(dylan::generic-fn 'sorted-applicable-methods
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #T #F)
(lambda (generic-function . args)
(sorted-applicable-methods
(generic-function.methods generic-function)
args))))
(define dylan:remove-method
(dylan::generic-fn 'remove-method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)
(METHOD ,<method>)) #F #F #F)
(lambda (generic-function method)
(if (generic-function.read-only? generic-function)
(dylan-call dylan:error
"remove-method -- generic function is read-only"
generic-function method))
(delete-method! generic-function method))))
(define dylan:slot-descriptor
;; I'm ignoring the problem of making singletons of
;; Scheme-native immutable objects, and adding slots to the
;; singleton.
(dylan::generic-fn 'slot-descriptor
(make-param-list `((INSTANCE ,<object>)
(GETTER ,<generic-function>)) #F #F #F)
(lambda (obj getter)
(or (and (instance? obj)
(instance.singleton obj)
(same-slot-getter-in-slot-vector->slot
getter
(singleton.extra-slot-descriptors
(instance.singleton obj))))
(same-slot-getter-in-slot-vector->slot
getter
(class.slots (get-type obj)))))))
(define dylan:slot-value
(dylan::generic-fn 'slot-value
(make-param-list `((INSTANCE ,<object>)
(SLOT-DESC ,<slot-descriptor>)) #F #F #F)
(lambda (instance slot-desc)
(let ((allocation (slot.allocation slot-desc))
(loc (slot.data-location slot-desc)))
(case allocation
((INSTANCE) (vector-ref instance loc))
((CLASS) (vector-ref (class.class-data (car loc)) (cdr loc)))
((EACH-SUBCLASS) (vector-ref (get-type instance) loc))
((VIRTUAL) ((slot.getter slot-desc) instance))
((CONSTANT) loc)
(else (dylan-call dylan:error
"slot-value -- internal error"
slot-desc allocation)))))))
(define dylan:setter/slot-value/
(dylan::generic-fn 'slot-value
(make-param-list `((INSTANCE ,<object>)
(SLOT-DESC ,<slot-descriptor>)
(NEW-VALUE ,<object>)) #F #F #F)
(lambda (instance slot-desc new-value)
(if (not (match-specializer? new-value (slot.type slot-desc)))
(dylan-call dylan:error
"(setter slot-value) -- type conflict"
instance (slot.type slot-desc)
slot-desc new-value))
(let ((allocation (slot.allocation slot-desc))
(loc (slot.data-location slot-desc)))
(case allocation
((INSTANCE) (vector-set! instance loc new-value))
((CLASS)
(vector-set! (class.class-data (car loc)) (cdr loc) new-value))
((EACH-SUBCLASS) (vector-set! (get-type instance) loc new-value))
((VIRTUAL)
(let ((setter (slot.setter slot-desc)))
(if (not setter)
(dylan-call dylan:error
"(setter slot-value) -- no setter for virtual slot"
instance slot-desc new-value))
(setter instance new-value))
((slot.setter slot-desc) instance))
((CONSTANT)
(dylan-call dylan:error
"(setter slot-value) -- can't set a constant slot"
instance slot-desc new-value))
(else (dylan-call dylan:error
"(setter slot-value) -- internal error"
slot-desc allocation)))))))
(define dylan:make-read-only
(dylan::generic-fn 'make-read-only one-class
(lambda (class)
(set-class.read-only?! class #T)
class)))
(add-method dylan:make-read-only
(dylan::function->method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #F #F)
(lambda (generic-function)
(set-generic-function.read-only?! generic-function #T))))
(define dylan:seal
(dylan::generic-fn 'seal one-class
(lambda (class)
(set-class.sealed?! class #T)
class)))
(define dylan:remove-slot #F)
CRL additions
(define dylan:display (make-dylan-callable display 1))
(define dylan:newline (make-dylan-callable newline 0))
(define dylan:write-line (make-dylan-callable write-line 1))
(define dylan:print (make-dylan-callable write-line 1))
| null | https://raw.githubusercontent.com/pablomarx/Thomas/c8ab3f6fa92a9a39667fe37dfe060b651affb18e/kits/gambit/src/runtime-functions.scm | scheme | * All Rights Reserved
*
* Permission to use, copy, and modify this software and its documentation is
* hereby granted only under the following terms and conditions. Both the
* above copyright notice and this permission notice must appear in all copies
* of the software, derivative works or modified versions, and any portions
* thereof, and both notices must appear in supporting documentation.
*
* Users of this software agree to the terms and conditions set forth herein,
* right and license under any changes, enhancements or extensions made to the
* core functions of the software, including but not limited to those affording
* compatibility with other hardware or software environments, but excluding
* applications which incorporate this software. Users further agree to use
*
* Cambridge MA 02139
*
* This software may be distributed (but not offered for sale or transferred
* abide by the terms and conditions of this notice.
*
* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
Miscellaneous Dylan Functions
ignored
ignored
Ignored
Misc Generic Functions
Ignored for now
I'm ignoring the problem of making singletons of
Scheme-native immutable objects, and adding slots to the
singleton. | * Copyright 1992 Digital Equipment Corporation
* and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free
* their best efforts to return to Digital any such changes , enhancements or
* extensions that they make and inform Digital of noteworthy uses of this
* software . Correspondence should be provided to Digital at :
* Director , Cambridge Research Lab
* Digital Equipment Corp
* One Kendall Square , Bldg 700
* for compensation ) to third parties , provided such third parties agree to
* THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL
* PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
$ I d : runtime - functions.scm , v 1.25 1992/09/11 21:23:40 jmiller Exp $
Specialized MAKE for some built in classes
(add-method dylan:make
(dylan::function->method
(make-param-list `((CLASS ,(dylan::make-singleton <generic-function>)))
#F #F '(debug-name: required: rest?: key?:))
(lambda (class . rest)
(let ((name (dylan::find-keyword rest 'debug-name:
(lambda ()
"Anonymous Generic Function")))
(nrequired
(dylan::find-keyword
rest 'required:
(lambda ()
(dylan-call dylan:error "(make (singleton <generic-function>)) -- required: not supplied" class rest))))
(rest? (dylan::find-keyword rest 'rest?: (lambda () #F)))
(keys (dylan::find-keyword rest 'key?: (lambda () #F))))
(dylan::create-generic-function name nrequired keys rest?)))))
(add-method dylan:make
(dylan::function->method
(make-param-list
`((CLASS ,(dylan::make-singleton <singleton>))) #F #F '(object:))
(lambda (class . rest)
(let ((object (dylan::find-keyword
rest 'object:
(lambda ()
(dylan-call dylan:error "(make (singleton <singleton>)) -- object not supplied" class rest)))))
(dylan::make-singleton object)))))
(add-method dylan:make
(dylan::function->method
(make-param-list `((CLASS ,(dylan::make-singleton <complex>)))
#F #F '(real: imag: magnitude: angle:))
(lambda (class . rest)
(let ((real (dylan::find-keyword rest 'real: (lambda () #F)))
(imag (dylan::find-keyword rest 'imag: (lambda () #F)))
(mag (dylan::find-keyword rest 'magnitude: (lambda () #F)))
(angle (dylan::find-keyword rest 'angle: (lambda () #F))))
(cond ((and (not real) (not imag) (not mag) (not angle))
(dylan-call dylan:make-rectangular 0 0))
((and real (not imag) (not mag) (not angle))
(dylan-call dylan:make-rectangular real 0))
((and (not real) imag (not mag) (not angle))
(dylan-call dylan:make-rectangular 0 imag))
((and real imag (not mag) (not angle))
(dylan-call dylan:make-rectangular real imag))
((and (not real) (not imag) mag (not angle))
(dylan-call dylan:make-polar mag 0))
((and (not real) (not imag) (not mag) angle)
(dylan-call dylan:make-polar 0 angle))
((and (not real) (not imag) mag angle)
(dylan-call dylan:make-polar mag angle))
(else
(dylan-call dylan:error "(make (singleton <complex>)) -- invalid keyword combination" class rest)))))))
(define dylan:find-method
(dylan::generic-fn 'find-method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)
(SPECIALIZERS ,<list>)) #F #F #F)
find-method))
(define dylan:generic-function-methods
(dylan::generic-fn 'generic-function-methods
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #F #F)
(lambda (generic-function)
(generic-function.methods generic-function))))
(define dylan:acosh
(dylan::generic-fn 'acosh
one-number
(lambda (z)
(log (+ z (* (+ z 1) (sqrt (/ (- z 1) (+ z 1)))))))))
(define dylan:asinh
(dylan::generic-fn 'asinh
one-number
(lambda (z)
(log (+ z (sqrt (+ 1 (* z z))))))))
(define dylan:atanh
(dylan::generic-fn 'atanh
one-number
(lambda (z)
(log (* (+ 1 z) (sqrt (/ 1 (- 1 (* z z)))))))))
(define dylan:cosh
(dylan::generic-fn 'cosh
one-number
(lambda (z)
(/ (+ (exp z) (exp (- z))) 2))))
(define dylan:sinh
(dylan::generic-fn 'sinh
one-number
(lambda (z)
(/ (- (exp z) (exp (- z))) 2))))
(define dylan:tanh
(dylan::generic-fn 'tanh
one-number
(lambda (z)
(/ (- (exp z) (exp (- z)))
(+ (exp z) (exp (- z)))))))
(define dylan:add-slot
(dylan::generic-fn 'add-slot
(make-param-list `((SLOT-OWNER ,<object>))
#F #F '(getter: setter: type: init-value:
init-function: init-keyword:
required-init-keyword: debug-name:
allocation:))
add-slot))
(define dylan:freeze-methods
(dylan::generic-fn 'freeze-methods
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #T #F)
(lambda (generic-function . specializers)
generic-function)))
(define dylan:function-arguments
(dylan::generic-fn 'function-arguments
(make-param-list `((FN ,<function>)) #F #F #F)
#F))
(begin
(add-method dylan:function-arguments
(dylan::dylan-callable->method
(make-param-list `((METHOD ,<method>)) #F #F #F)
(lambda (multiple-values next-method method)
(dylan-full-call dylan:values multiple-values next-method
(method.nrequired method)
(method.rest? method)
(method.keys method)))))
(add-method dylan:function-arguments
(dylan::dylan-callable->method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #F #F)
(lambda (multiple-values next-method generic-function)
(dylan-full-call dylan:values multiple-values next-method
(generic-function.nrequired generic-function)
(generic-function.rest? generic-function)
(generic-function.keys generic-function))))))
(define dylan:make-polar
(dylan::generic-fn 'make-polar two-reals
(lambda (magnitude angle)
(if (zero? angle)
magnitude
(+ (* magnitude (cos angle))
(* magnitude (sin angle) (get-+i)))))))
(define dylan:make-rectangular
(dylan::generic-fn 'make-rectangular two-reals
(lambda (real imaginary)
(if (zero? imaginary)
real
(+ real (* (get-+i) imaginary))))))
(define dylan:method-specializers
(dylan::generic-fn 'method-specializers
(make-param-list `((METHOD ,<method>)) #F #F #F)
(lambda (method) (method.specializers method))))
(define dylan:singleton
(dylan::generic-fn 'singleton one-object dylan::make-singleton))
(define dylan:sorted-applicable-methods
(dylan::generic-fn 'sorted-applicable-methods
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #T #F)
(lambda (generic-function . args)
(sorted-applicable-methods
(generic-function.methods generic-function)
args))))
(define dylan:remove-method
(dylan::generic-fn 'remove-method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)
(METHOD ,<method>)) #F #F #F)
(lambda (generic-function method)
(if (generic-function.read-only? generic-function)
(dylan-call dylan:error
"remove-method -- generic function is read-only"
generic-function method))
(delete-method! generic-function method))))
(define dylan:slot-descriptor
(dylan::generic-fn 'slot-descriptor
(make-param-list `((INSTANCE ,<object>)
(GETTER ,<generic-function>)) #F #F #F)
(lambda (obj getter)
(or (and (instance? obj)
(instance.singleton obj)
(same-slot-getter-in-slot-vector->slot
getter
(singleton.extra-slot-descriptors
(instance.singleton obj))))
(same-slot-getter-in-slot-vector->slot
getter
(class.slots (get-type obj)))))))
(define dylan:slot-value
(dylan::generic-fn 'slot-value
(make-param-list `((INSTANCE ,<object>)
(SLOT-DESC ,<slot-descriptor>)) #F #F #F)
(lambda (instance slot-desc)
(let ((allocation (slot.allocation slot-desc))
(loc (slot.data-location slot-desc)))
(case allocation
((INSTANCE) (vector-ref instance loc))
((CLASS) (vector-ref (class.class-data (car loc)) (cdr loc)))
((EACH-SUBCLASS) (vector-ref (get-type instance) loc))
((VIRTUAL) ((slot.getter slot-desc) instance))
((CONSTANT) loc)
(else (dylan-call dylan:error
"slot-value -- internal error"
slot-desc allocation)))))))
(define dylan:setter/slot-value/
(dylan::generic-fn 'slot-value
(make-param-list `((INSTANCE ,<object>)
(SLOT-DESC ,<slot-descriptor>)
(NEW-VALUE ,<object>)) #F #F #F)
(lambda (instance slot-desc new-value)
(if (not (match-specializer? new-value (slot.type slot-desc)))
(dylan-call dylan:error
"(setter slot-value) -- type conflict"
instance (slot.type slot-desc)
slot-desc new-value))
(let ((allocation (slot.allocation slot-desc))
(loc (slot.data-location slot-desc)))
(case allocation
((INSTANCE) (vector-set! instance loc new-value))
((CLASS)
(vector-set! (class.class-data (car loc)) (cdr loc) new-value))
((EACH-SUBCLASS) (vector-set! (get-type instance) loc new-value))
((VIRTUAL)
(let ((setter (slot.setter slot-desc)))
(if (not setter)
(dylan-call dylan:error
"(setter slot-value) -- no setter for virtual slot"
instance slot-desc new-value))
(setter instance new-value))
((slot.setter slot-desc) instance))
((CONSTANT)
(dylan-call dylan:error
"(setter slot-value) -- can't set a constant slot"
instance slot-desc new-value))
(else (dylan-call dylan:error
"(setter slot-value) -- internal error"
slot-desc allocation)))))))
(define dylan:make-read-only
(dylan::generic-fn 'make-read-only one-class
(lambda (class)
(set-class.read-only?! class #T)
class)))
(add-method dylan:make-read-only
(dylan::function->method
(make-param-list `((GENERIC-FUNCTION ,<generic-function>)) #F #F #F)
(lambda (generic-function)
(set-generic-function.read-only?! generic-function #T))))
(define dylan:seal
(dylan::generic-fn 'seal one-class
(lambda (class)
(set-class.sealed?! class #T)
class)))
(define dylan:remove-slot #F)
CRL additions
(define dylan:display (make-dylan-callable display 1))
(define dylan:newline (make-dylan-callable newline 0))
(define dylan:write-line (make-dylan-callable write-line 1))
(define dylan:print (make-dylan-callable write-line 1))
|
cf61c3ac627f0ae135708ae767f3fae06d585d3d7e5b4e79d29870299eb5222e | mfoemmel/erlang-otp | egd_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2007 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online 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.
%%
%% %CopyrightEnd%
%%
-module(egd_SUITE).
-include("test_server.hrl").
%% Test server specific exports
-export([all/1]).
-export([init_per_suite/1, end_per_suite/1]).
-export([init_per_testcase/2, end_per_testcase/2]).
%% Test cases
-export([
image_create_and_destroy/1,
image_shape/1,
image_colors/1,
image_font/1,
image_png_compliant/1
]).
%% Default timetrap timeout (set in init_per_testcase)
-define(default_timeout, ?t:minutes(1)).
init_per_suite(Config) when is_list(Config) ->
{A1,A2,A3} = now(),
random:seed(A1, A2, A3),
Config.
end_per_suite(Config) when is_list(Config) ->
Config.
init_per_testcase(_Case, Config) ->
Dog = ?t:timetrap(?default_timeout),
[{max_size, 800}, {watchdog,Dog} | Config].
end_per_testcase(_Case, Config) ->
Dog = ?config(watchdog, Config),
?t:timetrap_cancel(Dog),
ok.
all(suite) ->
% Test cases
[
image_create_and_destroy,
image_shape,
image_colors,
image_font,
image_png_compliant
].
%%----------------------------------------------------------------------
%% Tests
%%----------------------------------------------------------------------
image_create_and_destroy(suite) ->
[];
image_create_and_destroy(doc) ->
["Image creation and destroy test."];
image_create_and_destroy(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
?line Image = egd:create(W, H),
?line ok = egd:destroy(Image),
ok.
image_colors(suite) ->
[];
image_colors(doc) ->
["Image color test."];
image_colors(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
?line Image = egd:create(W, H),
put(image_size, {W,H}),
RGB = get_rgb(),
?line Black = egd:color({0,0,0}),
?line Red = egd:color({255,0,0}),
?line Green = egd:color({0,255,0}),
?line Blue = egd:color({0,0,255}),
?line Random = egd:color(Image, RGB),
?line ok = egd:line(Image, get_point(), get_point(), Random),
?line ok = egd:line(Image, get_point(), get_point(), Red),
?line ok = egd:line(Image, get_point(), get_point(), Green),
?line ok = egd:line(Image, get_point(), get_point(), Black),
?line ok = egd:line(Image, get_point(), get_point(), Blue),
HtmlDefaultNames = [black,silver,gray,white,maroon,red,
purple,fuchia,green,lime,olive,yellow,navy,blue,teal,
aqua],
lists:foreach(fun
(ColorName) ->
?line Color = egd:color(ColorName),
?line ok = egd:line(Image, get_point(), get_point(), Color)
end, HtmlDefaultNames),
?line <<_/binary>> = egd:render(Image),
?line ok = egd:destroy(Image),
erase(image_size),
ok.
image_shape(suite) ->
[];
image_shape(doc) ->
["Image shape api test."];
image_shape(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
put(image_size, {W,H}),
?line Im = egd:create(W, H),
?line Fgc = egd:color({255,0,0}),
?line ok = egd:line(Im, get_point(), get_point(), Fgc),
?line ok = egd:rectangle(Im, get_point(), get_point(), Fgc),
?line ok = egd:filledEllipse(Im, get_point(), get_point(), Fgc),
?line ok = egd:arc(Im, get_point(), get_point(), Fgc),
?line ok = egd:arc(Im, get_point(), get_point(), 100, Fgc),
Pt1 = get_point(),
Pt2 = get_point(),
?line ok = egd:filledRectangle(Im, Pt1, Pt2, Fgc),
?line Bitmap = egd:render(Im, raw_bitmap),
?line ok = bitmap_point_has_color(Bitmap, {W,H}, Pt2, Fgc),
?line ok = bitmap_point_has_color(Bitmap, {W,H}, Pt1, Fgc),
?line ok = egd:destroy(Im),
erase(image_size),
ok.
image_font(suite) ->
[];
image_font(doc) ->
["Image font test."];
image_font(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
put(image_size, {W,H}),
?line Im = egd:create(W, H),
?line Fgc = egd:color({0,130,0}),
?line Filename = filename:join([code:priv_dir(percept),"fonts","6x11_latin1.wingsfont"]),
?line Font = egd_font:load(Filename),
% simple text
?line ok = egd:text(Im, get_point(), Font, "Hello World", Fgc),
?line <<_/binary>> = egd:render(Im, png),
& ' ( ) * + , -./ " , % Codes 32 - > 47
Codes 48 - > 57
Codes 58 - > 64
Codes 65 - > 90
Codes 91 - > 96
Codes 97 - > 122
Codes 123 - > 126
?line ok = egd:text(Im, get_point(), Font, GlyphStr1, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, NumericStr, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, GlyphStr2, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, AlphaBigStr, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, GlyphStr3, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, AlphaSmStr, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, GlyphStr4, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:destroy(Im),
erase(image_size),
ok.
image_png_compliant(suite) ->
[];
image_png_compliant(doc) ->
["Image png compliant test."];
image_png_compliant(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
put(image_size, {W,H}),
?line Im = egd:create(W, H),
?line Fgc = egd:color({0,0,0}),
?line ok = egd:filledRectangle(Im, get_point(), get_point(), Fgc),
?line Bin = egd:render(Im, png),
?line true = binary_is_png_compliant(Bin),
?line ok = egd:destroy(Im),
erase(image_size),
ok.
%%----------------------------------------------------------------------
%% Auxiliary tests
%%----------------------------------------------------------------------
bitmap_point_has_color(Bitmap, {W,_}, {X,Y}, C) ->
{CR,CG,CB,_} = egd_primitives:rgb_float2byte(C),
N = W*Y*3 + X*3,
<< _:N/binary, R,G,B, _/binary>> = Bitmap,
case {R,G,B} of
{CR,CG,CB} -> ok;
Other ->
io:format("bitmap_point_has_color: error color was ~p, should be ~p~n", [Other, {CR,CG,CB}]),
{error, {Other,{CR,CG,CB}}}
end.
%% jfif header by specification
2 bytes , length
5 bytes , identifier = " JFIF\0 "
2 bytes , version , ( major , minor )
1 byte , units
However , seems to start at 6 ( 7 with 1 - index ) ?
binary_is_jfif_compliant(JpegBin) ->
?line {Bin, _} = split_binary(JpegBin, 11),
List = binary_to_list(Bin),
case lists:sublist(List, 7, 4) of
"JFIF" -> true;
Other ->
io:format("img -> ~p~n", [Other]),
false
end.
binary_is_gif_compliant(GifBin) ->
?line {Bin, _} = split_binary(GifBin, 10),
List = binary_to_list(Bin),
case lists:sublist(List, 1,5) of
"GIF87" -> true;
Other ->
io:format("img -> ~p~n", [Other]),
false
end.
binary_is_png_compliant(PngBin) ->
?line {Bin, _} = split_binary(PngBin, 10),
List = binary_to_list(Bin),
case lists:sublist(List, 2,3) of
"PNG" -> true;
Other ->
io:format("img -> ~p~n", [Other]),
false
end.
%%----------------------------------------------------------------------
%% Auxiliary
%%----------------------------------------------------------------------
get_rgb() ->
R = random(255),
G = random(255),
B = random(255),
{R,G,B}.
get_angle() ->
random(359).
get_point() ->
get_point(get(image_size)).
get_point({W,H}) ->
X = random(W - 1),
Y = random(H - 1),
{X,Y}.
get_size(Max) ->
W = trunc(random(Max/2) + Max/2 + 1),
H = trunc(random(Max/2) + Max/2 + 1),
io:format("Image size will be ~p x ~p~n", [W,H]),
{W,H}.
get_points(N) ->
get_points(N, []).
get_points(0, Out) ->
Out;
get_points(N, Out) ->
get_points(N - 1, [get_point() | Out]).
random(N) -> trunc(random:uniform(trunc(N + 1)) - 1).
| null | https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/percept/test/egd_SUITE.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online 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.
%CopyrightEnd%
Test server specific exports
Test cases
Default timetrap timeout (set in init_per_testcase)
Test cases
----------------------------------------------------------------------
Tests
----------------------------------------------------------------------
simple text
Codes 32 - > 47
----------------------------------------------------------------------
Auxiliary tests
----------------------------------------------------------------------
jfif header by specification
----------------------------------------------------------------------
Auxiliary
---------------------------------------------------------------------- | Copyright Ericsson AB 2007 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang 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 "
-module(egd_SUITE).
-include("test_server.hrl").
-export([all/1]).
-export([init_per_suite/1, end_per_suite/1]).
-export([init_per_testcase/2, end_per_testcase/2]).
-export([
image_create_and_destroy/1,
image_shape/1,
image_colors/1,
image_font/1,
image_png_compliant/1
]).
-define(default_timeout, ?t:minutes(1)).
init_per_suite(Config) when is_list(Config) ->
{A1,A2,A3} = now(),
random:seed(A1, A2, A3),
Config.
end_per_suite(Config) when is_list(Config) ->
Config.
init_per_testcase(_Case, Config) ->
Dog = ?t:timetrap(?default_timeout),
[{max_size, 800}, {watchdog,Dog} | Config].
end_per_testcase(_Case, Config) ->
Dog = ?config(watchdog, Config),
?t:timetrap_cancel(Dog),
ok.
all(suite) ->
[
image_create_and_destroy,
image_shape,
image_colors,
image_font,
image_png_compliant
].
image_create_and_destroy(suite) ->
[];
image_create_and_destroy(doc) ->
["Image creation and destroy test."];
image_create_and_destroy(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
?line Image = egd:create(W, H),
?line ok = egd:destroy(Image),
ok.
image_colors(suite) ->
[];
image_colors(doc) ->
["Image color test."];
image_colors(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
?line Image = egd:create(W, H),
put(image_size, {W,H}),
RGB = get_rgb(),
?line Black = egd:color({0,0,0}),
?line Red = egd:color({255,0,0}),
?line Green = egd:color({0,255,0}),
?line Blue = egd:color({0,0,255}),
?line Random = egd:color(Image, RGB),
?line ok = egd:line(Image, get_point(), get_point(), Random),
?line ok = egd:line(Image, get_point(), get_point(), Red),
?line ok = egd:line(Image, get_point(), get_point(), Green),
?line ok = egd:line(Image, get_point(), get_point(), Black),
?line ok = egd:line(Image, get_point(), get_point(), Blue),
HtmlDefaultNames = [black,silver,gray,white,maroon,red,
purple,fuchia,green,lime,olive,yellow,navy,blue,teal,
aqua],
lists:foreach(fun
(ColorName) ->
?line Color = egd:color(ColorName),
?line ok = egd:line(Image, get_point(), get_point(), Color)
end, HtmlDefaultNames),
?line <<_/binary>> = egd:render(Image),
?line ok = egd:destroy(Image),
erase(image_size),
ok.
image_shape(suite) ->
[];
image_shape(doc) ->
["Image shape api test."];
image_shape(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
put(image_size, {W,H}),
?line Im = egd:create(W, H),
?line Fgc = egd:color({255,0,0}),
?line ok = egd:line(Im, get_point(), get_point(), Fgc),
?line ok = egd:rectangle(Im, get_point(), get_point(), Fgc),
?line ok = egd:filledEllipse(Im, get_point(), get_point(), Fgc),
?line ok = egd:arc(Im, get_point(), get_point(), Fgc),
?line ok = egd:arc(Im, get_point(), get_point(), 100, Fgc),
Pt1 = get_point(),
Pt2 = get_point(),
?line ok = egd:filledRectangle(Im, Pt1, Pt2, Fgc),
?line Bitmap = egd:render(Im, raw_bitmap),
?line ok = bitmap_point_has_color(Bitmap, {W,H}, Pt2, Fgc),
?line ok = bitmap_point_has_color(Bitmap, {W,H}, Pt1, Fgc),
?line ok = egd:destroy(Im),
erase(image_size),
ok.
image_font(suite) ->
[];
image_font(doc) ->
["Image font test."];
image_font(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
put(image_size, {W,H}),
?line Im = egd:create(W, H),
?line Fgc = egd:color({0,130,0}),
?line Filename = filename:join([code:priv_dir(percept),"fonts","6x11_latin1.wingsfont"]),
?line Font = egd_font:load(Filename),
?line ok = egd:text(Im, get_point(), Font, "Hello World", Fgc),
?line <<_/binary>> = egd:render(Im, png),
Codes 48 - > 57
Codes 58 - > 64
Codes 65 - > 90
Codes 91 - > 96
Codes 97 - > 122
Codes 123 - > 126
?line ok = egd:text(Im, get_point(), Font, GlyphStr1, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, NumericStr, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, GlyphStr2, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, AlphaBigStr, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, GlyphStr3, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, AlphaSmStr, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:text(Im, get_point(), Font, GlyphStr4, Fgc),
?line <<_/binary>> = egd:render(Im, png),
?line ok = egd:destroy(Im),
erase(image_size),
ok.
image_png_compliant(suite) ->
[];
image_png_compliant(doc) ->
["Image png compliant test."];
image_png_compliant(Config) when is_list(Config) ->
{W,H} = get_size(?config(max_size, Config)),
put(image_size, {W,H}),
?line Im = egd:create(W, H),
?line Fgc = egd:color({0,0,0}),
?line ok = egd:filledRectangle(Im, get_point(), get_point(), Fgc),
?line Bin = egd:render(Im, png),
?line true = binary_is_png_compliant(Bin),
?line ok = egd:destroy(Im),
erase(image_size),
ok.
bitmap_point_has_color(Bitmap, {W,_}, {X,Y}, C) ->
{CR,CG,CB,_} = egd_primitives:rgb_float2byte(C),
N = W*Y*3 + X*3,
<< _:N/binary, R,G,B, _/binary>> = Bitmap,
case {R,G,B} of
{CR,CG,CB} -> ok;
Other ->
io:format("bitmap_point_has_color: error color was ~p, should be ~p~n", [Other, {CR,CG,CB}]),
{error, {Other,{CR,CG,CB}}}
end.
2 bytes , length
5 bytes , identifier = " JFIF\0 "
2 bytes , version , ( major , minor )
1 byte , units
However , seems to start at 6 ( 7 with 1 - index ) ?
binary_is_jfif_compliant(JpegBin) ->
?line {Bin, _} = split_binary(JpegBin, 11),
List = binary_to_list(Bin),
case lists:sublist(List, 7, 4) of
"JFIF" -> true;
Other ->
io:format("img -> ~p~n", [Other]),
false
end.
binary_is_gif_compliant(GifBin) ->
?line {Bin, _} = split_binary(GifBin, 10),
List = binary_to_list(Bin),
case lists:sublist(List, 1,5) of
"GIF87" -> true;
Other ->
io:format("img -> ~p~n", [Other]),
false
end.
binary_is_png_compliant(PngBin) ->
?line {Bin, _} = split_binary(PngBin, 10),
List = binary_to_list(Bin),
case lists:sublist(List, 2,3) of
"PNG" -> true;
Other ->
io:format("img -> ~p~n", [Other]),
false
end.
get_rgb() ->
R = random(255),
G = random(255),
B = random(255),
{R,G,B}.
get_angle() ->
random(359).
get_point() ->
get_point(get(image_size)).
get_point({W,H}) ->
X = random(W - 1),
Y = random(H - 1),
{X,Y}.
get_size(Max) ->
W = trunc(random(Max/2) + Max/2 + 1),
H = trunc(random(Max/2) + Max/2 + 1),
io:format("Image size will be ~p x ~p~n", [W,H]),
{W,H}.
get_points(N) ->
get_points(N, []).
get_points(0, Out) ->
Out;
get_points(N, Out) ->
get_points(N - 1, [get_point() | Out]).
random(N) -> trunc(random:uniform(trunc(N + 1)) - 1).
|
89d5959bd155069c881e9f2dcbb03b8d356bac3977a1ae01505f52311102f805 | cenary-lang/cenary | CodegenError.hs | module Cenary.Codegen.CodegenError where
import Cenary.Syntax
import Data.Semigroup ((<>))
data ErrorDetails = NoDetails
| ExprDetails Expr
| StmtDetails Stmt
| TextDetails String
deriving Show -- TODO: we can use a manual instance declaration, actually.
data CodegenError =
MainFunctionDoesNotExist
| VariableNotDeclared String ErrorDetails
| VariableAlreadyDeclared String
| VariableNotDefined String
| TypeMismatch String PrimType PrimType
| ScopedTypeViolation String PrimType PrimType
| InternalError String
| WrongOperandTypes PrimType PrimType
| FuncArgLengthMismatch String Int Int
| ArrayElementsTypeMismatch PrimType PrimType
| EmptyArrayValue
| NonInitializedArrayAccess String
| NonInitializedArrayResize String
| IllegalArrAccess String PrimType
| SupportError String
| CannotResizeNonArray PrimType
| Custom String
| NoReturnStatement
instance Show CodegenError where
show (VariableNotDeclared var details) = "Variable " <> var <> " is not declared. Details: " ++ show details
show (VariableNotDefined var) = "Variable " <> var <> " is not defined."
show (VariableAlreadyDeclared var) = "Variable " <> var <> " is already declared."
show (TypeMismatch name expected actual) = "Type mismatch for variable "
<> name
<> ". Expected: "
<> show expected
<> " , actual: "
<> show actual
show (ScopedTypeViolation name global local) = "TypeScopeViolation for variable "
<> name
<> ". In global scope, it has "
<> show global
<> " while in local scope it has "
<> show local
show (InternalError err) = "InternalError: " <> err
show (WrongOperandTypes tyL tyR) = "Wrong operand types: "
<> "Expected a value of "
<> show tyL
<> " but a value of type "
<> show tyR
<> " is provided."
show (FuncArgLengthMismatch name expected given) = "Function "
<> name
<> " expected "
<> show expected
<> " arguments, but you have given "
<> show given
show (ArrayElementsTypeMismatch ty1 ty2) = "Array has elements from different types: type " <> show ty1 <> " and type " <> show ty2
show EmptyArrayValue = "Sorry! We can't handle type polymorphism right now, so you should not create empty arrays as right-hand-side values"
show (NonInitializedArrayAccess name) = "Array " <> name <> " is not initialized yet, and you wanted to access an element of it"
show (NonInitializedArrayResize name) = "Array " <> name <> " is not initialized yet, and you wanted to resize it"
show (IllegalArrAccess name ty) = "You wanted to access to variable " <> name <> " as if it's an array, but it's type is " <> show ty
show NoReturnStatement = "Functions should have return statement as their last statement"
show MainFunctionDoesNotExist = "Main function does not exist"
show (SupportError description) = "Not supported yet: " <> description
show (CannotResizeNonArray ty) = "You tried to resize a variable of type " <> show ty <> ", only array types are resizable, are you sure you know what you are doing?"
show (Custom err) = "Non-specialized error: " <> err
| null | https://raw.githubusercontent.com/cenary-lang/cenary/bf5ab4ac6bbc2353b072d32de2f3bc86cbc88266/src/Cenary/Codegen/CodegenError.hs | haskell | TODO: we can use a manual instance declaration, actually. | module Cenary.Codegen.CodegenError where
import Cenary.Syntax
import Data.Semigroup ((<>))
data ErrorDetails = NoDetails
| ExprDetails Expr
| StmtDetails Stmt
| TextDetails String
data CodegenError =
MainFunctionDoesNotExist
| VariableNotDeclared String ErrorDetails
| VariableAlreadyDeclared String
| VariableNotDefined String
| TypeMismatch String PrimType PrimType
| ScopedTypeViolation String PrimType PrimType
| InternalError String
| WrongOperandTypes PrimType PrimType
| FuncArgLengthMismatch String Int Int
| ArrayElementsTypeMismatch PrimType PrimType
| EmptyArrayValue
| NonInitializedArrayAccess String
| NonInitializedArrayResize String
| IllegalArrAccess String PrimType
| SupportError String
| CannotResizeNonArray PrimType
| Custom String
| NoReturnStatement
instance Show CodegenError where
show (VariableNotDeclared var details) = "Variable " <> var <> " is not declared. Details: " ++ show details
show (VariableNotDefined var) = "Variable " <> var <> " is not defined."
show (VariableAlreadyDeclared var) = "Variable " <> var <> " is already declared."
show (TypeMismatch name expected actual) = "Type mismatch for variable "
<> name
<> ". Expected: "
<> show expected
<> " , actual: "
<> show actual
show (ScopedTypeViolation name global local) = "TypeScopeViolation for variable "
<> name
<> ". In global scope, it has "
<> show global
<> " while in local scope it has "
<> show local
show (InternalError err) = "InternalError: " <> err
show (WrongOperandTypes tyL tyR) = "Wrong operand types: "
<> "Expected a value of "
<> show tyL
<> " but a value of type "
<> show tyR
<> " is provided."
show (FuncArgLengthMismatch name expected given) = "Function "
<> name
<> " expected "
<> show expected
<> " arguments, but you have given "
<> show given
show (ArrayElementsTypeMismatch ty1 ty2) = "Array has elements from different types: type " <> show ty1 <> " and type " <> show ty2
show EmptyArrayValue = "Sorry! We can't handle type polymorphism right now, so you should not create empty arrays as right-hand-side values"
show (NonInitializedArrayAccess name) = "Array " <> name <> " is not initialized yet, and you wanted to access an element of it"
show (NonInitializedArrayResize name) = "Array " <> name <> " is not initialized yet, and you wanted to resize it"
show (IllegalArrAccess name ty) = "You wanted to access to variable " <> name <> " as if it's an array, but it's type is " <> show ty
show NoReturnStatement = "Functions should have return statement as their last statement"
show MainFunctionDoesNotExist = "Main function does not exist"
show (SupportError description) = "Not supported yet: " <> description
show (CannotResizeNonArray ty) = "You tried to resize a variable of type " <> show ty <> ", only array types are resizable, are you sure you know what you are doing?"
show (Custom err) = "Non-specialized error: " <> err
|
915184a634bec7104f804563972a6d745c88ce38a8881d217fb049ce2e6adcad | hammerlab/biokepi | ttfi_pipeline.ml | (** This test uses the high-level EDSL and tries different compilation targets,
but does not produce runnable workflows.
The workflow itself is voluntarily too big and abuses lambda expressions.
*)
open Nonstd
module type TEST_PIPELINE =
functor (Bfx : Biokepi.EDSL.Semantics) ->
sig
val run : unit -> unit Bfx.observation
end
module Run_test(Test_pipeline : TEST_PIPELINE) = struct
let write_file file ~content =
let out_file = open_out file in
try
output_string out_file content;
close_out out_file
with _ ->
close_out out_file
let cmdf fmt =
ksprintf (fun s ->
printf "CMD: %s\n%!" s;
match Sys.command s with
| 0 -> ()
| other -> ksprintf failwith "non-zero-exit: %s -> %d" s other) fmt
let (//) = Filename.concat
let test_dir = "_build/ttfi-test-results/"
let main prefix =
let start_time = Unix.gettimeofday () in
cmdf "mkdir -p %s" test_dir;
let results = ref [] in
let add_result fmt = ksprintf (fun s -> results := s :: !results) fmt in
let add_result_file name path =
let size =
let s = Unix.stat path in
match s.Unix.st_size with
| 0 -> "EMPTY"
| small when small < 1024 -> sprintf "%d B" small
| avg when avg < (1024 * 1024) ->
sprintf "%.2f KB" (float avg /. 1024.)
| big ->
sprintf "%.2f MB" (float big /. (1024. *. 1024.))
in
add_result "%s: `%s` (%s)" name path size;
in
let output_path suffix = test_dir // prefix ^ suffix in
begin
let module Display_pipeline = Test_pipeline(Biokepi.EDSL.Compile.To_display) in
let pseudocode = output_path "-pseudocode.txt" in
write_file pseudocode
~content:(Display_pipeline.run () |> SmartPrint.to_string 80 2);
add_result_file "Pseudo-code" pseudocode;
end;
begin
let module Jsonize_pipeline =
Test_pipeline(Biokepi.EDSL.Compile.To_json) in
let json = output_path ".json" in
write_file json
~content:(Jsonize_pipeline.run ()
|> Yojson.Basic.pretty_to_string ~std:true);
add_result_file "JSON" json;
end;
let output_dot sm dot png =
try
let out = open_out dot in
SmartPrint.to_out_channel 80 2 out sm;
close_out out;
add_result_file "DOT" dot;
let dotlog = png ^ ".log" in
cmdf "dot -v -x -Tpng %s -o %s > %s 2>&1" dot png dotlog;
add_result_file "PNG" png;
with e ->
add_result "FAILED TO OUTPUT: %s (%s)" dot (Printexc.to_string e);
in
begin
let module Dotize_pipeline = Test_pipeline(Biokepi.EDSL.Compile.To_dot) in
let sm_dot =
Dotize_pipeline.run () Biokepi.EDSL.Compile.To_dot.default_parameters in
let dot = output_path "-1.dot" in
let png = output_path "-1.png" in
output_dot sm_dot dot png
end;
begin
let module Dotize_twice_beta_reduced_pipeline =
Test_pipeline(
Biokepi.EDSL.Transform.Apply_functions(
Biokepi.EDSL.Transform.Apply_functions(
Biokepi.EDSL.Compile.To_dot
)
)
)
in
let dot = output_path "-double-beta.dot" in
let sm_dot =
Dotize_twice_beta_reduced_pipeline.run ()
~parameters:Biokepi.EDSL.Compile.To_dot.default_parameters in
let png = output_path "-double-beta.png" in
output_dot sm_dot dot png
end;
begin
let module Workflow_compiler =
Biokepi.EDSL.Compile.To_workflow.Make(struct
include Biokepi.EDSL.Compile.To_workflow.Defaults
let processors = 42
let work_dir = "/work/dir/"
let results_dir = Some "/result/dir"
let machine =
Biokepi.Setup.Build_machine.create
"ssh/"
end)
in
let module Ketrew_pipeline = Test_pipeline(Workflow_compiler) in
let workflow =
Ketrew_pipeline.run ()
|> Biokepi.EDSL.Compile.To_workflow.get_workflow
~name:"Biokepi TTFI test top-level node"
in
ignore workflow
end;
let end_time = Unix.gettimeofday () in
add_result "Total-time: %.2f s" (end_time -. start_time);
List.rev !results
end
module Pipeline_insane (Bfx : Biokepi.EDSL.Semantics) = struct
let fastq_list ~dataset files =
List.map files ~f:begin function
| `Pair (r1, r2) ->
if Filename.check_suffix r1 ".gz"
|| Filename.check_suffix r1 ".fqz"
then
Bfx.(fastq_gz ~sample_name:dataset
~r1:(input_url r1) ~r2:(input_url r2) () |> gunzip)
else
Bfx.(fastq ~sample_name:dataset
~r1:(input_url r1) ~r2:(input_url r2) ())
end
|> Bfx.list
let every_vc_on_fastqs ~reference_build ~normal ~tumor =
let aligner which_one =
Bfx.lambda (fun fq -> which_one ~reference_build fq) in
let align_list how (list_of_fastqs : [ `Fastq ] list Bfx.repr) =
Bfx.list_map list_of_fastqs ~f:how |> Bfx.merge_bams
in
let aligners = Bfx.list [
aligner @@ Bfx.bwa_aln ?configuration: None;
aligner @@ Bfx.bwa_mem ?configuration: None;
aligner @@ Bfx.hisat ~configuration:Biokepi.Tools.Hisat.Configuration.default_v1;
aligner @@ Bfx.hisat ~configuration:Biokepi.Tools.Hisat.Configuration.default_v2;
aligner @@ Bfx.star ~configuration:Biokepi.Tools.Star.Configuration.Align.default;
aligner @@ Bfx.mosaik;
aligner @@ (fun ~reference_build fastq ->
Bfx.bwa_aln ~reference_build fastq
|> Bfx.bam_to_fastq `PE
|> Bfx.bwa_mem ?configuration: None ~reference_build
);
] in
let somatic_of_pair how =
Bfx.lambda (fun pair ->
let normal = Bfx.pair_first pair in
let tumor = Bfx.pair_second pair in
how ~normal ~tumor ())
in
let somatic_vcs =
List.map ~f:somatic_of_pair [
Bfx.mutect
~configuration:Biokepi.Tools.Mutect.Configuration.default;
Bfx.mutect2
~configuration:Biokepi.Tools.Gatk.Configuration.Mutect2.default;
Bfx.somaticsniper
~configuration:Biokepi.Tools.Somaticsniper.Configuration.default;
Bfx.strelka
~configuration:Biokepi.Tools.Strelka.Configuration.default;
Bfx.varscan_somatic ?adjust_mapq:None;
Bfx.muse
~configuration:Biokepi.Tools.Muse.Configuration.wes;
Bfx.virmid
~configuration:Biokepi.Tools.Virmid.Configuration.default;
]
in
let aligned_pairs
: (([ `Fastq ] list * [ `Fastq ] list) -> ([ `Bam ] * [ `Bam ]) list) Bfx.repr =
Bfx.lambda (fun pair ->
Bfx.list_map aligners ~f:(
Bfx.lambda (fun (al : ([ `Fastq ] -> [ `Bam ]) Bfx.repr) ->
Bfx.pair
(align_list al (Bfx.pair_first pair : [ `Fastq ] list Bfx.repr))
(align_list al (Bfx.pair_second pair))
)
)
)
in
let vcfs =
Bfx.lambda (fun pair ->
List.map somatic_vcs ~f:(fun vc ->
Bfx.list_map (Bfx.apply aligned_pairs pair) ~f:(
Bfx.lambda (fun bam_pair ->
let (||>) x f = Bfx.apply f x in
let indelreal =
Bfx.lambda (fun pair ->
Bfx.gatk_indel_realigner_joint
~configuration: Biokepi.Tools.Gatk.Configuration.default_indel_realigner
pair)
in
let map_pair f =
Bfx.lambda (fun pair ->
let b1 = Bfx.pair_first pair in
let b2 = Bfx.pair_second pair in
Bfx.pair (f b1) (f b2)
)
in
let bqsr_pair =
Bfx.gatk_bqsr
~configuration: Biokepi.Tools.Gatk.Configuration.default_bqsr
|> map_pair in
let markdups_pair =
Bfx.picard_mark_duplicates
~configuration:Biokepi.Tools.Picard.Mark_duplicates_settings.default
|> map_pair in
bam_pair ||> markdups_pair ||> indelreal ||> bqsr_pair ||> vc
||> Bfx.lambda Bfx.to_unit
)
)
)
|> Bfx.list
)
in
let workflow_of_pair =
Bfx.lambda (fun pair ->
Bfx.list [
(Bfx.apply aligned_pairs pair
|> Bfx.list_map ~f:(Bfx.lambda (fun p ->
Bfx.pair_first p
|> Bfx.stringtie
~configuration:Biokepi.Tools.Stringtie.Configuration.default)
)) |> Bfx.to_unit;
Bfx.apply vcfs pair |> Bfx.to_unit;
begin
Bfx.apply
(Bfx.lambda (fun p -> Bfx.pair_first p |> Bfx.concat |> Bfx.seq2hla))
pair
|> Bfx.to_unit
end;
begin
Bfx.apply
(Bfx.lambda (fun p -> Bfx.pair_first p |> Bfx.concat |> Bfx.fastqc))
pair
|> Bfx.to_unit
end;
begin
Bfx.apply
(Bfx.lambda (fun p -> Bfx.pair_second p |> Bfx.concat |> Bfx.optitype `RNA))
pair
|> Bfx.to_unit
end;
begin
Bfx.apply aligned_pairs pair
|> Bfx.list_map ~f:(Bfx.lambda (fun p ->
Bfx.pair_first p
|> Bfx.gatk_haplotype_caller
))
|> Bfx.to_unit
end;
]
|> Bfx.to_unit
)
in
Bfx.apply workflow_of_pair (Bfx.pair normal tumor)
let normal =
("normal-1", [
`Pair ("/input/normal-1-001-r1.fastq", "/input/normal-1-001-r2.fastq");
`Pair ("/input/normal-1-002-r1.fastq", "/input/normal-1-002-r2.fastq");
`Pair ("/input/normal-1-003-r1.fqz", "/input/normal-1-003-r2.fqz");
])
let tumor =
("tumor-1", [
`Pair ("/input/tumor-1-001-r1.fastq.gz", "/input/tumor-1-001-r2.fastq.gz");
`Pair ("/input/tumor-1-002-r1.fastq.gz", "/input/tumor-1-002-r2.fastq.gz");
])
let run () =
Bfx.observe (fun () ->
every_vc_on_fastqs
~reference_build:"b37"
~normal:(fastq_list ~dataset:(fst normal) (snd normal))
~tumor:(fastq_list ~dataset:(fst tumor) (snd tumor))
)
end
module Somatic_simplish(Bfx: Biokepi.EDSL.Semantics) = struct
module Insane_library = Pipeline_insane(Bfx)
let vc =
let normal =
Insane_library.(fastq_list ~dataset:(fst normal) (snd normal))
in
let tumor =
Insane_library.(fastq_list ~dataset:(fst tumor) (snd tumor))
in
let ot_hla =
normal |> Bfx.concat |> Bfx.optitype `DNA |> Bfx.to_unit
in
let align fastq =
Bfx.list_map fastq ~f:(Bfx.lambda (fun fq ->
Bfx.bwa_mem fq
~reference_build:"b37"
|> Bfx.picard_mark_duplicates
~configuration:Biokepi.Tools.Picard.Mark_duplicates_settings.default
)) in
let normal_bam = align normal |> Bfx.merge_bams in
let tumor_bam = align tumor |> Bfx.merge_bams in
let bam_pair = Bfx.pair normal_bam tumor_bam in
let indel_realigned_pair =
Bfx.gatk_indel_realigner_joint bam_pair
~configuration: Biokepi.Tools.Gatk.Configuration.default_indel_realigner
in
let final_normal_bam =
Bfx.pair_first indel_realigned_pair
|> Bfx.gatk_bqsr
~configuration: Biokepi.Tools.Gatk.Configuration.default_bqsr
in
let final_tumor_bam =
Bfx.pair_second indel_realigned_pair
|> Bfx.gatk_bqsr
~configuration: Biokepi.Tools.Gatk.Configuration.default_bqsr
in
let vcfs =
let normal, tumor = final_normal_bam, final_tumor_bam in
Bfx.list [
Bfx.mutect ~normal ~tumor ()
|> Bfx.save ~name:"Mutect VCF";
Bfx.somaticsniper ~normal ~tumor ()
|> Bfx.save ~name:"SS VCF";
Bfx.strelka ~normal ~tumor ()
|> Bfx.save ~name:"Strelka VCF";
] in
Bfx.list [
Bfx.to_unit vcfs;
ot_hla;
] |> Bfx.to_unit
let run () =
Bfx.observe (fun () -> vc)
end
let () =
let module Go_insane = Run_test(Pipeline_insane) in
let insane_result = Go_insane.main "pipeline-insane" in
let module Go_simple_somatic = Run_test(Somatic_simplish) in
let simple_somatic_result = Go_simple_somatic.main "pipeline-simple-somatic" in
let display_result mod_name results =
printf "- `%s`:\n%s\n%!"
mod_name
(List.map results ~f:(sprintf " * %s\n") |> String.concat "");
in
printf "\n### Test results:\n\n";
display_result "Pipeline_insane" insane_result;
display_result "Somatic_simplish" simple_somatic_result;
()
| null | https://raw.githubusercontent.com/hammerlab/biokepi/d64eb2c891b41bda3444445cd2adf4e3251725d4/src/test/ttfi_pipeline.ml | ocaml | * This test uses the high-level EDSL and tries different compilation targets,
but does not produce runnable workflows.
The workflow itself is voluntarily too big and abuses lambda expressions.
| open Nonstd
module type TEST_PIPELINE =
functor (Bfx : Biokepi.EDSL.Semantics) ->
sig
val run : unit -> unit Bfx.observation
end
module Run_test(Test_pipeline : TEST_PIPELINE) = struct
let write_file file ~content =
let out_file = open_out file in
try
output_string out_file content;
close_out out_file
with _ ->
close_out out_file
let cmdf fmt =
ksprintf (fun s ->
printf "CMD: %s\n%!" s;
match Sys.command s with
| 0 -> ()
| other -> ksprintf failwith "non-zero-exit: %s -> %d" s other) fmt
let (//) = Filename.concat
let test_dir = "_build/ttfi-test-results/"
let main prefix =
let start_time = Unix.gettimeofday () in
cmdf "mkdir -p %s" test_dir;
let results = ref [] in
let add_result fmt = ksprintf (fun s -> results := s :: !results) fmt in
let add_result_file name path =
let size =
let s = Unix.stat path in
match s.Unix.st_size with
| 0 -> "EMPTY"
| small when small < 1024 -> sprintf "%d B" small
| avg when avg < (1024 * 1024) ->
sprintf "%.2f KB" (float avg /. 1024.)
| big ->
sprintf "%.2f MB" (float big /. (1024. *. 1024.))
in
add_result "%s: `%s` (%s)" name path size;
in
let output_path suffix = test_dir // prefix ^ suffix in
begin
let module Display_pipeline = Test_pipeline(Biokepi.EDSL.Compile.To_display) in
let pseudocode = output_path "-pseudocode.txt" in
write_file pseudocode
~content:(Display_pipeline.run () |> SmartPrint.to_string 80 2);
add_result_file "Pseudo-code" pseudocode;
end;
begin
let module Jsonize_pipeline =
Test_pipeline(Biokepi.EDSL.Compile.To_json) in
let json = output_path ".json" in
write_file json
~content:(Jsonize_pipeline.run ()
|> Yojson.Basic.pretty_to_string ~std:true);
add_result_file "JSON" json;
end;
let output_dot sm dot png =
try
let out = open_out dot in
SmartPrint.to_out_channel 80 2 out sm;
close_out out;
add_result_file "DOT" dot;
let dotlog = png ^ ".log" in
cmdf "dot -v -x -Tpng %s -o %s > %s 2>&1" dot png dotlog;
add_result_file "PNG" png;
with e ->
add_result "FAILED TO OUTPUT: %s (%s)" dot (Printexc.to_string e);
in
begin
let module Dotize_pipeline = Test_pipeline(Biokepi.EDSL.Compile.To_dot) in
let sm_dot =
Dotize_pipeline.run () Biokepi.EDSL.Compile.To_dot.default_parameters in
let dot = output_path "-1.dot" in
let png = output_path "-1.png" in
output_dot sm_dot dot png
end;
begin
let module Dotize_twice_beta_reduced_pipeline =
Test_pipeline(
Biokepi.EDSL.Transform.Apply_functions(
Biokepi.EDSL.Transform.Apply_functions(
Biokepi.EDSL.Compile.To_dot
)
)
)
in
let dot = output_path "-double-beta.dot" in
let sm_dot =
Dotize_twice_beta_reduced_pipeline.run ()
~parameters:Biokepi.EDSL.Compile.To_dot.default_parameters in
let png = output_path "-double-beta.png" in
output_dot sm_dot dot png
end;
begin
let module Workflow_compiler =
Biokepi.EDSL.Compile.To_workflow.Make(struct
include Biokepi.EDSL.Compile.To_workflow.Defaults
let processors = 42
let work_dir = "/work/dir/"
let results_dir = Some "/result/dir"
let machine =
Biokepi.Setup.Build_machine.create
"ssh/"
end)
in
let module Ketrew_pipeline = Test_pipeline(Workflow_compiler) in
let workflow =
Ketrew_pipeline.run ()
|> Biokepi.EDSL.Compile.To_workflow.get_workflow
~name:"Biokepi TTFI test top-level node"
in
ignore workflow
end;
let end_time = Unix.gettimeofday () in
add_result "Total-time: %.2f s" (end_time -. start_time);
List.rev !results
end
module Pipeline_insane (Bfx : Biokepi.EDSL.Semantics) = struct
let fastq_list ~dataset files =
List.map files ~f:begin function
| `Pair (r1, r2) ->
if Filename.check_suffix r1 ".gz"
|| Filename.check_suffix r1 ".fqz"
then
Bfx.(fastq_gz ~sample_name:dataset
~r1:(input_url r1) ~r2:(input_url r2) () |> gunzip)
else
Bfx.(fastq ~sample_name:dataset
~r1:(input_url r1) ~r2:(input_url r2) ())
end
|> Bfx.list
let every_vc_on_fastqs ~reference_build ~normal ~tumor =
let aligner which_one =
Bfx.lambda (fun fq -> which_one ~reference_build fq) in
let align_list how (list_of_fastqs : [ `Fastq ] list Bfx.repr) =
Bfx.list_map list_of_fastqs ~f:how |> Bfx.merge_bams
in
let aligners = Bfx.list [
aligner @@ Bfx.bwa_aln ?configuration: None;
aligner @@ Bfx.bwa_mem ?configuration: None;
aligner @@ Bfx.hisat ~configuration:Biokepi.Tools.Hisat.Configuration.default_v1;
aligner @@ Bfx.hisat ~configuration:Biokepi.Tools.Hisat.Configuration.default_v2;
aligner @@ Bfx.star ~configuration:Biokepi.Tools.Star.Configuration.Align.default;
aligner @@ Bfx.mosaik;
aligner @@ (fun ~reference_build fastq ->
Bfx.bwa_aln ~reference_build fastq
|> Bfx.bam_to_fastq `PE
|> Bfx.bwa_mem ?configuration: None ~reference_build
);
] in
let somatic_of_pair how =
Bfx.lambda (fun pair ->
let normal = Bfx.pair_first pair in
let tumor = Bfx.pair_second pair in
how ~normal ~tumor ())
in
let somatic_vcs =
List.map ~f:somatic_of_pair [
Bfx.mutect
~configuration:Biokepi.Tools.Mutect.Configuration.default;
Bfx.mutect2
~configuration:Biokepi.Tools.Gatk.Configuration.Mutect2.default;
Bfx.somaticsniper
~configuration:Biokepi.Tools.Somaticsniper.Configuration.default;
Bfx.strelka
~configuration:Biokepi.Tools.Strelka.Configuration.default;
Bfx.varscan_somatic ?adjust_mapq:None;
Bfx.muse
~configuration:Biokepi.Tools.Muse.Configuration.wes;
Bfx.virmid
~configuration:Biokepi.Tools.Virmid.Configuration.default;
]
in
let aligned_pairs
: (([ `Fastq ] list * [ `Fastq ] list) -> ([ `Bam ] * [ `Bam ]) list) Bfx.repr =
Bfx.lambda (fun pair ->
Bfx.list_map aligners ~f:(
Bfx.lambda (fun (al : ([ `Fastq ] -> [ `Bam ]) Bfx.repr) ->
Bfx.pair
(align_list al (Bfx.pair_first pair : [ `Fastq ] list Bfx.repr))
(align_list al (Bfx.pair_second pair))
)
)
)
in
let vcfs =
Bfx.lambda (fun pair ->
List.map somatic_vcs ~f:(fun vc ->
Bfx.list_map (Bfx.apply aligned_pairs pair) ~f:(
Bfx.lambda (fun bam_pair ->
let (||>) x f = Bfx.apply f x in
let indelreal =
Bfx.lambda (fun pair ->
Bfx.gatk_indel_realigner_joint
~configuration: Biokepi.Tools.Gatk.Configuration.default_indel_realigner
pair)
in
let map_pair f =
Bfx.lambda (fun pair ->
let b1 = Bfx.pair_first pair in
let b2 = Bfx.pair_second pair in
Bfx.pair (f b1) (f b2)
)
in
let bqsr_pair =
Bfx.gatk_bqsr
~configuration: Biokepi.Tools.Gatk.Configuration.default_bqsr
|> map_pair in
let markdups_pair =
Bfx.picard_mark_duplicates
~configuration:Biokepi.Tools.Picard.Mark_duplicates_settings.default
|> map_pair in
bam_pair ||> markdups_pair ||> indelreal ||> bqsr_pair ||> vc
||> Bfx.lambda Bfx.to_unit
)
)
)
|> Bfx.list
)
in
let workflow_of_pair =
Bfx.lambda (fun pair ->
Bfx.list [
(Bfx.apply aligned_pairs pair
|> Bfx.list_map ~f:(Bfx.lambda (fun p ->
Bfx.pair_first p
|> Bfx.stringtie
~configuration:Biokepi.Tools.Stringtie.Configuration.default)
)) |> Bfx.to_unit;
Bfx.apply vcfs pair |> Bfx.to_unit;
begin
Bfx.apply
(Bfx.lambda (fun p -> Bfx.pair_first p |> Bfx.concat |> Bfx.seq2hla))
pair
|> Bfx.to_unit
end;
begin
Bfx.apply
(Bfx.lambda (fun p -> Bfx.pair_first p |> Bfx.concat |> Bfx.fastqc))
pair
|> Bfx.to_unit
end;
begin
Bfx.apply
(Bfx.lambda (fun p -> Bfx.pair_second p |> Bfx.concat |> Bfx.optitype `RNA))
pair
|> Bfx.to_unit
end;
begin
Bfx.apply aligned_pairs pair
|> Bfx.list_map ~f:(Bfx.lambda (fun p ->
Bfx.pair_first p
|> Bfx.gatk_haplotype_caller
))
|> Bfx.to_unit
end;
]
|> Bfx.to_unit
)
in
Bfx.apply workflow_of_pair (Bfx.pair normal tumor)
let normal =
("normal-1", [
`Pair ("/input/normal-1-001-r1.fastq", "/input/normal-1-001-r2.fastq");
`Pair ("/input/normal-1-002-r1.fastq", "/input/normal-1-002-r2.fastq");
`Pair ("/input/normal-1-003-r1.fqz", "/input/normal-1-003-r2.fqz");
])
let tumor =
("tumor-1", [
`Pair ("/input/tumor-1-001-r1.fastq.gz", "/input/tumor-1-001-r2.fastq.gz");
`Pair ("/input/tumor-1-002-r1.fastq.gz", "/input/tumor-1-002-r2.fastq.gz");
])
let run () =
Bfx.observe (fun () ->
every_vc_on_fastqs
~reference_build:"b37"
~normal:(fastq_list ~dataset:(fst normal) (snd normal))
~tumor:(fastq_list ~dataset:(fst tumor) (snd tumor))
)
end
module Somatic_simplish(Bfx: Biokepi.EDSL.Semantics) = struct
module Insane_library = Pipeline_insane(Bfx)
let vc =
let normal =
Insane_library.(fastq_list ~dataset:(fst normal) (snd normal))
in
let tumor =
Insane_library.(fastq_list ~dataset:(fst tumor) (snd tumor))
in
let ot_hla =
normal |> Bfx.concat |> Bfx.optitype `DNA |> Bfx.to_unit
in
let align fastq =
Bfx.list_map fastq ~f:(Bfx.lambda (fun fq ->
Bfx.bwa_mem fq
~reference_build:"b37"
|> Bfx.picard_mark_duplicates
~configuration:Biokepi.Tools.Picard.Mark_duplicates_settings.default
)) in
let normal_bam = align normal |> Bfx.merge_bams in
let tumor_bam = align tumor |> Bfx.merge_bams in
let bam_pair = Bfx.pair normal_bam tumor_bam in
let indel_realigned_pair =
Bfx.gatk_indel_realigner_joint bam_pair
~configuration: Biokepi.Tools.Gatk.Configuration.default_indel_realigner
in
let final_normal_bam =
Bfx.pair_first indel_realigned_pair
|> Bfx.gatk_bqsr
~configuration: Biokepi.Tools.Gatk.Configuration.default_bqsr
in
let final_tumor_bam =
Bfx.pair_second indel_realigned_pair
|> Bfx.gatk_bqsr
~configuration: Biokepi.Tools.Gatk.Configuration.default_bqsr
in
let vcfs =
let normal, tumor = final_normal_bam, final_tumor_bam in
Bfx.list [
Bfx.mutect ~normal ~tumor ()
|> Bfx.save ~name:"Mutect VCF";
Bfx.somaticsniper ~normal ~tumor ()
|> Bfx.save ~name:"SS VCF";
Bfx.strelka ~normal ~tumor ()
|> Bfx.save ~name:"Strelka VCF";
] in
Bfx.list [
Bfx.to_unit vcfs;
ot_hla;
] |> Bfx.to_unit
let run () =
Bfx.observe (fun () -> vc)
end
let () =
let module Go_insane = Run_test(Pipeline_insane) in
let insane_result = Go_insane.main "pipeline-insane" in
let module Go_simple_somatic = Run_test(Somatic_simplish) in
let simple_somatic_result = Go_simple_somatic.main "pipeline-simple-somatic" in
let display_result mod_name results =
printf "- `%s`:\n%s\n%!"
mod_name
(List.map results ~f:(sprintf " * %s\n") |> String.concat "");
in
printf "\n### Test results:\n\n";
display_result "Pipeline_insane" insane_result;
display_result "Somatic_simplish" simple_somatic_result;
()
|
f01f909cbc7b804b17fc65d7a1126c239b13ef4d90ac479c9f102140a8236b1f | SamB/coq | discharge.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i $Id$ i*)
open Sign
open Cooking
open Declarations
open Entries
val process_inductive :
named_context -> work_list -> mutual_inductive_body -> mutual_inductive_entry
| null | https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/toplevel/discharge.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i $Id$ i | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Sign
open Cooking
open Declarations
open Entries
val process_inductive :
named_context -> work_list -> mutual_inductive_body -> mutual_inductive_entry
|
2ac090fec9515ddfd2c5c11d9cd3875998d56155b1da84a4bee0b4b0d7ab64ca | EligiusSantori/L2Apf | refresh_manor.scm | (module logic racket/base
(require
"../packet/game/client/refresh_manor_list.scm"
(only-in "../system/connection.scm" send-packet)
)
(provide refresh-manor)
(define (refresh-manor connection)
(send-packet connection (game-client-packet/refresh-manor-list))
)
)
| null | https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/api/refresh_manor.scm | scheme | (module logic racket/base
(require
"../packet/game/client/refresh_manor_list.scm"
(only-in "../system/connection.scm" send-packet)
)
(provide refresh-manor)
(define (refresh-manor connection)
(send-packet connection (game-client-packet/refresh-manor-list))
)
)
| |
b23f698b200bea8a92548e4321ac85bbe25b5f5398f0fbe8d0199937bed16f5f | ryanpbrewster/haskell | distinct_subsequences.hs | -- distinct_subsequences.hs
- Challenge Description :
-
- A subsequence of a given sequence S consists of S with zero or more elements
- deleted . Formally , a sequence Z = z1z2 .. zk is a subsequence of
- X = x1x2 ... xm , if there exists a strictly increasing sequence < i1,i2 ... >
- of indicies of X such that for all j=1,2, ... k we have . e.g. Z = is a subsequence of X = abcbdab with corresponding index sequence < 2,3,5,7 >
-
- Input sample :
-
- Your program should accept as its first argument a path to a filename . Each
- line in this file contains two comma separated strings . The first is the
- sequence X and the second is the subsequence e.g.
-
- babgbag , bag
- rabbbit , rabbit
-
- Output sample :
-
- Print out the number of distinct occurrences of Z in X as a subsequence e.g.
-
- 5
- 3
- Challenge Description:
-
- A subsequence of a given sequence S consists of S with zero or more elements
- deleted. Formally, a sequence Z = z1z2..zk is a subsequence of
- X = x1x2...xm, if there exists a strictly increasing sequence <i1,i2...ik>
- of indicies of X such that for all j=1,2,...k we have Xij = Zj. e.g. Z=bcdb
- is a subsequence of X=abcbdab with corresponding index sequence <2,3,5,7>
-
- Input sample:
-
- Your program should accept as its first argument a path to a filename. Each
- line in this file contains two comma separated strings. The first is the
- sequence X and the second is the subsequence Z. e.g.
-
- babgbag,bag
- rabbbit,rabbit
-
- Output sample:
-
- Print out the number of distinct occurrences of Z in X as a subsequence e.g.
-
- 5
- 3
-}
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
solveProblem txt = let inputs = [ wordsBy "," ln | ln <- lines txt ]
anss = [ occurrences z x | [x,z] <- inputs ]
in unlines $ map show anss
wordsBy delims s = wordsBy' delims s
where wordsBy' _ [] = []
wordsBy' delims s = let (f,r) = break (`elem` delims) s
in f:wordsBy' delims (dropWhile (`elem` delims) r)
occurrences [] _ = 1
occurrences _ [] = 0
occurrences zs@(z:zr) (x:xr) | z == x = occurrences zs xr + occurrences zr xr
| otherwise = occurrences zs xr
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/CodeEval/distinct_subsequences.hs | haskell | distinct_subsequences.hs |
- Challenge Description :
-
- A subsequence of a given sequence S consists of S with zero or more elements
- deleted . Formally , a sequence Z = z1z2 .. zk is a subsequence of
- X = x1x2 ... xm , if there exists a strictly increasing sequence < i1,i2 ... >
- of indicies of X such that for all j=1,2, ... k we have . e.g. Z = is a subsequence of X = abcbdab with corresponding index sequence < 2,3,5,7 >
-
- Input sample :
-
- Your program should accept as its first argument a path to a filename . Each
- line in this file contains two comma separated strings . The first is the
- sequence X and the second is the subsequence e.g.
-
- babgbag , bag
- rabbbit , rabbit
-
- Output sample :
-
- Print out the number of distinct occurrences of Z in X as a subsequence e.g.
-
- 5
- 3
- Challenge Description:
-
- A subsequence of a given sequence S consists of S with zero or more elements
- deleted. Formally, a sequence Z = z1z2..zk is a subsequence of
- X = x1x2...xm, if there exists a strictly increasing sequence <i1,i2...ik>
- of indicies of X such that for all j=1,2,...k we have Xij = Zj. e.g. Z=bcdb
- is a subsequence of X=abcbdab with corresponding index sequence <2,3,5,7>
-
- Input sample:
-
- Your program should accept as its first argument a path to a filename. Each
- line in this file contains two comma separated strings. The first is the
- sequence X and the second is the subsequence Z. e.g.
-
- babgbag,bag
- rabbbit,rabbit
-
- Output sample:
-
- Print out the number of distinct occurrences of Z in X as a subsequence e.g.
-
- 5
- 3
-}
import System.Environment (getArgs)
main = do
args <- getArgs
txt <- readFile (head args)
putStr $ solveProblem txt
solveProblem txt = let inputs = [ wordsBy "," ln | ln <- lines txt ]
anss = [ occurrences z x | [x,z] <- inputs ]
in unlines $ map show anss
wordsBy delims s = wordsBy' delims s
where wordsBy' _ [] = []
wordsBy' delims s = let (f,r) = break (`elem` delims) s
in f:wordsBy' delims (dropWhile (`elem` delims) r)
occurrences [] _ = 1
occurrences _ [] = 0
occurrences zs@(z:zr) (x:xr) | z == x = occurrences zs xr + occurrences zr xr
| otherwise = occurrences zs xr
|
8a30716d8bea762061999f821aa7854120f1761839d7b47adae01f66eedceda5 | Shirakumo/kandria | main-menu.lisp | (in-package #:org.shirakumo.fraf.kandria)
(defclass news-display (label)
((alloy:value :initform "")
(up-to-date :initform T :accessor up-to-date)
(markup :initform () :accessor markup)))
(defmethod initialize-instance :after ((display news-display) &key)
(fetch-news display))
(presentations:define-realization (ui news-display)
((version-warning simple:text)
(alloy:margins) (@ update-game-notification)
:size (alloy:un 15)
:pattern colors:red
:valign :top :halign :left
:font (setting :display :font))
((label simple:text)
(alloy:margins) alloy:text
:size (alloy:un 15)
:pattern colors:gray
:valign :bottom :halign :left
:font (setting :display :font)))
(presentations:define-update (ui news-display)
(version-warning
:hidden-p (up-to-date alloy:renderable))
(label
:text alloy:text
:markup (markup alloy:renderable)))
(defun parse-news (source)
(let ((version-line (read-line source))
(req (dialogue:resume (dialogue:run (dialogue:compile source T) (make-instance 'dialogue:vm)) 1)))
(values (dialogue:text req)
(normalize-markup (dialogue:markup req))
(subseq version-line 2))))
(defun fetch-news (target &optional (url ""))
(with-eval-in-task-thread ()
(v:info :kandria.news "Fetching news...")
(handler-case
(multiple-value-bind (text markup version) (parse-news (drakma:http-request url :want-stream T))
(setf (alloy:value target) text)
(setf (markup target) markup)
(setf (up-to-date target) (version<= version (version :app))))
(usocket:ns-try-again-condition ())
(error (e)
(v:severe :kandria.news "Failed to fetch news: ~a" e)))))
(defclass main-menu-button (button)
())
(defmethod alloy:activate :after ((button main-menu-button))
(harmony:play (// 'sound 'ui-confirm)))
(presentations:define-realization (ui main-menu-button)
((:label simple:text)
(alloy:margins) alloy:text
:font (setting :display :font)
:halign :middle :valign :middle
:wrap T)
((:border simple:rectangle)
(alloy:extent 0 0 (alloy:pw 1) 1)))
(presentations:define-update (ui main-menu-button)
(:label
:size (alloy:un 16)
:pattern colors:white)
(:border
:pattern (if alloy:focus colors:white colors:transparent)))
(presentations:define-animated-shapes main-menu-button
(:border (simple:pattern :duration 0.2)))
(defclass eating-constraint-layout (org.shirakumo.alloy.layouts.constraint:layout)
())
(defmethod alloy:handle ((ev alloy:pointer-event) (focus eating-constraint-layout))
(restart-case
(call-next-method)
(alloy:decline ()
(setf (alloy:cursor (alloy:ui focus)) :arrow)
T))
(when (typep ev 'alloy:drop-event)
(alloy:decline)))
(defclass main-menu (menuing-panel)
())
(defmethod initialize-instance :after ((panel main-menu) &key)
(let ((layout (make-instance 'eating-constraint-layout))
(menu (make-instance 'alloy:vertical-linear-layout :cell-margins (alloy:margins 5) :min-size (alloy:size 120 30)))
(focus (make-instance 'alloy:focus-list)))
(alloy:enter menu layout :constraints `((:center :w) (:bottom 20) (:height 350) (:width 300)))
(macrolet ((with-button ((name &rest initargs) &body body)
`(let ((button (alloy:represent (@ ,name) 'main-menu-button :focus-parent focus :layout-parent menu ,@initargs)))
(alloy:on alloy:activate (button)
,@body)
button)))
(when (and (list-saves)
(not (setting :debugging :kiosk-mode)))
(with-button (resume-game)
(handler-case
(with-error-logging (:kandria.save)
(resume-state (first (sort (list-saves) #'> :key #'save-time))))
#+kandria-release
(error () (messagebox (@ save-file-corrupted-notice)))))
(with-button (load-game-menu)
(show-panel 'save-menu :intent :load)))
(if (setting :debugging :kiosk-mode)
(with-button (new-game)
(setf (state +main+) (make-instance 'save-state :filename "1"))
(load-game NIL +main+))
(with-button (new-game)
(show-panel 'save-menu :intent :new)))
(with-button (options-menu)
(show-panel 'options-menu))
(with-button (mod-menu)
(show-panel 'module-menu))
(with-button (credits-menu)
(show-credits :on-hide (lambda () (show-panel 'main-menu))))
#++
(with-button (changelog-menu)
)
(let ((subbutton
(with-button (subscribe-cta)
(open-in-browser ""))))
(alloy:on alloy:focus (value subbutton)
(setf (presentations:update-overrides subbutton)
(if value
`((:label :markup ((0 1000 (:rainbow T)))))
`((:label :markup ()))))))
(let ((exit (with-button (exit-game)
(quit *context*))))
(alloy:on alloy:exit (focus)
(setf (alloy:focus exit) :weak)
(setf (alloy:focus focus) :strong)))
(let ((news (make-instance 'news-display)))
(alloy:enter news layout :constraints `((:left 5) (:bottom 5) (:height 60) (:width 500))))
(let ((version (make-instance 'label :value (format NIL "v~a" (version :app))
:style `((:label :pattern ,colors:gray :halign :right :valign :bottom :size ,(alloy:un 10))))))
(alloy:enter version layout :constraints `((:right 5) (:bottom 5) (:height 60) (:width 500)))))
(alloy:finish-structure panel layout focus)))
(define-shader-entity fullscreen-background (lit-entity textured-entity trial:fullscreen-entity)
((texture :initform (// 'kandria 'main-menu))))
(define-class-shader (fullscreen-background :fragment-shader -10)
"out vec4 color;
void main(){
color = apply_lighting_flat(color, vec2(0, -5), 0, vec2(0));
}")
(define-shader-entity star (lit-sprite listener)
((multiplier :initform 1.0 :accessor multiplier)
(texture :initform (// 'kandria 'star))
(size :initform (vec 105 105))
(clock :initform (random 1000.0) :accessor clock)))
(defmethod handle ((ev tick) (star star))
(incf (clock star) (dt ev)))
(defmethod render :before ((star star) (program shader-program))
(setf (uniform program "multiplier")
(float (+ 1.0 (/ (+ (sin (* 2 (clock star)))
(sin (* PI (clock star))))
2.0))
0f0)))
(define-class-shader (star :fragment-shader)
"uniform float multiplier = 1.0;
out vec4 color;
void main(){
color *= multiplier;
}")
(define-asset (kandria wave-grid) mesh
(with-vertex-filling ((make-instance 'vertex-mesh :face-length 4 :vertex-type 'basic-vertex))
(let* ((s (/ 512 64))
(s2 (/ s -2)))
(dotimes (x s)
(dotimes (y s)
(vertex :location (vec (+ x s2 -0.0) 0 (+ y s2 -0.0)) :uv (vec (/ (+ x 0) s) (/ (+ y 0) s)) :normal (vec 0 1 0))
(vertex :location (vec (+ x s2 +1.0) 0 (+ y s2 -0.0)) :uv (vec (/ (+ x 1) s) (/ (+ y 0) s)) :normal (vec 0 1 0))
(vertex :location (vec (+ x s2 +1.0) 0 (+ y s2 +1.0)) :uv (vec (/ (+ x 1) s) (/ (+ y 1) s)) :normal (vec 0 1 0))
(vertex :location (vec (+ x s2 -0.0) 0 (+ y s2 +1.0)) :uv (vec (/ (+ x 0) s) (/ (+ y 1) s)) :normal (vec 0 1 0))))))
:vertex-form :patches)
(define-shader-pass wave-propagate-pass (post-effect-pass)
((previous :port-type trial::static-input :accessor previous)
(next :port-type output :accessor next)
(framebuffer :accessor framebuffer)
(clock :initform 0.0 :accessor clock)))
(defmethod initialize-instance :after ((pass wave-propagate-pass) &key)
(setf (previous pass) (make-instance 'texture :target :texture-2d :internal-format :rg32f :width 512 :height 512))
(setf (next pass) (make-instance 'texture :target :texture-2d :internal-format :rg32f :width 512 :height 512))
(setf (framebuffer pass) (make-instance 'framebuffer :attachments `((:color-attachment0 ,(next pass))))))
(defmethod stage :after ((pass wave-propagate-pass) (area staging-area))
(stage (previous pass) area)
(stage (next pass) area))
(defmethod render :after ((pass wave-propagate-pass) thing)
;; Swap out the next and previous.
(v:with-muffled-logging ()
(rotatef (previous pass) (next pass)))
(gl:bind-framebuffer :framebuffer (gl-name (framebuffer pass)))
(%gl:framebuffer-texture :framebuffer :color-attachment0 (gl-name (next pass)) 0))
(defmethod handle ((ev tick) (pass wave-propagate-pass))
(when (<= (decf (clock pass) (dt ev)) 0.0)
(let ((pos (nv+ (vrandr 0 200) 256)))
(enter (vec (vx pos) (vy pos) (1+ (random 3)) (+ 0.5 (random 3.0))) pass))
(setf (clock pass) (+ 0.1 (random 0.5))))
(render pass (shader-program pass)))
(define-class-shader (wave-propagate-pass :fragment-shader)
"uniform sampler2D previous;
uniform float energy_compensation = 0.28;
uniform float propagation_speed = 0.46;
uniform float oscillator_speed = 0.001;
out vec4 color;
void main(){
ivec2 local = ivec2(gl_FragCoord.xy);
vec2 current = texelFetch(previous, local, 0).rg;
float previous_height = current.r;
current.r += (current.r-current.g);
current.g = previous_height;
current.r *= 1.0-oscillator_speed;
current.r += (current.r-current.g)*energy_compensation;
float local_sum = texelFetch(previous, local + ivec2(-1, 0), 0).r
+ texelFetch(previous, local + ivec2(+1, 0), 0).r
+ texelFetch(previous, local + ivec2(0, -1), 0).r
+ texelFetch(previous, local + ivec2(0, +1), 0).r;
current.r += (local_sum*0.25-current.r)*propagation_speed*0.5;
color = vec4(current.rg,0,1);
}")
(defmethod enter ((pos vec4) (pass wave-propagate-pass))
(let* ((r (round (vz pos)))
(a (vw pos))
(s (* 2 r))
(x (clamp 0 (- (round (vx pos)) r) (- 512 s)))
(y (clamp 0 (- (round (vy pos)) r) (- 512 s)))
(i -1))
(cffi:with-foreign-object (ptr :float (* 2 s s))
(dotimes (ix s)
(dotimes (iy s)
(let ((d (max 0.0 (- 1 (/ (+ (expt (- ix r) 2) (expt (- iy r) 2)) (expt r 2))))))
(setf (cffi:mem-aref ptr :float (incf i)) (* d a))
(setf (cffi:mem-aref ptr :float (incf i)) 0.0))))
(gl:bind-texture :texture-2d (gl-name (previous pass)))
(gl:tex-sub-image-2d :texture-2d 0 x y s s :rg :float ptr))))
(defmethod enter ((pos vec2) (pass wave-propagate-pass))
(enter (vec (vx pos) (vy pos) 2 2) pass))
(defmethod clear ((pass wave-propagate-pass))
(cffi:with-foreign-object (ptr :float 2)
(setf (cffi:mem-aref ptr :float 0) 0.0)
(setf (cffi:mem-aref ptr :float 1) 0.0)
(%gl:clear-tex-image (gl-name (previous pass)) 0 :rg :float ptr)))
(define-shader-entity wave (listener renderable)
((wave-pass :initform (make-instance 'wave-propagate-pass) :initarg :wave-pass :accessor wave-pass)
(vertex-array :initform (// 'kandria 'wave-grid) :accessor vertex-array)
(matrix :initform (meye 4) :accessor matrix)))
(defmethod initialize-instance :after ((wave wave) &key)
(handle (make-instance 'resize :width (width *context*) :height (height *context*)) wave))
(defmethod stage :after ((wave wave) (area staging-area))
(stage (wave-pass wave) area)
(stage (vertex-array wave) area))
(defmethod handle ((ev tick) (wave wave))
(handle ev (wave-pass wave)))
(defmethod handle ((ev resize) (wave wave))
(let ((mat (mperspective 50 (/ (max 1 (width ev)) (max 1 (height ev))) 1.0 100000.0)))
(nmlookat mat (vec 0 50 -200) (vec 0 30 0) (vec 0 1 0))
(nmscale mat (vec 64 1 64))
(setf (matrix wave) mat)))
(defmethod render ((wave wave) (program shader-program))
(handle (make-instance 'resize :width (width *context*) :height (height *context*)) wave)
(gl:active-texture :texture1)
(gl:bind-texture :texture-2d (gl-name (next (wave-pass wave))))
(setf (uniform program "heightmap") 1)
(setf (uniform program "transform_matrix") (matrix wave))
(let* ((vao (vertex-array wave)))
(gl:bind-vertex-array (gl-name vao))
(gl:patch-parameter :patch-vertices 4)
(%gl:draw-arrays :patches 0 (size vao))
(gl:bind-vertex-array 0)))
(define-class-shader (wave :vertex-shader)
"layout (location = 0) in vec3 position;
layout (location = 1) in vec2 uv;
out vec3 vPosition;
out vec2 vUV;
void main(){
vPosition = position;
vUV = uv;
}")
(define-class-shader (wave :tess-control-shader)
"#version 330
#extension GL_ARB_tessellation_shader : require
layout (vertices = 4) out;
in vec3 vPosition[];
in vec2 vUV[];
out vec3 tcPosition[];
out vec2 tcUV[];
const int subdivs = 64;
void main(){
tcPosition[gl_InvocationID] = vPosition[gl_InvocationID];
tcUV[gl_InvocationID] = vUV[gl_InvocationID];
if(gl_InvocationID == 0){
gl_TessLevelInner[0] = subdivs;
gl_TessLevelInner[1] = subdivs;
gl_TessLevelOuter[0] = subdivs;
gl_TessLevelOuter[1] = subdivs;
gl_TessLevelOuter[2] = subdivs;
gl_TessLevelOuter[3] = subdivs;
}
}")
(define-class-shader (wave :tess-evaluation-shader)
"#version 330
#extension GL_ARB_tessellation_shader : require
layout (quads) in;
uniform sampler2D heightmap;
uniform mat4 transform_matrix;
in vec2 tcUV[];
in vec3 tcPosition[];
out vec3 tePosition;
out vec2 texcoord;
out float height;
void main(){
vec3 a = mix(tcPosition[0], tcPosition[3], gl_TessCoord.x);
vec3 b = mix(tcPosition[1], tcPosition[2], gl_TessCoord.x);
vec2 u = mix(tcUV[0], tcUV[3], gl_TessCoord.x);
vec2 v = mix(tcUV[1], tcUV[2], gl_TessCoord.x);
tePosition = mix(a, b, gl_TessCoord.y);
texcoord = mix(u, v, gl_TessCoord.y);
height = texture(heightmap, texcoord).r;
tePosition.y += height;
gl_Position = transform_matrix * vec4(tePosition, 1);
}")
(define-class-shader (wave :fragment-shader)
"
in float height;
out vec4 color;
void main(){
color = vec4(vec3(min(1,1+height)), abs(height/5));
}")
(define-asset (kandria logo-rect) mesh
(make-rectangle 400 100))
(define-shader-entity logo (listener textured-entity vertex-entity located-entity)
((vertex-array :initform (// 'kandria 'logo-rect))
(texture :initform (// 'kandria 'logo))
(clock :initform 0.0 :accessor clock)
(previous-depth :initform 0.0 :accessor previous-depth))
(:inhibit-shaders (textured-entity :fragment-shader)))
(defmethod handle ((ev tick) (logo logo))
(incf (clock logo) (dt ev)))
(defmethod render :before ((logo logo) (program shader-program))
(let* ((tt (clock logo))
(depth (float (* (expt (- (rem tt 3.0) 1.0) 4.0)
(max 0.0 (/ (+ (sin (* PI tt)) (sin (* 13 tt))) 2.0)))
0f0)))
(gl:clear-color 1 1 1 1)
(setf (uniform program "clock") (float (/ tt 10) 0f0))
(setf (uniform program "max_attempts") (1+ (logand #x5 (sxhash (floor (* 3 tt))))))
(cond ((< (previous-depth logo) depth)
(setf (uniform program "depth") depth)
(setf (previous-depth logo) depth))
((<= depth 0)
(setf (uniform program "depth") depth)
(setf (previous-depth logo) depth)))))
(define-class-shader (logo :fragment-shader)
"
#define PI 3.1415926538
uniform sampler2D texture_image;
uniform int max_attempts = 3;
uniform float depth = 1.0;
uniform float clock = 0.0;
const vec2 tex_dx = vec2(1.0/128.0, 1.0/128.0);
in vec2 texcoord;
out vec4 color;
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
void main(){
float x = floor((texcoord.x-1)*300);
vec2 offset = texcoord;
color = vec4(0);
float r = rand(vec2(x,clock/10000.0));
for(int i=0; i<max_attempts; ++i){
offset.y -= tex_dx.y*r*depth;
vec4 local = texture(texture_image, offset);
if(0 < local.a){
color = vec4(local.rgb*5, local.a);
break;
}
}
}")
(defmethod stage :after ((menu main-menu) (area staging-area))
(stage (// 'music 'menu) area)
(stage (// 'music 'credits) area))
(defmethod show :after ((menu main-menu) &key)
(let* ((camera (camera +world+))
(tsize (target-size camera))
(yspread (/ (vy tsize) 1.5)))
(setf (lighting (unit 'lighting-pass +world+)) (gi 'one))
(setf (override (unit 'environment +world+)) (// 'music 'menu))
(trial:commit (make-instance 'star) (loader +main+) :unload NIL)
(trial:commit (stage (make-instance 'star) (unit 'render +world+)) (loader +main+) :unload NIL)
(enter-and-load (make-instance 'fullscreen-background) +world+ +main+)
(enter-and-load (make-instance 'logo :location (vec 0 80)) +world+ +main+)
;; Only enter the wave if we have tesselation available.
(when-gl-extension :GL-ARB-TESSELLATION-SHADER
(enter-and-load (make-instance 'wave) +world+ +main+))
(dotimes (i 100)
(let ((s (+ 8 (* 20 (/ (expt (random 10.0) 3) 1000.0)))))
(enter (make-instance 'star
:bsize (vec s s)
:location (vec (random* 0 (* 2 (vx tsize)))
(- (vy tsize) 10 (* yspread (/ (expt (random 10.0) 3) 1000.0)))))
+world+))))
;; Show prompt to try and resume from report save file.
(let ((report (find "report" (list-saves) :key (lambda (s) (pathname-name (file s))) :test #'string=)))
(when report
(show (make-instance 'prompt-panel
:text (@ recover-crashed-save)
:on-accept (lambda () (ignore-errors (rename-file (file report) (make-pathname :name "4" :defaults (file report)))))
:on-cancel (lambda () (ignore-errors (delete-file (file report)))))
:width (alloy:un 500)
:height (alloy:un 300)))))
(defmethod hide :after ((menu main-menu))
(setf (override (unit 'environment +world+)) NIL)
(for:for ((entity over +world+)
(garbage when (typep entity '(or star fullscreen-background logo wave)) collect entity))
(returning (dolist (entity garbage) (leave entity T)))))
(defun return-to-main-menu ()
(let ((state (state +main+))
(player (unit 'player +world+))
(pauser (make-instance 'listener)))
(clear +editor-history+)
(pause-game +world+ pauser)
(reset (unit 'environment +world+))
(transition
:kind :black
#+kandria-release
(when (and state player (setting :debugging :send-diagnostics))
(submit-trace state player)
(setf state NIL player NIL))
(unpause-game +world+ pauser)
(reset +main+))))
| null | https://raw.githubusercontent.com/Shirakumo/kandria/5bde3e568967063a37341454a70d0424ffff0484/ui/main-menu.lisp | lisp |
Swap out the next and previous.
i<max_attempts; ++i){
Only enter the wave if we have tesselation available.
Show prompt to try and resume from report save file. | (in-package #:org.shirakumo.fraf.kandria)
(defclass news-display (label)
((alloy:value :initform "")
(up-to-date :initform T :accessor up-to-date)
(markup :initform () :accessor markup)))
(defmethod initialize-instance :after ((display news-display) &key)
(fetch-news display))
(presentations:define-realization (ui news-display)
((version-warning simple:text)
(alloy:margins) (@ update-game-notification)
:size (alloy:un 15)
:pattern colors:red
:valign :top :halign :left
:font (setting :display :font))
((label simple:text)
(alloy:margins) alloy:text
:size (alloy:un 15)
:pattern colors:gray
:valign :bottom :halign :left
:font (setting :display :font)))
(presentations:define-update (ui news-display)
(version-warning
:hidden-p (up-to-date alloy:renderable))
(label
:text alloy:text
:markup (markup alloy:renderable)))
(defun parse-news (source)
(let ((version-line (read-line source))
(req (dialogue:resume (dialogue:run (dialogue:compile source T) (make-instance 'dialogue:vm)) 1)))
(values (dialogue:text req)
(normalize-markup (dialogue:markup req))
(subseq version-line 2))))
(defun fetch-news (target &optional (url ""))
(with-eval-in-task-thread ()
(v:info :kandria.news "Fetching news...")
(handler-case
(multiple-value-bind (text markup version) (parse-news (drakma:http-request url :want-stream T))
(setf (alloy:value target) text)
(setf (markup target) markup)
(setf (up-to-date target) (version<= version (version :app))))
(usocket:ns-try-again-condition ())
(error (e)
(v:severe :kandria.news "Failed to fetch news: ~a" e)))))
(defclass main-menu-button (button)
())
(defmethod alloy:activate :after ((button main-menu-button))
(harmony:play (// 'sound 'ui-confirm)))
(presentations:define-realization (ui main-menu-button)
((:label simple:text)
(alloy:margins) alloy:text
:font (setting :display :font)
:halign :middle :valign :middle
:wrap T)
((:border simple:rectangle)
(alloy:extent 0 0 (alloy:pw 1) 1)))
(presentations:define-update (ui main-menu-button)
(:label
:size (alloy:un 16)
:pattern colors:white)
(:border
:pattern (if alloy:focus colors:white colors:transparent)))
(presentations:define-animated-shapes main-menu-button
(:border (simple:pattern :duration 0.2)))
(defclass eating-constraint-layout (org.shirakumo.alloy.layouts.constraint:layout)
())
(defmethod alloy:handle ((ev alloy:pointer-event) (focus eating-constraint-layout))
(restart-case
(call-next-method)
(alloy:decline ()
(setf (alloy:cursor (alloy:ui focus)) :arrow)
T))
(when (typep ev 'alloy:drop-event)
(alloy:decline)))
(defclass main-menu (menuing-panel)
())
(defmethod initialize-instance :after ((panel main-menu) &key)
(let ((layout (make-instance 'eating-constraint-layout))
(menu (make-instance 'alloy:vertical-linear-layout :cell-margins (alloy:margins 5) :min-size (alloy:size 120 30)))
(focus (make-instance 'alloy:focus-list)))
(alloy:enter menu layout :constraints `((:center :w) (:bottom 20) (:height 350) (:width 300)))
(macrolet ((with-button ((name &rest initargs) &body body)
`(let ((button (alloy:represent (@ ,name) 'main-menu-button :focus-parent focus :layout-parent menu ,@initargs)))
(alloy:on alloy:activate (button)
,@body)
button)))
(when (and (list-saves)
(not (setting :debugging :kiosk-mode)))
(with-button (resume-game)
(handler-case
(with-error-logging (:kandria.save)
(resume-state (first (sort (list-saves) #'> :key #'save-time))))
#+kandria-release
(error () (messagebox (@ save-file-corrupted-notice)))))
(with-button (load-game-menu)
(show-panel 'save-menu :intent :load)))
(if (setting :debugging :kiosk-mode)
(with-button (new-game)
(setf (state +main+) (make-instance 'save-state :filename "1"))
(load-game NIL +main+))
(with-button (new-game)
(show-panel 'save-menu :intent :new)))
(with-button (options-menu)
(show-panel 'options-menu))
(with-button (mod-menu)
(show-panel 'module-menu))
(with-button (credits-menu)
(show-credits :on-hide (lambda () (show-panel 'main-menu))))
#++
(with-button (changelog-menu)
)
(let ((subbutton
(with-button (subscribe-cta)
(open-in-browser ""))))
(alloy:on alloy:focus (value subbutton)
(setf (presentations:update-overrides subbutton)
(if value
`((:label :markup ((0 1000 (:rainbow T)))))
`((:label :markup ()))))))
(let ((exit (with-button (exit-game)
(quit *context*))))
(alloy:on alloy:exit (focus)
(setf (alloy:focus exit) :weak)
(setf (alloy:focus focus) :strong)))
(let ((news (make-instance 'news-display)))
(alloy:enter news layout :constraints `((:left 5) (:bottom 5) (:height 60) (:width 500))))
(let ((version (make-instance 'label :value (format NIL "v~a" (version :app))
:style `((:label :pattern ,colors:gray :halign :right :valign :bottom :size ,(alloy:un 10))))))
(alloy:enter version layout :constraints `((:right 5) (:bottom 5) (:height 60) (:width 500)))))
(alloy:finish-structure panel layout focus)))
(define-shader-entity fullscreen-background (lit-entity textured-entity trial:fullscreen-entity)
((texture :initform (// 'kandria 'main-menu))))
(define-class-shader (fullscreen-background :fragment-shader -10)
void main(){
}")
(define-shader-entity star (lit-sprite listener)
((multiplier :initform 1.0 :accessor multiplier)
(texture :initform (// 'kandria 'star))
(size :initform (vec 105 105))
(clock :initform (random 1000.0) :accessor clock)))
(defmethod handle ((ev tick) (star star))
(incf (clock star) (dt ev)))
(defmethod render :before ((star star) (program shader-program))
(setf (uniform program "multiplier")
(float (+ 1.0 (/ (+ (sin (* 2 (clock star)))
(sin (* PI (clock star))))
2.0))
0f0)))
(define-class-shader (star :fragment-shader)
void main(){
}")
(define-asset (kandria wave-grid) mesh
(with-vertex-filling ((make-instance 'vertex-mesh :face-length 4 :vertex-type 'basic-vertex))
(let* ((s (/ 512 64))
(s2 (/ s -2)))
(dotimes (x s)
(dotimes (y s)
(vertex :location (vec (+ x s2 -0.0) 0 (+ y s2 -0.0)) :uv (vec (/ (+ x 0) s) (/ (+ y 0) s)) :normal (vec 0 1 0))
(vertex :location (vec (+ x s2 +1.0) 0 (+ y s2 -0.0)) :uv (vec (/ (+ x 1) s) (/ (+ y 0) s)) :normal (vec 0 1 0))
(vertex :location (vec (+ x s2 +1.0) 0 (+ y s2 +1.0)) :uv (vec (/ (+ x 1) s) (/ (+ y 1) s)) :normal (vec 0 1 0))
(vertex :location (vec (+ x s2 -0.0) 0 (+ y s2 +1.0)) :uv (vec (/ (+ x 0) s) (/ (+ y 1) s)) :normal (vec 0 1 0))))))
:vertex-form :patches)
(define-shader-pass wave-propagate-pass (post-effect-pass)
((previous :port-type trial::static-input :accessor previous)
(next :port-type output :accessor next)
(framebuffer :accessor framebuffer)
(clock :initform 0.0 :accessor clock)))
(defmethod initialize-instance :after ((pass wave-propagate-pass) &key)
(setf (previous pass) (make-instance 'texture :target :texture-2d :internal-format :rg32f :width 512 :height 512))
(setf (next pass) (make-instance 'texture :target :texture-2d :internal-format :rg32f :width 512 :height 512))
(setf (framebuffer pass) (make-instance 'framebuffer :attachments `((:color-attachment0 ,(next pass))))))
(defmethod stage :after ((pass wave-propagate-pass) (area staging-area))
(stage (previous pass) area)
(stage (next pass) area))
(defmethod render :after ((pass wave-propagate-pass) thing)
(v:with-muffled-logging ()
(rotatef (previous pass) (next pass)))
(gl:bind-framebuffer :framebuffer (gl-name (framebuffer pass)))
(%gl:framebuffer-texture :framebuffer :color-attachment0 (gl-name (next pass)) 0))
(defmethod handle ((ev tick) (pass wave-propagate-pass))
(when (<= (decf (clock pass) (dt ev)) 0.0)
(let ((pos (nv+ (vrandr 0 200) 256)))
(enter (vec (vx pos) (vy pos) (1+ (random 3)) (+ 0.5 (random 3.0))) pass))
(setf (clock pass) (+ 0.1 (random 0.5))))
(render pass (shader-program pass)))
(define-class-shader (wave-propagate-pass :fragment-shader)
void main(){
float local_sum = texelFetch(previous, local + ivec2(-1, 0), 0).r
+ texelFetch(previous, local + ivec2(+1, 0), 0).r
+ texelFetch(previous, local + ivec2(0, -1), 0).r
}")
(defmethod enter ((pos vec4) (pass wave-propagate-pass))
(let* ((r (round (vz pos)))
(a (vw pos))
(s (* 2 r))
(x (clamp 0 (- (round (vx pos)) r) (- 512 s)))
(y (clamp 0 (- (round (vy pos)) r) (- 512 s)))
(i -1))
(cffi:with-foreign-object (ptr :float (* 2 s s))
(dotimes (ix s)
(dotimes (iy s)
(let ((d (max 0.0 (- 1 (/ (+ (expt (- ix r) 2) (expt (- iy r) 2)) (expt r 2))))))
(setf (cffi:mem-aref ptr :float (incf i)) (* d a))
(setf (cffi:mem-aref ptr :float (incf i)) 0.0))))
(gl:bind-texture :texture-2d (gl-name (previous pass)))
(gl:tex-sub-image-2d :texture-2d 0 x y s s :rg :float ptr))))
(defmethod enter ((pos vec2) (pass wave-propagate-pass))
(enter (vec (vx pos) (vy pos) 2 2) pass))
(defmethod clear ((pass wave-propagate-pass))
(cffi:with-foreign-object (ptr :float 2)
(setf (cffi:mem-aref ptr :float 0) 0.0)
(setf (cffi:mem-aref ptr :float 1) 0.0)
(%gl:clear-tex-image (gl-name (previous pass)) 0 :rg :float ptr)))
(define-shader-entity wave (listener renderable)
((wave-pass :initform (make-instance 'wave-propagate-pass) :initarg :wave-pass :accessor wave-pass)
(vertex-array :initform (// 'kandria 'wave-grid) :accessor vertex-array)
(matrix :initform (meye 4) :accessor matrix)))
(defmethod initialize-instance :after ((wave wave) &key)
(handle (make-instance 'resize :width (width *context*) :height (height *context*)) wave))
(defmethod stage :after ((wave wave) (area staging-area))
(stage (wave-pass wave) area)
(stage (vertex-array wave) area))
(defmethod handle ((ev tick) (wave wave))
(handle ev (wave-pass wave)))
(defmethod handle ((ev resize) (wave wave))
(let ((mat (mperspective 50 (/ (max 1 (width ev)) (max 1 (height ev))) 1.0 100000.0)))
(nmlookat mat (vec 0 50 -200) (vec 0 30 0) (vec 0 1 0))
(nmscale mat (vec 64 1 64))
(setf (matrix wave) mat)))
(defmethod render ((wave wave) (program shader-program))
(handle (make-instance 'resize :width (width *context*) :height (height *context*)) wave)
(gl:active-texture :texture1)
(gl:bind-texture :texture-2d (gl-name (next (wave-pass wave))))
(setf (uniform program "heightmap") 1)
(setf (uniform program "transform_matrix") (matrix wave))
(let* ((vao (vertex-array wave)))
(gl:bind-vertex-array (gl-name vao))
(gl:patch-parameter :patch-vertices 4)
(%gl:draw-arrays :patches 0 (size vao))
(gl:bind-vertex-array 0)))
(define-class-shader (wave :vertex-shader)
void main(){
}")
(define-class-shader (wave :tess-control-shader)
"#version 330
#extension GL_ARB_tessellation_shader : require
void main(){
if(gl_InvocationID == 0){
}
}")
(define-class-shader (wave :tess-evaluation-shader)
"#version 330
#extension GL_ARB_tessellation_shader : require
void main(){
}")
(define-class-shader (wave :fragment-shader)
"
void main(){
}")
(define-asset (kandria logo-rect) mesh
(make-rectangle 400 100))
(define-shader-entity logo (listener textured-entity vertex-entity located-entity)
((vertex-array :initform (// 'kandria 'logo-rect))
(texture :initform (// 'kandria 'logo))
(clock :initform 0.0 :accessor clock)
(previous-depth :initform 0.0 :accessor previous-depth))
(:inhibit-shaders (textured-entity :fragment-shader)))
(defmethod handle ((ev tick) (logo logo))
(incf (clock logo) (dt ev)))
(defmethod render :before ((logo logo) (program shader-program))
(let* ((tt (clock logo))
(depth (float (* (expt (- (rem tt 3.0) 1.0) 4.0)
(max 0.0 (/ (+ (sin (* PI tt)) (sin (* 13 tt))) 2.0)))
0f0)))
(gl:clear-color 1 1 1 1)
(setf (uniform program "clock") (float (/ tt 10) 0f0))
(setf (uniform program "max_attempts") (1+ (logand #x5 (sxhash (floor (* 3 tt))))))
(cond ((< (previous-depth logo) depth)
(setf (uniform program "depth") depth)
(setf (previous-depth logo) depth))
((<= depth 0)
(setf (uniform program "depth") depth)
(setf (previous-depth logo) depth)))))
(define-class-shader (logo :fragment-shader)
"
#define PI 3.1415926538
float rand(vec2 co){
}
void main(){
if(0 < local.a){
}
}
}")
(defmethod stage :after ((menu main-menu) (area staging-area))
(stage (// 'music 'menu) area)
(stage (// 'music 'credits) area))
(defmethod show :after ((menu main-menu) &key)
(let* ((camera (camera +world+))
(tsize (target-size camera))
(yspread (/ (vy tsize) 1.5)))
(setf (lighting (unit 'lighting-pass +world+)) (gi 'one))
(setf (override (unit 'environment +world+)) (// 'music 'menu))
(trial:commit (make-instance 'star) (loader +main+) :unload NIL)
(trial:commit (stage (make-instance 'star) (unit 'render +world+)) (loader +main+) :unload NIL)
(enter-and-load (make-instance 'fullscreen-background) +world+ +main+)
(enter-and-load (make-instance 'logo :location (vec 0 80)) +world+ +main+)
(when-gl-extension :GL-ARB-TESSELLATION-SHADER
(enter-and-load (make-instance 'wave) +world+ +main+))
(dotimes (i 100)
(let ((s (+ 8 (* 20 (/ (expt (random 10.0) 3) 1000.0)))))
(enter (make-instance 'star
:bsize (vec s s)
:location (vec (random* 0 (* 2 (vx tsize)))
(- (vy tsize) 10 (* yspread (/ (expt (random 10.0) 3) 1000.0)))))
+world+))))
(let ((report (find "report" (list-saves) :key (lambda (s) (pathname-name (file s))) :test #'string=)))
(when report
(show (make-instance 'prompt-panel
:text (@ recover-crashed-save)
:on-accept (lambda () (ignore-errors (rename-file (file report) (make-pathname :name "4" :defaults (file report)))))
:on-cancel (lambda () (ignore-errors (delete-file (file report)))))
:width (alloy:un 500)
:height (alloy:un 300)))))
(defmethod hide :after ((menu main-menu))
(setf (override (unit 'environment +world+)) NIL)
(for:for ((entity over +world+)
(garbage when (typep entity '(or star fullscreen-background logo wave)) collect entity))
(returning (dolist (entity garbage) (leave entity T)))))
(defun return-to-main-menu ()
(let ((state (state +main+))
(player (unit 'player +world+))
(pauser (make-instance 'listener)))
(clear +editor-history+)
(pause-game +world+ pauser)
(reset (unit 'environment +world+))
(transition
:kind :black
#+kandria-release
(when (and state player (setting :debugging :send-diagnostics))
(submit-trace state player)
(setf state NIL player NIL))
(unpause-game +world+ pauser)
(reset +main+))))
|
e727c2251cad4c45d3a692e5bca7f01b4338182ab867c279abc20fb677596b02 | jakemcc/sicp-study | 1.17.clj | Exercise 1.17
Original O(b )
( defn my - mult [ a b ]
; (if (= b 0)
; 0
; (+ a (my-mult a (- b 1)))))
(defn doub [x] (* x 2))
(defn halve [x] (/ x 2))
(defn my-mult [a b]
(cond (= b 0) 0
(even? b) (my-mult (doub a) (halve b))
:else (+ a (my-mult a (dec b)))))
(defn print-mult [a b]
(do println (str a " * " b " = " (my-mult a b))))
(print-mult 2 4)
(print-mult 2 5)
(print-mult 1 5)
(print-mult 3 7)
(print-mult 3 10)
| null | https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section1.2/1.17.clj | clojure | (if (= b 0)
0
(+ a (my-mult a (- b 1))))) | Exercise 1.17
Original O(b )
( defn my - mult [ a b ]
(defn doub [x] (* x 2))
(defn halve [x] (/ x 2))
(defn my-mult [a b]
(cond (= b 0) 0
(even? b) (my-mult (doub a) (halve b))
:else (+ a (my-mult a (dec b)))))
(defn print-mult [a b]
(do println (str a " * " b " = " (my-mult a b))))
(print-mult 2 4)
(print-mult 2 5)
(print-mult 1 5)
(print-mult 3 7)
(print-mult 3 10)
|
3e13c3793df09c3fb84354d68b0e7243092fce4e25884d56ac27408e19237cb6 | nikita-volkov/ptr-poker | Write.hs | module PtrPoker.Write where
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Internal as ByteString
import qualified PtrPoker.ByteString as ByteString
import qualified PtrPoker.Ffi as Ffi
import qualified PtrPoker.Poke as Poke
import PtrPoker.Prelude hiding (concat)
import qualified PtrPoker.Size as Size
-- |
Execute Write , producing strict ByteString .
# INLINEABLE writeToByteString #
writeToByteString :: Write -> ByteString
writeToByteString Write {..} =
ByteString.unsafeCreate writeSize (void . Poke.pokePtr writePoke)
-- |
-- Specification of how many bytes to allocate and how to populate them.
--
-- Useful for creating strict bytestrings and tasks like that.
data Write = Write
{ writeSize :: Int,
writePoke :: Poke.Poke
}
instance Semigroup Write where
{-# INLINE (<>) #-}
Write lSize lPoke <> Write rSize rPoke =
Write (lSize + rSize) (lPoke <> rPoke)
# INLINE sconcat #
sconcat =
concat
instance Monoid Write where
# INLINE mempty #
mempty =
Write 0 mempty
# INLINE mconcat #
mconcat =
concat
-- |
Reuses the IsString instance of ' ByteString ' .
instance IsString Write where
{-# INLINE fromString #-}
fromString =
byteString . fromString
-- |
a foldable of writes .
# INLINE concat #
concat :: (Foldable f) => f Write -> Write
concat f =
Write
(foldl' (\a b -> a + writeSize b) 0 f)
(Poke.Poke (\p -> foldM (\p write -> Poke.pokePtr (writePoke write) p) p f))
-- |
-- Render Word8 as byte.
# INLINE word8 #
word8 :: Word8 -> Write
word8 a =
Write 1 (Poke.word8 a)
-- |
-- Render Word16 in Little-endian.
# INLINE lWord16 #
lWord16 :: Word16 -> Write
lWord16 a =
Write 2 (Poke.lWord16 a)
-- |
-- Render Word16 in Big-endian.
# INLINE bWord16 #
bWord16 :: Word16 -> Write
bWord16 a =
Write 2 (Poke.bWord16 a)
-- |
Render Word32 in Little - endian .
# INLINE lWord32 #
lWord32 :: Word32 -> Write
lWord32 a =
Write 4 (Poke.lWord32 a)
-- |
-- Render Word32 in Big-endian.
# INLINE bWord32 #
bWord32 :: Word32 -> Write
bWord32 a =
Write 4 (Poke.bWord32 a)
-- |
-- Render Word64 in Little-endian.
# INLINE lWord64 #
lWord64 :: Word64 -> Write
lWord64 a =
Write 8 (Poke.lWord64 a)
-- |
-- Render Word64 in Big-endian.
# INLINE bWord64 #
bWord64 :: Word64 -> Write
bWord64 a =
Write 8 (Poke.bWord64 a)
-- |
-- Render Int16 in Little-endian.
# INLINE lInt16 #
lInt16 :: Int16 -> Write
lInt16 a =
Write 2 (Poke.lInt16 a)
-- |
-- Render Int16 in Big-endian.
# INLINE bInt16 #
bInt16 :: Int16 -> Write
bInt16 a =
Write 2 (Poke.bInt16 a)
-- |
-- Render Int32 in Little-endian.
# INLINE lInt32 #
lInt32 :: Int32 -> Write
lInt32 a =
Write 4 (Poke.lInt32 a)
-- |
-- Render Int32 in Big-endian.
# INLINE bInt32 #
bInt32 :: Int32 -> Write
bInt32 a =
Write 4 (Poke.bInt32 a)
-- |
Render Int64 in Little - endian .
{-# INLINE lInt64 #-}
lInt64 :: Int64 -> Write
lInt64 a =
Write 8 (Poke.lInt64 a)
-- |
Render Int64 in Big - endian .
{-# INLINE bInt64 #-}
bInt64 :: Int64 -> Write
bInt64 a =
Write 8 (Poke.bInt64 a)
-- |
-- Render Word64 in ASCII decimal.
# INLINE word64AsciiDec #
word64AsciiDec :: Word64 -> Write
word64AsciiDec a =
Write size poke
where
size =
Size.word64AsciiDec a
poke =
Poke.sizedReverse size (Ffi.revPokeUInt64 (fromIntegral a))
-- |
Render Word in ASCII decimal .
{-# INLINE wordAsciiDec #-}
wordAsciiDec :: Word -> Write
wordAsciiDec =
word64AsciiDec . fromIntegral
-- |
Render Int64 in ASCII decimal .
# INLINE int64AsciiDec #
int64AsciiDec :: Int64 -> Write
int64AsciiDec a =
Write size poke
where
size =
Size.int64AsciiDec a
poke =
Poke.sizedReverse size (Ffi.revPokeInt64 (fromIntegral a))
-- |
-- Render Int in ASCII decimal.
{-# INLINE intAsciiDec #-}
intAsciiDec :: Int -> Write
intAsciiDec =
int64AsciiDec . fromIntegral
-- |
-- Render double interpreting non-real values,
such as @NaN@ , @Infinity@ , @-Infinity@ ,
-- as is.
# INLINE doubleAsciiDec #
doubleAsciiDec :: Double -> Write
doubleAsciiDec a =
if a == 0
then word8 48
else
if isNaN a
then "NaN"
else
if isInfinite a
then
if a < 0
then "-Infinity"
else "Infinity"
else
if a < 0
then word8 45 <> byteString (ByteString.double (negate a))
else byteString (ByteString.double a)
-- |
-- Render double interpreting non real values,
such as @NaN@ , @Infinity@ , @-Infinity@ ,
as zero .
# INLINE zeroNonRealDoubleAsciiDec #
zeroNonRealDoubleAsciiDec :: Double -> Write
zeroNonRealDoubleAsciiDec a =
if a == 0 || isNaN a || isInfinite a
then word8 48
else
if a < 0
then word8 45 <> byteString (ByteString.double (negate a))
else byteString (ByteString.double a)
-- |
Render Scientific in ASCII decimal .
# INLINE scientificAsciiDec #
scientificAsciiDec :: Scientific -> Write
scientificAsciiDec =
byteString . ByteString.scientific
-- |
Efficiently copy the contents of ByteString using @memcpy@.
# INLINE byteString #
byteString :: ByteString -> Write
byteString a =
Write (ByteString.length a) (inline Poke.byteString a)
-- |
Render Text in UTF8 .
--
-- Does pretty much the same as 'Data.Text.Encoding.encodeUtf8',
-- both implementation and performance-wise,
-- while allowing you to avoid redundant @memcpy@
compared to @('byteString ' . ' Data . Text . Encoding.encodeUtf8')@.
--
-- Following are the benchmark results comparing the performance of
-- @('writeToByteString' . 'textUtf8')@ with
-- @Data.Text.Encoding.'Data.Text.Encoding.encodeUtf8'@
on inputs in Latin and Greek ( requiring different number of surrogate bytes ) .
-- The results show that they are quite similar.
--
-- === __Benchmark results__
--
> textUtf8 / ptr - poker / 25.61 ns
> textUtf8 / ptr - poker / latin/10 31.59 ns
> textUtf8 / ptr - poker / latin/100 121.5 ns
> textUtf8 / ptr - poker / greek/1 28.54 ns
> textUtf8 / ptr - poker / greek/10 41.97 ns
> textUtf8 / ptr - poker / greek/100 250.3 ns
> textUtf8 / text / latin/1 22.84 ns
-- > textUtf8/text/latin/10 31.10 ns
-- > textUtf8/text/latin/100 118.2 ns
> textUtf8 / text / greek/1 25.80 ns
> textUtf8 / text / greek/10 40.80 ns
> textUtf8 / text / greek/100 293.1 ns
# INLINEABLE textUtf8 #
textUtf8 :: Text -> Write
textUtf8 a =
Write (Size.textUtf8 a) (Poke.textUtf8 a)
| null | https://raw.githubusercontent.com/nikita-volkov/ptr-poker/f2bb3652ae0f0ca58d4b4528888c4340257d0249/library/PtrPoker/Write.hs | haskell | |
|
Specification of how many bytes to allocate and how to populate them.
Useful for creating strict bytestrings and tasks like that.
# INLINE (<>) #
|
# INLINE fromString #
|
|
Render Word8 as byte.
|
Render Word16 in Little-endian.
|
Render Word16 in Big-endian.
|
|
Render Word32 in Big-endian.
|
Render Word64 in Little-endian.
|
Render Word64 in Big-endian.
|
Render Int16 in Little-endian.
|
Render Int16 in Big-endian.
|
Render Int32 in Little-endian.
|
Render Int32 in Big-endian.
|
# INLINE lInt64 #
|
# INLINE bInt64 #
|
Render Word64 in ASCII decimal.
|
# INLINE wordAsciiDec #
|
|
Render Int in ASCII decimal.
# INLINE intAsciiDec #
|
Render double interpreting non-real values,
as is.
|
Render double interpreting non real values,
|
|
|
Does pretty much the same as 'Data.Text.Encoding.encodeUtf8',
both implementation and performance-wise,
while allowing you to avoid redundant @memcpy@
Following are the benchmark results comparing the performance of
@('writeToByteString' . 'textUtf8')@ with
@Data.Text.Encoding.'Data.Text.Encoding.encodeUtf8'@
The results show that they are quite similar.
=== __Benchmark results__
> textUtf8/text/latin/10 31.10 ns
> textUtf8/text/latin/100 118.2 ns | module PtrPoker.Write where
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Internal as ByteString
import qualified PtrPoker.ByteString as ByteString
import qualified PtrPoker.Ffi as Ffi
import qualified PtrPoker.Poke as Poke
import PtrPoker.Prelude hiding (concat)
import qualified PtrPoker.Size as Size
Execute Write , producing strict ByteString .
# INLINEABLE writeToByteString #
writeToByteString :: Write -> ByteString
writeToByteString Write {..} =
ByteString.unsafeCreate writeSize (void . Poke.pokePtr writePoke)
data Write = Write
{ writeSize :: Int,
writePoke :: Poke.Poke
}
instance Semigroup Write where
Write lSize lPoke <> Write rSize rPoke =
Write (lSize + rSize) (lPoke <> rPoke)
# INLINE sconcat #
sconcat =
concat
instance Monoid Write where
# INLINE mempty #
mempty =
Write 0 mempty
# INLINE mconcat #
mconcat =
concat
Reuses the IsString instance of ' ByteString ' .
instance IsString Write where
fromString =
byteString . fromString
a foldable of writes .
# INLINE concat #
concat :: (Foldable f) => f Write -> Write
concat f =
Write
(foldl' (\a b -> a + writeSize b) 0 f)
(Poke.Poke (\p -> foldM (\p write -> Poke.pokePtr (writePoke write) p) p f))
# INLINE word8 #
word8 :: Word8 -> Write
word8 a =
Write 1 (Poke.word8 a)
# INLINE lWord16 #
lWord16 :: Word16 -> Write
lWord16 a =
Write 2 (Poke.lWord16 a)
# INLINE bWord16 #
bWord16 :: Word16 -> Write
bWord16 a =
Write 2 (Poke.bWord16 a)
Render Word32 in Little - endian .
# INLINE lWord32 #
lWord32 :: Word32 -> Write
lWord32 a =
Write 4 (Poke.lWord32 a)
# INLINE bWord32 #
bWord32 :: Word32 -> Write
bWord32 a =
Write 4 (Poke.bWord32 a)
# INLINE lWord64 #
lWord64 :: Word64 -> Write
lWord64 a =
Write 8 (Poke.lWord64 a)
# INLINE bWord64 #
bWord64 :: Word64 -> Write
bWord64 a =
Write 8 (Poke.bWord64 a)
# INLINE lInt16 #
lInt16 :: Int16 -> Write
lInt16 a =
Write 2 (Poke.lInt16 a)
# INLINE bInt16 #
bInt16 :: Int16 -> Write
bInt16 a =
Write 2 (Poke.bInt16 a)
# INLINE lInt32 #
lInt32 :: Int32 -> Write
lInt32 a =
Write 4 (Poke.lInt32 a)
# INLINE bInt32 #
bInt32 :: Int32 -> Write
bInt32 a =
Write 4 (Poke.bInt32 a)
Render Int64 in Little - endian .
lInt64 :: Int64 -> Write
lInt64 a =
Write 8 (Poke.lInt64 a)
Render Int64 in Big - endian .
bInt64 :: Int64 -> Write
bInt64 a =
Write 8 (Poke.bInt64 a)
# INLINE word64AsciiDec #
word64AsciiDec :: Word64 -> Write
word64AsciiDec a =
Write size poke
where
size =
Size.word64AsciiDec a
poke =
Poke.sizedReverse size (Ffi.revPokeUInt64 (fromIntegral a))
Render Word in ASCII decimal .
wordAsciiDec :: Word -> Write
wordAsciiDec =
word64AsciiDec . fromIntegral
Render Int64 in ASCII decimal .
# INLINE int64AsciiDec #
int64AsciiDec :: Int64 -> Write
int64AsciiDec a =
Write size poke
where
size =
Size.int64AsciiDec a
poke =
Poke.sizedReverse size (Ffi.revPokeInt64 (fromIntegral a))
intAsciiDec :: Int -> Write
intAsciiDec =
int64AsciiDec . fromIntegral
such as @NaN@ , @Infinity@ , @-Infinity@ ,
# INLINE doubleAsciiDec #
doubleAsciiDec :: Double -> Write
doubleAsciiDec a =
if a == 0
then word8 48
else
if isNaN a
then "NaN"
else
if isInfinite a
then
if a < 0
then "-Infinity"
else "Infinity"
else
if a < 0
then word8 45 <> byteString (ByteString.double (negate a))
else byteString (ByteString.double a)
such as @NaN@ , @Infinity@ , @-Infinity@ ,
as zero .
# INLINE zeroNonRealDoubleAsciiDec #
zeroNonRealDoubleAsciiDec :: Double -> Write
zeroNonRealDoubleAsciiDec a =
if a == 0 || isNaN a || isInfinite a
then word8 48
else
if a < 0
then word8 45 <> byteString (ByteString.double (negate a))
else byteString (ByteString.double a)
Render Scientific in ASCII decimal .
# INLINE scientificAsciiDec #
scientificAsciiDec :: Scientific -> Write
scientificAsciiDec =
byteString . ByteString.scientific
Efficiently copy the contents of ByteString using @memcpy@.
# INLINE byteString #
byteString :: ByteString -> Write
byteString a =
Write (ByteString.length a) (inline Poke.byteString a)
Render Text in UTF8 .
compared to @('byteString ' . ' Data . Text . Encoding.encodeUtf8')@.
on inputs in Latin and Greek ( requiring different number of surrogate bytes ) .
> textUtf8 / ptr - poker / 25.61 ns
> textUtf8 / ptr - poker / latin/10 31.59 ns
> textUtf8 / ptr - poker / latin/100 121.5 ns
> textUtf8 / ptr - poker / greek/1 28.54 ns
> textUtf8 / ptr - poker / greek/10 41.97 ns
> textUtf8 / ptr - poker / greek/100 250.3 ns
> textUtf8 / text / latin/1 22.84 ns
> textUtf8 / text / greek/1 25.80 ns
> textUtf8 / text / greek/10 40.80 ns
> textUtf8 / text / greek/100 293.1 ns
# INLINEABLE textUtf8 #
textUtf8 :: Text -> Write
textUtf8 a =
Write (Size.textUtf8 a) (Poke.textUtf8 a)
|
9fce5667ebd538329de70e15fe7f8ac7789e0e47c0ccfc496480f321d5352471 | poor-a/erlang-ffi | OTP.hs | -- |
Module : Foreign . Erlang . OTP
Copyright : ( c ) , 2008
( c ) , 2015
-- License : GPL3
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
module Foreign.Erlang.OTP (
module Foreign.Erlang.OTP.GenServer
, module Foreign.Erlang.OTP.Mnesia
) where
import Foreign.Erlang.OTP.GenServer
import Foreign.Erlang.OTP.Mnesia
| null | https://raw.githubusercontent.com/poor-a/erlang-ffi/9d03d5a0f2000ad3e3f12c721c8b597ba42185b6/src/Foreign/Erlang/OTP.hs | haskell | |
License : GPL3
Maintainer :
Stability : experimental
Portability : portable
| Module : Foreign . Erlang . OTP
Copyright : ( c ) , 2008
( c ) , 2015
module Foreign.Erlang.OTP (
module Foreign.Erlang.OTP.GenServer
, module Foreign.Erlang.OTP.Mnesia
) where
import Foreign.Erlang.OTP.GenServer
import Foreign.Erlang.OTP.Mnesia
|
c5642a1f97fb3e58bf6c225ae6a99ea0e99305eaab09642d80e7bdcbf9f017d3 | pfdietz/ansi-test | format-o.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Aug 1 06:36:30 2004
;;;; Contains: Tests of format directive ~O
(deftest format.o.1
(let ((fn (formatter "~o")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for s1 = (format nil "~O" i)
for j = (let ((*read-base* 8)) (read-from-string s1))
for s2 = (formatter-call-to-string fn i)
repeat 1000
when (or (/= i j)
(not (string= s1 s2))
(find #\. s1)
(find #\+ s1)
(find-if #'alpha-char-p s1))
collect (list i s1 j s2))))
nil)
(deftest format.o.2
(let ((fn (formatter "~@O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@o" i)
for j = (let ((*read-base* 8)) (read-from-string s1))
for s2 = (formatter-call-to-string fn i)
repeat 1000
when (or (/= i j)
(not (string= s1 s2))
(find #\. s1)
( find # \+ s1 )
(find-if #'alpha-char-p s1))
collect (list i s1 j s2))))
nil)
(deftest format.o.3
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~do" mincol)
for s2 = (format nil fmt i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest formatter.o.3
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~do" mincol)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
for pos = (search s1 s2)
repeat 100
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest format.o.4
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@O" i)
for fmt = (format nil "~~~d@o" mincol)
for s2 = (format nil fmt i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(and (>= i 0) (not (eql (elt s1 0) #\+)))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest formatter.o.4
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@O" i)
for fmt = (format nil "~~~d@o" mincol)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
for pos = (search s1 s2)
repeat 100
when (or (null pos)
(and (>= i 0) (not (eql (elt s1 0) #\+)))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest format.o.5
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~d,'~c~c" mincol padchar
(random-from-seq "oO"))
for s2 = (format nil fmt i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest formatter.o.5
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~d,'~c~c" mincol padchar
(random-from-seq "oO"))
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
for pos = (search s1 s2)
repeat 100
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest format.o.6
(let ((fn (formatter "~V,Vo")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for s2 = (format nil "~v,vO" mincol padchar i)
for s3 = (formatter-call-to-string fn mincol padchar i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(not (string= s2 s3))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 s3 pos))))
nil)
(deftest format.o.7
(let ((fn (formatter "~v,V@O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@o" i)
for s2 = (format nil "~v,v@o" mincol padchar i)
for s3 = (formatter-call-to-string fn mincol padchar i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(not (string= s2 s3))
(and (>= i 0) (not (eql (elt s1 0) #\+)))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 s3 pos))))
nil)
;;; Comma tests
(deftest format.o.8
(let ((fn (formatter "~:O")))
(loop for i from #o-777 to #o777
for s1 = (format nil "~o" i)
for s2 = (format nil "~:o" i)
for s3 = (formatter-call-to-string fn i)
unless (and (string= s1 s2) (string= s2 s3))
collect (list i s1 s2 s3)))
nil)
(deftest format.o.9
(let ((fn (formatter "~:o")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = #\,
for s1 = (format nil "~o" i)
for s2 = (format nil "~:O" i)
for s3 = (formatter-call-to-string fn i)
repeat 1000
unless (and (string= s1 (remove commachar s2))
(string= s2 s3)
(not (eql (elt s2 0) commachar))
(or (>= i 0) (not (eql (elt s2 1) commachar)))
(let ((len (length s2))
(ci+1 4))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(find (elt s2 i) "01234567")))))
collect (list x i commachar s1 s2 s3))))
nil)
(deftest format.o.10
(let ((fn (formatter "~,,v:o")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for s1 = (format nil "~o" i)
for s2 = (format nil "~,,v:o" commachar i)
for s3 = (formatter-call-to-string fn commachar i)
repeat 1000
unless (and
(eql (elt s1 0) (elt s2 0))
(string= s2 s3)
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 4)
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2 s3))))
nil)
(deftest format.o.11
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~,,'~c:~c" commachar (random-from-seq "oO"))
for s2 = (format nil fmt i)
repeat 1000
unless (and
(eql (elt s1 0) (elt s2 0))
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 4)
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2)))
nil)
(deftest formatter.o.11
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~,,'~c:~c" commachar (random-from-seq "oO"))
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
repeat 100
unless (and
(eql (elt s1 0) (elt s2 0))
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 4)
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2)))
nil)
(deftest format.o.12
(let ((fn (formatter "~,,V,v:O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for commaint = (1+ (random 20))
for s1 = (format nil "~o" i)
for s2 = (format nil "~,,v,v:O" commachar commaint i)
for s3 = (formatter-call-to-string fn commachar commaint i)
repeat 1000
unless (and
(eql (elt s1 0) (elt s2 0))
(string= s2 s3)
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 (1+ commaint))
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2 s3))))
nil)
(deftest format.o.13
(let ((fn (formatter "~,,v,V@:O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for commaint = (1+ (random 20))
for s1 = (format nil "~@o" i)
for s2 = (format nil "~,,v,v:@o" commachar commaint i)
for s3 = (formatter-call-to-string fn commachar commaint i)
repeat 1000
unless (and
(string= s2 s3)
(eql (elt s1 0) (elt s2 0))
(eql (elt s1 1) (elt s2 1))
(let ((len (length s2))
(ci+1 (1+ commaint))
(j 1))
(loop for i from 2 below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2 s3))))
nil)
NIL arguments
(def-format-test format.o.14
"~vO" (nil #o100) "100")
(def-format-test format.o.15
"~6,vO" (nil #o100) " 100")
(def-format-test format.o.16
"~,,v:o" (nil #o12345) "12,345")
(def-format-test format.o.17
"~,,'*,v:o" (nil #o12345) "12*345")
When the argument is not an integer , print as if using ~A and base 10
(deftest format.o.18
(let ((fn (formatter "~o")))
(loop for x in *mini-universe*
for s1 = (format nil "~o" x)
for s2 = (let ((*print-base* 8)) (format nil "~A" x))
for s3 = (formatter-call-to-string fn x)
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3)))
collect (list x s1 s2 s3)))
nil)
(deftest format.o.19
(let ((fn (formatter "~:o")))
(loop for x in *mini-universe*
for s1 = (format nil "~:o" x)
for s2 = (let ((*print-base* 8)) (format nil "~A" x))
for s3 = (formatter-call-to-string fn x)
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3)))
collect (list x s1 s2 s3)))
nil)
(deftest format.o.20
(let ((fn (formatter "~@o")))
(loop for x in *mini-universe*
for s1 = (format nil "~@o" x)
for s2 = (let ((*print-base* 8)) (format nil "~A" x))
for s3 = (formatter-call-to-string fn x)
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3)))
collect (list x s1 s2 s3)))
nil)
(deftest format.o.21
(let ((fn (formatter "~:@o")))
(loop for x in *mini-universe*
for s1 = (let ((*print-base* 8)) (format nil "~A" x))
for s2 = (format nil "~@:o" x)
for s3 = (formatter-call-to-string fn x)
for s4 = (let ((*print-base* 8)) (format nil "~A" x))
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3))
(string/= s1 s4))
collect (list x s1 s2 s3)))
nil)
;;; Must add tests for non-integers when the parameters
;;; are specified, but it's not clear what the meaning is.
Does mincol apply to the ~A equivalent ? What about padchar ?
;;; Are comma-char and comma-interval always ignored?
;;; # arguments
(deftest format.o.22
(apply
#'values
(let ((fn (formatter "~#o"))
(n #o12345))
(loop for i from 0 to 10
for args = (make-list i)
for s = (apply #'format nil "~#o" n args)
for s2 = (with-output-to-string
(stream)
(assert (equal (apply fn stream n args) args)))
do (assert (string= s s2))
collect s)))
"12345"
"12345"
"12345"
"12345"
"12345"
" 12345"
" 12345"
" 12345"
" 12345"
" 12345"
" 12345")
(deftest format.o.23
(apply
#'values
(let ((fn (formatter "~,,,#:o"))
(n #o1234567012))
(loop for i from 0 to 10
for args = (make-list i)
for s = (apply #'format nil "~,,,#:o" n args)
for s2 = (with-output-to-string
(stream)
(assert (equal (apply fn stream n args) args)))
do (assert (string= s s2))
collect s)))
"1,2,3,4,5,6,7,0,1,2"
"12,34,56,70,12"
"1,234,567,012"
"12,3456,7012"
"12345,67012"
"1234,567012"
"123,4567012"
"12,34567012"
"1,234567012"
"1234567012"
"1234567012")
(deftest format.o.24
(apply
#'values
(let ((fn (formatter "~,,,#:@o"))
(n #o1234567012))
(loop for i from 0 to 10
for args = (make-list i)
for s = (apply #'format nil "~,,,#@:O" n args)
for s2 = (with-output-to-string
(stream)
(assert (equal (apply fn stream n args) args)))
do (assert (string= s s2))
collect s)))
"+1,2,3,4,5,6,7,0,1,2"
"+12,34,56,70,12"
"+1,234,567,012"
"+12,3456,7012"
"+12345,67012"
"+1234,567012"
"+123,4567012"
"+12,34567012"
"+1,234567012"
"+1234567012"
"+1234567012")
(def-format-test format.o.25
"~+10o" (#o1234) " 1234")
(def-format-test format.o.26
"~+10@O" (#o1234) " +1234")
(def-format-test format.o.27
"~-1O" (#o1234) "1234")
(def-format-test format.o.28
"~-1000000000000000000o" (#o1234) "1234")
(def-format-test format.o.29
"~vo" ((1- most-negative-fixnum) #o1234) "1234")
;;; Randomized test
(deftest format.o.30
(let ((fn (formatter "~v,v,v,vo")))
(loop
for mincol = (and (coin) (random 50))
for padchar = (and (coin)
(random-from-seq +standard-chars+))
for commachar = (and (coin)
(random-from-seq +standard-chars+))
for commaint = (and (coin) (1+ (random 10)))
for k = (ash 1 (+ 2 (random 30)))
for x = (- (random (+ k k)) k)
for fmt = (concatenate
'string
(if mincol (format nil "~~~d," mincol) "~,")
(if padchar (format nil "'~c," padchar) ",")
(if commachar (format nil "'~c," commachar) ",")
(if commaint (format nil "~do" commaint) "o"))
for s1 = (format nil fmt x)
for s2 = (format nil "~v,v,v,vo" mincol padchar commachar commaint x)
for s3 = (formatter-call-to-string fn mincol padchar commachar commaint x)
repeat 2000
unless (and (string= s1 s2) (string= s2 s3))
collect (list mincol padchar commachar commaint fmt x s1 s2 s3)))
nil)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/printer/format/format-o.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests of format directive ~O
Comma tests
Must add tests for non-integers when the parameters
are specified, but it's not clear what the meaning is.
Are comma-char and comma-interval always ignored?
# arguments
Randomized test | Author :
Created : Sun Aug 1 06:36:30 2004
(deftest format.o.1
(let ((fn (formatter "~o")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for s1 = (format nil "~O" i)
for j = (let ((*read-base* 8)) (read-from-string s1))
for s2 = (formatter-call-to-string fn i)
repeat 1000
when (or (/= i j)
(not (string= s1 s2))
(find #\. s1)
(find #\+ s1)
(find-if #'alpha-char-p s1))
collect (list i s1 j s2))))
nil)
(deftest format.o.2
(let ((fn (formatter "~@O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@o" i)
for j = (let ((*read-base* 8)) (read-from-string s1))
for s2 = (formatter-call-to-string fn i)
repeat 1000
when (or (/= i j)
(not (string= s1 s2))
(find #\. s1)
( find # \+ s1 )
(find-if #'alpha-char-p s1))
collect (list i s1 j s2))))
nil)
(deftest format.o.3
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~do" mincol)
for s2 = (format nil fmt i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest formatter.o.3
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~do" mincol)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
for pos = (search s1 s2)
repeat 100
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest format.o.4
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@O" i)
for fmt = (format nil "~~~d@o" mincol)
for s2 = (format nil fmt i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(and (>= i 0) (not (eql (elt s1 0) #\+)))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest formatter.o.4
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@O" i)
for fmt = (format nil "~~~d@o" mincol)
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
for pos = (search s1 s2)
repeat 100
when (or (null pos)
(and (>= i 0) (not (eql (elt s1 0) #\+)))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(not (eql (position #\Space s2 :test-not #'eql)
(- (length s2) (length s1)))))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest format.o.5
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~d,'~c~c" mincol padchar
(random-from-seq "oO"))
for s2 = (format nil fmt i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest formatter.o.5
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~~d,'~c~c" mincol padchar
(random-from-seq "oO"))
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
for pos = (search s1 s2)
repeat 100
when (or (null pos)
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 pos)))
nil)
(deftest format.o.6
(let ((fn (formatter "~V,Vo")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~o" i)
for s2 = (format nil "~v,vO" mincol padchar i)
for s3 = (formatter-call-to-string fn mincol padchar i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(not (string= s2 s3))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 s3 pos))))
nil)
(deftest format.o.7
(let ((fn (formatter "~v,V@O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for mincol = (random 30)
for padchar = (random-from-seq +standard-chars+)
for i = (- (random (+ x x)) x)
for s1 = (format nil "~@o" i)
for s2 = (format nil "~v,v@o" mincol padchar i)
for s3 = (formatter-call-to-string fn mincol padchar i)
for pos = (search s1 s2)
repeat 1000
when (or (null pos)
(not (string= s2 s3))
(and (>= i 0) (not (eql (elt s1 0) #\+)))
(and (> mincol (length s1))
(or (/= (length s2) mincol)
(find padchar s2 :end (- (length s2) (length s1))
:test-not #'eql))))
collect (list i mincol s1 s2 s3 pos))))
nil)
(deftest format.o.8
(let ((fn (formatter "~:O")))
(loop for i from #o-777 to #o777
for s1 = (format nil "~o" i)
for s2 = (format nil "~:o" i)
for s3 = (formatter-call-to-string fn i)
unless (and (string= s1 s2) (string= s2 s3))
collect (list i s1 s2 s3)))
nil)
(deftest format.o.9
(let ((fn (formatter "~:o")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = #\,
for s1 = (format nil "~o" i)
for s2 = (format nil "~:O" i)
for s3 = (formatter-call-to-string fn i)
repeat 1000
unless (and (string= s1 (remove commachar s2))
(string= s2 s3)
(not (eql (elt s2 0) commachar))
(or (>= i 0) (not (eql (elt s2 1) commachar)))
(let ((len (length s2))
(ci+1 4))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(find (elt s2 i) "01234567")))))
collect (list x i commachar s1 s2 s3))))
nil)
(deftest format.o.10
(let ((fn (formatter "~,,v:o")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for s1 = (format nil "~o" i)
for s2 = (format nil "~,,v:o" commachar i)
for s3 = (formatter-call-to-string fn commachar i)
repeat 1000
unless (and
(eql (elt s1 0) (elt s2 0))
(string= s2 s3)
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 4)
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2 s3))))
nil)
(deftest format.o.11
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~,,'~c:~c" commachar (random-from-seq "oO"))
for s2 = (format nil fmt i)
repeat 1000
unless (and
(eql (elt s1 0) (elt s2 0))
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 4)
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2)))
nil)
(deftest formatter.o.11
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for s1 = (format nil "~o" i)
for fmt = (format nil "~~,,'~c:~c" commachar (random-from-seq "oO"))
for fn = (eval `(formatter ,fmt))
for s2 = (formatter-call-to-string fn i)
repeat 100
unless (and
(eql (elt s1 0) (elt s2 0))
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 4)
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2)))
nil)
(deftest format.o.12
(let ((fn (formatter "~,,V,v:O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for commaint = (1+ (random 20))
for s1 = (format nil "~o" i)
for s2 = (format nil "~,,v,v:O" commachar commaint i)
for s3 = (formatter-call-to-string fn commachar commaint i)
repeat 1000
unless (and
(eql (elt s1 0) (elt s2 0))
(string= s2 s3)
(if (< i 0) (eql (elt s1 1) (elt s2 1)) t)
(let ((len (length s2))
(ci+1 (1+ commaint))
(j (if (< i 0) 1 0)))
(loop for i from (if (< i 0) 2 1) below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2 s3))))
nil)
(deftest format.o.13
(let ((fn (formatter "~,,v,V@:O")))
(with-standard-io-syntax
(loop for x = (ash 1 (+ 2 (random 80)))
for i = (- (random (+ x x)) x)
for commachar = (random-from-seq +standard-chars+)
for commaint = (1+ (random 20))
for s1 = (format nil "~@o" i)
for s2 = (format nil "~,,v,v:@o" commachar commaint i)
for s3 = (formatter-call-to-string fn commachar commaint i)
repeat 1000
unless (and
(string= s2 s3)
(eql (elt s1 0) (elt s2 0))
(eql (elt s1 1) (elt s2 1))
(let ((len (length s2))
(ci+1 (1+ commaint))
(j 1))
(loop for i from 2 below len
always (if (= (mod (- len i) ci+1) 0)
(eql (elt s2 i) commachar)
(eql (elt s1 (incf j)) (elt s2 i))))))
collect (list x i commachar s1 s2 s3))))
nil)
NIL arguments
(def-format-test format.o.14
"~vO" (nil #o100) "100")
(def-format-test format.o.15
"~6,vO" (nil #o100) " 100")
(def-format-test format.o.16
"~,,v:o" (nil #o12345) "12,345")
(def-format-test format.o.17
"~,,'*,v:o" (nil #o12345) "12*345")
When the argument is not an integer , print as if using ~A and base 10
(deftest format.o.18
(let ((fn (formatter "~o")))
(loop for x in *mini-universe*
for s1 = (format nil "~o" x)
for s2 = (let ((*print-base* 8)) (format nil "~A" x))
for s3 = (formatter-call-to-string fn x)
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3)))
collect (list x s1 s2 s3)))
nil)
(deftest format.o.19
(let ((fn (formatter "~:o")))
(loop for x in *mini-universe*
for s1 = (format nil "~:o" x)
for s2 = (let ((*print-base* 8)) (format nil "~A" x))
for s3 = (formatter-call-to-string fn x)
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3)))
collect (list x s1 s2 s3)))
nil)
(deftest format.o.20
(let ((fn (formatter "~@o")))
(loop for x in *mini-universe*
for s1 = (format nil "~@o" x)
for s2 = (let ((*print-base* 8)) (format nil "~A" x))
for s3 = (formatter-call-to-string fn x)
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3)))
collect (list x s1 s2 s3)))
nil)
(deftest format.o.21
(let ((fn (formatter "~:@o")))
(loop for x in *mini-universe*
for s1 = (let ((*print-base* 8)) (format nil "~A" x))
for s2 = (format nil "~@:o" x)
for s3 = (formatter-call-to-string fn x)
for s4 = (let ((*print-base* 8)) (format nil "~A" x))
unless (or (integerp x) (and (string= s1 s2) (string= s2 s3))
(string/= s1 s4))
collect (list x s1 s2 s3)))
nil)
Does mincol apply to the ~A equivalent ? What about padchar ?
(deftest format.o.22
(apply
#'values
(let ((fn (formatter "~#o"))
(n #o12345))
(loop for i from 0 to 10
for args = (make-list i)
for s = (apply #'format nil "~#o" n args)
for s2 = (with-output-to-string
(stream)
(assert (equal (apply fn stream n args) args)))
do (assert (string= s s2))
collect s)))
"12345"
"12345"
"12345"
"12345"
"12345"
" 12345"
" 12345"
" 12345"
" 12345"
" 12345"
" 12345")
(deftest format.o.23
(apply
#'values
(let ((fn (formatter "~,,,#:o"))
(n #o1234567012))
(loop for i from 0 to 10
for args = (make-list i)
for s = (apply #'format nil "~,,,#:o" n args)
for s2 = (with-output-to-string
(stream)
(assert (equal (apply fn stream n args) args)))
do (assert (string= s s2))
collect s)))
"1,2,3,4,5,6,7,0,1,2"
"12,34,56,70,12"
"1,234,567,012"
"12,3456,7012"
"12345,67012"
"1234,567012"
"123,4567012"
"12,34567012"
"1,234567012"
"1234567012"
"1234567012")
(deftest format.o.24
(apply
#'values
(let ((fn (formatter "~,,,#:@o"))
(n #o1234567012))
(loop for i from 0 to 10
for args = (make-list i)
for s = (apply #'format nil "~,,,#@:O" n args)
for s2 = (with-output-to-string
(stream)
(assert (equal (apply fn stream n args) args)))
do (assert (string= s s2))
collect s)))
"+1,2,3,4,5,6,7,0,1,2"
"+12,34,56,70,12"
"+1,234,567,012"
"+12,3456,7012"
"+12345,67012"
"+1234,567012"
"+123,4567012"
"+12,34567012"
"+1,234567012"
"+1234567012"
"+1234567012")
(def-format-test format.o.25
"~+10o" (#o1234) " 1234")
(def-format-test format.o.26
"~+10@O" (#o1234) " +1234")
(def-format-test format.o.27
"~-1O" (#o1234) "1234")
(def-format-test format.o.28
"~-1000000000000000000o" (#o1234) "1234")
(def-format-test format.o.29
"~vo" ((1- most-negative-fixnum) #o1234) "1234")
(deftest format.o.30
(let ((fn (formatter "~v,v,v,vo")))
(loop
for mincol = (and (coin) (random 50))
for padchar = (and (coin)
(random-from-seq +standard-chars+))
for commachar = (and (coin)
(random-from-seq +standard-chars+))
for commaint = (and (coin) (1+ (random 10)))
for k = (ash 1 (+ 2 (random 30)))
for x = (- (random (+ k k)) k)
for fmt = (concatenate
'string
(if mincol (format nil "~~~d," mincol) "~,")
(if padchar (format nil "'~c," padchar) ",")
(if commachar (format nil "'~c," commachar) ",")
(if commaint (format nil "~do" commaint) "o"))
for s1 = (format nil fmt x)
for s2 = (format nil "~v,v,v,vo" mincol padchar commachar commaint x)
for s3 = (formatter-call-to-string fn mincol padchar commachar commaint x)
repeat 2000
unless (and (string= s1 s2) (string= s2 s3))
collect (list mincol padchar commachar commaint fmt x s1 s2 s3)))
nil)
|
5891e9b8e6560deb2cc37486d60449e652a2a571a8c6cb88b21e206ce487894a | hyperfiddle/electric | hfql16.clj | (ns dustin.hfql16
(:refer-clojure :exclude [sequence])
(:require [dustin.fiddle :refer :all]
[dustin.hf-nav :refer :all]
[meander.epsilon :as m :refer [match]]
[minitest :refer [tests]]
[promesa.core :as p]))
(defn pureSR [a]
(fn [s] (p/resolved [s a])))
(defn runS [SMa s]
(SMa s))
(defn bindSR [SRa f]
(fn [s]
(p/then (runS SRa s)
(fn [[s' a]]
(runS (f a) (merge s s'))))))
(tests
( runStateT ( pureSR 1 ) { } ) : = ( p / resolved [ { } 1 ] ) ; fails
@(runS (pureSR 1) {}) := @(p/resolved [{} 1])
@(runS
(bindSR (pureSR 1)
(fn [a]
(fn [s]
(p/resolved
[s (+ a (get s 'C))]))))
{'C 42})
:= @(p/resolved [{'C 42} 43])
)
(defn fmapSR [f SRa]
(fn [s]
(p/map
(fn [[s' a]]
[s (f a)])
(runS SRa s))))
( defn fmap [ f & Sas ]
; (fn [s]
; (let [as (->> Sas
; (map (fn [Sa]
; (let [[s' a] (run Sa s)]
; a))))]
; [s (apply f as)])))
(tests
@(runS (fmapSR inc (pureSR 1)) {})
:= @(p/resolved [{} 2])
( runS ( pureSR 1 ) { } ) : = [ { } 1 ]
( runS ( fmapSR + ( pureSR 1 ) ( pureSR 2 ) ) { } ) : = [ { } 3 ]
)
( defn sequenceSR [ mas ]
( apply fmapSR vector mas ) )
;(tests
; (run (sequence []) {}) := [{} []]
( run ( sequence [ ( pure 1 ) ( pure 2 ) ] ) { } ) : = [ { } [ 1 2 ] ]
; )
; ---
(defn hf-edge->sym [edge]
(if (keyword? edge) (symbol edge) edge))
(defn hf-apply [edge a scope]
(cond
(keyword? edge) (hf-nav edge a)
(seq? edge) (let [[f & args] edge]
(apply (clojure.core/resolve f) (replace scope args)))
() (println "hf-eval unmatched edge: " edge)))
(defn hf-eval [edge SRa]
(fn [s]
(p/map
(fn [[s' a]]
(let [b (hf-apply edge a (merge s s'))]
[(merge s {(hf-edge->sym edge) b})
b]))
(runS SRa s))))
(defn hf-pull-SR [pat SRa]
(match pat
one
(as-> SRa SRa
(hf-eval ?edge SRa)
(hf-pull-SR ?pat SRa)
#_(bindSR SRa (fn [a] (hf-pull-SR ?pat a)))
(fmapSR (fn [a] {?edge a}) SRa))
?leaf
(as-> SRa SRa
(hf-eval ?leaf SRa)
(fmapSR (fn [a] {?leaf a}) SRa))))
instance MonadTrans ( StateT s ) where
lift c = StateT $ \s - > c > > = ( \x - > return ( x , s ) )
(defn Ra->SRa ; lift ?
"upgrade base monad value into transformed monad value"
[Ra]
(fn [s]
(p/map
(fn [a] [s a])
Ra)))
(tests
( Ra->SRa ( p / resolved 1 ) ) : = ( fn [ s ] ( p / resolved [ s 1 ] ) )
@(runS (Ra->SRa (p/resolved 1)) {})
:= @(runS (fn [s] (p/resolved [s 1])) {})
:= @(p/resolved [{} 1])
:= [{} 1]
)
(defn hf-pull [pat Ra & [s]]
(p/map
(fn [[s' b]] b)
(runS (hf-pull-SR pat (Ra->SRa Ra)) (or s {}))))
(tests
@(runS (pureSR 17592186045421) {}) := [{} 17592186045421]
@(runS (hf-eval :dustingetz/gender (pureSR 17592186045421)) {})
:= @(p/resolved ['{dustingetz/gender :dustingetz/male} :dustingetz/male])
@(runS (hf-pull-SR :dustingetz/gender (pureSR 17592186045421)) {})
:= [{} #:dustingetz{:gender :dustingetz/male}]
@(hf-pull :dustingetz/gender (p/resolved 17592186045421))
:= #:dustingetz{:gender :dustingetz/male}
@(hf-pull :db/ident (p/resolved 17592186045421))
:= #:db{:ident :dustingetz/mens-small}
@(hf-pull '{:dustingetz/gender :db/ident} (p/resolved 17592186045421))
:= #:dustingetz{:gender #:db{:ident :dustingetz/male}}
@(hf-pull '(shirt-size dustingetz/gender) (p/resolved nil)
{'dustingetz/gender :dustingetz/male})
:= {'(shirt-size dustingetz/gender) 17592186045421}
@(hf-pull '{:dustingetz/gender (shirt-size dustingetz/gender)}
(p/resolved 17592186045421))
:= #:dustingetz{:gender {'(shirt-size dustingetz/gender) 17592186045421}}
@(hf-pull
'{:dustingetz/gender
{(shirt-size dustingetz/gender)
:db/ident}}
(p/resolved 17592186045421))
:= @(p/resolved
{:dustingetz/gender
{'(shirt-size dustingetz/gender)
{:db/ident :dustingetz/mens-small}}})
)
| null | https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2020/hfql/hfql16.clj | clojure | fails
(fn [s]
(let [as (->> Sas
(map (fn [Sa]
(let [[s' a] (run Sa s)]
a))))]
[s (apply f as)])))
(tests
(run (sequence []) {}) := [{} []]
)
---
lift ? | (ns dustin.hfql16
(:refer-clojure :exclude [sequence])
(:require [dustin.fiddle :refer :all]
[dustin.hf-nav :refer :all]
[meander.epsilon :as m :refer [match]]
[minitest :refer [tests]]
[promesa.core :as p]))
(defn pureSR [a]
(fn [s] (p/resolved [s a])))
(defn runS [SMa s]
(SMa s))
(defn bindSR [SRa f]
(fn [s]
(p/then (runS SRa s)
(fn [[s' a]]
(runS (f a) (merge s s'))))))
(tests
@(runS (pureSR 1) {}) := @(p/resolved [{} 1])
@(runS
(bindSR (pureSR 1)
(fn [a]
(fn [s]
(p/resolved
[s (+ a (get s 'C))]))))
{'C 42})
:= @(p/resolved [{'C 42} 43])
)
(defn fmapSR [f SRa]
(fn [s]
(p/map
(fn [[s' a]]
[s (f a)])
(runS SRa s))))
( defn fmap [ f & Sas ]
(tests
@(runS (fmapSR inc (pureSR 1)) {})
:= @(p/resolved [{} 2])
( runS ( pureSR 1 ) { } ) : = [ { } 1 ]
( runS ( fmapSR + ( pureSR 1 ) ( pureSR 2 ) ) { } ) : = [ { } 3 ]
)
( defn sequenceSR [ mas ]
( apply fmapSR vector mas ) )
( run ( sequence [ ( pure 1 ) ( pure 2 ) ] ) { } ) : = [ { } [ 1 2 ] ]
(defn hf-edge->sym [edge]
(if (keyword? edge) (symbol edge) edge))
(defn hf-apply [edge a scope]
(cond
(keyword? edge) (hf-nav edge a)
(seq? edge) (let [[f & args] edge]
(apply (clojure.core/resolve f) (replace scope args)))
() (println "hf-eval unmatched edge: " edge)))
(defn hf-eval [edge SRa]
(fn [s]
(p/map
(fn [[s' a]]
(let [b (hf-apply edge a (merge s s'))]
[(merge s {(hf-edge->sym edge) b})
b]))
(runS SRa s))))
(defn hf-pull-SR [pat SRa]
(match pat
one
(as-> SRa SRa
(hf-eval ?edge SRa)
(hf-pull-SR ?pat SRa)
#_(bindSR SRa (fn [a] (hf-pull-SR ?pat a)))
(fmapSR (fn [a] {?edge a}) SRa))
?leaf
(as-> SRa SRa
(hf-eval ?leaf SRa)
(fmapSR (fn [a] {?leaf a}) SRa))))
instance MonadTrans ( StateT s ) where
lift c = StateT $ \s - > c > > = ( \x - > return ( x , s ) )
"upgrade base monad value into transformed monad value"
[Ra]
(fn [s]
(p/map
(fn [a] [s a])
Ra)))
(tests
( Ra->SRa ( p / resolved 1 ) ) : = ( fn [ s ] ( p / resolved [ s 1 ] ) )
@(runS (Ra->SRa (p/resolved 1)) {})
:= @(runS (fn [s] (p/resolved [s 1])) {})
:= @(p/resolved [{} 1])
:= [{} 1]
)
(defn hf-pull [pat Ra & [s]]
(p/map
(fn [[s' b]] b)
(runS (hf-pull-SR pat (Ra->SRa Ra)) (or s {}))))
(tests
@(runS (pureSR 17592186045421) {}) := [{} 17592186045421]
@(runS (hf-eval :dustingetz/gender (pureSR 17592186045421)) {})
:= @(p/resolved ['{dustingetz/gender :dustingetz/male} :dustingetz/male])
@(runS (hf-pull-SR :dustingetz/gender (pureSR 17592186045421)) {})
:= [{} #:dustingetz{:gender :dustingetz/male}]
@(hf-pull :dustingetz/gender (p/resolved 17592186045421))
:= #:dustingetz{:gender :dustingetz/male}
@(hf-pull :db/ident (p/resolved 17592186045421))
:= #:db{:ident :dustingetz/mens-small}
@(hf-pull '{:dustingetz/gender :db/ident} (p/resolved 17592186045421))
:= #:dustingetz{:gender #:db{:ident :dustingetz/male}}
@(hf-pull '(shirt-size dustingetz/gender) (p/resolved nil)
{'dustingetz/gender :dustingetz/male})
:= {'(shirt-size dustingetz/gender) 17592186045421}
@(hf-pull '{:dustingetz/gender (shirt-size dustingetz/gender)}
(p/resolved 17592186045421))
:= #:dustingetz{:gender {'(shirt-size dustingetz/gender) 17592186045421}}
@(hf-pull
'{:dustingetz/gender
{(shirt-size dustingetz/gender)
:db/ident}}
(p/resolved 17592186045421))
:= @(p/resolved
{:dustingetz/gender
{'(shirt-size dustingetz/gender)
{:db/ident :dustingetz/mens-small}}})
)
|
0edc31f62fa7d25117ef6860f3ee879f05a406c6d48b9a19b39510a1b90784f7 | xu-hao/QueryArrow | Utils.hs | # LANGUAGE TypeFamilies , MultiParamTypeClasses , ExistentialQuantification , FlexibleInstances , OverloadedStrings ,
RankNTypes , FlexibleContexts , GADTs #
RankNTypes, FlexibleContexts, GADTs #-}
module QueryArrow.Utils where
import QueryArrow.DB.ResultStream
import QueryArrow.Syntax.Term
import QueryArrow.ListUtils
import QueryArrow.DB.DB
import QueryArrow.Semantics.Value
import QueryArrow.Syntax.Type
import Prelude hiding (lookup)
import Data.Map.Strict (Map, empty, insert, alter, lookup, mapKeys)
import qualified Data.Map.Strict as M
import Data.List ((\\), intercalate, transpose)
import Control.Monad.Catch
import Data.Maybe
import Data.Tree
import Data.Text (Text, pack, unpack)
import Data.Text.Encoding
import Data.Int (Int64)
import Data.Conduit
import Data.Namespace.Namespace
intResultStream :: (Monad m) => Int64 -> ResultStream m MapResultRow
intResultStream i = yield (insert (Var "i") (Int64Value i) empty)
-- map from predicate name to database names
type PredDBMap = Map Pred [String]
constructDBPredMap :: IDatabase0 db => db -> PredMap
constructDBPredMap db = foldr addPredToMap mempty preds where
addPredToMap thepred map1 =
insertObject (predName thepred) thepred map1
preds = getPreds db
-- construct map from predicates to db names
constructPredDBMap :: [AbstractDatabase row form] -> PredDBMap
constructPredDBMap = foldr addPredFromDBToMap empty where
addPredFromDBToMap :: AbstractDatabase row form -> PredDBMap -> PredDBMap
addPredFromDBToMap (AbstractDatabase db) predmap = foldr addPredToMap predmap preds where
dbname = getName db
addPredToMap thepred = alter alterValue thepred
alterValue Nothing = Just [dbname]
alterValue (Just dbnames) = Just (dbname : dbnames)
preds = getPreds db
combineLits :: PredTypeMap -> [Lit] -> ([Atom] -> [Atom] -> a) -> ([Atom] -> a) -> (Atom -> a) -> a
combineLits ptm lits generateUpdate generateInsert generateDelete = do
let objpredlits = filter (isObjectPredLit ptm) lits
let proppredlits = lits \\ objpredlits
let (posobjpredatoms, negobjpredatoms) = splitPosNegLits objpredlits
let (pospropredatoms, negproppredatoms) = splitPosNegLits proppredlits
case (posobjpredatoms, negobjpredatoms) of
([], []) -> generateUpdate pospropredatoms negproppredatoms -- update property
([posobjatom], []) -> case negproppredatoms of
[] -> generateInsert (posobjatom:pospropredatoms) -- insert
_ -> error "trying to delete properties of an object to be created"
([], [negobjatom]) -> case (pospropredatoms, negproppredatoms) of
([], _) -> generateDelete negobjatom
_ -> error "tyring to modify propertiese of an object to be deleted" -- delete
([posobjatom], [negobjatom]) -> generateUpdate (posobjatom:pospropredatoms) (negobjatom:negproppredatoms) -- update property
x -> error ("combineLits: uncombinable " ++ show x)
dbCatch :: (MonadCatch m) => m a -> m (Either SomeException a)
dbCatch action =
try action
pprint2 :: Bool -> [String] -> [Map String String] -> String
pprint2 showhdr vars rows =
pprint3 showhdr (vars, map (\row -> map (g row) vars) rows) where
g::Map String String ->String-> String
g row var0 = case lookup var0 row of
Nothing -> "null"
Just e -> e
pprint3 :: Bool -> ([String], [[String]]) -> String
pprint3 showhdr (vars, rows) = (if showhdr then join vars ++ "\n" else "") ++ intercalate "\n" rowstrs ++ "\n" where
join = intercalate " " . map (uncurry pad) . zip collen
rowstrs = map join m2
m2 = transpose m
collen = map (maximumd 0 . map length) m
m = map f [0..length vars-1]
f var0 = map (g var0) rows
g::Int-> [String] -> String
g var0 row = row !! var0
pad n s
| length s < n = s ++ replicate (n - length s) ' '
| otherwise = s
pprint :: Bool -> Bool -> [Var] -> [MapResultRow] -> String
pprint showhdr showdetails vars rows =
pprint2 showhdr (map unVar vars) (map (mapKeys unVar . M.map (if showdetails then show else show2)) rows) where
show2 a =
case a of
Int64Value i -> show i
Int32Value i -> show i
StringValue i -> show i
_ -> show a
showPredMap :: PredMap -> String
showPredMap workspace =
let show3 (k,a) = (case k of
Nothing -> ""
Just k2 -> k2) ++ (case a of
Nothing -> ""
Just a2 -> ":" ++ show a2)
in
drawTree (fmap show3 (toTree workspace))
samePredAndKey :: PredTypeMap -> Atom -> Atom -> Bool
samePredAndKey ptm (Atom p1 args1) (Atom p2 args2) | p1 == p2 =
let predtype = fromMaybe (error ("samePredAndKey: cannot find predicate " ++ show p1)) (lookup p1 ptm) in
keyComponents predtype args1 == keyComponents predtype args2
samePredAndKey _ _ _ = False
unionPred :: PredTypeMap -> [Atom] -> [Atom] -> [Atom]
unionPred ptm as1 as2 =
as1 ++ filter (not . samePredAndKeys ptm as1) as2 where
samePredAndKeys ptm0 as0 atom0 = any (samePredAndKey ptm0 atom0) as0
| null | https://raw.githubusercontent.com/xu-hao/QueryArrow/4dd5b8a22c8ed2d24818de5b8bcaa9abc456ef0d/QueryArrow-common/src/QueryArrow/Utils.hs | haskell | map from predicate name to database names
construct map from predicates to db names
update property
insert
delete
update property
| # LANGUAGE TypeFamilies , MultiParamTypeClasses , ExistentialQuantification , FlexibleInstances , OverloadedStrings ,
RankNTypes , FlexibleContexts , GADTs #
RankNTypes, FlexibleContexts, GADTs #-}
module QueryArrow.Utils where
import QueryArrow.DB.ResultStream
import QueryArrow.Syntax.Term
import QueryArrow.ListUtils
import QueryArrow.DB.DB
import QueryArrow.Semantics.Value
import QueryArrow.Syntax.Type
import Prelude hiding (lookup)
import Data.Map.Strict (Map, empty, insert, alter, lookup, mapKeys)
import qualified Data.Map.Strict as M
import Data.List ((\\), intercalate, transpose)
import Control.Monad.Catch
import Data.Maybe
import Data.Tree
import Data.Text (Text, pack, unpack)
import Data.Text.Encoding
import Data.Int (Int64)
import Data.Conduit
import Data.Namespace.Namespace
intResultStream :: (Monad m) => Int64 -> ResultStream m MapResultRow
intResultStream i = yield (insert (Var "i") (Int64Value i) empty)
type PredDBMap = Map Pred [String]
constructDBPredMap :: IDatabase0 db => db -> PredMap
constructDBPredMap db = foldr addPredToMap mempty preds where
addPredToMap thepred map1 =
insertObject (predName thepred) thepred map1
preds = getPreds db
constructPredDBMap :: [AbstractDatabase row form] -> PredDBMap
constructPredDBMap = foldr addPredFromDBToMap empty where
addPredFromDBToMap :: AbstractDatabase row form -> PredDBMap -> PredDBMap
addPredFromDBToMap (AbstractDatabase db) predmap = foldr addPredToMap predmap preds where
dbname = getName db
addPredToMap thepred = alter alterValue thepred
alterValue Nothing = Just [dbname]
alterValue (Just dbnames) = Just (dbname : dbnames)
preds = getPreds db
combineLits :: PredTypeMap -> [Lit] -> ([Atom] -> [Atom] -> a) -> ([Atom] -> a) -> (Atom -> a) -> a
combineLits ptm lits generateUpdate generateInsert generateDelete = do
let objpredlits = filter (isObjectPredLit ptm) lits
let proppredlits = lits \\ objpredlits
let (posobjpredatoms, negobjpredatoms) = splitPosNegLits objpredlits
let (pospropredatoms, negproppredatoms) = splitPosNegLits proppredlits
case (posobjpredatoms, negobjpredatoms) of
([posobjatom], []) -> case negproppredatoms of
_ -> error "trying to delete properties of an object to be created"
([], [negobjatom]) -> case (pospropredatoms, negproppredatoms) of
([], _) -> generateDelete negobjatom
x -> error ("combineLits: uncombinable " ++ show x)
dbCatch :: (MonadCatch m) => m a -> m (Either SomeException a)
dbCatch action =
try action
pprint2 :: Bool -> [String] -> [Map String String] -> String
pprint2 showhdr vars rows =
pprint3 showhdr (vars, map (\row -> map (g row) vars) rows) where
g::Map String String ->String-> String
g row var0 = case lookup var0 row of
Nothing -> "null"
Just e -> e
pprint3 :: Bool -> ([String], [[String]]) -> String
pprint3 showhdr (vars, rows) = (if showhdr then join vars ++ "\n" else "") ++ intercalate "\n" rowstrs ++ "\n" where
join = intercalate " " . map (uncurry pad) . zip collen
rowstrs = map join m2
m2 = transpose m
collen = map (maximumd 0 . map length) m
m = map f [0..length vars-1]
f var0 = map (g var0) rows
g::Int-> [String] -> String
g var0 row = row !! var0
pad n s
| length s < n = s ++ replicate (n - length s) ' '
| otherwise = s
pprint :: Bool -> Bool -> [Var] -> [MapResultRow] -> String
pprint showhdr showdetails vars rows =
pprint2 showhdr (map unVar vars) (map (mapKeys unVar . M.map (if showdetails then show else show2)) rows) where
show2 a =
case a of
Int64Value i -> show i
Int32Value i -> show i
StringValue i -> show i
_ -> show a
showPredMap :: PredMap -> String
showPredMap workspace =
let show3 (k,a) = (case k of
Nothing -> ""
Just k2 -> k2) ++ (case a of
Nothing -> ""
Just a2 -> ":" ++ show a2)
in
drawTree (fmap show3 (toTree workspace))
samePredAndKey :: PredTypeMap -> Atom -> Atom -> Bool
samePredAndKey ptm (Atom p1 args1) (Atom p2 args2) | p1 == p2 =
let predtype = fromMaybe (error ("samePredAndKey: cannot find predicate " ++ show p1)) (lookup p1 ptm) in
keyComponents predtype args1 == keyComponents predtype args2
samePredAndKey _ _ _ = False
unionPred :: PredTypeMap -> [Atom] -> [Atom] -> [Atom]
unionPred ptm as1 as2 =
as1 ++ filter (not . samePredAndKeys ptm as1) as2 where
samePredAndKeys ptm0 as0 atom0 = any (samePredAndKey ptm0 atom0) as0
|
d5332b6e9590aa450da81ba475a7e85815192223e49b649b1fbadde499b8c008 | jyh/metaprl | nuprl_experiments.mli | extends Ma_subtype_1
| null | https://raw.githubusercontent.com/jyh/metaprl/51ba0bbbf409ecb7f96f5abbeb91902fdec47a19/theories/mesa/nuprl_experiments.mli | ocaml | extends Ma_subtype_1
| |
45db1be3b9b391d7d27e877f1c43a3cae3041a17a0000f8f1c306ca560cdf9f2 | AlexanderButs/ecrontab | crontab_schedule_tests.erl | -module(crontab_schedule_tests).
-author("alexb").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
% parse tests
should_throw_if_incorrect_field_value_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("/10 * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("-10 * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("10- * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse(",10 * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("/10, * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* /4 * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* -4 * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* 4- * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* ,4 * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* /4, * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * /3 * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * -3 * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * 3- * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * ,3 * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * /3, * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * /3 *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * -3 *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * 3- *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * ,3 *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * /3, *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * /1")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * -1")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * 1-")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * ,1")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * /1,")).
should_throw_if_lower_value_days_test() ->
?assertException(throw, {bad_field, _, lower_then, _}, crontab_schedule:parse("* * 0-5 * *")).
should_throw_if_lower_value_month_test() ->
?assertException(throw, {bad_field, _, lower_then, _}, crontab_schedule:parse("* * * 0-5 *")).
should_throw_if_greater_value_minutes_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("65-71 * * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("55-71 * * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("71-55 * * * *")).
should_throw_if_greater_value_hours_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* 25-27 * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* 19-27 * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* 27-19 * * *")).
should_throw_if_greater_value_days_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * 33-35 * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * 28-35 * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * 35-28 * *")).
should_throw_if_greater_value_month_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * 19-24 *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * 9-14 *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * 14-9 *")).
should_throw_if_greater_value_day_of_week_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * * 15-18")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * * 5-8")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * * 8-5")).
should_throw_if_parse_empty_string_test() ->
?assertException(throw, empty_string, crontab_schedule:parse("")).
should_throw_if_minute_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("bad * * * *")).
should_throw_if_hour_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* bad * * *")).
should_throw_if_day_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * bad * *")).
should_throw_if_month_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * bad *")).
should_throw_if_day_of_week_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * bad")).
should_throw_if_fields_are_not_five_test() ->
?assertException(throw, invalid_fields_count, crontab_schedule:parse("* * * * * *")).
should_parse_stars_into_tuple_with_all_test() ->
?assertEqual({all, all, all, all, all}, crontab_schedule:parse("* * * * *")).
% slash tests
should_parse_slash_with_star_into_tuple_with_segment_minutes_test() ->
?assertEqual({[5, 15, 25, 35, 45, 55], all, all, all, all}, crontab_schedule:parse("5/10 * * * *")),
?assertEqual({[0, 10, 20, 30, 40, 50], all, all, all, all}, crontab_schedule:parse("*/10 * * * *")),
?assertEqual({[0, 15, 30, 45], all, all, all, all}, crontab_schedule:parse("*/15 * * * *")).
should_parse_slash_with_star_into_tuple_with_segment_hours_test() ->
?assertEqual({all, [2, 6, 10, 14, 18, 22], all, all, all}, crontab_schedule:parse("* 2/4 * * *")),
?assertEqual({all, [0, 4, 8, 12, 16, 20], all, all, all}, crontab_schedule:parse("* */4 * * *")),
?assertEqual({all, [0, 6, 12, 18], all, all, all}, crontab_schedule:parse("* */6 * * *")).
should_parse_slash_with_star_into_tuple_with_segment_days_test() ->
?assertEqual({all, all, [3, 8, 13, 18, 23, 28], all, all}, crontab_schedule:parse("* * 3/5 * *")),
?assertEqual({all, all, [1, 6, 11, 16, 21, 26, 31], all, all}, crontab_schedule:parse("* * */5 * *")),
?assertEqual({all, all, [1, 11, 21, 31], all, all}, crontab_schedule:parse("* * */10 * *")).
should_parse_slash_with_star_into_tuple_with_segment_month_test() ->
?assertEqual({all, all, all, [2, 5, 8, 11], all}, crontab_schedule:parse("* * * 2/3 *")),
?assertEqual({all, all, all, [1, 4, 7, 10], all}, crontab_schedule:parse("* * * */3 *")),
?assertEqual({all, all, all, [1, 6, 11], all}, crontab_schedule:parse("* * * */5 *")).
should_parse_slash_with_star_into_tuple_with_segment_day_of_week_test() ->
?assertEqual({all, all, all, all, [1, 3, 5]}, crontab_schedule:parse("* * * * 1/2")),
?assertEqual({all, all, all, all, [0, 2, 4, 6]}, crontab_schedule:parse("* * * * */2")),
?assertEqual({all, all, all, all, [0, 3, 6]}, crontab_schedule:parse("* * * * */3")),
?assertEqual({all, all, all, all, [0, 1, 2, 3, 4, 5, 6]}, crontab_schedule:parse("* * * * */1")).
% dash tests
should_parse_dash_into_tuple_with_segment_minutes_test() ->
?assertEqual({[10, 11, 12, 13, 14, 15], all, all, all, all}, crontab_schedule:parse("10-15 * * * *")),
?assertEqual({[37, 38, 39, 40, 41], all, all, all, all}, crontab_schedule:parse("41-37 * * * *")).
should_parse_dash_into_tuple_with_segment_hours_test() ->
?assertEqual({all, [4, 5, 6], all, all, all}, crontab_schedule:parse("* 4-6 * * *")),
?assertEqual({all, [7, 8, 9, 10, 11], all, all, all}, crontab_schedule:parse("* 11-7 * * *")).
should_parse_dash_into_tuple_with_segment_days_test() ->
?assertEqual({all, all, [5, 6, 7, 8], all, all}, crontab_schedule:parse("* * 5-8 * *")),
?assertEqual({all, all, [19, 20, 21, 22, 23], all, all}, crontab_schedule:parse("* * 23-19 * *")).
should_parse_dash_into_tuple_with_segment_month_test() ->
?assertEqual({all, all, all, [3, 4, 5, 6, 7], all}, crontab_schedule:parse("* * * 3-7 *")),
?assertEqual({all, all, all, [1, 2, 3, 4, 5], all}, crontab_schedule:parse("* * * 5-1 *")).
should_parse_dash_into_tuple_with_segment_day_of_week_test() ->
?assertEqual({all, all, all, all, [0, 1, 2]}, crontab_schedule:parse("* * * * 0-2")),
?assertEqual({all, all, all, all, [0, 1, 2, 3]}, crontab_schedule:parse("* * * * 3-0")).
% comma tests
should_parse_comma_into_tuple_with_segment_minutes_test() ->
?assertEqual({[10, 15, 17, 25], all, all, all, all}, crontab_schedule:parse("10,15,17,25 * * * *")).
should_parse_comma_into_tuple_with_segment_hours_test() ->
?assertEqual({all, [1, 5, 17, 23], all, all, all}, crontab_schedule:parse("* 1,5,17,23 * * *")).
should_parse_comma_into_tuple_with_segment_days_test() ->
?assertEqual({all, all, [5, 8, 26, 31], all, all}, crontab_schedule:parse("* * 5,8,26,31 * *")).
should_parse_comma_into_tuple_with_segment_month_test() ->
?assertEqual({all, all, all, [3, 7, 12], all}, crontab_schedule:parse("* * * 3,7,12 *")).
should_parse_comma_into_tuple_with_segment_day_of_week_test() ->
?assertEqual({all, all, all, all, [0, 2, 5]}, crontab_schedule:parse("* * * * 0,2,5")).
% mixed tests
should_parse_mixed_minutes_test() ->
?assertEqual({[10, 11, 12, 13, 14, 19, 29, 39, 49, 59], all, all, all, all}, crontab_schedule:parse("10-14,19/10 * * * *")),
?assertEqual({[10, 11, 12, 19, 20, 21, 30, 44, 58], all, all, all, all}, crontab_schedule:parse("10-12,19-21,30/14 * * * *")).
should_parse_mixed_hours_test() ->
?assertEqual({all, [10, 11, 12, 13, 14, 19, 21, 23], all, all, all}, crontab_schedule:parse("* 10-14,19/2 * * *")),
?assertEqual({all, [3, 4, 5, 14, 15, 16, 17, 18, 20, 22], all, all, all}, crontab_schedule:parse("* 3-5,14-17,18/2 * * *")).
should_parse_mixed_days_test() ->
?assertEqual({all, all, [5, 6, 7, 19, 23, 27, 31], all, all}, crontab_schedule:parse("* * 5-7,19/4 * *")),
?assertEqual({all, all, [3, 4, 5, 14, 15, 16, 17, 19, 22, 25, 28, 31], all, all}, crontab_schedule:parse("* * 3-5,14-17,19/3 * *")).
should_parse_mixed_month_test() ->
?assertEqual({all, all, all, [5, 6, 7, 9, 11], all}, crontab_schedule:parse("* * * 5-7,9/2 *")),
?assertEqual({all, all, all, [1, 2, 3, 5, 6, 8, 10, 12], all}, crontab_schedule:parse("* * * 1-3,5-6,8/2 *")).
should_parse_mixed_all_test() ->
?assertEqual({[10], all, all, [2, 4, 5, 6], all}, crontab_schedule:parse("10 * * February,April-Jun *")),
?assertEqual({[45], [16], [1], all, [1]}, crontab_schedule:parse("45 16 1 * Mon")).
% just numer tests
should_parse_just_numbers_test() ->
?assertEqual({[10], [20], [30], [6], [4]}, crontab_schedule:parse("10 20 30 6 4")).
% get_next_occurrence tests
should_calculate_next_occurrence_test() ->
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "* * * * *", {{2003,1,1},{0,1,0}}),
check_occurrence_calculation({{2003,1,1},{0,1,0}}, "* * * * *", {{2003,1,1},{0,2,0}}),
check_occurrence_calculation({{2003,1,1},{0,2,0}}, "* * * * *", {{2003,1,1},{0,3,0}}),
check_occurrence_calculation({{2003,1,1},{0,59,0}}, "* * * * *", {{2003,1,1},{1,0,0}}),
check_occurrence_calculation({{2003,1,1},{1,59,0}}, "* * * * *", {{2003,1,1},{2,0,0}}),
check_occurrence_calculation({{2003,1,1},{23,59,0}}, "* * * * *", {{2003,1,2},{0,0,0}}),
check_occurrence_calculation({{2003,12,31},{23,59,0}}, "* * * * *", {{2004,1,1},{0,0,0}}),
check_occurrence_calculation({{2003,2,28},{23,59,0}}, "* * * * *", {{2003,3,1},{0,0,0}}),
check_occurrence_calculation({{2004,2,28},{23,59,0}}, "* * * * *", {{2004,2,29},{0,0,0}}),
% Minute tests
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "45 * * * *", {{2003,1,1},{0,45,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,45,0}}),
check_occurrence_calculation({{2003,1,1},{0,45,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,46,0}}),
check_occurrence_calculation({{2003,1,1},{0,46,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,47,0}}),
check_occurrence_calculation({{2003,1,1},{0,47,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,48,0}}),
check_occurrence_calculation({{2003,1,1},{0,48,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,49,0}}),
check_occurrence_calculation({{2003,1,1},{0,49,0}}, "45-47,48,49 * * * *", {{2003,1,1},{1,45,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "2/5 * * * *", {{2003,1,1},{0,2,0}}),
check_occurrence_calculation({{2003,1,1},{0,2,0}}, "2/5 * * * *", {{2003,1,1},{0,7,0}}),
check_occurrence_calculation({{2003,1,1},{0,50,0}}, "2/5 * * * *", {{2003,1,1},{0,52,0}}),
check_occurrence_calculation({{2003,1,1},{0,52,0}}, "2/5 * * * *", {{2003,1,1},{0,57,0}}),
check_occurrence_calculation({{2003,1,1},{0,57,0}}, "2/5 * * * *", {{2003,1,1},{1,2,0}}),
% Hour tests
check_occurrence_calculation({{2003,12,20},{10,0,0}}, " * 3/4 * * *", {{2003,12,20},{11,0,0}}),
check_occurrence_calculation({{2003,12,20},{0,30,0}}, " * 3 * * *", {{2003,12,20},{3,0,0}}),
check_occurrence_calculation({{2003,12,20},{1,45,0}}, "30 3 * * *", {{2003,12,20},{3,30,0}}),
Day of month tests
check_occurrence_calculation({{2003,1,7},{0,0,0}}, "30 * 1 * *", {{2003,2,1},{0,30,0}}),
check_occurrence_calculation({{2003,2,1},{0,30,0}}, "30 * 1 * *", {{2003,2,1},{1,30,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "10 * 22 * *", {{2003,1,22},{0,10,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "30 23 19 * *", {{2003,1,19},{23,30,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "30 23 21 * *", {{2003,1,21},{23,30,0}}),
check_occurrence_calculation({{2003,1,1},{0,1,0}}, " * * 21 * *", {{2003,1,21},{0,0,0}}),
check_occurrence_calculation({{2003,7,10},{0,0,0}}, " * * 30,31 * *", {{2003,7,30},{0,0,0}}),
Test month rollovers for months with 28,29,30 and 31 days
check_occurrence_calculation({{2002,2,28},{23,59,0}}, "* * * 3 *", {{2002,3,1},{0,0,0}}),
check_occurrence_calculation({{2004,2,29},{23,59,0}}, "* * * 3 *", {{2004,3,1},{0,0,0}}),
check_occurrence_calculation({{2002,3,31},{23,59,0}}, "* * * 4 *", {{2002,4,1},{0,0,0}}),
check_occurrence_calculation({{2002,4,30},{23,59,0}}, "* * * 5 *", {{2002,5,1},{0,0,0}}),
% Test month 30,31 days
check_occurrence_calculation({{2000,1,1},{0,0,0}}, "0 0 15,30,31 * *", {{2000,1,15},{0,0,0}}),
check_occurrence_calculation({{2000,1,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,1,30},{0,0,0}}),
check_occurrence_calculation({{2000,1,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,1,31},{0,0,0}}),
check_occurrence_calculation({{2000,1,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,2,15},{0,0,0}}),
check_occurrence_calculation({{2000,2,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,3,15},{0,0,0}}),
check_occurrence_calculation({{2000,3,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,3,30},{0,0,0}}),
check_occurrence_calculation({{2000,3,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,3,31},{0,0,0}}),
check_occurrence_calculation({{2000,3,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,4,15},{0,0,0}}),
check_occurrence_calculation({{2000,4,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,4,30},{0,0,0}}),
check_occurrence_calculation({{2000,4,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,5,15},{0,0,0}}),
check_occurrence_calculation({{2000,5,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,5,30},{0,0,0}}),
check_occurrence_calculation({{2000,5,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,5,31},{0,0,0}}),
check_occurrence_calculation({{2000,5,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,6,15},{0,0,0}}),
check_occurrence_calculation({{2000,6,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,6,30},{0,0,0}}),
check_occurrence_calculation({{2000,6,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,7,15},{0,0,0}}),
check_occurrence_calculation({{2000,7,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,7,30},{0,0,0}}),
check_occurrence_calculation({{2000,7,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,7,31},{0,0,0}}),
check_occurrence_calculation({{2000,7,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,8,15},{0,0,0}}),
check_occurrence_calculation({{2000,8,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,8,30},{0,0,0}}),
check_occurrence_calculation({{2000,8,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,8,31},{0,0,0}}),
check_occurrence_calculation({{2000,8,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,9,15},{0,0,0}}),
check_occurrence_calculation({{2000,9,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,9,30},{0,0,0}}),
check_occurrence_calculation({{2000,9,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,10,15},{0,0,0}}),
check_occurrence_calculation({{2000,10,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,10,30},{0,0,0}}),
check_occurrence_calculation({{2000,10,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,10,31},{0,0,0}}),
check_occurrence_calculation({{2000,10,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,11,15},{0,0,0}}),
check_occurrence_calculation({{2000,11,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,11,30},{0,0,0}}),
check_occurrence_calculation({{2000,11,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,12,15},{0,0,0}}),
check_occurrence_calculation({{2000,12,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,12,30},{0,0,0}}),
check_occurrence_calculation({{2000,12,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,12,31},{0,0,0}}),
check_occurrence_calculation({{2000,12,31},{0,0,0}}, "0 0 15,30,31 * *", {{2001,1,15},{0,0,0}}),
Other month tests ( including year rollover )
check_occurrence_calculation({{2003,12,1},{5,0,0}}, "10 * * 6 *", {{2004,6,1},{0,10,0}}),
check_occurrence_calculation({{2003,1,4},{0,0,0}}, " 1 2 3 * *", {{2003,2,3},{2,1,0}}),
check_occurrence_calculation({{2002,7,1},{5,0,0}}, "10 * * February,April-Jun *", {{2003,2,1},{0,10,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "0 12 1 6 *", {{2003,6,1},{12,0,0}}),
check_occurrence_calculation({{1988,9,11},{14,23,0}}, "* 12 1 6 *", {{1989,6,1},{12,0,0}}),
check_occurrence_calculation({{1988,3,11},{14,23,0}}, "* 12 1 6 *", {{1988,6,1},{12,0,0}}),
check_occurrence_calculation({{1988,3,11},{14,23,0}}, "* 2,4-8,15 * 6 *", {{1988,6,1},{2,0,0}}),
check_occurrence_calculation({{1988,3,11},{14,23,0}}, "20 * * january,FeB,Mar,april,May,JuNE,July,Augu,SEPT-October,Nov,DECEM *", {{1988,3,11},{15,20,0}}),
Day of week tests
check_occurrence_calculation({{2003,6,26},{10,0,0}}, "30 6 * * 0", {{2003,6,29},{6,30,0}}),
check_occurrence_calculation({{2003,6,26},{10,0,0}}, "30 6 * * sunday", {{2003,6,29},{6,30,0}}),
check_occurrence_calculation({{2003,6,26},{10,0,0}}, "30 6 * * SUNDAY", {{2003,6,29},{6,30,0}}),
check_occurrence_calculation({{2003,6,19},{0,0,0}}, "1 12 * * 2", {{2003,6,24},{12,1,0}}),
check_occurrence_calculation({{2003,6,24},{12,1,0}}, "1 12 * * 2", {{2003,7,1},{12,1,0}}),
check_occurrence_calculation({{2003,6,1},{14,55,0}}, "15 18 * * Mon", {{2003,6,2},{18,15,0}}),
check_occurrence_calculation({{2003,6,2},{18,15,0}}, "15 18 * * Mon", {{2003,6,9},{18,15,0}}),
check_occurrence_calculation({{2003,6,9},{18,15,0}}, "15 18 * * Mon", {{2003,6,16},{18,15,0}}),
check_occurrence_calculation({{2003,6,16},{18,15,0}}, "15 18 * * Mon", {{2003,6,23},{18,15,0}}),
check_occurrence_calculation({{2003,6,23},{18,15,0}}, "15 18 * * Mon", {{2003,6,30},{18,15,0}}),
check_occurrence_calculation({{2003,6,30},{18,15,0}}, "15 18 * * Mon", {{2003,7,7},{18,15,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "* * * * Mon", {{2003,1,6},{0,0,0}}),
check_occurrence_calculation({{2003,1,1},{12,0,0}}, "45 16 1 * Mon", {{2003,9,1},{16,45,0}}),
check_occurrence_calculation({{2003,9,1},{23,45,0}}, "45 16 1 * Mon", {{2003,12,1},{16,45,0}}),
Leap year tests
check_occurrence_calculation({{2000,1,1},{12,0,0}}, "1 12 29 2 *", {{2000,2,29},{12,1,0}}),
check_occurrence_calculation({{2000,2,29},{12,1,0}}, "1 12 29 2 *", {{2004,2,29},{12,1,0}}),
check_occurrence_calculation({{2004,2,29},{12,1,0}}, "1 12 29 2 *", {{2008,2,29},{12,1,0}}),
% Non-leap year tests
check_occurrence_calculation({{2000,1,1},{12,0,0}}, "1 12 28 2 *", {{2000,2,28},{12,1,0}}),
check_occurrence_calculation({{2000,2,28},{12,1,0}}, "1 12 28 2 *", {{2001,2,28},{12,1,0}}),
check_occurrence_calculation({{2001,2,28},{12,1,0}}, "1 12 28 2 *", {{2002,2,28},{12,1,0}}),
check_occurrence_calculation({{2002,2,28},{12,1,0}}, "1 12 28 2 *", {{2003,2,28},{12,1,0}}),
check_occurrence_calculation({{2003,2,28},{12,1,0}}, "1 12 28 2 *", {{2004,2,28},{12,1,0}}),
check_occurrence_calculation({{2004,2,28},{12,1,0}}, "1 12 28 2 *", {{2005,2,28},{12,1,0}}).
check_occurrence_calculation(StartTime, CronExpression, NextTime) ->
Cron = crontab_schedule:parse(CronExpression),
?assertEqual(NextTime, crontab_schedule:get_next_occurrence(Cron, StartTime)).
% get_next_occurrence_after_ms tests
should_calculate_next_occurrence_in_milliseconds_test() ->
?assertEqual(60000, crontab_schedule:get_next_occurrence_after_ms({all, all, all, all, all}, {{2000,1,1},{0,0,0}})),
?assertEqual(60 * 60000, crontab_schedule:get_next_occurrence_after_ms({all, [1], all, all, all}, {{2000,1,1},{0,0,0}})),
?assertEqual(24 * 60 * 60000, crontab_schedule:get_next_occurrence_after_ms({all, all, [2], all, all}, {{2000,1,1},{0,0,0}})).
should_calculate_next_occurrances_test() ->
check_occurrences_calculation({{2004,1,1},{0,0,0}}, {{2004,1,1},{0,5,0}},
"* * * * *",
[{{2004,1,1},{0,1,0}}, {{2004,1,1},{0,2,0}}, {{2004,1,1},{0,3,0}}, {{2004,1,1},{0,4,0}}, {{2004,1,1},{0,5,0}}]).
check_occurrences_calculation(StartTime, EndTime, CronExpression, NextTimeList) ->
Cron = crontab_schedule:parse(CronExpression),
?assertEqual(NextTimeList, crontab_schedule:get_next_occurrences(Cron, StartTime, EndTime)).
| null | https://raw.githubusercontent.com/AlexanderButs/ecrontab/a3d43cb05685917620f0af693a5309c764b87304/src/crontab_schedule_tests.erl | erlang | parse tests
slash tests
dash tests
comma tests
mixed tests
just numer tests
get_next_occurrence tests
Minute tests
Hour tests
Test month 30,31 days
Non-leap year tests
get_next_occurrence_after_ms tests
| -module(crontab_schedule_tests).
-author("alexb").
-include_lib("eunit/include/eunit.hrl").
-compile(export_all).
should_throw_if_incorrect_field_value_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("/10 * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("-10 * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("10- * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse(",10 * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("/10, * * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* /4 * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* -4 * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* 4- * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* ,4 * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* /4, * * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * /3 * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * -3 * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * 3- * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * ,3 * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * /3, * *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * /3 *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * -3 *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * 3- *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * ,3 *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * /3, *")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * /1")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * -1")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * 1-")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * ,1")),
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * /1,")).
should_throw_if_lower_value_days_test() ->
?assertException(throw, {bad_field, _, lower_then, _}, crontab_schedule:parse("* * 0-5 * *")).
should_throw_if_lower_value_month_test() ->
?assertException(throw, {bad_field, _, lower_then, _}, crontab_schedule:parse("* * * 0-5 *")).
should_throw_if_greater_value_minutes_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("65-71 * * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("55-71 * * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("71-55 * * * *")).
should_throw_if_greater_value_hours_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* 25-27 * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* 19-27 * * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* 27-19 * * *")).
should_throw_if_greater_value_days_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * 33-35 * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * 28-35 * *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * 35-28 * *")).
should_throw_if_greater_value_month_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * 19-24 *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * 9-14 *")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * 14-9 *")).
should_throw_if_greater_value_day_of_week_test() ->
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * * 15-18")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * * 5-8")),
?assertException(throw, {bad_field, _, higher_then, _}, crontab_schedule:parse("* * * * 8-5")).
should_throw_if_parse_empty_string_test() ->
?assertException(throw, empty_string, crontab_schedule:parse("")).
should_throw_if_minute_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("bad * * * *")).
should_throw_if_hour_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* bad * * *")).
should_throw_if_day_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * bad * *")).
should_throw_if_month_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * bad *")).
should_throw_if_day_of_week_is_bad_test() ->
?assertException(throw, {bad_field, _}, crontab_schedule:parse("* * * * bad")).
should_throw_if_fields_are_not_five_test() ->
?assertException(throw, invalid_fields_count, crontab_schedule:parse("* * * * * *")).
should_parse_stars_into_tuple_with_all_test() ->
?assertEqual({all, all, all, all, all}, crontab_schedule:parse("* * * * *")).
should_parse_slash_with_star_into_tuple_with_segment_minutes_test() ->
?assertEqual({[5, 15, 25, 35, 45, 55], all, all, all, all}, crontab_schedule:parse("5/10 * * * *")),
?assertEqual({[0, 10, 20, 30, 40, 50], all, all, all, all}, crontab_schedule:parse("*/10 * * * *")),
?assertEqual({[0, 15, 30, 45], all, all, all, all}, crontab_schedule:parse("*/15 * * * *")).
should_parse_slash_with_star_into_tuple_with_segment_hours_test() ->
?assertEqual({all, [2, 6, 10, 14, 18, 22], all, all, all}, crontab_schedule:parse("* 2/4 * * *")),
?assertEqual({all, [0, 4, 8, 12, 16, 20], all, all, all}, crontab_schedule:parse("* */4 * * *")),
?assertEqual({all, [0, 6, 12, 18], all, all, all}, crontab_schedule:parse("* */6 * * *")).
should_parse_slash_with_star_into_tuple_with_segment_days_test() ->
?assertEqual({all, all, [3, 8, 13, 18, 23, 28], all, all}, crontab_schedule:parse("* * 3/5 * *")),
?assertEqual({all, all, [1, 6, 11, 16, 21, 26, 31], all, all}, crontab_schedule:parse("* * */5 * *")),
?assertEqual({all, all, [1, 11, 21, 31], all, all}, crontab_schedule:parse("* * */10 * *")).
should_parse_slash_with_star_into_tuple_with_segment_month_test() ->
?assertEqual({all, all, all, [2, 5, 8, 11], all}, crontab_schedule:parse("* * * 2/3 *")),
?assertEqual({all, all, all, [1, 4, 7, 10], all}, crontab_schedule:parse("* * * */3 *")),
?assertEqual({all, all, all, [1, 6, 11], all}, crontab_schedule:parse("* * * */5 *")).
should_parse_slash_with_star_into_tuple_with_segment_day_of_week_test() ->
?assertEqual({all, all, all, all, [1, 3, 5]}, crontab_schedule:parse("* * * * 1/2")),
?assertEqual({all, all, all, all, [0, 2, 4, 6]}, crontab_schedule:parse("* * * * */2")),
?assertEqual({all, all, all, all, [0, 3, 6]}, crontab_schedule:parse("* * * * */3")),
?assertEqual({all, all, all, all, [0, 1, 2, 3, 4, 5, 6]}, crontab_schedule:parse("* * * * */1")).
should_parse_dash_into_tuple_with_segment_minutes_test() ->
?assertEqual({[10, 11, 12, 13, 14, 15], all, all, all, all}, crontab_schedule:parse("10-15 * * * *")),
?assertEqual({[37, 38, 39, 40, 41], all, all, all, all}, crontab_schedule:parse("41-37 * * * *")).
should_parse_dash_into_tuple_with_segment_hours_test() ->
?assertEqual({all, [4, 5, 6], all, all, all}, crontab_schedule:parse("* 4-6 * * *")),
?assertEqual({all, [7, 8, 9, 10, 11], all, all, all}, crontab_schedule:parse("* 11-7 * * *")).
should_parse_dash_into_tuple_with_segment_days_test() ->
?assertEqual({all, all, [5, 6, 7, 8], all, all}, crontab_schedule:parse("* * 5-8 * *")),
?assertEqual({all, all, [19, 20, 21, 22, 23], all, all}, crontab_schedule:parse("* * 23-19 * *")).
should_parse_dash_into_tuple_with_segment_month_test() ->
?assertEqual({all, all, all, [3, 4, 5, 6, 7], all}, crontab_schedule:parse("* * * 3-7 *")),
?assertEqual({all, all, all, [1, 2, 3, 4, 5], all}, crontab_schedule:parse("* * * 5-1 *")).
should_parse_dash_into_tuple_with_segment_day_of_week_test() ->
?assertEqual({all, all, all, all, [0, 1, 2]}, crontab_schedule:parse("* * * * 0-2")),
?assertEqual({all, all, all, all, [0, 1, 2, 3]}, crontab_schedule:parse("* * * * 3-0")).
should_parse_comma_into_tuple_with_segment_minutes_test() ->
?assertEqual({[10, 15, 17, 25], all, all, all, all}, crontab_schedule:parse("10,15,17,25 * * * *")).
should_parse_comma_into_tuple_with_segment_hours_test() ->
?assertEqual({all, [1, 5, 17, 23], all, all, all}, crontab_schedule:parse("* 1,5,17,23 * * *")).
should_parse_comma_into_tuple_with_segment_days_test() ->
?assertEqual({all, all, [5, 8, 26, 31], all, all}, crontab_schedule:parse("* * 5,8,26,31 * *")).
should_parse_comma_into_tuple_with_segment_month_test() ->
?assertEqual({all, all, all, [3, 7, 12], all}, crontab_schedule:parse("* * * 3,7,12 *")).
should_parse_comma_into_tuple_with_segment_day_of_week_test() ->
?assertEqual({all, all, all, all, [0, 2, 5]}, crontab_schedule:parse("* * * * 0,2,5")).
should_parse_mixed_minutes_test() ->
?assertEqual({[10, 11, 12, 13, 14, 19, 29, 39, 49, 59], all, all, all, all}, crontab_schedule:parse("10-14,19/10 * * * *")),
?assertEqual({[10, 11, 12, 19, 20, 21, 30, 44, 58], all, all, all, all}, crontab_schedule:parse("10-12,19-21,30/14 * * * *")).
should_parse_mixed_hours_test() ->
?assertEqual({all, [10, 11, 12, 13, 14, 19, 21, 23], all, all, all}, crontab_schedule:parse("* 10-14,19/2 * * *")),
?assertEqual({all, [3, 4, 5, 14, 15, 16, 17, 18, 20, 22], all, all, all}, crontab_schedule:parse("* 3-5,14-17,18/2 * * *")).
should_parse_mixed_days_test() ->
?assertEqual({all, all, [5, 6, 7, 19, 23, 27, 31], all, all}, crontab_schedule:parse("* * 5-7,19/4 * *")),
?assertEqual({all, all, [3, 4, 5, 14, 15, 16, 17, 19, 22, 25, 28, 31], all, all}, crontab_schedule:parse("* * 3-5,14-17,19/3 * *")).
should_parse_mixed_month_test() ->
?assertEqual({all, all, all, [5, 6, 7, 9, 11], all}, crontab_schedule:parse("* * * 5-7,9/2 *")),
?assertEqual({all, all, all, [1, 2, 3, 5, 6, 8, 10, 12], all}, crontab_schedule:parse("* * * 1-3,5-6,8/2 *")).
should_parse_mixed_all_test() ->
?assertEqual({[10], all, all, [2, 4, 5, 6], all}, crontab_schedule:parse("10 * * February,April-Jun *")),
?assertEqual({[45], [16], [1], all, [1]}, crontab_schedule:parse("45 16 1 * Mon")).
should_parse_just_numbers_test() ->
?assertEqual({[10], [20], [30], [6], [4]}, crontab_schedule:parse("10 20 30 6 4")).
should_calculate_next_occurrence_test() ->
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "* * * * *", {{2003,1,1},{0,1,0}}),
check_occurrence_calculation({{2003,1,1},{0,1,0}}, "* * * * *", {{2003,1,1},{0,2,0}}),
check_occurrence_calculation({{2003,1,1},{0,2,0}}, "* * * * *", {{2003,1,1},{0,3,0}}),
check_occurrence_calculation({{2003,1,1},{0,59,0}}, "* * * * *", {{2003,1,1},{1,0,0}}),
check_occurrence_calculation({{2003,1,1},{1,59,0}}, "* * * * *", {{2003,1,1},{2,0,0}}),
check_occurrence_calculation({{2003,1,1},{23,59,0}}, "* * * * *", {{2003,1,2},{0,0,0}}),
check_occurrence_calculation({{2003,12,31},{23,59,0}}, "* * * * *", {{2004,1,1},{0,0,0}}),
check_occurrence_calculation({{2003,2,28},{23,59,0}}, "* * * * *", {{2003,3,1},{0,0,0}}),
check_occurrence_calculation({{2004,2,28},{23,59,0}}, "* * * * *", {{2004,2,29},{0,0,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "45 * * * *", {{2003,1,1},{0,45,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,45,0}}),
check_occurrence_calculation({{2003,1,1},{0,45,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,46,0}}),
check_occurrence_calculation({{2003,1,1},{0,46,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,47,0}}),
check_occurrence_calculation({{2003,1,1},{0,47,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,48,0}}),
check_occurrence_calculation({{2003,1,1},{0,48,0}}, "45-47,48,49 * * * *", {{2003,1,1},{0,49,0}}),
check_occurrence_calculation({{2003,1,1},{0,49,0}}, "45-47,48,49 * * * *", {{2003,1,1},{1,45,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "2/5 * * * *", {{2003,1,1},{0,2,0}}),
check_occurrence_calculation({{2003,1,1},{0,2,0}}, "2/5 * * * *", {{2003,1,1},{0,7,0}}),
check_occurrence_calculation({{2003,1,1},{0,50,0}}, "2/5 * * * *", {{2003,1,1},{0,52,0}}),
check_occurrence_calculation({{2003,1,1},{0,52,0}}, "2/5 * * * *", {{2003,1,1},{0,57,0}}),
check_occurrence_calculation({{2003,1,1},{0,57,0}}, "2/5 * * * *", {{2003,1,1},{1,2,0}}),
check_occurrence_calculation({{2003,12,20},{10,0,0}}, " * 3/4 * * *", {{2003,12,20},{11,0,0}}),
check_occurrence_calculation({{2003,12,20},{0,30,0}}, " * 3 * * *", {{2003,12,20},{3,0,0}}),
check_occurrence_calculation({{2003,12,20},{1,45,0}}, "30 3 * * *", {{2003,12,20},{3,30,0}}),
Day of month tests
check_occurrence_calculation({{2003,1,7},{0,0,0}}, "30 * 1 * *", {{2003,2,1},{0,30,0}}),
check_occurrence_calculation({{2003,2,1},{0,30,0}}, "30 * 1 * *", {{2003,2,1},{1,30,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "10 * 22 * *", {{2003,1,22},{0,10,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "30 23 19 * *", {{2003,1,19},{23,30,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "30 23 21 * *", {{2003,1,21},{23,30,0}}),
check_occurrence_calculation({{2003,1,1},{0,1,0}}, " * * 21 * *", {{2003,1,21},{0,0,0}}),
check_occurrence_calculation({{2003,7,10},{0,0,0}}, " * * 30,31 * *", {{2003,7,30},{0,0,0}}),
Test month rollovers for months with 28,29,30 and 31 days
check_occurrence_calculation({{2002,2,28},{23,59,0}}, "* * * 3 *", {{2002,3,1},{0,0,0}}),
check_occurrence_calculation({{2004,2,29},{23,59,0}}, "* * * 3 *", {{2004,3,1},{0,0,0}}),
check_occurrence_calculation({{2002,3,31},{23,59,0}}, "* * * 4 *", {{2002,4,1},{0,0,0}}),
check_occurrence_calculation({{2002,4,30},{23,59,0}}, "* * * 5 *", {{2002,5,1},{0,0,0}}),
check_occurrence_calculation({{2000,1,1},{0,0,0}}, "0 0 15,30,31 * *", {{2000,1,15},{0,0,0}}),
check_occurrence_calculation({{2000,1,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,1,30},{0,0,0}}),
check_occurrence_calculation({{2000,1,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,1,31},{0,0,0}}),
check_occurrence_calculation({{2000,1,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,2,15},{0,0,0}}),
check_occurrence_calculation({{2000,2,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,3,15},{0,0,0}}),
check_occurrence_calculation({{2000,3,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,3,30},{0,0,0}}),
check_occurrence_calculation({{2000,3,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,3,31},{0,0,0}}),
check_occurrence_calculation({{2000,3,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,4,15},{0,0,0}}),
check_occurrence_calculation({{2000,4,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,4,30},{0,0,0}}),
check_occurrence_calculation({{2000,4,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,5,15},{0,0,0}}),
check_occurrence_calculation({{2000,5,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,5,30},{0,0,0}}),
check_occurrence_calculation({{2000,5,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,5,31},{0,0,0}}),
check_occurrence_calculation({{2000,5,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,6,15},{0,0,0}}),
check_occurrence_calculation({{2000,6,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,6,30},{0,0,0}}),
check_occurrence_calculation({{2000,6,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,7,15},{0,0,0}}),
check_occurrence_calculation({{2000,7,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,7,30},{0,0,0}}),
check_occurrence_calculation({{2000,7,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,7,31},{0,0,0}}),
check_occurrence_calculation({{2000,7,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,8,15},{0,0,0}}),
check_occurrence_calculation({{2000,8,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,8,30},{0,0,0}}),
check_occurrence_calculation({{2000,8,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,8,31},{0,0,0}}),
check_occurrence_calculation({{2000,8,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,9,15},{0,0,0}}),
check_occurrence_calculation({{2000,9,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,9,30},{0,0,0}}),
check_occurrence_calculation({{2000,9,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,10,15},{0,0,0}}),
check_occurrence_calculation({{2000,10,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,10,30},{0,0,0}}),
check_occurrence_calculation({{2000,10,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,10,31},{0,0,0}}),
check_occurrence_calculation({{2000,10,31},{0,0,0}}, "0 0 15,30,31 * *", {{2000,11,15},{0,0,0}}),
check_occurrence_calculation({{2000,11,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,11,30},{0,0,0}}),
check_occurrence_calculation({{2000,11,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,12,15},{0,0,0}}),
check_occurrence_calculation({{2000,12,15},{0,0,0}}, "0 0 15,30,31 * *", {{2000,12,30},{0,0,0}}),
check_occurrence_calculation({{2000,12,30},{0,0,0}}, "0 0 15,30,31 * *", {{2000,12,31},{0,0,0}}),
check_occurrence_calculation({{2000,12,31},{0,0,0}}, "0 0 15,30,31 * *", {{2001,1,15},{0,0,0}}),
Other month tests ( including year rollover )
check_occurrence_calculation({{2003,12,1},{5,0,0}}, "10 * * 6 *", {{2004,6,1},{0,10,0}}),
check_occurrence_calculation({{2003,1,4},{0,0,0}}, " 1 2 3 * *", {{2003,2,3},{2,1,0}}),
check_occurrence_calculation({{2002,7,1},{5,0,0}}, "10 * * February,April-Jun *", {{2003,2,1},{0,10,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "0 12 1 6 *", {{2003,6,1},{12,0,0}}),
check_occurrence_calculation({{1988,9,11},{14,23,0}}, "* 12 1 6 *", {{1989,6,1},{12,0,0}}),
check_occurrence_calculation({{1988,3,11},{14,23,0}}, "* 12 1 6 *", {{1988,6,1},{12,0,0}}),
check_occurrence_calculation({{1988,3,11},{14,23,0}}, "* 2,4-8,15 * 6 *", {{1988,6,1},{2,0,0}}),
check_occurrence_calculation({{1988,3,11},{14,23,0}}, "20 * * january,FeB,Mar,april,May,JuNE,July,Augu,SEPT-October,Nov,DECEM *", {{1988,3,11},{15,20,0}}),
Day of week tests
check_occurrence_calculation({{2003,6,26},{10,0,0}}, "30 6 * * 0", {{2003,6,29},{6,30,0}}),
check_occurrence_calculation({{2003,6,26},{10,0,0}}, "30 6 * * sunday", {{2003,6,29},{6,30,0}}),
check_occurrence_calculation({{2003,6,26},{10,0,0}}, "30 6 * * SUNDAY", {{2003,6,29},{6,30,0}}),
check_occurrence_calculation({{2003,6,19},{0,0,0}}, "1 12 * * 2", {{2003,6,24},{12,1,0}}),
check_occurrence_calculation({{2003,6,24},{12,1,0}}, "1 12 * * 2", {{2003,7,1},{12,1,0}}),
check_occurrence_calculation({{2003,6,1},{14,55,0}}, "15 18 * * Mon", {{2003,6,2},{18,15,0}}),
check_occurrence_calculation({{2003,6,2},{18,15,0}}, "15 18 * * Mon", {{2003,6,9},{18,15,0}}),
check_occurrence_calculation({{2003,6,9},{18,15,0}}, "15 18 * * Mon", {{2003,6,16},{18,15,0}}),
check_occurrence_calculation({{2003,6,16},{18,15,0}}, "15 18 * * Mon", {{2003,6,23},{18,15,0}}),
check_occurrence_calculation({{2003,6,23},{18,15,0}}, "15 18 * * Mon", {{2003,6,30},{18,15,0}}),
check_occurrence_calculation({{2003,6,30},{18,15,0}}, "15 18 * * Mon", {{2003,7,7},{18,15,0}}),
check_occurrence_calculation({{2003,1,1},{0,0,0}}, "* * * * Mon", {{2003,1,6},{0,0,0}}),
check_occurrence_calculation({{2003,1,1},{12,0,0}}, "45 16 1 * Mon", {{2003,9,1},{16,45,0}}),
check_occurrence_calculation({{2003,9,1},{23,45,0}}, "45 16 1 * Mon", {{2003,12,1},{16,45,0}}),
Leap year tests
check_occurrence_calculation({{2000,1,1},{12,0,0}}, "1 12 29 2 *", {{2000,2,29},{12,1,0}}),
check_occurrence_calculation({{2000,2,29},{12,1,0}}, "1 12 29 2 *", {{2004,2,29},{12,1,0}}),
check_occurrence_calculation({{2004,2,29},{12,1,0}}, "1 12 29 2 *", {{2008,2,29},{12,1,0}}),
check_occurrence_calculation({{2000,1,1},{12,0,0}}, "1 12 28 2 *", {{2000,2,28},{12,1,0}}),
check_occurrence_calculation({{2000,2,28},{12,1,0}}, "1 12 28 2 *", {{2001,2,28},{12,1,0}}),
check_occurrence_calculation({{2001,2,28},{12,1,0}}, "1 12 28 2 *", {{2002,2,28},{12,1,0}}),
check_occurrence_calculation({{2002,2,28},{12,1,0}}, "1 12 28 2 *", {{2003,2,28},{12,1,0}}),
check_occurrence_calculation({{2003,2,28},{12,1,0}}, "1 12 28 2 *", {{2004,2,28},{12,1,0}}),
check_occurrence_calculation({{2004,2,28},{12,1,0}}, "1 12 28 2 *", {{2005,2,28},{12,1,0}}).
check_occurrence_calculation(StartTime, CronExpression, NextTime) ->
Cron = crontab_schedule:parse(CronExpression),
?assertEqual(NextTime, crontab_schedule:get_next_occurrence(Cron, StartTime)).
should_calculate_next_occurrence_in_milliseconds_test() ->
?assertEqual(60000, crontab_schedule:get_next_occurrence_after_ms({all, all, all, all, all}, {{2000,1,1},{0,0,0}})),
?assertEqual(60 * 60000, crontab_schedule:get_next_occurrence_after_ms({all, [1], all, all, all}, {{2000,1,1},{0,0,0}})),
?assertEqual(24 * 60 * 60000, crontab_schedule:get_next_occurrence_after_ms({all, all, [2], all, all}, {{2000,1,1},{0,0,0}})).
should_calculate_next_occurrances_test() ->
check_occurrences_calculation({{2004,1,1},{0,0,0}}, {{2004,1,1},{0,5,0}},
"* * * * *",
[{{2004,1,1},{0,1,0}}, {{2004,1,1},{0,2,0}}, {{2004,1,1},{0,3,0}}, {{2004,1,1},{0,4,0}}, {{2004,1,1},{0,5,0}}]).
check_occurrences_calculation(StartTime, EndTime, CronExpression, NextTimeList) ->
Cron = crontab_schedule:parse(CronExpression),
?assertEqual(NextTimeList, crontab_schedule:get_next_occurrences(Cron, StartTime, EndTime)).
|
5e4927f7dd7ecf4db0230c785de5b1deca2b06cd476a3d9790937f4e61c3a8b6 | ghcjs/ghcjs-dom | CSSKeyframesRule.hs | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
module GHCJS.DOM.JSFFI.Generated.CSSKeyframesRule
(js_insertRule, insertRule, js_appendRule, appendRule,
js_deleteRule, deleteRule, js_findRule, findRule, findRule_,
findRuleUnsafe, findRuleUnchecked, js_get, get, get_, js_setName,
setName, js_getName, getName, js_getCssRules, getCssRules,
CSSKeyframesRule(..), gTypeCSSKeyframesRule)
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
foreign import javascript unsafe "$1[\"insertRule\"]($2)"
js_insertRule :: CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.insertRule Mozilla CSSKeyframesRule.insertRule documentation >
insertRule ::
(MonadIO m, ToJSString rule) => CSSKeyframesRule -> rule -> m ()
insertRule self rule
= liftIO (js_insertRule self (toJSString rule))
foreign import javascript unsafe "$1[\"appendRule\"]($2)"
js_appendRule :: CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.appendRule Mozilla CSSKeyframesRule.appendRule documentation >
appendRule ::
(MonadIO m, ToJSString rule) => CSSKeyframesRule -> rule -> m ()
appendRule self rule
= liftIO (js_appendRule self (toJSString rule))
foreign import javascript unsafe "$1[\"deleteRule\"]($2)"
js_deleteRule :: CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.deleteRule Mozilla CSSKeyframesRule.deleteRule documentation >
deleteRule ::
(MonadIO m, ToJSString key) => CSSKeyframesRule -> key -> m ()
deleteRule self key = liftIO (js_deleteRule self (toJSString key))
foreign import javascript unsafe "$1[\"findRule\"]($2)" js_findRule
:: CSSKeyframesRule -> JSString -> IO (Nullable CSSKeyframeRule)
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRule ::
(MonadIO m, ToJSString key) =>
CSSKeyframesRule -> key -> m (Maybe CSSKeyframeRule)
findRule self key
= liftIO (nullableToMaybe <$> (js_findRule self (toJSString key)))
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRule_ ::
(MonadIO m, ToJSString key) => CSSKeyframesRule -> key -> m ()
findRule_ self key
= liftIO (void (js_findRule self (toJSString key)))
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRuleUnsafe ::
(MonadIO m, ToJSString key, HasCallStack) =>
CSSKeyframesRule -> key -> m CSSKeyframeRule
findRuleUnsafe self key
= liftIO
((nullableToMaybe <$> (js_findRule self (toJSString key))) >>=
maybe (Prelude.error "Nothing to return") return)
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRuleUnchecked ::
(MonadIO m, ToJSString key) =>
CSSKeyframesRule -> key -> m CSSKeyframeRule
findRuleUnchecked self key
= liftIO
(fromJust . nullableToMaybe <$>
(js_findRule self (toJSString key)))
foreign import javascript unsafe "$1[$2]" js_get ::
CSSKeyframesRule -> Word -> IO CSSKeyframeRule
| < -US/docs/Web/API/CSSKeyframesRule.get Mozilla CSSKeyframesRule.get documentation >
get :: (MonadIO m) => CSSKeyframesRule -> Word -> m CSSKeyframeRule
get self index = liftIO (js_get self index)
| < -US/docs/Web/API/CSSKeyframesRule.get Mozilla CSSKeyframesRule.get documentation >
get_ :: (MonadIO m) => CSSKeyframesRule -> Word -> m ()
get_ self index = liftIO (void (js_get self index))
foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName ::
CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.name Mozilla CSSKeyframesRule.name documentation >
setName ::
(MonadIO m, ToJSString val) => CSSKeyframesRule -> val -> m ()
setName self val = liftIO (js_setName self (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
CSSKeyframesRule -> IO JSString
| < -US/docs/Web/API/CSSKeyframesRule.name Mozilla CSSKeyframesRule.name documentation >
getName ::
(MonadIO m, FromJSString result) => CSSKeyframesRule -> m result
getName self = liftIO (fromJSString <$> (js_getName self))
foreign import javascript unsafe "$1[\"cssRules\"]" js_getCssRules
:: CSSKeyframesRule -> IO CSSRuleList
| < -US/docs/Web/API/CSSKeyframesRule.cssRules Mozilla CSSKeyframesRule.cssRules documentation >
getCssRules :: (MonadIO m) => CSSKeyframesRule -> m CSSRuleList
getCssRules self = liftIO (js_getCssRules self) | null | https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/CSSKeyframesRule.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures # | # LANGUAGE PatternSynonyms #
# LANGUAGE ForeignFunctionInterface #
# LANGUAGE JavaScriptFFI #
module GHCJS.DOM.JSFFI.Generated.CSSKeyframesRule
(js_insertRule, insertRule, js_appendRule, appendRule,
js_deleteRule, deleteRule, js_findRule, findRule, findRule_,
findRuleUnsafe, findRuleUnchecked, js_get, get, get_, js_setName,
setName, js_getName, getName, js_getCssRules, getCssRules,
CSSKeyframesRule(..), gTypeCSSKeyframesRule)
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
foreign import javascript unsafe "$1[\"insertRule\"]($2)"
js_insertRule :: CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.insertRule Mozilla CSSKeyframesRule.insertRule documentation >
insertRule ::
(MonadIO m, ToJSString rule) => CSSKeyframesRule -> rule -> m ()
insertRule self rule
= liftIO (js_insertRule self (toJSString rule))
foreign import javascript unsafe "$1[\"appendRule\"]($2)"
js_appendRule :: CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.appendRule Mozilla CSSKeyframesRule.appendRule documentation >
appendRule ::
(MonadIO m, ToJSString rule) => CSSKeyframesRule -> rule -> m ()
appendRule self rule
= liftIO (js_appendRule self (toJSString rule))
foreign import javascript unsafe "$1[\"deleteRule\"]($2)"
js_deleteRule :: CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.deleteRule Mozilla CSSKeyframesRule.deleteRule documentation >
deleteRule ::
(MonadIO m, ToJSString key) => CSSKeyframesRule -> key -> m ()
deleteRule self key = liftIO (js_deleteRule self (toJSString key))
foreign import javascript unsafe "$1[\"findRule\"]($2)" js_findRule
:: CSSKeyframesRule -> JSString -> IO (Nullable CSSKeyframeRule)
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRule ::
(MonadIO m, ToJSString key) =>
CSSKeyframesRule -> key -> m (Maybe CSSKeyframeRule)
findRule self key
= liftIO (nullableToMaybe <$> (js_findRule self (toJSString key)))
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRule_ ::
(MonadIO m, ToJSString key) => CSSKeyframesRule -> key -> m ()
findRule_ self key
= liftIO (void (js_findRule self (toJSString key)))
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRuleUnsafe ::
(MonadIO m, ToJSString key, HasCallStack) =>
CSSKeyframesRule -> key -> m CSSKeyframeRule
findRuleUnsafe self key
= liftIO
((nullableToMaybe <$> (js_findRule self (toJSString key))) >>=
maybe (Prelude.error "Nothing to return") return)
| < -US/docs/Web/API/CSSKeyframesRule.findRule Mozilla CSSKeyframesRule.findRule documentation >
findRuleUnchecked ::
(MonadIO m, ToJSString key) =>
CSSKeyframesRule -> key -> m CSSKeyframeRule
findRuleUnchecked self key
= liftIO
(fromJust . nullableToMaybe <$>
(js_findRule self (toJSString key)))
foreign import javascript unsafe "$1[$2]" js_get ::
CSSKeyframesRule -> Word -> IO CSSKeyframeRule
| < -US/docs/Web/API/CSSKeyframesRule.get Mozilla CSSKeyframesRule.get documentation >
get :: (MonadIO m) => CSSKeyframesRule -> Word -> m CSSKeyframeRule
get self index = liftIO (js_get self index)
| < -US/docs/Web/API/CSSKeyframesRule.get Mozilla CSSKeyframesRule.get documentation >
get_ :: (MonadIO m) => CSSKeyframesRule -> Word -> m ()
get_ self index = liftIO (void (js_get self index))
foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName ::
CSSKeyframesRule -> JSString -> IO ()
| < -US/docs/Web/API/CSSKeyframesRule.name Mozilla CSSKeyframesRule.name documentation >
setName ::
(MonadIO m, ToJSString val) => CSSKeyframesRule -> val -> m ()
setName self val = liftIO (js_setName self (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
CSSKeyframesRule -> IO JSString
| < -US/docs/Web/API/CSSKeyframesRule.name Mozilla CSSKeyframesRule.name documentation >
getName ::
(MonadIO m, FromJSString result) => CSSKeyframesRule -> m result
getName self = liftIO (fromJSString <$> (js_getName self))
foreign import javascript unsafe "$1[\"cssRules\"]" js_getCssRules
:: CSSKeyframesRule -> IO CSSRuleList
| < -US/docs/Web/API/CSSKeyframesRule.cssRules Mozilla CSSKeyframesRule.cssRules documentation >
getCssRules :: (MonadIO m) => CSSKeyframesRule -> m CSSRuleList
getCssRules self = liftIO (js_getCssRules self) |
61341a34a675ccc0ac1c15b820d14edbbb397110031ac6f7dd6a623d8dd62954 | callum-oakley/advent-of-code | 10.clj | (ns aoc.2018.10
(:require
[aoc.ocr :as ocr]
[aoc.vector :refer [+v]]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(->> s (re-seq #"-?\d+") (map read-string)
(partition 2) (map vec) (partition 2)))
(defn part-* [seconds points]
(->> points (iterate #(map (fn [[p v]] [(+v p v) v]) %)) (drop seconds) first
(map first) set ocr/draw ocr/parse))
(defn part-2 [_]
;; by inspection
10009)
(defn part-1 [points]
(part-* (part-2 nil) points))
(deftest test-example
(let [example
"position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0>
position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1>
position=< 2, -4> velocity=< 2, 2> position=<-6, 10> velocity=< 2, -2>
position=< 1, 8> velocity=< 1, -1> position=< 1, 7> velocity=< 1, 0>
position=<-3, 11> velocity=< 1, -2> position=< 7, 6> velocity=<-1, -1>
position=<-2, 3> velocity=< 1, 0> position=<-4, 3> velocity=< 2, 0>
position=<10, -3> velocity=<-1, 1> position=< 5, 11> velocity=< 1, -2>
position=< 4, 7> velocity=< 0, -1> position=< 8, -2> velocity=< 0, 1>
position=<15, 0> velocity=<-2, 0> position=< 1, 6> velocity=< 1, 0>
position=< 8, 9> velocity=< 0, -1> position=< 3, 3> velocity=<-1, 1>
position=< 0, 5> velocity=< 0, -1> position=<-2, 2> velocity=< 2, 0>
position=< 5, -2> velocity=< 1, 2> position=< 1, 4> velocity=< 2, 1>
position=<-2, 7> velocity=< 2, -2> position=< 3, 6> velocity=<-1, -1>
position=< 5, 0> velocity=< 1, 0> position=<-6, 0> velocity=< 2, 0>
position=< 5, 9> velocity=< 1, -2> position=<14, 7> velocity=<-2, 0>
position=<-3, 6> velocity=< 2, -1>"]
(is (= "HI" (part-* 3 (parse example))))))
| null | https://raw.githubusercontent.com/callum-oakley/advent-of-code/c8d9d912471415b0014707f768946b18f29b4531/src/aoc/2018/10.clj | clojure | by inspection | (ns aoc.2018.10
(:require
[aoc.ocr :as ocr]
[aoc.vector :refer [+v]]
[clojure.test :refer [deftest is]]))
(defn parse [s]
(->> s (re-seq #"-?\d+") (map read-string)
(partition 2) (map vec) (partition 2)))
(defn part-* [seconds points]
(->> points (iterate #(map (fn [[p v]] [(+v p v) v]) %)) (drop seconds) first
(map first) set ocr/draw ocr/parse))
(defn part-2 [_]
10009)
(defn part-1 [points]
(part-* (part-2 nil) points))
(deftest test-example
(let [example
"position=< 9, 1> velocity=< 0, 2> position=< 7, 0> velocity=<-1, 0>
position=< 3, -2> velocity=<-1, 1> position=< 6, 10> velocity=<-2, -1>
position=< 2, -4> velocity=< 2, 2> position=<-6, 10> velocity=< 2, -2>
position=< 1, 8> velocity=< 1, -1> position=< 1, 7> velocity=< 1, 0>
position=<-3, 11> velocity=< 1, -2> position=< 7, 6> velocity=<-1, -1>
position=<-2, 3> velocity=< 1, 0> position=<-4, 3> velocity=< 2, 0>
position=<10, -3> velocity=<-1, 1> position=< 5, 11> velocity=< 1, -2>
position=< 4, 7> velocity=< 0, -1> position=< 8, -2> velocity=< 0, 1>
position=<15, 0> velocity=<-2, 0> position=< 1, 6> velocity=< 1, 0>
position=< 8, 9> velocity=< 0, -1> position=< 3, 3> velocity=<-1, 1>
position=< 0, 5> velocity=< 0, -1> position=<-2, 2> velocity=< 2, 0>
position=< 5, -2> velocity=< 1, 2> position=< 1, 4> velocity=< 2, 1>
position=<-2, 7> velocity=< 2, -2> position=< 3, 6> velocity=<-1, -1>
position=< 5, 0> velocity=< 1, 0> position=<-6, 0> velocity=< 2, 0>
position=< 5, 9> velocity=< 1, -2> position=<14, 7> velocity=<-2, 0>
position=<-3, 6> velocity=< 2, -1>"]
(is (= "HI" (part-* 3 (parse example))))))
|
55948beb00dbd390cd94ee191a548551f7324cdcb6e7163a8626fde2d4f528a8 | practicalli/four-clojure | 012_intro_to_sequences.clj | (ns four-clojure.012-intro-to-sequences)
# 012 Intro to Sequences
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Difficulty: Elementary
;; Topics:
All Clojure collections support sequencing . You can operate on sequences with functions like first , second , and last .
;; Tests
(= _ _ ( first ' ( 3 2 1 ) ) )
(= _ _ ( second [ 2 3 4 ] ) )
;; (= __ (last (list 1 2 3)))
Deconstruct the problem
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; A simple exploration of data structures as sequences.
;; Notice that the sequence functions work on both lists and vectors in the same way.
(first '(3 2 1))
= > 3
(second [2 3 4])
= > 3
(last (list 1 2 3))
= > 3
;; Answers summary
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3
| null | https://raw.githubusercontent.com/practicalli/four-clojure/9812b63769a06f9b0bfd63e5ffce380b67e5468b/src/four_clojure/012_intro_to_sequences.clj | clojure |
Difficulty: Elementary
Topics:
Tests
(= __ (last (list 1 2 3)))
A simple exploration of data structures as sequences.
Notice that the sequence functions work on both lists and vectors in the same way.
Answers summary
| (ns four-clojure.012-intro-to-sequences)
# 012 Intro to Sequences
All Clojure collections support sequencing . You can operate on sequences with functions like first , second , and last .
(= _ _ ( first ' ( 3 2 1 ) ) )
(= _ _ ( second [ 2 3 4 ] ) )
Deconstruct the problem
(first '(3 2 1))
= > 3
(second [2 3 4])
= > 3
(last (list 1 2 3))
= > 3
3
|
17410a3550319709af05fa295f7ddbb04652861d0e805bcedb7ce54f6624e844 | nyu-acsys/drift | a-sub.ml |
let rec sub_helper hi hstart hn hlen (ha: int array) (hb: int array) =
if (hlen > 0 && hi < hlen) then
(Array.set hb hi (Array.get ha hstart);
sub_helper (hi + 1) (hstart + 1) hn hlen ha hb)
else ()
let rec sub (ma: int array) mstart mlen =
let la = Array.length ma in
let mb = Array.make mlen 0 in
sub_helper 0 mstart la mlen ma mb;
mb
let main_p (n:int) (start:int) (subl:int) =
if n > 0 then
let a = Array.make n 0 in
let res: int array =
let la = Array.length a in
if subl >= 0 && start >= 0 && start + subl < la then
sub a start subl
else
a
in
assert(Array.length res <= Array.length a)
else ()
let main (w:unit) =
let _ = main_p 10 3 4 in
let _ = main_p 100 30 50 in
()
let _ = main () | null | https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/DRIFT/array/a-sub.ml | ocaml |
let rec sub_helper hi hstart hn hlen (ha: int array) (hb: int array) =
if (hlen > 0 && hi < hlen) then
(Array.set hb hi (Array.get ha hstart);
sub_helper (hi + 1) (hstart + 1) hn hlen ha hb)
else ()
let rec sub (ma: int array) mstart mlen =
let la = Array.length ma in
let mb = Array.make mlen 0 in
sub_helper 0 mstart la mlen ma mb;
mb
let main_p (n:int) (start:int) (subl:int) =
if n > 0 then
let a = Array.make n 0 in
let res: int array =
let la = Array.length a in
if subl >= 0 && start >= 0 && start + subl < la then
sub a start subl
else
a
in
assert(Array.length res <= Array.length a)
else ()
let main (w:unit) =
let _ = main_p 10 3 4 in
let _ = main_p 100 30 50 in
()
let _ = main () | |
666f8a0044995c36ffd86bb9f72a9840748c3028536ea773debbdb6fe5be8304 | theangelperalta/cl-objc | reader-macro.lisp | (in-package :objc-reader)
(defparameter *old-readtable* nil)
(defparameter *objc-readtable* nil)
(defparameter *objc-argument-readtable* nil
"The readtable used to read arguments of messages")
(defparameter *accept-untyped-call* t
"If nil, methods have to be invoked with input type parameters.")
(defparameter *use-clos-interface* t)
(defun end-selector-char-p (char)
(member char '(#\Space #\])))
(defun separator-char-p (char)
(member char '(#\Space)))
(defun eat-separators (stream)
(loop
for char = (read-char stream nil nil t)
while (and char (separator-char-p char))
finally (when char (unread-char char stream))))
(defun read-selector-part (stream)
"Read a part of a selector. Returns 'eof if can't find any
selector."
(eat-separators stream)
(let ((string
(with-output-to-string (out)
(loop
for char = (read-char stream t nil t)
when (not char) return nil
until (end-selector-char-p char)
do (princ char out)
finally (unread-char char stream)))))
(if (zerop (length string))
'eof
string)))
(defun objc-read-right-square-bracket (stream char)
(declare (ignore stream char))
'eof)
(defmacro with-argument-readtable (&body body)
`(let ((*readtable* *objc-argument-readtable*))
,@body))
(defmacro with-old-readtable (&body body)
`(let ((*readtable* *old-readtable*))
,@body))
(defmacro with-objc-readtable (&body body)
`(let ((*readtable* *objc-readtable*))
(setf (readtable-case *readtable*) :preserve)
(prog1
(progn
,@body)
(setf (readtable-case *readtable*) (readtable-case *old-readtable*)))))
(defun objc-read-comma (stream char)
(declare (ignore char))
(eval (with-old-readtable
(read stream t nil t))))
(defun read-arg-and-type (stream)
"Returns a list with a cffi type and an argument for foreign
funcall.
If the type is unspecified, the argument is present and
*accept-untyped-call* is nil it signals an error.
If *accept-untyped-call* is t and the type is not present returns
a list with just the argument.
If both the argument and the type are not present returns a list
with the symbol 'eof."
(eat-separators stream)
(with-argument-readtable
(let ((ret (let ((type-or-arg (read stream nil 'eof t)))
(if (cffi-type-p type-or-arg)
(list type-or-arg (read stream nil 'eof t))
(list type-or-arg)))))
(cond
((eq (car ret) (intern "]")) (list 'eof)) ; using the old
; readtable so we need
; to convert the ] into
; 'eof
((and (not *accept-untyped-call*)
(= 1 (length ret))
(not (eq (car ret) 'eof))) (error "Params specified without correct CFFI type: ~s" ret)) ; the params are read
(t ret)))))
(defun read-args-and-selector (stream)
(do* ((selector-part (read-selector-part stream) (read-selector-part stream))
(arg/type (read-arg-and-type stream) (append arg/type (read-arg-and-type stream)))
(typed t)
(selector selector-part (if (not (eq 'eof selector-part))
(concatenate 'string selector selector-part)
selector)))
((or (eq selector-part 'eof)
(eq (car arg/type) 'eof)) (list (remove 'eof arg/type) selector typed))
(when (or (and (= 2 (length arg/type))
(eq 'eof (second arg/type)))
(= 1 (length arg/type)))
(setf typed nil))))
(defun objc-read-left-square-bracket (stream char)
"Read an objc form: [ receiver selector args*].
Both receiver selector and each arg can be a lisp form or an objc
form (starting with an another #\[).
The receiver and the selector will be read using the objc
readtable (so preserving the case). You can escape using the
comma (e.g. in order to use a lisp variable containing the class
object). As a special case if a class name is found as receiver
it will be read and evalued as (objc-get-class (symbol-name
receiver-read)).
The args will be read with the lisp readtable.
"
(declare (ignore char))
(flet ((starts-with-a-upcase-char-p (string)
(let ((first-char (elt string 0)))
(and (alpha-char-p first-char)
(char-equal (char-upcase first-char) first-char)))))
(with-objc-readtable
(let ((id (read stream t nil t)))
(let ((receiver (if (and (symbolp id) (starts-with-a-upcase-char-p (symbol-name id)))
(if *use-clos-interface*
`(objc-clos:meta (objc-class-name-to-symbol (class-name (objc-get-class ,(symbol-name id)))))
`(objc-get-class ,(symbol-name id)))
id)))
(destructuring-bind (args selector typed)
(read-args-and-selector stream)
(if typed
(if *use-clos-interface*
`(objc-clos:convert-result-from-objc (typed-objc-msg-send ((objc:objc-id ,receiver) ,selector) ,@args))
`(typed-objc-msg-send (,receiver ,selector) ,@args))
(if *use-clos-interface*
`(objc-clos:convert-result-from-objc (untyped-objc-msg-send (objc:objc-id ,receiver) ,selector ,@args))
`(untyped-objc-msg-send ,receiver ,selector ,@args)))))))))
(defun read-at-sign (stream char n)
(declare (ignore n))
(unread-char char stream)
(typed-objc-msg-send
((typed-objc-msg-send ((objc-get-class "NSString") "alloc"))
"initWithUTF8String:")
:string (read stream t nil t)))
(defun restore-readtable ()
"Restore the readtable being present before the call of
ACTIVATE-OBJC-READER-MACRO."
(setf *readtable* *old-readtable*))
(defun activate-objc-reader-macro (&optional (accept-untyped-call nil) (use-clos-interface nil))
"Installs a the ObjectiveC readtable. If ACCEPT-UNTYPED-CALL is
NIL method has to be invoked with input type parameters. It saves
the current readtable to be later restored with
RESTORE-READTABLE"
(setf *old-readtable* (copy-readtable)
*accept-untyped-call* accept-untyped-call
*use-clos-interface* use-clos-interface)
(set-macro-character #\] #'objc-read-right-square-bracket)
(unless (get-macro-character #\@)
(make-dispatch-macro-character #\@))
(set-dispatch-macro-character #\@ #\" #'read-at-sign)
(setf *objc-argument-readtable* (copy-readtable))
(set-macro-character #\[ #'objc-read-left-square-bracket)
(set-macro-character #\, #'objc-read-comma)
(setf *objc-readtable* (copy-readtable)))
Copyright ( c ) 2007 ,
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are
;; met:
;;
;; - Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; - Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; - The name of its contributors may not be used to endorse or
;; promote products derived from this software without specific
;; prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE ,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| null | https://raw.githubusercontent.com/theangelperalta/cl-objc/6daf2edf6d922e7ee1acaf259ea5510b16580379/src/reader-macro.lisp | lisp | using the old
readtable so we need
to convert the ] into
'eof
the params are read
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- The name of its contributors may not be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE ,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | (in-package :objc-reader)
(defparameter *old-readtable* nil)
(defparameter *objc-readtable* nil)
(defparameter *objc-argument-readtable* nil
"The readtable used to read arguments of messages")
(defparameter *accept-untyped-call* t
"If nil, methods have to be invoked with input type parameters.")
(defparameter *use-clos-interface* t)
(defun end-selector-char-p (char)
(member char '(#\Space #\])))
(defun separator-char-p (char)
(member char '(#\Space)))
(defun eat-separators (stream)
(loop
for char = (read-char stream nil nil t)
while (and char (separator-char-p char))
finally (when char (unread-char char stream))))
(defun read-selector-part (stream)
"Read a part of a selector. Returns 'eof if can't find any
selector."
(eat-separators stream)
(let ((string
(with-output-to-string (out)
(loop
for char = (read-char stream t nil t)
when (not char) return nil
until (end-selector-char-p char)
do (princ char out)
finally (unread-char char stream)))))
(if (zerop (length string))
'eof
string)))
(defun objc-read-right-square-bracket (stream char)
(declare (ignore stream char))
'eof)
(defmacro with-argument-readtable (&body body)
`(let ((*readtable* *objc-argument-readtable*))
,@body))
(defmacro with-old-readtable (&body body)
`(let ((*readtable* *old-readtable*))
,@body))
(defmacro with-objc-readtable (&body body)
`(let ((*readtable* *objc-readtable*))
(setf (readtable-case *readtable*) :preserve)
(prog1
(progn
,@body)
(setf (readtable-case *readtable*) (readtable-case *old-readtable*)))))
(defun objc-read-comma (stream char)
(declare (ignore char))
(eval (with-old-readtable
(read stream t nil t))))
(defun read-arg-and-type (stream)
"Returns a list with a cffi type and an argument for foreign
funcall.
If the type is unspecified, the argument is present and
*accept-untyped-call* is nil it signals an error.
If *accept-untyped-call* is t and the type is not present returns
a list with just the argument.
If both the argument and the type are not present returns a list
with the symbol 'eof."
(eat-separators stream)
(with-argument-readtable
(let ((ret (let ((type-or-arg (read stream nil 'eof t)))
(if (cffi-type-p type-or-arg)
(list type-or-arg (read stream nil 'eof t))
(list type-or-arg)))))
(cond
((and (not *accept-untyped-call*)
(= 1 (length ret))
(t ret)))))
(defun read-args-and-selector (stream)
(do* ((selector-part (read-selector-part stream) (read-selector-part stream))
(arg/type (read-arg-and-type stream) (append arg/type (read-arg-and-type stream)))
(typed t)
(selector selector-part (if (not (eq 'eof selector-part))
(concatenate 'string selector selector-part)
selector)))
((or (eq selector-part 'eof)
(eq (car arg/type) 'eof)) (list (remove 'eof arg/type) selector typed))
(when (or (and (= 2 (length arg/type))
(eq 'eof (second arg/type)))
(= 1 (length arg/type)))
(setf typed nil))))
(defun objc-read-left-square-bracket (stream char)
"Read an objc form: [ receiver selector args*].
Both receiver selector and each arg can be a lisp form or an objc
form (starting with an another #\[).
The receiver and the selector will be read using the objc
readtable (so preserving the case). You can escape using the
comma (e.g. in order to use a lisp variable containing the class
object). As a special case if a class name is found as receiver
it will be read and evalued as (objc-get-class (symbol-name
receiver-read)).
The args will be read with the lisp readtable.
"
(declare (ignore char))
(flet ((starts-with-a-upcase-char-p (string)
(let ((first-char (elt string 0)))
(and (alpha-char-p first-char)
(char-equal (char-upcase first-char) first-char)))))
(with-objc-readtable
(let ((id (read stream t nil t)))
(let ((receiver (if (and (symbolp id) (starts-with-a-upcase-char-p (symbol-name id)))
(if *use-clos-interface*
`(objc-clos:meta (objc-class-name-to-symbol (class-name (objc-get-class ,(symbol-name id)))))
`(objc-get-class ,(symbol-name id)))
id)))
(destructuring-bind (args selector typed)
(read-args-and-selector stream)
(if typed
(if *use-clos-interface*
`(objc-clos:convert-result-from-objc (typed-objc-msg-send ((objc:objc-id ,receiver) ,selector) ,@args))
`(typed-objc-msg-send (,receiver ,selector) ,@args))
(if *use-clos-interface*
`(objc-clos:convert-result-from-objc (untyped-objc-msg-send (objc:objc-id ,receiver) ,selector ,@args))
`(untyped-objc-msg-send ,receiver ,selector ,@args)))))))))
(defun read-at-sign (stream char n)
(declare (ignore n))
(unread-char char stream)
(typed-objc-msg-send
((typed-objc-msg-send ((objc-get-class "NSString") "alloc"))
"initWithUTF8String:")
:string (read stream t nil t)))
(defun restore-readtable ()
"Restore the readtable being present before the call of
ACTIVATE-OBJC-READER-MACRO."
(setf *readtable* *old-readtable*))
(defun activate-objc-reader-macro (&optional (accept-untyped-call nil) (use-clos-interface nil))
"Installs a the ObjectiveC readtable. If ACCEPT-UNTYPED-CALL is
NIL method has to be invoked with input type parameters. It saves
the current readtable to be later restored with
RESTORE-READTABLE"
(setf *old-readtable* (copy-readtable)
*accept-untyped-call* accept-untyped-call
*use-clos-interface* use-clos-interface)
(set-macro-character #\] #'objc-read-right-square-bracket)
(unless (get-macro-character #\@)
(make-dispatch-macro-character #\@))
(set-dispatch-macro-character #\@ #\" #'read-at-sign)
(setf *objc-argument-readtable* (copy-readtable))
(set-macro-character #\[ #'objc-read-left-square-bracket)
(set-macro-character #\, #'objc-read-comma)
(setf *objc-readtable* (copy-readtable)))
Copyright ( c ) 2007 ,
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT
THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
|
85cbb438c6653bbeefdeb491d38ecc4851968b3a8783f68ff1745745ac081a51 | AeroNotix/lispkit | package.lisp | (defpackage #:lispkit-test
(:use :cl :lispkit :prove))
| null | https://raw.githubusercontent.com/AeroNotix/lispkit/2482dbeabc79667407dabe7765dfbffc16584b08/test/package.lisp | lisp | (defpackage #:lispkit-test
(:use :cl :lispkit :prove))
| |
2396d04af3d5eaf7e29dc33236ee2b6432ce2a6573e8af1142345d5866b6498c | alex-hhh/ActivityLog2 | inspect-best-avg.rkt | #lang racket/base
;; inspect-mean-max.rkt -- mean-max plot view for a session. This is not
;; supported for swimming activites.
;;
;; This file is part of ActivityLog2, an fitness activity tracker
Copyright ( C ) 2015 , 2018 , 2019 , 2020 , 2021 < >
;;
;; 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 3 of the License , or ( at your option )
;; any later version.
;;
;; This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
;; more details.
(require data-frame
db/base
pict/snip
plot-container
plot-container/hover-util
plot/no-gui
racket/class
racket/date
racket/gui/base
racket/list
racket/match
"../bavg-util.rkt"
"../database.rkt"
"../dbapp.rkt"
"../fmt-util-ut.rkt"
"../fmt-util.rkt"
"../metrics.rkt"
"../models/critical-power.rkt"
"../session-df/native-series.rkt"
"../session-df/xdata-series.rkt"
"../utilities.rkt")
(provide mean-max-plot-panel%)
Filter AXIS - LIST to remove any axis definition that do n't have a data
series in DF , a data - frame%
(define (filter-axis-list df axis-list)
(define (valid? axis)
(if (list? axis)
(let ()
(match-define (list name a1 a2) axis)
(df-contains? df (send a1 series-name) (send a2 series-name)))
(df-contains? df (send axis series-name))))
(define (sort-key axis)
(if (list? axis) (first axis) (send axis headline)))
(sort (filter valid? axis-list) string<? #:key sort-key))
;; Find an axis that works in SERIES-NAME and return its position in
AXIS - LIST . Return # f is not found
(define (find-axis series-name axis-list)
(define (match? axis)
(let ((sn (if (list? axis)
(car axis)
(send axis series-name))))
(equal? series-name sn)))
(for/first ([(axis index) (in-indexed axis-list)]
#:when (match? axis))
index))
;; Axis choices for all non lap swimming sports. note that some axis choices
;; don't make sense, so they are not listed here, to keep the list smaller.
(define default-axis-choices
(list
axis-speed
axis-pace
axis-gap
axis-speed-zone
axis-grade
axis-grade-inverted
axis-hr-bpm
axis-hr-pct
axis-hr-zone
axis-cadence
axis-vertical-oscillation
axis-stance-time
axis-stance-time-percent
axis-stride
axis-vratio
axis-power
axis-power-zone
axis-left-torque-effectiveness
axis-right-torque-effectiveness
axis-left-pedal-smoothness
axis-right-pedal-smoothness
axis-left-power-phase-angle
axis-left-peak-power-phase-angle
axis-right-power-phase-angle
axis-right-peak-power-phase-angle
axis-temperature
))
;; Axis choices for lap swimming
(define swim-axis-choices
(list
axis-swim-avg-cadence
axis-swim-stroke-count
axis-swim-stroke-length
axis-swim-swolf
axis-swim-pace))
Return the start of today as a UNIX timestamp ( in seconds )
(define (this-day-start)
(let ((now (current-date)))
(date->seconds
(date 0 0 0
(date-day now) (date-month now) (date-year now)
0 0 (date-dst? now) (date-time-zone-offset now)))))
;; Default time periods for the "Show bests" plot.
(define default-periods
(list
(list "None" (lambda () #f))
(list "Last Month"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 30 24 3600)) (+ end (* 24 3600))))))
(list "Last 6 Weeks"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 42 24 3600)) (+ end (* 24 3600))))))
(list "Last 3 Months"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 90 24 3600)) (+ end (* 24 3600))))))
(list "Last 6 Months"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 180 24 3600)) (+ end (* 24 3600))))))
(list "Last 12 Months"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 365 24 3600)) (+ end (* 24 3600))))))
(list "All Time"
(lambda ()
(let ((end (this-day-start)))
(cons #f #f))))))
;; Return a list of time intervals for each defined season in the database.
;; The list is in the same format as `default-periods'
(define (make-periods-from-seasons db)
(for/list (((name start end)
(in-query db "select name, start_date, end_date from SEASON order by start_date")))
(list (format "~a season" name) (lambda () (cons start end)))))
;; Find an axis that works in SERIES-NAME and return its position in
AXIS - LIST . Return # f is not found
(define (find-period name period-list)
(define (match? ti) (equal? name (first ti)))
(for/first ([(ti index) (in-indexed period-list)]
#:when (match? ti))
index))
Return a list of session i d based that match SPORT , a ( Vectorof sport - id
sub - sport - id ) and TIME - INTERVAL , a ( Cons start end ) .
(define (get-candidate-sessions db sport period)
(if period
(match-let (((vector sport-id sub-sport-id) sport)
((cons start end) period))
(fetch-candidate-sessions db sport-id sub-sport-id start end))
'()))
Return suitable plot bounds for a mean - , considering all input
data . Returns four values : MIN - X , MAX - X , MIN - Y , MAX - Y.
(define (plot-bounds axis zero-base? mean-max-data bests-data cp-data)
(define inverted? (send axis inverted-mean-max?))
;; Start with the interval defined by the MEAN-MAX-DATA...
(define-values (min-x-0 max-x-0 min-y-0 max-y-0)
(get-mean-max-bounds mean-max-data))
;; Adjust the Y range to fit the BESTS-DATA as well (if any). Note that an
;; inverted series such as PACE, will need to update the minimum value, not
;; the maximum one.
(define-values (min-x-1 max-x-1 min-y-1 max-y-1)
(let-values ([(bmin-x bmax-x bmin-y bmax-y) (aggregate-mmax-bounds bests-data)])
(values min-x-0 max-x-0
(if (and inverted? bmin-y) (min bmin-y min-y-0) min-y-0)
(if (and (not inverted?) bmax-y) (max bmax-y max-y-0) max-y-0))))
The CP3 model also has a limit at 0 , so adjust the Y limit so the model
is inside the plot too ( CP2 is infinite at 0 , and would dwarf the rest of
;; the plot, so we don't adjust for it). If the series is inverted, we
;; adjust the minimum Y value.
(define-values (min-x-2 max-x-2 min-y-2 max-y-2)
(let ([pmax (and (cp3? cp-data) ((cp3-function cp-data) min-x-0))])
(if pmax
(values min-x-1 max-x-1
(if inverted? (min pmax min-y-1) min-y-1)
(if inverted? max-y-1 (max pmax max-y-1)))
(values min-x-1 max-x-1 min-y-1 max-y-1))))
;; Finally, if we are instructed to start the plot at 0, we do so...
(values min-x-2 max-x-2 (if zero-base? 0 min-y-2) max-y-2))
(define mean-max-plot-panel%
(class object% (init parent) (super-new)
(define pref-tag 'activity-log:mean-max-plot)
(define axis-choices '())
(define period-choices '())
(define selected-axis 0)
(define selected-aux-axis 0)
(define selected-period 0)
(define zero-base? #f)
;; Store plot parameters by sport type, to be restored when a session from
;; the same sport is used. See `save-params-for-sport',
;; 'restore-params-for-sport'.
;;
;; maps SPORT => params-by-series hash
(define params-by-sport (make-hash))
;; Store plot parameters for each selected series (what AUX axis and what
;; Bests period to show). See `save-params-for-series',
;; 'restore-params-for-series'
;;
maps SERIES NAME - > ( List AUX - SERIES - NAME BESTS - PERIOD - NAME ZERO - BASE ? )
(define params-by-series (make-hash))
;; Restore the saved preferences now.
(let ((pref (get-pref pref-tag (lambda () #f))))
(when (and pref (eqv? (length pref) 1))
(set! params-by-sport (hash-copy (first pref)))))
;; Root widget of the entire scatter plot panel
(define panel
(new (class vertical-panel%
(init) (super-new)
(define/public (interactive-export-image)
(on-interactive-export-image))
(define/public (interactive-export-data formatted?)
(on-interactive-export-data formatted?)))
[parent parent] [border 5] [spacing 5]
[alignment '(center top)]))
;; Holds the widgets that control the look of the plot
(define control-panel
(new horizontal-panel%
[parent panel] [spacing 10] [border 0]
[alignment '(center center)]
[stretchable-height #f]))
(define axis-choice-box
(new choice% [parent control-panel] [choices '()]
[min-width 300] [label "Best Avg: "]
[callback (lambda (c e) (on-axis-changed (send c get-selection)))]))
(define aux-axis-choice-box
(new choice% [parent control-panel] [choices '()]
[min-width 300] [label "Auxiliary: "]
[callback (lambda (c e) (on-aux-axis-changed (send c get-selection)))]))
(define period-choice-box
(new choice% [parent control-panel] [choices '()]
[min-width 300] [label "Show Best: "]
[callback (lambda (c e) (on-period-changed (send c get-selection)))]))
(define zero-base-check-box
(new check-box% [parent control-panel]
[value zero-base?] [label "Zero Base"]
[callback (lambda (c e) (on-zero-base (send c get-value)))]))
Pasteboard to display the actual MEAN - MAX plot
(define plot-pb (new plot-container% [columns 1] [parent panel]))
Graph data
(define data-frame #f)
(define mean-max-data '())
(define mean-max-plot-fn #f)
(define mean-max-aux-data '())
(define mean-max-aux-plot-fn #f)
(define mean-max-aux-invfn #f)
(define mean-max-pd-fn #f)
(define inhibit-refresh 0)
(define plot-rt #f)
;; The plot render tree for the "bests" plot
(define best-rt #f)
(define best-fn #f)
(define best-rt-generation 0)
(define bests-data '())
(define data-cache (make-hash))
;; The name of the file used by 'on-interactive-export-image'. This is
remembered between subsequent exports , but reset when one of the axis
;; changes.
(define img-export-file-name #f)
(define data-export-file-name #f)
(define pd-model-snip #f)
(define saved-pd-model-snip-location #f)
(define (current-sport)
(if data-frame (df-get-property data-frame 'sport) #f))
(define (session-id)
(if data-frame (df-get-property data-frame 'session-id) #f))
(define (get-series-axis)
(list-ref axis-choices selected-axis))
(define (get-aux-axis)
(and (> selected-aux-axis 0)
(list-ref axis-choices (sub1 selected-aux-axis))))
(define (get-best-rt-generation) best-rt-generation)
(define (install-axis-choices)
(let ((alist (append (if (df-get-property data-frame 'is-lap-swim?)
swim-axis-choices default-axis-choices)
(get-available-xdata-metadata))))
(set! axis-choices (filter-axis-list data-frame alist)))
(send axis-choice-box clear)
(send aux-axis-choice-box clear)
(send aux-axis-choice-box append "None")
(for ([a axis-choices])
(let ((n (send a axis-label)))
(send axis-choice-box append n)
(send aux-axis-choice-box append n))))
(define (install-period-choices)
(set! period-choices
(append default-periods
(make-periods-from-seasons (current-database))))
(send period-choice-box clear)
(for ([t period-choices])
(send period-choice-box append (car t))))
(define (on-period-changed new-index)
(unless (equal? selected-period new-index)
(set! selected-period new-index)
(refresh-bests-plot)))
When ' - save - previous ' is # t , previous axis params are not saved
;; before setting up the new axis. This is used when
;; 'restore-params-for-sport' installs the new axis and there is no
;; previous axis to save (otherwise the selected axis params will be
crossing from one sport to the other ) .
(define (on-axis-changed new-index (dont-save-previous #f))
(unless (equal? selected-axis new-index)
(unless dont-save-previous
(save-params-for-series))
(set! selected-axis new-index)
(set! img-export-file-name #f)
(set! data-export-file-name #f)
(restore-params-for-series)
(refresh-bests-plot)
(refresh-plot)))
(define (on-aux-axis-changed new-index)
(unless (equal? selected-aux-axis new-index)
(set! selected-aux-axis new-index)
(set! img-export-file-name #f)
(set! data-export-file-name #f)
(refresh-plot)))
(define (on-zero-base flag)
(unless (equal? zero-base? flag)
(set! zero-base? flag)
(refresh-plot)))
(define (make-plot-hover-callback)
(define axis (get-series-axis))
(define format-value (send axis value-formatter (current-sport) (session-id)))
(define axis-name (send axis name))
(define format-aux-value
(let ((aux (get-aux-axis)))
(and aux (send aux value-formatter (current-sport) (session-id)))))
(define aux-axis-name
(let ((aux (get-aux-axis)))
(and aux (send aux name))))
(lambda (snip event x y)
(define info '())
(define renderers '())
(define markers '())
(define (add-renderer r) (set! renderers (cons r renderers)))
(define (add-info tag value)
(set! info (cons (list tag value) info)))
(define (add-data-point name yfn format-fn)
(when yfn
(let ((py (yfn x)))
(when py
(add-info name (format-fn py))
(set! markers (cons (vector x py) markers))))))
(when (good-hover? snip x y event)
(add-renderer (hover-vrule x))
;; The aux values need special treatment: they are scaled to match the
;; main axis coordinate system, this works for the plot itself, but we
;; need to convert the value back for display.
(when (and mean-max-aux-plot-fn mean-max-aux-invfn)
(let* ((ay (mean-max-aux-plot-fn x)))
(when ay
(let ((actual-ay ((invertible-function-f mean-max-aux-invfn) ay)))
(add-info aux-axis-name (format-aux-value actual-ay))
(set! markers (cons (vector x ay) markers))))))
(add-data-point "Model" mean-max-pd-fn format-value)
;; Find the closest point on the bests plot and put the date on which
it was achieved . Technically , the hover will be between two such
;; measurements, but for simplicity we show only the one that it is
;; closest to the mouse. The trends-mmax plot shows both points.
(when bests-data
(let ((closest (lookup-duration/closest bests-data x)))
(when closest
See # 70 , the session might have been deleted from the
;; database
(define session-start-time (get-session-start-time (car closest)))
(when session-start-time
(add-info #f (date-time->string session-start-time))))))
(add-data-point "Best" best-fn format-value)
(add-data-point axis-name mean-max-plot-fn format-value)
(add-info "Duration" (duration->string x))
(unless (empty? info)
(add-renderer (hover-markers markers))
(add-renderer (hover-label x y (make-hover-badge (reverse info))))))
(set-overlay-renderers snip renderers)))
(define (put-plot-snip)
(when plot-rt
(let ((rt (list (tick-grid) plot-rt)))
(when best-rt
(set! rt (cons best-rt rt)))
(let* ([mean-max-axis (get-series-axis)]
NOTE : we assume that CP - DATA corresponds to the series if
the series has a CP estimate . However , this creates
;; problems for running activities which may have both a
Critical Power and a Critical Velocity , see also AB#33
[cp-data (and mean-max-axis
(send mean-max-axis have-cp-estimate?)
(df-get-property data-frame 'critical-power))]
[aux-axis (get-aux-axis)]
;; get the location of the pd-model-snip here, it will be
;; lost once we insert a new plot in the canvas.
[saved-location (get-snip-location pd-model-snip)])
(let-values (((min-x max-x min-y max-y)
(plot-bounds (get-series-axis) zero-base? mean-max-data bests-data cp-data)))
;; aux data might not exist, if an incorrect/invalid aux-axis is
;; selected
(if (> (length mean-max-aux-data) 0)
(let ((ivs (mk-invertible-function mean-max-aux-data mean-max-data zero-base?)))
(set! mean-max-aux-invfn ivs)
(parameterize ([plot-x-ticks (mean-max-ticks)]
[plot-x-label "Duration"]
[plot-x-transform log-transform]
[plot-x-tick-label-anchor 'top-right]
[plot-x-tick-label-angle 30]
[plot-y-ticks (send mean-max-axis plot-ticks)]
[plot-y-label (send mean-max-axis axis-label)]
[plot-y-far-ticks (ticks-scale (send aux-axis plot-ticks) ivs)]
[plot-y-far-label (send aux-axis axis-label)])
(define snip (plot-to-canvas rt plot-pb
#:x-min min-x #:x-max max-x
#:y-min min-y #:y-max max-y
))
(set-mouse-event-callback snip (make-plot-hover-callback))))
(parameterize ([plot-x-ticks (mean-max-ticks)]
[plot-x-label "Duration"]
[plot-x-transform log-transform]
[plot-x-tick-label-anchor 'top-right]
[plot-x-tick-label-angle 30]
[plot-y-ticks (send mean-max-axis plot-ticks)]
[plot-y-label (send mean-max-axis axis-label)])
(define snip (plot-to-canvas rt plot-pb
#:x-min min-x #:x-max max-x
#:y-min min-y #:y-max max-y))
(set-mouse-event-callback snip (make-plot-hover-callback))))
(when (and cp-data (send mean-max-axis have-cp-estimate?) mean-max-data)
;; NOTE: this is inefficient, as the plot-fn is already
;; computed in the `mean-max-renderer` and we are computing it
here a second time .
(let* ((fn (mean-max->spline mean-max-data))
(pict (send mean-max-axis pd-data-as-pict cp-data fn)))
(set! pd-model-snip (new pict-snip% [pict pict]))
(send plot-pb set-floating-snip pd-model-snip 0 0)
(move-snip-to pd-model-snip (or saved-location saved-pd-model-snip-location)))))))))
(define (refresh-plot)
(set! saved-pd-model-snip-location
(or (get-snip-location pd-model-snip)
saved-pd-model-snip-location))
(set! plot-rt #f)
(set! pd-model-snip #f)
(send plot-pb set-background-message "Working...")
(send plot-pb clear-all)
(unless (> inhibit-refresh 0)
;; Capture all needed data, as we will work in a different thread.
(let ((df data-frame)
(cache data-cache)
(axis (get-series-axis))
(aux-axis (get-aux-axis))
(zerob? zero-base?)
(renderer-tree '()))
(queue-task
"inspect-mean-max%/refresh-plot"
(lambda ()
(define data
(or (hash-ref cache axis #f)
(get-session-mmax df axis)))
(hash-set! cache axis data)
;; rebuild auxiliary data here
(define aux-data
(if aux-axis
(let ((series (send aux-axis series-name)))
(and (df-contains? df series)
(df-mean-max-aux df series data)))
'()))
(when (> (length data) 0) ; might not have any data points at all
(set! renderer-tree
(cons
(mean-max-renderer
data aux-data
#:color1 (send axis plot-color)
#:color2 (and aux-axis (send aux-axis plot-color))
#:zero-base? zerob?)
renderer-tree)))
(define pd-function
(let ((cp-data (df-get-property df 'critical-power)))
(and cp-data (send axis pd-function cp-data))))
(when pd-function
(set! renderer-tree
(cons (function pd-function #:color "red" #:width 1.5 #:style 'long-dash)
renderer-tree)))
;; NOTE: these are already calculated in mean-max-renderer!
(define plot-fn (mean-max->spline data))
(define aux-plot-fn (mean-max->spline (normalize-aux aux-data data zerob?)))
(queue-callback
(lambda ()
(cond ((not (null? renderer-tree))
(set! mean-max-data data)
(set! mean-max-aux-data aux-data)
(set! mean-max-plot-fn plot-fn)
(set! mean-max-aux-plot-fn aux-plot-fn)
(set! mean-max-pd-fn pd-function)
(set! plot-rt renderer-tree)
(set! cache data-cache)
(put-plot-snip))
(#t
(send plot-pb set-background-message "No data to plot"))))))))))
(define (refresh-bests-plot)
(define debug-tag "inspect-mean-max%/refresh-bests-plot")
(unless (> inhibit-refresh 0)
(set! best-rt-generation (add1 best-rt-generation))
(set! best-rt #f)
(let ((axis (get-series-axis))
(generation best-rt-generation)
(time-interval selected-period))
(queue-task
debug-tag
(lambda ()
(define candidates
(get-candidate-sessions
(current-database)
(df-get-property data-frame 'sport)
((second (list-ref period-choices time-interval)))))
(define inverted? (send axis inverted-mean-max?))
(define mmax (get-aggregate-mmax candidates axis #f))
(define fn (aggregate-mmax->spline-fn mmax))
(define brt
(and fn
(function-interval
;; The bottom (or top) of the shaded area needs to cover
;; the entire plot and it is too difficult to find out
;; the true min/max X value of the plot, so we just put
;; what we hope are large enough values. The plot will
;; be clipped at the right spot.
(if inverted? (lambda (x) 10000) (lambda (x) -10000))
fn
#:color (send axis plot-color)
#:alpha 0.1
#:line2-color "black"
#:line2-width 0.5
#:line1-style 'transparent)))
(queue-callback
(lambda ()
;; Discard changes if there was a new request since ours was
;; submitted.
(let ((current-generation (get-best-rt-generation)))
(when (= generation current-generation)
(set! best-rt brt)
(set! best-fn fn)
(set! bests-data mmax)
(put-plot-snip))))))))))
(define (save-params-for-sport)
(when (current-sport)
(save-params-for-series)
(let ((axis (get-series-axis)))
(hash-set! params-by-sport
(current-sport)
(list 'gen1 (send axis series-name) params-by-series)))))
(define (restore-params-for-sport)
(set! inhibit-refresh (add1 inhibit-refresh))
(let ((params (hash-ref params-by-sport (current-sport) #f)))
(if (and params (eq? (car params) 'gen1))
(match-let (((list tag series-name pbs) params))
(let ((selection 0))
(when series-name
(let ((index (find-axis series-name axis-choices)))
(set! selection (min (or index 0) (sub1 (length axis-choices))))))
(on-axis-changed selection #t)
(set! params-by-series (hash-copy pbs))))
(begin
(on-axis-changed 0 #t)
(set! params-by-series (make-hash))))
(send axis-choice-box set-selection selected-axis)
(restore-params-for-series)
(set! inhibit-refresh (sub1 inhibit-refresh))))
(define (save-params-for-series)
(when (current-sport)
(let ((axis (get-series-axis))
(aux-axis (get-aux-axis))
(period (list-ref period-choices selected-period)))
(hash-set!
params-by-series
(send axis series-name)
(hash
'aux-series-name (and aux-axis (send aux-axis series-name))
'period-name (first period)
'zero-base? zero-base?
'pd-model-snip-location (get-snip-location pd-model-snip))))))
(define (restore-params-for-series)
(set! inhibit-refresh (add1 inhibit-refresh))
(let* ((axis (get-series-axis))
(series-name (send axis series-name))
(params (hash-ref params-by-series series-name #f)))
(if (and params (hash? params))
(begin
(let ((aux-series-name (hash-ref params 'aux-series-name #f))
(selection 0))
(when aux-series-name
(let ((index (find-axis aux-series-name axis-choices)))
(set! selection (add1 (min (or index 0) (sub1 (length axis-choices)))))))
(on-aux-axis-changed selection))
(let ((period-name (hash-ref params 'period-name #f))
(selection 0))
(when period-name
(let ((index (find-period period-name period-choices)))
(set! selection (min (or index 0) (sub1 (length period-choices))))))
(on-period-changed selection))
(let ((zb? (hash-ref params 'zero-base? #f)))
(on-zero-base zb?))
(set! saved-pd-model-snip-location
(hash-ref params 'pd-model-snip-location #f)))
(begin
(on-aux-axis-changed 0)
(on-period-changed 0))))
(send aux-axis-choice-box set-selection selected-aux-axis)
(send period-choice-box set-selection selected-period)
(send zero-base-check-box set-value zero-base?)
(set! inhibit-refresh (sub1 inhibit-refresh)))
(define/public (save-visual-layout)
(when (> (length axis-choices) 0)
(save-params-for-sport)
(put-pref pref-tag (list params-by-sport))))
;; Return a suitable file name for use by 'on-interactive-export-image'.
;; If 'export-file-name' is set, we use that, otherwise we compose a file
;; name from the session id and axis names of the plot.
(define (get-default-export-file-name (extenstion "png"))
(let ((sid (df-get-property data-frame 'session-id))
(axis1 (get-series-axis))
(axis2 (get-aux-axis)))
(cond ((and sid axis1 axis2)
(format "mean-max-~a-~a-~a.~a" sid
(send axis1 series-name)
(send axis2 series-name)
extenstion))
((and sid axis1)
(format "mean-max-~a-~a.~a" sid
(send axis1 series-name)
extenstion))
(#t
(format "mean-max.~a" extenstion)))))
(define/public (on-interactive-export-image)
(let ((file (put-file "Select file to export to" #f #f
(or img-export-file-name (get-default-export-file-name "png"))
"png" '()
'(("PNG Files" "*.png") ("Any" "*.*")))))
(when file
(set! img-export-file-name file)
(send plot-pb export-image-to-file file))))
(define/public (on-interactive-export-data formatted?)
(let ((file (put-file "Select file to export to" #f #f
(or data-export-file-name (get-default-export-file-name "csv"))
"csv" '()
'(("CSV Files" "*.csv") ("Any" "*.*")))))
(when file
(set! data-export-file-name file)
(call-with-output-file file
(lambda (out) (export-data-as-csv out formatted?))
#:mode 'text #:exists 'truncate))))
(define (export-data-as-csv out formatted?)
(define have-aux? (and mean-max-aux-data (= (length mean-max-aux-data) (length mean-max-data))))
(define have-bests? (and bests-data (<= (length mean-max-data) (length bests-data))))
(write-string "Timestamp, Duration, Value" out)
(when have-aux? (write-string ", Aux Value" out))
(when have-bests? (write-string ", Best SID, Best Timestamp, Best Value" out))
(newline out)
(for ((index (in-range (length mean-max-data))))
(match-define (vector d m s)
(list-ref mean-max-data index))
(if m
(write-string (format "~a, ~a, ~a"
(exact->inexact s)
(exact->inexact d)
(exact->inexact m))
out)
(write-string (format ", , ") out))
(when have-aux?
(match-define (vector d m s)
(list-ref mean-max-aux-data index))
(if m
(write-string (format ", ~a" (exact->inexact m)) out)
(write-string ", " out)))
(when have-bests?
(match-define (list sid ts d m)
(list-ref bests-data index))
(format "bests: ~a ~a ~a ~a~%" sid ts d m)
(if m
(write-string (format ", ~a, ~a, ~a" sid (exact->inexact ts) (exact->inexact m)) out)
(write-string (format ", , ,") out)))
(newline out)))
(define/public (set-session s df)
(set! inhibit-refresh (add1 inhibit-refresh))
(save-params-for-sport)
(set! data-frame df)
(set! data-cache (make-hash))
(set! img-export-file-name #f)
(set! data-export-file-name #f)
(set! plot-rt #f)
(set! best-rt #f)
(install-axis-choices)
(if (> (length axis-choices) 0)
(begin
(install-period-choices)
(restore-params-for-sport)
(set! inhibit-refresh (sub1 inhibit-refresh))
(refresh-bests-plot)
(refresh-plot))
(set! inhibit-refresh (sub1 inhibit-refresh))))
))
| null | https://raw.githubusercontent.com/alex-hhh/ActivityLog2/b3aa88bb840b79e5a363a96b5ab35faf7aaf5a5b/rkt/session-inspector/inspect-best-avg.rkt | racket | inspect-mean-max.rkt -- mean-max plot view for a session. This is not
supported for swimming activites.
This file is part of ActivityLog2, an fitness activity tracker
This program is free software: you can redistribute it and/or modify it
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
Find an axis that works in SERIES-NAME and return its position in
Axis choices for all non lap swimming sports. note that some axis choices
don't make sense, so they are not listed here, to keep the list smaller.
Axis choices for lap swimming
Default time periods for the "Show bests" plot.
Return a list of time intervals for each defined season in the database.
The list is in the same format as `default-periods'
Find an axis that works in SERIES-NAME and return its position in
Start with the interval defined by the MEAN-MAX-DATA...
Adjust the Y range to fit the BESTS-DATA as well (if any). Note that an
inverted series such as PACE, will need to update the minimum value, not
the maximum one.
the plot, so we don't adjust for it). If the series is inverted, we
adjust the minimum Y value.
Finally, if we are instructed to start the plot at 0, we do so...
Store plot parameters by sport type, to be restored when a session from
the same sport is used. See `save-params-for-sport',
'restore-params-for-sport'.
maps SPORT => params-by-series hash
Store plot parameters for each selected series (what AUX axis and what
Bests period to show). See `save-params-for-series',
'restore-params-for-series'
Restore the saved preferences now.
Root widget of the entire scatter plot panel
Holds the widgets that control the look of the plot
The plot render tree for the "bests" plot
The name of the file used by 'on-interactive-export-image'. This is
changes.
before setting up the new axis. This is used when
'restore-params-for-sport' installs the new axis and there is no
previous axis to save (otherwise the selected axis params will be
The aux values need special treatment: they are scaled to match the
main axis coordinate system, this works for the plot itself, but we
need to convert the value back for display.
Find the closest point on the bests plot and put the date on which
measurements, but for simplicity we show only the one that it is
closest to the mouse. The trends-mmax plot shows both points.
database
problems for running activities which may have both a
get the location of the pd-model-snip here, it will be
lost once we insert a new plot in the canvas.
aux data might not exist, if an incorrect/invalid aux-axis is
selected
NOTE: this is inefficient, as the plot-fn is already
computed in the `mean-max-renderer` and we are computing it
Capture all needed data, as we will work in a different thread.
rebuild auxiliary data here
might not have any data points at all
NOTE: these are already calculated in mean-max-renderer!
The bottom (or top) of the shaded area needs to cover
the entire plot and it is too difficult to find out
the true min/max X value of the plot, so we just put
what we hope are large enough values. The plot will
be clipped at the right spot.
Discard changes if there was a new request since ours was
submitted.
Return a suitable file name for use by 'on-interactive-export-image'.
If 'export-file-name' is set, we use that, otherwise we compose a file
name from the session id and axis names of the plot. | #lang racket/base
Copyright ( C ) 2015 , 2018 , 2019 , 2020 , 2021 < >
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 )
(require data-frame
db/base
pict/snip
plot-container
plot-container/hover-util
plot/no-gui
racket/class
racket/date
racket/gui/base
racket/list
racket/match
"../bavg-util.rkt"
"../database.rkt"
"../dbapp.rkt"
"../fmt-util-ut.rkt"
"../fmt-util.rkt"
"../metrics.rkt"
"../models/critical-power.rkt"
"../session-df/native-series.rkt"
"../session-df/xdata-series.rkt"
"../utilities.rkt")
(provide mean-max-plot-panel%)
Filter AXIS - LIST to remove any axis definition that do n't have a data
series in DF , a data - frame%
(define (filter-axis-list df axis-list)
(define (valid? axis)
(if (list? axis)
(let ()
(match-define (list name a1 a2) axis)
(df-contains? df (send a1 series-name) (send a2 series-name)))
(df-contains? df (send axis series-name))))
(define (sort-key axis)
(if (list? axis) (first axis) (send axis headline)))
(sort (filter valid? axis-list) string<? #:key sort-key))
AXIS - LIST . Return # f is not found
(define (find-axis series-name axis-list)
(define (match? axis)
(let ((sn (if (list? axis)
(car axis)
(send axis series-name))))
(equal? series-name sn)))
(for/first ([(axis index) (in-indexed axis-list)]
#:when (match? axis))
index))
(define default-axis-choices
(list
axis-speed
axis-pace
axis-gap
axis-speed-zone
axis-grade
axis-grade-inverted
axis-hr-bpm
axis-hr-pct
axis-hr-zone
axis-cadence
axis-vertical-oscillation
axis-stance-time
axis-stance-time-percent
axis-stride
axis-vratio
axis-power
axis-power-zone
axis-left-torque-effectiveness
axis-right-torque-effectiveness
axis-left-pedal-smoothness
axis-right-pedal-smoothness
axis-left-power-phase-angle
axis-left-peak-power-phase-angle
axis-right-power-phase-angle
axis-right-peak-power-phase-angle
axis-temperature
))
(define swim-axis-choices
(list
axis-swim-avg-cadence
axis-swim-stroke-count
axis-swim-stroke-length
axis-swim-swolf
axis-swim-pace))
Return the start of today as a UNIX timestamp ( in seconds )
(define (this-day-start)
(let ((now (current-date)))
(date->seconds
(date 0 0 0
(date-day now) (date-month now) (date-year now)
0 0 (date-dst? now) (date-time-zone-offset now)))))
(define default-periods
(list
(list "None" (lambda () #f))
(list "Last Month"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 30 24 3600)) (+ end (* 24 3600))))))
(list "Last 6 Weeks"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 42 24 3600)) (+ end (* 24 3600))))))
(list "Last 3 Months"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 90 24 3600)) (+ end (* 24 3600))))))
(list "Last 6 Months"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 180 24 3600)) (+ end (* 24 3600))))))
(list "Last 12 Months"
(lambda ()
(let ((end (this-day-start)))
(cons (- end (* 365 24 3600)) (+ end (* 24 3600))))))
(list "All Time"
(lambda ()
(let ((end (this-day-start)))
(cons #f #f))))))
(define (make-periods-from-seasons db)
(for/list (((name start end)
(in-query db "select name, start_date, end_date from SEASON order by start_date")))
(list (format "~a season" name) (lambda () (cons start end)))))
AXIS - LIST . Return # f is not found
(define (find-period name period-list)
(define (match? ti) (equal? name (first ti)))
(for/first ([(ti index) (in-indexed period-list)]
#:when (match? ti))
index))
Return a list of session i d based that match SPORT , a ( Vectorof sport - id
sub - sport - id ) and TIME - INTERVAL , a ( Cons start end ) .
(define (get-candidate-sessions db sport period)
(if period
(match-let (((vector sport-id sub-sport-id) sport)
((cons start end) period))
(fetch-candidate-sessions db sport-id sub-sport-id start end))
'()))
Return suitable plot bounds for a mean - , considering all input
data . Returns four values : MIN - X , MAX - X , MIN - Y , MAX - Y.
(define (plot-bounds axis zero-base? mean-max-data bests-data cp-data)
(define inverted? (send axis inverted-mean-max?))
(define-values (min-x-0 max-x-0 min-y-0 max-y-0)
(get-mean-max-bounds mean-max-data))
(define-values (min-x-1 max-x-1 min-y-1 max-y-1)
(let-values ([(bmin-x bmax-x bmin-y bmax-y) (aggregate-mmax-bounds bests-data)])
(values min-x-0 max-x-0
(if (and inverted? bmin-y) (min bmin-y min-y-0) min-y-0)
(if (and (not inverted?) bmax-y) (max bmax-y max-y-0) max-y-0))))
The CP3 model also has a limit at 0 , so adjust the Y limit so the model
is inside the plot too ( CP2 is infinite at 0 , and would dwarf the rest of
(define-values (min-x-2 max-x-2 min-y-2 max-y-2)
(let ([pmax (and (cp3? cp-data) ((cp3-function cp-data) min-x-0))])
(if pmax
(values min-x-1 max-x-1
(if inverted? (min pmax min-y-1) min-y-1)
(if inverted? max-y-1 (max pmax max-y-1)))
(values min-x-1 max-x-1 min-y-1 max-y-1))))
(values min-x-2 max-x-2 (if zero-base? 0 min-y-2) max-y-2))
(define mean-max-plot-panel%
(class object% (init parent) (super-new)
(define pref-tag 'activity-log:mean-max-plot)
(define axis-choices '())
(define period-choices '())
(define selected-axis 0)
(define selected-aux-axis 0)
(define selected-period 0)
(define zero-base? #f)
(define params-by-sport (make-hash))
maps SERIES NAME - > ( List AUX - SERIES - NAME BESTS - PERIOD - NAME ZERO - BASE ? )
(define params-by-series (make-hash))
(let ((pref (get-pref pref-tag (lambda () #f))))
(when (and pref (eqv? (length pref) 1))
(set! params-by-sport (hash-copy (first pref)))))
(define panel
(new (class vertical-panel%
(init) (super-new)
(define/public (interactive-export-image)
(on-interactive-export-image))
(define/public (interactive-export-data formatted?)
(on-interactive-export-data formatted?)))
[parent parent] [border 5] [spacing 5]
[alignment '(center top)]))
(define control-panel
(new horizontal-panel%
[parent panel] [spacing 10] [border 0]
[alignment '(center center)]
[stretchable-height #f]))
(define axis-choice-box
(new choice% [parent control-panel] [choices '()]
[min-width 300] [label "Best Avg: "]
[callback (lambda (c e) (on-axis-changed (send c get-selection)))]))
(define aux-axis-choice-box
(new choice% [parent control-panel] [choices '()]
[min-width 300] [label "Auxiliary: "]
[callback (lambda (c e) (on-aux-axis-changed (send c get-selection)))]))
(define period-choice-box
(new choice% [parent control-panel] [choices '()]
[min-width 300] [label "Show Best: "]
[callback (lambda (c e) (on-period-changed (send c get-selection)))]))
(define zero-base-check-box
(new check-box% [parent control-panel]
[value zero-base?] [label "Zero Base"]
[callback (lambda (c e) (on-zero-base (send c get-value)))]))
Pasteboard to display the actual MEAN - MAX plot
(define plot-pb (new plot-container% [columns 1] [parent panel]))
Graph data
(define data-frame #f)
(define mean-max-data '())
(define mean-max-plot-fn #f)
(define mean-max-aux-data '())
(define mean-max-aux-plot-fn #f)
(define mean-max-aux-invfn #f)
(define mean-max-pd-fn #f)
(define inhibit-refresh 0)
(define plot-rt #f)
(define best-rt #f)
(define best-fn #f)
(define best-rt-generation 0)
(define bests-data '())
(define data-cache (make-hash))
remembered between subsequent exports , but reset when one of the axis
(define img-export-file-name #f)
(define data-export-file-name #f)
(define pd-model-snip #f)
(define saved-pd-model-snip-location #f)
(define (current-sport)
(if data-frame (df-get-property data-frame 'sport) #f))
(define (session-id)
(if data-frame (df-get-property data-frame 'session-id) #f))
(define (get-series-axis)
(list-ref axis-choices selected-axis))
(define (get-aux-axis)
(and (> selected-aux-axis 0)
(list-ref axis-choices (sub1 selected-aux-axis))))
(define (get-best-rt-generation) best-rt-generation)
(define (install-axis-choices)
(let ((alist (append (if (df-get-property data-frame 'is-lap-swim?)
swim-axis-choices default-axis-choices)
(get-available-xdata-metadata))))
(set! axis-choices (filter-axis-list data-frame alist)))
(send axis-choice-box clear)
(send aux-axis-choice-box clear)
(send aux-axis-choice-box append "None")
(for ([a axis-choices])
(let ((n (send a axis-label)))
(send axis-choice-box append n)
(send aux-axis-choice-box append n))))
(define (install-period-choices)
(set! period-choices
(append default-periods
(make-periods-from-seasons (current-database))))
(send period-choice-box clear)
(for ([t period-choices])
(send period-choice-box append (car t))))
(define (on-period-changed new-index)
(unless (equal? selected-period new-index)
(set! selected-period new-index)
(refresh-bests-plot)))
When ' - save - previous ' is # t , previous axis params are not saved
crossing from one sport to the other ) .
(define (on-axis-changed new-index (dont-save-previous #f))
(unless (equal? selected-axis new-index)
(unless dont-save-previous
(save-params-for-series))
(set! selected-axis new-index)
(set! img-export-file-name #f)
(set! data-export-file-name #f)
(restore-params-for-series)
(refresh-bests-plot)
(refresh-plot)))
(define (on-aux-axis-changed new-index)
(unless (equal? selected-aux-axis new-index)
(set! selected-aux-axis new-index)
(set! img-export-file-name #f)
(set! data-export-file-name #f)
(refresh-plot)))
(define (on-zero-base flag)
(unless (equal? zero-base? flag)
(set! zero-base? flag)
(refresh-plot)))
(define (make-plot-hover-callback)
(define axis (get-series-axis))
(define format-value (send axis value-formatter (current-sport) (session-id)))
(define axis-name (send axis name))
(define format-aux-value
(let ((aux (get-aux-axis)))
(and aux (send aux value-formatter (current-sport) (session-id)))))
(define aux-axis-name
(let ((aux (get-aux-axis)))
(and aux (send aux name))))
(lambda (snip event x y)
(define info '())
(define renderers '())
(define markers '())
(define (add-renderer r) (set! renderers (cons r renderers)))
(define (add-info tag value)
(set! info (cons (list tag value) info)))
(define (add-data-point name yfn format-fn)
(when yfn
(let ((py (yfn x)))
(when py
(add-info name (format-fn py))
(set! markers (cons (vector x py) markers))))))
(when (good-hover? snip x y event)
(add-renderer (hover-vrule x))
(when (and mean-max-aux-plot-fn mean-max-aux-invfn)
(let* ((ay (mean-max-aux-plot-fn x)))
(when ay
(let ((actual-ay ((invertible-function-f mean-max-aux-invfn) ay)))
(add-info aux-axis-name (format-aux-value actual-ay))
(set! markers (cons (vector x ay) markers))))))
(add-data-point "Model" mean-max-pd-fn format-value)
it was achieved . Technically , the hover will be between two such
(when bests-data
(let ((closest (lookup-duration/closest bests-data x)))
(when closest
See # 70 , the session might have been deleted from the
(define session-start-time (get-session-start-time (car closest)))
(when session-start-time
(add-info #f (date-time->string session-start-time))))))
(add-data-point "Best" best-fn format-value)
(add-data-point axis-name mean-max-plot-fn format-value)
(add-info "Duration" (duration->string x))
(unless (empty? info)
(add-renderer (hover-markers markers))
(add-renderer (hover-label x y (make-hover-badge (reverse info))))))
(set-overlay-renderers snip renderers)))
(define (put-plot-snip)
(when plot-rt
(let ((rt (list (tick-grid) plot-rt)))
(when best-rt
(set! rt (cons best-rt rt)))
(let* ([mean-max-axis (get-series-axis)]
NOTE : we assume that CP - DATA corresponds to the series if
the series has a CP estimate . However , this creates
Critical Power and a Critical Velocity , see also AB#33
[cp-data (and mean-max-axis
(send mean-max-axis have-cp-estimate?)
(df-get-property data-frame 'critical-power))]
[aux-axis (get-aux-axis)]
[saved-location (get-snip-location pd-model-snip)])
(let-values (((min-x max-x min-y max-y)
(plot-bounds (get-series-axis) zero-base? mean-max-data bests-data cp-data)))
(if (> (length mean-max-aux-data) 0)
(let ((ivs (mk-invertible-function mean-max-aux-data mean-max-data zero-base?)))
(set! mean-max-aux-invfn ivs)
(parameterize ([plot-x-ticks (mean-max-ticks)]
[plot-x-label "Duration"]
[plot-x-transform log-transform]
[plot-x-tick-label-anchor 'top-right]
[plot-x-tick-label-angle 30]
[plot-y-ticks (send mean-max-axis plot-ticks)]
[plot-y-label (send mean-max-axis axis-label)]
[plot-y-far-ticks (ticks-scale (send aux-axis plot-ticks) ivs)]
[plot-y-far-label (send aux-axis axis-label)])
(define snip (plot-to-canvas rt plot-pb
#:x-min min-x #:x-max max-x
#:y-min min-y #:y-max max-y
))
(set-mouse-event-callback snip (make-plot-hover-callback))))
(parameterize ([plot-x-ticks (mean-max-ticks)]
[plot-x-label "Duration"]
[plot-x-transform log-transform]
[plot-x-tick-label-anchor 'top-right]
[plot-x-tick-label-angle 30]
[plot-y-ticks (send mean-max-axis plot-ticks)]
[plot-y-label (send mean-max-axis axis-label)])
(define snip (plot-to-canvas rt plot-pb
#:x-min min-x #:x-max max-x
#:y-min min-y #:y-max max-y))
(set-mouse-event-callback snip (make-plot-hover-callback))))
(when (and cp-data (send mean-max-axis have-cp-estimate?) mean-max-data)
here a second time .
(let* ((fn (mean-max->spline mean-max-data))
(pict (send mean-max-axis pd-data-as-pict cp-data fn)))
(set! pd-model-snip (new pict-snip% [pict pict]))
(send plot-pb set-floating-snip pd-model-snip 0 0)
(move-snip-to pd-model-snip (or saved-location saved-pd-model-snip-location)))))))))
(define (refresh-plot)
(set! saved-pd-model-snip-location
(or (get-snip-location pd-model-snip)
saved-pd-model-snip-location))
(set! plot-rt #f)
(set! pd-model-snip #f)
(send plot-pb set-background-message "Working...")
(send plot-pb clear-all)
(unless (> inhibit-refresh 0)
(let ((df data-frame)
(cache data-cache)
(axis (get-series-axis))
(aux-axis (get-aux-axis))
(zerob? zero-base?)
(renderer-tree '()))
(queue-task
"inspect-mean-max%/refresh-plot"
(lambda ()
(define data
(or (hash-ref cache axis #f)
(get-session-mmax df axis)))
(hash-set! cache axis data)
(define aux-data
(if aux-axis
(let ((series (send aux-axis series-name)))
(and (df-contains? df series)
(df-mean-max-aux df series data)))
'()))
(set! renderer-tree
(cons
(mean-max-renderer
data aux-data
#:color1 (send axis plot-color)
#:color2 (and aux-axis (send aux-axis plot-color))
#:zero-base? zerob?)
renderer-tree)))
(define pd-function
(let ((cp-data (df-get-property df 'critical-power)))
(and cp-data (send axis pd-function cp-data))))
(when pd-function
(set! renderer-tree
(cons (function pd-function #:color "red" #:width 1.5 #:style 'long-dash)
renderer-tree)))
(define plot-fn (mean-max->spline data))
(define aux-plot-fn (mean-max->spline (normalize-aux aux-data data zerob?)))
(queue-callback
(lambda ()
(cond ((not (null? renderer-tree))
(set! mean-max-data data)
(set! mean-max-aux-data aux-data)
(set! mean-max-plot-fn plot-fn)
(set! mean-max-aux-plot-fn aux-plot-fn)
(set! mean-max-pd-fn pd-function)
(set! plot-rt renderer-tree)
(set! cache data-cache)
(put-plot-snip))
(#t
(send plot-pb set-background-message "No data to plot"))))))))))
(define (refresh-bests-plot)
(define debug-tag "inspect-mean-max%/refresh-bests-plot")
(unless (> inhibit-refresh 0)
(set! best-rt-generation (add1 best-rt-generation))
(set! best-rt #f)
(let ((axis (get-series-axis))
(generation best-rt-generation)
(time-interval selected-period))
(queue-task
debug-tag
(lambda ()
(define candidates
(get-candidate-sessions
(current-database)
(df-get-property data-frame 'sport)
((second (list-ref period-choices time-interval)))))
(define inverted? (send axis inverted-mean-max?))
(define mmax (get-aggregate-mmax candidates axis #f))
(define fn (aggregate-mmax->spline-fn mmax))
(define brt
(and fn
(function-interval
(if inverted? (lambda (x) 10000) (lambda (x) -10000))
fn
#:color (send axis plot-color)
#:alpha 0.1
#:line2-color "black"
#:line2-width 0.5
#:line1-style 'transparent)))
(queue-callback
(lambda ()
(let ((current-generation (get-best-rt-generation)))
(when (= generation current-generation)
(set! best-rt brt)
(set! best-fn fn)
(set! bests-data mmax)
(put-plot-snip))))))))))
(define (save-params-for-sport)
(when (current-sport)
(save-params-for-series)
(let ((axis (get-series-axis)))
(hash-set! params-by-sport
(current-sport)
(list 'gen1 (send axis series-name) params-by-series)))))
(define (restore-params-for-sport)
(set! inhibit-refresh (add1 inhibit-refresh))
(let ((params (hash-ref params-by-sport (current-sport) #f)))
(if (and params (eq? (car params) 'gen1))
(match-let (((list tag series-name pbs) params))
(let ((selection 0))
(when series-name
(let ((index (find-axis series-name axis-choices)))
(set! selection (min (or index 0) (sub1 (length axis-choices))))))
(on-axis-changed selection #t)
(set! params-by-series (hash-copy pbs))))
(begin
(on-axis-changed 0 #t)
(set! params-by-series (make-hash))))
(send axis-choice-box set-selection selected-axis)
(restore-params-for-series)
(set! inhibit-refresh (sub1 inhibit-refresh))))
(define (save-params-for-series)
(when (current-sport)
(let ((axis (get-series-axis))
(aux-axis (get-aux-axis))
(period (list-ref period-choices selected-period)))
(hash-set!
params-by-series
(send axis series-name)
(hash
'aux-series-name (and aux-axis (send aux-axis series-name))
'period-name (first period)
'zero-base? zero-base?
'pd-model-snip-location (get-snip-location pd-model-snip))))))
(define (restore-params-for-series)
(set! inhibit-refresh (add1 inhibit-refresh))
(let* ((axis (get-series-axis))
(series-name (send axis series-name))
(params (hash-ref params-by-series series-name #f)))
(if (and params (hash? params))
(begin
(let ((aux-series-name (hash-ref params 'aux-series-name #f))
(selection 0))
(when aux-series-name
(let ((index (find-axis aux-series-name axis-choices)))
(set! selection (add1 (min (or index 0) (sub1 (length axis-choices)))))))
(on-aux-axis-changed selection))
(let ((period-name (hash-ref params 'period-name #f))
(selection 0))
(when period-name
(let ((index (find-period period-name period-choices)))
(set! selection (min (or index 0) (sub1 (length period-choices))))))
(on-period-changed selection))
(let ((zb? (hash-ref params 'zero-base? #f)))
(on-zero-base zb?))
(set! saved-pd-model-snip-location
(hash-ref params 'pd-model-snip-location #f)))
(begin
(on-aux-axis-changed 0)
(on-period-changed 0))))
(send aux-axis-choice-box set-selection selected-aux-axis)
(send period-choice-box set-selection selected-period)
(send zero-base-check-box set-value zero-base?)
(set! inhibit-refresh (sub1 inhibit-refresh)))
(define/public (save-visual-layout)
(when (> (length axis-choices) 0)
(save-params-for-sport)
(put-pref pref-tag (list params-by-sport))))
(define (get-default-export-file-name (extenstion "png"))
(let ((sid (df-get-property data-frame 'session-id))
(axis1 (get-series-axis))
(axis2 (get-aux-axis)))
(cond ((and sid axis1 axis2)
(format "mean-max-~a-~a-~a.~a" sid
(send axis1 series-name)
(send axis2 series-name)
extenstion))
((and sid axis1)
(format "mean-max-~a-~a.~a" sid
(send axis1 series-name)
extenstion))
(#t
(format "mean-max.~a" extenstion)))))
(define/public (on-interactive-export-image)
(let ((file (put-file "Select file to export to" #f #f
(or img-export-file-name (get-default-export-file-name "png"))
"png" '()
'(("PNG Files" "*.png") ("Any" "*.*")))))
(when file
(set! img-export-file-name file)
(send plot-pb export-image-to-file file))))
(define/public (on-interactive-export-data formatted?)
(let ((file (put-file "Select file to export to" #f #f
(or data-export-file-name (get-default-export-file-name "csv"))
"csv" '()
'(("CSV Files" "*.csv") ("Any" "*.*")))))
(when file
(set! data-export-file-name file)
(call-with-output-file file
(lambda (out) (export-data-as-csv out formatted?))
#:mode 'text #:exists 'truncate))))
(define (export-data-as-csv out formatted?)
(define have-aux? (and mean-max-aux-data (= (length mean-max-aux-data) (length mean-max-data))))
(define have-bests? (and bests-data (<= (length mean-max-data) (length bests-data))))
(write-string "Timestamp, Duration, Value" out)
(when have-aux? (write-string ", Aux Value" out))
(when have-bests? (write-string ", Best SID, Best Timestamp, Best Value" out))
(newline out)
(for ((index (in-range (length mean-max-data))))
(match-define (vector d m s)
(list-ref mean-max-data index))
(if m
(write-string (format "~a, ~a, ~a"
(exact->inexact s)
(exact->inexact d)
(exact->inexact m))
out)
(write-string (format ", , ") out))
(when have-aux?
(match-define (vector d m s)
(list-ref mean-max-aux-data index))
(if m
(write-string (format ", ~a" (exact->inexact m)) out)
(write-string ", " out)))
(when have-bests?
(match-define (list sid ts d m)
(list-ref bests-data index))
(format "bests: ~a ~a ~a ~a~%" sid ts d m)
(if m
(write-string (format ", ~a, ~a, ~a" sid (exact->inexact ts) (exact->inexact m)) out)
(write-string (format ", , ,") out)))
(newline out)))
(define/public (set-session s df)
(set! inhibit-refresh (add1 inhibit-refresh))
(save-params-for-sport)
(set! data-frame df)
(set! data-cache (make-hash))
(set! img-export-file-name #f)
(set! data-export-file-name #f)
(set! plot-rt #f)
(set! best-rt #f)
(install-axis-choices)
(if (> (length axis-choices) 0)
(begin
(install-period-choices)
(restore-params-for-sport)
(set! inhibit-refresh (sub1 inhibit-refresh))
(refresh-bests-plot)
(refresh-plot))
(set! inhibit-refresh (sub1 inhibit-refresh))))
))
|
4aff82047b7b251b5517b83a1443aaaf5694abdf2bf3cb90b8e650bc41fa35f1 | jeapostrophe/raart | hack.rkt | #lang racket/base
(require racket/match
racket/format
racket/list
lux
raart
struct-define)
(define rows 24)
(define cols 80)
(define world-rows (- rows 3))
(define world-cols cols)
(struct obj (ox oy oc))
(define-struct-define obj-define obj)
(define-struct-define hack-define hack)
(define (step w dx dy)
(hack-define w)
(check
(hack (add1 steps)
(modulo (+ dx px) world-cols)
(modulo (+ dy py) world-rows)
score
objs)))
(define (check w)
(hack-define w)
(cond
[(empty? objs)
#f]
[else
(for/fold ([score score]
[objs '()]
#:result (hack steps px py score objs))
([o (in-list objs)])
(obj-define o)
(if (and (= ox px) (= oy py))
(values (add1 score) objs)
(values score (cons o objs))))]))
(struct hack (steps px py score objs)
#:methods gen:word
[(define (word-fps w) 0.0)
(define (word-label w ft) "Hack")
(define (word-event w e)
(hack-define w)
(match e
[(screen-size-report _ _) w]
["<left>" (step w -1 0)]
["<right>" (step w +1 0)]
["<up>" (step w 0 -1)]
["<down>" (step w 0 +1)]
["q" #f]))
(define (word-output w)
(hack-define w)
(without-cursor
(crop 0 cols 0 rows
(vappend
#:halign 'left
(text (~a "Hello Jack! Enjoy the hacking! Press q to quit."))
(place-at*
(for/fold ([c (blank world-cols world-rows)])
([o (in-list objs)])
(obj-define o)
(place-at c oy ox (fg 'blue (char oc))))
[py px (fg 'red (char #\@))])
(text (~a "Jack the Paren Hunter"))
(happend (text (~a "Steps: " steps " Score: " score)))))))
(define (word-return w)
(hack-define w)
(~a "You got " score " parens in " steps " steps!"))])
(define (initial-hack-state)
(hack 0 0 0 0
(for/list ([i (in-range 8)])
(obj (random world-cols) (random world-rows)
(if (zero? (random 2)) #\( #\))))))
(module+ main
(call-with-chaos
(make-raart)
(λ () (fiat-lux (initial-hack-state)))))
| null | https://raw.githubusercontent.com/jeapostrophe/raart/9d82f2f8ad0052c2f4a6a75a00d957b9806f33df/t/hack.rkt | racket | #lang racket/base
(require racket/match
racket/format
racket/list
lux
raart
struct-define)
(define rows 24)
(define cols 80)
(define world-rows (- rows 3))
(define world-cols cols)
(struct obj (ox oy oc))
(define-struct-define obj-define obj)
(define-struct-define hack-define hack)
(define (step w dx dy)
(hack-define w)
(check
(hack (add1 steps)
(modulo (+ dx px) world-cols)
(modulo (+ dy py) world-rows)
score
objs)))
(define (check w)
(hack-define w)
(cond
[(empty? objs)
#f]
[else
(for/fold ([score score]
[objs '()]
#:result (hack steps px py score objs))
([o (in-list objs)])
(obj-define o)
(if (and (= ox px) (= oy py))
(values (add1 score) objs)
(values score (cons o objs))))]))
(struct hack (steps px py score objs)
#:methods gen:word
[(define (word-fps w) 0.0)
(define (word-label w ft) "Hack")
(define (word-event w e)
(hack-define w)
(match e
[(screen-size-report _ _) w]
["<left>" (step w -1 0)]
["<right>" (step w +1 0)]
["<up>" (step w 0 -1)]
["<down>" (step w 0 +1)]
["q" #f]))
(define (word-output w)
(hack-define w)
(without-cursor
(crop 0 cols 0 rows
(vappend
#:halign 'left
(text (~a "Hello Jack! Enjoy the hacking! Press q to quit."))
(place-at*
(for/fold ([c (blank world-cols world-rows)])
([o (in-list objs)])
(obj-define o)
(place-at c oy ox (fg 'blue (char oc))))
[py px (fg 'red (char #\@))])
(text (~a "Jack the Paren Hunter"))
(happend (text (~a "Steps: " steps " Score: " score)))))))
(define (word-return w)
(hack-define w)
(~a "You got " score " parens in " steps " steps!"))])
(define (initial-hack-state)
(hack 0 0 0 0
(for/list ([i (in-range 8)])
(obj (random world-cols) (random world-rows)
(if (zero? (random 2)) #\( #\))))))
(module+ main
(call-with-chaos
(make-raart)
(λ () (fiat-lux (initial-hack-state)))))
| |
3bc537d22f7160ec49fe55fda130b203dd7aeb30c5f9e671ea083aa22b5303bb | LaurentMazare/ocaml-bert | gpt2_vocab.ml | vocab file : -vocab.json
merge file : -merges.txt
merge file: -merges.txt
*)
open! Base
module String_pair = struct
module T = struct
type t = string * string [@@deriving sexp]
let compare (s1, s1') (s2, s2') =
let cmp = String.compare s1 s2 in
if cmp <> 0 then cmp else String.compare s1' s2'
end
include T
include Comparator.Make (T)
end
type t =
{ tokens : string array
; token_indices : (string, int, String.comparator_witness) Map.t
; bpe_ranks : (String_pair.t, int, String_pair.comparator_witness) Map.t
; cache : (string, int list) Hashtbl.t
}
let create ~tokens ~bpe_ranks =
let token_indices =
List.mapi tokens ~f:(fun idx token -> String.strip token, idx)
|> Map.of_alist_exn (module String)
in
let bpe_ranks =
List.mapi bpe_ranks ~f:(fun idx pair -> pair, idx)
|> Map.of_alist_exn (module String_pair)
in
{ tokens = Array.of_list tokens
; token_indices
; bpe_ranks
; cache = Hashtbl.create (module String)
}
let load ~vocab_filename ~merge_filename =
let err ~kind =
Printf.failwithf
"error reading json file %s, expected string got %s"
vocab_filename
kind
()
in
let token_indices =
match Yojson.Basic.from_file vocab_filename with
| `Assoc assoc ->
List.map assoc ~f:(fun (name, id) -> name, Yojson.Basic.Util.to_int id)
|> Map.of_alist_exn (module String)
| `Bool _ -> err ~kind:"bool"
| `Float _ -> err ~kind:"float"
| `Int _ -> err ~kind:"int"
| `List _ -> err ~kind:"list"
| `Null -> err ~kind:"null"
| `String _ -> err ~kind:"string"
in
let len =
1 + Map.fold token_indices ~init:0 ~f:(fun ~key:_ ~data acc -> Int.max acc data)
in
let tokens = Array.create ~len "" in
Map.iteri token_indices ~f:(fun ~key ~data -> tokens.(data) <- key);
let bpe_ranks =
Stdio.In_channel.read_lines merge_filename
|> List.tl_exn
|> List.mapi ~f:(fun idx line ->
String.strip line
|> String.split ~on:' '
|> function
| [ str1; str2 ] -> (str1, str2), idx
| _ -> Printf.failwithf "multiple space characters in line %d: %s" idx line ())
|> Map.of_alist_exn (module String_pair)
in
{ tokens; token_indices; bpe_ranks; cache = Hashtbl.create (module String) }
let token_id t token = Map.find t.token_indices token
let token t id = t.tokens.(id)
let unicode_chars str =
let decoder = Uutf.decoder (`String str) in
let rec loop acc ~prev_start =
match Uutf.decode decoder with
| `Uchar _ ->
let next_start = Uutf.decoder_byte_count decoder in
let char = String.sub str ~pos:prev_start ~len:(next_start - prev_start) in
loop (char :: acc) ~prev_start:next_start
| `End | `Malformed _ -> List.rev acc
| `Await -> assert false
in
loop [] ~prev_start:0
let bytes_encoding str =
let buf = Buffer.create 128 in
String.iter str ~f:(fun chr ->
let c = Char.to_int chr in
if c <= 32
then Uutf.Buffer.add_utf_8 buf (Uchar.of_scalar_exn (c + 256))
else if 127 <= c && c <= 160
then Uutf.Buffer.add_utf_8 buf (Uchar.of_scalar_exn (c + 162))
else if c = 173
then Uutf.Buffer.add_utf_8 buf (Uchar.of_scalar_exn 323)
else Buffer.add_char buf chr);
Buffer.contents buf |> unicode_chars
let bpe_rank t pair = Map.find t.bpe_ranks pair
byte - level Byte - Pair - Encoding
let bpe_ t str =
let rec loop words =
let rec best_pair words min_rank =
match words with
| [] | [ _ ] -> min_rank
| head1 :: (head2 :: _ as words) ->
let pair = head1, head2 in
let min_rank =
match min_rank, bpe_rank t pair with
| None, None -> None
| None, Some value -> Some (value, pair)
| Some (min_value, _), Some value when value < min_value -> Some (value, pair)
| (Some _ as some), (None | Some _) -> some
in
best_pair words min_rank
in
match best_pair words None with
| None -> words
| Some (_min_value, (word1, word2)) ->
let word12 = word1 ^ word2 in
let rec group words acc =
match words with
| [] -> List.rev acc
| [ last ] -> List.rev (last :: acc)
| head1 :: head2 :: tail when String.(head1 = word1 && head2 = word2) ->
group tail (word12 :: acc)
| head :: tail -> group tail (head :: acc)
in
group words [] |> loop
in
loop (bytes_encoding str)
let bpe t str =
Hashtbl.find_or_add t.cache str ~default:(fun () ->
bpe_ t str |> List.filter_map ~f:(token_id t))
let%expect_test "bpe" =
let t = create ~tokens:[] ~bpe_ranks:[ "foo", "bar"; "fo", "o"; "f", "o" ] in
List.iter
~f:(fun str ->
bpe_ t str
|> List.map ~f:(Printf.sprintf "\"%s\"")
|> String.concat ~sep:","
|> Stdio.printf "\"%s\": %s\n%!" str)
[ "bafoor"; "foobar"; "fobar"; "foo"; "fo"; "o"; " foo bar"; "fo ofoo " ];
[%expect
{|
"bafoor": "b","a","foo","r"
"foobar": "foo","b","a","r"
"fobar": "fo","b","a","r"
"foo": "foo"
"fo": "fo"
"o": "o"
" foo bar": "Ġ","foo","Ġ","b","a","r"
"fo ofoo ": "fo","Ġ","o","foo","Ġ" |}]
| null | https://raw.githubusercontent.com/LaurentMazare/ocaml-bert/23d6697833cc54173d075f904a1018db0265261d/src/tokenize/gpt2_vocab.ml | ocaml | vocab file : -vocab.json
merge file : -merges.txt
merge file: -merges.txt
*)
open! Base
module String_pair = struct
module T = struct
type t = string * string [@@deriving sexp]
let compare (s1, s1') (s2, s2') =
let cmp = String.compare s1 s2 in
if cmp <> 0 then cmp else String.compare s1' s2'
end
include T
include Comparator.Make (T)
end
type t =
{ tokens : string array
; token_indices : (string, int, String.comparator_witness) Map.t
; bpe_ranks : (String_pair.t, int, String_pair.comparator_witness) Map.t
; cache : (string, int list) Hashtbl.t
}
let create ~tokens ~bpe_ranks =
let token_indices =
List.mapi tokens ~f:(fun idx token -> String.strip token, idx)
|> Map.of_alist_exn (module String)
in
let bpe_ranks =
List.mapi bpe_ranks ~f:(fun idx pair -> pair, idx)
|> Map.of_alist_exn (module String_pair)
in
{ tokens = Array.of_list tokens
; token_indices
; bpe_ranks
; cache = Hashtbl.create (module String)
}
let load ~vocab_filename ~merge_filename =
let err ~kind =
Printf.failwithf
"error reading json file %s, expected string got %s"
vocab_filename
kind
()
in
let token_indices =
match Yojson.Basic.from_file vocab_filename with
| `Assoc assoc ->
List.map assoc ~f:(fun (name, id) -> name, Yojson.Basic.Util.to_int id)
|> Map.of_alist_exn (module String)
| `Bool _ -> err ~kind:"bool"
| `Float _ -> err ~kind:"float"
| `Int _ -> err ~kind:"int"
| `List _ -> err ~kind:"list"
| `Null -> err ~kind:"null"
| `String _ -> err ~kind:"string"
in
let len =
1 + Map.fold token_indices ~init:0 ~f:(fun ~key:_ ~data acc -> Int.max acc data)
in
let tokens = Array.create ~len "" in
Map.iteri token_indices ~f:(fun ~key ~data -> tokens.(data) <- key);
let bpe_ranks =
Stdio.In_channel.read_lines merge_filename
|> List.tl_exn
|> List.mapi ~f:(fun idx line ->
String.strip line
|> String.split ~on:' '
|> function
| [ str1; str2 ] -> (str1, str2), idx
| _ -> Printf.failwithf "multiple space characters in line %d: %s" idx line ())
|> Map.of_alist_exn (module String_pair)
in
{ tokens; token_indices; bpe_ranks; cache = Hashtbl.create (module String) }
let token_id t token = Map.find t.token_indices token
let token t id = t.tokens.(id)
let unicode_chars str =
let decoder = Uutf.decoder (`String str) in
let rec loop acc ~prev_start =
match Uutf.decode decoder with
| `Uchar _ ->
let next_start = Uutf.decoder_byte_count decoder in
let char = String.sub str ~pos:prev_start ~len:(next_start - prev_start) in
loop (char :: acc) ~prev_start:next_start
| `End | `Malformed _ -> List.rev acc
| `Await -> assert false
in
loop [] ~prev_start:0
let bytes_encoding str =
let buf = Buffer.create 128 in
String.iter str ~f:(fun chr ->
let c = Char.to_int chr in
if c <= 32
then Uutf.Buffer.add_utf_8 buf (Uchar.of_scalar_exn (c + 256))
else if 127 <= c && c <= 160
then Uutf.Buffer.add_utf_8 buf (Uchar.of_scalar_exn (c + 162))
else if c = 173
then Uutf.Buffer.add_utf_8 buf (Uchar.of_scalar_exn 323)
else Buffer.add_char buf chr);
Buffer.contents buf |> unicode_chars
let bpe_rank t pair = Map.find t.bpe_ranks pair
byte - level Byte - Pair - Encoding
let bpe_ t str =
let rec loop words =
let rec best_pair words min_rank =
match words with
| [] | [ _ ] -> min_rank
| head1 :: (head2 :: _ as words) ->
let pair = head1, head2 in
let min_rank =
match min_rank, bpe_rank t pair with
| None, None -> None
| None, Some value -> Some (value, pair)
| Some (min_value, _), Some value when value < min_value -> Some (value, pair)
| (Some _ as some), (None | Some _) -> some
in
best_pair words min_rank
in
match best_pair words None with
| None -> words
| Some (_min_value, (word1, word2)) ->
let word12 = word1 ^ word2 in
let rec group words acc =
match words with
| [] -> List.rev acc
| [ last ] -> List.rev (last :: acc)
| head1 :: head2 :: tail when String.(head1 = word1 && head2 = word2) ->
group tail (word12 :: acc)
| head :: tail -> group tail (head :: acc)
in
group words [] |> loop
in
loop (bytes_encoding str)
let bpe t str =
Hashtbl.find_or_add t.cache str ~default:(fun () ->
bpe_ t str |> List.filter_map ~f:(token_id t))
let%expect_test "bpe" =
let t = create ~tokens:[] ~bpe_ranks:[ "foo", "bar"; "fo", "o"; "f", "o" ] in
List.iter
~f:(fun str ->
bpe_ t str
|> List.map ~f:(Printf.sprintf "\"%s\"")
|> String.concat ~sep:","
|> Stdio.printf "\"%s\": %s\n%!" str)
[ "bafoor"; "foobar"; "fobar"; "foo"; "fo"; "o"; " foo bar"; "fo ofoo " ];
[%expect
{|
"bafoor": "b","a","foo","r"
"foobar": "foo","b","a","r"
"fobar": "fo","b","a","r"
"foo": "foo"
"fo": "fo"
"o": "o"
" foo bar": "Ġ","foo","Ġ","b","a","r"
"fo ofoo ": "fo","Ġ","o","foo","Ġ" |}]
| |
9054867f7c651eef2b56001732e275cdcebc269d75633fd61beba7d2cdd1e299 | Bogdanp/racket-kafka | producer.rkt | #lang racket/base
(require kafka
kafka/producer
racket/format)
(define c (make-client))
(define p (make-producer c))
(define t "example-topic")
(create-topics
c
(make-CreateTopic
#:name t
#:partitions 2))
(define evts
(for/list ([i (in-range 128)])
(define pid (modulo i 2))
(define k #"a")
(define v (string->bytes/utf-8 (~a i)))
(produce
#:partition pid
#:headers (hash "Content-Type" #"text/plain")
p t k v)))
(producer-flush p)
(for ([evt (in-list evts)])
(println (sync evt)))
(disconnect-all c)
| null | https://raw.githubusercontent.com/Bogdanp/racket-kafka/81f10078fa3c31b0dfd493a2142408c2c8dd1b59/example/producer.rkt | racket | #lang racket/base
(require kafka
kafka/producer
racket/format)
(define c (make-client))
(define p (make-producer c))
(define t "example-topic")
(create-topics
c
(make-CreateTopic
#:name t
#:partitions 2))
(define evts
(for/list ([i (in-range 128)])
(define pid (modulo i 2))
(define k #"a")
(define v (string->bytes/utf-8 (~a i)))
(produce
#:partition pid
#:headers (hash "Content-Type" #"text/plain")
p t k v)))
(producer-flush p)
(for ([evt (in-list evts)])
(println (sync evt)))
(disconnect-all c)
| |
f77324eda8a118f942ee2a0754952dfc192132a63b6c1ad9417b73fd0b74ffa8 | vbmithr/ocaml-actor | test.ml | open Core
open Async
open Alcotest_async
module Event = struct
type t = unit
let dummy = ()
let level () = Logs.Info
let pp ppf () = Format.pp_print_bool ppf true
let http_port = None
end
module Request = struct
type 'a t = unit
type view = unit
let view () = ()
let level _ = Logs.Debug
let pp ppf () = Format.pp_print_bool ppf true
end
module Types = struct
type state = unit
type parameters = unit
type view = unit
let view () () = ()
let pp ppf () = Format.pp_print_bool ppf true
end
module W = Actor.Make(Event)(Request)(Types)
module Default_handlers = struct
type self = W.infinite W.queue W.t
let on_launch_complete _self =
Deferred.unit
let on_launch _self _name _params =
Deferred.unit
let on_request _ _ =
Deferred.never ()
let on_no_request _ =
Deferred.unit
let on_close _ =
Deferred.unit
let on_error _self _view _status _errors =
Deferred.unit
let on_completion _ () _ _ =
Deferred.unit
end
let src = Logs.Src.create "ocaml-actor.test"
let base_name = ["test"]
let worker_init () =
let table = W.create_table Queue in
let limits = Actor.Types.create_limits () in
W.launch table limits ~base_name ~name:"worker_init" () (module Default_handlers) >>= fun w ->
W.shutdown w
let worker_no_request () =
let iv = Ivar.create () in
let module Handlers = struct
include Default_handlers
let on_no_request _self =
Logs_async.debug
~src (fun m -> m "Entering 'on_no_request'") >>= fun () ->
Ivar.fill iv () ;
Deferred.unit
end in
let table = W.create_table Queue in
let limits = Actor.Types.create_limits () in
W.launch ~timeout:(Time_ns.Span.of_int_ms 500)
table limits ~base_name ~name:"worker_no_request" () (module Handlers) >>= fun w ->
Ivar.read iv >>= fun () ->
W.shutdown w
let basic =
"basic", [
test_case "init" `Quick worker_init ;
test_case "no_request" `Quick worker_no_request ;
]
let main () =
run "actor" [
basic
]
let () =
don't_wait_for (main ()) ;
never_returns (Scheduler.go ())
| null | https://raw.githubusercontent.com/vbmithr/ocaml-actor/d1c7dd1ad81a8e33efb1de07d5ce7db2edb91273/test/test.ml | ocaml | open Core
open Async
open Alcotest_async
module Event = struct
type t = unit
let dummy = ()
let level () = Logs.Info
let pp ppf () = Format.pp_print_bool ppf true
let http_port = None
end
module Request = struct
type 'a t = unit
type view = unit
let view () = ()
let level _ = Logs.Debug
let pp ppf () = Format.pp_print_bool ppf true
end
module Types = struct
type state = unit
type parameters = unit
type view = unit
let view () () = ()
let pp ppf () = Format.pp_print_bool ppf true
end
module W = Actor.Make(Event)(Request)(Types)
module Default_handlers = struct
type self = W.infinite W.queue W.t
let on_launch_complete _self =
Deferred.unit
let on_launch _self _name _params =
Deferred.unit
let on_request _ _ =
Deferred.never ()
let on_no_request _ =
Deferred.unit
let on_close _ =
Deferred.unit
let on_error _self _view _status _errors =
Deferred.unit
let on_completion _ () _ _ =
Deferred.unit
end
let src = Logs.Src.create "ocaml-actor.test"
let base_name = ["test"]
let worker_init () =
let table = W.create_table Queue in
let limits = Actor.Types.create_limits () in
W.launch table limits ~base_name ~name:"worker_init" () (module Default_handlers) >>= fun w ->
W.shutdown w
let worker_no_request () =
let iv = Ivar.create () in
let module Handlers = struct
include Default_handlers
let on_no_request _self =
Logs_async.debug
~src (fun m -> m "Entering 'on_no_request'") >>= fun () ->
Ivar.fill iv () ;
Deferred.unit
end in
let table = W.create_table Queue in
let limits = Actor.Types.create_limits () in
W.launch ~timeout:(Time_ns.Span.of_int_ms 500)
table limits ~base_name ~name:"worker_no_request" () (module Handlers) >>= fun w ->
Ivar.read iv >>= fun () ->
W.shutdown w
let basic =
"basic", [
test_case "init" `Quick worker_init ;
test_case "no_request" `Quick worker_no_request ;
]
let main () =
run "actor" [
basic
]
let () =
don't_wait_for (main ()) ;
never_returns (Scheduler.go ())
| |
603f07a7d9da9eb8441cbbb1b18a63bbb382952e37e16be69ef7a421b5016cc6 | haskell/fgl | Monad.hs | # LANGUAGE CPP , MultiParamTypeClasses #
( c ) 2002 by [ see file COPYRIGHT ]
-- | Monadic Graph Algorithms
module Data.Graph.Inductive.Query.Monad(
-- * Additional Graph Utilities
mapFst, mapSnd, (><), orP,
-- * Graph Transformer Monad
GT(..), apply, apply', applyWith, applyWith', runGT, condMGT', recMGT',
condMGT, recMGT,
-- * Graph Computations Based on Graph Monads
-- ** Monadic Graph Accessing Functions
getNode, getContext, getNodes', getNodes, sucGT, sucM,
* * Derived Graph Recursion Operators
graphRec, graphRec', graphUFold,
-- * Examples: Graph Algorithms as Instances of Recursion Operators
-- ** Instances of graphRec
graphNodesM0, graphNodesM, graphNodes, graphFilterM, graphFilter,
* Example : Monadic DFS Algorithm(s )
dfsGT, dfsM, dfsM', dffM, graphDff, graphDff',
) where
-- Why all this?
--
-- graph monad ensures single-threaded access
-- ==> we can safely use imperative updates in the graph implementation
--
import Control.Monad (ap, liftM, liftM2)
import Data.Tree
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative (..))
#endif
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Monad
-- some additional (graph) utilities
--
mapFst :: (a -> b) -> (a, c) -> (b, c)
mapFst f (x,y) = (f x,y)
mapSnd :: (a -> b) -> (c, a) -> (c, b)
mapSnd f (x,y) = (x,f y)
infixr 8 ><
(><) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
(f >< g) (x,y) = (f x,g y)
orP :: (a -> Bool) -> (b -> Bool) -> (a,b) -> Bool
orP p q (x,y) = p x || q y
----------------------------------------------------------------------
-- "wrapped" state transformer monad ==
-- monadic graph transformer monad
----------------------------------------------------------------------
newtype GT m g a = MGT (m g -> m (a,g))
apply :: GT m g a -> m g -> m (a,g)
apply (MGT f) = f
apply' :: (Monad m) => GT m g a -> g -> m (a,g)
apply' gt = apply gt . return
applyWith :: (Monad m) => (a -> b) -> GT m g a -> m g -> m (b,g)
applyWith h (MGT f) gm = do {(x,g) <- f gm; return (h x,g)}
applyWith' :: (Monad m) => (a -> b) -> GT m g a -> g -> m (b,g)
applyWith' h gt = applyWith h gt . return
runGT :: (Monad m) => GT m g a -> m g -> m a
runGT gt mg = do {(x,_) <- apply gt mg; return x}
instance (Monad m) => Functor (GT m g) where
fmap = liftM
instance (Monad m) => Applicative (GT m g) where
pure x = MGT (\mg->do {g<-mg; return (x,g)})
(<*>) = ap
instance (Monad m) => Monad (GT m g) where
return = pure
f >>= h = MGT (\mg->do {(x,g)<-apply f mg; apply' (h x) g})
condMGT' :: (Monad m) => (s -> Bool) -> GT m s a -> GT m s a -> GT m s a
condMGT' p f g = MGT (\mg->do {h<-mg; if p h then apply f mg else apply g mg})
recMGT' :: (Monad m) => (s -> Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b
recMGT' p mg f u = condMGT' p (return u)
(do {x<-mg;y<-recMGT' p mg f u;return (f x y)})
condMGT :: (Monad m) => (m s -> m Bool) -> GT m s a -> GT m s a -> GT m s a
condMGT p f g = MGT (\mg->do {b<-p mg; if b then apply f mg else apply g mg})
recMGT :: (Monad m) => (m s -> m Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b
recMGT p mg f u = condMGT p (return u)
(do {x<-mg;y<-recMGT p mg f u;return (f x y)})
----------------------------------------------------------------------
-- graph computations based on state monads/graph monads
----------------------------------------------------------------------
-- some monadic graph accessing functions
--
getNode :: (GraphM m gr) => GT m (gr a b) Node
getNode = MGT (\mg->do {((_,v,_,_),g) <- matchAnyM mg; return (v,g)})
getContext :: (GraphM m gr) => GT m (gr a b) (Context a b)
getContext = MGT matchAnyM
-- some functions defined by using the do-notation explicitly
-- Note: most of these can be expressed as an instance of graphRec
--
getNodes' :: (Graph gr,GraphM m gr) => GT m (gr a b) [Node]
getNodes' = condMGT' isEmpty (return []) nodeGetter
getNodes :: (GraphM m gr) => GT m (gr a b) [Node]
getNodes = condMGT isEmptyM (return []) nodeGetter
nodeGetter :: (GraphM m gr) => GT m (gr a b) [Node]
nodeGetter = liftM2 (:) getNode getNodes
sucGT :: (GraphM m gr) => Node -> GT m (gr a b) (Maybe [Node])
sucGT v = MGT (\mg->do (c,g) <- matchM v mg
case c of
Just (_,_,_,s) -> return (Just (map snd s),g)
Nothing -> return (Nothing,g)
)
sucM :: (GraphM m gr) => Node -> m (gr a b) -> m (Maybe [Node])
sucM v = runGT (sucGT v)
----------------------------------------------------------------------
-- some derived graph recursion operators
----------------------------------------------------------------------
--
-- graphRec :: GraphMonad a b c -> (c -> d -> d) -> d -> GraphMonad a b d
-- graphRec f g u = cond isEmpty (return u)
-- (do x <- f
-- y <- graphRec f g u
-- return (g x y))
-- | encapsulates a simple recursion schema on graphs
graphRec :: (GraphM m gr) => GT m (gr a b) c ->
(c -> d -> d) -> d -> GT m (gr a b) d
graphRec = recMGT isEmptyM
graphRec' :: (Graph gr,GraphM m gr) => GT m (gr a b) c ->
(c -> d -> d) -> d -> GT m (gr a b) d
graphRec' = recMGT' isEmpty
graphUFold :: (GraphM m gr) => (Context a b -> c -> c) -> c -> GT m (gr a b) c
graphUFold = graphRec getContext
----------------------------------------------------------------------
-- Examples: graph algorithms as instances of recursion operators
----------------------------------------------------------------------
-- instances of graphRec
--
graphNodesM0 :: (GraphM m gr) => GT m (gr a b) [Node]
graphNodesM0 = graphRec getNode (:) []
graphNodesM :: (GraphM m gr) => GT m (gr a b) [Node]
graphNodesM = graphUFold (\(_,v,_,_)->(v:)) []
graphNodes :: (GraphM m gr) => m (gr a b) -> m [Node]
graphNodes = runGT graphNodesM
graphFilterM :: (GraphM m gr) => (Context a b -> Bool) ->
GT m (gr a b) [Context a b]
graphFilterM p = graphUFold (\c cs->if p c then c:cs else cs) []
graphFilter :: (GraphM m gr) => (Context a b -> Bool) -> m (gr a b) -> m [Context a b]
graphFilter p = runGT (graphFilterM p)
----------------------------------------------------------------------
-- Example: monadic dfs algorithm(s)
----------------------------------------------------------------------
| Monadic graph algorithms are defined in two steps :
--
( 1 ) define the ( possibly parameterized ) graph transformer ( e.g. , dfsGT )
( 2 ) run the graph transformer ( applied to arguments ) ( e.g. , dfsM )
--
dfsGT :: (GraphM m gr) => [Node] -> GT m (gr a b) [Node]
dfsGT [] = return []
dfsGT (v:vs) = MGT (\mg->
do (mc,g') <- matchM v mg
case mc of
Just (_,_,_,s) -> applyWith' (v:) (dfsGT (map snd s++vs)) g'
Nothing -> apply' (dfsGT vs) g' )
| depth - first search yielding number of nodes
dfsM :: (GraphM m gr) => [Node] -> m (gr a b) -> m [Node]
dfsM vs = runGT (dfsGT vs)
dfsM' :: (GraphM m gr) => m (gr a b) -> m [Node]
dfsM' mg = do {vs <- nodesM mg; runGT (dfsGT vs) mg}
| depth - first search yielding dfs forest
dffM :: (GraphM m gr) => [Node] -> GT m (gr a b) [Tree Node]
dffM vs = MGT (\mg->
do g<-mg
b<-isEmptyM mg
if b||null vs then return ([],g) else
let (v:vs') = vs in
do (mc,g1) <- matchM v mg
case mc of
Nothing -> apply (dffM vs') (return g1)
Just c -> do (ts, g2) <- apply (dffM (suc' c)) (return g1)
(ts',g3) <- apply (dffM vs') (return g2)
return (Node (node' c) ts:ts',g3)
)
graphDff :: (GraphM m gr) => [Node] -> m (gr a b) -> m [Tree Node]
graphDff vs = runGT (dffM vs)
graphDff' :: (GraphM m gr) => m (gr a b) -> m [Tree Node]
graphDff' mg = do {vs <- nodesM mg; runGT (dffM vs) mg}
| null | https://raw.githubusercontent.com/haskell/fgl/a2c7fb6bd4b5658c885f0927dad7d61dd7a94f80/Data/Graph/Inductive/Query/Monad.hs | haskell | | Monadic Graph Algorithms
* Additional Graph Utilities
* Graph Transformer Monad
* Graph Computations Based on Graph Monads
** Monadic Graph Accessing Functions
* Examples: Graph Algorithms as Instances of Recursion Operators
** Instances of graphRec
Why all this?
graph monad ensures single-threaded access
==> we can safely use imperative updates in the graph implementation
some additional (graph) utilities
--------------------------------------------------------------------
"wrapped" state transformer monad ==
monadic graph transformer monad
--------------------------------------------------------------------
--------------------------------------------------------------------
graph computations based on state monads/graph monads
--------------------------------------------------------------------
some monadic graph accessing functions
some functions defined by using the do-notation explicitly
Note: most of these can be expressed as an instance of graphRec
--------------------------------------------------------------------
some derived graph recursion operators
--------------------------------------------------------------------
graphRec :: GraphMonad a b c -> (c -> d -> d) -> d -> GraphMonad a b d
graphRec f g u = cond isEmpty (return u)
(do x <- f
y <- graphRec f g u
return (g x y))
| encapsulates a simple recursion schema on graphs
--------------------------------------------------------------------
Examples: graph algorithms as instances of recursion operators
--------------------------------------------------------------------
instances of graphRec
--------------------------------------------------------------------
Example: monadic dfs algorithm(s)
--------------------------------------------------------------------
| # LANGUAGE CPP , MultiParamTypeClasses #
( c ) 2002 by [ see file COPYRIGHT ]
module Data.Graph.Inductive.Query.Monad(
mapFst, mapSnd, (><), orP,
GT(..), apply, apply', applyWith, applyWith', runGT, condMGT', recMGT',
condMGT, recMGT,
getNode, getContext, getNodes', getNodes, sucGT, sucM,
* * Derived Graph Recursion Operators
graphRec, graphRec', graphUFold,
graphNodesM0, graphNodesM, graphNodes, graphFilterM, graphFilter,
* Example : Monadic DFS Algorithm(s )
dfsGT, dfsM, dfsM', dffM, graphDff, graphDff',
) where
import Control.Monad (ap, liftM, liftM2)
import Data.Tree
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative (Applicative (..))
#endif
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Monad
mapFst :: (a -> b) -> (a, c) -> (b, c)
mapFst f (x,y) = (f x,y)
mapSnd :: (a -> b) -> (c, a) -> (c, b)
mapSnd f (x,y) = (x,f y)
infixr 8 ><
(><) :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
(f >< g) (x,y) = (f x,g y)
orP :: (a -> Bool) -> (b -> Bool) -> (a,b) -> Bool
orP p q (x,y) = p x || q y
newtype GT m g a = MGT (m g -> m (a,g))
apply :: GT m g a -> m g -> m (a,g)
apply (MGT f) = f
apply' :: (Monad m) => GT m g a -> g -> m (a,g)
apply' gt = apply gt . return
applyWith :: (Monad m) => (a -> b) -> GT m g a -> m g -> m (b,g)
applyWith h (MGT f) gm = do {(x,g) <- f gm; return (h x,g)}
applyWith' :: (Monad m) => (a -> b) -> GT m g a -> g -> m (b,g)
applyWith' h gt = applyWith h gt . return
runGT :: (Monad m) => GT m g a -> m g -> m a
runGT gt mg = do {(x,_) <- apply gt mg; return x}
instance (Monad m) => Functor (GT m g) where
fmap = liftM
instance (Monad m) => Applicative (GT m g) where
pure x = MGT (\mg->do {g<-mg; return (x,g)})
(<*>) = ap
instance (Monad m) => Monad (GT m g) where
return = pure
f >>= h = MGT (\mg->do {(x,g)<-apply f mg; apply' (h x) g})
condMGT' :: (Monad m) => (s -> Bool) -> GT m s a -> GT m s a -> GT m s a
condMGT' p f g = MGT (\mg->do {h<-mg; if p h then apply f mg else apply g mg})
recMGT' :: (Monad m) => (s -> Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b
recMGT' p mg f u = condMGT' p (return u)
(do {x<-mg;y<-recMGT' p mg f u;return (f x y)})
condMGT :: (Monad m) => (m s -> m Bool) -> GT m s a -> GT m s a -> GT m s a
condMGT p f g = MGT (\mg->do {b<-p mg; if b then apply f mg else apply g mg})
recMGT :: (Monad m) => (m s -> m Bool) -> GT m s a -> (a -> b -> b) -> b -> GT m s b
recMGT p mg f u = condMGT p (return u)
(do {x<-mg;y<-recMGT p mg f u;return (f x y)})
getNode :: (GraphM m gr) => GT m (gr a b) Node
getNode = MGT (\mg->do {((_,v,_,_),g) <- matchAnyM mg; return (v,g)})
getContext :: (GraphM m gr) => GT m (gr a b) (Context a b)
getContext = MGT matchAnyM
getNodes' :: (Graph gr,GraphM m gr) => GT m (gr a b) [Node]
getNodes' = condMGT' isEmpty (return []) nodeGetter
getNodes :: (GraphM m gr) => GT m (gr a b) [Node]
getNodes = condMGT isEmptyM (return []) nodeGetter
nodeGetter :: (GraphM m gr) => GT m (gr a b) [Node]
nodeGetter = liftM2 (:) getNode getNodes
sucGT :: (GraphM m gr) => Node -> GT m (gr a b) (Maybe [Node])
sucGT v = MGT (\mg->do (c,g) <- matchM v mg
case c of
Just (_,_,_,s) -> return (Just (map snd s),g)
Nothing -> return (Nothing,g)
)
sucM :: (GraphM m gr) => Node -> m (gr a b) -> m (Maybe [Node])
sucM v = runGT (sucGT v)
graphRec :: (GraphM m gr) => GT m (gr a b) c ->
(c -> d -> d) -> d -> GT m (gr a b) d
graphRec = recMGT isEmptyM
graphRec' :: (Graph gr,GraphM m gr) => GT m (gr a b) c ->
(c -> d -> d) -> d -> GT m (gr a b) d
graphRec' = recMGT' isEmpty
graphUFold :: (GraphM m gr) => (Context a b -> c -> c) -> c -> GT m (gr a b) c
graphUFold = graphRec getContext
graphNodesM0 :: (GraphM m gr) => GT m (gr a b) [Node]
graphNodesM0 = graphRec getNode (:) []
graphNodesM :: (GraphM m gr) => GT m (gr a b) [Node]
graphNodesM = graphUFold (\(_,v,_,_)->(v:)) []
graphNodes :: (GraphM m gr) => m (gr a b) -> m [Node]
graphNodes = runGT graphNodesM
graphFilterM :: (GraphM m gr) => (Context a b -> Bool) ->
GT m (gr a b) [Context a b]
graphFilterM p = graphUFold (\c cs->if p c then c:cs else cs) []
graphFilter :: (GraphM m gr) => (Context a b -> Bool) -> m (gr a b) -> m [Context a b]
graphFilter p = runGT (graphFilterM p)
| Monadic graph algorithms are defined in two steps :
( 1 ) define the ( possibly parameterized ) graph transformer ( e.g. , dfsGT )
( 2 ) run the graph transformer ( applied to arguments ) ( e.g. , dfsM )
dfsGT :: (GraphM m gr) => [Node] -> GT m (gr a b) [Node]
dfsGT [] = return []
dfsGT (v:vs) = MGT (\mg->
do (mc,g') <- matchM v mg
case mc of
Just (_,_,_,s) -> applyWith' (v:) (dfsGT (map snd s++vs)) g'
Nothing -> apply' (dfsGT vs) g' )
| depth - first search yielding number of nodes
dfsM :: (GraphM m gr) => [Node] -> m (gr a b) -> m [Node]
dfsM vs = runGT (dfsGT vs)
dfsM' :: (GraphM m gr) => m (gr a b) -> m [Node]
dfsM' mg = do {vs <- nodesM mg; runGT (dfsGT vs) mg}
| depth - first search yielding dfs forest
dffM :: (GraphM m gr) => [Node] -> GT m (gr a b) [Tree Node]
dffM vs = MGT (\mg->
do g<-mg
b<-isEmptyM mg
if b||null vs then return ([],g) else
let (v:vs') = vs in
do (mc,g1) <- matchM v mg
case mc of
Nothing -> apply (dffM vs') (return g1)
Just c -> do (ts, g2) <- apply (dffM (suc' c)) (return g1)
(ts',g3) <- apply (dffM vs') (return g2)
return (Node (node' c) ts:ts',g3)
)
graphDff :: (GraphM m gr) => [Node] -> m (gr a b) -> m [Tree Node]
graphDff vs = runGT (dffM vs)
graphDff' :: (GraphM m gr) => m (gr a b) -> m [Tree Node]
graphDff' mg = do {vs <- nodesM mg; runGT (dffM vs) mg}
|
5d991448390c82d81873ac85db41f6c5dbc76d7ddc9b3b6deaa2735a859e884c | ygmpkk/house | DebugLex.hs | module Main where
import System (getArgs)
import IO
import Text.XML.HaXml.Lex (xmlLex)
import Text.XML.HaXml.Wrappers (fix2Args)
Debug the HaXml library by showing what the lexer generates .
main =
fix2Args >>= \(inf,outf)->
( if inf=="-" then getContents
else readFile inf ) >>= \content->
( if outf=="-" then return stdout
else openFile outf WriteMode ) >>= \o->
mapM_ ( hPutStrLn o . show ) (xmlLex inf content)
| null | https://raw.githubusercontent.com/ygmpkk/house/1ed0eed82139869e85e3c5532f2b579cf2566fa2/ghc-6.2/libraries/HaXml/examples/DebugLex.hs | haskell | module Main where
import System (getArgs)
import IO
import Text.XML.HaXml.Lex (xmlLex)
import Text.XML.HaXml.Wrappers (fix2Args)
Debug the HaXml library by showing what the lexer generates .
main =
fix2Args >>= \(inf,outf)->
( if inf=="-" then getContents
else readFile inf ) >>= \content->
( if outf=="-" then return stdout
else openFile outf WriteMode ) >>= \o->
mapM_ ( hPutStrLn o . show ) (xmlLex inf content)
| |
0d4187b62fd6915a75acc94f5d7fb58de00f461e2e8bc512ffe8236db8a471a7 | shortishly/pgec | pgec.erl | Copyright ( c ) 2022 < >
%%
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(pgec).
-export([get_env/1]).
-export([priv_consult/1]).
-export([priv_dir/0]).
-export([start/0]).
-export([version/0]).
version() ->
{ok, Version} = application:get_key(resp, vsn),
Version.
start() ->
application:ensure_all_started(?MODULE).
priv_dir() ->
code:priv_dir(?MODULE).
priv_consult(Filename) ->
phrase_file:consult(filename:join(priv_dir(), Filename)).
get_env(Par) ->
application:get_env(?MODULE, Par).
| null | https://raw.githubusercontent.com/shortishly/pgec/c9dc938340cb8d0db5e1a241f8ab122313e7b9ea/src/pgec.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. | Copyright ( c ) 2022 < >
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(pgec).
-export([get_env/1]).
-export([priv_consult/1]).
-export([priv_dir/0]).
-export([start/0]).
-export([version/0]).
version() ->
{ok, Version} = application:get_key(resp, vsn),
Version.
start() ->
application:ensure_all_started(?MODULE).
priv_dir() ->
code:priv_dir(?MODULE).
priv_consult(Filename) ->
phrase_file:consult(filename:join(priv_dir(), Filename)).
get_env(Par) ->
application:get_env(?MODULE, Par).
|
9fcf0233416e3c257d79fedacae72bc493a177529ca7813b5fd559fe2ebe01e4 | batsh-dev-team/Dlist | dlist_test.ml |
Copyright ( c ) 2013 , BYVoid < >
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
* Neither the name of the BYVoid nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND
ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL BYVoid < > BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2013, BYVoid <>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the BYVoid nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL BYVoid <> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
open OUnit
let test_empty _ =
let dlst = Dlist.empty () in
let lst = Dlist.to_list dlst in
assert_equal [] lst
let test_append _ =
let lst1 = [1;2;3] in
let dlst1 = Dlist.of_list lst1 in
let lst2 = [6;2;7;3] in
let dlst2 = Dlist.of_list lst2 in
let dlst = Dlist.append dlst1 dlst2 in
let lst = Dlist.to_list dlst in
assert_equal (lst1 @ lst2) lst
let test_concat _ =
let lst1 = [1;2;3] in
let dlst1 = Dlist.of_list lst1 in
let lst2 = [6;2;7;3] in
let dlst2 = Dlist.of_list lst2 in
let dlst = Dlist.concat [dlst1; dlst2] in
let lst = Dlist.to_list dlst in
assert_equal (lst1 @ lst2) lst
let test_map _ =
let lst = [1;2;3] in
let dlst = Dlist.of_list lst in
let f a = a * 3 in
let mapped_dlst = Dlist.map ~f dlst in
let mapped_lst = List.map f lst in
assert_equal mapped_lst (Dlist.to_list mapped_dlst)
let test_map2 _ =
let lst1 = [1;2;3] in
let dlst1 = Dlist.of_list lst1 in
let lst2 = [4;5;6] in
let dlst2 = Dlist.of_list lst2 in
let f a b = a * b in
let mapped_dlst = Dlist.map2 ~f dlst1 dlst2 in
let mapped_lst = List.map2 f lst1 lst2 in
assert_equal mapped_lst (Dlist.to_list mapped_dlst)
let test_rev _ =
let lst = [1;2;3] in
let dlst = Dlist.of_list lst in
let reversed_dlst = Dlist.rev dlst in
let reversed_lst = List.rev lst in
assert_equal reversed_lst (Dlist.to_list reversed_dlst)
let test_cases = "Dlist Unit Tests" >::: [
"Empty" >:: test_empty;
"Append" >:: test_append;
"Concat" >:: test_concat;
"Map" >:: test_map;
"Map2" >:: test_map2;
"Rev" >:: test_rev;
]
let _ =
run_test_tt_main test_cases
| null | https://raw.githubusercontent.com/batsh-dev-team/Dlist/4f57f7cd0231d30b51673da7a64ed2cf52c14074/test/dlist_test.ml | ocaml |
Copyright ( c ) 2013 , BYVoid < >
All rights reserved .
Redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
* Redistributions of source code must retain the above copyright
notice , this list of conditions and the following disclaimer .
* Redistributions in binary form must reproduce the above copyright
notice , this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution .
* Neither the name of the BYVoid nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND
ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL BYVoid < > BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES
( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ;
LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
Copyright (c) 2013, BYVoid <>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the BYVoid nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL BYVoid <> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
open OUnit
let test_empty _ =
let dlst = Dlist.empty () in
let lst = Dlist.to_list dlst in
assert_equal [] lst
let test_append _ =
let lst1 = [1;2;3] in
let dlst1 = Dlist.of_list lst1 in
let lst2 = [6;2;7;3] in
let dlst2 = Dlist.of_list lst2 in
let dlst = Dlist.append dlst1 dlst2 in
let lst = Dlist.to_list dlst in
assert_equal (lst1 @ lst2) lst
let test_concat _ =
let lst1 = [1;2;3] in
let dlst1 = Dlist.of_list lst1 in
let lst2 = [6;2;7;3] in
let dlst2 = Dlist.of_list lst2 in
let dlst = Dlist.concat [dlst1; dlst2] in
let lst = Dlist.to_list dlst in
assert_equal (lst1 @ lst2) lst
let test_map _ =
let lst = [1;2;3] in
let dlst = Dlist.of_list lst in
let f a = a * 3 in
let mapped_dlst = Dlist.map ~f dlst in
let mapped_lst = List.map f lst in
assert_equal mapped_lst (Dlist.to_list mapped_dlst)
let test_map2 _ =
let lst1 = [1;2;3] in
let dlst1 = Dlist.of_list lst1 in
let lst2 = [4;5;6] in
let dlst2 = Dlist.of_list lst2 in
let f a b = a * b in
let mapped_dlst = Dlist.map2 ~f dlst1 dlst2 in
let mapped_lst = List.map2 f lst1 lst2 in
assert_equal mapped_lst (Dlist.to_list mapped_dlst)
let test_rev _ =
let lst = [1;2;3] in
let dlst = Dlist.of_list lst in
let reversed_dlst = Dlist.rev dlst in
let reversed_lst = List.rev lst in
assert_equal reversed_lst (Dlist.to_list reversed_dlst)
let test_cases = "Dlist Unit Tests" >::: [
"Empty" >:: test_empty;
"Append" >:: test_append;
"Concat" >:: test_concat;
"Map" >:: test_map;
"Map2" >:: test_map2;
"Rev" >:: test_rev;
]
let _ =
run_test_tt_main test_cases
| |
8976d32ea26ee1d5cad5a8f9d6132e33d4519abd2d75d0d811623c942f3477ee | namin/biohacker | sudoku-prototype.lisp | (in-package :COMMON-LISP-USER)
(eval
`(constraint
sudoku-board
,(apply #'concatenate 'list
(loop for i from 1 to 9 collect
(loop for j from 1 to 9 collect
`(,(name i j) cell))))
(formulae
,@(apply #'concatenate 'list
(loop for vss in (list (rows) (cols) (units)) collect
(apply #'concatenate 'list
(loop for vs in vss collect
(apply #'concatenate 'list
(loop for a in vs collect
(loop for b in vs when (not (eq a b)) collect
`(,a (,a ,b) (if (= ,a ,b) :LOSE :DISMISS))
))))))))))
| null | https://raw.githubusercontent.com/namin/biohacker/6b5da4c51c9caa6b5e1a68b046af171708d1af64/BPS/tcon/sudoku-prototype.lisp | lisp | (in-package :COMMON-LISP-USER)
(eval
`(constraint
sudoku-board
,(apply #'concatenate 'list
(loop for i from 1 to 9 collect
(loop for j from 1 to 9 collect
`(,(name i j) cell))))
(formulae
,@(apply #'concatenate 'list
(loop for vss in (list (rows) (cols) (units)) collect
(apply #'concatenate 'list
(loop for vs in vss collect
(apply #'concatenate 'list
(loop for a in vs collect
(loop for b in vs when (not (eq a b)) collect
`(,a (,a ,b) (if (= ,a ,b) :LOSE :DISMISS))
))))))))))
| |
ac2bd66f32a935e2953dce2f717b36c6bece8ea94e83b7b67702d1e48b672b0f | kompendium-ano/api-factom | Chain.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeOperators #-}
module Factom.Rest.Client.Types.Chain where
import Control.Applicative
import Control.Monad (forM_, join, mzero)
import Data.Aeson (FromJSON (..), ToJSON (..),
Value (..), decode, object,
pairs, (.:), (.:?), (.=))
import Data.Aeson.AutoType.Alternative
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Monoid
import Data.Text (Text)
import Elm (ElmType)
import qualified GHC.Generics
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (hPutStrLn, stderr)
--------------------------------------------------------------------------------
| Workaround for .
o .:?? val = fmap join (o .:? val)
data LinksElt = LinksElt {
linksEltHref :: Text,
linksEltRel :: Text
} deriving (Show,Eq,GHC.Generics.Generic, ElmType)
instance FromJSON LinksElt where
parseJSON (Object v) = LinksElt <$> v .: "href" <*> v .: "rel"
parseJSON _ = mzero
instance ToJSON LinksElt where
toJSON (LinksElt {..}) =
object ["href" .= linksEltHref, "rel" .= linksEltRel]
toEncoding (LinksElt {..}) =
pairs ("href" .= linksEltHref <> "rel" .= linksEltRel)
data ChainEntity = ChainEntity {
chainEntStatus :: Text,
chainEntCreatedAt :: Text,
chainEntChainId :: Text,
chainEntExtIds :: [Text],
chainEntLinks :: [LinksElt],
chainEntSynced :: Bool
} deriving (Show,Eq,GHC.Generics.Generic, ElmType)
instance FromJSON ChainEntity where
parseJSON (Object v) =
ChainEntity
<$> v
.: "status"
<*> v
.: "createdAt"
<*> v
.: "chainId"
<*> v
.: "extIds"
<*> v
.: "links"
<*> v
.: "synced"
parseJSON _ = mzero
instance ToJSON ChainEntity where
toJSON (ChainEntity {..}) = object
[ "status" .= chainEntStatus
, "createdAt" .= chainEntCreatedAt
, "chainId" .= chainEntChainId
, "extIds" .= chainEntExtIds
, "links" .= chainEntLinks
, "synced" .= chainEntSynced
]
toEncoding (ChainEntity {..}) = pairs
( "status"
.= chainEntStatus
<> "createdAt"
.= chainEntCreatedAt
<> "chainId"
.= chainEntChainId
<> "extIds"
.= chainEntExtIds
<> "links"
.= chainEntLinks
<> "synced"
.= chainEntSynced
)
data Chain = Chain {
chainChainEntity :: ChainEntity
} deriving (Show,Eq,GHC.Generics.Generic, ElmType)
instance FromJSON Chain where
parseJSON (Object v) = Chain <$> v .: "chainEnt"
parseJSON _ = mzero
instance ToJSON Chain where
toJSON (Chain {..}) = object ["chainEnt" .= chainChainEntity]
toEncoding (Chain {..}) = pairs ("chainEnt" .= chainChainEntity)
| null | https://raw.githubusercontent.com/kompendium-ano/api-factom/68359e60d82515c6fd66134f8b3661e827eb6599/factom-oapi-client/src/Factom/Rest/Client/Types/Chain.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE OverloadedStrings #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeOperators #
------------------------------------------------------------------------------ | # LANGUAGE DeriveGeneric #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
module Factom.Rest.Client.Types.Chain where
import Control.Applicative
import Control.Monad (forM_, join, mzero)
import Data.Aeson (FromJSON (..), ToJSON (..),
Value (..), decode, object,
pairs, (.:), (.:?), (.=))
import Data.Aeson.AutoType.Alternative
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.Monoid
import Data.Text (Text)
import Elm (ElmType)
import qualified GHC.Generics
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (hPutStrLn, stderr)
| Workaround for .
o .:?? val = fmap join (o .:? val)
data LinksElt = LinksElt {
linksEltHref :: Text,
linksEltRel :: Text
} deriving (Show,Eq,GHC.Generics.Generic, ElmType)
instance FromJSON LinksElt where
parseJSON (Object v) = LinksElt <$> v .: "href" <*> v .: "rel"
parseJSON _ = mzero
instance ToJSON LinksElt where
toJSON (LinksElt {..}) =
object ["href" .= linksEltHref, "rel" .= linksEltRel]
toEncoding (LinksElt {..}) =
pairs ("href" .= linksEltHref <> "rel" .= linksEltRel)
data ChainEntity = ChainEntity {
chainEntStatus :: Text,
chainEntCreatedAt :: Text,
chainEntChainId :: Text,
chainEntExtIds :: [Text],
chainEntLinks :: [LinksElt],
chainEntSynced :: Bool
} deriving (Show,Eq,GHC.Generics.Generic, ElmType)
instance FromJSON ChainEntity where
parseJSON (Object v) =
ChainEntity
<$> v
.: "status"
<*> v
.: "createdAt"
<*> v
.: "chainId"
<*> v
.: "extIds"
<*> v
.: "links"
<*> v
.: "synced"
parseJSON _ = mzero
instance ToJSON ChainEntity where
toJSON (ChainEntity {..}) = object
[ "status" .= chainEntStatus
, "createdAt" .= chainEntCreatedAt
, "chainId" .= chainEntChainId
, "extIds" .= chainEntExtIds
, "links" .= chainEntLinks
, "synced" .= chainEntSynced
]
toEncoding (ChainEntity {..}) = pairs
( "status"
.= chainEntStatus
<> "createdAt"
.= chainEntCreatedAt
<> "chainId"
.= chainEntChainId
<> "extIds"
.= chainEntExtIds
<> "links"
.= chainEntLinks
<> "synced"
.= chainEntSynced
)
data Chain = Chain {
chainChainEntity :: ChainEntity
} deriving (Show,Eq,GHC.Generics.Generic, ElmType)
instance FromJSON Chain where
parseJSON (Object v) = Chain <$> v .: "chainEnt"
parseJSON _ = mzero
instance ToJSON Chain where
toJSON (Chain {..}) = object ["chainEnt" .= chainChainEntity]
toEncoding (Chain {..}) = pairs ("chainEnt" .= chainChainEntity)
|
935e4e828ca952559081e6dd74584dd554f9b872dbb615bf3cd30a7615f0e19a | Tclv/HaskellBook | numberintowords.hs | module WordNumber where
import Data.List (intersperse)
import Data.Char
digitToWord :: Int -> String
digitToWord n
| n >= 0 && n < 10 = (chr ((ord '0') + n)) : []
digits :: Int -> [Int]
digits n
| n < 10 = [n]
| otherwise = (digits quot) ++ [rem]
where (quot, rem) = quotRem n 10
wordNumber :: Int -> String
wordNumber n = concat $ map digitToWord $ digits n
| null | https://raw.githubusercontent.com/Tclv/HaskellBook/78eaa5c67579526b0f00f85a10be3156bc304c14/ch8/numberintowords.hs | haskell | module WordNumber where
import Data.List (intersperse)
import Data.Char
digitToWord :: Int -> String
digitToWord n
| n >= 0 && n < 10 = (chr ((ord '0') + n)) : []
digits :: Int -> [Int]
digits n
| n < 10 = [n]
| otherwise = (digits quot) ++ [rem]
where (quot, rem) = quotRem n 10
wordNumber :: Int -> String
wordNumber n = concat $ map digitToWord $ digits n
| |
a76a4f797a14423653c0d49c12bb3a52e378bf210d57d464628d4728b693ef69 | ThoughtWorksInc/infra-problem | core.clj | (ns common-utils.core)
(defn config
"Gets a configuration value from the environment"
[var-name default]
(if-let [val (get (System/getenv) var-name)]
val
default))
| null | https://raw.githubusercontent.com/ThoughtWorksInc/infra-problem/cd4e94377e11d5545de06732e36213ccbd05c2ba/common-utils/src/common_utils/core.clj | clojure | (ns common-utils.core)
(defn config
"Gets a configuration value from the environment"
[var-name default]
(if-let [val (get (System/getenv) var-name)]
val
default))
| |
f3dc486053eba5a83a5652df074782cc0b0c91e8bc4bfc5d2d56c9ff21b5a49e | cedlemo/OCaml-GI-ctypes-bindings-generator | Menu_direction_type.mli | open Ctypes
type t = Parent | Child | Next | Prev
val of_value:
Unsigned.uint32 -> t
val to_value:
t -> Unsigned.uint32
val t_view: t typ
| null | https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Menu_direction_type.mli | ocaml | open Ctypes
type t = Parent | Child | Next | Prev
val of_value:
Unsigned.uint32 -> t
val to_value:
t -> Unsigned.uint32
val t_view: t typ
| |
0809d8048f6f844a426305369cc9778bb747ef4e4a41010d7ccd5340bdb6bb3b | racket/typed-racket | mandelbrot.rkt | #lang typed/racket/base/shallow #:optimize
(require racket/future racket/flonum)
(define: MAX-ITERS : Positive-Fixnum 50)
(define MAX-DIST 2.0)
(define: N : Positive-Fixnum 512)
(: mandelbrot-point : Integer Integer -> Integer)
(define (mandelbrot-point x y)
(define c
(+ (- (/ (* 2.0 (->fl x)) N) 1.5)
(* 0.0+1.0i (- (/ (* 2.0 (->fl y)) N) 1.0))))
(let loop ((i 0) (z 0.0+0.0i))
(cond
[(> i MAX-ITERS) (char->integer #\*)]
[(> (magnitude z) MAX-DIST)
(char->integer #\space)]
[else (loop (add1 i) (+ (* z z) c))])))
(: fs (Listof (Futureof Bytes)))
(define fs
(for/list ([y (in-range N)])
(let ([bstr (make-bytes N)])
(future
(lambda ()
(for ([x (in-range N)])
(bytes-set! bstr x (mandelbrot-point x y)))
bstr)))))
(lambda ()
(for: ([f : (Futureof Bytes) (in-list fs)])
(write-bytes (touch f))
(newline)))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/shallow/mandelbrot.rkt | racket | #lang typed/racket/base/shallow #:optimize
(require racket/future racket/flonum)
(define: MAX-ITERS : Positive-Fixnum 50)
(define MAX-DIST 2.0)
(define: N : Positive-Fixnum 512)
(: mandelbrot-point : Integer Integer -> Integer)
(define (mandelbrot-point x y)
(define c
(+ (- (/ (* 2.0 (->fl x)) N) 1.5)
(* 0.0+1.0i (- (/ (* 2.0 (->fl y)) N) 1.0))))
(let loop ((i 0) (z 0.0+0.0i))
(cond
[(> i MAX-ITERS) (char->integer #\*)]
[(> (magnitude z) MAX-DIST)
(char->integer #\space)]
[else (loop (add1 i) (+ (* z z) c))])))
(: fs (Listof (Futureof Bytes)))
(define fs
(for/list ([y (in-range N)])
(let ([bstr (make-bytes N)])
(future
(lambda ()
(for ([x (in-range N)])
(bytes-set! bstr x (mandelbrot-point x y)))
bstr)))))
(lambda ()
(for: ([f : (Futureof Bytes) (in-list fs)])
(write-bytes (touch f))
(newline)))
| |
682392897810d8a596f61e2f2025a08a8964b74a2d0a7e481dc255204564e6cb | vseloved/cl-agraph | agraph.lisp | CL - AGRAPH core
( c ) Vsevolod Dyomkin . see LICENSE file for permissions
(in-package :agraph)
(named-readtables:in-readtable rutils-readtable)
(defstruct (ag-config (:conc-name ag-))
(scheme :http)
(host "localhost")
(port 10035)
catalog
repo
(user "test")
(pass "xyzzy")
session)
(defvar *ag* (make-ag-config)
"Current agraph config.")
(defparameter *stream-mode* nil
"Ask for a stream of results from an agraph request.")
(define-condition ag-error (error)
((code :initarg :code :accessor ag-code)
(msg :initarg :msg :accessor ag-msg))
(:report (lambda (e out)
(format out "AG-ERROR ~A: ~A"
(ag-code e) (ag-msg e)))))
(defun open-ag (&key scheme host port catalog repo user pass sessionp timeout)
"Configure *AG* with SCHEME/HOST/POST/CATALOG/REPO/USER/PASS.
If SESSIONP, establish a session (optionally specify its lifetime as TIMEOUT)
and returns it. Otherwise, returns NIL."
(:= *ag* (apply 'make-ag-config
(append (when scheme (list :scheme scheme))
(when host (list :host host))
(when port (list :port port))
(when catalog (list :catalog catalog))
(when repo (list :repo repo))
(when user (list :user user))
(when pass (list :pass pass)))))
(:= *blank-nodes* (getset# *ag* *blank-nodes-repo* #h(equal)))
(when sessionp
(:= (ag-session *ag*) (ag-req "/session"
(when timeout (list "lifetime" timeout))
:method :post))))
(defun close-ag ()
"Terminate the current agraph session (if there's any). Clear *AG*."
(when (and *ag* (ag-session *ag*))
(ag-req "/session/close" nil :method :post))
(:= *ag* nil
*blank-nodes* (? *blank-nodes-repo* nil))
t)
(defmacro with-ag ((&key scheme host port catalog repo user pass
(sessionp t) timeout)
&body body)
"OPEN-AG and, if SESSIONP (default), establish a session
(its lifetime may be specified with TIMEOUT).
Execute BODY.
CLOSE-AG.
If the session is terminated, try to reestablish it once."
(once-only (scheme host port catalog repo user pass sessionp timeout)
(let ((rez (gensym)))
`(let (*ag*)
(block nil
(unwind-protect
(progn
(open-ag :scheme ,scheme
:host ,host
:port ,port
:catalog ,catalog
:repo ,repo
:user ,user
:pass ,pass
:sessionp ,sessionp
:timeout ,timeout)
(handler-case (let ((,rez (progn ,@body)))
(when ,sessionp (commit))
,rez)
(usocket:connection-refused-error ()
(warn "The current agraph sesssion is closed. Restarting it.")
(open-ag :scheme ,scheme
:host ,host
:port ,port
:catalog ,catalog
:repo ,repo
:user ,user
:pass ,pass
:timeout ,timeout
:sessionp t)
(let ((,rez (progn ,@body)))
(when ,sessionp (commit))
,rez))))
(close-ag)))))))
(defun ag-params (args)
"Transform ARGS to pairs suitable for passing as agraph HTTP query parameters."
(remove nil
(apply 'mapcar ^(when %% (cons % (prin1-to-string %%)))
(loop :for (k v) :on args :by #'cddr :while k
:collect k :into ks
:collect v :into vs
:finally (return (list ks vs))))))
(defun ag-req (query params
&key (ag *ag*) (method :get) content accept content-type)
"Run the Aagraph QUERY with PARAMS processed by ag-params
against the current session or the current repository.
METHOD, ACCEPT, CONTENT, and CONTENT-TYPE may be chnaged.
In case of 2xx HTTP return code, returns the result
as triples (if nquads content-type is returned)
or raw string result and the return code as a second value.
In case 4xx or 5xx return codes, signals AG-ERROR for them."
(with ((rez code headers
(drakma:http-request
(if-it (ag-session ag)
(fmt "~A~@[~A~]" it query)
(fmt "~A://~A:~A/~@[catalogs/~A/~]repositories/~A~@[~A~]"
(ag-scheme ag)
(ag-host ag)
(ag-port ag)
(ag-catalog ag)
(ag-repo ag)
query))
:method method
:content content
:content-type content-type
:parameters (ag-params params)
:basic-authorization (list (ag-user ag) (ag-pass ag))
:accept (or accept "text/x-nquads, */*")
:want-stream *stream-mode*)))
(ecase (floor code 100)
((4 5) (error 'ag-error :code code
:msg (if (streamp rez)
(asdf::slurp-stream-string rez)
rez)))
(2 (if (starts-with "text/x-nquads" (assoc1 :Content-Type headers))
(mapcar 'triple-from-list
(if *stream-mode* (parse-nq-doc rez)
(with-input-from-string (in rez)
(parse-nq-doc in))))
(values rez
code))))))
| null | https://raw.githubusercontent.com/vseloved/cl-agraph/e605b34fa57a9ede6fb6cc13ef82fc3438898567/src/agraph.lisp | lisp | CL - AGRAPH core
( c ) Vsevolod Dyomkin . see LICENSE file for permissions
(in-package :agraph)
(named-readtables:in-readtable rutils-readtable)
(defstruct (ag-config (:conc-name ag-))
(scheme :http)
(host "localhost")
(port 10035)
catalog
repo
(user "test")
(pass "xyzzy")
session)
(defvar *ag* (make-ag-config)
"Current agraph config.")
(defparameter *stream-mode* nil
"Ask for a stream of results from an agraph request.")
(define-condition ag-error (error)
((code :initarg :code :accessor ag-code)
(msg :initarg :msg :accessor ag-msg))
(:report (lambda (e out)
(format out "AG-ERROR ~A: ~A"
(ag-code e) (ag-msg e)))))
(defun open-ag (&key scheme host port catalog repo user pass sessionp timeout)
"Configure *AG* with SCHEME/HOST/POST/CATALOG/REPO/USER/PASS.
If SESSIONP, establish a session (optionally specify its lifetime as TIMEOUT)
and returns it. Otherwise, returns NIL."
(:= *ag* (apply 'make-ag-config
(append (when scheme (list :scheme scheme))
(when host (list :host host))
(when port (list :port port))
(when catalog (list :catalog catalog))
(when repo (list :repo repo))
(when user (list :user user))
(when pass (list :pass pass)))))
(:= *blank-nodes* (getset# *ag* *blank-nodes-repo* #h(equal)))
(when sessionp
(:= (ag-session *ag*) (ag-req "/session"
(when timeout (list "lifetime" timeout))
:method :post))))
(defun close-ag ()
"Terminate the current agraph session (if there's any). Clear *AG*."
(when (and *ag* (ag-session *ag*))
(ag-req "/session/close" nil :method :post))
(:= *ag* nil
*blank-nodes* (? *blank-nodes-repo* nil))
t)
(defmacro with-ag ((&key scheme host port catalog repo user pass
(sessionp t) timeout)
&body body)
"OPEN-AG and, if SESSIONP (default), establish a session
(its lifetime may be specified with TIMEOUT).
Execute BODY.
CLOSE-AG.
If the session is terminated, try to reestablish it once."
(once-only (scheme host port catalog repo user pass sessionp timeout)
(let ((rez (gensym)))
`(let (*ag*)
(block nil
(unwind-protect
(progn
(open-ag :scheme ,scheme
:host ,host
:port ,port
:catalog ,catalog
:repo ,repo
:user ,user
:pass ,pass
:sessionp ,sessionp
:timeout ,timeout)
(handler-case (let ((,rez (progn ,@body)))
(when ,sessionp (commit))
,rez)
(usocket:connection-refused-error ()
(warn "The current agraph sesssion is closed. Restarting it.")
(open-ag :scheme ,scheme
:host ,host
:port ,port
:catalog ,catalog
:repo ,repo
:user ,user
:pass ,pass
:timeout ,timeout
:sessionp t)
(let ((,rez (progn ,@body)))
(when ,sessionp (commit))
,rez))))
(close-ag)))))))
(defun ag-params (args)
"Transform ARGS to pairs suitable for passing as agraph HTTP query parameters."
(remove nil
(apply 'mapcar ^(when %% (cons % (prin1-to-string %%)))
(loop :for (k v) :on args :by #'cddr :while k
:collect k :into ks
:collect v :into vs
:finally (return (list ks vs))))))
(defun ag-req (query params
&key (ag *ag*) (method :get) content accept content-type)
"Run the Aagraph QUERY with PARAMS processed by ag-params
against the current session or the current repository.
METHOD, ACCEPT, CONTENT, and CONTENT-TYPE may be chnaged.
In case of 2xx HTTP return code, returns the result
as triples (if nquads content-type is returned)
or raw string result and the return code as a second value.
In case 4xx or 5xx return codes, signals AG-ERROR for them."
(with ((rez code headers
(drakma:http-request
(if-it (ag-session ag)
(fmt "~A~@[~A~]" it query)
(fmt "~A://~A:~A/~@[catalogs/~A/~]repositories/~A~@[~A~]"
(ag-scheme ag)
(ag-host ag)
(ag-port ag)
(ag-catalog ag)
(ag-repo ag)
query))
:method method
:content content
:content-type content-type
:parameters (ag-params params)
:basic-authorization (list (ag-user ag) (ag-pass ag))
:accept (or accept "text/x-nquads, */*")
:want-stream *stream-mode*)))
(ecase (floor code 100)
((4 5) (error 'ag-error :code code
:msg (if (streamp rez)
(asdf::slurp-stream-string rez)
rez)))
(2 (if (starts-with "text/x-nquads" (assoc1 :Content-Type headers))
(mapcar 'triple-from-list
(if *stream-mode* (parse-nq-doc rez)
(with-input-from-string (in rez)
(parse-nq-doc in))))
(values rez
code))))))
| |
bbabcc0512058958eca7d5e5b554d464ff4ebe40f7a131f6523f1c0203765a88 | byulparan/cl-collider | synthdef.lisp |
(in-package #:sc)
(defclass synthdef ()
((name :initarg :name :accessor name)
(controls :initarg :controls :initform nil :accessor controls)
(named-controls :initform nil :accessor named-controls)
(control-names :initarg :control-names :initform nil :accessor control-names)
(control-ugen-count :accessor control-ugen-count :initform 0)
(children :initform nil :accessor children)
(constants :initform nil :accessor constants)
(max-local-bufs :initform nil :accessor max-local-bufs)
(available :initform nil :accessor available)
(width-first-ugens :initform nil :accessor width-first-ugens)
(rewrite-in-progress :initform nil :accessor rewrite-in-progress)))
(defmethod print-object ((c synthdef) stream)
(format stream "#<~s :name ~s>" 'synthdef (name c)))
(defmethod add-ugen ((synthdef synthdef) (ugen ugen))
(unless (rewrite-in-progress synthdef)
(setf (synth-index ugen) (length (children synthdef)))
(setf (width-first-antecedents ugen) (copy-list (width-first-ugens synthdef)))
(alexandria:appendf (children synthdef) (list ugen)))
ugen)
(defmethod replace-ugen ((synthdef synthdef) (a ugen) (b ugen))
(unless (typep b 'ugen) (error "REPLACE-UGEN requires a UGen."))
(setf (width-first-antecedents b) (width-first-antecedents a))
(setf (descendants b) (descendants a))
(setf (synth-index b) (synth-index a))
(setf (nth (position a (children synthdef)) (children synthdef)) b)
(loop for item in (children synthdef)
for i from 0
do (when item
(loop for input in (inputs item) for j from 0
do (when (eql input a)
(setf (nth j (inputs item)) b))))))
(defmethod check-inputs ((synthdef synthdef))
(dolist (ugen (children synthdef))
(funcall (check-fn ugen) ugen)))
(defmethod add-constant ((synthdef synthdef) (const single-float))
(unless (find const (constants synthdef))
(alexandria:appendf (constants synthdef) (list const))))
(defmethod add-constant ((synthdef synthdef) (const t))
(error "can't available input: ~a" const))
(defmethod collect-constants ((synthdef synthdef))
(dolist (ugen (children synthdef))
(collect-constants ugen)))
(defmethod init-topo-sort ((synthdef synthdef))
(setf (available synthdef) nil)
(dolist (ugen (children synthdef))
(setf (antecedents ugen) nil (descendants ugen) nil))
(dolist (ugen (children synthdef))
(init-topo-sort ugen))
(dolist (ugen (reverse (children synthdef)))
(setf (descendants ugen) (sort (descendants ugen) #'< :key #'synth-index))
(make-available ugen)))
(defun topo-logical-sort (synthdef)
(let ((out-stack nil))
(init-topo-sort synthdef)
(loop while (> (length (available synthdef)) 0) do
(setf out-stack (schedule (pop (available synthdef)) out-stack)))
(setf (children synthdef) (nreverse out-stack))))
(defun index-ugens (synthdef)
(loop for ugen in (children synthdef)
for i from 0
do (setf (synth-index ugen) i)))
(defmethod optimize-graph ((synthdef synthdef))
(let ((old-size (length (children synthdef))))
(init-topo-sort synthdef)
(setf (rewrite-in-progress synthdef) t)
(dolist (ugen (children synthdef))
(optimize-graph ugen))
(setf (rewrite-in-progress synthdef) nil)
(unless (= old-size (length (children synthdef)))
(index-ugens synthdef))))
(defmethod build-synthdef ((synthdef synthdef))
(check-inputs synthdef)
(optimize-graph synthdef)
(collect-constants synthdef)
(topo-logical-sort synthdef)
(index-ugens synthdef)
synthdef)
(defun write-synthdef-file (name encoded-synthdef)
(let ((path (merge-pathnames (make-pathname :name name :type "scsyndef")
(full-pathname *sc-synthdefs-path*))))
(with-open-file (stream path :direction :output
:if-exists :supersede
:element-type '(unsigned-byte 8))
(write-sequence encoded-synthdef stream))
(namestring path)))
(defmethod load-synthdef ((synthdef synthdef) node &optional (completion-message 0))
(assert (is-local-p *s*) nil "Server ~a is not a local server, so it cannot load synthdefs from a file." *s*)
(message-distribute node (list "/d_load" (write-synthdef-file (name synthdef) (encode-synthdef synthdef)) completion-message) *s*))
(defmethod recv-synthdef ((synthdef synthdef) node &optional (completion-message 0))
(let* ((name (name synthdef))
(data (encode-synthdef synthdef)))
(cond ((>= usocket:+max-datagram-packet-size+ (length data)) (message-distribute node (list "/d_recv" data completion-message) *s*))
((is-local-p *s*) (progn (format t "~&~a too big for sending. Retrying via synthdef file.~%" name)
(load-synthdef synthdef node completion-message)))
(t (error "Synthdef ~a is too big to send." name)))))
(defclass control (multiout-ugen) ())
(defmethod new1 ((ugen control) &rest inputs)
(setf (inputs ugen) (third inputs))
(setf (channels ugen) (length (alexandria:flatten (first inputs))))
(setf (special-index ugen) (second inputs))
(add-to-synth ugen)
(let ((i 0))
(loop for control in (first inputs)
collect (unbubble (loop repeat (length (alexandria:ensure-list control))
collect (make-instance 'proxy-output
:source ugen
:rate (rate ugen)
:signal-range (signal-range ugen)
:output-index i)
do (incf i))))))
(defun add-controls (rate lag-p controls)
(ugen-new (if lag-p "LagControl" "Control")
rate 'control #'identity :bipolar (mapcar #'second controls) (control-ugen-count *synthdef*)
(alexandria:flatten
(when lag-p
(mapcar (lambda (ctrl)
(let ((lag-value (alexandria:if-let ((value (getf ctrl :lag))) value 0))
(ctrl-value (second ctrl)))
(when (and (consp lag-value) (numberp ctrl-value))
(error "Single control with multiple lag values is not supported."))
(when (and (consp lag-value) (consp ctrl-value) (/= (length lag-value) (length ctrl-value)))
(error "Number of control values does not match the number of lag values."))
(when (and (consp ctrl-value) (atom lag-value))
(setf lag-value (make-list (length ctrl-value) :initial-element lag-value)))
lag-value))
controls)))))
(defun make-control (params rate)
(assert (and (every #'stringp (mapcar #'first params))
(every #'numberp (alexandria:flatten (mapcar #'second params)))
(every #'(lambda (rate) (or (not rate) (find rate (list :ar :tr :lag)))) (mapcar #'third params))))
(labels ((make-ctrl (params)
(dolist (controls (mapcar #'second params))
(dolist (control-val (alexandria:ensure-list controls))
(alexandria:appendf (controls *synthdef*) (list (floatfy control-val)))))))
(let* ((trig-controls (remove-if-not #'(lambda (p) (eql :tr (third p))) params))
(audio-controls (remove-if-not #'(lambda (p) (eql :ar (third p))) params))
(controls (remove-if #'(lambda (p) (find (third p) (list :tr :ar))) params))
(lag-p (some #'(lambda (c) (getf c :lag)) controls)))
(alexandria:appendf (control-names *synthdef*)
(loop with control-names = (mapcar #'first (control-names *synthdef*))
for controls in (append trig-controls audio-controls controls)
and index = (control-ugen-count *synthdef*) then (incf index (length (alexandria:ensure-list (second controls))))
do (when (find (first controls) control-names :test #'string=)
(error "Duplicate control name: ~s" (first controls)))
collect (list (first controls) index)))
(make-ctrl trig-controls) (make-ctrl audio-controls) (make-ctrl controls)
(append
(when trig-controls
(prog1 (ugen-new "TrigControl" rate 'control #'identity :bipolar
(mapcar #'second trig-controls)
(control-ugen-count *synthdef*))
(incf (control-ugen-count *synthdef*) (length (alexandria:flatten (mapcar #'second trig-controls))))))
(when audio-controls
(prog1 (ugen-new "AudioControl" :audio 'control #'identity :bipolar
(mapcar #'second audio-controls)
(control-ugen-count *synthdef*))
(incf (control-ugen-count *synthdef*) (length (alexandria:flatten (mapcar #'second audio-controls))))))
(when controls
(prog1 (add-controls rate lag-p controls)
(incf (control-ugen-count *synthdef*) (length (alexandria:flatten (mapcar #'second controls))))))))))
(defmacro with-controls (params &body body)
(if params `(destructuring-bind ,(mapcar #'first (append
(remove-if-not (lambda (a) (eql :tr (third a))) params)
(remove-if-not (lambda (a) (eql :ar (third a))) params)
(remove-if (lambda (a) (or (eql :tr (third a)) (eql :ar (third a)))) params)))
(make-control (list ,@(mapcar (lambda (a)
(cons 'list (list (string-downcase (first a)) `(floatfy ,(second a)) (third a) (fourth a))))
params))
:control)
,@body)
`(progn ,@body)))
(defun named-control (name rate &optional value lag)
"A NamedControl directly combines a ControlName and a Control UGen conveniently. Also this makes it safe even if several identical controls exist"
(when (and (consp lag) (find 0 lag :test #'equalp)) (error "'lagTime' has bad input"))
(when (eql rate :tr) (setf lag nil))
(let* ((name (string-downcase name))
(lag (if (and (numberp lag) (zerop lag)) nil lag))
(rate (ecase rate
(:kr :control)
(:ar :audio)
(:tr :trig)))
(reg-control (cadr (assoc name (named-controls *synthdef*) :test #'string=))))
(if reg-control (let* ((ugen (getf reg-control :ugen))
(fixed-lag (getf reg-control :fixed-lag)))
(assert (eql rate (getf reg-control :rate)) nil
"NamedControl: cannot have more than one set of rates in the same control.")
(when value
(assert (equalp (alexandria:ensure-list (floatfy value))
(getf reg-control :value)) nil
"NamedControl: cannot have more than one set of default values in the same control."))
(when (and lag fixed-lag)
(assert (equalp (alexandria:ensure-list lag) (getf reg-control :lag)) nil
"NamedControl: cannot have more than one set of fixed lag values in the same control."))
(cond ((and lag (not fixed-lag) (equal rate :control)) (lag.kr ugen lag))
((and lag (not fixed-lag) (equal rate :audio)) (lag.ar ugen lag))
(t ugen)))
(let* ((fixed-lag (and lag (every #'numberp (alexandria:ensure-list lag)))))
(when (and (eql rate :control) value fixed-lag)
(when (and (numberp value) (consp lag) (/= 1 (length lag)))
(error "Single control with multiple lag values is not supported."))
(when (and (consp value) (consp lag) (/= (length lag) (length value)))
(error "Number of control values does not match the number of lag values."))
(when (and (consp value) (atom lag))
(setf lag (make-list (length value) :initial-element lag))))
(let* ((value (alexandria:ensure-list (floatfy (if value value 0.0))))
(lag (alexandria:ensure-list lag))
(lag (if fixed-lag (subseq lag 0 (length value)) lag))
(ugen-name (ecase rate
(:control (if fixed-lag "LagControl" "Control"))
(:audio "AudioControl")
(:trig "TrigControl")))
(ugen (unbubble (ugen-new ugen-name (if (eql rate :trig) :control rate) 'control #'identity :bipolar
value (control-ugen-count *synthdef*) lag))))
(alexandria:appendf (controls *synthdef*) value)
(alexandria:appendf (control-names *synthdef*) (list (list name (control-ugen-count *synthdef*))))
(incf (control-ugen-count *synthdef*) (length value))
(push (list name (list :rate rate :value value :lag lag :fixed-lag fixed-lag :ugen ugen)) (named-controls *synthdef*))
(when (and (eql rate :audio) lag) (setf ugen (lag.ar ugen lag)))
(when (and (eql rate :control) lag (not fixed-lag)) (setf ugen (lag.kr ugen lag)))
(pushnew (list name (unbubble value)) (synthdef-metadata (name *synthdef*) :controls))
ugen)))))
(defun kr (name &optional value lag)
"shortcut for named-control(control rate)"
(named-control name :kr value lag))
;;; build --------------------------------------------------------------------------------------
(defvar *synthdef-function-table* '((abs sc::abs~)
(floor sc::floor~)
(ceil sc::ceil~)
(sqrt sc::sqrt~)
(exp sc::exp~)
(sin sc::sin~)
(cos sc::cos~)
(tan sc::tan~)
(tanh sc::tanh~)
(expt sc::expt~)
(+ sc::+~)
(- sc::-~)
(* sc::*~)
(/ sc::/~)
(mod sc::mod~)
(round sc::round~)
(< sc::<~)
(> sc::>~)
(<= sc::<=~)
(>= sc::>=~)
(max sc::max~)
(min sc::min~)
(logand sc::logand~)
(logior sc::logior~)
(ash sc::ash~))
"Table mapping function names to their synthdef-compatible equivalents. Used by `convert-code' and `synthdef-equivalent-function' to convert lisp functions in synthdef bodies to ugen functions.")
(defun synthdef-equivalent-function (function)
"Get the synthdef-compatible equivalent of FUNCTION from `*synthdef-function-table*'. If FUNCTION is not found in the table, return it unchanged."
(or (cadr (assoc function *synthdef-function-table*))
function))
(defun (setf synthdef-equivalent-function) (value function)
"Set the synthdef-compatible equivalent of FUNCTION to VALUE in `*synthdef-function-table*'. If VALUE is nil, remove the entry for FUNCTION from the table."
(if value
(push (list function value) *synthdef-function-table*)
(alexandria:removef *synthdef-function-table* function :key #'car)))
(defun synthdef-embeddable-body (synth args)
"Make an \"embeddable\" synthdef body, to allow `synth' to be used inside `synthdef'."
(let* ((body (synthdef-metadata synth :body))
(args-keys (loop :for (k v) :on args :by #'cddr :collect k))
(unprovided-args (append
(loop :for (k v) :on args :by #'cddr
:for rk := (intern (symbol-name k))
:unless (eql rk v)
:collect (list rk v))
(mapcan (lambda (c)
(unless (or (string= (car c) 'out)
(member (car c) args-keys :test #'string=))
(list (if (string= (car c) 'amp)
(list (car c) 1) ;; default to full volume for embedded synths
c))))
(synthdef-metadata synth :controls)))))
(labels ((parse-item (body)
(if (listp body)
(if (member (car body) (list 'out.ar 'out.kr 'replace-out.ar 'replace-out.kr 'x-out.ar 'x-out.kr 'scope-out.ar 'scope-out.kr 'scope-out2.ar 'scope-out2.kr))
(caddr body)
(mapcar #'parse-item body))
body)))
`(let (,@unprovided-args)
,@(parse-item body)))))
(defun convert-code (form &optional head)
(cond ((null form) nil)
((atom form) (if head
(synthdef-equivalent-function form)
form))
((position (car form) (list 'let 'let*)) ;; avoid converting names of local bindings
`(,(car form) ,(mapcar (lambda (item)
(if (atom item)
item
`(,(car item) ,@(convert-code (cdr item)))))
(cadr form))
,@(convert-code (cddr form))))
((eql (car form) 'destructuring-bind)
`(,(car form) ,(cadr form) ,(caddr form)
,@(convert-code (cdddr form))))
((eql (car form) 'synth)
(let ((synth (cadr form))
(args (cddr form)))
(convert-code
(synthdef-embeddable-body (if (and (listp synth)
(eql 'quote (car synth)))
(cadr synth)
synth)
args))))
(t (cons (convert-code (car form) t)
(mapcar #'convert-code (cdr form))))))
(defparameter *synth-definition-mode* :recv)
(defparameter *synthdef-metadata* (make-hash-table)
"Metadata for each synthdef, such as its name, controls, body, etc.")
(defun synthdef-metadata (synth &optional key)
"Get metadata about the synthdef with the name of SYNTH. When KEY is provided, return that specific item from the metadata (i.e. controls, body, etc)."
(let ((metadata (gethash (as-keyword (if (typep synth 'node) (name synth) synth)) *synthdef-metadata*)))
(if key
(getf metadata (as-keyword key))
metadata)))
#-ecl
(uiop:with-deprecation (:style-warning)
(defun get-synthdef-metadata (synth &optional key)
"Deprecated alias for `synthdef-metadata'."
(synthdef-metadata synth key)))
(defun (setf synthdef-metadata) (value synth key)
"Set a metadatum for the synthdef SYNTH."
(setf (getf (gethash (as-keyword synth) *synthdef-metadata*) (as-keyword key)) value))
#-ecl
(uiop:with-deprecation (:style-warning)
(defun set-synthdef-metadata (synth key value)
"Deprecated alias for `(setf synthdef-metadata)'."
(setf (synthdef-metadata synth key) value)))
(defmacro defsynth (name params &body body)
(setf params (mapcar (lambda (param) (if (consp param) param (list param 0.0))) params))
(alexandria:with-gensyms (synthdef)
`(progn
(setf (synthdef-metadata ',name :name) ',name
(synthdef-metadata ',name :controls) (mapcar (lambda (param) (append (list (car param)) (cdr param)))
',params)
(synthdef-metadata ',name :body) ',body)
(let* ((,synthdef (make-instance 'synthdef :name ,(string-downcase name)))
(*synthdef* ,synthdef))
(with-controls (,@params)
,@(convert-code body)
(build-synthdef ,synthdef)
(when (and *s* (boot-p *s*))
(ecase *synth-definition-mode*
(:recv (recv-synthdef ,synthdef nil))
(:load (load-synthdef ,synthdef nil)))
(sync))
,synthdef)))))
(defvar *temp-synth-name* "temp-synth")
(defmacro play (body &key id (out-bus 0) (gain 1.0) (lag 1.0) (fade 0.02) (to 1) (pos :head))
(alexandria:with-gensyms (synthdef result dt buses gate gain-sym lag-sym
start-val env node-id name fade-time outlets seqs node)
`(let* ((,name *temp-synth-name*)
(,fade-time nil)
(,synthdef (make-instance 'synthdef :name ,name))
(*synthdef* ,synthdef))
(labels ((,seqs (indx lists)
(nth (mod indx (length lists)) lists))
(,outlets (f bus result gain lag)
(if (numberp gain) (funcall f bus (*~ result (var-lag.kr gain lag)))
(loop with bus = (alexandria:ensure-list bus)
with gain = (alexandria:ensure-list gain)
for i from 0 below (max (length bus) (length gain))
do (funcall f (,seqs i bus) (*~ (var-lag.kr (,seqs i gain) lag) result))))))
(let ((,result ,(convert-code body)))
(unless (eql :scalar (rate ,result))
(setf ,fade-time ,fade)
(destructuring-bind (,dt ,buses ,gate ,gain-sym ,lag-sym)
(make-control (list (list "fade" ,fade) (list "out-bus" ,out-bus)
(list "gate" 1.0) (list "gain" ,gain) (list "lag" ,lag)) :control)
(let* ((,start-val (<=~ ,dt 0))
(,env (env-gen.kr
(env (list ,start-val 1 0) (list 1,1) :lin 1) :gate ,gate :level-scale 1 :level-bias 0.0
:time-scale ,dt :act :free)))
(setf ,result (*~ ,env ,result))
(cond ((eql :audio (rate ,result)) (,outlets 'out.ar ,buses ,result ,gain-sym ,lag-sym))
((eql :control (rate ,result)) (,outlets 'out.kr ,buses ,result ,gain-sym ,lag-sym))
(t (error "Play: ~a is not a UGen." ,result))))))))
(build-synthdef ,synthdef)
(let* ((,node-id (or ,id (get-next-id *s*)))
(,node (make-instance 'node :server *s* :id ,node-id :name *temp-synth-name* :pos ,pos :to ,to
:meta (list :fade-time ,fade-time))))
(recv-synthdef ,synthdef ,node (apply 'sc-osc::encode-message (make-synth-msg *s* ,name ,node-id ,to ,pos)))
(sync)
,node))))
(defun synth (name &rest args)
"Start a synth by name."
(let* ((name-string (string-downcase (symbol-name name)))
(next-id (or (getf args :id) (get-next-id *s*)))
(to (or (getf args :to) 1))
(pos (or (getf args :pos) :head))
(new-synth (make-instance 'node :server *s* :id next-id :name name-string :pos pos :to to))
(args (loop :for (arg val) :on args :by #'cddr
:unless (member arg '(:id :to :pos))
:append (list (string-downcase arg) (floatfy val)))))
(message-distribute new-synth
(apply #'make-synth-msg *s* name-string next-id to pos args)
*s*)))
(defun get-controls-list (form)
"Scan FORM for (with-controls ...) and return the list of controls if it exists, or NIL otherwise."
(cond ((null form) nil)
((listp form)
(if (eq (car form) 'with-controls)
(cadr form)
(loop :for i :in (cdr form)
:for res = (get-controls-list i)
:unless (null res)
:return res)))))
(defmacro proxy (key body &key id (gain 1.0) (fade 0.5) (pos :head) (to 1) (out-bus 0))
(alexandria:with-gensyms (node node-alive-p d-key)
`(let* ((,node (gethash ,key (node-proxy-table *s*)))
(,node-alive-p (when ,node (if (typep *s* 'nrt-server) t (is-playing-p ,node)))))
,(if body
(alexandria:once-only (id fade)
`(labels ((clear-node ()
(when ,node-alive-p
(if (getf (meta ,node) :fade-time) (ctrl ,node :gate 0 :fade ,fade)
(free ,node)))))
(when (and (typep *s* 'rt-server) (is-playing-p ,id))
(error "already running id ~d~%" ,id))
(let ((,d-key (string-downcase ,key)))
(setf (synthdef-metadata ,d-key :name) ,d-key)
(let ((controls (get-controls-list ',body)))
(setf (synthdef-metadata ,d-key :controls) (mapcar (lambda (param) (append (list (car param)) (cdr param))) controls)))
(setf (synthdef-metadata ,d-key :body) ',body))
(let ((*temp-synth-name* (string-downcase ,key)))
(prog1 (setf (gethash ,key (node-proxy-table *s*))
(play ,body :id ,id :out-bus ,out-bus :fade ,fade :to ,to :pos ,pos :gain ,gain))
(clear-node)))))
`(when ,node-alive-p
(free ,node))))))
(defun proxy-ctrl (key &rest params &key &allow-other-keys)
(let* ((node (gethash key (node-proxy-table *s*)))
(node-alive-p (and node (if (typep *s* 'nrt-server) t (is-playing-p node)))))
(assert node nil "can't find proxy ~a" key)
(let* ((fade-time (getf (meta node) :fade-time)))
(flet ((clear-node ()
(if fade-time (ctrl node :gate 0 :fade (or (getf params :fade) fade-time))
(free node))))
(let* ((new-node (apply #'synth key params)))
(setf (meta new-node) (list :fade-time fade-time))
(prog1
(setf (gethash key (node-proxy-table *s*)) new-node)
(when node-alive-p
(clear-node))))))))
;;; ======================================================================
build to
;;; ======================================================================
(defparameter +type-id+ (map '(vector (unsigned-byte 8)) #'char-code "SCgf"))
(defparameter *synthdef-version* 2)
(defun encode-synthdef (synthdef)
(ecase *synthdef-version*
(1 (to-byte-array-synthdef-1 synthdef))
(2 (to-byte-array-synthdef-2 synthdef))))
(defun to-byte-array-synthdef-1 (synthdef)
(flex:with-output-to-sequence (stream)
(write-sequence +type-id+ stream)
(write-sequence (osc::encode-int32 *synthdef-version*) stream)
(write-sequence (sc-osc::encode-int16 1) stream)
(write-sequence (make-pstring (name synthdef)) stream)
(write-sequence (sc-osc::encode-int16 (length (constants synthdef))) stream)
(dolist (const (constants synthdef))
(write-sequence (osc::encode-float32 const) stream))
(write-sequence (sc-osc::encode-int16 (length (controls synthdef))) stream)
(dolist (control (controls synthdef))
(write-sequence (osc::encode-float32 control) stream))
(write-sequence (sc-osc::encode-int16 (length (control-names synthdef))) stream)
(dolist (name (control-names synthdef))
(write-sequence (make-pstring (first name)) stream)
(write-sequence (sc-osc::encode-int16 (second name)) stream))
(write-sequence (sc-osc::encode-int16 (length (children synthdef))) stream)
(dolist (ugen (children synthdef))
(write-def-ugen-version1 ugen stream))
(write-sequence (sc-osc::encode-int16 0) stream)))
(defun to-byte-array-synthdef-2 (synthdef)
(flex:with-output-to-sequence (stream)
(write-sequence +type-id+ stream)
(write-sequence (osc::encode-int32 *synthdef-version*) stream)
(write-sequence (sc-osc::encode-int16 1) stream)
(write-sequence (make-pstring (name synthdef)) stream)
(write-sequence (osc::encode-int32 (length (constants synthdef))) stream)
(dolist (const (constants synthdef))
(write-sequence (osc::encode-float32 const) stream))
(write-sequence (osc::encode-int32 (length (controls synthdef))) stream)
(dolist (control (controls synthdef))
(write-sequence (osc::encode-float32 control) stream))
(write-sequence (osc::encode-int32 (length (control-names synthdef))) stream)
(dolist (name (control-names synthdef))
(write-sequence (make-pstring (first name)) stream)
(write-sequence (osc::encode-int32 (second name)) stream))
(write-sequence (osc::encode-int32 (length (children synthdef))) stream)
(dolist (ugen (children synthdef))
(write-def-ugen-version2 ugen stream))
(write-sequence (sc-osc::encode-int16 0) stream)))
| null | https://raw.githubusercontent.com/byulparan/cl-collider/d601c1b6ace8fb7cf6d1ee0862a85fd80441d1ab/synthdef.lisp | lisp | build --------------------------------------------------------------------------------------
default to full volume for embedded synths
avoid converting names of local bindings
======================================================================
====================================================================== |
(in-package #:sc)
(defclass synthdef ()
((name :initarg :name :accessor name)
(controls :initarg :controls :initform nil :accessor controls)
(named-controls :initform nil :accessor named-controls)
(control-names :initarg :control-names :initform nil :accessor control-names)
(control-ugen-count :accessor control-ugen-count :initform 0)
(children :initform nil :accessor children)
(constants :initform nil :accessor constants)
(max-local-bufs :initform nil :accessor max-local-bufs)
(available :initform nil :accessor available)
(width-first-ugens :initform nil :accessor width-first-ugens)
(rewrite-in-progress :initform nil :accessor rewrite-in-progress)))
(defmethod print-object ((c synthdef) stream)
(format stream "#<~s :name ~s>" 'synthdef (name c)))
(defmethod add-ugen ((synthdef synthdef) (ugen ugen))
(unless (rewrite-in-progress synthdef)
(setf (synth-index ugen) (length (children synthdef)))
(setf (width-first-antecedents ugen) (copy-list (width-first-ugens synthdef)))
(alexandria:appendf (children synthdef) (list ugen)))
ugen)
(defmethod replace-ugen ((synthdef synthdef) (a ugen) (b ugen))
(unless (typep b 'ugen) (error "REPLACE-UGEN requires a UGen."))
(setf (width-first-antecedents b) (width-first-antecedents a))
(setf (descendants b) (descendants a))
(setf (synth-index b) (synth-index a))
(setf (nth (position a (children synthdef)) (children synthdef)) b)
(loop for item in (children synthdef)
for i from 0
do (when item
(loop for input in (inputs item) for j from 0
do (when (eql input a)
(setf (nth j (inputs item)) b))))))
(defmethod check-inputs ((synthdef synthdef))
(dolist (ugen (children synthdef))
(funcall (check-fn ugen) ugen)))
(defmethod add-constant ((synthdef synthdef) (const single-float))
(unless (find const (constants synthdef))
(alexandria:appendf (constants synthdef) (list const))))
(defmethod add-constant ((synthdef synthdef) (const t))
(error "can't available input: ~a" const))
(defmethod collect-constants ((synthdef synthdef))
(dolist (ugen (children synthdef))
(collect-constants ugen)))
(defmethod init-topo-sort ((synthdef synthdef))
(setf (available synthdef) nil)
(dolist (ugen (children synthdef))
(setf (antecedents ugen) nil (descendants ugen) nil))
(dolist (ugen (children synthdef))
(init-topo-sort ugen))
(dolist (ugen (reverse (children synthdef)))
(setf (descendants ugen) (sort (descendants ugen) #'< :key #'synth-index))
(make-available ugen)))
(defun topo-logical-sort (synthdef)
(let ((out-stack nil))
(init-topo-sort synthdef)
(loop while (> (length (available synthdef)) 0) do
(setf out-stack (schedule (pop (available synthdef)) out-stack)))
(setf (children synthdef) (nreverse out-stack))))
(defun index-ugens (synthdef)
(loop for ugen in (children synthdef)
for i from 0
do (setf (synth-index ugen) i)))
(defmethod optimize-graph ((synthdef synthdef))
(let ((old-size (length (children synthdef))))
(init-topo-sort synthdef)
(setf (rewrite-in-progress synthdef) t)
(dolist (ugen (children synthdef))
(optimize-graph ugen))
(setf (rewrite-in-progress synthdef) nil)
(unless (= old-size (length (children synthdef)))
(index-ugens synthdef))))
(defmethod build-synthdef ((synthdef synthdef))
(check-inputs synthdef)
(optimize-graph synthdef)
(collect-constants synthdef)
(topo-logical-sort synthdef)
(index-ugens synthdef)
synthdef)
(defun write-synthdef-file (name encoded-synthdef)
(let ((path (merge-pathnames (make-pathname :name name :type "scsyndef")
(full-pathname *sc-synthdefs-path*))))
(with-open-file (stream path :direction :output
:if-exists :supersede
:element-type '(unsigned-byte 8))
(write-sequence encoded-synthdef stream))
(namestring path)))
(defmethod load-synthdef ((synthdef synthdef) node &optional (completion-message 0))
(assert (is-local-p *s*) nil "Server ~a is not a local server, so it cannot load synthdefs from a file." *s*)
(message-distribute node (list "/d_load" (write-synthdef-file (name synthdef) (encode-synthdef synthdef)) completion-message) *s*))
(defmethod recv-synthdef ((synthdef synthdef) node &optional (completion-message 0))
(let* ((name (name synthdef))
(data (encode-synthdef synthdef)))
(cond ((>= usocket:+max-datagram-packet-size+ (length data)) (message-distribute node (list "/d_recv" data completion-message) *s*))
((is-local-p *s*) (progn (format t "~&~a too big for sending. Retrying via synthdef file.~%" name)
(load-synthdef synthdef node completion-message)))
(t (error "Synthdef ~a is too big to send." name)))))
(defclass control (multiout-ugen) ())
(defmethod new1 ((ugen control) &rest inputs)
(setf (inputs ugen) (third inputs))
(setf (channels ugen) (length (alexandria:flatten (first inputs))))
(setf (special-index ugen) (second inputs))
(add-to-synth ugen)
(let ((i 0))
(loop for control in (first inputs)
collect (unbubble (loop repeat (length (alexandria:ensure-list control))
collect (make-instance 'proxy-output
:source ugen
:rate (rate ugen)
:signal-range (signal-range ugen)
:output-index i)
do (incf i))))))
(defun add-controls (rate lag-p controls)
(ugen-new (if lag-p "LagControl" "Control")
rate 'control #'identity :bipolar (mapcar #'second controls) (control-ugen-count *synthdef*)
(alexandria:flatten
(when lag-p
(mapcar (lambda (ctrl)
(let ((lag-value (alexandria:if-let ((value (getf ctrl :lag))) value 0))
(ctrl-value (second ctrl)))
(when (and (consp lag-value) (numberp ctrl-value))
(error "Single control with multiple lag values is not supported."))
(when (and (consp lag-value) (consp ctrl-value) (/= (length lag-value) (length ctrl-value)))
(error "Number of control values does not match the number of lag values."))
(when (and (consp ctrl-value) (atom lag-value))
(setf lag-value (make-list (length ctrl-value) :initial-element lag-value)))
lag-value))
controls)))))
(defun make-control (params rate)
(assert (and (every #'stringp (mapcar #'first params))
(every #'numberp (alexandria:flatten (mapcar #'second params)))
(every #'(lambda (rate) (or (not rate) (find rate (list :ar :tr :lag)))) (mapcar #'third params))))
(labels ((make-ctrl (params)
(dolist (controls (mapcar #'second params))
(dolist (control-val (alexandria:ensure-list controls))
(alexandria:appendf (controls *synthdef*) (list (floatfy control-val)))))))
(let* ((trig-controls (remove-if-not #'(lambda (p) (eql :tr (third p))) params))
(audio-controls (remove-if-not #'(lambda (p) (eql :ar (third p))) params))
(controls (remove-if #'(lambda (p) (find (third p) (list :tr :ar))) params))
(lag-p (some #'(lambda (c) (getf c :lag)) controls)))
(alexandria:appendf (control-names *synthdef*)
(loop with control-names = (mapcar #'first (control-names *synthdef*))
for controls in (append trig-controls audio-controls controls)
and index = (control-ugen-count *synthdef*) then (incf index (length (alexandria:ensure-list (second controls))))
do (when (find (first controls) control-names :test #'string=)
(error "Duplicate control name: ~s" (first controls)))
collect (list (first controls) index)))
(make-ctrl trig-controls) (make-ctrl audio-controls) (make-ctrl controls)
(append
(when trig-controls
(prog1 (ugen-new "TrigControl" rate 'control #'identity :bipolar
(mapcar #'second trig-controls)
(control-ugen-count *synthdef*))
(incf (control-ugen-count *synthdef*) (length (alexandria:flatten (mapcar #'second trig-controls))))))
(when audio-controls
(prog1 (ugen-new "AudioControl" :audio 'control #'identity :bipolar
(mapcar #'second audio-controls)
(control-ugen-count *synthdef*))
(incf (control-ugen-count *synthdef*) (length (alexandria:flatten (mapcar #'second audio-controls))))))
(when controls
(prog1 (add-controls rate lag-p controls)
(incf (control-ugen-count *synthdef*) (length (alexandria:flatten (mapcar #'second controls))))))))))
(defmacro with-controls (params &body body)
(if params `(destructuring-bind ,(mapcar #'first (append
(remove-if-not (lambda (a) (eql :tr (third a))) params)
(remove-if-not (lambda (a) (eql :ar (third a))) params)
(remove-if (lambda (a) (or (eql :tr (third a)) (eql :ar (third a)))) params)))
(make-control (list ,@(mapcar (lambda (a)
(cons 'list (list (string-downcase (first a)) `(floatfy ,(second a)) (third a) (fourth a))))
params))
:control)
,@body)
`(progn ,@body)))
(defun named-control (name rate &optional value lag)
"A NamedControl directly combines a ControlName and a Control UGen conveniently. Also this makes it safe even if several identical controls exist"
(when (and (consp lag) (find 0 lag :test #'equalp)) (error "'lagTime' has bad input"))
(when (eql rate :tr) (setf lag nil))
(let* ((name (string-downcase name))
(lag (if (and (numberp lag) (zerop lag)) nil lag))
(rate (ecase rate
(:kr :control)
(:ar :audio)
(:tr :trig)))
(reg-control (cadr (assoc name (named-controls *synthdef*) :test #'string=))))
(if reg-control (let* ((ugen (getf reg-control :ugen))
(fixed-lag (getf reg-control :fixed-lag)))
(assert (eql rate (getf reg-control :rate)) nil
"NamedControl: cannot have more than one set of rates in the same control.")
(when value
(assert (equalp (alexandria:ensure-list (floatfy value))
(getf reg-control :value)) nil
"NamedControl: cannot have more than one set of default values in the same control."))
(when (and lag fixed-lag)
(assert (equalp (alexandria:ensure-list lag) (getf reg-control :lag)) nil
"NamedControl: cannot have more than one set of fixed lag values in the same control."))
(cond ((and lag (not fixed-lag) (equal rate :control)) (lag.kr ugen lag))
((and lag (not fixed-lag) (equal rate :audio)) (lag.ar ugen lag))
(t ugen)))
(let* ((fixed-lag (and lag (every #'numberp (alexandria:ensure-list lag)))))
(when (and (eql rate :control) value fixed-lag)
(when (and (numberp value) (consp lag) (/= 1 (length lag)))
(error "Single control with multiple lag values is not supported."))
(when (and (consp value) (consp lag) (/= (length lag) (length value)))
(error "Number of control values does not match the number of lag values."))
(when (and (consp value) (atom lag))
(setf lag (make-list (length value) :initial-element lag))))
(let* ((value (alexandria:ensure-list (floatfy (if value value 0.0))))
(lag (alexandria:ensure-list lag))
(lag (if fixed-lag (subseq lag 0 (length value)) lag))
(ugen-name (ecase rate
(:control (if fixed-lag "LagControl" "Control"))
(:audio "AudioControl")
(:trig "TrigControl")))
(ugen (unbubble (ugen-new ugen-name (if (eql rate :trig) :control rate) 'control #'identity :bipolar
value (control-ugen-count *synthdef*) lag))))
(alexandria:appendf (controls *synthdef*) value)
(alexandria:appendf (control-names *synthdef*) (list (list name (control-ugen-count *synthdef*))))
(incf (control-ugen-count *synthdef*) (length value))
(push (list name (list :rate rate :value value :lag lag :fixed-lag fixed-lag :ugen ugen)) (named-controls *synthdef*))
(when (and (eql rate :audio) lag) (setf ugen (lag.ar ugen lag)))
(when (and (eql rate :control) lag (not fixed-lag)) (setf ugen (lag.kr ugen lag)))
(pushnew (list name (unbubble value)) (synthdef-metadata (name *synthdef*) :controls))
ugen)))))
(defun kr (name &optional value lag)
"shortcut for named-control(control rate)"
(named-control name :kr value lag))
(defvar *synthdef-function-table* '((abs sc::abs~)
(floor sc::floor~)
(ceil sc::ceil~)
(sqrt sc::sqrt~)
(exp sc::exp~)
(sin sc::sin~)
(cos sc::cos~)
(tan sc::tan~)
(tanh sc::tanh~)
(expt sc::expt~)
(+ sc::+~)
(- sc::-~)
(* sc::*~)
(/ sc::/~)
(mod sc::mod~)
(round sc::round~)
(< sc::<~)
(> sc::>~)
(<= sc::<=~)
(>= sc::>=~)
(max sc::max~)
(min sc::min~)
(logand sc::logand~)
(logior sc::logior~)
(ash sc::ash~))
"Table mapping function names to their synthdef-compatible equivalents. Used by `convert-code' and `synthdef-equivalent-function' to convert lisp functions in synthdef bodies to ugen functions.")
(defun synthdef-equivalent-function (function)
"Get the synthdef-compatible equivalent of FUNCTION from `*synthdef-function-table*'. If FUNCTION is not found in the table, return it unchanged."
(or (cadr (assoc function *synthdef-function-table*))
function))
(defun (setf synthdef-equivalent-function) (value function)
"Set the synthdef-compatible equivalent of FUNCTION to VALUE in `*synthdef-function-table*'. If VALUE is nil, remove the entry for FUNCTION from the table."
(if value
(push (list function value) *synthdef-function-table*)
(alexandria:removef *synthdef-function-table* function :key #'car)))
(defun synthdef-embeddable-body (synth args)
"Make an \"embeddable\" synthdef body, to allow `synth' to be used inside `synthdef'."
(let* ((body (synthdef-metadata synth :body))
(args-keys (loop :for (k v) :on args :by #'cddr :collect k))
(unprovided-args (append
(loop :for (k v) :on args :by #'cddr
:for rk := (intern (symbol-name k))
:unless (eql rk v)
:collect (list rk v))
(mapcan (lambda (c)
(unless (or (string= (car c) 'out)
(member (car c) args-keys :test #'string=))
(list (if (string= (car c) 'amp)
c))))
(synthdef-metadata synth :controls)))))
(labels ((parse-item (body)
(if (listp body)
(if (member (car body) (list 'out.ar 'out.kr 'replace-out.ar 'replace-out.kr 'x-out.ar 'x-out.kr 'scope-out.ar 'scope-out.kr 'scope-out2.ar 'scope-out2.kr))
(caddr body)
(mapcar #'parse-item body))
body)))
`(let (,@unprovided-args)
,@(parse-item body)))))
(defun convert-code (form &optional head)
(cond ((null form) nil)
((atom form) (if head
(synthdef-equivalent-function form)
form))
`(,(car form) ,(mapcar (lambda (item)
(if (atom item)
item
`(,(car item) ,@(convert-code (cdr item)))))
(cadr form))
,@(convert-code (cddr form))))
((eql (car form) 'destructuring-bind)
`(,(car form) ,(cadr form) ,(caddr form)
,@(convert-code (cdddr form))))
((eql (car form) 'synth)
(let ((synth (cadr form))
(args (cddr form)))
(convert-code
(synthdef-embeddable-body (if (and (listp synth)
(eql 'quote (car synth)))
(cadr synth)
synth)
args))))
(t (cons (convert-code (car form) t)
(mapcar #'convert-code (cdr form))))))
(defparameter *synth-definition-mode* :recv)
(defparameter *synthdef-metadata* (make-hash-table)
"Metadata for each synthdef, such as its name, controls, body, etc.")
(defun synthdef-metadata (synth &optional key)
"Get metadata about the synthdef with the name of SYNTH. When KEY is provided, return that specific item from the metadata (i.e. controls, body, etc)."
(let ((metadata (gethash (as-keyword (if (typep synth 'node) (name synth) synth)) *synthdef-metadata*)))
(if key
(getf metadata (as-keyword key))
metadata)))
#-ecl
(uiop:with-deprecation (:style-warning)
(defun get-synthdef-metadata (synth &optional key)
"Deprecated alias for `synthdef-metadata'."
(synthdef-metadata synth key)))
(defun (setf synthdef-metadata) (value synth key)
"Set a metadatum for the synthdef SYNTH."
(setf (getf (gethash (as-keyword synth) *synthdef-metadata*) (as-keyword key)) value))
#-ecl
(uiop:with-deprecation (:style-warning)
(defun set-synthdef-metadata (synth key value)
"Deprecated alias for `(setf synthdef-metadata)'."
(setf (synthdef-metadata synth key) value)))
(defmacro defsynth (name params &body body)
(setf params (mapcar (lambda (param) (if (consp param) param (list param 0.0))) params))
(alexandria:with-gensyms (synthdef)
`(progn
(setf (synthdef-metadata ',name :name) ',name
(synthdef-metadata ',name :controls) (mapcar (lambda (param) (append (list (car param)) (cdr param)))
',params)
(synthdef-metadata ',name :body) ',body)
(let* ((,synthdef (make-instance 'synthdef :name ,(string-downcase name)))
(*synthdef* ,synthdef))
(with-controls (,@params)
,@(convert-code body)
(build-synthdef ,synthdef)
(when (and *s* (boot-p *s*))
(ecase *synth-definition-mode*
(:recv (recv-synthdef ,synthdef nil))
(:load (load-synthdef ,synthdef nil)))
(sync))
,synthdef)))))
(defvar *temp-synth-name* "temp-synth")
(defmacro play (body &key id (out-bus 0) (gain 1.0) (lag 1.0) (fade 0.02) (to 1) (pos :head))
(alexandria:with-gensyms (synthdef result dt buses gate gain-sym lag-sym
start-val env node-id name fade-time outlets seqs node)
`(let* ((,name *temp-synth-name*)
(,fade-time nil)
(,synthdef (make-instance 'synthdef :name ,name))
(*synthdef* ,synthdef))
(labels ((,seqs (indx lists)
(nth (mod indx (length lists)) lists))
(,outlets (f bus result gain lag)
(if (numberp gain) (funcall f bus (*~ result (var-lag.kr gain lag)))
(loop with bus = (alexandria:ensure-list bus)
with gain = (alexandria:ensure-list gain)
for i from 0 below (max (length bus) (length gain))
do (funcall f (,seqs i bus) (*~ (var-lag.kr (,seqs i gain) lag) result))))))
(let ((,result ,(convert-code body)))
(unless (eql :scalar (rate ,result))
(setf ,fade-time ,fade)
(destructuring-bind (,dt ,buses ,gate ,gain-sym ,lag-sym)
(make-control (list (list "fade" ,fade) (list "out-bus" ,out-bus)
(list "gate" 1.0) (list "gain" ,gain) (list "lag" ,lag)) :control)
(let* ((,start-val (<=~ ,dt 0))
(,env (env-gen.kr
(env (list ,start-val 1 0) (list 1,1) :lin 1) :gate ,gate :level-scale 1 :level-bias 0.0
:time-scale ,dt :act :free)))
(setf ,result (*~ ,env ,result))
(cond ((eql :audio (rate ,result)) (,outlets 'out.ar ,buses ,result ,gain-sym ,lag-sym))
((eql :control (rate ,result)) (,outlets 'out.kr ,buses ,result ,gain-sym ,lag-sym))
(t (error "Play: ~a is not a UGen." ,result))))))))
(build-synthdef ,synthdef)
(let* ((,node-id (or ,id (get-next-id *s*)))
(,node (make-instance 'node :server *s* :id ,node-id :name *temp-synth-name* :pos ,pos :to ,to
:meta (list :fade-time ,fade-time))))
(recv-synthdef ,synthdef ,node (apply 'sc-osc::encode-message (make-synth-msg *s* ,name ,node-id ,to ,pos)))
(sync)
,node))))
(defun synth (name &rest args)
"Start a synth by name."
(let* ((name-string (string-downcase (symbol-name name)))
(next-id (or (getf args :id) (get-next-id *s*)))
(to (or (getf args :to) 1))
(pos (or (getf args :pos) :head))
(new-synth (make-instance 'node :server *s* :id next-id :name name-string :pos pos :to to))
(args (loop :for (arg val) :on args :by #'cddr
:unless (member arg '(:id :to :pos))
:append (list (string-downcase arg) (floatfy val)))))
(message-distribute new-synth
(apply #'make-synth-msg *s* name-string next-id to pos args)
*s*)))
(defun get-controls-list (form)
"Scan FORM for (with-controls ...) and return the list of controls if it exists, or NIL otherwise."
(cond ((null form) nil)
((listp form)
(if (eq (car form) 'with-controls)
(cadr form)
(loop :for i :in (cdr form)
:for res = (get-controls-list i)
:unless (null res)
:return res)))))
(defmacro proxy (key body &key id (gain 1.0) (fade 0.5) (pos :head) (to 1) (out-bus 0))
(alexandria:with-gensyms (node node-alive-p d-key)
`(let* ((,node (gethash ,key (node-proxy-table *s*)))
(,node-alive-p (when ,node (if (typep *s* 'nrt-server) t (is-playing-p ,node)))))
,(if body
(alexandria:once-only (id fade)
`(labels ((clear-node ()
(when ,node-alive-p
(if (getf (meta ,node) :fade-time) (ctrl ,node :gate 0 :fade ,fade)
(free ,node)))))
(when (and (typep *s* 'rt-server) (is-playing-p ,id))
(error "already running id ~d~%" ,id))
(let ((,d-key (string-downcase ,key)))
(setf (synthdef-metadata ,d-key :name) ,d-key)
(let ((controls (get-controls-list ',body)))
(setf (synthdef-metadata ,d-key :controls) (mapcar (lambda (param) (append (list (car param)) (cdr param))) controls)))
(setf (synthdef-metadata ,d-key :body) ',body))
(let ((*temp-synth-name* (string-downcase ,key)))
(prog1 (setf (gethash ,key (node-proxy-table *s*))
(play ,body :id ,id :out-bus ,out-bus :fade ,fade :to ,to :pos ,pos :gain ,gain))
(clear-node)))))
`(when ,node-alive-p
(free ,node))))))
(defun proxy-ctrl (key &rest params &key &allow-other-keys)
(let* ((node (gethash key (node-proxy-table *s*)))
(node-alive-p (and node (if (typep *s* 'nrt-server) t (is-playing-p node)))))
(assert node nil "can't find proxy ~a" key)
(let* ((fade-time (getf (meta node) :fade-time)))
(flet ((clear-node ()
(if fade-time (ctrl node :gate 0 :fade (or (getf params :fade) fade-time))
(free node))))
(let* ((new-node (apply #'synth key params)))
(setf (meta new-node) (list :fade-time fade-time))
(prog1
(setf (gethash key (node-proxy-table *s*)) new-node)
(when node-alive-p
(clear-node))))))))
build to
(defparameter +type-id+ (map '(vector (unsigned-byte 8)) #'char-code "SCgf"))
(defparameter *synthdef-version* 2)
(defun encode-synthdef (synthdef)
(ecase *synthdef-version*
(1 (to-byte-array-synthdef-1 synthdef))
(2 (to-byte-array-synthdef-2 synthdef))))
(defun to-byte-array-synthdef-1 (synthdef)
(flex:with-output-to-sequence (stream)
(write-sequence +type-id+ stream)
(write-sequence (osc::encode-int32 *synthdef-version*) stream)
(write-sequence (sc-osc::encode-int16 1) stream)
(write-sequence (make-pstring (name synthdef)) stream)
(write-sequence (sc-osc::encode-int16 (length (constants synthdef))) stream)
(dolist (const (constants synthdef))
(write-sequence (osc::encode-float32 const) stream))
(write-sequence (sc-osc::encode-int16 (length (controls synthdef))) stream)
(dolist (control (controls synthdef))
(write-sequence (osc::encode-float32 control) stream))
(write-sequence (sc-osc::encode-int16 (length (control-names synthdef))) stream)
(dolist (name (control-names synthdef))
(write-sequence (make-pstring (first name)) stream)
(write-sequence (sc-osc::encode-int16 (second name)) stream))
(write-sequence (sc-osc::encode-int16 (length (children synthdef))) stream)
(dolist (ugen (children synthdef))
(write-def-ugen-version1 ugen stream))
(write-sequence (sc-osc::encode-int16 0) stream)))
(defun to-byte-array-synthdef-2 (synthdef)
(flex:with-output-to-sequence (stream)
(write-sequence +type-id+ stream)
(write-sequence (osc::encode-int32 *synthdef-version*) stream)
(write-sequence (sc-osc::encode-int16 1) stream)
(write-sequence (make-pstring (name synthdef)) stream)
(write-sequence (osc::encode-int32 (length (constants synthdef))) stream)
(dolist (const (constants synthdef))
(write-sequence (osc::encode-float32 const) stream))
(write-sequence (osc::encode-int32 (length (controls synthdef))) stream)
(dolist (control (controls synthdef))
(write-sequence (osc::encode-float32 control) stream))
(write-sequence (osc::encode-int32 (length (control-names synthdef))) stream)
(dolist (name (control-names synthdef))
(write-sequence (make-pstring (first name)) stream)
(write-sequence (osc::encode-int32 (second name)) stream))
(write-sequence (osc::encode-int32 (length (children synthdef))) stream)
(dolist (ugen (children synthdef))
(write-def-ugen-version2 ugen stream))
(write-sequence (sc-osc::encode-int16 0) stream)))
|
f2c3d040f1a11996a377d1bfdb2bcdb23f0a1a658198e8fee40bb49c65d1ea3c | yrashk/erlang | orddict.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online 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.
%%
%% %CopyrightEnd%
%%
-module(orddict).
%% Standard interface.
-export([new/0,is_key/2,to_list/1,from_list/1,size/1]).
-export([fetch/2,find/2,fetch_keys/1,erase/2]).
-export([store/3,append/3,append_list/3,update/3,update/4,update_counter/3]).
-export([fold/3,map/2,filter/2,merge/3]).
%%---------------------------------------------------------------------------
-type orddict() :: [{term(), term()}].
%%---------------------------------------------------------------------------
-spec new() -> orddict().
new() -> [].
-spec is_key(Key::term(), Dictionary::orddict()) -> bool().
is_key(Key, [{K,_}|_]) when Key < K -> false;
is_key(Key, [{K,_}|Dict]) when Key > K -> is_key(Key, Dict);
is_key(_Key, [{_K,_Val}|_]) -> true; %Key == K
is_key(_, []) -> false.
-spec to_list(orddict()) -> [{term(), term()}].
to_list(Dict) -> Dict.
-spec from_list([{term(), term()}]) -> orddict().
from_list(Pairs) ->
lists:foldl(fun ({K,V}, D) -> store(K, V, D) end, [], Pairs).
-spec size(orddict()) -> non_neg_integer().
size(D) -> length(D).
-spec fetch(Key::term(), Dictionary::orddict()) -> term().
fetch(Key, [{K,_}|D]) when Key > K -> fetch(Key, D);
fetch(Key, [{K,Value}|_]) when Key == K -> Value.
-spec find(Key::term(), Dictionary::orddict()) -> {'ok', term()} | 'error'.
find(Key, [{K,_}|_]) when Key < K -> error;
find(Key, [{K,_}|D]) when Key > K -> find(Key, D);
find(_Key, [{_K,Value}|_]) -> {ok,Value}; %Key == K
find(_, []) -> error.
-spec fetch_keys(Dictionary::orddict()) -> [term()].
fetch_keys([{Key,_}|Dict]) ->
[Key|fetch_keys(Dict)];
fetch_keys([]) -> [].
-spec erase(Key::term(), Dictionary::orddict()) -> orddict().
erase(Key, [{K,_}=E|Dict]) when Key < K -> [E|Dict];
erase(Key, [{K,_}=E|Dict]) when Key > K ->
[E|erase(Key, Dict)];
erase(_Key, [{_K,_Val}|Dict]) -> Dict; %Key == K
erase(_, []) -> [].
-spec store(Key::term(), Value::term(), Dictionary::orddict()) -> orddict().
store(Key, New, [{K,_}=E|Dict]) when Key < K ->
[{Key,New},E|Dict];
store(Key, New, [{K,_}=E|Dict]) when Key > K ->
[E|store(Key, New, Dict)];
store(Key, New, [{_K,_Old}|Dict]) -> %Key == K
[{Key,New}|Dict];
store(Key, New, []) -> [{Key,New}].
-spec append(Key::term(), Value::term(), Dictionary::orddict()) -> orddict().
append(Key, New, [{K,_}=E|Dict]) when Key < K ->
[{Key,[New]},E|Dict];
append(Key, New, [{K,_}=E|Dict]) when Key > K ->
[E|append(Key, New, Dict)];
append(Key, New, [{_K,Old}|Dict]) -> %Key == K
[{Key,Old ++ [New]}|Dict];
append(Key, New, []) -> [{Key,[New]}].
-spec append_list(Key::term(), ValueList::[term()], orddict()) -> orddict().
append_list(Key, NewList, [{K,_}=E|Dict]) when Key < K ->
[{Key,NewList},E|Dict];
append_list(Key, NewList, [{K,_}=E|Dict]) when Key > K ->
[E|append_list(Key, NewList, Dict)];
append_list(Key, NewList, [{_K,Old}|Dict]) -> %Key == K
[{Key,Old ++ NewList}|Dict];
append_list(Key, NewList, []) ->
[{Key,NewList}].
-spec update(Key::term(), Fun::fun((term()) -> term()), orddict()) -> orddict().
update(Key, Fun, [{K,_}=E|Dict]) when Key > K ->
[E|update(Key, Fun, Dict)];
update(Key, Fun, [{K,Val}|Dict]) when Key == K ->
[{Key,Fun(Val)}|Dict].
-spec update(term(), fun((term()) -> term()), term(), orddict()) -> orddict().
update(Key, _, Init, [{K,_}=E|Dict]) when Key < K ->
[{Key,Init},E|Dict];
update(Key, Fun, Init, [{K,_}=E|Dict]) when Key > K ->
[E|update(Key, Fun, Init, Dict)];
update(Key, Fun, _Init, [{_K,Val}|Dict]) -> %Key == K
[{Key,Fun(Val)}|Dict];
update(Key, _, Init, []) -> [{Key,Init}].
-spec update_counter(Key::term(), Incr::number(), orddict()) -> orddict().
update_counter(Key, Incr, [{K,_}=E|Dict]) when Key < K ->
[{Key,Incr},E|Dict];
update_counter(Key, Incr, [{K,_}=E|Dict]) when Key > K ->
[E|update_counter(Key, Incr, Dict)];
update_counter(Key, Incr, [{_K,Val}|Dict]) -> %Key == K
[{Key,Val+Incr}|Dict];
update_counter(Key, Incr, []) -> [{Key,Incr}].
-spec fold(fun((term(),term(),term()) -> term()), term(), orddict()) -> term().
fold(F, Acc, [{Key,Val}|D]) ->
fold(F, F(Key, Val, Acc), D);
fold(F, Acc, []) when is_function(F, 3) -> Acc.
-spec map(fun((term(), term()) -> term()), orddict()) -> orddict().
map(F, [{Key,Val}|D]) ->
[{Key,F(Key, Val)}|map(F, D)];
map(F, []) when is_function(F, 2) -> [].
-spec filter(fun((term(), term()) -> term()), orddict()) -> orddict().
filter(F, [{Key,Val}=E|D]) ->
case F(Key, Val) of
true -> [E|filter(F, D)];
false -> filter(F, D)
end;
filter(F, []) when is_function(F, 2) -> [].
-spec merge(fun((term(), term(), term()) -> term()), orddict(), orddict()) ->
orddict().
merge(F, [{K1,_}=E1|D1], [{K2,_}=E2|D2]) when K1 < K2 ->
[E1|merge(F, D1, [E2|D2])];
merge(F, [{K1,_}=E1|D1], [{K2,_}=E2|D2]) when K1 > K2 ->
[E2|merge(F, [E1|D1], D2)];
merge(F, [{K1,V1}|D1], [{_K2,V2}|D2]) -> %K1 == K2
[{K1,F(K1, V1, V2)}|merge(F, D1, D2)];
merge(F, [], D2) when is_function(F, 3) -> D2;
merge(F, D1, []) when is_function(F, 3) -> D1.
| null | https://raw.githubusercontent.com/yrashk/erlang/e1282325ed75e52a98d58f5bd9fb0fa27896173f/lib/stdlib/src/orddict.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online 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.
%CopyrightEnd%
Standard interface.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Key == K
Key == K
Key == K
Key == K
Key == K
Key == K
Key == K
Key == K
K1 == K2 | Copyright Ericsson AB 1996 - 2009 . All Rights Reserved .
The contents of this file are subject to the Erlang 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 "
-module(orddict).
-export([new/0,is_key/2,to_list/1,from_list/1,size/1]).
-export([fetch/2,find/2,fetch_keys/1,erase/2]).
-export([store/3,append/3,append_list/3,update/3,update/4,update_counter/3]).
-export([fold/3,map/2,filter/2,merge/3]).
-type orddict() :: [{term(), term()}].
-spec new() -> orddict().
new() -> [].
-spec is_key(Key::term(), Dictionary::orddict()) -> bool().
is_key(Key, [{K,_}|_]) when Key < K -> false;
is_key(Key, [{K,_}|Dict]) when Key > K -> is_key(Key, Dict);
is_key(_, []) -> false.
-spec to_list(orddict()) -> [{term(), term()}].
to_list(Dict) -> Dict.
-spec from_list([{term(), term()}]) -> orddict().
from_list(Pairs) ->
lists:foldl(fun ({K,V}, D) -> store(K, V, D) end, [], Pairs).
-spec size(orddict()) -> non_neg_integer().
size(D) -> length(D).
-spec fetch(Key::term(), Dictionary::orddict()) -> term().
fetch(Key, [{K,_}|D]) when Key > K -> fetch(Key, D);
fetch(Key, [{K,Value}|_]) when Key == K -> Value.
-spec find(Key::term(), Dictionary::orddict()) -> {'ok', term()} | 'error'.
find(Key, [{K,_}|_]) when Key < K -> error;
find(Key, [{K,_}|D]) when Key > K -> find(Key, D);
find(_, []) -> error.
-spec fetch_keys(Dictionary::orddict()) -> [term()].
fetch_keys([{Key,_}|Dict]) ->
[Key|fetch_keys(Dict)];
fetch_keys([]) -> [].
-spec erase(Key::term(), Dictionary::orddict()) -> orddict().
erase(Key, [{K,_}=E|Dict]) when Key < K -> [E|Dict];
erase(Key, [{K,_}=E|Dict]) when Key > K ->
[E|erase(Key, Dict)];
erase(_, []) -> [].
-spec store(Key::term(), Value::term(), Dictionary::orddict()) -> orddict().
store(Key, New, [{K,_}=E|Dict]) when Key < K ->
[{Key,New},E|Dict];
store(Key, New, [{K,_}=E|Dict]) when Key > K ->
[E|store(Key, New, Dict)];
[{Key,New}|Dict];
store(Key, New, []) -> [{Key,New}].
-spec append(Key::term(), Value::term(), Dictionary::orddict()) -> orddict().
append(Key, New, [{K,_}=E|Dict]) when Key < K ->
[{Key,[New]},E|Dict];
append(Key, New, [{K,_}=E|Dict]) when Key > K ->
[E|append(Key, New, Dict)];
[{Key,Old ++ [New]}|Dict];
append(Key, New, []) -> [{Key,[New]}].
-spec append_list(Key::term(), ValueList::[term()], orddict()) -> orddict().
append_list(Key, NewList, [{K,_}=E|Dict]) when Key < K ->
[{Key,NewList},E|Dict];
append_list(Key, NewList, [{K,_}=E|Dict]) when Key > K ->
[E|append_list(Key, NewList, Dict)];
[{Key,Old ++ NewList}|Dict];
append_list(Key, NewList, []) ->
[{Key,NewList}].
-spec update(Key::term(), Fun::fun((term()) -> term()), orddict()) -> orddict().
update(Key, Fun, [{K,_}=E|Dict]) when Key > K ->
[E|update(Key, Fun, Dict)];
update(Key, Fun, [{K,Val}|Dict]) when Key == K ->
[{Key,Fun(Val)}|Dict].
-spec update(term(), fun((term()) -> term()), term(), orddict()) -> orddict().
update(Key, _, Init, [{K,_}=E|Dict]) when Key < K ->
[{Key,Init},E|Dict];
update(Key, Fun, Init, [{K,_}=E|Dict]) when Key > K ->
[E|update(Key, Fun, Init, Dict)];
[{Key,Fun(Val)}|Dict];
update(Key, _, Init, []) -> [{Key,Init}].
-spec update_counter(Key::term(), Incr::number(), orddict()) -> orddict().
update_counter(Key, Incr, [{K,_}=E|Dict]) when Key < K ->
[{Key,Incr},E|Dict];
update_counter(Key, Incr, [{K,_}=E|Dict]) when Key > K ->
[E|update_counter(Key, Incr, Dict)];
[{Key,Val+Incr}|Dict];
update_counter(Key, Incr, []) -> [{Key,Incr}].
-spec fold(fun((term(),term(),term()) -> term()), term(), orddict()) -> term().
fold(F, Acc, [{Key,Val}|D]) ->
fold(F, F(Key, Val, Acc), D);
fold(F, Acc, []) when is_function(F, 3) -> Acc.
-spec map(fun((term(), term()) -> term()), orddict()) -> orddict().
map(F, [{Key,Val}|D]) ->
[{Key,F(Key, Val)}|map(F, D)];
map(F, []) when is_function(F, 2) -> [].
-spec filter(fun((term(), term()) -> term()), orddict()) -> orddict().
filter(F, [{Key,Val}=E|D]) ->
case F(Key, Val) of
true -> [E|filter(F, D)];
false -> filter(F, D)
end;
filter(F, []) when is_function(F, 2) -> [].
-spec merge(fun((term(), term(), term()) -> term()), orddict(), orddict()) ->
orddict().
merge(F, [{K1,_}=E1|D1], [{K2,_}=E2|D2]) when K1 < K2 ->
[E1|merge(F, D1, [E2|D2])];
merge(F, [{K1,_}=E1|D1], [{K2,_}=E2|D2]) when K1 > K2 ->
[E2|merge(F, [E1|D1], D2)];
[{K1,F(K1, V1, V2)}|merge(F, D1, D2)];
merge(F, [], D2) when is_function(F, 3) -> D2;
merge(F, D1, []) when is_function(F, 3) -> D1.
|
1695268466785b2cd68150d636c3601b246f63007645f8ed584bd630680a0b02 | ChrisPenner/rasa | StatusBar.hs | {-# language
OverloadedStrings
#-}
module Rasa.Ext.Views.Internal.StatusBar
( getTopStatusBar
, getBottomStatusBar
, addTopStatus
, addBottomStatus
) where
import Rasa.Ext
import Rasa.Ext.Views.Internal.AnyRenderable
import Data.List
import Data.Maybe
data GetTopStatusBar = GetTopStatusBar
data GetBottomStatusBar = GetBottomStatusBar
data StatusBar = StatusBar [AnyRenderable]
| Returns a for a given buffer
getTopStatusBar :: BufAction StatusBar
getTopStatusBar = StatusBar <$> dispatchBufEvent GetTopStatusBar
| Returns a for a given buffer
getBottomStatusBar :: BufAction StatusBar
getBottomStatusBar = StatusBar <$> dispatchBufEvent GetBottomStatusBar
| This registers a ' BufAction ' which results in a renderable and runs it
at render time to add the resulting ' ' to the status bar .
addTopStatus :: Renderable r => BufAction r -> BufAction ListenerId
addTopStatus bufAction = addBufListener (const (toRenderList <$> bufAction) :: GetTopStatusBar -> BufAction [AnyRenderable])
where toRenderList x = [AnyRenderable x]
addBottomStatus :: Renderable r => BufAction r -> BufAction ListenerId
addBottomStatus bufAction = addBufListener (const (toRenderList <$> bufAction) :: GetBottomStatusBar -> BufAction [AnyRenderable])
where toRenderList x = [AnyRenderable x]
instance Renderable StatusBar where
render width _ scrollAmt (StatusBar chunks) = do
parts <- traverse (render eachWidth 1 scrollAmt) chunks
return . Just . mconcat . intersperse (styleText " | " (fg Red)) . catMaybes $ parts
where
num = length chunks
eachWidth = width `div` num
| null | https://raw.githubusercontent.com/ChrisPenner/rasa/a2680324849088ee92f063fab091de21c4c2c086/rasa-ext-views/src/Rasa/Ext/Views/Internal/StatusBar.hs | haskell | # language
OverloadedStrings
# | module Rasa.Ext.Views.Internal.StatusBar
( getTopStatusBar
, getBottomStatusBar
, addTopStatus
, addBottomStatus
) where
import Rasa.Ext
import Rasa.Ext.Views.Internal.AnyRenderable
import Data.List
import Data.Maybe
data GetTopStatusBar = GetTopStatusBar
data GetBottomStatusBar = GetBottomStatusBar
data StatusBar = StatusBar [AnyRenderable]
| Returns a for a given buffer
getTopStatusBar :: BufAction StatusBar
getTopStatusBar = StatusBar <$> dispatchBufEvent GetTopStatusBar
| Returns a for a given buffer
getBottomStatusBar :: BufAction StatusBar
getBottomStatusBar = StatusBar <$> dispatchBufEvent GetBottomStatusBar
| This registers a ' BufAction ' which results in a renderable and runs it
at render time to add the resulting ' ' to the status bar .
addTopStatus :: Renderable r => BufAction r -> BufAction ListenerId
addTopStatus bufAction = addBufListener (const (toRenderList <$> bufAction) :: GetTopStatusBar -> BufAction [AnyRenderable])
where toRenderList x = [AnyRenderable x]
addBottomStatus :: Renderable r => BufAction r -> BufAction ListenerId
addBottomStatus bufAction = addBufListener (const (toRenderList <$> bufAction) :: GetBottomStatusBar -> BufAction [AnyRenderable])
where toRenderList x = [AnyRenderable x]
instance Renderable StatusBar where
render width _ scrollAmt (StatusBar chunks) = do
parts <- traverse (render eachWidth 1 scrollAmt) chunks
return . Just . mconcat . intersperse (styleText " | " (fg Red)) . catMaybes $ parts
where
num = length chunks
eachWidth = width `div` num
|
0c31dfecb4df21cbe00760ff216b3120fcf6aa8aab1a10e8aae27b903a0dae66 | racket/frtime | graphics-unit.rkt | #lang racket/base
(provide graphics@)
(require racket/unit
"graphics-sig.rkt"
"graphics-posn-less-unit.rkt")
(define-unit posn@ (import) (export graphics:posn^)
(define-struct posn (x y) #:mutable))
(define-compound-unit/infer graphics@
(import)
(export graphics:posn^ graphics:posn-less^)
(link posn@ graphics-posn-less@))
| null | https://raw.githubusercontent.com/racket/frtime/9b9db67581107f4d7b995541c70f2d08f03ae89e/animation/graphics-unit.rkt | racket | #lang racket/base
(provide graphics@)
(require racket/unit
"graphics-sig.rkt"
"graphics-posn-less-unit.rkt")
(define-unit posn@ (import) (export graphics:posn^)
(define-struct posn (x y) #:mutable))
(define-compound-unit/infer graphics@
(import)
(export graphics:posn^ graphics:posn-less^)
(link posn@ graphics-posn-less@))
| |
96bbc17e83d3e4c7e77769cf68362217461130b77537ca4cde99037cd4de9655 | racketscript/racketscript | interop.rkt | #lang racket/base
(require racket/match
racket/string
(only-in racketscript/compiler/util-untyped
js-identifier?))
(provide (rename-out [x-read read]
[x-read-syntax read-syntax]))
(define (x-read in)
(syntax->datum (x-read-syntax #f in)))
(define (x-read-syntax src in)
(skip-whitespace in)
(read-racketscript src in))
(define (skip-whitespace in)
(regexp-match #px"^\\s*" in))
(define (parts->ffi strs first-id?)
(define result (cond
[first-id? (car strs)]
[(js-identifier? (car strs))
`(#%js-ffi 'var ',(car strs))]
[else (error 'ffi "invalid characters in js identifier")]))
(let loop ([strs (cdr strs)]
[result result])
(match strs
['() (datum->syntax #f result)]
[(cons hd tl)
(loop tl
`(#%js-ffi 'ref ,result ',hd))])))
(define (get-id-parts in)
(map string->symbol (string-split
(symbol->string
(syntax-e
(read-syntax (object-name in) in)))
".")))
(define (read-racketscript src in)
(define-values (line col pos) (port-next-location in))
(define (peek-char=? offset chr)
(char=? (peek-char in offset) chr))
(cond
( peek - char= ? 0 # \j )
(peek-char=? 0 #\s)
(peek-char=? 1 #\.)
(read-string 2 in))
(parts->ffi (get-id-parts in) #t)]
( peek - char= ? 0 # \j )
(peek-char=? 0 #\s)
(peek-char=? 1 #\*)
(peek-char=? 2 #\.)
(read-string 2 in))
(parts->ffi (get-id-parts in) #f)]
[(and (peek-char=? 0 #\s)
(peek-char=? 1 #\")
(read-string 1 in))
(datum->syntax #f `(#%js-ffi 'string ,(read-syntax (object-name in) in)))]
[else #f]))
(module+ test
(require rackunit
racketscript/interop)
(define-simple-check (check-reader str expected)
(let ([actual (read-racketscript #f (open-input-string (substring str 2)))])
(equal?
(if actual
(syntax->datum actual)
actual)
expected)))
(check-reader "#js.window" 'window)
(check-reader "#js*.window" '(#%js-ffi 'var 'window))
(check-reader "#js.window.document" `(#%js-ffi 'ref window 'document))
(check-reader "#js.window.document.write"
`(#%js-ffi 'ref (#%js-ffi 'ref window 'document) 'write))
(check-reader "#js*.window.document"
`(#%js-ffi 'ref (#%js-ffi 'var 'window) 'document))
(check-reader "#js*.window.document.write"
`(#%js-ffi 'ref
(#%js-ffi 'ref
(#%js-ffi 'var 'window)
'document)
'write))
(check-reader "#js\"body\"" `(#%js-ffi 'string "body"))
(check-reader "#jQuery" #f))
| null | https://raw.githubusercontent.com/racketscript/racketscript/f94006d11338a674ae10f6bd83fc53e6806d07d8/racketscript-compiler/racketscript/boot/lang/private/interop.rkt | racket | #lang racket/base
(require racket/match
racket/string
(only-in racketscript/compiler/util-untyped
js-identifier?))
(provide (rename-out [x-read read]
[x-read-syntax read-syntax]))
(define (x-read in)
(syntax->datum (x-read-syntax #f in)))
(define (x-read-syntax src in)
(skip-whitespace in)
(read-racketscript src in))
(define (skip-whitespace in)
(regexp-match #px"^\\s*" in))
(define (parts->ffi strs first-id?)
(define result (cond
[first-id? (car strs)]
[(js-identifier? (car strs))
`(#%js-ffi 'var ',(car strs))]
[else (error 'ffi "invalid characters in js identifier")]))
(let loop ([strs (cdr strs)]
[result result])
(match strs
['() (datum->syntax #f result)]
[(cons hd tl)
(loop tl
`(#%js-ffi 'ref ,result ',hd))])))
(define (get-id-parts in)
(map string->symbol (string-split
(symbol->string
(syntax-e
(read-syntax (object-name in) in)))
".")))
(define (read-racketscript src in)
(define-values (line col pos) (port-next-location in))
(define (peek-char=? offset chr)
(char=? (peek-char in offset) chr))
(cond
( peek - char= ? 0 # \j )
(peek-char=? 0 #\s)
(peek-char=? 1 #\.)
(read-string 2 in))
(parts->ffi (get-id-parts in) #t)]
( peek - char= ? 0 # \j )
(peek-char=? 0 #\s)
(peek-char=? 1 #\*)
(peek-char=? 2 #\.)
(read-string 2 in))
(parts->ffi (get-id-parts in) #f)]
[(and (peek-char=? 0 #\s)
(peek-char=? 1 #\")
(read-string 1 in))
(datum->syntax #f `(#%js-ffi 'string ,(read-syntax (object-name in) in)))]
[else #f]))
(module+ test
(require rackunit
racketscript/interop)
(define-simple-check (check-reader str expected)
(let ([actual (read-racketscript #f (open-input-string (substring str 2)))])
(equal?
(if actual
(syntax->datum actual)
actual)
expected)))
(check-reader "#js.window" 'window)
(check-reader "#js*.window" '(#%js-ffi 'var 'window))
(check-reader "#js.window.document" `(#%js-ffi 'ref window 'document))
(check-reader "#js.window.document.write"
`(#%js-ffi 'ref (#%js-ffi 'ref window 'document) 'write))
(check-reader "#js*.window.document"
`(#%js-ffi 'ref (#%js-ffi 'var 'window) 'document))
(check-reader "#js*.window.document.write"
`(#%js-ffi 'ref
(#%js-ffi 'ref
(#%js-ffi 'var 'window)
'document)
'write))
(check-reader "#js\"body\"" `(#%js-ffi 'string "body"))
(check-reader "#jQuery" #f))
| |
83ab37b6e4279d99217abbf116e8fc2458d4579393f889834e5be166c7afabfb | sulami/spielwiese | 006-sum-square-difference.hs | -- Sum square difference
Problem 6
--
The sum of the squares of the first ten natural numbers is ,
12 + 22 + ... + 102 = 385
--
The square of the sum of the first ten natural numbers is ,
( 1 + 2 + ... + 10)^2 = 552 = 3025
--
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is 3025 − 385 = 2640 .
--
Find the difference between the sum of the squares of the first one hundred
-- natural numbers and the square of the sum.
{-# OPTIONS_GHC -O2 #-}
squareSum :: [Integer] -> Integer
squareSum n = sum $ map (^2) n
sumSquare :: [Integer] -> Integer
sumSquare n = (sum n) ^ 2
diff :: [Integer] -> Integer
diff n = abs $ squareSum n - sumSquare n
main = print $ diff [1..100]
| null | https://raw.githubusercontent.com/sulami/spielwiese/da354aa112d43d7ec5f258f4b5afafd7a88c8aa8/hEuler/006-sum-square-difference.hs | haskell | Sum square difference
natural numbers and the square of the sum.
# OPTIONS_GHC -O2 # | Problem 6
The sum of the squares of the first ten natural numbers is ,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is ,
( 1 + 2 + ... + 10)^2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is 3025 − 385 = 2640 .
Find the difference between the sum of the squares of the first one hundred
squareSum :: [Integer] -> Integer
squareSum n = sum $ map (^2) n
sumSquare :: [Integer] -> Integer
sumSquare n = (sum n) ^ 2
diff :: [Integer] -> Integer
diff n = abs $ squareSum n - sumSquare n
main = print $ diff [1..100]
|
71e4971c1c247e556ea2b7b803de7f64c5083e162afdb685e1639b7091a86dd0 | larcenists/larceny | iter2.scm | (text
(iter
(seq (nop)
(seq z! a!)
(nop)
ge!)))
00000000 90 nop
00000001 7505 jnz 0x8
00000003 7603 jna 0x8
00000005 90 nop
00000006 7DF8 jnl 0x0
| null | https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/src/Lib/Sassy/tests/prims/iter2.scm | scheme | (text
(iter
(seq (nop)
(seq z! a!)
(nop)
ge!)))
00000000 90 nop
00000001 7505 jnz 0x8
00000003 7603 jna 0x8
00000005 90 nop
00000006 7DF8 jnl 0x0
| |
6337607aea7820ff9b472ac13885ffee86aedfea4b6af544a3a9db60581b794f | xapi-project/xenvm | log.ml | open Sexplib.Std
type traced_operation = [
| `Set of string * string * [ `Producer | `Consumer | `Suspend | `Suspend_ack ] * [ `Int64 of int64 | `Bool of bool ]
| `Get of string * string * [ `Producer | `Consumer | `Suspend | `Suspend_ack ] * [ `Int64 of int64 | `Bool of bool ]
] with sexp
type traced_operation_list = traced_operation list with sexp
let debug fmt = Lwt_log.debug_f fmt
let info fmt = Lwt_log.info_f fmt
let warn fmt = Lwt_log.warning_f fmt
let error fmt = Lwt_log.error_f fmt
let trace_section = Lwt_log.Section.make "trace"
let trace ts =
let string_of_key = function
| `Producer -> "producer"
| `Consumer -> "consumer"
| `Suspend -> "suspend"
| `Suspend_ack -> "suspend_ack" in
let string_of_value = function
| `Int64 x -> Int64.to_string x
| `Bool b -> string_of_bool b in
let one = function
| `Set (_, queue, key, value) ->
Printf.sprintf "%s.%s := %s" queue (string_of_key key) (string_of_value value)
| `Get (__, queue, key, value) ->
Printf.sprintf "%s.%s == %s" queue (string_of_key key) (string_of_value value) in
Lwt_log.info_f ~section:trace_section "%s" (String.concat ", " (List.map one ts))
| null | https://raw.githubusercontent.com/xapi-project/xenvm/401754dfb05376b5fc78c9290453b006f6f38aa1/idl/log.ml | ocaml | open Sexplib.Std
type traced_operation = [
| `Set of string * string * [ `Producer | `Consumer | `Suspend | `Suspend_ack ] * [ `Int64 of int64 | `Bool of bool ]
| `Get of string * string * [ `Producer | `Consumer | `Suspend | `Suspend_ack ] * [ `Int64 of int64 | `Bool of bool ]
] with sexp
type traced_operation_list = traced_operation list with sexp
let debug fmt = Lwt_log.debug_f fmt
let info fmt = Lwt_log.info_f fmt
let warn fmt = Lwt_log.warning_f fmt
let error fmt = Lwt_log.error_f fmt
let trace_section = Lwt_log.Section.make "trace"
let trace ts =
let string_of_key = function
| `Producer -> "producer"
| `Consumer -> "consumer"
| `Suspend -> "suspend"
| `Suspend_ack -> "suspend_ack" in
let string_of_value = function
| `Int64 x -> Int64.to_string x
| `Bool b -> string_of_bool b in
let one = function
| `Set (_, queue, key, value) ->
Printf.sprintf "%s.%s := %s" queue (string_of_key key) (string_of_value value)
| `Get (__, queue, key, value) ->
Printf.sprintf "%s.%s == %s" queue (string_of_key key) (string_of_value value) in
Lwt_log.info_f ~section:trace_section "%s" (String.concat ", " (List.map one ts))
| |
bb7b92913c5bfb144c9fdca84c742713d38ea8f279102f14615e406d4f05044d | GaloisInc/mistral | ResolveTags.hs | module Mistral.CodeGen.ResolveTags where
import Mistral.Driver
import Mistral.ModuleSystem.Name ( mangleName )
import Mistral.TypeCheck.AST
import Mistral.Utils.SCC ( Group )
import Mistral.Utils.PP
import Control.Applicative ( (<$>), (<*>), pure )
import Data.Foldable ( foldMap, foldl' )
import qualified Data.Map as Map
import Data.Monoid ( Monoid(..) )
import qualified Data.Set as Set
import qualified Data.Traversable as T
resolveTags :: Program -> Driver Program
resolveTags prog =
do let tags = progTagMap prog
traceMsg (text "tag map:" $$ text (show tags))
nodes' <- mapM (resolveNamed resolveNode tags) (progNodes prog)
binds' <- mapM (resolveGroup resolveDecl tags) (progBinds prog)
return prog { progNodes = nodes'
, progBinds = binds' }
-- | Sets of tags, and the thing that they map to.
data TagMap = TagMap { getTopoTagMap :: AtomMap
, getTaskTagMap :: AtomMap
} deriving (Show)
type AtomMap = Map.Map Atom (Set.Set Name)
topoTags, taskTags :: AtomMap -> TagMap
topoTags tags = mempty { getTopoTagMap = tags }
taskTags tags = mempty { getTaskTagMap = tags }
hasTags :: Name -> Set.Set Atom -> AtomMap
hasTags n tags =
let s = Set.singleton n
in foldl' (\m t -> Map.insert t s m) Map.empty tags
instance Monoid TagMap where
mempty = TagMap Map.empty Map.empty
mappend (TagMap a b) (TagMap c d) =
let su = Map.unionWith Set.union
in TagMap (su a c) (su b d)
mconcat ms =
let su = Map.unionsWith Set.union
in TagMap (su (map getTopoTagMap ms)) (su (map getTaskTagMap ms))
type TagSet = [(Name,Set.Set Atom)]
resolveName :: Set.Set Atom -> AtomMap -> Maybe Name
resolveName tags names =
case validList of
[x] -> Just x
(_:_) -> Nothing -- error "Explicit fail on ambiguous tags pending further discussion"
_ -> Nothing
where
validList = Set.toList validSet
validSet = intersections (map lk (Set.toList tags))
intersections [] = mempty
intersections (x:xs) = foldl' Set.intersection x xs
lk t = maybe mempty id (Map.lookup t names)
-- | Construct the static task-tag map for a program.
progTagMap :: Program -> TagMap
progTagMap prog = foldMap nodeTagMap (progNodes prog)
nodeTagMap :: Named Node -> TagMap
nodeTagMap (Named name node) =
mconcat $ topoTags (name `hasTags` foldMap exprTags (nTags node))
: map taskTagMap (nTasks node)
taskTagMap :: Named Task -> TagMap
taskTagMap (Named name task) =
taskTags (name `hasTags` foldMap exprTags (tTags task))
exprTags :: Expr -> Set.Set Atom
exprTags e = case getTags e of
Just tags -> tags
Nothing -> mempty
resolveTaskSet :: TagMap -> Tasks -> Driver Tasks
resolveTaskSet tags tasks =
do ts' <- mapM (resolveTask tags) (taskTasks tasks)
return tasks { taskTasks = ts' }
resolveTask :: TagMap -> Named Task -> Driver (Named Task)
resolveTask tags o =
do let task = nValue o
cs' <- mapM (resolveTaskConstraint tags) (tConstraints task)
return o { nValue = task { tConstraints = cs' } }
resolveTaskConstraint :: TagMap -> TaskConstraint -> Driver TaskConstraint
resolveTaskConstraint tags tc = case tc of
TCOn ty e -> do n <- tagsToName (getTopoTagMap tags) e
return (TCOn ty (EVar n))
resolveNamed :: (TagMap -> a -> Driver a)
-> (TagMap -> Named a -> Driver (Named a))
resolveNamed resolve tags nm = T.traverse (resolve tags) nm
resolveNode :: TagMap -> Node -> Driver Node
resolveNode tags node =
do tasks <- mapM (resolveTask tags) (nTasks node)
return node { nTasks = tasks }
-- NOTE: resolving tags for bindings won't change the structure of a recursive
-- group, as tags aren't used to identify functions, beyond task declarations.
resolveGroup :: (TagMap -> a -> Driver a)
-> (TagMap -> Group a -> Driver (Group a))
resolveGroup resolve tags group = T.mapM (resolve tags) group
resolveDecl :: TagMap -> Decl -> Driver Decl
resolveDecl tags b =
do e' <- resolveExpr tags (bBody b)
return b { bBody = e' }
resolveExpr :: TagMap -> Expr -> Driver Expr
resolveExpr tags = go
where
go e = case elimEApp e of
-- XXX we really need the evidence from the constraint solver at this point,
-- but for now we just assume the send target is a tag expression defaulting
-- back to what was on error.
(send@(ETApp (EPrim PSend) _),[who,what]) ->
do (_,_,mb) <- tryMessages (tagsToName (getTaskTagMap tags) who)
case mb of
Just who' -> return $ appE send [ ELit (LString (mangleName who'))
, what]
Nothing -> return e
-- resolve node names in a task set
(ETaskSet tasks,args) ->
do tasks' <- resolveTaskSet tags tasks
args' <- mapM go args
return (appE (ETaskSet tasks') args')
(f,xs)
-- reached a single expression
| null xs -> case f of
ELet gs e' ty -> ELet <$> mapM (resolveGroup resolveDecl tags) gs
<*> go e'
<*> return ty
ECase s m rty -> ECase s <$> match m <*> return rty
EStmts ity ty as -> EStmts ity ty <$> mapM action as
-- XXX there are likely important cases being skipped
_ -> return e
-- traverse the application
| otherwise ->
appE <$> go f <*> mapM go xs
match :: Match pat -> Driver (Match pat)
match m = case m of
MCase s sty m' -> MCase <$> go s <*> pure sty <*> match m'
MRename n e ty m' -> MRename n<$> go e <*> pure ty <*> match m'
MPat pat m' -> MPat pat <$> match m'
MSplit l r -> MSplit <$> match l <*> match r
MFail -> return m
MExpr e -> MExpr <$> go e
MGuard e m' -> MGuard <$> go e <*> match m'
action a = case a of
ABind p m ty -> ABind p <$> go m <*> pure ty
AReceive r fs to wild -> AReceive r <$> T.traverse from fs <*> T.traverse timeout to
<*> T.traverse go wild
from (From src msg msgTy body) = From src msg msgTy <$> match body
timeout (Timeout lit body) = Timeout lit <$> go body
-- | Resolve a set of tags to a task identifier. Fail when one isn't uniquely
-- identified.
tagsToName :: AtomMap -> Expr -> Driver Name
tagsToName tags e =
do spec <- case getTags e of
Just spec -> return spec
Nothing -> fail "Invalid tag expression"
case resolveName spec tags of
Just n -> return n
_ -> fail $ "Unable to resolve tags: " ++ show (spec,tags)
getTags :: Expr -> Maybe (Set.Set Atom)
getTags e = case e of
EMkTuple elems | (tys,es) <- unzip elems, all (== atomCon) tys ->
mconcat `fmap` mapM getTags es
ELit (LAtom a) ->
Just (Set.singleton a)
_ -> Nothing
| null | https://raw.githubusercontent.com/GaloisInc/mistral/3464ab332d73c608e64512e822fe2b8a619ec8f3/src/Mistral/CodeGen/ResolveTags.hs | haskell | | Sets of tags, and the thing that they map to.
error "Explicit fail on ambiguous tags pending further discussion"
| Construct the static task-tag map for a program.
NOTE: resolving tags for bindings won't change the structure of a recursive
group, as tags aren't used to identify functions, beyond task declarations.
XXX we really need the evidence from the constraint solver at this point,
but for now we just assume the send target is a tag expression defaulting
back to what was on error.
resolve node names in a task set
reached a single expression
XXX there are likely important cases being skipped
traverse the application
| Resolve a set of tags to a task identifier. Fail when one isn't uniquely
identified. | module Mistral.CodeGen.ResolveTags where
import Mistral.Driver
import Mistral.ModuleSystem.Name ( mangleName )
import Mistral.TypeCheck.AST
import Mistral.Utils.SCC ( Group )
import Mistral.Utils.PP
import Control.Applicative ( (<$>), (<*>), pure )
import Data.Foldable ( foldMap, foldl' )
import qualified Data.Map as Map
import Data.Monoid ( Monoid(..) )
import qualified Data.Set as Set
import qualified Data.Traversable as T
resolveTags :: Program -> Driver Program
resolveTags prog =
do let tags = progTagMap prog
traceMsg (text "tag map:" $$ text (show tags))
nodes' <- mapM (resolveNamed resolveNode tags) (progNodes prog)
binds' <- mapM (resolveGroup resolveDecl tags) (progBinds prog)
return prog { progNodes = nodes'
, progBinds = binds' }
data TagMap = TagMap { getTopoTagMap :: AtomMap
, getTaskTagMap :: AtomMap
} deriving (Show)
type AtomMap = Map.Map Atom (Set.Set Name)
topoTags, taskTags :: AtomMap -> TagMap
topoTags tags = mempty { getTopoTagMap = tags }
taskTags tags = mempty { getTaskTagMap = tags }
hasTags :: Name -> Set.Set Atom -> AtomMap
hasTags n tags =
let s = Set.singleton n
in foldl' (\m t -> Map.insert t s m) Map.empty tags
instance Monoid TagMap where
mempty = TagMap Map.empty Map.empty
mappend (TagMap a b) (TagMap c d) =
let su = Map.unionWith Set.union
in TagMap (su a c) (su b d)
mconcat ms =
let su = Map.unionsWith Set.union
in TagMap (su (map getTopoTagMap ms)) (su (map getTaskTagMap ms))
type TagSet = [(Name,Set.Set Atom)]
resolveName :: Set.Set Atom -> AtomMap -> Maybe Name
resolveName tags names =
case validList of
[x] -> Just x
_ -> Nothing
where
validList = Set.toList validSet
validSet = intersections (map lk (Set.toList tags))
intersections [] = mempty
intersections (x:xs) = foldl' Set.intersection x xs
lk t = maybe mempty id (Map.lookup t names)
progTagMap :: Program -> TagMap
progTagMap prog = foldMap nodeTagMap (progNodes prog)
nodeTagMap :: Named Node -> TagMap
nodeTagMap (Named name node) =
mconcat $ topoTags (name `hasTags` foldMap exprTags (nTags node))
: map taskTagMap (nTasks node)
taskTagMap :: Named Task -> TagMap
taskTagMap (Named name task) =
taskTags (name `hasTags` foldMap exprTags (tTags task))
exprTags :: Expr -> Set.Set Atom
exprTags e = case getTags e of
Just tags -> tags
Nothing -> mempty
resolveTaskSet :: TagMap -> Tasks -> Driver Tasks
resolveTaskSet tags tasks =
do ts' <- mapM (resolveTask tags) (taskTasks tasks)
return tasks { taskTasks = ts' }
resolveTask :: TagMap -> Named Task -> Driver (Named Task)
resolveTask tags o =
do let task = nValue o
cs' <- mapM (resolveTaskConstraint tags) (tConstraints task)
return o { nValue = task { tConstraints = cs' } }
resolveTaskConstraint :: TagMap -> TaskConstraint -> Driver TaskConstraint
resolveTaskConstraint tags tc = case tc of
TCOn ty e -> do n <- tagsToName (getTopoTagMap tags) e
return (TCOn ty (EVar n))
resolveNamed :: (TagMap -> a -> Driver a)
-> (TagMap -> Named a -> Driver (Named a))
resolveNamed resolve tags nm = T.traverse (resolve tags) nm
resolveNode :: TagMap -> Node -> Driver Node
resolveNode tags node =
do tasks <- mapM (resolveTask tags) (nTasks node)
return node { nTasks = tasks }
resolveGroup :: (TagMap -> a -> Driver a)
-> (TagMap -> Group a -> Driver (Group a))
resolveGroup resolve tags group = T.mapM (resolve tags) group
resolveDecl :: TagMap -> Decl -> Driver Decl
resolveDecl tags b =
do e' <- resolveExpr tags (bBody b)
return b { bBody = e' }
resolveExpr :: TagMap -> Expr -> Driver Expr
resolveExpr tags = go
where
go e = case elimEApp e of
(send@(ETApp (EPrim PSend) _),[who,what]) ->
do (_,_,mb) <- tryMessages (tagsToName (getTaskTagMap tags) who)
case mb of
Just who' -> return $ appE send [ ELit (LString (mangleName who'))
, what]
Nothing -> return e
(ETaskSet tasks,args) ->
do tasks' <- resolveTaskSet tags tasks
args' <- mapM go args
return (appE (ETaskSet tasks') args')
(f,xs)
| null xs -> case f of
ELet gs e' ty -> ELet <$> mapM (resolveGroup resolveDecl tags) gs
<*> go e'
<*> return ty
ECase s m rty -> ECase s <$> match m <*> return rty
EStmts ity ty as -> EStmts ity ty <$> mapM action as
_ -> return e
| otherwise ->
appE <$> go f <*> mapM go xs
match :: Match pat -> Driver (Match pat)
match m = case m of
MCase s sty m' -> MCase <$> go s <*> pure sty <*> match m'
MRename n e ty m' -> MRename n<$> go e <*> pure ty <*> match m'
MPat pat m' -> MPat pat <$> match m'
MSplit l r -> MSplit <$> match l <*> match r
MFail -> return m
MExpr e -> MExpr <$> go e
MGuard e m' -> MGuard <$> go e <*> match m'
action a = case a of
ABind p m ty -> ABind p <$> go m <*> pure ty
AReceive r fs to wild -> AReceive r <$> T.traverse from fs <*> T.traverse timeout to
<*> T.traverse go wild
from (From src msg msgTy body) = From src msg msgTy <$> match body
timeout (Timeout lit body) = Timeout lit <$> go body
tagsToName :: AtomMap -> Expr -> Driver Name
tagsToName tags e =
do spec <- case getTags e of
Just spec -> return spec
Nothing -> fail "Invalid tag expression"
case resolveName spec tags of
Just n -> return n
_ -> fail $ "Unable to resolve tags: " ++ show (spec,tags)
getTags :: Expr -> Maybe (Set.Set Atom)
getTags e = case e of
EMkTuple elems | (tys,es) <- unzip elems, all (== atomCon) tys ->
mconcat `fmap` mapM getTags es
ELit (LAtom a) ->
Just (Set.singleton a)
_ -> Nothing
|
9040a79c9d8a7683f8c177300629cad4ce9a6c711ee02b86cbdd931e9f882f25 | metaocaml/ber-metaocaml | unused_functor_parameter.ml | (* TEST
flags = " -w A "
* expect
*)
module Foo(Unused : sig end) = struct end;;
[%%expect {|
Line 1, characters 11-17:
1 | module Foo(Unused : sig end) = struct end;;
^^^^^^
Warning 60: unused module Unused.
module Foo : functor (Unused : sig end) -> sig end
|}]
module type S = functor (Unused : sig end) -> sig end;;
[%%expect {|
Line 1, characters 25-31:
1 | module type S = functor (Unused : sig end) -> sig end;;
^^^^^^
Warning 67: unused functor parameter Unused.
module type S = functor (Unused : sig end) -> sig end
|}]
module type S = sig
module M (Unused : sig end) : sig end
end;;
[%%expect{|
Line 2, characters 12-18:
2 | module M (Unused : sig end) : sig end
^^^^^^
Warning 67: unused functor parameter Unused.
module type S = sig module M : functor (Unused : sig end) -> sig end end
|}]
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/testsuite/tests/typing-warnings/unused_functor_parameter.ml | ocaml | TEST
flags = " -w A "
* expect
|
module Foo(Unused : sig end) = struct end;;
[%%expect {|
Line 1, characters 11-17:
1 | module Foo(Unused : sig end) = struct end;;
^^^^^^
Warning 60: unused module Unused.
module Foo : functor (Unused : sig end) -> sig end
|}]
module type S = functor (Unused : sig end) -> sig end;;
[%%expect {|
Line 1, characters 25-31:
1 | module type S = functor (Unused : sig end) -> sig end;;
^^^^^^
Warning 67: unused functor parameter Unused.
module type S = functor (Unused : sig end) -> sig end
|}]
module type S = sig
module M (Unused : sig end) : sig end
end;;
[%%expect{|
Line 2, characters 12-18:
2 | module M (Unused : sig end) : sig end
^^^^^^
Warning 67: unused functor parameter Unused.
module type S = sig module M : functor (Unused : sig end) -> sig end end
|}]
|
4f102ca002e521cb1a52343f47cd9ffa9069c5cfcd11b177c2d384bb98746acb | codereport/SICP-2020 | conor_hoekstra_solutions.rkt | #lang sicp
;;;;;
Code from 4.1
;;;;;
from footnote on page 520
;; -7.4/doc-html/scheme_2.html#SEC24
;; A Scheme expression is a construct that returns a value. An expression may be a:
1 . literal ,
2 . a variable reference ,
3 . a special form ,
4 . or a procedure call .
(define (my-apply procedure arguments)
(cond ((primitive-procedure? procedure)
(apply-primitive-procedure procedure arguments))
((compound-procedure? procedure)
(eval-sequence
(procedure-body procedure)
(extend-environment
(procedure-parameters procedure)
arguments
(procedure-environment procedure))))
(else
(error
"Unknown procedure type: APPLY" procedure))))
(define (list-of-values exps env)
(if (no-operands? exps)
'()
(cons (eval (first-operand exps) env)
(list-of-values (rest-operands exps) env))))
(define (eval-if exp env)
(if (true? (eval (if-predicate exp) env))
(eval (if-consequent exp) env)
(eval (if-alternative exp) env)))
(define (eval-sequence exps env)
(cond ((last-exp? exps)
(eval (first-exp exps) env))
(else
(eval (first-exp exps) env)
(eval-sequence (rest-exps exps) env))))
(define (eval-assignment exp env)
(set-variable-value! (assignment-variable exp)
(eval (assignment-value exp) env)
env)
'ok)
(define (eval-definition exp env)
(define-variable! (definition-variable exp)
(eval (definition-value exp) env)
env)
'ok)
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
(define (variable? exp) (symbol? exp))
(define (quoted? exp) (tagged-list? exp 'quote))
(define (text-of-quotation exp) (cadr exp))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (assignment? exp) (tagged-list? exp 'set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
(define (definition? exp) (tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(make-lambda (cdadr exp) ; formal parameters
(cddr exp)))) ; body
(define (lambda? exp) (tagged-list? exp 'lambda))
(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))
(define (make-lambda parameters body)
(cons 'lambda (cons parameters body)))
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))
(define (make-if predicate consequent alternative)
(list 'if predicate consequent alternative))
(define (begin? exp) (tagged-list? exp 'begin))
(define (begin-actions exp) (cdr exp))
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (make-begin seq))))
(define (make-begin seq) (cons 'begin seq))
(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (no-operands? ops) (null? ops))
(define (first-operand ops) (car ops))
(define (rest-operands ops) (cdr ops))
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (cond->if exp) (expand-clauses (cond-clauses exp)))
(define (expand-clauses clauses)
(if (null? clauses)
'false ; no else clause
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last: COND->IF"
clauses))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
(define (true? x) (not (eq? x false))) ; enables: eval-if; if? clause in eval
(define (false? x) (eq? x false))
(define (make-procedure parameters body env) ; enables: lambda? clause in eval
(list 'procedure parameters body env))
(define (compound-procedure? p)
(tagged-list? p 'procedure))
(define (procedure-parameters p) (cadr p))
(define (procedure-body p) (caddr p))
(define (procedure-environment p) (cadddr p))
(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))
(define the-empty-environment '())
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
at this point need to switch to # sicp
(set-cdr! frame (cons val (cdr frame))))
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (lookup-variable-value var env) ; enables: variable? clause of eval
(define (env-loop env)
(define (scan vars vals) ; :(
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars)) (car vals))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (set-variable-value! var val env) ; enables: eval-assignment;
(define (env-loop env) ; assignment? clause of eval
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars)) (set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable: SET!" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (define-variable! var val env) ; enables: eval-definition
(let ((frame (first-frame env))) ; definition? clause of eval
(define (scan vars vals)
(cond ((null? vars)
(add-binding-to-frame! var val frame))
((eq? var (car vars)) (set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(scan (frame-variables frame) (frame-values frame))))
(define (primitive-procedure? proc) ; helps enable apply
(tagged-list? proc 'primitive))
(define (primitive-implementation proc) (cadr proc))
(define primitive-procedures
(list (list 'car car)
(list 'cdr cdr)
(list 'cons cons)
(list 'null? null?)
(list '+ +)
(list '> >)
(list '= =)
;;⟨ more primitives ⟩
))
(define (primitive-procedure-names)
(map car primitive-procedures))
(define (primitive-procedure-objects)
(map (lambda (proc) (list 'primitive (cadr proc)))
primitive-procedures))
(define (apply-primitive-procedure proc args)
(apply-in-underlying-scheme
(primitive-implementation proc) args))
(define input-prompt ";;; M-Eval input:")
(define output-prompt ";;; M-Eval value:")
(define (prompt-for-input string)
(newline) (newline) (display string) (newline))
(define (announce-output string)
(newline) (display string) (newline))
(define (user-print object)
(if (compound-procedure? object)
(display (list 'compound-procedure
(procedure-parameters object)
(procedure-body object)
'<procedure-env>))
(display object)))
(define (setup-environment)
(let ((initial-env
(extend-environment (primitive-procedure-names)
(primitive-procedure-objects)
the-empty-environment)))
(define-variable! 'true true initial-env)
(define-variable! 'false false initial-env)
initial-env))
;;;;;
End of Code from 4.1
;;;;;
;;;;;
Code from 5.2
;;;;;
;; 5.2.1 The Machine Model
(define (make-machine register-names ops controller-text)
(let ((machine (make-new-machine)))
(for-each
(lambda (register-name)
((machine 'allocate-register) register-name))
register-names)
((machine 'install-operations) ops)
((machine 'install-instruction-sequence)
(assemble controller-text machine))
machine))
;; Registers
(define (make-register name)
(let ((contents '*unassigned*))
(define (dispatch message)
(cond ((eq? message 'get) contents)
((eq? message 'set)
(lambda (value) (set! contents value)))
(else
(error "Unknown request: REGISTER" message))))
dispatch))
(define (get-contents register) (register 'get))
(define (set-contents! register value)
((register 'set) value))
;; The stack
(define (make-stack)
(let ((s '()))
(define (push x) (set! s (cons x s)))
(define (pop)
(if (null? s)
(error "Empty stack: POP")
(let ((top (car s)))
(set! s (cdr s))
top)))
(define (initialize)
(set! s '())
'done)
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
(else (error "Unknown request: STACK" message))))
dispatch))
(define (pop stack) (stack 'pop))
(define (push stack value) ((stack 'push) value))
;; The basic machine
(define (make-new-machine)
(let ((pc (make-register 'pc))
(flag (make-register 'flag))
(stack (make-stack))
(the-instruction-sequence '()))
(let ((the-ops
(list (list 'initialize-stack
(lambda () (stack 'initialize)))))
(register-table
(list (list 'pc pc) (list 'flag flag))))
(define (allocate-register name)
(if (assoc name register-table)
(error "Multiply defined register: " name)
(set! register-table
(cons (list name (make-register name))
register-table)))
'register-allocated)
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(error "Unknown register:" name))))
(define (execute)
(let ((insts (get-contents pc)))
(if (null? insts)
'done
(begin
((instruction-execution-proc (car insts)))
(execute)))))
(define (dispatch message)
(cond ((eq? message 'start)
(set-contents! pc the-instruction-sequence)
(execute))
((eq? message 'install-instruction-sequence)
(lambda (seq)
(set! the-instruction-sequence seq)))
((eq? message 'allocate-register)
allocate-register)
((eq? message 'get-register)
lookup-register)
((eq? message 'install-operations)
(lambda (ops)
(set! the-ops (append the-ops ops))))
((eq? message 'stack) stack)
((eq? message 'operations) the-ops)
(else (error "Unknown request: MACHINE"
message))))
dispatch)))
(define (start machine) (machine 'start))
(define (get-register-contents machine register-name)
(get-contents (get-register machine register-name)))
(define (set-register-contents! machine register-name value)
(set-contents! (get-register machine register-name)
value)
'done)
(define (get-register machine reg-name)
((machine 'get-register) reg-name))
5.2.2 The Assembler
(define (assemble controller-text machine)
(extract-labels
controller-text
(lambda (insts labels)
(update-insts! insts labels machine)
insts)))
(define (extract-labels text receive)
(if (null? text)
(receive '() '())
(extract-labels
(cdr text)
(lambda (insts labels)
(let ((next-inst (car text)))
(if (symbol? next-inst)
(if (assoc next-inst labels)
(error "repeated label: " next-inst)
(receive insts
(cons (make-label-entry next-inst
insts)
labels)))
(receive (cons (make-instruction next-inst)
insts)
labels)))))))
(define (update-insts! insts labels machine)
(let ((pc (get-register machine 'pc))
(flag (get-register machine 'flag))
(stack (machine 'stack))
(ops (machine 'operations)))
(for-each
(lambda (inst)
(set-instruction-execution-proc!
inst
(make-execution-procedure
(instruction-text inst)
labels machine pc flag stack ops)))
insts)))
(define (make-instruction text) (cons text '()))
(define (instruction-text inst) (car inst))
(define (instruction-execution-proc inst) (cdr inst))
(define (set-instruction-execution-proc! inst proc)
(set-cdr! inst proc))
(define (make-label-entry label-name insts)
(cons label-name insts))
(define (lookup-label labels label-name)
(let ((val (assoc label-name labels)))
(if val
(cdr val)
(error "Undefined label: ASSEMBLE"
label-name))))
;; 5.2.3 Generating Execution Procedures for Instructions
(define (make-execution-procedure
inst labels machine pc flag stack ops)
(cond ((eq? (car inst) 'assign)
(make-assign inst machine labels ops pc))
((eq? (car inst) 'test)
(make-test inst machine labels ops flag pc))
((eq? (car inst) 'branch)
(make-branch inst machine labels flag pc))
((eq? (car inst) 'goto)
(make-goto inst machine labels pc))
((eq? (car inst) 'save)
(make-save inst machine stack pc))
((eq? (car inst) 'restore)
(make-restore inst machine stack pc))
((eq? (car inst) 'perform)
(make-perform inst machine labels ops pc))
(else
(error "Unknown instruction type: ASSEMBLE"
inst))))
;; assign instructions
(define (make-assign inst machine labels operations pc)
(let ((target
(get-register machine (assign-reg-name inst)))
(value-exp (assign-value-exp inst)))
(let ((value-proc
(if (operation-exp? value-exp)
(make-operation-exp
value-exp machine labels operations)
(make-primitive-exp
(car value-exp) machine labels))))
(lambda () ; execution procedure for assign
(set-contents! target (value-proc))
(advance-pc pc)))))
(define (assign-reg-name assign-instruction)
(cadr assign-instruction))
(define (assign-value-exp assign-instruction)
(cddr assign-instruction))
(define (advance-pc pc)
(set-contents! pc (cdr (get-contents pc))))
;; test, branch, and goto instructions
(define (make-test inst machine labels operations flag pc)
(let ((condition (test-condition inst)))
(if (operation-exp? condition)
(let ((condition-proc
(make-operation-exp
condition machine labels operations)))
(lambda ()
(set-contents! flag (condition-proc))
(advance-pc pc)))
(error "Bad TEST instruction: ASSEMBLE" inst))))
(define (test-condition test-instruction)
(cdr test-instruction))
(define (make-branch inst machine labels flag pc)
(let ((dest (branch-dest inst)))
(if (label-exp? dest)
(let ((insts
(lookup-label
labels
(label-exp-label dest))))
(lambda ()
(if (get-contents flag)
(set-contents! pc insts)
(advance-pc pc))))
(error "Bad BRANCH instruction: ASSEMBLE" inst))))
(define (branch-dest branch-instruction)
(cadr branch-instruction))
(define (make-goto inst machine labels pc)
(let ((dest (goto-dest inst)))
(cond ((label-exp? dest)
(let ((insts (lookup-label
labels
(label-exp-label dest))))
(lambda () (set-contents! pc insts))))
((register-exp? dest)
(let ((reg (get-register
machine
(register-exp-reg dest))))
(lambda ()
(set-contents! pc (get-contents reg)))))
(else (error "Bad GOTO instruction: ASSEMBLE" inst)))))
(define (goto-dest goto-instruction)
(cadr goto-instruction))
;; Other instructions
(define (make-save inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(push stack (get-contents reg))
(advance-pc pc))))
(define (make-restore inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(set-contents! reg (pop stack))
(advance-pc pc))))
(define (stack-inst-reg-name stack-instruction)
(cadr stack-instruction))
(define (make-perform inst machine labels operations pc)
(let ((action (perform-action inst)))
(if (operation-exp? action)
(let ((action-proc
(make-operation-exp
action machine labels operations)))
(lambda () (action-proc) (advance-pc pc)))
(error "Bad PERFORM instruction: ASSEMBLE" inst))))
(define (perform-action inst) (cdr inst))
;; Execution procedures for subexpressions
(define (make-primitive-exp exp machine labels)
(cond ((constant-exp? exp)
(let ((c (constant-exp-value exp)))
(lambda () c)))
((label-exp? exp)
(let ((insts (lookup-label
labels
(label-exp-label exp))))
(lambda () insts)))
((register-exp? exp)
(let ((r (get-register machine (register-exp-reg exp))))
(lambda () (get-contents r))))
(else (error "Unknown expression type: ASSEMBLE" exp))))
(define (register-exp? exp) (tagged-list? exp 'reg))
(define (register-exp-reg exp) (cadr exp))
(define (constant-exp? exp) (tagged-list? exp 'const))
(define (constant-exp-value exp) (cadr exp))
(define (label-exp? exp) (tagged-list? exp 'label))
(define (label-exp-label exp) (cadr exp))
(define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp)
operations))
(aprocs
(map (lambda (e)
(make-primitive-exp e machine labels))
(operation-exp-operands exp))))
(lambda ()
(apply op (map (lambda (p) (p)) aprocs)))))
(define (operation-exp? exp)
(and (pair? exp) (tagged-list? (car exp) 'op)))
(define (operation-exp-op operation-exp)
(cadr (car operation-exp)))
(define (operation-exp-operands operation-exp)
(cdr operation-exp))
(define (lookup-prim symbol operations)
(let ((val (assoc symbol operations)))
(if val
(cadr val)
(error "Unknown operation: ASSEMBLE"
symbol))))
;;;;;
End of Code from 5.2
;;;;;
(define (empty-arglist) '())
(define (adjoin-arg arg arglist) (append arglist (list arg)))
(define (last-operand? ops) (null? (cdr ops)))
(define (no-more-exps? seq) (null? seq))
(define the-global-environment (setup-environment))
(define (get-global-environment) the-global-environment)
(define eceval-operations
(list (list 'self-evaluating? self-evaluating?)
(list 'variable? variable?)
(list 'quoted? quoted?)
(list 'assignment? assignment?)
(list 'definition? definition?)
(list 'if? if?)
(list 'cond? cond?)
(list 'lambda? lambda?)
;(list 'let? let?)
(list 'begin? begin?)
(list 'application? application?)
(list 'lookup-variable-value lookup-variable-value)
(list 'text-of-quotation text-of-quotation)
(list 'lambda-parameters lambda-parameters)
(list 'lambda-body lambda-body)
(list 'make-procedure make-procedure)
(list 'operands operands)
(list 'operator operator)
(list 'no-operands? no-operands?)
(list 'first-operand first-operand)
(list 'rest-operands rest-operands)
(list 'empty-arglist empty-arglist)
(list 'adjoin-arg adjoin-arg)
(list 'last-operand? last-operand?)
(list 'primitive-procedure? primitive-procedure?)
(list 'compound-procedure? compound-procedure?)
;(list 'compiled-procedure? compiled-procedure?)
(list 'apply-primitive-procedure apply-primitive-procedure)
(list 'procedure-parameters procedure-parameters)
(list 'procedure-body procedure-body)
(list 'procedure-environment procedure-environment)
;(list 'make-compiled-procedure make-compiled-procedure)
;(list 'compiled-procedure-entry compiled-procedure-entry)
;(list 'compiled-procedure-env compiled-procedure-env)
(list 'extend-environment extend-environment)
(list 'begin-actions begin-actions)
(list 'last-exp? last-exp?)
(list 'first-exp first-exp)
(list 'rest-exps rest-exps)
;(list 'compile? compile?)
;(list 'compile-and-run compile-and-run)
;(list 'compile-and-run-exp compile-and-run-exp)
(list 'if-predicate if-predicate)
(list 'if-consequent if-consequent)
(list 'if-alternative if-alternative)
(list 'false? false?)
(list 'true? true?)
(list 'list list)
(list 'cons cons)
(list '= =)
(list '* *)
(list '- -)
(list '+ +)
(list 'cond-clauses cond-clauses)
;(list 'no-conds? no-conds?)
( list ' first - cond first - cond )
;(list 'rest-conds rest-conds)
(list 'cond->if cond->if)
(list 'cond-predicate cond-predicate)
(list 'cond-actions cond-actions)
(list 'cond-else-clause? cond-else-clause?)
(list 'assignment-variable assignment-variable)
(list 'assignment-value assignment-value)
(list 'set-variable-value! set-variable-value!)
;(list 'lexical-address-lookup lexical-address-lookup)
;(list 'lexical-address-set! lexical-address-set!)
(list 'definition-variable definition-variable)
(list 'definition-value definition-value)
(list 'define-variable! define-variable!)
;(list 'let->combination let->combination)
(list 'prompt-for-input prompt-for-input)
(list 'read read)
(list 'announce-output announce-output)
(list 'user-print user-print)
(list 'eq? eq?)
(list 'no-more-exps? no-more-exps?)
(list 'get-global-environment get-global-environment)))
(define eceval
(make-machine
'(exp env val proc argl continue unev)
eceval-operations
'(
5.4.4 Running the Evaluator
read-eval-print-loop
(perform (op initialize-stack))
(perform
(op prompt-for-input) (const ";;EC-Eval input:"))
(assign exp (op read))
(assign env (op get-global-environment))
(assign continue (label print-result))
(goto (label eval-dispatch))
print-result
(perform (op announce-output) (const ";;EC-Eval value:"))
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
;;
unknown-expression-type
(assign val (const unknown-expression-type-error))
(goto (label signal-error))
unknown-procedure-type
(restore continue) ; clean up stack (from apply-dispatch )
(assign val (const unknown-procedure-type-error))
(goto (label signal-error))
signal-error
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
5.4.1 The Core of the Explicit - Control Evaluator
eval-dispatch
(test (op self-evaluating?) (reg exp))
(branch (label ev-self-eval))
(test (op variable?) (reg exp))
(branch (label ev-variable))
(test (op quoted?) (reg exp))
(branch (label ev-quoted))
(test (op assignment?) (reg exp))
(branch (label ev-assignment))
(test (op definition?) (reg exp))
(branch (label ev-definition))
(test (op if?) (reg exp))
(branch (label ev-if))
added for Exercise 5.23
added for Exercise 5.23
(test (op lambda?) (reg exp))
(branch (label ev-lambda))
(test (op begin?) (reg exp))
(branch (label ev-begin))
(test (op application?) (reg exp))
(branch (label ev-application))
(goto (label unknown-expression-type))
;;
;; Evaluating simple expressions
ev-self-eval
(assign val (reg exp))
(goto (reg continue))
ev-variable
(assign val (op lookup-variable-value) (reg exp) (reg env))
(goto (reg continue))
ev-quoted
(assign val (op text-of-quotation) (reg exp))
(goto (reg continue))
ev-lambda
(assign unev (op lambda-parameters) (reg exp))
(assign exp (op lambda-body) (reg exp))
(assign val (op make-procedure) (reg unev) (reg exp) (reg env))
(goto (reg continue))
;;
;; Evaluating procedure applications
ev-application
(save continue)
(save env)
(assign unev (op operands) (reg exp))
(save unev)
(assign exp (op operator) (reg exp))
(assign continue (label ev-appl-did-operator))
(goto (label eval-dispatch))
;;
ev-appl-did-operator
(restore unev) ; the operands
(restore env)
(assign argl (op empty-arglist))
(assign proc (reg val)) ; the operator
(test (op no-operands?) (reg unev))
(branch (label apply-dispatch))
(save proc)
;;
ev-appl-operand-loop
(save argl)
(assign exp (op first-operand) (reg unev))
(test (op last-operand?) (reg unev))
(branch (label ev-appl-last-arg))
(save env)
(save unev)
(assign continue (label ev-appl-accumulate-arg))
(goto (label eval-dispatch))
;;
ev-appl-accumulate-arg
(restore unev)
(restore env)
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(assign unev (op rest-operands) (reg unev))
(goto (label ev-appl-operand-loop))
;;
ev-appl-last-arg
(assign continue (label ev-appl-accum-last-arg))
(goto (label eval-dispatch))
ev-appl-accum-last-arg
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(restore proc)
(goto (label apply-dispatch))
;;
;; Procedure application
apply-dispatch
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-apply))
(test (op compound-procedure?) (reg proc))
(branch (label compound-apply))
(goto (label unknown-procedure-type))
;;
primitive-apply
(assign val (op apply-primitive-procedure)
(reg proc)
(reg argl))
(restore continue)
(goto (reg continue))
;;
compound-apply
(assign unev (op procedure-parameters) (reg proc))
(assign env (op procedure-environment) (reg proc))
(assign env (op extend-environment)
(reg unev) (reg argl) (reg env))
(assign unev (op procedure-body) (reg proc))
(goto (label ev-sequence))
;;
;; 5.4.2 Sequence Evaluation and Tail Recursion
ev-begin
(assign unev (op begin-actions) (reg exp))
(save continue)
(goto (label ev-sequence))
;;
;ev-sequence
;(assign exp (op first-exp) (reg unev))
;(test (op last-exp?) (reg unev))
;(branch (label ev-sequence-last-exp))
;(save unev)
;(save env)
;(assign continue (label ev-sequence-continue))
( goto ( label eval - dispatch ) )
;ev-sequence-continue
;(restore env)
;(restore unev)
;(assign unev (op rest-exps) (reg unev))
( goto ( label ev - sequence ) )
;ev-sequence-last-exp
;(restore continue)
( goto ( label eval - dispatch ) )
;;
;; Tail recursion
ev-sequence
(test (op no-more-exps?) (reg unev))
(branch (label ev-sequence-end))
(assign exp (op first-exp) (reg unev))
(save unev)
(save env)
(assign continue (label ev-sequence-continue))
(goto (label eval-dispatch))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
(goto (label ev-sequence))
ev-sequence-end
(restore continue)
(goto (reg continue))
;;
5.4.3 Conditionals , Assignments , and Definitions
ev-if
(save exp) ; save expression for later
(save env)
(save continue)
(assign continue (label ev-if-decide))
(assign exp (op if-predicate) (reg exp))
(goto (label eval-dispatch)) ; evaluate the predicate
;;
ev-if-decide
(restore continue)
(restore env)
(restore exp)
(test (op true?) (reg val))
(branch (label ev-if-consequent))
ev-if-alternative
(assign exp (op if-alternative) (reg exp))
(goto (label eval-dispatch))
ev-if-consequent
(assign exp (op if-consequent) (reg exp))
(goto (label eval-dispatch))
;;
Added for Exercise 5.23
ev-cond
(assign exp (op cond->if) (reg exp))
(goto (label ev-if))
;; Assignments and definitions
ev-assignment
(assign unev (op assignment-variable) (reg exp))
(save unev)
; save variable for later
(assign exp (op assignment-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-assignment-1))
(goto (label eval-dispatch))
; evaluate the assignment value
ev-assignment-1
(restore continue)
(restore env)
(restore unev)
(perform
(op set-variable-value!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
;;
ev-definition
(assign unev (op definition-variable) (reg exp))
(save unev)
; save variable for later
(assign exp (op definition-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-definition-1))
(goto (label eval-dispatch))
; evaluate the definition value
ev-definition-1
(restore continue)
(restore env)
(restore unev)
(perform
(op define-variable!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
;;
)))
(start eceval)
Exercise 5.23 ( page 758 )
EC - Eval input :
(define (positive? x)
(cond ((> x 0) 'positive)
((= x 0) 'zero)
(else 'negative)))
;; . . Unbound variable cond
( define ( positive ? x ) ( cond ( ( > x 0 ) ' positive ) ( (= x 0 ) ' zero ) ( else ' negative ) ) )
;; After changes
EC - Eval input :
(define (positive? x)
(cond ((> x 0) 'positive)
((= x 0) 'zero)
(else 'negative)))
EC - Eval value :
;; ok
EC - Eval input :
(positive? 10)
EC - Eval value :
;; positive
EC - Eval input :
(positive? 0)
EC - Eval value :
zero
EC - Eval input :
(positive? -10)
EC - Eval value :
;; negative
| null | https://raw.githubusercontent.com/codereport/SICP-2020/2d1e60048db89678830d93fcc558a846b7f57b76/Chapter%205.4%20Solutions/conor_hoekstra_solutions.rkt | racket |
-7.4/doc-html/scheme_2.html#SEC24
A Scheme expression is a construct that returns a value. An expression may be a:
formal parameters
body
no else clause
enables: eval-if; if? clause in eval
enables: lambda? clause in eval
enables: variable? clause of eval
:(
enables: eval-assignment;
assignment? clause of eval
enables: eval-definition
definition? clause of eval
helps enable apply
⟨ more primitives ⟩
5.2.1 The Machine Model
Registers
The stack
The basic machine
5.2.3 Generating Execution Procedures for Instructions
assign instructions
execution procedure for assign
test, branch, and goto instructions
Other instructions
Execution procedures for subexpressions
(list 'let? let?)
(list 'compiled-procedure? compiled-procedure?)
(list 'make-compiled-procedure make-compiled-procedure)
(list 'compiled-procedure-entry compiled-procedure-entry)
(list 'compiled-procedure-env compiled-procedure-env)
(list 'compile? compile?)
(list 'compile-and-run compile-and-run)
(list 'compile-and-run-exp compile-and-run-exp)
(list 'no-conds? no-conds?)
(list 'rest-conds rest-conds)
(list 'lexical-address-lookup lexical-address-lookup)
(list 'lexical-address-set! lexical-address-set!)
(list 'let->combination let->combination)
clean up stack (from apply-dispatch )
Evaluating simple expressions
Evaluating procedure applications
the operands
the operator
Procedure application
5.4.2 Sequence Evaluation and Tail Recursion
ev-sequence
(assign exp (op first-exp) (reg unev))
(test (op last-exp?) (reg unev))
(branch (label ev-sequence-last-exp))
(save unev)
(save env)
(assign continue (label ev-sequence-continue))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
ev-sequence-last-exp
(restore continue)
Tail recursion
save expression for later
evaluate the predicate
Assignments and definitions
save variable for later
evaluate the assignment value
save variable for later
evaluate the definition value
. . Unbound variable cond
After changes
ok
positive
negative | #lang sicp
Code from 4.1
from footnote on page 520
1 . literal ,
2 . a variable reference ,
3 . a special form ,
4 . or a procedure call .
(define (my-apply procedure arguments)
(cond ((primitive-procedure? procedure)
(apply-primitive-procedure procedure arguments))
((compound-procedure? procedure)
(eval-sequence
(procedure-body procedure)
(extend-environment
(procedure-parameters procedure)
arguments
(procedure-environment procedure))))
(else
(error
"Unknown procedure type: APPLY" procedure))))
(define (list-of-values exps env)
(if (no-operands? exps)
'()
(cons (eval (first-operand exps) env)
(list-of-values (rest-operands exps) env))))
(define (eval-if exp env)
(if (true? (eval (if-predicate exp) env))
(eval (if-consequent exp) env)
(eval (if-alternative exp) env)))
(define (eval-sequence exps env)
(cond ((last-exp? exps)
(eval (first-exp exps) env))
(else
(eval (first-exp exps) env)
(eval-sequence (rest-exps exps) env))))
(define (eval-assignment exp env)
(set-variable-value! (assignment-variable exp)
(eval (assignment-value exp) env)
env)
'ok)
(define (eval-definition exp env)
(define-variable! (definition-variable exp)
(eval (definition-value exp) env)
env)
'ok)
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
(define (variable? exp) (symbol? exp))
(define (quoted? exp) (tagged-list? exp 'quote))
(define (text-of-quotation exp) (cadr exp))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (assignment? exp) (tagged-list? exp 'set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
(define (definition? exp) (tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(define (lambda? exp) (tagged-list? exp 'lambda))
(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))
(define (make-lambda parameters body)
(cons 'lambda (cons parameters body)))
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))
(define (make-if predicate consequent alternative)
(list 'if predicate consequent alternative))
(define (begin? exp) (tagged-list? exp 'begin))
(define (begin-actions exp) (cdr exp))
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (make-begin seq))))
(define (make-begin seq) (cons 'begin seq))
(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (no-operands? ops) (null? ops))
(define (first-operand ops) (car ops))
(define (rest-operands ops) (cdr ops))
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (cond->if exp) (expand-clauses (cond-clauses exp)))
(define (expand-clauses clauses)
(if (null? clauses)
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last: COND->IF"
clauses))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
(define (false? x) (eq? x false))
(list 'procedure parameters body env))
(define (compound-procedure? p)
(tagged-list? p 'procedure))
(define (procedure-parameters p) (cadr p))
(define (procedure-body p) (caddr p))
(define (procedure-environment p) (cadddr p))
(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))
(define the-empty-environment '())
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
at this point need to switch to # sicp
(set-cdr! frame (cons val (cdr frame))))
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (env-loop env)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars)) (car vals))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars)) (set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable: SET!" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (scan vars vals)
(cond ((null? vars)
(add-binding-to-frame! var val frame))
((eq? var (car vars)) (set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(scan (frame-variables frame) (frame-values frame))))
(tagged-list? proc 'primitive))
(define (primitive-implementation proc) (cadr proc))
(define primitive-procedures
(list (list 'car car)
(list 'cdr cdr)
(list 'cons cons)
(list 'null? null?)
(list '+ +)
(list '> >)
(list '= =)
))
(define (primitive-procedure-names)
(map car primitive-procedures))
(define (primitive-procedure-objects)
(map (lambda (proc) (list 'primitive (cadr proc)))
primitive-procedures))
(define (apply-primitive-procedure proc args)
(apply-in-underlying-scheme
(primitive-implementation proc) args))
(define input-prompt ";;; M-Eval input:")
(define output-prompt ";;; M-Eval value:")
(define (prompt-for-input string)
(newline) (newline) (display string) (newline))
(define (announce-output string)
(newline) (display string) (newline))
(define (user-print object)
(if (compound-procedure? object)
(display (list 'compound-procedure
(procedure-parameters object)
(procedure-body object)
'<procedure-env>))
(display object)))
(define (setup-environment)
(let ((initial-env
(extend-environment (primitive-procedure-names)
(primitive-procedure-objects)
the-empty-environment)))
(define-variable! 'true true initial-env)
(define-variable! 'false false initial-env)
initial-env))
End of Code from 4.1
Code from 5.2
(define (make-machine register-names ops controller-text)
(let ((machine (make-new-machine)))
(for-each
(lambda (register-name)
((machine 'allocate-register) register-name))
register-names)
((machine 'install-operations) ops)
((machine 'install-instruction-sequence)
(assemble controller-text machine))
machine))
(define (make-register name)
(let ((contents '*unassigned*))
(define (dispatch message)
(cond ((eq? message 'get) contents)
((eq? message 'set)
(lambda (value) (set! contents value)))
(else
(error "Unknown request: REGISTER" message))))
dispatch))
(define (get-contents register) (register 'get))
(define (set-contents! register value)
((register 'set) value))
(define (make-stack)
(let ((s '()))
(define (push x) (set! s (cons x s)))
(define (pop)
(if (null? s)
(error "Empty stack: POP")
(let ((top (car s)))
(set! s (cdr s))
top)))
(define (initialize)
(set! s '())
'done)
(define (dispatch message)
(cond ((eq? message 'push) push)
((eq? message 'pop) (pop))
((eq? message 'initialize) (initialize))
(else (error "Unknown request: STACK" message))))
dispatch))
(define (pop stack) (stack 'pop))
(define (push stack value) ((stack 'push) value))
(define (make-new-machine)
(let ((pc (make-register 'pc))
(flag (make-register 'flag))
(stack (make-stack))
(the-instruction-sequence '()))
(let ((the-ops
(list (list 'initialize-stack
(lambda () (stack 'initialize)))))
(register-table
(list (list 'pc pc) (list 'flag flag))))
(define (allocate-register name)
(if (assoc name register-table)
(error "Multiply defined register: " name)
(set! register-table
(cons (list name (make-register name))
register-table)))
'register-allocated)
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(error "Unknown register:" name))))
(define (execute)
(let ((insts (get-contents pc)))
(if (null? insts)
'done
(begin
((instruction-execution-proc (car insts)))
(execute)))))
(define (dispatch message)
(cond ((eq? message 'start)
(set-contents! pc the-instruction-sequence)
(execute))
((eq? message 'install-instruction-sequence)
(lambda (seq)
(set! the-instruction-sequence seq)))
((eq? message 'allocate-register)
allocate-register)
((eq? message 'get-register)
lookup-register)
((eq? message 'install-operations)
(lambda (ops)
(set! the-ops (append the-ops ops))))
((eq? message 'stack) stack)
((eq? message 'operations) the-ops)
(else (error "Unknown request: MACHINE"
message))))
dispatch)))
(define (start machine) (machine 'start))
(define (get-register-contents machine register-name)
(get-contents (get-register machine register-name)))
(define (set-register-contents! machine register-name value)
(set-contents! (get-register machine register-name)
value)
'done)
(define (get-register machine reg-name)
((machine 'get-register) reg-name))
5.2.2 The Assembler
(define (assemble controller-text machine)
(extract-labels
controller-text
(lambda (insts labels)
(update-insts! insts labels machine)
insts)))
(define (extract-labels text receive)
(if (null? text)
(receive '() '())
(extract-labels
(cdr text)
(lambda (insts labels)
(let ((next-inst (car text)))
(if (symbol? next-inst)
(if (assoc next-inst labels)
(error "repeated label: " next-inst)
(receive insts
(cons (make-label-entry next-inst
insts)
labels)))
(receive (cons (make-instruction next-inst)
insts)
labels)))))))
(define (update-insts! insts labels machine)
(let ((pc (get-register machine 'pc))
(flag (get-register machine 'flag))
(stack (machine 'stack))
(ops (machine 'operations)))
(for-each
(lambda (inst)
(set-instruction-execution-proc!
inst
(make-execution-procedure
(instruction-text inst)
labels machine pc flag stack ops)))
insts)))
(define (make-instruction text) (cons text '()))
(define (instruction-text inst) (car inst))
(define (instruction-execution-proc inst) (cdr inst))
(define (set-instruction-execution-proc! inst proc)
(set-cdr! inst proc))
(define (make-label-entry label-name insts)
(cons label-name insts))
(define (lookup-label labels label-name)
(let ((val (assoc label-name labels)))
(if val
(cdr val)
(error "Undefined label: ASSEMBLE"
label-name))))
(define (make-execution-procedure
inst labels machine pc flag stack ops)
(cond ((eq? (car inst) 'assign)
(make-assign inst machine labels ops pc))
((eq? (car inst) 'test)
(make-test inst machine labels ops flag pc))
((eq? (car inst) 'branch)
(make-branch inst machine labels flag pc))
((eq? (car inst) 'goto)
(make-goto inst machine labels pc))
((eq? (car inst) 'save)
(make-save inst machine stack pc))
((eq? (car inst) 'restore)
(make-restore inst machine stack pc))
((eq? (car inst) 'perform)
(make-perform inst machine labels ops pc))
(else
(error "Unknown instruction type: ASSEMBLE"
inst))))
(define (make-assign inst machine labels operations pc)
(let ((target
(get-register machine (assign-reg-name inst)))
(value-exp (assign-value-exp inst)))
(let ((value-proc
(if (operation-exp? value-exp)
(make-operation-exp
value-exp machine labels operations)
(make-primitive-exp
(car value-exp) machine labels))))
(set-contents! target (value-proc))
(advance-pc pc)))))
(define (assign-reg-name assign-instruction)
(cadr assign-instruction))
(define (assign-value-exp assign-instruction)
(cddr assign-instruction))
(define (advance-pc pc)
(set-contents! pc (cdr (get-contents pc))))
(define (make-test inst machine labels operations flag pc)
(let ((condition (test-condition inst)))
(if (operation-exp? condition)
(let ((condition-proc
(make-operation-exp
condition machine labels operations)))
(lambda ()
(set-contents! flag (condition-proc))
(advance-pc pc)))
(error "Bad TEST instruction: ASSEMBLE" inst))))
(define (test-condition test-instruction)
(cdr test-instruction))
(define (make-branch inst machine labels flag pc)
(let ((dest (branch-dest inst)))
(if (label-exp? dest)
(let ((insts
(lookup-label
labels
(label-exp-label dest))))
(lambda ()
(if (get-contents flag)
(set-contents! pc insts)
(advance-pc pc))))
(error "Bad BRANCH instruction: ASSEMBLE" inst))))
(define (branch-dest branch-instruction)
(cadr branch-instruction))
(define (make-goto inst machine labels pc)
(let ((dest (goto-dest inst)))
(cond ((label-exp? dest)
(let ((insts (lookup-label
labels
(label-exp-label dest))))
(lambda () (set-contents! pc insts))))
((register-exp? dest)
(let ((reg (get-register
machine
(register-exp-reg dest))))
(lambda ()
(set-contents! pc (get-contents reg)))))
(else (error "Bad GOTO instruction: ASSEMBLE" inst)))))
(define (goto-dest goto-instruction)
(cadr goto-instruction))
(define (make-save inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(push stack (get-contents reg))
(advance-pc pc))))
(define (make-restore inst machine stack pc)
(let ((reg (get-register machine
(stack-inst-reg-name inst))))
(lambda ()
(set-contents! reg (pop stack))
(advance-pc pc))))
(define (stack-inst-reg-name stack-instruction)
(cadr stack-instruction))
(define (make-perform inst machine labels operations pc)
(let ((action (perform-action inst)))
(if (operation-exp? action)
(let ((action-proc
(make-operation-exp
action machine labels operations)))
(lambda () (action-proc) (advance-pc pc)))
(error "Bad PERFORM instruction: ASSEMBLE" inst))))
(define (perform-action inst) (cdr inst))
(define (make-primitive-exp exp machine labels)
(cond ((constant-exp? exp)
(let ((c (constant-exp-value exp)))
(lambda () c)))
((label-exp? exp)
(let ((insts (lookup-label
labels
(label-exp-label exp))))
(lambda () insts)))
((register-exp? exp)
(let ((r (get-register machine (register-exp-reg exp))))
(lambda () (get-contents r))))
(else (error "Unknown expression type: ASSEMBLE" exp))))
(define (register-exp? exp) (tagged-list? exp 'reg))
(define (register-exp-reg exp) (cadr exp))
(define (constant-exp? exp) (tagged-list? exp 'const))
(define (constant-exp-value exp) (cadr exp))
(define (label-exp? exp) (tagged-list? exp 'label))
(define (label-exp-label exp) (cadr exp))
(define (make-operation-exp exp machine labels operations)
(let ((op (lookup-prim (operation-exp-op exp)
operations))
(aprocs
(map (lambda (e)
(make-primitive-exp e machine labels))
(operation-exp-operands exp))))
(lambda ()
(apply op (map (lambda (p) (p)) aprocs)))))
(define (operation-exp? exp)
(and (pair? exp) (tagged-list? (car exp) 'op)))
(define (operation-exp-op operation-exp)
(cadr (car operation-exp)))
(define (operation-exp-operands operation-exp)
(cdr operation-exp))
(define (lookup-prim symbol operations)
(let ((val (assoc symbol operations)))
(if val
(cadr val)
(error "Unknown operation: ASSEMBLE"
symbol))))
End of Code from 5.2
(define (empty-arglist) '())
(define (adjoin-arg arg arglist) (append arglist (list arg)))
(define (last-operand? ops) (null? (cdr ops)))
(define (no-more-exps? seq) (null? seq))
(define the-global-environment (setup-environment))
(define (get-global-environment) the-global-environment)
(define eceval-operations
(list (list 'self-evaluating? self-evaluating?)
(list 'variable? variable?)
(list 'quoted? quoted?)
(list 'assignment? assignment?)
(list 'definition? definition?)
(list 'if? if?)
(list 'cond? cond?)
(list 'lambda? lambda?)
(list 'begin? begin?)
(list 'application? application?)
(list 'lookup-variable-value lookup-variable-value)
(list 'text-of-quotation text-of-quotation)
(list 'lambda-parameters lambda-parameters)
(list 'lambda-body lambda-body)
(list 'make-procedure make-procedure)
(list 'operands operands)
(list 'operator operator)
(list 'no-operands? no-operands?)
(list 'first-operand first-operand)
(list 'rest-operands rest-operands)
(list 'empty-arglist empty-arglist)
(list 'adjoin-arg adjoin-arg)
(list 'last-operand? last-operand?)
(list 'primitive-procedure? primitive-procedure?)
(list 'compound-procedure? compound-procedure?)
(list 'apply-primitive-procedure apply-primitive-procedure)
(list 'procedure-parameters procedure-parameters)
(list 'procedure-body procedure-body)
(list 'procedure-environment procedure-environment)
(list 'extend-environment extend-environment)
(list 'begin-actions begin-actions)
(list 'last-exp? last-exp?)
(list 'first-exp first-exp)
(list 'rest-exps rest-exps)
(list 'if-predicate if-predicate)
(list 'if-consequent if-consequent)
(list 'if-alternative if-alternative)
(list 'false? false?)
(list 'true? true?)
(list 'list list)
(list 'cons cons)
(list '= =)
(list '* *)
(list '- -)
(list '+ +)
(list 'cond-clauses cond-clauses)
( list ' first - cond first - cond )
(list 'cond->if cond->if)
(list 'cond-predicate cond-predicate)
(list 'cond-actions cond-actions)
(list 'cond-else-clause? cond-else-clause?)
(list 'assignment-variable assignment-variable)
(list 'assignment-value assignment-value)
(list 'set-variable-value! set-variable-value!)
(list 'definition-variable definition-variable)
(list 'definition-value definition-value)
(list 'define-variable! define-variable!)
(list 'prompt-for-input prompt-for-input)
(list 'read read)
(list 'announce-output announce-output)
(list 'user-print user-print)
(list 'eq? eq?)
(list 'no-more-exps? no-more-exps?)
(list 'get-global-environment get-global-environment)))
(define eceval
(make-machine
'(exp env val proc argl continue unev)
eceval-operations
'(
5.4.4 Running the Evaluator
read-eval-print-loop
(perform (op initialize-stack))
(perform
(op prompt-for-input) (const ";;EC-Eval input:"))
(assign exp (op read))
(assign env (op get-global-environment))
(assign continue (label print-result))
(goto (label eval-dispatch))
print-result
(perform (op announce-output) (const ";;EC-Eval value:"))
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
unknown-expression-type
(assign val (const unknown-expression-type-error))
(goto (label signal-error))
unknown-procedure-type
(assign val (const unknown-procedure-type-error))
(goto (label signal-error))
signal-error
(perform (op user-print) (reg val))
(goto (label read-eval-print-loop))
5.4.1 The Core of the Explicit - Control Evaluator
eval-dispatch
(test (op self-evaluating?) (reg exp))
(branch (label ev-self-eval))
(test (op variable?) (reg exp))
(branch (label ev-variable))
(test (op quoted?) (reg exp))
(branch (label ev-quoted))
(test (op assignment?) (reg exp))
(branch (label ev-assignment))
(test (op definition?) (reg exp))
(branch (label ev-definition))
(test (op if?) (reg exp))
(branch (label ev-if))
added for Exercise 5.23
added for Exercise 5.23
(test (op lambda?) (reg exp))
(branch (label ev-lambda))
(test (op begin?) (reg exp))
(branch (label ev-begin))
(test (op application?) (reg exp))
(branch (label ev-application))
(goto (label unknown-expression-type))
ev-self-eval
(assign val (reg exp))
(goto (reg continue))
ev-variable
(assign val (op lookup-variable-value) (reg exp) (reg env))
(goto (reg continue))
ev-quoted
(assign val (op text-of-quotation) (reg exp))
(goto (reg continue))
ev-lambda
(assign unev (op lambda-parameters) (reg exp))
(assign exp (op lambda-body) (reg exp))
(assign val (op make-procedure) (reg unev) (reg exp) (reg env))
(goto (reg continue))
ev-application
(save continue)
(save env)
(assign unev (op operands) (reg exp))
(save unev)
(assign exp (op operator) (reg exp))
(assign continue (label ev-appl-did-operator))
(goto (label eval-dispatch))
ev-appl-did-operator
(restore env)
(assign argl (op empty-arglist))
(test (op no-operands?) (reg unev))
(branch (label apply-dispatch))
(save proc)
ev-appl-operand-loop
(save argl)
(assign exp (op first-operand) (reg unev))
(test (op last-operand?) (reg unev))
(branch (label ev-appl-last-arg))
(save env)
(save unev)
(assign continue (label ev-appl-accumulate-arg))
(goto (label eval-dispatch))
ev-appl-accumulate-arg
(restore unev)
(restore env)
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(assign unev (op rest-operands) (reg unev))
(goto (label ev-appl-operand-loop))
ev-appl-last-arg
(assign continue (label ev-appl-accum-last-arg))
(goto (label eval-dispatch))
ev-appl-accum-last-arg
(restore argl)
(assign argl (op adjoin-arg) (reg val) (reg argl))
(restore proc)
(goto (label apply-dispatch))
apply-dispatch
(test (op primitive-procedure?) (reg proc))
(branch (label primitive-apply))
(test (op compound-procedure?) (reg proc))
(branch (label compound-apply))
(goto (label unknown-procedure-type))
primitive-apply
(assign val (op apply-primitive-procedure)
(reg proc)
(reg argl))
(restore continue)
(goto (reg continue))
compound-apply
(assign unev (op procedure-parameters) (reg proc))
(assign env (op procedure-environment) (reg proc))
(assign env (op extend-environment)
(reg unev) (reg argl) (reg env))
(assign unev (op procedure-body) (reg proc))
(goto (label ev-sequence))
ev-begin
(assign unev (op begin-actions) (reg exp))
(save continue)
(goto (label ev-sequence))
( goto ( label eval - dispatch ) )
( goto ( label ev - sequence ) )
( goto ( label eval - dispatch ) )
ev-sequence
(test (op no-more-exps?) (reg unev))
(branch (label ev-sequence-end))
(assign exp (op first-exp) (reg unev))
(save unev)
(save env)
(assign continue (label ev-sequence-continue))
(goto (label eval-dispatch))
ev-sequence-continue
(restore env)
(restore unev)
(assign unev (op rest-exps) (reg unev))
(goto (label ev-sequence))
ev-sequence-end
(restore continue)
(goto (reg continue))
5.4.3 Conditionals , Assignments , and Definitions
ev-if
(save env)
(save continue)
(assign continue (label ev-if-decide))
(assign exp (op if-predicate) (reg exp))
ev-if-decide
(restore continue)
(restore env)
(restore exp)
(test (op true?) (reg val))
(branch (label ev-if-consequent))
ev-if-alternative
(assign exp (op if-alternative) (reg exp))
(goto (label eval-dispatch))
ev-if-consequent
(assign exp (op if-consequent) (reg exp))
(goto (label eval-dispatch))
Added for Exercise 5.23
ev-cond
(assign exp (op cond->if) (reg exp))
(goto (label ev-if))
ev-assignment
(assign unev (op assignment-variable) (reg exp))
(save unev)
(assign exp (op assignment-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-assignment-1))
(goto (label eval-dispatch))
ev-assignment-1
(restore continue)
(restore env)
(restore unev)
(perform
(op set-variable-value!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
ev-definition
(assign unev (op definition-variable) (reg exp))
(save unev)
(assign exp (op definition-value) (reg exp))
(save env)
(save continue)
(assign continue (label ev-definition-1))
(goto (label eval-dispatch))
ev-definition-1
(restore continue)
(restore env)
(restore unev)
(perform
(op define-variable!) (reg unev) (reg val) (reg env))
(assign val (const ok))
(goto (reg continue))
)))
(start eceval)
Exercise 5.23 ( page 758 )
EC - Eval input :
(define (positive? x)
(cond ((> x 0) 'positive)
((= x 0) 'zero)
(else 'negative)))
( define ( positive ? x ) ( cond ( ( > x 0 ) ' positive ) ( (= x 0 ) ' zero ) ( else ' negative ) ) )
EC - Eval input :
(define (positive? x)
(cond ((> x 0) 'positive)
((= x 0) 'zero)
(else 'negative)))
EC - Eval value :
EC - Eval input :
(positive? 10)
EC - Eval value :
EC - Eval input :
(positive? 0)
EC - Eval value :
zero
EC - Eval input :
(positive? -10)
EC - Eval value :
|
502c08978d293b75b4780fe9cbcd3c7af1e1bcb29576c96d6ad175034f6c7c07 | crategus/cl-cffi-gtk | gtk.builder.lisp | ;;; ----------------------------------------------------------------------------
;;; gtk.builder.lisp
;;;
;;; The documentation of this file is taken from the GTK 3 Reference Manual
Version 3.24 and modified to document the Lisp binding to the GTK library .
;;; See <>. The API documentation of the Lisp binding is
available from < -cffi-gtk/ > .
;;;
Copyright ( C ) 2009 - 2011
Copyright ( C ) 2011 - 2021
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License for Lisp
as published by the Free Software Foundation , either version 3 of the
;;; License, or (at your option) any later version and with a preamble to
the GNU Lesser General Public License that clarifies the terms for use
;;; with Lisp programs and is referred as the LLGPL.
;;;
;;; 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 and the preamble to the Gnu Lesser
;;; General Public License. If not, see </>
;;; and <>.
;;; ----------------------------------------------------------------------------
;;;
GtkBuilder
;;;
;;; Build an interface from an XML UI definition
;;;
;;; Types and Values
;;;
GtkBuilder
;;; GtkBuilderError
;;;
;;; Functions
;;;
;;; GtkBuilderConnectFunc
;;;
gtk_builder_new
;;; gtk_builder_new_from_file
;;; gtk_builder_new_from_resource
;;; gtk_builder_new_from_string
;;; gtk_builder_add_callback_symbol
;;; gtk_builder_add_callback_symbols
;;; gtk_builder_lookup_callback_symbol
;;; gtk_builder_add_from_file
gtk_builder_add_from_resource
;;; gtk_builder_add_from_string
;;; gtk_builder_add_objects_from_file
;;; gtk_builder_add_objects_from_string
;;; gtk_builder_add_objects_from_resource
;;; gtk_builder_extend_with_template
;;; gtk_builder_get_object
;;; gtk_builder_get_objects
;;; gtk_builder_expose_object
;;; gtk_builder_connect_signals
gtk_builder_connect_signals_full
gtk_builder_set_translation_domain
gtk_builder_get_translation_domain
;;; gtk_builder_set_application
;;; gtk_builder_get_application
;;; gtk_builder_get_type_from_name
;;; gtk_builder_value_from_string
gtk_builder_value_from_string_type
;;;
GTK_BUILDER_WARN_INVALID_CHILD_TYPE
;;;
;;; Properties
;;;
;;; gchar* translation-domain Read / Write
;;;
;;; Object Hierarchy
;;;
;;; GObject
;;; ╰── GtkBuilder
;;; ----------------------------------------------------------------------------
(in-package :gtk)
;;; ----------------------------------------------------------------------------
;;; enum GtkBuilderError
;;; ----------------------------------------------------------------------------
(define-g-enum "GtkBuilderError" gtk-builder-error
(:export t
:type-initializer "gtk_builder_error_get_type")
(:invalid-type-function 0)
(:unhandled-tag 1)
(:missing-attribute 2)
(:invalid-attribute 3)
(:invalid-tag 4)
(:missing-property-value 5)
(:invalid-value 6)
(:version-mismatch 7)
(:duplicate-id 8)
(:type-refused 9)
(:template-mismatch 10)
(:invalid-property 11)
(:invalid-signal 12)
(:invalid-id 13))
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-builder-error atdoc:*symbol-name-alias*)
"GEnum"
(gethash 'gtk-builder-error atdoc:*external-symbols*)
"@version{2021-9-23}
@begin{short}
Error codes that identify various errors that can occur while parsing the
@class{gtk-builder} UI definition.
@end{short}
@begin{pre}
(define-g-enum \"GtkBuilderError\" gtk-builder-error
(:export t
:type-initializer \"gtk_builder_error_get_type\")
(:invalid-type-function 0)
(:unhandled-tag 1)
(:missing-attribute 2)
(:invalid-attribute 3)
(:invalid-tag 4)
(:missing-property-value 5)
(:invalid-value 6)
(:version-mismatch 7)
(:duplicate-id 8)
(:type-refused 9)
(:template-mismatch 10)
(:invalid-property 11)
(:invalid-signal 12)
(:invalid-id 13))
@end{pre}
@begin[code]{table}
@entry[:invalid-type-function]{A @code{type-func} attribute did not name a
function that returns a @class{g-type} type ID.}
@entry[:unhandled-tag]{The input contained a tag that a @class{gtk-builder}
object cannot handle.}
@entry[:missing-attribute]{An attribute that is required by a
@class{gtk-builder} object was missing.}
@entry[:invalid-attribute]{A @class{gtk-builder} object found an attribute
that it does not understand.}
@entry[:invalid-tag]{A @class{gtk-builder} object found a tag that it does
not understand.}
@entry[:missing-property-value]{A required property value was missing.}
@entry[:invalid-value]{A @class{gtk-builder} object could not parse some
attribute value.}
@entry[:version-mismatch]{The input file requires a newer version of GTK.}
@entry[:duplicate-id]{An object ID occurred twice.}
@entry[:type-refused]{A specified object type is of the same type or derived
from the type of the composite class being extended with builder XML.}
@entry[:template-mismatch]{The wrong type was specified in a composite
class’s template XML.}
@entry[:invalid-property]{The specified property is unknown for the object
class.}
@entry[:invalid-signal]{The specified signal is unknown for the object
class.}
@entry[:invalid-id]{An object ID is unknown.}
@end{table}
@see-class{gtk-builder}")
;;; ----------------------------------------------------------------------------
struct GtkBuilder
;;; ----------------------------------------------------------------------------
(define-g-object-class "GtkBuilder" gtk-builder
(:superclass g-object
:export t
:interfaces nil
:type-initializer "gtk_builder_get_type")
((translation-domain
gtk-builder-translation-domain
"translation-domain" "gchararray" t t)))
;;; This Lisp extension is not documented
(defmethod initialize-instance :after ((builder gtk-builder)
&key from-file from-string)
(when from-file
(gtk-builder-add-from-file builder from-file))
(when from-string
(gtk-builder-add-from-string builder from-string)))
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-builder 'type)
"@version{*2021-10-10}
@begin{short}
A @sym{gtk-builder} object is an auxiliary object that reads textual
descriptions of a user interface and instantiates the described objects.
@end{short}
To create a @sym{gtk-builder} object from a user interface description,
call the @fun{gtk-builder-new-from-file}, @fun{gtk-builder-new-from-resource}
or @fun{gtk-builder-new-from-string} functions.
In the (unusual) case that you want to add user interface descriptions from
multiple sources to the same @sym{gtk-builder} object you can call the
@fun{gtk-builder-new} function to get an empty builder and populate it by
(multiple) calls to the @fun{gtk-builder-add-from-file},
@fun{gtk-builder-add-from-resource} or @fun{gtk-builder-add-from-string}
functions.
A @sym{gtk-builder} object holds a reference to all objects that it has
constructed and drops these references when it is finalized. This finalization
can cause the destruction of non-widget objects or widgets which are not
contained in a toplevel window. For toplevel windows constructed by a builder,
it is the responsibility of the user to call the @fun{gtk-widget-destroy}
function to get rid of them and all the widgets they contain.
The @fun{gtk-builder-object} and @fun{gtk-builder-objects} functions can be
used to access the widgets in the interface by the names assigned to them
inside the UI description. Toplevel windows returned by these functions will
stay around until the user explicitly destroys them with the
@fun{gtk-widget-destroy} function. Other widgets will either be part of a
larger hierarchy constructed by the builder, in which case you should not have
to worry about their life cycle, or without a parent, in which case they have
to be added to some container to make use of them.
The @fun{gtk-builder-connect-signals} function and variants thereof can be
used to connect handlers to the named signals in the UI description.
@subheading{GtkBuilder UI Definitions}
The @sym{gtk-builder} implementation parses textual descriptions of user
interfaces which are specified in an XML format which can be roughly described
by the RELAX NG schema below. We refer to these descriptions as
@sym{gtk-builder} UI definitions or just UI definitions if the context is
clear. Do not confuse @sym{gtk-builder} UI Definitions with the deprecated
@class{gtk-ui-manager} UI Definitions, which are more limited in scope. It is
common to use @code{.ui} as the filename extension for files containing
@sym{gtk-builder} UI definitions.
@begin{pre}
start = element interface {
attribute domain { text @} ?,
( requires | object | menu ) *
@}
requires = element requires {
attribute lib { text @},
attribute version { text @}
@}
object = element object {
attribute id { xsd:ID @},
attribute class { text @},
attribute type-func { text @} ?,
attribute constructor { text @} ?,
(property | signal | child | ANY) *
@}
template = element template {
attribute class { text @},
attribute parent { text @},
(property | signal | child | ANY) *
@}
property = element property {
attribute name { text @},
attribute translatable { \"yes\" | \"no\" @} ?,
attribute comments { text @} ?,
attribute context { text @} ?,
text ?
@}
signal = element signal {
attribute name { text @},
attribute handler { text @},
attribute after { text @} ?,
attribute swapped { text @} ?,
attribute object { text @} ?,
attribute last_modification_time { text @} ?,
empty
@}
child = element child {
attribute type { text @} ?,
attribute internal-child { text @} ?,
(object | ANY)*
@}
menu = element menu {
attribute id { xsd:ID @},
attribute domain { text @} ?,
(item | submenu | section) *
@}
item = element item {
attribute id { xsd:ID @} ?,
(attribute_ | link) *
@}
attribute_ = element attribute {
attribute name { text @},
attribute type { text @} ?,
attribute translatable { \"yes\" | \"no\" @} ?,
attribute context { text @} ?,
attribute comments { text @} ?,
text ?
@}
link = element link {
attribute id { xsd:ID @} ?,
attribute name { text @},
item *
@}
submenu = element submenu {
attribute id { xsd:ID @} ?,
(attribute_ | item | submenu | section) *
@}
section = element section {
attribute id { xsd:ID @} ?,
(attribute_ | item | submenu | section) *
@}
ANY = element * - (interface | requires | object | property | signal
| child | menu | item | attribute | link
| submenu | section) {
attribute * { text @} *,
(ALL * & text ?)
@}
ALL = element * {
attribute * { text @} *,
(ALL * & text ?)
@}
@end{pre}
The toplevel element is @code{<interface>}. It optionally takes a
@code{\"domain\"} attribute, which will make the builder look for translated
strings using GNU gettext in the domain specified. This can also be done by
calling the @fun{gtk-builder-translation-domain} function on the builder.
Objects are described by @code{<object>} elements, which can contain
@code{<property>} elements to set properties, @code{<signal>} elements which
connect signals to handlers, and @code{<child>} elements, which describe child
objects, most often widgets inside a container, but also e.g. actions in an
action group, or columns in a tree model. A @code{<child>} element contains an
@code{<object>} element which describes the child object. The target toolkit
version(s) are described by @code{<requires>} elements, the @code{\"lib\"}
attribute specifies the widget library in question, (currently the only
supported value is @code{\"gtk+\"} and the @code{\"version\"} attribute
specifies the target version in the form @code{\"<major>.<minor>\"}. The
builder will error out if the version requirements are not met.
Typically, the specific kind of object represented by an @code{<object>}
element is specified by the @code{\"class\"} attribute. If the type has not
been loaded yet, GTK tries to find the @code{_get_type()} from the class
name by applying heuristics. This works in most cases, but if necessary, it
is possible to specify the name of the @code{_get_type()} explictly with the
@code{\"type-func\"} attribute. As a special case, the @sym{gtk-builder}
implementation allows to use an object that has been constructed by a
@class{gtk-ui-manager} object in another part of the UI definition by
specifying the ID of the @class{gtk-ui-manager} object in the
@code{\"constructor\"} attribute and the name of the object in the
@code{\"id\"} attribute.
Objects must be given a name with the @code{\"ID\"} attribute, which allows
the application to retrieve them from the builder with the
@fun{gtk-builder-object} function. An ID is also necessary to use the object
as property value in other parts of the UI definition.
@subheading{Note}
Prior to 2.20, the @sym{gtk-builder} implementation was setting the
@code{\"name\"} property of constructed widgets to the @code{\"id\"}
attribute. In GTK 2.20 or newer, you have to use the @fun{gtk-buildable-name}
function instead of the @fun{gtk-widget-name} function to obtain the
@code{\"id\"}, or set the @code{\"name\"} property in your UI definition.
Setting properties of objects is pretty straightforward with the
@code{<property>} element: the @code{\"name\"} attribute specifies the name
of the property, and the content of the element specifies the value. If the
@code{\"translatable\"} attribute is set to a true value, GTK uses GNU
gettext to find a translation for the value. This happens before the value is
parsed, so it can be used for properties of any type, but it is probably most
useful for string properties. It is also possible to specify a context to
disambiguate short strings, and comments which may help the translators.
The @sym{gtk-builder} implementation can parse textual representations for
the most common property types: characters, strings, integers, floating point
numbers, booleans, strings like \"TRUE\", \"t\", \"yes\", \"y\", \"1\" are
interpreted as @em{true}, strings like \"FALSE\", \"f\", \"no\", \"n\", \"0\"
are interpreted as @em{false}), enumerations, can be specified by their name,
nick or integer value, flags, can be specified by their name, nick, integer
value, optionally combined with \"|\", e.g. \"GTK_VISIBLE | GTK_REALIZED\",
and colors, in a format understood by the @fun{gdk-rgba-parse} function.
Objects can be referred to by their name. Pixbufs can be specified as a
filename of an image file to load. In general, the @sym{gtk-builder}
implementation allows forward references to objects - an object does not have
to be constructed before it can be referred to. The exception to this rule is
that an object has to be constructed before it can be used as the value of a
construct-only property.
Signal handlers are set up with the @code{<signal>} element. The
@code{\"name\"} attribute specifies the name of the signal, and the
@code{\"handler\"} attribute specifies the function to connect to the signal.
By default, GTK tries to find the handler using the @code{g_module_symbol()}
function, but this can be changed by passing a custom
@code{GtkBuilderConnectFunc} callback function to the
@fun{gtk-builder-connect-signals-full} function. The remaining attributes,
@code{\"after\"}, @code{\"swapped\"} and @code{\"object\"}, have the same
meaning as the corresponding parameters of the
@code{g_signal_connect_object()} or @code{g_signal_connect_data()} functions.
A @code{\"last_modification_time\"} attribute is also allowed, but it does not
have a meaning to the builder.
Sometimes it is necessary to refer to widgets which have implicitly been
constructed by GTK as part of a composite widget, to set properties on them
or to add further children, e.g. the @code{vbox} of a @class{gtk-dialog}
widget. This can be achieved by setting the @code{\"internal-child\"} propery
of the @code{<child>} element to a @em{true} value. Note that a
@sym{gtk-builder} object still requires an @code{<object>} element for the
internal child, even if it has already been constructed.
A number of widgets have different places where a child can be added, e.g.
tabs versus page content in notebooks. This can be reflected in a UI
definition by specifying the @code{\"type\"} attribute on a @code{<child>}.
The possible values for the @code{\"type\"} attribute are described in the
sections describing the widget specific portions of UI definitions.
@b{Example:} A @sym{gtk-builder} UI Definition
@begin{pre}
<interface>
<object class=\"GtkDialog\" id=\"dialog1\">
<child internal-child=\"vbox\">
<object class=\"GtkVBox\" id=\"vbox1\">
<property name=\"border-width\">10</property>
<child internal-child=\"action_area\">
<object class=\"GtkHButtonBox\" id=\"hbuttonbox1\">
<property name=\"border-width\">20</property>
<child>
<object class=\"GtkButton\" id=\"ok_button\">
<property name=\"label\">gtk-ok</property>
<property name=\"use-stock\">TRUE</property>
<signal name=\"clicked\" handler=\"ok_button_clicked\"/>
</object>
</child>
</object>
</child>
</object>
</child>
</object>
</interface>
@end{pre}
Beyond this general structure, several object classes define their own XML
DTD fragments for filling in the ANY placeholders in the DTD above. Note
that a custom element in a @code{<child>} element gets parsed by the custom
tag handler of the parent object, while a custom element in an @code{<object>}
element gets parsed by the custom tag handler of the object.
These XML fragments are explained in the documentation of the respective
objects.
Additionally, since 3.10 a special @code{<template>} tag has been added to the
format allowing one to define a widget class's components.
@subheading{Embedding other XML}
Apart from the language for UI descriptions that has been explained in the
previous section, the @sym{gtk-builder} implementation can also parse XML
fragments of @code{GMenu} markup. The resulting @class{g-menu} object and its
named submenus are available via the @fun{gtk-builder-object} function like
other constructed objects.
@see-slot{gtk-builder-translation-domain}
@see-class{gtk-buildable}")
;;; ----------------------------------------------------------------------------
;;; Property and Accessor Details
;;; ----------------------------------------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "translation-domain"
'gtk-builder) 't)
"The @code{translation-domain} property of type @code{:string} (Read / Write)
@br{}
The translation domain used when translating property values that have been
marked as translatable in interface descriptions. If the translation domain
is @code{nil}, the @sym{gtk-builder} object uses GNU gettext, otherwise
GLIB gettext. @br{}
Default value: @code{nil}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-builder-translation-domain atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-builder-translation-domain 'function)
"@version{2021-9-3}
@syntax[]{(gtk-builder-translation-domain object) => domain}
@syntax[]{(setf (gtk-builder-translation-domain object) domain)}
@argument[object]{a @class{gtk-builder} object}
@argument[domain]{a string with the translation domain or @code{nil}}
@begin{short}
Accessor of the @slot[gtk-builder]{translation-domain} slot of the
@class{gtk-builder} class.
@end{short}
The @sym{gtk-builder-translation-domain} slot access function gets the
translation domain of @arg{object}. The
@sym{(setf gtk-builder-translation-domain)} slot access function sets the
translation domain.
@see-class{gtk-builder}")
;;; ----------------------------------------------------------------------------
gtk_builder_new ( )
;;; ----------------------------------------------------------------------------
(declaim (inline gtk-builder-new))
(defun gtk-builder-new ()
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@return{A new @class{gtk-builder} object.}
@begin{short}
Creates a new builder object.
@end{short}
@see-class{gtk-builder}
@see-function{gtk-builder-new-from-file}
@see-function{gtk-builder-new-from-resource}
@see-function{gtk-builder-new-from-string}"
(make-instance 'gtk-builder))
(export 'gtk-builder-new)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_new_from_file ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_new_from_file" gtk-builder-new-from-file)
(g-object gtk-builder)
#+cl-cffi-gtk-documentation
"@version{*2021-11-30}
@argument[filename]{a string with the filename}
@return{A @class{gtk-builder} object containing the described interface.}
@begin{short}
Builds the @class{gtk-builder} UI definition from a user interface
description file.
@end{short}
If there is an error opening the file or parsing the description then the
program will be aborted. You should only ever attempt to parse user interface
descriptions that are shipped as part of your program.
@see-class{gtk-builder}"
(filename :string))
(export 'gtk-builder-new-from-file)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_new_from_resource ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_new_from_resource" gtk-builder-new-from-resource)
(g-object gtk-builder)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[path]{a string with the @class{g-resource} path}
@return{A @class{gtk-builder} object containing the described interface.}
@begin{short}
Builds the @class{gtk-builder} UI definition from a resource path.
@end{short}
If there is an error locating the resource or parsing the description then
the program will be aborted.
@see-class{gtk-builder}
@see-class{g-resource}
@see-function{gtk-builder-new}
@see-function{gtk-builder-new-from-file}
@see-function{gtk-builder-new-from-string}"
(path :string))
(export 'gtk-builder-new-from-resource)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_new_from_string ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_new_from_string" %gtk-builder-new-from-string)
(g-object gtk-builder)
(string :string)
(length :int))
(defun gtk-builder-new-from-string (string)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[string]{a string with the user interface description}
@return{A @class{gtk-builder} object containing the interface described by
@arg{string}.}
@begin{short}
Builds the user interface described by @arg{string} in the
@class{gtk-builder} UI definition format.
@end{short}
If there is an error parsing the string then the program will be aborted. You
should not attempt to parse user interface description from untrusted
sources.
@see-class{gtk-builder}
@see-function{gtk-builder-new}
@see-function{gtk-builder-new-from-file}
@see-function{gtk-builder-new-from-resource}"
(%gtk-builder-new-from-string string -1))
(export 'gtk-builder-new-from-string)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_add_callback_symbol ()
;;;
void gtk_builder_add_callback_symbol ( GtkBuilder * builder ,
;;; const gchar *callback_name,
;;; GCallback callback_symbol);
;;;
;;; Adds the callback_symbol to the scope of builder under the given
;;; callback_name .
;;;
;;; Using this function overrides the behavior of gtk_builder_connect_signals()
;;; for any callback symbols that are added. Using this method allows for better
;;; encapsulation as it does not require that callback symbols be declared in
;;; the global namespace.
;;;
;;; builder :
a GtkBuilder
;;;
;;; callback_name :
The name of the callback , as expected in the XML
;;;
;;; callback_symbol :
;;; The callback pointer.
;;;
Since 3.10
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; gtk_builder_add_callback_symbols ()
;;;
;;; void gtk_builder_add_callback_symbols (GtkBuilder *builder,
;;; const gchar *first_callback_name,
;;; GCallback first_callback_symbol,
;;; ...);
;;;
;;; A convenience function to add many callbacks instead of calling
;;; gtk_builder_add_callback_symbol() for each symbol.
;;;
;;; builder :
a GtkBuilder
;;;
;;; first_callback_name :
The name of the callback , as expected in the XML
;;;
;;; first_callback_symbol :
;;; The callback pointer.
;;;
;;; ... :
;;; A list of callback name and callback symbol pairs terminated with NULL
;;;
Since 3.10
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; gtk_builder_lookup_callback_symbol ()
;;;
;;; GCallback gtk_builder_lookup_callback_symbol (GtkBuilder *builder,
;;; const gchar *callback_name);
;;;
a symbol previously added to builder with
;;; gtk_builder_add_callback_symbols()
;;;
;;; This function is intended for possible use in language bindings or for any
;;; case that one might be cusomizing signal connections using
gtk_builder_connect_signals_full ( )
;;;
;;; builder :
a GtkBuilder
;;;
;;; callback_name :
;;; The name of the callback
;;;
;;; Returns :
;;; The callback symbol in builder for callback_name , or NULL
;;;
Since 3.10
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; gtk_builder_add_from_file ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_add_from_file" %gtk-builder-add-from-file) :uint
(builder (g-object gtk-builder))
(filename :string)
(err :pointer))
(defun gtk-builder-add-from-file (builder filename)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[filename]{a string with the name of the file to parse}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a file containing a @class{gtk-builder} UI definition and merges it
with the current contents of the builder.
@end{short}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-resource}
@see-function{gtk-builder-add-from-string}"
(with-g-error (err)
(%gtk-builder-add-from-file builder filename err)))
(export 'gtk-builder-add-from-file)
;;; ----------------------------------------------------------------------------
gtk_builder_add_from_resource ( )
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_add_from_resource" %gtk-builder-add-from-resource) :uint
(builder (g-object gtk-builder))
(path :string)
(err :pointer))
(defun gtk-builder-add-from-resource (builder path)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[path]{a string with the path of the resouce file to parse}
@return{A positive value on success, 0 if an error occured.}
@begin{short}
Parses a resource file containing a @class{gtk-builder} UI definition and
merges it with the current contents of the builder.
@end{short}
@see-class{gtk-builder}
@see-class{g-resource}
@see-function{gtk-builder-add-from-file}
@see-function{gtk-builder-add-from-string}"
(with-g-error (err)
(%gtk-builder-add-from-resource builder path err)))
(export 'gtk-builder-add-from-resource)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_add_from_string ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_add_from_string" %gtk-builder-add-from-string) :uint
(builder (g-object gtk-builder))
(string :string)
(length :int)
(err :pointer))
(defun gtk-builder-add-from-string (builder string)
#+cl-cffi-gtk-documentation
"@version{*2021-10-10}
@argument[builder]{a @class{gtk-builder} object}
@argument[string]{the string to parse}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a string containing a @class{gtk-builder} UI definition and merges
it with the current contents of the builder.
@end{short}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-file}
@see-function{gtk-builder-add-from-resource}"
(with-g-error (err)
(%gtk-builder-add-from-string builder string -1 err)))
(export 'gtk-builder-add-from-string)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_add_objects_from_file ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_add_objects_from_file"
%gtk-builder-add-objects-from-file) :uint
(builder (g-object gtk-builder))
(filename :string)
(object-ids :pointer)
(err :pointer))
(defun gtk-builder-add-objects-from-file (builder filename ids)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[filename]{a string with the name of the file to parse}
@argument[ids]{a list of strings with the object IDs to build}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a file containing a @class{gtk-builder} UI definition building only
the requested objects and merges them with the current contents of builder.
@end{short}
Upon errors 0 will be returned.
@begin[Note]{dictionary}
If you are adding an object that depends on an object that is not its
child, for instance a @class{gtk-tree-view} widget that depends on its
@class{gtk-tree-model} implementation, you have to explicitely list all of
them in @arg{ids}.
@end{dictionary}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-file}
@see-function{gtk-builder-add-objects-from-string}
@see-function{gtk-builder-add-objects-from-resource}"
(let ((ids-ptr (foreign-alloc :pointer :count (1+ (length ids)))))
(loop for i from 0
for object-id in ids
do (setf (mem-aref ids-ptr :pointer i)
(foreign-string-alloc object-id)))
(setf (mem-aref ids-ptr :pointer (length ids)) (null-pointer))
(unwind-protect
(with-g-error (err)
(%gtk-builder-add-objects-from-file builder filename ids-ptr err))
(progn
(loop for i from 0
repeat (1- (length ids))
do (foreign-string-free (mem-aref ids-ptr :pointer i)))
(foreign-free ids-ptr)))))
(export 'gtk-builder-add-objects-from-file)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_add_objects_from_string ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_add_objects_from_string"
%gtk-builder-add-objects-from-string) :uint
(builder (g-object gtk-builder))
(string :string)
(length :int)
(ids :pointer)
(err :pointer))
(defun gtk-builder-add-objects-from-string (builder string ids)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[string]{the string to parse}
@argument[ids]{list of strings with the object IDs to build}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a string containing a @class{gtk-builder} UI definition building only
the requested objects and merges them with the current contents of builder.
@end{short}
@begin[Note]{dictionary}
If you are adding an object that depends on an object that is not its child,
for instance a @class{gtk-tree-view} widget that depends on its
@class{gtk-tree-model} implementation, you have to explicitely list all of
them in @arg{ids}.
@end{dictionary}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-string}
@see-function{gtk-builder-add-objects-from-file}
@see-function{gtk-builder-add-objects-from-resource}"
(let ((ids-ptr (foreign-alloc :pointer :count (1+ (length ids)))))
(loop for i from 0
for object-id in ids
do (setf (mem-aref ids-ptr :pointer i)
(foreign-string-alloc object-id)))
(setf (mem-aref ids-ptr :pointer (length ids)) (null-pointer))
(unwind-protect
(with-g-error (err)
(%gtk-builder-add-objects-from-string builder string -1 ids-ptr err))
(progn
(loop for i from 0
repeat (1- (length ids))
do (foreign-string-free (mem-aref ids-ptr :pointer i)))
(foreign-free ids-ptr)))))
(export 'gtk-builder-add-objects-from-string)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_add_objects_from_resource ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_add_objects_from_resource"
%gtk-builder-add-objects-from-resource) :uint
(builder (g-object gtk-builder))
(path :string)
(ids :pointer)
(err :pointer))
(defun gtk-builder-add-objects-from-resource (builder path ids)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[path]{a string with the path of the resource file to parse}
@argument[ids]{list of strings with the object IDs to build}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a resource file containing a @class{gtk-builder} UI definition
building only the requested objects and merges them with the current
contents of builder.
@end{short}
@begin[Note]{dictionary}
If you are adding an object that depends on an object that is not its
child, for instance a @class{gtk-tree-view} widget that depends on its
@class{gtk-tree-model} implementation, you have to explicitely list all of
them in @arg{ids}.
@end{dictionary}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-resource}
@see-function{gtk-builder-add-objects-from-file}
@see-function{gtk-builder-add-objects-from-string}"
(let ((ids-ptr (foreign-alloc :pointer :count (1+ (length ids)))))
(loop for i from 0
for object-id in ids
do (setf (mem-aref ids-ptr :pointer i)
(foreign-string-alloc object-id)))
(unwind-protect
(with-g-error (err)
(%gtk-builder-add-objects-from-resource builder path ids-ptr err))
(progn
(loop for i from 0
repeat (1- (length ids))
do (foreign-string-free (mem-aref ids-ptr :pointer i)))
(foreign-free ids-ptr)))))
(export 'gtk-builder-add-objects-from-resource)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_extend_with_template ()
;;;
guint
;;; gtk_builder_extend_with_template (GtkBuilder *builder,
;;; GtkWidget *widget,
GType template_type ,
;;; const gchar *buffer,
;;; gsize length,
;;; GError **error);
;;;
;;; Main private entry point for building composite container components from
template XML .
;;;
;;; This is exported purely to let gtk-builder-tool validate templates,
;;; applications have no need to call this function.
;;;
;;; builder :
a GtkBuilder
;;;
;;; widget :
;;; the widget that is being extended
;;;
;;; template_type :
;;; the type that the template is for
;;;
;;; buffer :
;;; the string to parse
;;;
;;; length :
the length of buffer ( may be -1 if buffer is nul - terminated )
;;;
;;; error :
;;; return location for an error, or NULL.
;;;
;;; Returns :
;;; A positive value on success, 0 if an error occurred
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
;;; gtk_builder_get_object () -> gtk-builder-object
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_get_object" gtk-builder-object) g-object
#+cl-cffi-gtk-documentation
"@version{*2021-10-10}
@argument[builder]{a @class{gtk-builder} object}
@argument[name]{a string with the name of the object to get}
@return{The @class{g-object} instance named @arg{name} or @code{nil} if it
could not be found in the object tree.}
@begin{short}
Gets the object named @arg{name} from the @class{gtk-builder} UI definition.
@end{short}
@see-class{gtk-builder}
@see-class{g-object}
@see-function{gtk-builder-objects}"
(builder (g-object gtk-builder))
(name :string))
(export 'gtk-builder-object)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_get_objects () -> gtk-builder-objects
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_get_objects" gtk-builder-objects) (g-slist g-object)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@begin{return}
A list containing all the @class{g-object} instances constructed by the
@class{gtk-builder} object.
@end{return}
@begin{short}
Gets all objects that have been constructed by the builder.
@end{short}
@see-class{gtk-builder}
@see-class{g-object}
@see-function{gtk-builder-object}"
(builder (g-object gtk-builder)))
(export 'gtk-builder-objects)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_expose_object ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_expose_object" gtk-builder-expose-object) :void
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[name]{a string with the name of the object exposed to the builder}
@argument[object]{a @class{g-object} instance to expose}
@begin{short}
Adds an object to the builder object pool so it can be referenced just like
any other object built by the builder.
@end{short}
@see-class{gtk-builder}
@see-class{g-object}"
(builder (g-object gtk-builder))
(name :string)
(object g-object))
(export 'gtk-builder-expose-object)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_connect_signals ()
;;; ----------------------------------------------------------------------------
;; TODO: The documentation does not explain this implementation.
(defun gtk-builder-connect-signals (builder handlers)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[handlers]{a list sent in as user data to all signals}
@begin{short}
This method is a simpler variation of the
@fun{gtk-builder-connect-signals-full} function.
@end{short}
It uses introspective features of @code{GModule} to look at the symbol table
of the application. From here it tries to match the signal handler names given
in the interface description with symbols in the application and connects the
signals. Note that this function can only be called once, subsequent calls
will do nothing.
Note that this function will not work correctly if @code{GModule} is not
supported on the platform.
When compiling applications for Windows, you must declare signal callbacks
with @code{G_MODULE_EXPORT}, or they will not be put in the symbol table. On
Linux and Unices, this is not necessary.
@see-class{gtk-builder}
@see-function{gtk-builder-connect-signals-full}"
(flet ((connect-func (builder
object
signal-name
handler-name
connect-object
flags)
(declare (ignore builder connect-object))
(let ((handler (find handler-name
handlers
:key 'first :test 'string=)))
(when handler
(g-signal-connect object
signal-name
(second handler)
:after (member :after flags))))))
(gtk-builder-connect-signals-full builder #'connect-func)))
(export 'gtk-builder-connect-signals)
;;; ----------------------------------------------------------------------------
;;; GtkBuilderConnectFunc ()
;;; ----------------------------------------------------------------------------
(defcallback gtk-builder-connect-func :void
((builder (g-object gtk-builder))
(object g-object)
(signal (:string :free-from-foreign nil))
(handler (:string :free-from-foreign nil))
(connect g-object)
(flags g-connect-flags)
(data :pointer))
(restart-case
(let ((ptr (get-stable-pointer-value data)))
(funcall ptr builder object signal handler connect flags))
(return () nil)))
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-builder-connect-func atdoc:*symbol-name-alias*)
"Callback"
(gethash 'gtk-builder-connect-func atdoc:*external-symbols*)
"@version{2021-9-23}
@begin{short}
This is the signature of a callback function used to connect signals.
@end{short}
It is used by the @fun{gtk-builder-connect-signals} and
@fun{gtk-builder-connect-signals-full} functions. It is mainly intended for
interpreted language bindings, but could be useful where the programmer wants
more control over the signal connection process. Note that this function can
only be called once, subsequent calls will do nothing.
@begin{pre}
lambda (builder object signal-name handler-name connect-object flags)
@end{pre}
@begin[code]{table}
@entry[builder]{a @class{gtk-builder} object}
@entry[object]{a @class{g-object} instance to connect a signal to}
@entry[signal-name]{a string with the name of the signal}
@entry[handler-name]{a string with the name of the handler}
@entry[connect-object]{a @class{g-object} instance, if non-@code{nil}, use
the @fun{g-signal-connect-object} function}
@entry[flags]{a value of the @symbol{g-connect-flags} flags to use}
@end{table}
@see-class{gtk-builder}
@see-function{gtk-builder-connect-signals}
@see-function{gtk-builder-connect-signals-full}")
(export 'gtk-builder-connect-func)
;;; ----------------------------------------------------------------------------
gtk_builder_connect_signals_full ( )
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_connect_signals_full" %gtk-builder-connect-signals-full)
:void
(builder (g-object gtk-builder))
(func :pointer)
(data :pointer))
(defun gtk-builder-connect-signals-full (builder func)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[func]{a @symbol{gtk-builder-connect-func} callback function used to
connect the signals}
@begin{short}
This function can be thought of the interpreted language binding version of
the @fun{gtk-builder-connect-signals} function.
@end{short}
@see-class{gtk-builder}
@see-symbol{gtk-builder-connect-func}
@see-function{gtk-builder-connect-signals}"
(with-stable-pointer (ptr func)
(%gtk-builder-connect-signals-full builder
(callback gtk-builder-connect-func)
ptr)))
(export 'gtk-builder-connect-signals-full)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_get_application ()
;;; gtk_builder_set_application () -> gtk-builder-application
;;; ----------------------------------------------------------------------------
(defun (setf gtk-builder-application) (application builder)
(foreign-funcall "gtk_builder_set_application"
(g-object gtk-builder) builder
(g-object gtk-application) application
:void)
application)
(defcfun ("gtk_builder_get_application" gtk-builder-application)
(g-object gtk-application)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@syntax[]{(gtk-builder-application builder) => application}
@syntax[]{(setf (gtk-builder-application builder) application)}
@argument[builder]{a @class{gtk-builder} object}
@argument[application]{a @class{gtk-application} instance}
@begin{short}
Accessor of the application associated with the builder.
@end{short}
The @sym{gtk-builder-application} function gets the application associated
with the builder. The @sym{(setf gtk-builder-application)} function sets the
application.
The application is used for creating action proxies as requested from XML
that the builder is loading. By default, the builder uses the default
application: the one from the @fun{g-application-default} function. If you
want to use another application for constructing proxies, use the
@sym{(setf gtk-builder-application)} function.
You only need this function if there is more than one
@class{g-application} instance in your process. The @arg{application}
argument cannot be @code{nil}.
@see-class{gtk-builder}
@see-class{gtk-application}
@see-class{g-application}
@see-function{g-application-default}"
(builder (g-object gtk-builder)))
(export 'gtk-builder-application)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_get_type_from_name () -> gtk-builder-type-from-name
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_builder_get_type_from_name" gtk-builder-type-from-name) g-type
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[name]{a string with the type name to lookup}
@return{The @class{g-type} type ID found for @arg{name}.}
@begin{short}
Looks up a type by name, using the virtual function that the
@class{gtk-builder} class has for that purpose.
@end{short}
This is mainly used when implementing the @class{gtk-buildable} interface on
a type.
@see-class{gtk-builder}
@see-class{gtk-buildable}
@see-class{g-type}"
(builder (g-object gtk-builder))
(name :string))
(export 'gtk-builder-type-from-name)
;;; ----------------------------------------------------------------------------
;;; gtk_builder_value_from_string ()
;;;
;;; gboolean gtk_builder_value_from_string (GtkBuilder *builder,
GParamSpec * pspec ,
;;; const gchar *string,
;;; GValue *value,
;;; GError **error);
;;;
;;; This function demarshals a value from a string. This function calls
;;; g_value_init() on the value argument, so it need not be initialised
;;; beforehand.
;;;
This function can handle char , uchar , boolean , int , uint , long , ulong , enum ,
flags , float , double , string , GdkColor , GdkRGBA and GtkAdjustment type
values . Support for GtkWidget type values is still to come .
;;;
Upon errors FALSE will be returned and error will be assigned a GError from
;;; the GTK_BUILDER_ERROR domain.
;;;
;;; builder :
a GtkBuilder
;;;
pspec :
;;; the GParamSpec for the property
;;;
;;; string :
;;; the string representation of the value
;;;
;;; value :
;;; the GValue to store the result in
;;;
;;; error :
;;; return location for an error, or NULL
;;;
;;; Returns :
;;; TRUE on success
;;;
Since 2.12
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
gtk_builder_value_from_string_type ( )
;;;
gboolean gtk_builder_value_from_string_type ( GtkBuilder * builder ,
GType type ,
;;; const gchar *string,
;;; GValue *value,
GError * * error ) ;
;;;
;;; Like gtk_builder_value_from_string(), this function demarshals a value from
a string , but takes a GType instead of . This function calls
;;; g_value_init() on the value argument, so it need not be initialised
;;; beforehand.
;;;
Upon errors FALSE will be returned and error will be assigned a GError from
;;; the GTK_BUILDER_ERROR domain.
;;;
;;; builder :
a GtkBuilder
;;;
;;; type :
the GType of the value
;;;
;;; string :
;;; the string representation of the value
;;;
;;; value :
;;; the GValue to store the result in
;;;
;;; error :
;;; return location for an error, or NULL
;;;
;;; Returns :
;;; TRUE on success
;;;
Since 2.12
;;; ----------------------------------------------------------------------------
;;; ----------------------------------------------------------------------------
GTK_BUILDER_WARN_INVALID_CHILD_TYPE ( )
;;;
;;; #define GTK_BUILDER_WARN_INVALID_CHILD_TYPE(object, type)
;;;
;;; This macro should be used to emit a warning about and unexpected type value
;;; in a GtkBuildable add_child implementation.
;;;
;;; object :
;;; the GtkBuildable on which the warning ocurred
;;;
;;; type :
;;; the unexpected type value
;;; ----------------------------------------------------------------------------
;;; --- End of file gtk.builder.lisp -------------------------------------------
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/gtk/gtk.builder.lisp | lisp | ----------------------------------------------------------------------------
gtk.builder.lisp
The documentation of this file is taken from the GTK 3 Reference Manual
See <>. The API documentation of the Lisp binding is
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License for Lisp
License, or (at your option) any later version and with a preamble to
with Lisp programs and is referred as the LLGPL.
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
General Public License. If not, see </>
and <>.
----------------------------------------------------------------------------
Build an interface from an XML UI definition
Types and Values
GtkBuilderError
Functions
GtkBuilderConnectFunc
gtk_builder_new_from_file
gtk_builder_new_from_resource
gtk_builder_new_from_string
gtk_builder_add_callback_symbol
gtk_builder_add_callback_symbols
gtk_builder_lookup_callback_symbol
gtk_builder_add_from_file
gtk_builder_add_from_string
gtk_builder_add_objects_from_file
gtk_builder_add_objects_from_string
gtk_builder_add_objects_from_resource
gtk_builder_extend_with_template
gtk_builder_get_object
gtk_builder_get_objects
gtk_builder_expose_object
gtk_builder_connect_signals
gtk_builder_set_application
gtk_builder_get_application
gtk_builder_get_type_from_name
gtk_builder_value_from_string
Properties
gchar* translation-domain Read / Write
Object Hierarchy
GObject
╰── GtkBuilder
----------------------------------------------------------------------------
----------------------------------------------------------------------------
enum GtkBuilderError
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
This Lisp extension is not documented
----------------------------------------------------------------------------
Property and Accessor Details
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_new_from_file ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_new_from_resource ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_new_from_string ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_add_callback_symbol ()
const gchar *callback_name,
GCallback callback_symbol);
Adds the callback_symbol to the scope of builder under the given
callback_name .
Using this function overrides the behavior of gtk_builder_connect_signals()
for any callback symbols that are added. Using this method allows for better
encapsulation as it does not require that callback symbols be declared in
the global namespace.
builder :
callback_name :
callback_symbol :
The callback pointer.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_add_callback_symbols ()
void gtk_builder_add_callback_symbols (GtkBuilder *builder,
const gchar *first_callback_name,
GCallback first_callback_symbol,
...);
A convenience function to add many callbacks instead of calling
gtk_builder_add_callback_symbol() for each symbol.
builder :
first_callback_name :
first_callback_symbol :
The callback pointer.
... :
A list of callback name and callback symbol pairs terminated with NULL
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_lookup_callback_symbol ()
GCallback gtk_builder_lookup_callback_symbol (GtkBuilder *builder,
const gchar *callback_name);
gtk_builder_add_callback_symbols()
This function is intended for possible use in language bindings or for any
case that one might be cusomizing signal connections using
builder :
callback_name :
The name of the callback
Returns :
The callback symbol in builder for callback_name , or NULL
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_add_from_file ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_add_from_string ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_add_objects_from_file ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_add_objects_from_string ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_add_objects_from_resource ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_extend_with_template ()
gtk_builder_extend_with_template (GtkBuilder *builder,
GtkWidget *widget,
const gchar *buffer,
gsize length,
GError **error);
Main private entry point for building composite container components from
This is exported purely to let gtk-builder-tool validate templates,
applications have no need to call this function.
builder :
widget :
the widget that is being extended
template_type :
the type that the template is for
buffer :
the string to parse
length :
error :
return location for an error, or NULL.
Returns :
A positive value on success, 0 if an error occurred
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_get_object () -> gtk-builder-object
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_get_objects () -> gtk-builder-objects
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_expose_object ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_connect_signals ()
----------------------------------------------------------------------------
TODO: The documentation does not explain this implementation.
----------------------------------------------------------------------------
GtkBuilderConnectFunc ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_get_application ()
gtk_builder_set_application () -> gtk-builder-application
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_get_type_from_name () -> gtk-builder-type-from-name
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_builder_value_from_string ()
gboolean gtk_builder_value_from_string (GtkBuilder *builder,
const gchar *string,
GValue *value,
GError **error);
This function demarshals a value from a string. This function calls
g_value_init() on the value argument, so it need not be initialised
beforehand.
the GTK_BUILDER_ERROR domain.
builder :
the GParamSpec for the property
string :
the string representation of the value
value :
the GValue to store the result in
error :
return location for an error, or NULL
Returns :
TRUE on success
----------------------------------------------------------------------------
----------------------------------------------------------------------------
const gchar *string,
GValue *value,
Like gtk_builder_value_from_string(), this function demarshals a value from
g_value_init() on the value argument, so it need not be initialised
beforehand.
the GTK_BUILDER_ERROR domain.
builder :
type :
string :
the string representation of the value
value :
the GValue to store the result in
error :
return location for an error, or NULL
Returns :
TRUE on success
----------------------------------------------------------------------------
----------------------------------------------------------------------------
#define GTK_BUILDER_WARN_INVALID_CHILD_TYPE(object, type)
This macro should be used to emit a warning about and unexpected type value
in a GtkBuildable add_child implementation.
object :
the GtkBuildable on which the warning ocurred
type :
the unexpected type value
----------------------------------------------------------------------------
--- End of file gtk.builder.lisp ------------------------------------------- | Version 3.24 and modified to document the Lisp binding to the GTK library .
available from < -cffi-gtk/ > .
Copyright ( C ) 2009 - 2011
Copyright ( C ) 2011 - 2021
as published by the Free Software Foundation , either version 3 of the
the GNU Lesser General Public License that clarifies the terms for use
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 and the preamble to the Gnu Lesser
GtkBuilder
GtkBuilder
gtk_builder_new
gtk_builder_add_from_resource
gtk_builder_connect_signals_full
gtk_builder_set_translation_domain
gtk_builder_get_translation_domain
gtk_builder_value_from_string_type
GTK_BUILDER_WARN_INVALID_CHILD_TYPE
(in-package :gtk)
(define-g-enum "GtkBuilderError" gtk-builder-error
(:export t
:type-initializer "gtk_builder_error_get_type")
(:invalid-type-function 0)
(:unhandled-tag 1)
(:missing-attribute 2)
(:invalid-attribute 3)
(:invalid-tag 4)
(:missing-property-value 5)
(:invalid-value 6)
(:version-mismatch 7)
(:duplicate-id 8)
(:type-refused 9)
(:template-mismatch 10)
(:invalid-property 11)
(:invalid-signal 12)
(:invalid-id 13))
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-builder-error atdoc:*symbol-name-alias*)
"GEnum"
(gethash 'gtk-builder-error atdoc:*external-symbols*)
"@version{2021-9-23}
@begin{short}
Error codes that identify various errors that can occur while parsing the
@class{gtk-builder} UI definition.
@end{short}
@begin{pre}
(define-g-enum \"GtkBuilderError\" gtk-builder-error
(:export t
:type-initializer \"gtk_builder_error_get_type\")
(:invalid-type-function 0)
(:unhandled-tag 1)
(:missing-attribute 2)
(:invalid-attribute 3)
(:invalid-tag 4)
(:missing-property-value 5)
(:invalid-value 6)
(:version-mismatch 7)
(:duplicate-id 8)
(:type-refused 9)
(:template-mismatch 10)
(:invalid-property 11)
(:invalid-signal 12)
(:invalid-id 13))
@end{pre}
@begin[code]{table}
@entry[:invalid-type-function]{A @code{type-func} attribute did not name a
function that returns a @class{g-type} type ID.}
@entry[:unhandled-tag]{The input contained a tag that a @class{gtk-builder}
object cannot handle.}
@entry[:missing-attribute]{An attribute that is required by a
@class{gtk-builder} object was missing.}
@entry[:invalid-attribute]{A @class{gtk-builder} object found an attribute
that it does not understand.}
@entry[:invalid-tag]{A @class{gtk-builder} object found a tag that it does
not understand.}
@entry[:missing-property-value]{A required property value was missing.}
@entry[:invalid-value]{A @class{gtk-builder} object could not parse some
attribute value.}
@entry[:version-mismatch]{The input file requires a newer version of GTK.}
@entry[:duplicate-id]{An object ID occurred twice.}
@entry[:type-refused]{A specified object type is of the same type or derived
from the type of the composite class being extended with builder XML.}
@entry[:template-mismatch]{The wrong type was specified in a composite
class’s template XML.}
@entry[:invalid-property]{The specified property is unknown for the object
class.}
@entry[:invalid-signal]{The specified signal is unknown for the object
class.}
@entry[:invalid-id]{An object ID is unknown.}
@end{table}
@see-class{gtk-builder}")
struct GtkBuilder
(define-g-object-class "GtkBuilder" gtk-builder
(:superclass g-object
:export t
:interfaces nil
:type-initializer "gtk_builder_get_type")
((translation-domain
gtk-builder-translation-domain
"translation-domain" "gchararray" t t)))
(defmethod initialize-instance :after ((builder gtk-builder)
&key from-file from-string)
(when from-file
(gtk-builder-add-from-file builder from-file))
(when from-string
(gtk-builder-add-from-string builder from-string)))
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-builder 'type)
"@version{*2021-10-10}
@begin{short}
A @sym{gtk-builder} object is an auxiliary object that reads textual
descriptions of a user interface and instantiates the described objects.
@end{short}
To create a @sym{gtk-builder} object from a user interface description,
call the @fun{gtk-builder-new-from-file}, @fun{gtk-builder-new-from-resource}
or @fun{gtk-builder-new-from-string} functions.
In the (unusual) case that you want to add user interface descriptions from
multiple sources to the same @sym{gtk-builder} object you can call the
@fun{gtk-builder-new} function to get an empty builder and populate it by
(multiple) calls to the @fun{gtk-builder-add-from-file},
@fun{gtk-builder-add-from-resource} or @fun{gtk-builder-add-from-string}
functions.
A @sym{gtk-builder} object holds a reference to all objects that it has
constructed and drops these references when it is finalized. This finalization
can cause the destruction of non-widget objects or widgets which are not
contained in a toplevel window. For toplevel windows constructed by a builder,
it is the responsibility of the user to call the @fun{gtk-widget-destroy}
function to get rid of them and all the widgets they contain.
The @fun{gtk-builder-object} and @fun{gtk-builder-objects} functions can be
used to access the widgets in the interface by the names assigned to them
inside the UI description. Toplevel windows returned by these functions will
stay around until the user explicitly destroys them with the
@fun{gtk-widget-destroy} function. Other widgets will either be part of a
larger hierarchy constructed by the builder, in which case you should not have
to worry about their life cycle, or without a parent, in which case they have
to be added to some container to make use of them.
The @fun{gtk-builder-connect-signals} function and variants thereof can be
used to connect handlers to the named signals in the UI description.
@subheading{GtkBuilder UI Definitions}
The @sym{gtk-builder} implementation parses textual descriptions of user
interfaces which are specified in an XML format which can be roughly described
by the RELAX NG schema below. We refer to these descriptions as
@sym{gtk-builder} UI definitions or just UI definitions if the context is
clear. Do not confuse @sym{gtk-builder} UI Definitions with the deprecated
@class{gtk-ui-manager} UI Definitions, which are more limited in scope. It is
common to use @code{.ui} as the filename extension for files containing
@sym{gtk-builder} UI definitions.
@begin{pre}
start = element interface {
attribute domain { text @} ?,
( requires | object | menu ) *
@}
requires = element requires {
attribute lib { text @},
attribute version { text @}
@}
object = element object {
attribute id { xsd:ID @},
attribute class { text @},
attribute type-func { text @} ?,
attribute constructor { text @} ?,
(property | signal | child | ANY) *
@}
template = element template {
attribute class { text @},
attribute parent { text @},
(property | signal | child | ANY) *
@}
property = element property {
attribute name { text @},
attribute translatable { \"yes\" | \"no\" @} ?,
attribute comments { text @} ?,
attribute context { text @} ?,
text ?
@}
signal = element signal {
attribute name { text @},
attribute handler { text @},
attribute after { text @} ?,
attribute swapped { text @} ?,
attribute object { text @} ?,
attribute last_modification_time { text @} ?,
empty
@}
child = element child {
attribute type { text @} ?,
attribute internal-child { text @} ?,
(object | ANY)*
@}
menu = element menu {
attribute id { xsd:ID @},
attribute domain { text @} ?,
(item | submenu | section) *
@}
item = element item {
attribute id { xsd:ID @} ?,
(attribute_ | link) *
@}
attribute_ = element attribute {
attribute name { text @},
attribute type { text @} ?,
attribute translatable { \"yes\" | \"no\" @} ?,
attribute context { text @} ?,
attribute comments { text @} ?,
text ?
@}
link = element link {
attribute id { xsd:ID @} ?,
attribute name { text @},
item *
@}
submenu = element submenu {
attribute id { xsd:ID @} ?,
(attribute_ | item | submenu | section) *
@}
section = element section {
attribute id { xsd:ID @} ?,
(attribute_ | item | submenu | section) *
@}
ANY = element * - (interface | requires | object | property | signal
| child | menu | item | attribute | link
| submenu | section) {
attribute * { text @} *,
(ALL * & text ?)
@}
ALL = element * {
attribute * { text @} *,
(ALL * & text ?)
@}
@end{pre}
The toplevel element is @code{<interface>}. It optionally takes a
@code{\"domain\"} attribute, which will make the builder look for translated
strings using GNU gettext in the domain specified. This can also be done by
calling the @fun{gtk-builder-translation-domain} function on the builder.
Objects are described by @code{<object>} elements, which can contain
@code{<property>} elements to set properties, @code{<signal>} elements which
connect signals to handlers, and @code{<child>} elements, which describe child
objects, most often widgets inside a container, but also e.g. actions in an
action group, or columns in a tree model. A @code{<child>} element contains an
@code{<object>} element which describes the child object. The target toolkit
version(s) are described by @code{<requires>} elements, the @code{\"lib\"}
attribute specifies the widget library in question, (currently the only
supported value is @code{\"gtk+\"} and the @code{\"version\"} attribute
specifies the target version in the form @code{\"<major>.<minor>\"}. The
builder will error out if the version requirements are not met.
Typically, the specific kind of object represented by an @code{<object>}
element is specified by the @code{\"class\"} attribute. If the type has not
been loaded yet, GTK tries to find the @code{_get_type()} from the class
name by applying heuristics. This works in most cases, but if necessary, it
is possible to specify the name of the @code{_get_type()} explictly with the
@code{\"type-func\"} attribute. As a special case, the @sym{gtk-builder}
implementation allows to use an object that has been constructed by a
@class{gtk-ui-manager} object in another part of the UI definition by
specifying the ID of the @class{gtk-ui-manager} object in the
@code{\"constructor\"} attribute and the name of the object in the
@code{\"id\"} attribute.
Objects must be given a name with the @code{\"ID\"} attribute, which allows
the application to retrieve them from the builder with the
@fun{gtk-builder-object} function. An ID is also necessary to use the object
as property value in other parts of the UI definition.
@subheading{Note}
Prior to 2.20, the @sym{gtk-builder} implementation was setting the
@code{\"name\"} property of constructed widgets to the @code{\"id\"}
attribute. In GTK 2.20 or newer, you have to use the @fun{gtk-buildable-name}
function instead of the @fun{gtk-widget-name} function to obtain the
@code{\"id\"}, or set the @code{\"name\"} property in your UI definition.
Setting properties of objects is pretty straightforward with the
@code{<property>} element: the @code{\"name\"} attribute specifies the name
of the property, and the content of the element specifies the value. If the
@code{\"translatable\"} attribute is set to a true value, GTK uses GNU
gettext to find a translation for the value. This happens before the value is
parsed, so it can be used for properties of any type, but it is probably most
useful for string properties. It is also possible to specify a context to
disambiguate short strings, and comments which may help the translators.
The @sym{gtk-builder} implementation can parse textual representations for
the most common property types: characters, strings, integers, floating point
numbers, booleans, strings like \"TRUE\", \"t\", \"yes\", \"y\", \"1\" are
interpreted as @em{true}, strings like \"FALSE\", \"f\", \"no\", \"n\", \"0\"
are interpreted as @em{false}), enumerations, can be specified by their name,
nick or integer value, flags, can be specified by their name, nick, integer
value, optionally combined with \"|\", e.g. \"GTK_VISIBLE | GTK_REALIZED\",
and colors, in a format understood by the @fun{gdk-rgba-parse} function.
Objects can be referred to by their name. Pixbufs can be specified as a
filename of an image file to load. In general, the @sym{gtk-builder}
implementation allows forward references to objects - an object does not have
to be constructed before it can be referred to. The exception to this rule is
that an object has to be constructed before it can be used as the value of a
construct-only property.
Signal handlers are set up with the @code{<signal>} element. The
@code{\"name\"} attribute specifies the name of the signal, and the
@code{\"handler\"} attribute specifies the function to connect to the signal.
By default, GTK tries to find the handler using the @code{g_module_symbol()}
function, but this can be changed by passing a custom
@code{GtkBuilderConnectFunc} callback function to the
@fun{gtk-builder-connect-signals-full} function. The remaining attributes,
@code{\"after\"}, @code{\"swapped\"} and @code{\"object\"}, have the same
meaning as the corresponding parameters of the
@code{g_signal_connect_object()} or @code{g_signal_connect_data()} functions.
A @code{\"last_modification_time\"} attribute is also allowed, but it does not
have a meaning to the builder.
Sometimes it is necessary to refer to widgets which have implicitly been
constructed by GTK as part of a composite widget, to set properties on them
or to add further children, e.g. the @code{vbox} of a @class{gtk-dialog}
widget. This can be achieved by setting the @code{\"internal-child\"} propery
of the @code{<child>} element to a @em{true} value. Note that a
@sym{gtk-builder} object still requires an @code{<object>} element for the
internal child, even if it has already been constructed.
A number of widgets have different places where a child can be added, e.g.
tabs versus page content in notebooks. This can be reflected in a UI
definition by specifying the @code{\"type\"} attribute on a @code{<child>}.
The possible values for the @code{\"type\"} attribute are described in the
sections describing the widget specific portions of UI definitions.
@b{Example:} A @sym{gtk-builder} UI Definition
@begin{pre}
<interface>
<object class=\"GtkDialog\" id=\"dialog1\">
<child internal-child=\"vbox\">
<object class=\"GtkVBox\" id=\"vbox1\">
<property name=\"border-width\">10</property>
<child internal-child=\"action_area\">
<object class=\"GtkHButtonBox\" id=\"hbuttonbox1\">
<property name=\"border-width\">20</property>
<child>
<object class=\"GtkButton\" id=\"ok_button\">
<property name=\"label\">gtk-ok</property>
<property name=\"use-stock\">TRUE</property>
<signal name=\"clicked\" handler=\"ok_button_clicked\"/>
</object>
</child>
</object>
</child>
</object>
</child>
</object>
</interface>
@end{pre}
Beyond this general structure, several object classes define their own XML
DTD fragments for filling in the ANY placeholders in the DTD above. Note
that a custom element in a @code{<child>} element gets parsed by the custom
tag handler of the parent object, while a custom element in an @code{<object>}
element gets parsed by the custom tag handler of the object.
These XML fragments are explained in the documentation of the respective
objects.
Additionally, since 3.10 a special @code{<template>} tag has been added to the
format allowing one to define a widget class's components.
@subheading{Embedding other XML}
Apart from the language for UI descriptions that has been explained in the
previous section, the @sym{gtk-builder} implementation can also parse XML
fragments of @code{GMenu} markup. The resulting @class{g-menu} object and its
named submenus are available via the @fun{gtk-builder-object} function like
other constructed objects.
@see-slot{gtk-builder-translation-domain}
@see-class{gtk-buildable}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "translation-domain"
'gtk-builder) 't)
"The @code{translation-domain} property of type @code{:string} (Read / Write)
@br{}
The translation domain used when translating property values that have been
marked as translatable in interface descriptions. If the translation domain
is @code{nil}, the @sym{gtk-builder} object uses GNU gettext, otherwise
GLIB gettext. @br{}
Default value: @code{nil}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-builder-translation-domain atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-builder-translation-domain 'function)
"@version{2021-9-3}
@syntax[]{(gtk-builder-translation-domain object) => domain}
@syntax[]{(setf (gtk-builder-translation-domain object) domain)}
@argument[object]{a @class{gtk-builder} object}
@argument[domain]{a string with the translation domain or @code{nil}}
@begin{short}
Accessor of the @slot[gtk-builder]{translation-domain} slot of the
@class{gtk-builder} class.
@end{short}
The @sym{gtk-builder-translation-domain} slot access function gets the
translation domain of @arg{object}. The
@sym{(setf gtk-builder-translation-domain)} slot access function sets the
translation domain.
@see-class{gtk-builder}")
gtk_builder_new ( )
(declaim (inline gtk-builder-new))
(defun gtk-builder-new ()
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@return{A new @class{gtk-builder} object.}
@begin{short}
Creates a new builder object.
@end{short}
@see-class{gtk-builder}
@see-function{gtk-builder-new-from-file}
@see-function{gtk-builder-new-from-resource}
@see-function{gtk-builder-new-from-string}"
(make-instance 'gtk-builder))
(export 'gtk-builder-new)
(defcfun ("gtk_builder_new_from_file" gtk-builder-new-from-file)
(g-object gtk-builder)
#+cl-cffi-gtk-documentation
"@version{*2021-11-30}
@argument[filename]{a string with the filename}
@return{A @class{gtk-builder} object containing the described interface.}
@begin{short}
Builds the @class{gtk-builder} UI definition from a user interface
description file.
@end{short}
If there is an error opening the file or parsing the description then the
program will be aborted. You should only ever attempt to parse user interface
descriptions that are shipped as part of your program.
@see-class{gtk-builder}"
(filename :string))
(export 'gtk-builder-new-from-file)
(defcfun ("gtk_builder_new_from_resource" gtk-builder-new-from-resource)
(g-object gtk-builder)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[path]{a string with the @class{g-resource} path}
@return{A @class{gtk-builder} object containing the described interface.}
@begin{short}
Builds the @class{gtk-builder} UI definition from a resource path.
@end{short}
If there is an error locating the resource or parsing the description then
the program will be aborted.
@see-class{gtk-builder}
@see-class{g-resource}
@see-function{gtk-builder-new}
@see-function{gtk-builder-new-from-file}
@see-function{gtk-builder-new-from-string}"
(path :string))
(export 'gtk-builder-new-from-resource)
(defcfun ("gtk_builder_new_from_string" %gtk-builder-new-from-string)
(g-object gtk-builder)
(string :string)
(length :int))
(defun gtk-builder-new-from-string (string)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[string]{a string with the user interface description}
@return{A @class{gtk-builder} object containing the interface described by
@arg{string}.}
@begin{short}
Builds the user interface described by @arg{string} in the
@class{gtk-builder} UI definition format.
@end{short}
If there is an error parsing the string then the program will be aborted. You
should not attempt to parse user interface description from untrusted
sources.
@see-class{gtk-builder}
@see-function{gtk-builder-new}
@see-function{gtk-builder-new-from-file}
@see-function{gtk-builder-new-from-resource}"
(%gtk-builder-new-from-string string -1))
(export 'gtk-builder-new-from-string)
void gtk_builder_add_callback_symbol ( GtkBuilder * builder ,
a GtkBuilder
The name of the callback , as expected in the XML
Since 3.10
a GtkBuilder
The name of the callback , as expected in the XML
Since 3.10
a symbol previously added to builder with
gtk_builder_connect_signals_full ( )
a GtkBuilder
Since 3.10
(defcfun ("gtk_builder_add_from_file" %gtk-builder-add-from-file) :uint
(builder (g-object gtk-builder))
(filename :string)
(err :pointer))
(defun gtk-builder-add-from-file (builder filename)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[filename]{a string with the name of the file to parse}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a file containing a @class{gtk-builder} UI definition and merges it
with the current contents of the builder.
@end{short}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-resource}
@see-function{gtk-builder-add-from-string}"
(with-g-error (err)
(%gtk-builder-add-from-file builder filename err)))
(export 'gtk-builder-add-from-file)
gtk_builder_add_from_resource ( )
(defcfun ("gtk_builder_add_from_resource" %gtk-builder-add-from-resource) :uint
(builder (g-object gtk-builder))
(path :string)
(err :pointer))
(defun gtk-builder-add-from-resource (builder path)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[path]{a string with the path of the resouce file to parse}
@return{A positive value on success, 0 if an error occured.}
@begin{short}
Parses a resource file containing a @class{gtk-builder} UI definition and
merges it with the current contents of the builder.
@end{short}
@see-class{gtk-builder}
@see-class{g-resource}
@see-function{gtk-builder-add-from-file}
@see-function{gtk-builder-add-from-string}"
(with-g-error (err)
(%gtk-builder-add-from-resource builder path err)))
(export 'gtk-builder-add-from-resource)
(defcfun ("gtk_builder_add_from_string" %gtk-builder-add-from-string) :uint
(builder (g-object gtk-builder))
(string :string)
(length :int)
(err :pointer))
(defun gtk-builder-add-from-string (builder string)
#+cl-cffi-gtk-documentation
"@version{*2021-10-10}
@argument[builder]{a @class{gtk-builder} object}
@argument[string]{the string to parse}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a string containing a @class{gtk-builder} UI definition and merges
it with the current contents of the builder.
@end{short}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-file}
@see-function{gtk-builder-add-from-resource}"
(with-g-error (err)
(%gtk-builder-add-from-string builder string -1 err)))
(export 'gtk-builder-add-from-string)
(defcfun ("gtk_builder_add_objects_from_file"
%gtk-builder-add-objects-from-file) :uint
(builder (g-object gtk-builder))
(filename :string)
(object-ids :pointer)
(err :pointer))
(defun gtk-builder-add-objects-from-file (builder filename ids)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[filename]{a string with the name of the file to parse}
@argument[ids]{a list of strings with the object IDs to build}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a file containing a @class{gtk-builder} UI definition building only
the requested objects and merges them with the current contents of builder.
@end{short}
Upon errors 0 will be returned.
@begin[Note]{dictionary}
If you are adding an object that depends on an object that is not its
child, for instance a @class{gtk-tree-view} widget that depends on its
@class{gtk-tree-model} implementation, you have to explicitely list all of
them in @arg{ids}.
@end{dictionary}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-file}
@see-function{gtk-builder-add-objects-from-string}
@see-function{gtk-builder-add-objects-from-resource}"
(let ((ids-ptr (foreign-alloc :pointer :count (1+ (length ids)))))
(loop for i from 0
for object-id in ids
do (setf (mem-aref ids-ptr :pointer i)
(foreign-string-alloc object-id)))
(setf (mem-aref ids-ptr :pointer (length ids)) (null-pointer))
(unwind-protect
(with-g-error (err)
(%gtk-builder-add-objects-from-file builder filename ids-ptr err))
(progn
(loop for i from 0
repeat (1- (length ids))
do (foreign-string-free (mem-aref ids-ptr :pointer i)))
(foreign-free ids-ptr)))))
(export 'gtk-builder-add-objects-from-file)
(defcfun ("gtk_builder_add_objects_from_string"
%gtk-builder-add-objects-from-string) :uint
(builder (g-object gtk-builder))
(string :string)
(length :int)
(ids :pointer)
(err :pointer))
(defun gtk-builder-add-objects-from-string (builder string ids)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[string]{the string to parse}
@argument[ids]{list of strings with the object IDs to build}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a string containing a @class{gtk-builder} UI definition building only
the requested objects and merges them with the current contents of builder.
@end{short}
@begin[Note]{dictionary}
If you are adding an object that depends on an object that is not its child,
for instance a @class{gtk-tree-view} widget that depends on its
@class{gtk-tree-model} implementation, you have to explicitely list all of
them in @arg{ids}.
@end{dictionary}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-string}
@see-function{gtk-builder-add-objects-from-file}
@see-function{gtk-builder-add-objects-from-resource}"
(let ((ids-ptr (foreign-alloc :pointer :count (1+ (length ids)))))
(loop for i from 0
for object-id in ids
do (setf (mem-aref ids-ptr :pointer i)
(foreign-string-alloc object-id)))
(setf (mem-aref ids-ptr :pointer (length ids)) (null-pointer))
(unwind-protect
(with-g-error (err)
(%gtk-builder-add-objects-from-string builder string -1 ids-ptr err))
(progn
(loop for i from 0
repeat (1- (length ids))
do (foreign-string-free (mem-aref ids-ptr :pointer i)))
(foreign-free ids-ptr)))))
(export 'gtk-builder-add-objects-from-string)
(defcfun ("gtk_builder_add_objects_from_resource"
%gtk-builder-add-objects-from-resource) :uint
(builder (g-object gtk-builder))
(path :string)
(ids :pointer)
(err :pointer))
(defun gtk-builder-add-objects-from-resource (builder path ids)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[path]{a string with the path of the resource file to parse}
@argument[ids]{list of strings with the object IDs to build}
@return{A positive value on success, 0 if an error occurred.}
@begin{short}
Parses a resource file containing a @class{gtk-builder} UI definition
building only the requested objects and merges them with the current
contents of builder.
@end{short}
@begin[Note]{dictionary}
If you are adding an object that depends on an object that is not its
child, for instance a @class{gtk-tree-view} widget that depends on its
@class{gtk-tree-model} implementation, you have to explicitely list all of
them in @arg{ids}.
@end{dictionary}
@see-class{gtk-builder}
@see-function{gtk-builder-add-from-resource}
@see-function{gtk-builder-add-objects-from-file}
@see-function{gtk-builder-add-objects-from-string}"
(let ((ids-ptr (foreign-alloc :pointer :count (1+ (length ids)))))
(loop for i from 0
for object-id in ids
do (setf (mem-aref ids-ptr :pointer i)
(foreign-string-alloc object-id)))
(unwind-protect
(with-g-error (err)
(%gtk-builder-add-objects-from-resource builder path ids-ptr err))
(progn
(loop for i from 0
repeat (1- (length ids))
do (foreign-string-free (mem-aref ids-ptr :pointer i)))
(foreign-free ids-ptr)))))
(export 'gtk-builder-add-objects-from-resource)
guint
GType template_type ,
template XML .
a GtkBuilder
the length of buffer ( may be -1 if buffer is nul - terminated )
(defcfun ("gtk_builder_get_object" gtk-builder-object) g-object
#+cl-cffi-gtk-documentation
"@version{*2021-10-10}
@argument[builder]{a @class{gtk-builder} object}
@argument[name]{a string with the name of the object to get}
@return{The @class{g-object} instance named @arg{name} or @code{nil} if it
could not be found in the object tree.}
@begin{short}
Gets the object named @arg{name} from the @class{gtk-builder} UI definition.
@end{short}
@see-class{gtk-builder}
@see-class{g-object}
@see-function{gtk-builder-objects}"
(builder (g-object gtk-builder))
(name :string))
(export 'gtk-builder-object)
(defcfun ("gtk_builder_get_objects" gtk-builder-objects) (g-slist g-object)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@begin{return}
A list containing all the @class{g-object} instances constructed by the
@class{gtk-builder} object.
@end{return}
@begin{short}
Gets all objects that have been constructed by the builder.
@end{short}
@see-class{gtk-builder}
@see-class{g-object}
@see-function{gtk-builder-object}"
(builder (g-object gtk-builder)))
(export 'gtk-builder-objects)
(defcfun ("gtk_builder_expose_object" gtk-builder-expose-object) :void
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[name]{a string with the name of the object exposed to the builder}
@argument[object]{a @class{g-object} instance to expose}
@begin{short}
Adds an object to the builder object pool so it can be referenced just like
any other object built by the builder.
@end{short}
@see-class{gtk-builder}
@see-class{g-object}"
(builder (g-object gtk-builder))
(name :string)
(object g-object))
(export 'gtk-builder-expose-object)
(defun gtk-builder-connect-signals (builder handlers)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[handlers]{a list sent in as user data to all signals}
@begin{short}
This method is a simpler variation of the
@fun{gtk-builder-connect-signals-full} function.
@end{short}
It uses introspective features of @code{GModule} to look at the symbol table
of the application. From here it tries to match the signal handler names given
in the interface description with symbols in the application and connects the
signals. Note that this function can only be called once, subsequent calls
will do nothing.
Note that this function will not work correctly if @code{GModule} is not
supported on the platform.
When compiling applications for Windows, you must declare signal callbacks
with @code{G_MODULE_EXPORT}, or they will not be put in the symbol table. On
Linux and Unices, this is not necessary.
@see-class{gtk-builder}
@see-function{gtk-builder-connect-signals-full}"
(flet ((connect-func (builder
object
signal-name
handler-name
connect-object
flags)
(declare (ignore builder connect-object))
(let ((handler (find handler-name
handlers
:key 'first :test 'string=)))
(when handler
(g-signal-connect object
signal-name
(second handler)
:after (member :after flags))))))
(gtk-builder-connect-signals-full builder #'connect-func)))
(export 'gtk-builder-connect-signals)
(defcallback gtk-builder-connect-func :void
((builder (g-object gtk-builder))
(object g-object)
(signal (:string :free-from-foreign nil))
(handler (:string :free-from-foreign nil))
(connect g-object)
(flags g-connect-flags)
(data :pointer))
(restart-case
(let ((ptr (get-stable-pointer-value data)))
(funcall ptr builder object signal handler connect flags))
(return () nil)))
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-builder-connect-func atdoc:*symbol-name-alias*)
"Callback"
(gethash 'gtk-builder-connect-func atdoc:*external-symbols*)
"@version{2021-9-23}
@begin{short}
This is the signature of a callback function used to connect signals.
@end{short}
It is used by the @fun{gtk-builder-connect-signals} and
@fun{gtk-builder-connect-signals-full} functions. It is mainly intended for
interpreted language bindings, but could be useful where the programmer wants
more control over the signal connection process. Note that this function can
only be called once, subsequent calls will do nothing.
@begin{pre}
lambda (builder object signal-name handler-name connect-object flags)
@end{pre}
@begin[code]{table}
@entry[builder]{a @class{gtk-builder} object}
@entry[object]{a @class{g-object} instance to connect a signal to}
@entry[signal-name]{a string with the name of the signal}
@entry[handler-name]{a string with the name of the handler}
@entry[connect-object]{a @class{g-object} instance, if non-@code{nil}, use
the @fun{g-signal-connect-object} function}
@entry[flags]{a value of the @symbol{g-connect-flags} flags to use}
@end{table}
@see-class{gtk-builder}
@see-function{gtk-builder-connect-signals}
@see-function{gtk-builder-connect-signals-full}")
(export 'gtk-builder-connect-func)
gtk_builder_connect_signals_full ( )
(defcfun ("gtk_builder_connect_signals_full" %gtk-builder-connect-signals-full)
:void
(builder (g-object gtk-builder))
(func :pointer)
(data :pointer))
(defun gtk-builder-connect-signals-full (builder func)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[func]{a @symbol{gtk-builder-connect-func} callback function used to
connect the signals}
@begin{short}
This function can be thought of the interpreted language binding version of
the @fun{gtk-builder-connect-signals} function.
@end{short}
@see-class{gtk-builder}
@see-symbol{gtk-builder-connect-func}
@see-function{gtk-builder-connect-signals}"
(with-stable-pointer (ptr func)
(%gtk-builder-connect-signals-full builder
(callback gtk-builder-connect-func)
ptr)))
(export 'gtk-builder-connect-signals-full)
(defun (setf gtk-builder-application) (application builder)
(foreign-funcall "gtk_builder_set_application"
(g-object gtk-builder) builder
(g-object gtk-application) application
:void)
application)
(defcfun ("gtk_builder_get_application" gtk-builder-application)
(g-object gtk-application)
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@syntax[]{(gtk-builder-application builder) => application}
@syntax[]{(setf (gtk-builder-application builder) application)}
@argument[builder]{a @class{gtk-builder} object}
@argument[application]{a @class{gtk-application} instance}
@begin{short}
Accessor of the application associated with the builder.
@end{short}
The @sym{gtk-builder-application} function gets the application associated
with the builder. The @sym{(setf gtk-builder-application)} function sets the
application.
The application is used for creating action proxies as requested from XML
that the builder is loading. By default, the builder uses the default
application: the one from the @fun{g-application-default} function. If you
want to use another application for constructing proxies, use the
@sym{(setf gtk-builder-application)} function.
You only need this function if there is more than one
@class{g-application} instance in your process. The @arg{application}
argument cannot be @code{nil}.
@see-class{gtk-builder}
@see-class{gtk-application}
@see-class{g-application}
@see-function{g-application-default}"
(builder (g-object gtk-builder)))
(export 'gtk-builder-application)
(defcfun ("gtk_builder_get_type_from_name" gtk-builder-type-from-name) g-type
#+cl-cffi-gtk-documentation
"@version{2021-9-23}
@argument[builder]{a @class{gtk-builder} object}
@argument[name]{a string with the type name to lookup}
@return{The @class{g-type} type ID found for @arg{name}.}
@begin{short}
Looks up a type by name, using the virtual function that the
@class{gtk-builder} class has for that purpose.
@end{short}
This is mainly used when implementing the @class{gtk-buildable} interface on
a type.
@see-class{gtk-builder}
@see-class{gtk-buildable}
@see-class{g-type}"
(builder (g-object gtk-builder))
(name :string))
(export 'gtk-builder-type-from-name)
GParamSpec * pspec ,
This function can handle char , uchar , boolean , int , uint , long , ulong , enum ,
flags , float , double , string , GdkColor , GdkRGBA and GtkAdjustment type
values . Support for GtkWidget type values is still to come .
Upon errors FALSE will be returned and error will be assigned a GError from
a GtkBuilder
pspec :
Since 2.12
gtk_builder_value_from_string_type ( )
gboolean gtk_builder_value_from_string_type ( GtkBuilder * builder ,
GType type ,
a string , but takes a GType instead of . This function calls
Upon errors FALSE will be returned and error will be assigned a GError from
a GtkBuilder
the GType of the value
Since 2.12
GTK_BUILDER_WARN_INVALID_CHILD_TYPE ( )
|
3f84d46920e19f30c6aa072142033da2eed0ad248d8de11ebbe05136b81f0d39 | owickstrom/twitter-kinesis-lab | core_test.clj | (ns twitter-producer.core-test
(:require [clojure.test :refer :all]
[twitter-producer.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/owickstrom/twitter-kinesis-lab/254111d100b11a1896f713c82d55f9e8e98f2e9e/twitter-producer/test/twitter_producer/core_test.clj | clojure | (ns twitter-producer.core-test
(:require [clojure.test :refer :all]
[twitter-producer.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| |
eafaf37981bb6705deb82741619b0ef6f7b12c837a261dff396a5d0e768c166a | kadena-io/chainweaver | ModuleDetails.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE DataKinds #
# LANGUAGE ExtendedDefaultRules #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
-- | Details view for a particular module.
--
This view shows details about a particular Pact module and in particular
-- offers an interface for calling its functions.
--
Copyright : ( C ) 2020 - 2022 Kadena
-- License : BSD-style (see the file LICENSE)
--
module Frontend.UI.ModuleExplorer.ModuleDetails where
------------------------------------------------------------------------------
import Control.Monad ((<=<))
import Control.Lens
import Data.Bool (bool)
import Data.Maybe
import Data.Text (Text)
import Data.Traversable (for)
import Reflex
import Reflex.Dom
import Reflex.Network.Extended
------------------------------------------------------------------------------
import Frontend.Crypto.Class
import Frontend.JsonData
import Frontend.ModuleExplorer
import Frontend.Network
import Frontend.Log
import Frontend.UI.Button
import Frontend.UI.Dialogs.CallFunction
import Frontend.UI.Modal
import Frontend.UI.ModuleExplorer.ModuleList
------------------------------------------------------------------------------
| Constraints on the ` Model ` we have for our details screen .
type HasUIModuleDetailsModel model key t =
( HasModuleExplorer model t
, HasNetwork model t
, HasUICallFunctionModel model key t
, HasLogger model t
)
-- | Constraints on the model config we have for implementing this screen.
type HasUIModuleDetailsModelCfg mConf m t =
( Monoid mConf, Flattenable mConf t, HasModuleExplorerCfg mConf t
, HasNetworkCfg mConf t
, HasModalCfg mConf (Modal mConf m t) t
, HasUICallFunctionModelCfg (ModalCfg mConf t) t
, HasJsonDataCfg (ModalCfg mConf t) t
)
-- | Details screen for a Module/Interface
--
-- User can see and call the module's function and browse implemented
-- interfaces and used modules.
moduleDetails
:: forall key t m model mConf
. ( MonadWidget t m
, HasUIModuleDetailsModel model key t
, HasUIModuleDetailsModelCfg mConf m t
, HasCrypto key (Performable m)
, HasTransactionLogger m
)
=> model
-> (ModuleRef, ModuleDef (Term Name))
-> m mConf
moduleDetails m (selectedRef, selected) = do
headerCfg <- elClass "div" "segment" $ do
((onHome, onBack), onLoad) <- elClass "h2" "heading heading_type_h2" $ do
hb <- el "div" $ do
onHome <- switchHold never <=< dyn $ ffor (m ^. moduleExplorer_moduleStack) $ \ms ->
if length ms <= 1 then
pure never
else
homeButton "heading__left-double-button"
onBack <- backButton
pure (onHome, onBack)
(hb,) <$> openButton mempty
moduleTitle
pure $ mempty
& moduleExplorerCfg_goHome .~ onHome
& moduleExplorerCfg_popModule .~ onBack
& moduleExplorerCfg_loadModule .~ (selectedRef <$ onLoad)
bodyCfg1 <- showDeps "Implemented Interfaces" $
selected ^. interfacesOfModule
bodyCfg2 <- showDeps "Used Modules" $
selected ^. importNamesOfModule
functionConfigs <-
traverse uiDefTypeSegment . functionsByDefType $ functionsOfModule selected
pure (headerCfg <> bodyCfg1 <> bodyCfg2 <> mconcat functionConfigs)
where
uiDefTypeSegment :: (DefType, [PactFunction]) -> m mConf
uiDefTypeSegment (t, fs) =
case fs of
[] -> pure mempty
_ -> elClass "div" "segment" $ do
elClass "h3" "heading heading_type_h3" $
text $ defTypeHeading t
mkFunctionList fs
defTypeHeading :: DefType -> Text
defTypeHeading = \case
Defun -> "Functions"
Defpact -> "Pacts"
Defcap -> "Capabilities"
mkFunctionList :: [PactFunction] -> m mConf
mkFunctionList = functionList m $
if isModule selected
then getDeployedModuleRef selectedRef
else Nothing
moduleTitle = elClass "h2" "heading heading_type_h2" $ do
text $ textModuleRefName selectedRef
elClass "div" "heading__type-details" $ do
text $ textModuleRefSource (isModule selected) selectedRef
showDeps :: Text -> [ModuleName] -> m mConf
showDeps n deps =
let
refs = map (ModuleRef (_moduleRef_source selectedRef)) deps
in
case refs of
[] -> pure mempty
_ -> elClass "div" "segment" $ do
elClass "h3" "heading heading_type_h3" $ text n
onSel <- uiModuleList . pure $ refs
pure $ mempty & moduleExplorerCfg_pushModule .~ onSel
functionList
:: forall key t m mConf model
. ( MonadWidget t m, HasUIModuleDetailsModelCfg mConf m t
, HasUIModuleDetailsModel model key t
, HasCrypto key (Performable m)
, HasTransactionLogger m
)
=> model -> Maybe DeployedModuleRef -> [PactFunction] -> m mConf
functionList m mDeployed functions =
elClass "ol" "table table_type_primary" $ do
onView <- fmap leftmost . for functions $ \f ->
elClass "li" "table__row table__row_type_primary" $ do
divClass "table__text-cell table__cell_size_side title" $
text $ _pactFunction_name f
divClass "table__text-cell table__cell_size_double-main description" $
text $ fromMaybe "" $ _pactFunction_documentation f
divClass "table__cell_size_flex table__last-cell" $ do
let btnCls = "table__action-button"
let isDeployed = isJust mDeployed
let isCallable = isDeployed && functionIsCallable f
fmap (const f) <$> bool (viewButton btnCls) (callButton btnCls) isCallable
pure $ mempty & modalCfg_setModal .~ (Just . uiCallFunction m mDeployed <$> onView)
| null | https://raw.githubusercontent.com/kadena-io/chainweaver/5d40e91411995e0a9a7e782d6bb2d89ac1c65d52/frontend/src/Frontend/UI/ModuleExplorer/ModuleDetails.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings #
| Details view for a particular module.
offers an interface for calling its functions.
License : BSD-style (see the file LICENSE)
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
| Constraints on the model config we have for implementing this screen.
| Details screen for a Module/Interface
User can see and call the module's function and browse implemented
interfaces and used modules. | # LANGUAGE DataKinds #
# LANGUAGE ExtendedDefaultRules #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TupleSections #
# LANGUAGE TypeFamilies #
This view shows details about a particular Pact module and in particular
Copyright : ( C ) 2020 - 2022 Kadena
module Frontend.UI.ModuleExplorer.ModuleDetails where
import Control.Monad ((<=<))
import Control.Lens
import Data.Bool (bool)
import Data.Maybe
import Data.Text (Text)
import Data.Traversable (for)
import Reflex
import Reflex.Dom
import Reflex.Network.Extended
import Frontend.Crypto.Class
import Frontend.JsonData
import Frontend.ModuleExplorer
import Frontend.Network
import Frontend.Log
import Frontend.UI.Button
import Frontend.UI.Dialogs.CallFunction
import Frontend.UI.Modal
import Frontend.UI.ModuleExplorer.ModuleList
| Constraints on the ` Model ` we have for our details screen .
type HasUIModuleDetailsModel model key t =
( HasModuleExplorer model t
, HasNetwork model t
, HasUICallFunctionModel model key t
, HasLogger model t
)
type HasUIModuleDetailsModelCfg mConf m t =
( Monoid mConf, Flattenable mConf t, HasModuleExplorerCfg mConf t
, HasNetworkCfg mConf t
, HasModalCfg mConf (Modal mConf m t) t
, HasUICallFunctionModelCfg (ModalCfg mConf t) t
, HasJsonDataCfg (ModalCfg mConf t) t
)
moduleDetails
:: forall key t m model mConf
. ( MonadWidget t m
, HasUIModuleDetailsModel model key t
, HasUIModuleDetailsModelCfg mConf m t
, HasCrypto key (Performable m)
, HasTransactionLogger m
)
=> model
-> (ModuleRef, ModuleDef (Term Name))
-> m mConf
moduleDetails m (selectedRef, selected) = do
headerCfg <- elClass "div" "segment" $ do
((onHome, onBack), onLoad) <- elClass "h2" "heading heading_type_h2" $ do
hb <- el "div" $ do
onHome <- switchHold never <=< dyn $ ffor (m ^. moduleExplorer_moduleStack) $ \ms ->
if length ms <= 1 then
pure never
else
homeButton "heading__left-double-button"
onBack <- backButton
pure (onHome, onBack)
(hb,) <$> openButton mempty
moduleTitle
pure $ mempty
& moduleExplorerCfg_goHome .~ onHome
& moduleExplorerCfg_popModule .~ onBack
& moduleExplorerCfg_loadModule .~ (selectedRef <$ onLoad)
bodyCfg1 <- showDeps "Implemented Interfaces" $
selected ^. interfacesOfModule
bodyCfg2 <- showDeps "Used Modules" $
selected ^. importNamesOfModule
functionConfigs <-
traverse uiDefTypeSegment . functionsByDefType $ functionsOfModule selected
pure (headerCfg <> bodyCfg1 <> bodyCfg2 <> mconcat functionConfigs)
where
uiDefTypeSegment :: (DefType, [PactFunction]) -> m mConf
uiDefTypeSegment (t, fs) =
case fs of
[] -> pure mempty
_ -> elClass "div" "segment" $ do
elClass "h3" "heading heading_type_h3" $
text $ defTypeHeading t
mkFunctionList fs
defTypeHeading :: DefType -> Text
defTypeHeading = \case
Defun -> "Functions"
Defpact -> "Pacts"
Defcap -> "Capabilities"
mkFunctionList :: [PactFunction] -> m mConf
mkFunctionList = functionList m $
if isModule selected
then getDeployedModuleRef selectedRef
else Nothing
moduleTitle = elClass "h2" "heading heading_type_h2" $ do
text $ textModuleRefName selectedRef
elClass "div" "heading__type-details" $ do
text $ textModuleRefSource (isModule selected) selectedRef
showDeps :: Text -> [ModuleName] -> m mConf
showDeps n deps =
let
refs = map (ModuleRef (_moduleRef_source selectedRef)) deps
in
case refs of
[] -> pure mempty
_ -> elClass "div" "segment" $ do
elClass "h3" "heading heading_type_h3" $ text n
onSel <- uiModuleList . pure $ refs
pure $ mempty & moduleExplorerCfg_pushModule .~ onSel
functionList
:: forall key t m mConf model
. ( MonadWidget t m, HasUIModuleDetailsModelCfg mConf m t
, HasUIModuleDetailsModel model key t
, HasCrypto key (Performable m)
, HasTransactionLogger m
)
=> model -> Maybe DeployedModuleRef -> [PactFunction] -> m mConf
functionList m mDeployed functions =
elClass "ol" "table table_type_primary" $ do
onView <- fmap leftmost . for functions $ \f ->
elClass "li" "table__row table__row_type_primary" $ do
divClass "table__text-cell table__cell_size_side title" $
text $ _pactFunction_name f
divClass "table__text-cell table__cell_size_double-main description" $
text $ fromMaybe "" $ _pactFunction_documentation f
divClass "table__cell_size_flex table__last-cell" $ do
let btnCls = "table__action-button"
let isDeployed = isJust mDeployed
let isCallable = isDeployed && functionIsCallable f
fmap (const f) <$> bool (viewButton btnCls) (callButton btnCls) isCallable
pure $ mempty & modalCfg_setModal .~ (Just . uiCallFunction m mDeployed <$> onView)
|
1a74ea8493ac8853d3afbdf0100729696a896dffbad56381ae94e165993f3d6a | inclojure-org/intermediate-clojure-workshop | utils.clj | (ns workshop-app.utils
(:import (java.time LocalDate)
(java.time.temporal ChronoUnit)))
(defn parse-dt-str
[dt-str]
(when (seq dt-str)
(LocalDate/parse dt-str)))
(defn years-between
[d1 d2]
(.between ChronoUnit/YEARS d1 d2)) | null | https://raw.githubusercontent.com/inclojure-org/intermediate-clojure-workshop/3338a476aa815a587fa9e0b8b3804aa43492d15e/save-points/7/src/workshop_app/utils.clj | clojure | (ns workshop-app.utils
(:import (java.time LocalDate)
(java.time.temporal ChronoUnit)))
(defn parse-dt-str
[dt-str]
(when (seq dt-str)
(LocalDate/parse dt-str)))
(defn years-between
[d1 d2]
(.between ChronoUnit/YEARS d1 d2)) | |
b5ec8abaf425432180dc5bdb7ea58b26ba48542bc0069ecc194d9403e6c44ef3 | avsm/melange | dnsquery.ml |
dnsquery.ml -- map DNS query - response mechanism onto trie database
Copyright ( c ) 2005 - 2006 < >
dnsquery.ml -- map DNS query-response mechanism onto trie database
Copyright (c) 2005-2006 Tim Deegan <>
*)
open Dnsrr
open Dnstrie
open Dns
open Dns_rr
module H = Hashcons
We answer a query with RCODE , AA , ANSWERS , AUTHORITY and ADDITIONAL
type query_answer = {
rcode : Dns.rcode_t;
aa: bool;
answer: (Mpl_stdlib.env -> Dns.Answers.o) list;
authority: (Mpl_stdlib.env -> Dns.Authority.o) list;
additional: (Mpl_stdlib.env -> Dns.Additional.o) list;
}
let answer_query qname qtype trie =
let aa_flag = ref true in
let ans_rrs = ref [] in
let auth_rrs = ref [] in
let add_rrs = ref [] in
let addqueue = ref [] in
let rrlog = ref [] in
We must avoid repeating RRSets in the response . To do this , we
keep two lists : one of RRSets that are already included , and one of
RRSets we plan to put in the additional records section . When we
add an RRSet to the answer or authority section we strip it from
the additionals queue , and when we enqueue an additional RRSet we
make sure it 's not already been included .
N.B. ( 1 ) We only log those types that might turn up more than once .
( 2 ) We can use " = = " and " ! = " because owners are unique :
they are either the owner field of a dnsnode from the
trie , or they are the qname , which only happens if it
does not have any RRSets of its own and matched a wildcard .
keep two lists: one of RRSets that are already included, and one of
RRSets we plan to put in the additional records section. When we
add an RRSet to the answer or authority section we strip it from
the additionals queue, and when we enqueue an additional RRSet we
make sure it's not already been included.
N.B. (1) We only log those types that might turn up more than once.
N.B. (2) We can use "==" and "!=" because owners are unique:
they are either the owner field of a dnsnode from the
trie, or they are the qname, which only happens if it
does not have any RRSets of its own and matched a wildcard.*)
let log_rrset owner rrtype =
addqueue := List.filter
(fun (n, t) -> rrtype != t || owner != n.owner.H.node) !addqueue;
rrlog := (owner, rrtype) :: !rrlog
in
let in_log owner rrtype =
List.exists (fun (o, t) -> o == owner && t == rrtype) !rrlog
in
let enqueue_additional dnsnode rrtype =
if not (in_log dnsnode.owner.H.node rrtype)
then addqueue := (dnsnode, rrtype) :: !addqueue
in
Map an RRSet into MPL closures and include it in the response
let add_rrset owner ttl rdata section =
let addfn x = match section with
`Answer -> ans_rrs := (Dns.Answers.t ~rr:x) :: !ans_rrs
| `Authority -> auth_rrs := (Dns.Authority.t ~rr:x) :: !auth_rrs
| `Additional -> add_rrs := (Dns.Additional.t ~rr:x) :: !add_rrs
in
let mapfn ?(aclass = Some `IN) x = x ~name:owner ?aclass ~ttl:ttl in
match rdata with
A l -> log_rrset owner `A;
List.iter (fun i -> addfn (`A (mapfn Dns_rr.A.t ~ip:i))) l
| NS l -> log_rrset owner `NS;
List.iter (fun d ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`NS (mapfn Dns_rr.NS.t ~hostname:d.owner.H.node))) l
| CNAME l ->
List.iter (fun d ->
addfn (`CNAME (mapfn Dns_rr.CNAME.t ~cname:d.owner.H.node))) l
| SOA l -> log_rrset owner `SOA;
List.iter (fun (prim,admin,serial,refresh,retry,expire,minttl) ->
addfn (`SOA (mapfn Dns_rr.SOA.t ~primary_ns:prim.owner.H.node
~admin_mb:admin.owner.H.node ~serial:serial
~refresh:refresh ~retry:retry
~expiration:expire ~minttl:minttl))) l
| MB l ->
List.iter (fun d ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`MB (mapfn Dns_rr.MB.t ~madname:d.owner.H.node))) l
| MG l ->
List.iter (fun d ->
addfn (`MG (mapfn Dns_rr.MG.t ~mgmname:d.owner.H.node))) l
| MR l ->
List.iter (fun d ->
addfn (`MR (mapfn Dns_rr.MR.t ~newname:d.owner.H.node))) l
| WKS l ->
List.iter (fun (address, protocol, bitmap) ->
addfn (`WKS (mapfn Dns_rr.WKS.t ~address:address
~protocol:protocol ~bitmap:(`Str bitmap.H.node)))) l
| PTR l ->
List.iter (fun d ->
addfn (`PTR (mapfn Dns_rr.PTR.t ~ptrdname:d.owner.H.node))) l
| HINFO l ->
List.iter (fun (cpu, os) ->
addfn (`HINFO (mapfn Dns_rr.HINFO.t ~cpu:cpu.H.node
~os:os.H.node))) l
| MINFO l ->
List.iter (fun (rm, em) ->
addfn (`MINFO (mapfn Dns_rr.MINFO.t ~rmailbox:rm.owner.H.node
~emailbox:em.owner.H.node))) l
| MX l ->
List.iter (fun (pref, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`MX (mapfn Dns_rr.MX.t ~preference:pref
~hostname:d.owner.H.node))) l
| TXT l ->
List.iter (fun sl -> (* XXX handle multiple TXT cstrings properly *)
let s = String.concat "" (List.map (fun x -> x.H.node) sl) in
addfn (`TXT (mapfn Dns_rr.TXT.t ~data:s ~misc:`None))) l
| RP l ->
List.iter (fun (mbox, txt) ->
addfn (`RP (mapfn Dns_rr.RP.t ~mbox_dname:mbox.owner.H.node
~txt_dname:txt.owner.H.node))) l
| AFSDB l ->
List.iter (fun (t, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`AFSDB (mapfn Dns_rr.AFSDB.t ~subtype:t
~hostname:d.owner.H.node))) l
| X25 l -> log_rrset owner `X25;
List.iter (fun s ->
addfn (`X25 (mapfn Dns_rr.X25.t ~psdn_address:s.H.node))) l
| ISDN l -> log_rrset owner `ISDN;
List.iter (function (* XXX handle multiple cstrings properly *)
(addr, None) ->
addfn (`ISDN (mapfn Dns_rr.ISDN.t ~data:(addr.H.node)))
| (addr, Some sa) -> (* XXX Handle multible charstrings properly *)
addfn (`ISDN (mapfn Dns_rr.ISDN.t
~data:(addr.H.node ^ sa.H.node)))) l
| RT l ->
List.iter (fun (pref, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
enqueue_additional d `X25;
enqueue_additional d `ISDN;
addfn (`RT (mapfn Dns_rr.RT.t ~preference:pref
~intermediate_host:d.owner.H.node))) l
| AAAA l -> log_rrset owner `AAAA;
List.iter (fun i ->
addfn (`AAAA (mapfn Dns_rr.AAAA.t ~ip:(`Str i.H.node)))) l
| SRV l ->
List.iter (fun (pri, weight, port, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`SRV (mapfn Dns_rr.SRV.t ~priority:pri ~weight:weight
~port:port ~target:d.owner.H.node))) l
| UNSPEC l ->
List.iter (fun s ->
addfn (`UNSPEC (mapfn Dns_rr.UNSPEC.t ~data:(`Str s.H.node)))) l
| Unknown (t, l) -> () (* XXX Support unknown-type responses *)
in
(* Get an RRSet, which may not exist *)
let add_opt_rrset node rrtype section =
if not (in_log node.owner.H.node rrtype)
then let a = get_rrsets rrtype node.rrsets false in
List.iter (fun s -> add_rrset node.owner.H.node s.ttl s.rdata section) a
in
(* Get an RRSet, which must exist *)
let add_req_rrset node rrtype section =
if not (in_log node.owner.H.node rrtype)
then let a = get_rrsets rrtype node.rrsets false in
if a = [] then raise TrieCorrupt;
List.iter (fun s -> add_rrset node.owner.H.node s.ttl s.rdata section) a
in
(* Get the SOA RRSet for a negative response *)
let add_negative_soa_rrset node =
(* Don't need to check if it's already there *)
let a = get_rrsets `SOA node.rrsets false in
if a = [] then raise TrieCorrupt;
RFC 2308 : The of the SOA RRset in a negative response must be set to
the minimum of its own TTL and the " minimum " field of the SOA itself
the minimum of its own TTL and the "minimum" field of the SOA itself *)
List.iter (fun s ->
match s.rdata with
SOA ((_, _, _, _, _, _, ttl) :: _) ->
add_rrset node.owner.H.node (min s.ttl ttl) s.rdata `Authority
| _ -> raise TrieCorrupt ) a
in
(* Fill in the ANSWER section *)
let rec add_answer_rrsets owner ?(lc = 5) rrsets rrtype =
let add_answer_rrset s =
match s with
Only follow the first CNAME in a set
if not (lc < 1 || rrtype = `CNAME ) then begin
add_answer_rrsets d.owner.H.node ~lc:(lc - 1) d.rrsets rrtype end;
add_rrset owner s.ttl s.rdata `Answer;
| _ -> add_rrset owner s.ttl s.rdata `Answer
in
let a = get_rrsets rrtype rrsets true in
List.iter add_answer_rrset a
in
(* Call the trie lookup and assemble the RRs for a response *)
let main_lookup qname qtype trie =
let key = canon2key qname in
match lookup key trie with
`Found (sec, node, zonehead) -> (* Name has RRs, and we own it. *)
add_answer_rrsets node.owner.H.node node.rrsets qtype;
add_opt_rrset zonehead `NS `Authority;
`NoError
| `NoError (zonehead) -> (* Name "exists", but has no RRs. *)
add_negative_soa_rrset zonehead;
`NoError
| `NoErrorNSEC (zonehead, nsec) ->
add_negative_soa_rrset zonehead;
add_opt_rrset nsec ` NSEC ` Authority ;
`NoError
| `Delegated (sec, cutpoint) -> (* Name is delegated. *)
add_req_rrset cutpoint `NS `Authority;
aa_flag := false;
(* DNSSEC child zone keys *)
`NoError
| `Wildcard (source, zonehead) -> (* Name is matched by a wildcard. *)
add_answer_rrsets qname source.rrsets qtype;
add_opt_rrset zonehead `NS `Authority;
`NoError
| `WildcardNSEC (source, zonehead, nsec) ->
add_answer_rrsets qname source.rrsets qtype;
add_opt_rrset zonehead `NS `Authority;
add_opt_rrset nsec ` NSEC ` Authority ;
`NoError
| `NXDomain (zonehead) -> (* Name doesn't exist. *)
add_negative_soa_rrset zonehead;
`NXDomain
| `NXDomainNSEC (zonehead, nsec1, nsec2) ->
add_negative_soa_rrset zonehead;
(* add_opt_rrset nsec1 `NSEC `Authority; *)
add_opt_rrset nsec2 ` NSEC ` Authority ;
`NXDomain
in
try
let rc = main_lookup qname qtype trie in
List.iter (fun (o, t) -> add_opt_rrset o t `Additional) !addqueue;
{ rcode = rc; aa = !aa_flag;
answer = !ans_rrs; authority = !auth_rrs; additional = !add_rrs }
with
BadDomainName _ -> { rcode = `FormErr; aa = false;
answer = []; authority = []; additional=[] }
| TrieCorrupt -> { rcode = `ServFail; aa = false;
answer = []; authority = []; additional=[] }
| null | https://raw.githubusercontent.com/avsm/melange/e92240e6dc8a440cafa91488a1fc367e2ba57de1/lib/dns/dnsquery.ml | ocaml | XXX handle multiple TXT cstrings properly
XXX handle multiple cstrings properly
XXX Handle multible charstrings properly
XXX Support unknown-type responses
Get an RRSet, which may not exist
Get an RRSet, which must exist
Get the SOA RRSet for a negative response
Don't need to check if it's already there
Fill in the ANSWER section
Call the trie lookup and assemble the RRs for a response
Name has RRs, and we own it.
Name "exists", but has no RRs.
Name is delegated.
DNSSEC child zone keys
Name is matched by a wildcard.
Name doesn't exist.
add_opt_rrset nsec1 `NSEC `Authority; |
dnsquery.ml -- map DNS query - response mechanism onto trie database
Copyright ( c ) 2005 - 2006 < >
dnsquery.ml -- map DNS query-response mechanism onto trie database
Copyright (c) 2005-2006 Tim Deegan <>
*)
open Dnsrr
open Dnstrie
open Dns
open Dns_rr
module H = Hashcons
We answer a query with RCODE , AA , ANSWERS , AUTHORITY and ADDITIONAL
type query_answer = {
rcode : Dns.rcode_t;
aa: bool;
answer: (Mpl_stdlib.env -> Dns.Answers.o) list;
authority: (Mpl_stdlib.env -> Dns.Authority.o) list;
additional: (Mpl_stdlib.env -> Dns.Additional.o) list;
}
let answer_query qname qtype trie =
let aa_flag = ref true in
let ans_rrs = ref [] in
let auth_rrs = ref [] in
let add_rrs = ref [] in
let addqueue = ref [] in
let rrlog = ref [] in
We must avoid repeating RRSets in the response . To do this , we
keep two lists : one of RRSets that are already included , and one of
RRSets we plan to put in the additional records section . When we
add an RRSet to the answer or authority section we strip it from
the additionals queue , and when we enqueue an additional RRSet we
make sure it 's not already been included .
N.B. ( 1 ) We only log those types that might turn up more than once .
( 2 ) We can use " = = " and " ! = " because owners are unique :
they are either the owner field of a dnsnode from the
trie , or they are the qname , which only happens if it
does not have any RRSets of its own and matched a wildcard .
keep two lists: one of RRSets that are already included, and one of
RRSets we plan to put in the additional records section. When we
add an RRSet to the answer or authority section we strip it from
the additionals queue, and when we enqueue an additional RRSet we
make sure it's not already been included.
N.B. (1) We only log those types that might turn up more than once.
N.B. (2) We can use "==" and "!=" because owners are unique:
they are either the owner field of a dnsnode from the
trie, or they are the qname, which only happens if it
does not have any RRSets of its own and matched a wildcard.*)
let log_rrset owner rrtype =
addqueue := List.filter
(fun (n, t) -> rrtype != t || owner != n.owner.H.node) !addqueue;
rrlog := (owner, rrtype) :: !rrlog
in
let in_log owner rrtype =
List.exists (fun (o, t) -> o == owner && t == rrtype) !rrlog
in
let enqueue_additional dnsnode rrtype =
if not (in_log dnsnode.owner.H.node rrtype)
then addqueue := (dnsnode, rrtype) :: !addqueue
in
Map an RRSet into MPL closures and include it in the response
let add_rrset owner ttl rdata section =
let addfn x = match section with
`Answer -> ans_rrs := (Dns.Answers.t ~rr:x) :: !ans_rrs
| `Authority -> auth_rrs := (Dns.Authority.t ~rr:x) :: !auth_rrs
| `Additional -> add_rrs := (Dns.Additional.t ~rr:x) :: !add_rrs
in
let mapfn ?(aclass = Some `IN) x = x ~name:owner ?aclass ~ttl:ttl in
match rdata with
A l -> log_rrset owner `A;
List.iter (fun i -> addfn (`A (mapfn Dns_rr.A.t ~ip:i))) l
| NS l -> log_rrset owner `NS;
List.iter (fun d ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`NS (mapfn Dns_rr.NS.t ~hostname:d.owner.H.node))) l
| CNAME l ->
List.iter (fun d ->
addfn (`CNAME (mapfn Dns_rr.CNAME.t ~cname:d.owner.H.node))) l
| SOA l -> log_rrset owner `SOA;
List.iter (fun (prim,admin,serial,refresh,retry,expire,minttl) ->
addfn (`SOA (mapfn Dns_rr.SOA.t ~primary_ns:prim.owner.H.node
~admin_mb:admin.owner.H.node ~serial:serial
~refresh:refresh ~retry:retry
~expiration:expire ~minttl:minttl))) l
| MB l ->
List.iter (fun d ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`MB (mapfn Dns_rr.MB.t ~madname:d.owner.H.node))) l
| MG l ->
List.iter (fun d ->
addfn (`MG (mapfn Dns_rr.MG.t ~mgmname:d.owner.H.node))) l
| MR l ->
List.iter (fun d ->
addfn (`MR (mapfn Dns_rr.MR.t ~newname:d.owner.H.node))) l
| WKS l ->
List.iter (fun (address, protocol, bitmap) ->
addfn (`WKS (mapfn Dns_rr.WKS.t ~address:address
~protocol:protocol ~bitmap:(`Str bitmap.H.node)))) l
| PTR l ->
List.iter (fun d ->
addfn (`PTR (mapfn Dns_rr.PTR.t ~ptrdname:d.owner.H.node))) l
| HINFO l ->
List.iter (fun (cpu, os) ->
addfn (`HINFO (mapfn Dns_rr.HINFO.t ~cpu:cpu.H.node
~os:os.H.node))) l
| MINFO l ->
List.iter (fun (rm, em) ->
addfn (`MINFO (mapfn Dns_rr.MINFO.t ~rmailbox:rm.owner.H.node
~emailbox:em.owner.H.node))) l
| MX l ->
List.iter (fun (pref, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`MX (mapfn Dns_rr.MX.t ~preference:pref
~hostname:d.owner.H.node))) l
| TXT l ->
let s = String.concat "" (List.map (fun x -> x.H.node) sl) in
addfn (`TXT (mapfn Dns_rr.TXT.t ~data:s ~misc:`None))) l
| RP l ->
List.iter (fun (mbox, txt) ->
addfn (`RP (mapfn Dns_rr.RP.t ~mbox_dname:mbox.owner.H.node
~txt_dname:txt.owner.H.node))) l
| AFSDB l ->
List.iter (fun (t, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`AFSDB (mapfn Dns_rr.AFSDB.t ~subtype:t
~hostname:d.owner.H.node))) l
| X25 l -> log_rrset owner `X25;
List.iter (fun s ->
addfn (`X25 (mapfn Dns_rr.X25.t ~psdn_address:s.H.node))) l
| ISDN l -> log_rrset owner `ISDN;
(addr, None) ->
addfn (`ISDN (mapfn Dns_rr.ISDN.t ~data:(addr.H.node)))
addfn (`ISDN (mapfn Dns_rr.ISDN.t
~data:(addr.H.node ^ sa.H.node)))) l
| RT l ->
List.iter (fun (pref, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
enqueue_additional d `X25;
enqueue_additional d `ISDN;
addfn (`RT (mapfn Dns_rr.RT.t ~preference:pref
~intermediate_host:d.owner.H.node))) l
| AAAA l -> log_rrset owner `AAAA;
List.iter (fun i ->
addfn (`AAAA (mapfn Dns_rr.AAAA.t ~ip:(`Str i.H.node)))) l
| SRV l ->
List.iter (fun (pri, weight, port, d) ->
enqueue_additional d `A;
enqueue_additional d `AAAA;
addfn (`SRV (mapfn Dns_rr.SRV.t ~priority:pri ~weight:weight
~port:port ~target:d.owner.H.node))) l
| UNSPEC l ->
List.iter (fun s ->
addfn (`UNSPEC (mapfn Dns_rr.UNSPEC.t ~data:(`Str s.H.node)))) l
in
let add_opt_rrset node rrtype section =
if not (in_log node.owner.H.node rrtype)
then let a = get_rrsets rrtype node.rrsets false in
List.iter (fun s -> add_rrset node.owner.H.node s.ttl s.rdata section) a
in
let add_req_rrset node rrtype section =
if not (in_log node.owner.H.node rrtype)
then let a = get_rrsets rrtype node.rrsets false in
if a = [] then raise TrieCorrupt;
List.iter (fun s -> add_rrset node.owner.H.node s.ttl s.rdata section) a
in
let add_negative_soa_rrset node =
let a = get_rrsets `SOA node.rrsets false in
if a = [] then raise TrieCorrupt;
RFC 2308 : The of the SOA RRset in a negative response must be set to
the minimum of its own TTL and the " minimum " field of the SOA itself
the minimum of its own TTL and the "minimum" field of the SOA itself *)
List.iter (fun s ->
match s.rdata with
SOA ((_, _, _, _, _, _, ttl) :: _) ->
add_rrset node.owner.H.node (min s.ttl ttl) s.rdata `Authority
| _ -> raise TrieCorrupt ) a
in
let rec add_answer_rrsets owner ?(lc = 5) rrsets rrtype =
let add_answer_rrset s =
match s with
Only follow the first CNAME in a set
if not (lc < 1 || rrtype = `CNAME ) then begin
add_answer_rrsets d.owner.H.node ~lc:(lc - 1) d.rrsets rrtype end;
add_rrset owner s.ttl s.rdata `Answer;
| _ -> add_rrset owner s.ttl s.rdata `Answer
in
let a = get_rrsets rrtype rrsets true in
List.iter add_answer_rrset a
in
let main_lookup qname qtype trie =
let key = canon2key qname in
match lookup key trie with
add_answer_rrsets node.owner.H.node node.rrsets qtype;
add_opt_rrset zonehead `NS `Authority;
`NoError
add_negative_soa_rrset zonehead;
`NoError
| `NoErrorNSEC (zonehead, nsec) ->
add_negative_soa_rrset zonehead;
add_opt_rrset nsec ` NSEC ` Authority ;
`NoError
add_req_rrset cutpoint `NS `Authority;
aa_flag := false;
`NoError
add_answer_rrsets qname source.rrsets qtype;
add_opt_rrset zonehead `NS `Authority;
`NoError
| `WildcardNSEC (source, zonehead, nsec) ->
add_answer_rrsets qname source.rrsets qtype;
add_opt_rrset zonehead `NS `Authority;
add_opt_rrset nsec ` NSEC ` Authority ;
`NoError
add_negative_soa_rrset zonehead;
`NXDomain
| `NXDomainNSEC (zonehead, nsec1, nsec2) ->
add_negative_soa_rrset zonehead;
add_opt_rrset nsec2 ` NSEC ` Authority ;
`NXDomain
in
try
let rc = main_lookup qname qtype trie in
List.iter (fun (o, t) -> add_opt_rrset o t `Additional) !addqueue;
{ rcode = rc; aa = !aa_flag;
answer = !ans_rrs; authority = !auth_rrs; additional = !add_rrs }
with
BadDomainName _ -> { rcode = `FormErr; aa = false;
answer = []; authority = []; additional=[] }
| TrieCorrupt -> { rcode = `ServFail; aa = false;
answer = []; authority = []; additional=[] }
|
6798447284ad478ac7b71acf074eb6a3320050abe23e5a9a5e9ce751ecb8d069 | 0xd34df00d/can-i-haz | Spec.hs | # LANGUAGE MultiParamTypeClasses , RankNTypes , GADTs #
import Test.Hspec
import Test.HUnit.Lang
import Control.DeepSeq
import Control.Exception
import Data.List
import Control.Monad.Except.CoHas
import Control.Monad.Reader.Has
import Common
import TypecheckFailures
Reimplementing due to -not-typecheck/issues/18
shouldNotTypecheck :: NFData a => (() ~ () => a) -> Assertion
shouldNotTypecheck a = do
result <- try (evaluate $ force a)
case result of
Right _ -> assertFailure "Expected expression to not compile but it did compile"
Left e@(TypeError msg) -> if "(deferred type error)" `isSuffixOf` msg
then pure ()
else throwIO e
fooEnvTwice :: FooEnv -> FooEnv
fooEnvTwice (FooEnv n s) = FooEnv (n * 2) (s <> s)
barEnvCons :: BarEnv -> BarEnv
barEnvCons (BarEnv d xs) = BarEnv d (0 : xs)
main :: IO ()
main = hspec $ do
let baseFooEnv = FooEnv 10 "meh"
let baseFooEnvTwice = FooEnv 20 "mehmeh"
let baseBarEnv = BarEnv 4.2 [1, 2, 3]
let baseBarEnvCons = BarEnv 4.2 [0, 1, 2, 3]
describe "Has" $ do
describe "Basic instance" $ do
it "any type Has itself" $ do
let exFoo = extract baseFooEnv
exFoo `shouldBe` baseFooEnv
it "any type updates itself" $ do
let baseFooEnv' = update fooEnvTwice baseFooEnv
baseFooEnv' `shouldBe` baseFooEnvTwice
describe "Generic instances" $ do
it "envs have their components" $ do
let exFoo = extract $ AppEnv baseFooEnv baseBarEnv
exFoo `shouldBe` baseFooEnv
let exBar = extract $ AppEnv baseFooEnv baseBarEnv
exBar `shouldBe` baseBarEnv
it "envs update their components" $ do
let appEnv' = update fooEnvTwice $ update barEnvCons $ AppEnv baseFooEnv baseBarEnv
appEnv' `shouldBe` AppEnv baseFooEnvTwice baseBarEnvCons
it "tuples have their components" $ do
let exFoo = extract (baseFooEnv, baseBarEnv)
exFoo `shouldBe` baseFooEnv
let exBar = extract (baseFooEnv, baseBarEnv)
exBar `shouldBe` baseBarEnv
it "tuples update their components" $ do
let pair' = update fooEnvTwice $ update barEnvCons (baseFooEnv, baseBarEnv)
pair' `shouldBe` (baseFooEnvTwice, baseBarEnvCons)
describe "Should not typecheck" $ do
it "if there is no such type in the hierarchy" $ shouldNotTypecheck extractMissing
it "if there is more than one such type in the hierarchy" $ shouldNotTypecheck extractMultiple
describe "CoHas" $ do
describe "Basic instance" $
it "any type CoHas itself" $ do
let injected = 10 :: Int
let inFoo = inject injected
inFoo `shouldBe` injected
describe "Generic instances" $ do
it "sums have their components" $ do
let inFoo = inject baseFooEnv
inFoo `shouldBe` FooEnvErr baseFooEnv
let inBar = inject baseBarEnv
inBar `shouldBe` BarEnvErr baseBarEnv
it "Either has its components" $ do
let inFoo = inject baseFooEnv :: Either FooEnv Int
inFoo `shouldBe` Left baseFooEnv
let inBar = inject baseBarEnv :: Either Int BarEnv
inBar `shouldBe` Right baseBarEnv
describe "Should not typecheck" $ do
it "if there is no such type in the hierarchy" $ shouldNotTypecheck injectMissing
it "if there is more than one such type in the hierarchy" $ shouldNotTypecheck injectMultiple
| null | https://raw.githubusercontent.com/0xd34df00d/can-i-haz/da27c09b1380ee10b859152d542489bcb6296fed/test/Spec.hs | haskell | # LANGUAGE MultiParamTypeClasses , RankNTypes , GADTs #
import Test.Hspec
import Test.HUnit.Lang
import Control.DeepSeq
import Control.Exception
import Data.List
import Control.Monad.Except.CoHas
import Control.Monad.Reader.Has
import Common
import TypecheckFailures
Reimplementing due to -not-typecheck/issues/18
shouldNotTypecheck :: NFData a => (() ~ () => a) -> Assertion
shouldNotTypecheck a = do
result <- try (evaluate $ force a)
case result of
Right _ -> assertFailure "Expected expression to not compile but it did compile"
Left e@(TypeError msg) -> if "(deferred type error)" `isSuffixOf` msg
then pure ()
else throwIO e
fooEnvTwice :: FooEnv -> FooEnv
fooEnvTwice (FooEnv n s) = FooEnv (n * 2) (s <> s)
barEnvCons :: BarEnv -> BarEnv
barEnvCons (BarEnv d xs) = BarEnv d (0 : xs)
main :: IO ()
main = hspec $ do
let baseFooEnv = FooEnv 10 "meh"
let baseFooEnvTwice = FooEnv 20 "mehmeh"
let baseBarEnv = BarEnv 4.2 [1, 2, 3]
let baseBarEnvCons = BarEnv 4.2 [0, 1, 2, 3]
describe "Has" $ do
describe "Basic instance" $ do
it "any type Has itself" $ do
let exFoo = extract baseFooEnv
exFoo `shouldBe` baseFooEnv
it "any type updates itself" $ do
let baseFooEnv' = update fooEnvTwice baseFooEnv
baseFooEnv' `shouldBe` baseFooEnvTwice
describe "Generic instances" $ do
it "envs have their components" $ do
let exFoo = extract $ AppEnv baseFooEnv baseBarEnv
exFoo `shouldBe` baseFooEnv
let exBar = extract $ AppEnv baseFooEnv baseBarEnv
exBar `shouldBe` baseBarEnv
it "envs update their components" $ do
let appEnv' = update fooEnvTwice $ update barEnvCons $ AppEnv baseFooEnv baseBarEnv
appEnv' `shouldBe` AppEnv baseFooEnvTwice baseBarEnvCons
it "tuples have their components" $ do
let exFoo = extract (baseFooEnv, baseBarEnv)
exFoo `shouldBe` baseFooEnv
let exBar = extract (baseFooEnv, baseBarEnv)
exBar `shouldBe` baseBarEnv
it "tuples update their components" $ do
let pair' = update fooEnvTwice $ update barEnvCons (baseFooEnv, baseBarEnv)
pair' `shouldBe` (baseFooEnvTwice, baseBarEnvCons)
describe "Should not typecheck" $ do
it "if there is no such type in the hierarchy" $ shouldNotTypecheck extractMissing
it "if there is more than one such type in the hierarchy" $ shouldNotTypecheck extractMultiple
describe "CoHas" $ do
describe "Basic instance" $
it "any type CoHas itself" $ do
let injected = 10 :: Int
let inFoo = inject injected
inFoo `shouldBe` injected
describe "Generic instances" $ do
it "sums have their components" $ do
let inFoo = inject baseFooEnv
inFoo `shouldBe` FooEnvErr baseFooEnv
let inBar = inject baseBarEnv
inBar `shouldBe` BarEnvErr baseBarEnv
it "Either has its components" $ do
let inFoo = inject baseFooEnv :: Either FooEnv Int
inFoo `shouldBe` Left baseFooEnv
let inBar = inject baseBarEnv :: Either Int BarEnv
inBar `shouldBe` Right baseBarEnv
describe "Should not typecheck" $ do
it "if there is no such type in the hierarchy" $ shouldNotTypecheck injectMissing
it "if there is more than one such type in the hierarchy" $ shouldNotTypecheck injectMultiple
| |
f66a6f939f0998daca9d09fc8b7d53959c52b91eec42c474947316c13d987880 | yakaz/yamerl | yamerl_node_binary.erl | %-
Copyright ( c ) 2012 - 2014 Yakaz
Copyright ( c ) 2016 - 2022 < >
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions
% are met:
1 . Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
% OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
% OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
% SUCH DAMAGE.
@private
-module(yamerl_node_binary).
-include("yamerl_errors.hrl").
-include("yamerl_tokens.hrl").
-include("yamerl_nodes.hrl").
-include("yamerl_constr.hrl").
%% Public API.
-export([
tags/0,
try_construct_token/3,
construct_token/3,
node_pres/1
]).
-define(TAG, "tag:yaml.org,2002:binary").
%% -------------------------------------------------------------------
%% Public API.
%% -------------------------------------------------------------------
tags() -> [?TAG].
try_construct_token(Constr, Node,
#yamerl_scalar{tag = #yamerl_tag{uri = {non_specific, "?"}}} = Token) ->
try
construct_token(Constr, Node, Token)
catch
_:#yamerl_parsing_error{name = not_a_binary} ->
unrecognized
end;
try_construct_token(_, _, _) ->
unrecognized.
construct_token(#yamerl_constr{detailed_constr = false},
undefined, #yamerl_scalar{text = Text} = Token) ->
case catch base64:decode(Text) of
<<Result/bitstring>> -> {finished, Result};
{'EXIT', _} -> exception(Token)
end;
construct_token(#yamerl_constr{detailed_constr = true},
undefined, #yamerl_scalar{text = Text} = Token) ->
case catch base64:decode(Text) of
<<Result/bitstring>> ->
Pres = yamerl_constr:get_pres_details(Token),
Node = #yamerl_binary{
module = ?MODULE,
tag = ?TAG,
pres = Pres,
data = Result
},
{finished, Node};
{'EXIT', _} -> exception(Token)
end;
construct_token(_, _, Token) ->
exception(Token).
node_pres(Node) ->
?NODE_PRES(Node).
exception(Token) ->
Error = #yamerl_parsing_error{
name = not_a_binary,
token = Token,
text = "Invalid binary/Not base64",
line = ?TOKEN_LINE(Token),
column = ?TOKEN_COLUMN(Token)
},
throw(Error).
| null | https://raw.githubusercontent.com/yakaz/yamerl/bf9d8b743bfc9775f2ddad9fb8d18ba5dc29d3e1/src/yamerl_node_binary.erl | erlang | -
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Public API.
-------------------------------------------------------------------
Public API.
------------------------------------------------------------------- | Copyright ( c ) 2012 - 2014 Yakaz
Copyright ( c ) 2016 - 2022 < >
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
@private
-module(yamerl_node_binary).
-include("yamerl_errors.hrl").
-include("yamerl_tokens.hrl").
-include("yamerl_nodes.hrl").
-include("yamerl_constr.hrl").
-export([
tags/0,
try_construct_token/3,
construct_token/3,
node_pres/1
]).
-define(TAG, "tag:yaml.org,2002:binary").
tags() -> [?TAG].
try_construct_token(Constr, Node,
#yamerl_scalar{tag = #yamerl_tag{uri = {non_specific, "?"}}} = Token) ->
try
construct_token(Constr, Node, Token)
catch
_:#yamerl_parsing_error{name = not_a_binary} ->
unrecognized
end;
try_construct_token(_, _, _) ->
unrecognized.
construct_token(#yamerl_constr{detailed_constr = false},
undefined, #yamerl_scalar{text = Text} = Token) ->
case catch base64:decode(Text) of
<<Result/bitstring>> -> {finished, Result};
{'EXIT', _} -> exception(Token)
end;
construct_token(#yamerl_constr{detailed_constr = true},
undefined, #yamerl_scalar{text = Text} = Token) ->
case catch base64:decode(Text) of
<<Result/bitstring>> ->
Pres = yamerl_constr:get_pres_details(Token),
Node = #yamerl_binary{
module = ?MODULE,
tag = ?TAG,
pres = Pres,
data = Result
},
{finished, Node};
{'EXIT', _} -> exception(Token)
end;
construct_token(_, _, Token) ->
exception(Token).
node_pres(Node) ->
?NODE_PRES(Node).
exception(Token) ->
Error = #yamerl_parsing_error{
name = not_a_binary,
token = Token,
text = "Invalid binary/Not base64",
line = ?TOKEN_LINE(Token),
column = ?TOKEN_COLUMN(Token)
},
throw(Error).
|
5396b7b763e78bf8cd67011946ed212601254a7287b21922ff21d6b563b3f701 | gregnwosu/haskellbook | Main.hs | module Main where
import Addition
main :: IO ()
main = return ()
| null | https://raw.githubusercontent.com/gregnwosu/haskellbook/b21fb6772e58f07cff334d9c551d0477ec856897/chapter14/testing/app/Main.hs | haskell | module Main where
import Addition
main :: IO ()
main = return ()
| |
ed3d62b97fee6a859163ae07cfc61a2bedb25e3881d3129fa7da81f547b3aa8a | gtk2hs/gtk2hs | UTFString.hs | # LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE OverloadedStrings #-}
GIMP Toolkit ( GTK ) UTF aware string marshalling
--
Author :
--
Created : 22 June 2001
--
Copyright ( c ) 1999 .. 2002
--
-- This library 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 2.1 of the License , or ( at your option ) any later version .
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- |
-- Maintainer :
-- Stability : provisional
Portability : portable ( depends on GHC )
--
-- This module adds CString-like functions that handle UTF8 strings.
--
module System.Glib.UTFString (
GlibString(..),
readUTFString,
readCString,
withUTFStrings,
withUTFStringArray,
withUTFStringArray0,
peekUTFStringArray,
peekUTFStringArray0,
readUTFStringArray0,
UTFCorrection,
ofsToUTF,
ofsFromUTF,
glibToString,
stringToGlib,
DefaultGlibString,
GlibFilePath(..),
withUTFFilePaths,
withUTFFilePathArray,
withUTFFilePathArray0,
peekUTFFilePathArray0,
readUTFFilePathArray0
) where
import Codec.Binary.UTF8.String
import Control.Applicative ((<$>))
import Control.Monad (liftM)
import Data.Char (ord, chr)
import Data.Maybe (maybe)
import Data.String (IsString)
import Data.Monoid (Monoid)
import System.Glib.FFI
import qualified Data.Text as T (replace, length, pack, unpack, Text)
import qualified Data.Text.Foreign as T
(withCStringLen, peekCStringLen)
import Data.ByteString (useAsCString)
import Data.Text.Encoding (encodeUtf8)
class (IsString s, Monoid s, Show s) => GlibString s where
| Like ' withCString ' but using the UTF-8 encoding .
--
withUTFString :: s -> (CString -> IO a) -> IO a
| Like ' withCStringLen ' but using the UTF-8 encoding .
--
withUTFStringLen :: s -> (CStringLen -> IO a) -> IO a
| Like ' peekCString ' but using the UTF-8 encoding .
--
peekUTFString :: CString -> IO s
| Like ' maybePeek ' ' peekCString ' but using the UTF-8 encoding to retrieve
UTF-8 from a ' CString ' which may be the ' nullPtr ' .
--
maybePeekUTFString :: CString -> IO (Maybe s)
| Like ' peekCStringLen ' but using the UTF-8 encoding .
--
peekUTFStringLen :: CStringLen -> IO s
| Like ' newCString ' but using the UTF-8 encoding .
--
newUTFString :: s -> IO CString
| Like Define newUTFStringLen to emit UTF-8 .
--
newUTFStringLen :: s -> IO CStringLen
-- | Create a list of offset corrections.
--
genUTFOfs :: s -> UTFCorrection
-- | Length of the string in characters
--
stringLength :: s -> Int
Escape percent signs ( used in MessageDialog )
unPrintf :: s -> s
GTK+ has a lot of asserts that the ptr is not NULL even if the length is 0
-- Until they fix this we need to fudge pointer values to keep the noise level
-- in the logs.
noNullPtrs :: CStringLen -> CStringLen
noNullPtrs (p, 0) | p == nullPtr = (plusPtr p 1, 0)
noNullPtrs s = s
instance GlibString [Char] where
withUTFString = withCAString . encodeString
withUTFStringLen s f = withCAStringLen (encodeString s) (f . noNullPtrs)
peekUTFString = liftM decodeString . peekCAString
maybePeekUTFString = liftM (maybe Nothing (Just . decodeString)) . maybePeek peekCAString
peekUTFStringLen = liftM decodeString . peekCAStringLen
newUTFString = newCAString . encodeString
newUTFStringLen = newCAStringLen . encodeString
genUTFOfs str = UTFCorrection (gUO 0 str)
where
gUO n [] = []
gUO n (x:xs) | ord x<=0x007F = gUO (n+1) xs
| ord x<=0x07FF = n:gUO (n+1) xs
| ord x<=0xFFFF = n:n:gUO (n+1) xs
| otherwise = n:n:n:gUO (n+1) xs
stringLength = length
unPrintf s = s >>= replace
where
replace '%' = "%%"
replace c = return c
foreign import ccall unsafe "string.h strlen" c_strlen
:: CString -> IO CSize
instance GlibString T.Text where
withUTFString = useAsCString . encodeUtf8
withUTFStringLen s f = T.withCStringLen s (f . noNullPtrs)
peekUTFString s = do
len <- c_strlen s
T.peekCStringLen (s, fromIntegral len)
maybePeekUTFString = maybePeek peekUTFString
peekUTFStringLen = T.peekCStringLen
TODO optimize
TODO optimize
TODO optimize
stringLength = T.length
unPrintf = T.replace "%" "%%"
glibToString :: T.Text -> String
glibToString = T.unpack
stringToGlib :: String -> T.Text
stringToGlib = T.pack
-- | Like like 'peekUTFString' but then frees the string using g_free
--
readUTFString :: GlibString s => CString -> IO s
readUTFString strPtr = do
str <- peekUTFString strPtr
g_free strPtr
return str
| Like ' peekCString ' but then frees the string using @g_free@.
--
readCString :: CString -> IO String
readCString strPtr = do
str <- peekCAString strPtr
g_free strPtr
return str
foreign import ccall unsafe "g_free"
g_free :: Ptr a -> IO ()
| Temporarily allocate a list of UTF-8 ' CString 's .
--
withUTFStrings :: GlibString s => [s] -> ([CString] -> IO a) -> IO a
withUTFStrings hsStrs = withUTFStrings' hsStrs []
where withUTFStrings' :: GlibString s => [s] -> [CString] -> ([CString] -> IO a) -> IO a
withUTFStrings' [] cs body = body (reverse cs)
withUTFStrings' (s:ss) cs body = withUTFString s $ \c ->
withUTFStrings' ss (c:cs) body
| Temporarily allocate an array of UTF-8 encoded ' CString 's .
--
withUTFStringArray :: GlibString s => [s] -> (Ptr CString -> IO a) -> IO a
withUTFStringArray hsStr body =
withUTFStrings hsStr $ \cStrs -> do
withArray cStrs body
| Temporarily allocate a null - terminated array of UTF-8 encoded ' CString 's .
--
withUTFStringArray0 :: GlibString s => [s] -> (Ptr CString -> IO a) -> IO a
withUTFStringArray0 hsStr body =
withUTFStrings hsStr $ \cStrs -> do
withArray0 nullPtr cStrs body
| Convert an array ( of the given length ) of UTF-8 encoded ' CString 's to a
list of ' String 's .
--
peekUTFStringArray :: GlibString s => Int -> Ptr CString -> IO [s]
peekUTFStringArray len cStrArr = do
cStrs <- peekArray len cStrArr
mapM peekUTFString cStrs
| Convert a null - terminated array of UTF-8 encoded ' CString 's to a list of
' String 's .
--
peekUTFStringArray0 :: GlibString s => Ptr CString -> IO [s]
peekUTFStringArray0 cStrArr = do
cStrs <- peekArray0 nullPtr cStrArr
mapM peekUTFString cStrs
-- | Like 'peekUTFStringArray0' but then free the string array including all
-- strings.
--
-- To be used when functions indicate that their return value should be freed
-- with @g_strfreev@.
--
readUTFStringArray0 :: GlibString s => Ptr CString -> IO [s]
readUTFStringArray0 cStrArr | cStrArr == nullPtr = return []
| otherwise = do
cStrs <- peekArray0 nullPtr cStrArr
strings <- mapM peekUTFString cStrs
g_strfreev cStrArr
return strings
foreign import ccall unsafe "g_strfreev"
g_strfreev :: Ptr a -> IO ()
-- | Offset correction for String to UTF8 mapping.
--
newtype UTFCorrection = UTFCorrection [Int] deriving Show
ofsToUTF :: Int -> UTFCorrection -> Int
ofsToUTF n (UTFCorrection oc) = oTU oc
where
oTU [] = n
oTU (x:xs) | n<=x = n
| otherwise = 1+oTU xs
ofsFromUTF :: Int -> UTFCorrection -> Int
ofsFromUTF n (UTFCorrection oc) = oFU n oc
where
oFU n [] = n
oFU n (x:xs) | n<=x = n
| otherwise = oFU (n-1) xs
type DefaultGlibString = T.Text
class fp ~ FilePath => GlibFilePath fp where
withUTFFilePath :: fp -> (CString -> IO a) -> IO a
peekUTFFilePath :: CString -> IO fp
instance GlibFilePath FilePath where
withUTFFilePath = withUTFString . T.pack
peekUTFFilePath f = T.unpack <$> peekUTFString f
withUTFFilePaths :: GlibFilePath fp => [fp] -> ([CString] -> IO a) -> IO a
withUTFFilePaths hsStrs = withUTFFilePath' hsStrs []
where withUTFFilePath' :: GlibFilePath fp => [fp] -> [CString] -> ([CString] -> IO a) -> IO a
withUTFFilePath' [] cs body = body (reverse cs)
withUTFFilePath' (fp:fps) cs body = withUTFFilePath fp $ \c ->
withUTFFilePath' fps (c:cs) body
withUTFFilePathArray :: GlibFilePath fp => [fp] -> (Ptr CString -> IO a) -> IO a
withUTFFilePathArray hsFP body =
withUTFFilePaths hsFP $ \cStrs -> do
withArray cStrs body
withUTFFilePathArray0 :: GlibFilePath fp => [fp] -> (Ptr CString -> IO a) -> IO a
withUTFFilePathArray0 hsFP body =
withUTFFilePaths hsFP $ \cStrs -> do
withArray0 nullPtr cStrs body
peekUTFFilePathArray0 :: GlibFilePath fp => Ptr CString -> IO [fp]
peekUTFFilePathArray0 cStrArr = do
cStrs <- peekArray0 nullPtr cStrArr
mapM peekUTFFilePath cStrs
readUTFFilePathArray0 :: GlibFilePath fp => Ptr CString -> IO [fp]
readUTFFilePathArray0 cStrArr | cStrArr == nullPtr = return []
| otherwise = do
cStrs <- peekArray0 nullPtr cStrArr
fps <- mapM peekUTFFilePath cStrs
g_strfreev cStrArr
return fps
| null | https://raw.githubusercontent.com/gtk2hs/gtk2hs/0f90caa1dae319a0f4bbab76ed1a84f17c730adf/glib/System/Glib/UTFString.hs | haskell | # LANGUAGE OverloadedStrings #
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
|
Maintainer :
Stability : provisional
This module adds CString-like functions that handle UTF8 strings.
| Create a list of offset corrections.
| Length of the string in characters
Until they fix this we need to fudge pointer values to keep the noise level
in the logs.
| Like like 'peekUTFString' but then frees the string using g_free
| Like 'peekUTFStringArray0' but then free the string array including all
strings.
To be used when functions indicate that their return value should be freed
with @g_strfreev@.
| Offset correction for String to UTF8 mapping.
| # LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
GIMP Toolkit ( GTK ) UTF aware string marshalling
Author :
Created : 22 June 2001
Copyright ( c ) 1999 .. 2002
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
Portability : portable ( depends on GHC )
module System.Glib.UTFString (
GlibString(..),
readUTFString,
readCString,
withUTFStrings,
withUTFStringArray,
withUTFStringArray0,
peekUTFStringArray,
peekUTFStringArray0,
readUTFStringArray0,
UTFCorrection,
ofsToUTF,
ofsFromUTF,
glibToString,
stringToGlib,
DefaultGlibString,
GlibFilePath(..),
withUTFFilePaths,
withUTFFilePathArray,
withUTFFilePathArray0,
peekUTFFilePathArray0,
readUTFFilePathArray0
) where
import Codec.Binary.UTF8.String
import Control.Applicative ((<$>))
import Control.Monad (liftM)
import Data.Char (ord, chr)
import Data.Maybe (maybe)
import Data.String (IsString)
import Data.Monoid (Monoid)
import System.Glib.FFI
import qualified Data.Text as T (replace, length, pack, unpack, Text)
import qualified Data.Text.Foreign as T
(withCStringLen, peekCStringLen)
import Data.ByteString (useAsCString)
import Data.Text.Encoding (encodeUtf8)
class (IsString s, Monoid s, Show s) => GlibString s where
| Like ' withCString ' but using the UTF-8 encoding .
withUTFString :: s -> (CString -> IO a) -> IO a
| Like ' withCStringLen ' but using the UTF-8 encoding .
withUTFStringLen :: s -> (CStringLen -> IO a) -> IO a
| Like ' peekCString ' but using the UTF-8 encoding .
peekUTFString :: CString -> IO s
| Like ' maybePeek ' ' peekCString ' but using the UTF-8 encoding to retrieve
UTF-8 from a ' CString ' which may be the ' nullPtr ' .
maybePeekUTFString :: CString -> IO (Maybe s)
| Like ' peekCStringLen ' but using the UTF-8 encoding .
peekUTFStringLen :: CStringLen -> IO s
| Like ' newCString ' but using the UTF-8 encoding .
newUTFString :: s -> IO CString
| Like Define newUTFStringLen to emit UTF-8 .
newUTFStringLen :: s -> IO CStringLen
genUTFOfs :: s -> UTFCorrection
stringLength :: s -> Int
Escape percent signs ( used in MessageDialog )
unPrintf :: s -> s
GTK+ has a lot of asserts that the ptr is not NULL even if the length is 0
noNullPtrs :: CStringLen -> CStringLen
noNullPtrs (p, 0) | p == nullPtr = (plusPtr p 1, 0)
noNullPtrs s = s
instance GlibString [Char] where
withUTFString = withCAString . encodeString
withUTFStringLen s f = withCAStringLen (encodeString s) (f . noNullPtrs)
peekUTFString = liftM decodeString . peekCAString
maybePeekUTFString = liftM (maybe Nothing (Just . decodeString)) . maybePeek peekCAString
peekUTFStringLen = liftM decodeString . peekCAStringLen
newUTFString = newCAString . encodeString
newUTFStringLen = newCAStringLen . encodeString
genUTFOfs str = UTFCorrection (gUO 0 str)
where
gUO n [] = []
gUO n (x:xs) | ord x<=0x007F = gUO (n+1) xs
| ord x<=0x07FF = n:gUO (n+1) xs
| ord x<=0xFFFF = n:n:gUO (n+1) xs
| otherwise = n:n:n:gUO (n+1) xs
stringLength = length
unPrintf s = s >>= replace
where
replace '%' = "%%"
replace c = return c
foreign import ccall unsafe "string.h strlen" c_strlen
:: CString -> IO CSize
instance GlibString T.Text where
withUTFString = useAsCString . encodeUtf8
withUTFStringLen s f = T.withCStringLen s (f . noNullPtrs)
peekUTFString s = do
len <- c_strlen s
T.peekCStringLen (s, fromIntegral len)
maybePeekUTFString = maybePeek peekUTFString
peekUTFStringLen = T.peekCStringLen
TODO optimize
TODO optimize
TODO optimize
stringLength = T.length
unPrintf = T.replace "%" "%%"
glibToString :: T.Text -> String
glibToString = T.unpack
stringToGlib :: String -> T.Text
stringToGlib = T.pack
readUTFString :: GlibString s => CString -> IO s
readUTFString strPtr = do
str <- peekUTFString strPtr
g_free strPtr
return str
| Like ' peekCString ' but then frees the string using @g_free@.
readCString :: CString -> IO String
readCString strPtr = do
str <- peekCAString strPtr
g_free strPtr
return str
foreign import ccall unsafe "g_free"
g_free :: Ptr a -> IO ()
| Temporarily allocate a list of UTF-8 ' CString 's .
withUTFStrings :: GlibString s => [s] -> ([CString] -> IO a) -> IO a
withUTFStrings hsStrs = withUTFStrings' hsStrs []
where withUTFStrings' :: GlibString s => [s] -> [CString] -> ([CString] -> IO a) -> IO a
withUTFStrings' [] cs body = body (reverse cs)
withUTFStrings' (s:ss) cs body = withUTFString s $ \c ->
withUTFStrings' ss (c:cs) body
| Temporarily allocate an array of UTF-8 encoded ' CString 's .
withUTFStringArray :: GlibString s => [s] -> (Ptr CString -> IO a) -> IO a
withUTFStringArray hsStr body =
withUTFStrings hsStr $ \cStrs -> do
withArray cStrs body
| Temporarily allocate a null - terminated array of UTF-8 encoded ' CString 's .
withUTFStringArray0 :: GlibString s => [s] -> (Ptr CString -> IO a) -> IO a
withUTFStringArray0 hsStr body =
withUTFStrings hsStr $ \cStrs -> do
withArray0 nullPtr cStrs body
| Convert an array ( of the given length ) of UTF-8 encoded ' CString 's to a
list of ' String 's .
peekUTFStringArray :: GlibString s => Int -> Ptr CString -> IO [s]
peekUTFStringArray len cStrArr = do
cStrs <- peekArray len cStrArr
mapM peekUTFString cStrs
| Convert a null - terminated array of UTF-8 encoded ' CString 's to a list of
' String 's .
peekUTFStringArray0 :: GlibString s => Ptr CString -> IO [s]
peekUTFStringArray0 cStrArr = do
cStrs <- peekArray0 nullPtr cStrArr
mapM peekUTFString cStrs
readUTFStringArray0 :: GlibString s => Ptr CString -> IO [s]
readUTFStringArray0 cStrArr | cStrArr == nullPtr = return []
| otherwise = do
cStrs <- peekArray0 nullPtr cStrArr
strings <- mapM peekUTFString cStrs
g_strfreev cStrArr
return strings
foreign import ccall unsafe "g_strfreev"
g_strfreev :: Ptr a -> IO ()
newtype UTFCorrection = UTFCorrection [Int] deriving Show
ofsToUTF :: Int -> UTFCorrection -> Int
ofsToUTF n (UTFCorrection oc) = oTU oc
where
oTU [] = n
oTU (x:xs) | n<=x = n
| otherwise = 1+oTU xs
ofsFromUTF :: Int -> UTFCorrection -> Int
ofsFromUTF n (UTFCorrection oc) = oFU n oc
where
oFU n [] = n
oFU n (x:xs) | n<=x = n
| otherwise = oFU (n-1) xs
type DefaultGlibString = T.Text
class fp ~ FilePath => GlibFilePath fp where
withUTFFilePath :: fp -> (CString -> IO a) -> IO a
peekUTFFilePath :: CString -> IO fp
instance GlibFilePath FilePath where
withUTFFilePath = withUTFString . T.pack
peekUTFFilePath f = T.unpack <$> peekUTFString f
withUTFFilePaths :: GlibFilePath fp => [fp] -> ([CString] -> IO a) -> IO a
withUTFFilePaths hsStrs = withUTFFilePath' hsStrs []
where withUTFFilePath' :: GlibFilePath fp => [fp] -> [CString] -> ([CString] -> IO a) -> IO a
withUTFFilePath' [] cs body = body (reverse cs)
withUTFFilePath' (fp:fps) cs body = withUTFFilePath fp $ \c ->
withUTFFilePath' fps (c:cs) body
withUTFFilePathArray :: GlibFilePath fp => [fp] -> (Ptr CString -> IO a) -> IO a
withUTFFilePathArray hsFP body =
withUTFFilePaths hsFP $ \cStrs -> do
withArray cStrs body
withUTFFilePathArray0 :: GlibFilePath fp => [fp] -> (Ptr CString -> IO a) -> IO a
withUTFFilePathArray0 hsFP body =
withUTFFilePaths hsFP $ \cStrs -> do
withArray0 nullPtr cStrs body
peekUTFFilePathArray0 :: GlibFilePath fp => Ptr CString -> IO [fp]
peekUTFFilePathArray0 cStrArr = do
cStrs <- peekArray0 nullPtr cStrArr
mapM peekUTFFilePath cStrs
readUTFFilePathArray0 :: GlibFilePath fp => Ptr CString -> IO [fp]
readUTFFilePathArray0 cStrArr | cStrArr == nullPtr = return []
| otherwise = do
cStrs <- peekArray0 nullPtr cStrArr
fps <- mapM peekUTFFilePath cStrs
g_strfreev cStrArr
return fps
|
98ec94797bf9ca131c63dc638c5a677a0f906e859c1ab1172504955d4e226e28 | johnwhitington/haskell-from-the-very-beginning-exercises | Exercises.hs | --Prelimineries
length' :: Num b => [a] -> b
length' [] = 0
length' (_:xs) = 1 + length' xs
map' :: (a -> b) -> [a] -> [b]
map' f [] = []
map' f (x:xs) = f x : map' f xs
not' :: Bool -> Bool
not' False = True
not' True = False
take' :: (Eq a, Num a) => a -> [b] -> [b]
take' 0 l = []
take' n (x:xs) = x : take' (n - 1) xs
elem' :: Eq a => a -> [a] -> Bool
elem' e [] = False
elem' e (x:xs) = x == e || elem' e xs
elemAll :: Eq a => a -> [[a]] -> Bool
elemAll e ls =
let booleans = map' (elem' e) ls in
not' (elem' False booleans)
-- Haskell won't let us re-use a name in a script, so we call this length'2
elemAll2 :: Eq a => a -> [[a]] -> Bool
elemAll2 e ls =
not' (elem' False (map' (elem' e) ls))
elemAll3 :: Eq a => a -> [[a]] -> Bool
elemAll3 e =
not' . (elem' False) . (map' (elem' e))
mapll :: (a -> b) -> [[[a]]] -> [[[b]]]
mapll f l = map' (map' (map' f)) l
mapll2 :: (a -> b) -> [[[a]]] -> [[[b]]]
mapll2 f = map' (map' (map' f))
mapll3 :: (a -> b) -> [[[a]]] -> [[[b]]]
mapll3 = map' . map' . map'
truncateList :: (Ord a, Num a) => a -> [b] -> [b]
truncateList n l =
if length' l >= n then take' n l else l
truncateLists :: (Num a, Ord a) => a -> [[b]] -> [[b]]
truncateLists n ll = map' (truncateList n) ll
firstElt :: a -> [a] -> a
firstElt n [] = n
firstElt n (x:_) = x
firstElts :: a -> [[a]] -> [a]
firstElts n l = map' (firstElt n) l
addNum n ls = map' (n :) ls
| null | https://raw.githubusercontent.com/johnwhitington/haskell-from-the-very-beginning-exercises/18bda69bf8a0233feb6f023c6a2219b7c20e9fa1/exercises/Chapter9/Exercises.hs | haskell | Prelimineries
Haskell won't let us re-use a name in a script, so we call this length'2 | length' :: Num b => [a] -> b
length' [] = 0
length' (_:xs) = 1 + length' xs
map' :: (a -> b) -> [a] -> [b]
map' f [] = []
map' f (x:xs) = f x : map' f xs
not' :: Bool -> Bool
not' False = True
not' True = False
take' :: (Eq a, Num a) => a -> [b] -> [b]
take' 0 l = []
take' n (x:xs) = x : take' (n - 1) xs
elem' :: Eq a => a -> [a] -> Bool
elem' e [] = False
elem' e (x:xs) = x == e || elem' e xs
elemAll :: Eq a => a -> [[a]] -> Bool
elemAll e ls =
let booleans = map' (elem' e) ls in
not' (elem' False booleans)
elemAll2 :: Eq a => a -> [[a]] -> Bool
elemAll2 e ls =
not' (elem' False (map' (elem' e) ls))
elemAll3 :: Eq a => a -> [[a]] -> Bool
elemAll3 e =
not' . (elem' False) . (map' (elem' e))
mapll :: (a -> b) -> [[[a]]] -> [[[b]]]
mapll f l = map' (map' (map' f)) l
mapll2 :: (a -> b) -> [[[a]]] -> [[[b]]]
mapll2 f = map' (map' (map' f))
mapll3 :: (a -> b) -> [[[a]]] -> [[[b]]]
mapll3 = map' . map' . map'
truncateList :: (Ord a, Num a) => a -> [b] -> [b]
truncateList n l =
if length' l >= n then take' n l else l
truncateLists :: (Num a, Ord a) => a -> [[b]] -> [[b]]
truncateLists n ll = map' (truncateList n) ll
firstElt :: a -> [a] -> a
firstElt n [] = n
firstElt n (x:_) = x
firstElts :: a -> [[a]] -> [a]
firstElts n l = map' (firstElt n) l
addNum n ls = map' (n :) ls
|
2655a7c34e1d60a2fc50ac2019b09633a5656c3a5ae334d973f8c71335b7d6c1 | input-output-hk/ouroboros-network | Serialisation.hs | {-# LANGUAGE DerivingStrategies #-}
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# OPTIONS_GHC -Wno - orphans #
module Test.Consensus.Byron.Serialisation (tests) where
import Codec.CBOR.Write (toLazyByteString)
import qualified Data.ByteString.Lazy as Lazy
import Data.Functor.Identity
import Cardano.Chain.Block (ABlockOrBoundary (..))
import qualified Cardano.Chain.Block as CC.Block
import qualified Cardano.Chain.Update as CC.Update
import Ouroboros.Consensus.Config
import qualified Ouroboros.Consensus.Mempool as Mempool
import Ouroboros.Consensus.Node.ProtocolInfo
import Ouroboros.Consensus.Node.Serialisation ()
import Ouroboros.Consensus.Util (Dict (..))
import Ouroboros.Consensus.Storage.Common (BinaryBlockInfo (..))
import Ouroboros.Consensus.Byron.Ledger
import Ouroboros.Consensus.Byron.Node
import Test.QuickCheck hiding (Result)
import Test.Tasty
import Test.Tasty.QuickCheck
import qualified Test.Cardano.Chain.Genesis.Dummy as CC
import Test.Util.Corruption
import Test.Util.Orphans.Arbitrary ()
import Test.Util.Serialisation.Roundtrip
import Test.Consensus.Byron.Generators
tests :: TestTree
tests = testGroup "Byron"
[ roundtrip_all testCodecCfg dictNestedHdr
, testProperty "BinaryBlockInfo sanity check" prop_byronBinaryBlockInfo
, testGroup "Integrity"
[ testProperty "detect corruption in RegularBlock" prop_detectCorruption_RegularBlock
]
]
where
dictNestedHdr :: forall a. NestedCtxt_ ByronBlock Header a -> Dict (Eq a, Show a)
dictNestedHdr (CtxtByronBoundary _) = Dict
dictNestedHdr (CtxtByronRegular _) = Dict
------------------------------------------------------------------------------
BinaryBlockInfo
------------------------------------------------------------------------------
BinaryBlockInfo
-------------------------------------------------------------------------------}
prop_byronBinaryBlockInfo :: ByronBlock -> Property
prop_byronBinaryBlockInfo blk =
headerAnnotation === extractedHeader
where
BinaryBlockInfo { headerOffset, headerSize } =
byronBinaryBlockInfo blk
extractedHeader :: Lazy.ByteString
extractedHeader =
Lazy.take (fromIntegral headerSize) $
Lazy.drop (fromIntegral headerOffset) $
toLazyByteString (encodeByronBlock blk)
headerAnnotation :: Lazy.ByteString
headerAnnotation = Lazy.fromStrict $ case byronBlockRaw blk of
ABOBBoundary b -> CC.Block.boundaryHeaderAnnotation $ CC.Block.boundaryHeader b
ABOBBlock b -> CC.Block.headerAnnotation $ CC.Block.blockHeader b
{-------------------------------------------------------------------------------
Integrity
-------------------------------------------------------------------------------}
-- | Test that we can detect random bitflips in blocks.
--
-- We cannot do this for EBBs, as they are not signed nor have a hash, so we
-- only test with regular blocks.
prop_detectCorruption_RegularBlock :: RegularBlock -> Corruption -> Property
prop_detectCorruption_RegularBlock (RegularBlock blk) =
detectCorruption
encodeByronBlock
(decodeByronBlock epochSlots)
(verifyBlockIntegrity (configBlock testCfg))
blk
-- | Matches the values used for the generators.
testCfg :: TopLevelConfig ByronBlock
testCfg = pInfoConfig protocolInfo
where
protocolInfo :: ProtocolInfo Identity ByronBlock
protocolInfo =
protocolInfoByron $ ProtocolParamsByron {
byronGenesis = CC.dummyConfig
, byronPbftSignatureThreshold = Just (PBftSignatureThreshold 0.5)
, byronProtocolVersion = CC.Update.ProtocolVersion 1 0 0
, byronSoftwareVersion = CC.Update.SoftwareVersion (CC.Update.ApplicationName "Cardano Test") 2
, byronLeaderCredentials = Nothing
, byronMaxTxCapacityOverrides = Mempool.mkOverrides Mempool.noOverridesMeasure
}
-- | Matches the values used for the generators.
testCodecCfg :: CodecConfig ByronBlock
testCodecCfg = configCodec testCfg
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/ebb34fa4d1ba1357e3b803a49f750d2ae3df19e5/ouroboros-consensus-byron-test/test/Test/Consensus/Byron/Serialisation.hs | haskell | # LANGUAGE DerivingStrategies #
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-----------------------------------------------------------------------------}
------------------------------------------------------------------------------
Integrity
------------------------------------------------------------------------------
| Test that we can detect random bitflips in blocks.
We cannot do this for EBBs, as they are not signed nor have a hash, so we
only test with regular blocks.
| Matches the values used for the generators.
| Matches the values used for the generators. | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
# OPTIONS_GHC -Wno - orphans #
module Test.Consensus.Byron.Serialisation (tests) where
import Codec.CBOR.Write (toLazyByteString)
import qualified Data.ByteString.Lazy as Lazy
import Data.Functor.Identity
import Cardano.Chain.Block (ABlockOrBoundary (..))
import qualified Cardano.Chain.Block as CC.Block
import qualified Cardano.Chain.Update as CC.Update
import Ouroboros.Consensus.Config
import qualified Ouroboros.Consensus.Mempool as Mempool
import Ouroboros.Consensus.Node.ProtocolInfo
import Ouroboros.Consensus.Node.Serialisation ()
import Ouroboros.Consensus.Util (Dict (..))
import Ouroboros.Consensus.Storage.Common (BinaryBlockInfo (..))
import Ouroboros.Consensus.Byron.Ledger
import Ouroboros.Consensus.Byron.Node
import Test.QuickCheck hiding (Result)
import Test.Tasty
import Test.Tasty.QuickCheck
import qualified Test.Cardano.Chain.Genesis.Dummy as CC
import Test.Util.Corruption
import Test.Util.Orphans.Arbitrary ()
import Test.Util.Serialisation.Roundtrip
import Test.Consensus.Byron.Generators
tests :: TestTree
tests = testGroup "Byron"
[ roundtrip_all testCodecCfg dictNestedHdr
, testProperty "BinaryBlockInfo sanity check" prop_byronBinaryBlockInfo
, testGroup "Integrity"
[ testProperty "detect corruption in RegularBlock" prop_detectCorruption_RegularBlock
]
]
where
dictNestedHdr :: forall a. NestedCtxt_ ByronBlock Header a -> Dict (Eq a, Show a)
dictNestedHdr (CtxtByronBoundary _) = Dict
dictNestedHdr (CtxtByronRegular _) = Dict
BinaryBlockInfo
BinaryBlockInfo
prop_byronBinaryBlockInfo :: ByronBlock -> Property
prop_byronBinaryBlockInfo blk =
headerAnnotation === extractedHeader
where
BinaryBlockInfo { headerOffset, headerSize } =
byronBinaryBlockInfo blk
extractedHeader :: Lazy.ByteString
extractedHeader =
Lazy.take (fromIntegral headerSize) $
Lazy.drop (fromIntegral headerOffset) $
toLazyByteString (encodeByronBlock blk)
headerAnnotation :: Lazy.ByteString
headerAnnotation = Lazy.fromStrict $ case byronBlockRaw blk of
ABOBBoundary b -> CC.Block.boundaryHeaderAnnotation $ CC.Block.boundaryHeader b
ABOBBlock b -> CC.Block.headerAnnotation $ CC.Block.blockHeader b
prop_detectCorruption_RegularBlock :: RegularBlock -> Corruption -> Property
prop_detectCorruption_RegularBlock (RegularBlock blk) =
detectCorruption
encodeByronBlock
(decodeByronBlock epochSlots)
(verifyBlockIntegrity (configBlock testCfg))
blk
testCfg :: TopLevelConfig ByronBlock
testCfg = pInfoConfig protocolInfo
where
protocolInfo :: ProtocolInfo Identity ByronBlock
protocolInfo =
protocolInfoByron $ ProtocolParamsByron {
byronGenesis = CC.dummyConfig
, byronPbftSignatureThreshold = Just (PBftSignatureThreshold 0.5)
, byronProtocolVersion = CC.Update.ProtocolVersion 1 0 0
, byronSoftwareVersion = CC.Update.SoftwareVersion (CC.Update.ApplicationName "Cardano Test") 2
, byronLeaderCredentials = Nothing
, byronMaxTxCapacityOverrides = Mempool.mkOverrides Mempool.noOverridesMeasure
}
testCodecCfg :: CodecConfig ByronBlock
testCodecCfg = configCodec testCfg
|
c1863f6f695cb19d26176e6df5c131014d273ebfa8732e223eaa3cc9866c76ad | scmlab/gcl | Error.hs | {-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Pretty.Error where
import Data.Foldable ( toList )
import Data.Loc
import Prettyprinter
import Error
import GCL.Type ( TypeError(..) )
import GCL.WP.Type ( StructError(..)
, StructWarning(..)
)
import Prelude hiding ( Ordering(..) )
import Pretty.Abstract ( )
import Pretty.Predicate ( )
import Pretty.Util ( )
import Syntax.Parser.Error ( ParseError(..) )
-- | Error
instance Pretty Error where
pretty (ParseError err) = "Parse Error" <+> line <> pretty err
pretty (TypeError err) =
"Type Error" <+> pretty (locOf err) <> line <> pretty err
pretty (StructError err) =
"Struct Error" <+> pretty (locOf err) <> line <> pretty err
pretty (CannotReadFile path) = "CannotReadFile" <+> pretty path
pretty (Others msg ) = "Others" <+> pretty msg
instance Pretty ParseError where
pretty (LexicalError pos ) = "Lexical Error" <+> pretty (displayPos pos)
pretty (SyntacticError pairs _) = "Parse Error" <+> vsep
(map (\(loc, msg) -> pretty (displayLoc loc) <+> pretty msg) $ toList pairs)
the second argument was parsing log , used for debugging
instance Pretty StructWarning where
pretty (MissingBound loc) = "Missing Bound" <+> pretty loc
pretty (ExcessBound loc) = "Excess Bound" <+> pretty loc
instance Pretty StructError where
pretty (MissingAssertion loc) = "Missing Assertion" <+> pretty loc
pretty (MissingPostcondition loc) = "Missing Postcondition" <+> pretty loc
pretty (MultiDimArrayAsgnNotImp loc) =
"Assignment to Multi-Dimensional Array" <+> pretty loc
pretty (LocalVarExceedScope loc) =
"Local Variable(s) Exceeded Scope" <+> pretty loc
instance Pretty TypeError where
pretty (NotInScope name) =
"The definition" <+> pretty name <+> "is not in scope"
pretty (UnifyFailed a b _) =
"Cannot unify:" <+> pretty a <+> "with" <+> pretty b
pretty (RecursiveType v a _) =
"Recursive type variable: " <+> pretty v <+> "in" <+> pretty a
pretty (AssignToConst n) =
"The constant identifier: " <+> pretty n <+> "cannot be assigned"
pretty (UndefinedType n) =
"Undefined Type: " <+> "Type" <+> pretty n <+> "is undefined"
pretty (DuplicatedIdentifiers ns) =
"The identifiers:" <+> pretty ns <+> "are duplicated"
pretty (RedundantNames ns) = "The names: " <+> pretty ns <+> "are redundant"
pretty (RedundantExprs exprs) =
"The exprs: " <+> pretty exprs <+> "are redundant"
pretty (MissingArguments ns) =
"The arguments: " <+> pretty ns <+> "are missing"
| null | https://raw.githubusercontent.com/scmlab/gcl/b91605267750d38c20b1491c142632e632a28673/src/Pretty/Error.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE TypeSynonymInstances #
| Error |
module Pretty.Error where
import Data.Foldable ( toList )
import Data.Loc
import Prettyprinter
import Error
import GCL.Type ( TypeError(..) )
import GCL.WP.Type ( StructError(..)
, StructWarning(..)
)
import Prelude hiding ( Ordering(..) )
import Pretty.Abstract ( )
import Pretty.Predicate ( )
import Pretty.Util ( )
import Syntax.Parser.Error ( ParseError(..) )
instance Pretty Error where
pretty (ParseError err) = "Parse Error" <+> line <> pretty err
pretty (TypeError err) =
"Type Error" <+> pretty (locOf err) <> line <> pretty err
pretty (StructError err) =
"Struct Error" <+> pretty (locOf err) <> line <> pretty err
pretty (CannotReadFile path) = "CannotReadFile" <+> pretty path
pretty (Others msg ) = "Others" <+> pretty msg
instance Pretty ParseError where
pretty (LexicalError pos ) = "Lexical Error" <+> pretty (displayPos pos)
pretty (SyntacticError pairs _) = "Parse Error" <+> vsep
(map (\(loc, msg) -> pretty (displayLoc loc) <+> pretty msg) $ toList pairs)
the second argument was parsing log , used for debugging
instance Pretty StructWarning where
pretty (MissingBound loc) = "Missing Bound" <+> pretty loc
pretty (ExcessBound loc) = "Excess Bound" <+> pretty loc
instance Pretty StructError where
pretty (MissingAssertion loc) = "Missing Assertion" <+> pretty loc
pretty (MissingPostcondition loc) = "Missing Postcondition" <+> pretty loc
pretty (MultiDimArrayAsgnNotImp loc) =
"Assignment to Multi-Dimensional Array" <+> pretty loc
pretty (LocalVarExceedScope loc) =
"Local Variable(s) Exceeded Scope" <+> pretty loc
instance Pretty TypeError where
pretty (NotInScope name) =
"The definition" <+> pretty name <+> "is not in scope"
pretty (UnifyFailed a b _) =
"Cannot unify:" <+> pretty a <+> "with" <+> pretty b
pretty (RecursiveType v a _) =
"Recursive type variable: " <+> pretty v <+> "in" <+> pretty a
pretty (AssignToConst n) =
"The constant identifier: " <+> pretty n <+> "cannot be assigned"
pretty (UndefinedType n) =
"Undefined Type: " <+> "Type" <+> pretty n <+> "is undefined"
pretty (DuplicatedIdentifiers ns) =
"The identifiers:" <+> pretty ns <+> "are duplicated"
pretty (RedundantNames ns) = "The names: " <+> pretty ns <+> "are redundant"
pretty (RedundantExprs exprs) =
"The exprs: " <+> pretty exprs <+> "are redundant"
pretty (MissingArguments ns) =
"The arguments: " <+> pretty ns <+> "are missing"
|
1b88135b959bc463969a9a5149e2c2cc57ec0746831c1baec511681f76f74275 | sjl/bobbin | tests.lisp | (in-package :bobbin.test)
;;;; Utils --------------------------------------------------------------------
(defmacro define-test (name &body body)
`(test ,(intern (concatenate 'string (symbol-name 'test-) (symbol-name name)))
(let ((*package* ,*package*))
,@body)))
(defun run-tests ()
(1am:run))
(defun f (&rest args)
(apply #'format nil args))
(defmacro check (input width result)
(if (stringp input)
`(is (string= (format nil ,result)
(bobbin:wrap (f ,input) ,width)))
`(is (equal ',result (bobbin:wrap (mapcar #'f ',input) ,width)))))
;;;; Tests --------------------------------------------------------------------
(define-test noop
(check "" 10 "")
(check "foo bar" 10 "foo bar"))
(define-test basic-strings
(check "foo bar baz" 11 "foo bar baz")
(check "foo bar baz" 10 "foo bar~%baz")
(check "foo bar baz" 3 "foo~%bar~%baz")
(check "foo bar baz" 5 "foo~%bar~%baz")
(check "foo bar baz" 6 "foo~%bar~%baz"))
(define-test long-words
(check "abcdefghijklmnopqrstuvwxyz" 5 "abcde~%fghij~%klmno~%pqrst~%uvwxy~%z")
(check "foo abcdefghijklmnopqrstuvwxyz" 5 "foo~%abcde~%fghij~%klmno~%pqrst~%uvwxy~%z"))
(define-test spaces
(check "foo bar baz" 100 "foo bar baz")
(check "foo bar baz" 4 "foo~%bar~%baz")
(check "foo bar baz" 8 "foo bar~%baz")
(check "foo bar baz" 9 "foo bar~%baz")
(check "foo bar baz" 10 "foo bar~%baz")
(check "foo bar baz" 11 "foo bar~%baz"))
(define-test markdown
(check "This is a paragraph of text. It contains some words and some spaces."
20
"This is a paragraph~@
of text. It~@
contains some words~@
and some spaces.")
(check "Here is a list of a couple of things:~@
~@
* foo~@
* bar"
20
"Here is a list of a~@
couple of things:~@
~@
* foo~@
* bar"))
(define-test indentation
(check " foo~% bar" 50 " foo~% bar")
(check " foo bar" 3 "foo~%bar")
(check " foo~% bar" 5 " foo~% bar")
(check (" foo~% bar") 5 (" foo" " bar")))
(define-test lists
(check ("foo bar baz")
3
("foo" "bar" "baz"))
(check ("foo bar baz")
7
("foo bar" "baz"))
(check ("foo" "bar baz")
7
("foo" "bar baz")))
| null | https://raw.githubusercontent.com/sjl/bobbin/b454e8241b24ceab674eeeae464c8082b1b6d8ce/test/tests.lisp | lisp | Utils --------------------------------------------------------------------
Tests -------------------------------------------------------------------- | (in-package :bobbin.test)
(defmacro define-test (name &body body)
`(test ,(intern (concatenate 'string (symbol-name 'test-) (symbol-name name)))
(let ((*package* ,*package*))
,@body)))
(defun run-tests ()
(1am:run))
(defun f (&rest args)
(apply #'format nil args))
(defmacro check (input width result)
(if (stringp input)
`(is (string= (format nil ,result)
(bobbin:wrap (f ,input) ,width)))
`(is (equal ',result (bobbin:wrap (mapcar #'f ',input) ,width)))))
(define-test noop
(check "" 10 "")
(check "foo bar" 10 "foo bar"))
(define-test basic-strings
(check "foo bar baz" 11 "foo bar baz")
(check "foo bar baz" 10 "foo bar~%baz")
(check "foo bar baz" 3 "foo~%bar~%baz")
(check "foo bar baz" 5 "foo~%bar~%baz")
(check "foo bar baz" 6 "foo~%bar~%baz"))
(define-test long-words
(check "abcdefghijklmnopqrstuvwxyz" 5 "abcde~%fghij~%klmno~%pqrst~%uvwxy~%z")
(check "foo abcdefghijklmnopqrstuvwxyz" 5 "foo~%abcde~%fghij~%klmno~%pqrst~%uvwxy~%z"))
(define-test spaces
(check "foo bar baz" 100 "foo bar baz")
(check "foo bar baz" 4 "foo~%bar~%baz")
(check "foo bar baz" 8 "foo bar~%baz")
(check "foo bar baz" 9 "foo bar~%baz")
(check "foo bar baz" 10 "foo bar~%baz")
(check "foo bar baz" 11 "foo bar~%baz"))
(define-test markdown
(check "This is a paragraph of text. It contains some words and some spaces."
20
"This is a paragraph~@
of text. It~@
contains some words~@
and some spaces.")
(check "Here is a list of a couple of things:~@
~@
* foo~@
* bar"
20
"Here is a list of a~@
couple of things:~@
~@
* foo~@
* bar"))
(define-test indentation
(check " foo~% bar" 50 " foo~% bar")
(check " foo bar" 3 "foo~%bar")
(check " foo~% bar" 5 " foo~% bar")
(check (" foo~% bar") 5 (" foo" " bar")))
(define-test lists
(check ("foo bar baz")
3
("foo" "bar" "baz"))
(check ("foo bar baz")
7
("foo bar" "baz"))
(check ("foo" "bar baz")
7
("foo" "bar baz")))
|
2d0c22672c6b01fa179fce842d21043e6a3901d4b76cf10348a786b5658a81ea | facebook/pyre-check | model.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
Model : represents the model of a given callable .
*
* A model contains all the information the global fixpoint needs about a given
* callable , which is :
* - The set of sources returned by the callable ;
* - The set of sinks reached by the parameters of the callable ;
* - Whether a parameter propagates its taint to the return value , which we call
* taint - in - taint - out ( ) .
*
* For instance , for the following callable ` foo ` :
* ` ` `
* def foo(x , y , cond ):
* if cond :
* x = user_controlled ( )
* sql(str(y ) )
* return x
* ` ` `
*
* The model of ` foo ` would be :
* - sources returned : UserControlled
* - sinks : y - > SQL
* - tito : x - > LocalReturn
*
* A model contains all the information the global fixpoint needs about a given
* callable, which is:
* - The set of sources returned by the callable;
* - The set of sinks reached by the parameters of the callable;
* - Whether a parameter propagates its taint to the return value, which we call
* taint-in-taint-out (tito).
*
* For instance, for the following callable `foo`:
* ```
* def foo(x, y, cond):
* if cond:
* x = user_controlled()
* sql(str(y))
* return x
* ```
*
* The model of `foo` would be:
* - sources returned: UserControlled
* - sinks: y -> SQL
* - tito: x -> LocalReturn
*)
open Core
open Pyre
open Analysis
open Interprocedural
open Domains
let json_to_string ~indent json =
let lines = Yojson.Safe.to_string json |> Yojson.Safe.prettify |> String.split ~on:'\n' in
match lines with
| [line] -> line
| lines ->
lines
|> List.map ~f:(fun line -> indent ^ line)
|> String.concat ~sep:"\n"
|> fun content -> "\n" ^ content
module Forward = struct
type t = { source_taint: ForwardState.t }
let pp formatter { source_taint } =
Format.fprintf
formatter
" Sources: %s"
(json_to_string
~indent:" "
(ForwardState.to_json
~expand_overrides:None
~is_valid_callee:(fun ~port:_ ~path:_ ~callee:_ -> true)
~filename_lookup:None
source_taint))
let show = Format.asprintf "%a" pp
let empty = { source_taint = ForwardState.empty }
let is_empty { source_taint } = ForwardState.is_empty source_taint
let obscure = empty
let join { source_taint = left } { source_taint = right } =
{ source_taint = ForwardState.join left right }
let widen ~iteration ~previous:{ source_taint = prev } ~next:{ source_taint = next } =
{ source_taint = ForwardState.widen ~iteration ~prev ~next }
let less_or_equal ~left:{ source_taint = left } ~right:{ source_taint = right } =
ForwardState.less_or_equal ~left ~right
end
module Backward = struct
type t = {
taint_in_taint_out: BackwardState.t;
sink_taint: BackwardState.t;
}
let pp formatter { taint_in_taint_out; sink_taint } =
Format.fprintf
formatter
" Taint-in-taint-out: %s\n Sinks: %s"
(json_to_string
~indent:" "
(BackwardState.to_json
~expand_overrides:None
~is_valid_callee:(fun ~port:_ ~path:_ ~callee:_ -> true)
~filename_lookup:None
taint_in_taint_out))
(json_to_string
~indent:" "
(BackwardState.to_json
~expand_overrides:None
~is_valid_callee:(fun ~port:_ ~path:_ ~callee:_ -> true)
~filename_lookup:None
sink_taint))
let show = Format.asprintf "%a" pp
let empty = { sink_taint = BackwardState.empty; taint_in_taint_out = BackwardState.empty }
let is_empty { sink_taint; taint_in_taint_out } =
BackwardState.is_empty sink_taint && BackwardState.is_empty taint_in_taint_out
let obscure = empty
let join
{ sink_taint = sink_taint_left; taint_in_taint_out = tito_left }
{ sink_taint = sink_taint_right; taint_in_taint_out = tito_right }
=
{
sink_taint = BackwardState.join sink_taint_left sink_taint_right;
taint_in_taint_out = BackwardState.join tito_left tito_right;
}
let widen
~iteration
~previous:{ sink_taint = sink_taint_previous; taint_in_taint_out = tito_previous }
~next:{ sink_taint = sink_taint_next; taint_in_taint_out = tito_next }
=
let sink_taint =
BackwardState.widen ~iteration ~prev:sink_taint_previous ~next:sink_taint_next
in
let taint_in_taint_out = BackwardState.widen ~iteration ~prev:tito_previous ~next:tito_next in
{ sink_taint; taint_in_taint_out }
let less_or_equal
~left:{ sink_taint = sink_taint_left; taint_in_taint_out = tito_left }
~right:{ sink_taint = sink_taint_right; taint_in_taint_out = tito_right }
=
BackwardState.less_or_equal ~left:sink_taint_left ~right:sink_taint_right
&& BackwardState.less_or_equal ~left:tito_left ~right:tito_right
end
module Sanitizers = struct
type t = {
` global ` applies to all parameters and the return value .
* For :
* - sources are only sanitized in the forward trace ;
* - sinks are only sanitized in the backward trace ;
* - titos are sanitized in both traces ( using sanitize taint transforms ) .
* For attribute models , sanitizers are applied on attribute accesses , in both traces .
* For callables:
* - sources are only sanitized in the forward trace;
* - sinks are only sanitized in the backward trace;
* - titos are sanitized in both traces (using sanitize taint transforms).
* For attribute models, sanitizers are applied on attribute accesses, in both traces.
*)
global: Sanitize.t;
Sanitizers applying to all parameters , in both traces .
parameters: Sanitize.t;
(* Map from parameter or return value to sanitizers applying in both traces. *)
roots: Sanitize.RootMap.t;
}
let pp formatter { global; parameters; roots } =
Format.fprintf
formatter
" Global Sanitizer: %s\n Parameters Sanitizer: %s\n Sanitizers: %s"
(json_to_string ~indent:" " (Sanitize.to_json global))
(json_to_string ~indent:" " (Sanitize.to_json parameters))
(json_to_string ~indent:" " (Sanitize.RootMap.to_json roots))
let show = Format.asprintf "%a" pp
let empty =
{ global = Sanitize.empty; parameters = Sanitize.empty; roots = Sanitize.RootMap.bottom }
let is_empty { global; parameters; roots } =
Sanitize.is_empty global && Sanitize.is_empty parameters && Sanitize.RootMap.is_bottom roots
let join
{ global = global_left; parameters = parameters_left; roots = roots_left }
{ global = global_right; parameters = parameters_right; roots = roots_right }
=
{
global = Sanitize.join global_left global_right;
parameters = Sanitize.join parameters_left parameters_right;
roots = Sanitize.RootMap.join roots_left roots_right;
}
let widen ~iteration:_ ~previous ~next = join previous next
let less_or_equal
~left:{ global = global_left; parameters = parameters_left; roots = roots_left }
~right:{ global = global_right; parameters = parameters_right; roots = roots_right }
=
Sanitize.less_or_equal ~left:global_left ~right:global_right
&& Sanitize.less_or_equal ~left:parameters_left ~right:parameters_right
&& Sanitize.RootMap.less_or_equal ~left:roots_left ~right:roots_right
end
module Mode = struct
let name = "modes"
type t =
| Obscure
| SkipAnalysis (* Don't analyze at all *)
| SkipDecoratorWhenInlining
| SkipOverrides
| Entrypoint
[@@deriving compare, equal]
let pp formatter = function
| Obscure -> Format.fprintf formatter "Obscure"
| SkipAnalysis -> Format.fprintf formatter "SkipAnalysis"
| SkipDecoratorWhenInlining -> Format.fprintf formatter "SkipDecoratorWhenInlining"
| SkipOverrides -> Format.fprintf formatter "SkipOverrides"
| Entrypoint -> Format.fprintf formatter "Entrypoint"
let show = Format.asprintf "%a" pp
let to_json mode = `String (show mode)
let from_string = function
| "Obscure" -> Some Obscure
| "SkipAnalysis" -> Some SkipAnalysis
| "SkipDecoratorWhenInlining" -> Some SkipDecoratorWhenInlining
| "SkipOverrides" -> Some SkipOverrides
| "Entrypoint" -> Some Entrypoint
| _ -> None
end
module ModeSet = struct
module T = Abstract.SetDomain.Make (Mode)
include T
let empty = T.bottom
let is_empty = T.is_bottom
let equal left right = T.less_or_equal ~left ~right && T.less_or_equal ~left:right ~right:left
let to_json modes = `List (modes |> T.elements |> List.map ~f:Mode.to_json)
let pp formatter modes =
Format.fprintf formatter " Modes: %s" (json_to_string ~indent:" " (to_json modes))
end
type t = {
forward: Forward.t;
backward: Backward.t;
sanitizers: Sanitizers.t;
modes: ModeSet.t;
}
let pp formatter { forward; backward; sanitizers; modes } =
Format.fprintf
formatter
"%a\n%a\n%a\n%a"
Forward.pp
forward
Backward.pp
backward
Sanitizers.pp
sanitizers
ModeSet.pp
modes
let show = Format.asprintf "%a" pp
let is_empty ~with_modes { forward; backward; sanitizers; modes } =
Forward.is_empty forward
&& Backward.is_empty backward
&& Sanitizers.is_empty sanitizers
&& ModeSet.equal with_modes modes
let empty_model =
{
forward = Forward.empty;
backward = Backward.empty;
sanitizers = Sanitizers.empty;
modes = ModeSet.empty;
}
let empty_skip_model =
{
forward = Forward.empty;
backward = Backward.empty;
sanitizers = Sanitizers.empty;
modes = ModeSet.singleton SkipAnalysis;
}
let obscure_model =
{
forward = Forward.obscure;
backward = Backward.obscure;
sanitizers = Sanitizers.empty;
modes = ModeSet.singleton Obscure;
}
let is_obscure { modes; _ } = ModeSet.contains Obscure modes
let remove_obscureness ({ modes; _ } as model) = { model with modes = ModeSet.remove Obscure modes }
let remove_sinks model =
{ model with backward = { model.backward with sink_taint = BackwardState.empty } }
let add_obscure_sink ~resolution ~call_target model =
let real_target =
match call_target with
| Target.Function _ -> Some call_target
| Target.Method _ -> Some call_target
| Target.Override method_name -> Some (Target.Method method_name)
| Target.Object _ -> None
in
match real_target with
| None -> model
| Some real_target -> (
match
Target.get_module_and_definition
~resolution:(Resolution.global_resolution resolution)
real_target
with
| None ->
let () = Log.warning "Found no definition for %a" Target.pp_pretty real_target in
model
| Some (_, { value = { signature = { parameters; _ }; _ }; _ }) ->
let open Domains in
let sink =
BackwardTaint.singleton CallInfo.declaration (Sinks.NamedSink "Obscure") Frame.initial
|> BackwardState.Tree.create_leaf
in
let parameters = AccessPath.Root.normalize_parameters parameters in
let add_parameter_sink sink_taint (root, _, _) =
BackwardState.assign ~root ~path:[] sink sink_taint
in
let sink_taint =
List.fold_left ~init:model.backward.sink_taint ~f:add_parameter_sink parameters
in
{ model with backward = { model.backward with sink_taint } })
let join left right =
{
forward = Forward.join left.forward right.forward;
backward = Backward.join left.backward right.backward;
sanitizers = Sanitizers.join left.sanitizers right.sanitizers;
modes = ModeSet.join left.modes right.modes;
}
let widen ~iteration ~previous ~next =
{
forward = Forward.widen ~iteration ~previous:previous.forward ~next:next.forward;
backward = Backward.widen ~iteration ~previous:previous.backward ~next:next.backward;
sanitizers = Sanitizers.widen ~iteration ~previous:previous.sanitizers ~next:next.sanitizers;
modes = ModeSet.widen ~iteration ~prev:previous.modes ~next:next.modes;
}
let less_or_equal ~left ~right =
Forward.less_or_equal ~left:left.forward ~right:right.forward
&& Backward.less_or_equal ~left:left.backward ~right:right.backward
&& Sanitizers.less_or_equal ~left:left.sanitizers ~right:right.sanitizers
&& ModeSet.less_or_equal ~left:left.modes ~right:right.modes
let strip_for_callsite
{ forward = { source_taint }; backward = { sink_taint; taint_in_taint_out }; sanitizers; modes }
=
(* Remove positions and other info that are not needed at call site *)
let source_taint =
source_taint
|> ForwardState.transform Features.TitoPositionSet.Self Map ~f:(fun _ ->
Features.TitoPositionSet.bottom)
|> ForwardState.transform ForwardTaint.call_info Map ~f:CallInfo.strip_for_callsite
in
let sink_taint =
sink_taint
|> BackwardState.transform Features.TitoPositionSet.Self Map ~f:(fun _ ->
Features.TitoPositionSet.bottom)
|> BackwardState.transform BackwardTaint.call_info Map ~f:CallInfo.strip_for_callsite
in
let taint_in_taint_out =
taint_in_taint_out
|> BackwardState.transform Features.TitoPositionSet.Self Map ~f:(fun _ ->
Features.TitoPositionSet.bottom)
|> BackwardState.transform BackwardTaint.call_info Map ~f:CallInfo.strip_for_callsite
in
{ forward = { source_taint }; backward = { sink_taint; taint_in_taint_out }; sanitizers; modes }
let apply_sanitizers
~taint_configuration
{
forward = { source_taint };
backward = { taint_in_taint_out; sink_taint };
sanitizers = { global; parameters; roots } as sanitizers;
modes;
}
=
(* Apply the global sanitizer. *)
(* Here, we are applying the legacy behavior of sanitizers, where we only
* sanitize the forward trace or the backward trace. *)
let source_taint =
(* @SanitizeSingleTrace(TaintSource[...]) *)
ForwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~sanitizer:global
source_taint
in
let taint_in_taint_out =
(* @SanitizeSingleTrace(TaintInTaintOut[...]) *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~sanitizer:global
taint_in_taint_out
in
let sink_taint =
(* @SanitizeSingleTrace(TaintSink[...]) *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~sanitizer:global
sink_taint
in
(* Apply the parameters sanitizer. *)
(* Here, we apply sanitizers both in the forward and backward trace. *)
(* Note that by design, sanitizing a specific source or sink also sanitizes
* taint-in-taint-out for that source/sink. *)
let sink_taint =
(* Sanitize(Parameters[TaintSource[...]]) *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~sanitizer:parameters
sink_taint
in
let taint_in_taint_out =
(* Sanitize(Parameters[TaintSource[...]]) *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~sanitizer:parameters
taint_in_taint_out
in
let taint_in_taint_out =
(* Sanitize(Parameters[TaintInTaintOut[...]]) *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~sanitizer:parameters
taint_in_taint_out
in
let sink_taint =
(* Sanitize(Parameters[TaintSink[...]]) *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~sanitizer:parameters
sink_taint
in
let taint_in_taint_out =
(* Sanitize(Parameters[TaintSink[...]]) *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~sanitizer:parameters
taint_in_taint_out
in
(* Apply the return sanitizer. *)
let sanitize_return sanitizer (source_taint, taint_in_taint_out, sink_taint) =
let source_taint =
(* def foo() -> Sanitize[TaintSource[...]] *)
ForwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~sanitizer
source_taint
in
let taint_in_taint_out =
(* def foo() -> Sanitize[TaintSource[...]] *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~sanitizer
taint_in_taint_out
in
let taint_in_taint_out =
(* def foo() -> Sanitize[TaintInTaintOut[...]] *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~sanitizer
taint_in_taint_out
in
let source_taint =
(* def foo() -> Sanitize[TaintSink[...]] *)
ForwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~sanitizer
source_taint
in
let taint_in_taint_out =
(* def foo() -> Sanitize[TaintSink[...]] *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~sanitizer
taint_in_taint_out
in
source_taint, taint_in_taint_out, sink_taint
in
(* Apply the parameter-specific sanitizers. *)
let sanitize_parameter (parameter, sanitizer) (source_taint, taint_in_taint_out, sink_taint) =
let sink_taint =
(* def foo(x: Sanitize[TaintSource[...]]): ... *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~parameter
~sanitizer
sink_taint
in
let taint_in_taint_out =
(* def foo(x: Sanitize[TaintSource[...]]): ... *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~parameter
~sanitizer
taint_in_taint_out
in
let taint_in_taint_out =
(* def foo(x: Sanitize[TaintInTaintOut[...]]): ... *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~parameter
~sanitizer
taint_in_taint_out
in
let sink_taint =
(* def foo(x: Sanitize[TaintSink[...]]): ... *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~parameter
~sanitizer
sink_taint
in
let taint_in_taint_out =
(* def foo(x: Sanitize[TaintSink[...]]): ... *)
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~parameter
~sanitizer
taint_in_taint_out
in
source_taint, taint_in_taint_out, sink_taint
in
let sanitize_root (root, sanitizer) (source_taint, taint_in_taint_out, sink_taint) =
match root with
| AccessPath.Root.LocalResult ->
sanitize_return sanitizer (source_taint, taint_in_taint_out, sink_taint)
| PositionalParameter _
| NamedParameter _
| StarParameter _
| StarStarParameter _ ->
sanitize_parameter (root, sanitizer) (source_taint, taint_in_taint_out, sink_taint)
| Variable _ -> failwith "unexpected"
in
let source_taint, taint_in_taint_out, sink_taint =
Sanitize.RootMap.fold
Sanitize.RootMap.KeyValue
~f:sanitize_root
~init:(source_taint, taint_in_taint_out, sink_taint)
roots
in
{ forward = { source_taint }; backward = { sink_taint; taint_in_taint_out }; sanitizers; modes }
let should_externalize { forward; backward; sanitizers; _ } =
(not (Forward.is_empty forward))
|| (not (Backward.is_empty backward))
|| not (Sanitizers.is_empty sanitizers)
(* For every frame, convert the may breadcrumbs into must breadcrumbs. *)
let may_breadcrumbs_to_must
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
=
let source_taint = ForwardState.may_breadcrumbs_to_must source_taint in
let taint_in_taint_out = BackwardState.may_breadcrumbs_to_must taint_in_taint_out in
let sink_taint = BackwardState.may_breadcrumbs_to_must sink_taint in
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
Within every local taint , join every frame with the frame in the same local taint of the ` Attach `
kind .
kind. *)
let join_every_frame_with_attach
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
=
let source_taint = ForwardState.join_every_frame_with source_taint ~frame_kind:Sources.Attach in
let taint_in_taint_out =
BackwardState.join_every_frame_with taint_in_taint_out ~frame_kind:Sinks.Attach
in
let sink_taint = BackwardState.join_every_frame_with sink_taint ~frame_kind:Sinks.Attach in
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
(* A special case of join, only used for user-provided models. *)
let join_user_models ({ modes = left_modes; _ } as left) ({ modes = right_modes; _ } as right) =
let update_obscure_mode ({ modes; _ } as model) =
If one model has @SkipObscure and the other does not , we expect the joined model to also have
@SkipObscure
@SkipObscure *)
if (not (ModeSet.contains Obscure left_modes)) || not (ModeSet.contains Obscure right_modes)
then
{ model with modes = ModeSet.subtract (ModeSet.singleton Obscure) ~from:modes }
else
model
in
join left right |> update_obscure_mode |> join_every_frame_with_attach |> may_breadcrumbs_to_must
let to_json
~expand_overrides
~is_valid_callee
~filename_lookup
callable
{
forward = { source_taint };
backward = { sink_taint; taint_in_taint_out };
sanitizers =
{ global = global_sanitizer; parameters = parameters_sanitizer; roots = root_sanitizers };
modes;
}
=
let callable_name = Target.external_name callable in
let model_json = ["callable", `String callable_name] in
let model_json =
if not (ForwardState.is_empty source_taint) then
model_json
@ [
( "sources",
ForwardState.to_json ~expand_overrides ~is_valid_callee ~filename_lookup source_taint );
]
else
model_json
in
let model_json =
if not (BackwardState.is_empty sink_taint) then
model_json
@ [
( "sinks",
BackwardState.to_json ~expand_overrides ~is_valid_callee ~filename_lookup sink_taint );
]
else
model_json
in
let model_json =
if not (BackwardState.is_empty taint_in_taint_out) then
model_json
@ [
( "tito",
BackwardState.to_json
~expand_overrides
~is_valid_callee
~filename_lookup
taint_in_taint_out );
]
else
model_json
in
let model_json =
if not (Sanitize.is_empty global_sanitizer) then
model_json @ ["global_sanitizer", Sanitize.to_json global_sanitizer]
else
model_json
in
let model_json =
if not (Sanitize.is_empty parameters_sanitizer) then
model_json @ ["parameters_sanitizer", Sanitize.to_json parameters_sanitizer]
else
model_json
in
let model_json =
if not (Sanitize.RootMap.is_bottom root_sanitizers) then
model_json @ ["sanitizers", Sanitize.RootMap.to_json root_sanitizers]
else
model_json
in
let model_json =
if not (ModeSet.is_empty modes) then
model_json @ ["modes", ModeSet.to_json modes]
else
model_json
in
`Assoc ["kind", `String "model"; "data", `Assoc model_json]
module WithTarget = struct
type nonrec t = {
model: t;
target: Target.t;
}
end
module WithCallTarget = struct
type nonrec t = {
model: t;
call_target: CallGraph.CallTarget.t;
}
end
| null | https://raw.githubusercontent.com/facebook/pyre-check/b79c341c39e65877b36e55f538efa081853d33ed/source/interprocedural_analyses/taint/model.ml | ocaml | Map from parameter or return value to sanitizers applying in both traces.
Don't analyze at all
Remove positions and other info that are not needed at call site
Apply the global sanitizer.
Here, we are applying the legacy behavior of sanitizers, where we only
* sanitize the forward trace or the backward trace.
@SanitizeSingleTrace(TaintSource[...])
@SanitizeSingleTrace(TaintInTaintOut[...])
@SanitizeSingleTrace(TaintSink[...])
Apply the parameters sanitizer.
Here, we apply sanitizers both in the forward and backward trace.
Note that by design, sanitizing a specific source or sink also sanitizes
* taint-in-taint-out for that source/sink.
Sanitize(Parameters[TaintSource[...]])
Sanitize(Parameters[TaintSource[...]])
Sanitize(Parameters[TaintInTaintOut[...]])
Sanitize(Parameters[TaintSink[...]])
Sanitize(Parameters[TaintSink[...]])
Apply the return sanitizer.
def foo() -> Sanitize[TaintSource[...]]
def foo() -> Sanitize[TaintSource[...]]
def foo() -> Sanitize[TaintInTaintOut[...]]
def foo() -> Sanitize[TaintSink[...]]
def foo() -> Sanitize[TaintSink[...]]
Apply the parameter-specific sanitizers.
def foo(x: Sanitize[TaintSource[...]]): ...
def foo(x: Sanitize[TaintSource[...]]): ...
def foo(x: Sanitize[TaintInTaintOut[...]]): ...
def foo(x: Sanitize[TaintSink[...]]): ...
def foo(x: Sanitize[TaintSink[...]]): ...
For every frame, convert the may breadcrumbs into must breadcrumbs.
A special case of join, only used for user-provided models. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
Model : represents the model of a given callable .
*
* A model contains all the information the global fixpoint needs about a given
* callable , which is :
* - The set of sources returned by the callable ;
* - The set of sinks reached by the parameters of the callable ;
* - Whether a parameter propagates its taint to the return value , which we call
* taint - in - taint - out ( ) .
*
* For instance , for the following callable ` foo ` :
* ` ` `
* def foo(x , y , cond ):
* if cond :
* x = user_controlled ( )
* sql(str(y ) )
* return x
* ` ` `
*
* The model of ` foo ` would be :
* - sources returned : UserControlled
* - sinks : y - > SQL
* - tito : x - > LocalReturn
*
* A model contains all the information the global fixpoint needs about a given
* callable, which is:
* - The set of sources returned by the callable;
* - The set of sinks reached by the parameters of the callable;
* - Whether a parameter propagates its taint to the return value, which we call
* taint-in-taint-out (tito).
*
* For instance, for the following callable `foo`:
* ```
* def foo(x, y, cond):
* if cond:
* x = user_controlled()
* sql(str(y))
* return x
* ```
*
* The model of `foo` would be:
* - sources returned: UserControlled
* - sinks: y -> SQL
* - tito: x -> LocalReturn
*)
open Core
open Pyre
open Analysis
open Interprocedural
open Domains
let json_to_string ~indent json =
let lines = Yojson.Safe.to_string json |> Yojson.Safe.prettify |> String.split ~on:'\n' in
match lines with
| [line] -> line
| lines ->
lines
|> List.map ~f:(fun line -> indent ^ line)
|> String.concat ~sep:"\n"
|> fun content -> "\n" ^ content
module Forward = struct
type t = { source_taint: ForwardState.t }
let pp formatter { source_taint } =
Format.fprintf
formatter
" Sources: %s"
(json_to_string
~indent:" "
(ForwardState.to_json
~expand_overrides:None
~is_valid_callee:(fun ~port:_ ~path:_ ~callee:_ -> true)
~filename_lookup:None
source_taint))
let show = Format.asprintf "%a" pp
let empty = { source_taint = ForwardState.empty }
let is_empty { source_taint } = ForwardState.is_empty source_taint
let obscure = empty
let join { source_taint = left } { source_taint = right } =
{ source_taint = ForwardState.join left right }
let widen ~iteration ~previous:{ source_taint = prev } ~next:{ source_taint = next } =
{ source_taint = ForwardState.widen ~iteration ~prev ~next }
let less_or_equal ~left:{ source_taint = left } ~right:{ source_taint = right } =
ForwardState.less_or_equal ~left ~right
end
module Backward = struct
type t = {
taint_in_taint_out: BackwardState.t;
sink_taint: BackwardState.t;
}
let pp formatter { taint_in_taint_out; sink_taint } =
Format.fprintf
formatter
" Taint-in-taint-out: %s\n Sinks: %s"
(json_to_string
~indent:" "
(BackwardState.to_json
~expand_overrides:None
~is_valid_callee:(fun ~port:_ ~path:_ ~callee:_ -> true)
~filename_lookup:None
taint_in_taint_out))
(json_to_string
~indent:" "
(BackwardState.to_json
~expand_overrides:None
~is_valid_callee:(fun ~port:_ ~path:_ ~callee:_ -> true)
~filename_lookup:None
sink_taint))
let show = Format.asprintf "%a" pp
let empty = { sink_taint = BackwardState.empty; taint_in_taint_out = BackwardState.empty }
let is_empty { sink_taint; taint_in_taint_out } =
BackwardState.is_empty sink_taint && BackwardState.is_empty taint_in_taint_out
let obscure = empty
let join
{ sink_taint = sink_taint_left; taint_in_taint_out = tito_left }
{ sink_taint = sink_taint_right; taint_in_taint_out = tito_right }
=
{
sink_taint = BackwardState.join sink_taint_left sink_taint_right;
taint_in_taint_out = BackwardState.join tito_left tito_right;
}
let widen
~iteration
~previous:{ sink_taint = sink_taint_previous; taint_in_taint_out = tito_previous }
~next:{ sink_taint = sink_taint_next; taint_in_taint_out = tito_next }
=
let sink_taint =
BackwardState.widen ~iteration ~prev:sink_taint_previous ~next:sink_taint_next
in
let taint_in_taint_out = BackwardState.widen ~iteration ~prev:tito_previous ~next:tito_next in
{ sink_taint; taint_in_taint_out }
let less_or_equal
~left:{ sink_taint = sink_taint_left; taint_in_taint_out = tito_left }
~right:{ sink_taint = sink_taint_right; taint_in_taint_out = tito_right }
=
BackwardState.less_or_equal ~left:sink_taint_left ~right:sink_taint_right
&& BackwardState.less_or_equal ~left:tito_left ~right:tito_right
end
module Sanitizers = struct
type t = {
` global ` applies to all parameters and the return value .
* For :
* - sources are only sanitized in the forward trace ;
* - sinks are only sanitized in the backward trace ;
* - titos are sanitized in both traces ( using sanitize taint transforms ) .
* For attribute models , sanitizers are applied on attribute accesses , in both traces .
* For callables:
* - sources are only sanitized in the forward trace;
* - sinks are only sanitized in the backward trace;
* - titos are sanitized in both traces (using sanitize taint transforms).
* For attribute models, sanitizers are applied on attribute accesses, in both traces.
*)
global: Sanitize.t;
Sanitizers applying to all parameters , in both traces .
parameters: Sanitize.t;
roots: Sanitize.RootMap.t;
}
let pp formatter { global; parameters; roots } =
Format.fprintf
formatter
" Global Sanitizer: %s\n Parameters Sanitizer: %s\n Sanitizers: %s"
(json_to_string ~indent:" " (Sanitize.to_json global))
(json_to_string ~indent:" " (Sanitize.to_json parameters))
(json_to_string ~indent:" " (Sanitize.RootMap.to_json roots))
let show = Format.asprintf "%a" pp
let empty =
{ global = Sanitize.empty; parameters = Sanitize.empty; roots = Sanitize.RootMap.bottom }
let is_empty { global; parameters; roots } =
Sanitize.is_empty global && Sanitize.is_empty parameters && Sanitize.RootMap.is_bottom roots
let join
{ global = global_left; parameters = parameters_left; roots = roots_left }
{ global = global_right; parameters = parameters_right; roots = roots_right }
=
{
global = Sanitize.join global_left global_right;
parameters = Sanitize.join parameters_left parameters_right;
roots = Sanitize.RootMap.join roots_left roots_right;
}
let widen ~iteration:_ ~previous ~next = join previous next
let less_or_equal
~left:{ global = global_left; parameters = parameters_left; roots = roots_left }
~right:{ global = global_right; parameters = parameters_right; roots = roots_right }
=
Sanitize.less_or_equal ~left:global_left ~right:global_right
&& Sanitize.less_or_equal ~left:parameters_left ~right:parameters_right
&& Sanitize.RootMap.less_or_equal ~left:roots_left ~right:roots_right
end
module Mode = struct
let name = "modes"
type t =
| Obscure
| SkipDecoratorWhenInlining
| SkipOverrides
| Entrypoint
[@@deriving compare, equal]
let pp formatter = function
| Obscure -> Format.fprintf formatter "Obscure"
| SkipAnalysis -> Format.fprintf formatter "SkipAnalysis"
| SkipDecoratorWhenInlining -> Format.fprintf formatter "SkipDecoratorWhenInlining"
| SkipOverrides -> Format.fprintf formatter "SkipOverrides"
| Entrypoint -> Format.fprintf formatter "Entrypoint"
let show = Format.asprintf "%a" pp
let to_json mode = `String (show mode)
let from_string = function
| "Obscure" -> Some Obscure
| "SkipAnalysis" -> Some SkipAnalysis
| "SkipDecoratorWhenInlining" -> Some SkipDecoratorWhenInlining
| "SkipOverrides" -> Some SkipOverrides
| "Entrypoint" -> Some Entrypoint
| _ -> None
end
module ModeSet = struct
module T = Abstract.SetDomain.Make (Mode)
include T
let empty = T.bottom
let is_empty = T.is_bottom
let equal left right = T.less_or_equal ~left ~right && T.less_or_equal ~left:right ~right:left
let to_json modes = `List (modes |> T.elements |> List.map ~f:Mode.to_json)
let pp formatter modes =
Format.fprintf formatter " Modes: %s" (json_to_string ~indent:" " (to_json modes))
end
type t = {
forward: Forward.t;
backward: Backward.t;
sanitizers: Sanitizers.t;
modes: ModeSet.t;
}
let pp formatter { forward; backward; sanitizers; modes } =
Format.fprintf
formatter
"%a\n%a\n%a\n%a"
Forward.pp
forward
Backward.pp
backward
Sanitizers.pp
sanitizers
ModeSet.pp
modes
let show = Format.asprintf "%a" pp
let is_empty ~with_modes { forward; backward; sanitizers; modes } =
Forward.is_empty forward
&& Backward.is_empty backward
&& Sanitizers.is_empty sanitizers
&& ModeSet.equal with_modes modes
let empty_model =
{
forward = Forward.empty;
backward = Backward.empty;
sanitizers = Sanitizers.empty;
modes = ModeSet.empty;
}
let empty_skip_model =
{
forward = Forward.empty;
backward = Backward.empty;
sanitizers = Sanitizers.empty;
modes = ModeSet.singleton SkipAnalysis;
}
let obscure_model =
{
forward = Forward.obscure;
backward = Backward.obscure;
sanitizers = Sanitizers.empty;
modes = ModeSet.singleton Obscure;
}
let is_obscure { modes; _ } = ModeSet.contains Obscure modes
let remove_obscureness ({ modes; _ } as model) = { model with modes = ModeSet.remove Obscure modes }
let remove_sinks model =
{ model with backward = { model.backward with sink_taint = BackwardState.empty } }
let add_obscure_sink ~resolution ~call_target model =
let real_target =
match call_target with
| Target.Function _ -> Some call_target
| Target.Method _ -> Some call_target
| Target.Override method_name -> Some (Target.Method method_name)
| Target.Object _ -> None
in
match real_target with
| None -> model
| Some real_target -> (
match
Target.get_module_and_definition
~resolution:(Resolution.global_resolution resolution)
real_target
with
| None ->
let () = Log.warning "Found no definition for %a" Target.pp_pretty real_target in
model
| Some (_, { value = { signature = { parameters; _ }; _ }; _ }) ->
let open Domains in
let sink =
BackwardTaint.singleton CallInfo.declaration (Sinks.NamedSink "Obscure") Frame.initial
|> BackwardState.Tree.create_leaf
in
let parameters = AccessPath.Root.normalize_parameters parameters in
let add_parameter_sink sink_taint (root, _, _) =
BackwardState.assign ~root ~path:[] sink sink_taint
in
let sink_taint =
List.fold_left ~init:model.backward.sink_taint ~f:add_parameter_sink parameters
in
{ model with backward = { model.backward with sink_taint } })
let join left right =
{
forward = Forward.join left.forward right.forward;
backward = Backward.join left.backward right.backward;
sanitizers = Sanitizers.join left.sanitizers right.sanitizers;
modes = ModeSet.join left.modes right.modes;
}
let widen ~iteration ~previous ~next =
{
forward = Forward.widen ~iteration ~previous:previous.forward ~next:next.forward;
backward = Backward.widen ~iteration ~previous:previous.backward ~next:next.backward;
sanitizers = Sanitizers.widen ~iteration ~previous:previous.sanitizers ~next:next.sanitizers;
modes = ModeSet.widen ~iteration ~prev:previous.modes ~next:next.modes;
}
let less_or_equal ~left ~right =
Forward.less_or_equal ~left:left.forward ~right:right.forward
&& Backward.less_or_equal ~left:left.backward ~right:right.backward
&& Sanitizers.less_or_equal ~left:left.sanitizers ~right:right.sanitizers
&& ModeSet.less_or_equal ~left:left.modes ~right:right.modes
let strip_for_callsite
{ forward = { source_taint }; backward = { sink_taint; taint_in_taint_out }; sanitizers; modes }
=
let source_taint =
source_taint
|> ForwardState.transform Features.TitoPositionSet.Self Map ~f:(fun _ ->
Features.TitoPositionSet.bottom)
|> ForwardState.transform ForwardTaint.call_info Map ~f:CallInfo.strip_for_callsite
in
let sink_taint =
sink_taint
|> BackwardState.transform Features.TitoPositionSet.Self Map ~f:(fun _ ->
Features.TitoPositionSet.bottom)
|> BackwardState.transform BackwardTaint.call_info Map ~f:CallInfo.strip_for_callsite
in
let taint_in_taint_out =
taint_in_taint_out
|> BackwardState.transform Features.TitoPositionSet.Self Map ~f:(fun _ ->
Features.TitoPositionSet.bottom)
|> BackwardState.transform BackwardTaint.call_info Map ~f:CallInfo.strip_for_callsite
in
{ forward = { source_taint }; backward = { sink_taint; taint_in_taint_out }; sanitizers; modes }
let apply_sanitizers
~taint_configuration
{
forward = { source_taint };
backward = { taint_in_taint_out; sink_taint };
sanitizers = { global; parameters; roots } as sanitizers;
modes;
}
=
let source_taint =
ForwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~sanitizer:global
source_taint
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~sanitizer:global
taint_in_taint_out
in
let sink_taint =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~sanitizer:global
sink_taint
in
let sink_taint =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~sanitizer:parameters
sink_taint
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~sanitizer:parameters
taint_in_taint_out
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~sanitizer:parameters
taint_in_taint_out
in
let sink_taint =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~sanitizer:parameters
sink_taint
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~sanitizer:parameters
taint_in_taint_out
in
let sanitize_return sanitizer (source_taint, taint_in_taint_out, sink_taint) =
let source_taint =
ForwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~sanitizer
source_taint
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~sanitizer
taint_in_taint_out
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~sanitizer
taint_in_taint_out
in
let source_taint =
ForwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~sanitizer
source_taint
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~sanitizer
taint_in_taint_out
in
source_taint, taint_in_taint_out, sink_taint
in
let sanitize_parameter (parameter, sanitizer) (source_taint, taint_in_taint_out, sink_taint) =
let sink_taint =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~parameter
~sanitizer
sink_taint
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_source:true
~ignore_if_sanitize_all:true
~parameter
~sanitizer
taint_in_taint_out
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_tito:true
~insert_location:TaintTransformOperation.InsertLocation.Back
~parameter
~sanitizer
taint_in_taint_out
in
let sink_taint =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~parameter
~sanitizer
sink_taint
in
let taint_in_taint_out =
BackwardState.apply_sanitizers
~taint_configuration
~sanitize_sink:true
~ignore_if_sanitize_all:true
~parameter
~sanitizer
taint_in_taint_out
in
source_taint, taint_in_taint_out, sink_taint
in
let sanitize_root (root, sanitizer) (source_taint, taint_in_taint_out, sink_taint) =
match root with
| AccessPath.Root.LocalResult ->
sanitize_return sanitizer (source_taint, taint_in_taint_out, sink_taint)
| PositionalParameter _
| NamedParameter _
| StarParameter _
| StarStarParameter _ ->
sanitize_parameter (root, sanitizer) (source_taint, taint_in_taint_out, sink_taint)
| Variable _ -> failwith "unexpected"
in
let source_taint, taint_in_taint_out, sink_taint =
Sanitize.RootMap.fold
Sanitize.RootMap.KeyValue
~f:sanitize_root
~init:(source_taint, taint_in_taint_out, sink_taint)
roots
in
{ forward = { source_taint }; backward = { sink_taint; taint_in_taint_out }; sanitizers; modes }
let should_externalize { forward; backward; sanitizers; _ } =
(not (Forward.is_empty forward))
|| (not (Backward.is_empty backward))
|| not (Sanitizers.is_empty sanitizers)
let may_breadcrumbs_to_must
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
=
let source_taint = ForwardState.may_breadcrumbs_to_must source_taint in
let taint_in_taint_out = BackwardState.may_breadcrumbs_to_must taint_in_taint_out in
let sink_taint = BackwardState.may_breadcrumbs_to_must sink_taint in
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
Within every local taint , join every frame with the frame in the same local taint of the ` Attach `
kind .
kind. *)
let join_every_frame_with_attach
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
=
let source_taint = ForwardState.join_every_frame_with source_taint ~frame_kind:Sources.Attach in
let taint_in_taint_out =
BackwardState.join_every_frame_with taint_in_taint_out ~frame_kind:Sinks.Attach
in
let sink_taint = BackwardState.join_every_frame_with sink_taint ~frame_kind:Sinks.Attach in
{ forward = { source_taint }; backward = { taint_in_taint_out; sink_taint }; sanitizers; modes }
let join_user_models ({ modes = left_modes; _ } as left) ({ modes = right_modes; _ } as right) =
let update_obscure_mode ({ modes; _ } as model) =
If one model has @SkipObscure and the other does not , we expect the joined model to also have
@SkipObscure
@SkipObscure *)
if (not (ModeSet.contains Obscure left_modes)) || not (ModeSet.contains Obscure right_modes)
then
{ model with modes = ModeSet.subtract (ModeSet.singleton Obscure) ~from:modes }
else
model
in
join left right |> update_obscure_mode |> join_every_frame_with_attach |> may_breadcrumbs_to_must
let to_json
~expand_overrides
~is_valid_callee
~filename_lookup
callable
{
forward = { source_taint };
backward = { sink_taint; taint_in_taint_out };
sanitizers =
{ global = global_sanitizer; parameters = parameters_sanitizer; roots = root_sanitizers };
modes;
}
=
let callable_name = Target.external_name callable in
let model_json = ["callable", `String callable_name] in
let model_json =
if not (ForwardState.is_empty source_taint) then
model_json
@ [
( "sources",
ForwardState.to_json ~expand_overrides ~is_valid_callee ~filename_lookup source_taint );
]
else
model_json
in
let model_json =
if not (BackwardState.is_empty sink_taint) then
model_json
@ [
( "sinks",
BackwardState.to_json ~expand_overrides ~is_valid_callee ~filename_lookup sink_taint );
]
else
model_json
in
let model_json =
if not (BackwardState.is_empty taint_in_taint_out) then
model_json
@ [
( "tito",
BackwardState.to_json
~expand_overrides
~is_valid_callee
~filename_lookup
taint_in_taint_out );
]
else
model_json
in
let model_json =
if not (Sanitize.is_empty global_sanitizer) then
model_json @ ["global_sanitizer", Sanitize.to_json global_sanitizer]
else
model_json
in
let model_json =
if not (Sanitize.is_empty parameters_sanitizer) then
model_json @ ["parameters_sanitizer", Sanitize.to_json parameters_sanitizer]
else
model_json
in
let model_json =
if not (Sanitize.RootMap.is_bottom root_sanitizers) then
model_json @ ["sanitizers", Sanitize.RootMap.to_json root_sanitizers]
else
model_json
in
let model_json =
if not (ModeSet.is_empty modes) then
model_json @ ["modes", ModeSet.to_json modes]
else
model_json
in
`Assoc ["kind", `String "model"; "data", `Assoc model_json]
module WithTarget = struct
type nonrec t = {
model: t;
target: Target.t;
}
end
module WithCallTarget = struct
type nonrec t = {
model: t;
call_target: CallGraph.CallTarget.t;
}
end
|
4a6157f28e1eaef79c8e90a1553bfcac70934b99b5d911a8da371581805ad230 | owickstrom/gi-gtk-declarative | Collected.hs | # LANGUAGE DataKinds #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
-- | Internal helpers for applying attributes and signal handlers to GTK+
-- widgets.
module GI.Gtk.Declarative.Attributes.Collected
( CollectedProperties
, Collected(..)
, canBeModifiedTo
, collectAttributes
, constructProperties
, updateProperties
, updateClasses
)
where
import Data.Foldable
import qualified Data.GI.Base.Attributes as GI
import qualified Data.HashMap.Strict as HashMap
import Data.HashMap.Strict ( HashMap )
import qualified Data.HashSet as HashSet
import qualified Data.Set as Set
import qualified Data.Text as Text
import Data.Text ( Text )
import Data.Typeable
import Data.Vector ( Vector )
import GHC.TypeLits
import qualified GI.Gtk as Gtk
import GI.Gtk.Declarative.Attributes
-- | A collected property key/value pair, to be used when
-- settings properties when patching widgets.
data CollectedProperty widget where
CollectedProperty ::( GI.AttrOpAllowed 'GI.AttrConstruct info widget,
GI.AttrOpAllowed 'GI.AttrSet info widget,
GI.AttrGetC info widget attr getValue,
GI.AttrSetTypeConstraint info setValue,
KnownSymbol attr,
Typeable attr,
Eq setValue,
Typeable setValue
) =>
GI.AttrLabelProxy attr ->
setValue ->
CollectedProperty widget
-- | A collected map of key/value pairs, where the type-level property
-- names are represented as 'Text' values. This is used to calculate
-- differences in old and new property sets when patching.
type CollectedProperties widget = HashMap Text (CollectedProperty widget)
-- | Checks if the 'old' collected properties are a subset of the 'new' ones,
-- and thus if a widget thus be updated or if it has to be recreated.
canBeModifiedTo
:: CollectedProperties widget -> CollectedProperties widget -> Bool
old `canBeModifiedTo` new = Set.fromList (HashMap.keys old)
`Set.isSubsetOf` Set.fromList (HashMap.keys new)
-- | All the collected properties and classes for a widget. These are based
-- on the 'Attribute' list in the declarative markup, but collected separately
-- into more efficient data structures, optimized for patching.
data Collected widget event
= Collected
{ collectedClasses :: ClassSet,
collectedProperties :: CollectedProperties widget
}
instance Semigroup (Collected widget event) where
c1 <> c2 = Collected (collectedClasses c1 <> collectedClasses c2)
(collectedProperties c1 <> collectedProperties c2)
instance Monoid (Collected widget event) where
mempty = Collected mempty mempty
-- | Collect declarative markup attributes to the patching-optimized
-- 'Collected' data structure.
collectAttributes :: Vector (Attribute widget event) -> Collected widget event
collectAttributes = foldl' go mempty
where
go
:: Collected widget event
-> Attribute widget event
-> Collected widget event
go Collected {..} = \case
attr := value -> Collected
{ collectedProperties = HashMap.insert (Text.pack (symbolVal attr))
(CollectedProperty attr value)
collectedProperties
, ..
}
Classes classSet ->
Collected { collectedClasses = collectedClasses <> classSet, .. }
_ -> Collected { .. }
| Create a list of GTK construct operations based on collected
-- properties, used when creating new widgets.
constructProperties
:: Collected widget event -> [GI.AttrOp widget 'GI.AttrConstruct]
constructProperties c = map
(\(CollectedProperty attr value) -> attr Gtk.:= value)
(HashMap.elems (collectedProperties c))
-- | Update the changed properties of a widget, based on the old and new
-- collected properties.
updateProperties
:: widget -> CollectedProperties widget -> CollectedProperties widget -> IO ()
updateProperties (widget' :: widget) oldProps newProps = do
let toAdd = HashMap.elems (HashMap.difference newProps oldProps)
setOps = mconcat
(HashMap.elems (HashMap.intersectionWith toMaybeSetOp oldProps newProps)
)
GI.set widget' (map (toSetOp (Proxy @widget)) toAdd <> setOps)
where
toSetOp
:: Proxy widget
-> CollectedProperty widget
-> Gtk.AttrOp widget 'GI.AttrSet
toSetOp _ (CollectedProperty attr value) = attr Gtk.:= value
toMaybeSetOp
:: CollectedProperty widget
-> CollectedProperty widget
-> [Gtk.AttrOp widget 'GI.AttrSet]
toMaybeSetOp (CollectedProperty attr (v1 :: t1)) (CollectedProperty _ (v2 :: t2))
= case eqT @t1 @t2 of
Just Refl | v1 /= v2 -> pure (attr Gtk.:= v2)
_ -> mempty
-- | Update the style context's classes to only include the new set of
-- classes (last argument).
updateClasses :: Gtk.StyleContext -> ClassSet -> ClassSet -> IO ()
updateClasses ctx old new = do
let toAdd = HashSet.difference new old
toRemove = HashSet.difference old new
mapM_ (Gtk.styleContextAddClass ctx) toAdd
mapM_ (Gtk.styleContextRemoveClass ctx) toRemove
| null | https://raw.githubusercontent.com/owickstrom/gi-gtk-declarative/205351a54698be7b583dd34d189a89470ee2b11b/gi-gtk-declarative/src/GI/Gtk/Declarative/Attributes/Collected.hs | haskell | # LANGUAGE GADTs #
| Internal helpers for applying attributes and signal handlers to GTK+
widgets.
| A collected property key/value pair, to be used when
settings properties when patching widgets.
| A collected map of key/value pairs, where the type-level property
names are represented as 'Text' values. This is used to calculate
differences in old and new property sets when patching.
| Checks if the 'old' collected properties are a subset of the 'new' ones,
and thus if a widget thus be updated or if it has to be recreated.
| All the collected properties and classes for a widget. These are based
on the 'Attribute' list in the declarative markup, but collected separately
into more efficient data structures, optimized for patching.
| Collect declarative markup attributes to the patching-optimized
'Collected' data structure.
properties, used when creating new widgets.
| Update the changed properties of a widget, based on the old and new
collected properties.
| Update the style context's classes to only include the new set of
classes (last argument). | # LANGUAGE DataKinds #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
module GI.Gtk.Declarative.Attributes.Collected
( CollectedProperties
, Collected(..)
, canBeModifiedTo
, collectAttributes
, constructProperties
, updateProperties
, updateClasses
)
where
import Data.Foldable
import qualified Data.GI.Base.Attributes as GI
import qualified Data.HashMap.Strict as HashMap
import Data.HashMap.Strict ( HashMap )
import qualified Data.HashSet as HashSet
import qualified Data.Set as Set
import qualified Data.Text as Text
import Data.Text ( Text )
import Data.Typeable
import Data.Vector ( Vector )
import GHC.TypeLits
import qualified GI.Gtk as Gtk
import GI.Gtk.Declarative.Attributes
data CollectedProperty widget where
CollectedProperty ::( GI.AttrOpAllowed 'GI.AttrConstruct info widget,
GI.AttrOpAllowed 'GI.AttrSet info widget,
GI.AttrGetC info widget attr getValue,
GI.AttrSetTypeConstraint info setValue,
KnownSymbol attr,
Typeable attr,
Eq setValue,
Typeable setValue
) =>
GI.AttrLabelProxy attr ->
setValue ->
CollectedProperty widget
type CollectedProperties widget = HashMap Text (CollectedProperty widget)
canBeModifiedTo
:: CollectedProperties widget -> CollectedProperties widget -> Bool
old `canBeModifiedTo` new = Set.fromList (HashMap.keys old)
`Set.isSubsetOf` Set.fromList (HashMap.keys new)
data Collected widget event
= Collected
{ collectedClasses :: ClassSet,
collectedProperties :: CollectedProperties widget
}
instance Semigroup (Collected widget event) where
c1 <> c2 = Collected (collectedClasses c1 <> collectedClasses c2)
(collectedProperties c1 <> collectedProperties c2)
instance Monoid (Collected widget event) where
mempty = Collected mempty mempty
collectAttributes :: Vector (Attribute widget event) -> Collected widget event
collectAttributes = foldl' go mempty
where
go
:: Collected widget event
-> Attribute widget event
-> Collected widget event
go Collected {..} = \case
attr := value -> Collected
{ collectedProperties = HashMap.insert (Text.pack (symbolVal attr))
(CollectedProperty attr value)
collectedProperties
, ..
}
Classes classSet ->
Collected { collectedClasses = collectedClasses <> classSet, .. }
_ -> Collected { .. }
| Create a list of GTK construct operations based on collected
constructProperties
:: Collected widget event -> [GI.AttrOp widget 'GI.AttrConstruct]
constructProperties c = map
(\(CollectedProperty attr value) -> attr Gtk.:= value)
(HashMap.elems (collectedProperties c))
updateProperties
:: widget -> CollectedProperties widget -> CollectedProperties widget -> IO ()
updateProperties (widget' :: widget) oldProps newProps = do
let toAdd = HashMap.elems (HashMap.difference newProps oldProps)
setOps = mconcat
(HashMap.elems (HashMap.intersectionWith toMaybeSetOp oldProps newProps)
)
GI.set widget' (map (toSetOp (Proxy @widget)) toAdd <> setOps)
where
toSetOp
:: Proxy widget
-> CollectedProperty widget
-> Gtk.AttrOp widget 'GI.AttrSet
toSetOp _ (CollectedProperty attr value) = attr Gtk.:= value
toMaybeSetOp
:: CollectedProperty widget
-> CollectedProperty widget
-> [Gtk.AttrOp widget 'GI.AttrSet]
toMaybeSetOp (CollectedProperty attr (v1 :: t1)) (CollectedProperty _ (v2 :: t2))
= case eqT @t1 @t2 of
Just Refl | v1 /= v2 -> pure (attr Gtk.:= v2)
_ -> mempty
updateClasses :: Gtk.StyleContext -> ClassSet -> ClassSet -> IO ()
updateClasses ctx old new = do
let toAdd = HashSet.difference new old
toRemove = HashSet.difference old new
mapM_ (Gtk.styleContextAddClass ctx) toAdd
mapM_ (Gtk.styleContextRemoveClass ctx) toRemove
|
35f95212f701b64890235f1c4f406f6e798cfd31b745f6d8b98de801454b7987 | typeclasses/haskell-phrasebook | push-to-cache.hs | #! /usr/bin/env nix-shell
#! nix-shell --pure ../shell.nix
#! nix-shell --keep NIX_PATH
#! nix-shell -i runhaskell
-- We use this script to upload the Nix shell environment to Cachix.
import Control.Monad
import Data.Foldable
import System.Process
main = build >>= push
build = fmap (head . lines) $ readProcess "nix-build" ["shell.nix", "--attr", "buildInputs", "--no-out-link"] ""
push path = callProcess "cachix" ["push", "typeclasses", path]
| null | https://raw.githubusercontent.com/typeclasses/haskell-phrasebook/2b0aa44ef6f6e9745c51ed47b4e59ff704346c87/tools/push-to-cache.hs | haskell | pure ../shell.nix
keep NIX_PATH
We use this script to upload the Nix shell environment to Cachix. | #! /usr/bin/env nix-shell
#! nix-shell -i runhaskell
import Control.Monad
import Data.Foldable
import System.Process
main = build >>= push
build = fmap (head . lines) $ readProcess "nix-build" ["shell.nix", "--attr", "buildInputs", "--no-out-link"] ""
push path = callProcess "cachix" ["push", "typeclasses", path]
|
25283b5e465e2be59c2b2747f428905c9204156da86cb14274070f991c25b7a2 | jaked/orpc | gen_aux.ml |
* This file is part of orpc , OCaml signature to ONC RPC generator
* Copyright ( C ) 2008 - 9 Skydeck , Inc
* Copyright ( C ) 2010
*
* 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. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA
* This file is part of orpc, OCaml signature to ONC RPC generator
* Copyright (C) 2008-9 Skydeck, Inc
* Copyright (C) 2010 Jacob Donham
*
* 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., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA
*)
open Camlp4.PreCast
open Ast
open Types
open Util
let _loc = Camlp4.PreCast.Loc.ghost
module G = Gen_common
let s_arg id = id ^ "'arg"
let s_res id = id ^ "'res"
let xdr_p id = "xdr'" ^ id
let long_xdr id = "orpc_aux_xdr_" ^ id
let long_to_ id = "orpc_aux_to_" ^ id
let long_of_ id = "orpc_aux_of_" ^ id
let xdr id = "xdr_" ^ id
let to_ id = "to_" ^ id
let of_ id = "of_" ^ id
let gen_sig_typedef ?(qual_id=G.id) ds =
<:sig_item< $list:
List.map
(fun { td_vars = vars; td_id = id } ->
let appd =
G.tapps <:ctyp< $id:qual_id id$ >> (G.tvars vars) in
<:sig_item<
val $lid:long_to_ id$ :
$G.arrows
(List.map (fun v -> <:ctyp< Xdr.xdr_value -> '$lid:v$ >>) vars)
<:ctyp< Xdr.xdr_value -> $appd$ >>$
val $lid:long_of_ id$ :
$G.arrows
(List.map (fun v -> <:ctyp< '$lid:v$ -> Xdr.xdr_value >>) vars)
(TyArr (_loc, appd, <:ctyp< Xdr.xdr_value >>))
< : < $ appd$ - > Xdr.xdr_value > > broken in 3.12
val $lid:long_xdr id$ :
$G.arrows
(List.map (fun v -> <:ctyp< Xdr.xdr_type_term >>) vars)
<:ctyp< Xdr.xdr_type_term >>$
>>)
ds$
>>
let gen_mli name (typedefs, excs, funcs, kinds) =
let has_excs = excs <> [] in
let qual_id = G.qual_id name in
let gen_func (_, id, args, res) =
let arg =
match List.map typ_of_argtyp_option args with
| [] -> assert false
| [a] -> a
| args -> Tuple (g, args) in
let orpc_res =
if has_excs
then Apply (_loc, ["Orpc"], "orpc_result", [res; Apply (_loc, [], "exn", [])])
else res in
let items aid arg =
let t = G.gen_type qual_id arg in
<:sig_item<
val $lid:to_ aid$ : Xdr.xdr_value -> $t$
val $lid:of_ aid$ : $t$ -> Xdr.xdr_value
val $lid:xdr aid$ : Xdr.xdr_type_term
>> in
<:sig_item<
$items (s_arg id) arg$
$items (s_res id) orpc_res$
>> in
<:sig_item<
$list:List.map (gen_sig_typedef ~qual_id) typedefs$ ;;
$if has_excs
then
<:sig_item<
val $lid:long_to_ "exn"$ : Xdr.xdr_value -> exn
val $lid:long_of_ "exn"$ : exn -> Xdr.xdr_value
val $lid:long_xdr "exn"$ : Xdr.xdr_type_term ;;
>>
else <:sig_item< >>$ ;;
$list:List.map gen_func funcs$ ;;
val program : Rpc_program.t
>>
let rec gen_to qual_id t x =
let gen_to = gen_to qual_id in
match t with
| Abstract _ -> assert false
| Var (_loc, id) -> <:expr< $lid:G.to_p id$ $x$ >>
| Unit _loc -> <:expr< () >>
| Int _loc -> <:expr< Rtypes.int_of_int4 (Xdr.dest_xv_int $x$) >>
| Int32 _loc -> <:expr< Rtypes.int32_of_int4 (Xdr.dest_xv_int $x$) >>
| Int64 _loc -> <:expr< Rtypes.int64_of_int8 (Xdr.dest_xv_hyper $x$) >>
| Float _loc -> <:expr< Rtypes.float_of_fp8 (Xdr.dest_xv_double $x$) >>
| Bool _loc -> <:expr< Xdr.dest_xv_enum_fast $x$ = 1 >>
| Char _loc -> <:expr< char_of_int (Xdr.dest_xv_enum_fast $x$) >>
| String _loc -> <:expr< Xdr.dest_xv_string $x$>>
| Tuple (_loc, parts) ->
let (pps, pes) = G.vars parts in
<:expr<
match Xdr.dest_xv_struct_fast $x$ with
| [| $list:pps$ |] -> ( $tup:exCom_of_list (List.map2 gen_to parts pes)$ )
| _ -> assert false
>>
| Record (_loc, fields) ->
let (fps, fes) = G.vars fields in
let rb f e = <:rec_binding< $id:qual_id f.f_id$ = $gen_to f.f_typ e$ >> in
<:expr<
match Xdr.dest_xv_struct_fast $x$ with
| [| $list:fps$ |] ->
$ExRec(_loc, rbSem_of_list (List.map2 rb fields fes), <:expr< >>)$
| _ -> assert false
>>
| Variant (_loc, arms) ->
let mc (id, ts) i =
match ts with
| [] -> <:match_case< ($`int:i$, _) -> $id:qual_id id$ >>
| [t] -> <:match_case< ($`int:i$, x) -> $id:qual_id id$ $gen_to t <:expr< x >>$ >>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
($`int:i$, x) ->
match Xdr.dest_xv_struct_fast x with
| [| $list:pps$ |] ->
$G.apps
<:expr< $id:qual_id id$ >>
(List.map2 gen_to ts pes)$
| _ -> assert false
>> in
<:expr<
match Xdr.dest_xv_union_over_enum_fast $x$ with
$list:List.mapi mc arms$
| _ -> assert false
>>
| PolyVar (_loc, _, arms) ->
let arms = List.map (function Pv_pv _ -> assert false | Pv_of (id, ts) -> (id, ts)) arms in
let mc (id, ts) i =
match ts with
| [] -> <:match_case< ($`int:i$, _) -> `$id$ >>
| [t] -> <:match_case< ($`int:i$, x) -> `$id$ $gen_to t <:expr< x >>$ >>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
($`int:i$, x) ->
match Xdr.dest_xv_struct_fast x with
| [| $list:pps$ |] ->
$G.apps
<:expr< `$id$ >>
(List.map2 gen_to ts pes)$
| _ -> assert false
>> in
<:expr<
match Xdr.dest_xv_union_over_enum_fast $x$ with
$list:List.mapi mc arms$
| _ -> assert false
>>
| Array (_loc, String _) -> <:expr< Xdr.dest_xv_array_of_string_fast $x$ >>
| Array (_loc, t) ->
<:expr< Array.map (fun x -> $gen_to t <:expr< x >>$) (Xdr.dest_xv_array $x$) >>
| List (_loc, String _) -> <:expr< Array.to_list (Xdr.dest_xv_array_of_string_fast $x$) >>
| List (_loc, t) ->
<:expr< Orpc_onc.to_list (fun x -> $gen_to t <:expr< x >>$) $x$ >>
| Option (_loc, t) ->
<:expr< Orpc_onc.to_option (fun x -> $gen_to t <:expr< x >>$) $x$ >>
| Ref (_loc, t) -> <:expr< ref $gen_to t x$ >>
| Apply (_loc, mdl, id, args) ->
<:expr<
$G.apps
(<:expr< $id:G.module_id mdl (long_to_ id)$ >>)
(List.map (fun a -> <:expr< fun x -> $gen_to a <:expr< x >>$ >>) args)$
$x$
>>
| Arrow _ -> assert false
let rec gen_of qual_id t v =
let gen_of = gen_of qual_id in
match t with
| Abstract _ -> assert false
| Var (_loc, id) -> <:expr< $lid:G.of_p id$ $v$ >>
| Unit _loc -> <:expr< Xdr.XV_void >>
| Int _loc -> <:expr< Xdr.XV_int (Rtypes.int4_of_int $v$) >>
| Int32 _loc -> <:expr< Xdr.XV_int (Rtypes.int4_of_int32 $v$) >>
| Int64 _loc -> <:expr< Xdr.XV_hyper (Rtypes.int8_of_int64 $v$) >>
| Float _loc -> <:expr< Xdr.XV_double (Rtypes.fp8_of_float $v$) >>
| Bool _loc -> <:expr< Xdr.XV_enum_fast (if $v$ then 1 else 0) >>
| Char _loc -> <:expr< Xdr.XV_enum_fast (int_of_char $v$) >>
| String _loc -> <:expr< Xdr.XV_string $v$ >>
| Tuple (_loc, parts) ->
let (pps, pes) = G.vars parts in
<:expr<
let ( $tup:paCom_of_list pps$ ) = $v$ in
Xdr.XV_struct_fast [| $exSem_of_list (List.map2 gen_of parts pes)$ |] (* XXX not sure why list: doesn't work here *)
>>
| Record (_loc, fields) ->
let (fps, fes) = G.vars fields in
let rb f p = <:patt< $id:qual_id f.f_id$ = $p$ >> in
<:expr<
let { $paSem_of_list (List.map2 rb fields fps)$ } = $v$ in
Xdr.XV_struct_fast
[| $exSem_of_list (List.map2 (fun f v -> gen_of f.f_typ v) fields fes)$ |]
>>
| Variant (_loc, arms) ->
let mc (id, ts) i =
match ts with
| [] ->
<:match_case<
$id:qual_id id$ ->
Xdr.XV_union_over_enum_fast ($`int:i$, Xdr.XV_void)
>>
| [t] ->
<:match_case<
$id:qual_id id$ x ->
Xdr.XV_union_over_enum_fast ($`int:i$, $gen_of t <:expr< x >>$)
>>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
$G.papps <:patt< $id:qual_id id$ >> pps$ ->
Xdr.XV_union_over_enum_fast
($`int:i$,
Xdr.XV_struct_fast [| $exSem_of_list (List.map2 gen_of ts pes)$ |])
>> in
<:expr< match $v$ with $list:List.mapi mc arms$ >>
| PolyVar (_loc, _, arms) ->
let arms = List.map (function Pv_pv _ -> assert false | Pv_of (id, ts) -> (id, ts)) arms in
let mc (id, ts) i =
match ts with
| [] ->
<:match_case<
`$id$ ->
Xdr.XV_union_over_enum_fast ($`int:i$, Xdr.XV_void)
>>
| [t] ->
<:match_case<
`$id$ x ->
Xdr.XV_union_over_enum_fast ($`int:i$, $gen_of t <:expr< x >>$)
>>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
$G.papps <:patt< `$id$ >> pps$ ->
Xdr.XV_union_over_enum_fast
($`int:i$,
Xdr.XV_struct_fast [| $exSem_of_list (List.map2 gen_of ts pes)$ |])
>> in
<:expr< match $v$ with $list:List.mapi mc arms$ >>
| Array (_loc, String _) -> <:expr< Xdr.XV_array_of_string_fast $v$ >>
| Array (_loc, t) ->
<:expr< Xdr.XV_array (Array.map (fun v -> $gen_of t <:expr< v >>$) $v$) >>
| List (_loc, String _) -> <:expr< Xdr.XV_array_of_string_fast (Array.of_list $v$) >>
| List (_loc, t) ->
<:expr< Orpc_onc.of_list (fun v -> $gen_of t <:expr< v >>$) $v$ >>
| Option (_loc, t) ->
<:expr< Orpc_onc.of_option (fun v -> $gen_of t <:expr< v >>$) $v$ >>
| Ref (_loc, t) -> gen_of t <:expr< ! $v$ >>
| Apply (_loc, mdl, id, args) ->
<:expr<
$G.apps
(<:expr< $id:G.module_id mdl (long_of_ id)$ >>)
(List.map (fun a -> <:expr< fun v -> $gen_of a <:expr< v >>$ >>) args)$
$v$
>>
| Arrow _ -> assert false
let rec exList_of_list = function
| [] -> <:expr< [] >>
| e :: es -> <:expr< $e$ :: $exList_of_list es$ >>
this is kind of hairy because Xdr.xdr_type_term does n't have a nice
way to express mutual recursion and polymorphism . the basic problem
is that while X_rec / X_refer give you a way to tie a single
recursive loop , for forward references in mutual recursion you have
to inline a copy of the term you 're referring to . polymorphism
complicates things : ordinarily we express it at the OCaml level , but
when we inline a term we have to instantiate it explicitly .
some ways out of this ( requiring Xdr modifications ):
1 . provide explicit xdr_type_terms for mutually - recursive bundles
and projection out of a bundle , and for type abstraction and
instantiation .
2 . do everything at the OCaml level , no X_rec / X_refer . for this we
need a way to make circular data structures but be able to recurse
over them ( see how deriving does it in ) .
vs is an environment giving instantiations for type variables .
bs is an environment listing the bound constructors ( i.e. we 're in the scope of an X_rec )
ds is an environment defining constructors for forward inlining
this is kind of hairy because Xdr.xdr_type_term doesn't have a nice
way to express mutual recursion and polymorphism. the basic problem
is that while X_rec / X_refer give you a way to tie a single
recursive loop, for forward references in mutual recursion you have
to inline a copy of the term you're referring to. polymorphism
complicates things: ordinarily we express it at the OCaml level, but
when we inline a term we have to instantiate it explicitly.
some ways out of this (requiring Xdr modifications):
1. provide explicit xdr_type_terms for mutually-recursive bundles
and projection out of a bundle, and for type abstraction and
instantiation.
2. do everything at the OCaml level, no X_rec / X_refer. for this we
need a way to make circular data structures but be able to recurse
over them (see how deriving does it in Typeable).
vs is an environment giving instantiations for type variables.
bs is an environment listing the bound constructors (i.e. we're in the scope of an X_rec)
ds is an environment defining constructors for forward inlining
*)
let rec gen_xdr qual_id vs bs ds t =
let gen_xdr = gen_xdr qual_id vs bs ds in
match t with
| Abstract _ -> assert false
| Var (_loc, id) ->
begin
try List.assoc id vs
with Not_found -> <:expr< $lid:xdr_p id$ >>
end
| Unit _loc -> <:expr< Xdr.X_void >>
| Int _loc -> <:expr< Xdr.X_int >>
| Int32 _loc -> <:expr< Xdr.X_int >>
| Int64 _loc -> <:expr< Xdr.X_hyper >>
| Float _loc -> <:expr< Xdr.X_double >>
| Bool _loc -> <:expr< Xdr.x_bool >>
| Char _loc -> <:expr< Orpc_onc.x_char >>
| String _loc -> <:expr< Xdr.x_string_max >>
| Tuple (_loc, parts) ->
let px t i = <:expr< ( $`str:string_of_int i$, $gen_xdr t$ ) >> in
<:expr< Xdr.X_struct $exList_of_list (List.mapi px parts)$ >>
| Record (_loc, fields) ->
let fx f = <:expr< ( $`str:f.f_id$, $gen_xdr f.f_typ$ ) >> in
<:expr< Xdr.X_struct $exList_of_list (List.map fx fields)$ >>
| Variant (_loc, arms) ->
let tag (id, _) i = <:expr< ( $`str:id$, Rtypes.int4_of_int $`int:i$ ) >> in
let ax (id, ts) =
match ts with
| [] -> <:expr< ( $`str:id$, Xdr.X_void ) >>
| [t] -> <:expr< ( $`str:id$, $gen_xdr t$ ) >>
| _ ->
let px t i = <:expr< ( $`str:string_of_int i$, $gen_xdr t$ ) >> in
<:expr< ( $`str:id$, Xdr.X_struct $exList_of_list (List.mapi px ts)$) >> in
<:expr<
Xdr.X_union_over_enum
(Xdr.X_enum $exList_of_list (List.mapi tag arms)$,
$exList_of_list (List.map ax arms)$,
None)
>>
| PolyVar (_loc, _, arms) ->
let arms = List.map (function Pv_pv _ -> assert false | Pv_of (id, ts) -> (id, ts)) arms in
let tag (id, _) i = <:expr< ( $`str:id$, Rtypes.int4_of_int $`int:i$ ) >> in
let ax (id, ts) =
match ts with
| [] -> <:expr< ( $`str:id$, Xdr.X_void ) >>
| [t] -> <:expr< ( $`str:id$, $gen_xdr t$ ) >>
| _ ->
let px t i = <:expr< ( $`str:string_of_int i$, $gen_xdr t$ ) >> in
<:expr< ( $`str:id$, Xdr.X_struct $exList_of_list (List.mapi px ts)$) >> in
<:expr<
Xdr.X_union_over_enum
(Xdr.X_enum $exList_of_list (List.mapi tag arms)$,
$exList_of_list (List.map ax arms)$,
None)
>>
| Array (_loc, t) -> <:expr< Xdr.x_array_max $gen_xdr t$ >>
| List (_loc, t) -> <:expr< Orpc_onc.x_list $gen_xdr t$ >>
| Option (_loc, t) -> <:expr< Xdr.x_optional $gen_xdr t$ >>
| Ref (_loc, t) -> gen_xdr t
| Apply (_, [], id, args) ->
if List.mem id bs
(* refer to a def in scope *)
then <:expr< Xdr.X_refer $`str:id$ >>
else begin
try
let { td_vars = vars; td_typ = t } = List.find (fun { td_id = id' } -> id' = id) ds in
inline / instantiate a forward def . can just replace vs because defs have no free variables .
gen_xdr_def qual_id (List.combine vars (List.map gen_xdr args)) bs ds id t
with Not_found ->
(* refer to a previous def at the OCaml level *)
G.apps
(<:expr< $lid:long_xdr id$ >>)
(List.map gen_xdr args)
end
| Apply (_, mdl, id, args) ->
G.apps
(<:expr< $id:G.module_id mdl (long_xdr id)$ >>)
(List.map gen_xdr args)
| Arrow _ -> assert false
and gen_xdr_def qual_id vs bs ds id t =
<:expr< Xdr.X_rec ($`str:id$, $gen_xdr qual_id vs (id::bs) ds t$) >>
let gen_str_typedef ?(qual_id=G.id) stub ds =
<:str_item<
let rec
$list:
List.map
(fun { td_vars = vars; td_id = id; td_typ = t } ->
<:binding<
$lid:long_to_ id$ =
$G.funs_ids
(List.map G.to_p vars)
<:expr< fun x -> $if stub then <:expr< assert false >> else gen_to qual_id t <:expr< x >>$ >>$
>>)
ds$ ;;
let rec
$list:
List.map
(fun { td_vars = vars; td_id = id; td_typ = t } ->
<:binding<
$lid:long_of_ id$ =
$G.funs_ids
(List.map G.of_p vars)
<:expr< fun x -> $if stub then <:expr< assert false >> else gen_of qual_id t <:expr< x >>$ >>$
>>)
ds$ ;;
$list:
let rec loop ds =
match ds with
| [] -> []
| { td_vars = vars; td_id = id; td_typ = t }::ds ->
<:binding<
$lid:long_xdr id$ =
$G.funs_ids
(List.map xdr_p vars)
(if stub then <:expr< Xdr.X_void >> else gen_xdr_def qual_id [] [] ds id t)$
>> :: loop ds in
List.map (fun b -> <:str_item< let $b$ >>) (loop ds)$ ;;
>>
let gen_ml name (typedefs, excs, funcs, kinds) =
let has_excs = excs <> [] in
let qual_id = G.qual_id name in
let gen_of_exc t v =
match gen_of qual_id t v with
| ExMat (loc, e, cases) ->
ExMat (loc, e, McOr(_loc, cases, <:match_case< _ -> raise $v$ >>))
| _ -> assert false in
let gen_func (_, id, args, res) =
let arg =
match List.map typ_of_argtyp_option args with
| [] -> assert false
| [a] -> a
| args -> Tuple (_loc, args) in
let orpc_res =
if has_excs
then Apply (_loc, ["Orpc_onc"], "orpc_result", [res; Apply (_loc, [], "exn", [])])
else res in
let items aid arg =
<:str_item<
let $lid:to_ aid$ x = $gen_to qual_id arg <:expr< x >>$
let $lid:of_ aid$ v = $gen_of qual_id arg <:expr< v >>$
let $lid:xdr aid$ = $gen_xdr qual_id [] [] [] arg$
>> in
<:str_item<
$items (s_arg id) arg$ ;;
$items (s_res id) orpc_res$ ;;
>> in
<:str_item<
$list:List.map (gen_str_typedef ~qual_id false) typedefs$ ;;
$if has_excs
then
let t = Variant (_loc, List.map (fun (_, id, ts) -> (id, ts)) excs) in
<:str_item<
let $lid:long_to_ "exn"$ x = $gen_to qual_id t <:expr< x >>$
let $lid:long_of_ "exn"$ v = $gen_of_exc t <:expr< v >>$
let $lid:long_xdr "exn"$ = $gen_xdr qual_id [] [] [] t$ ;;
>>
else <:str_item< >>$ ;;
$list:List.map gen_func funcs$ ;;
let program =
Rpc_program.create
(Rtypes.uint4_of_int 0)
(Rtypes.uint4_of_int 0)
(Xdr.validate_xdr_type_system [])
$exList_of_list
(List.mapi
(fun (_,id,_,_) i ->
<:expr<
$`str:id$,
(Rtypes.uint4_of_int $`int:i$,
$lid:s_arg (xdr id)$,
$lid:s_res (xdr id)$)
>>)
funcs)$
>>
| null | https://raw.githubusercontent.com/jaked/orpc/ecb5df8ec928070cd89cf035167fcedf3623ee3c/src/generator/gen_aux.ml | ocaml | XXX not sure why list: doesn't work here
refer to a def in scope
refer to a previous def at the OCaml level |
* This file is part of orpc , OCaml signature to ONC RPC generator
* Copyright ( C ) 2008 - 9 Skydeck , Inc
* Copyright ( C ) 2010
*
* 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. , 59 Temple Place - Suite 330 , Boston , MA
* 02111 - 1307 , USA
* This file is part of orpc, OCaml signature to ONC RPC generator
* Copyright (C) 2008-9 Skydeck, Inc
* Copyright (C) 2010 Jacob Donham
*
* 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., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA
*)
open Camlp4.PreCast
open Ast
open Types
open Util
let _loc = Camlp4.PreCast.Loc.ghost
module G = Gen_common
let s_arg id = id ^ "'arg"
let s_res id = id ^ "'res"
let xdr_p id = "xdr'" ^ id
let long_xdr id = "orpc_aux_xdr_" ^ id
let long_to_ id = "orpc_aux_to_" ^ id
let long_of_ id = "orpc_aux_of_" ^ id
let xdr id = "xdr_" ^ id
let to_ id = "to_" ^ id
let of_ id = "of_" ^ id
let gen_sig_typedef ?(qual_id=G.id) ds =
<:sig_item< $list:
List.map
(fun { td_vars = vars; td_id = id } ->
let appd =
G.tapps <:ctyp< $id:qual_id id$ >> (G.tvars vars) in
<:sig_item<
val $lid:long_to_ id$ :
$G.arrows
(List.map (fun v -> <:ctyp< Xdr.xdr_value -> '$lid:v$ >>) vars)
<:ctyp< Xdr.xdr_value -> $appd$ >>$
val $lid:long_of_ id$ :
$G.arrows
(List.map (fun v -> <:ctyp< '$lid:v$ -> Xdr.xdr_value >>) vars)
(TyArr (_loc, appd, <:ctyp< Xdr.xdr_value >>))
< : < $ appd$ - > Xdr.xdr_value > > broken in 3.12
val $lid:long_xdr id$ :
$G.arrows
(List.map (fun v -> <:ctyp< Xdr.xdr_type_term >>) vars)
<:ctyp< Xdr.xdr_type_term >>$
>>)
ds$
>>
let gen_mli name (typedefs, excs, funcs, kinds) =
let has_excs = excs <> [] in
let qual_id = G.qual_id name in
let gen_func (_, id, args, res) =
let arg =
match List.map typ_of_argtyp_option args with
| [] -> assert false
| [a] -> a
| args -> Tuple (g, args) in
let orpc_res =
if has_excs
then Apply (_loc, ["Orpc"], "orpc_result", [res; Apply (_loc, [], "exn", [])])
else res in
let items aid arg =
let t = G.gen_type qual_id arg in
<:sig_item<
val $lid:to_ aid$ : Xdr.xdr_value -> $t$
val $lid:of_ aid$ : $t$ -> Xdr.xdr_value
val $lid:xdr aid$ : Xdr.xdr_type_term
>> in
<:sig_item<
$items (s_arg id) arg$
$items (s_res id) orpc_res$
>> in
<:sig_item<
$list:List.map (gen_sig_typedef ~qual_id) typedefs$ ;;
$if has_excs
then
<:sig_item<
val $lid:long_to_ "exn"$ : Xdr.xdr_value -> exn
val $lid:long_of_ "exn"$ : exn -> Xdr.xdr_value
val $lid:long_xdr "exn"$ : Xdr.xdr_type_term ;;
>>
else <:sig_item< >>$ ;;
$list:List.map gen_func funcs$ ;;
val program : Rpc_program.t
>>
let rec gen_to qual_id t x =
let gen_to = gen_to qual_id in
match t with
| Abstract _ -> assert false
| Var (_loc, id) -> <:expr< $lid:G.to_p id$ $x$ >>
| Unit _loc -> <:expr< () >>
| Int _loc -> <:expr< Rtypes.int_of_int4 (Xdr.dest_xv_int $x$) >>
| Int32 _loc -> <:expr< Rtypes.int32_of_int4 (Xdr.dest_xv_int $x$) >>
| Int64 _loc -> <:expr< Rtypes.int64_of_int8 (Xdr.dest_xv_hyper $x$) >>
| Float _loc -> <:expr< Rtypes.float_of_fp8 (Xdr.dest_xv_double $x$) >>
| Bool _loc -> <:expr< Xdr.dest_xv_enum_fast $x$ = 1 >>
| Char _loc -> <:expr< char_of_int (Xdr.dest_xv_enum_fast $x$) >>
| String _loc -> <:expr< Xdr.dest_xv_string $x$>>
| Tuple (_loc, parts) ->
let (pps, pes) = G.vars parts in
<:expr<
match Xdr.dest_xv_struct_fast $x$ with
| [| $list:pps$ |] -> ( $tup:exCom_of_list (List.map2 gen_to parts pes)$ )
| _ -> assert false
>>
| Record (_loc, fields) ->
let (fps, fes) = G.vars fields in
let rb f e = <:rec_binding< $id:qual_id f.f_id$ = $gen_to f.f_typ e$ >> in
<:expr<
match Xdr.dest_xv_struct_fast $x$ with
| [| $list:fps$ |] ->
$ExRec(_loc, rbSem_of_list (List.map2 rb fields fes), <:expr< >>)$
| _ -> assert false
>>
| Variant (_loc, arms) ->
let mc (id, ts) i =
match ts with
| [] -> <:match_case< ($`int:i$, _) -> $id:qual_id id$ >>
| [t] -> <:match_case< ($`int:i$, x) -> $id:qual_id id$ $gen_to t <:expr< x >>$ >>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
($`int:i$, x) ->
match Xdr.dest_xv_struct_fast x with
| [| $list:pps$ |] ->
$G.apps
<:expr< $id:qual_id id$ >>
(List.map2 gen_to ts pes)$
| _ -> assert false
>> in
<:expr<
match Xdr.dest_xv_union_over_enum_fast $x$ with
$list:List.mapi mc arms$
| _ -> assert false
>>
| PolyVar (_loc, _, arms) ->
let arms = List.map (function Pv_pv _ -> assert false | Pv_of (id, ts) -> (id, ts)) arms in
let mc (id, ts) i =
match ts with
| [] -> <:match_case< ($`int:i$, _) -> `$id$ >>
| [t] -> <:match_case< ($`int:i$, x) -> `$id$ $gen_to t <:expr< x >>$ >>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
($`int:i$, x) ->
match Xdr.dest_xv_struct_fast x with
| [| $list:pps$ |] ->
$G.apps
<:expr< `$id$ >>
(List.map2 gen_to ts pes)$
| _ -> assert false
>> in
<:expr<
match Xdr.dest_xv_union_over_enum_fast $x$ with
$list:List.mapi mc arms$
| _ -> assert false
>>
| Array (_loc, String _) -> <:expr< Xdr.dest_xv_array_of_string_fast $x$ >>
| Array (_loc, t) ->
<:expr< Array.map (fun x -> $gen_to t <:expr< x >>$) (Xdr.dest_xv_array $x$) >>
| List (_loc, String _) -> <:expr< Array.to_list (Xdr.dest_xv_array_of_string_fast $x$) >>
| List (_loc, t) ->
<:expr< Orpc_onc.to_list (fun x -> $gen_to t <:expr< x >>$) $x$ >>
| Option (_loc, t) ->
<:expr< Orpc_onc.to_option (fun x -> $gen_to t <:expr< x >>$) $x$ >>
| Ref (_loc, t) -> <:expr< ref $gen_to t x$ >>
| Apply (_loc, mdl, id, args) ->
<:expr<
$G.apps
(<:expr< $id:G.module_id mdl (long_to_ id)$ >>)
(List.map (fun a -> <:expr< fun x -> $gen_to a <:expr< x >>$ >>) args)$
$x$
>>
| Arrow _ -> assert false
let rec gen_of qual_id t v =
let gen_of = gen_of qual_id in
match t with
| Abstract _ -> assert false
| Var (_loc, id) -> <:expr< $lid:G.of_p id$ $v$ >>
| Unit _loc -> <:expr< Xdr.XV_void >>
| Int _loc -> <:expr< Xdr.XV_int (Rtypes.int4_of_int $v$) >>
| Int32 _loc -> <:expr< Xdr.XV_int (Rtypes.int4_of_int32 $v$) >>
| Int64 _loc -> <:expr< Xdr.XV_hyper (Rtypes.int8_of_int64 $v$) >>
| Float _loc -> <:expr< Xdr.XV_double (Rtypes.fp8_of_float $v$) >>
| Bool _loc -> <:expr< Xdr.XV_enum_fast (if $v$ then 1 else 0) >>
| Char _loc -> <:expr< Xdr.XV_enum_fast (int_of_char $v$) >>
| String _loc -> <:expr< Xdr.XV_string $v$ >>
| Tuple (_loc, parts) ->
let (pps, pes) = G.vars parts in
<:expr<
let ( $tup:paCom_of_list pps$ ) = $v$ in
>>
| Record (_loc, fields) ->
let (fps, fes) = G.vars fields in
let rb f p = <:patt< $id:qual_id f.f_id$ = $p$ >> in
<:expr<
let { $paSem_of_list (List.map2 rb fields fps)$ } = $v$ in
Xdr.XV_struct_fast
[| $exSem_of_list (List.map2 (fun f v -> gen_of f.f_typ v) fields fes)$ |]
>>
| Variant (_loc, arms) ->
let mc (id, ts) i =
match ts with
| [] ->
<:match_case<
$id:qual_id id$ ->
Xdr.XV_union_over_enum_fast ($`int:i$, Xdr.XV_void)
>>
| [t] ->
<:match_case<
$id:qual_id id$ x ->
Xdr.XV_union_over_enum_fast ($`int:i$, $gen_of t <:expr< x >>$)
>>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
$G.papps <:patt< $id:qual_id id$ >> pps$ ->
Xdr.XV_union_over_enum_fast
($`int:i$,
Xdr.XV_struct_fast [| $exSem_of_list (List.map2 gen_of ts pes)$ |])
>> in
<:expr< match $v$ with $list:List.mapi mc arms$ >>
| PolyVar (_loc, _, arms) ->
let arms = List.map (function Pv_pv _ -> assert false | Pv_of (id, ts) -> (id, ts)) arms in
let mc (id, ts) i =
match ts with
| [] ->
<:match_case<
`$id$ ->
Xdr.XV_union_over_enum_fast ($`int:i$, Xdr.XV_void)
>>
| [t] ->
<:match_case<
`$id$ x ->
Xdr.XV_union_over_enum_fast ($`int:i$, $gen_of t <:expr< x >>$)
>>
| _ ->
let (pps, pes) = G.vars ts in
<:match_case<
$G.papps <:patt< `$id$ >> pps$ ->
Xdr.XV_union_over_enum_fast
($`int:i$,
Xdr.XV_struct_fast [| $exSem_of_list (List.map2 gen_of ts pes)$ |])
>> in
<:expr< match $v$ with $list:List.mapi mc arms$ >>
| Array (_loc, String _) -> <:expr< Xdr.XV_array_of_string_fast $v$ >>
| Array (_loc, t) ->
<:expr< Xdr.XV_array (Array.map (fun v -> $gen_of t <:expr< v >>$) $v$) >>
| List (_loc, String _) -> <:expr< Xdr.XV_array_of_string_fast (Array.of_list $v$) >>
| List (_loc, t) ->
<:expr< Orpc_onc.of_list (fun v -> $gen_of t <:expr< v >>$) $v$ >>
| Option (_loc, t) ->
<:expr< Orpc_onc.of_option (fun v -> $gen_of t <:expr< v >>$) $v$ >>
| Ref (_loc, t) -> gen_of t <:expr< ! $v$ >>
| Apply (_loc, mdl, id, args) ->
<:expr<
$G.apps
(<:expr< $id:G.module_id mdl (long_of_ id)$ >>)
(List.map (fun a -> <:expr< fun v -> $gen_of a <:expr< v >>$ >>) args)$
$v$
>>
| Arrow _ -> assert false
let rec exList_of_list = function
| [] -> <:expr< [] >>
| e :: es -> <:expr< $e$ :: $exList_of_list es$ >>
this is kind of hairy because Xdr.xdr_type_term does n't have a nice
way to express mutual recursion and polymorphism . the basic problem
is that while X_rec / X_refer give you a way to tie a single
recursive loop , for forward references in mutual recursion you have
to inline a copy of the term you 're referring to . polymorphism
complicates things : ordinarily we express it at the OCaml level , but
when we inline a term we have to instantiate it explicitly .
some ways out of this ( requiring Xdr modifications ):
1 . provide explicit xdr_type_terms for mutually - recursive bundles
and projection out of a bundle , and for type abstraction and
instantiation .
2 . do everything at the OCaml level , no X_rec / X_refer . for this we
need a way to make circular data structures but be able to recurse
over them ( see how deriving does it in ) .
vs is an environment giving instantiations for type variables .
bs is an environment listing the bound constructors ( i.e. we 're in the scope of an X_rec )
ds is an environment defining constructors for forward inlining
this is kind of hairy because Xdr.xdr_type_term doesn't have a nice
way to express mutual recursion and polymorphism. the basic problem
is that while X_rec / X_refer give you a way to tie a single
recursive loop, for forward references in mutual recursion you have
to inline a copy of the term you're referring to. polymorphism
complicates things: ordinarily we express it at the OCaml level, but
when we inline a term we have to instantiate it explicitly.
some ways out of this (requiring Xdr modifications):
1. provide explicit xdr_type_terms for mutually-recursive bundles
and projection out of a bundle, and for type abstraction and
instantiation.
2. do everything at the OCaml level, no X_rec / X_refer. for this we
need a way to make circular data structures but be able to recurse
over them (see how deriving does it in Typeable).
vs is an environment giving instantiations for type variables.
bs is an environment listing the bound constructors (i.e. we're in the scope of an X_rec)
ds is an environment defining constructors for forward inlining
*)
let rec gen_xdr qual_id vs bs ds t =
let gen_xdr = gen_xdr qual_id vs bs ds in
match t with
| Abstract _ -> assert false
| Var (_loc, id) ->
begin
try List.assoc id vs
with Not_found -> <:expr< $lid:xdr_p id$ >>
end
| Unit _loc -> <:expr< Xdr.X_void >>
| Int _loc -> <:expr< Xdr.X_int >>
| Int32 _loc -> <:expr< Xdr.X_int >>
| Int64 _loc -> <:expr< Xdr.X_hyper >>
| Float _loc -> <:expr< Xdr.X_double >>
| Bool _loc -> <:expr< Xdr.x_bool >>
| Char _loc -> <:expr< Orpc_onc.x_char >>
| String _loc -> <:expr< Xdr.x_string_max >>
| Tuple (_loc, parts) ->
let px t i = <:expr< ( $`str:string_of_int i$, $gen_xdr t$ ) >> in
<:expr< Xdr.X_struct $exList_of_list (List.mapi px parts)$ >>
| Record (_loc, fields) ->
let fx f = <:expr< ( $`str:f.f_id$, $gen_xdr f.f_typ$ ) >> in
<:expr< Xdr.X_struct $exList_of_list (List.map fx fields)$ >>
| Variant (_loc, arms) ->
let tag (id, _) i = <:expr< ( $`str:id$, Rtypes.int4_of_int $`int:i$ ) >> in
let ax (id, ts) =
match ts with
| [] -> <:expr< ( $`str:id$, Xdr.X_void ) >>
| [t] -> <:expr< ( $`str:id$, $gen_xdr t$ ) >>
| _ ->
let px t i = <:expr< ( $`str:string_of_int i$, $gen_xdr t$ ) >> in
<:expr< ( $`str:id$, Xdr.X_struct $exList_of_list (List.mapi px ts)$) >> in
<:expr<
Xdr.X_union_over_enum
(Xdr.X_enum $exList_of_list (List.mapi tag arms)$,
$exList_of_list (List.map ax arms)$,
None)
>>
| PolyVar (_loc, _, arms) ->
let arms = List.map (function Pv_pv _ -> assert false | Pv_of (id, ts) -> (id, ts)) arms in
let tag (id, _) i = <:expr< ( $`str:id$, Rtypes.int4_of_int $`int:i$ ) >> in
let ax (id, ts) =
match ts with
| [] -> <:expr< ( $`str:id$, Xdr.X_void ) >>
| [t] -> <:expr< ( $`str:id$, $gen_xdr t$ ) >>
| _ ->
let px t i = <:expr< ( $`str:string_of_int i$, $gen_xdr t$ ) >> in
<:expr< ( $`str:id$, Xdr.X_struct $exList_of_list (List.mapi px ts)$) >> in
<:expr<
Xdr.X_union_over_enum
(Xdr.X_enum $exList_of_list (List.mapi tag arms)$,
$exList_of_list (List.map ax arms)$,
None)
>>
| Array (_loc, t) -> <:expr< Xdr.x_array_max $gen_xdr t$ >>
| List (_loc, t) -> <:expr< Orpc_onc.x_list $gen_xdr t$ >>
| Option (_loc, t) -> <:expr< Xdr.x_optional $gen_xdr t$ >>
| Ref (_loc, t) -> gen_xdr t
| Apply (_, [], id, args) ->
if List.mem id bs
then <:expr< Xdr.X_refer $`str:id$ >>
else begin
try
let { td_vars = vars; td_typ = t } = List.find (fun { td_id = id' } -> id' = id) ds in
inline / instantiate a forward def . can just replace vs because defs have no free variables .
gen_xdr_def qual_id (List.combine vars (List.map gen_xdr args)) bs ds id t
with Not_found ->
G.apps
(<:expr< $lid:long_xdr id$ >>)
(List.map gen_xdr args)
end
| Apply (_, mdl, id, args) ->
G.apps
(<:expr< $id:G.module_id mdl (long_xdr id)$ >>)
(List.map gen_xdr args)
| Arrow _ -> assert false
and gen_xdr_def qual_id vs bs ds id t =
<:expr< Xdr.X_rec ($`str:id$, $gen_xdr qual_id vs (id::bs) ds t$) >>
let gen_str_typedef ?(qual_id=G.id) stub ds =
<:str_item<
let rec
$list:
List.map
(fun { td_vars = vars; td_id = id; td_typ = t } ->
<:binding<
$lid:long_to_ id$ =
$G.funs_ids
(List.map G.to_p vars)
<:expr< fun x -> $if stub then <:expr< assert false >> else gen_to qual_id t <:expr< x >>$ >>$
>>)
ds$ ;;
let rec
$list:
List.map
(fun { td_vars = vars; td_id = id; td_typ = t } ->
<:binding<
$lid:long_of_ id$ =
$G.funs_ids
(List.map G.of_p vars)
<:expr< fun x -> $if stub then <:expr< assert false >> else gen_of qual_id t <:expr< x >>$ >>$
>>)
ds$ ;;
$list:
let rec loop ds =
match ds with
| [] -> []
| { td_vars = vars; td_id = id; td_typ = t }::ds ->
<:binding<
$lid:long_xdr id$ =
$G.funs_ids
(List.map xdr_p vars)
(if stub then <:expr< Xdr.X_void >> else gen_xdr_def qual_id [] [] ds id t)$
>> :: loop ds in
List.map (fun b -> <:str_item< let $b$ >>) (loop ds)$ ;;
>>
let gen_ml name (typedefs, excs, funcs, kinds) =
let has_excs = excs <> [] in
let qual_id = G.qual_id name in
let gen_of_exc t v =
match gen_of qual_id t v with
| ExMat (loc, e, cases) ->
ExMat (loc, e, McOr(_loc, cases, <:match_case< _ -> raise $v$ >>))
| _ -> assert false in
let gen_func (_, id, args, res) =
let arg =
match List.map typ_of_argtyp_option args with
| [] -> assert false
| [a] -> a
| args -> Tuple (_loc, args) in
let orpc_res =
if has_excs
then Apply (_loc, ["Orpc_onc"], "orpc_result", [res; Apply (_loc, [], "exn", [])])
else res in
let items aid arg =
<:str_item<
let $lid:to_ aid$ x = $gen_to qual_id arg <:expr< x >>$
let $lid:of_ aid$ v = $gen_of qual_id arg <:expr< v >>$
let $lid:xdr aid$ = $gen_xdr qual_id [] [] [] arg$
>> in
<:str_item<
$items (s_arg id) arg$ ;;
$items (s_res id) orpc_res$ ;;
>> in
<:str_item<
$list:List.map (gen_str_typedef ~qual_id false) typedefs$ ;;
$if has_excs
then
let t = Variant (_loc, List.map (fun (_, id, ts) -> (id, ts)) excs) in
<:str_item<
let $lid:long_to_ "exn"$ x = $gen_to qual_id t <:expr< x >>$
let $lid:long_of_ "exn"$ v = $gen_of_exc t <:expr< v >>$
let $lid:long_xdr "exn"$ = $gen_xdr qual_id [] [] [] t$ ;;
>>
else <:str_item< >>$ ;;
$list:List.map gen_func funcs$ ;;
let program =
Rpc_program.create
(Rtypes.uint4_of_int 0)
(Rtypes.uint4_of_int 0)
(Xdr.validate_xdr_type_system [])
$exList_of_list
(List.mapi
(fun (_,id,_,_) i ->
<:expr<
$`str:id$,
(Rtypes.uint4_of_int $`int:i$,
$lid:s_arg (xdr id)$,
$lid:s_res (xdr id)$)
>>)
funcs)$
>>
|
de5cb776298957344a5a06028db5b7d1bdb163d7575330fc6909b8d2355deb8b | cryptosense/pkcs11 | p11_slot_id.ml | type t = Unsigned.ULong.t [@@deriving ord]
let equal a b = compare a b = 0
let show = Unsigned.ULong.to_string
let pp fmt n = Format.pp_print_string fmt (show n)
let of_yojson = function
| `String s -> Ok (Unsigned.ULong.of_string s)
| _ -> Error "ulong_of_yojson: not a string"
let to_yojson ulong = `String (Unsigned.ULong.to_string ulong)
let to_string = Unsigned.ULong.to_string
let hash = Unsigned.ULong.to_int
| null | https://raw.githubusercontent.com/cryptosense/pkcs11/93c39c7a31c87f68f0beabf75ef90d85a782a983/lib/p11_slot_id.ml | ocaml | type t = Unsigned.ULong.t [@@deriving ord]
let equal a b = compare a b = 0
let show = Unsigned.ULong.to_string
let pp fmt n = Format.pp_print_string fmt (show n)
let of_yojson = function
| `String s -> Ok (Unsigned.ULong.of_string s)
| _ -> Error "ulong_of_yojson: not a string"
let to_yojson ulong = `String (Unsigned.ULong.to_string ulong)
let to_string = Unsigned.ULong.to_string
let hash = Unsigned.ULong.to_int
| |
f9f0d46ea29c120cbc3c0595f4823be3beaf1288863534887f6651594e7edc6c | pascal-knodel/haskell-craft | E'8''6.hs | --
--
--
----------------
Exercise 8.6 .
----------------
--
--
--
module E'8''6 where
import B'C'8 ( Strategy )
Note : Chapter 4 > cabal install
import B'C'4
(
Move ( Rock , Paper , Scissors )
)
-- In the guides on the net they said it could be an advantage to decide
-- the move in the very last moment. But how would we implement this? Maybe
-- with an additional type, indicating Information about what the next
move of the opponent could be . Example : similarity of Paper and Scissors .
-- And we would need the output of the device that scans the opponent :P
-- I'm not able to handle state in functional programming yet, so I have to
-- think of another 'move counting' strategy ...
react :: Move -> Move
react move
= case (move) of
Rock -> Paper -- Win against last Rock.
Paper -> Rock -- Lose against last Paper.
Scissors -> Scissors -- Draw with last Scissors.
reactPattern :: Strategy
reactPattern [] = Rock
reactPattern (latestMove : _)
= react latestMove
reactPattern' :: Strategy
reactPattern' [] = Rock
reactPattern' [latestMove] = Rock
reactPattern' (_ : moveBeforeLatestMove : _)
= react moveBeforeLatestMove
-- More suggestions: Play least frequent,
play average frequent , do n't play last two moves , ...
| null | https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/Chapter%208/E'8''6.hs | haskell |
--------------
--------------
In the guides on the net they said it could be an advantage to decide
the move in the very last moment. But how would we implement this? Maybe
with an additional type, indicating Information about what the next
And we would need the output of the device that scans the opponent :P
I'm not able to handle state in functional programming yet, so I have to
think of another 'move counting' strategy ...
Win against last Rock.
Lose against last Paper.
Draw with last Scissors.
More suggestions: Play least frequent, | Exercise 8.6 .
module E'8''6 where
import B'C'8 ( Strategy )
Note : Chapter 4 > cabal install
import B'C'4
(
Move ( Rock , Paper , Scissors )
)
move of the opponent could be . Example : similarity of Paper and Scissors .
react :: Move -> Move
react move
= case (move) of
reactPattern :: Strategy
reactPattern [] = Rock
reactPattern (latestMove : _)
= react latestMove
reactPattern' :: Strategy
reactPattern' [] = Rock
reactPattern' [latestMove] = Rock
reactPattern' (_ : moveBeforeLatestMove : _)
= react moveBeforeLatestMove
play average frequent , do n't play last two moves , ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.