_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
|
---|---|---|---|---|---|---|---|---|
3d70f8c84f7138cee1f7a4e4216b48b5d5a8d777e25d0da1618d9c6f188f11e3 | fdopen/uwt | t_fs.mli | val l: OUnitTest.test
val file_to_bytes: string -> bytes Lwt.t
val with_file:
mode:Uwt.Fs.uv_open_flag list ->
string ->
(Uwt.file -> 'a Lwt.t) ->
'a Lwt.t
| null | https://raw.githubusercontent.com/fdopen/uwt/44276aa6755b92eddc9ad58662a968afad243e8b/test/t_fs.mli | ocaml | val l: OUnitTest.test
val file_to_bytes: string -> bytes Lwt.t
val with_file:
mode:Uwt.Fs.uv_open_flag list ->
string ->
(Uwt.file -> 'a Lwt.t) ->
'a Lwt.t
|
|
e5d1b317df1cd4a1252a4219436029a776583632a547693e851562e41358c2cf | agentm/project-m36 | FSType.hs | # LANGUAGE CPP #
confirm that the filesystem type is a journaled FS type expected by Project : M36
use statfs on Linux and macOS and GetVolumeInformation on Windows
-- this could still be fooled with symlinks or by disabling journaling on filesystems that support that
module ProjectM36.FSType where
#if defined(mingw32_HOST_OS)
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# endif
import System.Win32.Types
import Foreign.ForeignPtr
import Data.Word
import Data.Bits
import Foreign.Storable
foreign import WINDOWS_CCONV unsafe "windows.h GetVolumePathNameW"
c_GetVolumePathName :: LPCTSTR -> LPTSTR -> DWORD -> IO BOOL
foreign import WINDOWS_CCONV unsafe "windows.h GetVolumeInformationW"
c_GetVolumeInformation :: LPCTSTR -> LPTSTR -> DWORD -> LPDWORD -> LPDWORD -> LPDWORD -> LPTSTR -> DWORD -> IO BOOL
#define FILE_SUPPORTS_USN_JOURNAL 0x02000000
getVolumePathName :: FilePath -> IO String
getVolumePathName path = do
let maxpathlen = 260 --ANSI MAX_PATH- we only care about the drive name anyway
withTString path $ \c_path -> do
fp_pathout <- mallocForeignPtrBytes maxpathlen
withForeignPtr fp_pathout $ \pathout -> do
failIfFalse_ ("GetVolumePathNameW " ++ path) (c_GetVolumePathName c_path pathout (fromIntegral maxpathlen))
peekTString pathout
fsTypeSupportsJournaling :: FilePath -> IO Bool
fsTypeSupportsJournaling path = do
-- get the drive path of the incoming path
drive <- getVolumePathName path
withTString drive $ \c_drive -> do
foreign_flags <- mallocForeignPtrBytes 8
withForeignPtr foreign_flags $ \ptr_fsFlags -> do
failIfFalse_ (unwords ["GetVolumeInformationW", path]) (c_GetVolumeInformation c_drive nullPtr 0 nullPtr nullPtr ptr_fsFlags nullPtr 0)
fsFlags <- peekByteOff ptr_fsFlags 0 :: IO Word64
pure (fsFlags .&. FILE_SUPPORTS_USN_JOURNAL /= 0)
#elif darwin_HOST_OS
import Foreign.C.Error
import Foreign.C.String
import Foreign.C.Types
reports journaling directly in the fs flags
type CStatFS = ()
foreign import ccall unsafe "cDarwinFSJournaled"
c_DarwinFSJournaled :: CString -> IO CInt
fsTypeSupportsJournaling :: FilePath -> IO Bool
fsTypeSupportsJournaling path =
withCString path $ \c_path -> do
ret <- throwErrnoIfMinus1 "statfs" (c_DarwinFSJournaled c_path)
pure (ret > (0 :: CInt))
#elif linux_HOST_OS
import Foreign
import Foreign.C.Error
import Foreign.C.String
import Foreign.C.Types
#include "MachDeps.h"
--Linux cannot report journaling, so we just check the filesystem type as a proxy
type CStatFS = ()
foreign import ccall unsafe "sys/vfs.h statfs"
c_statfs :: CString -> Ptr CStatFS -> IO CInt
#if WORD_SIZE_IN_BITS == 64
type CFSType = Word64
sizeofStructStatFS :: Int
sizeofStructStatFS = 120
#else
#error 32-bit not supported due to sizeof struct statfs missing
type CFSType = Word32
sizeofStructStatFS :: Int
sizeofStructStatFS = undefined
#endif
fsTypeSupportsJournaling :: FilePath -> IO Bool
fsTypeSupportsJournaling path = do
struct_statfs <- mallocForeignPtrBytes sizeofStructStatFS
withCString path $ \c_path -> do
withForeignPtr struct_statfs $ \ptr_statfs -> do
throwErrnoIfMinus1_ "statfs" (c_statfs c_path ptr_statfs)
cfstype <- peekByteOff ptr_statfs 0 :: IO CFSType
let journaledFS = [0xEF53, --EXT3+4
NTFS
0x52654973, --REISERFS
0x58465342, --XFS
0x3153464a --JFS
]
pure (elem cfstype journaledFS)
#endif
| null | https://raw.githubusercontent.com/agentm/project-m36/57a75b35e84bebf0945db6dae53350fda83f24b6/src/lib/ProjectM36/FSType.hs | haskell | this could still be fooled with symlinks or by disabling journaling on filesystems that support that
ANSI MAX_PATH- we only care about the drive name anyway
get the drive path of the incoming path
Linux cannot report journaling, so we just check the filesystem type as a proxy
EXT3+4
REISERFS
XFS
JFS | # LANGUAGE CPP #
confirm that the filesystem type is a journaled FS type expected by Project : M36
use statfs on Linux and macOS and GetVolumeInformation on Windows
module ProjectM36.FSType where
#if defined(mingw32_HOST_OS)
# if defined(i386_HOST_ARCH)
# define WINDOWS_CCONV stdcall
# elif defined(x86_64_HOST_ARCH)
# define WINDOWS_CCONV ccall
# endif
import System.Win32.Types
import Foreign.ForeignPtr
import Data.Word
import Data.Bits
import Foreign.Storable
foreign import WINDOWS_CCONV unsafe "windows.h GetVolumePathNameW"
c_GetVolumePathName :: LPCTSTR -> LPTSTR -> DWORD -> IO BOOL
foreign import WINDOWS_CCONV unsafe "windows.h GetVolumeInformationW"
c_GetVolumeInformation :: LPCTSTR -> LPTSTR -> DWORD -> LPDWORD -> LPDWORD -> LPDWORD -> LPTSTR -> DWORD -> IO BOOL
#define FILE_SUPPORTS_USN_JOURNAL 0x02000000
getVolumePathName :: FilePath -> IO String
getVolumePathName path = do
withTString path $ \c_path -> do
fp_pathout <- mallocForeignPtrBytes maxpathlen
withForeignPtr fp_pathout $ \pathout -> do
failIfFalse_ ("GetVolumePathNameW " ++ path) (c_GetVolumePathName c_path pathout (fromIntegral maxpathlen))
peekTString pathout
fsTypeSupportsJournaling :: FilePath -> IO Bool
fsTypeSupportsJournaling path = do
drive <- getVolumePathName path
withTString drive $ \c_drive -> do
foreign_flags <- mallocForeignPtrBytes 8
withForeignPtr foreign_flags $ \ptr_fsFlags -> do
failIfFalse_ (unwords ["GetVolumeInformationW", path]) (c_GetVolumeInformation c_drive nullPtr 0 nullPtr nullPtr ptr_fsFlags nullPtr 0)
fsFlags <- peekByteOff ptr_fsFlags 0 :: IO Word64
pure (fsFlags .&. FILE_SUPPORTS_USN_JOURNAL /= 0)
#elif darwin_HOST_OS
import Foreign.C.Error
import Foreign.C.String
import Foreign.C.Types
reports journaling directly in the fs flags
type CStatFS = ()
foreign import ccall unsafe "cDarwinFSJournaled"
c_DarwinFSJournaled :: CString -> IO CInt
fsTypeSupportsJournaling :: FilePath -> IO Bool
fsTypeSupportsJournaling path =
withCString path $ \c_path -> do
ret <- throwErrnoIfMinus1 "statfs" (c_DarwinFSJournaled c_path)
pure (ret > (0 :: CInt))
#elif linux_HOST_OS
import Foreign
import Foreign.C.Error
import Foreign.C.String
import Foreign.C.Types
#include "MachDeps.h"
type CStatFS = ()
foreign import ccall unsafe "sys/vfs.h statfs"
c_statfs :: CString -> Ptr CStatFS -> IO CInt
#if WORD_SIZE_IN_BITS == 64
type CFSType = Word64
sizeofStructStatFS :: Int
sizeofStructStatFS = 120
#else
#error 32-bit not supported due to sizeof struct statfs missing
type CFSType = Word32
sizeofStructStatFS :: Int
sizeofStructStatFS = undefined
#endif
fsTypeSupportsJournaling :: FilePath -> IO Bool
fsTypeSupportsJournaling path = do
struct_statfs <- mallocForeignPtrBytes sizeofStructStatFS
withCString path $ \c_path -> do
withForeignPtr struct_statfs $ \ptr_statfs -> do
throwErrnoIfMinus1_ "statfs" (c_statfs c_path ptr_statfs)
cfstype <- peekByteOff ptr_statfs 0 :: IO CFSType
NTFS
]
pure (elem cfstype journaledFS)
#endif
|
a2e96b949cff42ec12194d91894097533a3327a6e760f27ad9970b8a32c59c91 | yzhs/ocamlllvm | format.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
* Pretty printing .
This module implements a pretty - printing facility to format text
within ` ` pretty - printing boxes '' . The pretty - printer breaks lines
at specified break hints , and indents lines according to the box
structure .
For a gentle introduction to the basics of pretty - printing using
[ Format ] , read
{ { : } } .
You may consider this module as providing an extension to the
[ printf ] facility to provide automatic line breaking . The addition of
pretty - printing annotations to your regular [ printf ] formats gives you
fancy indentation and line breaks .
Pretty - printing annotations are described below in the documentation of
the function { ! Format.fprintf } .
You may also use the explicit box management and printing functions
provided by this module . This style is more basic but more verbose
than the [ fprintf ] concise formats .
For instance , the sequence
[ open_box 0 ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ]
that prints [ x = 1 ] within a pretty - printing box , can be
abbreviated as [ printf " @[%s@ % i@]@. " " x = " 1 ] , or even shorter
[ printf " @[x = @ % i@]@. " 1 ] .
Rule of thumb for casual users of this library :
- use simple boxes ( as obtained by [ open_box 0 ] ) ;
- use simple break hints ( as obtained by [ print_cut ( ) ] that outputs a
simple break hint , or by [ print_space ( ) ] that outputs a space
indicating a break hint ) ;
- once a box is opened , display its material with basic printing
functions ( [ print_int ] and [ print_string ] ) ;
- when the material for a box has been printed , call [ close_box ( ) ] to
close the box ;
- at the end of your routine , flush the pretty - printer to display all the
remaining material , e.g. evaluate [ print_newline ( ) ] .
The behaviour of pretty - printing commands is unspecified
if there is no opened pretty - printing box . Each box opened via
one of the [ open _ ] functions below must be closed using [ close_box ]
for proper formatting . Otherwise , some of the material printed in the
boxes may not be output , or may be formatted incorrectly .
In case of interactive use , the system closes all opened boxes and
flushes all pending text ( as with the [ print_newline ] function )
after each phrase . Each phrase is therefore executed in the initial
state of the pretty - printer .
Warning : the material output by the following functions is delayed
in the pretty - printer queue in order to compute the proper line
breaking . Hence , you should not mix calls to the printing functions
of the basic I / O system with calls to the functions of this module :
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands .
This module implements a pretty-printing facility to format text
within ``pretty-printing boxes''. The pretty-printer breaks lines
at specified break hints, and indents lines according to the box
structure.
For a gentle introduction to the basics of pretty-printing using
[Format], read
{{:}}.
You may consider this module as providing an extension to the
[printf] facility to provide automatic line breaking. The addition of
pretty-printing annotations to your regular [printf] formats gives you
fancy indentation and line breaks.
Pretty-printing annotations are described below in the documentation of
the function {!Format.fprintf}.
You may also use the explicit box management and printing functions
provided by this module. This style is more basic but more verbose
than the [fprintf] concise formats.
For instance, the sequence
[open_box 0; print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()]
that prints [x = 1] within a pretty-printing box, can be
abbreviated as [printf "@[%s@ %i@]@." "x =" 1], or even shorter
[printf "@[x =@ %i@]@." 1].
Rule of thumb for casual users of this library:
- use simple boxes (as obtained by [open_box 0]);
- use simple break hints (as obtained by [print_cut ()] that outputs a
simple break hint, or by [print_space ()] that outputs a space
indicating a break hint);
- once a box is opened, display its material with basic printing
functions (e. g. [print_int] and [print_string]);
- when the material for a box has been printed, call [close_box ()] to
close the box;
- at the end of your routine, flush the pretty-printer to display all the
remaining material, e.g. evaluate [print_newline ()].
The behaviour of pretty-printing commands is unspecified
if there is no opened pretty-printing box. Each box opened via
one of the [open_] functions below must be closed using [close_box]
for proper formatting. Otherwise, some of the material printed in the
boxes may not be output, or may be formatted incorrectly.
In case of interactive use, the system closes all opened boxes and
flushes all pending text (as with the [print_newline] function)
after each phrase. Each phrase is therefore executed in the initial
state of the pretty-printer.
Warning: the material output by the following functions is delayed
in the pretty-printer queue in order to compute the proper line
breaking. Hence, you should not mix calls to the printing functions
of the basic I/O system with calls to the functions of this module:
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands.
*)
* { 6 Boxes }
val open_box : int -> unit;;
(** [open_box d] opens a new pretty-printing box
with offset [d].
This box is the general purpose pretty-printing box.
Material in this box is displayed ``horizontal or vertical'':
break hints inside the box may lead to a new line, if there
is no more room on the line to print the remainder of the box,
or if a new line may lead to a new indentation
(demonstrating the indentation of the box).
When a new line is printed in the box, [d] is added to the
current indentation. *)
val close_box : unit -> unit;;
(** Closes the most recently opened pretty-printing box. *)
* { 6 Formatting functions }
val print_string : string -> unit;;
(** [print_string str] prints [str] in the current box. *)
val print_as : int -> string -> unit;;
* [ ] prints [ str ] in the
current box . The pretty - printer formats [ str ] as if
it were of length [ len ] .
current box. The pretty-printer formats [str] as if
it were of length [len]. *)
val print_int : int -> unit;;
(** Prints an integer in the current box. *)
val print_float : float -> unit;;
(** Prints a floating point number in the current box. *)
val print_char : char -> unit;;
(** Prints a character in the current box. *)
val print_bool : bool -> unit;;
(** Prints a boolean in the current box. *)
* { 6 Break hints }
val print_space : unit -> unit;;
* [ print_space ( ) ] is used to separate items ( typically to print
a space between two words ) .
It indicates that the line may be split at this
point . It either prints one space or splits the line .
It is equivalent to [ print_break 1 0 ] .
a space between two words).
It indicates that the line may be split at this
point. It either prints one space or splits the line.
It is equivalent to [print_break 1 0]. *)
val print_cut : unit -> unit;;
* [ print_cut ( ) ] is used to mark a good break position .
It indicates that the line may be split at this
point . It either prints nothing or splits the line .
This allows line splitting at the current
point , without printing spaces or adding indentation .
It is equivalent to [ print_break 0 0 ] .
It indicates that the line may be split at this
point. It either prints nothing or splits the line.
This allows line splitting at the current
point, without printing spaces or adding indentation.
It is equivalent to [print_break 0 0]. *)
val print_break : int -> int -> unit;;
(** Inserts a break hint in a pretty-printing box.
[print_break nspaces offset] indicates that the line may
be split (a newline character is printed) at this point,
if the contents of the current box does not fit on the
current line.
If the line is split at that point, [offset] is added to
the current indentation. If the line is not split,
[nspaces] spaces are printed. *)
val print_flush : unit -> unit;;
(** Flushes the pretty printer: all opened boxes are closed,
and all pending text is displayed. *)
val print_newline : unit -> unit;;
(** Equivalent to [print_flush] followed by a new line. *)
val force_newline : unit -> unit;;
(** Forces a newline in the current box. Not the normal way of
pretty-printing, you should prefer break hints. *)
val print_if_newline : unit -> unit;;
(** Executes the next formatting command if the preceding line
has just been split. Otherwise, ignore the next formatting
command. *)
* { 6 Margin }
val set_margin : int -> unit;;
* [ set_margin d ] sets the value of the right margin
to [ d ] ( in characters ): this value is used to detect line
overflows that leads to split lines .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the right margin is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
to [d] (in characters): this value is used to detect line
overflows that leads to split lines.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the right margin is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_margin : unit -> int;;
(** Returns the position of the right margin. *)
* { 6 Maximum indentation limit }
val set_max_indent : int -> unit;;
* [ set_max_indent d ] sets the value of the maximum
indentation limit to [ d ] ( in characters ):
once this limit is reached , boxes are rejected to the left ,
if they do not fit on the current line .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the limit is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
indentation limit to [d] (in characters):
once this limit is reached, boxes are rejected to the left,
if they do not fit on the current line.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the limit is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_max_indent : unit -> int;;
(** Return the value of the maximum indentation limit (in characters). *)
* { 6 Formatting depth : maximum number of boxes allowed before ellipsis }
val set_max_boxes : int -> unit;;
* [ set_max_boxes max ] sets the maximum number
of boxes simultaneously opened .
Material inside boxes nested deeper is printed as an
ellipsis ( more precisely as the text returned by
[ get_ellipsis_text ( ) ] ) .
Nothing happens if [ max ] is smaller than 2 .
of boxes simultaneously opened.
Material inside boxes nested deeper is printed as an
ellipsis (more precisely as the text returned by
[get_ellipsis_text ()]).
Nothing happens if [max] is smaller than 2. *)
val get_max_boxes : unit -> int;;
(** Returns the maximum number of boxes allowed before ellipsis. *)
val over_max_boxes : unit -> bool;;
(** Tests if the maximum number of boxes allowed have already been opened. *)
* { 6 Advanced formatting }
val open_hbox : unit -> unit;;
(** [open_hbox ()] opens a new pretty-printing box.
This box is ``horizontal'': the line is not split in this box
(new lines may still occur inside boxes nested deeper). *)
val open_vbox : int -> unit;;
(** [open_vbox d] opens a new pretty-printing box
with offset [d].
This box is ``vertical'': every break hint inside this
box leads to a new line.
When a new line is printed in the box, [d] is added to the
current indentation. *)
val open_hvbox : int -> unit;;
(** [open_hvbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal-vertical'': it behaves as an
``horizontal'' box if it fits on a single line,
otherwise it behaves as a ``vertical'' box.
When a new line is printed in the box, [d] is added to the
current indentation. *)
val open_hovbox : int -> unit;;
(** [open_hovbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal or vertical'': break hints
inside this box may lead to a new line, if there is no more room
on the line to print the remainder of the box.
When a new line is printed in the box, [d] is added to the
current indentation. *)
* { 6 Tabulations }
val open_tbox : unit -> unit;;
(** Opens a tabulation box. *)
val close_tbox : unit -> unit;;
(** Closes the most recently opened tabulation box. *)
val print_tbreak : int -> int -> unit;;
* Break hint in a tabulation box .
[ print_tbreak spaces offset ] moves the insertion point to
the next tabulation ( [ spaces ] being added to this position ) .
Nothing occurs if insertion point is already on a
tabulation mark .
If there is no next tabulation on the line , then a newline
is printed and the insertion point moves to the first
tabulation of the box .
If a new line is printed , [ offset ] is added to the current
indentation .
[print_tbreak spaces offset] moves the insertion point to
the next tabulation ([spaces] being added to this position).
Nothing occurs if insertion point is already on a
tabulation mark.
If there is no next tabulation on the line, then a newline
is printed and the insertion point moves to the first
tabulation of the box.
If a new line is printed, [offset] is added to the current
indentation. *)
val set_tab : unit -> unit;;
(** Sets a tabulation mark at the current insertion point. *)
val print_tab : unit -> unit;;
(** [print_tab ()] is equivalent to [print_tbreak 0 0]. *)
* { 6 Ellipsis }
val set_ellipsis_text : string -> unit;;
(** Set the text of the ellipsis printed when too many boxes
are opened (a single dot, [.], by default). *)
val get_ellipsis_text : unit -> string;;
(** Return the text of the ellipsis. *)
* { 6 : tags Semantics Tags }
type tag = string;;
* { i Semantics tags } ( or simply { e tags } ) are used to decorate printed
entities for user 's defined purposes , e.g. setting font and giving size
indications for a display device , or marking delimitation of semantics
entities ( e.g. HTML or TeX elements or terminal escape sequences ) .
By default , those tags do not influence line breaking calculation :
the tag ` ` markers '' are not considered as part of the printing
material that drives line breaking ( in other words , the length of
those strings is considered as zero for line breaking ) .
Thus , tag handling is in some sense transparent to pretty - printing
and does not interfere with usual pretty - printing . Hence , a single
pretty printing routine can output both simple ` ` verbatim ''
material or richer decorated output depending on the treatment of
tags . By default , tags are not active , hence the output is not
decorated with tag information . Once [ set_tags ] is set to [ true ] ,
the pretty printer engine honours tags and decorates the output
accordingly .
When a tag has been opened ( or closed ) , it is both and successively
` ` printed '' and ` ` marked '' . Printing a tag means calling a
formatter specific function with the name of the tag as argument :
that ` ` tag printing '' function can then print any regular material
to the formatter ( so that this material is enqueued as usual in the
formatter queue for further line - breaking computation ) . Marking a
tag means to output an arbitrary string ( the ` ` tag marker '' ) ,
directly into the output device of the formatter . Hence , the
formatter specific ` ` tag marking '' function must return the tag
marker string associated to its tag argument . Being flushed
directly into the output device of the formatter , tag marker
strings are not considered as part of the printing material that
drives line breaking ( in other words , the length of the strings
corresponding to tag markers is considered as zero for line
breaking ) . In addition , advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines , and
precisely when the queue is flushed into the output device .
In the spirit of HTML tags , the default tag marking functions
output tags enclosed in " < " and " > " : hence , the opening marker of
tag [ t ] is [ " < t > " ] and the closing marker [ " < /t > " ] .
tag printing functions just do nothing .
Tag marking and tag printing functions are user definable and can
be set by calling [ set_formatter_tag_functions ] .
entities for user's defined purposes, e.g. setting font and giving size
indications for a display device, or marking delimitation of semantics
entities (e.g. HTML or TeX elements or terminal escape sequences).
By default, those tags do not influence line breaking calculation:
the tag ``markers'' are not considered as part of the printing
material that drives line breaking (in other words, the length of
those strings is considered as zero for line breaking).
Thus, tag handling is in some sense transparent to pretty-printing
and does not interfere with usual pretty-printing. Hence, a single
pretty printing routine can output both simple ``verbatim''
material or richer decorated output depending on the treatment of
tags. By default, tags are not active, hence the output is not
decorated with tag information. Once [set_tags] is set to [true],
the pretty printer engine honours tags and decorates the output
accordingly.
When a tag has been opened (or closed), it is both and successively
``printed'' and ``marked''. Printing a tag means calling a
formatter specific function with the name of the tag as argument:
that ``tag printing'' function can then print any regular material
to the formatter (so that this material is enqueued as usual in the
formatter queue for further line-breaking computation). Marking a
tag means to output an arbitrary string (the ``tag marker''),
directly into the output device of the formatter. Hence, the
formatter specific ``tag marking'' function must return the tag
marker string associated to its tag argument. Being flushed
directly into the output device of the formatter, tag marker
strings are not considered as part of the printing material that
drives line breaking (in other words, the length of the strings
corresponding to tag markers is considered as zero for line
breaking). In addition, advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines, and
precisely when the queue is flushed into the output device.
In the spirit of HTML tags, the default tag marking functions
output tags enclosed in "<" and ">": hence, the opening marker of
tag [t] is ["<t>"] and the closing marker ["</t>"].
Default tag printing functions just do nothing.
Tag marking and tag printing functions are user definable and can
be set by calling [set_formatter_tag_functions]. *)
val open_tag : tag -> unit;;
(** [open_tag t] opens the tag named [t]; the [print_open_tag]
function of the formatter is called with [t] as argument;
the tag marker [mark_open_tag t] will be flushed into the output
device of the formatter. *)
val close_tag : unit -> unit;;
(** [close_tag ()] closes the most recently opened tag [t].
In addition, the [print_close_tag] function of the formatter is called
with [t] as argument. The marker [mark_close_tag t] will be flushed
into the output device of the formatter. *)
val set_tags : bool -> unit;;
(** [set_tags b] turns on or off the treatment of tags (default is off). *)
val set_print_tags : bool -> unit;;
val set_mark_tags : bool -> unit;;
(** [set_print_tags b] turns on or off the printing of tags, while
[set_mark_tags b] turns on or off the output of tag markers. *)
val get_print_tags : unit -> bool;;
val get_mark_tags : unit -> bool;;
(** Return the current status of tags printing and tags marking. *)
* { 6 Redirecting the standard formatter output }
val set_formatter_out_channel : Pervasives.out_channel -> unit;;
(** Redirect the pretty-printer output to the given channel.
(All the output functions of the standard formatter are set to the
default output functions printing to the given channel.) *)
val set_formatter_output_functions :
(string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
(** [set_formatter_output_functions out flush] redirects the
relevant pretty-printer output functions to the functions [out] and
[flush].
The [out] function performs the pretty-printer string output. It is called
with a string [s], a start position [p], and a number of characters
[n]; it is supposed to output characters [p] to [p + n - 1] of
[s]. The [flush] function is called whenever the pretty-printer is
flushed (via conversion [%!], pretty-printing indications [@?] or [@.],
or using low level function [print_flush] or [print_newline]). *)
val get_formatter_output_functions :
unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
(** Return the current output functions of the pretty-printer. *)
* { 6 : meaning Changing the meaning of standard formatter pretty printing }
(** The [Format] module is versatile enough to let you completely redefine
the meaning of pretty printing: you may provide your own functions to define
how to handle indentation, line breaking, and even printing of all the
characters that have to be printed! *)
val set_all_formatter_output_functions :
out:(string -> int -> int -> unit) ->
flush:(unit -> unit) ->
newline:(unit -> unit) ->
spaces:(int -> unit) ->
unit
;;
* [ set_all_formatter_output_functions out flush outnewline outspace ]
redirects the pretty - printer output to the functions [ out ] and
[ flush ] as described in [ set_formatter_output_functions ] . In
addition , the pretty - printer function that outputs a newline is set
to the function [ outnewline ] and the function that outputs
indentation spaces is set to the function [ outspace ] .
This way , you can change the meaning of indentation ( which can be
something else than just printing space characters ) and the
meaning of new lines opening ( which can be connected to any other
action needed by the application at hand ) . The two functions
[ outspace ] and [ outnewline ] are normally connected to [ out ] and
[ flush ] : respective default values for [ outspace ] and [ outnewline ]
are [ out ( String.make n ' ' ) 0 n ] and [ out " \n " 0 1 ] .
redirects the pretty-printer output to the functions [out] and
[flush] as described in [set_formatter_output_functions]. In
addition, the pretty-printer function that outputs a newline is set
to the function [outnewline] and the function that outputs
indentation spaces is set to the function [outspace].
This way, you can change the meaning of indentation (which can be
something else than just printing space characters) and the
meaning of new lines opening (which can be connected to any other
action needed by the application at hand). The two functions
[outspace] and [outnewline] are normally connected to [out] and
[flush]: respective default values for [outspace] and [outnewline]
are [out (String.make n ' ') 0 n] and [out "\n" 0 1]. *)
val get_all_formatter_output_functions :
unit ->
(string -> int -> int -> unit) *
(unit -> unit) *
(unit -> unit) *
(int -> unit)
;;
(** Return the current output functions of the pretty-printer,
including line breaking and indentation functions. Useful to record the
current setting and restore it afterwards. *)
* { 6 : tags Changing the meaning of printing semantics tags }
type formatter_tag_functions = {
mark_open_tag : tag -> string;
mark_close_tag : tag -> string;
print_open_tag : tag -> unit;
print_close_tag : tag -> unit;
}
;;
(** The tag handling functions specific to a formatter:
[mark] versions are the ``tag marking'' functions that associate a string
marker to a tag in order for the pretty-printing engine to flush
those markers as 0 length tokens in the output device of the formatter.
[print] versions are the ``tag printing'' functions that can perform
regular printing when a tag is closed or opened. *)
val set_formatter_tag_functions :
formatter_tag_functions -> unit
;;
(** [set_formatter_tag_functions tag_funs] changes the meaning of
opening and closing tags to use the functions in [tag_funs].
When opening a tag name [t], the string [t] is passed to the
opening tag marking function (the [mark_open_tag] field of the
record [tag_funs]), that must return the opening tag marker for
that name. When the next call to [close_tag ()] happens, the tag
name [t] is sent back to the closing tag marking function (the
[mark_close_tag] field of record [tag_funs]), that must return a
closing tag marker for that name.
The [print_] field of the record contains the functions that are
called at tag opening and tag closing time, to output regular
material in the pretty-printer queue. *)
val get_formatter_tag_functions :
unit -> formatter_tag_functions
;;
(** Return the current tag functions of the pretty-printer. *)
* { 6 Multiple formatted output }
type formatter;;
(** Abstract data corresponding to a pretty-printer (also called a
formatter) and all its machinery.
Defining new pretty-printers permits unrelated output of material in
parallel on several output channels.
All the parameters of a pretty-printer are local to this pretty-printer:
margin, maximum indentation limit, maximum number of boxes
simultaneously opened, ellipsis, and so on, are specific to
each pretty-printer and may be fixed independently.
Given a [Pervasives.out_channel] output channel [oc], a new formatter
writing to that channel is simply obtained by calling
[formatter_of_out_channel oc].
Alternatively, the [make_formatter] function allocates a new
formatter with explicit output and flushing functions
(convenient to output material to strings for instance).
*)
val formatter_of_out_channel : out_channel -> formatter;;
(** [formatter_of_out_channel oc] returns a new formatter that
writes to the corresponding channel [oc]. *)
val std_formatter : formatter;;
(** The standard formatter used by the formatting functions
above. It is defined as [formatter_of_out_channel stdout]. *)
val err_formatter : formatter;;
(** A formatter to use with formatting functions below for
output to standard error. It is defined as
[formatter_of_out_channel stderr]. *)
val formatter_of_buffer : Buffer.t -> formatter;;
(** [formatter_of_buffer b] returns a new formatter writing to
buffer [b]. As usual, the formatter has to be flushed at
the end of pretty printing, using [pp_print_flush] or
[pp_print_newline], to display all the pending material. *)
val stdbuf : Buffer.t;;
(** The string buffer in which [str_formatter] writes. *)
val str_formatter : formatter;;
(** A formatter to use with formatting functions below for
output to the [stdbuf] string buffer.
[str_formatter] is defined as [formatter_of_buffer stdbuf]. *)
val flush_str_formatter : unit -> string;;
(** Returns the material printed with [str_formatter], flushes
the formatter and resets the corresponding buffer. *)
val make_formatter :
(string -> int -> int -> unit) -> (unit -> unit) -> formatter
;;
(** [make_formatter out flush] returns a new formatter that writes according
to the output function [out], and the flushing function [flush]. For
instance, a formatter to the [Pervasives.out_channel] [oc] is returned by
[make_formatter (Pervasives.output oc) (fun () -> Pervasives.flush oc)]. *)
* { 6 Basic functions to use with formatters }
val pp_open_hbox : formatter -> unit -> unit;;
val pp_open_vbox : formatter -> int -> unit;;
val pp_open_hvbox : formatter -> int -> unit;;
val pp_open_hovbox : formatter -> int -> unit;;
val pp_open_box : formatter -> int -> unit;;
val pp_close_box : formatter -> unit -> unit;;
val pp_open_tag : formatter -> string -> unit;;
val pp_close_tag : formatter -> unit -> unit;;
val pp_print_string : formatter -> string -> unit;;
val pp_print_as : formatter -> int -> string -> unit;;
val pp_print_int : formatter -> int -> unit;;
val pp_print_float : formatter -> float -> unit;;
val pp_print_char : formatter -> char -> unit;;
val pp_print_bool : formatter -> bool -> unit;;
val pp_print_break : formatter -> int -> int -> unit;;
val pp_print_cut : formatter -> unit -> unit;;
val pp_print_space : formatter -> unit -> unit;;
val pp_force_newline : formatter -> unit -> unit;;
val pp_print_flush : formatter -> unit -> unit;;
val pp_print_newline : formatter -> unit -> unit;;
val pp_print_if_newline : formatter -> unit -> unit;;
val pp_open_tbox : formatter -> unit -> unit;;
val pp_close_tbox : formatter -> unit -> unit;;
val pp_print_tbreak : formatter -> int -> int -> unit;;
val pp_set_tab : formatter -> unit -> unit;;
val pp_print_tab : formatter -> unit -> unit;;
val pp_set_tags : formatter -> bool -> unit;;
val pp_set_print_tags : formatter -> bool -> unit;;
val pp_set_mark_tags : formatter -> bool -> unit;;
val pp_get_print_tags : formatter -> unit -> bool;;
val pp_get_mark_tags : formatter -> unit -> bool;;
val pp_set_margin : formatter -> int -> unit;;
val pp_get_margin : formatter -> unit -> int;;
val pp_set_max_indent : formatter -> int -> unit;;
val pp_get_max_indent : formatter -> unit -> int;;
val pp_set_max_boxes : formatter -> int -> unit;;
val pp_get_max_boxes : formatter -> unit -> int;;
val pp_over_max_boxes : formatter -> unit -> bool;;
val pp_set_ellipsis_text : formatter -> string -> unit;;
val pp_get_ellipsis_text : formatter -> unit -> string;;
val pp_set_formatter_out_channel : formatter -> Pervasives.out_channel -> unit;;
val pp_set_formatter_output_functions :
formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
val pp_get_formatter_output_functions :
formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
val pp_set_all_formatter_output_functions :
formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) ->
newline:(unit -> unit) -> spaces:(int -> unit) -> unit
;;
val pp_get_all_formatter_output_functions :
formatter -> unit ->
(string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) *
(int -> unit)
;;
val pp_set_formatter_tag_functions :
formatter -> formatter_tag_functions -> unit
;;
val pp_get_formatter_tag_functions :
formatter -> unit -> formatter_tag_functions
;;
(** These functions are the basic ones: usual functions
operating on the standard formatter are defined via partial
evaluation of these primitives. For instance,
[print_string] is equal to [pp_print_string std_formatter]. *)
* { 6 [ printf ] like functions for pretty - printing . }
val fprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* [ fprintf ff fmt arg1 ... argN ] formats the arguments [ arg1 ] to [ argN ]
according to the format string [ fmt ] , and outputs the resulting string on
the formatter [ ff ] .
The format [ fmt ] is a character string which contains three types of
objects : plain characters and conversion specifications as specified in
the [ Printf ] module , and pretty - printing indications specific to the
[ Format ] module .
The pretty - printing indication characters are introduced by
a [ @ ] character , and their meanings are :
- [ @\ [ ] : open a pretty - printing box . The type and offset of the
box may be optionally specified with the following syntax :
the [ < ] character , followed by an optional box type indication ,
then an optional integer offset , and the closing [ > ] character .
Box type is one of [ h ] , [ v ] , [ hv ] , [ b ] , or [ hov ] ,
which stand respectively for an horizontal box , a vertical box ,
an ` ` horizontal - vertical '' box , or an ` ` horizontal or
vertical '' box ( [ b ] standing for an ` ` horizontal or
vertical '' box demonstrating indentation and [ hov ] standing
for a regular``horizontal or vertical '' box ) .
For instance , [ @\[<hov 2 > ] opens an ` ` horizontal or vertical ''
box with indentation 2 as obtained with [ open_hovbox 2 ] .
For more details about boxes , see the various box opening
functions [ open_*box ] .
- [ @\ ] ] : close the most recently opened pretty - printing box .
- [ @ , ] : output a good break as with [ print_cut ( ) ] .
- [ @ ] : output a space , as with [ print_space ( ) ] .
- [ @\n ] : force a newline , as with [ force_newline ( ) ] .
- [ @ ; ] : output a good break as with [ print_break ] . The
[ nspaces ] and [ offset ] parameters of the break may be
optionally specified with the following syntax :
the [ < ] character , followed by an integer [ nspaces ] value ,
then an integer [ offset ] , and a closing [ > ] character .
If no parameters are provided , the good break defaults to a
space .
- [ @ ? ] : flush the pretty printer as with [ print_flush ( ) ] .
This is equivalent to the conversion [ % ! ] .
- [ @. ] : flush the pretty printer and output a new line , as with
[ print_newline ( ) ] .
- [ @<n > ] : print the following item as if it were of length [ n ] .
Hence , [ printf " @<0>%s " arg ] is equivalent to [ print_as 0 arg ] .
If [ @<n > ] is not followed by a conversion specification ,
then the following character of the format is printed as if
it were of length [ n ] .
- [ @\ { ] : open a tag . The name of the tag may be optionally
specified with the following syntax :
the [ < ] character , followed by an optional string
specification , and the closing [ > ] character . The string
specification is any character string that does not contain the
closing character [ ' > ' ] . If omitted , the tag name defaults to the
empty string .
For more details about tags , see the functions [ open_tag ] and
[ close_tag ] .
- [ @\ } ] : close the most recently opened tag .
- [ @@ ] : print a plain [ @ ] character .
Example : [ printf " @[%s@ % d@]@. " " x = " 1 ] is equivalent to
[ open_box ( ) ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ] .
It prints [ x = 1 ] within a pretty - printing box .
according to the format string [fmt], and outputs the resulting string on
the formatter [ff].
The format [fmt] is a character string which contains three types of
objects: plain characters and conversion specifications as specified in
the [Printf] module, and pretty-printing indications specific to the
[Format] module.
The pretty-printing indication characters are introduced by
a [@] character, and their meanings are:
- [@\[]: open a pretty-printing box. The type and offset of the
box may be optionally specified with the following syntax:
the [<] character, followed by an optional box type indication,
then an optional integer offset, and the closing [>] character.
Box type is one of [h], [v], [hv], [b], or [hov],
which stand respectively for an horizontal box, a vertical box,
an ``horizontal-vertical'' box, or an ``horizontal or
vertical'' box ([b] standing for an ``horizontal or
vertical'' box demonstrating indentation and [hov] standing
for a regular``horizontal or vertical'' box).
For instance, [@\[<hov 2>] opens an ``horizontal or vertical''
box with indentation 2 as obtained with [open_hovbox 2].
For more details about boxes, see the various box opening
functions [open_*box].
- [@\]]: close the most recently opened pretty-printing box.
- [@,]: output a good break as with [print_cut ()].
- [@ ]: output a space, as with [print_space ()].
- [@\n]: force a newline, as with [force_newline ()].
- [@;]: output a good break as with [print_break]. The
[nspaces] and [offset] parameters of the break may be
optionally specified with the following syntax:
the [<] character, followed by an integer [nspaces] value,
then an integer [offset], and a closing [>] character.
If no parameters are provided, the good break defaults to a
space.
- [@?]: flush the pretty printer as with [print_flush ()].
This is equivalent to the conversion [%!].
- [@.]: flush the pretty printer and output a new line, as with
[print_newline ()].
- [@<n>]: print the following item as if it were of length [n].
Hence, [printf "@<0>%s" arg] is equivalent to [print_as 0 arg].
If [@<n>] is not followed by a conversion specification,
then the following character of the format is printed as if
it were of length [n].
- [@\{]: open a tag. The name of the tag may be optionally
specified with the following syntax:
the [<] character, followed by an optional string
specification, and the closing [>] character. The string
specification is any character string that does not contain the
closing character ['>']. If omitted, the tag name defaults to the
empty string.
For more details about tags, see the functions [open_tag] and
[close_tag].
- [@\}]: close the most recently opened tag.
- [@@]: print a plain [@] character.
Example: [printf "@[%s@ %d@]@." "x =" 1] is equivalent to
[open_box (); print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()].
It prints [x = 1] within a pretty-printing box.
*)
val printf : ('a, formatter, unit) format -> 'a;;
(** Same as [fprintf] above, but output on [std_formatter]. *)
val eprintf : ('a, formatter, unit) format -> 'a;;
(** Same as [fprintf] above, but output on [err_formatter]. *)
val sprintf : ('a, unit, string) format -> 'a;;
(** Same as [printf] above, but instead of printing on a formatter,
returns a string containing the result of formatting the arguments.
Note that the pretty-printer queue is flushed at the end of {e each
call} to [sprintf].
In case of multiple and related calls to [sprintf] to output
material on a single string, you should consider using [fprintf]
with the predefined formatter [str_formatter] and call
[flush_str_formatter ()] to get the final result.
Alternatively, you can use [Format.fprintf] with a formatter writing to a
buffer of your own: flushing the formatter and the buffer at the end of
pretty-printing returns the desired string. *)
val ifprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* Same as [ fprintf ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.10.0
Useful to ignore some material when conditionally printing.
@since 3.10.0
*)
(** Formatted output functions with continuations. *)
val kfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ fprintf ] above , but instead of returning immediately ,
passes the formatter to its first argument at the end of printing .
passes the formatter to its first argument at the end of printing. *)
val ikfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.12.0
Useful to ignore some material when conditionally printing.
@since 3.12.0
*)
val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
* Same as [ sprintf ] above , but instead of returning the string ,
passes it to the first argument .
passes it to the first argument. *)
* { 6 Deprecated }
val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a;;
* A deprecated and error prone function . Do not use it .
If you need to print to some buffer [ b ] , you must first define a
formatter writing to [ b ] , using [ let to_b = formatter_of_buffer b ] ; then
use regular calls to [ Format.fprintf ] on formatter [ to_b ] .
If you need to print to some buffer [b], you must first define a
formatter writing to [b], using [let to_b = formatter_of_buffer b]; then
use regular calls to [Format.fprintf] on formatter [to_b]. *)
val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
(** A deprecated synonym for [ksprintf]. *)
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/stdlib/format.mli | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
*********************************************************************
* [open_box d] opens a new pretty-printing box
with offset [d].
This box is the general purpose pretty-printing box.
Material in this box is displayed ``horizontal or vertical'':
break hints inside the box may lead to a new line, if there
is no more room on the line to print the remainder of the box,
or if a new line may lead to a new indentation
(demonstrating the indentation of the box).
When a new line is printed in the box, [d] is added to the
current indentation.
* Closes the most recently opened pretty-printing box.
* [print_string str] prints [str] in the current box.
* Prints an integer in the current box.
* Prints a floating point number in the current box.
* Prints a character in the current box.
* Prints a boolean in the current box.
* Inserts a break hint in a pretty-printing box.
[print_break nspaces offset] indicates that the line may
be split (a newline character is printed) at this point,
if the contents of the current box does not fit on the
current line.
If the line is split at that point, [offset] is added to
the current indentation. If the line is not split,
[nspaces] spaces are printed.
* Flushes the pretty printer: all opened boxes are closed,
and all pending text is displayed.
* Equivalent to [print_flush] followed by a new line.
* Forces a newline in the current box. Not the normal way of
pretty-printing, you should prefer break hints.
* Executes the next formatting command if the preceding line
has just been split. Otherwise, ignore the next formatting
command.
* Returns the position of the right margin.
* Return the value of the maximum indentation limit (in characters).
* Returns the maximum number of boxes allowed before ellipsis.
* Tests if the maximum number of boxes allowed have already been opened.
* [open_hbox ()] opens a new pretty-printing box.
This box is ``horizontal'': the line is not split in this box
(new lines may still occur inside boxes nested deeper).
* [open_vbox d] opens a new pretty-printing box
with offset [d].
This box is ``vertical'': every break hint inside this
box leads to a new line.
When a new line is printed in the box, [d] is added to the
current indentation.
* [open_hvbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal-vertical'': it behaves as an
``horizontal'' box if it fits on a single line,
otherwise it behaves as a ``vertical'' box.
When a new line is printed in the box, [d] is added to the
current indentation.
* [open_hovbox d] opens a new pretty-printing box
with offset [d].
This box is ``horizontal or vertical'': break hints
inside this box may lead to a new line, if there is no more room
on the line to print the remainder of the box.
When a new line is printed in the box, [d] is added to the
current indentation.
* Opens a tabulation box.
* Closes the most recently opened tabulation box.
* Sets a tabulation mark at the current insertion point.
* [print_tab ()] is equivalent to [print_tbreak 0 0].
* Set the text of the ellipsis printed when too many boxes
are opened (a single dot, [.], by default).
* Return the text of the ellipsis.
* [open_tag t] opens the tag named [t]; the [print_open_tag]
function of the formatter is called with [t] as argument;
the tag marker [mark_open_tag t] will be flushed into the output
device of the formatter.
* [close_tag ()] closes the most recently opened tag [t].
In addition, the [print_close_tag] function of the formatter is called
with [t] as argument. The marker [mark_close_tag t] will be flushed
into the output device of the formatter.
* [set_tags b] turns on or off the treatment of tags (default is off).
* [set_print_tags b] turns on or off the printing of tags, while
[set_mark_tags b] turns on or off the output of tag markers.
* Return the current status of tags printing and tags marking.
* Redirect the pretty-printer output to the given channel.
(All the output functions of the standard formatter are set to the
default output functions printing to the given channel.)
* [set_formatter_output_functions out flush] redirects the
relevant pretty-printer output functions to the functions [out] and
[flush].
The [out] function performs the pretty-printer string output. It is called
with a string [s], a start position [p], and a number of characters
[n]; it is supposed to output characters [p] to [p + n - 1] of
[s]. The [flush] function is called whenever the pretty-printer is
flushed (via conversion [%!], pretty-printing indications [@?] or [@.],
or using low level function [print_flush] or [print_newline]).
* Return the current output functions of the pretty-printer.
* The [Format] module is versatile enough to let you completely redefine
the meaning of pretty printing: you may provide your own functions to define
how to handle indentation, line breaking, and even printing of all the
characters that have to be printed!
* Return the current output functions of the pretty-printer,
including line breaking and indentation functions. Useful to record the
current setting and restore it afterwards.
* The tag handling functions specific to a formatter:
[mark] versions are the ``tag marking'' functions that associate a string
marker to a tag in order for the pretty-printing engine to flush
those markers as 0 length tokens in the output device of the formatter.
[print] versions are the ``tag printing'' functions that can perform
regular printing when a tag is closed or opened.
* [set_formatter_tag_functions tag_funs] changes the meaning of
opening and closing tags to use the functions in [tag_funs].
When opening a tag name [t], the string [t] is passed to the
opening tag marking function (the [mark_open_tag] field of the
record [tag_funs]), that must return the opening tag marker for
that name. When the next call to [close_tag ()] happens, the tag
name [t] is sent back to the closing tag marking function (the
[mark_close_tag] field of record [tag_funs]), that must return a
closing tag marker for that name.
The [print_] field of the record contains the functions that are
called at tag opening and tag closing time, to output regular
material in the pretty-printer queue.
* Return the current tag functions of the pretty-printer.
* Abstract data corresponding to a pretty-printer (also called a
formatter) and all its machinery.
Defining new pretty-printers permits unrelated output of material in
parallel on several output channels.
All the parameters of a pretty-printer are local to this pretty-printer:
margin, maximum indentation limit, maximum number of boxes
simultaneously opened, ellipsis, and so on, are specific to
each pretty-printer and may be fixed independently.
Given a [Pervasives.out_channel] output channel [oc], a new formatter
writing to that channel is simply obtained by calling
[formatter_of_out_channel oc].
Alternatively, the [make_formatter] function allocates a new
formatter with explicit output and flushing functions
(convenient to output material to strings for instance).
* [formatter_of_out_channel oc] returns a new formatter that
writes to the corresponding channel [oc].
* The standard formatter used by the formatting functions
above. It is defined as [formatter_of_out_channel stdout].
* A formatter to use with formatting functions below for
output to standard error. It is defined as
[formatter_of_out_channel stderr].
* [formatter_of_buffer b] returns a new formatter writing to
buffer [b]. As usual, the formatter has to be flushed at
the end of pretty printing, using [pp_print_flush] or
[pp_print_newline], to display all the pending material.
* The string buffer in which [str_formatter] writes.
* A formatter to use with formatting functions below for
output to the [stdbuf] string buffer.
[str_formatter] is defined as [formatter_of_buffer stdbuf].
* Returns the material printed with [str_formatter], flushes
the formatter and resets the corresponding buffer.
* [make_formatter out flush] returns a new formatter that writes according
to the output function [out], and the flushing function [flush]. For
instance, a formatter to the [Pervasives.out_channel] [oc] is returned by
[make_formatter (Pervasives.output oc) (fun () -> Pervasives.flush oc)].
* These functions are the basic ones: usual functions
operating on the standard formatter are defined via partial
evaluation of these primitives. For instance,
[print_string] is equal to [pp_print_string std_formatter].
* Same as [fprintf] above, but output on [std_formatter].
* Same as [fprintf] above, but output on [err_formatter].
* Same as [printf] above, but instead of printing on a formatter,
returns a string containing the result of formatting the arguments.
Note that the pretty-printer queue is flushed at the end of {e each
call} to [sprintf].
In case of multiple and related calls to [sprintf] to output
material on a single string, you should consider using [fprintf]
with the predefined formatter [str_formatter] and call
[flush_str_formatter ()] to get the final result.
Alternatively, you can use [Format.fprintf] with a formatter writing to a
buffer of your own: flushing the formatter and the buffer at the end of
pretty-printing returns the desired string.
* Formatted output functions with continuations.
* A deprecated synonym for [ksprintf]. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
* Pretty printing .
This module implements a pretty - printing facility to format text
within ` ` pretty - printing boxes '' . The pretty - printer breaks lines
at specified break hints , and indents lines according to the box
structure .
For a gentle introduction to the basics of pretty - printing using
[ Format ] , read
{ { : } } .
You may consider this module as providing an extension to the
[ printf ] facility to provide automatic line breaking . The addition of
pretty - printing annotations to your regular [ printf ] formats gives you
fancy indentation and line breaks .
Pretty - printing annotations are described below in the documentation of
the function { ! Format.fprintf } .
You may also use the explicit box management and printing functions
provided by this module . This style is more basic but more verbose
than the [ fprintf ] concise formats .
For instance , the sequence
[ open_box 0 ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ]
that prints [ x = 1 ] within a pretty - printing box , can be
abbreviated as [ printf " @[%s@ % i@]@. " " x = " 1 ] , or even shorter
[ printf " @[x = @ % i@]@. " 1 ] .
Rule of thumb for casual users of this library :
- use simple boxes ( as obtained by [ open_box 0 ] ) ;
- use simple break hints ( as obtained by [ print_cut ( ) ] that outputs a
simple break hint , or by [ print_space ( ) ] that outputs a space
indicating a break hint ) ;
- once a box is opened , display its material with basic printing
functions ( [ print_int ] and [ print_string ] ) ;
- when the material for a box has been printed , call [ close_box ( ) ] to
close the box ;
- at the end of your routine , flush the pretty - printer to display all the
remaining material , e.g. evaluate [ print_newline ( ) ] .
The behaviour of pretty - printing commands is unspecified
if there is no opened pretty - printing box . Each box opened via
one of the [ open _ ] functions below must be closed using [ close_box ]
for proper formatting . Otherwise , some of the material printed in the
boxes may not be output , or may be formatted incorrectly .
In case of interactive use , the system closes all opened boxes and
flushes all pending text ( as with the [ print_newline ] function )
after each phrase . Each phrase is therefore executed in the initial
state of the pretty - printer .
Warning : the material output by the following functions is delayed
in the pretty - printer queue in order to compute the proper line
breaking . Hence , you should not mix calls to the printing functions
of the basic I / O system with calls to the functions of this module :
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands .
This module implements a pretty-printing facility to format text
within ``pretty-printing boxes''. The pretty-printer breaks lines
at specified break hints, and indents lines according to the box
structure.
For a gentle introduction to the basics of pretty-printing using
[Format], read
{{:}}.
You may consider this module as providing an extension to the
[printf] facility to provide automatic line breaking. The addition of
pretty-printing annotations to your regular [printf] formats gives you
fancy indentation and line breaks.
Pretty-printing annotations are described below in the documentation of
the function {!Format.fprintf}.
You may also use the explicit box management and printing functions
provided by this module. This style is more basic but more verbose
than the [fprintf] concise formats.
For instance, the sequence
[open_box 0; print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()]
that prints [x = 1] within a pretty-printing box, can be
abbreviated as [printf "@[%s@ %i@]@." "x =" 1], or even shorter
[printf "@[x =@ %i@]@." 1].
Rule of thumb for casual users of this library:
- use simple boxes (as obtained by [open_box 0]);
- use simple break hints (as obtained by [print_cut ()] that outputs a
simple break hint, or by [print_space ()] that outputs a space
indicating a break hint);
- once a box is opened, display its material with basic printing
functions (e. g. [print_int] and [print_string]);
- when the material for a box has been printed, call [close_box ()] to
close the box;
- at the end of your routine, flush the pretty-printer to display all the
remaining material, e.g. evaluate [print_newline ()].
The behaviour of pretty-printing commands is unspecified
if there is no opened pretty-printing box. Each box opened via
one of the [open_] functions below must be closed using [close_box]
for proper formatting. Otherwise, some of the material printed in the
boxes may not be output, or may be formatted incorrectly.
In case of interactive use, the system closes all opened boxes and
flushes all pending text (as with the [print_newline] function)
after each phrase. Each phrase is therefore executed in the initial
state of the pretty-printer.
Warning: the material output by the following functions is delayed
in the pretty-printer queue in order to compute the proper line
breaking. Hence, you should not mix calls to the printing functions
of the basic I/O system with calls to the functions of this module:
this could result in some strange output seemingly unrelated with
the evaluation order of printing commands.
*)
* { 6 Boxes }
val open_box : int -> unit;;
val close_box : unit -> unit;;
* { 6 Formatting functions }
val print_string : string -> unit;;
val print_as : int -> string -> unit;;
* [ ] prints [ str ] in the
current box . The pretty - printer formats [ str ] as if
it were of length [ len ] .
current box. The pretty-printer formats [str] as if
it were of length [len]. *)
val print_int : int -> unit;;
val print_float : float -> unit;;
val print_char : char -> unit;;
val print_bool : bool -> unit;;
* { 6 Break hints }
val print_space : unit -> unit;;
* [ print_space ( ) ] is used to separate items ( typically to print
a space between two words ) .
It indicates that the line may be split at this
point . It either prints one space or splits the line .
It is equivalent to [ print_break 1 0 ] .
a space between two words).
It indicates that the line may be split at this
point. It either prints one space or splits the line.
It is equivalent to [print_break 1 0]. *)
val print_cut : unit -> unit;;
* [ print_cut ( ) ] is used to mark a good break position .
It indicates that the line may be split at this
point . It either prints nothing or splits the line .
This allows line splitting at the current
point , without printing spaces or adding indentation .
It is equivalent to [ print_break 0 0 ] .
It indicates that the line may be split at this
point. It either prints nothing or splits the line.
This allows line splitting at the current
point, without printing spaces or adding indentation.
It is equivalent to [print_break 0 0]. *)
val print_break : int -> int -> unit;;
val print_flush : unit -> unit;;
val print_newline : unit -> unit;;
val force_newline : unit -> unit;;
val print_if_newline : unit -> unit;;
* { 6 Margin }
val set_margin : int -> unit;;
* [ set_margin d ] sets the value of the right margin
to [ d ] ( in characters ): this value is used to detect line
overflows that leads to split lines .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the right margin is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
to [d] (in characters): this value is used to detect line
overflows that leads to split lines.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the right margin is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_margin : unit -> int;;
* { 6 Maximum indentation limit }
val set_max_indent : int -> unit;;
* [ set_max_indent d ] sets the value of the maximum
indentation limit to [ d ] ( in characters ):
once this limit is reached , boxes are rejected to the left ,
if they do not fit on the current line .
Nothing happens if [ d ] is smaller than 2 .
If [ d ] is too large , the limit is set to the maximum
admissible value ( which is greater than [ 10 ^ 10 ] ) .
indentation limit to [d] (in characters):
once this limit is reached, boxes are rejected to the left,
if they do not fit on the current line.
Nothing happens if [d] is smaller than 2.
If [d] is too large, the limit is set to the maximum
admissible value (which is greater than [10^10]). *)
val get_max_indent : unit -> int;;
* { 6 Formatting depth : maximum number of boxes allowed before ellipsis }
val set_max_boxes : int -> unit;;
* [ set_max_boxes max ] sets the maximum number
of boxes simultaneously opened .
Material inside boxes nested deeper is printed as an
ellipsis ( more precisely as the text returned by
[ get_ellipsis_text ( ) ] ) .
Nothing happens if [ max ] is smaller than 2 .
of boxes simultaneously opened.
Material inside boxes nested deeper is printed as an
ellipsis (more precisely as the text returned by
[get_ellipsis_text ()]).
Nothing happens if [max] is smaller than 2. *)
val get_max_boxes : unit -> int;;
val over_max_boxes : unit -> bool;;
* { 6 Advanced formatting }
val open_hbox : unit -> unit;;
val open_vbox : int -> unit;;
val open_hvbox : int -> unit;;
val open_hovbox : int -> unit;;
* { 6 Tabulations }
val open_tbox : unit -> unit;;
val close_tbox : unit -> unit;;
val print_tbreak : int -> int -> unit;;
* Break hint in a tabulation box .
[ print_tbreak spaces offset ] moves the insertion point to
the next tabulation ( [ spaces ] being added to this position ) .
Nothing occurs if insertion point is already on a
tabulation mark .
If there is no next tabulation on the line , then a newline
is printed and the insertion point moves to the first
tabulation of the box .
If a new line is printed , [ offset ] is added to the current
indentation .
[print_tbreak spaces offset] moves the insertion point to
the next tabulation ([spaces] being added to this position).
Nothing occurs if insertion point is already on a
tabulation mark.
If there is no next tabulation on the line, then a newline
is printed and the insertion point moves to the first
tabulation of the box.
If a new line is printed, [offset] is added to the current
indentation. *)
val set_tab : unit -> unit;;
val print_tab : unit -> unit;;
* { 6 Ellipsis }
val set_ellipsis_text : string -> unit;;
val get_ellipsis_text : unit -> string;;
* { 6 : tags Semantics Tags }
type tag = string;;
* { i Semantics tags } ( or simply { e tags } ) are used to decorate printed
entities for user 's defined purposes , e.g. setting font and giving size
indications for a display device , or marking delimitation of semantics
entities ( e.g. HTML or TeX elements or terminal escape sequences ) .
By default , those tags do not influence line breaking calculation :
the tag ` ` markers '' are not considered as part of the printing
material that drives line breaking ( in other words , the length of
those strings is considered as zero for line breaking ) .
Thus , tag handling is in some sense transparent to pretty - printing
and does not interfere with usual pretty - printing . Hence , a single
pretty printing routine can output both simple ` ` verbatim ''
material or richer decorated output depending on the treatment of
tags . By default , tags are not active , hence the output is not
decorated with tag information . Once [ set_tags ] is set to [ true ] ,
the pretty printer engine honours tags and decorates the output
accordingly .
When a tag has been opened ( or closed ) , it is both and successively
` ` printed '' and ` ` marked '' . Printing a tag means calling a
formatter specific function with the name of the tag as argument :
that ` ` tag printing '' function can then print any regular material
to the formatter ( so that this material is enqueued as usual in the
formatter queue for further line - breaking computation ) . Marking a
tag means to output an arbitrary string ( the ` ` tag marker '' ) ,
directly into the output device of the formatter . Hence , the
formatter specific ` ` tag marking '' function must return the tag
marker string associated to its tag argument . Being flushed
directly into the output device of the formatter , tag marker
strings are not considered as part of the printing material that
drives line breaking ( in other words , the length of the strings
corresponding to tag markers is considered as zero for line
breaking ) . In addition , advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines , and
precisely when the queue is flushed into the output device .
In the spirit of HTML tags , the default tag marking functions
output tags enclosed in " < " and " > " : hence , the opening marker of
tag [ t ] is [ " < t > " ] and the closing marker [ " < /t > " ] .
tag printing functions just do nothing .
Tag marking and tag printing functions are user definable and can
be set by calling [ set_formatter_tag_functions ] .
entities for user's defined purposes, e.g. setting font and giving size
indications for a display device, or marking delimitation of semantics
entities (e.g. HTML or TeX elements or terminal escape sequences).
By default, those tags do not influence line breaking calculation:
the tag ``markers'' are not considered as part of the printing
material that drives line breaking (in other words, the length of
those strings is considered as zero for line breaking).
Thus, tag handling is in some sense transparent to pretty-printing
and does not interfere with usual pretty-printing. Hence, a single
pretty printing routine can output both simple ``verbatim''
material or richer decorated output depending on the treatment of
tags. By default, tags are not active, hence the output is not
decorated with tag information. Once [set_tags] is set to [true],
the pretty printer engine honours tags and decorates the output
accordingly.
When a tag has been opened (or closed), it is both and successively
``printed'' and ``marked''. Printing a tag means calling a
formatter specific function with the name of the tag as argument:
that ``tag printing'' function can then print any regular material
to the formatter (so that this material is enqueued as usual in the
formatter queue for further line-breaking computation). Marking a
tag means to output an arbitrary string (the ``tag marker''),
directly into the output device of the formatter. Hence, the
formatter specific ``tag marking'' function must return the tag
marker string associated to its tag argument. Being flushed
directly into the output device of the formatter, tag marker
strings are not considered as part of the printing material that
drives line breaking (in other words, the length of the strings
corresponding to tag markers is considered as zero for line
breaking). In addition, advanced users may take advantage of
the specificity of tag markers to be precisely output when the
pretty printer has already decided where to break the lines, and
precisely when the queue is flushed into the output device.
In the spirit of HTML tags, the default tag marking functions
output tags enclosed in "<" and ">": hence, the opening marker of
tag [t] is ["<t>"] and the closing marker ["</t>"].
Default tag printing functions just do nothing.
Tag marking and tag printing functions are user definable and can
be set by calling [set_formatter_tag_functions]. *)
val open_tag : tag -> unit;;
val close_tag : unit -> unit;;
val set_tags : bool -> unit;;
val set_print_tags : bool -> unit;;
val set_mark_tags : bool -> unit;;
val get_print_tags : unit -> bool;;
val get_mark_tags : unit -> bool;;
* { 6 Redirecting the standard formatter output }
val set_formatter_out_channel : Pervasives.out_channel -> unit;;
val set_formatter_output_functions :
(string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
val get_formatter_output_functions :
unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
* { 6 : meaning Changing the meaning of standard formatter pretty printing }
val set_all_formatter_output_functions :
out:(string -> int -> int -> unit) ->
flush:(unit -> unit) ->
newline:(unit -> unit) ->
spaces:(int -> unit) ->
unit
;;
* [ set_all_formatter_output_functions out flush outnewline outspace ]
redirects the pretty - printer output to the functions [ out ] and
[ flush ] as described in [ set_formatter_output_functions ] . In
addition , the pretty - printer function that outputs a newline is set
to the function [ outnewline ] and the function that outputs
indentation spaces is set to the function [ outspace ] .
This way , you can change the meaning of indentation ( which can be
something else than just printing space characters ) and the
meaning of new lines opening ( which can be connected to any other
action needed by the application at hand ) . The two functions
[ outspace ] and [ outnewline ] are normally connected to [ out ] and
[ flush ] : respective default values for [ outspace ] and [ outnewline ]
are [ out ( String.make n ' ' ) 0 n ] and [ out " \n " 0 1 ] .
redirects the pretty-printer output to the functions [out] and
[flush] as described in [set_formatter_output_functions]. In
addition, the pretty-printer function that outputs a newline is set
to the function [outnewline] and the function that outputs
indentation spaces is set to the function [outspace].
This way, you can change the meaning of indentation (which can be
something else than just printing space characters) and the
meaning of new lines opening (which can be connected to any other
action needed by the application at hand). The two functions
[outspace] and [outnewline] are normally connected to [out] and
[flush]: respective default values for [outspace] and [outnewline]
are [out (String.make n ' ') 0 n] and [out "\n" 0 1]. *)
val get_all_formatter_output_functions :
unit ->
(string -> int -> int -> unit) *
(unit -> unit) *
(unit -> unit) *
(int -> unit)
;;
* { 6 : tags Changing the meaning of printing semantics tags }
type formatter_tag_functions = {
mark_open_tag : tag -> string;
mark_close_tag : tag -> string;
print_open_tag : tag -> unit;
print_close_tag : tag -> unit;
}
;;
val set_formatter_tag_functions :
formatter_tag_functions -> unit
;;
val get_formatter_tag_functions :
unit -> formatter_tag_functions
;;
* { 6 Multiple formatted output }
type formatter;;
val formatter_of_out_channel : out_channel -> formatter;;
val std_formatter : formatter;;
val err_formatter : formatter;;
val formatter_of_buffer : Buffer.t -> formatter;;
val stdbuf : Buffer.t;;
val str_formatter : formatter;;
val flush_str_formatter : unit -> string;;
val make_formatter :
(string -> int -> int -> unit) -> (unit -> unit) -> formatter
;;
* { 6 Basic functions to use with formatters }
val pp_open_hbox : formatter -> unit -> unit;;
val pp_open_vbox : formatter -> int -> unit;;
val pp_open_hvbox : formatter -> int -> unit;;
val pp_open_hovbox : formatter -> int -> unit;;
val pp_open_box : formatter -> int -> unit;;
val pp_close_box : formatter -> unit -> unit;;
val pp_open_tag : formatter -> string -> unit;;
val pp_close_tag : formatter -> unit -> unit;;
val pp_print_string : formatter -> string -> unit;;
val pp_print_as : formatter -> int -> string -> unit;;
val pp_print_int : formatter -> int -> unit;;
val pp_print_float : formatter -> float -> unit;;
val pp_print_char : formatter -> char -> unit;;
val pp_print_bool : formatter -> bool -> unit;;
val pp_print_break : formatter -> int -> int -> unit;;
val pp_print_cut : formatter -> unit -> unit;;
val pp_print_space : formatter -> unit -> unit;;
val pp_force_newline : formatter -> unit -> unit;;
val pp_print_flush : formatter -> unit -> unit;;
val pp_print_newline : formatter -> unit -> unit;;
val pp_print_if_newline : formatter -> unit -> unit;;
val pp_open_tbox : formatter -> unit -> unit;;
val pp_close_tbox : formatter -> unit -> unit;;
val pp_print_tbreak : formatter -> int -> int -> unit;;
val pp_set_tab : formatter -> unit -> unit;;
val pp_print_tab : formatter -> unit -> unit;;
val pp_set_tags : formatter -> bool -> unit;;
val pp_set_print_tags : formatter -> bool -> unit;;
val pp_set_mark_tags : formatter -> bool -> unit;;
val pp_get_print_tags : formatter -> unit -> bool;;
val pp_get_mark_tags : formatter -> unit -> bool;;
val pp_set_margin : formatter -> int -> unit;;
val pp_get_margin : formatter -> unit -> int;;
val pp_set_max_indent : formatter -> int -> unit;;
val pp_get_max_indent : formatter -> unit -> int;;
val pp_set_max_boxes : formatter -> int -> unit;;
val pp_get_max_boxes : formatter -> unit -> int;;
val pp_over_max_boxes : formatter -> unit -> bool;;
val pp_set_ellipsis_text : formatter -> string -> unit;;
val pp_get_ellipsis_text : formatter -> unit -> string;;
val pp_set_formatter_out_channel : formatter -> Pervasives.out_channel -> unit;;
val pp_set_formatter_output_functions :
formatter -> (string -> int -> int -> unit) -> (unit -> unit) -> unit
;;
val pp_get_formatter_output_functions :
formatter -> unit -> (string -> int -> int -> unit) * (unit -> unit)
;;
val pp_set_all_formatter_output_functions :
formatter -> out:(string -> int -> int -> unit) -> flush:(unit -> unit) ->
newline:(unit -> unit) -> spaces:(int -> unit) -> unit
;;
val pp_get_all_formatter_output_functions :
formatter -> unit ->
(string -> int -> int -> unit) * (unit -> unit) * (unit -> unit) *
(int -> unit)
;;
val pp_set_formatter_tag_functions :
formatter -> formatter_tag_functions -> unit
;;
val pp_get_formatter_tag_functions :
formatter -> unit -> formatter_tag_functions
;;
* { 6 [ printf ] like functions for pretty - printing . }
val fprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* [ fprintf ff fmt arg1 ... argN ] formats the arguments [ arg1 ] to [ argN ]
according to the format string [ fmt ] , and outputs the resulting string on
the formatter [ ff ] .
The format [ fmt ] is a character string which contains three types of
objects : plain characters and conversion specifications as specified in
the [ Printf ] module , and pretty - printing indications specific to the
[ Format ] module .
The pretty - printing indication characters are introduced by
a [ @ ] character , and their meanings are :
- [ @\ [ ] : open a pretty - printing box . The type and offset of the
box may be optionally specified with the following syntax :
the [ < ] character , followed by an optional box type indication ,
then an optional integer offset , and the closing [ > ] character .
Box type is one of [ h ] , [ v ] , [ hv ] , [ b ] , or [ hov ] ,
which stand respectively for an horizontal box , a vertical box ,
an ` ` horizontal - vertical '' box , or an ` ` horizontal or
vertical '' box ( [ b ] standing for an ` ` horizontal or
vertical '' box demonstrating indentation and [ hov ] standing
for a regular``horizontal or vertical '' box ) .
For instance , [ @\[<hov 2 > ] opens an ` ` horizontal or vertical ''
box with indentation 2 as obtained with [ open_hovbox 2 ] .
For more details about boxes , see the various box opening
functions [ open_*box ] .
- [ @\ ] ] : close the most recently opened pretty - printing box .
- [ @ , ] : output a good break as with [ print_cut ( ) ] .
- [ @ ] : output a space , as with [ print_space ( ) ] .
- [ @\n ] : force a newline , as with [ force_newline ( ) ] .
- [ @ ; ] : output a good break as with [ print_break ] . The
[ nspaces ] and [ offset ] parameters of the break may be
optionally specified with the following syntax :
the [ < ] character , followed by an integer [ nspaces ] value ,
then an integer [ offset ] , and a closing [ > ] character .
If no parameters are provided , the good break defaults to a
space .
- [ @ ? ] : flush the pretty printer as with [ print_flush ( ) ] .
This is equivalent to the conversion [ % ! ] .
- [ @. ] : flush the pretty printer and output a new line , as with
[ print_newline ( ) ] .
- [ @<n > ] : print the following item as if it were of length [ n ] .
Hence , [ printf " @<0>%s " arg ] is equivalent to [ print_as 0 arg ] .
If [ @<n > ] is not followed by a conversion specification ,
then the following character of the format is printed as if
it were of length [ n ] .
- [ @\ { ] : open a tag . The name of the tag may be optionally
specified with the following syntax :
the [ < ] character , followed by an optional string
specification , and the closing [ > ] character . The string
specification is any character string that does not contain the
closing character [ ' > ' ] . If omitted , the tag name defaults to the
empty string .
For more details about tags , see the functions [ open_tag ] and
[ close_tag ] .
- [ @\ } ] : close the most recently opened tag .
- [ @@ ] : print a plain [ @ ] character .
Example : [ printf " @[%s@ % d@]@. " " x = " 1 ] is equivalent to
[ open_box ( ) ; print_string " x = " ; print_space ( ) ;
print_int 1 ; close_box ( ) ; print_newline ( ) ] .
It prints [ x = 1 ] within a pretty - printing box .
according to the format string [fmt], and outputs the resulting string on
the formatter [ff].
The format [fmt] is a character string which contains three types of
objects: plain characters and conversion specifications as specified in
the [Printf] module, and pretty-printing indications specific to the
[Format] module.
The pretty-printing indication characters are introduced by
a [@] character, and their meanings are:
- [@\[]: open a pretty-printing box. The type and offset of the
box may be optionally specified with the following syntax:
the [<] character, followed by an optional box type indication,
then an optional integer offset, and the closing [>] character.
Box type is one of [h], [v], [hv], [b], or [hov],
which stand respectively for an horizontal box, a vertical box,
an ``horizontal-vertical'' box, or an ``horizontal or
vertical'' box ([b] standing for an ``horizontal or
vertical'' box demonstrating indentation and [hov] standing
for a regular``horizontal or vertical'' box).
For instance, [@\[<hov 2>] opens an ``horizontal or vertical''
box with indentation 2 as obtained with [open_hovbox 2].
For more details about boxes, see the various box opening
functions [open_*box].
- [@\]]: close the most recently opened pretty-printing box.
- [@,]: output a good break as with [print_cut ()].
- [@ ]: output a space, as with [print_space ()].
- [@\n]: force a newline, as with [force_newline ()].
- [@;]: output a good break as with [print_break]. The
[nspaces] and [offset] parameters of the break may be
optionally specified with the following syntax:
the [<] character, followed by an integer [nspaces] value,
then an integer [offset], and a closing [>] character.
If no parameters are provided, the good break defaults to a
space.
- [@?]: flush the pretty printer as with [print_flush ()].
This is equivalent to the conversion [%!].
- [@.]: flush the pretty printer and output a new line, as with
[print_newline ()].
- [@<n>]: print the following item as if it were of length [n].
Hence, [printf "@<0>%s" arg] is equivalent to [print_as 0 arg].
If [@<n>] is not followed by a conversion specification,
then the following character of the format is printed as if
it were of length [n].
- [@\{]: open a tag. The name of the tag may be optionally
specified with the following syntax:
the [<] character, followed by an optional string
specification, and the closing [>] character. The string
specification is any character string that does not contain the
closing character ['>']. If omitted, the tag name defaults to the
empty string.
For more details about tags, see the functions [open_tag] and
[close_tag].
- [@\}]: close the most recently opened tag.
- [@@]: print a plain [@] character.
Example: [printf "@[%s@ %d@]@." "x =" 1] is equivalent to
[open_box (); print_string "x ="; print_space ();
print_int 1; close_box (); print_newline ()].
It prints [x = 1] within a pretty-printing box.
*)
val printf : ('a, formatter, unit) format -> 'a;;
val eprintf : ('a, formatter, unit) format -> 'a;;
val sprintf : ('a, unit, string) format -> 'a;;
val ifprintf : formatter -> ('a, formatter, unit) format -> 'a;;
* Same as [ fprintf ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.10.0
Useful to ignore some material when conditionally printing.
@since 3.10.0
*)
val kfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ fprintf ] above , but instead of returning immediately ,
passes the formatter to its first argument at the end of printing .
passes the formatter to its first argument at the end of printing. *)
val ikfprintf : (formatter -> 'a) -> formatter ->
('b, formatter, unit, 'a) format4 -> 'b
;;
* Same as [ ] above , but does not print anything .
Useful to ignore some material when conditionally printing .
@since 3.12.0
Useful to ignore some material when conditionally printing.
@since 3.12.0
*)
val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
* Same as [ sprintf ] above , but instead of returning the string ,
passes it to the first argument .
passes it to the first argument. *)
* { 6 Deprecated }
val bprintf : Buffer.t -> ('a, formatter, unit) format -> 'a;;
* A deprecated and error prone function . Do not use it .
If you need to print to some buffer [ b ] , you must first define a
formatter writing to [ b ] , using [ let to_b = formatter_of_buffer b ] ; then
use regular calls to [ Format.fprintf ] on formatter [ to_b ] .
If you need to print to some buffer [b], you must first define a
formatter writing to [b], using [let to_b = formatter_of_buffer b]; then
use regular calls to [Format.fprintf] on formatter [to_b]. *)
val kprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b;;
|
50f3ff3ed0369422df988cfa7b1509869195ef77292cbe21b287b385dc44a581 | andersfugmann/ppx_protocol_conv | unittest.ml | module type Test_module = sig
module Make : functor (Driver : Testable.Driver) -> sig
val unittest: unit Alcotest.test
end
end
let verbose = false
module Make(Driver : Testable.Driver) = struct
let test_modules : (module Test_module) list =
[
(module Test_arrays);
(module Test_driver);
(module Test_lists);
(module Test_nonrec);
(module Test_option_unit);
(module Test_param_types);
(module Test_poly);
(module Test_record);
(module Test_sig);
(module Test_types);
(module Test_unit);
(module Test_variant);
(module Test_result);
(module Test_exceptions);
]
(* Create a list of tests *)
let run ?(extra = []) () =
let tests =
List.map (fun (module Test : Test_module) ->
let module T = Test.Make(Driver) in
T.unittest)
test_modules
in
let tests = tests @ extra in
open_out "unittest.output" |> close_out;
Alcotest.run Driver.name tests
end
| null | https://raw.githubusercontent.com/andersfugmann/ppx_protocol_conv/e93eb01ca8ba8c7dd734070316cd281a199dee0d/test/unittest.ml | ocaml | Create a list of tests | module type Test_module = sig
module Make : functor (Driver : Testable.Driver) -> sig
val unittest: unit Alcotest.test
end
end
let verbose = false
module Make(Driver : Testable.Driver) = struct
let test_modules : (module Test_module) list =
[
(module Test_arrays);
(module Test_driver);
(module Test_lists);
(module Test_nonrec);
(module Test_option_unit);
(module Test_param_types);
(module Test_poly);
(module Test_record);
(module Test_sig);
(module Test_types);
(module Test_unit);
(module Test_variant);
(module Test_result);
(module Test_exceptions);
]
let run ?(extra = []) () =
let tests =
List.map (fun (module Test : Test_module) ->
let module T = Test.Make(Driver) in
T.unittest)
test_modules
in
let tests = tests @ extra in
open_out "unittest.output" |> close_out;
Alcotest.run Driver.name tests
end
|
75980ff76a63e3013ffbc34733663f035bb4f32de0458e2f654703caf7819adc | cyga/real-world-haskell | tempfile.7.hs | -- file: ch07/tempfile.7.hs
-- This extension enables us to tell the compiler about the types in
-- lambda expresions
# LANGUAGE ScopedTypeVariables #
import System.IO
import System.Directory(getTemporaryDirectory, removeFile)
catch is removed from system . IO.Error in ghc > 7
-- see #no1
import System . IO.Error(catch )
import Control.Exception(IOException,catch,finally)
-- The main entry point. Work with a temp file in myAction.
main :: IO ()
main = withTempFile "mytemp.txt" myAction
{- The guts of the program. Called with the path and handle of a temporary
file. When this function exits, that file will be closed and deleted
because myAction was called from withTempFile. -}
myAction :: FilePath -> Handle -> IO ()
myAction tempname temph =
do -- Start by displaying a greeting on the terminal
putStrLn "Welcome to tempfile.hs"
putStrLn $ "I have a temporary file at " ++ tempname
-- Let's see what the initial position is
pos <- hTell temph
putStrLn $ "My initial position is " ++ show pos
-- Now, write some data to the temporary file
let tempdata = show [1..10]
putStrLn $ "Writing one line containing " ++
show (length tempdata) ++ " bytes: " ++
tempdata
hPutStrLn temph tempdata
-- Get our new position. This doesn't actually modify pos
-- in memory, but makes the name "pos" correspond to a different
-- value for the remainder of the "do" block.
pos <- hTell temph
putStrLn $ "After writing, my new position is " ++ show pos
-- Seek to the beginning of the file and display it
putStrLn $ "The file content is: "
hSeek temph AbsoluteSeek 0
-- hGetContents performs a lazy read of the entire file
c <- hGetContents temph
-- Copy the file byte-for-byte to stdout, followed by \n
putStrLn c
Let 's also display it as a Haskell literal
putStrLn $ "Which could be expressed as this Haskell literal:"
print c
This function takes two parameters : a filename pattern and another
function . It will create a temporary file , and pass the name and Handle
of that file to the given function .
The temporary file is created with openTempFile . The directory is the one
indicated by getTemporaryDirectory , or , if the system has no notion of
a temporary directory , " . " is used . The given pattern is passed to
openTempFile .
After the given function terminates , even if it terminates due to an
exception , the Handle is closed and the file is deleted .
function. It will create a temporary file, and pass the name and Handle
of that file to the given function.
The temporary file is created with openTempFile. The directory is the one
indicated by getTemporaryDirectory, or, if the system has no notion of
a temporary directory, "." is used. The given pattern is passed to
openTempFile.
After the given function terminates, even if it terminates due to an
exception, the Handle is closed and the file is deleted. -}
withTempFile :: String -> (FilePath -> Handle -> IO a) -> IO a
withTempFile pattern func =
do -- The library ref says that getTemporaryDirectory may raise on
-- exception on systems that have no notion of a temporary directory.
-- So, we run getTemporaryDirectory under catch. catch takes
two functions : one to run , and a different one to run if the
-- first raised an exception. If getTemporaryDirectory raised an
-- exception, just use "." (the current working directory).
The catch version in Control . Exception has a type of
-- Exception e => IO a -> (e -> IO a) -> IO a
-- so the old catch expression won't type check
tempdir <- catch (getTemporaryDirectory) (\(_ :: IOException) -> return ".")
(tempfile, temph) <- openTempFile tempdir pattern
Call ( func ) to perform the action on the temporary
file . finally takes two actions . The first is the action to run .
The second is an action to run after the first , regardless of
whether the first action raised an exception . This way , we ensure
-- the temporary file is always deleted. The return value from finally
is the first action 's return value .
finally (func tempfile temph)
(do hClose temph
removeFile tempfile)
| null | https://raw.githubusercontent.com/cyga/real-world-haskell/4ed581af5b96c6ef03f20d763b8de26be69d43d9/ch07/tempfile.7.hs | haskell | file: ch07/tempfile.7.hs
This extension enables us to tell the compiler about the types in
lambda expresions
see #no1
The main entry point. Work with a temp file in myAction.
The guts of the program. Called with the path and handle of a temporary
file. When this function exits, that file will be closed and deleted
because myAction was called from withTempFile.
Start by displaying a greeting on the terminal
Let's see what the initial position is
Now, write some data to the temporary file
Get our new position. This doesn't actually modify pos
in memory, but makes the name "pos" correspond to a different
value for the remainder of the "do" block.
Seek to the beginning of the file and display it
hGetContents performs a lazy read of the entire file
Copy the file byte-for-byte to stdout, followed by \n
The library ref says that getTemporaryDirectory may raise on
exception on systems that have no notion of a temporary directory.
So, we run getTemporaryDirectory under catch. catch takes
first raised an exception. If getTemporaryDirectory raised an
exception, just use "." (the current working directory).
Exception e => IO a -> (e -> IO a) -> IO a
so the old catch expression won't type check
the temporary file is always deleted. The return value from finally | # LANGUAGE ScopedTypeVariables #
import System.IO
import System.Directory(getTemporaryDirectory, removeFile)
catch is removed from system . IO.Error in ghc > 7
import System . IO.Error(catch )
import Control.Exception(IOException,catch,finally)
main :: IO ()
main = withTempFile "mytemp.txt" myAction
myAction :: FilePath -> Handle -> IO ()
myAction tempname temph =
putStrLn "Welcome to tempfile.hs"
putStrLn $ "I have a temporary file at " ++ tempname
pos <- hTell temph
putStrLn $ "My initial position is " ++ show pos
let tempdata = show [1..10]
putStrLn $ "Writing one line containing " ++
show (length tempdata) ++ " bytes: " ++
tempdata
hPutStrLn temph tempdata
pos <- hTell temph
putStrLn $ "After writing, my new position is " ++ show pos
putStrLn $ "The file content is: "
hSeek temph AbsoluteSeek 0
c <- hGetContents temph
putStrLn c
Let 's also display it as a Haskell literal
putStrLn $ "Which could be expressed as this Haskell literal:"
print c
This function takes two parameters : a filename pattern and another
function . It will create a temporary file , and pass the name and Handle
of that file to the given function .
The temporary file is created with openTempFile . The directory is the one
indicated by getTemporaryDirectory , or , if the system has no notion of
a temporary directory , " . " is used . The given pattern is passed to
openTempFile .
After the given function terminates , even if it terminates due to an
exception , the Handle is closed and the file is deleted .
function. It will create a temporary file, and pass the name and Handle
of that file to the given function.
The temporary file is created with openTempFile. The directory is the one
indicated by getTemporaryDirectory, or, if the system has no notion of
a temporary directory, "." is used. The given pattern is passed to
openTempFile.
After the given function terminates, even if it terminates due to an
exception, the Handle is closed and the file is deleted. -}
withTempFile :: String -> (FilePath -> Handle -> IO a) -> IO a
withTempFile pattern func =
two functions : one to run , and a different one to run if the
The catch version in Control . Exception has a type of
tempdir <- catch (getTemporaryDirectory) (\(_ :: IOException) -> return ".")
(tempfile, temph) <- openTempFile tempdir pattern
Call ( func ) to perform the action on the temporary
file . finally takes two actions . The first is the action to run .
The second is an action to run after the first , regardless of
whether the first action raised an exception . This way , we ensure
is the first action 's return value .
finally (func tempfile temph)
(do hClose temph
removeFile tempfile)
|
31ce3317f40afe69c81a4986c1b380df27b4b8f54f9c5f1fad87b8ead877ff66 | euhmeuh/rilouworld | database.rkt | #lang racket/base
(provide
sprite-ref
make-database)
(require
racket/class
racket/function
pkg/lib
anaphoric
mode-lambda/static
rilouworld/private/utils/log
rilouworld/private/utils/struct
(prefix-in quest: rilouworld/quest))
(define (sprite-ref name index)
(string->symbol (format "~a/~a" name index)))
(define (add-placeholder-sprite! sprite-db)
(add-sprite!/file
sprite-db
'missing-image-placeholder
(build-path (pkg-directory "rilouworld")
"private/core/missing-image-placeholder.png")
#:palette 'palette))
(define (make-database resources)
(define sprite-db (make-sprite-db))
(add-palette!/file sprite-db 'palette (build-path "." "worlds" "palette.png"))
(add-placeholder-sprite! sprite-db)
(for-each
(lambda (resource)
(cond
[(quest:animation? resource) (handle-animation resource sprite-db)]
[(quest:image? resource) (handle-image resource sprite-db)]
[else (void)]))
resources)
(compile-sprite-db sprite-db))
(define (handle-image image sprite-db)
(with-values image (name path) from quest:resource
(set! path (build-path "." "worlds" path))
(if (file-exists? path)
(add-sprite!/file sprite-db
name
path
#:palette 'palette)
(warning 'sprite-build
"Could not find file '~a' for image '~a'." path name))))
(define (handle-animation animation sprite-db)
(with-values animation (name path) from quest:resource
(with-values animation (size) from quest:animation
(set! path (build-path "." "worlds" path))
(aif (open-bitmap path)
(for ([bitmap (cut-image-in-parts it size)]
[index (in-naturals)])
(add-sprite!/bm sprite-db
(sprite-ref name index)
(thunk bitmap)
#:palette 'palette))
(warning 'sprite-build
"Could not find file '~a' for animation '~a'." path name)))))
(define (open-bitmap path)
(local-require racket/draw)
(and (file-exists? path)
(read-bitmap path)))
(define (cut-image-in-parts bitmap size)
(local-require racket/draw)
(with-values size (w h) from quest:size
(define-values (bm-w bm-h) (bitmap-size bitmap))
(define-values (tiles-w tiles-h) (values (quotient bm-w w)
(quotient bm-h h)))
(for/list ([x (in-range 0 (* tiles-w tiles-h))])
(cut-image bitmap
(* (remainder x tiles-w) w)
(* (quotient x tiles-w) h)
w
h))))
(define (bitmap-size bitmap)
(local-require racket/draw)
(values (send bitmap get-width)
(send bitmap get-height)))
(define (cut-image bitmap x y w h)
(local-require racket/draw)
(let* ([result (make-bitmap w h)]
[dc (new bitmap-dc% [bitmap result])])
(send dc draw-bitmap-section bitmap 0 0 x y w h)
result))
| null | https://raw.githubusercontent.com/euhmeuh/rilouworld/184dea6c187f4f94da6616b89ec15cc8ba6bb786/private/core/database.rkt | racket | #lang racket/base
(provide
sprite-ref
make-database)
(require
racket/class
racket/function
pkg/lib
anaphoric
mode-lambda/static
rilouworld/private/utils/log
rilouworld/private/utils/struct
(prefix-in quest: rilouworld/quest))
(define (sprite-ref name index)
(string->symbol (format "~a/~a" name index)))
(define (add-placeholder-sprite! sprite-db)
(add-sprite!/file
sprite-db
'missing-image-placeholder
(build-path (pkg-directory "rilouworld")
"private/core/missing-image-placeholder.png")
#:palette 'palette))
(define (make-database resources)
(define sprite-db (make-sprite-db))
(add-palette!/file sprite-db 'palette (build-path "." "worlds" "palette.png"))
(add-placeholder-sprite! sprite-db)
(for-each
(lambda (resource)
(cond
[(quest:animation? resource) (handle-animation resource sprite-db)]
[(quest:image? resource) (handle-image resource sprite-db)]
[else (void)]))
resources)
(compile-sprite-db sprite-db))
(define (handle-image image sprite-db)
(with-values image (name path) from quest:resource
(set! path (build-path "." "worlds" path))
(if (file-exists? path)
(add-sprite!/file sprite-db
name
path
#:palette 'palette)
(warning 'sprite-build
"Could not find file '~a' for image '~a'." path name))))
(define (handle-animation animation sprite-db)
(with-values animation (name path) from quest:resource
(with-values animation (size) from quest:animation
(set! path (build-path "." "worlds" path))
(aif (open-bitmap path)
(for ([bitmap (cut-image-in-parts it size)]
[index (in-naturals)])
(add-sprite!/bm sprite-db
(sprite-ref name index)
(thunk bitmap)
#:palette 'palette))
(warning 'sprite-build
"Could not find file '~a' for animation '~a'." path name)))))
(define (open-bitmap path)
(local-require racket/draw)
(and (file-exists? path)
(read-bitmap path)))
(define (cut-image-in-parts bitmap size)
(local-require racket/draw)
(with-values size (w h) from quest:size
(define-values (bm-w bm-h) (bitmap-size bitmap))
(define-values (tiles-w tiles-h) (values (quotient bm-w w)
(quotient bm-h h)))
(for/list ([x (in-range 0 (* tiles-w tiles-h))])
(cut-image bitmap
(* (remainder x tiles-w) w)
(* (quotient x tiles-w) h)
w
h))))
(define (bitmap-size bitmap)
(local-require racket/draw)
(values (send bitmap get-width)
(send bitmap get-height)))
(define (cut-image bitmap x y w h)
(local-require racket/draw)
(let* ([result (make-bitmap w h)]
[dc (new bitmap-dc% [bitmap result])])
(send dc draw-bitmap-section bitmap 0 0 x y w h)
result))
|
|
368d11d1b464da0a1cb374f3ad11ef977221ccc05fa0970f92ac8c25c310b7f6 | modular-macros/ocaml-macros | unused_types.ml | module Unused : sig
end = struct
type unused = int
end
;;
module Unused_nonrec : sig
end = struct
type nonrec used = int
type nonrec unused = used
end
;;
module Unused_rec : sig
end = struct
type unused = A of unused
end
;;
module Unused_exception : sig
end = struct
exception Nobody_uses_me
end
;;
module Unused_extension_constructor : sig
type t = ..
end = struct
type t = ..
type t += Nobody_uses_me
end
;;
module Unused_exception_outside_patterns : sig
val falsity : exn -> bool
end = struct
exception Nobody_constructs_me
let falsity = function
| Nobody_constructs_me -> true
| _ -> false
end
;;
module Unused_extension_outside_patterns : sig
type t = ..
val falsity : t -> bool
end = struct
type t = ..
type t += Nobody_constructs_me
let falsity = function
| Nobody_constructs_me -> true
| _ -> false
end
;;
module Unused_private_exception : sig
type exn += private Private_exn
end = struct
exception Private_exn
end
;;
module Unused_private_extension : sig
type t = ..
type t += private Private_ext
end = struct
type t = ..
type t += Private_ext
end
;;
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/testsuite/tests/typing-warnings/unused_types.ml | ocaml | module Unused : sig
end = struct
type unused = int
end
;;
module Unused_nonrec : sig
end = struct
type nonrec used = int
type nonrec unused = used
end
;;
module Unused_rec : sig
end = struct
type unused = A of unused
end
;;
module Unused_exception : sig
end = struct
exception Nobody_uses_me
end
;;
module Unused_extension_constructor : sig
type t = ..
end = struct
type t = ..
type t += Nobody_uses_me
end
;;
module Unused_exception_outside_patterns : sig
val falsity : exn -> bool
end = struct
exception Nobody_constructs_me
let falsity = function
| Nobody_constructs_me -> true
| _ -> false
end
;;
module Unused_extension_outside_patterns : sig
type t = ..
val falsity : t -> bool
end = struct
type t = ..
type t += Nobody_constructs_me
let falsity = function
| Nobody_constructs_me -> true
| _ -> false
end
;;
module Unused_private_exception : sig
type exn += private Private_exn
end = struct
exception Private_exn
end
;;
module Unused_private_extension : sig
type t = ..
type t += private Private_ext
end = struct
type t = ..
type t += Private_ext
end
;;
|
|
0ec8a6d804834c62a42c82ae16c46b493e8d5612b62f76d9a16b084480d22ac3 | rowangithub/DOrder | up-nested.ml | let rec loopa i j n =
if ( j <= n ) then
// tmpl("le(i , j , k , n ) " ) ;
// i = 0 ;
// k = 0 ;
// i = 0;
// k = 0;*)
if ( i >= 0) then
while ( i < n ) {
// tmpl("le(i , j , k , n ) " ) ;
assert ( k>=i ) ;
i++ ;
;
}
while( i < n ) {
// tmpl("le(i,j,k,n)");
assert( k>=i);
i++;
k++;
}
*)
loopa i (j+1) n
else loopa i j n
else assert( i>= 0)
let main j n =
let i = 0 in
let k = 0 in
if ( j<=n ) then
loopa i j n
else ()
(*
j = 0;
while( j < n ) {
// tmpl("le(i,j,k,n)");
assert(k>0);
j++;
k--;
}
*)
let _ = main 3 6
let _ = main 4 5
let _ = main (-1) (-2) | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/folprograms/invgen/up-nested.ml | ocaml |
j = 0;
while( j < n ) {
// tmpl("le(i,j,k,n)");
assert(k>0);
j++;
k--;
}
| let rec loopa i j n =
if ( j <= n ) then
// tmpl("le(i , j , k , n ) " ) ;
// i = 0 ;
// k = 0 ;
// i = 0;
// k = 0;*)
if ( i >= 0) then
while ( i < n ) {
// tmpl("le(i , j , k , n ) " ) ;
assert ( k>=i ) ;
i++ ;
;
}
while( i < n ) {
// tmpl("le(i,j,k,n)");
assert( k>=i);
i++;
k++;
}
*)
loopa i (j+1) n
else loopa i j n
else assert( i>= 0)
let main j n =
let i = 0 in
let k = 0 in
if ( j<=n ) then
loopa i j n
else ()
let _ = main 3 6
let _ = main 4 5
let _ = main (-1) (-2) |
38356e789b71dee08e5a4a72de12e2d95ded2c86e3825cad21596a70e0702644 | jackfirth/lens | string.rkt | #lang racket/base
(require racket/contract/base)
(provide (contract-out
[string-ref-lens
(-> exact-nonnegative-integer?
(lens/c immutable-string? char?))]
[string-pick-lens
(->* [] #:rest (listof exact-nonnegative-integer?)
(lens/c immutable-string? immutable-string?))]
))
(require fancy-app
lens/private/base/main
lens/private/compound/main
"../util/immutable.rkt"
"../string/join-string.rkt")
(module+ test
(require rackunit lens/private/test-util/test-lens))
(define (string-ref-lens i)
(make-lens
(string-ref _ i)
(string-set _ i _)))
(define (string-set s i c)
(build-immutable-string
(string-length s)
(λ (j)
(if (= i j)
c
(string-ref s j)))))
(module+ test
(check-lens-view (string-ref-lens 2) "abc" #\c)
(check-lens-set (string-ref-lens 0) "abc" #\A "Abc"))
(define (string-pick-lens . is)
(apply lens-join/string (map string-ref-lens is)))
(module+ test
(define 1-5-6-lens (string-pick-lens 1 5 6))
(check-lens-view 1-5-6-lens "abcdefg"
"bfg")
(check-lens-set 1-5-6-lens "abcdefg" "BFG"
"aBcdeFG"))
| null | https://raw.githubusercontent.com/jackfirth/lens/733db7744921409b69ddc78ae5b23ffaa6b91e37/lens-data/lens/private/string/string.rkt | racket | #lang racket/base
(require racket/contract/base)
(provide (contract-out
[string-ref-lens
(-> exact-nonnegative-integer?
(lens/c immutable-string? char?))]
[string-pick-lens
(->* [] #:rest (listof exact-nonnegative-integer?)
(lens/c immutable-string? immutable-string?))]
))
(require fancy-app
lens/private/base/main
lens/private/compound/main
"../util/immutable.rkt"
"../string/join-string.rkt")
(module+ test
(require rackunit lens/private/test-util/test-lens))
(define (string-ref-lens i)
(make-lens
(string-ref _ i)
(string-set _ i _)))
(define (string-set s i c)
(build-immutable-string
(string-length s)
(λ (j)
(if (= i j)
c
(string-ref s j)))))
(module+ test
(check-lens-view (string-ref-lens 2) "abc" #\c)
(check-lens-set (string-ref-lens 0) "abc" #\A "Abc"))
(define (string-pick-lens . is)
(apply lens-join/string (map string-ref-lens is)))
(module+ test
(define 1-5-6-lens (string-pick-lens 1 5 6))
(check-lens-view 1-5-6-lens "abcdefg"
"bfg")
(check-lens-set 1-5-6-lens "abcdefg" "BFG"
"aBcdeFG"))
|
|
ef19ac3a3e5b93996f5fa4d0dbb44ad7961b8b1b1a48446269a5f8ec7662ffa6 | ferd/sups | sups_worker_sup.erl | -module(sups_worker_sup).
-export([start_link/0, init/1]).
-behaviour(supervisor).
start_link() -> supervisor:start_link(?MODULE, []).
init([]) ->
{ok, {#{strategy => one_for_one, intensity => 5, period => 10},
[#{id => worker1,
start => {sups_worker, start_link, []},
restart => permanent, modules => [sups_worker]}]
}}.
| null | https://raw.githubusercontent.com/ferd/sups/8f365c3b3079a3e52a15ffe13ac70621e2c31e38/src/sups_worker_sup.erl | erlang | -module(sups_worker_sup).
-export([start_link/0, init/1]).
-behaviour(supervisor).
start_link() -> supervisor:start_link(?MODULE, []).
init([]) ->
{ok, {#{strategy => one_for_one, intensity => 5, period => 10},
[#{id => worker1,
start => {sups_worker, start_link, []},
restart => permanent, modules => [sups_worker]}]
}}.
|
|
b80c822ce3f5e78de52896b5c004174f08798864e4b85de511260f735ef5771b | marigold-dev/mankavar | naive.ml | module type REDUCER = sig
type t
type msg
val reduce : msg -> t -> t
end
module Message = struct
module A = struct
type t =
| Add_i of int
| Add_b
end
module B = struct
type t = int
end
module AB = struct
type t = A of A.t | B of B.t
end
end
module type B_FOR_A = sig
type t
val get : t -> int
end
module A_make(B : B_FOR_A) = struct
type msg = Message.A.t
type b = B.t
type t = b * int * int
let reduce msg (bt , bc , c) = match msg with
| Message.A.Add_i i -> bt , bc , c + i
| Add_b -> bt , bc , c + (B.get bt)
end
module type A = sig
type b
include
module type of A_make(val (Obj.magic ()) : B_FOR_A with type t = b)
with type b := b
end
module type A_FOR_B = sig
type t
val add : int -> t -> t
end
module B_make(A : A_FOR_B) = struct
type a = A.t
type t = a * int
type msg = Message.B.t
let reduce i (at , c) =
A.add i at , c + i
end
module type B = sig
type a
include
module type of B_make(val (Obj.magic ()) : A_FOR_B with type t = a)
with type a := a
end
module AB = struct
module rec A : A = A_make(AB.B_for_A)
and B : B = B_make(AB.A_for_B)
and AB : sig
type t = A.t * B.t
module A_for_B : A_FOR_B
module B_for_A : B_FOR_A
val make : A.t -> B.t -> t
end = struct
type t = A.t * B.t
let make x y = x , y
module A_for_B : A_FOR_B = struct
type nonrec t = t
let add i ((bt , bc , c) , b) = ((bt , bc + i , c) , b)
end
module B_for_A : B_FOR_A = struct
type nonrec t = t
let get (_a , (_ , c)) = c
end
end
end
Does n't work .
- Too are cursed in OCaml
- Alternative would be an effectful interface
Doesn't work.
- Too Verbose
- Recursive Values are cursed in OCaml
- Alternative would be an effectful interface
*) | null | https://raw.githubusercontent.com/marigold-dev/mankavar/31ef2cc7dbdaa6646e4aa07915d10b38a7470d10/experiments/state_management/naive.ml | ocaml | module type REDUCER = sig
type t
type msg
val reduce : msg -> t -> t
end
module Message = struct
module A = struct
type t =
| Add_i of int
| Add_b
end
module B = struct
type t = int
end
module AB = struct
type t = A of A.t | B of B.t
end
end
module type B_FOR_A = sig
type t
val get : t -> int
end
module A_make(B : B_FOR_A) = struct
type msg = Message.A.t
type b = B.t
type t = b * int * int
let reduce msg (bt , bc , c) = match msg with
| Message.A.Add_i i -> bt , bc , c + i
| Add_b -> bt , bc , c + (B.get bt)
end
module type A = sig
type b
include
module type of A_make(val (Obj.magic ()) : B_FOR_A with type t = b)
with type b := b
end
module type A_FOR_B = sig
type t
val add : int -> t -> t
end
module B_make(A : A_FOR_B) = struct
type a = A.t
type t = a * int
type msg = Message.B.t
let reduce i (at , c) =
A.add i at , c + i
end
module type B = sig
type a
include
module type of B_make(val (Obj.magic ()) : A_FOR_B with type t = a)
with type a := a
end
module AB = struct
module rec A : A = A_make(AB.B_for_A)
and B : B = B_make(AB.A_for_B)
and AB : sig
type t = A.t * B.t
module A_for_B : A_FOR_B
module B_for_A : B_FOR_A
val make : A.t -> B.t -> t
end = struct
type t = A.t * B.t
let make x y = x , y
module A_for_B : A_FOR_B = struct
type nonrec t = t
let add i ((bt , bc , c) , b) = ((bt , bc + i , c) , b)
end
module B_for_A : B_FOR_A = struct
type nonrec t = t
let get (_a , (_ , c)) = c
end
end
end
Does n't work .
- Too are cursed in OCaml
- Alternative would be an effectful interface
Doesn't work.
- Too Verbose
- Recursive Values are cursed in OCaml
- Alternative would be an effectful interface
*) |
|
1e22deee1ba10e80503e26f215c2762103fe2fce5c2410f96018ef84261d3d20 | screenshotbot/screenshotbot-oss | package.lisp | ;; Copyright 2018-Present Modern Interpreters Inc.
;;
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
#+nil
(defpackage :screenshotbot-sdk
(:export #:main))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/0577066b0b5613cd41899dc38b36c41501048c72/src/screenshotbot/sdk/package.lisp | lisp | Copyright 2018-Present Modern Interpreters Inc.
| This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
#+nil
(defpackage :screenshotbot-sdk
(:export #:main))
|
6c4d6972c906a6065c0128066011c55fe339721e6ba8504e674a117001458235 | wilbowma/cur | defs.rkt | #lang racket
(require
scribble/base)
(provide todo omit title* section* subsubsub*section*)
;; TODO: made this disable-able in main.scrbl via parameters or
;; something
(define (todo . x)
(void)
( apply margin - note * " TODO : " x ) )
(define-syntax (omit syn) #'(void))
(define (first-word x)
(first (string-split (first x) #px"\\W")))
(define (title* . x)
(apply title #:tag
(format "sec:~a" (string-downcase (first-word x)))
x))
TODO : really , tag should be sec : section : subsection
(define (section* . x)
(apply section #:tag
(format "subsec:~a" (string-downcase (first-word x)))
x))
(define (subsubsub*section* . x)
#;(apply elem #:style "SSubSubSubSection" x)
(list ~ (apply subsubsub*section x)))
| null | https://raw.githubusercontent.com/wilbowma/cur/e039c98941b3d272c6e462387df22846e10b0128/cur-paper/defs.rkt | racket | TODO: made this disable-able in main.scrbl via parameters or
something
(apply elem #:style "SSubSubSubSection" x) | #lang racket
(require
scribble/base)
(provide todo omit title* section* subsubsub*section*)
(define (todo . x)
(void)
( apply margin - note * " TODO : " x ) )
(define-syntax (omit syn) #'(void))
(define (first-word x)
(first (string-split (first x) #px"\\W")))
(define (title* . x)
(apply title #:tag
(format "sec:~a" (string-downcase (first-word x)))
x))
TODO : really , tag should be sec : section : subsection
(define (section* . x)
(apply section #:tag
(format "subsec:~a" (string-downcase (first-word x)))
x))
(define (subsubsub*section* . x)
(list ~ (apply subsubsub*section x)))
|
7449618d64a8d02d4f974c06d022c1500368a919ad06e037bdaa103e333bd0f6 | dorchard/effect-monad | State.hs | # LANGUAGE InstanceSigs #
module Control.Effect.Parameterised.State where
-- Bye Monads... as we know them
import Prelude hiding (Monad(..))
import Control.Effect.Parameterised
newtype State s1 s2 a = State { runState :: s1 -> (a, s2) }
State parameterised monad
-- ... just like the
instance PMonad State where
return :: a -> State s s a
return x = State (\s -> (x, s))
(>>=) :: State s1 s2 a -> (a -> State s2 s3 b) -> State s1 s3 b
(State m) >>= k =
State $ \s0 -> let (a, s1) = m s0
State m' = k a in m' s1
| null | https://raw.githubusercontent.com/dorchard/effect-monad/5750ef8438f750e528002a0a4e255514cbf3150a/src/Control/Effect/Parameterised/State.hs | haskell | Bye Monads... as we know them
... just like the | # LANGUAGE InstanceSigs #
module Control.Effect.Parameterised.State where
import Prelude hiding (Monad(..))
import Control.Effect.Parameterised
newtype State s1 s2 a = State { runState :: s1 -> (a, s2) }
State parameterised monad
instance PMonad State where
return :: a -> State s s a
return x = State (\s -> (x, s))
(>>=) :: State s1 s2 a -> (a -> State s2 s3 b) -> State s1 s3 b
(State m) >>= k =
State $ \s0 -> let (a, s1) = m s0
State m' = k a in m' s1
|
edb6586e5dc749ee5d78c75765c41d6b38eb66ce163fe98736f03c4aebadff7c | isavita/category-theory-for-programmers-with-erlang | ch4.erl | -module(ch4).
-compile(export_all).
Explicite logger example
negate_with_log(X, Log) -> {not X, Log ++ "Not so!"}.
% Aggregated logger between function calls
negate_with_agg_log(X) -> {not X, "Not so!"}.
to_upper_case(String) -> string:to_upper(String).
to_words(Sentence) ->
Words =
lists:foldl(
fun(Splitter, Words) ->
lists:filtermap(
fun(Word) ->
case string:split(Word, Splitter, all) of
[[]] -> false;
Result -> {true, Result}
end
end,
Words
)
end,
[Sentence],
["...", "!", ";", "?", ".", ",", " "]
),
case Words of
"" -> "";
_ -> hd(Words)
end.
-record(optional, {value, is_valid}).
safe_reciprocal(X) ->
if
X == 0 -> #optional{is_valid=false};
true -> #optional{value=1/X, is_valid=true}
end.
safe_root(X) ->
if
X > 0 -> #optional{value=math:sqrt(X), is_valid=true};
true -> #optional{is_valid=false}
end.
compose(F1, F2) ->
fun(X) ->
case F1(X) of
{optional, Value, true} -> F2(Value);
_ -> #optional{is_valid=false}
end
end.
safe_root_reciprocal(X) -> (compose(fun safe_root/1, fun safe_reciprocal/1))(X).
| null | https://raw.githubusercontent.com/isavita/category-theory-for-programmers-with-erlang/4ffa11dd9ffc77e6a909ccf36e19bdfd5af117ce/ch4.erl | erlang | Aggregated logger between function calls | -module(ch4).
-compile(export_all).
Explicite logger example
negate_with_log(X, Log) -> {not X, Log ++ "Not so!"}.
negate_with_agg_log(X) -> {not X, "Not so!"}.
to_upper_case(String) -> string:to_upper(String).
to_words(Sentence) ->
Words =
lists:foldl(
fun(Splitter, Words) ->
lists:filtermap(
fun(Word) ->
case string:split(Word, Splitter, all) of
[[]] -> false;
Result -> {true, Result}
end
end,
Words
)
end,
[Sentence],
["...", "!", ";", "?", ".", ",", " "]
),
case Words of
"" -> "";
_ -> hd(Words)
end.
-record(optional, {value, is_valid}).
safe_reciprocal(X) ->
if
X == 0 -> #optional{is_valid=false};
true -> #optional{value=1/X, is_valid=true}
end.
safe_root(X) ->
if
X > 0 -> #optional{value=math:sqrt(X), is_valid=true};
true -> #optional{is_valid=false}
end.
compose(F1, F2) ->
fun(X) ->
case F1(X) of
{optional, Value, true} -> F2(Value);
_ -> #optional{is_valid=false}
end
end.
safe_root_reciprocal(X) -> (compose(fun safe_root/1, fun safe_reciprocal/1))(X).
|
22450aa3257f4232af41a91f323c9fdbb01ab494a98f72730e7a06f536ac9936 | esl/MongooseIM | mongoose_graphql_roster_user_mutation.erl | -module(mongoose_graphql_roster_user_mutation).
-behaviour(mongoose_graphql).
-export([execute/4]).
-ignore_xref([execute/4]).
-import(mongoose_graphql_helper, [make_error/2, format_result/2, null_to_default/2]).
execute(Ctx, _Obj, <<"addContact">>, Args) ->
add_contact(Ctx, Args);
execute(Ctx, _Obj, <<"addContacts">>, Args) ->
add_contacts(Ctx, Args);
execute(Ctx, _Obj, <<"subscription">>, Args) ->
subscription(Ctx, Args);
execute(Ctx, _Obj, <<"deleteContact">>, Args) ->
delete_contact(Ctx, Args);
execute(Ctx, _Obj, <<"deleteContacts">>, Args) ->
delete_contacts(Ctx, Args).
-spec add_contact(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:binary_result().
add_contact(#{user := UserJID}, #{<<"contact">> := ContactJID,
<<"name">> := Name,
<<"groups">> := Groups}) ->
mongoose_graphql_roster:add_contact(UserJID, ContactJID, Name, Groups).
-spec add_contacts(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:list_binary_result().
add_contacts(#{user := UserJID}, #{<<"contacts">> := Contacts}) ->
{ok, [mongoose_graphql_roster:add_contact(UserJID, ContactJID, Name, Groups)
|| #{<<"jid">> := ContactJID, <<"name">> := Name, <<"groups">> := Groups} <- Contacts]}.
-spec subscription(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:binary_result().
subscription(#{user := UserJID}, #{<<"contact">> := ContactJID, <<"action">> := Action}) ->
Type = mongoose_graphql_roster:translate_sub_action(Action),
Res = mod_roster_api:subscription(UserJID, ContactJID, Type),
format_result(Res, #{contact => jid:to_binary(ContactJID)}).
-spec delete_contact(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:binary_result().
delete_contact(#{user := UserJID}, #{<<"contact">> := ContactJID}) ->
mongoose_graphql_roster:delete_contact(UserJID, ContactJID).
-spec delete_contacts(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:list_binary_result().
delete_contacts(#{user := UserJID}, #{<<"contacts">> := ContactJIDs}) ->
{ok, [mongoose_graphql_roster:delete_contact(UserJID, ContactJID)
|| ContactJID <- ContactJIDs]}.
| null | https://raw.githubusercontent.com/esl/MongooseIM/891f7ab9ca5e7b41be5da9550152fec1590b0b22/src/graphql/user/mongoose_graphql_roster_user_mutation.erl | erlang | -module(mongoose_graphql_roster_user_mutation).
-behaviour(mongoose_graphql).
-export([execute/4]).
-ignore_xref([execute/4]).
-import(mongoose_graphql_helper, [make_error/2, format_result/2, null_to_default/2]).
execute(Ctx, _Obj, <<"addContact">>, Args) ->
add_contact(Ctx, Args);
execute(Ctx, _Obj, <<"addContacts">>, Args) ->
add_contacts(Ctx, Args);
execute(Ctx, _Obj, <<"subscription">>, Args) ->
subscription(Ctx, Args);
execute(Ctx, _Obj, <<"deleteContact">>, Args) ->
delete_contact(Ctx, Args);
execute(Ctx, _Obj, <<"deleteContacts">>, Args) ->
delete_contacts(Ctx, Args).
-spec add_contact(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:binary_result().
add_contact(#{user := UserJID}, #{<<"contact">> := ContactJID,
<<"name">> := Name,
<<"groups">> := Groups}) ->
mongoose_graphql_roster:add_contact(UserJID, ContactJID, Name, Groups).
-spec add_contacts(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:list_binary_result().
add_contacts(#{user := UserJID}, #{<<"contacts">> := Contacts}) ->
{ok, [mongoose_graphql_roster:add_contact(UserJID, ContactJID, Name, Groups)
|| #{<<"jid">> := ContactJID, <<"name">> := Name, <<"groups">> := Groups} <- Contacts]}.
-spec subscription(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:binary_result().
subscription(#{user := UserJID}, #{<<"contact">> := ContactJID, <<"action">> := Action}) ->
Type = mongoose_graphql_roster:translate_sub_action(Action),
Res = mod_roster_api:subscription(UserJID, ContactJID, Type),
format_result(Res, #{contact => jid:to_binary(ContactJID)}).
-spec delete_contact(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:binary_result().
delete_contact(#{user := UserJID}, #{<<"contact">> := ContactJID}) ->
mongoose_graphql_roster:delete_contact(UserJID, ContactJID).
-spec delete_contacts(mongoose_graphql:context(), mongoose_graphql:args()) ->
mongoose_graphql_roster:list_binary_result().
delete_contacts(#{user := UserJID}, #{<<"contacts">> := ContactJIDs}) ->
{ok, [mongoose_graphql_roster:delete_contact(UserJID, ContactJID)
|| ContactJID <- ContactJIDs]}.
|
|
84909c169580d26c901c7710b986b2194c4a2c7960cff68dbe3a2351de2bfbc6 | dhess/sicp-solutions | ex2.46.scm | (define (make-vect x y)
(cons x y))
(define (xcor-vect v)
(car v))
(define (ycor-vect v)
(cdr v))
(define (add-vect v1 v2)
(make-vect (+ (xcor-vect v1)
(xcor-vect v2))
(+ (ycor-vect v1)
(ycor-vect v2))))
(define (scale-vect s v)
(make-vect (* s (xcor-vect v))
(* s (ycor-vect v))))
(define (sub-vect v1 v2)
(add-vect v1
(scale-vect -1 v2)))
| null | https://raw.githubusercontent.com/dhess/sicp-solutions/2cf78db98917e9cb1252efda76fddc8e45fe4140/chap2/ex2.46.scm | scheme | (define (make-vect x y)
(cons x y))
(define (xcor-vect v)
(car v))
(define (ycor-vect v)
(cdr v))
(define (add-vect v1 v2)
(make-vect (+ (xcor-vect v1)
(xcor-vect v2))
(+ (ycor-vect v1)
(ycor-vect v2))))
(define (scale-vect s v)
(make-vect (* s (xcor-vect v))
(* s (ycor-vect v))))
(define (sub-vect v1 v2)
(add-vect v1
(scale-vect -1 v2)))
|
|
ce2eca0afb334551a51dbf4b8496bdf186a56eaf85ce2c76e3a2ef297e773a60 | mzp/coq-ruby | csymtable.mli | open Names
open Term
open Pre_env
val val_of_constr : env -> constr -> values
val set_opaque_const : constant -> unit
val set_transparent_const : constant -> unit
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/kernel/csymtable.mli | ocaml | open Names
open Term
open Pre_env
val val_of_constr : env -> constr -> values
val set_opaque_const : constant -> unit
val set_transparent_const : constant -> unit
|
|
33010bc7aee38e9f828645bb3bd2d8b2c8562cdc3cf3e86c6365c1780051132c | maxlapshin/fix | fix_proxy_client.erl | -module(fix_proxy_client).
-include("../include/business.hrl").
-include("../include/fix.hrl").
-export([run/2]).
run(Exchange, Symbol) ->
{ok, Pid} = fix_connection:start_link(self(), fix:get_value(fix_proxy)),
fix_connection:logon(Pid),
fix_connection:subscribe(Pid, Exchange, Symbol),
loop(Pid).
loop(Pid) ->
receive
#fix{pid = Pid, message = #market_data_snapshot_full_refresh{md_entries = MdEntries}} ->
Bid = [Entry || Entry <- MdEntries, proplists:get_value(md_entry_type,Entry) == bid],
Ask = [Entry || Entry <- MdEntries, proplists:get_value(md_entry_type,Entry) == offer],
if
length(Bid) > 0 andalso length(Ask) > 0 ->
[BestBid|_] = Bid,
BestBidSize = proplists:get_value(md_entry_size, BestBid),
BestBidPrice = proplists:get_value(md_entry_px, BestBid),
[BestAsk|_] = Ask,
BestAskSize = proplists:get_value(md_entry_size, BestAsk),
BestAskPrice = proplists:get_value(md_entry_px, BestAsk),
io:format("~6.. B@~.3f ~6.. B@~.3f (~B deep)~n", [BestBidSize, BestBidPrice*1.0, BestAskSize, BestAskPrice*1.0, length(MdEntries)]),
ok;
true ->
io:format("Trade~n")
end,
ok;
Else ->
io:format("Else: ~p~n", [Else])
end,
loop(Pid).
| null | https://raw.githubusercontent.com/maxlapshin/fix/4b5208c7c11528fe477954f48152a1922cf17630/src/fix_proxy_client.erl | erlang | -module(fix_proxy_client).
-include("../include/business.hrl").
-include("../include/fix.hrl").
-export([run/2]).
run(Exchange, Symbol) ->
{ok, Pid} = fix_connection:start_link(self(), fix:get_value(fix_proxy)),
fix_connection:logon(Pid),
fix_connection:subscribe(Pid, Exchange, Symbol),
loop(Pid).
loop(Pid) ->
receive
#fix{pid = Pid, message = #market_data_snapshot_full_refresh{md_entries = MdEntries}} ->
Bid = [Entry || Entry <- MdEntries, proplists:get_value(md_entry_type,Entry) == bid],
Ask = [Entry || Entry <- MdEntries, proplists:get_value(md_entry_type,Entry) == offer],
if
length(Bid) > 0 andalso length(Ask) > 0 ->
[BestBid|_] = Bid,
BestBidSize = proplists:get_value(md_entry_size, BestBid),
BestBidPrice = proplists:get_value(md_entry_px, BestBid),
[BestAsk|_] = Ask,
BestAskSize = proplists:get_value(md_entry_size, BestAsk),
BestAskPrice = proplists:get_value(md_entry_px, BestAsk),
io:format("~6.. B@~.3f ~6.. B@~.3f (~B deep)~n", [BestBidSize, BestBidPrice*1.0, BestAskSize, BestAskPrice*1.0, length(MdEntries)]),
ok;
true ->
io:format("Trade~n")
end,
ok;
Else ->
io:format("Else: ~p~n", [Else])
end,
loop(Pid).
|
|
adf94e44afb58334ae097bae8e0c546e8f69d5f43ab0f726e2b933a7704e2539 | ucsd-progsys/dsolve | outcometree.mli | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : outcometree.mli , v 1.15 2006/04/05 02:28:13 garrigue Exp $
(* Module [Outcometree]: results displayed by the toplevel *)
These types represent messages that the toplevel displays as normal
results or errors . The real displaying is customisable using the hooks :
[ Toploop.print_out_value ]
[ Toploop.print_out_type ]
[ Toploop.print_out_sig_item ]
[ Toploop.print_out_phrase ]
results or errors. The real displaying is customisable using the hooks:
[Toploop.print_out_value]
[Toploop.print_out_type]
[Toploop.print_out_sig_item]
[Toploop.print_out_phrase] *)
type out_ident =
| Oide_apply of out_ident * out_ident
| Oide_dot of out_ident * string
| Oide_ident of string
type out_value =
| Oval_array of out_value list
| Oval_char of char
| Oval_constr of out_ident * out_value list
| Oval_ellipsis
| Oval_float of float
| Oval_int of int
| Oval_int32 of int32
| Oval_int64 of int64
| Oval_nativeint of nativeint
| Oval_list of out_value list
| Oval_printer of (Format.formatter -> unit)
| Oval_record of (out_ident * out_value) list
| Oval_string of string
| Oval_stuff of string
| Oval_tuple of out_value list
| Oval_variant of string * out_value option
type out_type =
| Otyp_abstract
| Otyp_alias of out_type * string
| Otyp_arrow of string * out_type * out_type
| Otyp_class of bool * out_ident * out_type list
| Otyp_constr of out_ident * out_type list * out_qualifier option
| Otyp_manifest of out_type * out_type
| Otyp_object of (string * out_type) list * bool option
| Otyp_record of (string * bool * out_type) list
| Otyp_stuff of string
| Otyp_sum of (string * out_type list) list
| Otyp_tuple of out_type list * out_qualifier option
| Otyp_var of bool * string
| Otyp_variant of
bool * out_variant * bool * (string list) option
| Otyp_poly of string list * out_type
and out_variant =
| Ovar_fields of (string * bool * out_type list) list
| Ovar_name of out_ident * out_type list
and out_qualifier =
string list
type out_class_type =
| Octy_constr of out_ident * out_type list
| Octy_fun of string * out_type * out_class_type
| Octy_signature of out_type option * out_class_sig_item list
and out_class_sig_item =
| Ocsg_constraint of out_type * out_type
| Ocsg_method of string * bool * bool * out_type
| Ocsg_value of string * bool * bool * out_type
type out_module_type =
| Omty_abstract
| Omty_functor of string * out_module_type * out_module_type
| Omty_ident of out_ident
| Omty_signature of out_sig_item list
and out_sig_item =
| Osig_class of
bool * string * (string * (bool * bool)) list * out_class_type *
out_rec_status
| Osig_class_type of
bool * string * (string * (bool * bool)) list * out_class_type *
out_rec_status
| Osig_exception of string * out_type list
| Osig_modtype of string * out_module_type
| Osig_module of string * out_module_type * out_rec_status
| Osig_type of out_type_decl * out_rec_status
| Osig_value of string * out_type * string list
and out_type_decl =
string * (string * (bool * bool)) list * out_type * Asttypes.private_flag *
(out_type * out_type) list
and out_rec_status =
| Orec_not
| Orec_first
| Orec_next
type out_phrase =
| Ophr_eval of out_value * out_type
| Ophr_signature of (out_sig_item * out_value option) list
| Ophr_exception of (exn * out_value)
| null | https://raw.githubusercontent.com/ucsd-progsys/dsolve/bfbbb8ed9bbf352d74561e9f9127ab07b7882c0c/typing/outcometree.mli | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Module [Outcometree]: results displayed by the toplevel | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : outcometree.mli , v 1.15 2006/04/05 02:28:13 garrigue Exp $
These types represent messages that the toplevel displays as normal
results or errors . The real displaying is customisable using the hooks :
[ Toploop.print_out_value ]
[ Toploop.print_out_type ]
[ Toploop.print_out_sig_item ]
[ Toploop.print_out_phrase ]
results or errors. The real displaying is customisable using the hooks:
[Toploop.print_out_value]
[Toploop.print_out_type]
[Toploop.print_out_sig_item]
[Toploop.print_out_phrase] *)
type out_ident =
| Oide_apply of out_ident * out_ident
| Oide_dot of out_ident * string
| Oide_ident of string
type out_value =
| Oval_array of out_value list
| Oval_char of char
| Oval_constr of out_ident * out_value list
| Oval_ellipsis
| Oval_float of float
| Oval_int of int
| Oval_int32 of int32
| Oval_int64 of int64
| Oval_nativeint of nativeint
| Oval_list of out_value list
| Oval_printer of (Format.formatter -> unit)
| Oval_record of (out_ident * out_value) list
| Oval_string of string
| Oval_stuff of string
| Oval_tuple of out_value list
| Oval_variant of string * out_value option
type out_type =
| Otyp_abstract
| Otyp_alias of out_type * string
| Otyp_arrow of string * out_type * out_type
| Otyp_class of bool * out_ident * out_type list
| Otyp_constr of out_ident * out_type list * out_qualifier option
| Otyp_manifest of out_type * out_type
| Otyp_object of (string * out_type) list * bool option
| Otyp_record of (string * bool * out_type) list
| Otyp_stuff of string
| Otyp_sum of (string * out_type list) list
| Otyp_tuple of out_type list * out_qualifier option
| Otyp_var of bool * string
| Otyp_variant of
bool * out_variant * bool * (string list) option
| Otyp_poly of string list * out_type
and out_variant =
| Ovar_fields of (string * bool * out_type list) list
| Ovar_name of out_ident * out_type list
and out_qualifier =
string list
type out_class_type =
| Octy_constr of out_ident * out_type list
| Octy_fun of string * out_type * out_class_type
| Octy_signature of out_type option * out_class_sig_item list
and out_class_sig_item =
| Ocsg_constraint of out_type * out_type
| Ocsg_method of string * bool * bool * out_type
| Ocsg_value of string * bool * bool * out_type
type out_module_type =
| Omty_abstract
| Omty_functor of string * out_module_type * out_module_type
| Omty_ident of out_ident
| Omty_signature of out_sig_item list
and out_sig_item =
| Osig_class of
bool * string * (string * (bool * bool)) list * out_class_type *
out_rec_status
| Osig_class_type of
bool * string * (string * (bool * bool)) list * out_class_type *
out_rec_status
| Osig_exception of string * out_type list
| Osig_modtype of string * out_module_type
| Osig_module of string * out_module_type * out_rec_status
| Osig_type of out_type_decl * out_rec_status
| Osig_value of string * out_type * string list
and out_type_decl =
string * (string * (bool * bool)) list * out_type * Asttypes.private_flag *
(out_type * out_type) list
and out_rec_status =
| Orec_not
| Orec_first
| Orec_next
type out_phrase =
| Ophr_eval of out_value * out_type
| Ophr_signature of (out_sig_item * out_value option) list
| Ophr_exception of (exn * out_value)
|
2079355ed5087e4b9f358e5de4761eb332bb00a3f1386fbc01e6fc8a8ec00caa | glv2/cl-monero-tools | mnemonic.lisp | ;;;; This file is part of monero-tools
Copyright 2016 - 2017
Distributed under the GNU GPL v3 or later .
;;;; See the file LICENSE for terms of use and distribution.
(in-package :monero-tools-tests)
(def-suite mnemonic-tests
:description "Unit tests for mnemonic seed functions."
:in monero-tools-tests)
(in-suite mnemonic-tests)
(test secret-key->mnemonic-seed
(flet ((secret-key->mnemonic-seed/hex (secret-key language)
(secret-key->mnemonic-seed (hex-string->bytes secret-key) language)))
(is (string-equal "dedicated dubbed coexist having damp ember feline inquest september nobody alley binocular lopped moat agreed wayside gotten bays layout nail vixen imagine weird yahoo moat"
(secret-key->mnemonic-seed/hex "f61b1df1b8bc17126ebd95587494fb128a39217dd468e6bea57f2263626c1306" :english)))
(is (string-equal "brave visuel version tango davantage baobab quinze essai peau tellement balcon brevet tasse ordinaire rhume lueur oreille version stock agonie salon scoop rouge seuil peau"
(secret-key->mnemonic-seed/hex "b50710fdc751efdd2602635a0e271d0af6744a2bf58ca15a138dd6ca5ad78d0a" :french)))))
(test mnemonic-seed->secret-key
(flet ((mnemonic-seed->secret-key/hex (mnemonic-seed language)
(bytes->hex-string (mnemonic-seed->secret-key mnemonic-seed language))))
(is (string-equal "f61b1df1b8bc17126ebd95587494fb128a39217dd468e6bea57f2263626c1306"
(mnemonic-seed->secret-key/hex "dedicated dubbed coexist having damp ember feline inquest september nobody alley binocular lopped moat agreed wayside gotten bays layout nail vixen imagine weird yahoo moat" :english)))
(is (string-equal "b50710fdc751efdd2602635a0e271d0af6744a2bf58ca15a138dd6ca5ad78d0a"
(mnemonic-seed->secret-key/hex "brave visuel version tango davantage baobab quinze essai peau tellement balcon brevet tasse ordinaire rhume lueur oreille version stock agonie salon scoop rouge seuil peau" :french)))))
(test encrypt-mnemonic-seed
(is (string-equal "unbending bogeys bowling tender sorry upcoming textbook nozzle shackles vein sneeze cage sensible oaks fitting agreed upstairs onboard reunion obliged punch fifteen emotion firm sorry"
(encrypt-mnemonic-seed "dialect enough negative umbrella gourmet january tissue army sanity nugget against foxes nearby hobby alerts puddle unlikely noodles jolted citadel below vocal dauntless edited hobby"
"SomePassword"
:english)))
(is (string-equal "juerga casero jarra masivo poeta dirigir grúa iris pésimo revés lógica caer lombriz gajo explicar parar emoción minero ceniza oveja olmo lucir mito negar iris"
(encrypt-mnemonic-seed "boca lunes activo padre agua recreo inicio razón pichón gallo este canica curva carro bozal puerta perfil crisis pequeño farsa jungla mueble orilla pasar recreo"
"456uhbzerjkl951"
:spanish)))
(is (string-equal "いけん おどり うれしい うんちん つわり とのさま げこう なわとび こふう ぬくもり せつぶん いやす こうじ うすめる のせる いせかい せんさい おかわり たぶん とおる なっとう どうぐ てんし なふだ いけん"
(encrypt-mnemonic-seed "けまり こんいん ちへいせん おいかける だむる くいず ていねい しむける たまる いきる しゃこ げんぶつ そつえん げつようび あずかる せもたれ あんがい いちりゅう ぬいくぎ とさか あまり てれび てきとう ととのえる だむる"
"キーがテーブルにあります"
:japanese))))
(test decrypt-mnemonic-seed
(is (string-equal "dialect enough negative umbrella gourmet january tissue army sanity nugget against foxes nearby hobby alerts puddle unlikely noodles jolted citadel below vocal dauntless edited hobby"
(decrypt-mnemonic-seed "unbending bogeys bowling tender sorry upcoming textbook nozzle shackles vein sneeze cage sensible oaks fitting agreed upstairs onboard reunion obliged punch fifteen emotion firm sorry"
"SomePassword"
:english)))
(is (string-equal "boca lunes activo padre agua recreo inicio razón pichón gallo este canica curva carro bozal puerta perfil crisis pequeño farsa jungla mueble orilla pasar recreo"
(decrypt-mnemonic-seed "juerga casero jarra masivo poeta dirigir grúa iris pésimo revés lógica caer lombriz gajo explicar parar emoción minero ceniza oveja olmo lucir mito negar iris"
"456uhbzerjkl951"
:spanish)))
(is (string-equal "けまり こんいん ちへいせん おいかける だむる くいず ていねい しむける たまる いきる しゃこ げんぶつ そつえん げつようび あずかる せもたれ あんがい いちりゅう ぬいくぎ とさか あまり てれび てきとう ととのえる だむる"
(decrypt-mnemonic-seed "いけん おどり うれしい うんちん つわり とのさま げこう なわとび こふう ぬくもり せつぶん いやす こうじ うすめる のせる いせかい せんさい おかわり たぶん とおる なっとう どうぐ てんし なふだ いけん"
"キーがテーブルにあります"
:japanese))))
| null | https://raw.githubusercontent.com/glv2/cl-monero-tools/ab972ac3a7c5489cf23e3bdaa5d390d5cff1732b/tests/mnemonic.lisp | lisp | This file is part of monero-tools
See the file LICENSE for terms of use and distribution. | Copyright 2016 - 2017
Distributed under the GNU GPL v3 or later .
(in-package :monero-tools-tests)
(def-suite mnemonic-tests
:description "Unit tests for mnemonic seed functions."
:in monero-tools-tests)
(in-suite mnemonic-tests)
(test secret-key->mnemonic-seed
(flet ((secret-key->mnemonic-seed/hex (secret-key language)
(secret-key->mnemonic-seed (hex-string->bytes secret-key) language)))
(is (string-equal "dedicated dubbed coexist having damp ember feline inquest september nobody alley binocular lopped moat agreed wayside gotten bays layout nail vixen imagine weird yahoo moat"
(secret-key->mnemonic-seed/hex "f61b1df1b8bc17126ebd95587494fb128a39217dd468e6bea57f2263626c1306" :english)))
(is (string-equal "brave visuel version tango davantage baobab quinze essai peau tellement balcon brevet tasse ordinaire rhume lueur oreille version stock agonie salon scoop rouge seuil peau"
(secret-key->mnemonic-seed/hex "b50710fdc751efdd2602635a0e271d0af6744a2bf58ca15a138dd6ca5ad78d0a" :french)))))
(test mnemonic-seed->secret-key
(flet ((mnemonic-seed->secret-key/hex (mnemonic-seed language)
(bytes->hex-string (mnemonic-seed->secret-key mnemonic-seed language))))
(is (string-equal "f61b1df1b8bc17126ebd95587494fb128a39217dd468e6bea57f2263626c1306"
(mnemonic-seed->secret-key/hex "dedicated dubbed coexist having damp ember feline inquest september nobody alley binocular lopped moat agreed wayside gotten bays layout nail vixen imagine weird yahoo moat" :english)))
(is (string-equal "b50710fdc751efdd2602635a0e271d0af6744a2bf58ca15a138dd6ca5ad78d0a"
(mnemonic-seed->secret-key/hex "brave visuel version tango davantage baobab quinze essai peau tellement balcon brevet tasse ordinaire rhume lueur oreille version stock agonie salon scoop rouge seuil peau" :french)))))
(test encrypt-mnemonic-seed
(is (string-equal "unbending bogeys bowling tender sorry upcoming textbook nozzle shackles vein sneeze cage sensible oaks fitting agreed upstairs onboard reunion obliged punch fifteen emotion firm sorry"
(encrypt-mnemonic-seed "dialect enough negative umbrella gourmet january tissue army sanity nugget against foxes nearby hobby alerts puddle unlikely noodles jolted citadel below vocal dauntless edited hobby"
"SomePassword"
:english)))
(is (string-equal "juerga casero jarra masivo poeta dirigir grúa iris pésimo revés lógica caer lombriz gajo explicar parar emoción minero ceniza oveja olmo lucir mito negar iris"
(encrypt-mnemonic-seed "boca lunes activo padre agua recreo inicio razón pichón gallo este canica curva carro bozal puerta perfil crisis pequeño farsa jungla mueble orilla pasar recreo"
"456uhbzerjkl951"
:spanish)))
(is (string-equal "いけん おどり うれしい うんちん つわり とのさま げこう なわとび こふう ぬくもり せつぶん いやす こうじ うすめる のせる いせかい せんさい おかわり たぶん とおる なっとう どうぐ てんし なふだ いけん"
(encrypt-mnemonic-seed "けまり こんいん ちへいせん おいかける だむる くいず ていねい しむける たまる いきる しゃこ げんぶつ そつえん げつようび あずかる せもたれ あんがい いちりゅう ぬいくぎ とさか あまり てれび てきとう ととのえる だむる"
"キーがテーブルにあります"
:japanese))))
(test decrypt-mnemonic-seed
(is (string-equal "dialect enough negative umbrella gourmet january tissue army sanity nugget against foxes nearby hobby alerts puddle unlikely noodles jolted citadel below vocal dauntless edited hobby"
(decrypt-mnemonic-seed "unbending bogeys bowling tender sorry upcoming textbook nozzle shackles vein sneeze cage sensible oaks fitting agreed upstairs onboard reunion obliged punch fifteen emotion firm sorry"
"SomePassword"
:english)))
(is (string-equal "boca lunes activo padre agua recreo inicio razón pichón gallo este canica curva carro bozal puerta perfil crisis pequeño farsa jungla mueble orilla pasar recreo"
(decrypt-mnemonic-seed "juerga casero jarra masivo poeta dirigir grúa iris pésimo revés lógica caer lombriz gajo explicar parar emoción minero ceniza oveja olmo lucir mito negar iris"
"456uhbzerjkl951"
:spanish)))
(is (string-equal "けまり こんいん ちへいせん おいかける だむる くいず ていねい しむける たまる いきる しゃこ げんぶつ そつえん げつようび あずかる せもたれ あんがい いちりゅう ぬいくぎ とさか あまり てれび てきとう ととのえる だむる"
(decrypt-mnemonic-seed "いけん おどり うれしい うんちん つわり とのさま げこう なわとび こふう ぬくもり せつぶん いやす こうじ うすめる のせる いせかい せんさい おかわり たぶん とおる なっとう どうぐ てんし なふだ いけん"
"キーがテーブルにあります"
:japanese))))
|
a003093a3f15b69bfbeea5af0b1701641adaa4f013f90e384326a61755834e2c | jakemcc/sicp-study | 1.15.clj | Exercise 1.15
;(ns exercise1.15)
(defn cube [x] (* x x x))
(defn p [x]
(- (* 3 x)
(* 4 (cube x))))
(defn abs [x] (if (< x 0) (- x) x))
(defn sine [angle]
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0)))))
a ) How many times is p called when ( sine 12.15 ) is evaluated ?
( sine 12.15 )
5 times
; b) What is the order of growth in space and number of steps when (sine a) is evaluated
number of steps : O(log a ) , as input a doubles , p increases linearly
space : O(log a ) , same thing , since calls to p increase linearly and that is what is left to calculate with each step the growth in space grows linearly
(sine 2.0)
(sine 4.0)
(sine 8.0)
(sine 16.0)
(sine 32.0)
| null | https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section1.2/1.15.clj | clojure | (ns exercise1.15)
b) What is the order of growth in space and number of steps when (sine a) is evaluated | Exercise 1.15
(defn cube [x] (* x x x))
(defn p [x]
(- (* 3 x)
(* 4 (cube x))))
(defn abs [x] (if (< x 0) (- x) x))
(defn sine [angle]
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0)))))
a ) How many times is p called when ( sine 12.15 ) is evaluated ?
( sine 12.15 )
5 times
number of steps : O(log a ) , as input a doubles , p increases linearly
space : O(log a ) , same thing , since calls to p increase linearly and that is what is left to calculate with each step the growth in space grows linearly
(sine 2.0)
(sine 4.0)
(sine 8.0)
(sine 16.0)
(sine 32.0)
|
1e943cfd3f2bdf931e4cca0507df4ffd37959577fab229b0a0de9a151518be5a | scverif/scverif | glob_option.ml | Copyright 2019 - Inria , NXP
SPDX - License - Identifier : BSD-3 - Clause - Clear WITH modifications
let v_silent = 0
let v_normal = 1 (* normal printing *)
let v_normal_debug = 2 (* normal printing with extra info i.e full *)
let v_full = 3 (* full printing *)
let full = ref false
let set_full b =
full := b
let verbose = ref v_silent
let set_verbose lvl =
verbose := lvl;
set_full (v_normal_debug <= lvl);
Maskverif.Util.set_verbose lvl
let if_fprintf lvl =
if lvl <= !verbose then Format.fprintf
else Format.ifprintf
let if_printf lvl = if_fprintf lvl Format.std_formatter
let if_eprintf lvl = if_fprintf lvl Format.err_formatter
let print_silent x = if_printf v_silent x
let eprint_silent x = if_eprintf v_silent x
let print_normal x = if_printf v_normal x
let eprint_normal x = if_eprintf v_normal x
let print_full x = if_printf v_full x
let eprint_full x = if_eprintf v_full x
| null | https://raw.githubusercontent.com/scverif/scverif/307a17b61a2286fb7009d434825f9245caebfddc/src/glob_option.ml | ocaml | normal printing
normal printing with extra info i.e full
full printing | Copyright 2019 - Inria , NXP
SPDX - License - Identifier : BSD-3 - Clause - Clear WITH modifications
let v_silent = 0
let full = ref false
let set_full b =
full := b
let verbose = ref v_silent
let set_verbose lvl =
verbose := lvl;
set_full (v_normal_debug <= lvl);
Maskverif.Util.set_verbose lvl
let if_fprintf lvl =
if lvl <= !verbose then Format.fprintf
else Format.ifprintf
let if_printf lvl = if_fprintf lvl Format.std_formatter
let if_eprintf lvl = if_fprintf lvl Format.err_formatter
let print_silent x = if_printf v_silent x
let eprint_silent x = if_eprintf v_silent x
let print_normal x = if_printf v_normal x
let eprint_normal x = if_eprintf v_normal x
let print_full x = if_printf v_full x
let eprint_full x = if_eprintf v_full x
|
d130325b80e500acde367dc584666e5fa97ceadb8dac061c9f26ce43a35a5497 | hjcapple/reading-sicp | huffman.scm | P109 - [ 2.3.4 实例 : 编码树 ]
(define (make-leaf symbol weight)
(list 'leaf symbol weight))
(define (leaf? object)
(eq? (car object) 'leaf))
(define (symbol-leaf x)
(cadr x))
(define (weight-leaf x)
(caddr x))
(define (make-code-tree left right)
(list left
right
(append (symbol left) (symbol right))
(+ (weight left) (weight right))))
(define (left-branch tree)
(car tree))
(define (right-branch tree)
(cadr tree))
(define (symbol tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(define (decode bits tree)
(define (decode-1 bits current-branch)
(if (null? bits)
null
(let ((next-branch (choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-1 (cdr bits) tree))
(decode-1 (cdr bits) next-branch)))))
(decode-1 bits tree))
(define (choose-branch bit branch)
(cond ((= bit 0) (left-branch branch))
((= bit 1) (right-branch branch))
(else (error "bad bit -- CHOOSE-BRANCH" bit))))
(define (adjoin-set x set)
(cond ((null? set) (list x))
((< (weight x) (weight (car set))) (cons x set))
(else (cons (car set)
(adjoin-set x (cdr set))))))
(define (make-leaf-set pairs)
(if (null? pairs)
null
(let ((pair (car pairs)))
(adjoin-set (make-leaf (car pair) (cadr pair))
(make-leaf-set (cdr pairs))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
' ( ( leaf D 1 ) ( leaf C 1 ) ( leaf B 2 ) ( leaf A 4 ) )
(define sample-tree
(make-code-tree (make-leaf 'A 4)
(make-code-tree (make-leaf 'B 2)
(make-code-tree (make-leaf 'D 1)
(make-leaf 'C 1)))))
(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))
(decode sample-message sample-tree) ; '(A D A B B C A)
| null | https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_5/exercise_5_51/test_code/huffman.scm | scheme |
'(A D A B B C A) | P109 - [ 2.3.4 实例 : 编码树 ]
(define (make-leaf symbol weight)
(list 'leaf symbol weight))
(define (leaf? object)
(eq? (car object) 'leaf))
(define (symbol-leaf x)
(cadr x))
(define (weight-leaf x)
(caddr x))
(define (make-code-tree left right)
(list left
right
(append (symbol left) (symbol right))
(+ (weight left) (weight right))))
(define (left-branch tree)
(car tree))
(define (right-branch tree)
(cadr tree))
(define (symbol tree)
(if (leaf? tree)
(list (symbol-leaf tree))
(caddr tree)))
(define (weight tree)
(if (leaf? tree)
(weight-leaf tree)
(cadddr tree)))
(define (decode bits tree)
(define (decode-1 bits current-branch)
(if (null? bits)
null
(let ((next-branch (choose-branch (car bits) current-branch)))
(if (leaf? next-branch)
(cons (symbol-leaf next-branch)
(decode-1 (cdr bits) tree))
(decode-1 (cdr bits) next-branch)))))
(decode-1 bits tree))
(define (choose-branch bit branch)
(cond ((= bit 0) (left-branch branch))
((= bit 1) (right-branch branch))
(else (error "bad bit -- CHOOSE-BRANCH" bit))))
(define (adjoin-set x set)
(cond ((null? set) (list x))
((< (weight x) (weight (car set))) (cons x set))
(else (cons (car set)
(adjoin-set x (cdr set))))))
(define (make-leaf-set pairs)
(if (null? pairs)
null
(let ((pair (car pairs)))
(adjoin-set (make-leaf (car pair) (cadr pair))
(make-leaf-set (cdr pairs))))))
' ( ( leaf D 1 ) ( leaf C 1 ) ( leaf B 2 ) ( leaf A 4 ) )
(define sample-tree
(make-code-tree (make-leaf 'A 4)
(make-code-tree (make-leaf 'B 2)
(make-code-tree (make-leaf 'D 1)
(make-leaf 'C 1)))))
(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))
|
ecc2def313bc73d774505cde872e4601cb0c69f877747ebce732309e2bc04d5e | waldheinz/bling | Spectrum.hs | # LANGUAGE TypeFamilies #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE BangPatterns #-}
module Graphics.Bling.Spectrum (
Spectrum, WeightedSpectrum(..), ImageSample, Contribution,
white, black,
-- * Spectrum conversions
rgbToSpectrumRefl, rgbToSpectrumIllum, unGamma,
-- * Working with SPDs
Spd, mkSpd, mkSpd', mkSpdFunc, fromCIExy, spdToXYZ, evalSpd,
isBlack, sNaN, sInfinite,
xyzToRgb, toRGB, fromSpd, sConst, sBlackBody, sY,
sScale, sPow, sClamp, sClamp', chromaticityToXYZ,
spectrumToXYZ, xyzToSpectrum
) where
import Control.Monad (liftM, forM_)
import Data.List (sortBy)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Generic as GV
import qualified Data.Vector.Generic.Mutable as MV
import Control.DeepSeq as DS
import Prelude as P
import Graphics.Bling.Math
-- | the number of spectral bands we use for a spectrum
bands :: Int
# INLINE bands #
bands = 16
spectrumLambdaStart :: Float
# INLINE spectrumLambdaStart #
spectrumLambdaStart = 400
spectrumLambdaEnd :: Float
# INLINE spectrumLambdaEnd #
spectrumLambdaEnd = 700
newtype Spectrum = Spectrum { unSpectrum :: V.Vector Float } deriving (Show)
instance DS.NFData Spectrum where
rnf (Spectrum v) = seq v ()
# INLINE rnf #
--------------------------------------------------------------------------------
Unboxed Vectors of Spectra
--------------------------------------------------------------------------------
newtype instance V.MVector s Spectrum = MV_Spectrum (V.MVector s Float)
newtype instance V.Vector Spectrum = V_Spectrum (V.Vector Float)
instance V.Unbox Spectrum
instance MV.MVector V.MVector Spectrum where
basicLength (MV_Spectrum v) = MV.basicLength v `div` bands
# INLINE basicLength #
basicUnsafeSlice s l (MV_Spectrum v) =
MV_Spectrum (MV.unsafeSlice (s * bands) (l * bands) v)
# INLINE basicUnsafeSlice #
basicUnsafeNew l = MV_Spectrum `liftM` MV.unsafeNew (l * bands)
# INLINE basicUnsafeNew #
basicInitialize _ = return ()
basicOverlaps (MV_Spectrum v1) (MV_Spectrum v2) = MV.overlaps v1 v2
# INLINE basicOverlaps #
basicUnsafeRead (MV_Spectrum v) idx =
V.generateM bands (\i -> MV.unsafeRead v $(idx * bands) + i)
>>= \v' -> return (Spectrum v')
# INLINE basicUnsafeRead #
basicUnsafeWrite (MV_Spectrum v) idx (Spectrum vs) =
forM_ [0..bands-1] $ \i -> MV.unsafeWrite v ((idx * bands) + i) (V.unsafeIndex vs i)
# INLINE basicUnsafeWrite #
instance GV.Vector V.Vector Spectrum where
basicLength (V_Spectrum v) = GV.basicLength v `div` bands
# INLINE basicLength #
basicUnsafeSlice s l (V_Spectrum v) =
V_Spectrum $ (GV.unsafeSlice (s * bands) (l * bands) v)
# INLINE basicUnsafeSlice #
basicUnsafeFreeze (MV_Spectrum v) = V_Spectrum `liftM` (GV.unsafeFreeze v)
# INLINE basicUnsafeFreeze #
basicUnsafeThaw (V_Spectrum v) = MV_Spectrum `liftM` (GV.unsafeThaw v)
# INLINE basicUnsafeThaw #
basicUnsafeIndexM (V_Spectrum v) idx =
V.generateM bands (\i -> GV.unsafeIndexM v ((idx * bands) + i))
>>= \v' -> return (Spectrum v')
# INLINE basicUnsafeIndexM #
-- | a "black" @Spectrum@ (no transmittance or emission at all wavelengths)
black :: Spectrum
# INLINE black #
black = sConst 0
-- | a "white" @Spectrum@ (unit transmission at all wavelengths)
white :: Spectrum
# INLINE white #
white = sConst 1
| Removes the gamma correction from a RGB triple . The supplied RGB value is
supposed to have a gamma correction of 2.2 applied , which is reversed
-- by this function.
unGamma :: (Float, Float, Float) -> (Float, Float, Float)
# INLINE unGamma #
unGamma (r, g, b) = let ga = 2.2 in (r ** ga, g ** ga, b ** ga)
data RGBToSpectrumBase =
RGBBases
r , , b
!Spectrum !Spectrum !Spectrum -- c, m, y
!Spectrum -- w
rgbReflectance :: RGBToSpectrumBase
rgbReflectance = RGBBases
rgbReflRed rgbReflGreen rgbReflBlue
rgbReflCyan rgbReflMagenta rgbReflYellow
rgbReflWhite
rgbIlluminant :: RGBToSpectrumBase
rgbIlluminant = RGBBases
rgbIllumRed rgbIllumGreen rgbIllumBlue
rgbIllumCyan rgbIllumMagenta rgbIllumYellow
rgbIllumWhite
rgbToSpectrumRefl :: (Float, Float, Float) -> Spectrum
rgbToSpectrumRefl = rgbToSpectrum rgbReflectance
rgbToSpectrumIllum :: (Float, Float, Float) -> Spectrum
rgbToSpectrumIllum = rgbToSpectrum rgbIlluminant
rgbToSpectrum :: RGBToSpectrumBase -> (Float, Float, Float) -> Spectrum
rgbToSpectrum (RGBBases rb gb bb cb mb yb wb) (r, g, b)
| r <= g && r <= b =
sScale wb r + if g <= b
then sScale cb (g - r) + sScale bb (b - g)
else sScale cb (b - r) + sScale gb (g - b)
| g <= r && g <= b =
sScale wb g + if r <= b
then sScale mb (r - g) + sScale bb (b - r)
else sScale mb (b - g) + sScale rb (r - b)
| otherwise =
sScale wb b + if r <= b
then sScale yb (r - b) + sScale gb (g - r)
else sScale yb (g - b) + sScale rb (r - g)
| converts from CIE XYZ to sRGB
xyzToRgb
:: (Float, Float, Float) -- ^ (X, Y, Z)
^ ( r , , b )
xyzToRgb (x, y, z) = (r, g, b) where
r = 3.240479 * x - 1.537150 * y - 0.498535 * z
g = (-0.969256) * x + 1.875991 * y + 0.041556 * z
b = 0.055648 * x - 0.204043 * y + 1.057311 * z
--------------------------------------------------------------------------------
-- ImageSample and the like
--------------------------------------------------------------------------------
data WeightedSpectrum = WS {-# UNPACK #-} !Float !Spectrum -- the sample weight and the sampled spectrum
type ImageSample = (Float, Float, WeightedSpectrum) -- the pixel coordinates and the weighted spectrum
type Contribution = (Bool, ImageSample)
--------------------------------------------------------------------------------
-- SPDs
--------------------------------------------------------------------------------
data Spd
= IrregularSpd
{ _spdLambdas :: !(V.Vector Float)
, _spdValues :: !(V.Vector Float) }
| RegularSpd
{-# UNPACK #-} !Float -- min lambda
{-# UNPACK #-} !Float -- max lambda
!(V.Vector Float) -- amplitudes
| Chromaticity
M1
M2
| SpdFunc
!(Float -> Float) -- defined by a function
| creates a SPD from a list of ( lambda , value ) pairs , which must
-- not be empty
mkSpd
^ the SPD as ( lambda , amplitude ) pairs
-> Spd
mkSpd [] = error "empty SPD"
mkSpd xs = IrregularSpd ls vs where
ls = V.fromList (P.map fst sorted)
vs = V.fromList (P.map snd sorted)
sorted = sortBy cmp xs
cmp (l1, _) (l2, _) = compare l1 l2
| creates a SPD from a list of regulary sampled amplitudes
mkSpd'
^ the wavelength of the first amplitude sample
-> Float -- ^ the wavelength of the last amplitude sample
^ the amplitudes of the SPD , must not be empty
^ the resulting SPD
mkSpd' s e vs = RegularSpd s e (V.fromList vs)
mkSpdFunc
^ the SPD function from lambda in nanometers to amplitude
-> Spd
mkSpdFunc = SpdFunc
fromCIExy
:: Float
-> Float
-> Spd
fromCIExy x y = Chromaticity m1 m2 where
(m1, m2) = chromaParams x y
chromaParams :: Float -> Float -> (Float, Float)
chromaParams x y = (m1, m2) where
m1 = (-1.3515 - 1.7703 * x + 5.9114 * y) / (0.0241 + 0.2562 * x - 0.7341 * y)
m2 = (0.03 - 31.4424 * x + 30.0717 * y) / (0.0241 + 0.2562 * x - 0.7341 * y)
s0XYZ :: (Float, Float, Float)
s0XYZ = spdToXYZ cieS0
s1XYZ :: (Float, Float, Float)
s1XYZ = spdToXYZ cieS1
s2XYZ :: (Float, Float, Float)
s2XYZ = spdToXYZ cieS2
chromaticityToXYZ :: Float -> Float -> (Float, Float, Float)
chromaticityToXYZ x y = (x', y', z') where
(s0x, s0y, s0z) = s0XYZ
(s1x, s1y, s1z) = s1XYZ
(s2x, s2y, s2z) = s2XYZ
(m1, m2) = chromaParams x y
x' = s0x + m1 * s1x + m2 * s2x
y' = s0y + m1 * s1y + m2 * s2y
z' = s0z + m1 * s1z + m2 * s2z
| evaluates a SPD at a given wavelength
evalSpd
^ the SPD to evaluate
^ the lambda where the SPD should be evaluated
^ the SPD value at the specified lambda
evalSpd (IrregularSpd ls vs) l
| l <= V.head ls = V.head vs
| l >= V.last ls = V.last vs
| otherwise = lerp t (vs V.! i) (vs V.! (i+1)) where
t = (l - (ls V.! i)) / ((ls V.! (i+1)) - (ls V.! i))
i = fi 0 (V.length ls - 1)
fi lo hi -- binary search for index
| lo == mid = lo
| (ls V.! mid) == l = mid
| (ls V.! mid) < l = fi mid hi
| otherwise = fi lo mid where
mid = (lo + hi) `div` 2
evalSpd (RegularSpd l0 l1 amps) l
| l <= l0 = V.head amps
| l >= l1 = V.last amps
| otherwise = (1 - dx) * (amps V.! b0) + dx * (amps V.! b1)
where
1 / delta
x = (l - l0) * d1
b0 = floor x
b1 = min (b0 + 1) (V.length amps - 1)
dx = x - fromIntegral b0
evalSpd (Chromaticity m1 m2) l = s0 + m1 * s1 + m2 * s2 where
s0 = evalSpd cieS0 l
s1 = evalSpd cieS1 l
s2 = evalSpd cieS2 l
evalSpd (SpdFunc f) l = f l
| determines the average value of a @Spd@ in the specified interval
TODO : should compute the weighted average
avgSpd
:: Spd -- ^ the Spd to evaluate
-> Float -- ^ the minimum wavelength of interest
-> Float -- ^ the maximum wavelength of interest, must be >= the minimum
-> Float
avgSpd (RegularSpd s0 s1 amps) l0 l1
| l1 <= s0 = V.head amps
| l0 >= s1 = V.last amps
| otherwise = V.sum amps' / fromIntegral (V.length amps')
where
amps' = V.slice i0 (i1 - i0 + 1) amps
n = V.length amps
i0 = max 0 $ min n $ floor $ fromIntegral n * ((l0 - s0) / (s1 - s0))
i1 = max 0 $ min n $ floor $ fromIntegral n * ((l1 - s0) / (s1 - s0))
avgSpd (IrregularSpd ls vs) l0 l1
| l1 <= V.head ls = V.head vs
| l0 >= V.last ls = V.last vs
| otherwise = V.sum vs' / fromIntegral (V.length vs')
where
vs' = V.slice i0 (i1 - i0 + 1) vs
i0 = maybe 0 id $ V.findIndex (>= l0) ls
i1 = maybe (V.length vs - 1) id $ V.findIndex (>= l1) ls
avgSpd spd l0 l1 = (evalSpd spd l0 + evalSpd spd l1) * 0.5
| converts a @Spd@ to CIE XYZ values
spdToXYZ :: Spd -> (Float, Float, Float)
spdToXYZ spd = (x / yint, y / yint, z / yint) where
ls = [cieStart .. cieEnd]
vs = P.map (\l -> evalSpd spd (fromIntegral l)) ls
yint = P.sum (P.map (\l -> evalSpd cieY (fromIntegral l)) ls)
x = P.sum $ P.zipWith (*) (P.map (\l -> evalSpd cieX (fromIntegral l)) ls) vs
y = P.sum $ P.zipWith (*) (P.map (\l -> evalSpd cieY (fromIntegral l)) ls) vs
z = P.sum $ P.zipWith (*) (P.map (\l -> evalSpd cieZ (fromIntegral l)) ls) vs
-- | converts from a @Spd@ to @Spectrum@
fromSpd
:: Spd
-> Spectrum
fromSpd spd = Spectrum $ V.generate bands go where
go i = avgSpd spd l0 l1 where
l0 = lerp (fromIntegral i / fromIntegral bands) spectrumLambdaStart spectrumLambdaEnd
l1 = lerp (fromIntegral (i+1) / fromIntegral bands) spectrumLambdaStart spectrumLambdaEnd
spectrumCieX :: Spectrum
spectrumCieX = fromSpd cieX
spectrumCieY :: Spectrum
spectrumCieY = fromSpd cieY
spectrumCieZ :: Spectrum
spectrumCieZ = fromSpd cieZ
spectrumCieYSum :: Float
spectrumCieYSum = V.sum $ unSpectrum spectrumCieY
spectrumToXYZ :: Spectrum -> (Float, Float, Float)
spectrumToXYZ s = scale $ V.foldl' (\(a, b, c) (v, x, y, z) -> (a + x * v, b + y * v, c + z * v)) (0, 0, 0) $ V.zip4 vsv vsx vsy vsz where
vsx = unSpectrum spectrumCieX
vsy = unSpectrum spectrumCieY
vsz = unSpectrum spectrumCieZ
vsv = unSpectrum s
scale (x, y, z) = (x / spectrumCieYSum, y / spectrumCieYSum, z / spectrumCieYSum)
xyzToSpectrum :: (Float, Float, Float) -> Spectrum
xyzToSpectrum = rgbToSpectrumIllum . xyzToRgb
xyzToSpectrum ( x , y , z ) =
sScale spectrumCieX ( x / spectrumCieYSum ) +
sScale spectrumCieY ( y / spectrumCieYSum ) +
sScale ( z / spectrumCieYSum )
xyzToSpectrum (x, y, z) =
sScale spectrumCieX (x / spectrumCieYSum) +
sScale spectrumCieY (y / spectrumCieYSum) +
sScale spectrumCieZ (z / spectrumCieYSum)
-}
toRGB :: Spectrum -> (Float, Float, Float)
# INLINE toRGB #
toRGB (Spectrum v) = (v V.! 0, v V.! 1, v V.! 2)
-- | the brightness
sY :: Spectrum -> Float
# INLINE sY #
sY (Spectrum v) = (V.sum $ V.zipWith (*) v $ unSpectrum spectrumCieY) / spectrumCieYSum
sConst :: Float -> Spectrum
# INLINE sConst #
sConst r = Spectrum $ V.replicate bands r
sMap :: (Float -> Float) -> Spectrum -> Spectrum
# INLINE sMap #
sMap f s = Spectrum $ V.map f $ unSpectrum s
instance Floating Spectrum where
pi = sConst pi
# INLINE pi #
exp = sMap exp
# INLINE exp #
sqrt = sMap sqrt
# INLINE sqrt #
log = sMap log
# INLINE log #
(**) (Spectrum s1) (Spectrum s2) = Spectrum $ V.zipWith (**) s1 s2
{-# INLINE (**) #-}
logBase (Spectrum s1) (Spectrum s2) = Spectrum $ V.zipWith logBase s1 s2
# INLINE logBase #
sin = sMap sin
# INLINE sin #
tan = sMap tan
# INLINE tan #
cos = sMap cos
# INLINE cos #
asin = sMap asin
{-# INLINE asin #-}
atan = sMap atan
# INLINE atan #
acos = sMap acos
# INLINE acos #
sinh = sMap sinh
# INLINE sinh #
tanh = sMap tanh
# INLINE tanh #
cosh = sMap cosh
# INLINE cosh #
asinh = sMap asinh
# INLINE asinh #
atanh = sMap atanh
# INLINE atanh #
acosh = sMap acosh
# INLINE acosh #
instance Fractional Spectrum where
Spectrum v1 / Spectrum v2 = Spectrum $ V.zipWith (/) v1 v2
{-# INLINE (/) #-}
fromRational i = Spectrum $ V.replicate bands (fromRational i)
# INLINE fromRational #
instance Num Spectrum where
Spectrum v1 + Spectrum v2 = Spectrum $ V.zipWith (+) v1 v2
{-# INLINE (+) #-}
Spectrum v1 - Spectrum v2 = Spectrum $ V.zipWith (-) v1 v2
{-# INLINE (-) #-}
Spectrum v1 * Spectrum v2 = Spectrum $ V.zipWith (*) v1 v2
{-# INLINE (*) #-}
abs (Spectrum v) = Spectrum $ V.map abs v
# INLINE abs #
negate (Spectrum v) = Spectrum $ V.map negate v
# INLINE negate #
signum (Spectrum v) = Spectrum $ V.map signum v
# INLINE signum #
fromInteger i = Spectrum $ V.replicate bands (fromInteger i)
# INLINE fromInteger #
-- | Decides if a @Spectrum@ is black
isBlack :: Spectrum -> Bool
# INLINE isBlack #
isBlack (Spectrum v) = V.all (== 0) v
sScale :: Spectrum -> Float -> Spectrum
# INLINE sScale #
sScale (Spectrum v) f = Spectrum $ V.map (*f) v
-- | clamps the @Spectrum@ coefficients the specified range
sClamp :: Float -> Float -> Spectrum -> Spectrum
{-# INLINE sClamp #-}
sClamp smin smax (Spectrum v) = Spectrum $ V.map c v where
c x = max smin $ min smax x
| clamps the @Spectrum@ coefficients to [ 0,1 ]
sClamp' :: Spectrum -> Spectrum
{-# INLINE sClamp' #-}
sClamp' = sClamp 0 1
sNaN :: Spectrum -> Bool
# INLINE sNaN #
sNaN (Spectrum v) = V.any isNaN v
sInfinite :: Spectrum -> Bool
# INLINE sInfinite #
sInfinite (Spectrum v) = V.any isInfinite v
sPow :: Spectrum -> Spectrum -> Spectrum
# INLINE sPow #
sPow (Spectrum vc) (Spectrum ve) = Spectrum (V.zipWith p' vc ve) where
p' :: Float -> Float -> Float
p' c e
| c > 0 = c ** e
| otherwise = 0
-- | The spectrum of a black body emitter
sBlackBody
^ the temperature in Kelvin
-> Spectrum -- ^ the emission spectrum of the emitter
sBlackBody t = fromSpd $ mkSpdFunc (planck t)
sScale ( fromXYZ ( x , y , z ) ) ( 1 / ( fromIntegral ( cieEnd - cieStart ) ) ) where
z = max 0 $ P.sum $ P.map ( \wl - > ( wl ) * ( p wl ) ) [ cieStart .. cieEnd ]
y = max 0 $ P.sum $ P.map ( \wl - > ( cieY wl ) * ( p wl ) ) [ cieStart .. cieEnd ]
x = max 0 $ P.sum $ P.map ( \wl - > ( cieX wl ) * ( p wl ) ) [ cieStart .. cieEnd ]
-- p = (\wl -> planck t (fromIntegral wl))
planck :: RealFloat a => a -> a -> a
planck temp w = (0.4e-9 * (3.74183e-16 * w' ^^ (-5::Int))) / (exp (1.4388e-2 / (w' * temp)) - 1) where
w' = w * 1e-9
--
CIE chromaticity SPDs
--
cieS0 :: Spd
cieS0 = mkSpd' 300 830
[ 0.04, 6.0, 29.6, 55.3, 57.3, 61.8, 61.5, 68.8, 63.4,
65.8, 94.8, 104.8, 105.9, 96.8, 113.9, 125.6, 125.5, 121.3,
121.3, 113.5, 113.1, 110.8, 106.5, 108.8, 105.3, 104.4, 100.0,
96.0, 95.1, 89.1, 90.5, 90.3, 88.4, 84.0, 85.1, 81.9,
82.6, 84.9, 81.3, 71.9, 74.3, 76.4, 63.3, 71.7, 77.0,
65.2, 47.7, 68.6, 65.0, 66.0, 61.0, 53.3, 58.9, 61.9 ]
cieS1 :: Spd
cieS1 = mkSpd' 300 830
[ 0.02, 4.5, 22.4, 42.0, 40.6, 41.6, 38.0, 42.4, 38.5, 35.0, 43.4,
46.3, 43.9, 37.1, 36.7, 35.9, 32.6, 27.9, 24.3, 20.1, 16.2, 13.2,
8.6, 6.1, 4.2, 1.9, 0.0, -1.6, -3.5, -3.5, -5.8, -7.2, -8.6, -9.5,
-10.9, -10.7, -12.0, -14.0, -13.6, -12.0, -13.3, -12.9, -10.6,
-11.6, -12.2, -10.2, -7.8, -11.2, -10.4, -10.6, -9.7, -8.3, -9.3, -9.8]
cieS2 :: Spd
cieS2 = mkSpd' 300 830
[ 0.0, 2.0, 4.0, 8.5, 7.8, 6.7, 5.3, 6.1, 3.0, 1.2, -1.1, -0.5, -0.7,
-1.2, -2.6, -2.9, -2.8, -2.6, -2.6, -1.8, -1.5, -1.3, -1.2, -1.0,
-0.5, -0.3, 0.0, 0.2, 0.5, 2.1, 3.2, 4.1, 4.7, 5.1, 6.7, 7.3, 8.6,
9.8, 10.2, 8.3, 9.6, 8.5, 7.0, 7.6, 8.0, 6.7, 5.2, 7.4, 6.8, 7.0,
6.4, 5.5, 6.1, 6.5]
--------------------------------------------------------------------------------
CIE XYZ SPDs
--------------------------------------------------------------------------------
cieStart :: Int
cieStart = 360
cieEnd :: Int
cieEnd = 830
cieSpd :: [Float] -> Spd
cieSpd = mkSpd' (fromIntegral cieStart) (fromIntegral cieEnd)
cieX :: Spd
cieX = cieSpd cieXValues
cieY :: Spd
cieY = cieSpd cieYValues
cieZ :: Spd
cieZ = cieSpd cieZValues
--------------------------------------------------------------------------------
-- Only boring tables below
--------------------------------------------------------------------------------
rgbToSpectrumStart :: Float
rgbToSpectrumStart = 380
rgbToSpectrumEnd :: Float
rgbToSpectrumEnd = 720
rgbFunc :: [Float] -> Spectrum
rgbFunc vs = fromSpd $ mkSpd' rgbToSpectrumStart rgbToSpectrumEnd vs
rgbIllumWhite :: Spectrum
rgbIllumWhite = rgbFunc
[ 1.1565232050369776e+00, 1.1567225000119139e+00, 1.1566203150243823e+00,
1.1555782088080084e+00, 1.1562175509215700e+00, 1.1567674012207332e+00,
1.1568023194808630e+00, 1.1567677445485520e+00, 1.1563563182952830e+00,
1.1567054702510189e+00, 1.1565134139372772e+00, 1.1564336176499312e+00,
1.1568023181530034e+00, 1.1473147688514642e+00, 1.1339317140561065e+00,
1.1293876490671435e+00, 1.1290515328639648e+00, 1.0504864823782283e+00,
1.0459696042230884e+00, 9.9366687168595691e-01, 9.5601669265393940e-01,
9.2467482033511805e-01, 9.1499944702051761e-01, 8.9939467658453465e-01,
8.9542520751331112e-01, 8.8870566693814745e-01, 8.8222843814228114e-01,
8.7998311373826676e-01, 8.7635244612244578e-01, 8.8000368331709111e-01,
8.8065665428441120e-01, 8.8304706460276905e-01 ]
rgbIllumCyan :: Spectrum
rgbIllumCyan = rgbFunc
[ 1.1334479663682135e+00, 1.1266762330194116e+00, 1.1346827504710164e+00,
1.1357395805744794e+00, 1.1356371830149636e+00, 1.1361152989346193e+00,
1.1362179057706772e+00, 1.1364819652587022e+00, 1.1355107110714324e+00,
1.1364060941199556e+00, 1.1360363621722465e+00, 1.1360122641141395e+00,
1.1354266882467030e+00, 1.1363099407179136e+00, 1.1355450412632506e+00,
1.1353732327376378e+00, 1.1349496420726002e+00, 1.1111113947168556e+00,
9.0598740429727143e-01, 6.1160780787465330e-01, 2.9539752170999634e-01,
9.5954200671150097e-02,-1.1650792030826267e-02,-1.2144633073395025e-02,
-1.1148167569748318e-02,-1.1997606668458151e-02,-5.0506855475394852e-03,
-7.9982745819542154e-03,-9.4722817708236418e-03,-5.5329541006658815e-03,
-4.5428914028274488e-03,-1.2541015360921132e-02 ]
rgbIllumMagenta :: Spectrum
rgbIllumMagenta = rgbFunc
[ 1.0371892935878366e+00, 1.0587542891035364e+00, 1.0767271213688903e+00,
1.0762706844110288e+00, 1.0795289105258212e+00, 1.0743644742950074e+00,
1.0727028691194342e+00, 1.0732447452056488e+00, 1.0823760816041414e+00,
1.0840545681409282e+00, 9.5607567526306658e-01, 5.5197896855064665e-01,
8.4191094887247575e-02, 8.7940070557041006e-05,-2.3086408335071251e-03,
-1.1248136628651192e-03,-7.7297612754989586e-11,-2.7270769006770834e-04,
1.4466473094035592e-02, 2.5883116027169478e-01, 5.2907999827566732e-01,
9.0966624097105164e-01, 1.0690571327307956e+00, 1.0887326064796272e+00,
1.0637622289511852e+00, 1.0201812918094260e+00, 1.0262196688979945e+00,
1.0783085560613190e+00, 9.8333849623218872e-01, 1.0707246342802621e+00,
1.0634247770423768e+00, 1.0150875475729566e+00 ]
rgbIllumYellow :: Spectrum
rgbIllumYellow = rgbFunc
[ 2.7756958965811972e-03, 3.9673820990646612e-03,-1.4606936788606750e-04,
3.6198394557748065e-04,-2.5819258699309733e-04,-5.0133191628082274e-05,
-2.4437242866157116e-04,-7.8061419948038946e-05, 4.9690301207540921e-02,
4.8515973574763166e-01, 1.0295725854360589e+00, 1.0333210878457741e+00,
1.0368102644026933e+00, 1.0364884018886333e+00, 1.0365427939411784e+00,
1.0368595402854539e+00, 1.0365645405660555e+00, 1.0363938240707142e+00,
1.0367205578770746e+00, 1.0365239329446050e+00, 1.0361531226427443e+00,
1.0348785007827348e+00, 1.0042729660717318e+00, 8.4218486432354278e-01,
7.3759394894801567e-01, 6.5853154500294642e-01, 6.0531682444066282e-01,
5.9549794132420741e-01, 5.9419261278443136e-01, 5.6517682326634266e-01,
5.6061186014968556e-01, 5.8228610381018719e-01 ]
rgbIllumRed :: Spectrum
rgbIllumRed = rgbFunc
[ 5.4711187157291841e-02, 5.5609066498303397e-02, 6.0755873790918236e-02,
5.6232948615962369e-02, 4.6169940535708678e-02, 3.8012808167818095e-02,
2.4424225756670338e-02, 3.8983580581592181e-03,-5.6082252172734437e-04,
9.6493871255194652e-04, 3.7341198051510371e-04,-4.3367389093135200e-04,
-9.3533962256892034e-05,-1.2354967412842033e-04,-1.4524548081687461e-04,
-2.0047691915543731e-04,-4.9938587694693670e-04, 2.7255083540032476e-02,
1.6067405906297061e-01, 3.5069788873150953e-01, 5.7357465538418961e-01,
7.6392091890718949e-01, 8.9144466740381523e-01, 9.6394609909574891e-01,
9.8879464276016282e-01, 9.9897449966227203e-01, 9.8605140403564162e-01,
9.9532502805345202e-01, 9.7433478377305371e-01, 9.9134364616871407e-01,
9.8866287772174755e-01, 9.9713856089735531e-01 ]
rgbIllumGreen :: Spectrum
rgbIllumGreen = rgbFunc
[ 2.5168388755514630e-02, 3.9427438169423720e-02, 6.2059571596425793e-03,
7.1120859807429554e-03, 2.1760044649139429e-04, 7.3271839984290210e-12,
-2.1623066217181700e-02, 1.5670209409407512e-02, 2.8019603188636222e-03,
3.2494773799897647e-01, 1.0164917292316602e+00, 1.0329476657890369e+00,
1.0321586962991549e+00, 1.0358667411948619e+00, 1.0151235476834941e+00,
1.0338076690093119e+00, 1.0371372378155013e+00, 1.0361377027692558e+00,
1.0229822432557210e+00, 9.6910327335652324e-01,-5.1785923899878572e-03,
1.1131261971061429e-03, 6.6675503033011771e-03, 7.4024315686001957e-04,
2.1591567633473925e-02, 5.1481620056217231e-03, 1.4561928645728216e-03,
1.6414511045291513e-04,-6.4630764968453287e-03, 1.0250854718507939e-02,
4.2387394733956134e-02, 2.1252716926861620e-02 ]
rgbIllumBlue :: Spectrum
rgbIllumBlue = rgbFunc
[ 1.0570490759328752e+00, 1.0538466912851301e+00, 1.0550494258140670e+00,
1.0530407754701832e+00, 1.0579930596460185e+00, 1.0578439494812371e+00,
1.0583132387180239e+00, 1.0579712943137616e+00, 1.0561884233578465e+00,
1.0571399285426490e+00, 1.0425795187752152e+00, 3.2603084374056102e-01,
-1.9255628442412243e-03,-1.2959221137046478e-03,-1.4357356276938696e-03,
-1.2963697250337886e-03,-1.9227081162373899e-03, 1.2621152526221778e-03,
-1.6095249003578276e-03,-1.3029983817879568e-03,-1.7666600873954916e-03,
-1.2325281140280050e-03, 1.0316809673254932e-02, 3.1284512648354357e-02,
8.8773879881746481e-02, 1.3873621740236541e-01, 1.5535067531939065e-01,
1.4878477178237029e-01, 1.6624255403475907e-01, 1.6997613960634927e-01,
1.5769743995852967e-01, 1.9069090525482305e-01 ]
rgbReflWhite :: Spectrum
rgbReflWhite = rgbFunc
[ 1.0618958571272863e+00, 1.0615019980348779e+00, 1.0614335379927147e+00,
1.0622711654692485e+00, 1.0622036218416742e+00, 1.0625059965187085e+00,
1.0623938486985884e+00, 1.0624706448043137e+00, 1.0625048144827762e+00,
1.0624366131308856e+00, 1.0620694238892607e+00, 1.0613167586932164e+00,
1.0610334029377020e+00, 1.0613868564828413e+00, 1.0614215366116762e+00,
1.0620336151299086e+00, 1.0625497454805051e+00, 1.0624317487992085e+00,
1.0625249140554480e+00, 1.0624277664486914e+00, 1.0624749854090769e+00,
1.0625538581025402e+00, 1.0625326910104864e+00, 1.0623922312225325e+00,
1.0623650980354129e+00, 1.0625256476715284e+00, 1.0612277619533155e+00,
1.0594262608698046e+00, 1.0599810758292072e+00, 1.0602547314449409e+00,
1.0601263046243634e+00, 1.0606565756823634e+00 ]
rgbReflCyan :: Spectrum
rgbReflCyan = rgbFunc
[ 1.0414628021426751e+00, 1.0328661533771188e+00, 1.0126146228964314e+00,
1.0350460524836209e+00, 1.0078661447098567e+00, 1.0422280385081280e+00,
1.0442596738499825e+00, 1.0535238290294409e+00, 1.0180776226938120e+00,
1.0442729908727713e+00, 1.0529362541920750e+00, 1.0537034271160244e+00,
1.0533901869215969e+00, 1.0537782700979574e+00, 1.0527093770467102e+00,
1.0530449040446797e+00, 1.0550554640191208e+00, 1.0553673610724821e+00,
1.0454306634683976e+00, 6.2348950639230805e-01, 1.8038071613188977e-01,
-7.6303759201984539e-03,-1.5217847035781367e-04,-7.5102257347258311e-03,
-2.1708639328491472e-03, 6.5919466602369636e-04, 1.2278815318539780e-02,
-4.4669775637208031e-03, 1.7119799082865147e-02, 4.9211089759759801e-03,
5.8762925143334985e-03, 2.5259399415550079e-02 ]
rgbReflMagenta :: Spectrum
rgbReflMagenta = rgbFunc
[ 9.9422138151236850e-01, 9.8986937122975682e-01, 9.8293658286116958e-01,
9.9627868399859310e-01, 1.0198955019000133e+00, 1.0166395501210359e+00,
1.0220913178757398e+00, 9.9651666040682441e-01, 1.0097766178917882e+00,
1.0215422470827016e+00, 6.4031953387790963e-01, 2.5012379477078184e-03,
6.5339939555769944e-03, 2.8334080462675826e-03,-5.1209675389074505e-11,
-9.0592291646646381e-03, 3.3936718323331200e-03,-3.0638741121828406e-03,
2.2203936168286292e-01, 6.3141140024811970e-01, 9.7480985576500956e-01,
9.7209562333590571e-01, 1.0173770302868150e+00, 9.9875194322734129e-01,
9.4701725739602238e-01, 8.5258623154354796e-01, 9.4897798581660842e-01,
9.4751876096521492e-01, 9.9598944191059791e-01, 8.6301351503809076e-01,
8.9150987853523145e-01, 8.4866492652845082e-01 ]
rgbReflYellow :: Spectrum
rgbReflYellow = rgbFunc
[ 5.5740622924920873e-03,-4.7982831631446787e-03,
-5.2536564298613798e-03,-6.4571480044499710e-03,
-5.9693514658007013e-03,-2.1836716037686721e-03,
1.6781120601055327e-02, 9.6096355429062641e-02,
2.1217357081986446e-01, 3.6169133290685068e-01,
5.3961011543232529e-01, 7.4408810492171507e-01,
9.2209571148394054e-01, 1.0460304298411225e+00,
1.0513824989063714e+00, 1.0511991822135085e+00,
1.0510530911991052e+00, 1.0517397230360510e+00,
1.0516043086790485e+00, 1.0511944032061460e+00,
1.0511590325868068e+00, 1.0516612465483031e+00,
1.0514038526836869e+00, 1.0515941029228475e+00,
1.0511460436960840e+00, 1.0515123758830476e+00,
1.0508871369510702e+00, 1.0508923708102380e+00,
1.0477492815668303e+00, 1.0493272144017338e+00,
1.0435963333422726e+00, 1.0392280772051465e+00 ]
rgbReflRed :: Spectrum
rgbReflRed = rgbFunc
[ 1.6575604867086180e-01, 1.1846442802747797e-01,
1.2408293329637447e-01, 1.1371272058349924e-01,
7.8992434518899132e-02, 3.2205603593106549e-02,
-1.0798365407877875e-02, 1.8051975516730392e-02,
5.3407196598730527e-03, 1.3654918729501336e-02,
-5.9564213545642841e-03, -1.8444365067353252e-03,
-1.0571884361529504e-02, -2.9375521078000011e-03,
-1.0790476271835936e-02, -8.0224306697503633e-03,
-2.2669167702495940e-03, 7.0200240494706634e-03,
-8.1528469000299308e-03, 6.0772866969252792e-01,
9.8831560865432400e-01, 9.9391691044078823e-01,
1.0039338994753197e+00, 9.9234499861167125e-01,
9.9926530858855522e-01, 1.0084621557617270e+00,
9.8358296827441216e-01, 1.0085023660099048e+00,
9.7451138326568698e-01, 9.8543269570059944e-01,
9.3495763980962043e-01, 9.8713907792319400e-01 ]
rgbReflGreen :: Spectrum
rgbReflGreen = rgbFunc
[ 2.6494153587602255e-03, -5.0175013429732242e-03,
-1.2547236272489583e-02, -9.4554964308388671e-03,
-1.2526086181600525e-02, -7.9170697760437767e-03,
-7.9955735204175690e-03, -9.3559433444469070e-03,
6.5468611982999303e-02, 3.9572875517634137e-01,
7.5244022299886659e-01, 9.6376478690218559e-01,
9.9854433855162328e-01, 9.9992977025287921e-01,
9.9939086751140449e-01, 9.9994372267071396e-01,
9.9939121813418674e-01, 9.9911237310424483e-01,
9.6019584878271580e-01, 6.3186279338432438e-01,
2.5797401028763473e-01, 9.4014888527335638e-03,
-3.0798345608649747e-03, -4.5230367033685034e-03,
-6.8933410388274038e-03, -9.0352195539015398e-03,
-8.5913667165340209e-03, -8.3690869120289398e-03,
-7.8685832338754313e-03, -8.3657578711085132e-06,
5.4301225442817177e-03, -2.7745589759259194e-03 ]
rgbReflBlue :: Spectrum
rgbReflBlue = rgbFunc
[ 9.9209771469720676e-01, 9.8876426059369127e-01,
9.9539040744505636e-01, 9.9529317353008218e-01,
9.9181447411633950e-01, 1.0002584039673432e+00,
9.9968478437342512e-01, 9.9988120766657174e-01,
9.8504012146370434e-01, 7.9029849053031276e-01,
5.6082198617463974e-01, 3.3133458513996528e-01,
1.3692410840839175e-01, 1.8914906559664151e-02,
-5.1129770932550889e-06, -4.2395493167891873e-04,
-4.1934593101534273e-04, 1.7473028136486615e-03,
3.7999160177631316e-03, -5.5101474906588642e-04,
-4.3716662898480967e-05, 7.5874501748732798e-03,
2.5795650780554021e-02, 3.8168376532500548e-02,
4.9489586408030833e-02, 4.9595992290102905e-02,
4.9814819505812249e-02, 3.9840911064978023e-02,
3.0501024937233868e-02, 2.1243054765241080e-02,
6.9596532104356399e-03, 4.1733649330980525e-03 ]
cieXValues :: [Float]
# NOINLINE cieXValues #
cieXValues = [
0.0001299000, 0.0001458470, 0.0001638021, 0.0001840037,
0.0002066902, 0.0002321000, 0.0002607280, 0.0002930750,
0.0003293880, 0.0003699140, 0.0004149000, 0.0004641587,
0.0005189860, 0.0005818540, 0.0006552347, 0.0007416000,
0.0008450296, 0.0009645268, 0.001094949, 0.001231154,
0.001368000, 0.001502050, 0.001642328, 0.001802382,
0.001995757, 0.002236000, 0.002535385, 0.002892603,
0.003300829, 0.003753236, 0.004243000, 0.004762389,
0.005330048, 0.005978712, 0.006741117, 0.007650000,
0.008751373, 0.01002888, 0.01142170, 0.01286901,
0.01431000, 0.01570443, 0.01714744, 0.01878122,
0.02074801, 0.02319000, 0.02620736, 0.02978248,
0.03388092, 0.03846824, 0.04351000, 0.04899560,
0.05502260, 0.06171880, 0.06921200, 0.07763000,
0.08695811, 0.09717672, 0.1084063, 0.1207672,
0.1343800, 0.1493582, 0.1653957, 0.1819831,
0.1986110, 0.2147700, 0.2301868, 0.2448797,
0.2587773, 0.2718079, 0.2839000, 0.2949438,
0.3048965, 0.3137873, 0.3216454, 0.3285000,
0.3343513, 0.3392101, 0.3431213, 0.3461296,
0.3482800, 0.3495999, 0.3501474, 0.3500130,
0.3492870, 0.3480600, 0.3463733, 0.3442624,
0.3418088, 0.3390941, 0.3362000, 0.3331977,
0.3300411, 0.3266357, 0.3228868, 0.3187000,
0.3140251, 0.3088840, 0.3032904, 0.2972579,
0.2908000, 0.2839701, 0.2767214, 0.2689178,
0.2604227, 0.2511000, 0.2408475, 0.2298512,
0.2184072, 0.2068115, 0.1953600, 0.1842136,
0.1733273, 0.1626881, 0.1522833, 0.1421000,
0.1321786, 0.1225696, 0.1132752, 0.1042979,
0.09564000, 0.08729955, 0.07930804, 0.07171776,
0.06458099, 0.05795001, 0.05186211, 0.04628152,
0.04115088, 0.03641283, 0.03201000, 0.02791720,
0.02414440, 0.02068700, 0.01754040, 0.01470000,
0.01216179, 0.009919960, 0.007967240, 0.006296346,
0.004900000, 0.003777173, 0.002945320, 0.002424880,
0.002236293, 0.002400000, 0.002925520, 0.003836560,
0.005174840, 0.006982080, 0.009300000, 0.01214949,
0.01553588, 0.01947752, 0.02399277, 0.02910000,
0.03481485, 0.04112016, 0.04798504, 0.05537861,
0.06327000, 0.07163501, 0.08046224, 0.08973996,
0.09945645, 0.1096000, 0.1201674, 0.1311145,
0.1423679, 0.1538542, 0.1655000, 0.1772571,
0.1891400, 0.2011694, 0.2133658, 0.2257499,
0.2383209, 0.2510668, 0.2639922, 0.2771017,
0.2904000, 0.3038912, 0.3175726, 0.3314384,
0.3454828, 0.3597000, 0.3740839, 0.3886396,
0.4033784, 0.4183115, 0.4334499, 0.4487953,
0.4643360, 0.4800640, 0.4959713, 0.5120501,
0.5282959, 0.5446916, 0.5612094, 0.5778215,
0.5945000, 0.6112209, 0.6279758, 0.6447602,
0.6615697, 0.6784000, 0.6952392, 0.7120586,
0.7288284, 0.7455188, 0.7621000, 0.7785432,
0.7948256, 0.8109264, 0.8268248, 0.8425000,
0.8579325, 0.8730816, 0.8878944, 0.9023181,
0.9163000, 0.9297995, 0.9427984, 0.9552776,
0.9672179, 0.9786000, 0.9893856, 0.9995488,
1.0090892, 1.0180064, 1.0263000, 1.0339827,
1.0409860, 1.0471880, 1.0524667, 1.0567000,
1.0597944, 1.0617992, 1.0628068, 1.0629096,
1.0622000, 1.0607352, 1.0584436, 1.0552244,
1.0509768, 1.0456000, 1.0390369, 1.0313608,
1.0226662, 1.0130477, 1.0026000, 0.9913675,
0.9793314, 0.9664916, 0.9528479, 0.9384000,
0.9231940, 0.9072440, 0.8905020, 0.8729200,
0.8544499, 0.8350840, 0.8149460, 0.7941860,
0.7729540, 0.7514000, 0.7295836, 0.7075888,
0.6856022, 0.6638104, 0.6424000, 0.6215149,
0.6011138, 0.5811052, 0.5613977, 0.5419000,
0.5225995, 0.5035464, 0.4847436, 0.4661939,
0.4479000, 0.4298613, 0.4120980, 0.3946440,
0.3775333, 0.3608000, 0.3444563, 0.3285168,
0.3130192, 0.2980011, 0.2835000, 0.2695448,
0.2561184, 0.2431896, 0.2307272, 0.2187000,
0.2070971, 0.1959232, 0.1851708, 0.1748323,
0.1649000, 0.1553667, 0.1462300, 0.1374900,
0.1291467, 0.1212000, 0.1136397, 0.1064650,
0.09969044, 0.09333061, 0.08740000, 0.08190096,
0.07680428, 0.07207712, 0.06768664, 0.06360000,
0.05980685, 0.05628216, 0.05297104, 0.04981861,
0.04677000, 0.04378405, 0.04087536, 0.03807264,
0.03540461, 0.03290000, 0.03056419, 0.02838056,
0.02634484, 0.02445275, 0.02270000, 0.02108429,
0.01959988, 0.01823732, 0.01698717, 0.01584000,
0.01479064, 0.01383132, 0.01294868, 0.01212920,
0.01135916, 0.01062935, 0.009938846, 0.009288422,
0.008678854, 0.008110916, 0.007582388, 0.007088746,
0.006627313, 0.006195408, 0.005790346, 0.005409826,
0.005052583, 0.004717512, 0.004403507, 0.004109457,
0.003833913, 0.003575748, 0.003334342, 0.003109075,
0.002899327, 0.002704348, 0.002523020, 0.002354168,
0.002196616, 0.002049190, 0.001910960, 0.001781438,
0.001660110, 0.001546459, 0.001439971, 0.001340042,
0.001246275, 0.001158471, 0.001076430, 0.0009999493,
0.0009287358, 0.0008624332, 0.0008007503, 0.0007433960,
0.0006900786, 0.0006405156, 0.0005945021, 0.0005518646,
0.0005124290, 0.0004760213, 0.0004424536, 0.0004115117,
0.0003829814, 0.0003566491, 0.0003323011, 0.0003097586,
0.0002888871, 0.0002695394, 0.0002515682, 0.0002348261,
0.0002191710, 0.0002045258, 0.0001908405, 0.0001780654,
0.0001661505, 0.0001550236, 0.0001446219, 0.0001349098,
0.0001258520, 0.0001174130, 0.0001095515, 0.0001022245,
0.00009539445, 0.00008902390, 0.00008307527, 0.00007751269,
0.00007231304, 0.00006745778, 0.00006292844, 0.00005870652,
0.00005477028, 0.00005109918, 0.00004767654, 0.00004448567,
0.00004150994, 0.00003873324, 0.00003614203, 0.00003372352,
0.00003146487, 0.00002935326, 0.00002737573, 0.00002552433,
0.00002379376, 0.00002217870, 0.00002067383, 0.00001927226,
0.00001796640, 0.00001674991, 0.00001561648, 0.00001455977,
0.00001357387, 0.00001265436, 0.00001179723, 0.00001099844,
0.00001025398, 0.000009559646, 0.000008912044, 0.000008308358,
0.000007745769, 0.000007221456, 0.000006732475, 0.000006276423,
0.000005851304, 0.000005455118, 0.000005085868, 0.000004741466,
0.000004420236, 0.000004120783, 0.000003841716, 0.000003581652,
0.000003339127, 0.000003112949, 0.000002902121, 0.000002705645,
0.000002522525, 0.000002351726, 0.000002192415, 0.000002043902,
0.000001905497, 0.000001776509, 0.000001656215, 0.000001544022,
0.000001439440, 0.000001341977, 0.000001251141]
cieYValues :: [Float]
# NOINLINE cieYValues #
cieYValues = [
0.000003917000, 0.000004393581, 0.000004929604, 0.000005532136,
0.000006208245, 0.000006965000, 0.000007813219, 0.000008767336,
0.000009839844, 0.00001104323, 0.00001239000, 0.00001388641,
0.00001555728, 0.00001744296, 0.00001958375, 0.00002202000,
0.00002483965, 0.00002804126, 0.00003153104, 0.00003521521,
0.00003900000, 0.00004282640, 0.00004691460, 0.00005158960,
0.00005717640, 0.00006400000, 0.00007234421, 0.00008221224,
0.00009350816, 0.0001061361, 0.0001200000, 0.0001349840,
0.0001514920, 0.0001702080, 0.0001918160, 0.0002170000,
0.0002469067, 0.0002812400, 0.0003185200, 0.0003572667,
0.0003960000, 0.0004337147, 0.0004730240, 0.0005178760,
0.0005722187, 0.0006400000, 0.0007245600, 0.0008255000,
0.0009411600, 0.001069880, 0.001210000, 0.001362091,
0.001530752, 0.001720368, 0.001935323, 0.002180000,
0.002454800, 0.002764000, 0.003117800, 0.003526400,
0.004000000, 0.004546240, 0.005159320, 0.005829280,
0.006546160, 0.007300000, 0.008086507, 0.008908720,
0.009767680, 0.01066443, 0.01160000, 0.01257317,
0.01358272, 0.01462968, 0.01571509, 0.01684000,
0.01800736, 0.01921448, 0.02045392, 0.02171824,
0.02300000, 0.02429461, 0.02561024, 0.02695857,
0.02835125, 0.02980000, 0.03131083, 0.03288368,
0.03452112, 0.03622571, 0.03800000, 0.03984667,
0.04176800, 0.04376600, 0.04584267, 0.04800000,
0.05024368, 0.05257304, 0.05498056, 0.05745872,
0.06000000, 0.06260197, 0.06527752, 0.06804208,
0.07091109, 0.07390000, 0.07701600, 0.08026640,
0.08366680, 0.08723280, 0.09098000, 0.09491755,
0.09904584, 0.1033674, 0.1078846, 0.1126000,
0.1175320, 0.1226744, 0.1279928, 0.1334528,
0.1390200, 0.1446764, 0.1504693, 0.1564619,
0.1627177, 0.1693000, 0.1762431, 0.1835581,
0.1912735, 0.1994180, 0.2080200, 0.2171199,
0.2267345, 0.2368571, 0.2474812, 0.2586000,
0.2701849, 0.2822939, 0.2950505, 0.3085780,
0.3230000, 0.3384021, 0.3546858, 0.3716986,
0.3892875, 0.4073000, 0.4256299, 0.4443096,
0.4633944, 0.4829395, 0.5030000, 0.5235693,
0.5445120, 0.5656900, 0.5869653, 0.6082000,
0.6293456, 0.6503068, 0.6708752, 0.6908424,
0.7100000, 0.7281852, 0.7454636, 0.7619694,
0.7778368, 0.7932000, 0.8081104, 0.8224962,
0.8363068, 0.8494916, 0.8620000, 0.8738108,
0.8849624, 0.8954936, 0.9054432, 0.9148501,
0.9237348, 0.9320924, 0.9399226, 0.9472252,
0.9540000, 0.9602561, 0.9660074, 0.9712606,
0.9760225, 0.9803000, 0.9840924, 0.9874812,
0.9903128, 0.9928116, 0.9949501, 0.9967108,
0.9980983, 0.9991120, 0.9997482, 1.0000000,
0.9998567, 0.9993046, 0.9983255, 0.9968987,
0.9950000, 0.9926005, 0.9897426, 0.9864444,
0.9827241, 0.9786000, 0.9740837, 0.9691712,
0.9638568, 0.9581349, 0.9520000, 0.9454504,
0.9384992, 0.9311628, 0.9234576, 0.9154000,
0.9070064, 0.8982772, 0.8892048, 0.8797816,
0.8700000, 0.8598613, 0.8493920, 0.8386220,
0.8275813, 0.8163000, 0.8047947, 0.7930820,
0.7811920, 0.7691547, 0.7570000, 0.7447541,
0.7324224, 0.7200036, 0.7074965, 0.6949000,
0.6822192, 0.6694716, 0.6566744, 0.6438448,
0.6310000, 0.6181555, 0.6053144, 0.5924756,
0.5796379, 0.5668000, 0.5539611, 0.5411372,
0.5283528, 0.5156323, 0.5030000, 0.4904688,
0.4780304, 0.4656776, 0.4534032, 0.4412000,
0.4290800, 0.4170360, 0.4050320, 0.3930320,
0.3810000, 0.3689184, 0.3568272, 0.3447768,
0.3328176, 0.3210000, 0.3093381, 0.2978504,
0.2865936, 0.2756245, 0.2650000, 0.2547632,
0.2448896, 0.2353344, 0.2260528, 0.2170000,
0.2081616, 0.1995488, 0.1911552, 0.1829744,
0.1750000, 0.1672235, 0.1596464, 0.1522776,
0.1451259, 0.1382000, 0.1315003, 0.1250248,
0.1187792, 0.1127691, 0.1070000, 0.1014762,
0.09618864, 0.09112296, 0.08626485, 0.08160000,
0.07712064, 0.07282552, 0.06871008, 0.06476976,
0.06100000, 0.05739621, 0.05395504, 0.05067376,
0.04754965, 0.04458000, 0.04175872, 0.03908496,
0.03656384, 0.03420048, 0.03200000, 0.02996261,
0.02807664, 0.02632936, 0.02470805, 0.02320000,
0.02180077, 0.02050112, 0.01928108, 0.01812069,
0.01700000, 0.01590379, 0.01483718, 0.01381068,
0.01283478, 0.01192000, 0.01106831, 0.01027339,
0.009533311, 0.008846157, 0.008210000, 0.007623781,
0.007085424, 0.006591476, 0.006138485, 0.005723000,
0.005343059, 0.004995796, 0.004676404, 0.004380075,
0.004102000, 0.003838453, 0.003589099, 0.003354219,
0.003134093, 0.002929000, 0.002738139, 0.002559876,
0.002393244, 0.002237275, 0.002091000, 0.001953587,
0.001824580, 0.001703580, 0.001590187, 0.001484000,
0.001384496, 0.001291268, 0.001204092, 0.001122744,
0.001047000, 0.0009765896, 0.0009111088, 0.0008501332,
0.0007932384, 0.0007400000, 0.0006900827, 0.0006433100,
0.0005994960, 0.0005584547, 0.0005200000, 0.0004839136,
0.0004500528, 0.0004183452, 0.0003887184, 0.0003611000,
0.0003353835, 0.0003114404, 0.0002891656, 0.0002684539,
0.0002492000, 0.0002313019, 0.0002146856, 0.0001992884,
0.0001850475, 0.0001719000, 0.0001597781, 0.0001486044,
0.0001383016, 0.0001287925, 0.0001200000, 0.0001118595,
0.0001043224, 0.00009733560, 0.00009084587, 0.00008480000,
0.00007914667, 0.00007385800, 0.00006891600, 0.00006430267,
0.00006000000, 0.00005598187, 0.00005222560, 0.00004871840,
0.00004544747, 0.00004240000, 0.00003956104, 0.00003691512,
0.00003444868, 0.00003214816, 0.00003000000, 0.00002799125,
0.00002611356, 0.00002436024, 0.00002272461, 0.00002120000,
0.00001977855, 0.00001845285, 0.00001721687, 0.00001606459,
0.00001499000, 0.00001398728, 0.00001305155, 0.00001217818,
0.00001136254, 0.00001060000, 0.000009885877, 0.000009217304,
0.000008592362, 0.000008009133, 0.000007465700, 0.000006959567,
0.000006487995, 0.000006048699, 0.000005639396, 0.000005257800,
0.000004901771, 0.000004569720, 0.000004260194, 0.000003971739,
0.000003702900, 0.000003452163, 0.000003218302, 0.000003000300,
0.000002797139, 0.000002607800, 0.000002431220, 0.000002266531,
0.000002113013, 0.000001969943, 0.000001836600, 0.000001712230,
0.000001596228, 0.000001488090, 0.000001387314, 0.000001293400,
0.000001205820, 0.000001124143, 0.000001048009, 0.0000009770578,
0.0000009109300, 0.0000008492513, 0.0000007917212, 0.0000007380904,
0.0000006881098, 0.0000006415300, 0.0000005980895, 0.0000005575746,
0.0000005198080, 0.0000004846123, 0.0000004518100 ]
cieZValues :: [Float]
# NOINLINE cieZValues #
cieZValues = [
0.0006061000, 0.0006808792, 0.0007651456, 0.0008600124,
0.0009665928, 0.001086000, 0.001220586, 0.001372729,
0.001543579, 0.001734286, 0.001946000, 0.002177777,
0.002435809, 0.002731953, 0.003078064, 0.003486000,
0.003975227, 0.004540880, 0.005158320, 0.005802907,
0.006450001, 0.007083216, 0.007745488, 0.008501152,
0.009414544, 0.01054999, 0.01196580, 0.01365587,
0.01558805, 0.01773015, 0.02005001, 0.02251136,
0.02520288, 0.02827972, 0.03189704, 0.03621000,
0.04143771, 0.04750372, 0.05411988, 0.06099803,
0.06785001, 0.07448632, 0.08136156, 0.08915364,
0.09854048, 0.1102000, 0.1246133, 0.1417017,
0.1613035, 0.1832568, 0.2074000, 0.2336921,
0.2626114, 0.2947746, 0.3307985, 0.3713000,
0.4162091, 0.4654642, 0.5196948, 0.5795303,
0.6456000, 0.7184838, 0.7967133, 0.8778459,
0.9594390, 1.0390501, 1.1153673, 1.1884971,
1.2581233, 1.3239296, 1.3856000, 1.4426352,
1.4948035, 1.5421903, 1.5848807, 1.6229600,
1.6564048, 1.6852959, 1.7098745, 1.7303821,
1.7470600, 1.7600446, 1.7696233, 1.7762637,
1.7804334, 1.7826000, 1.7829682, 1.7816998,
1.7791982, 1.7758671, 1.7721100, 1.7682589,
1.7640390, 1.7589438, 1.7524663, 1.7441000,
1.7335595, 1.7208581, 1.7059369, 1.6887372,
1.6692000, 1.6475287, 1.6234127, 1.5960223,
1.5645280, 1.5281000, 1.4861114, 1.4395215,
1.3898799, 1.3387362, 1.2876400, 1.2374223,
1.1878243, 1.1387611, 1.0901480, 1.0419000,
0.9941976, 0.9473473, 0.9014531, 0.8566193,
0.8129501, 0.7705173, 0.7294448, 0.6899136,
0.6521049, 0.6162000, 0.5823286, 0.5504162,
0.5203376, 0.4919673, 0.4651800, 0.4399246,
0.4161836, 0.3938822, 0.3729459, 0.3533000,
0.3348578, 0.3175521, 0.3013375, 0.2861686,
0.2720000, 0.2588171, 0.2464838, 0.2347718,
0.2234533, 0.2123000, 0.2011692, 0.1901196,
0.1792254, 0.1685608, 0.1582000, 0.1481383,
0.1383758, 0.1289942, 0.1200751, 0.1117000,
0.1039048, 0.09666748, 0.08998272, 0.08384531,
0.07824999, 0.07320899, 0.06867816, 0.06456784,
0.06078835, 0.05725001, 0.05390435, 0.05074664,
0.04775276, 0.04489859, 0.04216000, 0.03950728,
0.03693564, 0.03445836, 0.03208872, 0.02984000,
0.02771181, 0.02569444, 0.02378716, 0.02198925,
0.02030000, 0.01871805, 0.01724036, 0.01586364,
0.01458461, 0.01340000, 0.01230723, 0.01130188,
0.01037792, 0.009529306, 0.008749999, 0.008035200,
0.007381600, 0.006785400, 0.006242800, 0.005749999,
0.005303600, 0.004899800, 0.004534200, 0.004202400,
0.003900000, 0.003623200, 0.003370600, 0.003141400,
0.002934800, 0.002749999, 0.002585200, 0.002438600,
0.002309400, 0.002196800, 0.002100000, 0.002017733,
0.001948200, 0.001889800, 0.001840933, 0.001800000,
0.001766267, 0.001737800, 0.001711200, 0.001683067,
0.001650001, 0.001610133, 0.001564400, 0.001513600,
0.001458533, 0.001400000, 0.001336667, 0.001270000,
0.001205000, 0.001146667, 0.001100000, 0.001068800,
0.001049400, 0.001035600, 0.001021200, 0.001000000,
0.0009686400, 0.0009299200, 0.0008868800, 0.0008425600,
0.0008000000, 0.0007609600, 0.0007236800, 0.0006859200,
0.0006454400, 0.0006000000, 0.0005478667, 0.0004916000,
0.0004354000, 0.0003834667, 0.0003400000, 0.0003072533,
0.0002831600, 0.0002654400, 0.0002518133, 0.0002400000,
0.0002295467, 0.0002206400, 0.0002119600, 0.0002021867,
0.0001900000, 0.0001742133, 0.0001556400, 0.0001359600,
0.0001168533, 0.0001000000, 0.00008613333, 0.00007460000,
0.00006500000, 0.00005693333, 0.00004999999, 0.00004416000,
0.00003948000, 0.00003572000, 0.00003264000, 0.00003000000,
0.00002765333, 0.00002556000, 0.00002364000, 0.00002181333,
0.00002000000, 0.00001813333, 0.00001620000, 0.00001420000,
0.00001213333, 0.00001000000, 0.000007733333, 0.000005400000,
0.000003200000, 0.000001333333, 0.000000000000, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0 ]
| null | https://raw.githubusercontent.com/waldheinz/bling/1f338f4b8dbd6a2708cb10787f4a2ac55f66d5a8/src/lib/Graphics/Bling/Spectrum.hs | haskell | # LANGUAGE BangPatterns #
* Spectrum conversions
* Working with SPDs
| the number of spectral bands we use for a spectrum
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| a "black" @Spectrum@ (no transmittance or emission at all wavelengths)
| a "white" @Spectrum@ (unit transmission at all wavelengths)
by this function.
c, m, y
w
^ (X, Y, Z)
------------------------------------------------------------------------------
ImageSample and the like
------------------------------------------------------------------------------
# UNPACK #
the sample weight and the sampled spectrum
the pixel coordinates and the weighted spectrum
------------------------------------------------------------------------------
SPDs
------------------------------------------------------------------------------
# UNPACK #
min lambda
# UNPACK #
max lambda
amplitudes
defined by a function
not be empty
^ the wavelength of the last amplitude sample
binary search for index
^ the Spd to evaluate
^ the minimum wavelength of interest
^ the maximum wavelength of interest, must be >= the minimum
| converts from a @Spd@ to @Spectrum@
| the brightness
# INLINE (**) #
# INLINE asin #
# INLINE (/) #
# INLINE (+) #
# INLINE (-) #
# INLINE (*) #
| Decides if a @Spectrum@ is black
| clamps the @Spectrum@ coefficients the specified range
# INLINE sClamp #
# INLINE sClamp' #
| The spectrum of a black body emitter
^ the emission spectrum of the emitter
p = (\wl -> planck t (fromIntegral wl))
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Only boring tables below
------------------------------------------------------------------------------ | # LANGUAGE TypeFamilies #
# LANGUAGE MultiParamTypeClasses #
module Graphics.Bling.Spectrum (
Spectrum, WeightedSpectrum(..), ImageSample, Contribution,
white, black,
rgbToSpectrumRefl, rgbToSpectrumIllum, unGamma,
Spd, mkSpd, mkSpd', mkSpdFunc, fromCIExy, spdToXYZ, evalSpd,
isBlack, sNaN, sInfinite,
xyzToRgb, toRGB, fromSpd, sConst, sBlackBody, sY,
sScale, sPow, sClamp, sClamp', chromaticityToXYZ,
spectrumToXYZ, xyzToSpectrum
) where
import Control.Monad (liftM, forM_)
import Data.List (sortBy)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Generic as GV
import qualified Data.Vector.Generic.Mutable as MV
import Control.DeepSeq as DS
import Prelude as P
import Graphics.Bling.Math
bands :: Int
# INLINE bands #
bands = 16
spectrumLambdaStart :: Float
# INLINE spectrumLambdaStart #
spectrumLambdaStart = 400
spectrumLambdaEnd :: Float
# INLINE spectrumLambdaEnd #
spectrumLambdaEnd = 700
newtype Spectrum = Spectrum { unSpectrum :: V.Vector Float } deriving (Show)
instance DS.NFData Spectrum where
rnf (Spectrum v) = seq v ()
# INLINE rnf #
Unboxed Vectors of Spectra
newtype instance V.MVector s Spectrum = MV_Spectrum (V.MVector s Float)
newtype instance V.Vector Spectrum = V_Spectrum (V.Vector Float)
instance V.Unbox Spectrum
instance MV.MVector V.MVector Spectrum where
basicLength (MV_Spectrum v) = MV.basicLength v `div` bands
# INLINE basicLength #
basicUnsafeSlice s l (MV_Spectrum v) =
MV_Spectrum (MV.unsafeSlice (s * bands) (l * bands) v)
# INLINE basicUnsafeSlice #
basicUnsafeNew l = MV_Spectrum `liftM` MV.unsafeNew (l * bands)
# INLINE basicUnsafeNew #
basicInitialize _ = return ()
basicOverlaps (MV_Spectrum v1) (MV_Spectrum v2) = MV.overlaps v1 v2
# INLINE basicOverlaps #
basicUnsafeRead (MV_Spectrum v) idx =
V.generateM bands (\i -> MV.unsafeRead v $(idx * bands) + i)
>>= \v' -> return (Spectrum v')
# INLINE basicUnsafeRead #
basicUnsafeWrite (MV_Spectrum v) idx (Spectrum vs) =
forM_ [0..bands-1] $ \i -> MV.unsafeWrite v ((idx * bands) + i) (V.unsafeIndex vs i)
# INLINE basicUnsafeWrite #
instance GV.Vector V.Vector Spectrum where
basicLength (V_Spectrum v) = GV.basicLength v `div` bands
# INLINE basicLength #
basicUnsafeSlice s l (V_Spectrum v) =
V_Spectrum $ (GV.unsafeSlice (s * bands) (l * bands) v)
# INLINE basicUnsafeSlice #
basicUnsafeFreeze (MV_Spectrum v) = V_Spectrum `liftM` (GV.unsafeFreeze v)
# INLINE basicUnsafeFreeze #
basicUnsafeThaw (V_Spectrum v) = MV_Spectrum `liftM` (GV.unsafeThaw v)
# INLINE basicUnsafeThaw #
basicUnsafeIndexM (V_Spectrum v) idx =
V.generateM bands (\i -> GV.unsafeIndexM v ((idx * bands) + i))
>>= \v' -> return (Spectrum v')
# INLINE basicUnsafeIndexM #
black :: Spectrum
# INLINE black #
black = sConst 0
white :: Spectrum
# INLINE white #
white = sConst 1
| Removes the gamma correction from a RGB triple . The supplied RGB value is
supposed to have a gamma correction of 2.2 applied , which is reversed
unGamma :: (Float, Float, Float) -> (Float, Float, Float)
# INLINE unGamma #
unGamma (r, g, b) = let ga = 2.2 in (r ** ga, g ** ga, b ** ga)
data RGBToSpectrumBase =
RGBBases
r , , b
rgbReflectance :: RGBToSpectrumBase
rgbReflectance = RGBBases
rgbReflRed rgbReflGreen rgbReflBlue
rgbReflCyan rgbReflMagenta rgbReflYellow
rgbReflWhite
rgbIlluminant :: RGBToSpectrumBase
rgbIlluminant = RGBBases
rgbIllumRed rgbIllumGreen rgbIllumBlue
rgbIllumCyan rgbIllumMagenta rgbIllumYellow
rgbIllumWhite
rgbToSpectrumRefl :: (Float, Float, Float) -> Spectrum
rgbToSpectrumRefl = rgbToSpectrum rgbReflectance
rgbToSpectrumIllum :: (Float, Float, Float) -> Spectrum
rgbToSpectrumIllum = rgbToSpectrum rgbIlluminant
rgbToSpectrum :: RGBToSpectrumBase -> (Float, Float, Float) -> Spectrum
rgbToSpectrum (RGBBases rb gb bb cb mb yb wb) (r, g, b)
| r <= g && r <= b =
sScale wb r + if g <= b
then sScale cb (g - r) + sScale bb (b - g)
else sScale cb (b - r) + sScale gb (g - b)
| g <= r && g <= b =
sScale wb g + if r <= b
then sScale mb (r - g) + sScale bb (b - r)
else sScale mb (b - g) + sScale rb (r - b)
| otherwise =
sScale wb b + if r <= b
then sScale yb (r - b) + sScale gb (g - r)
else sScale yb (g - b) + sScale rb (r - g)
| converts from CIE XYZ to sRGB
xyzToRgb
^ ( r , , b )
xyzToRgb (x, y, z) = (r, g, b) where
r = 3.240479 * x - 1.537150 * y - 0.498535 * z
g = (-0.969256) * x + 1.875991 * y + 0.041556 * z
b = 0.055648 * x - 0.204043 * y + 1.057311 * z
type Contribution = (Bool, ImageSample)
data Spd
= IrregularSpd
{ _spdLambdas :: !(V.Vector Float)
, _spdValues :: !(V.Vector Float) }
| RegularSpd
| Chromaticity
M1
M2
| SpdFunc
| creates a SPD from a list of ( lambda , value ) pairs , which must
mkSpd
^ the SPD as ( lambda , amplitude ) pairs
-> Spd
mkSpd [] = error "empty SPD"
mkSpd xs = IrregularSpd ls vs where
ls = V.fromList (P.map fst sorted)
vs = V.fromList (P.map snd sorted)
sorted = sortBy cmp xs
cmp (l1, _) (l2, _) = compare l1 l2
| creates a SPD from a list of regulary sampled amplitudes
mkSpd'
^ the wavelength of the first amplitude sample
^ the amplitudes of the SPD , must not be empty
^ the resulting SPD
mkSpd' s e vs = RegularSpd s e (V.fromList vs)
mkSpdFunc
^ the SPD function from lambda in nanometers to amplitude
-> Spd
mkSpdFunc = SpdFunc
fromCIExy
:: Float
-> Float
-> Spd
fromCIExy x y = Chromaticity m1 m2 where
(m1, m2) = chromaParams x y
chromaParams :: Float -> Float -> (Float, Float)
chromaParams x y = (m1, m2) where
m1 = (-1.3515 - 1.7703 * x + 5.9114 * y) / (0.0241 + 0.2562 * x - 0.7341 * y)
m2 = (0.03 - 31.4424 * x + 30.0717 * y) / (0.0241 + 0.2562 * x - 0.7341 * y)
s0XYZ :: (Float, Float, Float)
s0XYZ = spdToXYZ cieS0
s1XYZ :: (Float, Float, Float)
s1XYZ = spdToXYZ cieS1
s2XYZ :: (Float, Float, Float)
s2XYZ = spdToXYZ cieS2
chromaticityToXYZ :: Float -> Float -> (Float, Float, Float)
chromaticityToXYZ x y = (x', y', z') where
(s0x, s0y, s0z) = s0XYZ
(s1x, s1y, s1z) = s1XYZ
(s2x, s2y, s2z) = s2XYZ
(m1, m2) = chromaParams x y
x' = s0x + m1 * s1x + m2 * s2x
y' = s0y + m1 * s1y + m2 * s2y
z' = s0z + m1 * s1z + m2 * s2z
| evaluates a SPD at a given wavelength
evalSpd
^ the SPD to evaluate
^ the lambda where the SPD should be evaluated
^ the SPD value at the specified lambda
evalSpd (IrregularSpd ls vs) l
| l <= V.head ls = V.head vs
| l >= V.last ls = V.last vs
| otherwise = lerp t (vs V.! i) (vs V.! (i+1)) where
t = (l - (ls V.! i)) / ((ls V.! (i+1)) - (ls V.! i))
i = fi 0 (V.length ls - 1)
| lo == mid = lo
| (ls V.! mid) == l = mid
| (ls V.! mid) < l = fi mid hi
| otherwise = fi lo mid where
mid = (lo + hi) `div` 2
evalSpd (RegularSpd l0 l1 amps) l
| l <= l0 = V.head amps
| l >= l1 = V.last amps
| otherwise = (1 - dx) * (amps V.! b0) + dx * (amps V.! b1)
where
1 / delta
x = (l - l0) * d1
b0 = floor x
b1 = min (b0 + 1) (V.length amps - 1)
dx = x - fromIntegral b0
evalSpd (Chromaticity m1 m2) l = s0 + m1 * s1 + m2 * s2 where
s0 = evalSpd cieS0 l
s1 = evalSpd cieS1 l
s2 = evalSpd cieS2 l
evalSpd (SpdFunc f) l = f l
| determines the average value of a @Spd@ in the specified interval
TODO : should compute the weighted average
avgSpd
-> Float
avgSpd (RegularSpd s0 s1 amps) l0 l1
| l1 <= s0 = V.head amps
| l0 >= s1 = V.last amps
| otherwise = V.sum amps' / fromIntegral (V.length amps')
where
amps' = V.slice i0 (i1 - i0 + 1) amps
n = V.length amps
i0 = max 0 $ min n $ floor $ fromIntegral n * ((l0 - s0) / (s1 - s0))
i1 = max 0 $ min n $ floor $ fromIntegral n * ((l1 - s0) / (s1 - s0))
avgSpd (IrregularSpd ls vs) l0 l1
| l1 <= V.head ls = V.head vs
| l0 >= V.last ls = V.last vs
| otherwise = V.sum vs' / fromIntegral (V.length vs')
where
vs' = V.slice i0 (i1 - i0 + 1) vs
i0 = maybe 0 id $ V.findIndex (>= l0) ls
i1 = maybe (V.length vs - 1) id $ V.findIndex (>= l1) ls
avgSpd spd l0 l1 = (evalSpd spd l0 + evalSpd spd l1) * 0.5
| converts a @Spd@ to CIE XYZ values
spdToXYZ :: Spd -> (Float, Float, Float)
spdToXYZ spd = (x / yint, y / yint, z / yint) where
ls = [cieStart .. cieEnd]
vs = P.map (\l -> evalSpd spd (fromIntegral l)) ls
yint = P.sum (P.map (\l -> evalSpd cieY (fromIntegral l)) ls)
x = P.sum $ P.zipWith (*) (P.map (\l -> evalSpd cieX (fromIntegral l)) ls) vs
y = P.sum $ P.zipWith (*) (P.map (\l -> evalSpd cieY (fromIntegral l)) ls) vs
z = P.sum $ P.zipWith (*) (P.map (\l -> evalSpd cieZ (fromIntegral l)) ls) vs
fromSpd
:: Spd
-> Spectrum
fromSpd spd = Spectrum $ V.generate bands go where
go i = avgSpd spd l0 l1 where
l0 = lerp (fromIntegral i / fromIntegral bands) spectrumLambdaStart spectrumLambdaEnd
l1 = lerp (fromIntegral (i+1) / fromIntegral bands) spectrumLambdaStart spectrumLambdaEnd
spectrumCieX :: Spectrum
spectrumCieX = fromSpd cieX
spectrumCieY :: Spectrum
spectrumCieY = fromSpd cieY
spectrumCieZ :: Spectrum
spectrumCieZ = fromSpd cieZ
spectrumCieYSum :: Float
spectrumCieYSum = V.sum $ unSpectrum spectrumCieY
spectrumToXYZ :: Spectrum -> (Float, Float, Float)
spectrumToXYZ s = scale $ V.foldl' (\(a, b, c) (v, x, y, z) -> (a + x * v, b + y * v, c + z * v)) (0, 0, 0) $ V.zip4 vsv vsx vsy vsz where
vsx = unSpectrum spectrumCieX
vsy = unSpectrum spectrumCieY
vsz = unSpectrum spectrumCieZ
vsv = unSpectrum s
scale (x, y, z) = (x / spectrumCieYSum, y / spectrumCieYSum, z / spectrumCieYSum)
xyzToSpectrum :: (Float, Float, Float) -> Spectrum
xyzToSpectrum = rgbToSpectrumIllum . xyzToRgb
xyzToSpectrum ( x , y , z ) =
sScale spectrumCieX ( x / spectrumCieYSum ) +
sScale spectrumCieY ( y / spectrumCieYSum ) +
sScale ( z / spectrumCieYSum )
xyzToSpectrum (x, y, z) =
sScale spectrumCieX (x / spectrumCieYSum) +
sScale spectrumCieY (y / spectrumCieYSum) +
sScale spectrumCieZ (z / spectrumCieYSum)
-}
toRGB :: Spectrum -> (Float, Float, Float)
# INLINE toRGB #
toRGB (Spectrum v) = (v V.! 0, v V.! 1, v V.! 2)
sY :: Spectrum -> Float
# INLINE sY #
sY (Spectrum v) = (V.sum $ V.zipWith (*) v $ unSpectrum spectrumCieY) / spectrumCieYSum
sConst :: Float -> Spectrum
# INLINE sConst #
sConst r = Spectrum $ V.replicate bands r
sMap :: (Float -> Float) -> Spectrum -> Spectrum
# INLINE sMap #
sMap f s = Spectrum $ V.map f $ unSpectrum s
instance Floating Spectrum where
pi = sConst pi
# INLINE pi #
exp = sMap exp
# INLINE exp #
sqrt = sMap sqrt
# INLINE sqrt #
log = sMap log
# INLINE log #
(**) (Spectrum s1) (Spectrum s2) = Spectrum $ V.zipWith (**) s1 s2
logBase (Spectrum s1) (Spectrum s2) = Spectrum $ V.zipWith logBase s1 s2
# INLINE logBase #
sin = sMap sin
# INLINE sin #
tan = sMap tan
# INLINE tan #
cos = sMap cos
# INLINE cos #
asin = sMap asin
atan = sMap atan
# INLINE atan #
acos = sMap acos
# INLINE acos #
sinh = sMap sinh
# INLINE sinh #
tanh = sMap tanh
# INLINE tanh #
cosh = sMap cosh
# INLINE cosh #
asinh = sMap asinh
# INLINE asinh #
atanh = sMap atanh
# INLINE atanh #
acosh = sMap acosh
# INLINE acosh #
instance Fractional Spectrum where
Spectrum v1 / Spectrum v2 = Spectrum $ V.zipWith (/) v1 v2
fromRational i = Spectrum $ V.replicate bands (fromRational i)
# INLINE fromRational #
instance Num Spectrum where
Spectrum v1 + Spectrum v2 = Spectrum $ V.zipWith (+) v1 v2
Spectrum v1 - Spectrum v2 = Spectrum $ V.zipWith (-) v1 v2
Spectrum v1 * Spectrum v2 = Spectrum $ V.zipWith (*) v1 v2
abs (Spectrum v) = Spectrum $ V.map abs v
# INLINE abs #
negate (Spectrum v) = Spectrum $ V.map negate v
# INLINE negate #
signum (Spectrum v) = Spectrum $ V.map signum v
# INLINE signum #
fromInteger i = Spectrum $ V.replicate bands (fromInteger i)
# INLINE fromInteger #
isBlack :: Spectrum -> Bool
# INLINE isBlack #
isBlack (Spectrum v) = V.all (== 0) v
sScale :: Spectrum -> Float -> Spectrum
# INLINE sScale #
sScale (Spectrum v) f = Spectrum $ V.map (*f) v
sClamp :: Float -> Float -> Spectrum -> Spectrum
sClamp smin smax (Spectrum v) = Spectrum $ V.map c v where
c x = max smin $ min smax x
| clamps the @Spectrum@ coefficients to [ 0,1 ]
sClamp' :: Spectrum -> Spectrum
sClamp' = sClamp 0 1
sNaN :: Spectrum -> Bool
# INLINE sNaN #
sNaN (Spectrum v) = V.any isNaN v
sInfinite :: Spectrum -> Bool
# INLINE sInfinite #
sInfinite (Spectrum v) = V.any isInfinite v
sPow :: Spectrum -> Spectrum -> Spectrum
# INLINE sPow #
sPow (Spectrum vc) (Spectrum ve) = Spectrum (V.zipWith p' vc ve) where
p' :: Float -> Float -> Float
p' c e
| c > 0 = c ** e
| otherwise = 0
sBlackBody
^ the temperature in Kelvin
sBlackBody t = fromSpd $ mkSpdFunc (planck t)
sScale ( fromXYZ ( x , y , z ) ) ( 1 / ( fromIntegral ( cieEnd - cieStart ) ) ) where
z = max 0 $ P.sum $ P.map ( \wl - > ( wl ) * ( p wl ) ) [ cieStart .. cieEnd ]
y = max 0 $ P.sum $ P.map ( \wl - > ( cieY wl ) * ( p wl ) ) [ cieStart .. cieEnd ]
x = max 0 $ P.sum $ P.map ( \wl - > ( cieX wl ) * ( p wl ) ) [ cieStart .. cieEnd ]
planck :: RealFloat a => a -> a -> a
planck temp w = (0.4e-9 * (3.74183e-16 * w' ^^ (-5::Int))) / (exp (1.4388e-2 / (w' * temp)) - 1) where
w' = w * 1e-9
CIE chromaticity SPDs
cieS0 :: Spd
cieS0 = mkSpd' 300 830
[ 0.04, 6.0, 29.6, 55.3, 57.3, 61.8, 61.5, 68.8, 63.4,
65.8, 94.8, 104.8, 105.9, 96.8, 113.9, 125.6, 125.5, 121.3,
121.3, 113.5, 113.1, 110.8, 106.5, 108.8, 105.3, 104.4, 100.0,
96.0, 95.1, 89.1, 90.5, 90.3, 88.4, 84.0, 85.1, 81.9,
82.6, 84.9, 81.3, 71.9, 74.3, 76.4, 63.3, 71.7, 77.0,
65.2, 47.7, 68.6, 65.0, 66.0, 61.0, 53.3, 58.9, 61.9 ]
cieS1 :: Spd
cieS1 = mkSpd' 300 830
[ 0.02, 4.5, 22.4, 42.0, 40.6, 41.6, 38.0, 42.4, 38.5, 35.0, 43.4,
46.3, 43.9, 37.1, 36.7, 35.9, 32.6, 27.9, 24.3, 20.1, 16.2, 13.2,
8.6, 6.1, 4.2, 1.9, 0.0, -1.6, -3.5, -3.5, -5.8, -7.2, -8.6, -9.5,
-10.9, -10.7, -12.0, -14.0, -13.6, -12.0, -13.3, -12.9, -10.6,
-11.6, -12.2, -10.2, -7.8, -11.2, -10.4, -10.6, -9.7, -8.3, -9.3, -9.8]
cieS2 :: Spd
cieS2 = mkSpd' 300 830
[ 0.0, 2.0, 4.0, 8.5, 7.8, 6.7, 5.3, 6.1, 3.0, 1.2, -1.1, -0.5, -0.7,
-1.2, -2.6, -2.9, -2.8, -2.6, -2.6, -1.8, -1.5, -1.3, -1.2, -1.0,
-0.5, -0.3, 0.0, 0.2, 0.5, 2.1, 3.2, 4.1, 4.7, 5.1, 6.7, 7.3, 8.6,
9.8, 10.2, 8.3, 9.6, 8.5, 7.0, 7.6, 8.0, 6.7, 5.2, 7.4, 6.8, 7.0,
6.4, 5.5, 6.1, 6.5]
CIE XYZ SPDs
cieStart :: Int
cieStart = 360
cieEnd :: Int
cieEnd = 830
cieSpd :: [Float] -> Spd
cieSpd = mkSpd' (fromIntegral cieStart) (fromIntegral cieEnd)
cieX :: Spd
cieX = cieSpd cieXValues
cieY :: Spd
cieY = cieSpd cieYValues
cieZ :: Spd
cieZ = cieSpd cieZValues
rgbToSpectrumStart :: Float
rgbToSpectrumStart = 380
rgbToSpectrumEnd :: Float
rgbToSpectrumEnd = 720
rgbFunc :: [Float] -> Spectrum
rgbFunc vs = fromSpd $ mkSpd' rgbToSpectrumStart rgbToSpectrumEnd vs
rgbIllumWhite :: Spectrum
rgbIllumWhite = rgbFunc
[ 1.1565232050369776e+00, 1.1567225000119139e+00, 1.1566203150243823e+00,
1.1555782088080084e+00, 1.1562175509215700e+00, 1.1567674012207332e+00,
1.1568023194808630e+00, 1.1567677445485520e+00, 1.1563563182952830e+00,
1.1567054702510189e+00, 1.1565134139372772e+00, 1.1564336176499312e+00,
1.1568023181530034e+00, 1.1473147688514642e+00, 1.1339317140561065e+00,
1.1293876490671435e+00, 1.1290515328639648e+00, 1.0504864823782283e+00,
1.0459696042230884e+00, 9.9366687168595691e-01, 9.5601669265393940e-01,
9.2467482033511805e-01, 9.1499944702051761e-01, 8.9939467658453465e-01,
8.9542520751331112e-01, 8.8870566693814745e-01, 8.8222843814228114e-01,
8.7998311373826676e-01, 8.7635244612244578e-01, 8.8000368331709111e-01,
8.8065665428441120e-01, 8.8304706460276905e-01 ]
rgbIllumCyan :: Spectrum
rgbIllumCyan = rgbFunc
[ 1.1334479663682135e+00, 1.1266762330194116e+00, 1.1346827504710164e+00,
1.1357395805744794e+00, 1.1356371830149636e+00, 1.1361152989346193e+00,
1.1362179057706772e+00, 1.1364819652587022e+00, 1.1355107110714324e+00,
1.1364060941199556e+00, 1.1360363621722465e+00, 1.1360122641141395e+00,
1.1354266882467030e+00, 1.1363099407179136e+00, 1.1355450412632506e+00,
1.1353732327376378e+00, 1.1349496420726002e+00, 1.1111113947168556e+00,
9.0598740429727143e-01, 6.1160780787465330e-01, 2.9539752170999634e-01,
9.5954200671150097e-02,-1.1650792030826267e-02,-1.2144633073395025e-02,
-1.1148167569748318e-02,-1.1997606668458151e-02,-5.0506855475394852e-03,
-7.9982745819542154e-03,-9.4722817708236418e-03,-5.5329541006658815e-03,
-4.5428914028274488e-03,-1.2541015360921132e-02 ]
rgbIllumMagenta :: Spectrum
rgbIllumMagenta = rgbFunc
[ 1.0371892935878366e+00, 1.0587542891035364e+00, 1.0767271213688903e+00,
1.0762706844110288e+00, 1.0795289105258212e+00, 1.0743644742950074e+00,
1.0727028691194342e+00, 1.0732447452056488e+00, 1.0823760816041414e+00,
1.0840545681409282e+00, 9.5607567526306658e-01, 5.5197896855064665e-01,
8.4191094887247575e-02, 8.7940070557041006e-05,-2.3086408335071251e-03,
-1.1248136628651192e-03,-7.7297612754989586e-11,-2.7270769006770834e-04,
1.4466473094035592e-02, 2.5883116027169478e-01, 5.2907999827566732e-01,
9.0966624097105164e-01, 1.0690571327307956e+00, 1.0887326064796272e+00,
1.0637622289511852e+00, 1.0201812918094260e+00, 1.0262196688979945e+00,
1.0783085560613190e+00, 9.8333849623218872e-01, 1.0707246342802621e+00,
1.0634247770423768e+00, 1.0150875475729566e+00 ]
rgbIllumYellow :: Spectrum
rgbIllumYellow = rgbFunc
[ 2.7756958965811972e-03, 3.9673820990646612e-03,-1.4606936788606750e-04,
3.6198394557748065e-04,-2.5819258699309733e-04,-5.0133191628082274e-05,
-2.4437242866157116e-04,-7.8061419948038946e-05, 4.9690301207540921e-02,
4.8515973574763166e-01, 1.0295725854360589e+00, 1.0333210878457741e+00,
1.0368102644026933e+00, 1.0364884018886333e+00, 1.0365427939411784e+00,
1.0368595402854539e+00, 1.0365645405660555e+00, 1.0363938240707142e+00,
1.0367205578770746e+00, 1.0365239329446050e+00, 1.0361531226427443e+00,
1.0348785007827348e+00, 1.0042729660717318e+00, 8.4218486432354278e-01,
7.3759394894801567e-01, 6.5853154500294642e-01, 6.0531682444066282e-01,
5.9549794132420741e-01, 5.9419261278443136e-01, 5.6517682326634266e-01,
5.6061186014968556e-01, 5.8228610381018719e-01 ]
rgbIllumRed :: Spectrum
rgbIllumRed = rgbFunc
[ 5.4711187157291841e-02, 5.5609066498303397e-02, 6.0755873790918236e-02,
5.6232948615962369e-02, 4.6169940535708678e-02, 3.8012808167818095e-02,
2.4424225756670338e-02, 3.8983580581592181e-03,-5.6082252172734437e-04,
9.6493871255194652e-04, 3.7341198051510371e-04,-4.3367389093135200e-04,
-9.3533962256892034e-05,-1.2354967412842033e-04,-1.4524548081687461e-04,
-2.0047691915543731e-04,-4.9938587694693670e-04, 2.7255083540032476e-02,
1.6067405906297061e-01, 3.5069788873150953e-01, 5.7357465538418961e-01,
7.6392091890718949e-01, 8.9144466740381523e-01, 9.6394609909574891e-01,
9.8879464276016282e-01, 9.9897449966227203e-01, 9.8605140403564162e-01,
9.9532502805345202e-01, 9.7433478377305371e-01, 9.9134364616871407e-01,
9.8866287772174755e-01, 9.9713856089735531e-01 ]
rgbIllumGreen :: Spectrum
rgbIllumGreen = rgbFunc
[ 2.5168388755514630e-02, 3.9427438169423720e-02, 6.2059571596425793e-03,
7.1120859807429554e-03, 2.1760044649139429e-04, 7.3271839984290210e-12,
-2.1623066217181700e-02, 1.5670209409407512e-02, 2.8019603188636222e-03,
3.2494773799897647e-01, 1.0164917292316602e+00, 1.0329476657890369e+00,
1.0321586962991549e+00, 1.0358667411948619e+00, 1.0151235476834941e+00,
1.0338076690093119e+00, 1.0371372378155013e+00, 1.0361377027692558e+00,
1.0229822432557210e+00, 9.6910327335652324e-01,-5.1785923899878572e-03,
1.1131261971061429e-03, 6.6675503033011771e-03, 7.4024315686001957e-04,
2.1591567633473925e-02, 5.1481620056217231e-03, 1.4561928645728216e-03,
1.6414511045291513e-04,-6.4630764968453287e-03, 1.0250854718507939e-02,
4.2387394733956134e-02, 2.1252716926861620e-02 ]
rgbIllumBlue :: Spectrum
rgbIllumBlue = rgbFunc
[ 1.0570490759328752e+00, 1.0538466912851301e+00, 1.0550494258140670e+00,
1.0530407754701832e+00, 1.0579930596460185e+00, 1.0578439494812371e+00,
1.0583132387180239e+00, 1.0579712943137616e+00, 1.0561884233578465e+00,
1.0571399285426490e+00, 1.0425795187752152e+00, 3.2603084374056102e-01,
-1.9255628442412243e-03,-1.2959221137046478e-03,-1.4357356276938696e-03,
-1.2963697250337886e-03,-1.9227081162373899e-03, 1.2621152526221778e-03,
-1.6095249003578276e-03,-1.3029983817879568e-03,-1.7666600873954916e-03,
-1.2325281140280050e-03, 1.0316809673254932e-02, 3.1284512648354357e-02,
8.8773879881746481e-02, 1.3873621740236541e-01, 1.5535067531939065e-01,
1.4878477178237029e-01, 1.6624255403475907e-01, 1.6997613960634927e-01,
1.5769743995852967e-01, 1.9069090525482305e-01 ]
rgbReflWhite :: Spectrum
rgbReflWhite = rgbFunc
[ 1.0618958571272863e+00, 1.0615019980348779e+00, 1.0614335379927147e+00,
1.0622711654692485e+00, 1.0622036218416742e+00, 1.0625059965187085e+00,
1.0623938486985884e+00, 1.0624706448043137e+00, 1.0625048144827762e+00,
1.0624366131308856e+00, 1.0620694238892607e+00, 1.0613167586932164e+00,
1.0610334029377020e+00, 1.0613868564828413e+00, 1.0614215366116762e+00,
1.0620336151299086e+00, 1.0625497454805051e+00, 1.0624317487992085e+00,
1.0625249140554480e+00, 1.0624277664486914e+00, 1.0624749854090769e+00,
1.0625538581025402e+00, 1.0625326910104864e+00, 1.0623922312225325e+00,
1.0623650980354129e+00, 1.0625256476715284e+00, 1.0612277619533155e+00,
1.0594262608698046e+00, 1.0599810758292072e+00, 1.0602547314449409e+00,
1.0601263046243634e+00, 1.0606565756823634e+00 ]
rgbReflCyan :: Spectrum
rgbReflCyan = rgbFunc
[ 1.0414628021426751e+00, 1.0328661533771188e+00, 1.0126146228964314e+00,
1.0350460524836209e+00, 1.0078661447098567e+00, 1.0422280385081280e+00,
1.0442596738499825e+00, 1.0535238290294409e+00, 1.0180776226938120e+00,
1.0442729908727713e+00, 1.0529362541920750e+00, 1.0537034271160244e+00,
1.0533901869215969e+00, 1.0537782700979574e+00, 1.0527093770467102e+00,
1.0530449040446797e+00, 1.0550554640191208e+00, 1.0553673610724821e+00,
1.0454306634683976e+00, 6.2348950639230805e-01, 1.8038071613188977e-01,
-7.6303759201984539e-03,-1.5217847035781367e-04,-7.5102257347258311e-03,
-2.1708639328491472e-03, 6.5919466602369636e-04, 1.2278815318539780e-02,
-4.4669775637208031e-03, 1.7119799082865147e-02, 4.9211089759759801e-03,
5.8762925143334985e-03, 2.5259399415550079e-02 ]
rgbReflMagenta :: Spectrum
rgbReflMagenta = rgbFunc
[ 9.9422138151236850e-01, 9.8986937122975682e-01, 9.8293658286116958e-01,
9.9627868399859310e-01, 1.0198955019000133e+00, 1.0166395501210359e+00,
1.0220913178757398e+00, 9.9651666040682441e-01, 1.0097766178917882e+00,
1.0215422470827016e+00, 6.4031953387790963e-01, 2.5012379477078184e-03,
6.5339939555769944e-03, 2.8334080462675826e-03,-5.1209675389074505e-11,
-9.0592291646646381e-03, 3.3936718323331200e-03,-3.0638741121828406e-03,
2.2203936168286292e-01, 6.3141140024811970e-01, 9.7480985576500956e-01,
9.7209562333590571e-01, 1.0173770302868150e+00, 9.9875194322734129e-01,
9.4701725739602238e-01, 8.5258623154354796e-01, 9.4897798581660842e-01,
9.4751876096521492e-01, 9.9598944191059791e-01, 8.6301351503809076e-01,
8.9150987853523145e-01, 8.4866492652845082e-01 ]
rgbReflYellow :: Spectrum
rgbReflYellow = rgbFunc
[ 5.5740622924920873e-03,-4.7982831631446787e-03,
-5.2536564298613798e-03,-6.4571480044499710e-03,
-5.9693514658007013e-03,-2.1836716037686721e-03,
1.6781120601055327e-02, 9.6096355429062641e-02,
2.1217357081986446e-01, 3.6169133290685068e-01,
5.3961011543232529e-01, 7.4408810492171507e-01,
9.2209571148394054e-01, 1.0460304298411225e+00,
1.0513824989063714e+00, 1.0511991822135085e+00,
1.0510530911991052e+00, 1.0517397230360510e+00,
1.0516043086790485e+00, 1.0511944032061460e+00,
1.0511590325868068e+00, 1.0516612465483031e+00,
1.0514038526836869e+00, 1.0515941029228475e+00,
1.0511460436960840e+00, 1.0515123758830476e+00,
1.0508871369510702e+00, 1.0508923708102380e+00,
1.0477492815668303e+00, 1.0493272144017338e+00,
1.0435963333422726e+00, 1.0392280772051465e+00 ]
rgbReflRed :: Spectrum
rgbReflRed = rgbFunc
[ 1.6575604867086180e-01, 1.1846442802747797e-01,
1.2408293329637447e-01, 1.1371272058349924e-01,
7.8992434518899132e-02, 3.2205603593106549e-02,
-1.0798365407877875e-02, 1.8051975516730392e-02,
5.3407196598730527e-03, 1.3654918729501336e-02,
-5.9564213545642841e-03, -1.8444365067353252e-03,
-1.0571884361529504e-02, -2.9375521078000011e-03,
-1.0790476271835936e-02, -8.0224306697503633e-03,
-2.2669167702495940e-03, 7.0200240494706634e-03,
-8.1528469000299308e-03, 6.0772866969252792e-01,
9.8831560865432400e-01, 9.9391691044078823e-01,
1.0039338994753197e+00, 9.9234499861167125e-01,
9.9926530858855522e-01, 1.0084621557617270e+00,
9.8358296827441216e-01, 1.0085023660099048e+00,
9.7451138326568698e-01, 9.8543269570059944e-01,
9.3495763980962043e-01, 9.8713907792319400e-01 ]
rgbReflGreen :: Spectrum
rgbReflGreen = rgbFunc
[ 2.6494153587602255e-03, -5.0175013429732242e-03,
-1.2547236272489583e-02, -9.4554964308388671e-03,
-1.2526086181600525e-02, -7.9170697760437767e-03,
-7.9955735204175690e-03, -9.3559433444469070e-03,
6.5468611982999303e-02, 3.9572875517634137e-01,
7.5244022299886659e-01, 9.6376478690218559e-01,
9.9854433855162328e-01, 9.9992977025287921e-01,
9.9939086751140449e-01, 9.9994372267071396e-01,
9.9939121813418674e-01, 9.9911237310424483e-01,
9.6019584878271580e-01, 6.3186279338432438e-01,
2.5797401028763473e-01, 9.4014888527335638e-03,
-3.0798345608649747e-03, -4.5230367033685034e-03,
-6.8933410388274038e-03, -9.0352195539015398e-03,
-8.5913667165340209e-03, -8.3690869120289398e-03,
-7.8685832338754313e-03, -8.3657578711085132e-06,
5.4301225442817177e-03, -2.7745589759259194e-03 ]
rgbReflBlue :: Spectrum
rgbReflBlue = rgbFunc
[ 9.9209771469720676e-01, 9.8876426059369127e-01,
9.9539040744505636e-01, 9.9529317353008218e-01,
9.9181447411633950e-01, 1.0002584039673432e+00,
9.9968478437342512e-01, 9.9988120766657174e-01,
9.8504012146370434e-01, 7.9029849053031276e-01,
5.6082198617463974e-01, 3.3133458513996528e-01,
1.3692410840839175e-01, 1.8914906559664151e-02,
-5.1129770932550889e-06, -4.2395493167891873e-04,
-4.1934593101534273e-04, 1.7473028136486615e-03,
3.7999160177631316e-03, -5.5101474906588642e-04,
-4.3716662898480967e-05, 7.5874501748732798e-03,
2.5795650780554021e-02, 3.8168376532500548e-02,
4.9489586408030833e-02, 4.9595992290102905e-02,
4.9814819505812249e-02, 3.9840911064978023e-02,
3.0501024937233868e-02, 2.1243054765241080e-02,
6.9596532104356399e-03, 4.1733649330980525e-03 ]
cieXValues :: [Float]
# NOINLINE cieXValues #
cieXValues = [
0.0001299000, 0.0001458470, 0.0001638021, 0.0001840037,
0.0002066902, 0.0002321000, 0.0002607280, 0.0002930750,
0.0003293880, 0.0003699140, 0.0004149000, 0.0004641587,
0.0005189860, 0.0005818540, 0.0006552347, 0.0007416000,
0.0008450296, 0.0009645268, 0.001094949, 0.001231154,
0.001368000, 0.001502050, 0.001642328, 0.001802382,
0.001995757, 0.002236000, 0.002535385, 0.002892603,
0.003300829, 0.003753236, 0.004243000, 0.004762389,
0.005330048, 0.005978712, 0.006741117, 0.007650000,
0.008751373, 0.01002888, 0.01142170, 0.01286901,
0.01431000, 0.01570443, 0.01714744, 0.01878122,
0.02074801, 0.02319000, 0.02620736, 0.02978248,
0.03388092, 0.03846824, 0.04351000, 0.04899560,
0.05502260, 0.06171880, 0.06921200, 0.07763000,
0.08695811, 0.09717672, 0.1084063, 0.1207672,
0.1343800, 0.1493582, 0.1653957, 0.1819831,
0.1986110, 0.2147700, 0.2301868, 0.2448797,
0.2587773, 0.2718079, 0.2839000, 0.2949438,
0.3048965, 0.3137873, 0.3216454, 0.3285000,
0.3343513, 0.3392101, 0.3431213, 0.3461296,
0.3482800, 0.3495999, 0.3501474, 0.3500130,
0.3492870, 0.3480600, 0.3463733, 0.3442624,
0.3418088, 0.3390941, 0.3362000, 0.3331977,
0.3300411, 0.3266357, 0.3228868, 0.3187000,
0.3140251, 0.3088840, 0.3032904, 0.2972579,
0.2908000, 0.2839701, 0.2767214, 0.2689178,
0.2604227, 0.2511000, 0.2408475, 0.2298512,
0.2184072, 0.2068115, 0.1953600, 0.1842136,
0.1733273, 0.1626881, 0.1522833, 0.1421000,
0.1321786, 0.1225696, 0.1132752, 0.1042979,
0.09564000, 0.08729955, 0.07930804, 0.07171776,
0.06458099, 0.05795001, 0.05186211, 0.04628152,
0.04115088, 0.03641283, 0.03201000, 0.02791720,
0.02414440, 0.02068700, 0.01754040, 0.01470000,
0.01216179, 0.009919960, 0.007967240, 0.006296346,
0.004900000, 0.003777173, 0.002945320, 0.002424880,
0.002236293, 0.002400000, 0.002925520, 0.003836560,
0.005174840, 0.006982080, 0.009300000, 0.01214949,
0.01553588, 0.01947752, 0.02399277, 0.02910000,
0.03481485, 0.04112016, 0.04798504, 0.05537861,
0.06327000, 0.07163501, 0.08046224, 0.08973996,
0.09945645, 0.1096000, 0.1201674, 0.1311145,
0.1423679, 0.1538542, 0.1655000, 0.1772571,
0.1891400, 0.2011694, 0.2133658, 0.2257499,
0.2383209, 0.2510668, 0.2639922, 0.2771017,
0.2904000, 0.3038912, 0.3175726, 0.3314384,
0.3454828, 0.3597000, 0.3740839, 0.3886396,
0.4033784, 0.4183115, 0.4334499, 0.4487953,
0.4643360, 0.4800640, 0.4959713, 0.5120501,
0.5282959, 0.5446916, 0.5612094, 0.5778215,
0.5945000, 0.6112209, 0.6279758, 0.6447602,
0.6615697, 0.6784000, 0.6952392, 0.7120586,
0.7288284, 0.7455188, 0.7621000, 0.7785432,
0.7948256, 0.8109264, 0.8268248, 0.8425000,
0.8579325, 0.8730816, 0.8878944, 0.9023181,
0.9163000, 0.9297995, 0.9427984, 0.9552776,
0.9672179, 0.9786000, 0.9893856, 0.9995488,
1.0090892, 1.0180064, 1.0263000, 1.0339827,
1.0409860, 1.0471880, 1.0524667, 1.0567000,
1.0597944, 1.0617992, 1.0628068, 1.0629096,
1.0622000, 1.0607352, 1.0584436, 1.0552244,
1.0509768, 1.0456000, 1.0390369, 1.0313608,
1.0226662, 1.0130477, 1.0026000, 0.9913675,
0.9793314, 0.9664916, 0.9528479, 0.9384000,
0.9231940, 0.9072440, 0.8905020, 0.8729200,
0.8544499, 0.8350840, 0.8149460, 0.7941860,
0.7729540, 0.7514000, 0.7295836, 0.7075888,
0.6856022, 0.6638104, 0.6424000, 0.6215149,
0.6011138, 0.5811052, 0.5613977, 0.5419000,
0.5225995, 0.5035464, 0.4847436, 0.4661939,
0.4479000, 0.4298613, 0.4120980, 0.3946440,
0.3775333, 0.3608000, 0.3444563, 0.3285168,
0.3130192, 0.2980011, 0.2835000, 0.2695448,
0.2561184, 0.2431896, 0.2307272, 0.2187000,
0.2070971, 0.1959232, 0.1851708, 0.1748323,
0.1649000, 0.1553667, 0.1462300, 0.1374900,
0.1291467, 0.1212000, 0.1136397, 0.1064650,
0.09969044, 0.09333061, 0.08740000, 0.08190096,
0.07680428, 0.07207712, 0.06768664, 0.06360000,
0.05980685, 0.05628216, 0.05297104, 0.04981861,
0.04677000, 0.04378405, 0.04087536, 0.03807264,
0.03540461, 0.03290000, 0.03056419, 0.02838056,
0.02634484, 0.02445275, 0.02270000, 0.02108429,
0.01959988, 0.01823732, 0.01698717, 0.01584000,
0.01479064, 0.01383132, 0.01294868, 0.01212920,
0.01135916, 0.01062935, 0.009938846, 0.009288422,
0.008678854, 0.008110916, 0.007582388, 0.007088746,
0.006627313, 0.006195408, 0.005790346, 0.005409826,
0.005052583, 0.004717512, 0.004403507, 0.004109457,
0.003833913, 0.003575748, 0.003334342, 0.003109075,
0.002899327, 0.002704348, 0.002523020, 0.002354168,
0.002196616, 0.002049190, 0.001910960, 0.001781438,
0.001660110, 0.001546459, 0.001439971, 0.001340042,
0.001246275, 0.001158471, 0.001076430, 0.0009999493,
0.0009287358, 0.0008624332, 0.0008007503, 0.0007433960,
0.0006900786, 0.0006405156, 0.0005945021, 0.0005518646,
0.0005124290, 0.0004760213, 0.0004424536, 0.0004115117,
0.0003829814, 0.0003566491, 0.0003323011, 0.0003097586,
0.0002888871, 0.0002695394, 0.0002515682, 0.0002348261,
0.0002191710, 0.0002045258, 0.0001908405, 0.0001780654,
0.0001661505, 0.0001550236, 0.0001446219, 0.0001349098,
0.0001258520, 0.0001174130, 0.0001095515, 0.0001022245,
0.00009539445, 0.00008902390, 0.00008307527, 0.00007751269,
0.00007231304, 0.00006745778, 0.00006292844, 0.00005870652,
0.00005477028, 0.00005109918, 0.00004767654, 0.00004448567,
0.00004150994, 0.00003873324, 0.00003614203, 0.00003372352,
0.00003146487, 0.00002935326, 0.00002737573, 0.00002552433,
0.00002379376, 0.00002217870, 0.00002067383, 0.00001927226,
0.00001796640, 0.00001674991, 0.00001561648, 0.00001455977,
0.00001357387, 0.00001265436, 0.00001179723, 0.00001099844,
0.00001025398, 0.000009559646, 0.000008912044, 0.000008308358,
0.000007745769, 0.000007221456, 0.000006732475, 0.000006276423,
0.000005851304, 0.000005455118, 0.000005085868, 0.000004741466,
0.000004420236, 0.000004120783, 0.000003841716, 0.000003581652,
0.000003339127, 0.000003112949, 0.000002902121, 0.000002705645,
0.000002522525, 0.000002351726, 0.000002192415, 0.000002043902,
0.000001905497, 0.000001776509, 0.000001656215, 0.000001544022,
0.000001439440, 0.000001341977, 0.000001251141]
cieYValues :: [Float]
# NOINLINE cieYValues #
cieYValues = [
0.000003917000, 0.000004393581, 0.000004929604, 0.000005532136,
0.000006208245, 0.000006965000, 0.000007813219, 0.000008767336,
0.000009839844, 0.00001104323, 0.00001239000, 0.00001388641,
0.00001555728, 0.00001744296, 0.00001958375, 0.00002202000,
0.00002483965, 0.00002804126, 0.00003153104, 0.00003521521,
0.00003900000, 0.00004282640, 0.00004691460, 0.00005158960,
0.00005717640, 0.00006400000, 0.00007234421, 0.00008221224,
0.00009350816, 0.0001061361, 0.0001200000, 0.0001349840,
0.0001514920, 0.0001702080, 0.0001918160, 0.0002170000,
0.0002469067, 0.0002812400, 0.0003185200, 0.0003572667,
0.0003960000, 0.0004337147, 0.0004730240, 0.0005178760,
0.0005722187, 0.0006400000, 0.0007245600, 0.0008255000,
0.0009411600, 0.001069880, 0.001210000, 0.001362091,
0.001530752, 0.001720368, 0.001935323, 0.002180000,
0.002454800, 0.002764000, 0.003117800, 0.003526400,
0.004000000, 0.004546240, 0.005159320, 0.005829280,
0.006546160, 0.007300000, 0.008086507, 0.008908720,
0.009767680, 0.01066443, 0.01160000, 0.01257317,
0.01358272, 0.01462968, 0.01571509, 0.01684000,
0.01800736, 0.01921448, 0.02045392, 0.02171824,
0.02300000, 0.02429461, 0.02561024, 0.02695857,
0.02835125, 0.02980000, 0.03131083, 0.03288368,
0.03452112, 0.03622571, 0.03800000, 0.03984667,
0.04176800, 0.04376600, 0.04584267, 0.04800000,
0.05024368, 0.05257304, 0.05498056, 0.05745872,
0.06000000, 0.06260197, 0.06527752, 0.06804208,
0.07091109, 0.07390000, 0.07701600, 0.08026640,
0.08366680, 0.08723280, 0.09098000, 0.09491755,
0.09904584, 0.1033674, 0.1078846, 0.1126000,
0.1175320, 0.1226744, 0.1279928, 0.1334528,
0.1390200, 0.1446764, 0.1504693, 0.1564619,
0.1627177, 0.1693000, 0.1762431, 0.1835581,
0.1912735, 0.1994180, 0.2080200, 0.2171199,
0.2267345, 0.2368571, 0.2474812, 0.2586000,
0.2701849, 0.2822939, 0.2950505, 0.3085780,
0.3230000, 0.3384021, 0.3546858, 0.3716986,
0.3892875, 0.4073000, 0.4256299, 0.4443096,
0.4633944, 0.4829395, 0.5030000, 0.5235693,
0.5445120, 0.5656900, 0.5869653, 0.6082000,
0.6293456, 0.6503068, 0.6708752, 0.6908424,
0.7100000, 0.7281852, 0.7454636, 0.7619694,
0.7778368, 0.7932000, 0.8081104, 0.8224962,
0.8363068, 0.8494916, 0.8620000, 0.8738108,
0.8849624, 0.8954936, 0.9054432, 0.9148501,
0.9237348, 0.9320924, 0.9399226, 0.9472252,
0.9540000, 0.9602561, 0.9660074, 0.9712606,
0.9760225, 0.9803000, 0.9840924, 0.9874812,
0.9903128, 0.9928116, 0.9949501, 0.9967108,
0.9980983, 0.9991120, 0.9997482, 1.0000000,
0.9998567, 0.9993046, 0.9983255, 0.9968987,
0.9950000, 0.9926005, 0.9897426, 0.9864444,
0.9827241, 0.9786000, 0.9740837, 0.9691712,
0.9638568, 0.9581349, 0.9520000, 0.9454504,
0.9384992, 0.9311628, 0.9234576, 0.9154000,
0.9070064, 0.8982772, 0.8892048, 0.8797816,
0.8700000, 0.8598613, 0.8493920, 0.8386220,
0.8275813, 0.8163000, 0.8047947, 0.7930820,
0.7811920, 0.7691547, 0.7570000, 0.7447541,
0.7324224, 0.7200036, 0.7074965, 0.6949000,
0.6822192, 0.6694716, 0.6566744, 0.6438448,
0.6310000, 0.6181555, 0.6053144, 0.5924756,
0.5796379, 0.5668000, 0.5539611, 0.5411372,
0.5283528, 0.5156323, 0.5030000, 0.4904688,
0.4780304, 0.4656776, 0.4534032, 0.4412000,
0.4290800, 0.4170360, 0.4050320, 0.3930320,
0.3810000, 0.3689184, 0.3568272, 0.3447768,
0.3328176, 0.3210000, 0.3093381, 0.2978504,
0.2865936, 0.2756245, 0.2650000, 0.2547632,
0.2448896, 0.2353344, 0.2260528, 0.2170000,
0.2081616, 0.1995488, 0.1911552, 0.1829744,
0.1750000, 0.1672235, 0.1596464, 0.1522776,
0.1451259, 0.1382000, 0.1315003, 0.1250248,
0.1187792, 0.1127691, 0.1070000, 0.1014762,
0.09618864, 0.09112296, 0.08626485, 0.08160000,
0.07712064, 0.07282552, 0.06871008, 0.06476976,
0.06100000, 0.05739621, 0.05395504, 0.05067376,
0.04754965, 0.04458000, 0.04175872, 0.03908496,
0.03656384, 0.03420048, 0.03200000, 0.02996261,
0.02807664, 0.02632936, 0.02470805, 0.02320000,
0.02180077, 0.02050112, 0.01928108, 0.01812069,
0.01700000, 0.01590379, 0.01483718, 0.01381068,
0.01283478, 0.01192000, 0.01106831, 0.01027339,
0.009533311, 0.008846157, 0.008210000, 0.007623781,
0.007085424, 0.006591476, 0.006138485, 0.005723000,
0.005343059, 0.004995796, 0.004676404, 0.004380075,
0.004102000, 0.003838453, 0.003589099, 0.003354219,
0.003134093, 0.002929000, 0.002738139, 0.002559876,
0.002393244, 0.002237275, 0.002091000, 0.001953587,
0.001824580, 0.001703580, 0.001590187, 0.001484000,
0.001384496, 0.001291268, 0.001204092, 0.001122744,
0.001047000, 0.0009765896, 0.0009111088, 0.0008501332,
0.0007932384, 0.0007400000, 0.0006900827, 0.0006433100,
0.0005994960, 0.0005584547, 0.0005200000, 0.0004839136,
0.0004500528, 0.0004183452, 0.0003887184, 0.0003611000,
0.0003353835, 0.0003114404, 0.0002891656, 0.0002684539,
0.0002492000, 0.0002313019, 0.0002146856, 0.0001992884,
0.0001850475, 0.0001719000, 0.0001597781, 0.0001486044,
0.0001383016, 0.0001287925, 0.0001200000, 0.0001118595,
0.0001043224, 0.00009733560, 0.00009084587, 0.00008480000,
0.00007914667, 0.00007385800, 0.00006891600, 0.00006430267,
0.00006000000, 0.00005598187, 0.00005222560, 0.00004871840,
0.00004544747, 0.00004240000, 0.00003956104, 0.00003691512,
0.00003444868, 0.00003214816, 0.00003000000, 0.00002799125,
0.00002611356, 0.00002436024, 0.00002272461, 0.00002120000,
0.00001977855, 0.00001845285, 0.00001721687, 0.00001606459,
0.00001499000, 0.00001398728, 0.00001305155, 0.00001217818,
0.00001136254, 0.00001060000, 0.000009885877, 0.000009217304,
0.000008592362, 0.000008009133, 0.000007465700, 0.000006959567,
0.000006487995, 0.000006048699, 0.000005639396, 0.000005257800,
0.000004901771, 0.000004569720, 0.000004260194, 0.000003971739,
0.000003702900, 0.000003452163, 0.000003218302, 0.000003000300,
0.000002797139, 0.000002607800, 0.000002431220, 0.000002266531,
0.000002113013, 0.000001969943, 0.000001836600, 0.000001712230,
0.000001596228, 0.000001488090, 0.000001387314, 0.000001293400,
0.000001205820, 0.000001124143, 0.000001048009, 0.0000009770578,
0.0000009109300, 0.0000008492513, 0.0000007917212, 0.0000007380904,
0.0000006881098, 0.0000006415300, 0.0000005980895, 0.0000005575746,
0.0000005198080, 0.0000004846123, 0.0000004518100 ]
cieZValues :: [Float]
# NOINLINE cieZValues #
cieZValues = [
0.0006061000, 0.0006808792, 0.0007651456, 0.0008600124,
0.0009665928, 0.001086000, 0.001220586, 0.001372729,
0.001543579, 0.001734286, 0.001946000, 0.002177777,
0.002435809, 0.002731953, 0.003078064, 0.003486000,
0.003975227, 0.004540880, 0.005158320, 0.005802907,
0.006450001, 0.007083216, 0.007745488, 0.008501152,
0.009414544, 0.01054999, 0.01196580, 0.01365587,
0.01558805, 0.01773015, 0.02005001, 0.02251136,
0.02520288, 0.02827972, 0.03189704, 0.03621000,
0.04143771, 0.04750372, 0.05411988, 0.06099803,
0.06785001, 0.07448632, 0.08136156, 0.08915364,
0.09854048, 0.1102000, 0.1246133, 0.1417017,
0.1613035, 0.1832568, 0.2074000, 0.2336921,
0.2626114, 0.2947746, 0.3307985, 0.3713000,
0.4162091, 0.4654642, 0.5196948, 0.5795303,
0.6456000, 0.7184838, 0.7967133, 0.8778459,
0.9594390, 1.0390501, 1.1153673, 1.1884971,
1.2581233, 1.3239296, 1.3856000, 1.4426352,
1.4948035, 1.5421903, 1.5848807, 1.6229600,
1.6564048, 1.6852959, 1.7098745, 1.7303821,
1.7470600, 1.7600446, 1.7696233, 1.7762637,
1.7804334, 1.7826000, 1.7829682, 1.7816998,
1.7791982, 1.7758671, 1.7721100, 1.7682589,
1.7640390, 1.7589438, 1.7524663, 1.7441000,
1.7335595, 1.7208581, 1.7059369, 1.6887372,
1.6692000, 1.6475287, 1.6234127, 1.5960223,
1.5645280, 1.5281000, 1.4861114, 1.4395215,
1.3898799, 1.3387362, 1.2876400, 1.2374223,
1.1878243, 1.1387611, 1.0901480, 1.0419000,
0.9941976, 0.9473473, 0.9014531, 0.8566193,
0.8129501, 0.7705173, 0.7294448, 0.6899136,
0.6521049, 0.6162000, 0.5823286, 0.5504162,
0.5203376, 0.4919673, 0.4651800, 0.4399246,
0.4161836, 0.3938822, 0.3729459, 0.3533000,
0.3348578, 0.3175521, 0.3013375, 0.2861686,
0.2720000, 0.2588171, 0.2464838, 0.2347718,
0.2234533, 0.2123000, 0.2011692, 0.1901196,
0.1792254, 0.1685608, 0.1582000, 0.1481383,
0.1383758, 0.1289942, 0.1200751, 0.1117000,
0.1039048, 0.09666748, 0.08998272, 0.08384531,
0.07824999, 0.07320899, 0.06867816, 0.06456784,
0.06078835, 0.05725001, 0.05390435, 0.05074664,
0.04775276, 0.04489859, 0.04216000, 0.03950728,
0.03693564, 0.03445836, 0.03208872, 0.02984000,
0.02771181, 0.02569444, 0.02378716, 0.02198925,
0.02030000, 0.01871805, 0.01724036, 0.01586364,
0.01458461, 0.01340000, 0.01230723, 0.01130188,
0.01037792, 0.009529306, 0.008749999, 0.008035200,
0.007381600, 0.006785400, 0.006242800, 0.005749999,
0.005303600, 0.004899800, 0.004534200, 0.004202400,
0.003900000, 0.003623200, 0.003370600, 0.003141400,
0.002934800, 0.002749999, 0.002585200, 0.002438600,
0.002309400, 0.002196800, 0.002100000, 0.002017733,
0.001948200, 0.001889800, 0.001840933, 0.001800000,
0.001766267, 0.001737800, 0.001711200, 0.001683067,
0.001650001, 0.001610133, 0.001564400, 0.001513600,
0.001458533, 0.001400000, 0.001336667, 0.001270000,
0.001205000, 0.001146667, 0.001100000, 0.001068800,
0.001049400, 0.001035600, 0.001021200, 0.001000000,
0.0009686400, 0.0009299200, 0.0008868800, 0.0008425600,
0.0008000000, 0.0007609600, 0.0007236800, 0.0006859200,
0.0006454400, 0.0006000000, 0.0005478667, 0.0004916000,
0.0004354000, 0.0003834667, 0.0003400000, 0.0003072533,
0.0002831600, 0.0002654400, 0.0002518133, 0.0002400000,
0.0002295467, 0.0002206400, 0.0002119600, 0.0002021867,
0.0001900000, 0.0001742133, 0.0001556400, 0.0001359600,
0.0001168533, 0.0001000000, 0.00008613333, 0.00007460000,
0.00006500000, 0.00005693333, 0.00004999999, 0.00004416000,
0.00003948000, 0.00003572000, 0.00003264000, 0.00003000000,
0.00002765333, 0.00002556000, 0.00002364000, 0.00002181333,
0.00002000000, 0.00001813333, 0.00001620000, 0.00001420000,
0.00001213333, 0.00001000000, 0.000007733333, 0.000005400000,
0.000003200000, 0.000001333333, 0.000000000000, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0 ]
|
74a7d4fc7803727f89dee84aff84671db568d59245b0afbe3ae16eaa5d540e55 | goldfirere/thesis | Basics.hs | Copyright ( c ) 2016
-}
# LANGUAGE TypeOperators , TypeFamilies , TypeApplications ,
ExplicitForAll , ScopedTypeVariables , GADTs , ,
TypeInType , ConstraintKinds , UndecidableInstances ,
FlexibleInstances , MultiParamTypeClasses , FunctionalDependencies ,
FlexibleContexts , StandaloneDeriving , InstanceSigs ,
RankNTypes , UndecidableSuperClasses , AllowAmbiguousTypes #
ExplicitForAll, ScopedTypeVariables, GADTs, TypeFamilyDependencies,
TypeInType, ConstraintKinds, UndecidableInstances,
FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies,
FlexibleContexts, StandaloneDeriving, InstanceSigs,
RankNTypes, UndecidableSuperClasses, AllowAmbiguousTypes #-}
module Basics where
import Data.Type.Bool
import Data.Type.Equality
import GHC.TypeLits ( Symbol, KnownSymbol, sameSymbol, symbolVal )
import Data.Proxy
import GHC.Exts
import Data.Kind
import Unsafe.Coerce
-------------------------------
Utilities
-- Heterogeneous propositional equality
data (a :: k1) :~~: (b :: k2) where
HRefl :: a :~~: a
-- Type-level inequality
type a /= b = Not (a == b)
-- append type-level lists (schemas)
type family s1 ++ s2 where
'[] ++ s2 = s2
(s ': s1) ++ s2 = s ': (s1 ++ s2)
This is needed in order to prove disjointness , because GHC ca n't
-- handle inequality well.
assumeEquality :: forall a b r. ((a ~ b) => r) -> r
assumeEquality thing = case unsafeCoerce Refl :: a :~: b of
Refl -> thing
-- Shorter name for shorter example
eq :: TestEquality f => f a -> f b -> Maybe (a :~: b)
eq = testEquality
-------------------------------
Singleton lists
-- Unlike in the singletons paper, we now have injective type
-- families, so we use that to model singletons; it's a bit
-- cleaner than the original approach
type family Sing = (r :: k -> Type) | r -> k
-- Cute type synonym.
type Π = Sing
-- Really, just singleton lists. Named Schema for better output
-- during example.
data Schema :: forall k. [k] -> Type where
Nil :: Schema '[]
(:>>) :: Sing h -> Schema t -> Schema (h ': t)
infixr 5 :>>
type instance Sing = Schema
-- Append singleton lists
(%:++) :: Schema a -> Schema b -> Schema (a ++ b)
Nil %:++ x = x
(a :>> b) %:++ c = a :>> (b %:++ c)
--------------------------------
-- Type-indexed type representations
-- Based on "A reflection on types"
data TyCon (a :: k) where
Int :: TyCon Int
Bool :: TyCon Bool
Char :: TyCon Char
List :: TyCon []
Maybe :: TyCon Maybe
Arrow :: TyCon (->)
TYPE :: TyCon TYPE
RuntimeRep :: TyCon RuntimeRep
PtrRepLifted' :: TyCon 'PtrRepLifted
-- If extending, add to eqTyCon too
eqTyCon :: TyCon a -> TyCon b -> Maybe (a :~~: b)
eqTyCon Int Int = Just HRefl
eqTyCon Bool Bool = Just HRefl
eqTyCon Char Char = Just HRefl
eqTyCon List List = Just HRefl
eqTyCon Maybe Maybe = Just HRefl
eqTyCon Arrow Arrow = Just HRefl
eqTyCon TYPE TYPE = Just HRefl
eqTyCon RuntimeRep RuntimeRep = Just HRefl
eqTyCon PtrRepLifted' PtrRepLifted' = Just HRefl
eqTyCon _ _ = Nothing
Check whether or not a type is really a plain old ;
-- necessary to avoid warning in kindRep
type family Primitive (a :: k) :: Constraint where
Primitive (_ _) = ('False ~ 'True)
Primitive _ = (() :: Constraint)
data TypeRep (a :: k) where
TyCon :: forall (a :: k). (Primitive a, Typeable k) => TyCon a -> TypeRep a
TyApp :: TypeRep a -> TypeRep b -> TypeRep (a b)
Equality on TypeReps
eqT :: TypeRep a -> TypeRep b -> Maybe (a :~~: b)
eqT (TyCon tc1) (TyCon tc2) = eqTyCon tc1 tc2
eqT (TyApp f1 a1) (TyApp f2 a2) = do
HRefl <- eqT f1 f2
HRefl <- eqT a1 a2
return HRefl
eqT _ _ = Nothing
--------------------------------------
-- Existentials
data TyConX where
TyConX :: forall (a :: k). (Primitive a, Typeable k) => TyCon a -> TyConX
instance Read TyConX where
readsPrec _ "Int" = [(TyConX Int, "")]
readsPrec _ "Bool" = [(TyConX Bool, "")]
readsPrec _ "List" = [(TyConX List, "")]
readsPrec _ _ = []
-- This variant of TypeRepX allows you to specify an arbitrary
constraint on the inner TypeRep
data TypeRepX :: (forall k. k -> Constraint) -> Type where
TypeRepX :: forall k (c :: forall k'. k' -> Constraint) (a :: k).
c a => TypeRep a -> TypeRepX c
-- This constraint is always satisfied
needs the : : k to make it a specified tyvar
instance ConstTrue a
instance Show (TypeRepX ConstTrue) where
show (TypeRepX tr) = show tr
-- can't write Show (TypeRepX c) because c's kind mentions a forall,
and the impredicativity check gets nervous . See # 11519
instance Show (TypeRepX IsType) where
show (TypeRepX tr) = show tr
-- Just enough functionality to get through example. No parentheses
-- or other niceties.
instance Read (TypeRepX ConstTrue) where
readsPrec p s = do
let tokens = words s
tyreps <- mapM read_token tokens
return (foldl1 mk_app tyreps, "")
where
read_token "String" = return (TypeRepX $ typeRep @String)
read_token other = do
(TyConX tc, _) <- readsPrec p other
return (TypeRepX (TyCon tc))
mk_app :: TypeRepX ConstTrue -> TypeRepX ConstTrue -> TypeRepX ConstTrue
mk_app (TypeRepX f) (TypeRepX a) = case kindRep f of
TyCon Arrow `TyApp` k1 `TyApp` _
| Just HRefl <- k1 `eqT` kindRep a -> TypeRepX (TyApp f a)
_ -> error "ill-kinded type"
-- instance Read (TypeRepX ((~~) Type)) RAE: need (~~) :: forall k1. k1 -> forall k2. k2 -> Constraint
-- RAE: need kind signatures on classes
-- TypeRepX ((~~) Type)
-- (~~) :: forall k1 k2. k1 -> k2 -> Constraint
-- I need: (~~) :: forall k1. k1 -> forall k2. k2 -> Constraint
class k ~~ Type => IsType (x :: k)
instance k ~~ Type => IsType (x :: k)
instance Read (TypeRepX IsType) where
readsPrec p s = case readsPrec @(TypeRepX ConstTrue) p s of
[(TypeRepX tr, "")]
| Just HRefl <- eqT (kindRep tr) (typeRep @Type)
-> [(TypeRepX tr, "")]
_ -> error "wrong kind"
-----------------------------
-- Get the kind of a type
kindRep :: TypeRep (a :: k) -> TypeRep k
kindRep (TyCon _) = typeRep
kindRep (TyApp (f :: TypeRep (tf :: k1 -> k)) _) = case kindRep f :: TypeRep (k1 -> k) of
TyApp _ res -> res
Convert an explicit TypeRep into an implicit one . Does n't require unsafeCoerce
in Core
withTypeable :: forall a r. TypeRep a -> (Typeable a => r) -> r
withTypeable tr thing = unsafeCoerce (Don'tInstantiate thing :: DI a r) tr
newtype DI a r = Don'tInstantiate (Typeable a => r)
-----------------------------
-- Implicit TypeReps (Typeable)
class (Primitive a, Typeable k) => TyConAble (a :: k) where
tyCon :: TyCon a
instance TyConAble Int where tyCon = Int
instance TyConAble Bool where tyCon = Bool
instance TyConAble Char where tyCon = Char
instance TyConAble [] where tyCon = List
instance TyConAble Maybe where tyCon = Maybe
instance TyConAble (->) where tyCon = Arrow
instance TyConAble TYPE where tyCon = TYPE
instance TyConAble 'PtrRepLifted where tyCon = PtrRepLifted'
instance TyConAble RuntimeRep where tyCon = RuntimeRep
Ca n't just define the way we want , because the instances
-- overlap. So we have to mock up instance chains via closed type families.
class Typeable' (a :: k) (b :: Bool) where
typeRep' :: TypeRep a
type family CheckPrim a where
CheckPrim (_ _) = 'False
CheckPrim _ = 'True
NB : We need the : : k and the : : Constraint so that this has a CUSK , allowing
the polymorphic recursion with TypeRep . See also # 9200 , though the requirement
-- for the constraints is correct.
type Typeable (a :: k) = (Typeable' a (CheckPrim a) :: Constraint)
instance TyConAble a => Typeable' a 'True where
typeRep' = TyCon tyCon
instance (Typeable a, Typeable b) => Typeable' (a b) 'False where
typeRep' = TyApp typeRep typeRep
typeRep :: forall a. Typeable a => TypeRep a
RAE : # 11512 says we need the extra @ _ .
-----------------------------
-- Useful instances
instance Show (TypeRep a) where
show (TyCon tc) = show tc
show (TyApp tr1 tr2) = show tr1 ++ " " ++ show tr2
deriving instance Show (TyCon a)
instance TestEquality TypeRep where
testEquality tr1 tr2
| Just HRefl <- eqT tr1 tr2
= Just Refl
| otherwise
= Nothing
---------------------------
-- More singletons
a TypeRep really is a singleton
type instance Sing = (TypeRep :: Type -> Type)
data SSymbol :: Symbol -> Type where
SSym :: KnownSymbol s => SSymbol s
type instance Sing = SSymbol
instance TestEquality SSymbol where
testEquality :: forall s1 s2. SSymbol s1 -> SSymbol s2 -> Maybe (s1 :~: s2)
testEquality SSym SSym = sameSymbol @s1 @s2 Proxy Proxy
instance Show (SSymbol name) where
show s@SSym = symbolVal s
---------------------------------
Unary nats
data Nat = Zero | Succ Nat
| null | https://raw.githubusercontent.com/goldfirere/thesis/22f066bc26b1147530525aabb3df686416b3e4aa/defense/Basics.hs | haskell | -----------------------------
Heterogeneous propositional equality
Type-level inequality
append type-level lists (schemas)
handle inequality well.
Shorter name for shorter example
-----------------------------
Unlike in the singletons paper, we now have injective type
families, so we use that to model singletons; it's a bit
cleaner than the original approach
Cute type synonym.
Really, just singleton lists. Named Schema for better output
during example.
Append singleton lists
------------------------------
Type-indexed type representations
Based on "A reflection on types"
If extending, add to eqTyCon too
necessary to avoid warning in kindRep
------------------------------------
Existentials
This variant of TypeRepX allows you to specify an arbitrary
This constraint is always satisfied
can't write Show (TypeRepX c) because c's kind mentions a forall,
Just enough functionality to get through example. No parentheses
or other niceties.
instance Read (TypeRepX ((~~) Type)) RAE: need (~~) :: forall k1. k1 -> forall k2. k2 -> Constraint
RAE: need kind signatures on classes
TypeRepX ((~~) Type)
(~~) :: forall k1 k2. k1 -> k2 -> Constraint
I need: (~~) :: forall k1. k1 -> forall k2. k2 -> Constraint
---------------------------
Get the kind of a type
---------------------------
Implicit TypeReps (Typeable)
overlap. So we have to mock up instance chains via closed type families.
for the constraints is correct.
---------------------------
Useful instances
-------------------------
More singletons
------------------------------- | Copyright ( c ) 2016
-}
# LANGUAGE TypeOperators , TypeFamilies , TypeApplications ,
ExplicitForAll , ScopedTypeVariables , GADTs , ,
TypeInType , ConstraintKinds , UndecidableInstances ,
FlexibleInstances , MultiParamTypeClasses , FunctionalDependencies ,
FlexibleContexts , StandaloneDeriving , InstanceSigs ,
RankNTypes , UndecidableSuperClasses , AllowAmbiguousTypes #
ExplicitForAll, ScopedTypeVariables, GADTs, TypeFamilyDependencies,
TypeInType, ConstraintKinds, UndecidableInstances,
FlexibleInstances, MultiParamTypeClasses, FunctionalDependencies,
FlexibleContexts, StandaloneDeriving, InstanceSigs,
RankNTypes, UndecidableSuperClasses, AllowAmbiguousTypes #-}
module Basics where
import Data.Type.Bool
import Data.Type.Equality
import GHC.TypeLits ( Symbol, KnownSymbol, sameSymbol, symbolVal )
import Data.Proxy
import GHC.Exts
import Data.Kind
import Unsafe.Coerce
Utilities
data (a :: k1) :~~: (b :: k2) where
HRefl :: a :~~: a
type a /= b = Not (a == b)
type family s1 ++ s2 where
'[] ++ s2 = s2
(s ': s1) ++ s2 = s ': (s1 ++ s2)
This is needed in order to prove disjointness , because GHC ca n't
assumeEquality :: forall a b r. ((a ~ b) => r) -> r
assumeEquality thing = case unsafeCoerce Refl :: a :~: b of
Refl -> thing
eq :: TestEquality f => f a -> f b -> Maybe (a :~: b)
eq = testEquality
Singleton lists
type family Sing = (r :: k -> Type) | r -> k
type Π = Sing
data Schema :: forall k. [k] -> Type where
Nil :: Schema '[]
(:>>) :: Sing h -> Schema t -> Schema (h ': t)
infixr 5 :>>
type instance Sing = Schema
(%:++) :: Schema a -> Schema b -> Schema (a ++ b)
Nil %:++ x = x
(a :>> b) %:++ c = a :>> (b %:++ c)
data TyCon (a :: k) where
Int :: TyCon Int
Bool :: TyCon Bool
Char :: TyCon Char
List :: TyCon []
Maybe :: TyCon Maybe
Arrow :: TyCon (->)
TYPE :: TyCon TYPE
RuntimeRep :: TyCon RuntimeRep
PtrRepLifted' :: TyCon 'PtrRepLifted
eqTyCon :: TyCon a -> TyCon b -> Maybe (a :~~: b)
eqTyCon Int Int = Just HRefl
eqTyCon Bool Bool = Just HRefl
eqTyCon Char Char = Just HRefl
eqTyCon List List = Just HRefl
eqTyCon Maybe Maybe = Just HRefl
eqTyCon Arrow Arrow = Just HRefl
eqTyCon TYPE TYPE = Just HRefl
eqTyCon RuntimeRep RuntimeRep = Just HRefl
eqTyCon PtrRepLifted' PtrRepLifted' = Just HRefl
eqTyCon _ _ = Nothing
Check whether or not a type is really a plain old ;
type family Primitive (a :: k) :: Constraint where
Primitive (_ _) = ('False ~ 'True)
Primitive _ = (() :: Constraint)
data TypeRep (a :: k) where
TyCon :: forall (a :: k). (Primitive a, Typeable k) => TyCon a -> TypeRep a
TyApp :: TypeRep a -> TypeRep b -> TypeRep (a b)
Equality on TypeReps
eqT :: TypeRep a -> TypeRep b -> Maybe (a :~~: b)
eqT (TyCon tc1) (TyCon tc2) = eqTyCon tc1 tc2
eqT (TyApp f1 a1) (TyApp f2 a2) = do
HRefl <- eqT f1 f2
HRefl <- eqT a1 a2
return HRefl
eqT _ _ = Nothing
data TyConX where
TyConX :: forall (a :: k). (Primitive a, Typeable k) => TyCon a -> TyConX
instance Read TyConX where
readsPrec _ "Int" = [(TyConX Int, "")]
readsPrec _ "Bool" = [(TyConX Bool, "")]
readsPrec _ "List" = [(TyConX List, "")]
readsPrec _ _ = []
constraint on the inner TypeRep
data TypeRepX :: (forall k. k -> Constraint) -> Type where
TypeRepX :: forall k (c :: forall k'. k' -> Constraint) (a :: k).
c a => TypeRep a -> TypeRepX c
needs the : : k to make it a specified tyvar
instance ConstTrue a
instance Show (TypeRepX ConstTrue) where
show (TypeRepX tr) = show tr
and the impredicativity check gets nervous . See # 11519
instance Show (TypeRepX IsType) where
show (TypeRepX tr) = show tr
instance Read (TypeRepX ConstTrue) where
readsPrec p s = do
let tokens = words s
tyreps <- mapM read_token tokens
return (foldl1 mk_app tyreps, "")
where
read_token "String" = return (TypeRepX $ typeRep @String)
read_token other = do
(TyConX tc, _) <- readsPrec p other
return (TypeRepX (TyCon tc))
mk_app :: TypeRepX ConstTrue -> TypeRepX ConstTrue -> TypeRepX ConstTrue
mk_app (TypeRepX f) (TypeRepX a) = case kindRep f of
TyCon Arrow `TyApp` k1 `TyApp` _
| Just HRefl <- k1 `eqT` kindRep a -> TypeRepX (TyApp f a)
_ -> error "ill-kinded type"
class k ~~ Type => IsType (x :: k)
instance k ~~ Type => IsType (x :: k)
instance Read (TypeRepX IsType) where
readsPrec p s = case readsPrec @(TypeRepX ConstTrue) p s of
[(TypeRepX tr, "")]
| Just HRefl <- eqT (kindRep tr) (typeRep @Type)
-> [(TypeRepX tr, "")]
_ -> error "wrong kind"
kindRep :: TypeRep (a :: k) -> TypeRep k
kindRep (TyCon _) = typeRep
kindRep (TyApp (f :: TypeRep (tf :: k1 -> k)) _) = case kindRep f :: TypeRep (k1 -> k) of
TyApp _ res -> res
Convert an explicit TypeRep into an implicit one . Does n't require unsafeCoerce
in Core
withTypeable :: forall a r. TypeRep a -> (Typeable a => r) -> r
withTypeable tr thing = unsafeCoerce (Don'tInstantiate thing :: DI a r) tr
newtype DI a r = Don'tInstantiate (Typeable a => r)
class (Primitive a, Typeable k) => TyConAble (a :: k) where
tyCon :: TyCon a
instance TyConAble Int where tyCon = Int
instance TyConAble Bool where tyCon = Bool
instance TyConAble Char where tyCon = Char
instance TyConAble [] where tyCon = List
instance TyConAble Maybe where tyCon = Maybe
instance TyConAble (->) where tyCon = Arrow
instance TyConAble TYPE where tyCon = TYPE
instance TyConAble 'PtrRepLifted where tyCon = PtrRepLifted'
instance TyConAble RuntimeRep where tyCon = RuntimeRep
Ca n't just define the way we want , because the instances
class Typeable' (a :: k) (b :: Bool) where
typeRep' :: TypeRep a
type family CheckPrim a where
CheckPrim (_ _) = 'False
CheckPrim _ = 'True
NB : We need the : : k and the : : Constraint so that this has a CUSK , allowing
the polymorphic recursion with TypeRep . See also # 9200 , though the requirement
type Typeable (a :: k) = (Typeable' a (CheckPrim a) :: Constraint)
instance TyConAble a => Typeable' a 'True where
typeRep' = TyCon tyCon
instance (Typeable a, Typeable b) => Typeable' (a b) 'False where
typeRep' = TyApp typeRep typeRep
typeRep :: forall a. Typeable a => TypeRep a
RAE : # 11512 says we need the extra @ _ .
instance Show (TypeRep a) where
show (TyCon tc) = show tc
show (TyApp tr1 tr2) = show tr1 ++ " " ++ show tr2
deriving instance Show (TyCon a)
instance TestEquality TypeRep where
testEquality tr1 tr2
| Just HRefl <- eqT tr1 tr2
= Just Refl
| otherwise
= Nothing
a TypeRep really is a singleton
type instance Sing = (TypeRep :: Type -> Type)
data SSymbol :: Symbol -> Type where
SSym :: KnownSymbol s => SSymbol s
type instance Sing = SSymbol
instance TestEquality SSymbol where
testEquality :: forall s1 s2. SSymbol s1 -> SSymbol s2 -> Maybe (s1 :~: s2)
testEquality SSym SSym = sameSymbol @s1 @s2 Proxy Proxy
instance Show (SSymbol name) where
show s@SSym = symbolVal s
Unary nats
data Nat = Zero | Succ Nat
|
263846eb427042e72d0830f4d3ea75ca4d963d7bd641b439790041c0b1a08074 | rd--/hsc3 | trigAvg.help.hs | -- trigAvg
let x = mouseX kr 0 1000 Linear 0.2
b = mouseButton kr 0 1 0.2
n = X.trigAvg kr (roundTo x 100) b
in sinOsc ar n 0 * 0.1
-- trigAvg
let n = X.trigAvg kr (sinOsc ar 0.1 0) (impulse kr 0.2 0)
in sinOsc ar 220 0 * n * 0.25
| null | https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/trigAvg.help.hs | haskell | trigAvg
trigAvg | let x = mouseX kr 0 1000 Linear 0.2
b = mouseButton kr 0 1 0.2
n = X.trigAvg kr (roundTo x 100) b
in sinOsc ar n 0 * 0.1
let n = X.trigAvg kr (sinOsc ar 0.1 0) (impulse kr 0.2 0)
in sinOsc ar 220 0 * n * 0.25
|
aab36d7ce0a8297c11c1b4289bba66db9319f4db9ec1ff6fd5a4b7a9c53ae55a | input-output-hk/cardano-base | RoundTrip.hs | # LANGUAGE NumDecimals #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module Test.Cardano.Binary.RoundTrip
( tests
)
where
import Test.Cardano.Prelude ( eachOf, discoverRoundTrip )
import Data.Ratio ((%))
import Data.Fixed (E9, Fixed(..))
import Hedgehog (Property, Range, checkParallel)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Test.Cardano.Binary.Helpers.GoldenRoundTrip
(roundTripsCBORBuildable, roundTripsCBORShow)
tests :: IO Bool
tests = checkParallel $$discoverRoundTrip
roundTripUnitBi :: Property
roundTripUnitBi = eachOf 1 (pure ()) roundTripsCBORBuildable
roundTripBoolBi :: Property
roundTripBoolBi = eachOf 10 Gen.bool roundTripsCBORBuildable
| Tests up to ' Integer 's with multiple machine words using large upper bound
roundTripIntegerBi :: Property
roundTripIntegerBi = eachOf
1000
(Gen.integral (Range.linearFrom 0 (-1e40) 1e40 :: Range Integer))
roundTripsCBORBuildable
roundTripWordBi :: Property
roundTripWordBi =
eachOf 1000 (Gen.word Range.constantBounded) roundTripsCBORBuildable
roundTripWord8Bi :: Property
roundTripWord8Bi =
eachOf 1000 (Gen.word8 Range.constantBounded) roundTripsCBORBuildable
roundTripWord16Bi :: Property
roundTripWord16Bi =
eachOf 1000 (Gen.word16 Range.constantBounded) roundTripsCBORBuildable
roundTripWord32Bi :: Property
roundTripWord32Bi =
eachOf 1000 (Gen.word32 Range.constantBounded) roundTripsCBORBuildable
roundTripWord64Bi :: Property
roundTripWord64Bi =
eachOf 1000 (Gen.word64 Range.constantBounded) roundTripsCBORBuildable
roundTripIntBi :: Property
roundTripIntBi =
eachOf 1000 (Gen.int Range.constantBounded) roundTripsCBORBuildable
roundTripFloatBi :: Property
roundTripFloatBi =
eachOf 1000 (Gen.float (Range.constant (-1e12) 1e12)) roundTripsCBORBuildable
roundTripDoubleBi :: Property
roundTripDoubleBi =
eachOf 1000 (Gen.double (Range.constant (-1e308) 1e308)) roundTripsCBORBuildable
roundTripInt32Bi :: Property
roundTripInt32Bi =
eachOf 1000 (Gen.int32 Range.constantBounded) roundTripsCBORBuildable
roundTripInt64Bi :: Property
roundTripInt64Bi =
eachOf 1000 (Gen.int64 Range.constantBounded) roundTripsCBORBuildable
roundTripRatioBi :: Property
roundTripRatioBi =
eachOf
1000
(((%) :: Integer -> Integer -> Rational)
<$> Gen.integral (Range.constant (-2 ^ (128 :: Int)) (2 ^ (128 :: Int)))
<*> Gen.integral (Range.constant (-2 ^ (128 :: Int)) (2 ^ (128 :: Int)))
)
roundTripsCBORBuildable
roundTripNanoBi :: Property
roundTripNanoBi = eachOf
1000
((MkFixed :: Integer -> Fixed E9) <$> Gen.integral (Range.constantFrom 0 (-1e12) 1e12))
roundTripsCBORShow
roundTripMapBi :: Property
roundTripMapBi = eachOf
100
(Gen.map
(Range.constant 0 50)
((,) <$> Gen.int Range.constantBounded <*> Gen.int Range.constantBounded)
)
roundTripsCBORShow
roundTripSetBi :: Property
roundTripSetBi = eachOf
100
(Gen.set (Range.constant 0 50) (Gen.int Range.constantBounded))
roundTripsCBORShow
roundTripByteStringBi :: Property
roundTripByteStringBi =
eachOf 100 (Gen.bytes $ Range.constant 0 100) roundTripsCBORShow
roundTripTextBi :: Property
roundTripTextBi = eachOf
100
(Gen.text (Range.constant 0 100) Gen.unicode)
roundTripsCBORBuildable
| null | https://raw.githubusercontent.com/input-output-hk/cardano-base/7e64caa79e0f751f1333ccbce4a64cb48752ae69/cardano-binary/test/Test/Cardano/Binary/RoundTrip.hs | haskell | # LANGUAGE NumDecimals #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module Test.Cardano.Binary.RoundTrip
( tests
)
where
import Test.Cardano.Prelude ( eachOf, discoverRoundTrip )
import Data.Ratio ((%))
import Data.Fixed (E9, Fixed(..))
import Hedgehog (Property, Range, checkParallel)
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Test.Cardano.Binary.Helpers.GoldenRoundTrip
(roundTripsCBORBuildable, roundTripsCBORShow)
tests :: IO Bool
tests = checkParallel $$discoverRoundTrip
roundTripUnitBi :: Property
roundTripUnitBi = eachOf 1 (pure ()) roundTripsCBORBuildable
roundTripBoolBi :: Property
roundTripBoolBi = eachOf 10 Gen.bool roundTripsCBORBuildable
| Tests up to ' Integer 's with multiple machine words using large upper bound
roundTripIntegerBi :: Property
roundTripIntegerBi = eachOf
1000
(Gen.integral (Range.linearFrom 0 (-1e40) 1e40 :: Range Integer))
roundTripsCBORBuildable
roundTripWordBi :: Property
roundTripWordBi =
eachOf 1000 (Gen.word Range.constantBounded) roundTripsCBORBuildable
roundTripWord8Bi :: Property
roundTripWord8Bi =
eachOf 1000 (Gen.word8 Range.constantBounded) roundTripsCBORBuildable
roundTripWord16Bi :: Property
roundTripWord16Bi =
eachOf 1000 (Gen.word16 Range.constantBounded) roundTripsCBORBuildable
roundTripWord32Bi :: Property
roundTripWord32Bi =
eachOf 1000 (Gen.word32 Range.constantBounded) roundTripsCBORBuildable
roundTripWord64Bi :: Property
roundTripWord64Bi =
eachOf 1000 (Gen.word64 Range.constantBounded) roundTripsCBORBuildable
roundTripIntBi :: Property
roundTripIntBi =
eachOf 1000 (Gen.int Range.constantBounded) roundTripsCBORBuildable
roundTripFloatBi :: Property
roundTripFloatBi =
eachOf 1000 (Gen.float (Range.constant (-1e12) 1e12)) roundTripsCBORBuildable
roundTripDoubleBi :: Property
roundTripDoubleBi =
eachOf 1000 (Gen.double (Range.constant (-1e308) 1e308)) roundTripsCBORBuildable
roundTripInt32Bi :: Property
roundTripInt32Bi =
eachOf 1000 (Gen.int32 Range.constantBounded) roundTripsCBORBuildable
roundTripInt64Bi :: Property
roundTripInt64Bi =
eachOf 1000 (Gen.int64 Range.constantBounded) roundTripsCBORBuildable
roundTripRatioBi :: Property
roundTripRatioBi =
eachOf
1000
(((%) :: Integer -> Integer -> Rational)
<$> Gen.integral (Range.constant (-2 ^ (128 :: Int)) (2 ^ (128 :: Int)))
<*> Gen.integral (Range.constant (-2 ^ (128 :: Int)) (2 ^ (128 :: Int)))
)
roundTripsCBORBuildable
roundTripNanoBi :: Property
roundTripNanoBi = eachOf
1000
((MkFixed :: Integer -> Fixed E9) <$> Gen.integral (Range.constantFrom 0 (-1e12) 1e12))
roundTripsCBORShow
roundTripMapBi :: Property
roundTripMapBi = eachOf
100
(Gen.map
(Range.constant 0 50)
((,) <$> Gen.int Range.constantBounded <*> Gen.int Range.constantBounded)
)
roundTripsCBORShow
roundTripSetBi :: Property
roundTripSetBi = eachOf
100
(Gen.set (Range.constant 0 50) (Gen.int Range.constantBounded))
roundTripsCBORShow
roundTripByteStringBi :: Property
roundTripByteStringBi =
eachOf 100 (Gen.bytes $ Range.constant 0 100) roundTripsCBORShow
roundTripTextBi :: Property
roundTripTextBi = eachOf
100
(Gen.text (Range.constant 0 100) Gen.unicode)
roundTripsCBORBuildable
|
|
0fe6c3aed7fb209232723358d868d003365a8ff70c7e4b9b742ce9a9cdc7a4bd | SquircleSpace/shcl | sequence.lisp | Copyright 2019
;;
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.
(defpackage :shcl/core/sequence
(:use :common-lisp)
(:import-from :shcl/core/utility
#:required #:optimization-settings #:make-extensible-vector
#:document #:define-documentation-type)
(:import-from :bordeaux-threads #:make-lock #:with-lock-held)
(:import-from :fset)
(:import-from :alexandria)
(:export
#:empty-p #:attach #:empty-of #:empty-for-type #:walk #:head #:tail
#:attachf #:popf #:do-while-popf #:lazy-map #:eager-map #:lazy-filter
#:eager-filter #:pour-from #:concatenate-sequences #:flatten-sequence
#:eager-flatmap-sequence #:walkable-to-list #:sequence-sort #:do-sequence
#:sequence-find-if #:sequence-find-if-not #:sequence-find
#:eager-sequence-remove-if #:eager-sequence-remove-if-not
#:eager-sequence-remove #:sequence-count-if #:sequence-count-if-not
#:sequence-count #:sequence-nth-tail #:sequence-stable-sort
#:immutable-cons #:empty-immutable-list #:immutable-list #:immutable-list*
#:lazy-sequence #:sequence-starts-with-p #:wrap-with #:cache-impure))
(in-package :shcl/core/sequence)
(optimization-settings)
;;; Walkable protocol
(defgeneric head (walkable)
(:documentation
"Return the first element of the given walkable.
A walkable type is one that has methods for both `head' and `tail'.
`head' is conceptually equivalent to the `car' function, and `tail' is
conceptually equivalent to the `cdr' function. Methods on this
generic function must be thread safe. That is, a walkable may be used
simultaneously from multiple threads.
If the walkable is empty (i.e. has no values left to produce) then
this function should return two nil values. If the walkable isn't
empty then this function shall return two values: the first element of
the sequence and a non-nil value."))
(defmethod head (walkable)
(let ((walker (walk walkable)))
(head walker)))
(defgeneric tail (walkable)
(:documentation
"Return a walkable representing everything except the first element
in `walkable'.
A walkable type is one that has methods for both `head' and `tail'.
`head' is conceptually equivalent to the `car' function, and `tail' is
conceptually equivalent to the `cdr' function. Methods on this
generic function must be thread safe. That is, a walkable may be used
simultaneously from multiple threads.
If `walkable' is empty then this function will return `walkable'
unmodified."))
(defmethod tail (walkable)
(let ((walker (walk walkable)))
(tail walker)))
(defgeneric empty-p (walkable)
(:documentation
"Return non-nil iff the given walkable has elements left.
Methods on this generic function should produce the same result as
(not (nth-value 1 (head walkable))).
In fact, this generic function has a method that falls back to using
`head' as shown above. This generic function is provided in case it
is cheaper to check for empty-ness than it is to retrieve the first
element."))
(defmethod empty-p (walkable)
(not (nth-value 1 (head walkable))))
;;; Sequence protocol
(defgeneric attach (sequence &rest values)
(:documentation
"Return a new version of `sequence' that has the values in `values'
included in it.
Methods may choose to attach the given values to the sequence at any
location. For example, attaching a value to a list will put that
value at the head of the list, but attaching a value to some other
sequence type may put the value at the end of the sequence.
If `values' contains more than one element, this generic function
should behave in a left-associative way. So, for example, these two
forms should have equivalent results.
(attach sequence 1 2 3)
(attach (attach (attach sequence 1) 2) 3)
If no values are provided then this generic function should return
`sequence'.
This generic function is not allowed to modify `sequence'."))
(defgeneric empty-of (sequence)
(:documentation
"Return an empty sequence of the same type as `sequence'.
Note: This generic function is intended to be used with the rest of
the sequence protocol. In particular, this is intended to be used in
conjunction with `attach'. If you can't write an efficient method for
`attach' then you probably shouldn't write a method for this generic
function, either."))
(defgeneric empty-for-type (type)
(:documentation
"Return an empty sequence of the named type.
Note: This generic function is intended to be used with the rest of
the sequence protocol. In particular, this is intended to be used in
conjunction with `attach'. If you can't write an efficient method for
`attach' then you probably shouldn't write a method for this generic
function, either."))
(defgeneric walk (sequence)
(:documentation
"Return an object that contains all the values contained in
`sequence' and implements the walkable protocol.
See the documentation for `head' and `tail' for more information about
the walkable protocol."))
(define-modify-macro attachf (&rest values) attach
"Replace the sequence stored in `sequence-place' with one that has
had the given values attached.
This is a trivial place-modification macro wrapper around `attach'.
Assuming the relevant `attach' method is following the rules, this
doesn't actually modify the sequence. It only modifies the place
where the sequence is stored.")
(defmacro popf (sequence-place &environment env)
"This macro operates like `pop' for anything that is walkable."
The naive expansion that just calls setf directly would evaluate
;; sequence-place multiple times.
(multiple-value-bind
(vars vals store-vars store-form access-form)
(get-setf-expansion sequence-place env)
(let ((temporary-bindings
(loop :for var :in vars :for val :in vals :collect (list var val)))
(body
`(multiple-value-prog1 (head ,access-form)
(multiple-value-bind ,store-vars (tail ,access-form)
,store-form))))
(if temporary-bindings
`(let* ,temporary-bindings
,body)
body))))
;;; Immutable lists
(defstruct immutable-list
"An immutable list is like a normal list except that you can't
change the spine of the list after you create it."
;; Okay, its actually a mutable struct... but we're not going to
;; export a symbol that can be used to set the slots.
head
tail)
;; This is a bit hacky. We're not using nil to represent empty list
;; because its nice having a way to represent empty list that is
;; different from a mutable empty list. If the immutable empty list
;; isa immutable-list then things like method specialization work
;; nicely.
(defstruct (immutable-nil (:include immutable-list))
"This struct is used to represent the end of an immutable list.")
(defvar *immutable-nil* (make-immutable-nil))
(defun empty-immutable-list ()
"Return an object representing an empty immutable list.
See `immutable-cons' and `immutable-list'."
*immutable-nil*)
(defun immutable-cons (head tail)
"Return a new `immutable-list' with the given head and tail.
This function is analogous to `cons', but it returns an object that
cannot be modified.
`tail' can be any sequence. It doesn't need to be another
`immutable-list'."
(make-immutable-list :head head :tail tail))
(defun immutable-list (&rest things)
"Produce an `immutable-list' that contains the given values.
This is a convenience function that uses `immutable-cons' and
`empty-immutable-list' to construct the list."
(labels
((visit (list)
(if list
(immutable-cons (car list) (visit (cdr list)))
(empty-immutable-list))))
(visit things)))
(defun immutable-list* (&rest things)
"Produce an `immutable-list' in the same way that `list*' would.
This is the `immutable-list' version of `list*'. The final element of
`things' is treated as a list that the other elements of `things' are
cons'd onto."
(labels
((visit (sublist)
(if (cdr sublist)
(immutable-cons (car sublist) (visit (cdr sublist)))
(car sublist))))
(if things
(visit things)
(empty-immutable-list))))
(defmethod walk ((immutable-list immutable-list))
immutable-list)
(defmethod head ((immutable-list immutable-list))
(values (immutable-list-head immutable-list) t))
(defmethod head ((immutable-nil immutable-nil))
(values nil nil))
(defmethod tail ((immutable-list immutable-list))
(immutable-list-tail immutable-list))
(defmethod tail ((immutable-nil immutable-nil))
immutable-nil)
(defmethod empty-p ((immutable-list immutable-list))
nil)
(defmethod empty-p ((immutable-nil immutable-nil))
t)
(defmethod attach ((immutable-list immutable-list) &rest values)
"Attach the given values to the front of the list."
(dolist (value values)
(setf immutable-list (immutable-cons value immutable-list)))
immutable-list)
(defmethod empty-of ((immutable-list immutable-list))
(empty-immutable-list))
(defmethod empty-for-type ((sym (eql 'immutable-list)))
(empty-immutable-list))
;;; Lazy sequences
(defclass lazy-sequence ()
((generator
:initarg :generator
:initform (required)))
(:documentation
"This class represents a sequence that is produced lazily.
Instances of this class represents a sequence that hasn't been
evaluated, yet. The generator function is expected to return a
sequence. Whenever a sequence function (e.g. `head', `tail',
`attach', etc.) is invoked on a `lazy-sequence', the generator
function is evaluated and the sequence function is invoked on the
result.
This class is typically used with `immutable-list' to produce a lazy
list. See the `lazy-sequence' macro documentation for an example of
this."))
(defun force-lazy-sequence (lazy-sequence)
(with-slots (generator) lazy-sequence
(funcall generator)))
(defmethod walk ((lazy-sequence lazy-sequence))
lazy-sequence)
(defmethod head ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(head seq)))
(defmethod tail ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(tail seq)))
(defmethod empty-p ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(empty-p seq)))
(defmethod attach ((lazy-sequence lazy-sequence) &rest values)
(let ((seq (force-lazy-sequence lazy-sequence)))
(apply 'attach seq values)))
(defmethod empty-of ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(empty-of seq)))
(defun cache-impure (function)
"Wrap `function' with a function that caches the result of
`function'.
`function' is assumed to take no arguments. Synchronization is used
to ensure that `function' is called at most once. This is meant to be
used with the `wrap-with' declaration in a `lazy-sequence' body. The
name refers to the fact that the given `function' is assumed to have
stateful effects."
(let ((lock (make-lock))
evaluated-p
values)
(lambda ()
(with-lock-held (lock)
(unless evaluated-p
(setf values (multiple-value-list (funcall function)))
(setf evaluated-p t))
(values-list values)))))
;; Ideally, wrap-with would be documented in the declaration doc-type,
;; but that symbol is owned by the common-lisp package.
;; Implementations are well within their rights to have documentation
;; methods that know how to read/write the declaration doc-type. It
;; would be sad if we overwrote those methods, here.
(define-documentation-type lazy-sequence)
(document wrap-with lazy-sequence
"Wrap the body of a `lazy-sequence' using a wrapping function.
This declaration is only valid at the start of a `lazy-sequence'
macro body. See the `lazy-sequence' macro for more information.")
(defmacro lazy-sequence (&whole whole &body body)
"Create a `lazy-sequence' object that evalutes `body' when it needs
to generate a concrete sequence.
When used in conjunction with `immutable-list', this macro can be used
to create lazy lists. For example, this code snippet creates a lazy
list containing the natural numbers.
(labels
((generate (value)
(lazy-sequence
(immutable-cons value (generate (1+ value))))))
(generate 0))
By default, the returned sequence will evaluate `body' every time a
sequence function is called on it. You must ensure that the body is
idempotent, thread-safe, and relatively cheap to evaluate.
Since caching is often desirable, this macro will recognize the
`wrap-with' declaration. When you use the `wrap-with' declaration,
the body of the macro will be turned into a 0-argument lambda that is
passed into the function named by the `wrap-with' declaration. The
wrapping function must return a funcallable object. That object will
be called whenever the `lazy-sequence' needs to produce its value.
When combined with a wrapping function like `cache-impure', you'll get
a `lazy-sequence' that evalutes `body' at most once.
If `wrap-with' appears multiple times, each wrapping function will be
called in the reverse of the order that they appear. For example, the
following lazy sequences will have identical behaviors.
(lazy-sequence
(declare (wrap-with first-wrapper)
(wrap-with second-wrapper))
(body-forms))
(let ((fn (first-wrapper (second-wrapper (lambda () (body-forms))))))
(lazy-sequence
(funcall fn)))
Note that you can also name a macro instead of a function."
(multiple-value-bind (body declarations) (alexandria:parse-body body :whole whole)
(let (wrapping-functions)
(labels
((consume-declaration (declaration)
(destructuring-bind (declare-sym &rest decl-clauses) declaration
(assert (eq declare-sym 'declare))
(unless (find 'wrap-with decl-clauses :key (lambda (entry) (and (consp entry) (car entry))))
(return-from consume-declaration declaration))
(let ((result-clauses (make-extensible-vector)))
(dolist (clause decl-clauses)
(cond
((and (consp clause) (eq (car clause) 'wrap-with))
(destructuring-bind (decl-name value) clause
(assert (eq decl-name 'wrap-with))
(check-type value symbol)
(push value wrapping-functions)))
(t
(vector-push-extend clause result-clauses))))
(unless (zerop (length result-clauses))
`(declare ,@(coerce result-clauses 'list)))))))
(setf declarations (mapcar #'consume-declaration declarations))
(setf declarations (remove nil declarations)))
(let ((generator `(lambda () ,@declarations ,@body)))
(dolist (wrapper wrapping-functions)
(setf generator `(,wrapper ,generator)))
`(make-instance 'lazy-sequence :generator ,generator)))))
;;; Lists
(defmethod walk ((list list))
list)
(defmethod head ((list list))
(if list
(values (car list) t)
(values nil nil)))
(defmethod tail ((list list))
(cdr list))
(defmethod empty-p ((list list))
(null list))
(defmethod attach ((list list) &rest values)
"Attach the given values to the front of the list."
(dolist (value values)
(setf list (cons value list)))
list)
(defmethod empty-of ((list list))
nil)
(defmethod empty-for-type ((sym (eql 'list)))
nil)
;;; vector
(defstruct vector-walkable
vector
offset)
(defmethod walk ((vector vector))
(if (zerop (length vector))
(make-vector-walkable)
(make-vector-walkable :vector vector :offset 0)))
(defmethod walk ((vector-walkable vector-walkable))
vector-walkable)
(defmethod head ((vector vector))
(if (zerop (length vector))
(values nil nil)
(values (aref vector 0) t)))
(defmethod head ((vector-walkable vector-walkable))
(if (vector-walkable-vector vector-walkable)
(values (aref (vector-walkable-vector vector-walkable)
(vector-walkable-offset vector-walkable))
t)
(values nil nil)))
(defmethod tail ((vector-walkable vector-walkable))
(unless (vector-walkable-vector vector-walkable)
(return-from tail vector-walkable))
(if (>= (1+ (vector-walkable-offset vector-walkable))
(length (vector-walkable-vector vector-walkable)))
(make-vector-walkable)
(make-vector-walkable :vector (vector-walkable-vector vector-walkable)
:offset (1+ (vector-walkable-offset vector-walkable)))))
(defmethod tail ((vector vector))
(if (>= 1 (length vector))
(make-vector-walkable)
(make-vector-walkable :vector vector :offset 1)))
(defmethod empty-p ((vector-walkable vector-walkable))
(null (vector-walkable-vector vector-walkable)))
(defmethod empty-p ((vector vector))
(zerop (length vector)))
;;; fset:seq
(defmethod walk ((seq fset:seq))
seq)
(defmethod head ((seq fset:seq))
(multiple-value-bind (value valid-p) (fset:first seq)
(if valid-p
(values value t)
(values nil nil))))
(defmethod tail ((seq fset:seq))
(fset:less-first seq))
(defmethod empty-p ((seq fset:seq))
(fset:empty? seq))
(defmethod attach ((seq fset:seq) &rest values)
"Attach the given values to the end of the sequence."
(dolist (value values)
(setf seq (fset:with-last seq value)))
seq)
(defmethod empty-of ((seq fset:seq))
(fset:empty-seq))
(defmethod empty-for-type ((sym (eql 'fset:seq)))
(fset:empty-seq))
;;; fset:set
(defmethod walk ((set fset:set))
set)
(defmethod head ((set fset:set))
(fset:least set))
(defmethod tail ((set fset:set))
(multiple-value-bind (value valid-p) (fset:least set)
(if valid-p
(fset:less set value)
set)))
(defmethod empty-p ((set fset:set))
(fset:empty? set))
(defmethod attach ((set fset:set) &rest values)
(dolist (value values)
(setf set (fset:with set value)))
set)
(defmethod empty-of ((set fset:set))
(fset:empty-set))
(defmethod empty-for-type ((sym (eql 'fset:set)))
(fset:empty-set))
;;; fset:map
(defmethod walk ((map fset:map))
map)
(defmethod head ((map fset:map))
(multiple-value-bind (key value valid-p) (fset:least map)
(if valid-p
(values (cons key value) t)
(values nil nil))))
(defmethod tail ((map fset:map))
(multiple-value-bind (key value valid-p) (fset:least map)
(declare (ignore value))
(if valid-p
(fset:less map key)
map)))
(defmethod empty-p ((map fset:map))
(fset:empty? map))
(defmethod attach ((map fset:map) &rest values)
(dolist (pair values)
(setf map (fset:with map (car pair) (cdr pair))))
map)
(defmethod empty-of ((map fset:map))
(fset:empty-map))
(defmethod empty-for-type ((sym (eql 'fset:map)))
(fset:empty-map))
;;; fset:bag
(defmethod walk ((bag fset:bag))
bag)
(defmethod head ((bag fset:bag))
(multiple-value-bind (value count valid-p) (fset:least bag)
(declare (ignore count))
(if valid-p
(values value t)
(values nil nil))))
(defmethod tail ((bag fset:bag))
(multiple-value-bind (value count valid-p) (fset:least bag)
(declare (ignore count))
(if valid-p
(fset:less bag value)
bag)))
(defmethod empty-p ((bag fset:bag))
(fset:empty? bag))
(defmethod attach ((bag fset:bag) &rest values)
(dolist (value values)
(setf bag (fset:with bag value)))
bag)
(defmethod empty-of ((bag fset:bag))
(fset:empty-bag))
(defmethod empty-for-type ((sym (eql 'fset:bag)))
(fset:empty-bag))
Utilities
(defmacro do-while-popf ((var walkable-place &optional result) &body body)
"As long as `walkable-place' contains a non-empty walkable, this
macro will pop an element off the walkable, bind it to `var', and evaluate
`body'.
This macro is sort of like the walkable version of `dolist'. However,
in an effort to avoid retaining the head of the sequence, this macro
is intentionally destructive. That is, `walkable-place' will get
modified each time this macro evaluates `body'.
This macro repeatedly uses `popf' to remove an element from
`walkable-place' until the second return value is nil. As a result,
`walkable-place' will be evaluated multiple times."
(let ((value (gensym "VALUE"))
(valid-p (gensym "VALID-P")))
`(loop
(multiple-value-bind (,value ,valid-p) (popf ,walkable-place)
(unless ,valid-p
(return ,result))
(let ((,var ,value))
,@body)))))
(defmacro do-sequence ((var sequence &optional result) &body body)
"Repeatedly evaluate `body' with `var' bound to the successive
elements in `sequence'.
This macro is the walkable version of `dolist'.
Note that unlike regular cons lists, sequences may be lazy and have an
infinite number of distinct elements. Thus, it is important to avoid
unnecessarily retaining a pointer to an early part of a sequence while
traversing it with this macro. See also `do-while-popf'."
(let ((walker (gensym "WALKER")))
`(let ((,walker ,sequence))
(do-while-popf (,var ,walker ,result)
,@body))))
(defun sequence-to-vector (sequence)
(let ((result (make-extensible-vector)))
(do-while-popf (element sequence)
(vector-push-extend element result))
result))
(defun sequence-sort (sequence predicate &key key)
"Return a sequence with the same elements as `sequence' but sorted
in the order determined by `predicate'.
This is a non-mutating, generic version of the standard `sort'. The
`predicate' and `key' arguments work exactly like in the standard
`sort' function."
(sort (sequence-to-vector sequence) predicate :key key))
(defun sequence-stable-sort (sequence predicate &key key)
"Return a sequence with the same elements as `sequence' but sorted
in the order determined by `predicate'.
This is a non-mutating, generic version of the standard `stable-sort'.
The `predicate' and `key' arguments work exactly like in the standard
`stable-sort' function. Stability is guaranteed just like with
`stable-sort'."
(stable-sort (sequence-to-vector sequence) predicate :key key))
(defun sequence-nth-tail (sequence nth)
"Pop off `nth' elements from `sequence' and return the result.
If `sequence' has at least `nth' elements then the second return value
will be 0. If `sequence' has fewer than `nth' elements then the
second return value will contain the difference between `nth' and the
length of `sequence'."
(check-type nth (integer 0))
(loop :for remaining :above 0 :downfrom nth :do
(multiple-value-bind (head valid-p) (popf sequence)
(declare (ignore head))
(unless valid-p
(return-from sequence-nth-tail
(values sequence remaining)))))
(values sequence 0))
(defun sequence-find-if (predicate sequence &key (start 0) end key)
"Search through `sequence' for an element that satisfies `predicate'.
This is a generic version of Common Lisp's `find-if'. Note: unlike
`find-if', this function does not support the from-end keyword
argument.
In addition to returning the item that was found, this function also
returns the sequence starting at the point where the item was found.
If no item was found then this function returns nil for both the first
and second return value."
(check-type start (integer 0))
(check-type end (or null (integer 0)))
(when end
(cond
((< end start)
(error "end must not be less than start"))
((equal end start)
(return-from sequence-find-if
(values nil nil)))))
(multiple-value-bind
(new-sequence uncompleted-steps)
(sequence-nth-tail sequence start)
(unless (zerop uncompleted-steps)
(return-from sequence-find-if
(values nil nil)))
(setf sequence new-sequence))
(when end
(decf end start)
(assert (plusp end) (end) "This should be impossible"))
(let ((previous-sequence sequence))
(do-while-popf (item sequence)
(when (funcall predicate (if key (funcall key item) item))
(return-from sequence-find-if
(values item previous-sequence)))
(when end
(decf end)
(when (not (plusp end))
(return-from sequence-find-if
(values nil nil))))
(setf previous-sequence sequence))))
(defun sequence-find-if-not (predicate sequence &rest args &key (start 0) end key)
"Search through `sequence' for an element that fails to satisfy
`predicate'.
This is a generic version of Common Lisp's `find-if-not'. Note:
unlike `find-if-not', this function does not support the from-end
keyword argument.
In addition to returning the item that was found, this function also
returns the sequence starting at the point where the item was found.
If no item was found then this function returns nil for both the first
and second return value."
(declare (ignore start end key))
(apply 'sequence-find-if (lambda (item) (not (funcall predicate item))) sequence args))
(defun finder-predicate (item test test-not)
(cond
((and (null test)
(null test-not))
(lambda (seq-item)
(eql item seq-item)))
((and test test-not)
(error "Only one of test or test-not should be provided"))
(test
(lambda (seq-item)
(funcall test item seq-item)))
(test-not
(lambda (seq-item)
(not (funcall test-not item seq-item))))
(t
(assert nil nil "This should be impossible"))))
(defun sequence-find (item sequence &key test test-not (start 0) end key)
"Search through `sequence' for an element that matches `item'.
This is a generic version of Common Lisp's `find'. Note: unlike
`find', this function does not support the from-end keyword argument.
In addition to returning the item that was found, this function also
returns the sequence starting at the point where the item was found.
If no item was found then this function returns nil for both the first
and second return value."
(sequence-find-if
(finder-predicate item test test-not)
sequence :start start :end end :key key))
(defun eager-sequence-remove-if (predicate sequence output-sequence &key (start 0) end count key)
"Search through `sequence', remove every element that satisfies
`predicate', and attach the remaining elements to `output-sequence'.
This is a generic version of Common Lisp's `remove-if'. Note: unlike
`remove-if', this function does not support the from-end keyword
argument."
(check-type start (integer 0))
(check-type end (or null (integer 0)))
(check-type count (or null (integer 0)))
(when end
(cond
((< end start)
(error "end must not be less than start"))
((equal end start)
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))))
(dotimes (count start)
(multiple-value-bind (head valid-p) (popf sequence)
(unless valid-p
(return-from eager-sequence-remove-if output-sequence))
(attachf output-sequence head)))
(when end
(decf end start)
(assert (plusp end) (end) "This should be impossible"))
(when (and count (minusp count))
(setf count 0))
(when (and count (zerop count))
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))
(do-while-popf (item sequence)
(cond
((funcall predicate (if key (funcall key item) item))
(when count
(decf count)
(when (zerop count)
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))))
(t
(attachf output-sequence item)))
(when end
(decf end)
(when (zerop end)
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))))
output-sequence)
(defun eager-sequence-remove-if-not (predicate sequence output-sequence &rest args &key (start 0) end count key)
"Search through `sequence', remove every element that fails to
satisfy `predicate', and attach the remaining elements to
`output-sequence'.
This is a generic version of Common Lisp's `remove-if-not'. Note:
unlike `remove-if-not', this function does not support the from-end
keyword argument."
(declare (ignore start end key count))
(apply 'eager-sequence-remove-if
(lambda (item) (not (funcall predicate item)))
sequence
output-sequence
args))
(defun eager-sequence-remove (item sequence output-sequence &key test test-not (start 0) end count key)
"Search through `sequence', remove every element that matches
`item', and attach the remaining elements to `output-sequence'.
This is a generic version of Common Lisp's `remove'. Note: unlike
`remove', this function does not support the from-end keyword
argument."
(eager-sequence-remove-if
(finder-predicate item test test-not)
sequence output-sequence :start start :end end :key key :count count))
(defun sequence-count-if (predicate sequence &key (start 0) end key)
"Count the number of items in `sequence' that satisfy `predicate'.
This is a generic version of Common Lisp's `count-if'. Note: unlike
`count-if' this function does not support the from-end keyword argument."
(check-type start (integer 0))
(check-type end (or null (integer 0)))
(when end
(cond
((< end start)
(error "end must not be less than start"))
((equal end start)
(return-from sequence-count-if
0))))
(multiple-value-bind
(new-sequence uncompleted-steps)
(sequence-nth-tail sequence start)
(unless (zerop uncompleted-steps)
(return-from sequence-count-if
0))
(setf sequence new-sequence))
(when end
(decf end start)
(assert (plusp end) (end) "This should be impossible"))
(let ((count 0))
(do-while-popf (item sequence)
(when (funcall predicate (if key (funcall key item) item))
(incf count))
(when end
(decf end)
(when (not (plusp end))
(return-from sequence-count-if
count))))
count))
(defun sequence-count-if-not (predicate sequence &rest args &key (start 0) end key)
"Count the number of items in `sequence' that fail to satisfy
`predicate'.
This is a generic version of Common Lisp's `count-if-not'. Note:
unlike `count-if-not' this function does not support the from-end keyword
argument."
(declare (ignore start end key))
(apply 'sequence-count-if
(lambda (item) (not (funcall predicate item)))
sequence
args))
(defun sequence-count (item sequence &key (start 0) end key test test-not)
"Count the number of items in `sequence' that match `item'.
This is a generic version of Common Lisp's `count'. Note:
unlike `count' this function does not support the from-end keyword
argument."
(sequence-count-if
(finder-predicate item test test-not) sequence
:start start :end end :key key))
(defun lazy-map (walkable fn)
"Create a lazy sequence that consists of `fn' applied to each
element in `walkable'.
`fn' is called at most once per element in `walkable'."
(lazy-sequence
(declare (wrap-with cache-impure))
(multiple-value-bind (value valid-p) (head walkable)
(if valid-p
(immutable-cons (funcall fn value) (lazy-map (tail walkable) fn))
(empty-immutable-list)))))
(defun eager-map (walkable fn output-sequence)
"Create an eagerly-evaluated sequence consisting of `fn' applied to
each element in `walkable'.
The result of the map operation is attached to `output-sequence'.
If `fn' is the identity function then this is semantically equivalent
to `pour-from'."
(do-while-popf (value walkable)
(attachf output-sequence (funcall fn value)))
output-sequence)
(defun lazy-filter (walkable fn)
"Create a lazy sequence that consists of the elements of `walkable'
for which `fn' returns non-nil.
`fn' is called at most once per element in `walkable'."
(lazy-sequence
(declare (wrap-with cache-impure))
(multiple-value-bind (value valid-p) (head walkable)
(cond
((and valid-p (funcall fn value))
(immutable-cons value (lazy-filter (tail walkable) fn)))
(valid-p
(lazy-filter (tail walkable) fn))
(t
(empty-immutable-list))))))
(defun eager-filter (walkable fn output-sequence)
"Create an eagerly-evaluated sequence consisting of the elements of
`walkable' for which `fn' returns non-nil.
The result of the filter operation is attached to `output-sequence'.
If `fn' always returns non-nil then this is semantically equivalent to
`pour-from'."
(do-while-popf (value walkable)
(when (funcall fn value)
(attachf output-sequence value)))
output-sequence)
(defun pour-from (source sink)
"Walk through `source' and attach all the values encountered onto
`sink' and returns the result.
Note: since sequences have inconsistent behaviors regarding where
`attach' operates, this is NOT a generic way to convert one sequence
type to another type. For example, converting an `fset:seq' to an
`immutable-list' will reverse the order of the elements!"
(do-while-popf (value source)
(attachf sink value))
sink)
(defstruct concatenated
sequences)
(defmethod walk ((concatenated concatenated))
concatenated)
(defmethod head ((concatenated concatenated))
(let ((sequences (concatenated-sequences concatenated)))
(do-while-popf (sequence sequences)
(multiple-value-bind (value valid-p) (head sequence)
(when valid-p
(return-from head (values value valid-p))))))
(values nil nil))
(defvar *empty-concatenated-sequence*
(make-concatenated))
(defmethod tail ((concatenated concatenated))
(let ((sequences (concatenated-sequences concatenated))
popped-p)
(loop
(multiple-value-bind (sequence valid-p) (popf sequences)
(unless valid-p
(return-from tail *empty-concatenated-sequence*))
(unless popped-p
(multiple-value-bind (value valid-p) (popf sequence)
(declare (ignore value))
(when valid-p
(setf popped-p t))))
(unless (empty-p sequence)
(setf sequences (immutable-cons sequence sequences))
(return-from tail (make-concatenated :sequences sequences))))))
*empty-concatenated-sequence*)
(defun concatenate-sequences (&rest sequences)
"Return a walkable that contains all the elements in the provided
sequences.
This function is just a trivial wrapper around `flatten-sequence'."
(flatten-sequence sequences))
(define-method-combination concatenate-sequences
:identity-with-one-argument t
:documentation
"A method combination that combines method results using the
`concatenate-sequences' function.
This is like a generic version of the `nconc' method combination.
Instead of returning lists that are then destructively modified, you
may return any walkable sequence..")
(defun flatten-sequence (sequence-of-sequences)
"Return a walkable that traverses the sequences contained within
`sequence-of-sequences'."
(make-concatenated :sequences sequence-of-sequences))
(defun eager-flatmap-sequence (walkable fn output-sequence)
"Apply `fn' to each element in `walkable' and then `attachf' each
element in the returned sequence to `output-sequence'.
After attaching the values to `output-sequence', this function returns
the resulting value of `output-sequence'.
This function is semantically equivalent to the following.
(pour-from (flatten-sequence (eager-map walkable fn nil)) output-sequence)
However, unlike the above snippet this function will avoid creating
the intermediate sequences returned by `eager-map' and
`flatten-sequence'."
(do-while-popf (value walkable)
(let ((inner-sequence (funcall fn value)))
(do-while-popf (inner-value inner-sequence)
(attachf output-sequence inner-value))))
output-sequence)
(defun walkable-to-list (walkable)
"Convert the given walkable sequence into a list.
Let's face it. Some things just want lists. This gives you a proper
list."
(when (typep walkable 'list)
(return-from walkable-to-list walkable))
(let (head
tail)
(do-while-popf (value walkable)
(cond
(tail
(setf (cdr tail) (cons value nil))
(setf tail (cdr tail)))
(t
(setf head (cons value nil))
(setf tail head))))
head))
(defun sequence-starts-with-p (sequence prefix &key (test 'eql))
"Returns non-nil if the first elements of `sequence' match the
first elements of `prefix'.
`sequence' and `prefix' may be any types that can be walked using
`head' and `tail'. When non-equal elements are found (as determined
by the function provided in the `test' parameter), this function
returns nil. If `sequence' has fewer elements than `prefix', this
function returns nil."
(loop
(multiple-value-bind (seq-value seq-valid) (popf sequence)
(multiple-value-bind (prefix-value prefix-valid) (popf prefix)
(cond
((not prefix-valid)
(return-from sequence-starts-with-p t))
((not seq-valid)
(return-from sequence-starts-with-p nil))
((not (funcall test seq-value prefix-value))
(return-from sequence-starts-with-p nil)))))))
| null | https://raw.githubusercontent.com/SquircleSpace/shcl/cc8d3c841b8b64b6715bf8f238fb19cd6093a793/core/sequence.lisp | lisp |
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.
Walkable protocol
Sequence protocol
sequence-place multiple times.
Immutable lists
Okay, its actually a mutable struct... but we're not going to
export a symbol that can be used to set the slots.
This is a bit hacky. We're not using nil to represent empty list
because its nice having a way to represent empty list that is
different from a mutable empty list. If the immutable empty list
isa immutable-list then things like method specialization work
nicely.
Lazy sequences
Ideally, wrap-with would be documented in the declaration doc-type,
but that symbol is owned by the common-lisp package.
Implementations are well within their rights to have documentation
methods that know how to read/write the declaration doc-type. It
would be sad if we overwrote those methods, here.
Lists
vector
fset:seq
fset:set
fset:map
fset:bag | Copyright 2019
distributed under the License is distributed on an " AS IS " BASIS ,
(defpackage :shcl/core/sequence
(:use :common-lisp)
(:import-from :shcl/core/utility
#:required #:optimization-settings #:make-extensible-vector
#:document #:define-documentation-type)
(:import-from :bordeaux-threads #:make-lock #:with-lock-held)
(:import-from :fset)
(:import-from :alexandria)
(:export
#:empty-p #:attach #:empty-of #:empty-for-type #:walk #:head #:tail
#:attachf #:popf #:do-while-popf #:lazy-map #:eager-map #:lazy-filter
#:eager-filter #:pour-from #:concatenate-sequences #:flatten-sequence
#:eager-flatmap-sequence #:walkable-to-list #:sequence-sort #:do-sequence
#:sequence-find-if #:sequence-find-if-not #:sequence-find
#:eager-sequence-remove-if #:eager-sequence-remove-if-not
#:eager-sequence-remove #:sequence-count-if #:sequence-count-if-not
#:sequence-count #:sequence-nth-tail #:sequence-stable-sort
#:immutable-cons #:empty-immutable-list #:immutable-list #:immutable-list*
#:lazy-sequence #:sequence-starts-with-p #:wrap-with #:cache-impure))
(in-package :shcl/core/sequence)
(optimization-settings)
(defgeneric head (walkable)
(:documentation
"Return the first element of the given walkable.
A walkable type is one that has methods for both `head' and `tail'.
`head' is conceptually equivalent to the `car' function, and `tail' is
conceptually equivalent to the `cdr' function. Methods on this
generic function must be thread safe. That is, a walkable may be used
simultaneously from multiple threads.
If the walkable is empty (i.e. has no values left to produce) then
this function should return two nil values. If the walkable isn't
empty then this function shall return two values: the first element of
the sequence and a non-nil value."))
(defmethod head (walkable)
(let ((walker (walk walkable)))
(head walker)))
(defgeneric tail (walkable)
(:documentation
"Return a walkable representing everything except the first element
in `walkable'.
A walkable type is one that has methods for both `head' and `tail'.
`head' is conceptually equivalent to the `car' function, and `tail' is
conceptually equivalent to the `cdr' function. Methods on this
generic function must be thread safe. That is, a walkable may be used
simultaneously from multiple threads.
If `walkable' is empty then this function will return `walkable'
unmodified."))
(defmethod tail (walkable)
(let ((walker (walk walkable)))
(tail walker)))
(defgeneric empty-p (walkable)
(:documentation
"Return non-nil iff the given walkable has elements left.
Methods on this generic function should produce the same result as
(not (nth-value 1 (head walkable))).
In fact, this generic function has a method that falls back to using
`head' as shown above. This generic function is provided in case it
is cheaper to check for empty-ness than it is to retrieve the first
element."))
(defmethod empty-p (walkable)
(not (nth-value 1 (head walkable))))
(defgeneric attach (sequence &rest values)
(:documentation
"Return a new version of `sequence' that has the values in `values'
included in it.
Methods may choose to attach the given values to the sequence at any
location. For example, attaching a value to a list will put that
value at the head of the list, but attaching a value to some other
sequence type may put the value at the end of the sequence.
If `values' contains more than one element, this generic function
should behave in a left-associative way. So, for example, these two
forms should have equivalent results.
(attach sequence 1 2 3)
(attach (attach (attach sequence 1) 2) 3)
If no values are provided then this generic function should return
`sequence'.
This generic function is not allowed to modify `sequence'."))
(defgeneric empty-of (sequence)
(:documentation
"Return an empty sequence of the same type as `sequence'.
Note: This generic function is intended to be used with the rest of
the sequence protocol. In particular, this is intended to be used in
conjunction with `attach'. If you can't write an efficient method for
`attach' then you probably shouldn't write a method for this generic
function, either."))
(defgeneric empty-for-type (type)
(:documentation
"Return an empty sequence of the named type.
Note: This generic function is intended to be used with the rest of
the sequence protocol. In particular, this is intended to be used in
conjunction with `attach'. If you can't write an efficient method for
`attach' then you probably shouldn't write a method for this generic
function, either."))
(defgeneric walk (sequence)
(:documentation
"Return an object that contains all the values contained in
`sequence' and implements the walkable protocol.
See the documentation for `head' and `tail' for more information about
the walkable protocol."))
(define-modify-macro attachf (&rest values) attach
"Replace the sequence stored in `sequence-place' with one that has
had the given values attached.
This is a trivial place-modification macro wrapper around `attach'.
Assuming the relevant `attach' method is following the rules, this
doesn't actually modify the sequence. It only modifies the place
where the sequence is stored.")
(defmacro popf (sequence-place &environment env)
"This macro operates like `pop' for anything that is walkable."
The naive expansion that just calls setf directly would evaluate
(multiple-value-bind
(vars vals store-vars store-form access-form)
(get-setf-expansion sequence-place env)
(let ((temporary-bindings
(loop :for var :in vars :for val :in vals :collect (list var val)))
(body
`(multiple-value-prog1 (head ,access-form)
(multiple-value-bind ,store-vars (tail ,access-form)
,store-form))))
(if temporary-bindings
`(let* ,temporary-bindings
,body)
body))))
(defstruct immutable-list
"An immutable list is like a normal list except that you can't
change the spine of the list after you create it."
head
tail)
(defstruct (immutable-nil (:include immutable-list))
"This struct is used to represent the end of an immutable list.")
(defvar *immutable-nil* (make-immutable-nil))
(defun empty-immutable-list ()
"Return an object representing an empty immutable list.
See `immutable-cons' and `immutable-list'."
*immutable-nil*)
(defun immutable-cons (head tail)
"Return a new `immutable-list' with the given head and tail.
This function is analogous to `cons', but it returns an object that
cannot be modified.
`tail' can be any sequence. It doesn't need to be another
`immutable-list'."
(make-immutable-list :head head :tail tail))
(defun immutable-list (&rest things)
"Produce an `immutable-list' that contains the given values.
This is a convenience function that uses `immutable-cons' and
`empty-immutable-list' to construct the list."
(labels
((visit (list)
(if list
(immutable-cons (car list) (visit (cdr list)))
(empty-immutable-list))))
(visit things)))
(defun immutable-list* (&rest things)
"Produce an `immutable-list' in the same way that `list*' would.
This is the `immutable-list' version of `list*'. The final element of
`things' is treated as a list that the other elements of `things' are
cons'd onto."
(labels
((visit (sublist)
(if (cdr sublist)
(immutable-cons (car sublist) (visit (cdr sublist)))
(car sublist))))
(if things
(visit things)
(empty-immutable-list))))
(defmethod walk ((immutable-list immutable-list))
immutable-list)
(defmethod head ((immutable-list immutable-list))
(values (immutable-list-head immutable-list) t))
(defmethod head ((immutable-nil immutable-nil))
(values nil nil))
(defmethod tail ((immutable-list immutable-list))
(immutable-list-tail immutable-list))
(defmethod tail ((immutable-nil immutable-nil))
immutable-nil)
(defmethod empty-p ((immutable-list immutable-list))
nil)
(defmethod empty-p ((immutable-nil immutable-nil))
t)
(defmethod attach ((immutable-list immutable-list) &rest values)
"Attach the given values to the front of the list."
(dolist (value values)
(setf immutable-list (immutable-cons value immutable-list)))
immutable-list)
(defmethod empty-of ((immutable-list immutable-list))
(empty-immutable-list))
(defmethod empty-for-type ((sym (eql 'immutable-list)))
(empty-immutable-list))
(defclass lazy-sequence ()
((generator
:initarg :generator
:initform (required)))
(:documentation
"This class represents a sequence that is produced lazily.
Instances of this class represents a sequence that hasn't been
evaluated, yet. The generator function is expected to return a
sequence. Whenever a sequence function (e.g. `head', `tail',
`attach', etc.) is invoked on a `lazy-sequence', the generator
function is evaluated and the sequence function is invoked on the
result.
This class is typically used with `immutable-list' to produce a lazy
list. See the `lazy-sequence' macro documentation for an example of
this."))
(defun force-lazy-sequence (lazy-sequence)
(with-slots (generator) lazy-sequence
(funcall generator)))
(defmethod walk ((lazy-sequence lazy-sequence))
lazy-sequence)
(defmethod head ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(head seq)))
(defmethod tail ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(tail seq)))
(defmethod empty-p ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(empty-p seq)))
(defmethod attach ((lazy-sequence lazy-sequence) &rest values)
(let ((seq (force-lazy-sequence lazy-sequence)))
(apply 'attach seq values)))
(defmethod empty-of ((lazy-sequence lazy-sequence))
(let ((seq (force-lazy-sequence lazy-sequence)))
(empty-of seq)))
(defun cache-impure (function)
"Wrap `function' with a function that caches the result of
`function'.
`function' is assumed to take no arguments. Synchronization is used
to ensure that `function' is called at most once. This is meant to be
used with the `wrap-with' declaration in a `lazy-sequence' body. The
name refers to the fact that the given `function' is assumed to have
stateful effects."
(let ((lock (make-lock))
evaluated-p
values)
(lambda ()
(with-lock-held (lock)
(unless evaluated-p
(setf values (multiple-value-list (funcall function)))
(setf evaluated-p t))
(values-list values)))))
(define-documentation-type lazy-sequence)
(document wrap-with lazy-sequence
"Wrap the body of a `lazy-sequence' using a wrapping function.
This declaration is only valid at the start of a `lazy-sequence'
macro body. See the `lazy-sequence' macro for more information.")
(defmacro lazy-sequence (&whole whole &body body)
"Create a `lazy-sequence' object that evalutes `body' when it needs
to generate a concrete sequence.
When used in conjunction with `immutable-list', this macro can be used
to create lazy lists. For example, this code snippet creates a lazy
list containing the natural numbers.
(labels
((generate (value)
(lazy-sequence
(immutable-cons value (generate (1+ value))))))
(generate 0))
By default, the returned sequence will evaluate `body' every time a
sequence function is called on it. You must ensure that the body is
idempotent, thread-safe, and relatively cheap to evaluate.
Since caching is often desirable, this macro will recognize the
`wrap-with' declaration. When you use the `wrap-with' declaration,
the body of the macro will be turned into a 0-argument lambda that is
passed into the function named by the `wrap-with' declaration. The
wrapping function must return a funcallable object. That object will
be called whenever the `lazy-sequence' needs to produce its value.
When combined with a wrapping function like `cache-impure', you'll get
a `lazy-sequence' that evalutes `body' at most once.
If `wrap-with' appears multiple times, each wrapping function will be
called in the reverse of the order that they appear. For example, the
following lazy sequences will have identical behaviors.
(lazy-sequence
(declare (wrap-with first-wrapper)
(wrap-with second-wrapper))
(body-forms))
(let ((fn (first-wrapper (second-wrapper (lambda () (body-forms))))))
(lazy-sequence
(funcall fn)))
Note that you can also name a macro instead of a function."
(multiple-value-bind (body declarations) (alexandria:parse-body body :whole whole)
(let (wrapping-functions)
(labels
((consume-declaration (declaration)
(destructuring-bind (declare-sym &rest decl-clauses) declaration
(assert (eq declare-sym 'declare))
(unless (find 'wrap-with decl-clauses :key (lambda (entry) (and (consp entry) (car entry))))
(return-from consume-declaration declaration))
(let ((result-clauses (make-extensible-vector)))
(dolist (clause decl-clauses)
(cond
((and (consp clause) (eq (car clause) 'wrap-with))
(destructuring-bind (decl-name value) clause
(assert (eq decl-name 'wrap-with))
(check-type value symbol)
(push value wrapping-functions)))
(t
(vector-push-extend clause result-clauses))))
(unless (zerop (length result-clauses))
`(declare ,@(coerce result-clauses 'list)))))))
(setf declarations (mapcar #'consume-declaration declarations))
(setf declarations (remove nil declarations)))
(let ((generator `(lambda () ,@declarations ,@body)))
(dolist (wrapper wrapping-functions)
(setf generator `(,wrapper ,generator)))
`(make-instance 'lazy-sequence :generator ,generator)))))
(defmethod walk ((list list))
list)
(defmethod head ((list list))
(if list
(values (car list) t)
(values nil nil)))
(defmethod tail ((list list))
(cdr list))
(defmethod empty-p ((list list))
(null list))
(defmethod attach ((list list) &rest values)
"Attach the given values to the front of the list."
(dolist (value values)
(setf list (cons value list)))
list)
(defmethod empty-of ((list list))
nil)
(defmethod empty-for-type ((sym (eql 'list)))
nil)
(defstruct vector-walkable
vector
offset)
(defmethod walk ((vector vector))
(if (zerop (length vector))
(make-vector-walkable)
(make-vector-walkable :vector vector :offset 0)))
(defmethod walk ((vector-walkable vector-walkable))
vector-walkable)
(defmethod head ((vector vector))
(if (zerop (length vector))
(values nil nil)
(values (aref vector 0) t)))
(defmethod head ((vector-walkable vector-walkable))
(if (vector-walkable-vector vector-walkable)
(values (aref (vector-walkable-vector vector-walkable)
(vector-walkable-offset vector-walkable))
t)
(values nil nil)))
(defmethod tail ((vector-walkable vector-walkable))
(unless (vector-walkable-vector vector-walkable)
(return-from tail vector-walkable))
(if (>= (1+ (vector-walkable-offset vector-walkable))
(length (vector-walkable-vector vector-walkable)))
(make-vector-walkable)
(make-vector-walkable :vector (vector-walkable-vector vector-walkable)
:offset (1+ (vector-walkable-offset vector-walkable)))))
(defmethod tail ((vector vector))
(if (>= 1 (length vector))
(make-vector-walkable)
(make-vector-walkable :vector vector :offset 1)))
(defmethod empty-p ((vector-walkable vector-walkable))
(null (vector-walkable-vector vector-walkable)))
(defmethod empty-p ((vector vector))
(zerop (length vector)))
(defmethod walk ((seq fset:seq))
seq)
(defmethod head ((seq fset:seq))
(multiple-value-bind (value valid-p) (fset:first seq)
(if valid-p
(values value t)
(values nil nil))))
(defmethod tail ((seq fset:seq))
(fset:less-first seq))
(defmethod empty-p ((seq fset:seq))
(fset:empty? seq))
(defmethod attach ((seq fset:seq) &rest values)
"Attach the given values to the end of the sequence."
(dolist (value values)
(setf seq (fset:with-last seq value)))
seq)
(defmethod empty-of ((seq fset:seq))
(fset:empty-seq))
(defmethod empty-for-type ((sym (eql 'fset:seq)))
(fset:empty-seq))
(defmethod walk ((set fset:set))
set)
(defmethod head ((set fset:set))
(fset:least set))
(defmethod tail ((set fset:set))
(multiple-value-bind (value valid-p) (fset:least set)
(if valid-p
(fset:less set value)
set)))
(defmethod empty-p ((set fset:set))
(fset:empty? set))
(defmethod attach ((set fset:set) &rest values)
(dolist (value values)
(setf set (fset:with set value)))
set)
(defmethod empty-of ((set fset:set))
(fset:empty-set))
(defmethod empty-for-type ((sym (eql 'fset:set)))
(fset:empty-set))
(defmethod walk ((map fset:map))
map)
(defmethod head ((map fset:map))
(multiple-value-bind (key value valid-p) (fset:least map)
(if valid-p
(values (cons key value) t)
(values nil nil))))
(defmethod tail ((map fset:map))
(multiple-value-bind (key value valid-p) (fset:least map)
(declare (ignore value))
(if valid-p
(fset:less map key)
map)))
(defmethod empty-p ((map fset:map))
(fset:empty? map))
(defmethod attach ((map fset:map) &rest values)
(dolist (pair values)
(setf map (fset:with map (car pair) (cdr pair))))
map)
(defmethod empty-of ((map fset:map))
(fset:empty-map))
(defmethod empty-for-type ((sym (eql 'fset:map)))
(fset:empty-map))
(defmethod walk ((bag fset:bag))
bag)
(defmethod head ((bag fset:bag))
(multiple-value-bind (value count valid-p) (fset:least bag)
(declare (ignore count))
(if valid-p
(values value t)
(values nil nil))))
(defmethod tail ((bag fset:bag))
(multiple-value-bind (value count valid-p) (fset:least bag)
(declare (ignore count))
(if valid-p
(fset:less bag value)
bag)))
(defmethod empty-p ((bag fset:bag))
(fset:empty? bag))
(defmethod attach ((bag fset:bag) &rest values)
(dolist (value values)
(setf bag (fset:with bag value)))
bag)
(defmethod empty-of ((bag fset:bag))
(fset:empty-bag))
(defmethod empty-for-type ((sym (eql 'fset:bag)))
(fset:empty-bag))
Utilities
(defmacro do-while-popf ((var walkable-place &optional result) &body body)
"As long as `walkable-place' contains a non-empty walkable, this
macro will pop an element off the walkable, bind it to `var', and evaluate
`body'.
This macro is sort of like the walkable version of `dolist'. However,
in an effort to avoid retaining the head of the sequence, this macro
is intentionally destructive. That is, `walkable-place' will get
modified each time this macro evaluates `body'.
This macro repeatedly uses `popf' to remove an element from
`walkable-place' until the second return value is nil. As a result,
`walkable-place' will be evaluated multiple times."
(let ((value (gensym "VALUE"))
(valid-p (gensym "VALID-P")))
`(loop
(multiple-value-bind (,value ,valid-p) (popf ,walkable-place)
(unless ,valid-p
(return ,result))
(let ((,var ,value))
,@body)))))
(defmacro do-sequence ((var sequence &optional result) &body body)
"Repeatedly evaluate `body' with `var' bound to the successive
elements in `sequence'.
This macro is the walkable version of `dolist'.
Note that unlike regular cons lists, sequences may be lazy and have an
infinite number of distinct elements. Thus, it is important to avoid
unnecessarily retaining a pointer to an early part of a sequence while
traversing it with this macro. See also `do-while-popf'."
(let ((walker (gensym "WALKER")))
`(let ((,walker ,sequence))
(do-while-popf (,var ,walker ,result)
,@body))))
(defun sequence-to-vector (sequence)
(let ((result (make-extensible-vector)))
(do-while-popf (element sequence)
(vector-push-extend element result))
result))
(defun sequence-sort (sequence predicate &key key)
"Return a sequence with the same elements as `sequence' but sorted
in the order determined by `predicate'.
This is a non-mutating, generic version of the standard `sort'. The
`predicate' and `key' arguments work exactly like in the standard
`sort' function."
(sort (sequence-to-vector sequence) predicate :key key))
(defun sequence-stable-sort (sequence predicate &key key)
"Return a sequence with the same elements as `sequence' but sorted
in the order determined by `predicate'.
This is a non-mutating, generic version of the standard `stable-sort'.
The `predicate' and `key' arguments work exactly like in the standard
`stable-sort' function. Stability is guaranteed just like with
`stable-sort'."
(stable-sort (sequence-to-vector sequence) predicate :key key))
(defun sequence-nth-tail (sequence nth)
"Pop off `nth' elements from `sequence' and return the result.
If `sequence' has at least `nth' elements then the second return value
will be 0. If `sequence' has fewer than `nth' elements then the
second return value will contain the difference between `nth' and the
length of `sequence'."
(check-type nth (integer 0))
(loop :for remaining :above 0 :downfrom nth :do
(multiple-value-bind (head valid-p) (popf sequence)
(declare (ignore head))
(unless valid-p
(return-from sequence-nth-tail
(values sequence remaining)))))
(values sequence 0))
(defun sequence-find-if (predicate sequence &key (start 0) end key)
"Search through `sequence' for an element that satisfies `predicate'.
This is a generic version of Common Lisp's `find-if'. Note: unlike
`find-if', this function does not support the from-end keyword
argument.
In addition to returning the item that was found, this function also
returns the sequence starting at the point where the item was found.
If no item was found then this function returns nil for both the first
and second return value."
(check-type start (integer 0))
(check-type end (or null (integer 0)))
(when end
(cond
((< end start)
(error "end must not be less than start"))
((equal end start)
(return-from sequence-find-if
(values nil nil)))))
(multiple-value-bind
(new-sequence uncompleted-steps)
(sequence-nth-tail sequence start)
(unless (zerop uncompleted-steps)
(return-from sequence-find-if
(values nil nil)))
(setf sequence new-sequence))
(when end
(decf end start)
(assert (plusp end) (end) "This should be impossible"))
(let ((previous-sequence sequence))
(do-while-popf (item sequence)
(when (funcall predicate (if key (funcall key item) item))
(return-from sequence-find-if
(values item previous-sequence)))
(when end
(decf end)
(when (not (plusp end))
(return-from sequence-find-if
(values nil nil))))
(setf previous-sequence sequence))))
(defun sequence-find-if-not (predicate sequence &rest args &key (start 0) end key)
"Search through `sequence' for an element that fails to satisfy
`predicate'.
This is a generic version of Common Lisp's `find-if-not'. Note:
unlike `find-if-not', this function does not support the from-end
keyword argument.
In addition to returning the item that was found, this function also
returns the sequence starting at the point where the item was found.
If no item was found then this function returns nil for both the first
and second return value."
(declare (ignore start end key))
(apply 'sequence-find-if (lambda (item) (not (funcall predicate item))) sequence args))
(defun finder-predicate (item test test-not)
(cond
((and (null test)
(null test-not))
(lambda (seq-item)
(eql item seq-item)))
((and test test-not)
(error "Only one of test or test-not should be provided"))
(test
(lambda (seq-item)
(funcall test item seq-item)))
(test-not
(lambda (seq-item)
(not (funcall test-not item seq-item))))
(t
(assert nil nil "This should be impossible"))))
(defun sequence-find (item sequence &key test test-not (start 0) end key)
"Search through `sequence' for an element that matches `item'.
This is a generic version of Common Lisp's `find'. Note: unlike
`find', this function does not support the from-end keyword argument.
In addition to returning the item that was found, this function also
returns the sequence starting at the point where the item was found.
If no item was found then this function returns nil for both the first
and second return value."
(sequence-find-if
(finder-predicate item test test-not)
sequence :start start :end end :key key))
(defun eager-sequence-remove-if (predicate sequence output-sequence &key (start 0) end count key)
"Search through `sequence', remove every element that satisfies
`predicate', and attach the remaining elements to `output-sequence'.
This is a generic version of Common Lisp's `remove-if'. Note: unlike
`remove-if', this function does not support the from-end keyword
argument."
(check-type start (integer 0))
(check-type end (or null (integer 0)))
(check-type count (or null (integer 0)))
(when end
(cond
((< end start)
(error "end must not be less than start"))
((equal end start)
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))))
(dotimes (count start)
(multiple-value-bind (head valid-p) (popf sequence)
(unless valid-p
(return-from eager-sequence-remove-if output-sequence))
(attachf output-sequence head)))
(when end
(decf end start)
(assert (plusp end) (end) "This should be impossible"))
(when (and count (minusp count))
(setf count 0))
(when (and count (zerop count))
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))
(do-while-popf (item sequence)
(cond
((funcall predicate (if key (funcall key item) item))
(when count
(decf count)
(when (zerop count)
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))))
(t
(attachf output-sequence item)))
(when end
(decf end)
(when (zerop end)
(return-from eager-sequence-remove-if
(pour-from sequence output-sequence)))))
output-sequence)
(defun eager-sequence-remove-if-not (predicate sequence output-sequence &rest args &key (start 0) end count key)
"Search through `sequence', remove every element that fails to
satisfy `predicate', and attach the remaining elements to
`output-sequence'.
This is a generic version of Common Lisp's `remove-if-not'. Note:
unlike `remove-if-not', this function does not support the from-end
keyword argument."
(declare (ignore start end key count))
(apply 'eager-sequence-remove-if
(lambda (item) (not (funcall predicate item)))
sequence
output-sequence
args))
(defun eager-sequence-remove (item sequence output-sequence &key test test-not (start 0) end count key)
"Search through `sequence', remove every element that matches
`item', and attach the remaining elements to `output-sequence'.
This is a generic version of Common Lisp's `remove'. Note: unlike
`remove', this function does not support the from-end keyword
argument."
(eager-sequence-remove-if
(finder-predicate item test test-not)
sequence output-sequence :start start :end end :key key :count count))
(defun sequence-count-if (predicate sequence &key (start 0) end key)
"Count the number of items in `sequence' that satisfy `predicate'.
This is a generic version of Common Lisp's `count-if'. Note: unlike
`count-if' this function does not support the from-end keyword argument."
(check-type start (integer 0))
(check-type end (or null (integer 0)))
(when end
(cond
((< end start)
(error "end must not be less than start"))
((equal end start)
(return-from sequence-count-if
0))))
(multiple-value-bind
(new-sequence uncompleted-steps)
(sequence-nth-tail sequence start)
(unless (zerop uncompleted-steps)
(return-from sequence-count-if
0))
(setf sequence new-sequence))
(when end
(decf end start)
(assert (plusp end) (end) "This should be impossible"))
(let ((count 0))
(do-while-popf (item sequence)
(when (funcall predicate (if key (funcall key item) item))
(incf count))
(when end
(decf end)
(when (not (plusp end))
(return-from sequence-count-if
count))))
count))
(defun sequence-count-if-not (predicate sequence &rest args &key (start 0) end key)
"Count the number of items in `sequence' that fail to satisfy
`predicate'.
This is a generic version of Common Lisp's `count-if-not'. Note:
unlike `count-if-not' this function does not support the from-end keyword
argument."
(declare (ignore start end key))
(apply 'sequence-count-if
(lambda (item) (not (funcall predicate item)))
sequence
args))
(defun sequence-count (item sequence &key (start 0) end key test test-not)
"Count the number of items in `sequence' that match `item'.
This is a generic version of Common Lisp's `count'. Note:
unlike `count' this function does not support the from-end keyword
argument."
(sequence-count-if
(finder-predicate item test test-not) sequence
:start start :end end :key key))
(defun lazy-map (walkable fn)
"Create a lazy sequence that consists of `fn' applied to each
element in `walkable'.
`fn' is called at most once per element in `walkable'."
(lazy-sequence
(declare (wrap-with cache-impure))
(multiple-value-bind (value valid-p) (head walkable)
(if valid-p
(immutable-cons (funcall fn value) (lazy-map (tail walkable) fn))
(empty-immutable-list)))))
(defun eager-map (walkable fn output-sequence)
"Create an eagerly-evaluated sequence consisting of `fn' applied to
each element in `walkable'.
The result of the map operation is attached to `output-sequence'.
If `fn' is the identity function then this is semantically equivalent
to `pour-from'."
(do-while-popf (value walkable)
(attachf output-sequence (funcall fn value)))
output-sequence)
(defun lazy-filter (walkable fn)
"Create a lazy sequence that consists of the elements of `walkable'
for which `fn' returns non-nil.
`fn' is called at most once per element in `walkable'."
(lazy-sequence
(declare (wrap-with cache-impure))
(multiple-value-bind (value valid-p) (head walkable)
(cond
((and valid-p (funcall fn value))
(immutable-cons value (lazy-filter (tail walkable) fn)))
(valid-p
(lazy-filter (tail walkable) fn))
(t
(empty-immutable-list))))))
(defun eager-filter (walkable fn output-sequence)
"Create an eagerly-evaluated sequence consisting of the elements of
`walkable' for which `fn' returns non-nil.
The result of the filter operation is attached to `output-sequence'.
If `fn' always returns non-nil then this is semantically equivalent to
`pour-from'."
(do-while-popf (value walkable)
(when (funcall fn value)
(attachf output-sequence value)))
output-sequence)
(defun pour-from (source sink)
"Walk through `source' and attach all the values encountered onto
`sink' and returns the result.
Note: since sequences have inconsistent behaviors regarding where
`attach' operates, this is NOT a generic way to convert one sequence
type to another type. For example, converting an `fset:seq' to an
`immutable-list' will reverse the order of the elements!"
(do-while-popf (value source)
(attachf sink value))
sink)
(defstruct concatenated
sequences)
(defmethod walk ((concatenated concatenated))
concatenated)
(defmethod head ((concatenated concatenated))
(let ((sequences (concatenated-sequences concatenated)))
(do-while-popf (sequence sequences)
(multiple-value-bind (value valid-p) (head sequence)
(when valid-p
(return-from head (values value valid-p))))))
(values nil nil))
(defvar *empty-concatenated-sequence*
(make-concatenated))
(defmethod tail ((concatenated concatenated))
(let ((sequences (concatenated-sequences concatenated))
popped-p)
(loop
(multiple-value-bind (sequence valid-p) (popf sequences)
(unless valid-p
(return-from tail *empty-concatenated-sequence*))
(unless popped-p
(multiple-value-bind (value valid-p) (popf sequence)
(declare (ignore value))
(when valid-p
(setf popped-p t))))
(unless (empty-p sequence)
(setf sequences (immutable-cons sequence sequences))
(return-from tail (make-concatenated :sequences sequences))))))
*empty-concatenated-sequence*)
(defun concatenate-sequences (&rest sequences)
"Return a walkable that contains all the elements in the provided
sequences.
This function is just a trivial wrapper around `flatten-sequence'."
(flatten-sequence sequences))
(define-method-combination concatenate-sequences
:identity-with-one-argument t
:documentation
"A method combination that combines method results using the
`concatenate-sequences' function.
This is like a generic version of the `nconc' method combination.
Instead of returning lists that are then destructively modified, you
may return any walkable sequence..")
(defun flatten-sequence (sequence-of-sequences)
"Return a walkable that traverses the sequences contained within
`sequence-of-sequences'."
(make-concatenated :sequences sequence-of-sequences))
(defun eager-flatmap-sequence (walkable fn output-sequence)
"Apply `fn' to each element in `walkable' and then `attachf' each
element in the returned sequence to `output-sequence'.
After attaching the values to `output-sequence', this function returns
the resulting value of `output-sequence'.
This function is semantically equivalent to the following.
(pour-from (flatten-sequence (eager-map walkable fn nil)) output-sequence)
However, unlike the above snippet this function will avoid creating
the intermediate sequences returned by `eager-map' and
`flatten-sequence'."
(do-while-popf (value walkable)
(let ((inner-sequence (funcall fn value)))
(do-while-popf (inner-value inner-sequence)
(attachf output-sequence inner-value))))
output-sequence)
(defun walkable-to-list (walkable)
"Convert the given walkable sequence into a list.
Let's face it. Some things just want lists. This gives you a proper
list."
(when (typep walkable 'list)
(return-from walkable-to-list walkable))
(let (head
tail)
(do-while-popf (value walkable)
(cond
(tail
(setf (cdr tail) (cons value nil))
(setf tail (cdr tail)))
(t
(setf head (cons value nil))
(setf tail head))))
head))
(defun sequence-starts-with-p (sequence prefix &key (test 'eql))
"Returns non-nil if the first elements of `sequence' match the
first elements of `prefix'.
`sequence' and `prefix' may be any types that can be walked using
`head' and `tail'. When non-equal elements are found (as determined
by the function provided in the `test' parameter), this function
returns nil. If `sequence' has fewer elements than `prefix', this
function returns nil."
(loop
(multiple-value-bind (seq-value seq-valid) (popf sequence)
(multiple-value-bind (prefix-value prefix-valid) (popf prefix)
(cond
((not prefix-valid)
(return-from sequence-starts-with-p t))
((not seq-valid)
(return-from sequence-starts-with-p nil))
((not (funcall test seq-value prefix-value))
(return-from sequence-starts-with-p nil)))))))
|
7ca3e705e35da5f6425c03fcabd52f323ca5adc358262dbefd15b6749357567c | MarcusPlieninger/HtDP_2e_solutions | HtDP_2e_Exercise_007.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname HtDP_2e_Exercise_7) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
Exercise 7 . Boolean expressions can express some everyday problems .
Suppose you want to decide whether today is an appropriate day to go to the mall .
You go to the mall either if it is not sunny or if today is Friday ( because that is when stores post new sales items ) .
Here is how you could go about it using your new knowledge about Booleans .
First add these two lines to the definitions area of :
;(define sunny #true)
( define friday # false )
Now create an expression that computes whether sunny is false or friday is true .
;So in this particular case, the answer is #false. (Why?)
See exercise 1 for how to create expressions in .
How many combinations of Booleans can you associate with sunny and friday ?
(define sunny #true)
Sunny is a constant to which is assigned the Boolean value of true .
(define friday #false)
friday is a constant to which is assigned the Boolean value of false .
(or (not sunny) friday)
In this particular case , the answer is # false because not sunny evalutes to false and friday evaluates to false .
;A disjunction where both values are false evaluates to false.
The logical form of this expression is the negation of one premise in a disjunction .
;The reason for the negation is that whatever the boolean value of sunny is, its negation will determine the action.
So , if sunny is true , then it is false that there will be a trip to the mall -- unless of course it is Friday .
4 combinations of Booleans can be assocaited with sunny and friday :
sunny false , friday true
sunny false , friday false
sunny true , friday true
sunny true , friday false
| null | https://raw.githubusercontent.com/MarcusPlieninger/HtDP_2e_solutions/1b25b01ee950034c43cc9a907c4eabae2b5e4dbc/HtDP_2e_Exercise_007.rkt | racket | about the language level of this file in a form that our tools can easily process.
(define sunny #true)
So in this particular case, the answer is #false. (Why?)
A disjunction where both values are false evaluates to false.
The reason for the negation is that whatever the boolean value of sunny is, its negation will determine the action. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname HtDP_2e_Exercise_7) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
Exercise 7 . Boolean expressions can express some everyday problems .
Suppose you want to decide whether today is an appropriate day to go to the mall .
You go to the mall either if it is not sunny or if today is Friday ( because that is when stores post new sales items ) .
Here is how you could go about it using your new knowledge about Booleans .
First add these two lines to the definitions area of :
( define friday # false )
Now create an expression that computes whether sunny is false or friday is true .
See exercise 1 for how to create expressions in .
How many combinations of Booleans can you associate with sunny and friday ?
(define sunny #true)
Sunny is a constant to which is assigned the Boolean value of true .
(define friday #false)
friday is a constant to which is assigned the Boolean value of false .
(or (not sunny) friday)
In this particular case , the answer is # false because not sunny evalutes to false and friday evaluates to false .
The logical form of this expression is the negation of one premise in a disjunction .
So , if sunny is true , then it is false that there will be a trip to the mall -- unless of course it is Friday .
4 combinations of Booleans can be assocaited with sunny and friday :
sunny false , friday true
sunny false , friday false
sunny true , friday true
sunny true , friday false
|
8c48575740c6bc481b6a0e11d948d9ea481d0bb6122b6531ebffb952ce045100 | monadfix/shower | Class.hs | {- |
This module defines the representation of data that the parser produces and the
pretty-printer consumes.
-}
module Shower.Class where
-- | A tagless final encoding for a result builder (@ShowS@, @Doc@, @Html@, etc).
--
-- Note that 'showerStringLit' and 'showerCharLit' take exact uninterpreted
strings to avoid losing information ( e.g. @"\\n"@ vs. @"\\10"@ ) .
class Shower a where
| A record , @ { x = 24 , y = 42 } @ or @ { " a " : null , " b " : 13 } @.
showerRecord :: [ShowerComma (a, ShowerFieldSep, a)] -> a
| A list , @[1 , 2 , 3]@.
showerList :: [ShowerComma a] -> a
| A tuple , @(1 , 2 , 3)@.
showerTuple :: [ShowerComma a] -> a
-- | A string literal, @"hello, (world)"@.
showerStringLit :: String -> a
| A character literal , @'('@.
showerCharLit :: String -> a
-- | Variable names, numeric literals, and so on.
showerAtom :: String -> a
| Whitespace - separated elements .
showerSpace :: [a] -> a
| A field separator used in records , either @\'=\'@ for records or
-- @\':\'@ for JSON.
data ShowerFieldSep =
^ An equality sign , @\'=\'@
ShowerFieldSepColon {- ^ A colon, @\':\'@ -}
| Either a comma or an element .
For example , the tuple section @(,a,,b)@ is represented like this :
@
[ ShowerCommaSep ,
ShowerCommaElement " a " ,
ShowerCommaSep ,
ShowerCommaSep ,
ShowerCommaElement " b " ]
@
For example, the tuple section @(,a,,b)@ is represented like this:
@
[ ShowerCommaSep,
ShowerCommaElement "a",
ShowerCommaSep,
ShowerCommaSep,
ShowerCommaElement "b" ]
@
-}
data ShowerComma a =
^ A comma , @\',\'@
ShowerCommaElement a {- ^ An element -}
| null | https://raw.githubusercontent.com/monadfix/shower/3e02d92e0500e41b4e9932294f4960463a7222d4/lib/Shower/Class.hs | haskell | |
This module defines the representation of data that the parser produces and the
pretty-printer consumes.
| A tagless final encoding for a result builder (@ShowS@, @Doc@, @Html@, etc).
Note that 'showerStringLit' and 'showerCharLit' take exact uninterpreted
| A string literal, @"hello, (world)"@.
| Variable names, numeric literals, and so on.
@\':\'@ for JSON.
^ A colon, @\':\'@
^ An element | module Shower.Class where
strings to avoid losing information ( e.g. @"\\n"@ vs. @"\\10"@ ) .
class Shower a where
| A record , @ { x = 24 , y = 42 } @ or @ { " a " : null , " b " : 13 } @.
showerRecord :: [ShowerComma (a, ShowerFieldSep, a)] -> a
| A list , @[1 , 2 , 3]@.
showerList :: [ShowerComma a] -> a
| A tuple , @(1 , 2 , 3)@.
showerTuple :: [ShowerComma a] -> a
showerStringLit :: String -> a
| A character literal , @'('@.
showerCharLit :: String -> a
showerAtom :: String -> a
| Whitespace - separated elements .
showerSpace :: [a] -> a
| A field separator used in records , either @\'=\'@ for records or
data ShowerFieldSep =
^ An equality sign , @\'=\'@
| Either a comma or an element .
For example , the tuple section @(,a,,b)@ is represented like this :
@
[ ShowerCommaSep ,
ShowerCommaElement " a " ,
ShowerCommaSep ,
ShowerCommaSep ,
ShowerCommaElement " b " ]
@
For example, the tuple section @(,a,,b)@ is represented like this:
@
[ ShowerCommaSep,
ShowerCommaElement "a",
ShowerCommaSep,
ShowerCommaSep,
ShowerCommaElement "b" ]
@
-}
data ShowerComma a =
^ A comma , @\',\'@
|
4e09090042057da9a19d996db27934ba8104265d2db8793bdf3e66b9636f4029 | ayakout/tcp_router | tcp_router.erl | -module(tcp_router).
-export([start/2, stop/1]).
-define(INITIAL_ROUTE, 10000).
-define(ROUTER_PORT, 8001).
-behaviour(application).
-include("tcp_router.hrl").
Mnesia install
-export([install/1]).
start(normal, []) ->
ets:new(tcp_app_routes, [public, named_table]),
ets : new(tcp_route_backends , [ public , ] ) ,
ets:insert(tcp_app_routes, {next_port, ?INITIAL_ROUTE - 1}),
ets:insert(tcp_app_routes, {free_ports, []}),
inets:start(httpd, instance(?MODULE_STRING, ?ROUTER_PORT, [{all}])),
tcp_proc_sup:start_link().
stop([]) ->
ets:delete(tcp_app_routes),
ets:delete(tcp_route_backends),
ok.
instance(Name, Port, Handlers) ->
[{server_name, Name},
{server_root, "."},
{document_root, "."},
{port, Port},
{modules, [mod_tcprouter]},
{mime_types, [{".xml", "text/xml"}]},
{handlers, Handlers}].
%% @doc Install mnesia tables
install(Nodes) ->
{atomic, ok} = mnesia:create_table(app_route, [{attributes, record_info(fields, app_route)},
{ram_copies, Nodes}, {type, bag}]),
{atomic, ok} = mnesia:create_table(route_backend, [{attributes, record_info(fields, route_backend)},
{ram_copies, Nodes}, {type, bag}]),
ok.
| null | https://raw.githubusercontent.com/ayakout/tcp_router/57c23ca593890f8354ca958c87b7d0894f05601a/src/tcp_router.erl | erlang | @doc Install mnesia tables | -module(tcp_router).
-export([start/2, stop/1]).
-define(INITIAL_ROUTE, 10000).
-define(ROUTER_PORT, 8001).
-behaviour(application).
-include("tcp_router.hrl").
Mnesia install
-export([install/1]).
start(normal, []) ->
ets:new(tcp_app_routes, [public, named_table]),
ets : new(tcp_route_backends , [ public , ] ) ,
ets:insert(tcp_app_routes, {next_port, ?INITIAL_ROUTE - 1}),
ets:insert(tcp_app_routes, {free_ports, []}),
inets:start(httpd, instance(?MODULE_STRING, ?ROUTER_PORT, [{all}])),
tcp_proc_sup:start_link().
stop([]) ->
ets:delete(tcp_app_routes),
ets:delete(tcp_route_backends),
ok.
instance(Name, Port, Handlers) ->
[{server_name, Name},
{server_root, "."},
{document_root, "."},
{port, Port},
{modules, [mod_tcprouter]},
{mime_types, [{".xml", "text/xml"}]},
{handlers, Handlers}].
install(Nodes) ->
{atomic, ok} = mnesia:create_table(app_route, [{attributes, record_info(fields, app_route)},
{ram_copies, Nodes}, {type, bag}]),
{atomic, ok} = mnesia:create_table(route_backend, [{attributes, record_info(fields, route_backend)},
{ram_copies, Nodes}, {type, bag}]),
ok.
|
1eb4e5ef757b1e4be3083646567b75ef65fd9a6948f55bdf8a6ac548012d5136 | wireapp/wire-server | BulkPush.hs | -- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Wire.API.Internal.BulkPush where
import Control.Lens
import Data.Aeson
import Data.Id
import Data.Schema (ValueSchema)
import qualified Data.Schema as S
import qualified Data.Swagger as Swagger
import Imports
import Wire.API.Internal.Notification
data PushTarget = PushTarget
{ ptUserId :: !UserId,
ptConnId :: !ConnId
}
deriving
( Eq,
Ord,
Show,
Generic
)
deriving (FromJSON, ToJSON, Swagger.ToSchema) via S.Schema PushTarget
instance S.ToSchema PushTarget where
schema =
S.object "PushTarget" $
PushTarget
<$> ptUserId S..= S.field "user_id" S.schema
<*> ptConnId S..= S.field "conn_id" S.schema
newtype BulkPushRequest = BulkPushRequest
{ fromBulkPushRequest :: [(Notification, [PushTarget])]
}
deriving
( Eq,
Show,
Generic
)
deriving (ToJSON, FromJSON, Swagger.ToSchema) via S.Schema BulkPushRequest
instance S.ToSchema BulkPushRequest where
schema =
S.object "BulkPushRequest" $
BulkPushRequest
<$> fromBulkPushRequest S..= S.field "bulkpush_req" (S.array bulkpushReqItemSchema)
where
bulkpushReqItemSchema :: ValueSchema S.NamedSwaggerDoc (Notification, [PushTarget])
bulkpushReqItemSchema =
S.object "(Notification, [PushTarget])" $
(,)
<$> fst S..= S.field "notification" S.schema
<*> snd S..= S.field "targets" (S.array S.schema)
data PushStatus = PushStatusOk | PushStatusGone
deriving (Eq, Show, Bounded, Enum, Generic)
deriving (FromJSON, ToJSON, Swagger.ToSchema) via S.Schema PushStatus
instance S.ToSchema PushStatus where
schema =
S.enum @Text "PushStatus" $
mconcat
[ S.element "push_status_ok" PushStatusOk,
S.element "push_status_gone" PushStatusGone
]
newtype BulkPushResponse = BulkPushResponse
{ fromBulkPushResponse :: [(NotificationId, PushTarget, PushStatus)]
}
deriving
( Eq,
Show,
Generic
)
deriving (FromJSON, ToJSON, Swagger.ToSchema) via S.Schema BulkPushResponse
instance S.ToSchema BulkPushResponse where
schema =
S.object "BulkPushResponse" $
BulkPushResponse
<$> fromBulkPushResponse S..= S.field "bulkpush_resp" (S.array bulkPushResponseSchema)
where
bulkPushResponseSchema :: ValueSchema S.NamedSwaggerDoc (NotificationId, PushTarget, PushStatus)
bulkPushResponseSchema =
S.object "(NotificationId, PushTarget, PushStatus)" $
(,,)
<$> view _1 S..= S.field "notif_id" S.schema
<*> view _2 S..= S.field "target" S.schema
<*> view _3 S..= S.field "status" S.schema
| null | https://raw.githubusercontent.com/wireapp/wire-server/607d93e0cd6a7f312ab5bad071ad383068e896c5/libs/wire-api/src/Wire/API/Internal/BulkPush.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>. | Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Wire.API.Internal.BulkPush where
import Control.Lens
import Data.Aeson
import Data.Id
import Data.Schema (ValueSchema)
import qualified Data.Schema as S
import qualified Data.Swagger as Swagger
import Imports
import Wire.API.Internal.Notification
data PushTarget = PushTarget
{ ptUserId :: !UserId,
ptConnId :: !ConnId
}
deriving
( Eq,
Ord,
Show,
Generic
)
deriving (FromJSON, ToJSON, Swagger.ToSchema) via S.Schema PushTarget
instance S.ToSchema PushTarget where
schema =
S.object "PushTarget" $
PushTarget
<$> ptUserId S..= S.field "user_id" S.schema
<*> ptConnId S..= S.field "conn_id" S.schema
newtype BulkPushRequest = BulkPushRequest
{ fromBulkPushRequest :: [(Notification, [PushTarget])]
}
deriving
( Eq,
Show,
Generic
)
deriving (ToJSON, FromJSON, Swagger.ToSchema) via S.Schema BulkPushRequest
instance S.ToSchema BulkPushRequest where
schema =
S.object "BulkPushRequest" $
BulkPushRequest
<$> fromBulkPushRequest S..= S.field "bulkpush_req" (S.array bulkpushReqItemSchema)
where
bulkpushReqItemSchema :: ValueSchema S.NamedSwaggerDoc (Notification, [PushTarget])
bulkpushReqItemSchema =
S.object "(Notification, [PushTarget])" $
(,)
<$> fst S..= S.field "notification" S.schema
<*> snd S..= S.field "targets" (S.array S.schema)
data PushStatus = PushStatusOk | PushStatusGone
deriving (Eq, Show, Bounded, Enum, Generic)
deriving (FromJSON, ToJSON, Swagger.ToSchema) via S.Schema PushStatus
instance S.ToSchema PushStatus where
schema =
S.enum @Text "PushStatus" $
mconcat
[ S.element "push_status_ok" PushStatusOk,
S.element "push_status_gone" PushStatusGone
]
newtype BulkPushResponse = BulkPushResponse
{ fromBulkPushResponse :: [(NotificationId, PushTarget, PushStatus)]
}
deriving
( Eq,
Show,
Generic
)
deriving (FromJSON, ToJSON, Swagger.ToSchema) via S.Schema BulkPushResponse
instance S.ToSchema BulkPushResponse where
schema =
S.object "BulkPushResponse" $
BulkPushResponse
<$> fromBulkPushResponse S..= S.field "bulkpush_resp" (S.array bulkPushResponseSchema)
where
bulkPushResponseSchema :: ValueSchema S.NamedSwaggerDoc (NotificationId, PushTarget, PushStatus)
bulkPushResponseSchema =
S.object "(NotificationId, PushTarget, PushStatus)" $
(,,)
<$> view _1 S..= S.field "notif_id" S.schema
<*> view _2 S..= S.field "target" S.schema
<*> view _3 S..= S.field "status" S.schema
|
76ff4b270b0745a6c50c4584b01c99d631c0736aedb15a9acea762680846da04 | Lisp-Stat/special-functions | main.lisp | -*- Mode : LISP ; Base : 10 ; Syntax : ANSI - Common - Lisp ; Package : SPECIAL - FUNCTIONS - TESTS -*-
Copyright ( c ) 2020 by Symbolics Pte . Ltd. All rights reserved .
(in-package #:special-functions-tests)
(def-suite all-tests
:description "The master suite of all special functions tests.")
(in-suite all-tests)
;;; Fiveam get-float does not allow for ranges.
(defun gen-double (generator min max)
"Return a generator producing doubles between min and max, inclusive"
(lambda ()
(random-range-inclusive generator min max)))
(defun gen-positive-double (generator min max)
"Return a generator producing doubles between min and max, inclusive. If min or max is negative, return small value"
(lambda ()
(let ((min (if (plusp min) min 2.848094538889218D-306)))
(random-range-inclusive generator min max))))
(defparameter *report-epsilon* t "Print key statistics in terms of machine epsilon")
(defun print-test-summary (result &key (report-epsilon *report-epsilon*))
"Print summary of results.
Include some values in epsilon if report-epsilon is true. This is useful when comparing to other implementations"
(write result)
(when report-epsilon
(format t "~% Key stats in terms of epsilon:~% Max = ~,2Eε (Mean = ~,2Eε)~%"
(/ (max-error result) double-float-epsilon)
(/ (mean-error result) double-float-epsilon))))
(defun eps (x)
"Return a multiple of epsilon"
(* x double-float-epsilon))
(defun test-specfun ()
(run! 'all-tests))
| null | https://raw.githubusercontent.com/Lisp-Stat/special-functions/ff284b69e83708ed5e1a0d20f421122f9bf64909/tests/main.lisp | lisp | Base : 10 ; Syntax : ANSI - Common - Lisp ; Package : SPECIAL - FUNCTIONS - TESTS -*-
Fiveam get-float does not allow for ranges. | Copyright ( c ) 2020 by Symbolics Pte . Ltd. All rights reserved .
(in-package #:special-functions-tests)
(def-suite all-tests
:description "The master suite of all special functions tests.")
(in-suite all-tests)
(defun gen-double (generator min max)
"Return a generator producing doubles between min and max, inclusive"
(lambda ()
(random-range-inclusive generator min max)))
(defun gen-positive-double (generator min max)
"Return a generator producing doubles between min and max, inclusive. If min or max is negative, return small value"
(lambda ()
(let ((min (if (plusp min) min 2.848094538889218D-306)))
(random-range-inclusive generator min max))))
(defparameter *report-epsilon* t "Print key statistics in terms of machine epsilon")
(defun print-test-summary (result &key (report-epsilon *report-epsilon*))
"Print summary of results.
Include some values in epsilon if report-epsilon is true. This is useful when comparing to other implementations"
(write result)
(when report-epsilon
(format t "~% Key stats in terms of epsilon:~% Max = ~,2Eε (Mean = ~,2Eε)~%"
(/ (max-error result) double-float-epsilon)
(/ (mean-error result) double-float-epsilon))))
(defun eps (x)
"Return a multiple of epsilon"
(* x double-float-epsilon))
(defun test-specfun ()
(run! 'all-tests))
|
ff49b07759dc5d65187533fccad50a2da135779a0f6cda555e7e3a51700eaba5 | amuletml/amulet | Diagnostic.hs | # LANGUAGE OverloadedStrings , DuplicateRecordFields , FlexibleContexts #
| Provides helper methods for working with diagnostics , and converting
Amulet 's error messages into diagnostics .
Amulet's error messages into diagnostics. -}
module AmuletLsp.Diagnostic (diagnosticOf) where
import Control.Lens hiding (List)
import Data.Spanned
import Data.Span
import Language.LSP.Types.Lens
import Language.LSP.Types
import Control.Monad.Infer as T (TypeError(..))
import Syntax.Resolve.Error as R
import Syntax.Verify.Error
import Parser.Error
import AmuletLsp.Features
import Text.Pretty.Semantic hiding (line)
import Text.Pretty.Note
-- | Some type which can be converted to a diagnostic.
class DiagnosticLike a where
diagnosticOf :: a -> Diagnostic
instance DiagnosticLike ParseError where
diagnosticOf err = mkDiagnostic "amulet.parser" (spanOf err) (pretty err) err
instance DiagnosticLike R.ResolveError where
diagnosticOf resErr = go resErr where
mk msg = mkDiagnostic "amulet.resolve" (spanOf resErr) msg resErr
go :: R.ResolveError -> Diagnostic
go (R.ArisingFrom e _) = go e
go e@(NonLinearPattern _ ps) =
let d = mk (pretty e)
info p = DiagnosticRelatedInformation (locationOf (spanOf p)) "Variable declared here"
in d { _relatedInformation = Just (List (map info ps)) }
go e = mk (pretty e)
instance DiagnosticLike TypeError where
diagnosticOf err = mkDiagnostic "amulet.tc" (spanOf err) (pretty err) err
instance DiagnosticLike VerifyError where
diagnosticOf err = go err where
mk msg = mkDiagnostic "amulet.verify" (spanOf err) msg err
go e@DefinedUnused{} =
let d = mk (pretty e)
in d & tags ?~ List [ DtUnnecessary ]
go e = mk (pretty e)
-- | Construct a diagnostic of some error.
mkDiagnostic :: Note a b
=> DiagnosticSource -> Span -> Doc -> a
-> Diagnostic
mkDiagnostic source pos msg note =
Diagnostic
{ _range = rangeOf pos
, _severity = Just (severityOf (diagnosticKind note))
, _code = InL . fromIntegral <$> noteId note
, _message = renderBasic msg
, _relatedInformation = Nothing
, _source = Just source
, _tags = Nothing
}
severityOf :: NoteKind -> DiagnosticSeverity
severityOf NoteMessage = DsInfo
severityOf WarningMessage = DsWarning
severityOf ErrorMessage = DsError
| null | https://raw.githubusercontent.com/amuletml/amulet/fcba0b7e198b8d354e95722bbe118bccc8483f4e/bin/AmuletLsp/Diagnostic.hs | haskell | | Some type which can be converted to a diagnostic.
| Construct a diagnostic of some error. | # LANGUAGE OverloadedStrings , DuplicateRecordFields , FlexibleContexts #
| Provides helper methods for working with diagnostics , and converting
Amulet 's error messages into diagnostics .
Amulet's error messages into diagnostics. -}
module AmuletLsp.Diagnostic (diagnosticOf) where
import Control.Lens hiding (List)
import Data.Spanned
import Data.Span
import Language.LSP.Types.Lens
import Language.LSP.Types
import Control.Monad.Infer as T (TypeError(..))
import Syntax.Resolve.Error as R
import Syntax.Verify.Error
import Parser.Error
import AmuletLsp.Features
import Text.Pretty.Semantic hiding (line)
import Text.Pretty.Note
class DiagnosticLike a where
diagnosticOf :: a -> Diagnostic
instance DiagnosticLike ParseError where
diagnosticOf err = mkDiagnostic "amulet.parser" (spanOf err) (pretty err) err
instance DiagnosticLike R.ResolveError where
diagnosticOf resErr = go resErr where
mk msg = mkDiagnostic "amulet.resolve" (spanOf resErr) msg resErr
go :: R.ResolveError -> Diagnostic
go (R.ArisingFrom e _) = go e
go e@(NonLinearPattern _ ps) =
let d = mk (pretty e)
info p = DiagnosticRelatedInformation (locationOf (spanOf p)) "Variable declared here"
in d { _relatedInformation = Just (List (map info ps)) }
go e = mk (pretty e)
instance DiagnosticLike TypeError where
diagnosticOf err = mkDiagnostic "amulet.tc" (spanOf err) (pretty err) err
instance DiagnosticLike VerifyError where
diagnosticOf err = go err where
mk msg = mkDiagnostic "amulet.verify" (spanOf err) msg err
go e@DefinedUnused{} =
let d = mk (pretty e)
in d & tags ?~ List [ DtUnnecessary ]
go e = mk (pretty e)
mkDiagnostic :: Note a b
=> DiagnosticSource -> Span -> Doc -> a
-> Diagnostic
mkDiagnostic source pos msg note =
Diagnostic
{ _range = rangeOf pos
, _severity = Just (severityOf (diagnosticKind note))
, _code = InL . fromIntegral <$> noteId note
, _message = renderBasic msg
, _relatedInformation = Nothing
, _source = Just source
, _tags = Nothing
}
severityOf :: NoteKind -> DiagnosticSeverity
severityOf NoteMessage = DsInfo
severityOf WarningMessage = DsWarning
severityOf ErrorMessage = DsError
|
4ded295bcca4c21b6e6c75f34de53e14914f1697667e27a2c71bf85dfe40d60d | janestreet/merlin-jst | extensions.mli | open Parsetree
type extension_expr =
| Eexp_list_comprehension of expression * comprehension list
| Eexp_arr_comprehension of expression * comprehension list
and comprehension =
{
clauses: comprehension_clause list;
guard : expression option
}
and comprehension_clause =
[ ... for i = E2 to E3 ] ( flag = Upto )
[ ... for i = E2 downto E3 ] ( flag = downto )
[ ... for i = E2 downto E3 ] (flag = downto)*)
| From_to of pattern * expression * expression * Asttypes.direction_flag
(*[ ... for i in E3 ] *)
| In of pattern * expression
val payload_of_extension_expr: loc:Warnings.loc -> extension_expr -> extension
val extension_expr_of_payload: loc:Warnings.loc -> extension -> extension_expr
| null | https://raw.githubusercontent.com/janestreet/merlin-jst/980b574405617fa0dfb0b79a84a66536b46cd71b/upstream/ocaml_flambda/parsing/extensions.mli | ocaml | [ ... for i in E3 ] | open Parsetree
type extension_expr =
| Eexp_list_comprehension of expression * comprehension list
| Eexp_arr_comprehension of expression * comprehension list
and comprehension =
{
clauses: comprehension_clause list;
guard : expression option
}
and comprehension_clause =
[ ... for i = E2 to E3 ] ( flag = Upto )
[ ... for i = E2 downto E3 ] ( flag = downto )
[ ... for i = E2 downto E3 ] (flag = downto)*)
| From_to of pattern * expression * expression * Asttypes.direction_flag
| In of pattern * expression
val payload_of_extension_expr: loc:Warnings.loc -> extension_expr -> extension
val extension_expr_of_payload: loc:Warnings.loc -> extension -> extension_expr
|
b2039f985d640dda78aba1e85f83f34e8398b4eda0d3e0f6fd3a4626a6e151b6 | ryanpbrewster/haskell | length.hs | len([])=0
len(f:r)=1+len(r)
leng(l)=foldr (\x y->1+y) 0 l
main=print(length([1..100000]))
| null | https://raw.githubusercontent.com/ryanpbrewster/haskell/6edd0afe234008a48b4871032dedfd143ca6e412/hello-world/length.hs | haskell | len([])=0
len(f:r)=1+len(r)
leng(l)=foldr (\x y->1+y) 0 l
main=print(length([1..100000]))
|
|
189af21d14beed89b7c6c4052576d29ea95e173beef0782ffab08ec2ff2eed51 | OCamlPro/ez_api | ezServer.dummy.ml | (**************************************************************************)
(* *)
(* Copyright 2018-2023 OCamlPro *)
(* *)
(* 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. *)
(* *)
(**************************************************************************)
let server ?catch:_ _ =
Format.eprintf
"Cohttp or Httpaf server implementation not availble\n\
Try: `opam install cohttp-lwt-unix`\n\
or: `opam install httpaf-lwt-unix`@.";
Lwt.return_unit
let set_debug () = ()
| null | https://raw.githubusercontent.com/OCamlPro/ez_api/5253f7dd8936e923290aa969ee43ebd3dc6fce2d/src/server/default/ezServer.dummy.ml | ocaml | ************************************************************************
Copyright 2018-2023 OCamlPro
All rights reserved. This file is distributed under the terms of the
exception on linking described in the file LICENSE.
************************************************************************ | GNU Lesser General Public License version 2.1 , with the special
let server ?catch:_ _ =
Format.eprintf
"Cohttp or Httpaf server implementation not availble\n\
Try: `opam install cohttp-lwt-unix`\n\
or: `opam install httpaf-lwt-unix`@.";
Lwt.return_unit
let set_debug () = ()
|
e47998ec4a46308b014dded69b3e2d1bdaaff8e940b99db38a2c258822078138 | froggey/Mezzano | cons.lisp | ;;;; Cons-related primitives
(in-package :mezzano.compiler.backend.x86-64)
(define-builtin mezzano.runtime::%car ((cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list result `(:car ,cons))
:inputs (list cons)
:outputs (list result))))
(define-builtin mezzano.runtime::%cdr ((cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list result `(:cdr ,cons))
:inputs (list cons)
:outputs (list result))))
(define-builtin (setf mezzano.runtime::%car) ((value cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list `(:car ,cons) value)
:inputs (list cons value)
:outputs '()))
(emit (make-instance 'ir:move-instruction
:destination result
:source value)))
(define-builtin (setf mezzano.runtime::%cdr) ((value cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list `(:cdr ,cons) value)
:inputs (list cons value)
:outputs '()))
(emit (make-instance 'ir:move-instruction
:destination result
:source value)))
(define-builtin sys.int::%cas-cons-car ((cons old new) (:z result))
(emit (make-instance 'x86-cmpxchg-instruction
:object cons
:displacement (- sys.int::+tag-cons+)
:index 0
:old old
:new new
:result result
:prefix '(lap:lock))))
(define-builtin sys.int::%cas-cons-cdr ((cons old new) (:z result))
(emit (make-instance 'x86-cmpxchg-instruction
:object cons
:displacement (+ (- sys.int::+tag-cons+) 8)
:index 0
:old old
:new new
:result result
:prefix '(lap:lock))))
(define-builtin sys.int::%xchg-car ((cons new) result)
(emit (make-instance 'x86-atomic-instruction
:opcode 'lap:xchg64
:object cons
:displacement (- sys.int::+tag-cons+)
:index 0
:rhs new
:result result)))
(define-builtin sys.int::%xchg-cdr ((cons new) result)
(emit (make-instance 'x86-atomic-instruction
:opcode 'lap:xchg64
:object cons
:displacement (+ (- sys.int::+tag-cons+) 8)
:index 0
:rhs new
:result result)))
(define-builtin sys.int::%dcas-cons ((cons old-1 old-2 new-1 new-2) (:z result-1 result-2))
(emit (make-instance 'x86-cmpxchg16b-instruction
:object cons
:displacement (- sys.int::+tag-cons+)
:index 0
:old-1 old-1
:old-2 old-2
:new-1 new-1
:new-2 new-2
:result-1 result-1
:result-2 result-2
:prefix '(lap:lock))))
| null | https://raw.githubusercontent.com/froggey/Mezzano/f0eeb2a3f032098b394e31e3dfd32800f8a51122/compiler/backend/x86-64/cons.lisp | lisp | Cons-related primitives |
(in-package :mezzano.compiler.backend.x86-64)
(define-builtin mezzano.runtime::%car ((cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list result `(:car ,cons))
:inputs (list cons)
:outputs (list result))))
(define-builtin mezzano.runtime::%cdr ((cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list result `(:cdr ,cons))
:inputs (list cons)
:outputs (list result))))
(define-builtin (setf mezzano.runtime::%car) ((value cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list `(:car ,cons) value)
:inputs (list cons value)
:outputs '()))
(emit (make-instance 'ir:move-instruction
:destination result
:source value)))
(define-builtin (setf mezzano.runtime::%cdr) ((value cons) result)
(emit (make-instance 'x86-instruction
:opcode 'lap:mov64
:operands (list `(:cdr ,cons) value)
:inputs (list cons value)
:outputs '()))
(emit (make-instance 'ir:move-instruction
:destination result
:source value)))
(define-builtin sys.int::%cas-cons-car ((cons old new) (:z result))
(emit (make-instance 'x86-cmpxchg-instruction
:object cons
:displacement (- sys.int::+tag-cons+)
:index 0
:old old
:new new
:result result
:prefix '(lap:lock))))
(define-builtin sys.int::%cas-cons-cdr ((cons old new) (:z result))
(emit (make-instance 'x86-cmpxchg-instruction
:object cons
:displacement (+ (- sys.int::+tag-cons+) 8)
:index 0
:old old
:new new
:result result
:prefix '(lap:lock))))
(define-builtin sys.int::%xchg-car ((cons new) result)
(emit (make-instance 'x86-atomic-instruction
:opcode 'lap:xchg64
:object cons
:displacement (- sys.int::+tag-cons+)
:index 0
:rhs new
:result result)))
(define-builtin sys.int::%xchg-cdr ((cons new) result)
(emit (make-instance 'x86-atomic-instruction
:opcode 'lap:xchg64
:object cons
:displacement (+ (- sys.int::+tag-cons+) 8)
:index 0
:rhs new
:result result)))
(define-builtin sys.int::%dcas-cons ((cons old-1 old-2 new-1 new-2) (:z result-1 result-2))
(emit (make-instance 'x86-cmpxchg16b-instruction
:object cons
:displacement (- sys.int::+tag-cons+)
:index 0
:old-1 old-1
:old-2 old-2
:new-1 new-1
:new-2 new-2
:result-1 result-1
:result-2 result-2
:prefix '(lap:lock))))
|
821f3f236be5cba3ce742b5ca47ade2c73c0c5adace92fe79c948ac7f2137376 | c4-project/c4f | stub.ml | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
let try_parse_program_id (id : Common.C_id.t) : int Or_error.t =
let strid = Common.C_id.to_string id in
Or_error.(
tag ~tag:"Thread function does not have a well-formed name"
(try_with (fun () -> Caml.Scanf.sscanf strid "P%d" Fn.id)))
let to_param_opt (lit_id : Common.Litmus_id.t) (rc : Var_map.Record.t) :
(int * (Common.Litmus_id.t * Fir.Type.t)) option =
match rc.mapped_to with
| Param k -> Some (k, (lit_id, rc.c_type))
| Global -> None
let to_sorted_params_opt
(alist : (Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t =
alist
|> List.filter_map ~f:(fun (l, r) -> to_param_opt l r)
|> List.sort ~compare:(Comparable.lift Int.compare ~f:fst)
|> List.map ~f:snd
let sorted_params (vars : Var_map.t) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t =
vars |> Common.Scoped_map.to_litmus_id_map |> Map.to_alist
|> to_sorted_params_opt
* Adjusts the type of a parameter in a ( ID , type ) associative list by
turning it into a pointer if it is global , and leaving it unchanged
otherwise .
This serves to make the type fit its position in the stub : pointers to
the Litmus harness 's variables if global , local variables otherwise .
turning it into a pointer if it is global, and leaving it unchanged
otherwise.
This serves to make the type fit its position in the stub: pointers to
the Litmus harness's variables if global, local variables otherwise. *)
let type_adjusted_param ((id, ty) : Common.Litmus_id.t * Fir.Type.t) :
(Common.Litmus_id.t * Fir.Type.t) Or_error.t =
Or_error.Let_syntax.(
let%map ty' =
if Common.Litmus_id.is_global id then Fir.Type.ref ty else Ok ty
in
(id, ty'))
(** Produces a list of sorted, type-adjusted parameters from [vars]. These
are the parameters of the inner call, and need to be filtered to produce
the other parameter/argument lists. *)
let sorted_type_adjusted_params (vars : Var_map.t) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t Or_error.t =
vars |> sorted_params |> Tx.Or_error.combine_map ~f:type_adjusted_param
let thread_params :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t
-> (Common.C_id.t, Fir.Type.t) List.Assoc.t =
List.filter_map ~f:(fun (id, ty) ->
Option.map ~f:(fun id' -> (id', ty)) (Common.Litmus_id.as_global id) )
let local_decls (tid : int) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t
-> (Common.C_id.t, Fir.Initialiser.t) List.Assoc.t =
List.filter_map ~f:(fun (id, ty) ->
if [%equal: int option] (Common.Litmus_id.tid id) (Some tid) then
Some
( Common.Litmus_id.variable_name id
, Fir.
{ Initialiser.ty
TODO(@MattWindsor91 ): fix this properly .
value= Fir.Constant.int 0 } )
else None )
let inner_call_argument (lid : Common.Litmus_id.t) (ty : Fir.Type.t) :
Fir.Expression.t =
let id = Common.Litmus_id.variable_name lid in
let tid = Common.C_named.make ~name:id ty in
Fir.Expression.address (Fir.Address.on_address_of_typed_id tid)
let inner_call_arguments (tid : int) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t -> Fir.Expression.t list =
List.filter_map ~f:(fun (lid, ty) ->
if Common.Litmus_id.is_in_local_scope ~from:tid lid then
Some (inner_call_argument lid ty)
else None )
let inner_call_stm (tid : int) (function_id : Common.C_id.t)
(all_params : (Common.Litmus_id.t, Fir.Type.t) List.Assoc.t) :
unit Fir.Statement.t =
let arguments = inner_call_arguments tid all_params in
let call = Fir.Call.make ~function_id ~arguments () in
Accessor.construct
Fir.(Statement.prim' @> Prim_statement.procedure_call)
call
let make_function_stub (vars : Var_map.t) ~(old_id : Common.C_id.t)
~(new_id : Common.C_id.t) :
unit Fir.Function.t Common.C_named.t Or_error.t =
TODO(@MattWindsor91 ): eventually , we 'll have variables that do n't
propagate outside of the wrapper into Litmus ; in that case , the function
stub should pass in their initial values directly .
propagate outside of the wrapper into Litmus; in that case, the function
stub should pass in their initial values directly. *)
Or_error.Let_syntax.(
let%bind all_params = sorted_type_adjusted_params vars in
let parameters = thread_params all_params in
let%map tid = try_parse_program_id old_id in
let body_decls = local_decls tid all_params in
let body_stms = [inner_call_stm tid new_id all_params] in
let thread = Fir.Function.make ~parameters ~body_decls ~body_stms () in
Common.C_named.make thread ~name:old_id)
let make ({litmus_header; var_map; function_map} : Aux.t) :
Fir.Litmus.Test.t Or_error.t =
Or_error.Let_syntax.(
let%bind threads =
function_map
|> Map.to_alist ~key_order:`Increasing
|> List.filter_map ~f:(fun (old_id, record) ->
if Function_map.Record.is_thread_body record then
Some (make_function_stub var_map ~old_id ~new_id:record.c_id)
else None )
|> Or_error.combine_errors
in
Fir.Litmus.Test.make ~header:litmus_header ~threads)
module Filter = struct
let run (input : Plumbing.Input.t) (output : Plumbing.Output.t) :
unit Or_error.t =
Or_error.(
input |> Aux.load >>= make
>>= Utils.My_format.odump output (Fmt.vbox Litmus_c.Reify.pp_litmus))
end
| null | https://raw.githubusercontent.com/c4-project/c4f/8939477732861789abc807c8c1532a302b2848a5/lib/delitmus/src/stub.ml | ocaml | * Produces a list of sorted, type-adjusted parameters from [vars]. These
are the parameters of the inner call, and need to be filtered to produce
the other parameter/argument lists. | This file is part of c4f .
Copyright ( c ) 2018 - 2022 C4 Project
c4 t itself is licensed under the MIT License . See the LICENSE file in the
project root for more information .
Parts of c4 t are based on code from the Herdtools7 project
( ) : see the LICENSE.herd file in the
project root for more information .
Copyright (c) 2018-2022 C4 Project
c4t itself is licensed under the MIT License. See the LICENSE file in the
project root for more information.
Parts of c4t are based on code from the Herdtools7 project
() : see the LICENSE.herd file in the
project root for more information. *)
open Base
open Import
let try_parse_program_id (id : Common.C_id.t) : int Or_error.t =
let strid = Common.C_id.to_string id in
Or_error.(
tag ~tag:"Thread function does not have a well-formed name"
(try_with (fun () -> Caml.Scanf.sscanf strid "P%d" Fn.id)))
let to_param_opt (lit_id : Common.Litmus_id.t) (rc : Var_map.Record.t) :
(int * (Common.Litmus_id.t * Fir.Type.t)) option =
match rc.mapped_to with
| Param k -> Some (k, (lit_id, rc.c_type))
| Global -> None
let to_sorted_params_opt
(alist : (Common.Litmus_id.t, Var_map.Record.t) List.Assoc.t) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t =
alist
|> List.filter_map ~f:(fun (l, r) -> to_param_opt l r)
|> List.sort ~compare:(Comparable.lift Int.compare ~f:fst)
|> List.map ~f:snd
let sorted_params (vars : Var_map.t) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t =
vars |> Common.Scoped_map.to_litmus_id_map |> Map.to_alist
|> to_sorted_params_opt
* Adjusts the type of a parameter in a ( ID , type ) associative list by
turning it into a pointer if it is global , and leaving it unchanged
otherwise .
This serves to make the type fit its position in the stub : pointers to
the Litmus harness 's variables if global , local variables otherwise .
turning it into a pointer if it is global, and leaving it unchanged
otherwise.
This serves to make the type fit its position in the stub: pointers to
the Litmus harness's variables if global, local variables otherwise. *)
let type_adjusted_param ((id, ty) : Common.Litmus_id.t * Fir.Type.t) :
(Common.Litmus_id.t * Fir.Type.t) Or_error.t =
Or_error.Let_syntax.(
let%map ty' =
if Common.Litmus_id.is_global id then Fir.Type.ref ty else Ok ty
in
(id, ty'))
let sorted_type_adjusted_params (vars : Var_map.t) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t Or_error.t =
vars |> sorted_params |> Tx.Or_error.combine_map ~f:type_adjusted_param
let thread_params :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t
-> (Common.C_id.t, Fir.Type.t) List.Assoc.t =
List.filter_map ~f:(fun (id, ty) ->
Option.map ~f:(fun id' -> (id', ty)) (Common.Litmus_id.as_global id) )
let local_decls (tid : int) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t
-> (Common.C_id.t, Fir.Initialiser.t) List.Assoc.t =
List.filter_map ~f:(fun (id, ty) ->
if [%equal: int option] (Common.Litmus_id.tid id) (Some tid) then
Some
( Common.Litmus_id.variable_name id
, Fir.
{ Initialiser.ty
TODO(@MattWindsor91 ): fix this properly .
value= Fir.Constant.int 0 } )
else None )
let inner_call_argument (lid : Common.Litmus_id.t) (ty : Fir.Type.t) :
Fir.Expression.t =
let id = Common.Litmus_id.variable_name lid in
let tid = Common.C_named.make ~name:id ty in
Fir.Expression.address (Fir.Address.on_address_of_typed_id tid)
let inner_call_arguments (tid : int) :
(Common.Litmus_id.t, Fir.Type.t) List.Assoc.t -> Fir.Expression.t list =
List.filter_map ~f:(fun (lid, ty) ->
if Common.Litmus_id.is_in_local_scope ~from:tid lid then
Some (inner_call_argument lid ty)
else None )
let inner_call_stm (tid : int) (function_id : Common.C_id.t)
(all_params : (Common.Litmus_id.t, Fir.Type.t) List.Assoc.t) :
unit Fir.Statement.t =
let arguments = inner_call_arguments tid all_params in
let call = Fir.Call.make ~function_id ~arguments () in
Accessor.construct
Fir.(Statement.prim' @> Prim_statement.procedure_call)
call
let make_function_stub (vars : Var_map.t) ~(old_id : Common.C_id.t)
~(new_id : Common.C_id.t) :
unit Fir.Function.t Common.C_named.t Or_error.t =
TODO(@MattWindsor91 ): eventually , we 'll have variables that do n't
propagate outside of the wrapper into Litmus ; in that case , the function
stub should pass in their initial values directly .
propagate outside of the wrapper into Litmus; in that case, the function
stub should pass in their initial values directly. *)
Or_error.Let_syntax.(
let%bind all_params = sorted_type_adjusted_params vars in
let parameters = thread_params all_params in
let%map tid = try_parse_program_id old_id in
let body_decls = local_decls tid all_params in
let body_stms = [inner_call_stm tid new_id all_params] in
let thread = Fir.Function.make ~parameters ~body_decls ~body_stms () in
Common.C_named.make thread ~name:old_id)
let make ({litmus_header; var_map; function_map} : Aux.t) :
Fir.Litmus.Test.t Or_error.t =
Or_error.Let_syntax.(
let%bind threads =
function_map
|> Map.to_alist ~key_order:`Increasing
|> List.filter_map ~f:(fun (old_id, record) ->
if Function_map.Record.is_thread_body record then
Some (make_function_stub var_map ~old_id ~new_id:record.c_id)
else None )
|> Or_error.combine_errors
in
Fir.Litmus.Test.make ~header:litmus_header ~threads)
module Filter = struct
let run (input : Plumbing.Input.t) (output : Plumbing.Output.t) :
unit Or_error.t =
Or_error.(
input |> Aux.load >>= make
>>= Utils.My_format.odump output (Fmt.vbox Litmus_c.Reify.pp_litmus))
end
|
b5fa3cc0cd01bd35c3eb3d5c7fb3ca970fde4d6b9e87b4b175709484d4cb415e | JAremko/spacetools | head_test.clj | (ns spacetools.spacedoc.org.head-test
"Testing helpers for working with headers of documents."
(:require [clojure.spec.alpha :as s]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[spacetools.spacedoc.config :as cfg]
[clojure.test.check.properties :as prop]
[orchestra.spec.test :as st]
[spacetools.spacedoc.core :as sc]
[spacetools.spacedoc.node :as n]
[spacetools.spacedoc.org.head :refer :all]
[spacetools.spacedoc.util :as sdu]
[spacetools.test-util.interface :as tu]
[spacetools.spacedoc.org.orgify :as o]
[clojure.set :as set]
[clojure.core.reducers :as r]))
(st/instrument)
;;;; Test helpers
(defn test-toc-tmpl
"Wraps TOC children into TOC headline."
[& children]
(n/headline (cfg/toc-hl-val) (apply n/section children)))
(defn root-tags-n?
"Returns true if X is a root tags node."
[x]
(s/valid? :spacetools.spacedoc.node.meta/tags x))
(defn extract-head
"Returns [TITLE TAGS REST-OF-HEAD] of the ROOT node"
[root]
(let [{[{[title & rst] :children}] :children} root
tag-or-fr (first rst)]
(into [title] (if (root-tags-n? tag-or-fr)
[tag-or-fr (vec (rest rst))]
[nil (vec rst)]))))
(def root-meta-tags
"Tags of root meta nodes.
See `:spacetools.spacedoc.org.head/root-meta`."
#{:tags :title})
;;;; Tests
(deftest str-tags->set-fn
(are [string-tags set-tags] (= set-tags (str-tags->set string-tags))
"" #{}
"foo" #{"foo"}
"foo|bar" #{"foo" "bar"}
"Foo Bar" #{"Foo Bar"}
"Foo Bar|baz qux" #{"Foo Bar" "baz qux"}
"foo|bar|baz|qux" #{"foo" "bar" "baz" "qux"}))
(deftest set-tags->str-fn
(are [set-tags string-tags] (= string-tags (set-tags->str set-tags))
#{} ""
#{"a" "b" "c"} "a|b|c"
#{"b" "a" "c"} "a|b|c"
#{"foo"} "foo"
#{"foo" "bar"} "bar|foo"
#{"Foo Bar"} "Foo Bar"
#{"Foo Bar" "baz qux"} "Foo Bar|baz qux"
#{"foo" "bar" "baz" "qux"} "bar|baz|foo|qux"))
(deftest remove-root-meta-fn
(let [h+meta-a (n/section (n/key-word "TITLE" "foo")
(n/key-word "TAGS" "foo|bar|baz"))
h+meta-b (n/section (n/key-word "TITLE" "bar")
(n/key-word "TAGS" "qux"))
p (n/paragraph (n/text "text"))
h+meta+p (n/section (n/key-word "TITLE" "bar")
(n/key-word "TAGS" "qux")
p)
h+p (n/section p)
root-no-meta (n/root "foo" #{} (n/todo "bar"))
fadd (fn [n root] (update root :children (partial into [n])))
root-with-meta (fadd h+meta-a root-no-meta)
root-with-2x-meta (fadd h+meta-b root-with-meta)
root-with-meta+p (fadd h+meta+p root-no-meta)
root-with-p (fadd h+p root-no-meta)]
(is (tu/identity? remove-root-meta root-no-meta))
(is (tu/identity? remove-root-meta root-with-p))
(is (= root-no-meta (remove-root-meta root-with-meta)))
(is (= root-with-meta (remove-root-meta root-with-2x-meta)))
(is (= root-with-p (remove-root-meta root-with-meta+p)))))
(deftest add-root-meta-fn
(let [tags (tu/tags->tag->tag-descr ["a" "b" "c"])
ph (n/todo "bar")
h-node (n/paragraph (n/text "text"))
head (n/section h-node)]
(with-redefs-fn {#'spacetools.spacedoc.config/valid-tags
(constantly tags)}
#(are [root-node title-val tags-val rest-head]
(let [[title tags rest] (extract-head (add-root-meta root-node))]
(and (= title-val (:value title))
(= tags-val (:value tags))
(= rest-head rest)))
(n/root "foo" #{} ph) "foo" nil []
(n/root "foo" #{"a"} ph) "foo" "a" []
(n/root "foo" #{"a" "b"} ph) "foo" "a|b" []
(n/root "foo" #{"b" "a"} ph) "foo" "a|b" []
(n/root "foo" #{} head) "foo" nil [h-node]
(n/root "foo" #{"a"} head) "foo" "a" [h-node]
(n/root "foo" #{"a"} head ph) "foo" "a" [h-node]))))
(deftest root->toc-fn
(is (nil? (root->toc (n/root "foo" #{} (n/section (n/key-word "foo" "bar")))))
"Root node without headlines shouldn't have TOC.")
(is (= (:value (root->toc (n/root "foo" #{} (n/todo "bar"))))
(cfg/toc-hl-val))
"TOC headline value should be the same as in the setting.")
(is (= (root->toc (n/root "foo" #{} (n/todo "bar")))
(test-toc-tmpl (n/unordered-list [(n/link "#bar" (n/text "bar"))])))
"Simple TOC generation should work.")
(is (= (root->toc (n/root "foo" #{}
(n/todo "foo")
(n/todo "bar")
(n/todo "baz")))
(test-toc-tmpl
(n/unordered-list [(n/link "#foo" (n/text "foo"))])
(n/unordered-list [(n/link "#bar" (n/text "bar"))])
(n/unordered-list [(n/link "#baz" (n/text "baz"))])))
"Flat TOC generation should work.")
(is (= (->> "qux"
n/text
n/paragraph
n/section
(n/headline "baz")
(n/headline "bar")
(n/root "foo" #{})
root->toc)
(test-toc-tmpl
(n/unordered-list
[(n/link "#bar" (n/text "bar"))
(n/line-break)
(n/unordered-list [(n/link "#baz" (n/text "baz"))])])))
"Nested TOC generation should work."))
(deftest conj-toc-fn
(is (= (get-in (conj-toc (n/root "foo" #{} (n/todo "bar"))) [:children 0])
(test-toc-tmpl (n/unordered-list [(n/link "#bar" (n/text "bar"))])))
"TOC should be conjed.")
(let [root-no-hls (n/root "foo" #{} (n/section (n/key-word "foo" "bar")))]
(is (= root-no-hls (conj-toc root-no-hls))
"Root node without headlines shouldn't be altered.")))
| null | https://raw.githubusercontent.com/JAremko/spacetools/d047e99689918b5a4ad483022f35802b2015af5f/components/spacedoc/test/spacetools/spacedoc/org/head_test.clj | clojure | Test helpers
Tests | (ns spacetools.spacedoc.org.head-test
"Testing helpers for working with headers of documents."
(:require [clojure.spec.alpha :as s]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.test.check.clojure-test :refer [defspec]]
[clojure.test.check.generators :as gen]
[spacetools.spacedoc.config :as cfg]
[clojure.test.check.properties :as prop]
[orchestra.spec.test :as st]
[spacetools.spacedoc.core :as sc]
[spacetools.spacedoc.node :as n]
[spacetools.spacedoc.org.head :refer :all]
[spacetools.spacedoc.util :as sdu]
[spacetools.test-util.interface :as tu]
[spacetools.spacedoc.org.orgify :as o]
[clojure.set :as set]
[clojure.core.reducers :as r]))
(st/instrument)
(defn test-toc-tmpl
"Wraps TOC children into TOC headline."
[& children]
(n/headline (cfg/toc-hl-val) (apply n/section children)))
(defn root-tags-n?
"Returns true if X is a root tags node."
[x]
(s/valid? :spacetools.spacedoc.node.meta/tags x))
(defn extract-head
"Returns [TITLE TAGS REST-OF-HEAD] of the ROOT node"
[root]
(let [{[{[title & rst] :children}] :children} root
tag-or-fr (first rst)]
(into [title] (if (root-tags-n? tag-or-fr)
[tag-or-fr (vec (rest rst))]
[nil (vec rst)]))))
(def root-meta-tags
"Tags of root meta nodes.
See `:spacetools.spacedoc.org.head/root-meta`."
#{:tags :title})
(deftest str-tags->set-fn
(are [string-tags set-tags] (= set-tags (str-tags->set string-tags))
"" #{}
"foo" #{"foo"}
"foo|bar" #{"foo" "bar"}
"Foo Bar" #{"Foo Bar"}
"Foo Bar|baz qux" #{"Foo Bar" "baz qux"}
"foo|bar|baz|qux" #{"foo" "bar" "baz" "qux"}))
(deftest set-tags->str-fn
(are [set-tags string-tags] (= string-tags (set-tags->str set-tags))
#{} ""
#{"a" "b" "c"} "a|b|c"
#{"b" "a" "c"} "a|b|c"
#{"foo"} "foo"
#{"foo" "bar"} "bar|foo"
#{"Foo Bar"} "Foo Bar"
#{"Foo Bar" "baz qux"} "Foo Bar|baz qux"
#{"foo" "bar" "baz" "qux"} "bar|baz|foo|qux"))
(deftest remove-root-meta-fn
(let [h+meta-a (n/section (n/key-word "TITLE" "foo")
(n/key-word "TAGS" "foo|bar|baz"))
h+meta-b (n/section (n/key-word "TITLE" "bar")
(n/key-word "TAGS" "qux"))
p (n/paragraph (n/text "text"))
h+meta+p (n/section (n/key-word "TITLE" "bar")
(n/key-word "TAGS" "qux")
p)
h+p (n/section p)
root-no-meta (n/root "foo" #{} (n/todo "bar"))
fadd (fn [n root] (update root :children (partial into [n])))
root-with-meta (fadd h+meta-a root-no-meta)
root-with-2x-meta (fadd h+meta-b root-with-meta)
root-with-meta+p (fadd h+meta+p root-no-meta)
root-with-p (fadd h+p root-no-meta)]
(is (tu/identity? remove-root-meta root-no-meta))
(is (tu/identity? remove-root-meta root-with-p))
(is (= root-no-meta (remove-root-meta root-with-meta)))
(is (= root-with-meta (remove-root-meta root-with-2x-meta)))
(is (= root-with-p (remove-root-meta root-with-meta+p)))))
(deftest add-root-meta-fn
(let [tags (tu/tags->tag->tag-descr ["a" "b" "c"])
ph (n/todo "bar")
h-node (n/paragraph (n/text "text"))
head (n/section h-node)]
(with-redefs-fn {#'spacetools.spacedoc.config/valid-tags
(constantly tags)}
#(are [root-node title-val tags-val rest-head]
(let [[title tags rest] (extract-head (add-root-meta root-node))]
(and (= title-val (:value title))
(= tags-val (:value tags))
(= rest-head rest)))
(n/root "foo" #{} ph) "foo" nil []
(n/root "foo" #{"a"} ph) "foo" "a" []
(n/root "foo" #{"a" "b"} ph) "foo" "a|b" []
(n/root "foo" #{"b" "a"} ph) "foo" "a|b" []
(n/root "foo" #{} head) "foo" nil [h-node]
(n/root "foo" #{"a"} head) "foo" "a" [h-node]
(n/root "foo" #{"a"} head ph) "foo" "a" [h-node]))))
(deftest root->toc-fn
(is (nil? (root->toc (n/root "foo" #{} (n/section (n/key-word "foo" "bar")))))
"Root node without headlines shouldn't have TOC.")
(is (= (:value (root->toc (n/root "foo" #{} (n/todo "bar"))))
(cfg/toc-hl-val))
"TOC headline value should be the same as in the setting.")
(is (= (root->toc (n/root "foo" #{} (n/todo "bar")))
(test-toc-tmpl (n/unordered-list [(n/link "#bar" (n/text "bar"))])))
"Simple TOC generation should work.")
(is (= (root->toc (n/root "foo" #{}
(n/todo "foo")
(n/todo "bar")
(n/todo "baz")))
(test-toc-tmpl
(n/unordered-list [(n/link "#foo" (n/text "foo"))])
(n/unordered-list [(n/link "#bar" (n/text "bar"))])
(n/unordered-list [(n/link "#baz" (n/text "baz"))])))
"Flat TOC generation should work.")
(is (= (->> "qux"
n/text
n/paragraph
n/section
(n/headline "baz")
(n/headline "bar")
(n/root "foo" #{})
root->toc)
(test-toc-tmpl
(n/unordered-list
[(n/link "#bar" (n/text "bar"))
(n/line-break)
(n/unordered-list [(n/link "#baz" (n/text "baz"))])])))
"Nested TOC generation should work."))
(deftest conj-toc-fn
(is (= (get-in (conj-toc (n/root "foo" #{} (n/todo "bar"))) [:children 0])
(test-toc-tmpl (n/unordered-list [(n/link "#bar" (n/text "bar"))])))
"TOC should be conjed.")
(let [root-no-hls (n/root "foo" #{} (n/section (n/key-word "foo" "bar")))]
(is (= root-no-hls (conj-toc root-no-hls))
"Root node without headlines shouldn't be altered.")))
|
f541414d89387829f5e844cba660eb472cb8d039d38677605000f5837e9bf40f | input-output-hk/ouroboros-network | Split.hs | # LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Test.Util.Split (
spanLeft
, spanLeft'
, splitAtJust
) where
import Data.Bifunctor (first)
import Data.Word (Word64)
{-------------------------------------------------------------------------------
spanLeft
-------------------------------------------------------------------------------}
| The returned @b@ is the first in the list .
--
-- INVARIANT The output data is a segmentation of the given list.
spanLeft
:: forall x a b.
(x -> Either a b) -> [x] -> ([a], Maybe (b, [x]))
spanLeft prj xs = (reverse acc, mbBxs)
where
(acc, mbBxs) = spanLeft' prj xs
| As ' spanLeft ' , but the @[a]@ is reversed .
spanLeft'
:: forall x a b.
(x -> Either a b) -> [x] -> ([a], Maybe (b, [x]))
spanLeft' prj = go []
where
go acc = \case
[] -> (acc, Nothing)
x : xs -> case prj x of
Left a -> go (a : acc) xs
Right b -> (acc, Just (b, xs))
{-------------------------------------------------------------------------------
splitAtJust
-------------------------------------------------------------------------------}
| INVARIANT : The second is a function of the first .
data Prj a b = Prj !a !b
| The returned @b@ is either the @n@th @b@ or else the last in the given
-- list.
--
-- INVARIANT The output data is a segmentation of the given list.
splitAtJust
:: forall x b.
(x -> Maybe b) -> Word64 -> [x] -> (Maybe ([x], b), [x])
splitAtJust prj = \n xs ->
if 0 == n then (Nothing, xs)
else case peel xs of
(pre, Just (xb, xs')) -> Just `first` go pre xb (n - 1) xs'
(_, Nothing) -> (Nothing, xs)
where
peel :: [x] -> ([x], Maybe (Prj x b, [x]))
peel = spanLeft' prj'
where
prj' x = case prj x of
Nothing -> Left x
Just b -> Right (Prj x b)
go pre (Prj x b) n xs
| 0 == n = ((reverse pre, b), xs)
| otherwise = case peel xs of
(pre', Nothing ) -> ((reverse pre, b), reverse pre')
(pre', Just (xb, xs')) -> go (pre' ++ x : pre) xb (n - 1) xs'
| null | https://raw.githubusercontent.com/input-output-hk/ouroboros-network/c82309f403e99d916a76bb4d96d6812fb0a9db81/ouroboros-consensus-test/src/Test/Util/Split.hs | haskell | ------------------------------------------------------------------------------
spanLeft
------------------------------------------------------------------------------
INVARIANT The output data is a segmentation of the given list.
------------------------------------------------------------------------------
splitAtJust
------------------------------------------------------------------------------
list.
INVARIANT The output data is a segmentation of the given list. | # LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Test.Util.Split (
spanLeft
, spanLeft'
, splitAtJust
) where
import Data.Bifunctor (first)
import Data.Word (Word64)
| The returned @b@ is the first in the list .
spanLeft
:: forall x a b.
(x -> Either a b) -> [x] -> ([a], Maybe (b, [x]))
spanLeft prj xs = (reverse acc, mbBxs)
where
(acc, mbBxs) = spanLeft' prj xs
| As ' spanLeft ' , but the @[a]@ is reversed .
spanLeft'
:: forall x a b.
(x -> Either a b) -> [x] -> ([a], Maybe (b, [x]))
spanLeft' prj = go []
where
go acc = \case
[] -> (acc, Nothing)
x : xs -> case prj x of
Left a -> go (a : acc) xs
Right b -> (acc, Just (b, xs))
| INVARIANT : The second is a function of the first .
data Prj a b = Prj !a !b
| The returned @b@ is either the @n@th @b@ or else the last in the given
splitAtJust
:: forall x b.
(x -> Maybe b) -> Word64 -> [x] -> (Maybe ([x], b), [x])
splitAtJust prj = \n xs ->
if 0 == n then (Nothing, xs)
else case peel xs of
(pre, Just (xb, xs')) -> Just `first` go pre xb (n - 1) xs'
(_, Nothing) -> (Nothing, xs)
where
peel :: [x] -> ([x], Maybe (Prj x b, [x]))
peel = spanLeft' prj'
where
prj' x = case prj x of
Nothing -> Left x
Just b -> Right (Prj x b)
go pre (Prj x b) n xs
| 0 == n = ((reverse pre, b), xs)
| otherwise = case peel xs of
(pre', Nothing ) -> ((reverse pre, b), reverse pre')
(pre', Just (xb, xs')) -> go (pre' ++ x : pre) xb (n - 1) xs'
|
1f7afbd61bbbbc658c0eff75bb4d975d56bd25ea18a40d7f30e82529169f035a | generateme/inferme | project.clj | (defproject generateme/inferme "0.0.2-SNAPSHOT"
:description "MCMC based Bayesian inference toolkit"
:url ""
:license {:name "The Unlicense"
:url ""}
:scm {:name "git"
:url "/"}
:dependencies [[org.clojure/clojure "1.10.3"]
[cljplot "0.0.2a-SNAPSHOT"]]
:profiles {:dev {:dependencies [[anglican "1.1.0"]
[metaprob "0.1.0-SNAPSHOT"]]}})
| null | https://raw.githubusercontent.com/generateme/inferme/b6c65f0545d4c14531af6e93d8c2d015de3cec59/project.clj | clojure | (defproject generateme/inferme "0.0.2-SNAPSHOT"
:description "MCMC based Bayesian inference toolkit"
:url ""
:license {:name "The Unlicense"
:url ""}
:scm {:name "git"
:url "/"}
:dependencies [[org.clojure/clojure "1.10.3"]
[cljplot "0.0.2a-SNAPSHOT"]]
:profiles {:dev {:dependencies [[anglican "1.1.0"]
[metaprob "0.1.0-SNAPSHOT"]]}})
|
|
4388f63d7d9c8c6e47f0d49fb5d1b300e385d89bcbdb73f7b1c4c51af012998f | ucsd-progsys/liquidhaskell | ApplicativeList.hs | {-@ LIQUID "--expect-any-error" @-}
{-@ LIQUID "--reflection" @-}
module ApplicativeList where
import Prelude hiding (fmap, id, seq, pure)
-- | Applicative Laws :
-- | identity pure id <*> v = v
-- | composition pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
-- | homomorphism pure f <*> pure x = pure (f x)
-- | interchange u <*> pure y = pure ($ y) <*> u
{-@ reflect pure @-}
pure :: a -> L a
pure x = C x N
{-@ reflect seq @-}
seq :: L (a -> b) -> L a -> L b
seq fs xs
| llen fs > 0 = append (fmap (hd fs) xs) (seq (tl fs) xs)
| otherwise = N
{-@ reflect append @-}
append :: L a -> L a -> L a
append xs ys
| llen xs == 0 = ys
| otherwise = C (hd xs) (append (tl xs) ys)
@ reflect fmap @
fmap :: (a -> b) -> L a -> L b
fmap f xs
| llen xs == 0 = N
| otherwise = C (f (hd xs)) (fmap f (tl xs))
{-@ reflect id @-}
id :: a -> a
id x = x
@ reflect @
idollar :: a -> (a -> b) -> b
idollar x f = f x
{-@ reflect compose @-}
compose :: (b -> c) -> (a -> b) -> a -> c
compose f g x = f (g x)
-- | Identity
{-@ identity :: x:L a -> {v:Proof | seq (pure id) x /= x } @-}
identity :: L a -> Proof
identity xs
= seq (pure id) xs
=== seq (C id N) xs
=== append (fmap id xs) (seq N xs)
==? append (id xs) (seq N xs)
? fmap_id xs
=== append xs (seq N xs)
=== append xs N
==? xs
? prop_append_neutral xs
*** QED
-- | Composition
{-@ composition :: x:L (a -> a)
-> y:L (a -> a)
-> z:L a
-> {v:Proof | (seq (seq (seq (pure compose) x) y) z) /= seq x (seq y z) } @-}
composition :: L (a -> a) -> L (a -> a) -> L a -> Proof
composition xss@(C x xs) yss@(C y ys) zss@(C z zs)
= seq (seq (seq (pure compose) xss) yss) zss
==. seq (seq (seq (C compose N) xss) yss) zss
==. seq (seq (append (fmap compose xss) (seq N xss)) yss) zss
==. seq (seq (append (fmap compose xss) N) yss) zss
==. seq (seq (fmap compose xss) yss) zss ? prop_append_neutral (fmap compose xss)
==. seq (seq (fmap compose (C x xs)) yss) zss
==. seq (seq (C (compose x) (fmap compose xs)) yss) zss
==. seq (append (fmap (compose x) yss) (seq (fmap compose xs) yss)) zss
==. seq (append (fmap (compose x) (C y ys)) (seq (fmap compose xs) yss)) zss
==. seq (append (C (compose x y) (fmap (compose x) ys)) (seq (fmap compose xs) yss)) zss
==. seq (C (compose x y) (append (fmap (compose x) ys) (seq (fmap compose xs) yss))) zss
==. append (fmap (compose x y) zss) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss)
==. append (fmap (compose x y) (C z zs)) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss)
==. append (C (compose x y z) (fmap (compose x y) zs)) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss)
==. C (compose x y z) (append (fmap (compose x y) zs) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss))
==. C (x (y z)) (append (fmap (compose x y) zs) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss))
==. C (x (y z)) (append (fmap x (fmap y zs)) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss))
? map_fusion0 x y zs
==. C (x (y z)) (append (fmap x (fmap y zs)) (append (seq (fmap (compose x) ys) zss) (seq (seq (fmap compose xs) yss) zss)))
? seq_append (fmap (compose x) ys) (seq (fmap compose xs) yss) zss
==. C (x (y z)) (append (fmap x (fmap y zs)) (append (seq (fmap (compose x) ys) zss) (seq (seq (seq (pure compose) xs) yss) zss)))
? seq_one xs
==. C (x (y z)) (append (fmap x (fmap y zs)) (append (seq (fmap (compose x) ys) zss) (seq xs (seq yss zss))))
? composition xs yss zss
==. C (x (y z)) (append (append (fmap x (fmap y zs)) (seq (fmap (compose x) ys) zss)) (seq xs (seq yss zss)))
? append_distr (fmap x (fmap y zs)) (seq (fmap (compose x) ys) zss) (seq xs (seq yss zss))
==. C (x (y z)) (append (append (fmap x (fmap y zs)) (fmap x (seq ys zss))) (seq xs (seq yss zss)))
? seq_fmap x ys zss
==. C (x (y z)) (append (append (fmap x (fmap y zs)) (fmap x (seq ys zss))) (seq xs (seq yss zss)))
? append_fmap x (fmap y zs) (seq ys zss)
==. append (C (x (y z)) (fmap x (append (fmap y zs) (seq ys zss)))) (seq xs (seq yss zss))
==. append (fmap x (C (y z) (append (fmap y zs) (seq ys zss)))) (seq xs (seq yss zss))
==. append (fmap x (append (C (y z) (fmap y zs)) (seq ys zss))) (seq xs (seq yss zss))
==. append (fmap x (append (fmap y (C z zs)) (seq ys zss))) (seq xs (seq yss zss))
==. append (fmap x (append (fmap y zss) (seq ys zss))) (seq xs (seq yss zss))
==. append (fmap x (seq (C y ys) zss)) (seq xs (seq yss zss))
==. append (fmap x (seq yss zss)) (seq xs (seq yss zss))
==. seq (C x xs) (seq yss zss)
==. seq xss (seq yss zss)
*** QED
composition N yss zss
= seq (seq (seq (pure compose) N) yss) zss
==. seq (seq N yss) zss ? seq_nill (pure compose)
==. seq N zss
==. N
==. seq N (seq yss zss)
*** QED
composition xss N zss
= toProof $
seq (seq (seq (pure compose) xss) N) zss
==. seq N zss ? seq_nill (seq (pure compose) xss)
==. N
==. seq N zss
==. seq xss (seq N zss) ? (seq_nill xss &&& (toProof $ seq N zss ==. N))
composition xss yss N
= toProof $
seq (seq (seq (pure compose) xss) yss) N
==. N ? seq_nill (seq (seq (pure compose) xss) yss)
==. seq xss N ? seq_nill xss
==. seq xss (seq yss N) ? seq_nill yss
-- | homomorphism pure f <*> pure x = pure (f x)
{-@ homomorphism :: f:(a -> a) -> x:a
-> {v:Proof | seq (pure f) (pure x) /= pure (f x) } @-}
homomorphism :: (a -> a) -> a -> Proof
homomorphism f x
= toProof $
seq (pure f) (pure x)
==. seq (C f N) (C x N)
==. append (fmap f (C x N)) (seq N (C x N))
==. append (C (f x) (fmap f N)) N
==. append (C (f x) N) N
==. C (f x) N ? prop_append_neutral (C (f x) N)
==. pure (f x)
-- | interchange
interchange :: L (a -> a) -> a -> Proof
{-@ interchange :: u:(L (a -> a)) -> y:a
-> {v:Proof | seq u (pure y) /= seq (pure (idollar y)) u }
@-}
interchange N y
= toProof $
seq N (pure y)
==. N
==. seq (pure (idollar y)) N ? seq_nill (pure (idollar y))
interchange (C x xs) y
= toProof $
seq (C x xs) (pure y)
==. seq (C x xs) (C y N)
==. append (fmap x (C y N)) (seq xs (C y N))
==. append (C (x y) (fmap x N)) (seq xs (C y N))
==. append (C (x y) N) (seq xs (C y N))
==. C (x y) (append N (seq xs (C y N)))
==. C (x y) (seq xs (C y N))
==. C (x y) (seq xs (pure y))
==. C (x y) (seq (pure (idollar y)) xs) ? interchange xs y
==. C (x y) (fmap (idollar y) xs) ? seq_one' (idollar y) xs
==. C (idollar y x) (fmap (idollar y) xs)
==. fmap (idollar y) (C x xs)
==. append (fmap (idollar y) (C x xs)) N ? prop_append_neutral (fmap (idollar y) (C x xs))
==. append (fmap (idollar y) (C x xs)) (seq N (C x xs))
==. seq (C (idollar y) N) (C x xs)
==. seq (pure (idollar y)) (C x xs)
data L a = N | C a (L a)
{-@ data L [llen] @-}
{-@ measure llen @-}
llen :: L a -> Int
{-@ llen :: L a -> Nat @-}
llen N = 0
llen (C _ xs) = 1 + llen xs
{-@ measure hd @-}
@ hd : : { v : L a | llen v > 0 } - > a @
hd :: L a -> a
hd (C x _) = x
{-@ measure tl @-}
@ tl : : xs:{L a | llen xs > 0 } - > { v : L a | llen v = = llen xs - 1 } @
tl :: L a -> L a
tl (C _ xs) = xs
-- | TODO: Cuurently I cannot improve proofs
-- | HERE I duplicate the code...
-- TODO: remove stuff out of HERE
{-@ seq_nill :: fs:L (a -> b) -> {v:Proof | seq fs N == N } @-}
seq_nill :: L (a -> b) -> Proof
seq_nill N
= toProof $
seq N N ==. N
seq_nill (C x xs)
= toProof $
seq (C x xs) N
==. append (fmap x N) (seq xs N)
==. append N N ? seq_nill xs
==. N
@ append_fmap : : f:(a - > b ) - > xs : L a - > ys : L a
- > { v : Proof | append ( fmap f xs ) ( fmap f ys ) = = fmap f ( append xs ys ) } @
-> {v:Proof | append (fmap f xs) (fmap f ys) == fmap f (append xs ys) } @-}
append_fmap :: (a -> b) -> L a -> L a -> Proof
append_fmap = undefined
seq_fmap :: (a -> a) -> L (a -> a) -> L a -> Proof
@ seq_fmap : : f : ( a - > a ) - > fs : L ( a - > a ) - > xs : L a
- > { v : Proof | seq ( fmap ( compose f ) fs ) xs = = fmap f ( seq fs xs ) }
@
-> {v:Proof | seq (fmap (compose f) fs) xs == fmap f (seq fs xs) }
@-}
seq_fmap = undefined
{-@ append_distr :: xs:L a -> ys:L a -> zs:L a
-> {v:Proof | append xs (append ys zs) == append (append xs ys) zs } @-}
append_distr :: L a -> L a -> L a -> Proof
append_distr = undefined
{-@ seq_one' :: f:((a -> b) -> b) -> xs:L (a -> b) -> {v:Proof | fmap f xs == seq (pure f) xs} @-}
seq_one' :: ((a -> b) -> b) -> L (a -> b) -> Proof
seq_one' = undefined
{-@ seq_one :: xs:L (a -> b) -> {v:Proof | fmap compose xs == seq (pure compose) xs} @-}
seq_one :: L (a -> b) -> Proof
seq_one = undefined
{-@ seq_append :: fs1:L (a -> b) -> fs2: L (a -> b) -> xs: L a
-> {v:Proof | seq (append fs1 fs2) xs == append (seq fs1 xs) (seq fs2 xs) } @-}
seq_append :: L (a -> b) -> L (a -> b) -> L a -> Proof
seq_append = undefined
{-@ map_fusion0 :: f:(a -> a) -> g:(a -> a) -> xs:L a
-> {v:Proof | fmap (compose f g) xs == fmap f (fmap g xs) } @-}
map_fusion0 :: (a -> a) -> (a -> a) -> L a -> Proof
map_fusion0 = undefined
-- | FunctorList
{-@ fmap_id :: xs:L a -> {v:Proof | fmap id xs == id xs } @-}
fmap_id :: L a -> Proof
fmap_id N
= toProof $
fmap id N ==. N
==. id N
fmap_id (C x xs)
= toProof $
fmap id (C x xs) ==. C (id x) (fmap id xs)
==. C x (fmap id xs)
==. C x (id xs) ? fmap_id xs
==. C x xs
==. id (C x xs)
-- imported from Append
prop_append_neutral :: L a -> Proof
{-@ prop_append_neutral :: xs:L a -> {v:Proof | append xs N == xs } @-}
prop_append_neutral N
= toProof $
append N N ==. N
prop_append_neutral (C x xs)
= toProof $
append (C x xs) N ==. C x (append xs N)
==. C x xs ? prop_append_neutral xs
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/benchmarks/popl18/nople/neg/ApplicativeList.hs | haskell | @ LIQUID "--expect-any-error" @
@ LIQUID "--reflection" @
| Applicative Laws :
| identity pure id <*> v = v
| composition pure (.) <*> u <*> v <*> w = u <*> (v <*> w)
| homomorphism pure f <*> pure x = pure (f x)
| interchange u <*> pure y = pure ($ y) <*> u
@ reflect pure @
@ reflect seq @
@ reflect append @
@ reflect id @
@ reflect compose @
| Identity
@ identity :: x:L a -> {v:Proof | seq (pure id) x /= x } @
| Composition
@ composition :: x:L (a -> a)
-> y:L (a -> a)
-> z:L a
-> {v:Proof | (seq (seq (seq (pure compose) x) y) z) /= seq x (seq y z) } @
| homomorphism pure f <*> pure x = pure (f x)
@ homomorphism :: f:(a -> a) -> x:a
-> {v:Proof | seq (pure f) (pure x) /= pure (f x) } @
| interchange
@ interchange :: u:(L (a -> a)) -> y:a
-> {v:Proof | seq u (pure y) /= seq (pure (idollar y)) u }
@
@ data L [llen] @
@ measure llen @
@ llen :: L a -> Nat @
@ measure hd @
@ measure tl @
| TODO: Cuurently I cannot improve proofs
| HERE I duplicate the code...
TODO: remove stuff out of HERE
@ seq_nill :: fs:L (a -> b) -> {v:Proof | seq fs N == N } @
@ append_distr :: xs:L a -> ys:L a -> zs:L a
-> {v:Proof | append xs (append ys zs) == append (append xs ys) zs } @
@ seq_one' :: f:((a -> b) -> b) -> xs:L (a -> b) -> {v:Proof | fmap f xs == seq (pure f) xs} @
@ seq_one :: xs:L (a -> b) -> {v:Proof | fmap compose xs == seq (pure compose) xs} @
@ seq_append :: fs1:L (a -> b) -> fs2: L (a -> b) -> xs: L a
-> {v:Proof | seq (append fs1 fs2) xs == append (seq fs1 xs) (seq fs2 xs) } @
@ map_fusion0 :: f:(a -> a) -> g:(a -> a) -> xs:L a
-> {v:Proof | fmap (compose f g) xs == fmap f (fmap g xs) } @
| FunctorList
@ fmap_id :: xs:L a -> {v:Proof | fmap id xs == id xs } @
imported from Append
@ prop_append_neutral :: xs:L a -> {v:Proof | append xs N == xs } @ |
module ApplicativeList where
import Prelude hiding (fmap, id, seq, pure)
pure :: a -> L a
pure x = C x N
seq :: L (a -> b) -> L a -> L b
seq fs xs
| llen fs > 0 = append (fmap (hd fs) xs) (seq (tl fs) xs)
| otherwise = N
append :: L a -> L a -> L a
append xs ys
| llen xs == 0 = ys
| otherwise = C (hd xs) (append (tl xs) ys)
@ reflect fmap @
fmap :: (a -> b) -> L a -> L b
fmap f xs
| llen xs == 0 = N
| otherwise = C (f (hd xs)) (fmap f (tl xs))
id :: a -> a
id x = x
@ reflect @
idollar :: a -> (a -> b) -> b
idollar x f = f x
compose :: (b -> c) -> (a -> b) -> a -> c
compose f g x = f (g x)
identity :: L a -> Proof
identity xs
= seq (pure id) xs
=== seq (C id N) xs
=== append (fmap id xs) (seq N xs)
==? append (id xs) (seq N xs)
? fmap_id xs
=== append xs (seq N xs)
=== append xs N
==? xs
? prop_append_neutral xs
*** QED
composition :: L (a -> a) -> L (a -> a) -> L a -> Proof
composition xss@(C x xs) yss@(C y ys) zss@(C z zs)
= seq (seq (seq (pure compose) xss) yss) zss
==. seq (seq (seq (C compose N) xss) yss) zss
==. seq (seq (append (fmap compose xss) (seq N xss)) yss) zss
==. seq (seq (append (fmap compose xss) N) yss) zss
==. seq (seq (fmap compose xss) yss) zss ? prop_append_neutral (fmap compose xss)
==. seq (seq (fmap compose (C x xs)) yss) zss
==. seq (seq (C (compose x) (fmap compose xs)) yss) zss
==. seq (append (fmap (compose x) yss) (seq (fmap compose xs) yss)) zss
==. seq (append (fmap (compose x) (C y ys)) (seq (fmap compose xs) yss)) zss
==. seq (append (C (compose x y) (fmap (compose x) ys)) (seq (fmap compose xs) yss)) zss
==. seq (C (compose x y) (append (fmap (compose x) ys) (seq (fmap compose xs) yss))) zss
==. append (fmap (compose x y) zss) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss)
==. append (fmap (compose x y) (C z zs)) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss)
==. append (C (compose x y z) (fmap (compose x y) zs)) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss)
==. C (compose x y z) (append (fmap (compose x y) zs) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss))
==. C (x (y z)) (append (fmap (compose x y) zs) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss))
==. C (x (y z)) (append (fmap x (fmap y zs)) (seq (append (fmap (compose x) ys) (seq (fmap compose xs) yss)) zss))
? map_fusion0 x y zs
==. C (x (y z)) (append (fmap x (fmap y zs)) (append (seq (fmap (compose x) ys) zss) (seq (seq (fmap compose xs) yss) zss)))
? seq_append (fmap (compose x) ys) (seq (fmap compose xs) yss) zss
==. C (x (y z)) (append (fmap x (fmap y zs)) (append (seq (fmap (compose x) ys) zss) (seq (seq (seq (pure compose) xs) yss) zss)))
? seq_one xs
==. C (x (y z)) (append (fmap x (fmap y zs)) (append (seq (fmap (compose x) ys) zss) (seq xs (seq yss zss))))
? composition xs yss zss
==. C (x (y z)) (append (append (fmap x (fmap y zs)) (seq (fmap (compose x) ys) zss)) (seq xs (seq yss zss)))
? append_distr (fmap x (fmap y zs)) (seq (fmap (compose x) ys) zss) (seq xs (seq yss zss))
==. C (x (y z)) (append (append (fmap x (fmap y zs)) (fmap x (seq ys zss))) (seq xs (seq yss zss)))
? seq_fmap x ys zss
==. C (x (y z)) (append (append (fmap x (fmap y zs)) (fmap x (seq ys zss))) (seq xs (seq yss zss)))
? append_fmap x (fmap y zs) (seq ys zss)
==. append (C (x (y z)) (fmap x (append (fmap y zs) (seq ys zss)))) (seq xs (seq yss zss))
==. append (fmap x (C (y z) (append (fmap y zs) (seq ys zss)))) (seq xs (seq yss zss))
==. append (fmap x (append (C (y z) (fmap y zs)) (seq ys zss))) (seq xs (seq yss zss))
==. append (fmap x (append (fmap y (C z zs)) (seq ys zss))) (seq xs (seq yss zss))
==. append (fmap x (append (fmap y zss) (seq ys zss))) (seq xs (seq yss zss))
==. append (fmap x (seq (C y ys) zss)) (seq xs (seq yss zss))
==. append (fmap x (seq yss zss)) (seq xs (seq yss zss))
==. seq (C x xs) (seq yss zss)
==. seq xss (seq yss zss)
*** QED
composition N yss zss
= seq (seq (seq (pure compose) N) yss) zss
==. seq (seq N yss) zss ? seq_nill (pure compose)
==. seq N zss
==. N
==. seq N (seq yss zss)
*** QED
composition xss N zss
= toProof $
seq (seq (seq (pure compose) xss) N) zss
==. seq N zss ? seq_nill (seq (pure compose) xss)
==. N
==. seq N zss
==. seq xss (seq N zss) ? (seq_nill xss &&& (toProof $ seq N zss ==. N))
composition xss yss N
= toProof $
seq (seq (seq (pure compose) xss) yss) N
==. N ? seq_nill (seq (seq (pure compose) xss) yss)
==. seq xss N ? seq_nill xss
==. seq xss (seq yss N) ? seq_nill yss
homomorphism :: (a -> a) -> a -> Proof
homomorphism f x
= toProof $
seq (pure f) (pure x)
==. seq (C f N) (C x N)
==. append (fmap f (C x N)) (seq N (C x N))
==. append (C (f x) (fmap f N)) N
==. append (C (f x) N) N
==. C (f x) N ? prop_append_neutral (C (f x) N)
==. pure (f x)
interchange :: L (a -> a) -> a -> Proof
interchange N y
= toProof $
seq N (pure y)
==. N
==. seq (pure (idollar y)) N ? seq_nill (pure (idollar y))
interchange (C x xs) y
= toProof $
seq (C x xs) (pure y)
==. seq (C x xs) (C y N)
==. append (fmap x (C y N)) (seq xs (C y N))
==. append (C (x y) (fmap x N)) (seq xs (C y N))
==. append (C (x y) N) (seq xs (C y N))
==. C (x y) (append N (seq xs (C y N)))
==. C (x y) (seq xs (C y N))
==. C (x y) (seq xs (pure y))
==. C (x y) (seq (pure (idollar y)) xs) ? interchange xs y
==. C (x y) (fmap (idollar y) xs) ? seq_one' (idollar y) xs
==. C (idollar y x) (fmap (idollar y) xs)
==. fmap (idollar y) (C x xs)
==. append (fmap (idollar y) (C x xs)) N ? prop_append_neutral (fmap (idollar y) (C x xs))
==. append (fmap (idollar y) (C x xs)) (seq N (C x xs))
==. seq (C (idollar y) N) (C x xs)
==. seq (pure (idollar y)) (C x xs)
data L a = N | C a (L a)
llen :: L a -> Int
llen N = 0
llen (C _ xs) = 1 + llen xs
@ hd : : { v : L a | llen v > 0 } - > a @
hd :: L a -> a
hd (C x _) = x
@ tl : : xs:{L a | llen xs > 0 } - > { v : L a | llen v = = llen xs - 1 } @
tl :: L a -> L a
tl (C _ xs) = xs
seq_nill :: L (a -> b) -> Proof
seq_nill N
= toProof $
seq N N ==. N
seq_nill (C x xs)
= toProof $
seq (C x xs) N
==. append (fmap x N) (seq xs N)
==. append N N ? seq_nill xs
==. N
@ append_fmap : : f:(a - > b ) - > xs : L a - > ys : L a
- > { v : Proof | append ( fmap f xs ) ( fmap f ys ) = = fmap f ( append xs ys ) } @
-> {v:Proof | append (fmap f xs) (fmap f ys) == fmap f (append xs ys) } @-}
append_fmap :: (a -> b) -> L a -> L a -> Proof
append_fmap = undefined
seq_fmap :: (a -> a) -> L (a -> a) -> L a -> Proof
@ seq_fmap : : f : ( a - > a ) - > fs : L ( a - > a ) - > xs : L a
- > { v : Proof | seq ( fmap ( compose f ) fs ) xs = = fmap f ( seq fs xs ) }
@
-> {v:Proof | seq (fmap (compose f) fs) xs == fmap f (seq fs xs) }
@-}
seq_fmap = undefined
append_distr :: L a -> L a -> L a -> Proof
append_distr = undefined
seq_one' :: ((a -> b) -> b) -> L (a -> b) -> Proof
seq_one' = undefined
seq_one :: L (a -> b) -> Proof
seq_one = undefined
seq_append :: L (a -> b) -> L (a -> b) -> L a -> Proof
seq_append = undefined
map_fusion0 :: (a -> a) -> (a -> a) -> L a -> Proof
map_fusion0 = undefined
fmap_id :: L a -> Proof
fmap_id N
= toProof $
fmap id N ==. N
==. id N
fmap_id (C x xs)
= toProof $
fmap id (C x xs) ==. C (id x) (fmap id xs)
==. C x (fmap id xs)
==. C x (id xs) ? fmap_id xs
==. C x xs
==. id (C x xs)
prop_append_neutral :: L a -> Proof
prop_append_neutral N
= toProof $
append N N ==. N
prop_append_neutral (C x xs)
= toProof $
append (C x xs) N ==. C x (append xs N)
==. C x xs ? prop_append_neutral xs
|
29467e8759e1ee38efa1f71fcc30e817f74f6b8a77686604c92ac924b7f234ef | bcc32/projecteuler-ocaml | memo.ml | open! Core
open! Import
type ('a, 'b) fn = 'a -> 'b
let[@inline always] simple key f =
let cache = Hashtbl.create key in
fun x -> Hashtbl.findi_or_add cache x ~default:f
;;
let[@inline always] recursive key f =
let cache = Hashtbl.create key in
let rec memoized_f x = Hashtbl.findi_or_add cache x ~default:(f memoized_f) in
memoized_f
;;
| null | https://raw.githubusercontent.com/bcc32/projecteuler-ocaml/712f85902c70adc1ec13dcbbee456c8bfa8450b2/src/memo.ml | ocaml | open! Core
open! Import
type ('a, 'b) fn = 'a -> 'b
let[@inline always] simple key f =
let cache = Hashtbl.create key in
fun x -> Hashtbl.findi_or_add cache x ~default:f
;;
let[@inline always] recursive key f =
let cache = Hashtbl.create key in
let rec memoized_f x = Hashtbl.findi_or_add cache x ~default:(f memoized_f) in
memoized_f
;;
|
|
850b12c186f339040a0b960ee8fe00167458b04b9a5c63959db51e1fc0a3a9b6 | haskell-gi/haskell-gi | ForestStore.hs | # LANGUAGE CPP #
# LANGUAGE TypeFamilies #
# LANGUAGE DataKinds #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
-- -*-haskell-*-
GIMP Toolkit ( GTK ) CustomStore TreeModel
--
Author : ,
--
Created : 11 Feburary 2006
--
Copyright ( C ) 2005 - 2016 , ,
--
-- 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.
--
-- |
-- Stability : provisional
Portability : portable ( depends on GHC )
--
-- Standard model to store hierarchical data.
--
module Data.GI.Gtk.ModelView.ForestStore (
-- * Types
ForestStore(..),
-- * Constructors
forestStoreNew,
forestStoreNewDND,
-- * Implementation of Interfaces
forestStoreDefaultDragSourceIface,
forestStoreDefaultDragDestIface,
-- * Methods
forestStoreGetValue,
forestStoreGetTree,
forestStoreGetForest,
forestStoreLookup,
forestStoreSetValue,
forestStoreInsert,
forestStoreInsertTree,
forestStoreInsertForest,
forestStoreRemove,
forestStoreClear,
forestStoreChange,
forestStoreChangeM,
) where
import Prelude ()
import Prelude.Compat
import Data.Bits
import Data.Word (Word32)
import Data.Int (Int32)
import Data.Maybe ( fromMaybe, isJust )
import Data.Tree
import Control.Monad ((>=>), when)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Exception (assert)
import Data.IORef
import Foreign.ForeignPtr (ForeignPtr)
import Data.GI.Base.BasicTypes
(TypedObject(..), ManagedPtr(..), GObject)
import Data.GI.Base.ManagedPtr (withManagedPtr)
import Data.GI.Base.Overloading (HasParentTypes, ParentTypes)
import Data.GI.Gtk.ModelView.Types
import Data.GI.Gtk.ModelView.CustomStore
(customStoreGetStamp, customStoreGetPrivate,
TreeModelIface(..), customStoreNew, DragDestIface(..),
DragSourceIface(..), CustomStore(..), customStoreInvalidateIters)
import GI.GObject.Objects.Object (Object(..))
import GI.Gtk.Interfaces.TreeModel
(treeModelRowDeleted, treeModelRowInserted,
treeModelRowChanged, toTreeModel, TreeModel(..), IsTreeModel(..),
treeModelRowHasChildToggled)
import GI.Gtk.Functions (treeSetRowDragData, treeGetRowDragData)
import GI.Gtk.Structs.TreePath
(TreePath)
import GI.Gtk.Structs.TreeIter
(getTreeIterUserData3, getTreeIterUserData2, getTreeIterUserData,
getTreeIterStamp, setTreeIterUserData3, setTreeIterUserData2,
setTreeIterUserData, setTreeIterStamp, TreeIter(..))
import Data.GI.Base (get, new)
import Unsafe.Coerce (unsafeCoerce)
--------------------------------------------
-- internal model data types
--
data ForestStoreIter = ForestStoreIter Int32 Word32 Word32 Word32
fromForestStoreIter :: MonadIO m => ForestStoreIter -> m TreeIter
fromForestStoreIter (ForestStoreIter s u1 u2 u3) = do
i <- new TreeIter []
setTreeIterStamp i s
setTreeIterUserData i $ unsafeCoerce u1
setTreeIterUserData2 i $ unsafeCoerce u2
setTreeIterUserData3 i $ unsafeCoerce u3
return i
toForestStoreIter :: MonadIO m => TreeIter -> m ForestStoreIter
toForestStoreIter iter = do
stamp <- getTreeIterStamp iter
u1 <- getTreeIterUserData iter
u2 <- getTreeIterUserData2 iter
u3 <- getTreeIterUserData3 iter
return $ ForestStoreIter stamp (unsafeCoerce u1) (unsafeCoerce u2) (unsafeCoerce u3)
forestStoreIterSetStamp :: ForestStoreIter -> Int32 -> ForestStoreIter
forestStoreIterSetStamp (ForestStoreIter _ a b c) s = ForestStoreIter s a b c
-- | A store for hierarchical data.
--
newtype ForestStore a = ForestStore (ManagedPtr (CustomStore (IORef (Store a)) a))
mkForestStore :: CustomStore (IORef (Store a)) a -> ForestStore a
mkForestStore (CustomStore ptr) = ForestStore ptr
instance HasParentTypes (ForestStore a)
type instance ParentTypes (ForestStore a) = '[TreeModel]
instance TypedObject (ForestStore a) where
glibType = glibType @TreeModel
instance GObject (ForestStore a)
instance IsTypedTreeModel ForestStore
-- | Maximum number of nodes on each level.
--
-- * These numbers determine how many bits in a 'TreeIter' are devoted to
-- each level. Hence, these numbers reflect log2 of the maximum number
-- of nodes at a level, rounded up.
--
type Depth = [Int]
data Store a = Store {
depth :: Depth,
content :: Cache a
}
-- | Create a new list store.
--
-- * The given rose tree determines the initial content and may be the empty
list . Each ' Tree ' in the forest corresponds to one top - level node .
--
* The ForestStore maintains the initially given Forest and aligns the ' TreePath '
bits to fit in 96 - bit length ' TreeIter ' storage .
--
-- * Additionally, a cache is used to achieve higher performance if operating on
-- recently used TreePaths.
--
-- * __Note:__ due to the limited amount of bits available in TreeIter storage, only
-- limited depth forests can be used with this implementation, the result of too deep
-- Forests is an undefined behaviour while trying to retrieve the deeply nested nodes.
For example : assuming the average requiement is 8 bits per tree level ( max number of
children at the level is 255 ) , then we can only use 12 levels deep trees ( 96/8 ) -
-- any further levels in a TreePath will not be encoded in the corresponding TreeIter
-- storage.
--
forestStoreNew :: MonadIO m => Forest a -> m (ForestStore a)
forestStoreNew forest = forestStoreNewDND forest
(Just forestStoreDefaultDragSourceIface)
(Just forestStoreDefaultDragDestIface)
-- | Create a new list store.
--
* In addition to ' forestStoreNew ' , this function takes an two interfaces
-- to implement user-defined drag-and-drop functionality.
--
forestStoreNewDND :: MonadIO m => Forest a -- ^ the inital tree stored in this model
-> Maybe (DragSourceIface ForestStore a) -- ^ an optional interface for drags
-> Maybe (DragDestIface ForestStore a) -- ^ an optional interface to handle drops
-> m (ForestStore a)
forestStoreNewDND forest mDSource mDDest = liftIO $ do
(storeRef :: IORef (Store a)) <- newIORef Store {
depth = calcForestDepth forest,
content = storeToCache forest
}
let withStore :: (Store a -> IO result) -> IO result
withStore f = readIORef storeRef >>= f
withStoreUpdateCache :: (Store a -> (result, Cache a)) -> IO result
withStoreUpdateCache f = do
store <- readIORef storeRef
let (result, cache') = f store
writeIORef storeRef store { content = cache' }
return result
customStoreNew storeRef mkForestStore TreeModelIface {
treeModelIfaceGetFlags = return [],
treeModelIfaceGetIter = \path -> withStore $
\Store { depth = d } -> fromPath d <$> treePathGetIndices' path >>= mapM fromForestStoreIter,
treeModelIfaceGetPath = toForestStoreIter >=> \iter -> withStore $
\Store { depth = d } -> treePathNewFromIndices' $ toPath d iter,
treeModelIfaceGetRow = toForestStoreIter >=> \iter -> withStoreUpdateCache $
\Store { depth = d, content = cache } ->
case checkSuccess d iter cache of
(True, cache'@((_, (Node { rootLabel = val }:_)):_)) ->
(val, cache')
_ -> error "ForestStore.getRow: iter does not refer to a valid entry",
treeModelIfaceIterNext = toForestStoreIter >=> \iter -> withStoreUpdateCache (
\Store { depth = d, content = cache } -> iterNext d iter cache) >>= mapM fromForestStoreIter,
treeModelIfaceIterChildren = \mIter -> do
iter <- maybe (return invalidIter) toForestStoreIter mIter
withStoreUpdateCache (
\Store { depth = d, content = cache } ->
iterNthChild d 0 iter cache) >>= mapM fromForestStoreIter,
treeModelIfaceIterHasChild = toForestStoreIter >=> \iter -> withStoreUpdateCache $
\Store { depth = d, content = cache } ->
let (mIter, cache') = iterNthChild d 0 iter cache
in (isJust mIter, cache'),
treeModelIfaceIterNChildren = mapM toForestStoreIter >=> \mIter -> withStoreUpdateCache $
\Store { depth = d, content = cache } ->
let iter = fromMaybe invalidIter mIter
in iterNChildren d iter cache,
treeModelIfaceIterNthChild = \mIter idx -> do
iter <- maybe (return invalidIter) toForestStoreIter mIter
withStoreUpdateCache (
\Store { depth = d, content = cache } ->
iterNthChild d idx iter cache) >>= mapM fromForestStoreIter,
treeModelIfaceIterParent = toForestStoreIter >=> \iter -> withStore $
\Store { depth = d } -> mapM fromForestStoreIter (iterParent d iter),
treeModelIfaceRefNode = \_ -> return (),
treeModelIfaceUnrefNode = \_ -> return ()
} mDSource mDDest
-- | Default drag functions for
-- 'Data.GI.Gtk.ModelView.ForestStore'. These functions allow the rows of
-- the model to serve as drag source. Any row is allowed to be dragged and the
-- data set in the 'SelectionDataM' object is set with 'treeSetRowDragData',
-- i.e. it contains the model and the 'TreePath' to the row.
forestStoreDefaultDragSourceIface :: DragSourceIface ForestStore row
forestStoreDefaultDragSourceIface = DragSourceIface {
customDragSourceRowDraggable = \_ _-> return True,
customDragSourceDragDataGet = \model path sel -> treeSetRowDragData sel model path,
customDragSourceDragDataDelete = \model path -> treePathGetIndices' path >>= \dest@(_:_) -> do
liftIO $ forestStoreRemove model path
return True
}
-- | Default drop functions for 'Data.GI.Gtk.ModelView.ForestStore'. These
-- functions accept a row and insert the row into the new location if it is
-- dragged into a tree view
-- that uses the same model.
forestStoreDefaultDragDestIface :: DragDestIface ForestStore row
forestStoreDefaultDragDestIface = DragDestIface {
customDragDestRowDropPossible = \model path sel -> do
mModelPath <- treeGetRowDragData sel
case mModelPath of
(True, Just model', source) -> do
tm <- toTreeModel model
withManagedPtr tm $ \m ->
withManagedPtr model' $ \m' -> return (m==m')
_ -> return False,
customDragDestDragDataReceived = \model path sel -> do
dest@(_:_) <- treePathGetIndices' path
mModelPath <- treeGetRowDragData sel
case mModelPath of
(True, Just model', Just path) -> do
source@(_:_) <- treePathGetIndices' path
tm <- toTreeModel model
withManagedPtr tm $ \m ->
withManagedPtr model' $ \m' ->
if m/=m' then return False
else do
row <- forestStoreGetTree model =<< treePathNewFromIndices' source
initPath <- treePathNewFromIndices' (init dest)
forestStoreInsertTree model initPath (fromIntegral $ last dest) row
return True
_ -> return False
}
--------------------------------------------
-- low level bit-twiddling utility functions
--
bitsNeeded :: Word32 -> Int
bitsNeeded n = bitsNeeded' 0 n
where bitsNeeded' b 0 = b
bitsNeeded' b n = bitsNeeded' (b+1) (n `shiftR` 1)
getBitSlice :: ForestStoreIter -> Int -> Int -> Word32
getBitSlice (ForestStoreIter _ a b c) off count =
getBitSliceWord a off count
.|. getBitSliceWord b (off-32) count
.|. getBitSliceWord c (off-64) count
where getBitSliceWord :: Word32 -> Int -> Int -> Word32
getBitSliceWord word off count =
word `shift` (-off) .&. (1 `shiftL` count - 1)
setBitSlice :: ForestStoreIter -> Int -> Int -> Word32 -> ForestStoreIter
setBitSlice (ForestStoreIter stamp a b c) off count value =
assert (value < 1 `shiftL` count) $
ForestStoreIter stamp
(setBitSliceWord a off count value)
(setBitSliceWord b (off-32) count value)
(setBitSliceWord c (off-64) count value)
where setBitSliceWord :: Word32 -> Int -> Int -> Word32 -> Word32
setBitSliceWord word off count value =
let mask = (1 `shiftL` count - 1) `shift` off
in (word .&. complement mask) .|. (value `shift` off)
--iterPrefixEqual :: TreeIter -> TreeIter -> Int -> Bool
--iterPrefixEqual (TreeIter _ a1 b1 c1) (TreeIter _ a2 b2 c2) pos
| pos>64 = let mask = 1 ` shiftL ` ( pos-64 ) - 1 in
a1==a2 & & b1==b2 & & ( c1 . & . mask ) = = ( c2 . & . mask )
| pos>32 = let mask = 1 ` shiftL ` ( pos-32 ) - 1 in
a1==a2 & & ( b1 . & . mask ) = = ( b2 . & . mask )
| otherwise = let mask = 1 ` shiftL ` pos - 1 in
-- (a1 .&. mask) == (a2 .&. mask)
-- | The invalid tree iterator.
--
invalidIter :: ForestStoreIter
invalidIter = ForestStoreIter 0 0 0 0
--showIterBits (TreeIter _ a b c) = [showBits a, showBits b, showBits c]
--
--showBits :: Bits a => a -> String
--showBits a = [ if testBit a i then '1' else '0' | i <- [0..bitSize a - 1] ]
-- | Calculate the maximum number of nodes on a per-level basis.
--
calcForestDepth :: Forest a -> Depth
calcForestDepth f = map bitsNeeded $
takeWhile (/=0) $
foldr calcTreeDepth (repeat 0) f
where
calcTreeDepth Node { subForest = f } (d:ds) =
(d+1): zipWith max ds (foldr calcTreeDepth (repeat 0) f)
-- | Convert an iterator into a path.
--
toPath :: Depth -> ForestStoreIter -> [Int32]
toPath d iter = gP 0 d
where
gP pos [] = []
gP pos (d:ds) = let idx = getBitSlice iter pos d in
if idx==0 then [] else fromIntegral (idx-1) : gP (pos+d) ds
-- | Try to convert a path into a 'TreeIter'.
--
fromPath :: Depth -> [Int32] -> Maybe ForestStoreIter
fromPath = fP 0 invalidIter
where
the remaining bits are zero anyway
fP pos ti [] _ = Nothing
fP pos ti (d:ds) (p:ps) = let idx = fromIntegral (p+1) in
if idx >= bit d then Nothing else
fP (pos+d) (setBitSlice ti pos d idx) ds ps
-- | The 'Cache' type synonym is only used iternally. What it represents
-- the stack during a (fictional) lookup operations.
-- The topmost frame is the node
-- for which this lookup was started and the innermost frame (the last
-- element of the list) contains the root of the tree.
--
type Cache a = [(ForestStoreIter, Forest a)]
-- | Create a traversal structure that allows a pre-order traversal in linear
-- time.
--
* The returned structure points at the root of the first level which does n't
really exist , but serves to indicate that it is before the very first
-- node.
--
storeToCache :: Forest a -> Cache a
storeToCache [] = []
storeToCache forest = [(invalidIter, [Node root forest])]
where
root = error "ForestStore.storeToCache: accessed non-exitent root of tree"
-- | Extract the store from the cache data structure.
cacheToStore :: Cache a -> Forest a
cacheToStore [] = []
cacheToStore cache = case last cache of (_, [Node _ forest]) -> forest
-- | Advance the traversal structure to the given 'TreeIter'.
--
advanceCache :: Depth -> ForestStoreIter -> Cache a -> Cache a
advanceCache depth goal [] = []
advanceCache depth goal cache@((rootIter,_):_) =
moveToSameLevel 0 depth
where
moveToSameLevel pos [] = cache
moveToSameLevel pos (d:ds) =
let
goalIdx = getBitSlice goal pos d
curIdx = getBitSlice rootIter pos d
isNonZero pos d (ti,_) = getBitSlice ti pos d/=0
in
if goalIdx==curIdx then moveToSameLevel (pos+d) ds else
if goalIdx==0 then dropWhile (isNonZero pos d) cache else
if curIdx==0 then moveToChild pos (d:ds) cache else
if goalIdx<curIdx then
moveToChild pos (d:ds) (dropWhile (isNonZero pos d) cache)
else let
-- advance the current iterator to coincide with the goal iterator
-- at this level
moveWithinLevel pos d ((ti,forest):parents) = let
diff = fromIntegral (goalIdx-curIdx)
(dropped, remain) = splitAt diff forest
advance = length dropped
ti' = setBitSlice ti pos d (curIdx+fromIntegral advance)
in
if advance==diff then moveToChild (pos+d) ds ((ti',remain):parents)
else (ti',remain):parents -- node not found
in moveWithinLevel pos d $ case ds of
[] -> cache
(d':_) -> dropWhile (isNonZero (pos+d) d') cache
-- Descend into the topmost forest to find the goal iterator. The position
and the remainding depths specify the index in the cache that is zero .
-- All indices in front of pos coincide with that of the goal iterator.
moveToChild :: Int -> Depth -> Cache a -> Cache a
moveToChild pos [] cache = cache -- we can't set more than the leaf
moveToChild pos (d:ds) cache@((ti,forest):parents)
| getBitSlice goal pos d == 0 = cache
| otherwise = case forest of
[] -> cache -- impossible request
Node { subForest = children }:_ ->
let
childIdx :: Int
childIdx = fromIntegral (getBitSlice goal pos d)-1
(dropped, remain) = splitAt childIdx children
advanced = length dropped
ti' = setBitSlice ti pos d (fromIntegral advanced+1)
in if advanced<childIdx then ((ti',remain):cache) else
moveToChild (pos+d) ds ((ti',remain):cache)
-- | Advance to the given iterator and return weather this was successful.
--
checkSuccess :: Depth -> ForestStoreIter -> Cache a -> (Bool, Cache a)
checkSuccess depth iter cache = case advanceCache depth iter cache of
cache'@((cur,sibs):_) -> (cmp cur iter && not (null sibs), cache')
[] -> (False, [])
where
cmp (ForestStoreIter _ a1 b1 c1) (ForestStoreIter _ a2 b2 c2) =
a1==a2 && b1==b2 && c2==c2
-- | Get the leaf index of this iterator.
--
-- * Due to the way we construct the 'TreeIter's, we can check which the last
level of an iterator is : The bit sequence of level n is zero if n is
-- greater or equal to the level that the iterator refers to. The returned
triple is ( pos , leaf , zero ) such that pos .. pos+leaf denotes the leaf
index and pos+leaf .. pos+leaf+zero denotes the bit field that is zero .
--
getTreeIterLeaf :: Depth -> ForestStoreIter -> (Int, Int, Int)
getTreeIterLeaf ds ti = gTIL 0 0 ds
where
gTIL pos dCur (dNext:ds)
| getBitSlice ti (pos+dCur) dNext==0 = (pos,dCur,dNext)
| otherwise = gTIL (pos+dCur) dNext ds
gTIL pos d [] = (pos, d, 0)
-- | Move an iterator forwards on the same level.
--
iterNext :: Depth -> ForestStoreIter -> Cache a -> (Maybe ForestStoreIter, Cache a)
iterNext depth iter cache = let
(pos,leaf,_child) = getTreeIterLeaf depth iter
curIdx = getBitSlice iter pos leaf
nextIdx = curIdx+1
nextIter = setBitSlice iter pos leaf nextIdx
in
if nextIdx==bit leaf then (Nothing, cache) else
case checkSuccess depth nextIter cache of
(True, cache) -> (Just nextIter, cache)
(False, cache) -> (Nothing, cache)
-- | Move down to the child of the given iterator.
--
iterNthChild :: Depth -> Int -> ForestStoreIter -> Cache a ->
(Maybe ForestStoreIter, Cache a)
iterNthChild depth childIdx_ iter cache = let
(pos,leaf,child) = getTreeIterLeaf depth iter
childIdx = fromIntegral childIdx_+1
nextIter = setBitSlice iter (pos+leaf) child childIdx
in
if childIdx>=bit child then (Nothing, cache) else
case checkSuccess depth nextIter cache of
(True, cache) -> (Just nextIter, cache)
(False, cache) -> (Nothing, cache)
| Descend to the first child .
--
iterNChildren :: Depth -> ForestStoreIter -> Cache a -> (Int, Cache a)
iterNChildren depth iter cache = case checkSuccess depth iter cache of
(True, cache@((_,Node { subForest = forest}:_):_)) -> (length forest, cache)
(_, cache) -> (0, cache)
-- | Ascend to parent.
--
iterParent :: Depth -> ForestStoreIter -> Maybe ForestStoreIter
iterParent depth iter = let
(pos,leaf,_child) = getTreeIterLeaf depth iter
in if pos==0 then Nothing else
if getBitSlice iter pos leaf==0 then Nothing else
Just (setBitSlice iter pos leaf 0)
-- | Insert nodes into the store.
--
-- * The given list of nodes is inserted into given parent at @pos@.
-- If the parent existed, the function returns @Just path@ where @path@
is the position of the newly inserted elements . If @pos@ is negative
or greater or equal to the number of children of the node at @path@ ,
-- the new nodes are appended to the list.
--
forestStoreInsertForest :: MonadIO m
=> ForestStore a -- ^ the store
-> TreePath -- ^ @path@ - the position of the parent
-> Int -- ^ @pos@ - the index of the new tree
-> Forest a -- ^ the list of trees to be inserted
-> m ()
forestStoreInsertForest (ForestStore model) path pos nodes = liftIO $ do
ipath <- treePathGetIndices' path
customStoreInvalidateIters $ CustomStore model
(idx, toggle) <- atomicModifyIORef (customStoreGetPrivate $ CustomStore model) $
\store@Store { depth = d, content = cache } ->
case insertIntoForest (cacheToStore cache) nodes ipath pos of
Nothing -> error ("forestStoreInsertForest: path does not exist " ++ show ipath)
Just (newForest, idx, toggle) ->
let depth = calcForestDepth newForest
in (Store { depth = depth,
content = storeToCache newForest },
(idx, toggle))
Store { depth = depth } <- readIORef (customStoreGetPrivate $ CustomStore model)
let rpath = reverse ipath
stamp <- customStoreGetStamp $ CustomStore model
sequence_ [ let p' = reverse p
Just iter = fromPath depth p'
in do
p'' <- treePathNewFromIndices' p'
treeModelRowInserted (CustomStore model) p'' =<< fromForestStoreIter (forestStoreIterSetStamp iter stamp)
| (i, node) <- zip [idx..] nodes
, p <- paths (fromIntegral i : rpath) node ]
let Just iter = fromPath depth ipath
when toggle $ treeModelRowHasChildToggled (CustomStore model) path
=<< fromForestStoreIter (forestStoreIterSetStamp iter stamp)
where paths :: [Int32] -> Tree a -> [[Int32]]
paths path Node { subForest = ts } =
path : concat [ paths (n:path) t | (n, t) <- zip [0..] ts ]
-- | Insert a node into the store.
--
forestStoreInsertTree :: MonadIO m
=> ForestStore a -- ^ the store
-> TreePath -- ^ @path@ - the position of the parent
-> Int -- ^ @pos@ - the index of the new tree
-> Tree a -- ^ the value to be inserted
-> m ()
forestStoreInsertTree store path pos node =
forestStoreInsertForest store path pos [node]
-- | Insert a single node into the store.
--
-- * This function inserts a single node without children into the tree.
-- Its arguments are similar to those of 'forestStoreInsert'.
--
forestStoreInsert :: MonadIO m
=> ForestStore a -- ^ the store
-> TreePath -- ^ @path@ - the position of the parent
-> Int -- ^ @pos@ - the index of the new tree
-> a -- ^ the value to be inserted
-> m ()
forestStoreInsert store path pos node =
forestStoreInsertForest store path pos [Node node []]
-- | Insert nodes into a forest.
--
-- * If the parent was found, returns the new tree, the child number
and a flag denoting if these new nodes were the first children
-- of the parent.
--
insertIntoForest :: Forest a -> Forest a -> [Int32] -> Int ->
Maybe (Forest a, Int, Bool)
insertIntoForest forest nodes [] pos
| pos<0 = Just (forest++nodes, length forest, null forest)
| otherwise = Just (prev++nodes++next, length prev, null forest)
where (prev, next) = splitAt pos forest
insertIntoForest forest nodes (p:ps) pos = case splitAt (fromIntegral p) forest of
(prev, []) -> Nothing
(prev, Node { rootLabel = val,
subForest = for}:next) ->
case insertIntoForest for nodes ps pos of
Nothing -> Nothing
Just (for, pos, toggle) -> Just (prev++Node { rootLabel = val,
subForest = for }:next,
pos, toggle)
-- | Remove a node from the store.
--
-- * The node denoted by the path is removed, along with all its children.
The function returns @True@ if the given node was found .
--
forestStoreRemove :: MonadIO m => ForestStore a -> TreePath -> m Bool
forestStoreRemove model path = treePathGetIndices' path >>= forestStoreRemoveImpl model path
forestStoreRemoveImpl :: MonadIO m => ForestStore a -> TreePath -> [Int32] -> m Bool
--TODO: eliminate this special case without segfaulting!
forestStoreRemoveImpl (ForestStore model) _ [] = return False
forestStoreRemoveImpl (ForestStore model) path ipath = liftIO $ do
customStoreInvalidateIters (CustomStore model)
(found, toggle) <- atomicModifyIORef (customStoreGetPrivate (CustomStore model)) $
\store@Store { depth = d, content = cache } ->
if null cache then (store, (False, False)) else
case deleteFromForest (cacheToStore cache) ipath of
Nothing -> (store, (False, False))
Just (newForest, toggle) ->
(Store { depth = d, -- this might be a space leak
content = storeToCache newForest }, (True, toggle))
when found $ do
when (toggle && not (null ipath)) $ do
Store { depth = depth } <- readIORef (customStoreGetPrivate (CustomStore model))
let iparent = init ipath
Just iter = fromPath depth iparent
parent <- treePathNewFromIndices' iparent
treeModelRowHasChildToggled (CustomStore model) parent =<< fromForestStoreIter iter
treeModelRowDeleted (CustomStore model) path
return found
forestStoreClear :: MonadIO m => ForestStore a -> m ()
forestStoreClear (ForestStore model) = liftIO $ do
customStoreInvalidateIters (CustomStore model)
Store { content = cache } <- readIORef (customStoreGetPrivate (CustomStore model))
let forest = cacheToStore cache
writeIORef (customStoreGetPrivate (CustomStore model)) Store {
depth = calcForestDepth [],
content = storeToCache []
}
let loop (-1) = return ()
loop n = treePathNewFromIndices' [fromIntegral n] >>= treeModelRowDeleted (CustomStore model) >> loop (n-1)
loop (length forest - 1)
-- | Remove a node from a rose tree.
--
-- * Returns the new tree if the node was found. The returned flag is
@True@ if deleting the node left the parent without any children .
--
deleteFromForest :: Forest a -> [Int32] -> Maybe (Forest a, Bool)
deleteFromForest forest [] = Just ([], False)
deleteFromForest forest (p:ps) =
case splitAt (fromIntegral p) forest of
(prev, kill@Node { rootLabel = val,
subForest = for}:next) ->
if null ps then Just (prev++next, null prev && null next) else
case deleteFromForest for ps of
Nothing -> Nothing
Just (for,toggle) -> Just (prev++Node {rootLabel = val,
subForest = for }:next, toggle)
(prev, []) -> Nothing
-- | Set a node in the store.
--
forestStoreSetValue :: MonadIO m => ForestStore a -> TreePath -> a -> m ()
forestStoreSetValue store path value = forestStoreChangeM store path (\_ -> return value)
>> return ()
-- | Change a node in the store.
--
* Returns if the node was found . For a monadic version , see
-- 'forestStoreChangeM'.
--
forestStoreChange :: MonadIO m => ForestStore a -> TreePath -> (a -> a) -> m Bool
forestStoreChange store path func = forestStoreChangeM store path (return . func)
-- | Change a node in the store.
--
* Returns if the node was found . For a purely functional version , see
-- 'forestStoreChange'.
--
forestStoreChangeM :: MonadIO m => ForestStore a -> TreePath -> (a -> m a) -> m Bool
forestStoreChangeM (ForestStore model) path act = do
ipath <- treePathGetIndices' path
customStoreInvalidateIters (CustomStore model)
store@Store { depth = d, content = cache } <-
liftIO $ readIORef (customStoreGetPrivate (CustomStore model))
(store'@Store { depth = d, content = cache }, found) <- do
mRes <- changeForest (cacheToStore cache) act ipath
return $ case mRes of
Nothing -> (store, False)
Just newForest -> (Store { depth = d,
content = storeToCache newForest }, True)
liftIO $ writeIORef (customStoreGetPrivate (CustomStore model)) store'
let Just iter = fromPath d ipath
stamp <- customStoreGetStamp (CustomStore model)
when found $ treeModelRowChanged (CustomStore model) path =<< fromForestStoreIter (forestStoreIterSetStamp iter stamp)
return found
-- | Change a node in the forest.
--
* Returns if the given node was found .
--
changeForest :: MonadIO m => Forest a -> (a -> m a) -> [Int32] -> m (Maybe (Forest a))
changeForest forest act [] = return Nothing
changeForest forest act (p:ps) = case splitAt (fromIntegral p) forest of
(prev, []) -> return Nothing
(prev, Node { rootLabel = val,
subForest = for}:next) ->
if null ps then do
val' <- act val
return (Just (prev++Node { rootLabel = val',
subForest = for }:next))
else do
mFor <- changeForest for act ps
case mFor of
Nothing -> return Nothing
Just for -> return $ Just (prev++Node { rootLabel = val,
subForest = for }:next)
| Extract one node from the current model . Fails if the given
-- 'TreePath' refers to a non-existent node.
--
forestStoreGetValue :: (Applicative m, MonadIO m) => ForestStore a -> TreePath -> m a
forestStoreGetValue model path = rootLabel <$> forestStoreGetTree model path
-- | Extract a subtree from the current model. Fails if the given
-- 'TreePath' refers to a non-existent node.
--
forestStoreGetTree :: MonadIO m => ForestStore a -> TreePath -> m (Tree a)
forestStoreGetTree (ForestStore model) path = liftIO $ do
ipath <- treePathGetIndices' path
store@Store { depth = d, content = cache } <-
readIORef (customStoreGetPrivate (CustomStore model))
case fromPath d ipath of
(Just iter) -> do
let (res, cache') = checkSuccess d iter cache
writeIORef (customStoreGetPrivate (CustomStore model)) store { content = cache' }
case cache' of
((_,node:_):_) | res -> return node
_ -> fail ("forestStoreGetTree: path does not exist " ++ show ipath)
_ -> fail ("forestStoreGetTree: path does not exist " ++ show ipath)
-- | Extract the forest from the current model.
--
forestStoreGetForest :: MonadIO m => ForestStore a -> m (Forest a)
forestStoreGetForest (ForestStore model) = liftIO $ do
store@Store { depth = d, content = cache } <-
readIORef (customStoreGetPrivate (CustomStore model))
return $ cacheToStore cache
-- | Extract a subtree from the current model. Like 'forestStoreGetTree'
-- but returns @Nothing@ if the path refers to a non-existant node.
--
forestStoreLookup :: MonadIO m => ForestStore a -> TreePath -> m (Maybe (Tree a))
forestStoreLookup (ForestStore model) path = liftIO $ do
ipath <- treePathGetIndices' path
store@Store { depth = d, content = cache } <-
readIORef (customStoreGetPrivate (CustomStore model))
case fromPath d ipath of
(Just iter) -> do
let (res, cache') = checkSuccess d iter cache
writeIORef (customStoreGetPrivate (CustomStore model)) store { content = cache' }
case cache' of
((_,node:_):_) | res -> return (Just node)
_ -> return Nothing
_ -> return Nothing
| null | https://raw.githubusercontent.com/haskell-gi/haskell-gi/bff8f3b92bf2594ea3d6745c346a8de594fc3709/gi-gtk-hs/src/Data/GI/Gtk/ModelView/ForestStore.hs | haskell | -*-haskell-*-
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.
|
Stability : provisional
Standard model to store hierarchical data.
* Types
* Constructors
* Implementation of Interfaces
* Methods
------------------------------------------
internal model data types
| A store for hierarchical data.
| Maximum number of nodes on each level.
* These numbers determine how many bits in a 'TreeIter' are devoted to
each level. Hence, these numbers reflect log2 of the maximum number
of nodes at a level, rounded up.
| Create a new list store.
* The given rose tree determines the initial content and may be the empty
* Additionally, a cache is used to achieve higher performance if operating on
recently used TreePaths.
* __Note:__ due to the limited amount of bits available in TreeIter storage, only
limited depth forests can be used with this implementation, the result of too deep
Forests is an undefined behaviour while trying to retrieve the deeply nested nodes.
any further levels in a TreePath will not be encoded in the corresponding TreeIter
storage.
| Create a new list store.
to implement user-defined drag-and-drop functionality.
^ the inital tree stored in this model
^ an optional interface for drags
^ an optional interface to handle drops
| Default drag functions for
'Data.GI.Gtk.ModelView.ForestStore'. These functions allow the rows of
the model to serve as drag source. Any row is allowed to be dragged and the
data set in the 'SelectionDataM' object is set with 'treeSetRowDragData',
i.e. it contains the model and the 'TreePath' to the row.
| Default drop functions for 'Data.GI.Gtk.ModelView.ForestStore'. These
functions accept a row and insert the row into the new location if it is
dragged into a tree view
that uses the same model.
------------------------------------------
low level bit-twiddling utility functions
iterPrefixEqual :: TreeIter -> TreeIter -> Int -> Bool
iterPrefixEqual (TreeIter _ a1 b1 c1) (TreeIter _ a2 b2 c2) pos
(a1 .&. mask) == (a2 .&. mask)
| The invalid tree iterator.
showIterBits (TreeIter _ a b c) = [showBits a, showBits b, showBits c]
showBits :: Bits a => a -> String
showBits a = [ if testBit a i then '1' else '0' | i <- [0..bitSize a - 1] ]
| Calculate the maximum number of nodes on a per-level basis.
| Convert an iterator into a path.
| Try to convert a path into a 'TreeIter'.
| The 'Cache' type synonym is only used iternally. What it represents
the stack during a (fictional) lookup operations.
The topmost frame is the node
for which this lookup was started and the innermost frame (the last
element of the list) contains the root of the tree.
| Create a traversal structure that allows a pre-order traversal in linear
time.
node.
| Extract the store from the cache data structure.
| Advance the traversal structure to the given 'TreeIter'.
advance the current iterator to coincide with the goal iterator
at this level
node not found
Descend into the topmost forest to find the goal iterator. The position
All indices in front of pos coincide with that of the goal iterator.
we can't set more than the leaf
impossible request
| Advance to the given iterator and return weather this was successful.
| Get the leaf index of this iterator.
* Due to the way we construct the 'TreeIter's, we can check which the last
greater or equal to the level that the iterator refers to. The returned
| Move an iterator forwards on the same level.
| Move down to the child of the given iterator.
| Ascend to parent.
| Insert nodes into the store.
* The given list of nodes is inserted into given parent at @pos@.
If the parent existed, the function returns @Just path@ where @path@
the new nodes are appended to the list.
^ the store
^ @path@ - the position of the parent
^ @pos@ - the index of the new tree
^ the list of trees to be inserted
| Insert a node into the store.
^ the store
^ @path@ - the position of the parent
^ @pos@ - the index of the new tree
^ the value to be inserted
| Insert a single node into the store.
* This function inserts a single node without children into the tree.
Its arguments are similar to those of 'forestStoreInsert'.
^ the store
^ @path@ - the position of the parent
^ @pos@ - the index of the new tree
^ the value to be inserted
| Insert nodes into a forest.
* If the parent was found, returns the new tree, the child number
of the parent.
| Remove a node from the store.
* The node denoted by the path is removed, along with all its children.
TODO: eliminate this special case without segfaulting!
this might be a space leak
| Remove a node from a rose tree.
* Returns the new tree if the node was found. The returned flag is
| Set a node in the store.
| Change a node in the store.
'forestStoreChangeM'.
| Change a node in the store.
'forestStoreChange'.
| Change a node in the forest.
'TreePath' refers to a non-existent node.
| Extract a subtree from the current model. Fails if the given
'TreePath' refers to a non-existent node.
| Extract the forest from the current model.
| Extract a subtree from the current model. Like 'forestStoreGetTree'
but returns @Nothing@ if the path refers to a non-existant node.
| # LANGUAGE CPP #
# LANGUAGE TypeFamilies #
# LANGUAGE DataKinds #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
GIMP Toolkit ( GTK ) CustomStore TreeModel
Author : ,
Created : 11 Feburary 2006
Copyright ( C ) 2005 - 2016 , ,
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 Data.GI.Gtk.ModelView.ForestStore (
ForestStore(..),
forestStoreNew,
forestStoreNewDND,
forestStoreDefaultDragSourceIface,
forestStoreDefaultDragDestIface,
forestStoreGetValue,
forestStoreGetTree,
forestStoreGetForest,
forestStoreLookup,
forestStoreSetValue,
forestStoreInsert,
forestStoreInsertTree,
forestStoreInsertForest,
forestStoreRemove,
forestStoreClear,
forestStoreChange,
forestStoreChangeM,
) where
import Prelude ()
import Prelude.Compat
import Data.Bits
import Data.Word (Word32)
import Data.Int (Int32)
import Data.Maybe ( fromMaybe, isJust )
import Data.Tree
import Control.Monad ((>=>), when)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Exception (assert)
import Data.IORef
import Foreign.ForeignPtr (ForeignPtr)
import Data.GI.Base.BasicTypes
(TypedObject(..), ManagedPtr(..), GObject)
import Data.GI.Base.ManagedPtr (withManagedPtr)
import Data.GI.Base.Overloading (HasParentTypes, ParentTypes)
import Data.GI.Gtk.ModelView.Types
import Data.GI.Gtk.ModelView.CustomStore
(customStoreGetStamp, customStoreGetPrivate,
TreeModelIface(..), customStoreNew, DragDestIface(..),
DragSourceIface(..), CustomStore(..), customStoreInvalidateIters)
import GI.GObject.Objects.Object (Object(..))
import GI.Gtk.Interfaces.TreeModel
(treeModelRowDeleted, treeModelRowInserted,
treeModelRowChanged, toTreeModel, TreeModel(..), IsTreeModel(..),
treeModelRowHasChildToggled)
import GI.Gtk.Functions (treeSetRowDragData, treeGetRowDragData)
import GI.Gtk.Structs.TreePath
(TreePath)
import GI.Gtk.Structs.TreeIter
(getTreeIterUserData3, getTreeIterUserData2, getTreeIterUserData,
getTreeIterStamp, setTreeIterUserData3, setTreeIterUserData2,
setTreeIterUserData, setTreeIterStamp, TreeIter(..))
import Data.GI.Base (get, new)
import Unsafe.Coerce (unsafeCoerce)
data ForestStoreIter = ForestStoreIter Int32 Word32 Word32 Word32
fromForestStoreIter :: MonadIO m => ForestStoreIter -> m TreeIter
fromForestStoreIter (ForestStoreIter s u1 u2 u3) = do
i <- new TreeIter []
setTreeIterStamp i s
setTreeIterUserData i $ unsafeCoerce u1
setTreeIterUserData2 i $ unsafeCoerce u2
setTreeIterUserData3 i $ unsafeCoerce u3
return i
toForestStoreIter :: MonadIO m => TreeIter -> m ForestStoreIter
toForestStoreIter iter = do
stamp <- getTreeIterStamp iter
u1 <- getTreeIterUserData iter
u2 <- getTreeIterUserData2 iter
u3 <- getTreeIterUserData3 iter
return $ ForestStoreIter stamp (unsafeCoerce u1) (unsafeCoerce u2) (unsafeCoerce u3)
forestStoreIterSetStamp :: ForestStoreIter -> Int32 -> ForestStoreIter
forestStoreIterSetStamp (ForestStoreIter _ a b c) s = ForestStoreIter s a b c
newtype ForestStore a = ForestStore (ManagedPtr (CustomStore (IORef (Store a)) a))
mkForestStore :: CustomStore (IORef (Store a)) a -> ForestStore a
mkForestStore (CustomStore ptr) = ForestStore ptr
instance HasParentTypes (ForestStore a)
type instance ParentTypes (ForestStore a) = '[TreeModel]
instance TypedObject (ForestStore a) where
glibType = glibType @TreeModel
instance GObject (ForestStore a)
instance IsTypedTreeModel ForestStore
type Depth = [Int]
data Store a = Store {
depth :: Depth,
content :: Cache a
}
list . Each ' Tree ' in the forest corresponds to one top - level node .
* The ForestStore maintains the initially given Forest and aligns the ' TreePath '
bits to fit in 96 - bit length ' TreeIter ' storage .
For example : assuming the average requiement is 8 bits per tree level ( max number of
children at the level is 255 ) , then we can only use 12 levels deep trees ( 96/8 ) -
forestStoreNew :: MonadIO m => Forest a -> m (ForestStore a)
forestStoreNew forest = forestStoreNewDND forest
(Just forestStoreDefaultDragSourceIface)
(Just forestStoreDefaultDragDestIface)
* In addition to ' forestStoreNew ' , this function takes an two interfaces
-> m (ForestStore a)
forestStoreNewDND forest mDSource mDDest = liftIO $ do
(storeRef :: IORef (Store a)) <- newIORef Store {
depth = calcForestDepth forest,
content = storeToCache forest
}
let withStore :: (Store a -> IO result) -> IO result
withStore f = readIORef storeRef >>= f
withStoreUpdateCache :: (Store a -> (result, Cache a)) -> IO result
withStoreUpdateCache f = do
store <- readIORef storeRef
let (result, cache') = f store
writeIORef storeRef store { content = cache' }
return result
customStoreNew storeRef mkForestStore TreeModelIface {
treeModelIfaceGetFlags = return [],
treeModelIfaceGetIter = \path -> withStore $
\Store { depth = d } -> fromPath d <$> treePathGetIndices' path >>= mapM fromForestStoreIter,
treeModelIfaceGetPath = toForestStoreIter >=> \iter -> withStore $
\Store { depth = d } -> treePathNewFromIndices' $ toPath d iter,
treeModelIfaceGetRow = toForestStoreIter >=> \iter -> withStoreUpdateCache $
\Store { depth = d, content = cache } ->
case checkSuccess d iter cache of
(True, cache'@((_, (Node { rootLabel = val }:_)):_)) ->
(val, cache')
_ -> error "ForestStore.getRow: iter does not refer to a valid entry",
treeModelIfaceIterNext = toForestStoreIter >=> \iter -> withStoreUpdateCache (
\Store { depth = d, content = cache } -> iterNext d iter cache) >>= mapM fromForestStoreIter,
treeModelIfaceIterChildren = \mIter -> do
iter <- maybe (return invalidIter) toForestStoreIter mIter
withStoreUpdateCache (
\Store { depth = d, content = cache } ->
iterNthChild d 0 iter cache) >>= mapM fromForestStoreIter,
treeModelIfaceIterHasChild = toForestStoreIter >=> \iter -> withStoreUpdateCache $
\Store { depth = d, content = cache } ->
let (mIter, cache') = iterNthChild d 0 iter cache
in (isJust mIter, cache'),
treeModelIfaceIterNChildren = mapM toForestStoreIter >=> \mIter -> withStoreUpdateCache $
\Store { depth = d, content = cache } ->
let iter = fromMaybe invalidIter mIter
in iterNChildren d iter cache,
treeModelIfaceIterNthChild = \mIter idx -> do
iter <- maybe (return invalidIter) toForestStoreIter mIter
withStoreUpdateCache (
\Store { depth = d, content = cache } ->
iterNthChild d idx iter cache) >>= mapM fromForestStoreIter,
treeModelIfaceIterParent = toForestStoreIter >=> \iter -> withStore $
\Store { depth = d } -> mapM fromForestStoreIter (iterParent d iter),
treeModelIfaceRefNode = \_ -> return (),
treeModelIfaceUnrefNode = \_ -> return ()
} mDSource mDDest
forestStoreDefaultDragSourceIface :: DragSourceIface ForestStore row
forestStoreDefaultDragSourceIface = DragSourceIface {
customDragSourceRowDraggable = \_ _-> return True,
customDragSourceDragDataGet = \model path sel -> treeSetRowDragData sel model path,
customDragSourceDragDataDelete = \model path -> treePathGetIndices' path >>= \dest@(_:_) -> do
liftIO $ forestStoreRemove model path
return True
}
forestStoreDefaultDragDestIface :: DragDestIface ForestStore row
forestStoreDefaultDragDestIface = DragDestIface {
customDragDestRowDropPossible = \model path sel -> do
mModelPath <- treeGetRowDragData sel
case mModelPath of
(True, Just model', source) -> do
tm <- toTreeModel model
withManagedPtr tm $ \m ->
withManagedPtr model' $ \m' -> return (m==m')
_ -> return False,
customDragDestDragDataReceived = \model path sel -> do
dest@(_:_) <- treePathGetIndices' path
mModelPath <- treeGetRowDragData sel
case mModelPath of
(True, Just model', Just path) -> do
source@(_:_) <- treePathGetIndices' path
tm <- toTreeModel model
withManagedPtr tm $ \m ->
withManagedPtr model' $ \m' ->
if m/=m' then return False
else do
row <- forestStoreGetTree model =<< treePathNewFromIndices' source
initPath <- treePathNewFromIndices' (init dest)
forestStoreInsertTree model initPath (fromIntegral $ last dest) row
return True
_ -> return False
}
bitsNeeded :: Word32 -> Int
bitsNeeded n = bitsNeeded' 0 n
where bitsNeeded' b 0 = b
bitsNeeded' b n = bitsNeeded' (b+1) (n `shiftR` 1)
getBitSlice :: ForestStoreIter -> Int -> Int -> Word32
getBitSlice (ForestStoreIter _ a b c) off count =
getBitSliceWord a off count
.|. getBitSliceWord b (off-32) count
.|. getBitSliceWord c (off-64) count
where getBitSliceWord :: Word32 -> Int -> Int -> Word32
getBitSliceWord word off count =
word `shift` (-off) .&. (1 `shiftL` count - 1)
setBitSlice :: ForestStoreIter -> Int -> Int -> Word32 -> ForestStoreIter
setBitSlice (ForestStoreIter stamp a b c) off count value =
assert (value < 1 `shiftL` count) $
ForestStoreIter stamp
(setBitSliceWord a off count value)
(setBitSliceWord b (off-32) count value)
(setBitSliceWord c (off-64) count value)
where setBitSliceWord :: Word32 -> Int -> Int -> Word32 -> Word32
setBitSliceWord word off count value =
let mask = (1 `shiftL` count - 1) `shift` off
in (word .&. complement mask) .|. (value `shift` off)
| pos>64 = let mask = 1 ` shiftL ` ( pos-64 ) - 1 in
a1==a2 & & b1==b2 & & ( c1 . & . mask ) = = ( c2 . & . mask )
| pos>32 = let mask = 1 ` shiftL ` ( pos-32 ) - 1 in
a1==a2 & & ( b1 . & . mask ) = = ( b2 . & . mask )
| otherwise = let mask = 1 ` shiftL ` pos - 1 in
invalidIter :: ForestStoreIter
invalidIter = ForestStoreIter 0 0 0 0
calcForestDepth :: Forest a -> Depth
calcForestDepth f = map bitsNeeded $
takeWhile (/=0) $
foldr calcTreeDepth (repeat 0) f
where
calcTreeDepth Node { subForest = f } (d:ds) =
(d+1): zipWith max ds (foldr calcTreeDepth (repeat 0) f)
toPath :: Depth -> ForestStoreIter -> [Int32]
toPath d iter = gP 0 d
where
gP pos [] = []
gP pos (d:ds) = let idx = getBitSlice iter pos d in
if idx==0 then [] else fromIntegral (idx-1) : gP (pos+d) ds
fromPath :: Depth -> [Int32] -> Maybe ForestStoreIter
fromPath = fP 0 invalidIter
where
the remaining bits are zero anyway
fP pos ti [] _ = Nothing
fP pos ti (d:ds) (p:ps) = let idx = fromIntegral (p+1) in
if idx >= bit d then Nothing else
fP (pos+d) (setBitSlice ti pos d idx) ds ps
type Cache a = [(ForestStoreIter, Forest a)]
* The returned structure points at the root of the first level which does n't
really exist , but serves to indicate that it is before the very first
storeToCache :: Forest a -> Cache a
storeToCache [] = []
storeToCache forest = [(invalidIter, [Node root forest])]
where
root = error "ForestStore.storeToCache: accessed non-exitent root of tree"
cacheToStore :: Cache a -> Forest a
cacheToStore [] = []
cacheToStore cache = case last cache of (_, [Node _ forest]) -> forest
advanceCache :: Depth -> ForestStoreIter -> Cache a -> Cache a
advanceCache depth goal [] = []
advanceCache depth goal cache@((rootIter,_):_) =
moveToSameLevel 0 depth
where
moveToSameLevel pos [] = cache
moveToSameLevel pos (d:ds) =
let
goalIdx = getBitSlice goal pos d
curIdx = getBitSlice rootIter pos d
isNonZero pos d (ti,_) = getBitSlice ti pos d/=0
in
if goalIdx==curIdx then moveToSameLevel (pos+d) ds else
if goalIdx==0 then dropWhile (isNonZero pos d) cache else
if curIdx==0 then moveToChild pos (d:ds) cache else
if goalIdx<curIdx then
moveToChild pos (d:ds) (dropWhile (isNonZero pos d) cache)
else let
moveWithinLevel pos d ((ti,forest):parents) = let
diff = fromIntegral (goalIdx-curIdx)
(dropped, remain) = splitAt diff forest
advance = length dropped
ti' = setBitSlice ti pos d (curIdx+fromIntegral advance)
in
if advance==diff then moveToChild (pos+d) ds ((ti',remain):parents)
in moveWithinLevel pos d $ case ds of
[] -> cache
(d':_) -> dropWhile (isNonZero (pos+d) d') cache
and the remainding depths specify the index in the cache that is zero .
moveToChild :: Int -> Depth -> Cache a -> Cache a
moveToChild pos (d:ds) cache@((ti,forest):parents)
| getBitSlice goal pos d == 0 = cache
| otherwise = case forest of
Node { subForest = children }:_ ->
let
childIdx :: Int
childIdx = fromIntegral (getBitSlice goal pos d)-1
(dropped, remain) = splitAt childIdx children
advanced = length dropped
ti' = setBitSlice ti pos d (fromIntegral advanced+1)
in if advanced<childIdx then ((ti',remain):cache) else
moveToChild (pos+d) ds ((ti',remain):cache)
checkSuccess :: Depth -> ForestStoreIter -> Cache a -> (Bool, Cache a)
checkSuccess depth iter cache = case advanceCache depth iter cache of
cache'@((cur,sibs):_) -> (cmp cur iter && not (null sibs), cache')
[] -> (False, [])
where
cmp (ForestStoreIter _ a1 b1 c1) (ForestStoreIter _ a2 b2 c2) =
a1==a2 && b1==b2 && c2==c2
level of an iterator is : The bit sequence of level n is zero if n is
triple is ( pos , leaf , zero ) such that pos .. pos+leaf denotes the leaf
index and pos+leaf .. pos+leaf+zero denotes the bit field that is zero .
getTreeIterLeaf :: Depth -> ForestStoreIter -> (Int, Int, Int)
getTreeIterLeaf ds ti = gTIL 0 0 ds
where
gTIL pos dCur (dNext:ds)
| getBitSlice ti (pos+dCur) dNext==0 = (pos,dCur,dNext)
| otherwise = gTIL (pos+dCur) dNext ds
gTIL pos d [] = (pos, d, 0)
iterNext :: Depth -> ForestStoreIter -> Cache a -> (Maybe ForestStoreIter, Cache a)
iterNext depth iter cache = let
(pos,leaf,_child) = getTreeIterLeaf depth iter
curIdx = getBitSlice iter pos leaf
nextIdx = curIdx+1
nextIter = setBitSlice iter pos leaf nextIdx
in
if nextIdx==bit leaf then (Nothing, cache) else
case checkSuccess depth nextIter cache of
(True, cache) -> (Just nextIter, cache)
(False, cache) -> (Nothing, cache)
iterNthChild :: Depth -> Int -> ForestStoreIter -> Cache a ->
(Maybe ForestStoreIter, Cache a)
iterNthChild depth childIdx_ iter cache = let
(pos,leaf,child) = getTreeIterLeaf depth iter
childIdx = fromIntegral childIdx_+1
nextIter = setBitSlice iter (pos+leaf) child childIdx
in
if childIdx>=bit child then (Nothing, cache) else
case checkSuccess depth nextIter cache of
(True, cache) -> (Just nextIter, cache)
(False, cache) -> (Nothing, cache)
| Descend to the first child .
iterNChildren :: Depth -> ForestStoreIter -> Cache a -> (Int, Cache a)
iterNChildren depth iter cache = case checkSuccess depth iter cache of
(True, cache@((_,Node { subForest = forest}:_):_)) -> (length forest, cache)
(_, cache) -> (0, cache)
iterParent :: Depth -> ForestStoreIter -> Maybe ForestStoreIter
iterParent depth iter = let
(pos,leaf,_child) = getTreeIterLeaf depth iter
in if pos==0 then Nothing else
if getBitSlice iter pos leaf==0 then Nothing else
Just (setBitSlice iter pos leaf 0)
is the position of the newly inserted elements . If @pos@ is negative
or greater or equal to the number of children of the node at @path@ ,
forestStoreInsertForest :: MonadIO m
-> m ()
forestStoreInsertForest (ForestStore model) path pos nodes = liftIO $ do
ipath <- treePathGetIndices' path
customStoreInvalidateIters $ CustomStore model
(idx, toggle) <- atomicModifyIORef (customStoreGetPrivate $ CustomStore model) $
\store@Store { depth = d, content = cache } ->
case insertIntoForest (cacheToStore cache) nodes ipath pos of
Nothing -> error ("forestStoreInsertForest: path does not exist " ++ show ipath)
Just (newForest, idx, toggle) ->
let depth = calcForestDepth newForest
in (Store { depth = depth,
content = storeToCache newForest },
(idx, toggle))
Store { depth = depth } <- readIORef (customStoreGetPrivate $ CustomStore model)
let rpath = reverse ipath
stamp <- customStoreGetStamp $ CustomStore model
sequence_ [ let p' = reverse p
Just iter = fromPath depth p'
in do
p'' <- treePathNewFromIndices' p'
treeModelRowInserted (CustomStore model) p'' =<< fromForestStoreIter (forestStoreIterSetStamp iter stamp)
| (i, node) <- zip [idx..] nodes
, p <- paths (fromIntegral i : rpath) node ]
let Just iter = fromPath depth ipath
when toggle $ treeModelRowHasChildToggled (CustomStore model) path
=<< fromForestStoreIter (forestStoreIterSetStamp iter stamp)
where paths :: [Int32] -> Tree a -> [[Int32]]
paths path Node { subForest = ts } =
path : concat [ paths (n:path) t | (n, t) <- zip [0..] ts ]
forestStoreInsertTree :: MonadIO m
-> m ()
forestStoreInsertTree store path pos node =
forestStoreInsertForest store path pos [node]
forestStoreInsert :: MonadIO m
-> m ()
forestStoreInsert store path pos node =
forestStoreInsertForest store path pos [Node node []]
and a flag denoting if these new nodes were the first children
insertIntoForest :: Forest a -> Forest a -> [Int32] -> Int ->
Maybe (Forest a, Int, Bool)
insertIntoForest forest nodes [] pos
| pos<0 = Just (forest++nodes, length forest, null forest)
| otherwise = Just (prev++nodes++next, length prev, null forest)
where (prev, next) = splitAt pos forest
insertIntoForest forest nodes (p:ps) pos = case splitAt (fromIntegral p) forest of
(prev, []) -> Nothing
(prev, Node { rootLabel = val,
subForest = for}:next) ->
case insertIntoForest for nodes ps pos of
Nothing -> Nothing
Just (for, pos, toggle) -> Just (prev++Node { rootLabel = val,
subForest = for }:next,
pos, toggle)
The function returns @True@ if the given node was found .
forestStoreRemove :: MonadIO m => ForestStore a -> TreePath -> m Bool
forestStoreRemove model path = treePathGetIndices' path >>= forestStoreRemoveImpl model path
forestStoreRemoveImpl :: MonadIO m => ForestStore a -> TreePath -> [Int32] -> m Bool
forestStoreRemoveImpl (ForestStore model) _ [] = return False
forestStoreRemoveImpl (ForestStore model) path ipath = liftIO $ do
customStoreInvalidateIters (CustomStore model)
(found, toggle) <- atomicModifyIORef (customStoreGetPrivate (CustomStore model)) $
\store@Store { depth = d, content = cache } ->
if null cache then (store, (False, False)) else
case deleteFromForest (cacheToStore cache) ipath of
Nothing -> (store, (False, False))
Just (newForest, toggle) ->
content = storeToCache newForest }, (True, toggle))
when found $ do
when (toggle && not (null ipath)) $ do
Store { depth = depth } <- readIORef (customStoreGetPrivate (CustomStore model))
let iparent = init ipath
Just iter = fromPath depth iparent
parent <- treePathNewFromIndices' iparent
treeModelRowHasChildToggled (CustomStore model) parent =<< fromForestStoreIter iter
treeModelRowDeleted (CustomStore model) path
return found
forestStoreClear :: MonadIO m => ForestStore a -> m ()
forestStoreClear (ForestStore model) = liftIO $ do
customStoreInvalidateIters (CustomStore model)
Store { content = cache } <- readIORef (customStoreGetPrivate (CustomStore model))
let forest = cacheToStore cache
writeIORef (customStoreGetPrivate (CustomStore model)) Store {
depth = calcForestDepth [],
content = storeToCache []
}
let loop (-1) = return ()
loop n = treePathNewFromIndices' [fromIntegral n] >>= treeModelRowDeleted (CustomStore model) >> loop (n-1)
loop (length forest - 1)
@True@ if deleting the node left the parent without any children .
deleteFromForest :: Forest a -> [Int32] -> Maybe (Forest a, Bool)
deleteFromForest forest [] = Just ([], False)
deleteFromForest forest (p:ps) =
case splitAt (fromIntegral p) forest of
(prev, kill@Node { rootLabel = val,
subForest = for}:next) ->
if null ps then Just (prev++next, null prev && null next) else
case deleteFromForest for ps of
Nothing -> Nothing
Just (for,toggle) -> Just (prev++Node {rootLabel = val,
subForest = for }:next, toggle)
(prev, []) -> Nothing
forestStoreSetValue :: MonadIO m => ForestStore a -> TreePath -> a -> m ()
forestStoreSetValue store path value = forestStoreChangeM store path (\_ -> return value)
>> return ()
* Returns if the node was found . For a monadic version , see
forestStoreChange :: MonadIO m => ForestStore a -> TreePath -> (a -> a) -> m Bool
forestStoreChange store path func = forestStoreChangeM store path (return . func)
* Returns if the node was found . For a purely functional version , see
forestStoreChangeM :: MonadIO m => ForestStore a -> TreePath -> (a -> m a) -> m Bool
forestStoreChangeM (ForestStore model) path act = do
ipath <- treePathGetIndices' path
customStoreInvalidateIters (CustomStore model)
store@Store { depth = d, content = cache } <-
liftIO $ readIORef (customStoreGetPrivate (CustomStore model))
(store'@Store { depth = d, content = cache }, found) <- do
mRes <- changeForest (cacheToStore cache) act ipath
return $ case mRes of
Nothing -> (store, False)
Just newForest -> (Store { depth = d,
content = storeToCache newForest }, True)
liftIO $ writeIORef (customStoreGetPrivate (CustomStore model)) store'
let Just iter = fromPath d ipath
stamp <- customStoreGetStamp (CustomStore model)
when found $ treeModelRowChanged (CustomStore model) path =<< fromForestStoreIter (forestStoreIterSetStamp iter stamp)
return found
* Returns if the given node was found .
changeForest :: MonadIO m => Forest a -> (a -> m a) -> [Int32] -> m (Maybe (Forest a))
changeForest forest act [] = return Nothing
changeForest forest act (p:ps) = case splitAt (fromIntegral p) forest of
(prev, []) -> return Nothing
(prev, Node { rootLabel = val,
subForest = for}:next) ->
if null ps then do
val' <- act val
return (Just (prev++Node { rootLabel = val',
subForest = for }:next))
else do
mFor <- changeForest for act ps
case mFor of
Nothing -> return Nothing
Just for -> return $ Just (prev++Node { rootLabel = val,
subForest = for }:next)
| Extract one node from the current model . Fails if the given
forestStoreGetValue :: (Applicative m, MonadIO m) => ForestStore a -> TreePath -> m a
forestStoreGetValue model path = rootLabel <$> forestStoreGetTree model path
forestStoreGetTree :: MonadIO m => ForestStore a -> TreePath -> m (Tree a)
forestStoreGetTree (ForestStore model) path = liftIO $ do
ipath <- treePathGetIndices' path
store@Store { depth = d, content = cache } <-
readIORef (customStoreGetPrivate (CustomStore model))
case fromPath d ipath of
(Just iter) -> do
let (res, cache') = checkSuccess d iter cache
writeIORef (customStoreGetPrivate (CustomStore model)) store { content = cache' }
case cache' of
((_,node:_):_) | res -> return node
_ -> fail ("forestStoreGetTree: path does not exist " ++ show ipath)
_ -> fail ("forestStoreGetTree: path does not exist " ++ show ipath)
forestStoreGetForest :: MonadIO m => ForestStore a -> m (Forest a)
forestStoreGetForest (ForestStore model) = liftIO $ do
store@Store { depth = d, content = cache } <-
readIORef (customStoreGetPrivate (CustomStore model))
return $ cacheToStore cache
forestStoreLookup :: MonadIO m => ForestStore a -> TreePath -> m (Maybe (Tree a))
forestStoreLookup (ForestStore model) path = liftIO $ do
ipath <- treePathGetIndices' path
store@Store { depth = d, content = cache } <-
readIORef (customStoreGetPrivate (CustomStore model))
case fromPath d ipath of
(Just iter) -> do
let (res, cache') = checkSuccess d iter cache
writeIORef (customStoreGetPrivate (CustomStore model)) store { content = cache' }
case cache' of
((_,node:_):_) | res -> return (Just node)
_ -> return Nothing
_ -> return Nothing
|
5f8f59facc3eb9f6d16cfceffacbfb1a4a8a3eeaa18353eefe4ff211c6b709e9 | BinaryAnalysisPlatform/bap | elf_parse.mli | open Core_kernel[@@warning "-D"]
open Elf_types
val from_bigstring : ?pos:int -> ?len:int -> Bigstring.t -> elf Or_error.t
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/bap_elf/elf_parse.mli | ocaml | open Core_kernel[@@warning "-D"]
open Elf_types
val from_bigstring : ?pos:int -> ?len:int -> Bigstring.t -> elf Or_error.t
|
|
e1dbcf02f7ee43d40ebcd401f73ddb7956e5f046b995c841e9d4ce040ec2acfb | transient-haskell/transient | Internals.stateio.hs | -----------------------------------------------------------------------------
--
-- Module : Base
-- Copyright :
License : MIT
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- | See
-- Everything in this module is exported in order to allow extensibility.
-----------------------------------------------------------------------------
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE Rank2Types #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE CPP #-}
# LANGUAGE InstanceSigs #
{-# LANGUAGE ConstraintKinds #-}
module Transient.Internals where
import Control.Applicative
import Control.Monad.State
import Data.Dynamic
import qualified Data.Map as M
import System.IO.Unsafe
import Unsafe.Coerce
import Control.Exception hiding (try,onException)
import qualified Control.Exception (try)
import Control.Concurrent
import GHC.Conc(unsafeIOToSTM)
import Control.Concurrent.STM hiding (retry)
import qualified Control.Concurrent.STM as STM (retry)
import System.Mem.StableName
import Data.Maybe
import Data.List
import Data.IORef
import System.Environment
import System.IO
import qualified Data.ByteString.Char8 as BS
#ifdef DEBUG
import Data.Monoid
import Debug.Trace
import System.Exit
{-# INLINE (!>) #-}
(!>) :: Show a => b -> a -> b
(!>) x y = trace (show y) x
infixr 0 !>
#else
{-# INLINE (!>) #-}
(!>) :: a -> b -> a
(!>) = const
#endif
type StateIO = StateT EventF IO
newtype TransIO a = Transient { runTrans :: StateIO (Maybe a) }
type SData = ()
type EventId = Int
type TransientIO = TransIO
data LifeCycle = Alive | Parent | Listener | Dead
deriving (Eq, Show)
| EventF describes the context of a TransientIO computation :
data EventF = forall a b. EventF
{ meffects :: ()
, event :: Maybe SData
-- ^ Not yet consumed result (event) from the last asynchronous run of the
-- computation
, xcomp :: StateIO (Maybe a)
, fcomp :: [b -> StateIO (Maybe b)]
-- ^ List of continuations
, mfData :: M.Map TypeRep SData
-- ^ State data accessed with get or put operations
, mfSequence :: Int
, threadId :: ThreadId
, freeTh :: Bool
-- ^ When 'True', threads are not killed using kill primitives
, parent :: Maybe EventF
-- ^ The parent of this thread
, children :: MVar [EventF]
-- ^ Forked child threads, used only when 'freeTh' is 'False'
, maxThread :: Maybe (IORef Int)
-- ^ Maximum number of threads that are allowed to be created
, labelth :: IORef (LifeCycle, BS.ByteString)
-- ^ Label the thread with its lifecycle state and a label string
} deriving Typeable
type Effects =
forall a b c. TransIO a -> TransIO a -> (a -> TransIO b)
-> StateIO (StateIO (Maybe c) -> StateIO (Maybe c), Maybe a)
instance MonadState EventF TransIO where
get = Transient $ get >>= return . Just
put x = Transient $ put x >> return (Just ())
state f = Transient $ do
s <- get
let ~(a, s') = f s
put s'
return $ Just a
-- | Run a "non transient" computation within the underlying state monad, so it is
-- guaranteed that the computation neither can stop neither can trigger additional
-- events/threads.
noTrans :: StateIO x -> TransIO x
noTrans x = Transient $ x >>= return . Just
emptyEventF :: ThreadId -> IORef (LifeCycle, BS.ByteString) -> MVar [EventF] -> EventF
emptyEventF th label childs =
EventF { meffects = mempty
, event = mempty
, xcomp = empty
, fcomp = []
, mfData = mempty
, mfSequence = 0
, threadId = th
, freeTh = False
, parent = Nothing
, children = childs
, maxThread = Nothing
, labelth = label }
-- | Run a transient computation with a default initial state
runTransient :: TransIO a -> IO (Maybe a, EventF)
runTransient t = do
th <- myThreadId
label <- newIORef $ (Alive, BS.pack "top")
childs <- newMVar []
runStateT (runTrans t) $ emptyEventF th label childs
-- | Run a transient computation with a given initial state
runTransState :: EventF -> TransIO x -> IO (Maybe x, EventF)
runTransState st x = runStateT (runTrans x) st
-- | Get the continuation context: closure, continuation, state, child threads etc
getCont :: TransIO EventF
getCont = Transient $ Just <$> get
-- | Run the closure and the continuation using the state data of the calling thread
runCont :: EventF -> StateIO (Maybe a)
runCont EventF { xcomp = mx, fcomp = fs } = do
r <- unsafeCoerce mx
case r of
Nothing -> return Nothing
Just x -> (compose fs) x
-- | Run the closure and the continuation using its own state data.
runCont' :: EventF -> IO (Maybe a, EventF)
runCont' cont = runStateT (runCont cont) cont
-- | Warning: Radically untyped stuff. handle with care
getContinuations :: StateIO [a -> StateIO (Maybe b)]
getContinuations = do
EventF { fcomp = fs } <- get
return $ unsafeCoerce fs
{-
runCont cont = do
mr <- runClosure cont
case mr of
Nothing -> return Nothing
Just r -> runContinuation cont r
-}
-- | Compose a list of continuations.
compose :: [a -> StateIO (Maybe a)] -> a -> StateIO (Maybe b)
compose [] = const empty
compose (f:fs) = \x -> f x >>= \mx -> case mx of Nothing -> return Nothing; Just x -> (compose fs) x
-- | Run the closure (the 'x' in 'x >>= f') of the current bind operation.
runClosure :: EventF -> StateIO (Maybe a)
( )
-- | Run the continuation (the 'f' in 'x >>= f') of the current bind operation with the current state.
runContinuation :: EventF -> a -> StateIO (Maybe b)
runContinuation EventF { fcomp = fs } =
runTrans . (unsafeCoerce $ compose $ fs)
-- | Save a closure and a continuation ('x' and 'f' in 'x >>= f').
setContinuation :: TransIO a -> (a -> TransIO b) -> [c -> StateIO (Maybe c)] -> StateIO ()
setContinuation b c fs = do
modify $ \EventF{..} -> EventF { xcomp = runTrans b
, fcomp = (\x -> runTrans $ unsafeCoerce c x) : fs
, .. }
-- | Save a closure and continuation, run the closure, restore the old continuation.
-- | NOTE: The old closure is discarded.
withContinuation :: b -> TransIO a -> TransIO a
withContinuation c mx = do
EventF { fcomp = fs, .. } <- get
put $ EventF { xcomp = runTrans mx
, fcomp = unsafeCoerce c : fs
, .. }
r <- mx
restoreStack fs
return r
-- | Restore the continuations to the provided ones.
-- | NOTE: Events are also cleared out.
restoreStack :: MonadState EventF m => [a -> StateIO (Maybe a)] -> m ()
restoreStack fs = modify $ \EventF {..} -> EventF { event = Nothing, fcomp = fs, .. }
-- | Run a chain of continuations.
-- WARNING: It is up to the programmer to assure that each continuation typechecks
with the next , and that the parameter type match the input of the first
-- continuation.
-- NOTE: Normally this makes sense to stop the current flow with `stop` after the
-- invocation.
runContinuations :: [a -> StateIO (Maybe b)] -> c -> StateIO (Maybe d)
runContinuations fs x = compose (unsafeCoerce fs) x
-- Instances for Transient Monad
instance Functor TransIO where
fmap f mx = do
x <- mx
return $ f x
instance Applicative TransIO where
pure a = Transient . return $ Just a
f <*> g = Transient $ do
rf <- liftIO $ newIORef (Nothing,[])
rg <- liftIO $ newIORef (Nothing,[])
fs <- getContinuations
let hasWait (_:Wait:_) = True
hasWait _ = False
appf k = Transient $ do
Log rec _ full <- getData `onNothing` return (Log False [] [])
(liftIO $ writeIORef rf (Just k,full))
! > ( show $ unsafePerformIO myThreadId ) + + " APPF "
(x, full2)<- liftIO $ readIORef rg
when (hasWait full ) $
( ! > ( hasWait full,"full",full , " \nfull2",full2 ) ) $
let full'= head full: full2
in (setData $ Log rec full' full')
-- !> ("result1",full')
return $ Just k <*> x
appg x = Transient $ do
Log rec _ full <- getData `onNothing` return (Log False [] [])
liftIO $ writeIORef rg (Just x, full)
! > ( show $ unsafePerformIO myThreadId ) + + " APPG "
(k,full1) <- liftIO $ readIORef rf
when (hasWait full) $
-- (!> ("full", full, "\nfull1",full1)) $
let full'= head full: full1
in (setData $ Log rec full' full')
-- !> ("result2",full')
return $ k <*> Just x
setContinuation f appf fs
k <- runTrans f
-- !> ( show $ unsafePerformIO myThreadId)++ "RUN f"
was <- getData `onNothing` return NoRemote
when (was == WasParallel) $ setData NoRemote
Log recovery _ full <- getData `onNothing` return (Log False [] [])
if was== WasRemote || (not recovery && was == NoRemote && isNothing k )
-- !> ("was,recovery,isNothing=",was,recovery, isNothing k)
if the first operand was a remote request
-- (so this node is not master and hasn't to execute the whole expression)
-- or it was not an asyncronous term (a normal term without async or parallel
-- like primitives) and is nothing
then do
restoreStack fs
return Nothing
else do
when (isJust k) $ liftIO $ writeIORef rf (k,full)
when necessary since it maybe WasParallel and Nothing
setContinuation g appg fs
x <- runTrans g
! > ( show $ unsafePerformIO myThreadId ) + + " RUN g "
Log recovery _ full' <- getData `onNothing` return (Log False [] [])
liftIO $ writeIORef rg (x,full')
restoreStack fs
k'' <- if was== WasParallel
then do
(k',_) <- liftIO $ readIORef rf -- since k may have been updated by a parallel f
return k'
else return k
return $ k'' <*> x
instance ( Cont r ) where
-- return a = Cont ($ a)
m > > = k = Cont $ \c - > runCont m $ \a - > runCont ( k a ) c
instance MonadCont ( Cont r ) where
callCC f = Cont $ \c - > runCont ( f ( \a - > Cont $ \ _ - > c a ) ) c
instance Monad TransIO where
return = pure
x >>= f = Transient $ do
cont <- setEventCont x f
runCont cont
-- mk <- runTrans x
resetEventCont mk
-- case mk of
-- Just k -> runTrans (f k)
-- Nothing -> return Nothing
instance MonadIO TransIO where
-- liftIO mx = do
-- ex <- liftIO' $ (mx >>= return . Right) `catch`
( \(e : : SomeException ) - > return $ Left e )
-- case ex of
-- Left e -> back e
-- Right x -> return x
-- where
liftIO x = Transient $ liftIO x >>= return . Just
instance Monoid a => Monoid (TransIO a) where
mappend x y = mappend <$> x <*> y
mempty = return mempty
instance Alternative TransIO where
empty = Transient $ return Nothing
(<|>) = mplus
instance MonadPlus TransIO where
mzero = empty
mplus x y = Transient $ do
mx <- runTrans x
was <- getData `onNothing` return NoRemote
if was == WasRemote
then return Nothing
else case mx of
Nothing -> runTrans y
justx -> return justx
readWithErr :: (Typeable a, Read a) => String -> IO [(a, String)]
readWithErr line =
(v `seq` return [(v, left)])
`catch` (\(e :: SomeException) ->
error $ "read error trying to read type: \"" ++ show (typeOf v)
++ "\" in: " ++ " <" ++ show line ++ "> ")
where [(v, left)] = readsPrec 0 line
readsPrec' _ = unsafePerformIO . readWithErr
-- | Constraint type synonym for a value that can be logged.
type Loggable a = (Show a, Read a, Typeable a)
-- | Dynamic serializable data for logging.
data IDynamic =
IDyns String
| forall a. Loggable a => IDynamic a
instance Show IDynamic where
show (IDynamic x) = show (show x)
show (IDyns s) = show s
instance Read IDynamic where
readsPrec n str = map (\(x,s) -> (IDyns x,s)) $ readsPrec' n str
type Recover = Bool
type CurrentPointer = [LogElem]
type LogEntries = [LogElem]
data LogElem = Wait | Exec | Var IDynamic
deriving (Read, Show)
data Log = Log Recover CurrentPointer LogEntries
deriving (Typeable, Show)
data RemoteStatus = WasRemote | WasParallel | NoRemote
deriving (Typeable, Eq, Show)
-- | A synonym of 'empty' that can be used in a monadic expression. It stops
-- the computation, which allows the next computation in an 'Alternative'
-- ('<|>') composition to run.
stop :: Alternative m => m stopped
stop = empty
instance ( a , Eq a , Fractional a ) = > Fractional ( TransIO a)where
-- mf / mg = (/) <$> mf <*> mg
fromRational ( x:%y ) = fromInteger x % fromInteger y
instance (Num a, Eq a) => Num (TransIO a) where
fromInteger = return . fromInteger
mf + mg = (+) <$> mf <*> mg
mf * mg = (*) <$> mf <*> mg
negate f = f >>= return . negate
abs f = f >>= return . abs
signum f = f >>= return . signum
class AdditionalOperators m where
-- | Run @m a@ discarding its result before running @m b@.
(**>) :: m a -> m b -> m b
| Run @m b@ discarding its result , after the whole task set @m a@ is
-- done.
(<**) :: m a -> m b -> m a
atEnd' :: m a -> m b -> m a
atEnd' = (<**)
-- | Run @m b@ discarding its result, once after each task in @m a@, and
-- once again after the whole task set is done.
(<***) :: m a -> m b -> m a
atEnd :: m a -> m b -> m a
atEnd = (<***)
instance AdditionalOperators TransIO where
(**>) :: TransIO a -> TransIO b -> TransIO b
(**>) x y =
Transient $ do
runTrans x
runTrans y
(<***) :: TransIO a -> TransIO b -> TransIO a
(<***) ma mb =
Transient $ do
fs <- getContinuations
setContinuation ma (\x -> mb >> return x) fs
a <- runTrans ma
runTrans mb
restoreStack fs
return a
(<**) :: TransIO a -> TransIO b -> TransIO a
(<**) ma mb =
Transient $ do
a <- runTrans ma
runTrans mb
return a
infixr 1 <***, <**, **>
| Run @b@ once , discarding its result when the first task in task set @a@
has finished . Useful to start a singleton task after the first task has been
-- setup.
(<|) :: TransIO a -> TransIO b -> TransIO a
(<|) ma mb = Transient $ do
fs <- getContinuations
ref <- liftIO $ newIORef False
setContinuation ma (cont ref) fs
r <- runTrans ma
restoreStack fs
return r
where cont ref x = Transient $ do
n <- liftIO $ readIORef ref
if n == True
then return $ Just x
else do liftIO $ writeIORef ref True
runTrans mb
return $ Just x
-- | Set the current closure and continuation for the current statement
setEventCont :: TransIO a -> (a -> TransIO b) -> StateIO EventF
setEventCont x f = do
EventF { fcomp = fs, .. }<- get
let cont'= EventF { xcomp = runTrans x
, fcomp = [(\x -> runTrans $ (unsafeCoerce f) x)] -- : fs
, .. }
put cont'
return cont'
-- | Reset the closure and continuation. Remove inner binds than the previous
-- computations may have stacked in the list of continuations.
resetEventCont : : Maybe a - > EventF - > StateIO ( )
resetEventCont mx = do
EventF { fcomp = fs, .. } <- get
let f mx = case mx of
Nothing -> empty
Just x -> unsafeCoerce (head fs) x
put $ EventF { xcomp = f mx
, fcomp = tailsafe fs
, .. }
return ()
-- | Total variant of `tail` that returns an empty list when given an empty list.
tailsafe :: [a] -> [a]
tailsafe [] = []
tailsafe (_:xs) = xs
--instance MonadTrans (Transient ) where
-- lift mx = Transient $ mx >>= return . Just
-- * Threads
waitQSemB sem = atomicModifyIORef sem $ \n ->
if n > 0 then(n - 1, True) else (n, False)
signalQSemB sem = atomicModifyIORef sem $ \n -> (n + 1, ())
-- | Sets the maximum number of threads that can be created for the given task
set . When set to 0 , new tasks start synchronously in the current thread .
-- New threads are created by 'parallel', and APIs that use parallel.
threads :: Int -> TransIO a -> TransIO a
threads n process = do
msem <- gets maxThread
sem <- liftIO $ newIORef n
modify $ \s -> s { maxThread = Just sem }
r <- process <** (modify $ \s -> s { maxThread = msem }) -- restore it
return r
-- | Terminate all the child threads in the given task set and continue
-- execution in the current thread. Useful to reap the children when a task is
-- done.
--
oneThread :: TransIO a -> TransIO a
oneThread comp = do
st <- get
chs <- liftIO $ newMVar []
label <- liftIO $ newIORef (Alive, BS.pack "oneThread")
let st' = st { parent = Just st
, children = chs
, labelth = label }
liftIO $ hangThread st st'
put st'
x <- comp
th <- liftIO myThreadId
-- !> ("FATHER:", threadId st)
chs <- liftIO $ readMVar chs -- children st'
liftIO $ mapM_ (killChildren1 th) chs
return x
where killChildren1 :: ThreadId -> EventF -> IO ()
killChildren1 th state = do
ths' <- modifyMVar (children state) $ \ths -> do
let (inn, ths')= partition (\st -> threadId st == th) ths
return (inn, ths')
mapM_ (killChildren1 th) ths'
mapM_ (killThread . threadId) ths'
-- !> ("KILLEVENT1 ", map threadId ths' )
-- | Add a label to the current passing threads so it can be printed by debugging calls like `showThreads`
labelState :: (MonadIO m,MonadState EventF m) => String -> m ()
labelState l = do
st <- get
liftIO $ atomicModifyIORef (labelth st) $ \(status,_) -> ((status, BS.pack l), ())
printBlock :: MVar ()
printBlock = unsafePerformIO $ newMVar ()
-- | Show the tree of threads hanging from the state.
showThreads :: MonadIO m => EventF -> m ()
showThreads st = liftIO $ withMVar printBlock $ const $ do
mythread <- myThreadId
putStrLn "---------Threads-----------"
let showTree n ch = do
liftIO $ do
putStr $ take n $ repeat ' '
(state, label) <- readIORef $ labelth ch
if BS.null label
then putStr . show $ threadId ch
else do BS.putStr label; putStr . drop 8 . show $ threadId ch
when (state == Dead) $ putStr " dead"
putStrLn $ if mythread == threadId ch then " <--" else ""
chs <- readMVar $ children ch
mapM_ (showTree $ n + 2) $ reverse chs
showTree 0 st
-- | Return the state of the thread that initiated the transient computation
topState :: TransIO EventF
topState = do
st <- get
return $ toplevel st
where toplevel st = case parent st of
Nothing -> st
Just p -> toplevel p
-- | Return the state variable of the type desired with which a thread, identified by his number in the treee was initiated
showState :: (Typeable a, MonadIO m, Alternative m) => String -> EventF -> m (Maybe a)
showState th top = resp
where resp = do
let thstring = drop 9 . show $ threadId top
if thstring == th
then getstate top
else do
sts <- liftIO $ readMVar $ children top
foldl (<|>) empty $ map (showState th) sts
getstate st =
case M.lookup (typeOf $ typeResp resp) $ mfData st of
Just x -> return . Just $ unsafeCoerce x
Nothing -> return Nothing
typeResp :: m (Maybe x) -> x
typeResp = undefined
-- | Add n threads to the limit of threads. If there is no limit, the limit is set.
addThreads' :: Int -> TransIO ()
addThreads' n= noTrans $ do
msem <- gets maxThread
case msem of
Just sem -> liftIO $ modifyIORef sem $ \n' -> n + n'
Nothing -> do
sem <- liftIO (newIORef n)
modify $ \ s -> s { maxThread = Just sem }
-- | Ensure that at least n threads are available for the current task set.
addThreads :: Int -> TransIO ()
addThreads n = noTrans $ do
msem <- gets maxThread
case msem of
Nothing -> return ()
Just sem -> liftIO $ modifyIORef sem $ \n' -> if n' > n then n' else n
--getNonUsedThreads :: TransIO (Maybe Int)
--getNonUsedThreads= Transient $ do
< - gets
case of
-- Just sem -> liftIO $ Just <$> readIORef sem
-- Nothing -> return Nothing
-- | Disable tracking and therefore the ability to terminate the child threads.
-- By default, child threads are terminated automatically when the parent
-- thread dies, or they can be terminated using the kill primitives. Disabling
-- it may improve performance a bit, however, all threads must be well-behaved
-- to exit on their own to avoid a leak.
freeThreads :: TransIO a -> TransIO a
freeThreads process = Transient $ do
st <- get
put st { freeTh = True }
r <- runTrans process
modify $ \s -> s { freeTh = freeTh st }
return r
-- | Enable tracking and therefore the ability to terminate the child threads.
-- This is the default but can be used to re-enable tracking if it was
-- previously disabled with 'freeThreads'.
hookedThreads :: TransIO a -> TransIO a
hookedThreads process = Transient $ do
st <- get
put st {freeTh = False}
r <- runTrans process
modify $ \st -> st { freeTh = freeTh st }
return r
-- | Kill all the child threads of the current thread.
killChilds :: TransIO ()
killChilds = noTrans $ do
cont <- get
liftIO $ do
killChildren $ children cont
writeIORef (labelth cont) (Alive, mempty)
-- !> (threadId cont,"relabeled")
return ()
-- | Kill the current thread and the childs.
killBranch :: TransIO ()
killBranch = noTrans $ do
st <- get
liftIO $ killBranch' st
-- | Kill the childs and the thread of an state
killBranch' :: EventF -> IO ()
killBranch' cont = do
killChildren $ children cont
let thisth = threadId cont
mparent = parent cont
when (isJust mparent) $
modifyMVar_ (children $ fromJust mparent) $ \sts ->
return $ filter (\st -> threadId st /= thisth) sts
killThread $ thisth
-- * Extensible State: Session Data Management
-- | Same as 'getSData' but with a more general type. If the data is found, a
-- 'Just' value is returned. Otherwise, a 'Nothing' value is returned.
getData :: (MonadState EventF m, Typeable a) => m (Maybe a)
getData = resp
where resp = do
list <- gets mfData
case M.lookup (typeOf $ typeResp resp) list of
Just x -> return . Just $ unsafeCoerce x
Nothing -> return Nothing
typeResp :: m (Maybe x) -> x
typeResp = undefined
-- | Retrieve a previously stored data item of the given data type from the
-- monad state. The data type to retrieve is implicitly determined from the
-- requested type context.
-- If the data item is not found, an 'empty' value (a void event) is returned.
-- Remember that an empty value stops the monad computation. If you want to
-- print an error message or a default value in that case, you can use an
-- 'Alternative' composition. For example:
--
-- > getSData <|> error "no data"
-- > getInt = getSData <|> return (0 :: Int)
getSData :: Typeable a => TransIO a
getSData = Transient getData
-- | Same as `getSData`
getState :: Typeable a => TransIO a
getState = getSData
-- | 'setData' stores a data item in the monad state which can be retrieved
-- later using 'getData' or 'getSData'. Stored data items are keyed by their
data type , and therefore only one item of a given type can be stored . A
newtype wrapper can be used to distinguish two data items of the same type .
--
-- @
import Control . Monad . IO.Class ( liftIO )
-- import Transient.Base
import Data . Typeable
--
-- data Person = Person
-- { name :: String
-- , age :: Int
} deriving
--
-- main = keep $ do
setData $ Person " " 55
-- Person name age <- getSData
-- liftIO $ print (name, age)
-- @
setData :: (MonadState EventF m, Typeable a) => a -> m ()
setData x = modify $ \st -> st { mfData = M.insert t (unsafeCoerce x) (mfData st) }
where t = typeOf x
-- | Accepts a function that takes the current value of the stored data type
-- and returns the modified value. If the function returns 'Nothing' the value
-- is deleted otherwise updated.
modifyData :: (MonadState EventF m, Typeable a) => (Maybe a -> Maybe a) -> m ()
modifyData f = modify $ \st -> st { mfData = M.alter alterf t (mfData st) }
where typeResp :: (Maybe a -> b) -> a
typeResp = undefined
t = typeOf (typeResp f)
alterf mx = unsafeCoerce $ f x'
where x' = case mx of
Just x -> Just $ unsafeCoerce x
Nothing -> Nothing
-- | Same as modifyData
modifyState :: (MonadState EventF m, Typeable a) => (Maybe a -> Maybe a) -> m ()
modifyState = modifyData
-- | Same as 'setData'
setState :: (MonadState EventF m, Typeable a) => a -> m ()
setState = setData
-- | Delete the data item of the given type from the monad state.
delData :: (MonadState EventF m, Typeable a) => a -> m ()
delData x = modify $ \st -> st { mfData = M.delete (typeOf x) (mfData st) }
-- | Same as 'delData'
delState :: (MonadState EventF m, Typeable a) => a -> m ()
delState = delData
STRefs for the Transient monad
newtype Ref a = Ref (IORef a)
-- | mutable state reference that can be updated (similar to STRef in the state monad)
--
Initialized the first time it is set .
setRState:: Typeable a => a -> TransIO ()
setRState x= do
Ref ref <- getSData
liftIO $ atomicModifyIORef ref $ const (x,())
<|> do
ref <- liftIO (newIORef x)
setData $ Ref ref
getRState :: Typeable a => TransIO a
getRState= do
Ref ref <- getSData
liftIO $ readIORef ref
delRState x= delState (undefined `asTypeOf` ref x)
where ref :: a -> IORef a
ref= undefined
-- | Run an action, if it does not succeed, undo any state changes
-- that it might have caused and allow aternative actions to run with the original state
try :: TransIO a -> TransIO a
try mx = do
sd <- gets mfData
mx <|> (modify (\s -> s { mfData = sd }) >> empty)
-- | Executes the computation and reset the state either if it fails or not.
sandbox :: TransIO a -> TransIO a
sandbox mx = do
sd <- gets mfData
mx <*** modify (\s ->s { mfData = sd})
-- | Generator of identifiers that are unique within the current monadic
-- sequence They are not unique in the whole program.
genId :: MonadState EventF m => m Int
genId = do
st <- get
let n = mfSequence st
put st { mfSequence = n + 1 }
return n
getPrevId :: MonadState EventF m => m Int
getPrevId = gets mfSequence
instance Read SomeException where
readsPrec n str = [(SomeException $ ErrorCall s, r)]
where [(s , r)] = read str
-- | 'StreamData' represents a task in a task stream being generated.
data StreamData a =
SMore a -- ^ More tasks to come
| SLast a -- ^ This is the last task
| SDone -- ^ No more tasks, we are done
| SError SomeException -- ^ An error occurred
deriving (Typeable, Show,Read)
-- | An task stream generator that produces an infinite stream of tasks by
-- running an IO computation in a loop. A task is triggered carrying the output
-- of the computation. See 'parallel' for notes on the return value.
waitEvents :: IO a -> TransIO a
waitEvents io = do
mr <- parallel (SMore <$> io)
case mr of
SMore x -> return x
SError e -> back e
-- | Run an IO computation asynchronously and generate a single task carrying
-- the result of the computation when it completes. See 'parallel' for notes on
-- the return value.
async :: IO a -> TransIO a
async io = do
mr <- parallel (SLast <$> io)
case mr of
SLast x -> return x
SError e -> back e
-- | Force an async computation to run synchronously. It can be useful in an
-- 'Alternative' composition to run the alternative only after finishing a
computation . Note that in Applicatives it might result in an undesired
-- serialization.
sync :: TransIO a -> TransIO a
sync x = do
setData WasRemote
r <- x
delData WasRemote
return r
| @spawn = freeThreads .
spawn :: IO a -> TransIO a
spawn = freeThreads . waitEvents
-- | An task stream generator that produces an infinite stream of tasks by
-- running an IO computation periodically at the specified time interval. The
-- task carries the result of the computation. A new task is generated only if
-- the output of the computation is different from the previous one. See
-- 'parallel' for notes on the return value.
sample :: Eq a => IO a -> Int -> TransIO a
sample action interval = do
v <- liftIO action
prev <- liftIO $ newIORef v
waitEvents (loop action prev) <|> async (return v)
where loop action prev = loop'
where loop' = do
threadDelay interval
v <- action
v' <- readIORef prev
if v /= v' then writeIORef prev v >> return v else loop'
| Run an IO action one or more times to generate a stream of tasks . The IO
action returns a ' StreamData ' . When it returns an ' SMore ' or ' SLast ' a new
task is triggered with the result value . If the return value is ' SMore ' , the
-- action is run again to generate the next task, otherwise task creation
-- stops.
--
-- Unless the maximum number of threads (set with 'threads') has been reached,
-- the task is generated in a new thread and the current thread returns a void
-- task.
parallel :: IO (StreamData b) -> TransIO (StreamData b)
parallel ioaction = Transient $ do
cont <- get
! > " PARALLEL "
case event cont of
j@(Just _) -> do
put cont { event = Nothing }
return $ unsafeCoerce j
Nothing -> do
liftIO $ atomicModifyIORef (labelth cont) $ \(_, lab) -> ((Parent, lab), ())
liftIO $ loop cont ioaction
was <- getData `onNothing` return NoRemote
when (was /= WasRemote) $ setData WasParallel
-- th <- liftIO myThreadId
-- return () !> ("finish",th)
return Nothing
| Execute the IO action and the continuation
loop :: EventF -> IO (StreamData t) -> IO ()
loop parentc rec = forkMaybe parentc $ \cont -> do
Execute the IO computation and then the closure - continuation
liftIO $ atomicModifyIORef (labelth cont) $ const ((Listener,BS.pack "wait"),())
let loop'= do
mdat <- rec `catch` \(e :: SomeException) -> return $ SError e
case mdat of
se@(SError _) -> setworker cont >> iocont se cont
SDone -> setworker cont >> iocont SDone cont
last@(SLast _) -> setworker cont >> iocont last cont
more@(SMore _) -> do
forkMaybe cont $ iocont more
loop'
where
setworker cont= liftIO $ atomicModifyIORef (labelth cont) $ const ((Alive,BS.pack "work"),())
iocont dat cont = do
let cont'= cont{event= Just $ unsafeCoerce dat}
runStateT (runCont cont') cont'
return ()
loop'
return ()
where
# INLINABLE forkMaybe #
forkMaybe parent proc = do
case maxThread parent of
Nothing -> forkIt parent proc
Just sem -> do
dofork <- waitQSemB sem
if dofork then forkIt parent proc else proc parent
forkIt parent proc= do
chs <- liftIO $ newMVar []
label <- newIORef (Alive, BS.pack "work")
let cont = parent{parent=Just parent,children= chs, labelth= label}
forkFinally1 (do
th <- myThreadId
let cont'= cont{threadId=th}
when(not $ freeTh parent )$ hangThread parent cont'
-- !> ("thread created: ",th,"in",threadId parent )
proc cont')
$ \me -> do
case me of
Left e -> exceptBack cont e >> return ()
_ -> do
case maxThread cont of
Just sem -> signalQSemB sem -- !> "freed thread"
Nothing -> return ()
when(not $ freeTh parent ) $ do -- if was not a free thread
th <- myThreadId
(can,label) <- atomicModifyIORef (labelth cont) $ \(l@(status,label)) ->
((if status== Alive then Dead else status, label),l)
when (can/= Parent ) $ free th parent
return ()
forkFinally1 :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally1 action and_then =
mask $ \restore -> forkIO $ Control.Exception.try (restore action) >>= and_then
free th env= do
-- return () !> ("freeing",th,"in",threadId env)
let sibling= children env
(sbs',found) <- modifyMVar sibling $ \sbs -> do
let (sbs', found) = drop [] th sbs
return (sbs',(sbs',found))
if found
then do
-- !> ("new list for",threadId env,map threadId sbs')
(typ,_) <- readIORef $ labelth env
if (null sbs' && typ /= Listener && isJust (parent env))
-- free the parent
then free (threadId env) ( fromJust $ parent env)
else return ()
-- return env
else return () -- putMVar sibling sbs
-- !> (th,"orphan")
where
drop processed th []= (processed,False)
drop processed th (ev:evts)| th == threadId ev= (processed ++ evts, True)
| otherwise= drop (ev:processed) th evts
hangThread parentProc child = do
let headpths= children parentProc
modifyMVar_ headpths $ \ths -> return (child:ths)
-- ths <- takeMVar headpths
( child : )
-- !> ("hang", threadId child, threadId parentProc,map threadId ths,unsafePerformIO $ readIORef $ labelth parentProc)
-- | kill all the child threads associated with the continuation context
killChildren childs = do
ths <- modifyMVar childs $ \ths -> return ([],ths)
-- ths <- takeMVar childs
-- putMVar childs []
mapM_ (killChildren . children) ths
mapM_ (killThread . threadId) ths -- !> ("KILL", map threadId ths )
-- | Make a transient task generator from an asynchronous callback handler.
--
The first parameter is a callback . The second parameter is a value to be
-- returned to the callback; if the callback expects no return value it
-- can just be a @return ()@. The callback expects a setter function taking the
@eventdata@ as an argument and returning a value to the callback ; this
-- function is supplied by 'react'.
--
-- Callbacks from foreign code can be wrapped into such a handler and hooked
-- into the transient monad using 'react'. Every time the callback is called it
-- generates a new task for the transient monad.
--
react
:: Typeable eventdata
=> ((eventdata -> IO response) -> IO ())
-> IO response
-> TransIO eventdata
react setHandler iob= Transient $ do
cont <- get
case event cont of
Nothing -> do
liftIO $ setHandler $ \dat ->do
runStateT (runCont cont) cont{event= Just $ unsafeCoerce dat}
iob
was <- getData `onNothing` return NoRemote
when (was /= WasRemote) $ setData WasParallel
return Nothing
j@(Just _) -> do
put cont{event=Nothing}
return $ unsafeCoerce j
-- | Runs a computation asynchronously without generating any events. Returns
-- 'empty' in an 'Alternative' composition.
abduce = async $ return ()
-- * non-blocking keyboard input
getLineRef= unsafePerformIO $ newTVarIO Nothing
roption= unsafePerformIO $ newMVar []
| Waits on stdin in a loop and triggers a new task every time the input data
matches the first parameter . The value contained by the task is the matched
value i.e. the first argument itself . The second parameter is a label for
-- the option. The label is displayed on the console when the option is
-- activated.
--
Note that if two independent invocations of ' option ' are expecting the same
input , only one of them gets it and triggers a task . It can not be
-- predicted which one gets it.
--
option :: (Typeable b, Show b, Read b, Eq b) =>
b -> String -> TransIO b
option ret message= do
let sret= show ret
liftIO $ putStrLn $ "Enter "++sret++"\tto: " ++ message
liftIO $ modifyMVar_ roption $ \msgs-> return $ sret:msgs
waitEvents $ getLine' (==ret)
liftIO $ putStr "\noption: " >> putStrLn (show ret)
return ret
| Waits on stdin and triggers a task when a console input matches the
predicate specified in the first argument . The second parameter is a string
-- to be displayed on the console before waiting.
--
input cond prompt= input' Nothing cond prompt
input' :: (Typeable a, Read a,Show a) => Maybe a -> (a -> Bool) -> String -> TransIO a
input' mv cond prompt= Transient . liftIO $do
putStr prompt >> hFlush stdout
atomically $ do
mr <- readTVar getLineRef
case mr of
Nothing -> STM.retry
Just r ->
case reads2 r of
(s,_):_ -> if cond s !> show (cond s)
then do
unsafeIOToSTM $ print s
writeTVar getLineRef Nothing !>"match"
return $ Just s
else return mv
_ -> return mv !> "return "
where
reads2 s= x where
x= if typeOf(typeOfr x) == typeOf ""
then unsafeCoerce[(s,"")]
else unsafePerformIO $ return (reads s) `catch` \(e :: SomeException) -> (return [])
typeOfr :: [(a,String)] -> a
typeOfr = undefined
-- | Non blocking `getLine` with a validator
getLine' cond= do
atomically $ do
mr <- readTVar getLineRef
case mr of
Nothing -> STM.retry
Just r ->
case reads1 r of -- !> ("received " ++ show r ++ show (unsafePerformIO myThreadId)) of
(s,_):_ -> if cond s -- !> show (cond s)
then do
writeTVar getLineRef Nothing -- !>"match"
return s
else STM.retry
_ -> STM.retry
reads1 s=x where
x= if typeOf(typeOfr x) == typeOf "" then unsafeCoerce[(s,"")] else readsPrec' 0 s
typeOfr :: [(a,String)] -> a
typeOfr = undefined
inputLoop= do
r <- getLine
-- XXX hoping that the previous value has been consumed by now.
-- otherwise its just lost by overwriting.
atomically $ writeTVar getLineRef Nothing
processLine r
inputLoop
processLine r= do
let rs = breakSlash [] r
-- XXX this blocks forever if an input is not consumed by any consumer.
e.g. try this " xxx / xxx " on the stdin
liftIO $ mapM_ (\ r ->
atomically $ do
threadDelay 1000000
t <- readTVar getLineRef
when (isJust t) STM.retry
writeTVar getLineRef $ Just r ) rs
where
breakSlash :: [String] -> String -> [String]
breakSlash [] ""= [""]
breakSlash s ""= s
breakSlash res ('\"':s)=
let (r,rest) = span(/= '\"') s
in breakSlash (res++[r]) $ tail1 rest
breakSlash res s=
let (r,rest) = span(\x -> x /= '/' && x /= ' ') s
in breakSlash (res++[r]) $ tail1 rest
tail1 []=[]
tail1 x= tail x
-- | Wait for the execution of `exit` and return the result or the exhaustion of thread activity
stay rexit= takeMVar rexit
`catch` \(e :: BlockedIndefinitelyOnMVar) -> return Nothing
newtype Exit a= Exit a deriving Typeable
-- | Runs the transient computation in a child thread and keeps the main thread
-- running until all the user threads exit or some thread invokes 'exit'.
--
-- The main thread provides facilities to accept keyboard input in a
-- non-blocking but line-oriented manner. The program reads the standard input
-- and feeds it to all the async input consumers (e.g. 'option' and 'input').
-- All async input consumers contend for each line entered on the standard
-- input and try to read it atomically. When a consumer consumes the input
-- others do not get to see it, otherwise it is left in the buffer for others
-- to consume. If nobody consumes the input, it is discarded.
--
-- A @/@ in the input line is treated as a newline.
--
-- When using asynchronous input, regular synchronous IO APIs like getLine
-- cannot be used as they will contend for the standard input along with the
-- asynchronous input thread. Instead you can use the asynchronous input APIs
-- provided by transient.
--
A built - in interactive command handler also reads the stdin asynchronously .
-- All available commands handled by the command handler are displayed when the
-- program is run. The following commands are available:
--
1 . @ps@ : show threads
2 . : inspect the log of a thread
3 . @end@ , @exit@ : terminate the program
--
-- An input not handled by the command handler can be handled by the program.
--
The program 's command line is scanned for @-p@ or @--path@ command line
-- options. The arguments to these options are injected into the async input
-- channel as keyboard input to the program. Each line of input is separated by
-- a @/@. For example:
--
> foo -p ps / end
--
keep :: Typeable a => TransIO a -> IO (Maybe a)
keep mx = do
liftIO $ hSetBuffering stdout LineBuffering
rexit <- newEmptyMVar
forkIO $ do
-- liftIO $ putMVar rexit $ Right Nothing
runTransient $ do
st <- get
setData $ Exit rexit
(async (return ()) >> labelState "input" >> liftIO inputLoop)
<|> do
option "ps" "show threads"
liftIO $ showThreads st
empty
<|> do
option "log" "inspect the log of a thread"
th <- input (const True) "thread number>"
ml <- liftIO $ showState th st
liftIO $ print $ fmap (\(Log _ _ log) -> reverse log) ml
empty
<|> do
option "end" "exit"
killChilds
liftIO $ putMVar rexit Nothing
empty
<|> mx
return ()
threadDelay 10000
execCommandLine
stay rexit
where
type1 :: TransIO a -> Either String (Maybe a)
type1= undefined
-- | Same as `keep` but does not read from the standard input, and therefore
-- the async input APIs ('option' and 'input') cannot be used in the monad.
-- However, keyboard input can still be passed via command line arguments as
-- described in 'keep'. Useful for debugging or for creating background tasks,
-- as well as to embed the Transient monad inside another computation. It
-- returns either the value returned by `exit`. or Nothing, when there are no
-- more threads running
--
keep' :: Typeable a => TransIO a -> IO (Maybe a)
keep' mx = do
liftIO $ hSetBuffering stdout LineBuffering
rexit <- newEmptyMVar
forkIO $ do
runTransient $ do
setData $ Exit rexit
mx
return ()
threadDelay 10000
forkIO $ execCommandLine
stay rexit
execCommandLine= do
args <- getArgs
let mindex = findIndex (\o -> o == "-p" || o == "--path" ) args
when (isJust mindex) $ do
let i= fromJust mindex +1
when (length args >= i) $ do
let path= args !! i
putStr "Executing: " >> print path
processLine path
-- | Exit the main thread, and thus all the Transient threads (and the
-- application if there is no more code)
exit :: Typeable a => a -> TransIO a
exit x= do
Exit rexit <- getSData <|> error "exit: not the type expected" `asTypeOf` type1 x
liftIO $ putMVar rexit $ Just x
stop
where
type1 :: a -> TransIO (Exit (MVar (Maybe a)))
type1= undefined
| If the first parameter is ' Nothing ' return the second parameter otherwise
return the first parameter ..
onNothing :: Monad m => m (Maybe b) -> m b -> m b
onNothing iox iox'= do
mx <- iox
case mx of
Just x -> return x
Nothing -> iox'
----------------------------------backtracking ------------------------
data Backtrack b= Show b =>Backtrack{backtracking :: Maybe b
,backStack :: [EventF] }
deriving Typeable
-- | Delete all the undo actions registered till now for the given track id.
backCut :: (Typeable b, Show b) => b -> TransientIO ()
backCut reason= Transient $ do
delData $ Backtrack (Just reason) []
return $ Just ()
-- | 'backCut' for the default track; equivalent to @backCut ()@.
undoCut :: TransientIO ()
undoCut = backCut ()
| Run the action in the first parameter and register the second parameter as
the undo action . On undo ( ' back ' ) the second parameter is called with the
-- undo track id as argument.
--
# NOINLINE onBack #
onBack :: (Typeable b, Show b) => TransientIO a -> ( b -> TransientIO a) -> TransientIO a
onBack ac bac = registerBack (typeof bac) $ Transient $ do
Backtrack mreason stack <- getData `onNothing` backStateOf (typeof bac)
runTrans $ case mreason of
Nothing -> ac
Just reason -> do
setState $ Backtrack mreason $ tail stack -- to avoid recursive call tot he same handler
bac reason
where
typeof :: (b -> TransIO a) -> b
typeof = undefined
-- | 'onBack' for the default track; equivalent to @onBack ()@.
onUndo :: TransientIO a -> TransientIO a -> TransientIO a
onUndo x y= onBack x (\() -> y)
| Register an undo action to be executed when backtracking . The first
-- parameter is a "witness" whose data type is used to uniquely identify this
-- backtracking action. The value of the witness parameter is not used.
--
# NOINLINE registerUndo #
registerBack :: (Typeable b, Show b) => b -> TransientIO a -> TransientIO a
registerBack witness f = Transient $ do
! ! > " "
md <- getData `asTypeOf` (Just <$> backStateOf witness)
case md of
Just (Backtrack _ []) -> empty
Just (bss@(Backtrack b (bs@((EventF _ _ x' _ _ _ _ _ _ _ _ _):_)))) ->
when (isNothing b) $ do
addrx <- addr x
addrx' <- addr x' -- to avoid duplicate backtracking points
setData $ if addrx == addrx' then bss else Backtrack mwit (cont:bs)
Nothing -> setData $ Backtrack mwit [cont]
runTrans f
where
mwit= Nothing `asTypeOf` (Just witness)
addr x = liftIO $ return . hashStableName =<< (makeStableName $! x)
registerUndo :: TransientIO a -> TransientIO a
registerUndo f= registerBack () f
-- XXX Should we enforce retry of the same track which is being undone? If the
-- user specifies a different track would it make sense?
--
-- | For a given undo track id, stop executing more backtracking actions and
-- resume normal execution in the forward direction. Used inside an undo
-- action.
--
forward :: (Typeable b, Show b) => b -> TransIO ()
forward reason= Transient $ do
Backtrack _ stack <- getData `onNothing` (backStateOf reason)
setData $ Backtrack(Nothing `asTypeOf` Just reason) stack
return $ Just ()
| ' forward ' for the default undo track ; equivalent to @forward ( ) @.
retry= forward ()
-- | Abort finish. Stop executing more finish actions and resume normal
-- execution. Used inside 'onFinish' actions.
--
noFinish= continue
-- | Start the undo process for the given undo track id. Performs all the undo
-- actions registered till now in reverse order. An undo action can use
-- 'forward' to stop the undo process and resume forward execution. If there
-- are no more undo actions registered execution stops and a 'stop' action is
-- returned.
--
back :: (Typeable b, Show b) => b -> TransientIO a
back reason = Transient $ do
bs <- getData `onNothing` backStateOf reason
! ! > " GOBACK "
where
goBackt (Backtrack _ [] )= return Nothing -- !!> "END"
goBackt (Backtrack b (stack@(first : bs)) )= do
setData $ Backtrack (Just reason) stack
mr <- runClosure first -- !> ("RUNCLOSURE",length stack)
Backtrack back _ <- getData `onNothing` backStateOf reason
-- !> "END RUNCLOSURE"
case mr of
Nothing -> return empty -- !> "END EXECUTION"
Just x -> case back of
Nothing -> runContinuation first x -- !> "FORWARD EXEC"
! > ( " BACK AGAIN",back )
backStateOf :: (Monad m, Show a, Typeable a) => a -> m (Backtrack a)
backStateOf reason= return $ Backtrack (Nothing `asTypeOf` (Just reason)) []
-- | 'back' for the default undo track; equivalent to @back ()@.
--
undo :: TransIO a
undo= back ()
------ finalization
newtype Finish= Finish String deriving Show
instance Exception Finish
newtype FinishReason= FinishReason ( Maybe SomeException ) deriving ( Typeable , Show )
-- | Clear all finish actions registered till now.
-- initFinish= backCut (FinishReason Nothing)
-- | Register an action that to be run when 'finish' is called. 'onFinish' can
-- be used multiple times to register multiple actions. Actions are run in
-- reverse order. Used in infix style.
--
onFinish :: (Finish ->TransIO ()) -> TransIO ()
onFinish f= onException' (return ()) f
| Run the action specified in the first parameter and register the second
-- parameter as a finish action to be run when 'finish' is called. Used in
-- infix style.
--
onFinish' ::TransIO a ->(Finish ->TransIO a) -> TransIO a
onFinish' proc f= proc `onException'` f
-- | Execute all the finalization actions registered up to the last
' initFinish ' , in reverse order and continue the execution . Either an exception or ' Nothing ' can be
initFinish = cutExceptions
-- passed to 'finish'. The argument passed is made available in the 'onFinish'
-- actions invoked.
--
finish :: String -> TransIO ()
finish reason= (throwt $ Finish reason) <|> return()
-- | trigger finish when the stream of data ends
checkFinalize v=
case v of
SDone -> stop
SLast x -> return x
SError e -> throwt e
SMore x -> return x
------ exceptions ---
--
| Install an exception handler . Handlers are executed in reverse ( i.e. last in , first out ) order when such exception happens in the
-- continuation. Note that multiple handlers can be installed for the same exception type.
--
The semantic is thus very different than the one of ` Control . Exception . Base.onException `
onException :: Exception e => (e -> TransIO ()) -> TransIO ()
onException exc= return () `onException'` exc
onException' :: Exception e => TransIO a -> (e -> TransIO a) -> TransIO a
onException' mx f= onAnyException mx $ \e ->
case fromException e of
Nothing -> empty
Just e' -> f e'
where
onAnyException :: TransIO a -> (SomeException ->TransIO a) -> TransIO a
onAnyException mx f= ioexp `onBack` f
ioexp = Transient $ do
st <- get
(mx,st') <- liftIO $ (runStateT (do
case event st of
Nothing -> do
r <- runTrans mx -- !> "mx"
modify $ \s -> s{event= Just $ unsafeCoerce r}
runCont st
was <- getData `onNothing` return NoRemote
when (was /= WasRemote) $ setData WasParallel
return Nothing
Just r -> do
modify $ \s -> s{event=Nothing}
return $ unsafeCoerce r) st)
`catch` exceptBack st
put st'
return mx
exceptBack st = \(e ::SomeException) -> do -- recursive catch itself
-- return () !> "CATCH"
runStateT ( runTrans $ back e ) st
`catch` exceptBack st
-- | Delete all the exception handlers registered till now.
cutExceptions :: TransIO ()
cutExceptions= backCut (undefined :: SomeException)
-- | Use it inside an exception handler. it stop executing any further exception
-- handlers and resume normal execution from this point on.
continue :: TransIO ()
continue = forward (undefined :: SomeException) !> "CONTINUE"
-- | catch an exception in a Transient block
--
-- The semantic is the same than `catch` but the computation and the exception handler can be multirhreaded
catcht :: Exception e => TransIO b -> (e -> TransIO b) -> TransIO b
catcht mx exc= do
rpassed <- liftIO $ newIORef False
sandbox $ do
cutExceptions
r <- onException' mx (\e -> do
passed <- liftIO $ readIORef rpassed
if not passed then continue >> exc e else empty)
liftIO $ writeIORef rpassed True
return r
where
sandbox mx= do
exState <- getState <|> backStateOf (undefined :: SomeException)
mx
<*** do setState exState
-- | throw an exception in the Transient monad
throwt :: Exception e => e -> TransIO a
throwt= back . toException
-- catcht1 :: Exception e => TransIO a -> (e ->TransIO a) -> TransIO a
-- catcht1 mx exc= Transient $ do
-- st <- get
-- case event st of
-- Nothing -> do
( mx , st ' ) < - liftIO $ ( runStateT(runTrans mx ) st ) ` catch ` \(e : : SomeException ) - >
-- runStateT ( runTrans $ f e ) st
-- put st'
-- modify $ \s -> s{event= Just $ unsafeCoerce mx}
-- runCont st
-- was <- getData `onNothing` return NoRemote
when ( was /= WasRemote ) $ setData WasParallel
-- return Nothing
-- Just r -> do
-- modify $ \s -> s{event=Nothing}
return $ unsafeCoerce r
-- where
-- f e=case fromException e of
-- Nothing -> empty
-- Just e' -> exc e'
| null | https://raw.githubusercontent.com/transient-haskell/transient/301831888887fb199e9f9bfaba2502389e73bc93/src/Transient/Internals.stateio.hs | haskell | ---------------------------------------------------------------------------
Module : Base
Copyright :
Maintainer :
Stability :
Portability :
| See
Everything in this module is exported in order to allow extensibility.
---------------------------------------------------------------------------
# LANGUAGE ScopedTypeVariables #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE UndecidableInstances #
# LANGUAGE Rank2Types #
# LANGUAGE CPP #
# LANGUAGE ConstraintKinds #
# INLINE (!>) #
# INLINE (!>) #
^ Not yet consumed result (event) from the last asynchronous run of the
computation
^ List of continuations
^ State data accessed with get or put operations
^ When 'True', threads are not killed using kill primitives
^ The parent of this thread
^ Forked child threads, used only when 'freeTh' is 'False'
^ Maximum number of threads that are allowed to be created
^ Label the thread with its lifecycle state and a label string
| Run a "non transient" computation within the underlying state monad, so it is
guaranteed that the computation neither can stop neither can trigger additional
events/threads.
| Run a transient computation with a default initial state
| Run a transient computation with a given initial state
| Get the continuation context: closure, continuation, state, child threads etc
| Run the closure and the continuation using the state data of the calling thread
| Run the closure and the continuation using its own state data.
| Warning: Radically untyped stuff. handle with care
runCont cont = do
mr <- runClosure cont
case mr of
Nothing -> return Nothing
Just r -> runContinuation cont r
| Compose a list of continuations.
| Run the closure (the 'x' in 'x >>= f') of the current bind operation.
| Run the continuation (the 'f' in 'x >>= f') of the current bind operation with the current state.
| Save a closure and a continuation ('x' and 'f' in 'x >>= f').
| Save a closure and continuation, run the closure, restore the old continuation.
| NOTE: The old closure is discarded.
| Restore the continuations to the provided ones.
| NOTE: Events are also cleared out.
| Run a chain of continuations.
WARNING: It is up to the programmer to assure that each continuation typechecks
continuation.
NOTE: Normally this makes sense to stop the current flow with `stop` after the
invocation.
Instances for Transient Monad
!> ("result1",full')
(!> ("full", full, "\nfull1",full1)) $
!> ("result2",full')
!> ( show $ unsafePerformIO myThreadId)++ "RUN f"
!> ("was,recovery,isNothing=",was,recovery, isNothing k)
(so this node is not master and hasn't to execute the whole expression)
or it was not an asyncronous term (a normal term without async or parallel
like primitives) and is nothing
since k may have been updated by a parallel f
return a = Cont ($ a)
mk <- runTrans x
case mk of
Just k -> runTrans (f k)
Nothing -> return Nothing
liftIO mx = do
ex <- liftIO' $ (mx >>= return . Right) `catch`
case ex of
Left e -> back e
Right x -> return x
where
| Constraint type synonym for a value that can be logged.
| Dynamic serializable data for logging.
| A synonym of 'empty' that can be used in a monadic expression. It stops
the computation, which allows the next computation in an 'Alternative'
('<|>') composition to run.
mf / mg = (/) <$> mf <*> mg
| Run @m a@ discarding its result before running @m b@.
done.
| Run @m b@ discarding its result, once after each task in @m a@, and
once again after the whole task set is done.
setup.
| Set the current closure and continuation for the current statement
: fs
| Reset the closure and continuation. Remove inner binds than the previous
computations may have stacked in the list of continuations.
| Total variant of `tail` that returns an empty list when given an empty list.
instance MonadTrans (Transient ) where
lift mx = Transient $ mx >>= return . Just
* Threads
| Sets the maximum number of threads that can be created for the given task
New threads are created by 'parallel', and APIs that use parallel.
restore it
| Terminate all the child threads in the given task set and continue
execution in the current thread. Useful to reap the children when a task is
done.
!> ("FATHER:", threadId st)
children st'
!> ("KILLEVENT1 ", map threadId ths' )
| Add a label to the current passing threads so it can be printed by debugging calls like `showThreads`
| Show the tree of threads hanging from the state.
| Return the state of the thread that initiated the transient computation
| Return the state variable of the type desired with which a thread, identified by his number in the treee was initiated
| Add n threads to the limit of threads. If there is no limit, the limit is set.
| Ensure that at least n threads are available for the current task set.
getNonUsedThreads :: TransIO (Maybe Int)
getNonUsedThreads= Transient $ do
Just sem -> liftIO $ Just <$> readIORef sem
Nothing -> return Nothing
| Disable tracking and therefore the ability to terminate the child threads.
By default, child threads are terminated automatically when the parent
thread dies, or they can be terminated using the kill primitives. Disabling
it may improve performance a bit, however, all threads must be well-behaved
to exit on their own to avoid a leak.
| Enable tracking and therefore the ability to terminate the child threads.
This is the default but can be used to re-enable tracking if it was
previously disabled with 'freeThreads'.
| Kill all the child threads of the current thread.
!> (threadId cont,"relabeled")
| Kill the current thread and the childs.
| Kill the childs and the thread of an state
* Extensible State: Session Data Management
| Same as 'getSData' but with a more general type. If the data is found, a
'Just' value is returned. Otherwise, a 'Nothing' value is returned.
| Retrieve a previously stored data item of the given data type from the
monad state. The data type to retrieve is implicitly determined from the
requested type context.
If the data item is not found, an 'empty' value (a void event) is returned.
Remember that an empty value stops the monad computation. If you want to
print an error message or a default value in that case, you can use an
'Alternative' composition. For example:
> getSData <|> error "no data"
> getInt = getSData <|> return (0 :: Int)
| Same as `getSData`
| 'setData' stores a data item in the monad state which can be retrieved
later using 'getData' or 'getSData'. Stored data items are keyed by their
@
import Transient.Base
data Person = Person
{ name :: String
, age :: Int
main = keep $ do
Person name age <- getSData
liftIO $ print (name, age)
@
| Accepts a function that takes the current value of the stored data type
and returns the modified value. If the function returns 'Nothing' the value
is deleted otherwise updated.
| Same as modifyData
| Same as 'setData'
| Delete the data item of the given type from the monad state.
| Same as 'delData'
| mutable state reference that can be updated (similar to STRef in the state monad)
| Run an action, if it does not succeed, undo any state changes
that it might have caused and allow aternative actions to run with the original state
| Executes the computation and reset the state either if it fails or not.
| Generator of identifiers that are unique within the current monadic
sequence They are not unique in the whole program.
| 'StreamData' represents a task in a task stream being generated.
^ More tasks to come
^ This is the last task
^ No more tasks, we are done
^ An error occurred
| An task stream generator that produces an infinite stream of tasks by
running an IO computation in a loop. A task is triggered carrying the output
of the computation. See 'parallel' for notes on the return value.
| Run an IO computation asynchronously and generate a single task carrying
the result of the computation when it completes. See 'parallel' for notes on
the return value.
| Force an async computation to run synchronously. It can be useful in an
'Alternative' composition to run the alternative only after finishing a
serialization.
| An task stream generator that produces an infinite stream of tasks by
running an IO computation periodically at the specified time interval. The
task carries the result of the computation. A new task is generated only if
the output of the computation is different from the previous one. See
'parallel' for notes on the return value.
action is run again to generate the next task, otherwise task creation
stops.
Unless the maximum number of threads (set with 'threads') has been reached,
the task is generated in a new thread and the current thread returns a void
task.
th <- liftIO myThreadId
return () !> ("finish",th)
!> ("thread created: ",th,"in",threadId parent )
!> "freed thread"
if was not a free thread
return () !> ("freeing",th,"in",threadId env)
!> ("new list for",threadId env,map threadId sbs')
free the parent
return env
putMVar sibling sbs
!> (th,"orphan")
ths <- takeMVar headpths
!> ("hang", threadId child, threadId parentProc,map threadId ths,unsafePerformIO $ readIORef $ labelth parentProc)
| kill all the child threads associated with the continuation context
ths <- takeMVar childs
putMVar childs []
!> ("KILL", map threadId ths )
| Make a transient task generator from an asynchronous callback handler.
returned to the callback; if the callback expects no return value it
can just be a @return ()@. The callback expects a setter function taking the
function is supplied by 'react'.
Callbacks from foreign code can be wrapped into such a handler and hooked
into the transient monad using 'react'. Every time the callback is called it
generates a new task for the transient monad.
| Runs a computation asynchronously without generating any events. Returns
'empty' in an 'Alternative' composition.
* non-blocking keyboard input
the option. The label is displayed on the console when the option is
activated.
predicted which one gets it.
to be displayed on the console before waiting.
| Non blocking `getLine` with a validator
!> ("received " ++ show r ++ show (unsafePerformIO myThreadId)) of
!> show (cond s)
!>"match"
XXX hoping that the previous value has been consumed by now.
otherwise its just lost by overwriting.
XXX this blocks forever if an input is not consumed by any consumer.
| Wait for the execution of `exit` and return the result or the exhaustion of thread activity
| Runs the transient computation in a child thread and keeps the main thread
running until all the user threads exit or some thread invokes 'exit'.
The main thread provides facilities to accept keyboard input in a
non-blocking but line-oriented manner. The program reads the standard input
and feeds it to all the async input consumers (e.g. 'option' and 'input').
All async input consumers contend for each line entered on the standard
input and try to read it atomically. When a consumer consumes the input
others do not get to see it, otherwise it is left in the buffer for others
to consume. If nobody consumes the input, it is discarded.
A @/@ in the input line is treated as a newline.
When using asynchronous input, regular synchronous IO APIs like getLine
cannot be used as they will contend for the standard input along with the
asynchronous input thread. Instead you can use the asynchronous input APIs
provided by transient.
All available commands handled by the command handler are displayed when the
program is run. The following commands are available:
An input not handled by the command handler can be handled by the program.
path@ command line
options. The arguments to these options are injected into the async input
channel as keyboard input to the program. Each line of input is separated by
a @/@. For example:
liftIO $ putMVar rexit $ Right Nothing
| Same as `keep` but does not read from the standard input, and therefore
the async input APIs ('option' and 'input') cannot be used in the monad.
However, keyboard input can still be passed via command line arguments as
described in 'keep'. Useful for debugging or for creating background tasks,
as well as to embed the Transient monad inside another computation. It
returns either the value returned by `exit`. or Nothing, when there are no
more threads running
| Exit the main thread, and thus all the Transient threads (and the
application if there is no more code)
--------------------------------backtracking ------------------------
| Delete all the undo actions registered till now for the given track id.
| 'backCut' for the default track; equivalent to @backCut ()@.
undo track id as argument.
to avoid recursive call tot he same handler
| 'onBack' for the default track; equivalent to @onBack ()@.
parameter is a "witness" whose data type is used to uniquely identify this
backtracking action. The value of the witness parameter is not used.
to avoid duplicate backtracking points
XXX Should we enforce retry of the same track which is being undone? If the
user specifies a different track would it make sense?
| For a given undo track id, stop executing more backtracking actions and
resume normal execution in the forward direction. Used inside an undo
action.
| Abort finish. Stop executing more finish actions and resume normal
execution. Used inside 'onFinish' actions.
| Start the undo process for the given undo track id. Performs all the undo
actions registered till now in reverse order. An undo action can use
'forward' to stop the undo process and resume forward execution. If there
are no more undo actions registered execution stops and a 'stop' action is
returned.
!!> "END"
!> ("RUNCLOSURE",length stack)
!> "END RUNCLOSURE"
!> "END EXECUTION"
!> "FORWARD EXEC"
| 'back' for the default undo track; equivalent to @back ()@.
---- finalization
| Clear all finish actions registered till now.
initFinish= backCut (FinishReason Nothing)
| Register an action that to be run when 'finish' is called. 'onFinish' can
be used multiple times to register multiple actions. Actions are run in
reverse order. Used in infix style.
parameter as a finish action to be run when 'finish' is called. Used in
infix style.
| Execute all the finalization actions registered up to the last
passed to 'finish'. The argument passed is made available in the 'onFinish'
actions invoked.
| trigger finish when the stream of data ends
---- exceptions ---
continuation. Note that multiple handlers can be installed for the same exception type.
!> "mx"
recursive catch itself
return () !> "CATCH"
| Delete all the exception handlers registered till now.
| Use it inside an exception handler. it stop executing any further exception
handlers and resume normal execution from this point on.
| catch an exception in a Transient block
The semantic is the same than `catch` but the computation and the exception handler can be multirhreaded
| throw an exception in the Transient monad
catcht1 :: Exception e => TransIO a -> (e ->TransIO a) -> TransIO a
catcht1 mx exc= Transient $ do
st <- get
case event st of
Nothing -> do
runStateT ( runTrans $ f e ) st
put st'
modify $ \s -> s{event= Just $ unsafeCoerce mx}
runCont st
was <- getData `onNothing` return NoRemote
return Nothing
Just r -> do
modify $ \s -> s{event=Nothing}
where
f e=case fromException e of
Nothing -> empty
Just e' -> exc e' | License : MIT
# LANGUAGE ExistentialQuantification #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RecordWildCards #
# LANGUAGE InstanceSigs #
module Transient.Internals where
import Control.Applicative
import Control.Monad.State
import Data.Dynamic
import qualified Data.Map as M
import System.IO.Unsafe
import Unsafe.Coerce
import Control.Exception hiding (try,onException)
import qualified Control.Exception (try)
import Control.Concurrent
import GHC.Conc(unsafeIOToSTM)
import Control.Concurrent.STM hiding (retry)
import qualified Control.Concurrent.STM as STM (retry)
import System.Mem.StableName
import Data.Maybe
import Data.List
import Data.IORef
import System.Environment
import System.IO
import qualified Data.ByteString.Char8 as BS
#ifdef DEBUG
import Data.Monoid
import Debug.Trace
import System.Exit
(!>) :: Show a => b -> a -> b
(!>) x y = trace (show y) x
infixr 0 !>
#else
(!>) :: a -> b -> a
(!>) = const
#endif
type StateIO = StateT EventF IO
newtype TransIO a = Transient { runTrans :: StateIO (Maybe a) }
type SData = ()
type EventId = Int
type TransientIO = TransIO
data LifeCycle = Alive | Parent | Listener | Dead
deriving (Eq, Show)
| EventF describes the context of a TransientIO computation :
data EventF = forall a b. EventF
{ meffects :: ()
, event :: Maybe SData
, xcomp :: StateIO (Maybe a)
, fcomp :: [b -> StateIO (Maybe b)]
, mfData :: M.Map TypeRep SData
, mfSequence :: Int
, threadId :: ThreadId
, freeTh :: Bool
, parent :: Maybe EventF
, children :: MVar [EventF]
, maxThread :: Maybe (IORef Int)
, labelth :: IORef (LifeCycle, BS.ByteString)
} deriving Typeable
type Effects =
forall a b c. TransIO a -> TransIO a -> (a -> TransIO b)
-> StateIO (StateIO (Maybe c) -> StateIO (Maybe c), Maybe a)
instance MonadState EventF TransIO where
get = Transient $ get >>= return . Just
put x = Transient $ put x >> return (Just ())
state f = Transient $ do
s <- get
let ~(a, s') = f s
put s'
return $ Just a
noTrans :: StateIO x -> TransIO x
noTrans x = Transient $ x >>= return . Just
emptyEventF :: ThreadId -> IORef (LifeCycle, BS.ByteString) -> MVar [EventF] -> EventF
emptyEventF th label childs =
EventF { meffects = mempty
, event = mempty
, xcomp = empty
, fcomp = []
, mfData = mempty
, mfSequence = 0
, threadId = th
, freeTh = False
, parent = Nothing
, children = childs
, maxThread = Nothing
, labelth = label }
runTransient :: TransIO a -> IO (Maybe a, EventF)
runTransient t = do
th <- myThreadId
label <- newIORef $ (Alive, BS.pack "top")
childs <- newMVar []
runStateT (runTrans t) $ emptyEventF th label childs
runTransState :: EventF -> TransIO x -> IO (Maybe x, EventF)
runTransState st x = runStateT (runTrans x) st
getCont :: TransIO EventF
getCont = Transient $ Just <$> get
runCont :: EventF -> StateIO (Maybe a)
runCont EventF { xcomp = mx, fcomp = fs } = do
r <- unsafeCoerce mx
case r of
Nothing -> return Nothing
Just x -> (compose fs) x
runCont' :: EventF -> IO (Maybe a, EventF)
runCont' cont = runStateT (runCont cont) cont
getContinuations :: StateIO [a -> StateIO (Maybe b)]
getContinuations = do
EventF { fcomp = fs } <- get
return $ unsafeCoerce fs
compose :: [a -> StateIO (Maybe a)] -> a -> StateIO (Maybe b)
compose [] = const empty
compose (f:fs) = \x -> f x >>= \mx -> case mx of Nothing -> return Nothing; Just x -> (compose fs) x
runClosure :: EventF -> StateIO (Maybe a)
( )
runContinuation :: EventF -> a -> StateIO (Maybe b)
runContinuation EventF { fcomp = fs } =
runTrans . (unsafeCoerce $ compose $ fs)
setContinuation :: TransIO a -> (a -> TransIO b) -> [c -> StateIO (Maybe c)] -> StateIO ()
setContinuation b c fs = do
modify $ \EventF{..} -> EventF { xcomp = runTrans b
, fcomp = (\x -> runTrans $ unsafeCoerce c x) : fs
, .. }
withContinuation :: b -> TransIO a -> TransIO a
withContinuation c mx = do
EventF { fcomp = fs, .. } <- get
put $ EventF { xcomp = runTrans mx
, fcomp = unsafeCoerce c : fs
, .. }
r <- mx
restoreStack fs
return r
restoreStack :: MonadState EventF m => [a -> StateIO (Maybe a)] -> m ()
restoreStack fs = modify $ \EventF {..} -> EventF { event = Nothing, fcomp = fs, .. }
with the next , and that the parameter type match the input of the first
runContinuations :: [a -> StateIO (Maybe b)] -> c -> StateIO (Maybe d)
runContinuations fs x = compose (unsafeCoerce fs) x
instance Functor TransIO where
fmap f mx = do
x <- mx
return $ f x
instance Applicative TransIO where
pure a = Transient . return $ Just a
f <*> g = Transient $ do
rf <- liftIO $ newIORef (Nothing,[])
rg <- liftIO $ newIORef (Nothing,[])
fs <- getContinuations
let hasWait (_:Wait:_) = True
hasWait _ = False
appf k = Transient $ do
Log rec _ full <- getData `onNothing` return (Log False [] [])
(liftIO $ writeIORef rf (Just k,full))
! > ( show $ unsafePerformIO myThreadId ) + + " APPF "
(x, full2)<- liftIO $ readIORef rg
when (hasWait full ) $
( ! > ( hasWait full,"full",full , " \nfull2",full2 ) ) $
let full'= head full: full2
in (setData $ Log rec full' full')
return $ Just k <*> x
appg x = Transient $ do
Log rec _ full <- getData `onNothing` return (Log False [] [])
liftIO $ writeIORef rg (Just x, full)
! > ( show $ unsafePerformIO myThreadId ) + + " APPG "
(k,full1) <- liftIO $ readIORef rf
when (hasWait full) $
let full'= head full: full1
in (setData $ Log rec full' full')
return $ k <*> Just x
setContinuation f appf fs
k <- runTrans f
was <- getData `onNothing` return NoRemote
when (was == WasParallel) $ setData NoRemote
Log recovery _ full <- getData `onNothing` return (Log False [] [])
if was== WasRemote || (not recovery && was == NoRemote && isNothing k )
if the first operand was a remote request
then do
restoreStack fs
return Nothing
else do
when (isJust k) $ liftIO $ writeIORef rf (k,full)
when necessary since it maybe WasParallel and Nothing
setContinuation g appg fs
x <- runTrans g
! > ( show $ unsafePerformIO myThreadId ) + + " RUN g "
Log recovery _ full' <- getData `onNothing` return (Log False [] [])
liftIO $ writeIORef rg (x,full')
restoreStack fs
k'' <- if was== WasParallel
then do
return k'
else return k
return $ k'' <*> x
instance ( Cont r ) where
m > > = k = Cont $ \c - > runCont m $ \a - > runCont ( k a ) c
instance MonadCont ( Cont r ) where
callCC f = Cont $ \c - > runCont ( f ( \a - > Cont $ \ _ - > c a ) ) c
instance Monad TransIO where
return = pure
x >>= f = Transient $ do
cont <- setEventCont x f
runCont cont
resetEventCont mk
instance MonadIO TransIO where
( \(e : : SomeException ) - > return $ Left e )
liftIO x = Transient $ liftIO x >>= return . Just
instance Monoid a => Monoid (TransIO a) where
mappend x y = mappend <$> x <*> y
mempty = return mempty
instance Alternative TransIO where
empty = Transient $ return Nothing
(<|>) = mplus
instance MonadPlus TransIO where
mzero = empty
mplus x y = Transient $ do
mx <- runTrans x
was <- getData `onNothing` return NoRemote
if was == WasRemote
then return Nothing
else case mx of
Nothing -> runTrans y
justx -> return justx
readWithErr :: (Typeable a, Read a) => String -> IO [(a, String)]
readWithErr line =
(v `seq` return [(v, left)])
`catch` (\(e :: SomeException) ->
error $ "read error trying to read type: \"" ++ show (typeOf v)
++ "\" in: " ++ " <" ++ show line ++ "> ")
where [(v, left)] = readsPrec 0 line
readsPrec' _ = unsafePerformIO . readWithErr
type Loggable a = (Show a, Read a, Typeable a)
data IDynamic =
IDyns String
| forall a. Loggable a => IDynamic a
instance Show IDynamic where
show (IDynamic x) = show (show x)
show (IDyns s) = show s
instance Read IDynamic where
readsPrec n str = map (\(x,s) -> (IDyns x,s)) $ readsPrec' n str
type Recover = Bool
type CurrentPointer = [LogElem]
type LogEntries = [LogElem]
data LogElem = Wait | Exec | Var IDynamic
deriving (Read, Show)
data Log = Log Recover CurrentPointer LogEntries
deriving (Typeable, Show)
data RemoteStatus = WasRemote | WasParallel | NoRemote
deriving (Typeable, Eq, Show)
stop :: Alternative m => m stopped
stop = empty
instance ( a , Eq a , Fractional a ) = > Fractional ( TransIO a)where
fromRational ( x:%y ) = fromInteger x % fromInteger y
instance (Num a, Eq a) => Num (TransIO a) where
fromInteger = return . fromInteger
mf + mg = (+) <$> mf <*> mg
mf * mg = (*) <$> mf <*> mg
negate f = f >>= return . negate
abs f = f >>= return . abs
signum f = f >>= return . signum
class AdditionalOperators m where
(**>) :: m a -> m b -> m b
| Run @m b@ discarding its result , after the whole task set @m a@ is
(<**) :: m a -> m b -> m a
atEnd' :: m a -> m b -> m a
atEnd' = (<**)
(<***) :: m a -> m b -> m a
atEnd :: m a -> m b -> m a
atEnd = (<***)
instance AdditionalOperators TransIO where
(**>) :: TransIO a -> TransIO b -> TransIO b
(**>) x y =
Transient $ do
runTrans x
runTrans y
(<***) :: TransIO a -> TransIO b -> TransIO a
(<***) ma mb =
Transient $ do
fs <- getContinuations
setContinuation ma (\x -> mb >> return x) fs
a <- runTrans ma
runTrans mb
restoreStack fs
return a
(<**) :: TransIO a -> TransIO b -> TransIO a
(<**) ma mb =
Transient $ do
a <- runTrans ma
runTrans mb
return a
infixr 1 <***, <**, **>
| Run @b@ once , discarding its result when the first task in task set @a@
has finished . Useful to start a singleton task after the first task has been
(<|) :: TransIO a -> TransIO b -> TransIO a
(<|) ma mb = Transient $ do
fs <- getContinuations
ref <- liftIO $ newIORef False
setContinuation ma (cont ref) fs
r <- runTrans ma
restoreStack fs
return r
where cont ref x = Transient $ do
n <- liftIO $ readIORef ref
if n == True
then return $ Just x
else do liftIO $ writeIORef ref True
runTrans mb
return $ Just x
setEventCont :: TransIO a -> (a -> TransIO b) -> StateIO EventF
setEventCont x f = do
EventF { fcomp = fs, .. }<- get
let cont'= EventF { xcomp = runTrans x
, .. }
put cont'
return cont'
resetEventCont : : Maybe a - > EventF - > StateIO ( )
resetEventCont mx = do
EventF { fcomp = fs, .. } <- get
let f mx = case mx of
Nothing -> empty
Just x -> unsafeCoerce (head fs) x
put $ EventF { xcomp = f mx
, fcomp = tailsafe fs
, .. }
return ()
tailsafe :: [a] -> [a]
tailsafe [] = []
tailsafe (_:xs) = xs
waitQSemB sem = atomicModifyIORef sem $ \n ->
if n > 0 then(n - 1, True) else (n, False)
signalQSemB sem = atomicModifyIORef sem $ \n -> (n + 1, ())
set . When set to 0 , new tasks start synchronously in the current thread .
threads :: Int -> TransIO a -> TransIO a
threads n process = do
msem <- gets maxThread
sem <- liftIO $ newIORef n
modify $ \s -> s { maxThread = Just sem }
return r
oneThread :: TransIO a -> TransIO a
oneThread comp = do
st <- get
chs <- liftIO $ newMVar []
label <- liftIO $ newIORef (Alive, BS.pack "oneThread")
let st' = st { parent = Just st
, children = chs
, labelth = label }
liftIO $ hangThread st st'
put st'
x <- comp
th <- liftIO myThreadId
liftIO $ mapM_ (killChildren1 th) chs
return x
where killChildren1 :: ThreadId -> EventF -> IO ()
killChildren1 th state = do
ths' <- modifyMVar (children state) $ \ths -> do
let (inn, ths')= partition (\st -> threadId st == th) ths
return (inn, ths')
mapM_ (killChildren1 th) ths'
mapM_ (killThread . threadId) ths'
labelState :: (MonadIO m,MonadState EventF m) => String -> m ()
labelState l = do
st <- get
liftIO $ atomicModifyIORef (labelth st) $ \(status,_) -> ((status, BS.pack l), ())
printBlock :: MVar ()
printBlock = unsafePerformIO $ newMVar ()
showThreads :: MonadIO m => EventF -> m ()
showThreads st = liftIO $ withMVar printBlock $ const $ do
mythread <- myThreadId
putStrLn "---------Threads-----------"
let showTree n ch = do
liftIO $ do
putStr $ take n $ repeat ' '
(state, label) <- readIORef $ labelth ch
if BS.null label
then putStr . show $ threadId ch
else do BS.putStr label; putStr . drop 8 . show $ threadId ch
when (state == Dead) $ putStr " dead"
putStrLn $ if mythread == threadId ch then " <--" else ""
chs <- readMVar $ children ch
mapM_ (showTree $ n + 2) $ reverse chs
showTree 0 st
topState :: TransIO EventF
topState = do
st <- get
return $ toplevel st
where toplevel st = case parent st of
Nothing -> st
Just p -> toplevel p
showState :: (Typeable a, MonadIO m, Alternative m) => String -> EventF -> m (Maybe a)
showState th top = resp
where resp = do
let thstring = drop 9 . show $ threadId top
if thstring == th
then getstate top
else do
sts <- liftIO $ readMVar $ children top
foldl (<|>) empty $ map (showState th) sts
getstate st =
case M.lookup (typeOf $ typeResp resp) $ mfData st of
Just x -> return . Just $ unsafeCoerce x
Nothing -> return Nothing
typeResp :: m (Maybe x) -> x
typeResp = undefined
addThreads' :: Int -> TransIO ()
addThreads' n= noTrans $ do
msem <- gets maxThread
case msem of
Just sem -> liftIO $ modifyIORef sem $ \n' -> n + n'
Nothing -> do
sem <- liftIO (newIORef n)
modify $ \ s -> s { maxThread = Just sem }
addThreads :: Int -> TransIO ()
addThreads n = noTrans $ do
msem <- gets maxThread
case msem of
Nothing -> return ()
Just sem -> liftIO $ modifyIORef sem $ \n' -> if n' > n then n' else n
< - gets
case of
freeThreads :: TransIO a -> TransIO a
freeThreads process = Transient $ do
st <- get
put st { freeTh = True }
r <- runTrans process
modify $ \s -> s { freeTh = freeTh st }
return r
hookedThreads :: TransIO a -> TransIO a
hookedThreads process = Transient $ do
st <- get
put st {freeTh = False}
r <- runTrans process
modify $ \st -> st { freeTh = freeTh st }
return r
killChilds :: TransIO ()
killChilds = noTrans $ do
cont <- get
liftIO $ do
killChildren $ children cont
writeIORef (labelth cont) (Alive, mempty)
return ()
killBranch :: TransIO ()
killBranch = noTrans $ do
st <- get
liftIO $ killBranch' st
killBranch' :: EventF -> IO ()
killBranch' cont = do
killChildren $ children cont
let thisth = threadId cont
mparent = parent cont
when (isJust mparent) $
modifyMVar_ (children $ fromJust mparent) $ \sts ->
return $ filter (\st -> threadId st /= thisth) sts
killThread $ thisth
getData :: (MonadState EventF m, Typeable a) => m (Maybe a)
getData = resp
where resp = do
list <- gets mfData
case M.lookup (typeOf $ typeResp resp) list of
Just x -> return . Just $ unsafeCoerce x
Nothing -> return Nothing
typeResp :: m (Maybe x) -> x
typeResp = undefined
getSData :: Typeable a => TransIO a
getSData = Transient getData
getState :: Typeable a => TransIO a
getState = getSData
data type , and therefore only one item of a given type can be stored . A
newtype wrapper can be used to distinguish two data items of the same type .
import Control . Monad . IO.Class ( liftIO )
import Data . Typeable
} deriving
setData $ Person " " 55
setData :: (MonadState EventF m, Typeable a) => a -> m ()
setData x = modify $ \st -> st { mfData = M.insert t (unsafeCoerce x) (mfData st) }
where t = typeOf x
modifyData :: (MonadState EventF m, Typeable a) => (Maybe a -> Maybe a) -> m ()
modifyData f = modify $ \st -> st { mfData = M.alter alterf t (mfData st) }
where typeResp :: (Maybe a -> b) -> a
typeResp = undefined
t = typeOf (typeResp f)
alterf mx = unsafeCoerce $ f x'
where x' = case mx of
Just x -> Just $ unsafeCoerce x
Nothing -> Nothing
modifyState :: (MonadState EventF m, Typeable a) => (Maybe a -> Maybe a) -> m ()
modifyState = modifyData
setState :: (MonadState EventF m, Typeable a) => a -> m ()
setState = setData
delData :: (MonadState EventF m, Typeable a) => a -> m ()
delData x = modify $ \st -> st { mfData = M.delete (typeOf x) (mfData st) }
delState :: (MonadState EventF m, Typeable a) => a -> m ()
delState = delData
STRefs for the Transient monad
newtype Ref a = Ref (IORef a)
Initialized the first time it is set .
setRState:: Typeable a => a -> TransIO ()
setRState x= do
Ref ref <- getSData
liftIO $ atomicModifyIORef ref $ const (x,())
<|> do
ref <- liftIO (newIORef x)
setData $ Ref ref
getRState :: Typeable a => TransIO a
getRState= do
Ref ref <- getSData
liftIO $ readIORef ref
delRState x= delState (undefined `asTypeOf` ref x)
where ref :: a -> IORef a
ref= undefined
try :: TransIO a -> TransIO a
try mx = do
sd <- gets mfData
mx <|> (modify (\s -> s { mfData = sd }) >> empty)
sandbox :: TransIO a -> TransIO a
sandbox mx = do
sd <- gets mfData
mx <*** modify (\s ->s { mfData = sd})
genId :: MonadState EventF m => m Int
genId = do
st <- get
let n = mfSequence st
put st { mfSequence = n + 1 }
return n
getPrevId :: MonadState EventF m => m Int
getPrevId = gets mfSequence
instance Read SomeException where
readsPrec n str = [(SomeException $ ErrorCall s, r)]
where [(s , r)] = read str
data StreamData a =
deriving (Typeable, Show,Read)
waitEvents :: IO a -> TransIO a
waitEvents io = do
mr <- parallel (SMore <$> io)
case mr of
SMore x -> return x
SError e -> back e
async :: IO a -> TransIO a
async io = do
mr <- parallel (SLast <$> io)
case mr of
SLast x -> return x
SError e -> back e
computation . Note that in Applicatives it might result in an undesired
sync :: TransIO a -> TransIO a
sync x = do
setData WasRemote
r <- x
delData WasRemote
return r
| @spawn = freeThreads .
spawn :: IO a -> TransIO a
spawn = freeThreads . waitEvents
sample :: Eq a => IO a -> Int -> TransIO a
sample action interval = do
v <- liftIO action
prev <- liftIO $ newIORef v
waitEvents (loop action prev) <|> async (return v)
where loop action prev = loop'
where loop' = do
threadDelay interval
v <- action
v' <- readIORef prev
if v /= v' then writeIORef prev v >> return v else loop'
| Run an IO action one or more times to generate a stream of tasks . The IO
action returns a ' StreamData ' . When it returns an ' SMore ' or ' SLast ' a new
task is triggered with the result value . If the return value is ' SMore ' , the
parallel :: IO (StreamData b) -> TransIO (StreamData b)
parallel ioaction = Transient $ do
cont <- get
! > " PARALLEL "
case event cont of
j@(Just _) -> do
put cont { event = Nothing }
return $ unsafeCoerce j
Nothing -> do
liftIO $ atomicModifyIORef (labelth cont) $ \(_, lab) -> ((Parent, lab), ())
liftIO $ loop cont ioaction
was <- getData `onNothing` return NoRemote
when (was /= WasRemote) $ setData WasParallel
return Nothing
| Execute the IO action and the continuation
loop :: EventF -> IO (StreamData t) -> IO ()
loop parentc rec = forkMaybe parentc $ \cont -> do
Execute the IO computation and then the closure - continuation
liftIO $ atomicModifyIORef (labelth cont) $ const ((Listener,BS.pack "wait"),())
let loop'= do
mdat <- rec `catch` \(e :: SomeException) -> return $ SError e
case mdat of
se@(SError _) -> setworker cont >> iocont se cont
SDone -> setworker cont >> iocont SDone cont
last@(SLast _) -> setworker cont >> iocont last cont
more@(SMore _) -> do
forkMaybe cont $ iocont more
loop'
where
setworker cont= liftIO $ atomicModifyIORef (labelth cont) $ const ((Alive,BS.pack "work"),())
iocont dat cont = do
let cont'= cont{event= Just $ unsafeCoerce dat}
runStateT (runCont cont') cont'
return ()
loop'
return ()
where
# INLINABLE forkMaybe #
forkMaybe parent proc = do
case maxThread parent of
Nothing -> forkIt parent proc
Just sem -> do
dofork <- waitQSemB sem
if dofork then forkIt parent proc else proc parent
forkIt parent proc= do
chs <- liftIO $ newMVar []
label <- newIORef (Alive, BS.pack "work")
let cont = parent{parent=Just parent,children= chs, labelth= label}
forkFinally1 (do
th <- myThreadId
let cont'= cont{threadId=th}
when(not $ freeTh parent )$ hangThread parent cont'
proc cont')
$ \me -> do
case me of
Left e -> exceptBack cont e >> return ()
_ -> do
case maxThread cont of
Nothing -> return ()
th <- myThreadId
(can,label) <- atomicModifyIORef (labelth cont) $ \(l@(status,label)) ->
((if status== Alive then Dead else status, label),l)
when (can/= Parent ) $ free th parent
return ()
forkFinally1 :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally1 action and_then =
mask $ \restore -> forkIO $ Control.Exception.try (restore action) >>= and_then
free th env= do
let sibling= children env
(sbs',found) <- modifyMVar sibling $ \sbs -> do
let (sbs', found) = drop [] th sbs
return (sbs',(sbs',found))
if found
then do
(typ,_) <- readIORef $ labelth env
if (null sbs' && typ /= Listener && isJust (parent env))
then free (threadId env) ( fromJust $ parent env)
else return ()
where
drop processed th []= (processed,False)
drop processed th (ev:evts)| th == threadId ev= (processed ++ evts, True)
| otherwise= drop (ev:processed) th evts
hangThread parentProc child = do
let headpths= children parentProc
modifyMVar_ headpths $ \ths -> return (child:ths)
( child : )
killChildren childs = do
ths <- modifyMVar childs $ \ths -> return ([],ths)
mapM_ (killChildren . children) ths
The first parameter is a callback . The second parameter is a value to be
@eventdata@ as an argument and returning a value to the callback ; this
react
:: Typeable eventdata
=> ((eventdata -> IO response) -> IO ())
-> IO response
-> TransIO eventdata
react setHandler iob= Transient $ do
cont <- get
case event cont of
Nothing -> do
liftIO $ setHandler $ \dat ->do
runStateT (runCont cont) cont{event= Just $ unsafeCoerce dat}
iob
was <- getData `onNothing` return NoRemote
when (was /= WasRemote) $ setData WasParallel
return Nothing
j@(Just _) -> do
put cont{event=Nothing}
return $ unsafeCoerce j
abduce = async $ return ()
getLineRef= unsafePerformIO $ newTVarIO Nothing
roption= unsafePerformIO $ newMVar []
| Waits on stdin in a loop and triggers a new task every time the input data
matches the first parameter . The value contained by the task is the matched
value i.e. the first argument itself . The second parameter is a label for
Note that if two independent invocations of ' option ' are expecting the same
input , only one of them gets it and triggers a task . It can not be
option :: (Typeable b, Show b, Read b, Eq b) =>
b -> String -> TransIO b
option ret message= do
let sret= show ret
liftIO $ putStrLn $ "Enter "++sret++"\tto: " ++ message
liftIO $ modifyMVar_ roption $ \msgs-> return $ sret:msgs
waitEvents $ getLine' (==ret)
liftIO $ putStr "\noption: " >> putStrLn (show ret)
return ret
| Waits on stdin and triggers a task when a console input matches the
predicate specified in the first argument . The second parameter is a string
input cond prompt= input' Nothing cond prompt
input' :: (Typeable a, Read a,Show a) => Maybe a -> (a -> Bool) -> String -> TransIO a
input' mv cond prompt= Transient . liftIO $do
putStr prompt >> hFlush stdout
atomically $ do
mr <- readTVar getLineRef
case mr of
Nothing -> STM.retry
Just r ->
case reads2 r of
(s,_):_ -> if cond s !> show (cond s)
then do
unsafeIOToSTM $ print s
writeTVar getLineRef Nothing !>"match"
return $ Just s
else return mv
_ -> return mv !> "return "
where
reads2 s= x where
x= if typeOf(typeOfr x) == typeOf ""
then unsafeCoerce[(s,"")]
else unsafePerformIO $ return (reads s) `catch` \(e :: SomeException) -> (return [])
typeOfr :: [(a,String)] -> a
typeOfr = undefined
getLine' cond= do
atomically $ do
mr <- readTVar getLineRef
case mr of
Nothing -> STM.retry
Just r ->
then do
return s
else STM.retry
_ -> STM.retry
reads1 s=x where
x= if typeOf(typeOfr x) == typeOf "" then unsafeCoerce[(s,"")] else readsPrec' 0 s
typeOfr :: [(a,String)] -> a
typeOfr = undefined
inputLoop= do
r <- getLine
atomically $ writeTVar getLineRef Nothing
processLine r
inputLoop
processLine r= do
let rs = breakSlash [] r
e.g. try this " xxx / xxx " on the stdin
liftIO $ mapM_ (\ r ->
atomically $ do
threadDelay 1000000
t <- readTVar getLineRef
when (isJust t) STM.retry
writeTVar getLineRef $ Just r ) rs
where
breakSlash :: [String] -> String -> [String]
breakSlash [] ""= [""]
breakSlash s ""= s
breakSlash res ('\"':s)=
let (r,rest) = span(/= '\"') s
in breakSlash (res++[r]) $ tail1 rest
breakSlash res s=
let (r,rest) = span(\x -> x /= '/' && x /= ' ') s
in breakSlash (res++[r]) $ tail1 rest
tail1 []=[]
tail1 x= tail x
stay rexit= takeMVar rexit
`catch` \(e :: BlockedIndefinitelyOnMVar) -> return Nothing
newtype Exit a= Exit a deriving Typeable
A built - in interactive command handler also reads the stdin asynchronously .
1 . @ps@ : show threads
2 . : inspect the log of a thread
3 . @end@ , @exit@ : terminate the program
> foo -p ps / end
keep :: Typeable a => TransIO a -> IO (Maybe a)
keep mx = do
liftIO $ hSetBuffering stdout LineBuffering
rexit <- newEmptyMVar
forkIO $ do
runTransient $ do
st <- get
setData $ Exit rexit
(async (return ()) >> labelState "input" >> liftIO inputLoop)
<|> do
option "ps" "show threads"
liftIO $ showThreads st
empty
<|> do
option "log" "inspect the log of a thread"
th <- input (const True) "thread number>"
ml <- liftIO $ showState th st
liftIO $ print $ fmap (\(Log _ _ log) -> reverse log) ml
empty
<|> do
option "end" "exit"
killChilds
liftIO $ putMVar rexit Nothing
empty
<|> mx
return ()
threadDelay 10000
execCommandLine
stay rexit
where
type1 :: TransIO a -> Either String (Maybe a)
type1= undefined
keep' :: Typeable a => TransIO a -> IO (Maybe a)
keep' mx = do
liftIO $ hSetBuffering stdout LineBuffering
rexit <- newEmptyMVar
forkIO $ do
runTransient $ do
setData $ Exit rexit
mx
return ()
threadDelay 10000
forkIO $ execCommandLine
stay rexit
execCommandLine= do
args <- getArgs
let mindex = findIndex (\o -> o == "-p" || o == "--path" ) args
when (isJust mindex) $ do
let i= fromJust mindex +1
when (length args >= i) $ do
let path= args !! i
putStr "Executing: " >> print path
processLine path
exit :: Typeable a => a -> TransIO a
exit x= do
Exit rexit <- getSData <|> error "exit: not the type expected" `asTypeOf` type1 x
liftIO $ putMVar rexit $ Just x
stop
where
type1 :: a -> TransIO (Exit (MVar (Maybe a)))
type1= undefined
| If the first parameter is ' Nothing ' return the second parameter otherwise
return the first parameter ..
onNothing :: Monad m => m (Maybe b) -> m b -> m b
onNothing iox iox'= do
mx <- iox
case mx of
Just x -> return x
Nothing -> iox'
data Backtrack b= Show b =>Backtrack{backtracking :: Maybe b
,backStack :: [EventF] }
deriving Typeable
backCut :: (Typeable b, Show b) => b -> TransientIO ()
backCut reason= Transient $ do
delData $ Backtrack (Just reason) []
return $ Just ()
undoCut :: TransientIO ()
undoCut = backCut ()
| Run the action in the first parameter and register the second parameter as
the undo action . On undo ( ' back ' ) the second parameter is called with the
# NOINLINE onBack #
onBack :: (Typeable b, Show b) => TransientIO a -> ( b -> TransientIO a) -> TransientIO a
onBack ac bac = registerBack (typeof bac) $ Transient $ do
Backtrack mreason stack <- getData `onNothing` backStateOf (typeof bac)
runTrans $ case mreason of
Nothing -> ac
Just reason -> do
bac reason
where
typeof :: (b -> TransIO a) -> b
typeof = undefined
onUndo :: TransientIO a -> TransientIO a -> TransientIO a
onUndo x y= onBack x (\() -> y)
| Register an undo action to be executed when backtracking . The first
# NOINLINE registerUndo #
registerBack :: (Typeable b, Show b) => b -> TransientIO a -> TransientIO a
registerBack witness f = Transient $ do
! ! > " "
md <- getData `asTypeOf` (Just <$> backStateOf witness)
case md of
Just (Backtrack _ []) -> empty
Just (bss@(Backtrack b (bs@((EventF _ _ x' _ _ _ _ _ _ _ _ _):_)))) ->
when (isNothing b) $ do
addrx <- addr x
setData $ if addrx == addrx' then bss else Backtrack mwit (cont:bs)
Nothing -> setData $ Backtrack mwit [cont]
runTrans f
where
mwit= Nothing `asTypeOf` (Just witness)
addr x = liftIO $ return . hashStableName =<< (makeStableName $! x)
registerUndo :: TransientIO a -> TransientIO a
registerUndo f= registerBack () f
forward :: (Typeable b, Show b) => b -> TransIO ()
forward reason= Transient $ do
Backtrack _ stack <- getData `onNothing` (backStateOf reason)
setData $ Backtrack(Nothing `asTypeOf` Just reason) stack
return $ Just ()
| ' forward ' for the default undo track ; equivalent to @forward ( ) @.
retry= forward ()
noFinish= continue
back :: (Typeable b, Show b) => b -> TransientIO a
back reason = Transient $ do
bs <- getData `onNothing` backStateOf reason
! ! > " GOBACK "
where
goBackt (Backtrack b (stack@(first : bs)) )= do
setData $ Backtrack (Just reason) stack
Backtrack back _ <- getData `onNothing` backStateOf reason
case mr of
Just x -> case back of
! > ( " BACK AGAIN",back )
backStateOf :: (Monad m, Show a, Typeable a) => a -> m (Backtrack a)
backStateOf reason= return $ Backtrack (Nothing `asTypeOf` (Just reason)) []
undo :: TransIO a
undo= back ()
newtype Finish= Finish String deriving Show
instance Exception Finish
newtype FinishReason= FinishReason ( Maybe SomeException ) deriving ( Typeable , Show )
onFinish :: (Finish ->TransIO ()) -> TransIO ()
onFinish f= onException' (return ()) f
| Run the action specified in the first parameter and register the second
onFinish' ::TransIO a ->(Finish ->TransIO a) -> TransIO a
onFinish' proc f= proc `onException'` f
' initFinish ' , in reverse order and continue the execution . Either an exception or ' Nothing ' can be
initFinish = cutExceptions
finish :: String -> TransIO ()
finish reason= (throwt $ Finish reason) <|> return()
checkFinalize v=
case v of
SDone -> stop
SLast x -> return x
SError e -> throwt e
SMore x -> return x
| Install an exception handler . Handlers are executed in reverse ( i.e. last in , first out ) order when such exception happens in the
The semantic is thus very different than the one of ` Control . Exception . Base.onException `
onException :: Exception e => (e -> TransIO ()) -> TransIO ()
onException exc= return () `onException'` exc
onException' :: Exception e => TransIO a -> (e -> TransIO a) -> TransIO a
onException' mx f= onAnyException mx $ \e ->
case fromException e of
Nothing -> empty
Just e' -> f e'
where
onAnyException :: TransIO a -> (SomeException ->TransIO a) -> TransIO a
onAnyException mx f= ioexp `onBack` f
ioexp = Transient $ do
st <- get
(mx,st') <- liftIO $ (runStateT (do
case event st of
Nothing -> do
modify $ \s -> s{event= Just $ unsafeCoerce r}
runCont st
was <- getData `onNothing` return NoRemote
when (was /= WasRemote) $ setData WasParallel
return Nothing
Just r -> do
modify $ \s -> s{event=Nothing}
return $ unsafeCoerce r) st)
`catch` exceptBack st
put st'
return mx
runStateT ( runTrans $ back e ) st
`catch` exceptBack st
cutExceptions :: TransIO ()
cutExceptions= backCut (undefined :: SomeException)
continue :: TransIO ()
continue = forward (undefined :: SomeException) !> "CONTINUE"
catcht :: Exception e => TransIO b -> (e -> TransIO b) -> TransIO b
catcht mx exc= do
rpassed <- liftIO $ newIORef False
sandbox $ do
cutExceptions
r <- onException' mx (\e -> do
passed <- liftIO $ readIORef rpassed
if not passed then continue >> exc e else empty)
liftIO $ writeIORef rpassed True
return r
where
sandbox mx= do
exState <- getState <|> backStateOf (undefined :: SomeException)
mx
<*** do setState exState
throwt :: Exception e => e -> TransIO a
throwt= back . toException
( mx , st ' ) < - liftIO $ ( runStateT(runTrans mx ) st ) ` catch ` \(e : : SomeException ) - >
when ( was /= WasRemote ) $ setData WasParallel
return $ unsafeCoerce r
|
d8c8accbd7314f5946120184f6f1918fbf64de09dfacceea599d3d88115f65e9 | astrada/ocamlfuse | hello.ml | open Unix
open LargeFile
open Bigarray
open Fuse
let default_stats = LargeFile.stat "."
let fname = "hello"
let name = "/" ^ fname
let contents : Fuse.buffer =
Array1.of_array Bigarray.char Bigarray.c_layout
[| 'H'; 'e'; 'l'; 'l'; 'o'; ' '; 'w'; 'o'; 'r'; 'l'; 'd'; '!' |]
let do_getattr path =
if path = "/" then default_stats
else if path = name then
{
default_stats with
st_nlink = 1;
st_kind = S_REG;
st_perm = 0o444;
st_size = Int64.of_int (Array1.dim contents);
}
else raise (Unix_error (ENOENT, "stat", path))
let do_readdir path _ =
if path = "/" then [ "."; ".."; fname ]
else raise (Unix_error (ENOENT, "readdir", path))
let do_fopen path _flags =
if path = name then None else raise (Unix_error (ENOENT, "open", path))
let do_read path buf ofs _ =
if path = name then (
if ofs > Int64.of_int max_int then 0
else
let ofs = Int64.to_int ofs in
let len = min (Array1.dim contents - ofs) (Array1.dim buf) in
Array1.blit (Array1.sub contents ofs len) (Array1.sub buf 0 len);
len )
else raise (Unix_error (ENOENT, "read", path))
let _ =
main Sys.argv
{
default_operations with
getattr = do_getattr;
readdir = do_readdir;
fopen = do_fopen;
read = do_read;
}
| null | https://raw.githubusercontent.com/astrada/ocamlfuse/08f90ac0b976b94022a7ecac992da9f88e6cd78b/example/hello.ml | ocaml | open Unix
open LargeFile
open Bigarray
open Fuse
let default_stats = LargeFile.stat "."
let fname = "hello"
let name = "/" ^ fname
let contents : Fuse.buffer =
Array1.of_array Bigarray.char Bigarray.c_layout
[| 'H'; 'e'; 'l'; 'l'; 'o'; ' '; 'w'; 'o'; 'r'; 'l'; 'd'; '!' |]
let do_getattr path =
if path = "/" then default_stats
else if path = name then
{
default_stats with
st_nlink = 1;
st_kind = S_REG;
st_perm = 0o444;
st_size = Int64.of_int (Array1.dim contents);
}
else raise (Unix_error (ENOENT, "stat", path))
let do_readdir path _ =
if path = "/" then [ "."; ".."; fname ]
else raise (Unix_error (ENOENT, "readdir", path))
let do_fopen path _flags =
if path = name then None else raise (Unix_error (ENOENT, "open", path))
let do_read path buf ofs _ =
if path = name then (
if ofs > Int64.of_int max_int then 0
else
let ofs = Int64.to_int ofs in
let len = min (Array1.dim contents - ofs) (Array1.dim buf) in
Array1.blit (Array1.sub contents ofs len) (Array1.sub buf 0 len);
len )
else raise (Unix_error (ENOENT, "read", path))
let _ =
main Sys.argv
{
default_operations with
getattr = do_getattr;
readdir = do_readdir;
fopen = do_fopen;
read = do_read;
}
|
|
fa81d76185603a64b6ccd16d2877f45eabbfd39df8624ba5915dd4e8d9982cb6 | janestreet/base | ordering.mli | (** [Ordering] is intended to make code that matches on the result of a comparison
more concise and easier to read.
For example, instead of writing:
{[
let r = compare x y in
if r < 0 then
...
else if r = 0 then
...
else
...
]}
you could simply write:
{[
match Ordering.of_int (compare x y) with
| Less -> ...
| Equal -> ...
| Greater -> ...
]}
*)
open! Import
type t =
| Less
| Equal
| Greater
[@@deriving_inline compare, hash, sexp, sexp_grammar]
include Ppx_compare_lib.Comparable.S with type t := t
include Ppx_hash_lib.Hashable.S with type t := t
include Sexplib0.Sexpable.S with type t := t
val t_sexp_grammar : t Sexplib0.Sexp_grammar.t
[@@@end]
(*_ Avoid [@@deriving_inline enumerate] due to circular dependency *)
val all : t list
include Equal.S with type t := t
* [ of_int n ] is :
{ v
Less if n < 0
Equal if n = 0
Greater if n > 0
v }
{v
Less if n < 0
Equal if n = 0
Greater if n > 0
v} *)
val of_int : int -> t
(** [to_int t] is:
{v
Less -> -1
Equal -> 0
Greater -> 1
v}
It can be useful when writing a comparison function to allow one to return
[Ordering.t] values and transform them to [int]s later. *)
val to_int : t -> int
module Export : sig
type _ordering = t =
| Less
| Equal
| Greater
end
| null | https://raw.githubusercontent.com/janestreet/base/db8a9e93393074a2eb52db0b121f891c1c5bd392/src/ordering.mli | ocaml | * [Ordering] is intended to make code that matches on the result of a comparison
more concise and easier to read.
For example, instead of writing:
{[
let r = compare x y in
if r < 0 then
...
else if r = 0 then
...
else
...
]}
you could simply write:
{[
match Ordering.of_int (compare x y) with
| Less -> ...
| Equal -> ...
| Greater -> ...
]}
_ Avoid [@@deriving_inline enumerate] due to circular dependency
* [to_int t] is:
{v
Less -> -1
Equal -> 0
Greater -> 1
v}
It can be useful when writing a comparison function to allow one to return
[Ordering.t] values and transform them to [int]s later. |
open! Import
type t =
| Less
| Equal
| Greater
[@@deriving_inline compare, hash, sexp, sexp_grammar]
include Ppx_compare_lib.Comparable.S with type t := t
include Ppx_hash_lib.Hashable.S with type t := t
include Sexplib0.Sexpable.S with type t := t
val t_sexp_grammar : t Sexplib0.Sexp_grammar.t
[@@@end]
val all : t list
include Equal.S with type t := t
* [ of_int n ] is :
{ v
Less if n < 0
Equal if n = 0
Greater if n > 0
v }
{v
Less if n < 0
Equal if n = 0
Greater if n > 0
v} *)
val of_int : int -> t
val to_int : t -> int
module Export : sig
type _ordering = t =
| Less
| Equal
| Greater
end
|
65ca7e8372316010b5e2de3351a57c78c5e120cdedc45f155b1f50362606ee7a | sionescu/iolib | address-arithmetic.lisp | ;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
;;;
;;; --- Arithmetic with addresses and network masks.
;;;
(in-package :iolib/sockets)
(defun make-netmask (&key cidr class)
"Create a subnet mask by specifying either its class(:A, :B or :C) or
a CIDR suffix(a number between 0 and 32)."
(assert (or cidr class) (cidr class) "You must either specify a CIDR or a network class.")
(cond
(cidr (check-type cidr (mod 33) "a number between 0 and 32"))
(class (check-type class (member :a :b :c)
"a valid network class - one of :A, :B or :C")
(setf cidr (case class (:a 8) (:b 16) (:c 24)))))
(let ((mask #xFFFFFFFF))
(declare (type ub32 mask))
(setf (ldb (byte (- 32 cidr) 0) mask) 0)
(make-instance 'ipv4-address :name (integer-to-vector mask))))
(defun ensure-netmask (thing)
"If THING is of type IPV4-ADDRESS it is returned as is; if keyword it must be one of
:A, :B or :C otherwise it's treated as a CIDR suffix."
(etypecase thing
(ipv4-address thing)
(unsigned-byte (make-netmask :cidr thing))
(keyword (make-netmask :class thing))))
(defgeneric inet-address-network-portion (address netmask)
(:documentation "Apply network netmask NETMASK to ADDRESS in order to calculate the
network part of ADDRESS.")
(:method ((address ipv4-address) netmask)
(setf netmask (ensure-netmask netmask))
(let ((v (make-array 4 :element-type 'ub8))
(av (address-name address))
(mv (address-name netmask)))
(dotimes (i 4)
(setf (aref v i)
(logand (aref av i)
(aref mv i))))
(make-instance 'ipv4-address :name v))))
(defgeneric inet-address-host-portion (address netmask)
(:documentation "Apply network netmask NETMASK to ADDRESS in order to calculate the
host part of ADDRESS.")
(:method ((address ipv4-address) netmask)
(setf netmask (ensure-netmask netmask))
(let ((v (make-array 4 :element-type 'ub8))
(av (address-name address))
(mv (address-name netmask)))
(dotimes (i 4)
(setf (aref v i)
(logand (aref av i)
(logxor (aref mv i) 255))))
(make-instance 'ipv4-address :name v))))
(defclass ipv4-network ()
((address :accessor address-of)
(netmask :accessor netmask-of)
(cidr :accessor cidr-of))
(:documentation "IPv4 network: an address plus a netmask."))
(declaim (inline count-trailing-zeroes/32))
(defun count-trailing-zeroes/32 (n)
(declare (optimize speed)
(type (unsigned-byte 32) n))
(1- (integer-length (logand n (- n)))))
(defun cidr-subnet-zeroes (netmask)
(count-trailing-zeroes/32 (vector-to-integer (address-name netmask))))
(defmethod initialize-instance :after ((network ipv4-network)
&key address netmask)
(check-type address ipv4-address "an Ipv4 address")
(check-type netmask ipv4-address "an Ipv4 netmask")
(setf (cidr-of network) (- 32 (cidr-subnet-zeroes netmask)))
(setf (netmask-of network) netmask)
(setf (address-of network)
(inet-address-network-portion address netmask)))
(defmethod print-object ((network ipv4-network) stream)
(let ((namestring
(format nil "~A/~A"
(address-to-string (address-of network))
(cidr-of network))))
(if (or *print-readably* *print-escape*)
(format stream "#/~S/~A" 'net namestring)
(write-string namestring stream))))
(defgeneric ipv4-network= (net1 net2)
(:documentation "Returns T if the addresses and the netmasks of the
two arguments are respectively ADDRESS=.")
(:method ((net1 ipv4-network) (net2 ipv4-network))
(and (address= (address-of net1) (address-of net2))
(address= (netmask-of net1) (netmask-of net2)))))
(defgeneric inet-address-in-network-p (address network)
(:documentation "Return T if ADDRESS is part of the subnet specified by NETWORK.")
(:method ((address ipv4-address) (network ipv4-network))
(address= (inet-address-network-portion address (netmask-of network))
(address-of network))))
(defgeneric inet-addresses-in-same-network-p (address1 address2 network)
(:documentation "Return T if ADDRESS1 and ADDRESS2 are both part part of the
subnet specified by NETWORK.")
(:method ((address1 ipv4-address) (address2 ipv4-address) (network ipv4-network))
(let ((address1-network (inet-address-network-portion address1 (netmask-of network)))
(address2-network (inet-address-network-portion address2 (netmask-of network))))
(and (address= address1-network (address-of network))
(address= address2-network (address-of network))))))
(defgeneric inet-address-network-class (address)
(:documentation "Return the network class of ADDRESS: one of :A, :B, :C, :D or :E .")
(:method ((address ipv4-address))
(let ((octet (aref (address-name address) 0)))
(cond
((= #b0000 (ldb (byte 1 7) octet)) :a) ; 0.0.0.0 - 127.255.255.255
128.0.0.0 - 191.255.255.255
192.0.0.0 - 223.255.255.255
224.0.0.0 - 239.255.255.255
240.0.0.0 - 255.255.255.255
))))
(defgeneric inet-address-private-p (address)
(:documentation "Returns T if ADDRESS is in a private network range.
Private IPv4 networks are 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
See for details.")
(:method ((address ipv4-address))
(let* ((address-name (address-name address))
(first (aref address-name 0))
(second (aref address-name 1)))
(values (or (= first 10)
(and (= first 172)
(<= 16 second 31))
(and (= first 192)
(= second 168)))
(inet-address-network-class address))))
(:method ((address address))
nil))
| null | https://raw.githubusercontent.com/sionescu/iolib/dac715c81db55704db623d8b2cfc399ebcf6175f/src/sockets/address-arithmetic.lisp | lisp | -*- Mode: Lisp; indent-tabs-mode: nil -*-
--- Arithmetic with addresses and network masks.
if keyword it must be one of
0.0.0.0 - 127.255.255.255 |
(in-package :iolib/sockets)
(defun make-netmask (&key cidr class)
"Create a subnet mask by specifying either its class(:A, :B or :C) or
a CIDR suffix(a number between 0 and 32)."
(assert (or cidr class) (cidr class) "You must either specify a CIDR or a network class.")
(cond
(cidr (check-type cidr (mod 33) "a number between 0 and 32"))
(class (check-type class (member :a :b :c)
"a valid network class - one of :A, :B or :C")
(setf cidr (case class (:a 8) (:b 16) (:c 24)))))
(let ((mask #xFFFFFFFF))
(declare (type ub32 mask))
(setf (ldb (byte (- 32 cidr) 0) mask) 0)
(make-instance 'ipv4-address :name (integer-to-vector mask))))
(defun ensure-netmask (thing)
:A, :B or :C otherwise it's treated as a CIDR suffix."
(etypecase thing
(ipv4-address thing)
(unsigned-byte (make-netmask :cidr thing))
(keyword (make-netmask :class thing))))
(defgeneric inet-address-network-portion (address netmask)
(:documentation "Apply network netmask NETMASK to ADDRESS in order to calculate the
network part of ADDRESS.")
(:method ((address ipv4-address) netmask)
(setf netmask (ensure-netmask netmask))
(let ((v (make-array 4 :element-type 'ub8))
(av (address-name address))
(mv (address-name netmask)))
(dotimes (i 4)
(setf (aref v i)
(logand (aref av i)
(aref mv i))))
(make-instance 'ipv4-address :name v))))
(defgeneric inet-address-host-portion (address netmask)
(:documentation "Apply network netmask NETMASK to ADDRESS in order to calculate the
host part of ADDRESS.")
(:method ((address ipv4-address) netmask)
(setf netmask (ensure-netmask netmask))
(let ((v (make-array 4 :element-type 'ub8))
(av (address-name address))
(mv (address-name netmask)))
(dotimes (i 4)
(setf (aref v i)
(logand (aref av i)
(logxor (aref mv i) 255))))
(make-instance 'ipv4-address :name v))))
(defclass ipv4-network ()
((address :accessor address-of)
(netmask :accessor netmask-of)
(cidr :accessor cidr-of))
(:documentation "IPv4 network: an address plus a netmask."))
(declaim (inline count-trailing-zeroes/32))
(defun count-trailing-zeroes/32 (n)
(declare (optimize speed)
(type (unsigned-byte 32) n))
(1- (integer-length (logand n (- n)))))
(defun cidr-subnet-zeroes (netmask)
(count-trailing-zeroes/32 (vector-to-integer (address-name netmask))))
(defmethod initialize-instance :after ((network ipv4-network)
&key address netmask)
(check-type address ipv4-address "an Ipv4 address")
(check-type netmask ipv4-address "an Ipv4 netmask")
(setf (cidr-of network) (- 32 (cidr-subnet-zeroes netmask)))
(setf (netmask-of network) netmask)
(setf (address-of network)
(inet-address-network-portion address netmask)))
(defmethod print-object ((network ipv4-network) stream)
(let ((namestring
(format nil "~A/~A"
(address-to-string (address-of network))
(cidr-of network))))
(if (or *print-readably* *print-escape*)
(format stream "#/~S/~A" 'net namestring)
(write-string namestring stream))))
(defgeneric ipv4-network= (net1 net2)
(:documentation "Returns T if the addresses and the netmasks of the
two arguments are respectively ADDRESS=.")
(:method ((net1 ipv4-network) (net2 ipv4-network))
(and (address= (address-of net1) (address-of net2))
(address= (netmask-of net1) (netmask-of net2)))))
(defgeneric inet-address-in-network-p (address network)
(:documentation "Return T if ADDRESS is part of the subnet specified by NETWORK.")
(:method ((address ipv4-address) (network ipv4-network))
(address= (inet-address-network-portion address (netmask-of network))
(address-of network))))
(defgeneric inet-addresses-in-same-network-p (address1 address2 network)
(:documentation "Return T if ADDRESS1 and ADDRESS2 are both part part of the
subnet specified by NETWORK.")
(:method ((address1 ipv4-address) (address2 ipv4-address) (network ipv4-network))
(let ((address1-network (inet-address-network-portion address1 (netmask-of network)))
(address2-network (inet-address-network-portion address2 (netmask-of network))))
(and (address= address1-network (address-of network))
(address= address2-network (address-of network))))))
(defgeneric inet-address-network-class (address)
(:documentation "Return the network class of ADDRESS: one of :A, :B, :C, :D or :E .")
(:method ((address ipv4-address))
(let ((octet (aref (address-name address) 0)))
(cond
128.0.0.0 - 191.255.255.255
192.0.0.0 - 223.255.255.255
224.0.0.0 - 239.255.255.255
240.0.0.0 - 255.255.255.255
))))
(defgeneric inet-address-private-p (address)
(:documentation "Returns T if ADDRESS is in a private network range.
Private IPv4 networks are 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16.
See for details.")
(:method ((address ipv4-address))
(let* ((address-name (address-name address))
(first (aref address-name 0))
(second (aref address-name 1)))
(values (or (= first 10)
(and (= first 172)
(<= 16 second 31))
(and (= first 192)
(= second 168)))
(inet-address-network-class address))))
(:method ((address address))
nil))
|
b5252151b11cc9519ddc3aadb765c9e380960c9f7836593aeedf87ecc4c7da52 | jaredly/reason-language-server | main_args.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Para , INRIA Rocquencourt
(* *)
Copyright 1998 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
ATTENTION ! When you add or modify a parsing or typing option , do not forget
to update ocamldoc options too , in odoc_args.ml .
to update ocamldoc options too, in odoc_args.ml. *)
module type Common_options = sig
val _absname : unit -> unit
val _I : string -> unit
val _labels : unit -> unit
val _alias_deps : unit -> unit
val _no_alias_deps : unit -> unit
val _app_funct : unit -> unit
val _no_app_funct : unit -> unit
val _noassert : unit -> unit
val _nolabels : unit -> unit
val _nostdlib : unit -> unit
val _open : string -> unit
val _ppx : string -> unit
val _principal : unit -> unit
val _no_principal : unit -> unit
val _rectypes : unit -> unit
val _no_rectypes : unit -> unit
val _safe_string : unit -> unit
val _short_paths : unit -> unit
val _strict_sequence : unit -> unit
val _no_strict_sequence : unit -> unit
val _strict_formats : unit -> unit
val _no_strict_formats : unit -> unit
val _unboxed_types : unit -> unit
val _no_unboxed_types : unit -> unit
val _unsafe : unit -> unit
val _unsafe_string : unit -> unit
val _version : unit -> unit
val _vnum : unit -> unit
val _w : string -> unit
val _warn_error : string -> unit
val _warn_help : unit -> unit
val _dno_unique_ids : unit -> unit
val _dunique_ids : unit -> unit
val _dsource : unit -> unit
val _dparsetree : unit -> unit
val _dtypedtree : unit -> unit
val _drawlambda : unit -> unit
val _dlambda : unit -> unit
val anonymous : string -> unit
end;;
module type Compiler_options = sig
val _a : unit -> unit
val _annot : unit -> unit
val _binannot : unit -> unit
val _c : unit -> unit
val _cc : string -> unit
val _cclib : string -> unit
val _ccopt : string -> unit
val _config : unit -> unit
val _for_pack : string -> unit
val _g : unit -> unit
val _i : unit -> unit
val _impl : string -> unit
val _intf : string -> unit
val _intf_suffix : string -> unit
val _keep_docs : unit -> unit
val _no_keep_docs : unit -> unit
val _keep_locs : unit -> unit
val _no_keep_locs : unit -> unit
val _linkall : unit -> unit
val _noautolink : unit -> unit
val _o : string -> unit
val _opaque : unit -> unit
val _output_obj : unit -> unit
val _output_complete_obj : unit -> unit
val _pack : unit -> unit
val _plugin : string -> unit
val _pp : string -> unit
val _principal : unit -> unit
val _no_principal : unit -> unit
val _rectypes : unit -> unit
val _runtime_variant : string -> unit
val _safe_string : unit -> unit
val _short_paths : unit -> unit
val _thread : unit -> unit
val _v : unit -> unit
val _verbose : unit -> unit
val _where : unit -> unit
val _color : string -> unit
val _nopervasives : unit -> unit
val _dtimings : unit -> unit
val _dprofile : unit -> unit
val _args: string -> string array
val _args0: string -> string array
end
;;
module type Toplevel_options = sig
include Common_options
val _init : string -> unit
val _noinit : unit -> unit
val _no_version : unit -> unit
val _noprompt : unit -> unit
val _nopromptcont : unit -> unit
val _stdin : unit -> unit
val _args: string -> string array
val _args0: string -> string array
end
;;
module type Bytecomp_options = sig
include Common_options
include Compiler_options
val _compat_32 : unit -> unit
val _custom : unit -> unit
val _no_check_prims : unit -> unit
val _dllib : string -> unit
val _dllpath : string -> unit
val _make_runtime : unit -> unit
val _vmthread : unit -> unit
val _use_runtime : string -> unit
val _dinstr : unit -> unit
val _use_prims : string -> unit
end;;
module type Bytetop_options = sig
include Toplevel_options
val _dinstr : unit -> unit
end;;
module type Optcommon_options = sig
val _compact : unit -> unit
val _inline : string -> unit
val _inline_toplevel : string -> unit
val _inlining_report : unit -> unit
val _dump_pass : string -> unit
val _inline_max_depth : string -> unit
val _rounds : int -> unit
val _inline_max_unroll : string -> unit
val _classic_inlining : unit -> unit
val _inline_call_cost : string -> unit
val _inline_alloc_cost : string -> unit
val _inline_prim_cost : string -> unit
val _inline_branch_cost : string -> unit
val _inline_indirect_cost : string -> unit
val _inline_lifting_benefit : string -> unit
val _unbox_closures : unit -> unit
val _unbox_closures_factor : int -> unit
val _inline_branch_factor : string -> unit
val _remove_unused_arguments : unit -> unit
val _no_unbox_free_vars_of_closures : unit -> unit
val _no_unbox_specialised_args : unit -> unit
val _o2 : unit -> unit
val _o3 : unit -> unit
val _clambda_checks : unit -> unit
val _dflambda : unit -> unit
val _drawflambda : unit -> unit
val _dflambda_invariants : unit -> unit
val _dflambda_no_invariants : unit -> unit
val _dflambda_let : int -> unit
val _dflambda_verbose : unit -> unit
val _drawclambda : unit -> unit
val _dclambda : unit -> unit
val _dcmm : unit -> unit
val _dsel : unit -> unit
val _dcombine : unit -> unit
val _dcse : unit -> unit
val _dlive : unit -> unit
val _davail : unit -> unit
val _drunavail : unit -> unit
val _dspill : unit -> unit
val _dsplit : unit -> unit
val _dinterf : unit -> unit
val _dprefer : unit -> unit
val _dalloc : unit -> unit
val _dreload : unit -> unit
val _dscheduling : unit -> unit
val _dlinear : unit -> unit
val _dstartup : unit -> unit
end;;
module type Optcomp_options = sig
include Common_options
include Compiler_options
include Optcommon_options
val _linscan : unit -> unit
val _no_float_const_prop : unit -> unit
val _nodynlink : unit -> unit
val _p : unit -> unit
val _pp : string -> unit
val _S : unit -> unit
val _shared : unit -> unit
val _afl_instrument : unit -> unit
val _afl_inst_ratio : int -> unit
val _dinterval : unit -> unit
end;;
module type Opttop_options = sig
include Toplevel_options
include Optcommon_options
val _verbose : unit -> unit
val _S : unit -> unit
end;;
module type Ocamldoc_options = sig
include Common_options
val _impl : string -> unit
val _intf : string -> unit
val _intf_suffix : string -> unit
val _pp : string -> unit
val _principal : unit -> unit
val _rectypes : unit -> unit
val _safe_string : unit -> unit
val _short_paths : unit -> unit
val _thread : unit -> unit
val _v : unit -> unit
val _verbose : unit -> unit
val _vmthread : unit -> unit
end;;
module type Arg_list = sig
val list : (string * Arg.spec * string) list
end;;
module Make_bytecomp_options (F : Bytecomp_options) : Arg_list;;
module Make_bytetop_options (F : Bytetop_options) : Arg_list;;
module Make_optcomp_options (F : Optcomp_options) : Arg_list;;
module Make_opttop_options (F : Opttop_options) : Arg_list;;
module Make_ocamldoc_options (F : Ocamldoc_options) : Arg_list;;
| null | https://raw.githubusercontent.com/jaredly/reason-language-server/ce1b3f8ddb554b6498c2a83ea9c53a6bdf0b6081/ocaml_typing/407/main_args.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************ | , projet Para , INRIA Rocquencourt
Copyright 1998 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
ATTENTION ! When you add or modify a parsing or typing option , do not forget
to update ocamldoc options too , in odoc_args.ml .
to update ocamldoc options too, in odoc_args.ml. *)
module type Common_options = sig
val _absname : unit -> unit
val _I : string -> unit
val _labels : unit -> unit
val _alias_deps : unit -> unit
val _no_alias_deps : unit -> unit
val _app_funct : unit -> unit
val _no_app_funct : unit -> unit
val _noassert : unit -> unit
val _nolabels : unit -> unit
val _nostdlib : unit -> unit
val _open : string -> unit
val _ppx : string -> unit
val _principal : unit -> unit
val _no_principal : unit -> unit
val _rectypes : unit -> unit
val _no_rectypes : unit -> unit
val _safe_string : unit -> unit
val _short_paths : unit -> unit
val _strict_sequence : unit -> unit
val _no_strict_sequence : unit -> unit
val _strict_formats : unit -> unit
val _no_strict_formats : unit -> unit
val _unboxed_types : unit -> unit
val _no_unboxed_types : unit -> unit
val _unsafe : unit -> unit
val _unsafe_string : unit -> unit
val _version : unit -> unit
val _vnum : unit -> unit
val _w : string -> unit
val _warn_error : string -> unit
val _warn_help : unit -> unit
val _dno_unique_ids : unit -> unit
val _dunique_ids : unit -> unit
val _dsource : unit -> unit
val _dparsetree : unit -> unit
val _dtypedtree : unit -> unit
val _drawlambda : unit -> unit
val _dlambda : unit -> unit
val anonymous : string -> unit
end;;
module type Compiler_options = sig
val _a : unit -> unit
val _annot : unit -> unit
val _binannot : unit -> unit
val _c : unit -> unit
val _cc : string -> unit
val _cclib : string -> unit
val _ccopt : string -> unit
val _config : unit -> unit
val _for_pack : string -> unit
val _g : unit -> unit
val _i : unit -> unit
val _impl : string -> unit
val _intf : string -> unit
val _intf_suffix : string -> unit
val _keep_docs : unit -> unit
val _no_keep_docs : unit -> unit
val _keep_locs : unit -> unit
val _no_keep_locs : unit -> unit
val _linkall : unit -> unit
val _noautolink : unit -> unit
val _o : string -> unit
val _opaque : unit -> unit
val _output_obj : unit -> unit
val _output_complete_obj : unit -> unit
val _pack : unit -> unit
val _plugin : string -> unit
val _pp : string -> unit
val _principal : unit -> unit
val _no_principal : unit -> unit
val _rectypes : unit -> unit
val _runtime_variant : string -> unit
val _safe_string : unit -> unit
val _short_paths : unit -> unit
val _thread : unit -> unit
val _v : unit -> unit
val _verbose : unit -> unit
val _where : unit -> unit
val _color : string -> unit
val _nopervasives : unit -> unit
val _dtimings : unit -> unit
val _dprofile : unit -> unit
val _args: string -> string array
val _args0: string -> string array
end
;;
module type Toplevel_options = sig
include Common_options
val _init : string -> unit
val _noinit : unit -> unit
val _no_version : unit -> unit
val _noprompt : unit -> unit
val _nopromptcont : unit -> unit
val _stdin : unit -> unit
val _args: string -> string array
val _args0: string -> string array
end
;;
module type Bytecomp_options = sig
include Common_options
include Compiler_options
val _compat_32 : unit -> unit
val _custom : unit -> unit
val _no_check_prims : unit -> unit
val _dllib : string -> unit
val _dllpath : string -> unit
val _make_runtime : unit -> unit
val _vmthread : unit -> unit
val _use_runtime : string -> unit
val _dinstr : unit -> unit
val _use_prims : string -> unit
end;;
module type Bytetop_options = sig
include Toplevel_options
val _dinstr : unit -> unit
end;;
module type Optcommon_options = sig
val _compact : unit -> unit
val _inline : string -> unit
val _inline_toplevel : string -> unit
val _inlining_report : unit -> unit
val _dump_pass : string -> unit
val _inline_max_depth : string -> unit
val _rounds : int -> unit
val _inline_max_unroll : string -> unit
val _classic_inlining : unit -> unit
val _inline_call_cost : string -> unit
val _inline_alloc_cost : string -> unit
val _inline_prim_cost : string -> unit
val _inline_branch_cost : string -> unit
val _inline_indirect_cost : string -> unit
val _inline_lifting_benefit : string -> unit
val _unbox_closures : unit -> unit
val _unbox_closures_factor : int -> unit
val _inline_branch_factor : string -> unit
val _remove_unused_arguments : unit -> unit
val _no_unbox_free_vars_of_closures : unit -> unit
val _no_unbox_specialised_args : unit -> unit
val _o2 : unit -> unit
val _o3 : unit -> unit
val _clambda_checks : unit -> unit
val _dflambda : unit -> unit
val _drawflambda : unit -> unit
val _dflambda_invariants : unit -> unit
val _dflambda_no_invariants : unit -> unit
val _dflambda_let : int -> unit
val _dflambda_verbose : unit -> unit
val _drawclambda : unit -> unit
val _dclambda : unit -> unit
val _dcmm : unit -> unit
val _dsel : unit -> unit
val _dcombine : unit -> unit
val _dcse : unit -> unit
val _dlive : unit -> unit
val _davail : unit -> unit
val _drunavail : unit -> unit
val _dspill : unit -> unit
val _dsplit : unit -> unit
val _dinterf : unit -> unit
val _dprefer : unit -> unit
val _dalloc : unit -> unit
val _dreload : unit -> unit
val _dscheduling : unit -> unit
val _dlinear : unit -> unit
val _dstartup : unit -> unit
end;;
module type Optcomp_options = sig
include Common_options
include Compiler_options
include Optcommon_options
val _linscan : unit -> unit
val _no_float_const_prop : unit -> unit
val _nodynlink : unit -> unit
val _p : unit -> unit
val _pp : string -> unit
val _S : unit -> unit
val _shared : unit -> unit
val _afl_instrument : unit -> unit
val _afl_inst_ratio : int -> unit
val _dinterval : unit -> unit
end;;
module type Opttop_options = sig
include Toplevel_options
include Optcommon_options
val _verbose : unit -> unit
val _S : unit -> unit
end;;
module type Ocamldoc_options = sig
include Common_options
val _impl : string -> unit
val _intf : string -> unit
val _intf_suffix : string -> unit
val _pp : string -> unit
val _principal : unit -> unit
val _rectypes : unit -> unit
val _safe_string : unit -> unit
val _short_paths : unit -> unit
val _thread : unit -> unit
val _v : unit -> unit
val _verbose : unit -> unit
val _vmthread : unit -> unit
end;;
module type Arg_list = sig
val list : (string * Arg.spec * string) list
end;;
module Make_bytecomp_options (F : Bytecomp_options) : Arg_list;;
module Make_bytetop_options (F : Bytetop_options) : Arg_list;;
module Make_optcomp_options (F : Optcomp_options) : Arg_list;;
module Make_opttop_options (F : Opttop_options) : Arg_list;;
module Make_ocamldoc_options (F : Ocamldoc_options) : Arg_list;;
|
f5894594569dcfca3306bc49525acb0ea7464b446df3d85202fed72383453b8f | nominolo/lambdachine | Pretty.hs | # LANGUAGE FlexibleInstances #
{-# LANGUAGE TypeSynonymInstances #-}
-- |
Module : Lambdachine . Utils . Pretty
Copyright : ( c ) 2009
-- License : BSD-style
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
module Lambdachine.Utils.Pretty
( module Lambdachine.Utils.Pretty
, (<>)
)
where
import qualified Text.PrettyPrint.ANSI.Leijen as P
import Control.Applicative
import Data.Functor.Identity
import Data.Map ( Map )
import Data.Set ( Set )
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Lazy.UTF8 as B
import qualified Data.Vector as V
import Data.Monoid
import DynFlags ( DynFlags )
import Debug.Trace
------------------------------------------------------------------------
-- * Global Environment Stuff
newtype GlobalEnv = GlobalEnv
{ envDynFlags :: DynFlags }
class HasGlobalEnv env where
-- | A lens for reading and writing the global environment. Use
-- 'mkGlobalEnvL' to construct a lens from a getter and a setter.
--
-- You may can use this with the utilities from the @lens@ package, but for
-- convenience, there are also simple getter and setter utilities via
-- 'viewGlobalEnv' and 'setGlobalEnv'.
globalEnvL :: Functor f => (GlobalEnv -> f GlobalEnv) -> env -> f env
mkGlobalEnvL :: Functor f =>
(env -> GlobalEnv) -> (env -> GlobalEnv -> env)
-> (GlobalEnv -> f GlobalEnv) -> env -> f env
mkGlobalEnvL getE setE f env = setE env <$> f (getE env)
viewGlobalEnv :: HasGlobalEnv env => env -> GlobalEnv
viewGlobalEnv env = getConst $ globalEnvL Const env
setGlobalEnv :: HasGlobalEnv env => env -> GlobalEnv -> env
setGlobalEnv env newE = runIdentity $ globalEnvL (Identity . const newE) env
instance HasGlobalEnv PDocContext where
globalEnvL = mkGlobalEnvL pdocGlobalEnv (\ctx ge -> ctx{ pdocGlobalEnv = ge })
------------------------------------------------------------------------
-- * The @Pretty@ Class
class Pretty a where
ppr :: a -> PDoc
data PDocContext = PDocContext
{ pdocStyle :: !PrettyStyle
, pdocGlobalEnv :: !GlobalEnv
}
data PrettyStyle
= DebugStyle
| UserStyle
deriving (Eq, Ord, Show)
newtype PDoc = PDoc{ runPDoc :: PDocContext -> P.Doc }
instance Monoid PDoc where
mempty = PDoc $ \_ -> P.empty
mappend d1 d2 = PDoc $ \env -> runPDoc d1 env P.<> runPDoc d2 env
instance Show PDoc where show = render
instance where x = = y = show x = = show y
instance Show PDoc where show = render
instance Eq PDoc where x == y = show x == show y
-}
pretty :: Pretty a => GlobalEnv -> a -> String
pretty env x = render env (ppr x)
pprint :: Pretty a => GlobalEnv -> a -> IO ()
pprint env x = B.putStrLn $ B.fromString $ pretty env x
debugPrint :: Pretty a => GlobalEnv -> a -> IO ()
debugPrint env x = B.putStrLn $ B.fromString $ pretty env (withDebugStyle (ppr x))
render :: GlobalEnv -> PDoc -> String
render env d = P.displayS (P.renderPretty 0.8 100 $
runPDoc d $! PDocContext UserStyle env) ""
debugRender :: GlobalEnv -> PDoc -> String
debugRender env d = render env (withDebugStyle d)
------------------------------------------------------------------------
-- * Combinators
-- ** Primitives
liftP :: P.Doc -> PDoc
liftP doc = PDoc $ \_ -> doc
liftP1 :: (P.Doc -> P.Doc) -> PDoc -> PDoc
liftP1 f d1 = PDoc $ \env -> f (runPDoc d1 env)
liftP2 :: (P.Doc -> P.Doc -> P.Doc) -> PDoc -> PDoc -> PDoc
liftP2 f d1 d2 = PDoc $ \env -> runPDoc d1 env `f` runPDoc d2 env
liftPn :: ([P.Doc] -> P.Doc) -> [PDoc] -> PDoc
liftPn f ds = PDoc $ \env -> f [ runPDoc d env | d <- ds ]
empty :: PDoc
empty = liftP P.empty
char :: Char -> PDoc
char c = liftP $ P.char c
text :: String -> PDoc
text s = liftP $ P.text s
int :: Int -> PDoc
int i = liftP $ P.int i
infixr 6 < > -- same as Data . Monoid . < >
infixr 6 <+>
infixr 5 $$, $+$, <//>, </>
-- Monoid instance for functions and P.Doc do the same
-- (<>) :: PDoc -> PDoc -> PDoc
-- (<>) d1 d2 sty = d1 sty P.<> d2 sty
(<+>) :: PDoc -> PDoc -> PDoc
(<+>) = liftP2 (P.<+>)
($$) :: PDoc -> PDoc -> PDoc
($$) = liftP2 (P.<$>)
($+$) :: PDoc -> PDoc -> PDoc
($+$) = liftP2 (P.<$$>)
(<//>) :: PDoc -> PDoc -> PDoc
(<//>) = liftP2 (P.<//>)
(</>) :: PDoc -> PDoc -> PDoc
(</>) = liftP2 (P.</>)
linebreak :: PDoc
linebreak = liftP $ P.linebreak
hcat :: [PDoc] -> PDoc
hcat = liftPn P.hcat
hsep :: [PDoc] -> PDoc
hsep = liftPn P.hsep
vcat :: [PDoc] -> PDoc
vcat = liftPn P.vcat
cat :: [PDoc] -> PDoc
cat = liftPn P.cat
sep :: [PDoc] -> PDoc
sep = liftPn P.sep
fillCat :: [PDoc] -> PDoc
fillCat = liftPn P.fillCat
fillSep :: [PDoc] -> PDoc
fillSep = liftPn P.fillSep
nest :: Int -> PDoc -> PDoc
nest n = liftP1 $ P.nest n
align :: PDoc -> PDoc
align = liftP1 P.align
-- | @hang d1 n d2 = sep [d1, nest n d2]@
hang :: Int -> PDoc -> PDoc
hang n = liftP1 $ P.hang n
indent :: Int -> PDoc -> PDoc
indent n = liftP1 $ P.indent n
fillBreak :: Int -> PDoc -> PDoc
fillBreak n = liftP1 $ P.fillBreak n
-- | @punctuate p [d1, ... dn] = [d1 \<> p, d2 \<> p, ... dn-1 \<> p, dn]@
punctuate :: PDoc -> [PDoc] -> [PDoc]
punctuate _ [] = []
punctuate p (d:ds) = go d ds
where go d' [] = [d']
go d' (e:es) = (d' <> p) : go e es
-- ** Parenthesis
parens :: PDoc -> PDoc
parens = liftP1 P.parens
braces :: PDoc -> PDoc
braces = liftP1 P.braces
brackets :: PDoc -> PDoc
brackets = liftP1 P.brackets
angleBrackets :: PDoc -> PDoc
angleBrackets d = char '<' <> d <> char '>'
-- ** Symbols
comma :: PDoc
comma = liftP P.comma
arrow :: PDoc
arrow = text "->"
colon :: PDoc
colon = char ':'
semi :: PDoc
semi = char ';'
-- | A string where words are automatically wrapped.
wrappingText :: String -> PDoc
wrappingText msg = fillSep $ map text $ words msg
textWords :: String -> [PDoc]
textWords msg = map text (words msg)
------------------------------------------------------------------------
-- ** Terminal Styles
withStyle :: (P.Doc -> P.Doc) -> PDoc -> PDoc
withStyle = liftP1
-- ansiTermStyle :: String -> PDoc -> PDoc
ansiTermStyle ansi d =
P.zeroWidthText ( " \027 [ " + + ansi + + " m " ) P. < >
-- d sty P.<>
P.zeroWidthText " \027[0 m "
-- ansiTermStyle2 :: String -> String -> PDoc -> PDoc
-- ansiTermStyle2 start end d sty =
P.zeroWidthText ( " \027 [ " + + start + + " m " ) P. < >
-- d sty P.<>
P.zeroWidthText ( " \027 [ " + + end + + " m " )
bold :: PDoc -> PDoc
bold = withStyle P.bold
underline :: PDoc -> PDoc
underline = withStyle P.underline
keyword :: String -> PDoc
keyword = bold . text
colour1 :: PDoc -> PDoc
colour1 = withStyle P.cyan
colour2 :: PDoc -> PDoc
colour2 = withStyle P.red
pale :: PDoc -> PDoc
pale = withStyle P.dullwhite
varcolour :: PDoc -> PDoc
varcolour = id -- withStyle P.magenta
gblcolour :: PDoc -> PDoc
gblcolour = withStyle P.dullgreen
dconcolour :: PDoc -> PDoc
dconcolour = withStyle P.blue
-- ** Style-specific Combinators
ifDebugStyle :: PDoc -> PDoc
ifDebugStyle d = PDoc $ \env ->
case pdocStyle env of
DebugStyle -> P.dullwhite (runPDoc d env)
_ -> P.empty
withDebugStyle :: PDoc -> PDoc
withDebugStyle d = PDoc $ \env -> runPDoc d env{ pdocStyle = DebugStyle }
withGlobalEnv :: (GlobalEnv -> PDoc) -> PDoc
withGlobalEnv k = PDoc $ \env -> runPDoc (k (viewGlobalEnv env)) env
-- ** Utils
commaSep :: [PDoc] -> [PDoc]
commaSep = punctuate comma
ppFill :: Int -> Int -> PDoc
ppFill digits val
| digits <= 1 || val >= 10 ^ (digits - 1)
= ppr val
| otherwise
= char '0' <> ppFill (digits - 1) val
------------------------------------------------------------------------
-- * Prelude Type Instances
instance Pretty PDoc where ppr = id
instance (Pretty a, Pretty b) => Pretty (Either a b) where
ppr (Left a) = ppr a
ppr (Right b) = ppr b
instance Pretty Bool where
ppr True = text "true"
ppr False = text "false"
instance Pretty Int where
ppr n = text (show n)
instance Pretty Integer where
ppr n = text (show n)
instance Pretty a => Pretty (Maybe a) where
ppr Nothing = text "(nothing)"
ppr (Just a) = ppr a
instance (Pretty a, Pretty b) => Pretty (a,b) where
ppr (a,b) = parens (sep [ppr a <> comma, ppr b])
instance (Pretty a, Pretty b, Pretty c) => Pretty (a,b,c) where
ppr (a,b,c) = parens (sep [ppr a <> comma, ppr b <> comma, ppr c])
instance (Pretty a, Pretty b, Pretty c, Pretty d) => Pretty (a,b,c,d) where
ppr (a,b,c,d) =
parens (sep [ppr a <> comma, ppr b <> comma, ppr c <> comma, ppr d])
instance Pretty s => Pretty (Set s) where
ppr s = braces (fillSep (punctuate comma (map ppr (S.toList s))))
instance Pretty IS.IntSet where
ppr s = braces (fillSep (punctuate comma (map ppr (IS.toList s))))
instance Pretty a => Pretty (V.Vector a) where
ppr vec = ppr (V.toList vec)
instance Pretty a => Pretty [a] where
ppr l = brackets (fillSep (punctuate comma (map ppr l)))
instance (Pretty k, Pretty a) => Pretty (Map k a) where
ppr s = braces (vcat (punctuate comma (map ppr_elem (M.toList s))))
where ppr_elem (k, v) = colour1 (ppr k) <> colon <+> ppr v
instance (Pretty a) => Pretty (IM.IntMap a) where
ppr s = braces (fillSep (punctuate comma (map ppr_elem (IM.toList s))))
where ppr_elem (k, v) = ppr k <> colon <+> ppr v
| null | https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/compiler/Lambdachine/Utils/Pretty.hs | haskell | # LANGUAGE TypeSynonymInstances #
|
License : BSD-style
Maintainer :
Stability : experimental
Portability : portable
----------------------------------------------------------------------
* Global Environment Stuff
| A lens for reading and writing the global environment. Use
'mkGlobalEnvL' to construct a lens from a getter and a setter.
You may can use this with the utilities from the @lens@ package, but for
convenience, there are also simple getter and setter utilities via
'viewGlobalEnv' and 'setGlobalEnv'.
----------------------------------------------------------------------
* The @Pretty@ Class
----------------------------------------------------------------------
* Combinators
** Primitives
same as Data . Monoid . < >
Monoid instance for functions and P.Doc do the same
(<>) :: PDoc -> PDoc -> PDoc
(<>) d1 d2 sty = d1 sty P.<> d2 sty
| @hang d1 n d2 = sep [d1, nest n d2]@
| @punctuate p [d1, ... dn] = [d1 \<> p, d2 \<> p, ... dn-1 \<> p, dn]@
** Parenthesis
** Symbols
| A string where words are automatically wrapped.
----------------------------------------------------------------------
** Terminal Styles
ansiTermStyle :: String -> PDoc -> PDoc
d sty P.<>
ansiTermStyle2 :: String -> String -> PDoc -> PDoc
ansiTermStyle2 start end d sty =
d sty P.<>
withStyle P.magenta
** Style-specific Combinators
** Utils
----------------------------------------------------------------------
* Prelude Type Instances | # LANGUAGE FlexibleInstances #
Module : Lambdachine . Utils . Pretty
Copyright : ( c ) 2009
module Lambdachine.Utils.Pretty
( module Lambdachine.Utils.Pretty
, (<>)
)
where
import qualified Text.PrettyPrint.ANSI.Leijen as P
import Control.Applicative
import Data.Functor.Identity
import Data.Map ( Map )
import Data.Set ( Set )
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Lazy.UTF8 as B
import qualified Data.Vector as V
import Data.Monoid
import DynFlags ( DynFlags )
import Debug.Trace
newtype GlobalEnv = GlobalEnv
{ envDynFlags :: DynFlags }
class HasGlobalEnv env where
globalEnvL :: Functor f => (GlobalEnv -> f GlobalEnv) -> env -> f env
mkGlobalEnvL :: Functor f =>
(env -> GlobalEnv) -> (env -> GlobalEnv -> env)
-> (GlobalEnv -> f GlobalEnv) -> env -> f env
mkGlobalEnvL getE setE f env = setE env <$> f (getE env)
viewGlobalEnv :: HasGlobalEnv env => env -> GlobalEnv
viewGlobalEnv env = getConst $ globalEnvL Const env
setGlobalEnv :: HasGlobalEnv env => env -> GlobalEnv -> env
setGlobalEnv env newE = runIdentity $ globalEnvL (Identity . const newE) env
instance HasGlobalEnv PDocContext where
globalEnvL = mkGlobalEnvL pdocGlobalEnv (\ctx ge -> ctx{ pdocGlobalEnv = ge })
class Pretty a where
ppr :: a -> PDoc
data PDocContext = PDocContext
{ pdocStyle :: !PrettyStyle
, pdocGlobalEnv :: !GlobalEnv
}
data PrettyStyle
= DebugStyle
| UserStyle
deriving (Eq, Ord, Show)
newtype PDoc = PDoc{ runPDoc :: PDocContext -> P.Doc }
instance Monoid PDoc where
mempty = PDoc $ \_ -> P.empty
mappend d1 d2 = PDoc $ \env -> runPDoc d1 env P.<> runPDoc d2 env
instance Show PDoc where show = render
instance where x = = y = show x = = show y
instance Show PDoc where show = render
instance Eq PDoc where x == y = show x == show y
-}
pretty :: Pretty a => GlobalEnv -> a -> String
pretty env x = render env (ppr x)
pprint :: Pretty a => GlobalEnv -> a -> IO ()
pprint env x = B.putStrLn $ B.fromString $ pretty env x
debugPrint :: Pretty a => GlobalEnv -> a -> IO ()
debugPrint env x = B.putStrLn $ B.fromString $ pretty env (withDebugStyle (ppr x))
render :: GlobalEnv -> PDoc -> String
render env d = P.displayS (P.renderPretty 0.8 100 $
runPDoc d $! PDocContext UserStyle env) ""
debugRender :: GlobalEnv -> PDoc -> String
debugRender env d = render env (withDebugStyle d)
liftP :: P.Doc -> PDoc
liftP doc = PDoc $ \_ -> doc
liftP1 :: (P.Doc -> P.Doc) -> PDoc -> PDoc
liftP1 f d1 = PDoc $ \env -> f (runPDoc d1 env)
liftP2 :: (P.Doc -> P.Doc -> P.Doc) -> PDoc -> PDoc -> PDoc
liftP2 f d1 d2 = PDoc $ \env -> runPDoc d1 env `f` runPDoc d2 env
liftPn :: ([P.Doc] -> P.Doc) -> [PDoc] -> PDoc
liftPn f ds = PDoc $ \env -> f [ runPDoc d env | d <- ds ]
empty :: PDoc
empty = liftP P.empty
char :: Char -> PDoc
char c = liftP $ P.char c
text :: String -> PDoc
text s = liftP $ P.text s
int :: Int -> PDoc
int i = liftP $ P.int i
infixr 6 <+>
infixr 5 $$, $+$, <//>, </>
(<+>) :: PDoc -> PDoc -> PDoc
(<+>) = liftP2 (P.<+>)
($$) :: PDoc -> PDoc -> PDoc
($$) = liftP2 (P.<$>)
($+$) :: PDoc -> PDoc -> PDoc
($+$) = liftP2 (P.<$$>)
(<//>) :: PDoc -> PDoc -> PDoc
(<//>) = liftP2 (P.<//>)
(</>) :: PDoc -> PDoc -> PDoc
(</>) = liftP2 (P.</>)
linebreak :: PDoc
linebreak = liftP $ P.linebreak
hcat :: [PDoc] -> PDoc
hcat = liftPn P.hcat
hsep :: [PDoc] -> PDoc
hsep = liftPn P.hsep
vcat :: [PDoc] -> PDoc
vcat = liftPn P.vcat
cat :: [PDoc] -> PDoc
cat = liftPn P.cat
sep :: [PDoc] -> PDoc
sep = liftPn P.sep
fillCat :: [PDoc] -> PDoc
fillCat = liftPn P.fillCat
fillSep :: [PDoc] -> PDoc
fillSep = liftPn P.fillSep
nest :: Int -> PDoc -> PDoc
nest n = liftP1 $ P.nest n
align :: PDoc -> PDoc
align = liftP1 P.align
hang :: Int -> PDoc -> PDoc
hang n = liftP1 $ P.hang n
indent :: Int -> PDoc -> PDoc
indent n = liftP1 $ P.indent n
fillBreak :: Int -> PDoc -> PDoc
fillBreak n = liftP1 $ P.fillBreak n
punctuate :: PDoc -> [PDoc] -> [PDoc]
punctuate _ [] = []
punctuate p (d:ds) = go d ds
where go d' [] = [d']
go d' (e:es) = (d' <> p) : go e es
parens :: PDoc -> PDoc
parens = liftP1 P.parens
braces :: PDoc -> PDoc
braces = liftP1 P.braces
brackets :: PDoc -> PDoc
brackets = liftP1 P.brackets
angleBrackets :: PDoc -> PDoc
angleBrackets d = char '<' <> d <> char '>'
comma :: PDoc
comma = liftP P.comma
arrow :: PDoc
arrow = text "->"
colon :: PDoc
colon = char ':'
semi :: PDoc
semi = char ';'
wrappingText :: String -> PDoc
wrappingText msg = fillSep $ map text $ words msg
textWords :: String -> [PDoc]
textWords msg = map text (words msg)
withStyle :: (P.Doc -> P.Doc) -> PDoc -> PDoc
withStyle = liftP1
ansiTermStyle ansi d =
P.zeroWidthText ( " \027 [ " + + ansi + + " m " ) P. < >
P.zeroWidthText " \027[0 m "
P.zeroWidthText ( " \027 [ " + + start + + " m " ) P. < >
P.zeroWidthText ( " \027 [ " + + end + + " m " )
bold :: PDoc -> PDoc
bold = withStyle P.bold
underline :: PDoc -> PDoc
underline = withStyle P.underline
keyword :: String -> PDoc
keyword = bold . text
colour1 :: PDoc -> PDoc
colour1 = withStyle P.cyan
colour2 :: PDoc -> PDoc
colour2 = withStyle P.red
pale :: PDoc -> PDoc
pale = withStyle P.dullwhite
varcolour :: PDoc -> PDoc
gblcolour :: PDoc -> PDoc
gblcolour = withStyle P.dullgreen
dconcolour :: PDoc -> PDoc
dconcolour = withStyle P.blue
ifDebugStyle :: PDoc -> PDoc
ifDebugStyle d = PDoc $ \env ->
case pdocStyle env of
DebugStyle -> P.dullwhite (runPDoc d env)
_ -> P.empty
withDebugStyle :: PDoc -> PDoc
withDebugStyle d = PDoc $ \env -> runPDoc d env{ pdocStyle = DebugStyle }
withGlobalEnv :: (GlobalEnv -> PDoc) -> PDoc
withGlobalEnv k = PDoc $ \env -> runPDoc (k (viewGlobalEnv env)) env
commaSep :: [PDoc] -> [PDoc]
commaSep = punctuate comma
ppFill :: Int -> Int -> PDoc
ppFill digits val
| digits <= 1 || val >= 10 ^ (digits - 1)
= ppr val
| otherwise
= char '0' <> ppFill (digits - 1) val
instance Pretty PDoc where ppr = id
instance (Pretty a, Pretty b) => Pretty (Either a b) where
ppr (Left a) = ppr a
ppr (Right b) = ppr b
instance Pretty Bool where
ppr True = text "true"
ppr False = text "false"
instance Pretty Int where
ppr n = text (show n)
instance Pretty Integer where
ppr n = text (show n)
instance Pretty a => Pretty (Maybe a) where
ppr Nothing = text "(nothing)"
ppr (Just a) = ppr a
instance (Pretty a, Pretty b) => Pretty (a,b) where
ppr (a,b) = parens (sep [ppr a <> comma, ppr b])
instance (Pretty a, Pretty b, Pretty c) => Pretty (a,b,c) where
ppr (a,b,c) = parens (sep [ppr a <> comma, ppr b <> comma, ppr c])
instance (Pretty a, Pretty b, Pretty c, Pretty d) => Pretty (a,b,c,d) where
ppr (a,b,c,d) =
parens (sep [ppr a <> comma, ppr b <> comma, ppr c <> comma, ppr d])
instance Pretty s => Pretty (Set s) where
ppr s = braces (fillSep (punctuate comma (map ppr (S.toList s))))
instance Pretty IS.IntSet where
ppr s = braces (fillSep (punctuate comma (map ppr (IS.toList s))))
instance Pretty a => Pretty (V.Vector a) where
ppr vec = ppr (V.toList vec)
instance Pretty a => Pretty [a] where
ppr l = brackets (fillSep (punctuate comma (map ppr l)))
instance (Pretty k, Pretty a) => Pretty (Map k a) where
ppr s = braces (vcat (punctuate comma (map ppr_elem (M.toList s))))
where ppr_elem (k, v) = colour1 (ppr k) <> colon <+> ppr v
instance (Pretty a) => Pretty (IM.IntMap a) where
ppr s = braces (fillSep (punctuate comma (map ppr_elem (IM.toList s))))
where ppr_elem (k, v) = ppr k <> colon <+> ppr v
|
07929467a6c11985250ac6ffa7587ed30182ba1939b837c83a55e1d87a3ca722 | karimarttila/clojure | session_dynamodb.clj | (ns simpleserver.sessiondb.session-dynamodb
(:require
[clojure.tools.logging :as log]
[clj-time.core :as c-time]
[ring.middleware.cors :refer [wrap-cors]]
[buddy.sign.jwt :as buddy-jwt]
[amazonica.aws.dynamodbv2 :as dynamodb]
[simpleserver.util.prop :as ss-prop]
[simpleserver.sessiondb.session-service-interface :as ss-session-service-interface]
[simpleserver.util.aws-utils :as ss-aws-utils]
[environ.core :as environ]
[simpleserver.sessiondb.session-common :as ss-session-common])
(:import (com.amazonaws.services.dynamodbv2.model AmazonDynamoDBException)))
(defn get-token
[token]
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
my-table (str my-table-prefix "-" my-env "-session")
ret (dynamodb/query (ss-aws-utils/get-dynamodb-config)
:table-name my-table
:select "ALL_ATTRIBUTES"
:key-conditions {:token {:attribute-value-list [token]
:comparison-operator "EQ"}})
items (ret :items)
found-token (first items)]
found-token))
(defn remove-token
[token]
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
my-table (str my-table-prefix "-" my-env "-session")]
(dynamodb/delete-item (ss-aws-utils/get-dynamodb-config) :table-name my-table :key {:token {:s token}})))
(defrecord Env-dynamodb [env]
ss-session-service-interface/SessionServiceInterface
(create-json-web-token
[env email]
(log/debug (str "ENTER create-json-web-token, email: " email))
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
my-table (str my-table-prefix "-" my-env "-session")
json-web-token (ss-session-common/create-json-web-token email)
ret (try
(dynamodb/put-item (ss-aws-utils/get-dynamodb-config)
:table-name my-table
:item {
:token json-web-token
})
(catch AmazonDynamoDBException e {:email email,
:ret :failed
:msg (str "Exception occured: " (.toString e))}))]
json-web-token))
(validate-token
[env token]
(log/debug (str "ENTER validate-token, token: " token))
(ss-session-common/validate-token token get-token remove-token))
(get-sessions
[env]
(log/debug (str "ENTER get-sessions"))
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
ret (dynamodb/scan (ss-aws-utils/get-dynamodb-config)
:table-name (str my-table-prefix "-" my-env "-session"))
items (ret :items)]
(reduce (fn [sessions session]
(conj sessions (session :token)))
#{}
items)))
)
| null | https://raw.githubusercontent.com/karimarttila/clojure/ee1261b9a8e6be92cb47aeb325f82a278f2c1ed3/clj-ring-cljs-reagent-demo/simple-server/src/simpleserver/sessiondb/session_dynamodb.clj | clojure | (ns simpleserver.sessiondb.session-dynamodb
(:require
[clojure.tools.logging :as log]
[clj-time.core :as c-time]
[ring.middleware.cors :refer [wrap-cors]]
[buddy.sign.jwt :as buddy-jwt]
[amazonica.aws.dynamodbv2 :as dynamodb]
[simpleserver.util.prop :as ss-prop]
[simpleserver.sessiondb.session-service-interface :as ss-session-service-interface]
[simpleserver.util.aws-utils :as ss-aws-utils]
[environ.core :as environ]
[simpleserver.sessiondb.session-common :as ss-session-common])
(:import (com.amazonaws.services.dynamodbv2.model AmazonDynamoDBException)))
(defn get-token
[token]
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
my-table (str my-table-prefix "-" my-env "-session")
ret (dynamodb/query (ss-aws-utils/get-dynamodb-config)
:table-name my-table
:select "ALL_ATTRIBUTES"
:key-conditions {:token {:attribute-value-list [token]
:comparison-operator "EQ"}})
items (ret :items)
found-token (first items)]
found-token))
(defn remove-token
[token]
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
my-table (str my-table-prefix "-" my-env "-session")]
(dynamodb/delete-item (ss-aws-utils/get-dynamodb-config) :table-name my-table :key {:token {:s token}})))
(defrecord Env-dynamodb [env]
ss-session-service-interface/SessionServiceInterface
(create-json-web-token
[env email]
(log/debug (str "ENTER create-json-web-token, email: " email))
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
my-table (str my-table-prefix "-" my-env "-session")
json-web-token (ss-session-common/create-json-web-token email)
ret (try
(dynamodb/put-item (ss-aws-utils/get-dynamodb-config)
:table-name my-table
:item {
:token json-web-token
})
(catch AmazonDynamoDBException e {:email email,
:ret :failed
:msg (str "Exception occured: " (.toString e))}))]
json-web-token))
(validate-token
[env token]
(log/debug (str "ENTER validate-token, token: " token))
(ss-session-common/validate-token token get-token remove-token))
(get-sessions
[env]
(log/debug (str "ENTER get-sessions"))
(let [my-env (environ/env :my-env)
my-table-prefix (environ/env :ss-table-prefix)
ret (dynamodb/scan (ss-aws-utils/get-dynamodb-config)
:table-name (str my-table-prefix "-" my-env "-session"))
items (ret :items)]
(reduce (fn [sessions session]
(conj sessions (session :token)))
#{}
items)))
)
|
|
650fdba64bbc87366feb80ae5e1f03a8bce571ff15d1d93adf135ec2e808f466 | zmthy/http-media | MediaType.hs | ------------------------------------------------------------------------------
| Defines the ' MediaType ' accept header with an ' Accept ' instance for use
-- in content-type negotiation.
module Network.HTTP.Media.MediaType
(
-- * Type and creation
MediaType
, Parameters
, (//)
, (/:)
-- * Querying
, mainType
, subType
, parameters
, (/?)
, (/.)
) where
import qualified Data.ByteString.Char8 as BS
import qualified Data.CaseInsensitive as CI
import qualified Data.Map as Map
import Data.ByteString (ByteString)
import Data.CaseInsensitive (CI)
import Data.Map (empty, insert)
import qualified Network.HTTP.Media.MediaType.Internal as Internal
import Network.HTTP.Media.MediaType.Internal (MediaType (MediaType))
import Network.HTTP.Media.MediaType.Internal hiding (MediaType (..))
import Network.HTTP.Media.Utils
------------------------------------------------------------------------------
| Retrieves the main type of a ' MediaType ' .
mainType :: MediaType -> CI ByteString
mainType = Internal.mainType
------------------------------------------------------------------------------
| Retrieves the sub type of a ' MediaType ' .
subType :: MediaType -> CI ByteString
subType = Internal.subType
------------------------------------------------------------------------------
| Retrieves the parameters of a ' MediaType ' .
parameters :: MediaType -> Parameters
parameters = Internal.parameters
------------------------------------------------------------------------------
| Builds a ' MediaType ' without parameters . Can produce an error if
-- either type is invalid.
(//) :: ByteString -> ByteString -> MediaType
a // b
| a == "*" && b == "*" = MediaType (CI.mk a) (CI.mk b) empty
| b == "*" = MediaType (ensureR a) (CI.mk b) empty
| otherwise = MediaType (ensureR a) (ensureR b) empty
------------------------------------------------------------------------------
| Adds a parameter to a ' MediaType ' . Can produce an error if either
-- string is invalid.
(/:) :: MediaType -> (ByteString, ByteString) -> MediaType
(MediaType a b p) /: (k, v) = MediaType a b $ insert (ensureR k) (ensureV v) p
------------------------------------------------------------------------------
| Evaluates if a ' MediaType ' has a parameter of the given name .
(/?) :: MediaType -> ByteString -> Bool
(MediaType _ _ p) /? k = Map.member (CI.mk k) p
------------------------------------------------------------------------------
| Retrieves a parameter from a ' MediaType ' .
(/.) :: MediaType -> ByteString -> Maybe (CI ByteString)
(MediaType _ _ p) /. k = Map.lookup (CI.mk k) p
------------------------------------------------------------------------------
| Ensures that the ' ByteString ' matches the ABNF for ` reg - name ` in RFC
-- 4288.
ensureR :: ByteString -> CI ByteString
ensureR bs = CI.mk $ if l == 0 || l > 127
then error $ "Invalid length for " ++ show bs else ensure isMediaChar bs
where l = BS.length bs
------------------------------------------------------------------------------
-- | Ensures that the 'ByteString' does not contain invalid characters for
-- a parameter value. RFC 4288 does not specify what characters are valid, so
-- here we just disallow parameter and media type breakers, ',' and ';'.
ensureV :: ByteString -> CI ByteString
ensureV = CI.mk . ensure (`notElem` [',', ';'])
------------------------------------------------------------------------------
-- | Ensures the predicate matches for every character in the given string.
ensure :: (Char -> Bool) -> ByteString -> ByteString
ensure f bs = maybe
(error $ "Invalid character in " ++ show bs) (const bs) (BS.find f bs)
| null | https://raw.githubusercontent.com/zmthy/http-media/bc45b456299712299078167cb4b29eba551c54c9/src/Network/HTTP/Media/MediaType.hs | haskell | ----------------------------------------------------------------------------
in content-type negotiation.
* Type and creation
* Querying
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
either type is invalid.
----------------------------------------------------------------------------
string is invalid.
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
4288.
----------------------------------------------------------------------------
| Ensures that the 'ByteString' does not contain invalid characters for
a parameter value. RFC 4288 does not specify what characters are valid, so
here we just disallow parameter and media type breakers, ',' and ';'.
----------------------------------------------------------------------------
| Ensures the predicate matches for every character in the given string. | | Defines the ' MediaType ' accept header with an ' Accept ' instance for use
module Network.HTTP.Media.MediaType
(
MediaType
, Parameters
, (//)
, (/:)
, mainType
, subType
, parameters
, (/?)
, (/.)
) where
import qualified Data.ByteString.Char8 as BS
import qualified Data.CaseInsensitive as CI
import qualified Data.Map as Map
import Data.ByteString (ByteString)
import Data.CaseInsensitive (CI)
import Data.Map (empty, insert)
import qualified Network.HTTP.Media.MediaType.Internal as Internal
import Network.HTTP.Media.MediaType.Internal (MediaType (MediaType))
import Network.HTTP.Media.MediaType.Internal hiding (MediaType (..))
import Network.HTTP.Media.Utils
| Retrieves the main type of a ' MediaType ' .
mainType :: MediaType -> CI ByteString
mainType = Internal.mainType
| Retrieves the sub type of a ' MediaType ' .
subType :: MediaType -> CI ByteString
subType = Internal.subType
| Retrieves the parameters of a ' MediaType ' .
parameters :: MediaType -> Parameters
parameters = Internal.parameters
| Builds a ' MediaType ' without parameters . Can produce an error if
(//) :: ByteString -> ByteString -> MediaType
a // b
| a == "*" && b == "*" = MediaType (CI.mk a) (CI.mk b) empty
| b == "*" = MediaType (ensureR a) (CI.mk b) empty
| otherwise = MediaType (ensureR a) (ensureR b) empty
| Adds a parameter to a ' MediaType ' . Can produce an error if either
(/:) :: MediaType -> (ByteString, ByteString) -> MediaType
(MediaType a b p) /: (k, v) = MediaType a b $ insert (ensureR k) (ensureV v) p
| Evaluates if a ' MediaType ' has a parameter of the given name .
(/?) :: MediaType -> ByteString -> Bool
(MediaType _ _ p) /? k = Map.member (CI.mk k) p
| Retrieves a parameter from a ' MediaType ' .
(/.) :: MediaType -> ByteString -> Maybe (CI ByteString)
(MediaType _ _ p) /. k = Map.lookup (CI.mk k) p
| Ensures that the ' ByteString ' matches the ABNF for ` reg - name ` in RFC
ensureR :: ByteString -> CI ByteString
ensureR bs = CI.mk $ if l == 0 || l > 127
then error $ "Invalid length for " ++ show bs else ensure isMediaChar bs
where l = BS.length bs
ensureV :: ByteString -> CI ByteString
ensureV = CI.mk . ensure (`notElem` [',', ';'])
ensure :: (Char -> Bool) -> ByteString -> ByteString
ensure f bs = maybe
(error $ "Invalid character in " ++ show bs) (const bs) (BS.find f bs)
|
28335f9e0770d84a562d5c9d3c312c4c273ed0daa00b5cfd60a42f04c244dcc6 | uber/queryparser | Internal.hs | Copyright ( c ) 2017 Uber Technologies , Inc.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
--
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
module Database.Sql.Hive.Parser.Internal where
import qualified Text.Parsec as P
import Database.Sql.Hive.Token
import Database.Sql.Position
import Control.Monad.Reader
import Data.Text.Lazy (Text)
import Data.Set (Set)
type ScopeTableRef = Text
data ParserScope = ParserScope
{ selectTableAliases :: Maybe (Set ScopeTableRef) }
deriving (Eq, Ord, Show)
type Parser = P.ParsecT [(Token, Position, Position)] Integer (Reader ParserScope)
getNextCounter :: Parser Integer
getNextCounter = P.modifyState (+1) >> P.getState
| null | https://raw.githubusercontent.com/uber/queryparser/6015e8f273f4498326fec0315ac5580d7036f8a4/dialects/hive/src/Database/Sql/Hive/Parser/Internal.hs | haskell |
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. | Copyright ( c ) 2017 Uber Technologies , Inc.
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
module Database.Sql.Hive.Parser.Internal where
import qualified Text.Parsec as P
import Database.Sql.Hive.Token
import Database.Sql.Position
import Control.Monad.Reader
import Data.Text.Lazy (Text)
import Data.Set (Set)
type ScopeTableRef = Text
data ParserScope = ParserScope
{ selectTableAliases :: Maybe (Set ScopeTableRef) }
deriving (Eq, Ord, Show)
type Parser = P.ParsecT [(Token, Position, Position)] Integer (Reader ParserScope)
getNextCounter :: Parser Integer
getNextCounter = P.modifyState (+1) >> P.getState
|
d8d471652162fee62fb3e69d7a503c4f75d3ceffa4bcb1f34d0da45419d2df40 | liquidz/antq | download_test.clj | (ns antq.download-test
(:require
[antq.download :as sut]
[antq.util.git :as u.git]
[clojure.test :as t]
[clojure.tools.deps :as deps]))
(defn- test-download!
[m]
(-> m
(sut/download!)
(dissoc :mvn/repos)))
(t/deftest download!-test
(with-redefs [deps/resolve-deps (fn [deps-map _args-map] deps-map)]
(t/testing "java"
(t/is (= {:deps {'foo/bar {:mvn/version "1.0.0"}}}
(test-download! [{:type :java
:name 'foo/bar
:latest-version "1.0.0"}]))))
(t/testing "git-sha"
(t/is (= {:deps {'foo/bar {:git/url ""
:git/sha "SHA"}}}
(test-download! [{:type :git-sha
:name 'foo/bar
:latest-version "SHA"
:extra {:url ""}}]))))
(t/testing "git-tag-and-sha"
(with-redefs [u.git/tag-sha-by-ls-remote
(fn [url tag]
(when (and (= "" url)
(= "v1.0.0" tag))
"SHA2"))]
(t/is (= {:deps {'foo/bar {:git/url ""
:git/tag "v1.0.0"
:git/sha "SHA2"}}}
(test-download! [{:type :git-tag-and-sha
:name 'foo/bar
:latest-version "v1.0.0"
:extra {:url ""}}])))))
(t/testing "else"
(t/is (= {:deps nil}
(test-download! [{:type :invalid}]))))))
| null | https://raw.githubusercontent.com/liquidz/antq/4a4fb5e61ddb2f3400e18bdd5c856ca4f04cdfd7/test/antq/download_test.clj | clojure | (ns antq.download-test
(:require
[antq.download :as sut]
[antq.util.git :as u.git]
[clojure.test :as t]
[clojure.tools.deps :as deps]))
(defn- test-download!
[m]
(-> m
(sut/download!)
(dissoc :mvn/repos)))
(t/deftest download!-test
(with-redefs [deps/resolve-deps (fn [deps-map _args-map] deps-map)]
(t/testing "java"
(t/is (= {:deps {'foo/bar {:mvn/version "1.0.0"}}}
(test-download! [{:type :java
:name 'foo/bar
:latest-version "1.0.0"}]))))
(t/testing "git-sha"
(t/is (= {:deps {'foo/bar {:git/url ""
:git/sha "SHA"}}}
(test-download! [{:type :git-sha
:name 'foo/bar
:latest-version "SHA"
:extra {:url ""}}]))))
(t/testing "git-tag-and-sha"
(with-redefs [u.git/tag-sha-by-ls-remote
(fn [url tag]
(when (and (= "" url)
(= "v1.0.0" tag))
"SHA2"))]
(t/is (= {:deps {'foo/bar {:git/url ""
:git/tag "v1.0.0"
:git/sha "SHA2"}}}
(test-download! [{:type :git-tag-and-sha
:name 'foo/bar
:latest-version "v1.0.0"
:extra {:url ""}}])))))
(t/testing "else"
(t/is (= {:deps nil}
(test-download! [{:type :invalid}]))))))
|
|
9319cbd6ca3e48fcabe267a5b4a6b0791d9908b2cf9d98d4717de7ce72f3f56e | picty/parsifal | dns.ml | open Parsifal
open BasePTypes
open PTypes
enum rr_type (16, UnknownVal UnknownQueryType) =
| 1 -> RRT_A, "A"
| 2 -> RRT_NS, "NS"
| 3 -> RRT_MD, "MD"
| 4 -> RRT_MF, "MF"
| 5 -> RRT_CNAME, "CNAME"
| 6 -> RRT_SOA, "SOA"
| 7 -> RRT_MB, "MB"
| 8 -> RRT_MG, "MG"
| 9 -> RRT_MR, "MR"
| 10 -> RRT_NULL, "NULL"
| 11 -> RRT_WKS, "WKS"
| 12 -> RRT_PTR, "PTR"
| 13 -> RRT_HINFO, "HINFO"
| 14 -> RRT_MINFO, "MINFO"
| 15 -> RRT_MX, "MX"
| 16 -> RRT_TXT, "TXT"
| 252 -> RRT_AXFR, "AXFR"
| 253 -> RRT_MAILB, "MAILB"
| 254 -> RRT_MAILA, "MAILA"
| 255 -> RRT_ANYTYPE, "*"
enum rr_class (16, UnknownVal UnknownQueryClass) =
| 1 -> RRC_IN, "IN"
| 2 -> RRC_CS, "CSNET"
| 3 -> RRC_CH, "CHAOS"
| 4 -> RRC_HS, "Hesiod"
| 255 -> RRC_ANYCLASS, "*"
type domain =
| DomainLabel of string * domain
| DomainPointer of int
| DomainEnd
type dns_pcontext = {
base_offset : int;
direct_resolver : (int, domain) Hashtbl.t;
}
type dns_dcontext = {
output_offset : int;
reverse_resolver : (domain, int) Hashtbl.t;
}
let parse_dns_pcontext input = {
base_offset = input.cur_base + input.cur_offset;
direct_resolver = Hashtbl.create 10;
}
let dump_dns_dcontext buf = {
output_offset = POutput.length buf;
reverse_resolver = Hashtbl.create 10;
}
let resolve_domains = ref true
let compress_domains = ref true
let rec parse_domain ctx input =
let o = input.cur_base + input.cur_offset in
let n = parse_uint8 input in
match (n land 0xc0), (n land 0x3f) with
| 0, 0 -> DomainEnd
| 0xc0, hi_offset ->
let lo_offset = parse_uint8 input in
let offset = (hi_offset lsl 8) lor lo_offset in
let d = DomainPointer offset in
if should_enrich resolve_domains input.enrich
then hash_get ctx.direct_resolver offset d
else d
| 0, len ->
let label = parse_string len input in
let rem = parse_domain ctx input in
let d = DomainLabel (label, rem) in
if should_enrich resolve_domains input.enrich
then Hashtbl.replace ctx.direct_resolver (o - ctx.base_offset) d;
d
| _ -> raise (ParsingException (CustomException "Invalid label length", _h_of_si input))
let rec dump_domain ctx buf = function
| DomainEnd -> dump_uint8 buf 0
| DomainPointer p -> dump_uint16 buf (0xc000 land p)
| (DomainLabel (l, r)) as d ->
if !compress_domains then begin
try
dump_domain ctx buf (DomainPointer (Hashtbl.find ctx.reverse_resolver d))
with Not_found ->
Hashtbl.replace ctx.reverse_resolver d (POutput.length buf - ctx.output_offset);
dump_varlen_string dump_uint8 buf l;
dump_domain ctx buf r
end else begin
dump_varlen_string dump_uint8 buf l;
dump_domain ctx buf r
end
let rec string_of_domain = function
| DomainLabel (s, rem) -> s::(string_of_domain rem)
| DomainPointer p -> ["@" ^ (string_of_int p)]
| DomainEnd -> []
let value_of_domain d =
let content = string_of_domain d in
VRecord [
"@name", VString ("domain", false);
"@string_of", VString (String.concat "." content, false);
"content", VList (List.map value_of_string content)
]
struct soa_rdata [both_param ctx; novalueof] = {
soa_mname : domain[ctx];
soa_rname : domain[ctx];
soa_serial: uint32;
soa_refresh : uint32;
soa_retry : uint32;
soa_expire : uint32;
soa_minimum : uint32
}
let value_of_soa_rdata soa_rdata =
let mname = String.concat "." (string_of_domain soa_rdata.soa_mname) in
let rname = String.concat "." (string_of_domain soa_rdata.soa_rname) in
VRecord [
"@name", VString ("soa_rdata", false);
"@string_of", VString (Printf.sprintf "%s %s %d %d %d %d %d" mname rname
soa_rdata.soa_serial soa_rdata.soa_refresh
soa_rdata.soa_retry soa_rdata.soa_expire
soa_rdata.soa_minimum, false);
"soa_mname", value_of_domain soa_rdata.soa_mname;
"soa_rname", value_of_domain soa_rdata.soa_rname;
"soa_serial", VInt soa_rdata.soa_serial;
"soa_refresh", VInt soa_rdata.soa_refresh;
"soa_retry", VInt soa_rdata.soa_retry;
"soa_expire", VInt soa_rdata.soa_expire;
"soa_minimum", VInt soa_rdata.soa_minimum;
]
struct hinfo_rdata = {
hinfo_cpu : string[uint8];
hinfo_os : string[uint8];
}
struct mx_rdata [both_param ctx; novalueof] = {
mx_preference : uint16;
mx_host : domain[ctx]
}
let value_of_mx_rdata mx_rdata =
let content = string_of_domain mx_rdata.mx_host in
let domain = String.concat "." content in
VRecord [
"@name", VString ("mx_rdata", false);
"@string_of", VString (Printf.sprintf "%d %s" mx_rdata.mx_preference domain, false);
"mx_preference", VInt mx_rdata.mx_preference;
"mx_host", value_of_domain mx_rdata.mx_host;
]
alias txt_rdata [novalueof] = list of string[uint8]
let value_of_txt_rdata txt_rdata = VString (String.concat "." txt_rdata, false)
union rdata [enrich; both_param ctx] (UnparsedRData) =
| RRT_A -> Address of ipv4
| RRT_NS -> Domain of domain[ctx]
| RRT_CNAME -> Domain of domain[ctx]
| RRT_SOA -> SOA of soa_rdata[ctx]
| RRT_NULL -> NullRData of binstring
| RRT_PTR -> Domain of domain[ctx]
| RRT_HINFO -> HInfo of hinfo_rdata
| RRT_MX -> MX of mx_rdata[ctx]
| RRT_TXT -> TXT of txt_rdata
struct question [both_param ctx] = {
qname : domain[ctx];
qtype : rr_type;
qclass : rr_class
}
struct rr [both_param ctx] = {
rname : domain[ctx];
rtype : rr_type;
rclass : rr_class;
ttl : uint32;
rdata : container[uint16] of rdata(BOTH ctx; rtype)
}
enum opcode (4, UnknownVal UnknownOpcode) =
| 0 -> StandardQuery
| 1 -> InverseQuery
| 2 -> ServerStatusRequest
enum rcode (4, UnknownVal UnkownRCode) =
| 0 -> RC_NoError, "NOERROR"
| 1 -> RC_FormatError, "FORMERR"
| 2 -> RC_ServerFailure, "SERVFAIL"
| 3 -> RC_NameError, "NXDOMAIN"
| 4 -> RC_NotImplemented, "NOTIMP"
| 5 -> RC_Refused, "REFUSED"
struct dns_message [top] = {
parse_checkpoint ctx : dns_pcontext;
dump_checkpoint ctx : dns_dcontext;
id : uint16;
qr : bit_bool;
opcode : opcode;
aa : bit_bool;
tc : bit_bool;
rd : bit_bool;
ra : bit_bool;
z : bit_int[3];
rcode : rcode;
qdcount : uint16;
ancount : uint16;
nscount : uint16;
arcount : uint16;
questions : list(qdcount) of question[ctx];
answers : list(ancount) of rr[ctx];
authority_answers : list(nscount) of rr[ctx];
additional_records : list(arcount) of rr[ctx]
}
| null | https://raw.githubusercontent.com/picty/parsifal/767a1d558ea6da23ada46d8d96a057514b0aa2a8/net/dns.ml | ocaml | open Parsifal
open BasePTypes
open PTypes
enum rr_type (16, UnknownVal UnknownQueryType) =
| 1 -> RRT_A, "A"
| 2 -> RRT_NS, "NS"
| 3 -> RRT_MD, "MD"
| 4 -> RRT_MF, "MF"
| 5 -> RRT_CNAME, "CNAME"
| 6 -> RRT_SOA, "SOA"
| 7 -> RRT_MB, "MB"
| 8 -> RRT_MG, "MG"
| 9 -> RRT_MR, "MR"
| 10 -> RRT_NULL, "NULL"
| 11 -> RRT_WKS, "WKS"
| 12 -> RRT_PTR, "PTR"
| 13 -> RRT_HINFO, "HINFO"
| 14 -> RRT_MINFO, "MINFO"
| 15 -> RRT_MX, "MX"
| 16 -> RRT_TXT, "TXT"
| 252 -> RRT_AXFR, "AXFR"
| 253 -> RRT_MAILB, "MAILB"
| 254 -> RRT_MAILA, "MAILA"
| 255 -> RRT_ANYTYPE, "*"
enum rr_class (16, UnknownVal UnknownQueryClass) =
| 1 -> RRC_IN, "IN"
| 2 -> RRC_CS, "CSNET"
| 3 -> RRC_CH, "CHAOS"
| 4 -> RRC_HS, "Hesiod"
| 255 -> RRC_ANYCLASS, "*"
type domain =
| DomainLabel of string * domain
| DomainPointer of int
| DomainEnd
type dns_pcontext = {
base_offset : int;
direct_resolver : (int, domain) Hashtbl.t;
}
type dns_dcontext = {
output_offset : int;
reverse_resolver : (domain, int) Hashtbl.t;
}
let parse_dns_pcontext input = {
base_offset = input.cur_base + input.cur_offset;
direct_resolver = Hashtbl.create 10;
}
let dump_dns_dcontext buf = {
output_offset = POutput.length buf;
reverse_resolver = Hashtbl.create 10;
}
let resolve_domains = ref true
let compress_domains = ref true
let rec parse_domain ctx input =
let o = input.cur_base + input.cur_offset in
let n = parse_uint8 input in
match (n land 0xc0), (n land 0x3f) with
| 0, 0 -> DomainEnd
| 0xc0, hi_offset ->
let lo_offset = parse_uint8 input in
let offset = (hi_offset lsl 8) lor lo_offset in
let d = DomainPointer offset in
if should_enrich resolve_domains input.enrich
then hash_get ctx.direct_resolver offset d
else d
| 0, len ->
let label = parse_string len input in
let rem = parse_domain ctx input in
let d = DomainLabel (label, rem) in
if should_enrich resolve_domains input.enrich
then Hashtbl.replace ctx.direct_resolver (o - ctx.base_offset) d;
d
| _ -> raise (ParsingException (CustomException "Invalid label length", _h_of_si input))
let rec dump_domain ctx buf = function
| DomainEnd -> dump_uint8 buf 0
| DomainPointer p -> dump_uint16 buf (0xc000 land p)
| (DomainLabel (l, r)) as d ->
if !compress_domains then begin
try
dump_domain ctx buf (DomainPointer (Hashtbl.find ctx.reverse_resolver d))
with Not_found ->
Hashtbl.replace ctx.reverse_resolver d (POutput.length buf - ctx.output_offset);
dump_varlen_string dump_uint8 buf l;
dump_domain ctx buf r
end else begin
dump_varlen_string dump_uint8 buf l;
dump_domain ctx buf r
end
let rec string_of_domain = function
| DomainLabel (s, rem) -> s::(string_of_domain rem)
| DomainPointer p -> ["@" ^ (string_of_int p)]
| DomainEnd -> []
let value_of_domain d =
let content = string_of_domain d in
VRecord [
"@name", VString ("domain", false);
"@string_of", VString (String.concat "." content, false);
"content", VList (List.map value_of_string content)
]
struct soa_rdata [both_param ctx; novalueof] = {
soa_mname : domain[ctx];
soa_rname : domain[ctx];
soa_serial: uint32;
soa_refresh : uint32;
soa_retry : uint32;
soa_expire : uint32;
soa_minimum : uint32
}
let value_of_soa_rdata soa_rdata =
let mname = String.concat "." (string_of_domain soa_rdata.soa_mname) in
let rname = String.concat "." (string_of_domain soa_rdata.soa_rname) in
VRecord [
"@name", VString ("soa_rdata", false);
"@string_of", VString (Printf.sprintf "%s %s %d %d %d %d %d" mname rname
soa_rdata.soa_serial soa_rdata.soa_refresh
soa_rdata.soa_retry soa_rdata.soa_expire
soa_rdata.soa_minimum, false);
"soa_mname", value_of_domain soa_rdata.soa_mname;
"soa_rname", value_of_domain soa_rdata.soa_rname;
"soa_serial", VInt soa_rdata.soa_serial;
"soa_refresh", VInt soa_rdata.soa_refresh;
"soa_retry", VInt soa_rdata.soa_retry;
"soa_expire", VInt soa_rdata.soa_expire;
"soa_minimum", VInt soa_rdata.soa_minimum;
]
struct hinfo_rdata = {
hinfo_cpu : string[uint8];
hinfo_os : string[uint8];
}
struct mx_rdata [both_param ctx; novalueof] = {
mx_preference : uint16;
mx_host : domain[ctx]
}
let value_of_mx_rdata mx_rdata =
let content = string_of_domain mx_rdata.mx_host in
let domain = String.concat "." content in
VRecord [
"@name", VString ("mx_rdata", false);
"@string_of", VString (Printf.sprintf "%d %s" mx_rdata.mx_preference domain, false);
"mx_preference", VInt mx_rdata.mx_preference;
"mx_host", value_of_domain mx_rdata.mx_host;
]
alias txt_rdata [novalueof] = list of string[uint8]
let value_of_txt_rdata txt_rdata = VString (String.concat "." txt_rdata, false)
union rdata [enrich; both_param ctx] (UnparsedRData) =
| RRT_A -> Address of ipv4
| RRT_NS -> Domain of domain[ctx]
| RRT_CNAME -> Domain of domain[ctx]
| RRT_SOA -> SOA of soa_rdata[ctx]
| RRT_NULL -> NullRData of binstring
| RRT_PTR -> Domain of domain[ctx]
| RRT_HINFO -> HInfo of hinfo_rdata
| RRT_MX -> MX of mx_rdata[ctx]
| RRT_TXT -> TXT of txt_rdata
struct question [both_param ctx] = {
qname : domain[ctx];
qtype : rr_type;
qclass : rr_class
}
struct rr [both_param ctx] = {
rname : domain[ctx];
rtype : rr_type;
rclass : rr_class;
ttl : uint32;
rdata : container[uint16] of rdata(BOTH ctx; rtype)
}
enum opcode (4, UnknownVal UnknownOpcode) =
| 0 -> StandardQuery
| 1 -> InverseQuery
| 2 -> ServerStatusRequest
enum rcode (4, UnknownVal UnkownRCode) =
| 0 -> RC_NoError, "NOERROR"
| 1 -> RC_FormatError, "FORMERR"
| 2 -> RC_ServerFailure, "SERVFAIL"
| 3 -> RC_NameError, "NXDOMAIN"
| 4 -> RC_NotImplemented, "NOTIMP"
| 5 -> RC_Refused, "REFUSED"
struct dns_message [top] = {
parse_checkpoint ctx : dns_pcontext;
dump_checkpoint ctx : dns_dcontext;
id : uint16;
qr : bit_bool;
opcode : opcode;
aa : bit_bool;
tc : bit_bool;
rd : bit_bool;
ra : bit_bool;
z : bit_int[3];
rcode : rcode;
qdcount : uint16;
ancount : uint16;
nscount : uint16;
arcount : uint16;
questions : list(qdcount) of question[ctx];
answers : list(ancount) of rr[ctx];
authority_answers : list(nscount) of rr[ctx];
additional_records : list(arcount) of rr[ctx]
}
|
|
767bf34a13755d90d7e9a14dd1fb998d7ecd7b30669313bcb82aac16e2536070 | RichiH/git-annex | Drop.hs | git - annex command
-
- Copyright 2010 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2010 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Command.Drop where
import Command
import qualified Remote
import qualified Annex
import Annex.UUID
import Logs.Location
import Logs.Trust
import Logs.PreferredContent
import Annex.NumCopies
import Annex.Content
import Annex.Wanted
import Annex.Notification
import System.Log.Logger (debugM)
import qualified Data.Set as S
cmd :: Command
cmd = withGlobalOptions (jobsOption : jsonOption : annexedMatchingOptions) $
command "drop" SectionCommon
"remove content of files from repository"
paramPaths (seek <$$> optParser)
data DropOptions = DropOptions
{ dropFiles :: CmdParams
, dropFrom :: Maybe (DeferredParse Remote)
, autoMode :: Bool
, keyOptions :: Maybe KeyOptions
, batchOption :: BatchMode
}
optParser :: CmdParamsDesc -> Parser DropOptions
optParser desc = DropOptions
<$> cmdParams desc
<*> optional parseDropFromOption
<*> parseAutoOption
<*> optional parseKeyOptions
<*> parseBatchOption
parseDropFromOption :: Parser (DeferredParse Remote)
parseDropFromOption = parseRemoteOption <$> strOption
( long "from" <> short 'f' <> metavar paramRemote
<> help "drop content from a remote"
<> completeRemotes
)
seek :: DropOptions -> CommandSeek
seek o = allowConcurrentOutput $
case batchOption o of
Batch -> batchInput Right (batchCommandAction . go)
NoBatch -> withKeyOptions (keyOptions o) (autoMode o)
(startKeys o)
(withFilesInGit go)
=<< workTreeItems (dropFiles o)
where
go = whenAnnexed $ start o
start :: DropOptions -> FilePath -> Key -> CommandStart
start o file key = start' o key afile (mkActionItem afile)
where
afile = AssociatedFile (Just file)
start' :: DropOptions -> Key -> AssociatedFile -> ActionItem -> CommandStart
start' o key afile ai = do
from <- maybe (pure Nothing) (Just <$$> getParsed) (dropFrom o)
checkDropAuto (autoMode o) from afile key $ \numcopies ->
stopUnless (want from) $
case from of
Nothing -> startLocal afile ai numcopies key []
Just remote -> do
u <- getUUID
if Remote.uuid remote == u
then startLocal afile ai numcopies key []
else startRemote afile ai numcopies key remote
where
want from
| autoMode o = wantDrop False (Remote.uuid <$> from) (Just key) afile
| otherwise = return True
startKeys :: DropOptions -> Key -> ActionItem -> CommandStart
startKeys o key = start' o key (AssociatedFile Nothing)
startLocal :: AssociatedFile -> ActionItem -> NumCopies -> Key -> [VerifiedCopy] -> CommandStart
startLocal afile ai numcopies key preverified = stopUnless (inAnnex key) $ do
showStart' "drop" key ai
next $ performLocal key afile numcopies preverified
startRemote :: AssociatedFile -> ActionItem -> NumCopies -> Key -> Remote -> CommandStart
startRemote afile ai numcopies key remote = do
showStart' ("drop " ++ Remote.name remote) key ai
next $ performRemote key afile numcopies remote
performLocal :: Key -> AssociatedFile -> NumCopies -> [VerifiedCopy] -> CommandPerform
performLocal key afile numcopies preverified = lockContentForRemoval key $ \contentlock -> do
u <- getUUID
(tocheck, verified) <- verifiableCopies key [u]
doDrop u (Just contentlock) key afile numcopies [] (preverified ++ verified) tocheck
( \proof -> do
liftIO $ debugM "drop" $ unwords
[ "Dropping from here"
, "proof:"
, show proof
]
removeAnnex contentlock
notifyDrop afile True
next $ cleanupLocal key
, do
notifyDrop afile False
stop
)
performRemote :: Key -> AssociatedFile -> NumCopies -> Remote -> CommandPerform
performRemote key afile numcopies remote = do
-- Filter the remote it's being dropped from out of the lists of
-- places assumed to have the key, and places to check.
When the local repo has the key , that 's one additional copy ,
-- as long as the local repo is not untrusted.
(tocheck, verified) <- verifiableCopies key [uuid]
doDrop uuid Nothing key afile numcopies [uuid] verified tocheck
( \proof -> do
liftIO $ debugM "drop" $ unwords
[ "Dropping from remote"
, show remote
, "proof:"
, show proof
]
ok <- Remote.removeKey remote key
next $ cleanupRemote key remote ok
, stop
)
where
uuid = Remote.uuid remote
cleanupLocal :: Key -> CommandCleanup
cleanupLocal key = do
logStatus key InfoMissing
return True
cleanupRemote :: Key -> Remote -> Bool -> CommandCleanup
cleanupRemote key remote ok = do
when ok $
Remote.logStatus remote key InfoMissing
return ok
Before running the dropaction , checks specified remotes to
- verify that enough copies of a key exist to allow it to be
- safely removed ( with no data loss ) .
-
- Also checks if it 's required content , and refuses to drop if so .
-
- --force overrides and always allows dropping .
- verify that enough copies of a key exist to allow it to be
- safely removed (with no data loss).
-
- Also checks if it's required content, and refuses to drop if so.
-
- --force overrides and always allows dropping.
-}
doDrop
:: UUID
-> Maybe ContentRemovalLock
-> Key
-> AssociatedFile
-> NumCopies
-> [UUID]
-> [VerifiedCopy]
-> [UnVerifiedCopy]
-> (Maybe SafeDropProof -> CommandPerform, CommandPerform)
-> CommandPerform
doDrop dropfrom contentlock key afile numcopies skip preverified check (dropaction, nodropaction) =
ifM (Annex.getState Annex.force)
( dropaction Nothing
, ifM (checkRequiredContent dropfrom key afile)
( verifyEnoughCopiesToDrop nolocmsg key
contentlock numcopies
skip preverified check
(dropaction . Just)
(forcehint nodropaction)
, stop
)
)
where
nolocmsg = "Rather than dropping this file, try using: git annex move"
forcehint a = do
showLongNote "(Use --force to override this check, or adjust numcopies.)"
a
checkRequiredContent :: UUID -> Key -> AssociatedFile -> Annex Bool
checkRequiredContent u k afile =
ifM (isRequiredContent (Just u) S.empty (Just k) afile False)
( requiredContent
, return True
)
requiredContent :: Annex Bool
requiredContent = do
showLongNote "That file is required content, it cannot be dropped!"
showLongNote "(Use --force to override this check, or adjust required content configuration.)"
return False
{- In auto mode, only runs the action if there are enough
- copies on other semitrusted repositories. -}
checkDropAuto :: Bool -> Maybe Remote -> AssociatedFile -> Key -> (NumCopies -> CommandStart) -> CommandStart
checkDropAuto automode mremote (AssociatedFile afile) key a =
go =<< maybe getNumCopies getFileNumCopies afile
where
go numcopies
| automode = do
locs <- Remote.keyLocations key
uuid <- getUUID
let remoteuuid = fromMaybe uuid $ Remote.uuid <$> mremote
locs' <- trustExclude UnTrusted $ filter (/= remoteuuid) locs
if NumCopies (length locs') >= numcopies
then a numcopies
else stop
| otherwise = a numcopies
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Command/Drop.hs | haskell | Filter the remote it's being dropped from out of the lists of
places assumed to have the key, and places to check.
as long as the local repo is not untrusted.
force overrides and always allows dropping .
force overrides and always allows dropping.
In auto mode, only runs the action if there are enough
- copies on other semitrusted repositories. | git - annex command
-
- Copyright 2010 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2010 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Command.Drop where
import Command
import qualified Remote
import qualified Annex
import Annex.UUID
import Logs.Location
import Logs.Trust
import Logs.PreferredContent
import Annex.NumCopies
import Annex.Content
import Annex.Wanted
import Annex.Notification
import System.Log.Logger (debugM)
import qualified Data.Set as S
cmd :: Command
cmd = withGlobalOptions (jobsOption : jsonOption : annexedMatchingOptions) $
command "drop" SectionCommon
"remove content of files from repository"
paramPaths (seek <$$> optParser)
data DropOptions = DropOptions
{ dropFiles :: CmdParams
, dropFrom :: Maybe (DeferredParse Remote)
, autoMode :: Bool
, keyOptions :: Maybe KeyOptions
, batchOption :: BatchMode
}
optParser :: CmdParamsDesc -> Parser DropOptions
optParser desc = DropOptions
<$> cmdParams desc
<*> optional parseDropFromOption
<*> parseAutoOption
<*> optional parseKeyOptions
<*> parseBatchOption
parseDropFromOption :: Parser (DeferredParse Remote)
parseDropFromOption = parseRemoteOption <$> strOption
( long "from" <> short 'f' <> metavar paramRemote
<> help "drop content from a remote"
<> completeRemotes
)
seek :: DropOptions -> CommandSeek
seek o = allowConcurrentOutput $
case batchOption o of
Batch -> batchInput Right (batchCommandAction . go)
NoBatch -> withKeyOptions (keyOptions o) (autoMode o)
(startKeys o)
(withFilesInGit go)
=<< workTreeItems (dropFiles o)
where
go = whenAnnexed $ start o
start :: DropOptions -> FilePath -> Key -> CommandStart
start o file key = start' o key afile (mkActionItem afile)
where
afile = AssociatedFile (Just file)
start' :: DropOptions -> Key -> AssociatedFile -> ActionItem -> CommandStart
start' o key afile ai = do
from <- maybe (pure Nothing) (Just <$$> getParsed) (dropFrom o)
checkDropAuto (autoMode o) from afile key $ \numcopies ->
stopUnless (want from) $
case from of
Nothing -> startLocal afile ai numcopies key []
Just remote -> do
u <- getUUID
if Remote.uuid remote == u
then startLocal afile ai numcopies key []
else startRemote afile ai numcopies key remote
where
want from
| autoMode o = wantDrop False (Remote.uuid <$> from) (Just key) afile
| otherwise = return True
startKeys :: DropOptions -> Key -> ActionItem -> CommandStart
startKeys o key = start' o key (AssociatedFile Nothing)
startLocal :: AssociatedFile -> ActionItem -> NumCopies -> Key -> [VerifiedCopy] -> CommandStart
startLocal afile ai numcopies key preverified = stopUnless (inAnnex key) $ do
showStart' "drop" key ai
next $ performLocal key afile numcopies preverified
startRemote :: AssociatedFile -> ActionItem -> NumCopies -> Key -> Remote -> CommandStart
startRemote afile ai numcopies key remote = do
showStart' ("drop " ++ Remote.name remote) key ai
next $ performRemote key afile numcopies remote
performLocal :: Key -> AssociatedFile -> NumCopies -> [VerifiedCopy] -> CommandPerform
performLocal key afile numcopies preverified = lockContentForRemoval key $ \contentlock -> do
u <- getUUID
(tocheck, verified) <- verifiableCopies key [u]
doDrop u (Just contentlock) key afile numcopies [] (preverified ++ verified) tocheck
( \proof -> do
liftIO $ debugM "drop" $ unwords
[ "Dropping from here"
, "proof:"
, show proof
]
removeAnnex contentlock
notifyDrop afile True
next $ cleanupLocal key
, do
notifyDrop afile False
stop
)
performRemote :: Key -> AssociatedFile -> NumCopies -> Remote -> CommandPerform
performRemote key afile numcopies remote = do
When the local repo has the key , that 's one additional copy ,
(tocheck, verified) <- verifiableCopies key [uuid]
doDrop uuid Nothing key afile numcopies [uuid] verified tocheck
( \proof -> do
liftIO $ debugM "drop" $ unwords
[ "Dropping from remote"
, show remote
, "proof:"
, show proof
]
ok <- Remote.removeKey remote key
next $ cleanupRemote key remote ok
, stop
)
where
uuid = Remote.uuid remote
cleanupLocal :: Key -> CommandCleanup
cleanupLocal key = do
logStatus key InfoMissing
return True
cleanupRemote :: Key -> Remote -> Bool -> CommandCleanup
cleanupRemote key remote ok = do
when ok $
Remote.logStatus remote key InfoMissing
return ok
Before running the dropaction , checks specified remotes to
- verify that enough copies of a key exist to allow it to be
- safely removed ( with no data loss ) .
-
- Also checks if it 's required content , and refuses to drop if so .
-
- verify that enough copies of a key exist to allow it to be
- safely removed (with no data loss).
-
- Also checks if it's required content, and refuses to drop if so.
-
-}
doDrop
:: UUID
-> Maybe ContentRemovalLock
-> Key
-> AssociatedFile
-> NumCopies
-> [UUID]
-> [VerifiedCopy]
-> [UnVerifiedCopy]
-> (Maybe SafeDropProof -> CommandPerform, CommandPerform)
-> CommandPerform
doDrop dropfrom contentlock key afile numcopies skip preverified check (dropaction, nodropaction) =
ifM (Annex.getState Annex.force)
( dropaction Nothing
, ifM (checkRequiredContent dropfrom key afile)
( verifyEnoughCopiesToDrop nolocmsg key
contentlock numcopies
skip preverified check
(dropaction . Just)
(forcehint nodropaction)
, stop
)
)
where
nolocmsg = "Rather than dropping this file, try using: git annex move"
forcehint a = do
showLongNote "(Use --force to override this check, or adjust numcopies.)"
a
checkRequiredContent :: UUID -> Key -> AssociatedFile -> Annex Bool
checkRequiredContent u k afile =
ifM (isRequiredContent (Just u) S.empty (Just k) afile False)
( requiredContent
, return True
)
requiredContent :: Annex Bool
requiredContent = do
showLongNote "That file is required content, it cannot be dropped!"
showLongNote "(Use --force to override this check, or adjust required content configuration.)"
return False
checkDropAuto :: Bool -> Maybe Remote -> AssociatedFile -> Key -> (NumCopies -> CommandStart) -> CommandStart
checkDropAuto automode mremote (AssociatedFile afile) key a =
go =<< maybe getNumCopies getFileNumCopies afile
where
go numcopies
| automode = do
locs <- Remote.keyLocations key
uuid <- getUUID
let remoteuuid = fromMaybe uuid $ Remote.uuid <$> mremote
locs' <- trustExclude UnTrusted $ filter (/= remoteuuid) locs
if NumCopies (length locs') >= numcopies
then a numcopies
else stop
| otherwise = a numcopies
|
93b4ce9b628f259cdc6fdec8fecb501573b2a7efe7030ee5701c129d5edab2f1 | Anut-py/h-raylib | Core.hs | {-# OPTIONS -Wall #-}
# LANGUAGE ForeignFunctionInterface #
module Raylib.Core where
import Data.IORef (modifyIORef', readIORef)
import qualified Data.Map as Map
import Foreign
( Ptr,
Storable (peek, sizeOf),
castPtr,
fromBool,
peekArray,
toBool,
)
import Foreign.C
( CInt (CInt),
CUChar,
CUInt (CUInt),
peekCString,
withCString,
)
import Raylib.ForeignUtil (c'free, configsToBitflag, pop, popCArray, popCString, withFreeable, withFreeableArray, withFreeableArrayLen, withMaybeCString)
import Raylib.Internal (addShaderId, shaderLocations, unloadFrameBuffers, unloadShaders, unloadSingleShader, unloadTextures, unloadVaoIds, unloadVboIds)
import Raylib.Native
( c'beginBlendMode,
c'beginMode2D,
c'beginMode3D,
c'beginScissorMode,
c'beginShaderMode,
c'beginTextureMode,
c'beginVrStereoMode,
c'changeDirectory,
c'clearBackground,
c'clearWindowState,
c'closeWindow,
c'compressData,
c'decodeDataBase64,
c'decompressData,
c'directoryExists,
c'encodeDataBase64,
c'exportDataAsCode,
c'fileExists,
c'getApplicationDirectory,
c'getCameraMatrix,
c'getCameraMatrix2D,
c'getCharPressed,
c'getClipboardText,
c'getCurrentMonitor,
c'getDirectoryPath,
c'getFPS,
c'getFileExtension,
c'getFileLength,
c'getFileModTime,
c'getFileName,
c'getFileNameWithoutExt,
c'getFrameTime,
c'getGamepadAxisCount,
c'getGamepadAxisMovement,
c'getGamepadButtonPressed,
c'getGamepadName,
c'getGestureDetected,
c'getGestureDragAngle,
c'getGestureDragVector,
c'getGestureHoldDuration,
c'getGesturePinchAngle,
c'getGesturePinchVector,
c'getKeyPressed,
c'getMonitorCount,
c'getMonitorHeight,
c'getMonitorName,
c'getMonitorPhysicalHeight,
c'getMonitorPhysicalWidth,
c'getMonitorPosition,
c'getMonitorRefreshRate,
c'getMonitorWidth,
c'getMouseDelta,
c'getMousePosition,
c'getMouseRay,
c'getMouseWheelMove,
c'getMouseWheelMoveV,
c'getMouseX,
c'getMouseY,
c'getPrevDirectoryPath,
c'getRandomValue,
c'getRenderHeight,
c'getRenderWidth,
c'getScreenHeight,
c'getScreenToWorld2D,
c'getScreenWidth,
c'getShaderLocation,
c'getShaderLocationAttrib,
c'getTime,
c'getTouchPointCount,
c'getTouchPointId,
c'getTouchPosition,
c'getTouchX,
c'getTouchY,
c'getWindowPosition,
c'getWindowScaleDPI,
c'getWorkingDirectory,
c'getWorldToScreen,
c'getWorldToScreen2D,
c'getWorldToScreenEx,
c'initWindow,
c'isCursorHidden,
c'isCursorOnScreen,
c'isFileDropped,
c'isFileExtension,
c'isGamepadAvailable,
c'isGamepadButtonDown,
c'isGamepadButtonPressed,
c'isGamepadButtonReleased,
c'isGamepadButtonUp,
c'isGestureDetected,
c'isKeyDown,
c'isKeyPressed,
c'isKeyReleased,
c'isKeyUp,
c'isMouseButtonDown,
c'isMouseButtonPressed,
c'isMouseButtonReleased,
c'isMouseButtonUp,
c'isPathFile,
c'isShaderReady,
c'isWindowFocused,
c'isWindowFullscreen,
c'isWindowHidden,
c'isWindowMaximized,
c'isWindowMinimized,
c'isWindowReady,
c'isWindowResized,
c'isWindowState,
c'loadDirectoryFiles,
c'loadDirectoryFilesEx,
c'loadDroppedFiles,
c'loadFileData,
c'loadFileText,
c'loadShader,
c'loadShaderFromMemory,
c'loadVrStereoConfig,
c'openURL,
c'saveFileData,
c'saveFileText,
c'setClipboardText,
c'setConfigFlags,
c'setExitKey,
c'setGamepadMappings,
c'setGesturesEnabled,
c'setMouseCursor,
c'setMouseOffset,
c'setMousePosition,
c'setMouseScale,
c'setRandomSeed,
c'setShaderValue,
c'setShaderValueMatrix,
c'setShaderValueTexture,
c'setShaderValueV,
c'setTargetFPS,
c'setTraceLogLevel,
c'setWindowIcon,
c'setWindowIcons,
c'setWindowMinSize,
c'setWindowMonitor,
c'setWindowOpacity,
c'setWindowPosition,
c'setWindowSize,
c'setWindowState,
c'setWindowTitle,
c'takeScreenshot,
c'traceLog,
c'updateCamera,
c'waitTime,
c'windowShouldClose,
)
import Raylib.Types
( BlendMode,
Camera2D,
Camera3D,
CameraMode,
Color,
ConfigFlag,
FilePathList,
GamepadAxis,
GamepadButton,
Gesture,
Image,
KeyboardKey,
LoadFileDataCallback,
LoadFileTextCallback,
Matrix,
MouseButton,
MouseCursor,
Ray,
RenderTexture,
SaveFileDataCallback,
SaveFileTextCallback,
Shader (shader'id),
ShaderUniformData,
ShaderUniformDataV,
Texture,
TraceLogLevel,
Vector2,
Vector3,
VrDeviceInfo,
VrStereoConfig,
unpackShaderUniformData,
unpackShaderUniformDataV,
)
initWindow :: Int -> Int -> String -> IO ()
initWindow width height title = withCString title $ c'initWindow (fromIntegral width) (fromIntegral height)
windowShouldClose :: IO Bool
windowShouldClose = toBool <$> c'windowShouldClose
closeWindow :: IO ()
closeWindow = do
unloadShaders
unloadTextures
unloadFrameBuffers
unloadVaoIds
unloadVboIds
c'closeWindow
isWindowReady :: IO Bool
isWindowReady = toBool <$> c'isWindowReady
isWindowFullscreen :: IO Bool
isWindowFullscreen = toBool <$> c'isWindowFullscreen
isWindowHidden :: IO Bool
isWindowHidden = toBool <$> c'isWindowHidden
isWindowMinimized :: IO Bool
isWindowMinimized = toBool <$> c'isWindowMinimized
isWindowMaximized :: IO Bool
isWindowMaximized = toBool <$> c'isWindowMaximized
isWindowFocused :: IO Bool
isWindowFocused = toBool <$> c'isWindowFocused
isWindowResized :: IO Bool
isWindowResized = toBool <$> c'isWindowResized
isWindowState :: [ConfigFlag] -> IO Bool
isWindowState flags = toBool <$> c'isWindowState (fromIntegral $ configsToBitflag flags)
setWindowState :: [ConfigFlag] -> IO ()
setWindowState = c'setWindowState . fromIntegral . configsToBitflag
clearWindowState :: [ConfigFlag] -> IO ()
clearWindowState = c'clearWindowState . fromIntegral . configsToBitflag
foreign import ccall safe "raylib.h ToggleFullscreen"
toggleFullscreen ::
IO ()
foreign import ccall safe "raylib.h MaximizeWindow"
maximizeWindow ::
IO ()
foreign import ccall safe "raylib.h MinimizeWindow"
minimizeWindow ::
IO ()
foreign import ccall safe "raylib.h RestoreWindow"
restoreWindow ::
IO ()
setWindowIcon :: Image -> IO ()
setWindowIcon image = withFreeable image c'setWindowIcon
setWindowIcons :: [Image] -> IO ()
setWindowIcons images = withFreeableArrayLen images (\l ptr -> c'setWindowIcons ptr (fromIntegral l))
setWindowTitle :: String -> IO ()
setWindowTitle title = withCString title c'setWindowTitle
setWindowPosition :: Int -> Int -> IO ()
setWindowPosition x y = c'setWindowPosition (fromIntegral x) (fromIntegral y)
setWindowMonitor :: Int -> IO ()
setWindowMonitor = c'setWindowMonitor . fromIntegral
setWindowMinSize :: Int -> Int -> IO ()
setWindowMinSize x y = c'setWindowMinSize (fromIntegral x) (fromIntegral y)
setWindowSize :: Int -> Int -> IO ()
setWindowSize x y = c'setWindowSize (fromIntegral x) (fromIntegral y)
setWindowOpacity :: Float -> IO ()
setWindowOpacity opacity = c'setWindowOpacity $ realToFrac opacity
foreign import ccall safe "raylib.h GetWindowHandle"
getWindowHandle ::
IO (Ptr ())
getScreenWidth :: IO Int
getScreenWidth = fromIntegral <$> c'getScreenWidth
getScreenHeight :: IO Int
getScreenHeight = fromIntegral <$> c'getScreenHeight
getRenderWidth :: IO Int
getRenderWidth = fromIntegral <$> c'getRenderWidth
getRenderHeight :: IO Int
getRenderHeight = fromIntegral <$> c'getRenderHeight
getMonitorCount :: IO Int
getMonitorCount = fromIntegral <$> c'getMonitorCount
getCurrentMonitor :: IO Int
getCurrentMonitor = fromIntegral <$> c'getCurrentMonitor
getMonitorPosition :: Int -> IO Vector2
getMonitorPosition monitor = c'getMonitorPosition (fromIntegral monitor) >>= pop
getMonitorWidth :: Int -> IO Int
getMonitorWidth monitor = fromIntegral <$> c'getMonitorWidth (fromIntegral monitor)
getMonitorHeight :: Int -> IO Int
getMonitorHeight monitor = fromIntegral <$> c'getMonitorHeight (fromIntegral monitor)
getMonitorPhysicalWidth :: Int -> IO Int
getMonitorPhysicalWidth monitor = fromIntegral <$> c'getMonitorPhysicalWidth (fromIntegral monitor)
getMonitorPhysicalHeight :: Int -> IO Int
getMonitorPhysicalHeight monitor = fromIntegral <$> c'getMonitorPhysicalHeight (fromIntegral monitor)
getMonitorRefreshRate :: Int -> IO Int
getMonitorRefreshRate monitor = fromIntegral <$> c'getMonitorRefreshRate (fromIntegral monitor)
getWindowPosition :: IO Vector2
getWindowPosition = c'getWindowPosition >>= pop
getWindowScaleDPI :: IO Vector2
getWindowScaleDPI = c'getWindowScaleDPI >>= pop
getMonitorName :: Int -> IO String
getMonitorName monitor = c'getMonitorName (fromIntegral monitor) >>= peekCString
setClipboardText :: String -> IO ()
setClipboardText text = withCString text c'setClipboardText
getClipboardText :: IO String
getClipboardText = c'getClipboardText >>= peekCString
foreign import ccall safe "raylib.h EnableEventWaiting"
enableEventWaiting ::
IO ()
foreign import ccall safe "raylib.h DisableEventWaiting"
disableEventWaiting ::
IO ()
foreign import ccall safe "raylib.h SwapScreenBuffer"
swapScreenBuffer ::
IO ()
foreign import ccall safe "raylib.h PollInputEvents"
pollInputEvents ::
IO ()
waitTime :: Double -> IO ()
waitTime seconds = c'waitTime $ realToFrac seconds
foreign import ccall safe "raylib.h ShowCursor"
showCursor ::
IO ()
foreign import ccall safe "raylib.h HideCursor"
hideCursor ::
IO ()
isCursorHidden :: IO Bool
isCursorHidden = toBool <$> c'isCursorHidden
foreign import ccall safe "raylib.h EnableCursor"
enableCursor ::
IO ()
foreign import ccall safe "raylib.h DisableCursor"
disableCursor ::
IO ()
isCursorOnScreen :: IO Bool
isCursorOnScreen = toBool <$> c'isCursorOnScreen
clearBackground :: Color -> IO ()
clearBackground color = withFreeable color c'clearBackground
foreign import ccall safe "raylib.h BeginDrawing"
beginDrawing ::
IO ()
foreign import ccall safe "raylib.h EndDrawing"
endDrawing ::
IO ()
beginMode2D :: Camera2D -> IO ()
beginMode2D camera = withFreeable camera c'beginMode2D
foreign import ccall safe "raylib.h EndMode2D"
endMode2D ::
IO ()
beginMode3D :: Camera3D -> IO ()
beginMode3D camera = withFreeable camera c'beginMode3D
foreign import ccall safe "raylib.h EndMode3D"
endMode3D ::
IO ()
beginTextureMode :: RenderTexture -> IO ()
beginTextureMode renderTexture = withFreeable renderTexture c'beginTextureMode
foreign import ccall safe "raylib.h EndTextureMode"
endTextureMode ::
IO ()
beginShaderMode :: Shader -> IO ()
beginShaderMode shader = withFreeable shader c'beginShaderMode
foreign import ccall safe "raylib.h EndShaderMode"
endShaderMode ::
IO ()
beginBlendMode :: BlendMode -> IO ()
beginBlendMode = c'beginBlendMode . fromIntegral . fromEnum
foreign import ccall safe "raylib.h EndBlendMode"
endBlendMode ::
IO ()
beginScissorMode :: Int -> Int -> Int -> Int -> IO ()
beginScissorMode x y width height = c'beginScissorMode (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)
foreign import ccall safe "raylib.h EndScissorMode"
endScissorMode ::
IO ()
beginVrStereoMode :: VrStereoConfig -> IO ()
beginVrStereoMode config = withFreeable config c'beginVrStereoMode
foreign import ccall safe "raylib.h EndVrStereoMode"
endVrStereoMode ::
IO ()
loadVrStereoConfig :: VrDeviceInfo -> IO VrStereoConfig
loadVrStereoConfig deviceInfo = withFreeable deviceInfo c'loadVrStereoConfig >>= pop
loadShader :: Maybe String -> Maybe String -> IO Shader
loadShader vsFileName fsFileName = do
shader <- withMaybeCString vsFileName (withMaybeCString fsFileName . c'loadShader) >>= pop
addShaderId $ shader'id shader
return shader
loadShaderFromMemory :: Maybe String -> Maybe String -> IO Shader
loadShaderFromMemory vsCode fsCode = do
shader <- withMaybeCString vsCode (withMaybeCString fsCode . c'loadShaderFromMemory) >>= pop
addShaderId $ shader'id shader
return shader
isShaderReady :: Shader -> IO Bool
isShaderReady shader = toBool <$> withFreeable shader c'isShaderReady
getShaderLocation :: Shader -> String -> IO Int
getShaderLocation shader uniformName = do
let sId = shader'id shader
locs <- readIORef shaderLocations
-- TODO: Clean this up if possible
case Map.lookup sId locs of
Nothing -> do
idx <- locIdx
let newMap = Map.fromList [(uniformName, idx)]
modifyIORef' shaderLocations (Map.insert sId newMap)
return idx
Just m -> case Map.lookup uniformName m of
Nothing -> do
idx <- locIdx
let newMap = Map.insert uniformName idx m
modifyIORef' shaderLocations (Map.insert sId newMap)
return idx
Just val -> return val
where
locIdx = fromIntegral <$> withFreeable shader (withCString uniformName . c'getShaderLocation)
getShaderLocationAttrib :: Shader -> String -> IO Int
getShaderLocationAttrib shader attribName = fromIntegral <$> withFreeable shader (withCString attribName . c'getShaderLocationAttrib)
setShaderValue :: Shader -> String -> ShaderUniformData -> IO ()
setShaderValue shader uniformName value = do
idx <- getShaderLocation shader uniformName
nativeSetShaderValue shader idx value
setShaderValueV :: Shader -> String -> ShaderUniformDataV -> IO ()
setShaderValueV shader uniformName values = do
idx <- getShaderLocation shader uniformName
nativeSetShaderValueV shader idx values
nativeSetShaderValue :: Shader -> Int -> ShaderUniformData -> IO ()
nativeSetShaderValue shader locIndex value = do
(uniformType, ptr) <- unpackShaderUniformData value
withFreeable shader (\s -> c'setShaderValue s (fromIntegral locIndex) ptr (fromIntegral $ fromEnum uniformType))
c'free $ castPtr ptr
nativeSetShaderValueV :: Shader -> Int -> ShaderUniformDataV -> IO ()
nativeSetShaderValueV shader locIndex values = do
(uniformType, ptr, l) <- unpackShaderUniformDataV values
withFreeable shader (\s -> c'setShaderValueV s (fromIntegral locIndex) ptr (fromIntegral $ fromEnum uniformType) (fromIntegral l))
c'free $ castPtr ptr
setShaderValueMatrix :: Shader -> Int -> Matrix -> IO ()
setShaderValueMatrix shader locIndex mat = withFreeable shader (\s -> withFreeable mat (c'setShaderValueMatrix s (fromIntegral locIndex)))
setShaderValueTexture :: Shader -> Int -> Texture -> IO ()
setShaderValueTexture shader locIndex tex = withFreeable shader (\s -> withFreeable tex (c'setShaderValueTexture s (fromIntegral locIndex)))
-- | Unloads a shader from GPU memory (VRAM). Shaders are automatically unloaded
-- when `closeWindow` is called, so manually unloading shaders is not required.
-- In larger projects, you may want to manually unload shaders to avoid having
them in VRAM for too long .
unloadShader :: Shader -> IO ()
unloadShader shader = unloadSingleShader (shader'id shader)
getMouseRay :: Vector2 -> Camera3D -> IO Ray
getMouseRay mousePosition camera = withFreeable mousePosition (withFreeable camera . c'getMouseRay) >>= pop
getCameraMatrix :: Camera3D -> IO Matrix
getCameraMatrix camera = withFreeable camera c'getCameraMatrix >>= pop
getCameraMatrix2D :: Camera2D -> IO Matrix
getCameraMatrix2D camera = withFreeable camera c'getCameraMatrix2D >>= pop
getWorldToScreen :: Vector3 -> Camera3D -> IO Vector2
getWorldToScreen position camera = withFreeable position (withFreeable camera . c'getWorldToScreen) >>= pop
getScreenToWorld2D :: Vector2 -> Camera2D -> IO Vector2
getScreenToWorld2D position camera = withFreeable position (withFreeable camera . c'getScreenToWorld2D) >>= pop
getWorldToScreenEx :: Vector3 -> Camera3D -> Int -> Int -> IO Vector2
getWorldToScreenEx position camera width height = withFreeable position (\p -> withFreeable camera (\c -> c'getWorldToScreenEx p c (fromIntegral width) (fromIntegral height))) >>= pop
getWorldToScreen2D :: Vector2 -> Camera2D -> IO Vector2
getWorldToScreen2D position camera = withFreeable position (withFreeable camera . c'getWorldToScreen2D) >>= pop
setTargetFPS :: Int -> IO ()
setTargetFPS fps = c'setTargetFPS $ fromIntegral fps
getFPS :: IO Int
getFPS = fromIntegral <$> c'getFPS
getFrameTime :: IO Float
getFrameTime = realToFrac <$> c'getFrameTime
getTime :: IO Double
getTime = realToFrac <$> c'getTime
getRandomValue :: Int -> Int -> IO Int
getRandomValue minVal maxVal = fromIntegral <$> c'getRandomValue (fromIntegral minVal) (fromIntegral maxVal)
setRandomSeed :: Integer -> IO ()
setRandomSeed seed = c'setRandomSeed $ fromIntegral seed
takeScreenshot :: String -> IO ()
takeScreenshot fileName = withCString fileName c'takeScreenshot
setConfigFlags :: [ConfigFlag] -> IO ()
setConfigFlags flags = c'setConfigFlags $ fromIntegral $ configsToBitflag flags
traceLog :: TraceLogLevel -> String -> IO ()
traceLog logLevel text = withCString text $ c'traceLog $ fromIntegral $ fromEnum logLevel
setTraceLogLevel :: TraceLogLevel -> IO ()
setTraceLogLevel = c'setTraceLogLevel . fromIntegral . fromEnum
openURL :: String -> IO ()
openURL url = withCString url c'openURL
foreign import ccall safe "raylib.h SetLoadFileDataCallback"
setLoadFileDataCallback ::
LoadFileDataCallback -> IO ()
foreign import ccall safe "raylib.h SetSaveFileDataCallback"
setSaveFileDataCallback ::
SaveFileDataCallback -> IO ()
foreign import ccall safe "raylib.h SetLoadFileTextCallback"
setLoadFileTextCallback ::
LoadFileTextCallback -> IO ()
foreign import ccall safe "raylib.h SetSaveFileTextCallback"
setSaveFileTextCallback ::
SaveFileTextCallback -> IO ()
loadFileData :: String -> IO [Integer]
loadFileData fileName =
withFreeable
0
( \size -> do
withCString
fileName
( \path -> do
ptr <- c'loadFileData path size
arrSize <- fromIntegral <$> peek size
map fromIntegral <$> popCArray arrSize ptr
)
)
saveFileData :: (Storable a) => String -> Ptr a -> Integer -> IO Bool
saveFileData fileName contents bytesToWrite =
toBool <$> withCString fileName (\s -> c'saveFileData s (castPtr contents) (fromIntegral bytesToWrite))
exportDataAsCode :: [Integer] -> Integer -> String -> IO Bool
exportDataAsCode contents size fileName =
toBool <$> withFreeableArray (map fromInteger contents) (\c -> withCString fileName (c'exportDataAsCode c (fromIntegral size)))
loadFileText :: String -> IO String
loadFileText fileName = withCString fileName c'loadFileText >>= popCString
saveFileText :: String -> String -> IO Bool
saveFileText fileName text = toBool <$> withCString fileName (withCString text . c'saveFileText)
fileExists :: String -> IO Bool
fileExists fileName = toBool <$> withCString fileName c'fileExists
directoryExists :: String -> IO Bool
directoryExists dirPath = toBool <$> withCString dirPath c'directoryExists
isFileExtension :: String -> String -> IO Bool
isFileExtension fileName ext = toBool <$> withCString fileName (withCString ext . c'isFileExtension)
getFileLength :: String -> IO Bool
getFileLength fileName = toBool <$> withCString fileName c'getFileLength
getFileExtension :: String -> IO String
getFileExtension fileName = withCString fileName c'getFileExtension >>= peekCString
getFileName :: String -> IO String
getFileName filePath = withCString filePath c'getFileName >>= peekCString
getFileNameWithoutExt :: String -> IO String
getFileNameWithoutExt fileName = withCString fileName c'getFileNameWithoutExt >>= peekCString
getDirectoryPath :: String -> IO String
getDirectoryPath filePath = withCString filePath c'getDirectoryPath >>= peekCString
getPrevDirectoryPath :: String -> IO String
getPrevDirectoryPath dirPath = withCString dirPath c'getPrevDirectoryPath >>= peekCString
getWorkingDirectory :: IO String
getWorkingDirectory = c'getWorkingDirectory >>= peekCString
getApplicationDirectory :: IO String
getApplicationDirectory = c'getApplicationDirectory >>= peekCString
changeDirectory :: String -> IO Bool
changeDirectory dir = toBool <$> withCString dir c'changeDirectory
isPathFile :: String -> IO Bool
isPathFile path = toBool <$> withCString path c'isPathFile
loadDirectoryFiles :: String -> IO FilePathList
loadDirectoryFiles dirPath = withCString dirPath c'loadDirectoryFiles >>= pop
loadDirectoryFilesEx :: String -> String -> Bool -> IO FilePathList
loadDirectoryFilesEx basePath filterStr scanSubdirs =
withCString basePath (\b -> withCString filterStr (\f -> c'loadDirectoryFilesEx b f (fromBool scanSubdirs))) >>= pop
isFileDropped :: IO Bool
isFileDropped = toBool <$> c'isFileDropped
loadDroppedFiles :: IO FilePathList
loadDroppedFiles = c'loadDroppedFiles >>= pop
getFileModTime :: String -> IO Integer
getFileModTime fileName = fromIntegral <$> withCString fileName c'getFileModTime
compressData :: [Integer] -> IO [Integer]
compressData contents = do
withFreeableArrayLen
(map fromIntegral contents)
( \size c -> do
withFreeable
0
( \ptr -> do
compressed <- c'compressData c (fromIntegral $ size * sizeOf (0 :: CUChar)) ptr
compressedSize <- fromIntegral <$> peek ptr
arr <- peekArray compressedSize compressed
return $ map fromIntegral arr
)
)
decompressData :: [Integer] -> IO [Integer]
decompressData compressedData = do
withFreeableArrayLen
(map fromIntegral compressedData)
( \size c -> do
withFreeable
0
( \ptr -> do
decompressed <- c'decompressData c (fromIntegral $ size * sizeOf (0 :: CUChar)) ptr
decompressedSize <- fromIntegral <$> peek ptr
arr <- peekArray decompressedSize decompressed
return $ map fromIntegral arr
)
)
encodeDataBase64 :: [Integer] -> IO [Integer]
encodeDataBase64 contents = do
withFreeableArrayLen
(map fromIntegral contents)
( \size c -> do
withFreeable
0
( \ptr -> do
encoded <- c'encodeDataBase64 c (fromIntegral $ size * sizeOf (0 :: CUChar)) ptr
encodedSize <- fromIntegral <$> peek ptr
arr <- peekArray encodedSize encoded
return $ map fromIntegral arr
)
)
decodeDataBase64 :: [Integer] -> IO [Integer]
decodeDataBase64 encodedData = do
withFreeableArray
(map fromIntegral encodedData)
( \c -> do
withFreeable
0
( \ptr -> do
decoded <- c'decodeDataBase64 c ptr
decodedSize <- fromIntegral <$> peek ptr
arr <- peekArray decodedSize decoded
return $ map fromIntegral arr
)
)
isKeyPressed :: KeyboardKey -> IO Bool
isKeyPressed key = toBool <$> c'isKeyPressed (fromIntegral $ fromEnum key)
isKeyDown :: KeyboardKey -> IO Bool
isKeyDown key = toBool <$> c'isKeyDown (fromIntegral $ fromEnum key)
isKeyReleased :: KeyboardKey -> IO Bool
isKeyReleased key = toBool <$> c'isKeyReleased (fromIntegral $ fromEnum key)
isKeyUp :: KeyboardKey -> IO Bool
isKeyUp key = toBool <$> c'isKeyUp (fromIntegral $ fromEnum key)
setExitKey :: KeyboardKey -> IO ()
setExitKey = c'setExitKey . fromIntegral . fromEnum
getKeyPressed :: IO KeyboardKey
getKeyPressed = toEnum . fromIntegral <$> c'getKeyPressed
getCharPressed :: IO Int
getCharPressed = fromIntegral <$> c'getCharPressed
isGamepadAvailable :: Int -> IO Bool
isGamepadAvailable gamepad = toBool <$> c'isGamepadAvailable (fromIntegral gamepad)
getGamepadName :: Int -> IO String
getGamepadName gamepad = c'getGamepadName (fromIntegral gamepad) >>= peekCString
isGamepadButtonPressed :: Int -> GamepadButton -> IO Bool
isGamepadButtonPressed gamepad button = toBool <$> c'isGamepadButtonPressed (fromIntegral gamepad) (fromIntegral $ fromEnum button)
isGamepadButtonDown :: Int -> GamepadButton -> IO Bool
isGamepadButtonDown gamepad button = toBool <$> c'isGamepadButtonDown (fromIntegral gamepad) (fromIntegral $ fromEnum button)
isGamepadButtonReleased :: Int -> GamepadButton -> IO Bool
isGamepadButtonReleased gamepad button = toBool <$> c'isGamepadButtonReleased (fromIntegral gamepad) (fromIntegral $ fromEnum button)
isGamepadButtonUp :: Int -> GamepadButton -> IO Bool
isGamepadButtonUp gamepad button = toBool <$> c'isGamepadButtonUp (fromIntegral gamepad) (fromIntegral $ fromEnum button)
getGamepadButtonPressed :: IO GamepadButton
getGamepadButtonPressed = toEnum . fromIntegral <$> c'getGamepadButtonPressed
getGamepadAxisCount :: Int -> IO Int
getGamepadAxisCount gamepad = fromIntegral <$> c'getGamepadAxisCount (fromIntegral gamepad)
getGamepadAxisMovement :: Int -> GamepadAxis -> IO Float
getGamepadAxisMovement gamepad axis = realToFrac <$> c'getGamepadAxisMovement (fromIntegral gamepad) (fromIntegral $ fromEnum axis)
setGamepadMappings :: String -> IO Int
setGamepadMappings mappings = fromIntegral <$> withCString mappings c'setGamepadMappings
isMouseButtonPressed :: MouseButton -> IO Bool
isMouseButtonPressed button = toBool <$> c'isMouseButtonPressed (fromIntegral $ fromEnum button)
isMouseButtonDown :: MouseButton -> IO Bool
isMouseButtonDown button = toBool <$> c'isMouseButtonDown (fromIntegral $ fromEnum button)
isMouseButtonReleased :: MouseButton -> IO Bool
isMouseButtonReleased button = toBool <$> c'isMouseButtonReleased (fromIntegral $ fromEnum button)
isMouseButtonUp :: MouseButton -> IO Bool
isMouseButtonUp button = toBool <$> c'isMouseButtonUp (fromIntegral $ fromEnum button)
getMouseX :: IO Int
getMouseX = fromIntegral <$> c'getMouseX
getMouseY :: IO Int
getMouseY = fromIntegral <$> c'getMouseY
getMousePosition :: IO Vector2
getMousePosition = c'getMousePosition >>= pop
getMouseDelta :: IO Vector2
getMouseDelta = c'getMouseDelta >>= pop
setMousePosition :: Int -> Int -> IO ()
setMousePosition x y = c'setMousePosition (fromIntegral x) (fromIntegral y)
setMouseOffset :: Int -> Int -> IO ()
setMouseOffset x y = c'setMouseOffset (fromIntegral x) (fromIntegral y)
setMouseScale :: Float -> Float -> IO ()
setMouseScale x y = c'setMouseScale (realToFrac x) (realToFrac y)
getMouseWheelMove :: IO Float
getMouseWheelMove = realToFrac <$> c'getMouseWheelMove
getMouseWheelMoveV :: IO Vector2
getMouseWheelMoveV = c'getMouseWheelMoveV >>= pop
setMouseCursor :: MouseCursor -> IO ()
setMouseCursor cursor = c'setMouseCursor . fromIntegral $ fromEnum cursor
getTouchX :: IO Int
getTouchX = fromIntegral <$> c'getTouchX
getTouchY :: IO Int
getTouchY = fromIntegral <$> c'getTouchY
getTouchPosition :: Int -> IO Vector2
getTouchPosition index = c'getTouchPosition (fromIntegral index) >>= pop
getTouchPointId :: Int -> IO Int
getTouchPointId index = fromIntegral <$> c'getTouchPointId (fromIntegral index)
getTouchPointCount :: IO Int
getTouchPointCount = fromIntegral <$> c'getTouchPointCount
setGesturesEnabled :: [Gesture] -> IO ()
setGesturesEnabled flags = c'setGesturesEnabled (fromIntegral $ configsToBitflag flags)
isGestureDetected :: Gesture -> IO Bool
isGestureDetected gesture = toBool <$> c'isGestureDetected (fromIntegral $ fromEnum gesture)
getGestureDetected :: IO Gesture
getGestureDetected = toEnum . fromIntegral <$> c'getGestureDetected
getGestureHoldDuration :: IO Float
getGestureHoldDuration = realToFrac <$> c'getGestureHoldDuration
getGestureDragVector :: IO Vector2
getGestureDragVector = c'getGestureDragVector >>= pop
getGestureDragAngle :: IO Float
getGestureDragAngle = realToFrac <$> c'getGestureDragAngle
getGesturePinchVector :: IO Vector2
getGesturePinchVector = c'getGesturePinchVector >>= pop
getGesturePinchAngle :: IO Float
getGesturePinchAngle = realToFrac <$> c'getGesturePinchAngle
updateCamera :: Camera3D -> CameraMode -> IO Camera3D
updateCamera camera mode =
withFreeable
camera
( \c -> do
c'updateCamera c (fromIntegral $ fromEnum mode)
peek c
)
| null | https://raw.githubusercontent.com/Anut-py/h-raylib/22116158546b5f604a512192c67bf2bf07bb31c8/src/Raylib/Core.hs | haskell | # OPTIONS -Wall #
TODO: Clean this up if possible
| Unloads a shader from GPU memory (VRAM). Shaders are automatically unloaded
when `closeWindow` is called, so manually unloading shaders is not required.
In larger projects, you may want to manually unload shaders to avoid having | # LANGUAGE ForeignFunctionInterface #
module Raylib.Core where
import Data.IORef (modifyIORef', readIORef)
import qualified Data.Map as Map
import Foreign
( Ptr,
Storable (peek, sizeOf),
castPtr,
fromBool,
peekArray,
toBool,
)
import Foreign.C
( CInt (CInt),
CUChar,
CUInt (CUInt),
peekCString,
withCString,
)
import Raylib.ForeignUtil (c'free, configsToBitflag, pop, popCArray, popCString, withFreeable, withFreeableArray, withFreeableArrayLen, withMaybeCString)
import Raylib.Internal (addShaderId, shaderLocations, unloadFrameBuffers, unloadShaders, unloadSingleShader, unloadTextures, unloadVaoIds, unloadVboIds)
import Raylib.Native
( c'beginBlendMode,
c'beginMode2D,
c'beginMode3D,
c'beginScissorMode,
c'beginShaderMode,
c'beginTextureMode,
c'beginVrStereoMode,
c'changeDirectory,
c'clearBackground,
c'clearWindowState,
c'closeWindow,
c'compressData,
c'decodeDataBase64,
c'decompressData,
c'directoryExists,
c'encodeDataBase64,
c'exportDataAsCode,
c'fileExists,
c'getApplicationDirectory,
c'getCameraMatrix,
c'getCameraMatrix2D,
c'getCharPressed,
c'getClipboardText,
c'getCurrentMonitor,
c'getDirectoryPath,
c'getFPS,
c'getFileExtension,
c'getFileLength,
c'getFileModTime,
c'getFileName,
c'getFileNameWithoutExt,
c'getFrameTime,
c'getGamepadAxisCount,
c'getGamepadAxisMovement,
c'getGamepadButtonPressed,
c'getGamepadName,
c'getGestureDetected,
c'getGestureDragAngle,
c'getGestureDragVector,
c'getGestureHoldDuration,
c'getGesturePinchAngle,
c'getGesturePinchVector,
c'getKeyPressed,
c'getMonitorCount,
c'getMonitorHeight,
c'getMonitorName,
c'getMonitorPhysicalHeight,
c'getMonitorPhysicalWidth,
c'getMonitorPosition,
c'getMonitorRefreshRate,
c'getMonitorWidth,
c'getMouseDelta,
c'getMousePosition,
c'getMouseRay,
c'getMouseWheelMove,
c'getMouseWheelMoveV,
c'getMouseX,
c'getMouseY,
c'getPrevDirectoryPath,
c'getRandomValue,
c'getRenderHeight,
c'getRenderWidth,
c'getScreenHeight,
c'getScreenToWorld2D,
c'getScreenWidth,
c'getShaderLocation,
c'getShaderLocationAttrib,
c'getTime,
c'getTouchPointCount,
c'getTouchPointId,
c'getTouchPosition,
c'getTouchX,
c'getTouchY,
c'getWindowPosition,
c'getWindowScaleDPI,
c'getWorkingDirectory,
c'getWorldToScreen,
c'getWorldToScreen2D,
c'getWorldToScreenEx,
c'initWindow,
c'isCursorHidden,
c'isCursorOnScreen,
c'isFileDropped,
c'isFileExtension,
c'isGamepadAvailable,
c'isGamepadButtonDown,
c'isGamepadButtonPressed,
c'isGamepadButtonReleased,
c'isGamepadButtonUp,
c'isGestureDetected,
c'isKeyDown,
c'isKeyPressed,
c'isKeyReleased,
c'isKeyUp,
c'isMouseButtonDown,
c'isMouseButtonPressed,
c'isMouseButtonReleased,
c'isMouseButtonUp,
c'isPathFile,
c'isShaderReady,
c'isWindowFocused,
c'isWindowFullscreen,
c'isWindowHidden,
c'isWindowMaximized,
c'isWindowMinimized,
c'isWindowReady,
c'isWindowResized,
c'isWindowState,
c'loadDirectoryFiles,
c'loadDirectoryFilesEx,
c'loadDroppedFiles,
c'loadFileData,
c'loadFileText,
c'loadShader,
c'loadShaderFromMemory,
c'loadVrStereoConfig,
c'openURL,
c'saveFileData,
c'saveFileText,
c'setClipboardText,
c'setConfigFlags,
c'setExitKey,
c'setGamepadMappings,
c'setGesturesEnabled,
c'setMouseCursor,
c'setMouseOffset,
c'setMousePosition,
c'setMouseScale,
c'setRandomSeed,
c'setShaderValue,
c'setShaderValueMatrix,
c'setShaderValueTexture,
c'setShaderValueV,
c'setTargetFPS,
c'setTraceLogLevel,
c'setWindowIcon,
c'setWindowIcons,
c'setWindowMinSize,
c'setWindowMonitor,
c'setWindowOpacity,
c'setWindowPosition,
c'setWindowSize,
c'setWindowState,
c'setWindowTitle,
c'takeScreenshot,
c'traceLog,
c'updateCamera,
c'waitTime,
c'windowShouldClose,
)
import Raylib.Types
( BlendMode,
Camera2D,
Camera3D,
CameraMode,
Color,
ConfigFlag,
FilePathList,
GamepadAxis,
GamepadButton,
Gesture,
Image,
KeyboardKey,
LoadFileDataCallback,
LoadFileTextCallback,
Matrix,
MouseButton,
MouseCursor,
Ray,
RenderTexture,
SaveFileDataCallback,
SaveFileTextCallback,
Shader (shader'id),
ShaderUniformData,
ShaderUniformDataV,
Texture,
TraceLogLevel,
Vector2,
Vector3,
VrDeviceInfo,
VrStereoConfig,
unpackShaderUniformData,
unpackShaderUniformDataV,
)
initWindow :: Int -> Int -> String -> IO ()
initWindow width height title = withCString title $ c'initWindow (fromIntegral width) (fromIntegral height)
windowShouldClose :: IO Bool
windowShouldClose = toBool <$> c'windowShouldClose
closeWindow :: IO ()
closeWindow = do
unloadShaders
unloadTextures
unloadFrameBuffers
unloadVaoIds
unloadVboIds
c'closeWindow
isWindowReady :: IO Bool
isWindowReady = toBool <$> c'isWindowReady
isWindowFullscreen :: IO Bool
isWindowFullscreen = toBool <$> c'isWindowFullscreen
isWindowHidden :: IO Bool
isWindowHidden = toBool <$> c'isWindowHidden
isWindowMinimized :: IO Bool
isWindowMinimized = toBool <$> c'isWindowMinimized
isWindowMaximized :: IO Bool
isWindowMaximized = toBool <$> c'isWindowMaximized
isWindowFocused :: IO Bool
isWindowFocused = toBool <$> c'isWindowFocused
isWindowResized :: IO Bool
isWindowResized = toBool <$> c'isWindowResized
isWindowState :: [ConfigFlag] -> IO Bool
isWindowState flags = toBool <$> c'isWindowState (fromIntegral $ configsToBitflag flags)
setWindowState :: [ConfigFlag] -> IO ()
setWindowState = c'setWindowState . fromIntegral . configsToBitflag
clearWindowState :: [ConfigFlag] -> IO ()
clearWindowState = c'clearWindowState . fromIntegral . configsToBitflag
foreign import ccall safe "raylib.h ToggleFullscreen"
toggleFullscreen ::
IO ()
foreign import ccall safe "raylib.h MaximizeWindow"
maximizeWindow ::
IO ()
foreign import ccall safe "raylib.h MinimizeWindow"
minimizeWindow ::
IO ()
foreign import ccall safe "raylib.h RestoreWindow"
restoreWindow ::
IO ()
setWindowIcon :: Image -> IO ()
setWindowIcon image = withFreeable image c'setWindowIcon
setWindowIcons :: [Image] -> IO ()
setWindowIcons images = withFreeableArrayLen images (\l ptr -> c'setWindowIcons ptr (fromIntegral l))
setWindowTitle :: String -> IO ()
setWindowTitle title = withCString title c'setWindowTitle
setWindowPosition :: Int -> Int -> IO ()
setWindowPosition x y = c'setWindowPosition (fromIntegral x) (fromIntegral y)
setWindowMonitor :: Int -> IO ()
setWindowMonitor = c'setWindowMonitor . fromIntegral
setWindowMinSize :: Int -> Int -> IO ()
setWindowMinSize x y = c'setWindowMinSize (fromIntegral x) (fromIntegral y)
setWindowSize :: Int -> Int -> IO ()
setWindowSize x y = c'setWindowSize (fromIntegral x) (fromIntegral y)
setWindowOpacity :: Float -> IO ()
setWindowOpacity opacity = c'setWindowOpacity $ realToFrac opacity
foreign import ccall safe "raylib.h GetWindowHandle"
getWindowHandle ::
IO (Ptr ())
getScreenWidth :: IO Int
getScreenWidth = fromIntegral <$> c'getScreenWidth
getScreenHeight :: IO Int
getScreenHeight = fromIntegral <$> c'getScreenHeight
getRenderWidth :: IO Int
getRenderWidth = fromIntegral <$> c'getRenderWidth
getRenderHeight :: IO Int
getRenderHeight = fromIntegral <$> c'getRenderHeight
getMonitorCount :: IO Int
getMonitorCount = fromIntegral <$> c'getMonitorCount
getCurrentMonitor :: IO Int
getCurrentMonitor = fromIntegral <$> c'getCurrentMonitor
getMonitorPosition :: Int -> IO Vector2
getMonitorPosition monitor = c'getMonitorPosition (fromIntegral monitor) >>= pop
getMonitorWidth :: Int -> IO Int
getMonitorWidth monitor = fromIntegral <$> c'getMonitorWidth (fromIntegral monitor)
getMonitorHeight :: Int -> IO Int
getMonitorHeight monitor = fromIntegral <$> c'getMonitorHeight (fromIntegral monitor)
getMonitorPhysicalWidth :: Int -> IO Int
getMonitorPhysicalWidth monitor = fromIntegral <$> c'getMonitorPhysicalWidth (fromIntegral monitor)
getMonitorPhysicalHeight :: Int -> IO Int
getMonitorPhysicalHeight monitor = fromIntegral <$> c'getMonitorPhysicalHeight (fromIntegral monitor)
getMonitorRefreshRate :: Int -> IO Int
getMonitorRefreshRate monitor = fromIntegral <$> c'getMonitorRefreshRate (fromIntegral monitor)
getWindowPosition :: IO Vector2
getWindowPosition = c'getWindowPosition >>= pop
getWindowScaleDPI :: IO Vector2
getWindowScaleDPI = c'getWindowScaleDPI >>= pop
getMonitorName :: Int -> IO String
getMonitorName monitor = c'getMonitorName (fromIntegral monitor) >>= peekCString
setClipboardText :: String -> IO ()
setClipboardText text = withCString text c'setClipboardText
getClipboardText :: IO String
getClipboardText = c'getClipboardText >>= peekCString
foreign import ccall safe "raylib.h EnableEventWaiting"
enableEventWaiting ::
IO ()
foreign import ccall safe "raylib.h DisableEventWaiting"
disableEventWaiting ::
IO ()
foreign import ccall safe "raylib.h SwapScreenBuffer"
swapScreenBuffer ::
IO ()
foreign import ccall safe "raylib.h PollInputEvents"
pollInputEvents ::
IO ()
waitTime :: Double -> IO ()
waitTime seconds = c'waitTime $ realToFrac seconds
foreign import ccall safe "raylib.h ShowCursor"
showCursor ::
IO ()
foreign import ccall safe "raylib.h HideCursor"
hideCursor ::
IO ()
isCursorHidden :: IO Bool
isCursorHidden = toBool <$> c'isCursorHidden
foreign import ccall safe "raylib.h EnableCursor"
enableCursor ::
IO ()
foreign import ccall safe "raylib.h DisableCursor"
disableCursor ::
IO ()
isCursorOnScreen :: IO Bool
isCursorOnScreen = toBool <$> c'isCursorOnScreen
clearBackground :: Color -> IO ()
clearBackground color = withFreeable color c'clearBackground
foreign import ccall safe "raylib.h BeginDrawing"
beginDrawing ::
IO ()
foreign import ccall safe "raylib.h EndDrawing"
endDrawing ::
IO ()
beginMode2D :: Camera2D -> IO ()
beginMode2D camera = withFreeable camera c'beginMode2D
foreign import ccall safe "raylib.h EndMode2D"
endMode2D ::
IO ()
beginMode3D :: Camera3D -> IO ()
beginMode3D camera = withFreeable camera c'beginMode3D
foreign import ccall safe "raylib.h EndMode3D"
endMode3D ::
IO ()
beginTextureMode :: RenderTexture -> IO ()
beginTextureMode renderTexture = withFreeable renderTexture c'beginTextureMode
foreign import ccall safe "raylib.h EndTextureMode"
endTextureMode ::
IO ()
beginShaderMode :: Shader -> IO ()
beginShaderMode shader = withFreeable shader c'beginShaderMode
foreign import ccall safe "raylib.h EndShaderMode"
endShaderMode ::
IO ()
beginBlendMode :: BlendMode -> IO ()
beginBlendMode = c'beginBlendMode . fromIntegral . fromEnum
foreign import ccall safe "raylib.h EndBlendMode"
endBlendMode ::
IO ()
beginScissorMode :: Int -> Int -> Int -> Int -> IO ()
beginScissorMode x y width height = c'beginScissorMode (fromIntegral x) (fromIntegral y) (fromIntegral width) (fromIntegral height)
foreign import ccall safe "raylib.h EndScissorMode"
endScissorMode ::
IO ()
beginVrStereoMode :: VrStereoConfig -> IO ()
beginVrStereoMode config = withFreeable config c'beginVrStereoMode
foreign import ccall safe "raylib.h EndVrStereoMode"
endVrStereoMode ::
IO ()
loadVrStereoConfig :: VrDeviceInfo -> IO VrStereoConfig
loadVrStereoConfig deviceInfo = withFreeable deviceInfo c'loadVrStereoConfig >>= pop
loadShader :: Maybe String -> Maybe String -> IO Shader
loadShader vsFileName fsFileName = do
shader <- withMaybeCString vsFileName (withMaybeCString fsFileName . c'loadShader) >>= pop
addShaderId $ shader'id shader
return shader
loadShaderFromMemory :: Maybe String -> Maybe String -> IO Shader
loadShaderFromMemory vsCode fsCode = do
shader <- withMaybeCString vsCode (withMaybeCString fsCode . c'loadShaderFromMemory) >>= pop
addShaderId $ shader'id shader
return shader
isShaderReady :: Shader -> IO Bool
isShaderReady shader = toBool <$> withFreeable shader c'isShaderReady
getShaderLocation :: Shader -> String -> IO Int
getShaderLocation shader uniformName = do
let sId = shader'id shader
locs <- readIORef shaderLocations
case Map.lookup sId locs of
Nothing -> do
idx <- locIdx
let newMap = Map.fromList [(uniformName, idx)]
modifyIORef' shaderLocations (Map.insert sId newMap)
return idx
Just m -> case Map.lookup uniformName m of
Nothing -> do
idx <- locIdx
let newMap = Map.insert uniformName idx m
modifyIORef' shaderLocations (Map.insert sId newMap)
return idx
Just val -> return val
where
locIdx = fromIntegral <$> withFreeable shader (withCString uniformName . c'getShaderLocation)
getShaderLocationAttrib :: Shader -> String -> IO Int
getShaderLocationAttrib shader attribName = fromIntegral <$> withFreeable shader (withCString attribName . c'getShaderLocationAttrib)
setShaderValue :: Shader -> String -> ShaderUniformData -> IO ()
setShaderValue shader uniformName value = do
idx <- getShaderLocation shader uniformName
nativeSetShaderValue shader idx value
setShaderValueV :: Shader -> String -> ShaderUniformDataV -> IO ()
setShaderValueV shader uniformName values = do
idx <- getShaderLocation shader uniformName
nativeSetShaderValueV shader idx values
nativeSetShaderValue :: Shader -> Int -> ShaderUniformData -> IO ()
nativeSetShaderValue shader locIndex value = do
(uniformType, ptr) <- unpackShaderUniformData value
withFreeable shader (\s -> c'setShaderValue s (fromIntegral locIndex) ptr (fromIntegral $ fromEnum uniformType))
c'free $ castPtr ptr
nativeSetShaderValueV :: Shader -> Int -> ShaderUniformDataV -> IO ()
nativeSetShaderValueV shader locIndex values = do
(uniformType, ptr, l) <- unpackShaderUniformDataV values
withFreeable shader (\s -> c'setShaderValueV s (fromIntegral locIndex) ptr (fromIntegral $ fromEnum uniformType) (fromIntegral l))
c'free $ castPtr ptr
setShaderValueMatrix :: Shader -> Int -> Matrix -> IO ()
setShaderValueMatrix shader locIndex mat = withFreeable shader (\s -> withFreeable mat (c'setShaderValueMatrix s (fromIntegral locIndex)))
setShaderValueTexture :: Shader -> Int -> Texture -> IO ()
setShaderValueTexture shader locIndex tex = withFreeable shader (\s -> withFreeable tex (c'setShaderValueTexture s (fromIntegral locIndex)))
them in VRAM for too long .
unloadShader :: Shader -> IO ()
unloadShader shader = unloadSingleShader (shader'id shader)
getMouseRay :: Vector2 -> Camera3D -> IO Ray
getMouseRay mousePosition camera = withFreeable mousePosition (withFreeable camera . c'getMouseRay) >>= pop
getCameraMatrix :: Camera3D -> IO Matrix
getCameraMatrix camera = withFreeable camera c'getCameraMatrix >>= pop
getCameraMatrix2D :: Camera2D -> IO Matrix
getCameraMatrix2D camera = withFreeable camera c'getCameraMatrix2D >>= pop
getWorldToScreen :: Vector3 -> Camera3D -> IO Vector2
getWorldToScreen position camera = withFreeable position (withFreeable camera . c'getWorldToScreen) >>= pop
getScreenToWorld2D :: Vector2 -> Camera2D -> IO Vector2
getScreenToWorld2D position camera = withFreeable position (withFreeable camera . c'getScreenToWorld2D) >>= pop
getWorldToScreenEx :: Vector3 -> Camera3D -> Int -> Int -> IO Vector2
getWorldToScreenEx position camera width height = withFreeable position (\p -> withFreeable camera (\c -> c'getWorldToScreenEx p c (fromIntegral width) (fromIntegral height))) >>= pop
getWorldToScreen2D :: Vector2 -> Camera2D -> IO Vector2
getWorldToScreen2D position camera = withFreeable position (withFreeable camera . c'getWorldToScreen2D) >>= pop
setTargetFPS :: Int -> IO ()
setTargetFPS fps = c'setTargetFPS $ fromIntegral fps
getFPS :: IO Int
getFPS = fromIntegral <$> c'getFPS
getFrameTime :: IO Float
getFrameTime = realToFrac <$> c'getFrameTime
getTime :: IO Double
getTime = realToFrac <$> c'getTime
getRandomValue :: Int -> Int -> IO Int
getRandomValue minVal maxVal = fromIntegral <$> c'getRandomValue (fromIntegral minVal) (fromIntegral maxVal)
setRandomSeed :: Integer -> IO ()
setRandomSeed seed = c'setRandomSeed $ fromIntegral seed
takeScreenshot :: String -> IO ()
takeScreenshot fileName = withCString fileName c'takeScreenshot
setConfigFlags :: [ConfigFlag] -> IO ()
setConfigFlags flags = c'setConfigFlags $ fromIntegral $ configsToBitflag flags
traceLog :: TraceLogLevel -> String -> IO ()
traceLog logLevel text = withCString text $ c'traceLog $ fromIntegral $ fromEnum logLevel
setTraceLogLevel :: TraceLogLevel -> IO ()
setTraceLogLevel = c'setTraceLogLevel . fromIntegral . fromEnum
openURL :: String -> IO ()
openURL url = withCString url c'openURL
foreign import ccall safe "raylib.h SetLoadFileDataCallback"
setLoadFileDataCallback ::
LoadFileDataCallback -> IO ()
foreign import ccall safe "raylib.h SetSaveFileDataCallback"
setSaveFileDataCallback ::
SaveFileDataCallback -> IO ()
foreign import ccall safe "raylib.h SetLoadFileTextCallback"
setLoadFileTextCallback ::
LoadFileTextCallback -> IO ()
foreign import ccall safe "raylib.h SetSaveFileTextCallback"
setSaveFileTextCallback ::
SaveFileTextCallback -> IO ()
loadFileData :: String -> IO [Integer]
loadFileData fileName =
withFreeable
0
( \size -> do
withCString
fileName
( \path -> do
ptr <- c'loadFileData path size
arrSize <- fromIntegral <$> peek size
map fromIntegral <$> popCArray arrSize ptr
)
)
saveFileData :: (Storable a) => String -> Ptr a -> Integer -> IO Bool
saveFileData fileName contents bytesToWrite =
toBool <$> withCString fileName (\s -> c'saveFileData s (castPtr contents) (fromIntegral bytesToWrite))
exportDataAsCode :: [Integer] -> Integer -> String -> IO Bool
exportDataAsCode contents size fileName =
toBool <$> withFreeableArray (map fromInteger contents) (\c -> withCString fileName (c'exportDataAsCode c (fromIntegral size)))
loadFileText :: String -> IO String
loadFileText fileName = withCString fileName c'loadFileText >>= popCString
saveFileText :: String -> String -> IO Bool
saveFileText fileName text = toBool <$> withCString fileName (withCString text . c'saveFileText)
fileExists :: String -> IO Bool
fileExists fileName = toBool <$> withCString fileName c'fileExists
directoryExists :: String -> IO Bool
directoryExists dirPath = toBool <$> withCString dirPath c'directoryExists
isFileExtension :: String -> String -> IO Bool
isFileExtension fileName ext = toBool <$> withCString fileName (withCString ext . c'isFileExtension)
getFileLength :: String -> IO Bool
getFileLength fileName = toBool <$> withCString fileName c'getFileLength
getFileExtension :: String -> IO String
getFileExtension fileName = withCString fileName c'getFileExtension >>= peekCString
getFileName :: String -> IO String
getFileName filePath = withCString filePath c'getFileName >>= peekCString
getFileNameWithoutExt :: String -> IO String
getFileNameWithoutExt fileName = withCString fileName c'getFileNameWithoutExt >>= peekCString
getDirectoryPath :: String -> IO String
getDirectoryPath filePath = withCString filePath c'getDirectoryPath >>= peekCString
getPrevDirectoryPath :: String -> IO String
getPrevDirectoryPath dirPath = withCString dirPath c'getPrevDirectoryPath >>= peekCString
getWorkingDirectory :: IO String
getWorkingDirectory = c'getWorkingDirectory >>= peekCString
getApplicationDirectory :: IO String
getApplicationDirectory = c'getApplicationDirectory >>= peekCString
changeDirectory :: String -> IO Bool
changeDirectory dir = toBool <$> withCString dir c'changeDirectory
isPathFile :: String -> IO Bool
isPathFile path = toBool <$> withCString path c'isPathFile
loadDirectoryFiles :: String -> IO FilePathList
loadDirectoryFiles dirPath = withCString dirPath c'loadDirectoryFiles >>= pop
loadDirectoryFilesEx :: String -> String -> Bool -> IO FilePathList
loadDirectoryFilesEx basePath filterStr scanSubdirs =
withCString basePath (\b -> withCString filterStr (\f -> c'loadDirectoryFilesEx b f (fromBool scanSubdirs))) >>= pop
isFileDropped :: IO Bool
isFileDropped = toBool <$> c'isFileDropped
loadDroppedFiles :: IO FilePathList
loadDroppedFiles = c'loadDroppedFiles >>= pop
getFileModTime :: String -> IO Integer
getFileModTime fileName = fromIntegral <$> withCString fileName c'getFileModTime
compressData :: [Integer] -> IO [Integer]
compressData contents = do
withFreeableArrayLen
(map fromIntegral contents)
( \size c -> do
withFreeable
0
( \ptr -> do
compressed <- c'compressData c (fromIntegral $ size * sizeOf (0 :: CUChar)) ptr
compressedSize <- fromIntegral <$> peek ptr
arr <- peekArray compressedSize compressed
return $ map fromIntegral arr
)
)
decompressData :: [Integer] -> IO [Integer]
decompressData compressedData = do
withFreeableArrayLen
(map fromIntegral compressedData)
( \size c -> do
withFreeable
0
( \ptr -> do
decompressed <- c'decompressData c (fromIntegral $ size * sizeOf (0 :: CUChar)) ptr
decompressedSize <- fromIntegral <$> peek ptr
arr <- peekArray decompressedSize decompressed
return $ map fromIntegral arr
)
)
encodeDataBase64 :: [Integer] -> IO [Integer]
encodeDataBase64 contents = do
withFreeableArrayLen
(map fromIntegral contents)
( \size c -> do
withFreeable
0
( \ptr -> do
encoded <- c'encodeDataBase64 c (fromIntegral $ size * sizeOf (0 :: CUChar)) ptr
encodedSize <- fromIntegral <$> peek ptr
arr <- peekArray encodedSize encoded
return $ map fromIntegral arr
)
)
decodeDataBase64 :: [Integer] -> IO [Integer]
decodeDataBase64 encodedData = do
withFreeableArray
(map fromIntegral encodedData)
( \c -> do
withFreeable
0
( \ptr -> do
decoded <- c'decodeDataBase64 c ptr
decodedSize <- fromIntegral <$> peek ptr
arr <- peekArray decodedSize decoded
return $ map fromIntegral arr
)
)
isKeyPressed :: KeyboardKey -> IO Bool
isKeyPressed key = toBool <$> c'isKeyPressed (fromIntegral $ fromEnum key)
isKeyDown :: KeyboardKey -> IO Bool
isKeyDown key = toBool <$> c'isKeyDown (fromIntegral $ fromEnum key)
isKeyReleased :: KeyboardKey -> IO Bool
isKeyReleased key = toBool <$> c'isKeyReleased (fromIntegral $ fromEnum key)
isKeyUp :: KeyboardKey -> IO Bool
isKeyUp key = toBool <$> c'isKeyUp (fromIntegral $ fromEnum key)
setExitKey :: KeyboardKey -> IO ()
setExitKey = c'setExitKey . fromIntegral . fromEnum
getKeyPressed :: IO KeyboardKey
getKeyPressed = toEnum . fromIntegral <$> c'getKeyPressed
getCharPressed :: IO Int
getCharPressed = fromIntegral <$> c'getCharPressed
isGamepadAvailable :: Int -> IO Bool
isGamepadAvailable gamepad = toBool <$> c'isGamepadAvailable (fromIntegral gamepad)
getGamepadName :: Int -> IO String
getGamepadName gamepad = c'getGamepadName (fromIntegral gamepad) >>= peekCString
isGamepadButtonPressed :: Int -> GamepadButton -> IO Bool
isGamepadButtonPressed gamepad button = toBool <$> c'isGamepadButtonPressed (fromIntegral gamepad) (fromIntegral $ fromEnum button)
isGamepadButtonDown :: Int -> GamepadButton -> IO Bool
isGamepadButtonDown gamepad button = toBool <$> c'isGamepadButtonDown (fromIntegral gamepad) (fromIntegral $ fromEnum button)
isGamepadButtonReleased :: Int -> GamepadButton -> IO Bool
isGamepadButtonReleased gamepad button = toBool <$> c'isGamepadButtonReleased (fromIntegral gamepad) (fromIntegral $ fromEnum button)
isGamepadButtonUp :: Int -> GamepadButton -> IO Bool
isGamepadButtonUp gamepad button = toBool <$> c'isGamepadButtonUp (fromIntegral gamepad) (fromIntegral $ fromEnum button)
getGamepadButtonPressed :: IO GamepadButton
getGamepadButtonPressed = toEnum . fromIntegral <$> c'getGamepadButtonPressed
getGamepadAxisCount :: Int -> IO Int
getGamepadAxisCount gamepad = fromIntegral <$> c'getGamepadAxisCount (fromIntegral gamepad)
getGamepadAxisMovement :: Int -> GamepadAxis -> IO Float
getGamepadAxisMovement gamepad axis = realToFrac <$> c'getGamepadAxisMovement (fromIntegral gamepad) (fromIntegral $ fromEnum axis)
setGamepadMappings :: String -> IO Int
setGamepadMappings mappings = fromIntegral <$> withCString mappings c'setGamepadMappings
isMouseButtonPressed :: MouseButton -> IO Bool
isMouseButtonPressed button = toBool <$> c'isMouseButtonPressed (fromIntegral $ fromEnum button)
isMouseButtonDown :: MouseButton -> IO Bool
isMouseButtonDown button = toBool <$> c'isMouseButtonDown (fromIntegral $ fromEnum button)
isMouseButtonReleased :: MouseButton -> IO Bool
isMouseButtonReleased button = toBool <$> c'isMouseButtonReleased (fromIntegral $ fromEnum button)
isMouseButtonUp :: MouseButton -> IO Bool
isMouseButtonUp button = toBool <$> c'isMouseButtonUp (fromIntegral $ fromEnum button)
getMouseX :: IO Int
getMouseX = fromIntegral <$> c'getMouseX
getMouseY :: IO Int
getMouseY = fromIntegral <$> c'getMouseY
getMousePosition :: IO Vector2
getMousePosition = c'getMousePosition >>= pop
getMouseDelta :: IO Vector2
getMouseDelta = c'getMouseDelta >>= pop
setMousePosition :: Int -> Int -> IO ()
setMousePosition x y = c'setMousePosition (fromIntegral x) (fromIntegral y)
setMouseOffset :: Int -> Int -> IO ()
setMouseOffset x y = c'setMouseOffset (fromIntegral x) (fromIntegral y)
setMouseScale :: Float -> Float -> IO ()
setMouseScale x y = c'setMouseScale (realToFrac x) (realToFrac y)
getMouseWheelMove :: IO Float
getMouseWheelMove = realToFrac <$> c'getMouseWheelMove
getMouseWheelMoveV :: IO Vector2
getMouseWheelMoveV = c'getMouseWheelMoveV >>= pop
setMouseCursor :: MouseCursor -> IO ()
setMouseCursor cursor = c'setMouseCursor . fromIntegral $ fromEnum cursor
getTouchX :: IO Int
getTouchX = fromIntegral <$> c'getTouchX
getTouchY :: IO Int
getTouchY = fromIntegral <$> c'getTouchY
getTouchPosition :: Int -> IO Vector2
getTouchPosition index = c'getTouchPosition (fromIntegral index) >>= pop
getTouchPointId :: Int -> IO Int
getTouchPointId index = fromIntegral <$> c'getTouchPointId (fromIntegral index)
getTouchPointCount :: IO Int
getTouchPointCount = fromIntegral <$> c'getTouchPointCount
setGesturesEnabled :: [Gesture] -> IO ()
setGesturesEnabled flags = c'setGesturesEnabled (fromIntegral $ configsToBitflag flags)
isGestureDetected :: Gesture -> IO Bool
isGestureDetected gesture = toBool <$> c'isGestureDetected (fromIntegral $ fromEnum gesture)
getGestureDetected :: IO Gesture
getGestureDetected = toEnum . fromIntegral <$> c'getGestureDetected
getGestureHoldDuration :: IO Float
getGestureHoldDuration = realToFrac <$> c'getGestureHoldDuration
getGestureDragVector :: IO Vector2
getGestureDragVector = c'getGestureDragVector >>= pop
getGestureDragAngle :: IO Float
getGestureDragAngle = realToFrac <$> c'getGestureDragAngle
getGesturePinchVector :: IO Vector2
getGesturePinchVector = c'getGesturePinchVector >>= pop
getGesturePinchAngle :: IO Float
getGesturePinchAngle = realToFrac <$> c'getGesturePinchAngle
updateCamera :: Camera3D -> CameraMode -> IO Camera3D
updateCamera camera mode =
withFreeable
camera
( \c -> do
c'updateCamera c (fromIntegral $ fromEnum mode)
peek c
)
|
7b8d1a9154a7cd6370b1b53488d38094feaf72984b366980a8f18db6aec191db | xvw/preface | freer_selective_ping_pong.ml | type 'a f =
| Read : string f
| Write : string -> unit f
type 'a io =
| IORead : string io
| IOWrite : string -> unit io
module IO = struct
include Preface.Make.Freer_monad.Over (struct
type 'a t = 'a io
end)
let get_line = perform IORead
let put_line s = perform (IOWrite s)
module Selective =
Preface.Make.Selective.Over_applicative_via_select
(Applicative)
(Preface.Make.Selective.Select_from_monad (Monad))
end
module Freer = struct
include Preface.Make.Freer_selective.Over (struct
type nonrec 'a t = 'a f
end)
let get_line = promote Read
let put_line s = promote (Write s)
end
module Run = Freer.To_selective (IO.Selective)
let ping_pong =
let open Freer in
when_ ((map (String.equal "ping")) get_line) (put_line "pong")
;;
let free_to_io p =
let nt =
let open Run in
let transform : type a. a f -> a IO.t = function
| Read -> IO.get_line
| Write s -> IO.put_line s
in
{ transform }
in
Run.run nt p
;;
let test_when_read_returns_ping () =
let state = ref [] in
let _ =
IO.run
{
handler =
(fun resume effect ->
let f : type b. (b -> 'a) -> b io -> 'a =
fun resume -> function
| IOWrite s ->
let () = state := !state @ [ "Write " ^ s ] in
resume ()
| IORead ->
let () = state := !state @ [ "Read" ] in
resume "ping"
in
f resume effect )
}
(free_to_io ping_pong)
in
Alcotest.(check (list string))
"The handler should recording pong" [ "Read"; "Write pong" ] !state
;;
let test_when_read_returns_something_else () =
let state = ref [] in
let _ =
IO.run
{
handler =
(fun resume effect ->
let f : type b. (b -> 'a) -> b io -> 'a =
fun resume -> function
| IOWrite s ->
let () = state := !state @ [ "Write " ^ s ] in
resume ()
| IORead ->
let () = state := !state @ [ "Read" ] in
resume "not_ping"
in
f resume effect )
}
(free_to_io ping_pong)
in
Alcotest.(check (list string))
"The handler should recording pong" [ "Read" ] !state
;;
let cases =
let open Alcotest in
[
( "Freer Selective Ping Pong"
, [
test_case "test reading ping, writing pong" `Quick
test_when_read_returns_ping
; test_case "test reading not_ping, writing nothing" `Quick
test_when_read_returns_something_else
] )
]
;;
| null | https://raw.githubusercontent.com/xvw/preface/89af07e80f2e7458a1381ec22aa85036b68e6e8a/test/preface_examples_test/freer_selective_ping_pong.ml | ocaml | type 'a f =
| Read : string f
| Write : string -> unit f
type 'a io =
| IORead : string io
| IOWrite : string -> unit io
module IO = struct
include Preface.Make.Freer_monad.Over (struct
type 'a t = 'a io
end)
let get_line = perform IORead
let put_line s = perform (IOWrite s)
module Selective =
Preface.Make.Selective.Over_applicative_via_select
(Applicative)
(Preface.Make.Selective.Select_from_monad (Monad))
end
module Freer = struct
include Preface.Make.Freer_selective.Over (struct
type nonrec 'a t = 'a f
end)
let get_line = promote Read
let put_line s = promote (Write s)
end
module Run = Freer.To_selective (IO.Selective)
let ping_pong =
let open Freer in
when_ ((map (String.equal "ping")) get_line) (put_line "pong")
;;
let free_to_io p =
let nt =
let open Run in
let transform : type a. a f -> a IO.t = function
| Read -> IO.get_line
| Write s -> IO.put_line s
in
{ transform }
in
Run.run nt p
;;
let test_when_read_returns_ping () =
let state = ref [] in
let _ =
IO.run
{
handler =
(fun resume effect ->
let f : type b. (b -> 'a) -> b io -> 'a =
fun resume -> function
| IOWrite s ->
let () = state := !state @ [ "Write " ^ s ] in
resume ()
| IORead ->
let () = state := !state @ [ "Read" ] in
resume "ping"
in
f resume effect )
}
(free_to_io ping_pong)
in
Alcotest.(check (list string))
"The handler should recording pong" [ "Read"; "Write pong" ] !state
;;
let test_when_read_returns_something_else () =
let state = ref [] in
let _ =
IO.run
{
handler =
(fun resume effect ->
let f : type b. (b -> 'a) -> b io -> 'a =
fun resume -> function
| IOWrite s ->
let () = state := !state @ [ "Write " ^ s ] in
resume ()
| IORead ->
let () = state := !state @ [ "Read" ] in
resume "not_ping"
in
f resume effect )
}
(free_to_io ping_pong)
in
Alcotest.(check (list string))
"The handler should recording pong" [ "Read" ] !state
;;
let cases =
let open Alcotest in
[
( "Freer Selective Ping Pong"
, [
test_case "test reading ping, writing pong" `Quick
test_when_read_returns_ping
; test_case "test reading not_ping, writing nothing" `Quick
test_when_read_returns_something_else
] )
]
;;
|
|
327b07d6953bf3ae8b6d4afb7d8dbeaaf51e8a6f830ebe65cc67f962bc8d45a3 | LaurentMazare/ocaml-torch | gan_stability.ml | GAN stability
adapted from /
adapted from /
*)
open Base
open Torch
let img_size = 128
let latent_dim = 128
let batch_size = 16
let learning_rate = 1e-4
let reg_param = 10.
let nf = 32
let batches = 10 ** 8
let leaky_relu xs = Tensor.(max xs (xs * f 0.2))
let conv2d = Layer.conv2d_ ~stride:1
let upsample xs =
let _, _, x, y = Tensor.shape4_exn xs in
Tensor.upsample_nearest2d
xs
~output_size:[ 2 * x; 2 * y ]
~scales_h:(Some 2.0)
~scales_w:(Some 2.0)
let avg_pool2d = Tensor.avg_pool2d ~ksize:(3, 3) ~stride:(2, 2) ~padding:(1, 1)
(* Use the resnet2 model similar to:
*)
let resnet_block vs ~input_dim output_dim =
let hidden_dim = Int.min input_dim output_dim in
let c0 = conv2d vs ~ksize:3 ~padding:1 ~input_dim hidden_dim in
let c1 = conv2d vs ~ksize:3 ~padding:1 ~input_dim:hidden_dim output_dim in
let shortcut =
if input_dim = output_dim
then Layer.id
else conv2d vs ~ksize:1 ~padding:0 ~use_bias:false ~input_dim output_dim
in
Layer.of_fn (fun xs ->
leaky_relu xs
|> Layer.forward c0
|> leaky_relu
|> Layer.forward c1
|> fun ys -> Tensor.(Layer.forward shortcut xs + (ys * f 0.1)))
let create_generator vs =
let s0 = img_size / 32 in
let fc = Layer.linear vs ~input_dim:latent_dim (16 * nf * s0 * s0) in
let rn00 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn01 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn10 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn11 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn20 = resnet_block vs ~input_dim:(16 * nf) (8 * nf) in
let rn21 = resnet_block vs ~input_dim:(8 * nf) (8 * nf) in
let rn30 = resnet_block vs ~input_dim:(8 * nf) (4 * nf) in
let rn31 = resnet_block vs ~input_dim:(4 * nf) (4 * nf) in
let rn40 = resnet_block vs ~input_dim:(4 * nf) (2 * nf) in
let rn41 = resnet_block vs ~input_dim:(2 * nf) (2 * nf) in
let rn50 = resnet_block vs ~input_dim:(2 * nf) (1 * nf) in
let rn51 = resnet_block vs ~input_dim:(1 * nf) (1 * nf) in
let conv = conv2d vs ~ksize:3 ~padding:1 ~input_dim:nf 3 in
fun rand_input ->
Tensor.to_device rand_input ~device:(Var_store.device vs)
|> Layer.forward fc
|> Tensor.view ~size:[ batch_size; 16 * nf; s0; s0 ]
|> Layer.forward rn00
|> Layer.forward rn01
|> upsample
|> Layer.forward rn10
|> Layer.forward rn11
|> upsample
|> Layer.forward rn20
|> Layer.forward rn21
|> upsample
|> Layer.forward rn30
|> Layer.forward rn31
|> upsample
|> Layer.forward rn40
|> Layer.forward rn41
|> upsample
|> Layer.forward rn50
|> Layer.forward rn51
|> leaky_relu
|> Layer.forward conv
|> Tensor.tanh
let create_discriminator vs =
let s0 = img_size / 32 in
let conv = conv2d vs ~ksize:3 ~padding:1 ~input_dim:3 nf in
let rn00 = resnet_block vs ~input_dim:(1 * nf) (1 * nf) in
let rn01 = resnet_block vs ~input_dim:(1 * nf) (2 * nf) in
let rn10 = resnet_block vs ~input_dim:(2 * nf) (2 * nf) in
let rn11 = resnet_block vs ~input_dim:(2 * nf) (4 * nf) in
let rn20 = resnet_block vs ~input_dim:(4 * nf) (4 * nf) in
let rn21 = resnet_block vs ~input_dim:(4 * nf) (8 * nf) in
let rn30 = resnet_block vs ~input_dim:(8 * nf) (8 * nf) in
let rn31 = resnet_block vs ~input_dim:(8 * nf) (16 * nf) in
let rn40 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn41 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn50 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn51 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let fc = Layer.linear vs ~input_dim:(16 * nf * s0 * s0) 1 in
fun xs ->
Tensor.to_device xs ~device:(Var_store.device vs)
|> Layer.forward conv
|> Layer.forward rn00
|> Layer.forward rn01
|> avg_pool2d
|> Layer.forward rn10
|> Layer.forward rn11
|> avg_pool2d
|> Layer.forward rn20
|> Layer.forward rn21
|> avg_pool2d
|> Layer.forward rn30
|> Layer.forward rn31
|> avg_pool2d
|> Layer.forward rn40
|> Layer.forward rn41
|> avg_pool2d
|> Layer.forward rn50
|> Layer.forward rn51
|> Tensor.view ~size:[ batch_size; 16 * nf * s0 * s0 ]
|> leaky_relu
|> Layer.forward fc
let z_dist () = Tensor.randn [ batch_size; latent_dim ]
let write_samples samples ~filename =
List.init 4 ~f:(fun i ->
List.init 4 ~f:(fun j ->
Tensor.narrow samples ~dim:0 ~start:((4 * i) + j) ~length:1)
|> Tensor.cat ~dim:2)
|> Tensor.cat ~dim:3
|> Torch_vision.Image.write_image ~filename
let grad2 d_out x_in =
let grad_dout =
Tensor.run_backward [ Tensor.sum d_out ] [ x_in ] ~create_graph:true ~keep_graph:true
|> List.hd_exn
in
Tensor.(grad_dout * grad_dout)
|> Tensor.view ~size:[ batch_size; -1 ]
|> Tensor.sum_dim_intlist ~dim:(Some [ 1 ]) ~keepdim:false ~dtype:(T Float)
let () =
let module Sys = Caml.Sys in
let device = Device.cuda_if_available () in
if Array.length Sys.argv < 2 then Printf.failwithf "Usage: %s images.ot" Sys.argv.(0) ();
let bce_loss_with_logits ys ~target =
Tensor.bce_loss (Tensor.sigmoid ys) ~targets:Tensor.(ones_like ys * f target)
in
let images = Serialize.load ~filename:Sys.argv.(1) in
let train_size = Tensor.shape images |> List.hd_exn in
let generator_vs = Var_store.create ~name:"gen" ~device () in
let generator = create_generator generator_vs in
let opt_g = Optimizer.adam generator_vs ~learning_rate in
let discriminator_vs = Var_store.create ~name:"disc" ~device () in
let discriminator = create_discriminator discriminator_vs in
let opt_d = Optimizer.adam discriminator_vs ~learning_rate in
let z_test = z_dist () in
Checkpointing.loop
~start_index:1
~end_index:batches
~var_stores:[ generator_vs; discriminator_vs ]
~checkpoint_base:"gan-stability.ot"
~checkpoint_every:(`seconds 600.)
(fun ~index:batch_idx ->
let x_real =
let index =
Tensor.randint ~high:train_size ~size:[ batch_size ] ~options:(T Int64, Cpu)
in
Tensor.index_select images ~dim:0 ~index
|> Tensor.to_type ~type_:(T Float)
|> fun xs -> Tensor.((xs / f 127.5) - f 1.)
in
let discriminator_loss =
Var_store.freeze generator_vs;
Var_store.unfreeze discriminator_vs;
Optimizer.zero_grad opt_d;
let x_real = Tensor.set_requires_grad x_real ~r:true in
let d_real = discriminator x_real in
let d_loss_real = bce_loss_with_logits d_real ~target:1. in
Tensor.backward d_loss_real ~keep_graph:true;
let reg = Tensor.(f reg_param * grad2 d_real x_real |> mean) in
Tensor.backward reg;
let x_fake = Tensor.no_grad (fun () -> z_dist () |> generator) in
let x_fake = Tensor.set_requires_grad x_fake ~r:true in
let d_fake = discriminator x_fake in
let d_loss_fake = bce_loss_with_logits d_fake ~target:0. in
Tensor.backward d_loss_fake;
Optimizer.step opt_d;
Tensor.( + ) d_loss_real d_loss_fake
in
let generator_loss =
Var_store.unfreeze generator_vs;
Var_store.freeze discriminator_vs;
Optimizer.zero_grad opt_g;
let z = z_dist () in
let x_fake = generator z in
let d_fake = discriminator x_fake in
let g_loss = bce_loss_with_logits d_fake ~target:1. in
Tensor.backward g_loss;
Optimizer.step opt_g;
g_loss
in
if batch_idx % 100 = 0
then
Stdio.printf
"batch %4d d-loss: %12.6f g-loss: %12.6f\n%!"
batch_idx
(Tensor.float_value discriminator_loss)
(Tensor.float_value generator_loss);
Caml.Gc.full_major ();
if batch_idx % 25000 = 0 || (batch_idx < 100000 && batch_idx % 5000 = 0)
then
Tensor.no_grad (fun () -> generator z_test)
|> Tensor.view ~size:[ batch_size; 3; img_size; img_size ]
|> Tensor.to_device ~device:Cpu
|> fun xs ->
Tensor.((xs + f 1.) * f 127.5)
|> Tensor.clamp ~min:(Scalar.float 0.) ~max:(Scalar.float 255.)
|> Tensor.to_type ~type_:(T Uint8)
|> write_samples ~filename:(Printf.sprintf "out%d.png" batch_idx))
| null | https://raw.githubusercontent.com/LaurentMazare/ocaml-torch/76fbfb80c588b274f383684ba59977a139201aca/examples/gan/gan_stability.ml | ocaml | Use the resnet2 model similar to:
| GAN stability
adapted from /
adapted from /
*)
open Base
open Torch
let img_size = 128
let latent_dim = 128
let batch_size = 16
let learning_rate = 1e-4
let reg_param = 10.
let nf = 32
let batches = 10 ** 8
let leaky_relu xs = Tensor.(max xs (xs * f 0.2))
let conv2d = Layer.conv2d_ ~stride:1
let upsample xs =
let _, _, x, y = Tensor.shape4_exn xs in
Tensor.upsample_nearest2d
xs
~output_size:[ 2 * x; 2 * y ]
~scales_h:(Some 2.0)
~scales_w:(Some 2.0)
let avg_pool2d = Tensor.avg_pool2d ~ksize:(3, 3) ~stride:(2, 2) ~padding:(1, 1)
let resnet_block vs ~input_dim output_dim =
let hidden_dim = Int.min input_dim output_dim in
let c0 = conv2d vs ~ksize:3 ~padding:1 ~input_dim hidden_dim in
let c1 = conv2d vs ~ksize:3 ~padding:1 ~input_dim:hidden_dim output_dim in
let shortcut =
if input_dim = output_dim
then Layer.id
else conv2d vs ~ksize:1 ~padding:0 ~use_bias:false ~input_dim output_dim
in
Layer.of_fn (fun xs ->
leaky_relu xs
|> Layer.forward c0
|> leaky_relu
|> Layer.forward c1
|> fun ys -> Tensor.(Layer.forward shortcut xs + (ys * f 0.1)))
let create_generator vs =
let s0 = img_size / 32 in
let fc = Layer.linear vs ~input_dim:latent_dim (16 * nf * s0 * s0) in
let rn00 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn01 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn10 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn11 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn20 = resnet_block vs ~input_dim:(16 * nf) (8 * nf) in
let rn21 = resnet_block vs ~input_dim:(8 * nf) (8 * nf) in
let rn30 = resnet_block vs ~input_dim:(8 * nf) (4 * nf) in
let rn31 = resnet_block vs ~input_dim:(4 * nf) (4 * nf) in
let rn40 = resnet_block vs ~input_dim:(4 * nf) (2 * nf) in
let rn41 = resnet_block vs ~input_dim:(2 * nf) (2 * nf) in
let rn50 = resnet_block vs ~input_dim:(2 * nf) (1 * nf) in
let rn51 = resnet_block vs ~input_dim:(1 * nf) (1 * nf) in
let conv = conv2d vs ~ksize:3 ~padding:1 ~input_dim:nf 3 in
fun rand_input ->
Tensor.to_device rand_input ~device:(Var_store.device vs)
|> Layer.forward fc
|> Tensor.view ~size:[ batch_size; 16 * nf; s0; s0 ]
|> Layer.forward rn00
|> Layer.forward rn01
|> upsample
|> Layer.forward rn10
|> Layer.forward rn11
|> upsample
|> Layer.forward rn20
|> Layer.forward rn21
|> upsample
|> Layer.forward rn30
|> Layer.forward rn31
|> upsample
|> Layer.forward rn40
|> Layer.forward rn41
|> upsample
|> Layer.forward rn50
|> Layer.forward rn51
|> leaky_relu
|> Layer.forward conv
|> Tensor.tanh
let create_discriminator vs =
let s0 = img_size / 32 in
let conv = conv2d vs ~ksize:3 ~padding:1 ~input_dim:3 nf in
let rn00 = resnet_block vs ~input_dim:(1 * nf) (1 * nf) in
let rn01 = resnet_block vs ~input_dim:(1 * nf) (2 * nf) in
let rn10 = resnet_block vs ~input_dim:(2 * nf) (2 * nf) in
let rn11 = resnet_block vs ~input_dim:(2 * nf) (4 * nf) in
let rn20 = resnet_block vs ~input_dim:(4 * nf) (4 * nf) in
let rn21 = resnet_block vs ~input_dim:(4 * nf) (8 * nf) in
let rn30 = resnet_block vs ~input_dim:(8 * nf) (8 * nf) in
let rn31 = resnet_block vs ~input_dim:(8 * nf) (16 * nf) in
let rn40 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn41 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn50 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let rn51 = resnet_block vs ~input_dim:(16 * nf) (16 * nf) in
let fc = Layer.linear vs ~input_dim:(16 * nf * s0 * s0) 1 in
fun xs ->
Tensor.to_device xs ~device:(Var_store.device vs)
|> Layer.forward conv
|> Layer.forward rn00
|> Layer.forward rn01
|> avg_pool2d
|> Layer.forward rn10
|> Layer.forward rn11
|> avg_pool2d
|> Layer.forward rn20
|> Layer.forward rn21
|> avg_pool2d
|> Layer.forward rn30
|> Layer.forward rn31
|> avg_pool2d
|> Layer.forward rn40
|> Layer.forward rn41
|> avg_pool2d
|> Layer.forward rn50
|> Layer.forward rn51
|> Tensor.view ~size:[ batch_size; 16 * nf * s0 * s0 ]
|> leaky_relu
|> Layer.forward fc
let z_dist () = Tensor.randn [ batch_size; latent_dim ]
let write_samples samples ~filename =
List.init 4 ~f:(fun i ->
List.init 4 ~f:(fun j ->
Tensor.narrow samples ~dim:0 ~start:((4 * i) + j) ~length:1)
|> Tensor.cat ~dim:2)
|> Tensor.cat ~dim:3
|> Torch_vision.Image.write_image ~filename
let grad2 d_out x_in =
let grad_dout =
Tensor.run_backward [ Tensor.sum d_out ] [ x_in ] ~create_graph:true ~keep_graph:true
|> List.hd_exn
in
Tensor.(grad_dout * grad_dout)
|> Tensor.view ~size:[ batch_size; -1 ]
|> Tensor.sum_dim_intlist ~dim:(Some [ 1 ]) ~keepdim:false ~dtype:(T Float)
let () =
let module Sys = Caml.Sys in
let device = Device.cuda_if_available () in
if Array.length Sys.argv < 2 then Printf.failwithf "Usage: %s images.ot" Sys.argv.(0) ();
let bce_loss_with_logits ys ~target =
Tensor.bce_loss (Tensor.sigmoid ys) ~targets:Tensor.(ones_like ys * f target)
in
let images = Serialize.load ~filename:Sys.argv.(1) in
let train_size = Tensor.shape images |> List.hd_exn in
let generator_vs = Var_store.create ~name:"gen" ~device () in
let generator = create_generator generator_vs in
let opt_g = Optimizer.adam generator_vs ~learning_rate in
let discriminator_vs = Var_store.create ~name:"disc" ~device () in
let discriminator = create_discriminator discriminator_vs in
let opt_d = Optimizer.adam discriminator_vs ~learning_rate in
let z_test = z_dist () in
Checkpointing.loop
~start_index:1
~end_index:batches
~var_stores:[ generator_vs; discriminator_vs ]
~checkpoint_base:"gan-stability.ot"
~checkpoint_every:(`seconds 600.)
(fun ~index:batch_idx ->
let x_real =
let index =
Tensor.randint ~high:train_size ~size:[ batch_size ] ~options:(T Int64, Cpu)
in
Tensor.index_select images ~dim:0 ~index
|> Tensor.to_type ~type_:(T Float)
|> fun xs -> Tensor.((xs / f 127.5) - f 1.)
in
let discriminator_loss =
Var_store.freeze generator_vs;
Var_store.unfreeze discriminator_vs;
Optimizer.zero_grad opt_d;
let x_real = Tensor.set_requires_grad x_real ~r:true in
let d_real = discriminator x_real in
let d_loss_real = bce_loss_with_logits d_real ~target:1. in
Tensor.backward d_loss_real ~keep_graph:true;
let reg = Tensor.(f reg_param * grad2 d_real x_real |> mean) in
Tensor.backward reg;
let x_fake = Tensor.no_grad (fun () -> z_dist () |> generator) in
let x_fake = Tensor.set_requires_grad x_fake ~r:true in
let d_fake = discriminator x_fake in
let d_loss_fake = bce_loss_with_logits d_fake ~target:0. in
Tensor.backward d_loss_fake;
Optimizer.step opt_d;
Tensor.( + ) d_loss_real d_loss_fake
in
let generator_loss =
Var_store.unfreeze generator_vs;
Var_store.freeze discriminator_vs;
Optimizer.zero_grad opt_g;
let z = z_dist () in
let x_fake = generator z in
let d_fake = discriminator x_fake in
let g_loss = bce_loss_with_logits d_fake ~target:1. in
Tensor.backward g_loss;
Optimizer.step opt_g;
g_loss
in
if batch_idx % 100 = 0
then
Stdio.printf
"batch %4d d-loss: %12.6f g-loss: %12.6f\n%!"
batch_idx
(Tensor.float_value discriminator_loss)
(Tensor.float_value generator_loss);
Caml.Gc.full_major ();
if batch_idx % 25000 = 0 || (batch_idx < 100000 && batch_idx % 5000 = 0)
then
Tensor.no_grad (fun () -> generator z_test)
|> Tensor.view ~size:[ batch_size; 3; img_size; img_size ]
|> Tensor.to_device ~device:Cpu
|> fun xs ->
Tensor.((xs + f 1.) * f 127.5)
|> Tensor.clamp ~min:(Scalar.float 0.) ~max:(Scalar.float 255.)
|> Tensor.to_type ~type_:(T Uint8)
|> write_samples ~filename:(Printf.sprintf "out%d.png" batch_idx))
|
38da47bf1740d29536efeb1ca4973c1aed60828a7da4cf1204ab7e5759f84397 | kupl/LearnML | original.ml | type aexp =
| Const of int
| Var of string
| Power of (string * int)
| Times of aexp list
| Sum of aexp list
let rec diff ((aexp : aexp), (x : string)) : aexp =
match aexp with
| Const n -> Const 0
| Var x -> Const 1
| Power (x, n) -> (
match n with
| 0 -> Const 1
| _ -> Times [ Const n; diff (Power (x, n - 1), x) ] )
| Times a :: b :: tl -> Times [ a; diff (b, x) ]
| Sum hd :: tl -> (
match hd with
| Const 0 -> Const 0
| _ -> Sum [ diff (hd, x); diff (Sum tl, x) ] )
| Times [] -> raise Failure "error"
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/diff/sub47/original.ml | ocaml | type aexp =
| Const of int
| Var of string
| Power of (string * int)
| Times of aexp list
| Sum of aexp list
let rec diff ((aexp : aexp), (x : string)) : aexp =
match aexp with
| Const n -> Const 0
| Var x -> Const 1
| Power (x, n) -> (
match n with
| 0 -> Const 1
| _ -> Times [ Const n; diff (Power (x, n - 1), x) ] )
| Times a :: b :: tl -> Times [ a; diff (b, x) ]
| Sum hd :: tl -> (
match hd with
| Const 0 -> Const 0
| _ -> Sum [ diff (hd, x); diff (Sum tl, x) ] )
| Times [] -> raise Failure "error"
|
|
f1e12f25c47680b4ba2ec1befc808b5d8dd91c4af5e0af14a9578abc3d7cf0d1 | huangz1990/SICP-answers | 50-rotate180.scm | 50-rotate180.scm
(define (rotate180 painter)
(transform-painter painter
(make-vect 1.0 1.0)
(make-vect 0.0 1.0)
(make-vect 1.0 0.0)))
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/50-rotate180.scm | scheme | 50-rotate180.scm
(define (rotate180 painter)
(transform-painter painter
(make-vect 1.0 1.0)
(make-vect 0.0 1.0)
(make-vect 1.0 0.0)))
|
|
45a4f6d78a1477bf15dccfe885c6692b30372f8c0067f8b8ba4a9711a4bef141 | SparkFund/spec-tacular | spec_tacular_test.clj | (ns spark.spec-tacular-test
(:use spark.spec-tacular
clojure.test
[spark.spec-tacular.generators :exclude [prop-check-components]])
(:require [clojure.core.typed :as t]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :as ct]))
;; -----------------------------------------------------------------------------
;; defspec
(defspec TestSpec1
[val1 :is-a :long :required]
[val2 :is-a :string]
[val3 :is-a :long :default-value 3]
[val4 :is-a :keyword :default-value (fn [] :val)]
[val5 :is-a :TestSpec3])
(deftest test-TestSpec1
(testing "valid"
(is (some? (get-spec :TestSpec1)))
(is (some? (get-spec :TestSpec1 :TestSpec1)))
(is (some? (get-spec {:spec-tacular/spec :TestSpec1})))
(is (some? (get-spec (get-spec :TestSpec1))))
(let [good (testspec1 {:val1 3 :val2 "hi"})]
(is (testspec1? good))
(is (= (:val1 good) 3))
(is (= (:val2 good) "hi"))
(is (= (:val3 good) 3))
(is (= (:val4 good) :val))
(is (= (keys good) [:val1 :val2 :val3 :val4]))
(testing "has-spec?"
(is (has-spec? good))
(is (not (has-spec? 5)))))
(is (= (count (into #{} [(testspec1 {:val1 5}) (testspec1 {:val1 5})])) 1)))
(testing "invalid"
(is (not (testspec1? {:val1 3 :val2 "hi"}))
"not a record")
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"required"
(testspec1 {:val1 nil}))
"missing required field")
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"required"
(testspec1 {:val2 1}))
"missing required field")
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"invalid type"
(testspec1 {:val1 0 :val2 1}))
"wrong type")
(is (thrown? clojure.lang.ExceptionInfo (testspec1 {:val1 3 :extra-key true}))
"extra key")))
;; -----------------------------------------------------------------------------
;; link
(defspec TestSpec2
(:link [ts1 :is-a :TestSpec1]))
(defspec TestSpec3)
(deftest test-TestSpec2
(is (doall (testspec2 {:ts1 (testspec1 {:val1 42})})))
(testing "order of spec definition does not matter"
(is (testspec1? (testspec1 {:val1 1 :val5 (testspec3)}))))
(testing "links are not checked"
(let [ts1 (i_TestSpec1. {::bad-key true} (atom {}) nil)]
(is (testspec2 {:ts1 ts1})))))
;; -----------------------------------------------------------------------------
;; booleans, is-many
(defspec TestSpec4
[val1 :is-a :boolean]
[val2 :is-many :boolean])
(deftest test-TestSpec4
(testing "booleans"
(is (some? (check-component! (get-spec :TestSpec4) :val1 false)))
(is (testspec4? (testspec4 {:val1 false})))
(is (some? (re-find #"false" (pr-str (testspec4 {:val1 false})))))))
;; -----------------------------------------------------------------------------
;; required
(defspec TestSpec5
[name :is-a :string :required])
(deftest test-TestSpec5
(testing "empty string"
(is (some? (check-component! (get-spec :TestSpec5) :name "")))))
;; -----------------------------------------------------------------------------
;; forward references
(defspec A [b :is-a :B])
(defspec B [a :is-a :A])
;; -----------------------------------------------------------------------------
;; unions
(defunion testunion :TestSpec2 :TestSpec3)
(defspec ES [foo :is-a :testunion])
(defspec ESParent [es :is-a :ES])
(deftest test-defunion
(is (some? (get-spec :testunion)))
(is (= (get-spec :testunion {:spec-tacular/spec :TestSpec2})
(get-spec :TestSpec2)))
(is (= (:elements (get-spec :testunion))
#{:TestSpec2 :TestSpec3}))
(is (testunion? (testspec2 {})))
(is (instance? spark.spec_tacular.spec.UnionSpec (get-spec :testunion)))
(is (check-component! (get-spec :ES) :foo (testspec2 {})))
(is (thrown? clojure.lang.ExceptionInfo (check-component! (get-spec :ES) :foo :nope)))
(is (thrown? clojure.lang.ExceptionInfo (es (testspec1 {:val1 1}))))
(is (thrown? clojure.lang.ExceptionInfo (get-spec :testunion (testspec1 {:val1 1}))))
(is (thrown? clojure.lang.ExceptionInfo (esparent {:es {:foo (testspec1 {:val1 1})}})))
(is (thrown? clojure.lang.ExceptionInfo (es {:foo (a {})}))))
(defunion UnionFoo :UnionForward)
(defspec UnionForward)
(defspec TestSpec6
[union :is-many :UnionFoo])
;; -----------------------------------------------------------------------------
;; enums
(defenum IsEnum how now brown cow)
(defspec HasEnum
[word :is-a :IsEnum]
[words :is-many :IsEnum])
(deftest test-defenum
(is (isenum? :IsEnum/how))
(is (isenum? :IsEnum/cow))
(is (= (get-spec :IsEnum)
(get-spec :IsEnum/how)
IsEnum))
(is (hasenum {:word :IsEnum/how}))
(is (hasenum? (hasenum {:word :IsEnum/now})))
(is (isenum? (:word (hasenum {:word :IsEnum/brown}))))
(is (every? isenum? (:words (hasenum {:words #{:IsEnum/how :IsEnum/cow}})))))
;; -----------------------------------------------------------------------------
;; complex
(defspec Link
(:link
[ts1 :is-a :TestSpec1]
[ts2 :is-many :TestSpec2])
[ts3 :is-a :TestSpec3]
[ts4 :is-many :TestSpec4]
[s1 :is-many :string])
(deftest test-refless=
(is (refless= #{false} #{false}))
(is (refless= #{nil} #{nil})))
(deftest test-link
(let [many [(testspec2) (testspec2 {:ts1 (testspec1 {:val1 42})})]
l (link {:ts1 (testspec1 {:val1 42})
:ts2 many
:ts3 (testspec3)
:ts4 [(testspec4 {:val1 false})]})]
(is (link? l))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"not a map"
(recursive-ctor :TestSpec2 many)))
(is (= (:ts2 l) (set many)))
(is (doall (with-out-str (prn l)))))
(let [l (link {:s1 ["a" "b" "c"]})]
(is (link? l)))
(let [l (link {:ts3 nil})]
(is (link? l))
(is (not (:ts3 l))))
(let [l1 (link {:ts3 (assoc (testspec3) :db-ref 1)})]
(is (= (refless l1)
(link {:ts3 (testspec3)}))))
(let [l1 (link {:ts3 (testspec3 {:db-ref 1}) :db-ref 3})
l2 (link {:ts3 (testspec3 {:db-ref 2}) :db-ref 4})]
(is (refless= [[[l1]]] [[[l2]]]) "refless equality"))
(testing "is-many"
(is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]})
(link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]})))
(is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]})
(link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]})))))
(defspec TestSpec7
[nums :is-many :long])
(deftest test-is-many
(is (= (testspec7 {:nums [1 2 3 4]})
(testspec7 {:nums #{1 2 3 4}}))))
(defspec TestSpec8
[day :is-a :calendarday])
(deftest test-calendarday
(is (= (:day (assoc (testspec8) :day "2015-1-1"))
(clj-time.core/date-time 2015 1 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; random testing
(defn prop-check-components
"property for verifying that check-component!, create!, and update! work correctly"
[spec-key]
(let [sp-gen (mk-spec-generator spec-key)
spec (get-spec spec-key)
gen (gen/bind sp-gen gen/return)
fields (map :name (:items spec))]
(prop/for-all [instance gen]
(and (every? #(check-component! spec % (get instance %)) fields)
(do (with-out-str (prn instance)) true)))))
(ct/defspec gen-TestSpec3 100 (prop-check-components :TestSpec3))
(ct/defspec gen-TestSpec1 100 (prop-check-components :TestSpec1))
(ct/defspec gen-TestSpec2 100 (prop-check-components :TestSpec2))
(ct/defspec gen-TestSpec4 100 (prop-check-components :TestSpec4))
(ct/defspec gen-TestSpec5 100 (prop-check-components :TestSpec5))
(ct/defspec gen-testunion 100 (prop-check-components :testunion))
(ct/defspec gen-ES 100 (prop-check-components :ES))
(ct/defspec gen-ESParent 100 (prop-check-components :ESParent))
(ct/defspec gen-TestSpec6 100 (prop-check-components :TestSpec6))
(ct/defspec gen-Link 100 (prop-check-components :Link))
(ct/defspec gen-HasEnum 100 (prop-check-components :HasEnum))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; diff
(defspec Human
[name :is-a :string]
[age :is-a :long]
[pets :is-many :Animal])
(deftest test-diff
(let [peter (human {:name "Peter" :age 17})
paul (human {:name "Paul" :age 18})
#_mary #_(human {:name "Mary" :age 18 :pets [(dog {:name "George"}) (cat {:name "Ringo"})]})]
(is (= (diff peter paul)
[{:name "Peter" :age 17} {:name "Paul" :age 18} {}]))
(is (= (diff peter (human {:name "Peter" :age 25}))
[{:age 17} {:age 25} {:name "Peter"}]))
(is (= (diff peter (human {:age 25}))
[{:name "Peter" :age 17} {:age 25} {}]))
#_(is (= (diff mary (human {:name "Mary" :age 18 :pets [(cat {:name "Ringo"}) (dog {:name "George"})]}))
[{} {} {:age 18,
:name "Mary",
:pets #{(cat {:name "Ringo"}) (dog {:name "George"})}}]))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; docstrings
(defspec Complicated
"A complicated thing that really needs documentation"
[name :is-a :string])
(defunion Complexity
"Complexity is complicated"
:Complicated)
(defenum Complications
"Simple isn't easy"
Simple
Easy)
(deftest test-docstrings
(is (= "A complicated thing that really needs documentation"
(:doc (meta #'Complicated))))
(is (= "Complexity is complicated"
(:doc (meta #'Complexity))))
(is (= "Simple isn't easy"
(:doc (meta #'Complications)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ns
(def ns-specs (namespace->specs *ns*))
(deftest test-namespace->specs
(let [[a b both] (clojure.data/diff
(into #{} (map :name ns-specs))
#{:TestSpec1 :TestSpec2 :TestSpec3 :TestSpec4 :TestSpec5
:testunion :ES :ESParent :UnionFoo :UnionForward :A :B
:Link :Human :TestSpec6 :TestSpec7 :IsEnum :HasEnum
:TestSpec8 :Complicated :Complexity :Complications})]
(is (= (count both) 22) "total number of specs")
(is (nil? b) "no missing specs")
(is (nil? a) "no extra specs")))
| null | https://raw.githubusercontent.com/SparkFund/spec-tacular/2ddeaa0a33593a5e71f377368ded4701fa223e20/test/spark/spec_tacular_test.clj | clojure | -----------------------------------------------------------------------------
defspec
-----------------------------------------------------------------------------
link
-----------------------------------------------------------------------------
booleans, is-many
-----------------------------------------------------------------------------
required
-----------------------------------------------------------------------------
forward references
-----------------------------------------------------------------------------
unions
-----------------------------------------------------------------------------
enums
-----------------------------------------------------------------------------
complex
random testing
diff
docstrings
ns | (ns spark.spec-tacular-test
(:use spark.spec-tacular
clojure.test
[spark.spec-tacular.generators :exclude [prop-check-components]])
(:require [clojure.core.typed :as t]
[clojure.test.check :as tc]
[clojure.test.check.generators :as gen]
[clojure.test.check.properties :as prop]
[clojure.test.check.clojure-test :as ct]))
(defspec TestSpec1
[val1 :is-a :long :required]
[val2 :is-a :string]
[val3 :is-a :long :default-value 3]
[val4 :is-a :keyword :default-value (fn [] :val)]
[val5 :is-a :TestSpec3])
(deftest test-TestSpec1
(testing "valid"
(is (some? (get-spec :TestSpec1)))
(is (some? (get-spec :TestSpec1 :TestSpec1)))
(is (some? (get-spec {:spec-tacular/spec :TestSpec1})))
(is (some? (get-spec (get-spec :TestSpec1))))
(let [good (testspec1 {:val1 3 :val2 "hi"})]
(is (testspec1? good))
(is (= (:val1 good) 3))
(is (= (:val2 good) "hi"))
(is (= (:val3 good) 3))
(is (= (:val4 good) :val))
(is (= (keys good) [:val1 :val2 :val3 :val4]))
(testing "has-spec?"
(is (has-spec? good))
(is (not (has-spec? 5)))))
(is (= (count (into #{} [(testspec1 {:val1 5}) (testspec1 {:val1 5})])) 1)))
(testing "invalid"
(is (not (testspec1? {:val1 3 :val2 "hi"}))
"not a record")
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"required"
(testspec1 {:val1 nil}))
"missing required field")
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"required"
(testspec1 {:val2 1}))
"missing required field")
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"invalid type"
(testspec1 {:val1 0 :val2 1}))
"wrong type")
(is (thrown? clojure.lang.ExceptionInfo (testspec1 {:val1 3 :extra-key true}))
"extra key")))
(defspec TestSpec2
(:link [ts1 :is-a :TestSpec1]))
(defspec TestSpec3)
(deftest test-TestSpec2
(is (doall (testspec2 {:ts1 (testspec1 {:val1 42})})))
(testing "order of spec definition does not matter"
(is (testspec1? (testspec1 {:val1 1 :val5 (testspec3)}))))
(testing "links are not checked"
(let [ts1 (i_TestSpec1. {::bad-key true} (atom {}) nil)]
(is (testspec2 {:ts1 ts1})))))
(defspec TestSpec4
[val1 :is-a :boolean]
[val2 :is-many :boolean])
(deftest test-TestSpec4
(testing "booleans"
(is (some? (check-component! (get-spec :TestSpec4) :val1 false)))
(is (testspec4? (testspec4 {:val1 false})))
(is (some? (re-find #"false" (pr-str (testspec4 {:val1 false})))))))
(defspec TestSpec5
[name :is-a :string :required])
(deftest test-TestSpec5
(testing "empty string"
(is (some? (check-component! (get-spec :TestSpec5) :name "")))))
(defspec A [b :is-a :B])
(defspec B [a :is-a :A])
(defunion testunion :TestSpec2 :TestSpec3)
(defspec ES [foo :is-a :testunion])
(defspec ESParent [es :is-a :ES])
(deftest test-defunion
(is (some? (get-spec :testunion)))
(is (= (get-spec :testunion {:spec-tacular/spec :TestSpec2})
(get-spec :TestSpec2)))
(is (= (:elements (get-spec :testunion))
#{:TestSpec2 :TestSpec3}))
(is (testunion? (testspec2 {})))
(is (instance? spark.spec_tacular.spec.UnionSpec (get-spec :testunion)))
(is (check-component! (get-spec :ES) :foo (testspec2 {})))
(is (thrown? clojure.lang.ExceptionInfo (check-component! (get-spec :ES) :foo :nope)))
(is (thrown? clojure.lang.ExceptionInfo (es (testspec1 {:val1 1}))))
(is (thrown? clojure.lang.ExceptionInfo (get-spec :testunion (testspec1 {:val1 1}))))
(is (thrown? clojure.lang.ExceptionInfo (esparent {:es {:foo (testspec1 {:val1 1})}})))
(is (thrown? clojure.lang.ExceptionInfo (es {:foo (a {})}))))
(defunion UnionFoo :UnionForward)
(defspec UnionForward)
(defspec TestSpec6
[union :is-many :UnionFoo])
(defenum IsEnum how now brown cow)
(defspec HasEnum
[word :is-a :IsEnum]
[words :is-many :IsEnum])
(deftest test-defenum
(is (isenum? :IsEnum/how))
(is (isenum? :IsEnum/cow))
(is (= (get-spec :IsEnum)
(get-spec :IsEnum/how)
IsEnum))
(is (hasenum {:word :IsEnum/how}))
(is (hasenum? (hasenum {:word :IsEnum/now})))
(is (isenum? (:word (hasenum {:word :IsEnum/brown}))))
(is (every? isenum? (:words (hasenum {:words #{:IsEnum/how :IsEnum/cow}})))))
(defspec Link
(:link
[ts1 :is-a :TestSpec1]
[ts2 :is-many :TestSpec2])
[ts3 :is-a :TestSpec3]
[ts4 :is-many :TestSpec4]
[s1 :is-many :string])
(deftest test-refless=
(is (refless= #{false} #{false}))
(is (refless= #{nil} #{nil})))
(deftest test-link
(let [many [(testspec2) (testspec2 {:ts1 (testspec1 {:val1 42})})]
l (link {:ts1 (testspec1 {:val1 42})
:ts2 many
:ts3 (testspec3)
:ts4 [(testspec4 {:val1 false})]})]
(is (link? l))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"not a map"
(recursive-ctor :TestSpec2 many)))
(is (= (:ts2 l) (set many)))
(is (doall (with-out-str (prn l)))))
(let [l (link {:s1 ["a" "b" "c"]})]
(is (link? l)))
(let [l (link {:ts3 nil})]
(is (link? l))
(is (not (:ts3 l))))
(let [l1 (link {:ts3 (assoc (testspec3) :db-ref 1)})]
(is (= (refless l1)
(link {:ts3 (testspec3)}))))
(let [l1 (link {:ts3 (testspec3 {:db-ref 1}) :db-ref 3})
l2 (link {:ts3 (testspec3 {:db-ref 2}) :db-ref 4})]
(is (refless= [[[l1]]] [[[l2]]]) "refless equality"))
(testing "is-many"
(is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]})
(link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]})))
(is (not= (link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 true})]})
(link {:ts4 [(testspec4 {:val1 true}) (testspec4 {:val1 false})]})))))
(defspec TestSpec7
[nums :is-many :long])
(deftest test-is-many
(is (= (testspec7 {:nums [1 2 3 4]})
(testspec7 {:nums #{1 2 3 4}}))))
(defspec TestSpec8
[day :is-a :calendarday])
(deftest test-calendarday
(is (= (:day (assoc (testspec8) :day "2015-1-1"))
(clj-time.core/date-time 2015 1 1))))
(defn prop-check-components
"property for verifying that check-component!, create!, and update! work correctly"
[spec-key]
(let [sp-gen (mk-spec-generator spec-key)
spec (get-spec spec-key)
gen (gen/bind sp-gen gen/return)
fields (map :name (:items spec))]
(prop/for-all [instance gen]
(and (every? #(check-component! spec % (get instance %)) fields)
(do (with-out-str (prn instance)) true)))))
(ct/defspec gen-TestSpec3 100 (prop-check-components :TestSpec3))
(ct/defspec gen-TestSpec1 100 (prop-check-components :TestSpec1))
(ct/defspec gen-TestSpec2 100 (prop-check-components :TestSpec2))
(ct/defspec gen-TestSpec4 100 (prop-check-components :TestSpec4))
(ct/defspec gen-TestSpec5 100 (prop-check-components :TestSpec5))
(ct/defspec gen-testunion 100 (prop-check-components :testunion))
(ct/defspec gen-ES 100 (prop-check-components :ES))
(ct/defspec gen-ESParent 100 (prop-check-components :ESParent))
(ct/defspec gen-TestSpec6 100 (prop-check-components :TestSpec6))
(ct/defspec gen-Link 100 (prop-check-components :Link))
(ct/defspec gen-HasEnum 100 (prop-check-components :HasEnum))
(defspec Human
[name :is-a :string]
[age :is-a :long]
[pets :is-many :Animal])
(deftest test-diff
(let [peter (human {:name "Peter" :age 17})
paul (human {:name "Paul" :age 18})
#_mary #_(human {:name "Mary" :age 18 :pets [(dog {:name "George"}) (cat {:name "Ringo"})]})]
(is (= (diff peter paul)
[{:name "Peter" :age 17} {:name "Paul" :age 18} {}]))
(is (= (diff peter (human {:name "Peter" :age 25}))
[{:age 17} {:age 25} {:name "Peter"}]))
(is (= (diff peter (human {:age 25}))
[{:name "Peter" :age 17} {:age 25} {}]))
#_(is (= (diff mary (human {:name "Mary" :age 18 :pets [(cat {:name "Ringo"}) (dog {:name "George"})]}))
[{} {} {:age 18,
:name "Mary",
:pets #{(cat {:name "Ringo"}) (dog {:name "George"})}}]))))
(defspec Complicated
"A complicated thing that really needs documentation"
[name :is-a :string])
(defunion Complexity
"Complexity is complicated"
:Complicated)
(defenum Complications
"Simple isn't easy"
Simple
Easy)
(deftest test-docstrings
(is (= "A complicated thing that really needs documentation"
(:doc (meta #'Complicated))))
(is (= "Complexity is complicated"
(:doc (meta #'Complexity))))
(is (= "Simple isn't easy"
(:doc (meta #'Complications)))))
(def ns-specs (namespace->specs *ns*))
(deftest test-namespace->specs
(let [[a b both] (clojure.data/diff
(into #{} (map :name ns-specs))
#{:TestSpec1 :TestSpec2 :TestSpec3 :TestSpec4 :TestSpec5
:testunion :ES :ESParent :UnionFoo :UnionForward :A :B
:Link :Human :TestSpec6 :TestSpec7 :IsEnum :HasEnum
:TestSpec8 :Complicated :Complexity :Complications})]
(is (= (count both) 22) "total number of specs")
(is (nil? b) "no missing specs")
(is (nil? a) "no extra specs")))
|
2ab4301267f910a31a8049b063f12e22811c4a78acf721d154a1c5daa4c81f95 | B-Lang-org/bsc | BExpr.hs | # LANGUAGE CPP #
module BExpr(BExpr, bNothing, bAdd, bImplies, bImpliesB) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 804)
import Prelude hiding ((<>))
#endif
import Util(isOrdSubset, mergeOrdNoDup)
import PPrint
import ISyntax
import ISyntaxUtil
import BDD
import Prim
--import Debug.Trace
A BExpr records information when is know to be true .
-- bNothing is no information
bAdd adds an additional fact
-- bImplies checks if the know facts implies an expression.
-- bImplies is allowed to answer False even if the implication
-- is true, but not the other way around.
bNothing :: BExpr a
bAdd :: IExpr a -> BExpr a -> BExpr a
bImplies :: BExpr a -> IExpr a -> Bool
bImpliesB :: BExpr a -> BExpr a -> Bool
-- This implementation is exact , but slow .
newtype BExpr = B ( BDD IExpr )
instance PPrint BExpr where
pPrint d p _ = text " BExpr "
toBExpr : : IExpr - > BDD IExpr
toBExpr ( IAps ( ICon _ ( ICPrim _ ) ) _ [ e1 , e2 ] ) = bddAnd ( toBExpr e1 ) ( toBExpr e2 )
toBExpr ( IAps ( ICon _ ( ICPrim _ PrimBOr ) ) _ [ e1 , e2 ] ) = bddOr ( toBExpr e1 ) ( toBExpr e2 )
toBExpr ( IAps ( ICon _ ( ICPrim _ PrimBNot ) ) _ [ e ] ) = bddNot ( toBExpr e )
toBExpr e = if e = = iTrue then bddTrue else if e = = iFalse then bddFalse else bddVar e
bNothing = B bddTrue
bAdd e ( B bdd ) = B ( bddAnd ( toBExpr e ) bdd )
bImplies ( B bdd ) e = bddIsTrue ( bddImplies bdd ( toBExpr e ) )
-- This implementation is exact, but slow.
newtype BExpr = B (BDD IExpr)
instance PPrint BExpr where
pPrint d p _ = text "BExpr"
toBExpr :: IExpr -> BDD IExpr
toBExpr (IAps (ICon _ (ICPrim _ PrimBAnd)) _ [e1, e2]) = bddAnd (toBExpr e1) (toBExpr e2)
toBExpr (IAps (ICon _ (ICPrim _ PrimBOr)) _ [e1, e2]) = bddOr (toBExpr e1) (toBExpr e2)
toBExpr (IAps (ICon _ (ICPrim _ PrimBNot)) _ [e]) = bddNot (toBExpr e)
toBExpr e = if e == iTrue then bddTrue else if e == iFalse then bddFalse else bddVar e
bNothing = B bddTrue
bAdd e (B bdd) = B (bddAnd (toBExpr e) bdd)
bImplies (B bdd) e = bddIsTrue (bddImplies bdd (toBExpr e))
-}
---------
-- Trivial implementation .
newtype BExpr a = B ( )
instance ( BExpr a ) where
pPrint d p _ = text " BExpr "
bNothing = B ( )
bAdd _ _ = B ( )
bImplies _ e = isTrue e
bImpliesB _ _ = False
---------
-- Trivial implementation.
newtype BExpr a = B ()
instance PPrint (BExpr a) where
pPrint d p _ = text "BExpr"
bNothing = B ()
bAdd _ _ = B ()
bImplies _ e = isTrue e
bImpliesB _ _ = False
---------
-}
newtype BExpr a = A [IExpr a]
instance PPrint (BExpr a) where
pPrint d p (A es) = text "(B" <+> pPrint d 0 es <> text ")"
bNothing = A [iTrue]
bAdd e (A es) = A $ mergeOrdNoDup (get e) es
bImplies (A es) e =
if length es > 1 then trace ( ppReadable ( e , es , isOrdSubset ( get e ) es ) ) $ isOrdSubset ( get e ) es
isOrdSubset (get e) es
bImpliesB b (A es) = all (bImplies b) es
get :: IExpr a -> [IExpr a]
get = getAnds . norm
getAnds :: IExpr a -> [IExpr a]
getAnds (IAps (ICon _ (ICPrim _ PrimBAnd)) _ [e1, e2]) = mergeOrdNoDup (getAnds e1) (getAnds e2)
getAnds e = [e]
norm :: IExpr a -> IExpr a
norm (IAps (ICon _ (ICPrim _ PrimBNot)) _ [e]) = invert e
norm e = e
invert :: IExpr a -> IExpr a
invert (IAps (ICon _ (ICPrim _ PrimBAnd)) _ [e1, e2]) = ieOr (invert e1) (invert e2)
invert (IAps (ICon _ (ICPrim _ PrimBOr )) _ [e1, e2]) = ieAnd (invert e1) (invert e2)
invert (IAps (ICon _ (ICPrim _ PrimBNot)) _ [e] ) = e
invert e = ieNot e
| null | https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/comp/BExpr.hs | haskell | import Debug.Trace
bNothing is no information
bImplies checks if the know facts implies an expression.
bImplies is allowed to answer False even if the implication
is true, but not the other way around.
This implementation is exact , but slow .
This implementation is exact, but slow.
-------
Trivial implementation .
-------
Trivial implementation.
------- | # LANGUAGE CPP #
module BExpr(BExpr, bNothing, bAdd, bImplies, bImpliesB) where
#if defined(__GLASGOW_HASKELL__) && (__GLASGOW_HASKELL__ >= 804)
import Prelude hiding ((<>))
#endif
import Util(isOrdSubset, mergeOrdNoDup)
import PPrint
import ISyntax
import ISyntaxUtil
import BDD
import Prim
A BExpr records information when is know to be true .
bAdd adds an additional fact
bNothing :: BExpr a
bAdd :: IExpr a -> BExpr a -> BExpr a
bImplies :: BExpr a -> IExpr a -> Bool
bImpliesB :: BExpr a -> BExpr a -> Bool
newtype BExpr = B ( BDD IExpr )
instance PPrint BExpr where
pPrint d p _ = text " BExpr "
toBExpr : : IExpr - > BDD IExpr
toBExpr ( IAps ( ICon _ ( ICPrim _ ) ) _ [ e1 , e2 ] ) = bddAnd ( toBExpr e1 ) ( toBExpr e2 )
toBExpr ( IAps ( ICon _ ( ICPrim _ PrimBOr ) ) _ [ e1 , e2 ] ) = bddOr ( toBExpr e1 ) ( toBExpr e2 )
toBExpr ( IAps ( ICon _ ( ICPrim _ PrimBNot ) ) _ [ e ] ) = bddNot ( toBExpr e )
toBExpr e = if e = = iTrue then bddTrue else if e = = iFalse then bddFalse else bddVar e
bNothing = B bddTrue
bAdd e ( B bdd ) = B ( bddAnd ( toBExpr e ) bdd )
bImplies ( B bdd ) e = bddIsTrue ( bddImplies bdd ( toBExpr e ) )
newtype BExpr = B (BDD IExpr)
instance PPrint BExpr where
pPrint d p _ = text "BExpr"
toBExpr :: IExpr -> BDD IExpr
toBExpr (IAps (ICon _ (ICPrim _ PrimBAnd)) _ [e1, e2]) = bddAnd (toBExpr e1) (toBExpr e2)
toBExpr (IAps (ICon _ (ICPrim _ PrimBOr)) _ [e1, e2]) = bddOr (toBExpr e1) (toBExpr e2)
toBExpr (IAps (ICon _ (ICPrim _ PrimBNot)) _ [e]) = bddNot (toBExpr e)
toBExpr e = if e == iTrue then bddTrue else if e == iFalse then bddFalse else bddVar e
bNothing = B bddTrue
bAdd e (B bdd) = B (bddAnd (toBExpr e) bdd)
bImplies (B bdd) e = bddIsTrue (bddImplies bdd (toBExpr e))
-}
newtype BExpr a = B ( )
instance ( BExpr a ) where
pPrint d p _ = text " BExpr "
bNothing = B ( )
bAdd _ _ = B ( )
bImplies _ e = isTrue e
bImpliesB _ _ = False
newtype BExpr a = B ()
instance PPrint (BExpr a) where
pPrint d p _ = text "BExpr"
bNothing = B ()
bAdd _ _ = B ()
bImplies _ e = isTrue e
bImpliesB _ _ = False
-}
newtype BExpr a = A [IExpr a]
instance PPrint (BExpr a) where
pPrint d p (A es) = text "(B" <+> pPrint d 0 es <> text ")"
bNothing = A [iTrue]
bAdd e (A es) = A $ mergeOrdNoDup (get e) es
bImplies (A es) e =
if length es > 1 then trace ( ppReadable ( e , es , isOrdSubset ( get e ) es ) ) $ isOrdSubset ( get e ) es
isOrdSubset (get e) es
bImpliesB b (A es) = all (bImplies b) es
get :: IExpr a -> [IExpr a]
get = getAnds . norm
getAnds :: IExpr a -> [IExpr a]
getAnds (IAps (ICon _ (ICPrim _ PrimBAnd)) _ [e1, e2]) = mergeOrdNoDup (getAnds e1) (getAnds e2)
getAnds e = [e]
norm :: IExpr a -> IExpr a
norm (IAps (ICon _ (ICPrim _ PrimBNot)) _ [e]) = invert e
norm e = e
invert :: IExpr a -> IExpr a
invert (IAps (ICon _ (ICPrim _ PrimBAnd)) _ [e1, e2]) = ieOr (invert e1) (invert e2)
invert (IAps (ICon _ (ICPrim _ PrimBOr )) _ [e1, e2]) = ieAnd (invert e1) (invert e2)
invert (IAps (ICon _ (ICPrim _ PrimBNot)) _ [e] ) = e
invert e = ieNot e
|
77cb0b8cdd6fce8183caad9bee74164dac9b71decdca612b1a9856798a3b2ac1 | ucsd-progsys/liquidhaskell | Vector0.hs | {-@ LIQUID "--expect-any-error" @-}
module Vector0 (x0, prop0, prop1, prop2, prop3) where
import Language.Haskell.Liquid.Prelude
import Data.Vector hiding (map, concat, zipWith, filter, foldr, foldl, (++))
xs :: [Int]
xs = [1,2,3,4]
vs :: Vector Int
vs = fromList xs
prop0 :: Bool
prop0 = liquidAssertB (x >= 0)
where x = Prelude.head xs
prop1 :: Bool
prop1 = liquidAssertB (n > 0)
where n = Prelude.length xs
prop2 :: Bool
prop2 = liquidAssertB (Data.Vector.length vs > 0)
prop3 :: Bool
prop3 = liquidAssertB (Data.Vector.length vs > 3)
x0 :: [ Int ]
x0 = [ vs ! 0
, vs ! 1
, vs ! 2
, vs ! 3
, vs ! 4 ]
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/names/neg/Vector0.hs | haskell | @ LIQUID "--expect-any-error" @ | module Vector0 (x0, prop0, prop1, prop2, prop3) where
import Language.Haskell.Liquid.Prelude
import Data.Vector hiding (map, concat, zipWith, filter, foldr, foldl, (++))
xs :: [Int]
xs = [1,2,3,4]
vs :: Vector Int
vs = fromList xs
prop0 :: Bool
prop0 = liquidAssertB (x >= 0)
where x = Prelude.head xs
prop1 :: Bool
prop1 = liquidAssertB (n > 0)
where n = Prelude.length xs
prop2 :: Bool
prop2 = liquidAssertB (Data.Vector.length vs > 0)
prop3 :: Bool
prop3 = liquidAssertB (Data.Vector.length vs > 3)
x0 :: [ Int ]
x0 = [ vs ! 0
, vs ! 1
, vs ! 2
, vs ! 3
, vs ! 4 ]
|
d7517aed923c37ae455ef3f28e0cfe90bed634bc5f1d15faee950bbf8cfd7b20 | funcool/dost | crypto.cljs | Copyright 2016 < >
;;
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.
(ns dost.core.crypto
(:refer-clojure :exclude [reset! -reset])
(:require [cljs.nodejs :as node]
[promesa.core :as p :include-macros true]
[dost.core.hash :as hash]
[dost.core.stream :as stream]
[dost.core.buffer :as buffer]
[dost.core.codecs :as codecs]))
(def ^:private crypto (node/require "crypto"))
(def ^:private buffer? buffer/buffer?)
(defprotocol ICipher
"Hash engine common interface definition."
(-init [_ opts] "Initialize cipher.")
(-authtag [_] "Return the authentication tag (only on AEAD ciphers).")
(-update [_ input] "Update bytes in a current instance.")
(-end [_] "Return the computed mac and reset the engine."))
(deftype Cipher [id ^:mutable __engine]
ICipher
(-init [_ opts]
(assert (buffer? (:iv opts)) "The `iv` parameter is mandatory.")
(assert (buffer? (:key opts)) "The `key` parameter is mandatory.")
(let [{:keys [op key iv padding? tag aad]
:or {op :encrypt padding? true}} opts
engine (case op
:encrypt (.createCipheriv crypto id key iv)
:decrypt (.createDecipheriv crypto id key iv)
(throw (ex-info "Invalid operation" {:op op})))]
(when-not padding? (.setAutoPadding engine false))
(when (buffer? tag) (.setAuthTag engine))
(when (buffer? aad) (.setAAD engine aad))
(set! __engine engine)))
(-authtag [_]
(assert __engine "Cipher not initialized.")
(.getAuthTag __engine))
(-update [_ input]
(assert __engine "Cipher not initialized.")
(.update __engine input))
(-end [_]
(assert __engine "Cipher not initialized.")
(.final __engine)))
;; --- Public API
(def available-ciphers
(into #{} (map keyword (.getCiphers crypto))))
(defn cipher?
[v]
(instance? Cipher v))
(defn cipher
[alg]
(assert (available-ciphers alg) "Not supported cipher.")
(Cipher. (name alg) nil))
(defn init!
[c opts]
{:pre [(cipher? c)]}
(-init c opts))
(defn update!
[c input]
{:pre [(cipher? c)]}
(let [input (buffer/from input)]
(-update c input)))
(defn end!
[c]
(-end c))
| null | https://raw.githubusercontent.com/funcool/dost/e68a23ff7d99892d3f2d7bc6fe733bd74d1743a3/src/dost/core/crypto.cljs | clojure |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--- Public API | Copyright 2016 < >
Licensed under the Apache License , Version 2.0 ( the " License " )
distributed under the License is distributed on an " AS IS " BASIS ,
(ns dost.core.crypto
(:refer-clojure :exclude [reset! -reset])
(:require [cljs.nodejs :as node]
[promesa.core :as p :include-macros true]
[dost.core.hash :as hash]
[dost.core.stream :as stream]
[dost.core.buffer :as buffer]
[dost.core.codecs :as codecs]))
(def ^:private crypto (node/require "crypto"))
(def ^:private buffer? buffer/buffer?)
(defprotocol ICipher
"Hash engine common interface definition."
(-init [_ opts] "Initialize cipher.")
(-authtag [_] "Return the authentication tag (only on AEAD ciphers).")
(-update [_ input] "Update bytes in a current instance.")
(-end [_] "Return the computed mac and reset the engine."))
(deftype Cipher [id ^:mutable __engine]
ICipher
(-init [_ opts]
(assert (buffer? (:iv opts)) "The `iv` parameter is mandatory.")
(assert (buffer? (:key opts)) "The `key` parameter is mandatory.")
(let [{:keys [op key iv padding? tag aad]
:or {op :encrypt padding? true}} opts
engine (case op
:encrypt (.createCipheriv crypto id key iv)
:decrypt (.createDecipheriv crypto id key iv)
(throw (ex-info "Invalid operation" {:op op})))]
(when-not padding? (.setAutoPadding engine false))
(when (buffer? tag) (.setAuthTag engine))
(when (buffer? aad) (.setAAD engine aad))
(set! __engine engine)))
(-authtag [_]
(assert __engine "Cipher not initialized.")
(.getAuthTag __engine))
(-update [_ input]
(assert __engine "Cipher not initialized.")
(.update __engine input))
(-end [_]
(assert __engine "Cipher not initialized.")
(.final __engine)))
(def available-ciphers
(into #{} (map keyword (.getCiphers crypto))))
(defn cipher?
[v]
(instance? Cipher v))
(defn cipher
[alg]
(assert (available-ciphers alg) "Not supported cipher.")
(Cipher. (name alg) nil))
(defn init!
[c opts]
{:pre [(cipher? c)]}
(-init c opts))
(defn update!
[c input]
{:pre [(cipher? c)]}
(let [input (buffer/from input)]
(-update c input)))
(defn end!
[c]
(-end c))
|
02c6ba5c31bdfba548af39a6e18ea691b33be678afb1b6318817a791b2ad9c33 | haskus/haskus-system | Deflate.hs | # LANGUAGE MultiWayIf , LambdaCase #
-- | Implement DEFLATE (de)compression algorithm
--
--
--
-- TODO: use BufferBuilder instead of Seq Word8!
--
-- TODO: the function `putFixedCode` is currently exported to avoid a compiler
-- warning. We should implement the whole compression algorithms and export a
-- "compress" method instead.
module Haskus.Format.Compression.Algorithms.Deflate
( decompress
, makeHuffmanCodes
, makeBitGetFromCodes
-- * Internal functions
, putFixedCode
)
where
import qualified Data.Sequence as Seq
import Data.Sequence ((><), Seq, (|>))
import Data.Foldable (toList)
import Data.Ord(comparing)
import Haskus.Utils.Flow (when,replicateM)
import Haskus.Utils.List (sortBy)
import Haskus.Utils.Tuple (swap)
import Haskus.Utils.Maybe (fromJust)
import Haskus.Binary.Bits (shiftL, xor, (.|.), (.&.), testBit)
import Haskus.Number.Word
import Haskus.Binary.Buffer
import Haskus.Binary.Bits.Get
import Haskus.Binary.Bits.Order
import Haskus.Binary.Bits.Put
import Haskus.Format.Compression.Algorithms.Huffman
--
-- Compressed data are split in blocks. Blocks are *not* byte aligned.
--
-- | Decompress all blocks
decompress :: BitGet (Seq Word8)
decompress = withBitGetOrder LL (rec Seq.empty)
where
rec s = getBlock s >>= \case
(s',True) -> return s' -- Final block
(s',False) -> rec s'
| Decompress a block and indicate if it is the last one
--
-- Blocks may require data from previous blocks to be decompressed, hence you
must pass these data as the first parameter .
getBlock :: Seq Word8 -> BitGet (Seq Word8,Bool)
getBlock s = do
(isFinal,comp) <- getBlockHeader
content <- case comp of
NoCompression -> (s ><) <$> getRawBlock
FixedHuffman -> decodeBlock getFixedToken s
DynamicHuffman -> do
g <- getDynamicToken
decodeBlock g s
return (content,isFinal)
-- | Block compression method
data Compression
= NoCompression
| FixedHuffman
| DynamicHuffman
deriving (Show,Eq,Enum)
| Read block header and returns ( isFinal , compression )
--
If compression type = = 3 ( not supposed to happen ) , then toEnum will fail
getBlockHeader :: BitGet (Bool,Compression)
getBlockHeader = (,)
<$> getBitBoolM
<*> (toEnum . fromIntegral <$> (getBitsM 2 :: BitGet Word8))
-- | Read an uncompressed block
getRawBlock :: BitGet (Seq Word8)
getRawBlock = do
-- align on the next byte boundary
skipBitsToAlignOnWord8M
Two bytes : len and nlen
@nlen@ is the one 's complement of len
@len@ is the number of raw bytes that follow
(len,nlen) <- (,) <$> (getBitsM 8 :: BitGet Word8) <*> getBitsM 8
when (len /= nlen `xor` 0xFF) $
error "Invalid uncompressed block length"
-- Read raw data
bs <- withBitGetOrder BB $ getBitsBSM (fromIntegral len)
return (Seq.fromList (bufferUnpackByteList bs))
-- | A block is a sequence of tokens
data Token a
= Literal a -- ^ Literal value (will be copied as-is)
| EndOfBlock -- ^ End of block marker
| Copy Int Int -- ^ Copy dist len: move backwards dist and copy len bytes
deriving (Show,Eq)
| Decode a block using the getToken method provided
decodeBlock :: BitGet (Token Word8) -> Seq Word8 -> BitGet (Seq Word8)
decodeBlock getToken s = getToken >>= \case
EndOfBlock -> return s
Literal x -> decodeBlock getToken (s |> x)
Copy dist len -> decodeBlock getToken (s >< w)
where
pre = Seq.length s - fromIntegral dist
ss = cycle (drop pre (toList s))
w = Seq.fromList (take len ss)
| Create a getToken getter
makeGetToken :: BitGet Word -> BitGet Word8 -> BitGet (Token Word8)
makeGetToken getCode getDistCode = do
code <- getCode
case code of
256 -> return EndOfBlock
_ | code < 256 -> return (Literal (fromIntegral code))
_ -> do
len <- getFixedLength code
dist <- getDistCode >>= getDistance
return (Copy dist len)
| Return the next token with fixed Huffman compression
getFixedToken :: BitGet (Token Word8)
getFixedToken = makeGetToken getFixedCode getFixedDistanceCode
| Create the getToken method with dynamic Huffman compression
--
It reads tables at the beginning of the block that contain the codes
-- to use to decode tokens.
getDynamicToken :: BitGet (BitGet (Token Word8))
getDynamicToken = do
(lits,dist) <- getTables
let
getCode = makeBitGetFromCodes ([0..285] `zip` lits)
getDistCode = makeBitGetFromCodes ([0..29] `zip` dist)
return $ makeGetToken getCode getDistCode
| Read tables for dynamic Huffman compression
--
Tables are encoded using a Run - Length Encoding . The RLE tokens are encoded
using a dynamic Huffman compression . Hence , we first read the table to
-- decode RLE tokens and build a "table decoder" BitGet instance.
getTables :: BitGet ([Word8],[Word8])
getTables = do
-- Get the number of entries in each table
# of literal / length codes [ 257 .. 286 ]
# of distance codes [ 1 .. 32 ]
# of RLE code lengths [ 4 .. 19 ]
-- Get the table decoder
getTable <- getTableDecoder nclen
-- Decode both tables at once because the RLE coding can overlap
values <- getTable (nlits + ndist)
Split values into two tables
return (splitAt nlits values)
-- | Run-length encoding
data RLECode
^ A value [ 1 .. 15 ]
^ 2 extra bits indicating repetition of last value ( 3 - 6 times )
^ 3 extra bits indicating repetition of 0 ( 3 - 10 times )
^ 7 extra bits indicating repetition of 0 ( 11 - 138 times )
deriving (Show,Eq)
instance Ord RLECode where
compare = comparing f
where
f (Value x) = x
f Repeat2bits = 16
f Repeat3bits = 17
f Repeat7bits = 18
-- | Read the table to build the RLE decoder. Return a RLE-encoded table decoder.
getTableDecoder :: Int -> BitGet (Int -> BitGet [Word8])
getTableDecoder nclen = do
Get 3 - bit lengths
clens <- replicateM nclen (getBitsM 3 :: BitGet Word8)
The first RLE tokens are the most used ones . The last ones may be missing
in the table . This way , instead of wasting 3 bits to indicate that a RLE
-- token is not used in the block, the nclen can be shortened to remove the
-- trailing codes
let
cl = [Repeat2bits, Repeat3bits, Repeat7bits, Value 0,
Value 8, Value 7, Value 9, Value 6, Value 10,
Value 5, Value 11, Value 4, Value 12, Value 3,
Value 13, Value 2, Value 14, Value 1, Value 15]
g = makeBitGetFromCodes (cl `zip` clens)
return (makeRLEDecoder g)
-- | Create a decoder for RLE-encoded tables
--
The table decoder uses the tree to decode the RLE code .
-- Then it decodes the RLE code and returns the decoded values.
makeRLEDecoder :: BitGet RLECode -> Int -> BitGet [Word8]
makeRLEDecoder get = rec []
where
rec xs 0 = return (reverse xs)
rec xs n = get >>= \case
Value x -> rec (x:xs) (n-1)
Repeat2bits -> do
rep <- fromIntegral . (+3) <$> (getBitsM 2 :: BitGet Word8)
rec (replicate rep (head xs) ++ xs) (n-rep)
Repeat3bits -> do
rep <- fromIntegral . (+3) <$> (getBitsM 3 :: BitGet Word8)
rec (replicate rep 0 ++ xs) (n-rep)
Repeat7bits -> do
rep <- fromIntegral . (+11) <$> (getBitsM 7 :: BitGet Word16)
rec (replicate rep 0 ++ xs) (n-rep)
| Read the length for the token with the fixed Huffman compression
getFixedLength :: Word -> BitGet Int
getFixedLength code = case code of
x | x <= 260 -> return (fromIntegral code - 254)
-- In the RFC, the length is given in a table. I figured out a formula to
-- compute it instead. It uses the formula to compute the sum of a
geometric sequence ( common ratio = 2 ) .
--
-- 4*(1-2^n)/(1-2) + r*(2^n) + e + 7
--
-- It simplifies to: (4+r)*2^n + e + 3
x | x <= 284 -> f <$> (getBitsM n :: BitGet Word16)
where
(n,r) = (code-261) `divMod` 4
r' = fromIntegral r
f e = fromIntegral $ (4+r') * (1 `shiftL` fromIntegral n) + e + 3
285 -> return 258
_ -> error $ "Invalid length code: " ++ show code
| Read distance code with the fixed Huffman compression
getFixedDistanceCode :: BitGet Word8
getFixedDistanceCode = withBitGetOrder LB (getBitsM 5 :: BitGet Word8)
| Read the distance for the token with the fixed Huffman compression
getDistance :: Word8 -> BitGet Int
getDistance = \case
x | x <= 1 -> return (fromIntegral x + 1)
-- The magic formula is very similar to the one in 'getFixedLength'
2*(1 - 2^n)/(1 - 2 ) + r*(2^n ) + e + 1
--
It simplifies to : ( r+2 ) * 2^n + e + 1
x -> f <$> (getBitsM n :: BitGet Word32)
where
(n,r) = (fromIntegral x-2) `divMod` 2
r' = fromIntegral r
f e = fromIntegral $ (r'+2) * (1 `shiftL` fromIntegral n) + e + 1
| Put the token code with the fixed Huffman compression
putFixedCode :: Word -> BitPut ()
putFixedCode code
| code <= 143 = do -- A
8 bit code , starting from 00110000 to 10111111
let c = code + 48
putBitsM 8 c
| code <= 255 = do -- B
9 bit code , starting from 110010000 to 111111111
let c = code-144 + 400
putBitsM 9 c
| code <= 279 = do -- C
7 bit code , starting from 0000000 to
let c = code-256
putBitsM 7 c
| code <= 287 = do -- D
8 bit code , starting from 11000000 to 11000111
let c = code-280 + 192
putBitsM 8 c
| otherwise = error "Invalid code"
| Get the token code with the fixed Huffman compression
getFixedCode :: BitGet Word
getFixedCode = fromIntegral <$> do
b <- getBitsM 4
-- D
if | b == 0xC -> do
b2 <- getBitsM 4
let r = (b `shiftL` 4) .|. (b2 :: Word16)
return (r - 192 + 280)
-- B
| b .&. 0xC == 0xC -> do
b2 <- getBitsM 5
let r = (b `shiftL` 5) .|. b2
return (r - 400 + 144)
-- C
| (b .&. 0xC == 0) && (testBit b 0 /= testBit b 1) -> do
b2 <- getBitsM 3
let r = (b `shiftL` 3) .|. b2
return (r + 256)
-- A
| otherwise -> do
b2 <- getBitsM 4
let r = (b `shiftL` 4) .|. b2
return (r - 48)
-- | Compute Huffman codes from a list of code lengths with given (unchecked)
-- properties.
--
Deflate algorithm uses Huffman coding with some additional rules :
For two symbols a and b :
-- 1) if codelength(a) == codelength(b) then
-- if code(a) < code(b) then
-- a < b
-- else
-- a > b
--
2 ) if codelength(a ) < codelength(b ) then
-- code(a) < code(b)
--
-- where:
-- * code(x) is the value of the coding of x
-- * codelength(x) is the length of the coding of x (i.e. the number of
-- bits)
--
These properties allow the Huffman encoding to be provided with only a
-- sequence of code lengths. A null code length indicates an element that
-- cannot be encoded.
makeHuffmanCodes :: (Show b,Show a, Ord a, Ord b,Num b) => [(a,b)] -> [(Code,a)]
makeHuffmanCodes = rec emptyCode [] . msort
where
-- sort by length, then by value ordering
msort = sortBy (comparing swap)
-- Encode each symbol, recursively
rec _ xs [] = reverse xs
rec c xs ys@((v,l):ls)
Skip symbols with length = = 0
| l == 0 = rec c xs ls
-- Assign current code if the code length matches
| l == cl = rec (codeAdd 1 c) ((c,v):xs) ls
-- Otherwise, increase the current code length, prefixed with the
-- current code
| cl < l = rec (codeShiftL 1 c) xs ys
-- Shouldn't occur, except for negative code lengths...
| otherwise = error $ "Invalid length: " ++ show l ++ " cl: " ++ show cl
where
cl = fromIntegral (codeLength c)
| Create a Huffman code getter from a list of codes
makeBitGetFromCodes :: (Show a, Show b, Ord a, Ord b, Num b) => [(a,b)] -> BitGet a
makeBitGetFromCodes = fmap fromJust . makeBitGet True . computeHuffmanTreeFromCodes . makeHuffmanCodes
| null | https://raw.githubusercontent.com/haskus/haskus-system/38b3a363c26bc4d82e3493d8638d46bc35678616/haskus-system/src/lib/Haskus/Format/Compression/Algorithms/Deflate.hs | haskell | | Implement DEFLATE (de)compression algorithm
TODO: use BufferBuilder instead of Seq Word8!
TODO: the function `putFixedCode` is currently exported to avoid a compiler
warning. We should implement the whole compression algorithms and export a
"compress" method instead.
* Internal functions
Compressed data are split in blocks. Blocks are *not* byte aligned.
| Decompress all blocks
Final block
Blocks may require data from previous blocks to be decompressed, hence you
| Block compression method
| Read an uncompressed block
align on the next byte boundary
Read raw data
| A block is a sequence of tokens
^ Literal value (will be copied as-is)
^ End of block marker
^ Copy dist len: move backwards dist and copy len bytes
to use to decode tokens.
decode RLE tokens and build a "table decoder" BitGet instance.
Get the number of entries in each table
Get the table decoder
Decode both tables at once because the RLE coding can overlap
| Run-length encoding
| Read the table to build the RLE decoder. Return a RLE-encoded table decoder.
token is not used in the block, the nclen can be shortened to remove the
trailing codes
| Create a decoder for RLE-encoded tables
Then it decodes the RLE code and returns the decoded values.
In the RFC, the length is given in a table. I figured out a formula to
compute it instead. It uses the formula to compute the sum of a
4*(1-2^n)/(1-2) + r*(2^n) + e + 7
It simplifies to: (4+r)*2^n + e + 3
The magic formula is very similar to the one in 'getFixedLength'
A
B
C
D
D
B
C
A
| Compute Huffman codes from a list of code lengths with given (unchecked)
properties.
1) if codelength(a) == codelength(b) then
if code(a) < code(b) then
a < b
else
a > b
code(a) < code(b)
where:
* code(x) is the value of the coding of x
* codelength(x) is the length of the coding of x (i.e. the number of
bits)
sequence of code lengths. A null code length indicates an element that
cannot be encoded.
sort by length, then by value ordering
Encode each symbol, recursively
Assign current code if the code length matches
Otherwise, increase the current code length, prefixed with the
current code
Shouldn't occur, except for negative code lengths... | # LANGUAGE MultiWayIf , LambdaCase #
module Haskus.Format.Compression.Algorithms.Deflate
( decompress
, makeHuffmanCodes
, makeBitGetFromCodes
, putFixedCode
)
where
import qualified Data.Sequence as Seq
import Data.Sequence ((><), Seq, (|>))
import Data.Foldable (toList)
import Data.Ord(comparing)
import Haskus.Utils.Flow (when,replicateM)
import Haskus.Utils.List (sortBy)
import Haskus.Utils.Tuple (swap)
import Haskus.Utils.Maybe (fromJust)
import Haskus.Binary.Bits (shiftL, xor, (.|.), (.&.), testBit)
import Haskus.Number.Word
import Haskus.Binary.Buffer
import Haskus.Binary.Bits.Get
import Haskus.Binary.Bits.Order
import Haskus.Binary.Bits.Put
import Haskus.Format.Compression.Algorithms.Huffman
decompress :: BitGet (Seq Word8)
decompress = withBitGetOrder LL (rec Seq.empty)
where
rec s = getBlock s >>= \case
(s',False) -> rec s'
| Decompress a block and indicate if it is the last one
must pass these data as the first parameter .
getBlock :: Seq Word8 -> BitGet (Seq Word8,Bool)
getBlock s = do
(isFinal,comp) <- getBlockHeader
content <- case comp of
NoCompression -> (s ><) <$> getRawBlock
FixedHuffman -> decodeBlock getFixedToken s
DynamicHuffman -> do
g <- getDynamicToken
decodeBlock g s
return (content,isFinal)
data Compression
= NoCompression
| FixedHuffman
| DynamicHuffman
deriving (Show,Eq,Enum)
| Read block header and returns ( isFinal , compression )
If compression type = = 3 ( not supposed to happen ) , then toEnum will fail
getBlockHeader :: BitGet (Bool,Compression)
getBlockHeader = (,)
<$> getBitBoolM
<*> (toEnum . fromIntegral <$> (getBitsM 2 :: BitGet Word8))
getRawBlock :: BitGet (Seq Word8)
getRawBlock = do
skipBitsToAlignOnWord8M
Two bytes : len and nlen
@nlen@ is the one 's complement of len
@len@ is the number of raw bytes that follow
(len,nlen) <- (,) <$> (getBitsM 8 :: BitGet Word8) <*> getBitsM 8
when (len /= nlen `xor` 0xFF) $
error "Invalid uncompressed block length"
bs <- withBitGetOrder BB $ getBitsBSM (fromIntegral len)
return (Seq.fromList (bufferUnpackByteList bs))
data Token a
deriving (Show,Eq)
| Decode a block using the getToken method provided
decodeBlock :: BitGet (Token Word8) -> Seq Word8 -> BitGet (Seq Word8)
decodeBlock getToken s = getToken >>= \case
EndOfBlock -> return s
Literal x -> decodeBlock getToken (s |> x)
Copy dist len -> decodeBlock getToken (s >< w)
where
pre = Seq.length s - fromIntegral dist
ss = cycle (drop pre (toList s))
w = Seq.fromList (take len ss)
| Create a getToken getter
makeGetToken :: BitGet Word -> BitGet Word8 -> BitGet (Token Word8)
makeGetToken getCode getDistCode = do
code <- getCode
case code of
256 -> return EndOfBlock
_ | code < 256 -> return (Literal (fromIntegral code))
_ -> do
len <- getFixedLength code
dist <- getDistCode >>= getDistance
return (Copy dist len)
| Return the next token with fixed Huffman compression
getFixedToken :: BitGet (Token Word8)
getFixedToken = makeGetToken getFixedCode getFixedDistanceCode
| Create the getToken method with dynamic Huffman compression
It reads tables at the beginning of the block that contain the codes
getDynamicToken :: BitGet (BitGet (Token Word8))
getDynamicToken = do
(lits,dist) <- getTables
let
getCode = makeBitGetFromCodes ([0..285] `zip` lits)
getDistCode = makeBitGetFromCodes ([0..29] `zip` dist)
return $ makeGetToken getCode getDistCode
| Read tables for dynamic Huffman compression
Tables are encoded using a Run - Length Encoding . The RLE tokens are encoded
using a dynamic Huffman compression . Hence , we first read the table to
getTables :: BitGet ([Word8],[Word8])
getTables = do
# of literal / length codes [ 257 .. 286 ]
# of distance codes [ 1 .. 32 ]
# of RLE code lengths [ 4 .. 19 ]
getTable <- getTableDecoder nclen
values <- getTable (nlits + ndist)
Split values into two tables
return (splitAt nlits values)
data RLECode
^ A value [ 1 .. 15 ]
^ 2 extra bits indicating repetition of last value ( 3 - 6 times )
^ 3 extra bits indicating repetition of 0 ( 3 - 10 times )
^ 7 extra bits indicating repetition of 0 ( 11 - 138 times )
deriving (Show,Eq)
instance Ord RLECode where
compare = comparing f
where
f (Value x) = x
f Repeat2bits = 16
f Repeat3bits = 17
f Repeat7bits = 18
getTableDecoder :: Int -> BitGet (Int -> BitGet [Word8])
getTableDecoder nclen = do
Get 3 - bit lengths
clens <- replicateM nclen (getBitsM 3 :: BitGet Word8)
The first RLE tokens are the most used ones . The last ones may be missing
in the table . This way , instead of wasting 3 bits to indicate that a RLE
let
cl = [Repeat2bits, Repeat3bits, Repeat7bits, Value 0,
Value 8, Value 7, Value 9, Value 6, Value 10,
Value 5, Value 11, Value 4, Value 12, Value 3,
Value 13, Value 2, Value 14, Value 1, Value 15]
g = makeBitGetFromCodes (cl `zip` clens)
return (makeRLEDecoder g)
The table decoder uses the tree to decode the RLE code .
makeRLEDecoder :: BitGet RLECode -> Int -> BitGet [Word8]
makeRLEDecoder get = rec []
where
rec xs 0 = return (reverse xs)
rec xs n = get >>= \case
Value x -> rec (x:xs) (n-1)
Repeat2bits -> do
rep <- fromIntegral . (+3) <$> (getBitsM 2 :: BitGet Word8)
rec (replicate rep (head xs) ++ xs) (n-rep)
Repeat3bits -> do
rep <- fromIntegral . (+3) <$> (getBitsM 3 :: BitGet Word8)
rec (replicate rep 0 ++ xs) (n-rep)
Repeat7bits -> do
rep <- fromIntegral . (+11) <$> (getBitsM 7 :: BitGet Word16)
rec (replicate rep 0 ++ xs) (n-rep)
| Read the length for the token with the fixed Huffman compression
getFixedLength :: Word -> BitGet Int
getFixedLength code = case code of
x | x <= 260 -> return (fromIntegral code - 254)
geometric sequence ( common ratio = 2 ) .
x | x <= 284 -> f <$> (getBitsM n :: BitGet Word16)
where
(n,r) = (code-261) `divMod` 4
r' = fromIntegral r
f e = fromIntegral $ (4+r') * (1 `shiftL` fromIntegral n) + e + 3
285 -> return 258
_ -> error $ "Invalid length code: " ++ show code
| Read distance code with the fixed Huffman compression
getFixedDistanceCode :: BitGet Word8
getFixedDistanceCode = withBitGetOrder LB (getBitsM 5 :: BitGet Word8)
| Read the distance for the token with the fixed Huffman compression
getDistance :: Word8 -> BitGet Int
getDistance = \case
x | x <= 1 -> return (fromIntegral x + 1)
2*(1 - 2^n)/(1 - 2 ) + r*(2^n ) + e + 1
It simplifies to : ( r+2 ) * 2^n + e + 1
x -> f <$> (getBitsM n :: BitGet Word32)
where
(n,r) = (fromIntegral x-2) `divMod` 2
r' = fromIntegral r
f e = fromIntegral $ (r'+2) * (1 `shiftL` fromIntegral n) + e + 1
| Put the token code with the fixed Huffman compression
putFixedCode :: Word -> BitPut ()
putFixedCode code
8 bit code , starting from 00110000 to 10111111
let c = code + 48
putBitsM 8 c
9 bit code , starting from 110010000 to 111111111
let c = code-144 + 400
putBitsM 9 c
7 bit code , starting from 0000000 to
let c = code-256
putBitsM 7 c
8 bit code , starting from 11000000 to 11000111
let c = code-280 + 192
putBitsM 8 c
| otherwise = error "Invalid code"
| Get the token code with the fixed Huffman compression
getFixedCode :: BitGet Word
getFixedCode = fromIntegral <$> do
b <- getBitsM 4
if | b == 0xC -> do
b2 <- getBitsM 4
let r = (b `shiftL` 4) .|. (b2 :: Word16)
return (r - 192 + 280)
| b .&. 0xC == 0xC -> do
b2 <- getBitsM 5
let r = (b `shiftL` 5) .|. b2
return (r - 400 + 144)
| (b .&. 0xC == 0) && (testBit b 0 /= testBit b 1) -> do
b2 <- getBitsM 3
let r = (b `shiftL` 3) .|. b2
return (r + 256)
| otherwise -> do
b2 <- getBitsM 4
let r = (b `shiftL` 4) .|. b2
return (r - 48)
Deflate algorithm uses Huffman coding with some additional rules :
For two symbols a and b :
2 ) if codelength(a ) < codelength(b ) then
These properties allow the Huffman encoding to be provided with only a
makeHuffmanCodes :: (Show b,Show a, Ord a, Ord b,Num b) => [(a,b)] -> [(Code,a)]
makeHuffmanCodes = rec emptyCode [] . msort
where
msort = sortBy (comparing swap)
rec _ xs [] = reverse xs
rec c xs ys@((v,l):ls)
Skip symbols with length = = 0
| l == 0 = rec c xs ls
| l == cl = rec (codeAdd 1 c) ((c,v):xs) ls
| cl < l = rec (codeShiftL 1 c) xs ys
| otherwise = error $ "Invalid length: " ++ show l ++ " cl: " ++ show cl
where
cl = fromIntegral (codeLength c)
| Create a Huffman code getter from a list of codes
makeBitGetFromCodes :: (Show a, Show b, Ord a, Ord b, Num b) => [(a,b)] -> BitGet a
makeBitGetFromCodes = fmap fromJust . makeBitGet True . computeHuffmanTreeFromCodes . makeHuffmanCodes
|
0967ca6cb6ba5d45daf6f6a5aa0fd3855eed58d28dbea096e2c6b9e52247d88b | vmchale/apple | R.hs | {-# LANGUAGE RankNTypes #-}
module R ( Renames (..)
, HasRenames (..)
, maxLens
, rG
, rE
) where
import A
import Control.Monad.State.Strict (MonadState, runState)
import Data.Bifunctor (second)
import Data.Functor (($>))
import qualified Data.IntMap as IM
import Lens.Micro (Lens')
import Lens.Micro.Mtl (use, (%=), (.=))
import Name
import Ty.Clone
import U
data Renames = Renames { max_ :: Int, bound :: IM.IntMap Int }
class HasRenames a where
rename :: Lens' a Renames
instance HasRenames Renames where
rename = id
maxLens :: Lens' Renames Int
maxLens f s = fmap (\x -> s { max_ = x }) (f (max_ s))
boundLens :: Lens' Renames (IM.IntMap Int)
boundLens f s = fmap (\x -> s { bound = x }) (f (bound s))
mapBound :: (IM.IntMap Int -> IM.IntMap Int) -> Renames -> Renames
mapBound f (Renames m b) = Renames m (f b)
setMax :: Int -> Renames -> Renames
setMax i r = r { max_ = i }
-- Make sure you don't have cycles in the renames map!
replaceUnique :: (MonadState s m, HasRenames s) => U -> m U
replaceUnique u@(U i) = do
rSt <- use (rename.boundLens)
case IM.lookup i rSt of
Nothing -> pure u
Just j -> replaceUnique (U j)
replaceVar :: (MonadState s m, HasRenames s) => Name a -> m (Name a)
replaceVar (Name n u l) = do
u' <- replaceUnique u
pure $ Name n u' l
withRenames :: (HasRenames s, MonadState s m) => (Renames -> Renames) -> m a -> m a
withRenames modSt act = do
preSt <- use rename
rename %= modSt
res <- act
postMax <- use (rename.maxLens)
rename .= setMax postMax preSt
pure res
withName :: (HasRenames s, MonadState s m)
=> Name a
-> m (Name a, Renames -> Renames)
withName (Name t (U i) l) = do
m <- use (rename.maxLens)
let newUniq = m+1
rename.maxLens .= newUniq
pure (Name t (U newUniq) l, mapBound (IM.insert i (m+1)))
-- globally unique
rG :: Int -> E a -> (E a, Int)
rG i = second max_ . flip runState (Renames i IM.empty) . rE
# INLINABLE liftR #
liftR :: (HasRenames s, MonadState s m) => T a -> m (T a)
liftR t = do
i <- use (rename.maxLens)
let (u,t',_) = cloneTClosed i t
(rename.maxLens .= u) $> t'
# INLINABLE rE #
rE :: (HasRenames s, MonadState s m) => E a -> m (E a)
rE (Lam l n e) = do
(n', modR) <- withName n
Lam l n' <$> withRenames modR (rE e)
rE (Let l (n, eϵ) e) = do
eϵ' <- rE eϵ
(n', modR) <- withName n
Let l (n', eϵ') <$> withRenames modR (rE e)
rE (Def l (n, eϵ) e) = do
eϵ' <- rE eϵ
(n', modR) <- withName n
Def l (n', eϵ') <$> withRenames modR (rE e)
rE (LLet l (n, eϵ) e) = do
eϵ' <- rE eϵ
(n', modR) <- withName n
LLet l (n', eϵ') <$> withRenames modR (rE e)
rE e@Builtin{} = pure e
rE e@FLit{} = pure e
rE e@ILit{} = pure e
rE e@BLit{} = pure e
rE (ALit l es) = ALit l <$> traverse rE es
rE (Tup l es) = Tup l <$> traverse rE es
rE (EApp l e e') = EApp l <$> rE e <*> rE e'
rE (Cond l e e' e'') = Cond l <$> rE e <*> rE e' <*> rE e''
rE (Var l n) = Var l <$> replaceVar n
rE (Ann l e t) = Ann l <$> rE e <*> liftR t
rE (Id l (AShLit is es)) = Id l . AShLit is <$> traverse rE es
| null | https://raw.githubusercontent.com/vmchale/apple/ed41443012d6dd2a73edcff10915c0defda0e34b/src/R.hs | haskell | # LANGUAGE RankNTypes #
Make sure you don't have cycles in the renames map!
globally unique |
module R ( Renames (..)
, HasRenames (..)
, maxLens
, rG
, rE
) where
import A
import Control.Monad.State.Strict (MonadState, runState)
import Data.Bifunctor (second)
import Data.Functor (($>))
import qualified Data.IntMap as IM
import Lens.Micro (Lens')
import Lens.Micro.Mtl (use, (%=), (.=))
import Name
import Ty.Clone
import U
data Renames = Renames { max_ :: Int, bound :: IM.IntMap Int }
class HasRenames a where
rename :: Lens' a Renames
instance HasRenames Renames where
rename = id
maxLens :: Lens' Renames Int
maxLens f s = fmap (\x -> s { max_ = x }) (f (max_ s))
boundLens :: Lens' Renames (IM.IntMap Int)
boundLens f s = fmap (\x -> s { bound = x }) (f (bound s))
mapBound :: (IM.IntMap Int -> IM.IntMap Int) -> Renames -> Renames
mapBound f (Renames m b) = Renames m (f b)
setMax :: Int -> Renames -> Renames
setMax i r = r { max_ = i }
replaceUnique :: (MonadState s m, HasRenames s) => U -> m U
replaceUnique u@(U i) = do
rSt <- use (rename.boundLens)
case IM.lookup i rSt of
Nothing -> pure u
Just j -> replaceUnique (U j)
replaceVar :: (MonadState s m, HasRenames s) => Name a -> m (Name a)
replaceVar (Name n u l) = do
u' <- replaceUnique u
pure $ Name n u' l
withRenames :: (HasRenames s, MonadState s m) => (Renames -> Renames) -> m a -> m a
withRenames modSt act = do
preSt <- use rename
rename %= modSt
res <- act
postMax <- use (rename.maxLens)
rename .= setMax postMax preSt
pure res
withName :: (HasRenames s, MonadState s m)
=> Name a
-> m (Name a, Renames -> Renames)
withName (Name t (U i) l) = do
m <- use (rename.maxLens)
let newUniq = m+1
rename.maxLens .= newUniq
pure (Name t (U newUniq) l, mapBound (IM.insert i (m+1)))
rG :: Int -> E a -> (E a, Int)
rG i = second max_ . flip runState (Renames i IM.empty) . rE
# INLINABLE liftR #
liftR :: (HasRenames s, MonadState s m) => T a -> m (T a)
liftR t = do
i <- use (rename.maxLens)
let (u,t',_) = cloneTClosed i t
(rename.maxLens .= u) $> t'
# INLINABLE rE #
rE :: (HasRenames s, MonadState s m) => E a -> m (E a)
rE (Lam l n e) = do
(n', modR) <- withName n
Lam l n' <$> withRenames modR (rE e)
rE (Let l (n, eϵ) e) = do
eϵ' <- rE eϵ
(n', modR) <- withName n
Let l (n', eϵ') <$> withRenames modR (rE e)
rE (Def l (n, eϵ) e) = do
eϵ' <- rE eϵ
(n', modR) <- withName n
Def l (n', eϵ') <$> withRenames modR (rE e)
rE (LLet l (n, eϵ) e) = do
eϵ' <- rE eϵ
(n', modR) <- withName n
LLet l (n', eϵ') <$> withRenames modR (rE e)
rE e@Builtin{} = pure e
rE e@FLit{} = pure e
rE e@ILit{} = pure e
rE e@BLit{} = pure e
rE (ALit l es) = ALit l <$> traverse rE es
rE (Tup l es) = Tup l <$> traverse rE es
rE (EApp l e e') = EApp l <$> rE e <*> rE e'
rE (Cond l e e' e'') = Cond l <$> rE e <*> rE e' <*> rE e''
rE (Var l n) = Var l <$> replaceVar n
rE (Ann l e t) = Ann l <$> rE e <*> liftR t
rE (Id l (AShLit is es)) = Id l . AShLit is <$> traverse rE es
|
933cb23e6c4fdbed6fd75fbcb00a0c75ab4dcca404c0af262b7b4bec1b47408d | OlivierSohn/hamazed | Image.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE LambdaCase #
module Imj.Random.MWC.Image
( mkMWC256Image
, mkMWC256ImageGray
, mkMWC256ImageGray'
, mkMWC256ImageRGB
) where
import Imj.Prelude
import Codec.Picture
import Data.Bits(shiftR)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Storable.Mutable as MS
import Data.Word(Word32)
import System.Random.MWC(uniform)
import Imj.Space.Types
import Imj.Data.AlmostFloat
import Imj.Profile.Result
import Imj.Random.MWC.Util
import Imj.Space
import Imj.Util
mkMWC256Image :: SeedNumber -> Size -> AlmostFloat -> IO (Image Word8)
mkMWC256Image seed sz@(Size (Length h) (Length w)) proba =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew nBlocks
this cuts a random in 4 Word8 , then checks for probability
v <- S.unsafeFreeze mv
return $ generateImage
(\i j ->
case v S.! (i + j*w) of
MaterialAndKey 0xFFFF -> minBound :: Word8
MaterialAndKey _ -> maxBound :: Word8)
w h
genImg _ = error "logic"
mkMWC256ImageGray :: SeedNumber -> Size -> IO (Image Word8)
mkMWC256ImageGray seed sz@(Size (Length h) (Length w)) =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew $ ceilToMultiple 4 nBlocks
forM_ [0..quot nBlocks 4 - 1] $ \i -> do
w32 <- uniform gen :: IO Word32
let w1 = fromIntegral w32 :: Word8
w2 = fromIntegral (w32 `shiftR` 8) :: Word8
w3 = fromIntegral (w32 `shiftR` 16) :: Word8
w4 = fromIntegral (w32 `shiftR` 24) :: Word8
forM_ (zip [4*i..] [w1,w2,w3,w4]) $ uncurry (MS.unsafeWrite mv)
v <- S.unsafeFreeze mv
return $ generateImage
(\i j -> v S.! (i + j*w))
w h
genImg _ = error "logic"
mkMWC256ImageGray' :: SeedNumber -> Size -> IO (Image Word8)
mkMWC256ImageGray' seed sz@(Size (Length h) (Length w)) =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew nBlocks
forM_ [0..nBlocks - 1] $ \i -> do
w32 <- uniform gen :: IO Word32
MS.unsafeWrite mv i $ fromIntegral w32
v <- S.unsafeFreeze mv
return $ generateImage
(\i j -> v S.! (i + j*w))
w h
genImg _ = error "logic"
mkMWC256ImageRGB :: SeedNumber -> Size -> IO (Image PixelRGB8)
mkMWC256ImageRGB seed sz@(Size (Length h) (Length w)) =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew nBlocks
forM_ [0..nBlocks - 1] $ \i -> do
w32 <- uniform gen :: IO Word32
MS.unsafeWrite mv i w32
v <- S.unsafeFreeze mv
return $ generateImage
(\i j ->
let w32 = v S.! (i + j*w)
w1 = fromIntegral w32 :: Word8
w2 = fromIntegral (w32 `shiftR` 8) :: Word8
w3 = fromIntegral (w32 `shiftR` 16) :: Word8
w4 = fromIntegral ( w32 ` shiftR ` 24 ) : : Word8
in PixelRGB8 w1 w2 w3)
w h
genImg _ = error "logic"
| null | https://raw.githubusercontent.com/OlivierSohn/hamazed/c0df1bb60a8538ac75e413d2f5bf0bf050e5bc37/imj-profile/src/Imj/Random/MWC/Image.hs | haskell | # LANGUAGE NoImplicitPrelude #
# LANGUAGE LambdaCase #
module Imj.Random.MWC.Image
( mkMWC256Image
, mkMWC256ImageGray
, mkMWC256ImageGray'
, mkMWC256ImageRGB
) where
import Imj.Prelude
import Codec.Picture
import Data.Bits(shiftR)
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.Vector.Storable as S
import qualified Data.Vector.Storable.Mutable as MS
import Data.Word(Word32)
import System.Random.MWC(uniform)
import Imj.Space.Types
import Imj.Data.AlmostFloat
import Imj.Profile.Result
import Imj.Random.MWC.Util
import Imj.Space
import Imj.Util
mkMWC256Image :: SeedNumber -> Size -> AlmostFloat -> IO (Image Word8)
mkMWC256Image seed sz@(Size (Length h) (Length w)) proba =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew nBlocks
this cuts a random in 4 Word8 , then checks for probability
v <- S.unsafeFreeze mv
return $ generateImage
(\i j ->
case v S.! (i + j*w) of
MaterialAndKey 0xFFFF -> minBound :: Word8
MaterialAndKey _ -> maxBound :: Word8)
w h
genImg _ = error "logic"
mkMWC256ImageGray :: SeedNumber -> Size -> IO (Image Word8)
mkMWC256ImageGray seed sz@(Size (Length h) (Length w)) =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew $ ceilToMultiple 4 nBlocks
forM_ [0..quot nBlocks 4 - 1] $ \i -> do
w32 <- uniform gen :: IO Word32
let w1 = fromIntegral w32 :: Word8
w2 = fromIntegral (w32 `shiftR` 8) :: Word8
w3 = fromIntegral (w32 `shiftR` 16) :: Word8
w4 = fromIntegral (w32 `shiftR` 24) :: Word8
forM_ (zip [4*i..] [w1,w2,w3,w4]) $ uncurry (MS.unsafeWrite mv)
v <- S.unsafeFreeze mv
return $ generateImage
(\i j -> v S.! (i + j*w))
w h
genImg _ = error "logic"
mkMWC256ImageGray' :: SeedNumber -> Size -> IO (Image Word8)
mkMWC256ImageGray' seed sz@(Size (Length h) (Length w)) =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew nBlocks
forM_ [0..nBlocks - 1] $ \i -> do
w32 <- uniform gen :: IO Word32
MS.unsafeWrite mv i $ fromIntegral w32
v <- S.unsafeFreeze mv
return $ generateImage
(\i j -> v S.! (i + j*w))
w h
genImg _ = error "logic"
mkMWC256ImageRGB :: SeedNumber -> Size -> IO (Image PixelRGB8)
mkMWC256ImageRGB seed sz@(Size (Length h) (Length w)) =
withNumberedSeeds genImg (pure seed)
where
nBlocks = area sz
genImg (gen:|[]) = do
mv <- MS.unsafeNew nBlocks
forM_ [0..nBlocks - 1] $ \i -> do
w32 <- uniform gen :: IO Word32
MS.unsafeWrite mv i w32
v <- S.unsafeFreeze mv
return $ generateImage
(\i j ->
let w32 = v S.! (i + j*w)
w1 = fromIntegral w32 :: Word8
w2 = fromIntegral (w32 `shiftR` 8) :: Word8
w3 = fromIntegral (w32 `shiftR` 16) :: Word8
w4 = fromIntegral ( w32 ` shiftR ` 24 ) : : Word8
in PixelRGB8 w1 w2 w3)
w h
genImg _ = error "logic"
|
|
4f065d49ebe4973ffd3a3d13da4f348d340fcb44ffba93e00d414084e326a5cb | TyOverby/mono | test_to_string.ml | open! Core
open! Import
let show ?filter_printed_attributes node =
let t = node |> Node_helpers.unsafe_convert_exn in
t |> [%sexp_of: Node_helpers.t] |> print_s;
print_endline "----------------------";
t |> Node_helpers.to_string_html ?filter_printed_attributes |> print_endline
;;
let%expect_test "basic text" =
show (Node.text "hello");
[%expect {|
(Text hello)
----------------------
hello |}]
;;
let%expect_test "empty div" =
show (Node.div []);
[%expect
{|
(Element ((tag_name div)))
----------------------
<div> </div> |}]
;;
let%expect_test "empty div" =
show (Node.div []);
[%expect
{|
(Element ((tag_name div)))
----------------------
<div> </div> |}]
;;
let%expect_test "inner_html" =
show
(Node.inner_html
~tag:"div"
~attr:Attr.empty
~this_html_is_sanitized_and_is_totally_safe_trust_me:"<b>hi</b>");
[%expect
{|
(Widget (inner-html div <b>hi</b>))
----------------------
<widget (inner-html div <b>hi</b>) /> |}]
;;
let%expect_test "div with some text" =
show (Node.div [ Node.text "hello world" ]);
[%expect
{|
(Element ((tag_name div) (children ((Text "hello world")))))
----------------------
<div> hello world </div> |}]
;;
let%expect_test "empty div with key" =
show (Node.div ~key:"keykey" []);
[%expect
{|
(Element ((tag_name div) (key keykey)))
----------------------
<div @key=keykey> </div> |}]
;;
let%expect_test "empty div with string property" =
show (Node.div ~attr:(Attr.string_property "foo" "bar") []);
[%expect
{|
(Element ((tag_name div) (string_properties ((foo bar)))))
----------------------
<div #foo="bar"> </div> |}]
;;
let%expect_test "empty div with bool property" =
show (Node.div ~attr:(Attr.bool_property "foo" true) []);
[%expect
{|
(Element ((tag_name div) (bool_properties ((foo true)))))
----------------------
<div #foo="true"> </div> |}]
;;
let%expect_test "nested div with span" =
show (Node.div [ Node.span [] ]);
[%expect
{|
(Element ((tag_name div) (children ((Element ((tag_name span)))))))
----------------------
<div>
<span> </span>
</div> |}]
;;
let%expect_test "empty div with string attribute" =
show (Node.div ~attr:(Attr.create "key" "value") []);
[%expect
{|
(Element ((tag_name div) (attributes ((key value)))))
----------------------
<div key="value"> </div> |}]
;;
let%expect_test "empty div with float attribute" =
show (Node.div ~attr:(Attr.create_float "some_attr" 1.2345) []);
[%expect
{|
(Element ((tag_name div) (attributes ((some_attr 1.2345)))))
----------------------
<div some_attr="1.2345"> </div> |}]
;;
let%expect_test "widget" =
let widget =
Node.widget
~id:(Type_equal.Id.create ~name:"name_goes_here" [%sexp_of: opaque])
~init:(fun _ -> failwith "unreachable")
()
in
show widget;
[%expect
{|
(Widget name_goes_here)
----------------------
<widget name_goes_here /> |}]
;;
let%expect_test "widget inside of something else" =
let widget =
Node.div
[ Node.widget
~id:(Type_equal.Id.create ~name:"name_goes_here" [%sexp_of: opaque])
~init:(fun _ -> failwith "unreachable")
()
]
in
show widget;
[%expect
{|
(Element ((tag_name div) (children ((Widget name_goes_here)))))
----------------------
<div>
<widget name_goes_here />
</div> |}]
;;
let%expect_test "widget with info" =
let widget =
Node.widget
~info:(lazy (Sexp.Atom "info name"))
~id:(Type_equal.Id.create ~name:"name_goes_here" [%sexp_of: opaque])
~init:(fun _ -> failwith "unreachable")
()
in
show widget;
[%expect
{|
(Widget "info name")
----------------------
<widget "info name" /> |}]
;;
let%expect_test "empty div with callback" =
show (Node.div ~attr:(Attr.on_click (Fn.const Effect.Ignore)) []);
[%expect
{|
(Element ((tag_name div) (handlers ((onclick <handler>)))))
----------------------
<div onclick> </div> |}]
;;
let%expect_test "empty div with class list" =
show (Node.div ~attr:(Attr.classes [ "a"; "b"; "c" ]) []);
[%expect
{|
(Element ((tag_name div) (attributes ((class "a b c")))))
----------------------
<div class="a b c"> </div> |}]
;;
let%expect_test "empty div with id" =
show (Node.div ~attr:(Attr.id "my-id") []);
[%expect
{|
(Element ((tag_name div) (attributes ((id my-id)))))
----------------------
<div id="my-id"> </div> |}]
;;
let%expect_test "later attributes override earlier ones" =
show
(Node.div ~attr:Attr.(many_without_merge [ id "overwritten-id"; id "final-id" ]) []);
[%expect
{|
("WARNING: not combining attributes" (name id))
(Element ((tag_name div) (attributes ((id final-id)))))
----------------------
<div id="final-id"> </div> |}]
;;
let%expect_test "later properties override earlier ones" =
show
(Node.div
~attr:
Attr.(
many_without_merge
[ string_property "prop" "overwritten-prop"
; string_property "prop" "final-prop"
])
[]);
[%expect
{|
("WARNING: not combining properties" (name prop))
(Element ((tag_name div) (string_properties ((prop final-prop)))))
----------------------
<div #prop="final-prop"> </div> |}]
;;
let%expect_test "no merging without [many]" =
show
(Node.div ~attr:Attr.(many_without_merge [ class_ "a"; class_ "b"; class_ "c" ]) []);
[%expect
{|
("WARNING: not combining classes" (first (a)) (second (b)))
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class c)))))
----------------------
<div class="c"> </div> |}]
;;
let%expect_test "merging only within [many]" =
show
(Node.div
~attr:Attr.(many_without_merge [ class_ "a"; class_ "b"; many [ class_ "c" ] ])
[]);
[%expect
{|
("WARNING: not combining classes" (first (a)) (second (b)))
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class c)))))
----------------------
<div class="c"> </div> |}]
;;
let%expect_test "empty div with [many] classes" =
show
(Node.div ~attr:(Attr.many [ Attr.class_ "a"; Attr.class_ "b"; Attr.class_ "c" ]) []);
[%expect
{|
(Element ((tag_name div) (attributes ((class "a b c")))))
----------------------
<div class="a b c"> </div> |}]
;;
let%expect_test "empty div with [many] different attributes" =
show
(Node.div
~attr:
(Attr.many
[ Attr.class_ "a"
; Attr.on_click (fun _ -> Ui_effect.Ignore)
; Attr.style Css_gen.bold
; Attr.class_ "b"
; Attr.style (Css_gen.z_index 42)
; Attr.id "my-id"
; Attr.class_ "c"
; Attr.Always_focus_hook.attr `Read_the_docs__this_hook_is_unpredictable
; Attr.style (Css_gen.display `Table)
; Attr.class_ "d"
; Attr.on_click (fun _ -> Ui_effect.Ignore)
; Attr.Always_focus_hook.attr `Read_the_docs__this_hook_is_unpredictable
])
[]);
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (class "a b c d")))
(styles ((font-weight bold) (z-index 42) (display table)))
(handlers ((onclick <handler>))) (hooks ((always-focus-hook ())))))
----------------------
<div id="my-id"
class="a b c d"
always-focus-hook=()
onclick
style={
font-weight: bold;
z-index: 42;
display: table;
}> </div> |}]
;;
let%expect_test "empty div with tree of nested [many]" =
show
(Node.div
~attr:
(Attr.many
[ Attr.many [ Attr.class_ "a"; Attr.style (Css_gen.text_align `Center) ]
; Attr.many [ Attr.many [ Attr.class_ "b"; Attr.class_ "c" ] ]
; Attr.many
[ Attr.many
[ Attr.many
[ Attr.id "my-id"; Attr.style (Css_gen.box_sizing `Border_box) ]
]
]
])
[]);
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (class "a b c")))
(styles ((text-align center) (box-sizing border-box)))))
----------------------
<div id="my-id" class="a b c" style={ text-align: center; box-sizing: border-box; }> </div> |}]
;;
let%expect_test "empty div with [many] different attributes" =
let view =
Node.div
~attr:
Attr.(
many_without_merge
[ class_ "a"
; on_click (fun _ -> Ui_effect.Ignore)
; on_blur (fun _ -> Ui_effect.Ignore)
; style Css_gen.bold
; id "my-id"
; checked
])
[]
in
show ~filter_printed_attributes:(String.is_prefix ~prefix:"on") view;
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (checked "") (class a)))
(styles ((font-weight bold)))
(handlers ((onblur <handler>) (onclick <handler>)))))
----------------------
<div onblur onclick> </div> |}];
show
~filter_printed_attributes:(fun attribute ->
not (String.is_prefix ~prefix:"on" attribute))
view;
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (checked "") (class a)))
(styles ((font-weight bold)))
(handlers ((onblur <handler>) (onclick <handler>)))))
----------------------
<div id="my-id" checked="" class="a" style={ font-weight: bold; }> </div> |}]
;;
let%expect_test "[many_without_merge] inside merge" =
let view =
Node.div
~attr:Attr.(class_ "a" @ many_without_merge [ class_ "b"; class_ "c" ] @ class_ "d")
[]
in
show view;
[%expect
{|
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class "a c d")))))
----------------------
<div class="a c d"> </div> |}];
let view =
Node.div
~attr:
Attr.(
many_without_merge
(Multi.merge_classes_and_styles
[ class_ "a"; many_without_merge [ class_ "b"; class_ "c" ]; class_ "d" ]))
[]
in
show view;
[%expect
{|
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class "a c d")))))
----------------------
<div class="a c d"> </div> |}];
let view =
Node.div
~attr:
Attr.(
class_ "a"
@ many_without_merge
[ class_ "b"
; class_ "ba" @ class_ "bb"
; class_ "c" @ many_without_merge [ class_ "baa"; class_ "bab" ]
]
@ class_ "d")
[]
in
show view;
[%expect
{|
("WARNING: not combining classes" (first (b)) (second (ba bb)))
("WARNING: not combining classes" (first (baa)) (second (bab)))
("WARNING: not combining classes" (first (ba bb)) (second (bab c)))
(Element ((tag_name div) (attributes ((class "a bab c d")))))
----------------------
<div class="a bab c d"> </div> |}]
;;
let%expect_test "combining hooks" =
let module H =
Virtual_dom.Vdom.Attr.Hooks.Make (struct
module State = Unit
module Input = struct
type t = string list [@@deriving sexp_of]
let combine a b =
print_endline "in combine";
a @ b
;;
end
let init _ _ = ()
let on_mount _ () _ = ()
let update ~old_input:_ ~new_input:_ () _ = ()
let destroy _ () _ = ()
end)
in
let make s = Attr.create_hook "my-hook" (H.create [ s ]) in
show (Node.div ~attr:Attr.(class_ "x" @ make "hello" @ make "world") []);
[%expect
{|
in combine
(Element
((tag_name div) (attributes ((class x))) (hooks ((my-hook (hello world))))))
----------------------
<div class="x" my-hook=(hello world)> </div> |}]
;;
| null | https://raw.githubusercontent.com/TyOverby/mono/8d6b3484d5db63f2f5472c7367986ea30290764d/vendor/janestreet-virtual_dom/test/test_to_string.ml | ocaml | open! Core
open! Import
let show ?filter_printed_attributes node =
let t = node |> Node_helpers.unsafe_convert_exn in
t |> [%sexp_of: Node_helpers.t] |> print_s;
print_endline "----------------------";
t |> Node_helpers.to_string_html ?filter_printed_attributes |> print_endline
;;
let%expect_test "basic text" =
show (Node.text "hello");
[%expect {|
(Text hello)
----------------------
hello |}]
;;
let%expect_test "empty div" =
show (Node.div []);
[%expect
{|
(Element ((tag_name div)))
----------------------
<div> </div> |}]
;;
let%expect_test "empty div" =
show (Node.div []);
[%expect
{|
(Element ((tag_name div)))
----------------------
<div> </div> |}]
;;
let%expect_test "inner_html" =
show
(Node.inner_html
~tag:"div"
~attr:Attr.empty
~this_html_is_sanitized_and_is_totally_safe_trust_me:"<b>hi</b>");
[%expect
{|
(Widget (inner-html div <b>hi</b>))
----------------------
<widget (inner-html div <b>hi</b>) /> |}]
;;
let%expect_test "div with some text" =
show (Node.div [ Node.text "hello world" ]);
[%expect
{|
(Element ((tag_name div) (children ((Text "hello world")))))
----------------------
<div> hello world </div> |}]
;;
let%expect_test "empty div with key" =
show (Node.div ~key:"keykey" []);
[%expect
{|
(Element ((tag_name div) (key keykey)))
----------------------
<div @key=keykey> </div> |}]
;;
let%expect_test "empty div with string property" =
show (Node.div ~attr:(Attr.string_property "foo" "bar") []);
[%expect
{|
(Element ((tag_name div) (string_properties ((foo bar)))))
----------------------
<div #foo="bar"> </div> |}]
;;
let%expect_test "empty div with bool property" =
show (Node.div ~attr:(Attr.bool_property "foo" true) []);
[%expect
{|
(Element ((tag_name div) (bool_properties ((foo true)))))
----------------------
<div #foo="true"> </div> |}]
;;
let%expect_test "nested div with span" =
show (Node.div [ Node.span [] ]);
[%expect
{|
(Element ((tag_name div) (children ((Element ((tag_name span)))))))
----------------------
<div>
<span> </span>
</div> |}]
;;
let%expect_test "empty div with string attribute" =
show (Node.div ~attr:(Attr.create "key" "value") []);
[%expect
{|
(Element ((tag_name div) (attributes ((key value)))))
----------------------
<div key="value"> </div> |}]
;;
let%expect_test "empty div with float attribute" =
show (Node.div ~attr:(Attr.create_float "some_attr" 1.2345) []);
[%expect
{|
(Element ((tag_name div) (attributes ((some_attr 1.2345)))))
----------------------
<div some_attr="1.2345"> </div> |}]
;;
let%expect_test "widget" =
let widget =
Node.widget
~id:(Type_equal.Id.create ~name:"name_goes_here" [%sexp_of: opaque])
~init:(fun _ -> failwith "unreachable")
()
in
show widget;
[%expect
{|
(Widget name_goes_here)
----------------------
<widget name_goes_here /> |}]
;;
let%expect_test "widget inside of something else" =
let widget =
Node.div
[ Node.widget
~id:(Type_equal.Id.create ~name:"name_goes_here" [%sexp_of: opaque])
~init:(fun _ -> failwith "unreachable")
()
]
in
show widget;
[%expect
{|
(Element ((tag_name div) (children ((Widget name_goes_here)))))
----------------------
<div>
<widget name_goes_here />
</div> |}]
;;
let%expect_test "widget with info" =
let widget =
Node.widget
~info:(lazy (Sexp.Atom "info name"))
~id:(Type_equal.Id.create ~name:"name_goes_here" [%sexp_of: opaque])
~init:(fun _ -> failwith "unreachable")
()
in
show widget;
[%expect
{|
(Widget "info name")
----------------------
<widget "info name" /> |}]
;;
let%expect_test "empty div with callback" =
show (Node.div ~attr:(Attr.on_click (Fn.const Effect.Ignore)) []);
[%expect
{|
(Element ((tag_name div) (handlers ((onclick <handler>)))))
----------------------
<div onclick> </div> |}]
;;
let%expect_test "empty div with class list" =
show (Node.div ~attr:(Attr.classes [ "a"; "b"; "c" ]) []);
[%expect
{|
(Element ((tag_name div) (attributes ((class "a b c")))))
----------------------
<div class="a b c"> </div> |}]
;;
let%expect_test "empty div with id" =
show (Node.div ~attr:(Attr.id "my-id") []);
[%expect
{|
(Element ((tag_name div) (attributes ((id my-id)))))
----------------------
<div id="my-id"> </div> |}]
;;
let%expect_test "later attributes override earlier ones" =
show
(Node.div ~attr:Attr.(many_without_merge [ id "overwritten-id"; id "final-id" ]) []);
[%expect
{|
("WARNING: not combining attributes" (name id))
(Element ((tag_name div) (attributes ((id final-id)))))
----------------------
<div id="final-id"> </div> |}]
;;
let%expect_test "later properties override earlier ones" =
show
(Node.div
~attr:
Attr.(
many_without_merge
[ string_property "prop" "overwritten-prop"
; string_property "prop" "final-prop"
])
[]);
[%expect
{|
("WARNING: not combining properties" (name prop))
(Element ((tag_name div) (string_properties ((prop final-prop)))))
----------------------
<div #prop="final-prop"> </div> |}]
;;
let%expect_test "no merging without [many]" =
show
(Node.div ~attr:Attr.(many_without_merge [ class_ "a"; class_ "b"; class_ "c" ]) []);
[%expect
{|
("WARNING: not combining classes" (first (a)) (second (b)))
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class c)))))
----------------------
<div class="c"> </div> |}]
;;
let%expect_test "merging only within [many]" =
show
(Node.div
~attr:Attr.(many_without_merge [ class_ "a"; class_ "b"; many [ class_ "c" ] ])
[]);
[%expect
{|
("WARNING: not combining classes" (first (a)) (second (b)))
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class c)))))
----------------------
<div class="c"> </div> |}]
;;
let%expect_test "empty div with [many] classes" =
show
(Node.div ~attr:(Attr.many [ Attr.class_ "a"; Attr.class_ "b"; Attr.class_ "c" ]) []);
[%expect
{|
(Element ((tag_name div) (attributes ((class "a b c")))))
----------------------
<div class="a b c"> </div> |}]
;;
let%expect_test "empty div with [many] different attributes" =
show
(Node.div
~attr:
(Attr.many
[ Attr.class_ "a"
; Attr.on_click (fun _ -> Ui_effect.Ignore)
; Attr.style Css_gen.bold
; Attr.class_ "b"
; Attr.style (Css_gen.z_index 42)
; Attr.id "my-id"
; Attr.class_ "c"
; Attr.Always_focus_hook.attr `Read_the_docs__this_hook_is_unpredictable
; Attr.style (Css_gen.display `Table)
; Attr.class_ "d"
; Attr.on_click (fun _ -> Ui_effect.Ignore)
; Attr.Always_focus_hook.attr `Read_the_docs__this_hook_is_unpredictable
])
[]);
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (class "a b c d")))
(styles ((font-weight bold) (z-index 42) (display table)))
(handlers ((onclick <handler>))) (hooks ((always-focus-hook ())))))
----------------------
<div id="my-id"
class="a b c d"
always-focus-hook=()
onclick
style={
font-weight: bold;
z-index: 42;
display: table;
}> </div> |}]
;;
let%expect_test "empty div with tree of nested [many]" =
show
(Node.div
~attr:
(Attr.many
[ Attr.many [ Attr.class_ "a"; Attr.style (Css_gen.text_align `Center) ]
; Attr.many [ Attr.many [ Attr.class_ "b"; Attr.class_ "c" ] ]
; Attr.many
[ Attr.many
[ Attr.many
[ Attr.id "my-id"; Attr.style (Css_gen.box_sizing `Border_box) ]
]
]
])
[]);
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (class "a b c")))
(styles ((text-align center) (box-sizing border-box)))))
----------------------
<div id="my-id" class="a b c" style={ text-align: center; box-sizing: border-box; }> </div> |}]
;;
let%expect_test "empty div with [many] different attributes" =
let view =
Node.div
~attr:
Attr.(
many_without_merge
[ class_ "a"
; on_click (fun _ -> Ui_effect.Ignore)
; on_blur (fun _ -> Ui_effect.Ignore)
; style Css_gen.bold
; id "my-id"
; checked
])
[]
in
show ~filter_printed_attributes:(String.is_prefix ~prefix:"on") view;
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (checked "") (class a)))
(styles ((font-weight bold)))
(handlers ((onblur <handler>) (onclick <handler>)))))
----------------------
<div onblur onclick> </div> |}];
show
~filter_printed_attributes:(fun attribute ->
not (String.is_prefix ~prefix:"on" attribute))
view;
[%expect
{|
(Element
((tag_name div) (attributes ((id my-id) (checked "") (class a)))
(styles ((font-weight bold)))
(handlers ((onblur <handler>) (onclick <handler>)))))
----------------------
<div id="my-id" checked="" class="a" style={ font-weight: bold; }> </div> |}]
;;
let%expect_test "[many_without_merge] inside merge" =
let view =
Node.div
~attr:Attr.(class_ "a" @ many_without_merge [ class_ "b"; class_ "c" ] @ class_ "d")
[]
in
show view;
[%expect
{|
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class "a c d")))))
----------------------
<div class="a c d"> </div> |}];
let view =
Node.div
~attr:
Attr.(
many_without_merge
(Multi.merge_classes_and_styles
[ class_ "a"; many_without_merge [ class_ "b"; class_ "c" ]; class_ "d" ]))
[]
in
show view;
[%expect
{|
("WARNING: not combining classes" (first (b)) (second (c)))
(Element ((tag_name div) (attributes ((class "a c d")))))
----------------------
<div class="a c d"> </div> |}];
let view =
Node.div
~attr:
Attr.(
class_ "a"
@ many_without_merge
[ class_ "b"
; class_ "ba" @ class_ "bb"
; class_ "c" @ many_without_merge [ class_ "baa"; class_ "bab" ]
]
@ class_ "d")
[]
in
show view;
[%expect
{|
("WARNING: not combining classes" (first (b)) (second (ba bb)))
("WARNING: not combining classes" (first (baa)) (second (bab)))
("WARNING: not combining classes" (first (ba bb)) (second (bab c)))
(Element ((tag_name div) (attributes ((class "a bab c d")))))
----------------------
<div class="a bab c d"> </div> |}]
;;
let%expect_test "combining hooks" =
let module H =
Virtual_dom.Vdom.Attr.Hooks.Make (struct
module State = Unit
module Input = struct
type t = string list [@@deriving sexp_of]
let combine a b =
print_endline "in combine";
a @ b
;;
end
let init _ _ = ()
let on_mount _ () _ = ()
let update ~old_input:_ ~new_input:_ () _ = ()
let destroy _ () _ = ()
end)
in
let make s = Attr.create_hook "my-hook" (H.create [ s ]) in
show (Node.div ~attr:Attr.(class_ "x" @ make "hello" @ make "world") []);
[%expect
{|
in combine
(Element
((tag_name div) (attributes ((class x))) (hooks ((my-hook (hello world))))))
----------------------
<div class="x" my-hook=(hello world)> </div> |}]
;;
|
|
19b814dfe218d5e36847355325b109138aaaf2af5dd3e2b2bf44a87ac77aa923 | PrecursorApp/precursor | colors.cljs | (ns frontend.colors
(:require [clojure.string :as str]))
;; Note that these are ordered so that next-color will choose
;; a color with high contrast to the previous color
(def color-idents
[:color.name/red
:color.name/cyan
:color.name/purple
:color.name/orange
:color.name/blue
:color.name/yellow
:color.name/pink
:color.name/green])
(defn next-color [choices current-color]
(let [n (inc (count (take-while #(not= current-color %) choices)))]
(nth choices (mod n (count choices)))))
(defn uuid-part->long [uuid-part]
(js/parseInt (str "0x" uuid-part) 16))
(defn choose-from-uuid [choices uuid]
(let [parts (str/split (str uuid) #"-")
num (-> (uuid-part->long (first parts))
(bit-shift-left 16)
(bit-or (uuid-part->long (second parts)))
(bit-shift-left 16)
(bit-or (uuid-part->long (nth parts 2))))]
(nth choices (mod (js/Math.abs num) (count choices)))))
(defn find-color [uuid->cust cust-uuid alt-uuid]
(or (get-in uuid->cust [cust-uuid :cust/color-name])
(if alt-uuid ;; handles old chats that are missing a session/uuid
(choose-from-uuid color-idents alt-uuid)
:color.name/gray)))
| null | https://raw.githubusercontent.com/PrecursorApp/precursor/30202e40365f6883c4767e423d6299f0d13dc528/src-cljs/frontend/colors.cljs | clojure | Note that these are ordered so that next-color will choose
a color with high contrast to the previous color
handles old chats that are missing a session/uuid | (ns frontend.colors
(:require [clojure.string :as str]))
(def color-idents
[:color.name/red
:color.name/cyan
:color.name/purple
:color.name/orange
:color.name/blue
:color.name/yellow
:color.name/pink
:color.name/green])
(defn next-color [choices current-color]
(let [n (inc (count (take-while #(not= current-color %) choices)))]
(nth choices (mod n (count choices)))))
(defn uuid-part->long [uuid-part]
(js/parseInt (str "0x" uuid-part) 16))
(defn choose-from-uuid [choices uuid]
(let [parts (str/split (str uuid) #"-")
num (-> (uuid-part->long (first parts))
(bit-shift-left 16)
(bit-or (uuid-part->long (second parts)))
(bit-shift-left 16)
(bit-or (uuid-part->long (nth parts 2))))]
(nth choices (mod (js/Math.abs num) (count choices)))))
(defn find-color [uuid->cust cust-uuid alt-uuid]
(or (get-in uuid->cust [cust-uuid :cust/color-name])
(choose-from-uuid color-idents alt-uuid)
:color.name/gray)))
|
7b4e22ebcae50507a72740832036b8ad6234ccdeec4b0d3edabd1cc030dc9bbd | hyperfiddle/electric | api.cljc | (ns hyperfiddle.api
#?(:cljs (:require-macros [hyperfiddle.api :refer [hfql]]))
(:import [hyperfiddle.electric Pending]
#?(:cljs [goog.math Long]))
(:require clojure.edn
[contrib.dynamic :refer [call-sym]]
[clojure.spec.alpha :as s]
[hyperfiddle.hfql :as hfql]
[hyperfiddle.electric :as e]
[missionary.core :as m]
hyperfiddle.electric-dom2))
dbval , for REPL usage . Available in cljs for HFQL datascript tests
(e/def db "inject database value for hyperfiddle stage and HFQL")
(s/def ::ref? any?)
(e/def secure-db "database value excluding stage, so that user can't tamper")
(e/def with "inject datomic.api/with or equivalent, used by stage")
(e/def into-tx')
(def -read-edn-str-default (partial clojure.edn/read-string
datomic cloud long ids
:clj {})}))
avoid Electric warning about goog.math . Long
(e/def ^:dynamic *nav!*)
([query] `(hfql/hfql ~query))
([bindings query] `(hfql/hfql ~bindings ~query))
([bindings query eid] `(hfql/hfql ~bindings ~query ~eid)))
(e/def Render hfql/Render)
Database
(def db-state #?(:clj (atom nil))) ; Server side only
(e/def db-name)
(e/def schema "pre-fetched schema for explorer")
(e/def ^{:dynamic true, :doc "To be bound to a function [db attribute] -> schema"} *schema*)
(e/def ^{:dynamic true, :doc "To be bound to a function schema -> ::hf/one | ::hf/many"} *cardinality*
(fn cardinality [schemaf db attr]
(let [card
({:db.cardinality/one ::one
:db.cardinality/many ::many} (:db/cardinality (schemaf db attr)))]
card)))
(defn entity [ctx] (or (::entity ctx) (::entity (::parent ctx))))
(defn attribute [ctx] (or (::attribute ctx) (::attribute (::parent ctx))))
(e/def validation-hints nil)
(e/defn tx "WIP, this default impl captures the essence" [v' props] ; meant to be called by a renderer
Does it return a tx or side - effect to the staging area ?
(assert false "TBD")
provided by ( props ... { : : hf / tx ( p / fn [ ] ... ) } )
(Txfn. v')
(when v'
context is a stack of [ [ E a ] ... ] in dynamic scope ; MISSING today
[[:db/add (E.) a v']]))))
(defmulti tx-meta (fn [schema tx] (if (map? tx) ::map (first tx))))
(s/def ::tx-cardinality (s/or :one :many))
(s/def ::tx-identifier map?)
(s/def ::tx-inverse fn?)
(s/def ::tx-special fn?)
(s/def ::transaction-meta (s/keys :req [::tx-identifier]
:opt [::tx-cardinality ::tx-inverse ::tx-special
::tx-conflicting?]))
(s/fdef tx-meta :ret ::transaction-meta)
; resolve cycle - hyperfiddle.txn needs hf/tx-meta
#?(:clj (require 'hyperfiddle.txn)) ; [rosie] before rcf turns on due to test/seattle undefined
#?(:clj (defn expand-hf-tx [tx] (call-sym 'hyperfiddle.txn/expand-hf-tx tx)))
# ? (:
; (defmacro into-tx
( [ ] ` ( call - sym ~'hyperfiddle.txn / into - tx ~hyperfiddle.api / schema ~tx ~tx ' ) ) ; Electric call can infer schema
( [ schema ] ` ( call - sym ~'hyperfiddle.txn / into - tx ~schema ~tx ~tx ' ) ) ) ; clojure compatible call
; :cljs (def into-tx nil))
#?(:clj (defn into-tx
( [ ] ( into - tx schema ) ) -- needs Electric->Clojure binding conveyance
([schema tx tx'] (call-sym 'hyperfiddle.txn/into-tx schema tx tx'))))
(e/defn Transact!* [!t tx] ; colorless, !t on server
; need the flattening be atomic?
stabilize first loop ( optional )
(new (e/task->cp
;; workaround: Datomic doesn't handle a thread interrupt correctly
(m/compel
(m/via m/blk
;; return basis-t ?
(swap! !t (fn [[db tx0]]
injected datomic dep
(into-tx' schema tx0 tx)]))))))) ; datascript is different
(e/def Transact!) ; server
(e/def stage) ; server
(e/def loading) ; client
(e/defn Load-timer []
(e/client
(let [[x] (e/with-cycle [[elapsed start :as s] [0 nil]]
(case hyperfiddle.api/loading
true [(some->> start (- e/system-time-ms))
(js/Date.now)]
s))]
x)))
(e/defn Branch [Body-server] ; todo colorless
(e/server
(let [!ret (atom nil)
!t (atom #_::unknown [db []])
[db stage] (e/watch !t)]
(binding [hyperfiddle.api/db db
hyperfiddle.api/stage stage
hyperfiddle.api/Transact! (e/fn [tx]
#_(println "Transact! " (hash !t) "committing: " tx)
(let [r (Transact!*. !t tx)]
#_(println "Transact! " (hash !t) "commit result: " r)))]
(e/client
(e/with-cycle [loading false]
(binding [hyperfiddle.api/loading loading]
#_(dom/div (name loading) " " (str (Load-timer.)) "ms")
(try
(e/server
(let [x (Body-server.)] ; cycle x?
#_(println 'Branch x)
(reset! !ret x))) ; if the body returns something, return it. (Likely not used)
false (catch Pending e true))))
nil))
(e/watch !ret)))) ; do we need this? Popover using it currently
(defmacro branch [& body] `(new Branch (e/fn [] ~@body)))
(def ^:dynamic *http-request* "Bound to the HTTP request of the page in which the current Electric program is running." nil)
(e/def page-drop -1)
(e/def page-take -1)
(e/defn Paginate [xs]
(if (coll? xs)
(cond->> xs
(pos-int? page-drop) (drop page-drop)
(pos-int? page-take) (take page-take))
xs))
| null | https://raw.githubusercontent.com/hyperfiddle/electric/a057d75280fecac4c0667a4fa8d4c182b9363fb8/src/hyperfiddle/api.cljc | clojure | Server side only
meant to be called by a renderer
MISSING today
resolve cycle - hyperfiddle.txn needs hf/tx-meta
[rosie] before rcf turns on due to test/seattle undefined
(defmacro into-tx
Electric call can infer schema
clojure compatible call
:cljs (def into-tx nil))
colorless, !t on server
need the flattening be atomic?
workaround: Datomic doesn't handle a thread interrupt correctly
return basis-t ?
datascript is different
server
server
client
todo colorless
cycle x?
if the body returns something, return it. (Likely not used)
do we need this? Popover using it currently | (ns hyperfiddle.api
#?(:cljs (:require-macros [hyperfiddle.api :refer [hfql]]))
(:import [hyperfiddle.electric Pending]
#?(:cljs [goog.math Long]))
(:require clojure.edn
[contrib.dynamic :refer [call-sym]]
[clojure.spec.alpha :as s]
[hyperfiddle.hfql :as hfql]
[hyperfiddle.electric :as e]
[missionary.core :as m]
hyperfiddle.electric-dom2))
dbval , for REPL usage . Available in cljs for HFQL datascript tests
(e/def db "inject database value for hyperfiddle stage and HFQL")
(s/def ::ref? any?)
(e/def secure-db "database value excluding stage, so that user can't tamper")
(e/def with "inject datomic.api/with or equivalent, used by stage")
(e/def into-tx')
(def -read-edn-str-default (partial clojure.edn/read-string
datomic cloud long ids
:clj {})}))
avoid Electric warning about goog.math . Long
(e/def ^:dynamic *nav!*)
([query] `(hfql/hfql ~query))
([bindings query] `(hfql/hfql ~bindings ~query))
([bindings query eid] `(hfql/hfql ~bindings ~query ~eid)))
(e/def Render hfql/Render)
Database
(e/def db-name)
(e/def schema "pre-fetched schema for explorer")
(e/def ^{:dynamic true, :doc "To be bound to a function [db attribute] -> schema"} *schema*)
(e/def ^{:dynamic true, :doc "To be bound to a function schema -> ::hf/one | ::hf/many"} *cardinality*
(fn cardinality [schemaf db attr]
(let [card
({:db.cardinality/one ::one
:db.cardinality/many ::many} (:db/cardinality (schemaf db attr)))]
card)))
(defn entity [ctx] (or (::entity ctx) (::entity (::parent ctx))))
(defn attribute [ctx] (or (::attribute ctx) (::attribute (::parent ctx))))
(e/def validation-hints nil)
Does it return a tx or side - effect to the staging area ?
(assert false "TBD")
provided by ( props ... { : : hf / tx ( p / fn [ ] ... ) } )
(Txfn. v')
(when v'
[[:db/add (E.) a v']]))))
(defmulti tx-meta (fn [schema tx] (if (map? tx) ::map (first tx))))
(s/def ::tx-cardinality (s/or :one :many))
(s/def ::tx-identifier map?)
(s/def ::tx-inverse fn?)
(s/def ::tx-special fn?)
(s/def ::transaction-meta (s/keys :req [::tx-identifier]
:opt [::tx-cardinality ::tx-inverse ::tx-special
::tx-conflicting?]))
(s/fdef tx-meta :ret ::transaction-meta)
#?(:clj (defn expand-hf-tx [tx] (call-sym 'hyperfiddle.txn/expand-hf-tx tx)))
# ? (:
#?(:clj (defn into-tx
( [ ] ( into - tx schema ) ) -- needs Electric->Clojure binding conveyance
([schema tx tx'] (call-sym 'hyperfiddle.txn/into-tx schema tx tx'))))
stabilize first loop ( optional )
(new (e/task->cp
(m/compel
(m/via m/blk
(swap! !t (fn [[db tx0]]
injected datomic dep
(e/defn Load-timer []
(e/client
(let [[x] (e/with-cycle [[elapsed start :as s] [0 nil]]
(case hyperfiddle.api/loading
true [(some->> start (- e/system-time-ms))
(js/Date.now)]
s))]
x)))
(e/server
(let [!ret (atom nil)
!t (atom #_::unknown [db []])
[db stage] (e/watch !t)]
(binding [hyperfiddle.api/db db
hyperfiddle.api/stage stage
hyperfiddle.api/Transact! (e/fn [tx]
#_(println "Transact! " (hash !t) "committing: " tx)
(let [r (Transact!*. !t tx)]
#_(println "Transact! " (hash !t) "commit result: " r)))]
(e/client
(e/with-cycle [loading false]
(binding [hyperfiddle.api/loading loading]
#_(dom/div (name loading) " " (str (Load-timer.)) "ms")
(try
(e/server
#_(println 'Branch x)
false (catch Pending e true))))
nil))
(defmacro branch [& body] `(new Branch (e/fn [] ~@body)))
(def ^:dynamic *http-request* "Bound to the HTTP request of the page in which the current Electric program is running." nil)
(e/def page-drop -1)
(e/def page-take -1)
(e/defn Paginate [xs]
(if (coll? xs)
(cond->> xs
(pos-int? page-drop) (drop page-drop)
(pos-int? page-take) (take page-take))
xs))
|
2b8187c4a71689950b2c760d63ce1d28a84005665c0b67e283cb1f878484e0e0 | pfdietz/ansi-test | pathname-directory.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sat Dec 6 14:24:39 2003
;;;; Contains: Tests for PATHNAME-DIRECTORY
(deftest pathname-directory.1
(loop for p in *pathnames*
for directory = (pathname-directory p)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.2
(loop for p in *pathnames*
for directory = (pathname-directory p :case :local)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.3
(loop for p in *pathnames*
for directory = (pathname-directory p :case :common)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.4
(loop for p in *pathnames*
for directory = (pathname-directory p :allow-other-keys nil)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.5
(loop for p in *pathnames*
for directory = (pathname-directory p :foo 'bar :allow-other-keys t)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.6
(loop for p in *pathnames*
for directory = (pathname-directory p :allow-other-keys t
:allow-other-keys nil
'foo 'bar)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
;;; section 19.3.2.1
(deftest pathname-directory.7
(loop for p in *logical-pathnames*
when (eq (pathname-directory p) :unspecific)
collect p)
nil)
(deftest pathname-directory.8
(do-special-strings (s "" nil) (pathname-directory s))
nil)
(deftest pathname-directory.error.1
(signals-error (pathname-directory) program-error)
t)
(deftest pathname-directory.error.2
(check-type-error #'pathname-directory #'could-be-pathname-designator)
nil)
| null | https://raw.githubusercontent.com/pfdietz/ansi-test/3f4b9d31c3408114f0467eaeca4fd13b28e2ce31/pathnames/pathname-directory.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests for PATHNAME-DIRECTORY
section 19.3.2.1 | Author :
Created : Sat Dec 6 14:24:39 2003
(deftest pathname-directory.1
(loop for p in *pathnames*
for directory = (pathname-directory p)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.2
(loop for p in *pathnames*
for directory = (pathname-directory p :case :local)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.3
(loop for p in *pathnames*
for directory = (pathname-directory p :case :common)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.4
(loop for p in *pathnames*
for directory = (pathname-directory p :allow-other-keys nil)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.5
(loop for p in *pathnames*
for directory = (pathname-directory p :foo 'bar :allow-other-keys t)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.6
(loop for p in *pathnames*
for directory = (pathname-directory p :allow-other-keys t
:allow-other-keys nil
'foo 'bar)
unless (or (stringp directory)
(member directory '(nil :wild :unspecific))
(and (consp directory)
(member (car directory) '(:absolute :relative))))
collect (list p directory))
nil)
(deftest pathname-directory.7
(loop for p in *logical-pathnames*
when (eq (pathname-directory p) :unspecific)
collect p)
nil)
(deftest pathname-directory.8
(do-special-strings (s "" nil) (pathname-directory s))
nil)
(deftest pathname-directory.error.1
(signals-error (pathname-directory) program-error)
t)
(deftest pathname-directory.error.2
(check-type-error #'pathname-directory #'could-be-pathname-designator)
nil)
|
4d0c7f2e8e51b3439c74587224a90f692e144b53afbb4c7092ed673027e3250a | ashwinbhaskar/google-drive-file-uploader | drive_test.clj | (ns google-drive-file-uploader.drive-test
(:require [clojure.test :refer :all]
[google-drive-file-uploader.drive :as drive]
[mock-clj.core :as m]
[failjure.core :as f]))
(deftest upload-file-to-folder-test
(testing "Should check the validity of access token before calling get-files"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true]
(is (not (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:access-token "foo-access-token"
:refresh-token "foo-refresh-token"
:client-id "foo-client-id"
:client-secret "foo-client-secret"}))))
(is (= 1
(m/call-count #'drive/valid-access-token?)))
(is (= 1
(m/call-count #'drive/get-files)))
(is (= 1
(m/call-count #'drive/upload-file-multipart)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-id-1" "/users/foo/a.apk" "foo-name.apk" "foo-access-token"]
(m/last-call #'drive/upload-file-multipart)))))
(testing "Should fetch a new access token if the supplied access-token is not valid"
(m/with-mock [drive/valid-access-token? false
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (not (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:access-token "foo-access-token"
:refresh-token "foo-refresh-token"
:client-id "foo-client-id"
:client-secret "foo-client-secret"}))))
(is (= 1
(m/call-count #'drive/valid-access-token?)))
(is (= 1
(m/call-count #'drive/get-files)))
(is (= 1
(m/call-count #'drive/upload-file-multipart)))
(is (= 1
(m/call-count #'drive/authorization-token)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-refresh-token" "foo-client-id" "foo-client-secret"]
(m/last-call #'drive/authorization-token)))
(is (= ["foo-id-1" "/users/foo/a.apk" "foo-name.apk" "new-access-token"]
(m/last-call #'drive/upload-file-multipart)))))
(testing "Should fail when access-token and refresh-token are not given"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:client-id "foo-client-id"
:client-secret "foo-client-secret"})))
(is (= 0
(m/call-count #'drive/valid-access-token?)))
(is (= 0
(m/call-count #'drive/get-files)))
(is (= 0
(m/call-count #'drive/upload-file-multipart)))
(is (= 0
(m/call-count #'drive/authorization-token)))))
(testing "Should fail when access-token and client-id are not given"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:refresh-token "foo-refresh-token"
:client-secret "foo-client-secret"})))
(is (= 0
(m/call-count #'drive/valid-access-token?)))
(is (= 0
(m/call-count #'drive/get-files)))
(is (= 0
(m/call-count #'drive/upload-file-multipart)))
(is (= 0
(m/call-count #'drive/authorization-token)))))
(testing "Should fail when access-token and client-secret are not given"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:refresh-token "foo-refresh-token"
:client-id "foo-client-id"})))
(is (= 0
(m/call-count #'drive/valid-access-token?)))
(is (= 0
(m/call-count #'drive/get-files)))
(is (= 0
(m/call-count #'drive/upload-file-multipart)))
(is (= 0
(m/call-count #'drive/authorization-token))))))
| null | https://raw.githubusercontent.com/ashwinbhaskar/google-drive-file-uploader/16e2e763ec9137f2be69dfd12dc6fad4e9d0d71f/test/google_drive_file_uploader/drive_test.clj | clojure | (ns google-drive-file-uploader.drive-test
(:require [clojure.test :refer :all]
[google-drive-file-uploader.drive :as drive]
[mock-clj.core :as m]
[failjure.core :as f]))
(deftest upload-file-to-folder-test
(testing "Should check the validity of access token before calling get-files"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true]
(is (not (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:access-token "foo-access-token"
:refresh-token "foo-refresh-token"
:client-id "foo-client-id"
:client-secret "foo-client-secret"}))))
(is (= 1
(m/call-count #'drive/valid-access-token?)))
(is (= 1
(m/call-count #'drive/get-files)))
(is (= 1
(m/call-count #'drive/upload-file-multipart)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-id-1" "/users/foo/a.apk" "foo-name.apk" "foo-access-token"]
(m/last-call #'drive/upload-file-multipart)))))
(testing "Should fetch a new access token if the supplied access-token is not valid"
(m/with-mock [drive/valid-access-token? false
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (not (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:access-token "foo-access-token"
:refresh-token "foo-refresh-token"
:client-id "foo-client-id"
:client-secret "foo-client-secret"}))))
(is (= 1
(m/call-count #'drive/valid-access-token?)))
(is (= 1
(m/call-count #'drive/get-files)))
(is (= 1
(m/call-count #'drive/upload-file-multipart)))
(is (= 1
(m/call-count #'drive/authorization-token)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-access-token"]
(m/last-call #'drive/valid-access-token?)))
(is (= ["foo-refresh-token" "foo-client-id" "foo-client-secret"]
(m/last-call #'drive/authorization-token)))
(is (= ["foo-id-1" "/users/foo/a.apk" "foo-name.apk" "new-access-token"]
(m/last-call #'drive/upload-file-multipart)))))
(testing "Should fail when access-token and refresh-token are not given"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:client-id "foo-client-id"
:client-secret "foo-client-secret"})))
(is (= 0
(m/call-count #'drive/valid-access-token?)))
(is (= 0
(m/call-count #'drive/get-files)))
(is (= 0
(m/call-count #'drive/upload-file-multipart)))
(is (= 0
(m/call-count #'drive/authorization-token)))))
(testing "Should fail when access-token and client-id are not given"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:refresh-token "foo-refresh-token"
:client-secret "foo-client-secret"})))
(is (= 0
(m/call-count #'drive/valid-access-token?)))
(is (= 0
(m/call-count #'drive/get-files)))
(is (= 0
(m/call-count #'drive/upload-file-multipart)))
(is (= 0
(m/call-count #'drive/authorization-token)))))
(testing "Should fail when access-token and client-secret are not given"
(m/with-mock [drive/valid-access-token? true
drive/get-files {:files [{:id "foo-id-1"
:name "foo-folder"
:mime-type "application/vnd.google-apps.folder"}]}
drive/upload-file-multipart true
drive/authorization-token "new-access-token"]
(is (f/failed? (drive/upload-file-to-folder {:folder "foo-folder"
:file-path "/users/foo/a.apk"
:file-name "foo-name.apk"
:refresh-token "foo-refresh-token"
:client-id "foo-client-id"})))
(is (= 0
(m/call-count #'drive/valid-access-token?)))
(is (= 0
(m/call-count #'drive/get-files)))
(is (= 0
(m/call-count #'drive/upload-file-multipart)))
(is (= 0
(m/call-count #'drive/authorization-token))))))
|
|
3524b571f75b6e4856b6802ef8d588f3b97922189bfe10866e14b30f46f6bbb3 | fukamachi/as-interval | as-interval.lisp | (in-package :cl-user)
(defpackage as-interval-test
(:use :cl
:as-interval
:cl-test-more))
(in-package :as-interval-test)
(plan 1)
(diag "Running a test... this takes 10 seconds...")
(is-print (as:with-event-loop ()
(let ((event (interval
(lambda ()
(princ "Hi!"))
:time 3)))
(as:delay (lambda () (remove-interval event))
:time 10)))
"Hi!Hi!Hi!")
(finalize)
| null | https://raw.githubusercontent.com/fukamachi/as-interval/1fc6b823834b3ad56544b225500178a141a9c14a/t/as-interval.lisp | lisp | (in-package :cl-user)
(defpackage as-interval-test
(:use :cl
:as-interval
:cl-test-more))
(in-package :as-interval-test)
(plan 1)
(diag "Running a test... this takes 10 seconds...")
(is-print (as:with-event-loop ()
(let ((event (interval
(lambda ()
(princ "Hi!"))
:time 3)))
(as:delay (lambda () (remove-interval event))
:time 10)))
"Hi!Hi!Hi!")
(finalize)
|
|
da1c6b99ee8662bae671501b102cb4bff9d69794fd9ded9b256112dc14e56df0 | McParen/croatoan | menu.lisp | (in-package :de.anvi.croatoan)
;; menu
;; curses extension for programming menus
;; -island.net/ncurses/man/menu.3x.html
default size of ncurses menus is 16 rows , 1 col .
(defclass menu (element layout)
((menu-type
:initarg :menu-type
:initform :selection
:accessor menu-type
:type keyword
:documentation "Types of menus: :selection (default) or :checklist.")
(current-item-position
:initarg :current-item-position
:initform nil
:accessor current-item-position
:type (or null cons)
:documentation "Position (y x) of the current item in the window.
This can be used to position the cursor on the current item after the menu is drawn.")
(current-item-mark
:initarg :current-item-mark
:initform ""
:reader current-item-mark
:type string
:documentation "A string prefixed to the current item in the menu.")
(tablep
:initarg :table
:initform nil
:reader tablep
:type boolean
:documentation "If t, table row and column lines are drawn between the items.")
(item-padding-top
:initarg :item-padding-top
:initform 0
:type integer
:documentation "Additional space added to the top of the item title, with the same background style.")
(item-padding-bottom
:initarg :item-padding-bottom
:initform 0
:type integer
:documentation "Additional space added below the item title, with the same background style.")
(item-padding-left
:initarg :item-padding-left
:initform 0
:type integer
:documentation "Additional space added to the left of the item title, with the same background style.")
(item-padding-right
:initarg :item-padding-right
:initform 0
:type integer
:documentation "Additional space added to the right of the item title, with the same background style.")
(variable-column-width-p
:initarg :variable-column-width
:initform nil
:reader variable-column-width-p
:type boolean
:documentation "If t, columns widths are calculated from the items.
If nil (default), use max-item-length as the width for every column.")
see examples t19b2 , t19b3 .
(draw-stack-p
:initarg :draw-stack
:initform t
:reader draw-stack-p
:type boolean
:documentation
"Redraw all menus in the stack when a submenu is quit/entered, so we see the whole stack.
If nil, only one direct parent/child is redrawn, so we move through the stack one by one.
At the moment, this setting applies only to stacks of simple (non-window) menus).")
(max-item-length
:initarg :max-item-length
:initform 15
:accessor max-item-length
:type integer
:documentation "Max number of characters displayed for a single item."))
(:default-initargs :keymap 'menu-map)
(:documentation
"A menu is a list of items displayed in a grid that can be selected by the user.
Item types can be strings, symbols, numbers, other menus or callback functions."))
;; init for menus which aren't menu windows
(defmethod initialize-instance :after ((menu menu) &key item-padding)
(with-slots (children grid-rows grid-columns region-rows region-columns region-start-row region-start-column
tablep grid-row-gap grid-column-gap) menu
(setf region-start-row 0
region-start-column 0)
;; item-padding is either an integer, or a list (top-bottom left-right) or (top bottom left right).
(when item-padding
(with-slots ((pt item-padding-top) (pb item-padding-bottom) (pl item-padding-left) (pr item-padding-right)) menu
(typecase item-padding
(list
(case (length item-padding)
(4 (setf pt (nth 0 item-padding)
pb (nth 1 item-padding)
pl (nth 2 item-padding)
pr (nth 3 item-padding)))
(2 (setf pt (nth 0 item-padding)
pb (nth 0 item-padding)
pl (nth 1 item-padding)
pr (nth 1 item-padding)))))
(integer
(setf pt item-padding
pb item-padding
pl item-padding
pr item-padding)))))
;; Convert strings and symbols to item objects
(setf children (mapcar (lambda (item)
(if (typep item 'menu-item)
;; if an item object is given, just return it
item
;; if we have strings, symbols or menus, convert them to menu-items
(make-instance 'menu-item
:name (typecase item
(string nil)
(number nil)
(symbol item)
(menu (name item)))
:title (typecase item
(string item)
(symbol (symbol-name item))
(number (princ-to-string item))
;; if there is a title string, take it,
;; otherwise use the menu name as the item title
(menu (if (and (title item)
(stringp (title item)))
(title item)
(symbol-name (name item)))))
:value item)))
;; apply the function to the init arg passed to make-instance.
children))
if the layout was nt passed as an argument , initialize it as a single one - column menu .
(unless grid-rows
(setf grid-rows (length children)))
(unless grid-columns
(setf grid-columns 1))
;; If table lines have to be drawn, a gap between the items also has to be set.
(when tablep
(when (zerop grid-row-gap)
(setf grid-row-gap 1))
(when (zerop grid-column-gap)
(setf grid-column-gap 1)))))
(defmethod width ((obj menu))
(with-accessors ((len max-item-length)
(variable-column-width-p variable-column-width-p)
(items items)) obj
(with-slots (scrolling-enabled-p
menu-type
item-padding-left
item-padding-right
(m grid-rows)
(n grid-columns)
(cg grid-column-gap)
(m0 region-start-row)
(n0 region-start-column)
(m1 region-rows)
(n1 region-columns)) obj
(if variable-column-width-p
;; variable column width
(destructuring-bind (m0 n0 m1 n1) (if scrolling-enabled-p (list m0 n0 m1 n1) (list 0 0 m n))
(let* ((widths- (mapcar (lambda (i) (+ i item-padding-left item-padding-right))
(if variable-column-width-p
(subseq (column-widths items (list m n)) n0 (+ n0 n1))
(loop for i below n1 collect len))))
(widths (if (eq menu-type :checklist)
(mapcar (lambda (i) (+ i 4)) widths-)
widths-))
(gaps (if (plusp cg) (* (1- n1) cg) 0)))
(+ gaps
(loop for i in widths sum i))))
;; fixed column width
(destructuring-bind (m0 n0 m1 n1) (if scrolling-enabled-p (list m0 n0 m1 n1) (list 0 0 m n))
(let* ((w (* n1 (if (eq menu-type :checklist)
(+ len 4)
len)))
;; if a table is drawn, we have n-1 row lines
(gaps (if (plusp cg) (* (1- n1) cg) 0)))
(+ w
gaps
(* n1 item-padding-left)
(* n1 item-padding-right))))))))
(defmethod height ((obj menu))
(with-accessors ((m visible-grid-rows)) obj
(with-slots ((rg grid-row-gap)
item-padding-top
item-padding-bottom) obj
(let* ((gaps (if (plusp rg) (* (1- m) rg) 0)))
the height of the menu is a sum of m items of height 1
;; m-1 gaps between the items, and m top and bottom paddings.
(+ m
gaps
(* m item-padding-top)
(* m item-padding-bottom))))))
(defmethod visible-width ((obj menu))
"visible width = content width + padding"
(with-accessors ((w width) (borderp borderp) (tablep tablep) (bl border-width-left) (br border-width-right) (pl padding-left) (pr padding-right)) obj
(cond (tablep
;; for tables, the outer border is part of the content
(+ w bl br))
(t
;; padding (inside the border) is part of the content
(+ w pl pr)))))
(defmethod external-width ((obj menu))
"external-width = content width + (padding + border-width)
= visible-width + border-width"
(with-accessors ((w width) (borderp borderp) (tablep tablep) (bl border-width-left) (br border-width-right) (pl padding-left) (pr padding-right)) obj
(cond (tablep
;; for tables, item padding is part of the content
(+ w bl br))
(borderp
(+ w pl pr bl br))
(t
(+ w pl pr)))))
(defmethod visible-height ((obj menu))
(with-accessors ((h height) (borderp borderp) (tablep tablep) (bt border-width-top) (bb border-width-bottom) (pt padding-top) (pb padding-bottom)) obj
(cond (tablep
(+ h bt bb))
(t
(+ h pt pb)))))
(defmethod external-height ((obj menu))
(with-accessors ((h height) (borderp borderp) (tablep tablep) (bt border-width-top) (bb border-width-bottom) (pt padding-top) (pb padding-bottom)) obj
(cond (tablep
(+ h bt bb))
(borderp
(+ h pt pb bt bb))
(t
(+ h pt pb)))))
(defclass menu-window (menu window)
()
(:default-initargs :keymap 'menu-window-map)
(:documentation "A menu-window is an extended window displaying a menu in its sub-window."))
(defmethod initialize-instance :after ((win menu-window) &key color-pair)
(with-slots (winptr children type height width (y position-y) (x position-x) borderp tablep
border-width-top border-width-bottom border-width-left border-width-right
grid-rows grid-columns region-rows region-columns max-item-length current-item-mark fgcolor bgcolor) win
;; only for menu windows
(when (eq (type-of win) 'menu-window)
;; if no layout was given, use a vertical list (n 1)
(unless grid-rows (setf grid-rows (length children)))
(unless grid-columns (setf grid-columns 1))
;; if height and width of the _window_ are not given as
;; initargs but calculated from menu data
(unless height (setf height (external-height win)))
(unless width (setf width (external-width win)))
(setf winptr (ncurses:newwin height width y x))
(cond ((or fgcolor bgcolor)
(set-color-pair winptr (color-pair win))
(setf (background win) (make-instance 'complex-char :color-pair (color-pair win))))
;; when a color-pair is passed as a keyword
(color-pair
;; set fg and bg, pass to ncurses
(setf (color-pair win) color-pair
(background win) (make-instance 'complex-char :color-pair color-pair)))))))
;; although it is not a stream, we will abuse close to close a menu's window and subwindow, which _are_ streams.
(defmethod close ((stream menu-window) &key abort)
(declare (ignore abort))
(ncurses:delwin (winptr stream)))
(defclass checklist (menu)
()
(:default-initargs
:menu-type :checklist
:keymap 'checklist-map)
(:documentation "A checklist is a multi-selection menu with checkable items."))
(defclass menu-item (checkbox)
((value
:type (or symbol keyword string menu menu-window function number)
:documentation "The value of an item can be a string, a number, a sub menu or a function to be called when the item is selected."))
(:documentation "A menu contains of a list of menu items."))
;; not used anywhere
(defun list2array (list dimensions)
"Example: (list2array '(a b c d e f) '(3 2)) => #2A((A B) (C D) (E F))"
(let ((m (car dimensions))
(n (cadr dimensions)))
(assert (= (length list) (* m n)))
(let ((array (make-array dimensions :initial-element nil)))
(loop for i from 0 to (- m 1)
do (loop for j from 0 to (- n 1)
do (setf (aref array i j) (nth (+ (* i n) j) list))))
array)))
(defun rmi2sub (dimensions rmi)
"Take array dimensions and an index in row-major order, return two subscripts.
This works analogous to cl:row-major-aref.
Example: (rmi2sub '(2 3) 5) => (1 2)"
(let ((m (car dimensions))
(n (cadr dimensions)))
(assert (< rmi (* m n)))
(multiple-value-bind (q r) (floor rmi n)
(list q r))))
(defun sub2rmi (dimensions subs)
"Take array dimensions and two subscripts, return an index in row-major order.
This works analogous to cl:array-row-major-index.
Example: (sub2rmi '(2 3) '(1 2)) => 5"
(let ((m (car dimensions))
(n (cadr dimensions))
(i (car subs))
(j (cadr subs)))
(assert (and (< i m) (< j n)))
(+ (* i n) j)))
(defmethod clear ((obj menu) &key)
(with-accessors ((x position-x) (y position-y) (ew external-width) (eh external-height) (vw visible-width) (vh visible-height) (tablep tablep)
(bt border-width-top) (bl border-width-left) (borderp borderp) (selectedp selectedp) (win window) (style style)) obj
(let* ((bg-style (if selectedp
(getf style :selected-background)
(getf style :background)))
(border-style (if selectedp
(getf style :selected-border)
(getf style :border))))
(cond (tablep
(fill-rectangle win (apply #'make-instance 'complex-char bg-style) y x vh vw))
(borderp
(fill-rectangle win (apply #'make-instance 'complex-char border-style) y x eh ew)
(fill-rectangle win (apply #'make-instance 'complex-char bg-style) (+ y bt) (+ x bl) vh vw))
(t
(fill-rectangle win (apply #'make-instance 'complex-char bg-style) y x vh vw))))))
(defmethod clear ((obj menu-window) &key)
(with-accessors ((ew external-width) (eh external-height) (vw visible-width) (vh visible-height) (tablep tablep)
(bt border-width-top) (bl border-width-left) (borderp borderp) (selectedp selectedp) (style style)) obj
(let* ((bg-style (if selectedp
(getf style :selected-background)
(getf style :background)))
(border-style (if selectedp
(getf style :selected-border)
(getf style :border))))
;; the position of the menu in a menu-window is always (0 0).
(let ((y 0)
(x 0))
(cond (tablep
(fill-rectangle obj (apply #'make-instance 'complex-char bg-style) y x vh vw))
(borderp
(fill-rectangle obj (apply #'make-instance 'complex-char border-style) y x eh ew)
(fill-rectangle obj (apply #'make-instance 'complex-char bg-style) (+ y bt) (+ x bl) vh vw))
(t
(fill-rectangle obj (apply #'make-instance 'complex-char bg-style) y x vh vw)))))))
(defun draw-table-top (win widths)
"Draw the top line of a table at the current position using ANSI drawing characters.
The top line is only drawn when border is t."
(add-char win :upper-left-corner)
(dolist (n (butlast widths))
(add-char win :horizontal-line :n n)
(add-char win :tee-pointing-down))
(add-char win :horizontal-line :n (car (last widths)))
(add-char win :upper-right-corner))
(defun draw-table-row-separator (win widths borderp)
"Draw the horizontal line between table cells."
the first char is only drawn for the border .
(when borderp
(crt:add-char win :tee-pointing-right))
;; draw -- then + for every column.
(dolist (n (butlast widths))
(crt:add-char win :horizontal-line :n n)
(crt:add-char win :crossover-plus))
;; finally, thaw only -- for the last column.
(add-char win :horizontal-line :n (car (last widths)))
;; the last char is only drawn for the border.
(when borderp
(add-char win :tee-pointing-left)))
(defun draw-table-bottom (win widths)
"Draw the top line of a table at the current position using ANSI drawing characters.
The bottom line is only drawn when border is t."
(add-char win :lower-left-corner)
(dolist (n (butlast widths))
(add-char win :horizontal-line :n n)
(add-char win :tee-pointing-up))
(add-char win :horizontal-line :n (car (last widths)))
(add-char win :lower-right-corner))
(defun draw-table-lines (win y x m n rg cg bt bl pt pb widths heights borderp)
;; y position
;; x position
;; m number of displayed rows
;; n number of displayed columns
;; rg row gap
;; cg column-gap
;; bt width of the top border
;; bl width of the left border
;; pt padding top
;; pb padding bottom
witdhs , - list of widths of columns
;;; draw the n1+1 vertical lines (plain, without endings and crossings)
;; first vline (left border)
(when borderp
(draw-vline win
the first line is the top border , we start below the border .
(+ y bt)
x
;; length of the vertical lines
(+ m ; rows
(- m 1) ; row separators
(* m (+ pt pb))))) ; top and bottom padding
;; n-1 column separator vlines
(dotimes (j (1- n))
(draw-vline win
(+ y bt)
(+ x bl (* j cg) (loop for i from 0 to j sum (nth i widths)))
(+ (1- (* m 2))
(* m (+ pt pb)))))
;; last vline (right border)
(when borderp
(draw-vline win
the first line is the border top , we start below the border .
(+ y bt)
(+ x
bl
(* (1- n) cg)
(reduce #'+ widths))
;; length of the vertical lines
(+ m ; rows
(- m 1) ; row separators
(* m (+ pt pb))))) ; top and bottom padding
draw m+1 horizontal lines ( with endings and crossings )
;; they have to be drawn _after_ the vertical lines, because the
;; drawn vertical lines do not contain the crossover chars.
top horizontal line of the table , only drawn if borderp is t.
(when borderp
(move win y x)
(draw-table-top win widths))
;; m-1 row separators
(dotimes (i (- m 1))
(move win
(+ y bt (* i rg) (loop for j from 0 to i sum (nth j heights)))
x)
(draw-table-row-separator win widths borderp))
bottom line , only drawn if borderp is t.
(when borderp
(move win (+ y (* 2 m) (* m (+ pt pb))) x)
(draw-table-bottom win widths)))
(defun format-menu-item (menu item selectedp)
"Take a menu and return item item-number as a properly formatted string.
If the menu is a checklist, return [ ] or [X] at the first position.
If a mark is set for the current item, display the mark at the second position.
Display the same number of spaces for other items.
At the third position, display the item given by item-number."
(with-accessors ((type menu-type)
(current-item-number current-item-number)
(current-item-mark current-item-mark)) menu
;; return as string
(format nil "~A~A~A"
two types of menus : : selection or : checklist
;; show the checkbox before the item in checklists
(if (eq type :checklist)
(if (checkedp item) "[X] " "[ ] ")
"")
;; for the current item, draw the current-item-mark
;; for all other items, draw a space
(if selectedp
current-item-mark
(make-string (length current-item-mark) :initial-element #\space))
;; then add the item title
(format-title item))))
(defmethod external-width ((obj menu-item))
(length (title obj)))
;; draws to any window, not just to a sub-window of a menu-window.
(defun draw-menu (win y x menu)
"Draw the menu to the window."
(with-slots (scrolling-enabled-p
variable-column-width-p
menu-type
item-padding-top
item-padding-bottom
item-padding-left
item-padding-right
(pl padding-left)
(pt padding-top)
(cmark current-item-mark)
(cpos current-item-position)
(len max-item-length)
(items children)
(borderp borderp)
(tablep tablep)
(r grid-row)
(c grid-column)
(m grid-rows)
(n grid-columns)
(m0 region-start-row)
(n0 region-start-column)
(m1 region-rows)
(n1 region-columns)
(rg grid-row-gap)
(cg grid-column-gap)
(bt border-width-top)
(bl border-width-left)) menu
(with-accessors ((style style)) menu
(clear menu)
;; start and end indexes
(destructuring-bind (m0 n0 m1 n1)
;; when the menu is too big to be displayed at once, only a part
;; is displayed, and the menu can be scrolled
(if scrolling-enabled-p (list m0 n0 m1 n1) (list 0 0 m n))
(let* ((widths- (mapcar (lambda (i) (+ i item-padding-left item-padding-right))
(if variable-column-width-p
(subseq (column-widths items (list m n)) n0 (+ n0 n1))
(loop for i below n1 collect len))))
(widths (if (eq menu-type :checklist)
(mapcar (lambda (i) (+ i 4)) widths-)
widths-))
(xs (cumsum-predecessors widths))
height of one item is 1 and the padding .
(h (+ 1 item-padding-top item-padding-bottom))
(heights (loop for i below m1 collect h)))
(when borderp
(if (typep menu 'window)
(draw-rectangle win y x
;; If window dimensions have been explicitely given, override the calculated
;; menu dimensions. This allows to draw a "menu bar", which can be wider
than the sum of its items , see t19e2 .
(if (slot-value win 'height)(slot-value win 'height) (external-height menu))
(if (slot-value win 'width) (slot-value win 'width) (external-width menu))
:style (getf style :border))
;; if menu is a simple menu, we are not able to set
;; the width manually to a value different than the
;; calculated width
(draw-rectangle win y x
(external-height menu)
(external-width menu)
:style (getf style :border))))
(when tablep
;; to draw table lines between the grid cells, a grid gap is required.
(draw-table-lines win y x m1 n1 rg cg bt bl item-padding-top item-padding-bottom widths heights borderp))
(dogrid ((i 0 m1)
(j 0 n1))
;; the menu is given as a flat list, so we have to access it as a 2d array in row major order
(let* ((item (ref2d items (list m n) (+ m0 i) (+ n0 j)))
(selectedp (and (= i (- r m0)) (= j (- c n0))))
;; calculated position of the item
posy
posx)
(setq posy (+ y
(if borderp bt 0)
(if (and borderp (not tablep)) pt 0)
(* i rg)
(* i h))
posx (+ x
(if borderp bl 0)
(if (and borderp (not tablep)) pl 0)
(* j cg)
(nth j xs)))
;; save the position of the current item, to be used in update-cursor-position.
(when selectedp
(setf cpos (list posy posx)))
(let ((fg-style (if style
(getf style (if selectedp :selected-foreground :foreground))
;; default foreground style
(if selectedp (list :attributes (list :reverse)) nil)))
(bg-style (if style
(getf style (if selectedp :selected-background :background))
;; default background style
(if selectedp (list :attributes (list :reverse)) nil))))
;; draw the top padding lines
(when (plusp item-padding-top)
(dotimes (k item-padding-top)
(move win (+ posy k) posx)
(add win #\space :style bg-style :n (nth j widths))))
(move win (+ posy item-padding-top) posx)
write an empty string as the background first .
(save-excursion win (add win #\space :style bg-style :n (nth j widths)))
;; display the itemt in the window associated with the menu
(add win
(format nil
(concatenate 'string
(make-string item-padding-left :initial-element #\space)
;; "~v,,,' @A" to right-justify
"~v,,,' A"
(make-string item-padding-right :initial-element #\space))
(- (nth j widths) item-padding-left item-padding-right)
(format-menu-item menu item selectedp))
:style fg-style)
;; draw the bottom padding lines
(when (plusp item-padding-bottom)
(dotimes (k item-padding-bottom)
(move win (+ posy item-padding-top 1 k) posx)
(add win #\space :style bg-style :n (nth j widths))))))))
(refresh win)))))
(defmethod draw ((menu menu))
"Draw the menu to its associated window."
(draw-menu (window menu)
(car (widget-position menu))
(cadr (widget-position menu))
menu)
;; when menu is a part of a form: update-cursor-position = place the cursor on the current item
;; if the menu is a checklist, place the cursor inside the [_], like it is done with a single checkbox.
(update-cursor-position menu))
(defmethod draw ((menu menu-window))
"Draw the menu to position (0 0) of its window."
(draw-menu menu
0
0
menu))
;; called from:
;; return-from-menu
(defun reset-menu (menu)
"After the menu is closed reset it to its initial state."
(with-slots (children current-item-number grid-row grid-column region-start-row region-start-column menu-type) menu
(setf current-item-number 0
grid-row 0
grid-column 0
region-start-row 0
region-start-column 0)
(when (eq menu-type :checklist)
(loop for i in children if (checkedp i) do (setf (checkedp i) nil)))))
;; stack for managing overlapping menu windows
(defparameter *menu-stack* (make-instance 'stack))
(defun return-from-menu (menu return-value)
"Pop the menu from the menu stack, refresh the remaining menu stack.
If the menu is not a window, clear the menu from the window.
Return the value from select."
(if (typep menu 'window)
(unless (stack-empty-p *menu-stack*)
(stack-pop *menu-stack*))
;; if the menu is not a menu-window, clear the parent window.
(unless (stack-empty-p *menu-stack*)
(stack-pop *menu-stack*)
(clear (window menu))
(when (draw-stack-p menu)
(mapc #'draw (reverse (items *menu-stack*))))
(refresh (window menu))))
(reset-menu menu)
(throw menu return-value))
(defun exit-menu-event-loop (menu)
"Associate this function with an event to exit the menu event loop."
(return-from-menu menu nil))
(defun checked-items (menu)
"Take a menu, return a list of checked menu items."
(loop for i in (items menu) if (checkedp i) collect i))
(defmethod value ((menu menu))
"Return the value of the selected item."
(value (current-item menu)))
(defmethod value ((checklist checklist))
"Return the list of values of the checked items."
(mapcar #'value (checked-items checklist)))
(defun accept-selection (menu)
"Return the value of the currently selected item or all checked items."
;; menu vs checklist
(case (menu-type menu)
(:checklist
when one or more items have been checked ,
;; return the checked items (not their values).
(when (checked-items menu)
(return-from-menu menu (checked-items menu))))
(:selection
(let ((val (value (current-item menu))))
(cond
;; if the item is a string or symbol, just return it.
((or (typep val 'string)
(typep val 'symbol)
(typep val 'number))
(return-from-menu menu val))
;; if the item is a function object, call it.
((typep val 'function)
(funcall val)
(return-from-menu menu (name (current-item menu))))
;; if the item is a menu (and thus also a menu-window), recursively select an item from that submenu
((or (typep val 'menu)
(typep val 'menu-window))
;; when the stack is not drawn, clear the parent menu before drawing the sub menu
(unless (draw-stack-p val)
(clear (window menu)))
(let ((selected-item (select val)))
when we have more than one menu in one window , redraw the parent menu after we return from the submenu .
(when (or (eq (type-of val) 'menu)
(eq (type-of val) 'checklist))
(draw menu))
;; if a value was returned by the sub-menu, return it as the value of the parent menu.
(when selected-item
(return-from-menu menu selected-item)))) )))))
(defun toggle-item-checkbox (menu)
"Toggle the checked state of the current item, used in checkbox menus."
(setf (checkedp (current-item menu)) (not (checkedp (current-item menu))))
(draw menu))
(defun sync-collection-grid (obj)
"Sync the position in 1D collection list with the yx position in a 2D grid."
(with-slots (current-item-number grid-rows grid-columns grid-row grid-column) obj
(setf current-item-number (sub2rmi (list grid-rows grid-columns) (list grid-row grid-column)))))
(defun sync-grid-collection (obj)
"Set the 2D yx grid position from the 1D position in the collection list."
(with-slots ((i current-item-number)
(m grid-rows)
(n grid-columns)
(y grid-row)
(x grid-column)) obj
(setf y (car (rmi2sub (list m n) i))
x (cadr (rmi2sub (list m n) i)))))
(defmethod move-left ((obj menu))
;; update the grid
(call-next-method obj)
;; sync the 1D collection and the 2D grid
(sync-collection-grid obj)
;; redraw the menu
(draw obj))
(defmethod move-right ((obj menu))
(call-next-method obj)
(sync-collection-grid obj)
(draw obj))
(defmethod move-up ((obj menu))
(call-next-method obj)
(sync-collection-grid obj)
(draw obj))
(defmethod move-down ((obj menu))
(call-next-method obj)
(with-slots (current-item-number grid-rows grid-columns grid-row grid-column) obj
(setf current-item-number
(sub2rmi (list grid-rows grid-columns)
(list grid-row grid-column))))
(draw obj))
all of these take two arguments : menu event
;; there is no :default action, all other events are ignored for menus.
(define-keymap menu-map
(:up 'move-up)
(:down 'move-down)
(:left 'move-left)
(:right 'move-right))
(define-keymap checklist-map
(#\x 'toggle-item-checkbox)
(:up 'move-up)
(:down 'move-down)
(:left 'move-left)
(:right 'move-right))
(define-keymap menu-window-map
;; q doesnt return a value, just nil, i.e. in the case of a checklist, an empty list.
(#\q 'exit-menu-event-loop)
(#\x 'toggle-item-checkbox)
(:up 'move-up)
(:down 'move-down)
(:left 'move-left)
(:right 'move-right)
return the selected item or all checked items , then exit the menu like q.
(#\newline 'accept-selection))
(defgeneric select (obj))
(defmethod select ((obj menu))
(stack-push obj *menu-stack*)
(draw obj)
(run-event-loop obj))
(defmethod select ((menu menu-window))
"Display the menu, let the user select an item, return the selected item.
If the selected item is a menu object, recursively display the sub menu."
;; when the menu is selected, push it to the menu stack.
(stack-push menu *menu-stack*)
(draw menu)
;; here we can pass the menu to run-event-loop because it is a menu-window.
;; all handler functions have to accept window and event as arguments.
(let ((val (run-event-loop menu)))
;; when we return from a menu, the menu is closed and we have to repaint the windows below the menu.
;; this can be done manually or by adding them to the main stack with :stacked t
(unless (stack-empty-p *main-stack*)
(refresh *main-stack*))
;; when we return from a menu, we pop the menu from the menu stack, then repain the remaining stack
;; that way a stack of open sub-menus is cleanly displayed
(unless (stack-empty-p *menu-stack*)
(refresh *menu-stack*))
;; the return value of select is the return value of run-event-loop
;; is the value thrown to the catch tag 'event-loop.
val))
| null | https://raw.githubusercontent.com/McParen/croatoan/c38cca13706d597b6276b7c466dd64f733aaef5e/src/menu.lisp | lisp | menu
curses extension for programming menus
-island.net/ncurses/man/menu.3x.html
init for menus which aren't menu windows
item-padding is either an integer, or a list (top-bottom left-right) or (top bottom left right).
Convert strings and symbols to item objects
if an item object is given, just return it
if we have strings, symbols or menus, convert them to menu-items
if there is a title string, take it,
otherwise use the menu name as the item title
apply the function to the init arg passed to make-instance.
If table lines have to be drawn, a gap between the items also has to be set.
variable column width
fixed column width
if a table is drawn, we have n-1 row lines
m-1 gaps between the items, and m top and bottom paddings.
for tables, the outer border is part of the content
padding (inside the border) is part of the content
for tables, item padding is part of the content
only for menu windows
if no layout was given, use a vertical list (n 1)
if height and width of the _window_ are not given as
initargs but calculated from menu data
when a color-pair is passed as a keyword
set fg and bg, pass to ncurses
although it is not a stream, we will abuse close to close a menu's window and subwindow, which _are_ streams.
not used anywhere
the position of the menu in a menu-window is always (0 0).
draw -- then + for every column.
finally, thaw only -- for the last column.
the last char is only drawn for the border.
y position
x position
m number of displayed rows
n number of displayed columns
rg row gap
cg column-gap
bt width of the top border
bl width of the left border
pt padding top
pb padding bottom
draw the n1+1 vertical lines (plain, without endings and crossings)
first vline (left border)
length of the vertical lines
rows
row separators
top and bottom padding
n-1 column separator vlines
last vline (right border)
length of the vertical lines
rows
row separators
top and bottom padding
they have to be drawn _after_ the vertical lines, because the
drawn vertical lines do not contain the crossover chars.
m-1 row separators
return as string
show the checkbox before the item in checklists
for the current item, draw the current-item-mark
for all other items, draw a space
then add the item title
draws to any window, not just to a sub-window of a menu-window.
start and end indexes
when the menu is too big to be displayed at once, only a part
is displayed, and the menu can be scrolled
If window dimensions have been explicitely given, override the calculated
menu dimensions. This allows to draw a "menu bar", which can be wider
if menu is a simple menu, we are not able to set
the width manually to a value different than the
calculated width
to draw table lines between the grid cells, a grid gap is required.
the menu is given as a flat list, so we have to access it as a 2d array in row major order
calculated position of the item
save the position of the current item, to be used in update-cursor-position.
default foreground style
default background style
draw the top padding lines
display the itemt in the window associated with the menu
"~v,,,' @A" to right-justify
draw the bottom padding lines
when menu is a part of a form: update-cursor-position = place the cursor on the current item
if the menu is a checklist, place the cursor inside the [_], like it is done with a single checkbox.
called from:
return-from-menu
stack for managing overlapping menu windows
if the menu is not a menu-window, clear the parent window.
menu vs checklist
return the checked items (not their values).
if the item is a string or symbol, just return it.
if the item is a function object, call it.
if the item is a menu (and thus also a menu-window), recursively select an item from that submenu
when the stack is not drawn, clear the parent menu before drawing the sub menu
if a value was returned by the sub-menu, return it as the value of the parent menu.
update the grid
sync the 1D collection and the 2D grid
redraw the menu
there is no :default action, all other events are ignored for menus.
q doesnt return a value, just nil, i.e. in the case of a checklist, an empty list.
when the menu is selected, push it to the menu stack.
here we can pass the menu to run-event-loop because it is a menu-window.
all handler functions have to accept window and event as arguments.
when we return from a menu, the menu is closed and we have to repaint the windows below the menu.
this can be done manually or by adding them to the main stack with :stacked t
when we return from a menu, we pop the menu from the menu stack, then repain the remaining stack
that way a stack of open sub-menus is cleanly displayed
the return value of select is the return value of run-event-loop
is the value thrown to the catch tag 'event-loop. | (in-package :de.anvi.croatoan)
default size of ncurses menus is 16 rows , 1 col .
(defclass menu (element layout)
((menu-type
:initarg :menu-type
:initform :selection
:accessor menu-type
:type keyword
:documentation "Types of menus: :selection (default) or :checklist.")
(current-item-position
:initarg :current-item-position
:initform nil
:accessor current-item-position
:type (or null cons)
:documentation "Position (y x) of the current item in the window.
This can be used to position the cursor on the current item after the menu is drawn.")
(current-item-mark
:initarg :current-item-mark
:initform ""
:reader current-item-mark
:type string
:documentation "A string prefixed to the current item in the menu.")
(tablep
:initarg :table
:initform nil
:reader tablep
:type boolean
:documentation "If t, table row and column lines are drawn between the items.")
(item-padding-top
:initarg :item-padding-top
:initform 0
:type integer
:documentation "Additional space added to the top of the item title, with the same background style.")
(item-padding-bottom
:initarg :item-padding-bottom
:initform 0
:type integer
:documentation "Additional space added below the item title, with the same background style.")
(item-padding-left
:initarg :item-padding-left
:initform 0
:type integer
:documentation "Additional space added to the left of the item title, with the same background style.")
(item-padding-right
:initarg :item-padding-right
:initform 0
:type integer
:documentation "Additional space added to the right of the item title, with the same background style.")
(variable-column-width-p
:initarg :variable-column-width
:initform nil
:reader variable-column-width-p
:type boolean
:documentation "If t, columns widths are calculated from the items.
If nil (default), use max-item-length as the width for every column.")
see examples t19b2 , t19b3 .
(draw-stack-p
:initarg :draw-stack
:initform t
:reader draw-stack-p
:type boolean
:documentation
"Redraw all menus in the stack when a submenu is quit/entered, so we see the whole stack.
If nil, only one direct parent/child is redrawn, so we move through the stack one by one.
At the moment, this setting applies only to stacks of simple (non-window) menus).")
(max-item-length
:initarg :max-item-length
:initform 15
:accessor max-item-length
:type integer
:documentation "Max number of characters displayed for a single item."))
(:default-initargs :keymap 'menu-map)
(:documentation
"A menu is a list of items displayed in a grid that can be selected by the user.
Item types can be strings, symbols, numbers, other menus or callback functions."))
(defmethod initialize-instance :after ((menu menu) &key item-padding)
(with-slots (children grid-rows grid-columns region-rows region-columns region-start-row region-start-column
tablep grid-row-gap grid-column-gap) menu
(setf region-start-row 0
region-start-column 0)
(when item-padding
(with-slots ((pt item-padding-top) (pb item-padding-bottom) (pl item-padding-left) (pr item-padding-right)) menu
(typecase item-padding
(list
(case (length item-padding)
(4 (setf pt (nth 0 item-padding)
pb (nth 1 item-padding)
pl (nth 2 item-padding)
pr (nth 3 item-padding)))
(2 (setf pt (nth 0 item-padding)
pb (nth 0 item-padding)
pl (nth 1 item-padding)
pr (nth 1 item-padding)))))
(integer
(setf pt item-padding
pb item-padding
pl item-padding
pr item-padding)))))
(setf children (mapcar (lambda (item)
(if (typep item 'menu-item)
item
(make-instance 'menu-item
:name (typecase item
(string nil)
(number nil)
(symbol item)
(menu (name item)))
:title (typecase item
(string item)
(symbol (symbol-name item))
(number (princ-to-string item))
(menu (if (and (title item)
(stringp (title item)))
(title item)
(symbol-name (name item)))))
:value item)))
children))
if the layout was nt passed as an argument , initialize it as a single one - column menu .
(unless grid-rows
(setf grid-rows (length children)))
(unless grid-columns
(setf grid-columns 1))
(when tablep
(when (zerop grid-row-gap)
(setf grid-row-gap 1))
(when (zerop grid-column-gap)
(setf grid-column-gap 1)))))
(defmethod width ((obj menu))
(with-accessors ((len max-item-length)
(variable-column-width-p variable-column-width-p)
(items items)) obj
(with-slots (scrolling-enabled-p
menu-type
item-padding-left
item-padding-right
(m grid-rows)
(n grid-columns)
(cg grid-column-gap)
(m0 region-start-row)
(n0 region-start-column)
(m1 region-rows)
(n1 region-columns)) obj
(if variable-column-width-p
(destructuring-bind (m0 n0 m1 n1) (if scrolling-enabled-p (list m0 n0 m1 n1) (list 0 0 m n))
(let* ((widths- (mapcar (lambda (i) (+ i item-padding-left item-padding-right))
(if variable-column-width-p
(subseq (column-widths items (list m n)) n0 (+ n0 n1))
(loop for i below n1 collect len))))
(widths (if (eq menu-type :checklist)
(mapcar (lambda (i) (+ i 4)) widths-)
widths-))
(gaps (if (plusp cg) (* (1- n1) cg) 0)))
(+ gaps
(loop for i in widths sum i))))
(destructuring-bind (m0 n0 m1 n1) (if scrolling-enabled-p (list m0 n0 m1 n1) (list 0 0 m n))
(let* ((w (* n1 (if (eq menu-type :checklist)
(+ len 4)
len)))
(gaps (if (plusp cg) (* (1- n1) cg) 0)))
(+ w
gaps
(* n1 item-padding-left)
(* n1 item-padding-right))))))))
(defmethod height ((obj menu))
(with-accessors ((m visible-grid-rows)) obj
(with-slots ((rg grid-row-gap)
item-padding-top
item-padding-bottom) obj
(let* ((gaps (if (plusp rg) (* (1- m) rg) 0)))
the height of the menu is a sum of m items of height 1
(+ m
gaps
(* m item-padding-top)
(* m item-padding-bottom))))))
(defmethod visible-width ((obj menu))
"visible width = content width + padding"
(with-accessors ((w width) (borderp borderp) (tablep tablep) (bl border-width-left) (br border-width-right) (pl padding-left) (pr padding-right)) obj
(cond (tablep
(+ w bl br))
(t
(+ w pl pr)))))
(defmethod external-width ((obj menu))
"external-width = content width + (padding + border-width)
= visible-width + border-width"
(with-accessors ((w width) (borderp borderp) (tablep tablep) (bl border-width-left) (br border-width-right) (pl padding-left) (pr padding-right)) obj
(cond (tablep
(+ w bl br))
(borderp
(+ w pl pr bl br))
(t
(+ w pl pr)))))
(defmethod visible-height ((obj menu))
(with-accessors ((h height) (borderp borderp) (tablep tablep) (bt border-width-top) (bb border-width-bottom) (pt padding-top) (pb padding-bottom)) obj
(cond (tablep
(+ h bt bb))
(t
(+ h pt pb)))))
(defmethod external-height ((obj menu))
(with-accessors ((h height) (borderp borderp) (tablep tablep) (bt border-width-top) (bb border-width-bottom) (pt padding-top) (pb padding-bottom)) obj
(cond (tablep
(+ h bt bb))
(borderp
(+ h pt pb bt bb))
(t
(+ h pt pb)))))
(defclass menu-window (menu window)
()
(:default-initargs :keymap 'menu-window-map)
(:documentation "A menu-window is an extended window displaying a menu in its sub-window."))
(defmethod initialize-instance :after ((win menu-window) &key color-pair)
(with-slots (winptr children type height width (y position-y) (x position-x) borderp tablep
border-width-top border-width-bottom border-width-left border-width-right
grid-rows grid-columns region-rows region-columns max-item-length current-item-mark fgcolor bgcolor) win
(when (eq (type-of win) 'menu-window)
(unless grid-rows (setf grid-rows (length children)))
(unless grid-columns (setf grid-columns 1))
(unless height (setf height (external-height win)))
(unless width (setf width (external-width win)))
(setf winptr (ncurses:newwin height width y x))
(cond ((or fgcolor bgcolor)
(set-color-pair winptr (color-pair win))
(setf (background win) (make-instance 'complex-char :color-pair (color-pair win))))
(color-pair
(setf (color-pair win) color-pair
(background win) (make-instance 'complex-char :color-pair color-pair)))))))
(defmethod close ((stream menu-window) &key abort)
(declare (ignore abort))
(ncurses:delwin (winptr stream)))
(defclass checklist (menu)
()
(:default-initargs
:menu-type :checklist
:keymap 'checklist-map)
(:documentation "A checklist is a multi-selection menu with checkable items."))
(defclass menu-item (checkbox)
((value
:type (or symbol keyword string menu menu-window function number)
:documentation "The value of an item can be a string, a number, a sub menu or a function to be called when the item is selected."))
(:documentation "A menu contains of a list of menu items."))
(defun list2array (list dimensions)
"Example: (list2array '(a b c d e f) '(3 2)) => #2A((A B) (C D) (E F))"
(let ((m (car dimensions))
(n (cadr dimensions)))
(assert (= (length list) (* m n)))
(let ((array (make-array dimensions :initial-element nil)))
(loop for i from 0 to (- m 1)
do (loop for j from 0 to (- n 1)
do (setf (aref array i j) (nth (+ (* i n) j) list))))
array)))
(defun rmi2sub (dimensions rmi)
"Take array dimensions and an index in row-major order, return two subscripts.
This works analogous to cl:row-major-aref.
Example: (rmi2sub '(2 3) 5) => (1 2)"
(let ((m (car dimensions))
(n (cadr dimensions)))
(assert (< rmi (* m n)))
(multiple-value-bind (q r) (floor rmi n)
(list q r))))
(defun sub2rmi (dimensions subs)
"Take array dimensions and two subscripts, return an index in row-major order.
This works analogous to cl:array-row-major-index.
Example: (sub2rmi '(2 3) '(1 2)) => 5"
(let ((m (car dimensions))
(n (cadr dimensions))
(i (car subs))
(j (cadr subs)))
(assert (and (< i m) (< j n)))
(+ (* i n) j)))
(defmethod clear ((obj menu) &key)
(with-accessors ((x position-x) (y position-y) (ew external-width) (eh external-height) (vw visible-width) (vh visible-height) (tablep tablep)
(bt border-width-top) (bl border-width-left) (borderp borderp) (selectedp selectedp) (win window) (style style)) obj
(let* ((bg-style (if selectedp
(getf style :selected-background)
(getf style :background)))
(border-style (if selectedp
(getf style :selected-border)
(getf style :border))))
(cond (tablep
(fill-rectangle win (apply #'make-instance 'complex-char bg-style) y x vh vw))
(borderp
(fill-rectangle win (apply #'make-instance 'complex-char border-style) y x eh ew)
(fill-rectangle win (apply #'make-instance 'complex-char bg-style) (+ y bt) (+ x bl) vh vw))
(t
(fill-rectangle win (apply #'make-instance 'complex-char bg-style) y x vh vw))))))
(defmethod clear ((obj menu-window) &key)
(with-accessors ((ew external-width) (eh external-height) (vw visible-width) (vh visible-height) (tablep tablep)
(bt border-width-top) (bl border-width-left) (borderp borderp) (selectedp selectedp) (style style)) obj
(let* ((bg-style (if selectedp
(getf style :selected-background)
(getf style :background)))
(border-style (if selectedp
(getf style :selected-border)
(getf style :border))))
(let ((y 0)
(x 0))
(cond (tablep
(fill-rectangle obj (apply #'make-instance 'complex-char bg-style) y x vh vw))
(borderp
(fill-rectangle obj (apply #'make-instance 'complex-char border-style) y x eh ew)
(fill-rectangle obj (apply #'make-instance 'complex-char bg-style) (+ y bt) (+ x bl) vh vw))
(t
(fill-rectangle obj (apply #'make-instance 'complex-char bg-style) y x vh vw)))))))
(defun draw-table-top (win widths)
"Draw the top line of a table at the current position using ANSI drawing characters.
The top line is only drawn when border is t."
(add-char win :upper-left-corner)
(dolist (n (butlast widths))
(add-char win :horizontal-line :n n)
(add-char win :tee-pointing-down))
(add-char win :horizontal-line :n (car (last widths)))
(add-char win :upper-right-corner))
(defun draw-table-row-separator (win widths borderp)
"Draw the horizontal line between table cells."
the first char is only drawn for the border .
(when borderp
(crt:add-char win :tee-pointing-right))
(dolist (n (butlast widths))
(crt:add-char win :horizontal-line :n n)
(crt:add-char win :crossover-plus))
(add-char win :horizontal-line :n (car (last widths)))
(when borderp
(add-char win :tee-pointing-left)))
(defun draw-table-bottom (win widths)
"Draw the top line of a table at the current position using ANSI drawing characters.
The bottom line is only drawn when border is t."
(add-char win :lower-left-corner)
(dolist (n (butlast widths))
(add-char win :horizontal-line :n n)
(add-char win :tee-pointing-up))
(add-char win :horizontal-line :n (car (last widths)))
(add-char win :lower-right-corner))
(defun draw-table-lines (win y x m n rg cg bt bl pt pb widths heights borderp)
witdhs , - list of widths of columns
(when borderp
(draw-vline win
the first line is the top border , we start below the border .
(+ y bt)
x
(dotimes (j (1- n))
(draw-vline win
(+ y bt)
(+ x bl (* j cg) (loop for i from 0 to j sum (nth i widths)))
(+ (1- (* m 2))
(* m (+ pt pb)))))
(when borderp
(draw-vline win
the first line is the border top , we start below the border .
(+ y bt)
(+ x
bl
(* (1- n) cg)
(reduce #'+ widths))
draw m+1 horizontal lines ( with endings and crossings )
top horizontal line of the table , only drawn if borderp is t.
(when borderp
(move win y x)
(draw-table-top win widths))
(dotimes (i (- m 1))
(move win
(+ y bt (* i rg) (loop for j from 0 to i sum (nth j heights)))
x)
(draw-table-row-separator win widths borderp))
bottom line , only drawn if borderp is t.
(when borderp
(move win (+ y (* 2 m) (* m (+ pt pb))) x)
(draw-table-bottom win widths)))
(defun format-menu-item (menu item selectedp)
"Take a menu and return item item-number as a properly formatted string.
If the menu is a checklist, return [ ] or [X] at the first position.
If a mark is set for the current item, display the mark at the second position.
Display the same number of spaces for other items.
At the third position, display the item given by item-number."
(with-accessors ((type menu-type)
(current-item-number current-item-number)
(current-item-mark current-item-mark)) menu
(format nil "~A~A~A"
two types of menus : : selection or : checklist
(if (eq type :checklist)
(if (checkedp item) "[X] " "[ ] ")
"")
(if selectedp
current-item-mark
(make-string (length current-item-mark) :initial-element #\space))
(format-title item))))
(defmethod external-width ((obj menu-item))
(length (title obj)))
(defun draw-menu (win y x menu)
"Draw the menu to the window."
(with-slots (scrolling-enabled-p
variable-column-width-p
menu-type
item-padding-top
item-padding-bottom
item-padding-left
item-padding-right
(pl padding-left)
(pt padding-top)
(cmark current-item-mark)
(cpos current-item-position)
(len max-item-length)
(items children)
(borderp borderp)
(tablep tablep)
(r grid-row)
(c grid-column)
(m grid-rows)
(n grid-columns)
(m0 region-start-row)
(n0 region-start-column)
(m1 region-rows)
(n1 region-columns)
(rg grid-row-gap)
(cg grid-column-gap)
(bt border-width-top)
(bl border-width-left)) menu
(with-accessors ((style style)) menu
(clear menu)
(destructuring-bind (m0 n0 m1 n1)
(if scrolling-enabled-p (list m0 n0 m1 n1) (list 0 0 m n))
(let* ((widths- (mapcar (lambda (i) (+ i item-padding-left item-padding-right))
(if variable-column-width-p
(subseq (column-widths items (list m n)) n0 (+ n0 n1))
(loop for i below n1 collect len))))
(widths (if (eq menu-type :checklist)
(mapcar (lambda (i) (+ i 4)) widths-)
widths-))
(xs (cumsum-predecessors widths))
height of one item is 1 and the padding .
(h (+ 1 item-padding-top item-padding-bottom))
(heights (loop for i below m1 collect h)))
(when borderp
(if (typep menu 'window)
(draw-rectangle win y x
than the sum of its items , see t19e2 .
(if (slot-value win 'height)(slot-value win 'height) (external-height menu))
(if (slot-value win 'width) (slot-value win 'width) (external-width menu))
:style (getf style :border))
(draw-rectangle win y x
(external-height menu)
(external-width menu)
:style (getf style :border))))
(when tablep
(draw-table-lines win y x m1 n1 rg cg bt bl item-padding-top item-padding-bottom widths heights borderp))
(dogrid ((i 0 m1)
(j 0 n1))
(let* ((item (ref2d items (list m n) (+ m0 i) (+ n0 j)))
(selectedp (and (= i (- r m0)) (= j (- c n0))))
posy
posx)
(setq posy (+ y
(if borderp bt 0)
(if (and borderp (not tablep)) pt 0)
(* i rg)
(* i h))
posx (+ x
(if borderp bl 0)
(if (and borderp (not tablep)) pl 0)
(* j cg)
(nth j xs)))
(when selectedp
(setf cpos (list posy posx)))
(let ((fg-style (if style
(getf style (if selectedp :selected-foreground :foreground))
(if selectedp (list :attributes (list :reverse)) nil)))
(bg-style (if style
(getf style (if selectedp :selected-background :background))
(if selectedp (list :attributes (list :reverse)) nil))))
(when (plusp item-padding-top)
(dotimes (k item-padding-top)
(move win (+ posy k) posx)
(add win #\space :style bg-style :n (nth j widths))))
(move win (+ posy item-padding-top) posx)
write an empty string as the background first .
(save-excursion win (add win #\space :style bg-style :n (nth j widths)))
(add win
(format nil
(concatenate 'string
(make-string item-padding-left :initial-element #\space)
"~v,,,' A"
(make-string item-padding-right :initial-element #\space))
(- (nth j widths) item-padding-left item-padding-right)
(format-menu-item menu item selectedp))
:style fg-style)
(when (plusp item-padding-bottom)
(dotimes (k item-padding-bottom)
(move win (+ posy item-padding-top 1 k) posx)
(add win #\space :style bg-style :n (nth j widths))))))))
(refresh win)))))
(defmethod draw ((menu menu))
"Draw the menu to its associated window."
(draw-menu (window menu)
(car (widget-position menu))
(cadr (widget-position menu))
menu)
(update-cursor-position menu))
(defmethod draw ((menu menu-window))
"Draw the menu to position (0 0) of its window."
(draw-menu menu
0
0
menu))
(defun reset-menu (menu)
"After the menu is closed reset it to its initial state."
(with-slots (children current-item-number grid-row grid-column region-start-row region-start-column menu-type) menu
(setf current-item-number 0
grid-row 0
grid-column 0
region-start-row 0
region-start-column 0)
(when (eq menu-type :checklist)
(loop for i in children if (checkedp i) do (setf (checkedp i) nil)))))
(defparameter *menu-stack* (make-instance 'stack))
(defun return-from-menu (menu return-value)
"Pop the menu from the menu stack, refresh the remaining menu stack.
If the menu is not a window, clear the menu from the window.
Return the value from select."
(if (typep menu 'window)
(unless (stack-empty-p *menu-stack*)
(stack-pop *menu-stack*))
(unless (stack-empty-p *menu-stack*)
(stack-pop *menu-stack*)
(clear (window menu))
(when (draw-stack-p menu)
(mapc #'draw (reverse (items *menu-stack*))))
(refresh (window menu))))
(reset-menu menu)
(throw menu return-value))
(defun exit-menu-event-loop (menu)
"Associate this function with an event to exit the menu event loop."
(return-from-menu menu nil))
(defun checked-items (menu)
"Take a menu, return a list of checked menu items."
(loop for i in (items menu) if (checkedp i) collect i))
(defmethod value ((menu menu))
"Return the value of the selected item."
(value (current-item menu)))
(defmethod value ((checklist checklist))
"Return the list of values of the checked items."
(mapcar #'value (checked-items checklist)))
(defun accept-selection (menu)
"Return the value of the currently selected item or all checked items."
(case (menu-type menu)
(:checklist
when one or more items have been checked ,
(when (checked-items menu)
(return-from-menu menu (checked-items menu))))
(:selection
(let ((val (value (current-item menu))))
(cond
((or (typep val 'string)
(typep val 'symbol)
(typep val 'number))
(return-from-menu menu val))
((typep val 'function)
(funcall val)
(return-from-menu menu (name (current-item menu))))
((or (typep val 'menu)
(typep val 'menu-window))
(unless (draw-stack-p val)
(clear (window menu)))
(let ((selected-item (select val)))
when we have more than one menu in one window , redraw the parent menu after we return from the submenu .
(when (or (eq (type-of val) 'menu)
(eq (type-of val) 'checklist))
(draw menu))
(when selected-item
(return-from-menu menu selected-item)))) )))))
(defun toggle-item-checkbox (menu)
"Toggle the checked state of the current item, used in checkbox menus."
(setf (checkedp (current-item menu)) (not (checkedp (current-item menu))))
(draw menu))
(defun sync-collection-grid (obj)
"Sync the position in 1D collection list with the yx position in a 2D grid."
(with-slots (current-item-number grid-rows grid-columns grid-row grid-column) obj
(setf current-item-number (sub2rmi (list grid-rows grid-columns) (list grid-row grid-column)))))
(defun sync-grid-collection (obj)
"Set the 2D yx grid position from the 1D position in the collection list."
(with-slots ((i current-item-number)
(m grid-rows)
(n grid-columns)
(y grid-row)
(x grid-column)) obj
(setf y (car (rmi2sub (list m n) i))
x (cadr (rmi2sub (list m n) i)))))
(defmethod move-left ((obj menu))
(call-next-method obj)
(sync-collection-grid obj)
(draw obj))
(defmethod move-right ((obj menu))
(call-next-method obj)
(sync-collection-grid obj)
(draw obj))
(defmethod move-up ((obj menu))
(call-next-method obj)
(sync-collection-grid obj)
(draw obj))
(defmethod move-down ((obj menu))
(call-next-method obj)
(with-slots (current-item-number grid-rows grid-columns grid-row grid-column) obj
(setf current-item-number
(sub2rmi (list grid-rows grid-columns)
(list grid-row grid-column))))
(draw obj))
all of these take two arguments : menu event
(define-keymap menu-map
(:up 'move-up)
(:down 'move-down)
(:left 'move-left)
(:right 'move-right))
(define-keymap checklist-map
(#\x 'toggle-item-checkbox)
(:up 'move-up)
(:down 'move-down)
(:left 'move-left)
(:right 'move-right))
(define-keymap menu-window-map
(#\q 'exit-menu-event-loop)
(#\x 'toggle-item-checkbox)
(:up 'move-up)
(:down 'move-down)
(:left 'move-left)
(:right 'move-right)
return the selected item or all checked items , then exit the menu like q.
(#\newline 'accept-selection))
(defgeneric select (obj))
(defmethod select ((obj menu))
(stack-push obj *menu-stack*)
(draw obj)
(run-event-loop obj))
(defmethod select ((menu menu-window))
"Display the menu, let the user select an item, return the selected item.
If the selected item is a menu object, recursively display the sub menu."
(stack-push menu *menu-stack*)
(draw menu)
(let ((val (run-event-loop menu)))
(unless (stack-empty-p *main-stack*)
(refresh *main-stack*))
(unless (stack-empty-p *menu-stack*)
(refresh *menu-stack*))
val))
|
5eb4bacbbbbda04c2074b336f76f15a8e6d830bf4c37ca6301203d894382f053 | schell/odin | TextInput.hs | module Odin.Engine.GUI.TextInput
( TextInputState(..)
, TextInputData(..)
, TextInput
, slotTextInput
, renderTextInput
, sizeOfTextInput
) where
import Odin.Engine.GUI.TextInput.Internal
| null | https://raw.githubusercontent.com/schell/odin/97ae1610a7abd19aa150bc7dfc132082d88ca9ea/odin-engine/src/Odin/Engine/GUI/TextInput.hs | haskell | module Odin.Engine.GUI.TextInput
( TextInputState(..)
, TextInputData(..)
, TextInput
, slotTextInput
, renderTextInput
, sizeOfTextInput
) where
import Odin.Engine.GUI.TextInput.Internal
|
|
ecde6e31efe77cff80294c75e8cff4a04bf145fe6f79e9f63a260559fb57072a | azimut/shiny | drum.lisp | (in-package :shiny)
THIS SYNTX SUCKS ! ! !
(pa (quant 4) (repeat 4 '(60))
(mapcar #'rhythm `(1/4 2/4 ,(+ 2/4 1/8) 3/4))
60
11
(mapcar #'rhythm `(1/4 2/4 ,(+ 2/4 1/8) 3/4)))
(defmacro drumthis (time note beats velocity channel)
(alexandria:with-gensyms (lbeats nbeats)
`(let ((,lbeats (length ,beats))
(,nbeats (mapcar #'rhythm ,beats)))
(pa ,time (repeat ,lbeats (list ,note))
,nbeats ,velocity ,channel ,nbeats))))
;; ?
(drumthis (quant 4) 60 '(1/4 2/4 5/8 3/4) 60 3)
(p (quant 4) 60 60 1 0)
| null | https://raw.githubusercontent.com/azimut/shiny/774381a9bde21c4ec7e7092c7516dd13a5a50780/compositions/drafts/drum.lisp | lisp | ? | (in-package :shiny)
THIS SYNTX SUCKS ! ! !
(pa (quant 4) (repeat 4 '(60))
(mapcar #'rhythm `(1/4 2/4 ,(+ 2/4 1/8) 3/4))
60
11
(mapcar #'rhythm `(1/4 2/4 ,(+ 2/4 1/8) 3/4)))
(defmacro drumthis (time note beats velocity channel)
(alexandria:with-gensyms (lbeats nbeats)
`(let ((,lbeats (length ,beats))
(,nbeats (mapcar #'rhythm ,beats)))
(pa ,time (repeat ,lbeats (list ,note))
,nbeats ,velocity ,channel ,nbeats))))
(drumthis (quant 4) 60 '(1/4 2/4 5/8 3/4) 60 3)
(p (quant 4) 60 60 1 0)
|
c484327ed11a47e5591e7d4ee0726544f17db30df8fb692256c4cb05117b97d8 | atomvm/atomvm_lib | sx126x_cmd.erl | %%
Copyright ( c ) 2022 dushin.net
%% 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(sx126x_cmd).
%%%
%%% @doc
An SPI driver for the LoRa ( SX126X ) chipset .
%%%
This module can be used to send and receive messages using LoRa modulation .
%%% Currently, this module only supports point-to-point communications. This
module does not support LoRaWAN .
%%%
%%% References
SemTech SX126x data sheet : /#E0000000JelG/a/2R0000001Rbr/6EfVZUorrpoKFfvaF_Fkpgp5kzjiNyiAbqcpqh9qSjE
SemTech reference implementation : -net/sx126x_driver
%%% Python implementation (for interoperability testing): -tl/micropySX126X
%%%
%%% @end
-compile(export_all).
% -define(TRACE_ENABLED, true).
-include_lib("atomvm_lib/include/trace.hrl").
%%
%% SX126x command set
%%
The following SPI " commands " ( opcodes and arguments ) are used to configure
the SemTech SX126x modem .
%%
See section 13 ( commands interface ) for the meanings of these SPI commands .
%%
-define(EMPTY_BINARY, <<"">>).
-define(NOP, <<16#00:8>>).
-define(LORA_SYNC_WORD_ADDRESS, 16#0740).
@private
set_sync_word(SPI, SyncWord) ->
?TRACE("set_sync_word(~p)", [SyncWord]),
MSB = (SyncWord band 16#F0) bor 16#04,
LSB = ((SyncWord band 16#0F) bsl 4) bor 16#04,
Data = <<MSB:8, LSB:8>>,
_Response = write_register(SPI, ?LORA_SYNC_WORD_ADDRESS, Data),
ok.
-define(OCP_CURRENT_LIMIT_ADDRESS, 16#08E7).
@private
set_current_limit(SPI, CurrentLimit) ->
?TRACE("set_current_limit(~p)", [CurrentLimit]),
RawLimit = rational:divide(CurrentLimit * 2, 5),
TODO broken
Data = <<RawLimit:16>>,
_Response = write_register(SPI, ?OCP_CURRENT_LIMIT_ADDRESS, Data),
ok.
13.1.1 SetSleep
-define(SET_SLEEP_OPCODE, 16#84).
-define(SLEEP_START_COLD, 2#000).
-define(SLEEP_START_WARM, 2#100).
-define(SLEEP_RTC_DISABLE, 2#000).
-define(SLEEP_RTC_ENABLE, 2#001).
@private
set_sleep(SPI) ->
set_sleep(SPI, ?SLEEP_START_COLD, ?SLEEP_RTC_ENABLE).
@private
set_sleep(SPI, Start, RTC) ->
?TRACE("SetSleep(~p, ~p)", [Start, RTC]),
Data = <<(Start bor RTC):8>>,
write_command(SPI, ?SET_SLEEP_OPCODE, Data).
13.1.2 SetStandby
-define(SET_STANDBY_OPCODE, 16#80).
-define(STDBY_RC, 16#00).
-define(STDBY_XOSC, 16#01).
@private
set_standby(SPI) ->
set_standby(SPI, ?STDBY_RC).
set_standby_xosc(SPI) ->
set_standby(SPI, ?STDBY_XOSC).
@private
set_standby(SPI, StandbyConfig) ->
?TRACE("SetStandby(~p)", [StandbyConfig]),
Data = <<StandbyConfig:8>>,
write_command(SPI, ?SET_STANDBY_OPCODE, Data).
% %% 13.1.3 SetFS
% -define(SET_FS_OPCODE, 16#C1).
% %% @private
% set_fs(SPI) ->
? ( ) " , [ ] ) ,
write_command(SPI , ? SET_FS_OPCODE , ? EMPTY_BINARY ) .
13.1.4 SetTx
-define(SET_TX_OPCODE, 16#83).
-define(TX_TIMEOUT_DISABLE, 16#000000).
@private
set_tx(SPI) -> set_tx(SPI, ?TX_TIMEOUT_DISABLE).
@private
set_tx(SPI, Timeout) ->
?TRACE("SetTx(~p)", [Timeout]),
Data = <<Timeout:24>>,
write_command(SPI, ?SET_TX_OPCODE, Data).
13.1.5 SetRx
-define(SET_RX_OPCODE, 16#82).
-define(RX_SINGLE_MODE, 16#000000).
-define(RX_CONTINUOUS_MODE, 16#FFFFFF).
@private
set_rx(SPI) ->
set_rx(SPI, ?RX_CONTINUOUS_MODE).
@private
set_rx(SPI, Timeout) ->
?TRACE("SetRx(~p)", [Timeout]),
Data = <<Timeout:24>>,
write_command(SPI, ?SET_RX_OPCODE, Data).
% %% 13.1.6 StopTimerOnPreamble
-define(STOP_TIMER_ON_PREAMBLE_OPCODE , 16#9F ) .
-define(STOP_TIMER_ON_PREAMBLE_DISABLE , 16#00 ) .
% -define(STOP_TIMER_ON_PREAMBLE_ENABLE, 16#01).
% %% @private
% stop_timer_on_preamble(SPI, Value) ->
? ) " , [ Value ] ) ,
% Data = <<Value:8>>,
write_command(SPI , ? STOP_TIMER_ON_PREAMBLE_OPCODE , Data ) .
% %% 13.1.7 SetRxDutyCycle
-define(SET_RX_DUTY_CYCLE_OPCODE , ) .
% %% @private
set_rx_duty_cycle(SPI , RxPeriod , ) - >
? TRACE("SetRxDutyCycle(~p , ~p ) " , [ RxPeriod , ] ) ,
% Data = <<RxPeriod:24, SleepPeriod:24>>,
write_command(SPI , ? SET_RX_DUTY_CYCLE_OPCODE , Data ) .
% %% 13.1.8 SetCad
% -define(SET_CAD_OPCODE, 16#C5).
% %% @private
% set_cad(SPI) ->
? ( ) " , [ ] ) ,
write_command(SPI , ? SET_CAD_OPCODE , ? EMPTY_BINARY ) .
% % 13.1.9 SetTxContinuousWave
% -define(SET_TX_CONTINUOUS_WAVE_OPCODE, 16#D1).
% %% @private
% set_tx_continuous_wave(SPI) ->
% ?TRACE("SetTxContinuousWave()", []),
write_command(SPI , ? SET_TX_CONTINUOUS_WAVE_OPCODE , ? EMPTY_BINARY ) .
% % 13.1.10 SetTxInfinitePreamble
% -define(SET_TX_INFINITE_PREAMBLE_OPCODE, 16#D2).
% %% @private
% set_tx_infinite_preamble(SPI) ->
% ?TRACE("SetTxInfinitePreamble()", []),
write_command(SPI , ? SET_TX_INFINITE_PREAMBLE_OPCODE , ? EMPTY_BINARY ) .
13.1.11 SetRegulatorMode
-define(SET_REGULATOR_MODE_OPCODE, 16#96).
-define(REGULATOR_MODE_ONLY_LDO, 16#00).
-define(REGULATOR_MODE_DC_DC_LRO, 16#01).
set_regulator_mode(SPI) ->
set_regulator_mode(SPI, ?REGULATOR_MODE_DC_DC_LRO).
@private
set_regulator_mode(SPI, Mode) ->
?TRACE("SetRegulatorMode()", []),
Data = <<Mode:8>>,
write_command(SPI, ?SET_REGULATOR_MODE_OPCODE, Data).
13.1.12 CalibrateFunction
-define(CALIBRATE_FUNCTION_OPCODE, 16#89).
-define(RC64K_CALIBRATION_ENABLED, 16#01).
-define(RC13M_CALIBRATION_ENABLED, 16#02).
-define(PLL_CALIBRATION_ENABLED, 16#04).
-define(ADC_PULSE_CALIBRATION_ENABLED, 16#08).
-define(ADC_BULK_N_CALIBRATION_ENABLED, 16#10).
-define(ADC_BULK_P_CALIBRATION_ENABLED, 16#20).
-define(IMAGE_CALIBRATION_ENABLED, 16#40).
@private
calibration_all(SPI) ->
calibration_function(SPI, 16#7F).
@private
calibration_function(SPI, CalibParam) ->
?TRACE("CalibrateFunction(~p)", [CalibParam]),
Data = <<CalibParam:8>>,
write_command(SPI, ?CALIBRATE_FUNCTION_OPCODE, Data).
13.1.13 CalibrateImage
-define(CALIBRATE_IMAGE_OPCODE, 16#98).
-define(FREQ_BAND_430_440, <<16#6B:8, 16#6F:8>>).
-define(FREQ_BAND_470_510, <<16#75:8, 16#81:8>>).
-define(FREQ_BAND_779_787, <<16#C1:8, 16#C5:8>>).
-define(FREQ_BAND_863_870, <<16#D7:8, 16#DB:8>>).
-define(FREQ_BAND_902_928, <<16#E1:8, 16#E9:8>>).
calibrate_image(SPI) ->
%% TODO for now use defaults
calibrate_image(SPI, ?FREQ_BAND_902_928).
@private
calibrate_image(SPI, FreqBand) ->
?TRACE("CalibrateImage(~p)", [FreqBand]),
write_command(SPI, ?CALIBRATE_IMAGE_OPCODE, FreqBand).
13.1.14 SetPaConfig
-define(SET_PA_CONFIG_OPCODE, 16#95).
TODO parameterize -- see datasheet for optimal combinations
TODO parameterize
-define(SX1262_SEL, 16#00).
-define(PA_LUT, 16#01).
@private
set_pa_config(SPI, sx1262) ->
set_pa_config(SPI, ?PA_DUTY_CYCLE, ?HP_MAX, ?SX1262_SEL, ?PA_LUT).
@private
set_pa_config(SPI, PaDutyCycle, HpMax, DevSel, PaLut) ->
?TRACE("SetPaConfig(~p, ~p, ~p, ~p)", [PaDutyCycle, HpMax, DevSel, PaLut]),
Data = <<PaDutyCycle:8, HpMax:8, DevSel:8, PaLut:8>>,
write_command(SPI, ?SET_PA_CONFIG_OPCODE, Data).
13.1.15 SetRxTxFallbackMode
-define(SET_RX_TX_FALLBACK_MODE_OPCODE, 16#93).
-define(FALLBACK_MODE_FS, 16#40).
-define(FALLBACK_MODE_XOSC, 16#30).
-define(FALLBACK_MODE_RC, 16#20).
@private
set_rx_tx_fallback_mode(SPI, rc) ->
set_rx_tx_fallback_mode(SPI, ?FALLBACK_MODE_RC);
set_rx_tx_fallback_mode(SPI, FallbackMode) ->
?TRACE("SetRxTxFallbackMode(~p)", [FallbackMode]),
Data = <<FallbackMode:8>>,
write_command(SPI, ?SET_RX_TX_FALLBACK_MODE_OPCODE, Data).
13.2 Registers and Buffer Access
13.2.1 WriteRegister Function
-define(WRITE_REGISTER_OPCODE, 16#0D).
@private
write_register(SPI, Address, Data) ->
?TRACE("WriteRegister(~p, ~p)", [Address, Data]),
InputData = <<Address:16, Data/binary>>,
write_read_command(SPI, ?WRITE_REGISTER_OPCODE, InputData).
13.2.2 ReadRegister Function
-define(READ_REGISTER_OPCODE, 16#1D).
@private
read_register(SPI, Address, Len) ->
?TRACE("ReadRegister(~p, ~p, ~p)", [SPI, Address, Len]),
NopPayload = create_nop_payload(Len + 1, []),
InputData = <<Address:16, NopPayload/binary>>,
Response = write_read_command(SPI, ?READ_REGISTER_OPCODE, InputData),
<<_AddressStatus:2/binary, _FirstNopStatus:8, OutputData/binary>> = Response,
OutputData.
%% 13.2.3 WriteBuffer Function
-define(WRITE_BUFFER_OPCODE, 16#0E).
@private
write_buffer(SPI, Data) ->
write_buffer(SPI, 0, Data).
@private
write_buffer(SPI, Offset, Data) ->
?TRACE("WriteBuffer(~p, ~p)", [Offset, Data]),
InputData = <<Offset:8, Data/binary>>,
Response = write_read_command(SPI, ?WRITE_BUFFER_OPCODE, InputData),
Response.
%% 13.2.4 ReadBuffer Function
-define(READ_BUFFER_OPCODE, 16#1E).
@private
read_buffer(SPI, Offset, Len) ->
?TRACE("ReadBuffer(~p, ~p)", [Offset, Len]),
NopPayload = create_nop_payload(Len + 1, []),
InputData = <<Offset:8, NopPayload/binary>>,
Response = write_read_command(SPI, ?READ_BUFFER_OPCODE, InputData),
<<_RFU:8, _OffsetStatus:8, _FirstNopStatus:8, OutputData/binary>> = Response,
OutputData.
@private
create_nop_payload(0, Accum) ->
erlang:iolist_to_binary(Accum);
create_nop_payload(I, Accum) ->
create_nop_payload(I - 1, [?NOP|Accum]).
13.3 DIO and IRQ Control Functions
%% 13.3.1 SetDioIrqParams
-define(SET_DIO_IRQ_PARAMS_OPCODE, 16#08).
-define(IRQ_MASK_NONE, 2#0000000000).
-define(IRQ_MASK_TX_DONE, 2#0000000001).
-define(IRQ_MASK_RX_DONE, 2#0000000010).
-define(IRQ_MASK_PREABLE_DETECTED, 2#0000000100).
-define(IRQ_MASK_SYNC_WORD_VALID, 2#0000001000).
-define(IRQ_MASK_HEADER_VALID, 2#0000010000).
-define(IRQ_MASK_HEADER_ERR, 2#0000100000).
-define(IRQ_MASK_CRC_ERR, 2#0001000000).
-define(IRQ_MASK_CAD_DONE, 2#0010000000).
-define(IRQ_MASK_CAD_DETECTED, 2#0100000000).
-define(IRQ_MASK_TIMEOUT, 2#1000000000).
-define(IRQ_MASK_LIST, [
{?IRQ_MASK_TX_DONE, tx_done},
{?IRQ_MASK_RX_DONE, rx_done},
{?IRQ_MASK_PREABLE_DETECTED, preamble_detected},
{?IRQ_MASK_SYNC_WORD_VALID, sync_word_valid},
{?IRQ_MASK_HEADER_VALID, header_valid},
{?IRQ_MASK_HEADER_ERR, header_err},
{?IRQ_MASK_CRC_ERR, crc_err},
{?IRQ_MASK_CAD_DONE, cad_done},
{?IRQ_MASK_CAD_DETECTED, cad_detected},
{?IRQ_MASK_TIMEOUT, timeout}
]).
@private
clear_irq_params(SPI) ->
set_dio_irq_params(SPI, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE).
@private
set_tx_irq(SPI) ->
set_dio_irq_params(SPI, ?IRQ_MASK_TX_DONE, ?IRQ_MASK_TX_DONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE).
@private
set_rx_irq(SPI) ->
set_dio_irq_params(SPI, ?IRQ_MASK_RX_DONE, ?IRQ_MASK_RX_DONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE).
@private
set_dio_irq_params(SPI, IRQMask, DIO1Mask, DIO2Mask, DIO3Mask) ->
?TRACE("SetDioIrqParams(~p, ~p, ~p, ~p)", [IRQMask, DIO1Mask, DIO2Mask, DIO3Mask]),
Data = <<IRQMask:16, DIO1Mask:16, DIO2Mask:16, DIO3Mask:16>>,
write_command(SPI, ?SET_DIO_IRQ_PARAMS_OPCODE, Data).
13.3.3 GetIrqStatus
-define(GET_IRQ_STATUS_OPCODE, 16#12).
get_irq_status(SPI) ->
?TRACE("GetIrqStatus()", []),
Response = write_read_command(SPI, ?GET_IRQ_STATUS_OPCODE, <<?NOP/binary, ?NOP/binary, ?NOP/binary>>),
% ?TRACE("Response: ~p", [Response]),
<<_RFU:8, _Status:8, IrqStatus:16>> = Response,
[Mnemonic || {Mask, Mnemonic} <- ?IRQ_MASK_LIST, Mask band IrqStatus =/= 0].
13.3.4 ClearIrqStatus
-define(CLEAR_IRQ_STATUS_OPCODE, 16#02).
@private
clear_irq_status(SPI) ->
clear_irq_status(SPI, 16#03FF).
clear_irq_status(SPI, Mask) ->
?TRACE("ClearIrqStatus(~p)", [Mask]),
Data = <<Mask:16>>,
write_command(SPI, ?CLEAR_IRQ_STATUS_OPCODE, Data).
13.3.5 SetDIO2AsRfSwitchCtrl
-define(SET_DIO2_AS_RF_SWITCH_CTL_OPCODE, 16#9D).
-define(DIO2_AS_RF_SWITCH_DISABLE, 16#00).
-define(DIO2_AS_RF_SWITCH_ENABLE, 16#01).
@private
set_dio2_as_rf_switch_ctl(SPI, enable) ->
set_dio2_as_rf_switch_ctl(SPI, ?DIO2_AS_RF_SWITCH_ENABLE);
set_dio2_as_rf_switch_ctl(SPI, disable) ->
set_dio2_as_rf_switch_ctl(SPI, ?DIO2_AS_RF_SWITCH_DISABLE);
set_dio2_as_rf_switch_ctl(SPI, Enable) ->
?TRACE("SetDIO2AsRfSwitchCtrl(~p)", [Enable]),
Data = <<Enable:8>>,
write_command(SPI, ?SET_DIO2_AS_RF_SWITCH_CTL_OPCODE, Data).
13.3.6
-define(SET_DIO3_AS_TCXOC_CTL_OPCODE, 16#97).
-define(TCXOC_VOLTAGE_16, 16#00).
-define(TCXOC_VOLTAGE_17, 16#01).
-define(TCXOC_VOLTAGE_18, 16#02).
-define(TCXOC_VOLTAGE_22, 16#03).
-define(TCXOC_VOLTAGE_24, 16#04).
-define(TCXOC_VOLTAGE_27, 16#05).
-define(TCXOC_VOLTAGE_30, 16#06).
-define(TCXOC_VOLTAGE_33, 16#07).
@private
set_dio3_as_tcxoc_ctl(SPI) ->
set_dio3_as_tcxoc_ctl(SPI, v_17, 320).
@private
set_dio3_as_tcxoc_ctl(SPI, Voltage, Delay) ->
?TRACE("SetDIO3AsTCXOCtrl(~p, ~p)", [Voltage, Delay]),
V = get_voltage(Voltage),
Data = <<V:8, Delay:24>>,
write_command(SPI, ?SET_DIO3_AS_TCXOC_CTL_OPCODE, Data).
@private
get_voltage(v_16) -> ?TCXOC_VOLTAGE_16;
get_voltage(v_17) -> ?TCXOC_VOLTAGE_17;
get_voltage(v_18) -> ?TCXOC_VOLTAGE_18;
get_voltage(v_22) -> ?TCXOC_VOLTAGE_22;
get_voltage(v_24) -> ?TCXOC_VOLTAGE_24;
get_voltage(v_27) -> ?TCXOC_VOLTAGE_27;
get_voltage(v_30) -> ?TCXOC_VOLTAGE_30;
get_voltage(v_33) -> ?TCXOC_VOLTAGE_33.
13.4 Modulation and Packet - Related Functions
13.4.1 SetRfFrequency
-define(SET_RF_FREQUENCY_OPCODE, 16#86).
@private
set_frequency(SPI, freq_169mhz) ->
% rational:reduce(rational:multiply(169000000, {16384,15625})).
% {177209344,1}
set_rf_frequency(SPI, 177209344);
set_frequency(SPI, freq_433mhz) ->
% rational:reduce(rational:multiply(433000000, {16384,15625})).
{ 454033408,1 }
set_rf_frequency(SPI, 454033408);
set_frequency(SPI, freq_868mhz) ->
rational : reduce(rational : , { 16384,15625 } ) ) .
{ 910163968,1 }
set_rf_frequency(SPI, 910163968);
set_frequency(SPI, freq_915mhz) ->
rational : reduce(rational : multiply(915000000 , { 16384,15625 } ) ) .
% {959447040,1}
set_rf_frequency(SPI, 959447040);
set_frequency(SPI, Freq) when is_integer(Freq) ->
Caution : requires fix for parsing external terms > 0x0FFFFFFF
%% from datasheet
%%
%% RF * F
Freq
%% RF = --------------------
frequency 25
2
%%
Where F_{XTAL } =
%%
{F, _} = rational:simplify(
rational:reduce(
rational:multiply(
Freq,
2 ^ 25/32Mhz or rational : reduce(rational : 25 , 32000000 ) )
)
)
),
set_rf_frequency(SPI, F).
@private
set_rf_frequency(SPI, F) when is_integer(F) ->
?TRACE("SetRfFrequency(~p)", [F]),
% Data = <<F:32>>,
Data = <<
((F bsr 24) band 16#FF):8,
((F bsr 16) band 16#FF):8,
((F bsr 8) band 16#FF):8,
(F band 16#FF):8
>>,
write_command(SPI, ?SET_RF_FREQUENCY_OPCODE, Data).
13.4.2 SetPacketType
-define(SET_PACKET_TYPE_OPCODE, 16#8A).
-define(PACKET_TYPE_GFSK, 16#00).
-define(PACKET_TYPE_LORA, 16#01).
@private
set_lora_packet_type(SPI) -> set_packet_type(SPI, ?PACKET_TYPE_LORA).
@private
set_packet_type(SPI, PacketType) ->
?TRACE("SetPacketType(~p)", [PacketType]),
Data = <<PacketType:8>>,
write_command(SPI, ?SET_PACKET_TYPE_OPCODE, Data).
13.4.3 GetPacketType
-define(GET_PACKET_TYPE_OPCODE, 16#11).
get_packet_type(SPI) ->
?TRACE("GetPacketType()", []),
Data = create_nop_payload(2, []),
Response = write_read_command(SPI, ?GET_PACKET_TYPE_OPCODE, Data),
<<_RFU:8, _Status:8, PacketType:8>> = Response,
PacketType.
% 13.4.4 SetTxParams
-define(SET_TX_PARAMS_OPCODE, 16#8E).
-define(TX_PARAMS_RAMP_10U, 16#00).
-define(TX_PARAMS_RAMP_20U, 16#01).
-define(TX_PARAMS_RAMP_40U, 16#02).
-define(TX_PARAMS_RAMP_80U, 16#03).
-define(TX_PARAMS_RAMP_200U, 16#04).
-define(TX_PARAMS_RAMP_800U, 16#05).
-define(TX_PARAMS_RAMP_1700U, 16#06).
-define(TX_PARAMS_RAMP_3400U, 16#07).
@private
set_tx_params(SPI, Power) ->
set_tx_params(SPI, Power, ?TX_PARAMS_RAMP_200U).
@private
set_tx_params(SPI, Power, RampTime) when -9 =< Power andalso Power =< 22 andalso 16#00 =< RampTime andalso RampTime =< 16#07 ->
?TRACE("SetTxParams(~p, ~p)", [Power, RampTime]),
Data = <<Power:8, RampTime:8>>,
write_command(SPI, ?SET_TX_PARAMS_OPCODE, Data).
%% 13.4.5 SetModulationParams
-define(SET_MODULATION_PARAMS_OPCODE, 16#8B).
@private
set_modulation_params(SPI, SpreadingFactor, BandWidth, CodingRate, LowDataRateOptimize) ->
SF = sf_value(SpreadingFactor),
BW = bw_value(BandWidth),
CR = cr_value(CodingRate),
LDRO = ldro_value(LowDataRateOptimize),
?TRACE("SetModulationParams(~p, ~p, ~p, ~p)", [SF, BW, CR, LDRO]),
Data = <<SF:8, BW:8, CR:8, LDRO:8>>,
write_command(SPI, ?SET_MODULATION_PARAMS_OPCODE, Data).
@private
sf_value(sf_5) -> 16#05;
sf_value(sf_6) -> 16#06;
sf_value(sf_7) -> 16#07;
sf_value(sf_8) -> 16#08;
sf_value(sf_9) -> 16#09;
sf_value(sf_10) -> 16#0A;
sf_value(sf_11) -> 16#0B;
sf_value(sf_12) -> 16#0C;
sf_value(X) when is_integer(X) ->
io:format("WARNING: Using deprecated spreading factor integer value (~p) -- Use atomic mnemonics, instead.~n", [X]),
X.
@private
bw_value(bw_7_8khz) -> 16#00;
bw_value(bw_10_4khz) -> 16#08;
bw_value(bw_15_6khz) -> 16#01;
bw_value(bw_20_8khz) -> 16#09;
bw_value(bw_31_25khz) -> 16#02;
bw_value(bw_41_7khz) -> 16#0A;
bw_value(bw_62_5khz) -> 16#03;
bw_value(bw_125khz) -> 16#04;
bw_value(bw_250khz) -> 16#05;
bw_value(bw_500khz) -> 16#06.
@private
cr_value(cr_4_5) -> 16#01;
cr_value(cr_4_6) -> 16#02;
cr_value(cr_4_7) -> 16#03;
cr_value(cr_4_8) -> 16#04.
@private
ldro_value(off) -> 16#00;
ldro_value(on) -> 16#01.
13.4.6 SetPacketParams
-define(SET_PACKET_PARAMS_OPCODE, 16#8C).
@private
set_packet_params(SPI, PreambleLength, HeaderType, PayloadLength, CRCType, InvertIQ) ->
HT = ht_value(HeaderType),
CRC = crc_value(CRCType),
IIRQ = iirq_value(InvertIQ),
?TRACE("SetPacketParams(~p, ~p, ~p, ~p, ~p)", [PreambleLength, HT, PayloadLength, CRC, IIRQ]),
Data = <<PreambleLength:16, HT:8, PayloadLength:8, CRC:8, IIRQ:8>>,
write_command(SPI, ?SET_PACKET_PARAMS_OPCODE, Data).
@private
ht_value(explicit) -> 16#00;
ht_value(implicit) -> 16#01.
@private
crc_value(false) -> 16#00;
crc_value(true) -> 16#01.
@private
iirq_value(false) -> 16#00;
iirq_value(true) -> 16#01.
13.4.7 SetCadParams
-define(SET_CAD_PARAMS_OPCODE, 16#88).
-define(CAD_ON_1_SYMB, 16#00).
-define(CAD_ON_2_SYMB, 16#01).
-define(CAD_ON_4_SYMB, 16#02).
-define(CAD_ON_8_SYMB, 16#03).
-define(CAD_ON_16_SYMB, 16#04).
-define(CAD_ONLY, 16#00).
-define(CAD_RX, 16#01).
@private
set_cad_params(SPI) ->
% data[0] = SX126X_CAD_ON_8_SYMB
data[1 ] = self._sf + 13
data[2 ] = 10
data[3 ] = SX126X_CAD_GOTO_STDBY
data[4 ] = 0x00
data[5 ] = 0x00
data[6 ] = 0x00
set_cad_params(SPI, ?CAD_ON_8_SYMB, 16#19, 10, ?CAD_ONLY, 0).
@private
set_cad_params(SPI, CadSymbolNum, CadDetPeak, CadDetMin, CadExitMode, CadTimeout) ->
?TRACE("SetCadParams(~p, ~p, ~p, ~p, ~p)", [CadSymbolNum, CadDetPeak, CadDetMin, CadExitMode, CadTimeout]),
Data = <<CadSymbolNum:8, CadDetPeak:8, CadDetMin:8, CadExitMode:8, CadTimeout:24>>,
write_command(SPI, ?SET_CAD_PARAMS_OPCODE, Data).
%% 13.4.8 SetBufferBaseAddress
-define(SET_BUFFER_ADDRESS_OPCODE, 16#8F).
set_buffer_base_address(SPI, TXBaseAddress, RXBaseAddres) ->
?TRACE("SetBufferBaseAddress(~p, ~p)", [TXBaseAddress, RXBaseAddres]),
Data = <<TXBaseAddress:8, RXBaseAddres:8>>,
write_command(SPI, ?SET_BUFFER_ADDRESS_OPCODE, Data).
%% 13.4.9 SetLoRaSymbNumTimeout
-define(SET_LORA_SYMB_NUM_TIMEOUT_OPCODE, 16#A0).
13.5 Communication Status Information
13.5.1 GetStatus
-define(GET_STATUS_OPCODE, 16#C0).
get_status(SPI) ->
?TRACE("GetStatus()", []),
write_read_command(SPI, ?GET_STATUS_OPCODE, ?NOP).
13.5.2 GetRxBufferStatus
-define(GET_RX_BUFFER_STATUS_OPCODE, 16#13).
get_rx_buffer_status(SPI) ->
?TRACE("GetRxBufferStatus()", []),
Data = create_nop_payload(3, []),
Response = write_read_command(SPI, ?GET_RX_BUFFER_STATUS_OPCODE, Data),
<<_RFU:8, _Status:8, PayloadLengthRx:8, RxStartBufferPointer:8>> = Response,
{PayloadLengthRx, RxStartBufferPointer}.
%% 13.5.3 GetPacketStatus
-define(GET_PACKET_STATUS_OPCODE, 16#14).
get_packet_status(SPI) ->
?TRACE("GetPacketStatus()", []),
Data = create_nop_payload(4, []),
Response = write_read_command(SPI, ?GET_PACKET_STATUS_OPCODE, Data),
<<_RFU:8, _Status:8, RssiPkt:8, SnrPkt:8, SignalRssiPkt>> = Response,
{ RssiPkt , SnrPkt , SignalRssiPkt } .
{-1 * RssiPkt div 2, SnrPkt div 4, -1 * SignalRssiPkt div 2}.
13.5.4 GetRssiInst
-define(GET_RSSI_INST_OPCODE, 16#15).
13.5.5 GetStats
-define(GET_STATS_OPCODE, 16#10).
13.5.6 ResetStats
-define(RESET_STATS_OPCODE, 16#00).
13.6 Miscellaneous
%% 13.6.1 GetDeviceErrors
-define(GET_DEVICE_ERRORS_OPCODE, 16#17).
get_device_errors(SPI) ->
?TRACE("GetDeviceErrors()", []),
Data = create_nop_payload(3, []),
Response = write_read_command(SPI, ?GET_DEVICE_ERRORS_OPCODE, Data),
<<_RFU:8, _Status:8, OpError:16>> = Response,
OpError.
13.6.2 ClearDeviceErrors
-define(CLEAR_DEVICE_ERRORS_OPCODE, 16#07).
clear_device_errors(SPI) ->
?TRACE("ClearDeviceErrors()", []),
Data = create_nop_payload(2, []),
Response = write_read_command(SPI, ?CLEAR_DEVICE_ERRORS_OPCODE, Data),
<<_RFU:8, Status:16>> = Response,
Status.
%%
%% internal functions
%%
% %% @private
% read_command({SPI, DeviceName}, OpCode) ->
{ ok , read_at(SPI , DeviceName , OpCode , 8) ,
< < Data:8 > > = ,
% {ok, Data}.
@private
write_command({SPI, DeviceName}, OpCode, Data) ->
Payload = <<OpCode:8, Data/binary>>,
% ?TRACE("[erl] write [~s]", [atomvm_lib:to_hex(Payload)]),
Result = spi:write(SPI, DeviceName, #{write_data => Payload}),
Result.
@private
write_read_command({SPI, DeviceName}, OpCode, Data) ->
Payload = <<OpCode:8, Data/binary>>,
{ok, Response} = spi:write_read(SPI, DeviceName, #{write_data => Payload}),
% ?TRACE("[erl] write-read [~s] -> [~s]", [atomvm_lib:to_hex(Payload), atomvm_lib:to_hex(Response)]),
Response.
| null | https://raw.githubusercontent.com/atomvm/atomvm_lib/0a35b8efc334a97fcc4e23d4d948962160e5fd4d/src/sx126x_cmd.erl | erlang |
All rights reserved.
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc
Currently, this module only supports point-to-point communications. This
References
Python implementation (for interoperability testing): -tl/micropySX126X
@end
-define(TRACE_ENABLED, true).
SX126x command set
%% 13.1.3 SetFS
-define(SET_FS_OPCODE, 16#C1).
%% @private
set_fs(SPI) ->
%% 13.1.6 StopTimerOnPreamble
-define(STOP_TIMER_ON_PREAMBLE_ENABLE, 16#01).
%% @private
stop_timer_on_preamble(SPI, Value) ->
Data = <<Value:8>>,
%% 13.1.7 SetRxDutyCycle
%% @private
Data = <<RxPeriod:24, SleepPeriod:24>>,
%% 13.1.8 SetCad
-define(SET_CAD_OPCODE, 16#C5).
%% @private
set_cad(SPI) ->
% 13.1.9 SetTxContinuousWave
-define(SET_TX_CONTINUOUS_WAVE_OPCODE, 16#D1).
%% @private
set_tx_continuous_wave(SPI) ->
?TRACE("SetTxContinuousWave()", []),
% 13.1.10 SetTxInfinitePreamble
-define(SET_TX_INFINITE_PREAMBLE_OPCODE, 16#D2).
%% @private
set_tx_infinite_preamble(SPI) ->
?TRACE("SetTxInfinitePreamble()", []),
TODO for now use defaults
13.2.3 WriteBuffer Function
13.2.4 ReadBuffer Function
13.3.1 SetDioIrqParams
?TRACE("Response: ~p", [Response]),
rational:reduce(rational:multiply(169000000, {16384,15625})).
{177209344,1}
rational:reduce(rational:multiply(433000000, {16384,15625})).
{959447040,1}
from datasheet
RF * F
RF = --------------------
Data = <<F:32>>,
13.4.4 SetTxParams
13.4.5 SetModulationParams
data[0] = SX126X_CAD_ON_8_SYMB
13.4.8 SetBufferBaseAddress
13.4.9 SetLoRaSymbNumTimeout
13.5.3 GetPacketStatus
13.6.1 GetDeviceErrors
internal functions
%% @private
read_command({SPI, DeviceName}, OpCode) ->
{ok, Data}.
?TRACE("[erl] write [~s]", [atomvm_lib:to_hex(Payload)]),
?TRACE("[erl] write-read [~s] -> [~s]", [atomvm_lib:to_hex(Payload), atomvm_lib:to_hex(Response)]), | Copyright ( c ) 2022 dushin.net
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(sx126x_cmd).
An SPI driver for the LoRa ( SX126X ) chipset .
This module can be used to send and receive messages using LoRa modulation .
module does not support LoRaWAN .
SemTech SX126x data sheet : /#E0000000JelG/a/2R0000001Rbr/6EfVZUorrpoKFfvaF_Fkpgp5kzjiNyiAbqcpqh9qSjE
SemTech reference implementation : -net/sx126x_driver
-compile(export_all).
-include_lib("atomvm_lib/include/trace.hrl").
The following SPI " commands " ( opcodes and arguments ) are used to configure
the SemTech SX126x modem .
See section 13 ( commands interface ) for the meanings of these SPI commands .
-define(EMPTY_BINARY, <<"">>).
-define(NOP, <<16#00:8>>).
-define(LORA_SYNC_WORD_ADDRESS, 16#0740).
@private
set_sync_word(SPI, SyncWord) ->
?TRACE("set_sync_word(~p)", [SyncWord]),
MSB = (SyncWord band 16#F0) bor 16#04,
LSB = ((SyncWord band 16#0F) bsl 4) bor 16#04,
Data = <<MSB:8, LSB:8>>,
_Response = write_register(SPI, ?LORA_SYNC_WORD_ADDRESS, Data),
ok.
-define(OCP_CURRENT_LIMIT_ADDRESS, 16#08E7).
@private
set_current_limit(SPI, CurrentLimit) ->
?TRACE("set_current_limit(~p)", [CurrentLimit]),
RawLimit = rational:divide(CurrentLimit * 2, 5),
TODO broken
Data = <<RawLimit:16>>,
_Response = write_register(SPI, ?OCP_CURRENT_LIMIT_ADDRESS, Data),
ok.
13.1.1 SetSleep
-define(SET_SLEEP_OPCODE, 16#84).
-define(SLEEP_START_COLD, 2#000).
-define(SLEEP_START_WARM, 2#100).
-define(SLEEP_RTC_DISABLE, 2#000).
-define(SLEEP_RTC_ENABLE, 2#001).
@private
set_sleep(SPI) ->
set_sleep(SPI, ?SLEEP_START_COLD, ?SLEEP_RTC_ENABLE).
@private
set_sleep(SPI, Start, RTC) ->
?TRACE("SetSleep(~p, ~p)", [Start, RTC]),
Data = <<(Start bor RTC):8>>,
write_command(SPI, ?SET_SLEEP_OPCODE, Data).
13.1.2 SetStandby
-define(SET_STANDBY_OPCODE, 16#80).
-define(STDBY_RC, 16#00).
-define(STDBY_XOSC, 16#01).
@private
set_standby(SPI) ->
set_standby(SPI, ?STDBY_RC).
set_standby_xosc(SPI) ->
set_standby(SPI, ?STDBY_XOSC).
@private
set_standby(SPI, StandbyConfig) ->
?TRACE("SetStandby(~p)", [StandbyConfig]),
Data = <<StandbyConfig:8>>,
write_command(SPI, ?SET_STANDBY_OPCODE, Data).
? ( ) " , [ ] ) ,
write_command(SPI , ? SET_FS_OPCODE , ? EMPTY_BINARY ) .
13.1.4 SetTx
-define(SET_TX_OPCODE, 16#83).
-define(TX_TIMEOUT_DISABLE, 16#000000).
@private
set_tx(SPI) -> set_tx(SPI, ?TX_TIMEOUT_DISABLE).
@private
set_tx(SPI, Timeout) ->
?TRACE("SetTx(~p)", [Timeout]),
Data = <<Timeout:24>>,
write_command(SPI, ?SET_TX_OPCODE, Data).
13.1.5 SetRx
-define(SET_RX_OPCODE, 16#82).
-define(RX_SINGLE_MODE, 16#000000).
-define(RX_CONTINUOUS_MODE, 16#FFFFFF).
@private
set_rx(SPI) ->
set_rx(SPI, ?RX_CONTINUOUS_MODE).
@private
set_rx(SPI, Timeout) ->
?TRACE("SetRx(~p)", [Timeout]),
Data = <<Timeout:24>>,
write_command(SPI, ?SET_RX_OPCODE, Data).
-define(STOP_TIMER_ON_PREAMBLE_OPCODE , 16#9F ) .
-define(STOP_TIMER_ON_PREAMBLE_DISABLE , 16#00 ) .
? ) " , [ Value ] ) ,
write_command(SPI , ? STOP_TIMER_ON_PREAMBLE_OPCODE , Data ) .
-define(SET_RX_DUTY_CYCLE_OPCODE , ) .
set_rx_duty_cycle(SPI , RxPeriod , ) - >
? TRACE("SetRxDutyCycle(~p , ~p ) " , [ RxPeriod , ] ) ,
write_command(SPI , ? SET_RX_DUTY_CYCLE_OPCODE , Data ) .
? ( ) " , [ ] ) ,
write_command(SPI , ? SET_CAD_OPCODE , ? EMPTY_BINARY ) .
write_command(SPI , ? SET_TX_CONTINUOUS_WAVE_OPCODE , ? EMPTY_BINARY ) .
write_command(SPI , ? SET_TX_INFINITE_PREAMBLE_OPCODE , ? EMPTY_BINARY ) .
13.1.11 SetRegulatorMode
-define(SET_REGULATOR_MODE_OPCODE, 16#96).
-define(REGULATOR_MODE_ONLY_LDO, 16#00).
-define(REGULATOR_MODE_DC_DC_LRO, 16#01).
set_regulator_mode(SPI) ->
set_regulator_mode(SPI, ?REGULATOR_MODE_DC_DC_LRO).
@private
set_regulator_mode(SPI, Mode) ->
?TRACE("SetRegulatorMode()", []),
Data = <<Mode:8>>,
write_command(SPI, ?SET_REGULATOR_MODE_OPCODE, Data).
13.1.12 CalibrateFunction
-define(CALIBRATE_FUNCTION_OPCODE, 16#89).
-define(RC64K_CALIBRATION_ENABLED, 16#01).
-define(RC13M_CALIBRATION_ENABLED, 16#02).
-define(PLL_CALIBRATION_ENABLED, 16#04).
-define(ADC_PULSE_CALIBRATION_ENABLED, 16#08).
-define(ADC_BULK_N_CALIBRATION_ENABLED, 16#10).
-define(ADC_BULK_P_CALIBRATION_ENABLED, 16#20).
-define(IMAGE_CALIBRATION_ENABLED, 16#40).
@private
calibration_all(SPI) ->
calibration_function(SPI, 16#7F).
@private
calibration_function(SPI, CalibParam) ->
?TRACE("CalibrateFunction(~p)", [CalibParam]),
Data = <<CalibParam:8>>,
write_command(SPI, ?CALIBRATE_FUNCTION_OPCODE, Data).
13.1.13 CalibrateImage
-define(CALIBRATE_IMAGE_OPCODE, 16#98).
-define(FREQ_BAND_430_440, <<16#6B:8, 16#6F:8>>).
-define(FREQ_BAND_470_510, <<16#75:8, 16#81:8>>).
-define(FREQ_BAND_779_787, <<16#C1:8, 16#C5:8>>).
-define(FREQ_BAND_863_870, <<16#D7:8, 16#DB:8>>).
-define(FREQ_BAND_902_928, <<16#E1:8, 16#E9:8>>).
calibrate_image(SPI) ->
calibrate_image(SPI, ?FREQ_BAND_902_928).
@private
calibrate_image(SPI, FreqBand) ->
?TRACE("CalibrateImage(~p)", [FreqBand]),
write_command(SPI, ?CALIBRATE_IMAGE_OPCODE, FreqBand).
13.1.14 SetPaConfig
-define(SET_PA_CONFIG_OPCODE, 16#95).
TODO parameterize -- see datasheet for optimal combinations
TODO parameterize
-define(SX1262_SEL, 16#00).
-define(PA_LUT, 16#01).
@private
set_pa_config(SPI, sx1262) ->
set_pa_config(SPI, ?PA_DUTY_CYCLE, ?HP_MAX, ?SX1262_SEL, ?PA_LUT).
@private
set_pa_config(SPI, PaDutyCycle, HpMax, DevSel, PaLut) ->
?TRACE("SetPaConfig(~p, ~p, ~p, ~p)", [PaDutyCycle, HpMax, DevSel, PaLut]),
Data = <<PaDutyCycle:8, HpMax:8, DevSel:8, PaLut:8>>,
write_command(SPI, ?SET_PA_CONFIG_OPCODE, Data).
13.1.15 SetRxTxFallbackMode
-define(SET_RX_TX_FALLBACK_MODE_OPCODE, 16#93).
-define(FALLBACK_MODE_FS, 16#40).
-define(FALLBACK_MODE_XOSC, 16#30).
-define(FALLBACK_MODE_RC, 16#20).
@private
set_rx_tx_fallback_mode(SPI, rc) ->
set_rx_tx_fallback_mode(SPI, ?FALLBACK_MODE_RC);
set_rx_tx_fallback_mode(SPI, FallbackMode) ->
?TRACE("SetRxTxFallbackMode(~p)", [FallbackMode]),
Data = <<FallbackMode:8>>,
write_command(SPI, ?SET_RX_TX_FALLBACK_MODE_OPCODE, Data).
13.2 Registers and Buffer Access
13.2.1 WriteRegister Function
-define(WRITE_REGISTER_OPCODE, 16#0D).
@private
write_register(SPI, Address, Data) ->
?TRACE("WriteRegister(~p, ~p)", [Address, Data]),
InputData = <<Address:16, Data/binary>>,
write_read_command(SPI, ?WRITE_REGISTER_OPCODE, InputData).
13.2.2 ReadRegister Function
-define(READ_REGISTER_OPCODE, 16#1D).
@private
read_register(SPI, Address, Len) ->
?TRACE("ReadRegister(~p, ~p, ~p)", [SPI, Address, Len]),
NopPayload = create_nop_payload(Len + 1, []),
InputData = <<Address:16, NopPayload/binary>>,
Response = write_read_command(SPI, ?READ_REGISTER_OPCODE, InputData),
<<_AddressStatus:2/binary, _FirstNopStatus:8, OutputData/binary>> = Response,
OutputData.
-define(WRITE_BUFFER_OPCODE, 16#0E).
@private
write_buffer(SPI, Data) ->
write_buffer(SPI, 0, Data).
@private
write_buffer(SPI, Offset, Data) ->
?TRACE("WriteBuffer(~p, ~p)", [Offset, Data]),
InputData = <<Offset:8, Data/binary>>,
Response = write_read_command(SPI, ?WRITE_BUFFER_OPCODE, InputData),
Response.
-define(READ_BUFFER_OPCODE, 16#1E).
@private
read_buffer(SPI, Offset, Len) ->
?TRACE("ReadBuffer(~p, ~p)", [Offset, Len]),
NopPayload = create_nop_payload(Len + 1, []),
InputData = <<Offset:8, NopPayload/binary>>,
Response = write_read_command(SPI, ?READ_BUFFER_OPCODE, InputData),
<<_RFU:8, _OffsetStatus:8, _FirstNopStatus:8, OutputData/binary>> = Response,
OutputData.
@private
create_nop_payload(0, Accum) ->
erlang:iolist_to_binary(Accum);
create_nop_payload(I, Accum) ->
create_nop_payload(I - 1, [?NOP|Accum]).
13.3 DIO and IRQ Control Functions
-define(SET_DIO_IRQ_PARAMS_OPCODE, 16#08).
-define(IRQ_MASK_NONE, 2#0000000000).
-define(IRQ_MASK_TX_DONE, 2#0000000001).
-define(IRQ_MASK_RX_DONE, 2#0000000010).
-define(IRQ_MASK_PREABLE_DETECTED, 2#0000000100).
-define(IRQ_MASK_SYNC_WORD_VALID, 2#0000001000).
-define(IRQ_MASK_HEADER_VALID, 2#0000010000).
-define(IRQ_MASK_HEADER_ERR, 2#0000100000).
-define(IRQ_MASK_CRC_ERR, 2#0001000000).
-define(IRQ_MASK_CAD_DONE, 2#0010000000).
-define(IRQ_MASK_CAD_DETECTED, 2#0100000000).
-define(IRQ_MASK_TIMEOUT, 2#1000000000).
-define(IRQ_MASK_LIST, [
{?IRQ_MASK_TX_DONE, tx_done},
{?IRQ_MASK_RX_DONE, rx_done},
{?IRQ_MASK_PREABLE_DETECTED, preamble_detected},
{?IRQ_MASK_SYNC_WORD_VALID, sync_word_valid},
{?IRQ_MASK_HEADER_VALID, header_valid},
{?IRQ_MASK_HEADER_ERR, header_err},
{?IRQ_MASK_CRC_ERR, crc_err},
{?IRQ_MASK_CAD_DONE, cad_done},
{?IRQ_MASK_CAD_DETECTED, cad_detected},
{?IRQ_MASK_TIMEOUT, timeout}
]).
@private
clear_irq_params(SPI) ->
set_dio_irq_params(SPI, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE).
@private
set_tx_irq(SPI) ->
set_dio_irq_params(SPI, ?IRQ_MASK_TX_DONE, ?IRQ_MASK_TX_DONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE).
@private
set_rx_irq(SPI) ->
set_dio_irq_params(SPI, ?IRQ_MASK_RX_DONE, ?IRQ_MASK_RX_DONE, ?IRQ_MASK_NONE, ?IRQ_MASK_NONE).
@private
set_dio_irq_params(SPI, IRQMask, DIO1Mask, DIO2Mask, DIO3Mask) ->
?TRACE("SetDioIrqParams(~p, ~p, ~p, ~p)", [IRQMask, DIO1Mask, DIO2Mask, DIO3Mask]),
Data = <<IRQMask:16, DIO1Mask:16, DIO2Mask:16, DIO3Mask:16>>,
write_command(SPI, ?SET_DIO_IRQ_PARAMS_OPCODE, Data).
13.3.3 GetIrqStatus
-define(GET_IRQ_STATUS_OPCODE, 16#12).
get_irq_status(SPI) ->
?TRACE("GetIrqStatus()", []),
Response = write_read_command(SPI, ?GET_IRQ_STATUS_OPCODE, <<?NOP/binary, ?NOP/binary, ?NOP/binary>>),
<<_RFU:8, _Status:8, IrqStatus:16>> = Response,
[Mnemonic || {Mask, Mnemonic} <- ?IRQ_MASK_LIST, Mask band IrqStatus =/= 0].
13.3.4 ClearIrqStatus
-define(CLEAR_IRQ_STATUS_OPCODE, 16#02).
@private
clear_irq_status(SPI) ->
clear_irq_status(SPI, 16#03FF).
clear_irq_status(SPI, Mask) ->
?TRACE("ClearIrqStatus(~p)", [Mask]),
Data = <<Mask:16>>,
write_command(SPI, ?CLEAR_IRQ_STATUS_OPCODE, Data).
13.3.5 SetDIO2AsRfSwitchCtrl
-define(SET_DIO2_AS_RF_SWITCH_CTL_OPCODE, 16#9D).
-define(DIO2_AS_RF_SWITCH_DISABLE, 16#00).
-define(DIO2_AS_RF_SWITCH_ENABLE, 16#01).
@private
set_dio2_as_rf_switch_ctl(SPI, enable) ->
set_dio2_as_rf_switch_ctl(SPI, ?DIO2_AS_RF_SWITCH_ENABLE);
set_dio2_as_rf_switch_ctl(SPI, disable) ->
set_dio2_as_rf_switch_ctl(SPI, ?DIO2_AS_RF_SWITCH_DISABLE);
set_dio2_as_rf_switch_ctl(SPI, Enable) ->
?TRACE("SetDIO2AsRfSwitchCtrl(~p)", [Enable]),
Data = <<Enable:8>>,
write_command(SPI, ?SET_DIO2_AS_RF_SWITCH_CTL_OPCODE, Data).
13.3.6
-define(SET_DIO3_AS_TCXOC_CTL_OPCODE, 16#97).
-define(TCXOC_VOLTAGE_16, 16#00).
-define(TCXOC_VOLTAGE_17, 16#01).
-define(TCXOC_VOLTAGE_18, 16#02).
-define(TCXOC_VOLTAGE_22, 16#03).
-define(TCXOC_VOLTAGE_24, 16#04).
-define(TCXOC_VOLTAGE_27, 16#05).
-define(TCXOC_VOLTAGE_30, 16#06).
-define(TCXOC_VOLTAGE_33, 16#07).
@private
set_dio3_as_tcxoc_ctl(SPI) ->
set_dio3_as_tcxoc_ctl(SPI, v_17, 320).
@private
set_dio3_as_tcxoc_ctl(SPI, Voltage, Delay) ->
?TRACE("SetDIO3AsTCXOCtrl(~p, ~p)", [Voltage, Delay]),
V = get_voltage(Voltage),
Data = <<V:8, Delay:24>>,
write_command(SPI, ?SET_DIO3_AS_TCXOC_CTL_OPCODE, Data).
@private
get_voltage(v_16) -> ?TCXOC_VOLTAGE_16;
get_voltage(v_17) -> ?TCXOC_VOLTAGE_17;
get_voltage(v_18) -> ?TCXOC_VOLTAGE_18;
get_voltage(v_22) -> ?TCXOC_VOLTAGE_22;
get_voltage(v_24) -> ?TCXOC_VOLTAGE_24;
get_voltage(v_27) -> ?TCXOC_VOLTAGE_27;
get_voltage(v_30) -> ?TCXOC_VOLTAGE_30;
get_voltage(v_33) -> ?TCXOC_VOLTAGE_33.
13.4 Modulation and Packet - Related Functions
13.4.1 SetRfFrequency
-define(SET_RF_FREQUENCY_OPCODE, 16#86).
@private
set_frequency(SPI, freq_169mhz) ->
set_rf_frequency(SPI, 177209344);
set_frequency(SPI, freq_433mhz) ->
{ 454033408,1 }
set_rf_frequency(SPI, 454033408);
set_frequency(SPI, freq_868mhz) ->
rational : reduce(rational : , { 16384,15625 } ) ) .
{ 910163968,1 }
set_rf_frequency(SPI, 910163968);
set_frequency(SPI, freq_915mhz) ->
rational : reduce(rational : multiply(915000000 , { 16384,15625 } ) ) .
set_rf_frequency(SPI, 959447040);
set_frequency(SPI, Freq) when is_integer(Freq) ->
Caution : requires fix for parsing external terms > 0x0FFFFFFF
Freq
frequency 25
2
Where F_{XTAL } =
{F, _} = rational:simplify(
rational:reduce(
rational:multiply(
Freq,
2 ^ 25/32Mhz or rational : reduce(rational : 25 , 32000000 ) )
)
)
),
set_rf_frequency(SPI, F).
@private
set_rf_frequency(SPI, F) when is_integer(F) ->
?TRACE("SetRfFrequency(~p)", [F]),
Data = <<
((F bsr 24) band 16#FF):8,
((F bsr 16) band 16#FF):8,
((F bsr 8) band 16#FF):8,
(F band 16#FF):8
>>,
write_command(SPI, ?SET_RF_FREQUENCY_OPCODE, Data).
13.4.2 SetPacketType
-define(SET_PACKET_TYPE_OPCODE, 16#8A).
-define(PACKET_TYPE_GFSK, 16#00).
-define(PACKET_TYPE_LORA, 16#01).
@private
set_lora_packet_type(SPI) -> set_packet_type(SPI, ?PACKET_TYPE_LORA).
@private
set_packet_type(SPI, PacketType) ->
?TRACE("SetPacketType(~p)", [PacketType]),
Data = <<PacketType:8>>,
write_command(SPI, ?SET_PACKET_TYPE_OPCODE, Data).
13.4.3 GetPacketType
-define(GET_PACKET_TYPE_OPCODE, 16#11).
get_packet_type(SPI) ->
?TRACE("GetPacketType()", []),
Data = create_nop_payload(2, []),
Response = write_read_command(SPI, ?GET_PACKET_TYPE_OPCODE, Data),
<<_RFU:8, _Status:8, PacketType:8>> = Response,
PacketType.
-define(SET_TX_PARAMS_OPCODE, 16#8E).
-define(TX_PARAMS_RAMP_10U, 16#00).
-define(TX_PARAMS_RAMP_20U, 16#01).
-define(TX_PARAMS_RAMP_40U, 16#02).
-define(TX_PARAMS_RAMP_80U, 16#03).
-define(TX_PARAMS_RAMP_200U, 16#04).
-define(TX_PARAMS_RAMP_800U, 16#05).
-define(TX_PARAMS_RAMP_1700U, 16#06).
-define(TX_PARAMS_RAMP_3400U, 16#07).
@private
set_tx_params(SPI, Power) ->
set_tx_params(SPI, Power, ?TX_PARAMS_RAMP_200U).
@private
set_tx_params(SPI, Power, RampTime) when -9 =< Power andalso Power =< 22 andalso 16#00 =< RampTime andalso RampTime =< 16#07 ->
?TRACE("SetTxParams(~p, ~p)", [Power, RampTime]),
Data = <<Power:8, RampTime:8>>,
write_command(SPI, ?SET_TX_PARAMS_OPCODE, Data).
-define(SET_MODULATION_PARAMS_OPCODE, 16#8B).
@private
set_modulation_params(SPI, SpreadingFactor, BandWidth, CodingRate, LowDataRateOptimize) ->
SF = sf_value(SpreadingFactor),
BW = bw_value(BandWidth),
CR = cr_value(CodingRate),
LDRO = ldro_value(LowDataRateOptimize),
?TRACE("SetModulationParams(~p, ~p, ~p, ~p)", [SF, BW, CR, LDRO]),
Data = <<SF:8, BW:8, CR:8, LDRO:8>>,
write_command(SPI, ?SET_MODULATION_PARAMS_OPCODE, Data).
@private
sf_value(sf_5) -> 16#05;
sf_value(sf_6) -> 16#06;
sf_value(sf_7) -> 16#07;
sf_value(sf_8) -> 16#08;
sf_value(sf_9) -> 16#09;
sf_value(sf_10) -> 16#0A;
sf_value(sf_11) -> 16#0B;
sf_value(sf_12) -> 16#0C;
sf_value(X) when is_integer(X) ->
io:format("WARNING: Using deprecated spreading factor integer value (~p) -- Use atomic mnemonics, instead.~n", [X]),
X.
@private
bw_value(bw_7_8khz) -> 16#00;
bw_value(bw_10_4khz) -> 16#08;
bw_value(bw_15_6khz) -> 16#01;
bw_value(bw_20_8khz) -> 16#09;
bw_value(bw_31_25khz) -> 16#02;
bw_value(bw_41_7khz) -> 16#0A;
bw_value(bw_62_5khz) -> 16#03;
bw_value(bw_125khz) -> 16#04;
bw_value(bw_250khz) -> 16#05;
bw_value(bw_500khz) -> 16#06.
@private
cr_value(cr_4_5) -> 16#01;
cr_value(cr_4_6) -> 16#02;
cr_value(cr_4_7) -> 16#03;
cr_value(cr_4_8) -> 16#04.
@private
ldro_value(off) -> 16#00;
ldro_value(on) -> 16#01.
13.4.6 SetPacketParams
-define(SET_PACKET_PARAMS_OPCODE, 16#8C).
@private
set_packet_params(SPI, PreambleLength, HeaderType, PayloadLength, CRCType, InvertIQ) ->
HT = ht_value(HeaderType),
CRC = crc_value(CRCType),
IIRQ = iirq_value(InvertIQ),
?TRACE("SetPacketParams(~p, ~p, ~p, ~p, ~p)", [PreambleLength, HT, PayloadLength, CRC, IIRQ]),
Data = <<PreambleLength:16, HT:8, PayloadLength:8, CRC:8, IIRQ:8>>,
write_command(SPI, ?SET_PACKET_PARAMS_OPCODE, Data).
@private
ht_value(explicit) -> 16#00;
ht_value(implicit) -> 16#01.
@private
crc_value(false) -> 16#00;
crc_value(true) -> 16#01.
@private
iirq_value(false) -> 16#00;
iirq_value(true) -> 16#01.
13.4.7 SetCadParams
-define(SET_CAD_PARAMS_OPCODE, 16#88).
-define(CAD_ON_1_SYMB, 16#00).
-define(CAD_ON_2_SYMB, 16#01).
-define(CAD_ON_4_SYMB, 16#02).
-define(CAD_ON_8_SYMB, 16#03).
-define(CAD_ON_16_SYMB, 16#04).
-define(CAD_ONLY, 16#00).
-define(CAD_RX, 16#01).
@private
set_cad_params(SPI) ->
data[1 ] = self._sf + 13
data[2 ] = 10
data[3 ] = SX126X_CAD_GOTO_STDBY
data[4 ] = 0x00
data[5 ] = 0x00
data[6 ] = 0x00
set_cad_params(SPI, ?CAD_ON_8_SYMB, 16#19, 10, ?CAD_ONLY, 0).
@private
set_cad_params(SPI, CadSymbolNum, CadDetPeak, CadDetMin, CadExitMode, CadTimeout) ->
?TRACE("SetCadParams(~p, ~p, ~p, ~p, ~p)", [CadSymbolNum, CadDetPeak, CadDetMin, CadExitMode, CadTimeout]),
Data = <<CadSymbolNum:8, CadDetPeak:8, CadDetMin:8, CadExitMode:8, CadTimeout:24>>,
write_command(SPI, ?SET_CAD_PARAMS_OPCODE, Data).
-define(SET_BUFFER_ADDRESS_OPCODE, 16#8F).
set_buffer_base_address(SPI, TXBaseAddress, RXBaseAddres) ->
?TRACE("SetBufferBaseAddress(~p, ~p)", [TXBaseAddress, RXBaseAddres]),
Data = <<TXBaseAddress:8, RXBaseAddres:8>>,
write_command(SPI, ?SET_BUFFER_ADDRESS_OPCODE, Data).
-define(SET_LORA_SYMB_NUM_TIMEOUT_OPCODE, 16#A0).
13.5 Communication Status Information
13.5.1 GetStatus
-define(GET_STATUS_OPCODE, 16#C0).
get_status(SPI) ->
?TRACE("GetStatus()", []),
write_read_command(SPI, ?GET_STATUS_OPCODE, ?NOP).
13.5.2 GetRxBufferStatus
-define(GET_RX_BUFFER_STATUS_OPCODE, 16#13).
get_rx_buffer_status(SPI) ->
?TRACE("GetRxBufferStatus()", []),
Data = create_nop_payload(3, []),
Response = write_read_command(SPI, ?GET_RX_BUFFER_STATUS_OPCODE, Data),
<<_RFU:8, _Status:8, PayloadLengthRx:8, RxStartBufferPointer:8>> = Response,
{PayloadLengthRx, RxStartBufferPointer}.
-define(GET_PACKET_STATUS_OPCODE, 16#14).
get_packet_status(SPI) ->
?TRACE("GetPacketStatus()", []),
Data = create_nop_payload(4, []),
Response = write_read_command(SPI, ?GET_PACKET_STATUS_OPCODE, Data),
<<_RFU:8, _Status:8, RssiPkt:8, SnrPkt:8, SignalRssiPkt>> = Response,
{ RssiPkt , SnrPkt , SignalRssiPkt } .
{-1 * RssiPkt div 2, SnrPkt div 4, -1 * SignalRssiPkt div 2}.
13.5.4 GetRssiInst
-define(GET_RSSI_INST_OPCODE, 16#15).
13.5.5 GetStats
-define(GET_STATS_OPCODE, 16#10).
13.5.6 ResetStats
-define(RESET_STATS_OPCODE, 16#00).
13.6 Miscellaneous
-define(GET_DEVICE_ERRORS_OPCODE, 16#17).
get_device_errors(SPI) ->
?TRACE("GetDeviceErrors()", []),
Data = create_nop_payload(3, []),
Response = write_read_command(SPI, ?GET_DEVICE_ERRORS_OPCODE, Data),
<<_RFU:8, _Status:8, OpError:16>> = Response,
OpError.
13.6.2 ClearDeviceErrors
-define(CLEAR_DEVICE_ERRORS_OPCODE, 16#07).
clear_device_errors(SPI) ->
?TRACE("ClearDeviceErrors()", []),
Data = create_nop_payload(2, []),
Response = write_read_command(SPI, ?CLEAR_DEVICE_ERRORS_OPCODE, Data),
<<_RFU:8, Status:16>> = Response,
Status.
{ ok , read_at(SPI , DeviceName , OpCode , 8) ,
< < Data:8 > > = ,
@private
write_command({SPI, DeviceName}, OpCode, Data) ->
Payload = <<OpCode:8, Data/binary>>,
Result = spi:write(SPI, DeviceName, #{write_data => Payload}),
Result.
@private
write_read_command({SPI, DeviceName}, OpCode, Data) ->
Payload = <<OpCode:8, Data/binary>>,
{ok, Response} = spi:write_read(SPI, DeviceName, #{write_data => Payload}),
Response.
|
400b9efbab333204b15c575feb969aa884817391e553189c4eb4b8fe68b4b6d8 | rtoy/ansi-cl-tests | max.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Sun Aug 3 15:55:17 2003
Contains : Tests of MAX
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
;;; Error tests
(deftest max.error.1
(signals-error (max) program-error)
t)
(deftest max.error.2
(check-type-error #'max #'realp)
nil)
(deftest max.error.3
(check-type-error #'(lambda (x) (max 0 x)) #'realp)
nil)
;;; Non-error tests
(deftest max.1
(loop for n in *reals*
when (or (not (eql (max n) n))
(not (eql (max n n) n))
(not (eql (max n n n) n))
(not (eql (apply #'max (make-list
(min 256 (1- call-arguments-limit))
:initial-element n))
n)))
collect n)
nil)
(deftest max.2
(max.2-fn)
nil)
(deftest max.3
(loop for x = (- (random 60000) 30000)
for y = (- (random 60000) 30000)
for m = (max x y)
for m2 = (if (>= x y) x y)
repeat 1000
unless (eql m m2)
collect (list x y m m2))
nil)
(deftest max.4
(loop for x = (- (random 6000000) 3000000)
for y = (- (random 6000000) 3000000)
for m = (max x y)
for m2 = (if (>= x y) x y)
repeat 1000
unless (eql m m2)
collect (list x y m m2))
nil)
(deftest max.5
(loop for x = (- (random 1000000000000) 500000000000)
for y = (- (random 1000000000000) 500000000000)
for m = (max x y)
for m2 = (if (>= x y) x y)
repeat 1000
unless (eql m m2)
collect (list x y m m2))
nil)
(deftest max.6
(let ((m (max 2 1.0s0)))
(or (eqlt m 2)
(eqlt m 2.0s0)))
t)
(deftest max.7
(max 0 1.0s0)
1.0s0)
(deftest max.8
(let ((m (max 2 1.0f0)))
(or (eqlt m 2)
(eqlt m 2.0f0)))
t)
(deftest max.9
(max 0 1.0f0)
1.0f0)
(deftest max.10
(let ((m (max 2 1.0d0)))
(or (eqlt m 2)
(eqlt m 2.0d0)))
t)
(deftest max.11
(max 0 1.0d0)
1.0d0)
(deftest max.12
(let ((m (max 2 1.0l0)))
(or (eqlt m 2)
(eqlt m 2.0l0)))
t)
(deftest max.13
(max 0 1.0l0)
1.0l0)
(deftest max.15
(let ((m (max 1.0s0 0.0f0)))
(or (eqlt m 1.0s0)
(eqlt m 1.0f0)))
t)
(deftest max.16
(max 0.0s0 1.0f0)
1.0f0)
(deftest max.17
(let ((m (max 1.0s0 0.0d0)))
(or (eqlt m 1.0s0)
(eqlt m 1.0d0)))
t)
(deftest max.18
(max 0.0s0 1.0d0)
1.0d0)
(deftest max.19
(let ((m (max 1.0s0 0.0l0)))
(or (eqlt m 1.0s0)
(eqlt m 1.0l0)))
t)
(deftest max.20
(max 0.0s0 1.0l0)
1.0l0)
(deftest max.21
(let ((m (max 1.0f0 0.0d0)))
(or (eqlt m 1.0f0)
(eqlt m 1.0d0)))
t)
(deftest max.22
(max 0.0f0 1.0d0)
1.0d0)
(deftest max.23
(let ((m (max 1.0f0 0.0l0)))
(or (eqlt m 1.0f0)
(eqlt m 1.0l0)))
t)
(deftest max.24
(max 0.0f0 1.0l0)
1.0l0)
(deftest max.25
(let ((m (max 1.0d0 0.0l0)))
(or (eqlt m 1.0d0)
(eqlt m 1.0l0)))
t)
(deftest max.26
(max 0.0d0 1.0l0)
1.0l0)
(deftest max.27
(loop for i from 1 to (min 256 (1- call-arguments-limit))
for x = (make-list i :initial-element 0)
do (setf (elt x (random i)) 1)
unless (eql (apply #'max x) 1)
collect x)
nil)
(deftest max.28
(let ((m (max 1/3 0.2s0)))
(or (eqlt m 1/3)
(eqlt m (float 1/3 0.2s0))))
t)
(deftest max.29
(let ((m (max 1.0s0 3 2.0f0)))
(or (eqlt m 3)
(eqlt m 3.0f0)))
t)
(deftest max.30
(let ((m (max 1.0d0 3 2.0f0)))
(or (eqlt m 3)
(eqlt m 3.0d0)))
t)
(deftest max.31
(let ((m (max 1.0s0 3 2.0l0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.32
(let ((m (max 1.0l0 3 2.0s0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.33
(let ((m (max 1.0d0 3 2.0l0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.34
(let ((m (max 1.0l0 3 2.0d0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.order.1
(let ((i 0) x y)
(values
(max (progn (setf x (incf i)) 10)
(progn (setf y (incf i)) 20))
i x y))
20 2 1 2)
(deftest max.order.2
(let ((i 0) x y z)
(values
(max (progn (setf x (incf i)) 10)
(progn (setf y (incf i)) 20)
(progn (setf z (incf i)) 30))
i x y z))
30 3 1 2 3)
(deftest max.order.3
(let ((i 0) u v w x y z)
(values
(max (progn (setf u (incf i)) 10)
(progn (setf v (incf i)) 20)
(progn (setf w (incf i)) 30)
(progn (setf x (incf i)) 10)
(progn (setf y (incf i)) 20)
(progn (setf z (incf i)) 30))
i u v w x y z))
30 6 1 2 3 4 5 6)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/max.lsp | lisp | -*- Mode: Lisp -*-
Error tests
Non-error tests | Author :
Created : Sun Aug 3 15:55:17 2003
Contains : Tests of MAX
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
(deftest max.error.1
(signals-error (max) program-error)
t)
(deftest max.error.2
(check-type-error #'max #'realp)
nil)
(deftest max.error.3
(check-type-error #'(lambda (x) (max 0 x)) #'realp)
nil)
(deftest max.1
(loop for n in *reals*
when (or (not (eql (max n) n))
(not (eql (max n n) n))
(not (eql (max n n n) n))
(not (eql (apply #'max (make-list
(min 256 (1- call-arguments-limit))
:initial-element n))
n)))
collect n)
nil)
(deftest max.2
(max.2-fn)
nil)
(deftest max.3
(loop for x = (- (random 60000) 30000)
for y = (- (random 60000) 30000)
for m = (max x y)
for m2 = (if (>= x y) x y)
repeat 1000
unless (eql m m2)
collect (list x y m m2))
nil)
(deftest max.4
(loop for x = (- (random 6000000) 3000000)
for y = (- (random 6000000) 3000000)
for m = (max x y)
for m2 = (if (>= x y) x y)
repeat 1000
unless (eql m m2)
collect (list x y m m2))
nil)
(deftest max.5
(loop for x = (- (random 1000000000000) 500000000000)
for y = (- (random 1000000000000) 500000000000)
for m = (max x y)
for m2 = (if (>= x y) x y)
repeat 1000
unless (eql m m2)
collect (list x y m m2))
nil)
(deftest max.6
(let ((m (max 2 1.0s0)))
(or (eqlt m 2)
(eqlt m 2.0s0)))
t)
(deftest max.7
(max 0 1.0s0)
1.0s0)
(deftest max.8
(let ((m (max 2 1.0f0)))
(or (eqlt m 2)
(eqlt m 2.0f0)))
t)
(deftest max.9
(max 0 1.0f0)
1.0f0)
(deftest max.10
(let ((m (max 2 1.0d0)))
(or (eqlt m 2)
(eqlt m 2.0d0)))
t)
(deftest max.11
(max 0 1.0d0)
1.0d0)
(deftest max.12
(let ((m (max 2 1.0l0)))
(or (eqlt m 2)
(eqlt m 2.0l0)))
t)
(deftest max.13
(max 0 1.0l0)
1.0l0)
(deftest max.15
(let ((m (max 1.0s0 0.0f0)))
(or (eqlt m 1.0s0)
(eqlt m 1.0f0)))
t)
(deftest max.16
(max 0.0s0 1.0f0)
1.0f0)
(deftest max.17
(let ((m (max 1.0s0 0.0d0)))
(or (eqlt m 1.0s0)
(eqlt m 1.0d0)))
t)
(deftest max.18
(max 0.0s0 1.0d0)
1.0d0)
(deftest max.19
(let ((m (max 1.0s0 0.0l0)))
(or (eqlt m 1.0s0)
(eqlt m 1.0l0)))
t)
(deftest max.20
(max 0.0s0 1.0l0)
1.0l0)
(deftest max.21
(let ((m (max 1.0f0 0.0d0)))
(or (eqlt m 1.0f0)
(eqlt m 1.0d0)))
t)
(deftest max.22
(max 0.0f0 1.0d0)
1.0d0)
(deftest max.23
(let ((m (max 1.0f0 0.0l0)))
(or (eqlt m 1.0f0)
(eqlt m 1.0l0)))
t)
(deftest max.24
(max 0.0f0 1.0l0)
1.0l0)
(deftest max.25
(let ((m (max 1.0d0 0.0l0)))
(or (eqlt m 1.0d0)
(eqlt m 1.0l0)))
t)
(deftest max.26
(max 0.0d0 1.0l0)
1.0l0)
(deftest max.27
(loop for i from 1 to (min 256 (1- call-arguments-limit))
for x = (make-list i :initial-element 0)
do (setf (elt x (random i)) 1)
unless (eql (apply #'max x) 1)
collect x)
nil)
(deftest max.28
(let ((m (max 1/3 0.2s0)))
(or (eqlt m 1/3)
(eqlt m (float 1/3 0.2s0))))
t)
(deftest max.29
(let ((m (max 1.0s0 3 2.0f0)))
(or (eqlt m 3)
(eqlt m 3.0f0)))
t)
(deftest max.30
(let ((m (max 1.0d0 3 2.0f0)))
(or (eqlt m 3)
(eqlt m 3.0d0)))
t)
(deftest max.31
(let ((m (max 1.0s0 3 2.0l0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.32
(let ((m (max 1.0l0 3 2.0s0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.33
(let ((m (max 1.0d0 3 2.0l0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.34
(let ((m (max 1.0l0 3 2.0d0)))
(or (eqlt m 3)
(eqlt m 3.0l0)))
t)
(deftest max.order.1
(let ((i 0) x y)
(values
(max (progn (setf x (incf i)) 10)
(progn (setf y (incf i)) 20))
i x y))
20 2 1 2)
(deftest max.order.2
(let ((i 0) x y z)
(values
(max (progn (setf x (incf i)) 10)
(progn (setf y (incf i)) 20)
(progn (setf z (incf i)) 30))
i x y z))
30 3 1 2 3)
(deftest max.order.3
(let ((i 0) u v w x y z)
(values
(max (progn (setf u (incf i)) 10)
(progn (setf v (incf i)) 20)
(progn (setf w (incf i)) 30)
(progn (setf x (incf i)) 10)
(progn (setf y (incf i)) 20)
(progn (setf z (incf i)) 30))
i u v w x y z))
30 6 1 2 3 4 5 6)
|
0fdd956024a34353f92ffa032e1cb2dff37903322f1f836f392a223ebbe48822 | theodormoroianu/SecondYearCourses | LambdaChurch_20210415164336.hs | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
-- alpha-equivalence
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
-- subst u x t defines [u/x]t, i.e., substituting u for x in t
for example [ 3 / x](x + x ) = = 3 + 3
-- This substitution avoids variable captures so it is safe to be used when
-- reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
subst
:: Term -- ^ substitution term
-> Variable -- ^ variable to be substitutes
-> Term -- ^ term in which the substitution occurs
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
-- Normal order reduction
-- - like call by name
-- - but also reduce under lambda abstractions if no application is possible
-- - guarantees reaching a normal form if it exists
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
-- alpha-beta equivalence (for strongly normalizing terms) is obtained by
-- fully evaluating the terms using beta-reduction, then checking their
-- alpha-equivalence.
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
-- Church Encodings in Lambda
churchTrue :: Term
churchTrue = lams ["t", "f"] (v "t")
churchFalse :: Term
churchFalse = lams ["t", "f"] (v "f")
churchIf :: Term
churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else")
churchNot :: Term
churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue)
churchAnd :: Term
churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse)
churchOr :: Term
churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2")
church0 :: Term
church0 = lams ["s", "z"] (v "z") -- note that it's the same as churchFalse
church1 :: Term
church1 = lams ["s", "z"] (v "s" $$ v "z")
church2 :: Term
church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z"))
churchS :: Term
churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z"))
churchNat :: Integer -> Term
churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z"))
churchPlus :: Term
churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z"))
churchPlus' :: Term
churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m")
churchMul :: Term
churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s"))
churchMul' :: Term
churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0)
churchPow :: Term
churchPow = lams ["m", "n"] (v "n" $$ v "m")
churchPow' :: Term
churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1)
churchIs0 :: Term
churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue)
churchS' :: Term
churchS' = lam "n" (v "n" $$ churchS $$ church1)
churchS'Rev0 :: Term
churchS'Rev0 = lams ["s","z"] church0
churchPred :: Term
churchPred =
lam "n"
(churchIf
$$ (churchIs0 $$ v "n")
$$ church0
$$ (v "n" $$ churchS' $$ churchS'Rev0))
churchSub :: Term
churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m")
churchLte :: Term
churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n"))
churchGte :: Term
churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m")
churchLt :: Term
churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n"))
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
churchGt :: Term
churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m")
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
churchEq :: Term
churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m"))
(==:) :: CNat -> CNat -> CBool
(==:) = \m n -> m <=: n &&: n <=: m
instance Eq CNat where
m == n = cIf (m ==: n) True False
instance Ord CNat where
m <= n = cIf (m <=: n) True False
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
churchPair :: Term
churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s")
cPair :: a -> b -> CPair a b
cPair = \x y -> CPair $ \action -> action x y
churchFst :: Term
churchFst = lam "pair" (v "pair" $$ churchTrue)
cFst :: CPair a b -> a
cFst = \p -> (cOn p $ \x y -> x)
churchSnd :: Term
churchSnd = lam "pair" (v "pair" $$ churchFalse)
cSnd :: CPair a b -> b
cSnd = \p -> (cOn p $ \x y -> y)
churchPred' :: Term
churchPred' = lam "n" (churchFst $$
(v "n"
$$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ church0 $$ church0)
))
cPred :: CNat -> CNat
cPred = \n -> cFst $
cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0)
churchFactorial :: Term
churchFactorial = lam "n" (churchSnd $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchS $$ (churchFst $$ v "p"))
$$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church1 $$ church1)
))
cFactorial :: CNat -> CNat
cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1)
churchFibonacci :: Term
churchFibonacci = lam "n" (churchFst $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchSnd $$ v "p")
$$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church0 $$ church1)
))
cFibonacci :: CNat -> CNat
cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1)
churchDivMod :: Term
churchDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(churchIf
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair"))
$$ (churchPair
$$ (churchS $$ (churchFst $$ v "pair"))
$$ (churchSub
$$ (churchSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (churchPair $$ church0 $$ v "m")
)
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b }
instance Foldable CList where
foldr agg init xs = cFoldR xs agg init
churchNil :: Term
churchNil = lams ["agg", "init"] (v "init")
cNil :: CList a
cNil = CList $ \agg init -> init
churchCons :: Term
churchCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
(.:) :: a -> CList a -> CList a
(.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init)
churchList :: [Term] -> Term
churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil
cList :: [a] -> CList a
cList = foldr (.:) cNil
churchNatList :: [Integer] -> Term
churchNatList = churchList . map churchNat
cNatList :: [Integer] -> CList CNat
cNatList = cList . map cNat
churchSum :: Term
churchSum = lam "l" (v "l" $$ churchPlus $$ church0)
cSum :: CList CNat -> CNat
since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0
churchIsNil :: Term
churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue)
cIsNil :: CList a -> CBool
cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue
churchHead :: Term
churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cHead :: CList a -> a -> a
cHead = \l d -> cFoldR l (\x _ -> x) d
churchTail :: Term
churchTail = lam "l" (churchFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ churchNil $$ churchNil)
))
cTail :: CList a -> CList a
cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil)
cLength :: CList a -> CNat
cLength = \l -> cFoldR l (\_ n -> cS n) 0
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b)
divmod m n = divmod' (0, 0)
where
divmod' (x, y)
| x' <= m = divmod' (x', succ y)
| otherwise = (y, m - x)
where x' = x + n
divmod' m n =
if n == 0 then (0, m)
else
Function.fix
(\f p ->
(\x' ->
if x' > 0 then f ((,) (succ (fst p)) x')
else if (<=) n (snd p) then ((,) (succ (fst p)) 0)
else p)
((-) (snd p) n))
(0, m)
churchDivMod' :: Term
churchDivMod' = lams ["m", "n"]
(churchIs0 $$ v "n"
$$ (churchPair $$ church0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(churchIs0 $$ v "x"
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "p")
$$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0)
$$ v "p"
)
$$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x"))
)
$$ (churchSub $$ (churchSnd $$ v "p") $$ v "n")
)
$$ (churchPair $$ church0 $$ v "m")
)
)
churchSudan :: Term
churchSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(churchIs0 $$ v "n"
$$ (churchPlus $$ v "x" $$ v "y")
$$ (churchIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (churchPred $$ v "n")
$$ v "fnpy"
$$ (churchPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y"))
)
)
))
churchAckermann :: Term
churchAckermann = fix $$ lam "A" (lams ["m", "n"]
(churchIs0 $$ v "m"
$$ (churchS $$ v "n")
$$ (churchIs0 $$ v "n"
$$ (v "A" $$ (churchPred $$ v "m") $$ church1)
$$ (v "A" $$ (churchPred $$ v "m")
$$ (v "A" $$ v "m" $$ (churchPred $$ v "n")))
)
)
)
| null | https://raw.githubusercontent.com/theodormoroianu/SecondYearCourses/5e359e6a7cf588a527d27209bf53b4ce6b8d5e83/FLP/Laboratoare/Lab%209/.history/LambdaChurch_20210415164336.hs | haskell | alpha-equivalence
subst u x t defines [u/x]t, i.e., substituting u for x in t
This substitution avoids variable captures so it is safe to be used when
reducing terms with free variables (e.g., if evaluating inside lambda abstractions)
^ substitution term
^ variable to be substitutes
^ term in which the substitution occurs
Normal order reduction
- like call by name
- but also reduce under lambda abstractions if no application is possible
- guarantees reaching a normal form if it exists
alpha-beta equivalence (for strongly normalizing terms) is obtained by
fully evaluating the terms using beta-reduction, then checking their
alpha-equivalence.
Church Encodings in Lambda
note that it's the same as churchFalse | module LambdaChurch where
import Data.Char (isLetter)
import Data.List ( nub )
class ShowNice a where
showNice :: a -> String
class ReadNice a where
readNice :: String -> (a, String)
data Variable
= Variable
{ name :: String
, count :: Int
}
deriving (Show, Eq, Ord)
var :: String -> Variable
var x = Variable x 0
instance ShowNice Variable where
showNice (Variable x 0) = x
showNice (Variable x cnt) = x <> "_" <> show cnt
instance ReadNice Variable where
readNice s
| null x = error $ "expected variable but found " <> s
| otherwise = (var x, s')
where
(x, s') = span isLetter s
freshVariable :: Variable -> [Variable] -> Variable
freshVariable var vars = Variable x (cnt + 1)
where
x = name var
varsWithName = filter ((== x) . name) vars
Variable _ cnt = maximum (var : varsWithName)
data Term
= V Variable
| App Term Term
| Lam Variable Term
deriving (Show)
aEq :: Term -> Term -> Bool
aEq (V x) (V x') = x == x'
aEq (App t1 t2) (App t1' t2') = aEq t1 t1' && aEq t2 t2'
aEq (Lam x t) (Lam x' t')
| x == x' = aEq t t'
| otherwise = aEq (subst (V y) x t) (subst (V y) x' t')
where
fvT = freeVars t
fvT' = freeVars t'
allFV = nub ([x, x'] ++ fvT ++ fvT')
y = freshVariable x allFV
aEq _ _ = False
v :: String -> Term
v x = V (var x)
lam :: String -> Term -> Term
lam x = Lam (var x)
lams :: [String] -> Term -> Term
lams xs t = foldr lam t xs
($$) :: Term -> Term -> Term
($$) = App
infixl 9 $$
instance ShowNice Term where
showNice (V var) = showNice var
showNice (App t1 t2) = "(" <> showNice t1 <> " " <> showNice t2 <> ")"
showNice (Lam var t) = "(" <> "\\" <> showNice var <> "." <> showNice t <> ")"
instance ReadNice Term where
readNice [] = error "Nothing to read"
readNice ('(' : '\\' : s) = (Lam var t, s'')
where
(var, '.' : s') = readNice s
(t, ')' : s'') = readNice s'
readNice ('(' : s) = (App t1 t2, s'')
where
(t1, ' ' : s') = readNice s
(t2, ')' : s'') = readNice s'
readNice s = (V var, s')
where
(var, s') = readNice s
freeVars :: Term -> [Variable]
freeVars (V var) = [var]
freeVars (App t1 t2) = nub $ freeVars t1 ++ freeVars t2
freeVars (Lam var t) = filter (/= var) (freeVars t)
for example [ 3 / x](x + x ) = = 3 + 3
subst
-> Term
subst u x (V y)
| x == y = u
| otherwise = V y
subst u x (App t1 t2) = App (subst u x t1) (subst u x t2)
subst u x (Lam y t)
| x == y = Lam y t
| y `notElem` fvU = Lam y (subst u x t)
| x `notElem` fvT = Lam y t
| otherwise = Lam y' (subst u x (subst (V y') y t))
where
fvT = freeVars t
fvU = freeVars u
allFV = nub ([x] ++ fvU ++ fvT)
y' = freshVariable y allFV
normalReduceStep :: Term -> Maybe Term
normalReduceStep (App (Lam v t) t2) = Just $ subst t2 v t
normalReduceStep (App t1 t2)
| Just t1' <- normalReduceStep t1 = Just $ App t1' t2
| Just t2' <- normalReduceStep t2 = Just $ App t1 t2'
normalReduceStep (Lam x t)
| Just t' <- normalReduceStep t = Just $ Lam x t'
normalReduceStep _ = Nothing
normalReduce :: Term -> Term
normalReduce t
| Just t' <- normalReduceStep t = normalReduce t'
| otherwise = t
reduce :: Term -> Term
reduce = normalReduce
abEq :: Term -> Term -> Bool
abEq t1 t2 = aEq (reduce t1) (reduce t2)
evaluate :: String -> String
evaluate s = showNice (reduce t)
where
(t, "") = readNice s
churchTrue :: Term
churchTrue = lams ["t", "f"] (v "t")
churchFalse :: Term
churchFalse = lams ["t", "f"] (v "f")
churchIf :: Term
churchIf = lams ["c", "then", "else"] (v "c" $$ v "then" $$ v "else")
churchNot :: Term
churchNot = lam "b" (v "b" $$ churchFalse $$ churchTrue)
churchAnd :: Term
churchAnd = lams ["b1", "b2"] (v "b1" $$ v "b2" $$ churchFalse)
churchOr :: Term
churchOr = lams ["b1", "b2"] (v "b1" $$ churchTrue $$ v "b2")
church0 :: Term
church1 :: Term
church1 = lams ["s", "z"] (v "s" $$ v "z")
church2 :: Term
church2 = lams ["s", "z"] (v "s" $$ (v "s" $$ v "z"))
churchS :: Term
churchS = lams ["t","s","z"] (v "s" $$ (v "t" $$ v "s" $$ v "z"))
churchNat :: Integer -> Term
churchNat n = lams ["s", "z"] (iterate' n (v "s" $$) (v "z"))
churchPlus :: Term
churchPlus = lams ["n", "m", "s", "z"] (v "n" $$ v "s" $$ (v "m" $$ v "s" $$ v "z"))
churchPlus' :: Term
churchPlus' = lams ["n", "m"] (v "n" $$ churchS $$ v "m")
churchMul :: Term
churchMul = lams ["n", "m", "s"] (v "n" $$ (v "m" $$ v "s"))
churchMul' :: Term
churchMul' = lams ["n", "m"] (v "n" $$ (churchPlus' $$ v "m") $$ church0)
churchPow :: Term
churchPow = lams ["m", "n"] (v "n" $$ v "m")
churchPow' :: Term
churchPow' = lams ["m", "n"] (v "n" $$ (churchMul' $$ v "m") $$ church1)
churchIs0 :: Term
churchIs0 = lam "n" (v "n" $$ (churchAnd $$ churchFalse) $$ churchTrue)
churchS' :: Term
churchS' = lam "n" (v "n" $$ churchS $$ church1)
churchS'Rev0 :: Term
churchS'Rev0 = lams ["s","z"] church0
churchPred :: Term
churchPred =
lam "n"
(churchIf
$$ (churchIs0 $$ v "n")
$$ church0
$$ (v "n" $$ churchS' $$ churchS'Rev0))
churchSub :: Term
churchSub = lams ["m", "n"] (v "n" $$ churchPred $$ v "m")
churchLte :: Term
churchLte = lams ["m", "n"] (churchIs0 $$ (churchSub $$ v "m" $$ v "n"))
churchGte :: Term
churchGte = lams ["m", "n"] (churchLte $$ v "n" $$ v "m")
churchLt :: Term
churchLt = lams ["m", "n"] (churchNot $$ (churchGte $$ v "m" $$ v "n"))
(<:) :: CNat -> CNat -> CBool
(<:) = \m n -> cNot (m >=: n)
infix 4 <:
churchGt :: Term
churchGt = lams ["m", "n"] (churchLt $$ v "n" $$ v "m")
(>:) :: CNat -> CNat -> CBool
(>:) = \m n -> n <: m
infix 4 >:
churchEq :: Term
churchEq = lams ["m", "n"] (churchAnd $$ (churchLte $$ v "m" $$ v "n") $$ (churchLte $$ v "n" $$ v "m"))
(==:) :: CNat -> CNat -> CBool
(==:) = \m n -> m <=: n &&: n <=: m
instance Eq CNat where
m == n = cIf (m ==: n) True False
instance Ord CNat where
m <= n = cIf (m <=: n) True False
newtype CPair a b = CPair { cOn :: forall c . (a -> b -> c) -> c }
instance (Show a, Show b) => Show (CPair a b) where
show p = show $ cOn p (,)
churchPair :: Term
churchPair = lams ["f", "s", "action"] (v "action" $$ v "f" $$ v "s")
cPair :: a -> b -> CPair a b
cPair = \x y -> CPair $ \action -> action x y
churchFst :: Term
churchFst = lam "pair" (v "pair" $$ churchTrue)
cFst :: CPair a b -> a
cFst = \p -> (cOn p $ \x y -> x)
churchSnd :: Term
churchSnd = lam "pair" (v "pair" $$ churchFalse)
cSnd :: CPair a b -> b
cSnd = \p -> (cOn p $ \x y -> y)
churchPred' :: Term
churchPred' = lam "n" (churchFst $$
(v "n"
$$ lam "p" (lam "x" (churchPair $$ v "x" $$ (churchS $$ v "x"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ church0 $$ church0)
))
cPred :: CNat -> CNat
cPred = \n -> cFst $
cFor n (\p -> (\x -> cPair x (cS x)) (cSnd p)) (cPair 0 0)
churchFactorial :: Term
churchFactorial = lam "n" (churchSnd $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchS $$ (churchFst $$ v "p"))
$$ (churchMul $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church1 $$ church1)
))
cFactorial :: CNat -> CNat
cFactorial = \n -> cSnd $ cFor n (\p -> cPair (cFst p) (cFst p * cSnd p)) (cPair 1 1)
churchFibonacci :: Term
churchFibonacci = lam "n" (churchFst $$
(v "n"
$$ lam "p"
(churchPair
$$ (churchSnd $$ v "p")
$$ (churchPlus $$ (churchFst $$ v "p") $$ (churchSnd $$ v "p"))
)
$$ (churchPair $$ church0 $$ church1)
))
cFibonacci :: CNat -> CNat
cFibonacci = \n -> cFst $ cFor n (\p -> cPair (cSnd p) (cFst p + cSnd p)) (cPair 0 1)
churchDivMod :: Term
churchDivMod =
lams ["m", "n"]
(v "m"
$$ lam "pair"
(churchIf
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "pair"))
$$ (churchPair
$$ (churchS $$ (churchFst $$ v "pair"))
$$ (churchSub
$$ (churchSnd $$ v "pair")
$$ v "n"
)
)
$$ v "pair"
)
$$ (churchPair $$ church0 $$ v "m")
)
cDivMod :: CNat -> CNat -> CPair CNat CNat
cDivMod = \m n -> cFor m (\p -> cIf (n <=: cSnd p) (cPair (cS (cFst p)) (cSnd p - n)) p) (cPair 0 m)
newtype CList a = CList { cFoldR :: forall b. (a -> b -> b) -> b -> b }
instance Foldable CList where
foldr agg init xs = cFoldR xs agg init
churchNil :: Term
churchNil = lams ["agg", "init"] (v "init")
cNil :: CList a
cNil = CList $ \agg init -> init
churchCons :: Term
churchCons = lams ["x","l","agg", "init"]
(v "agg"
$$ v "x"
$$ (v "l" $$ v "agg" $$ v "init")
)
(.:) :: a -> CList a -> CList a
(.:) = \x xs -> CList $ \agg init -> agg x (cFoldR xs agg init)
churchList :: [Term] -> Term
churchList = foldr (\x l -> churchCons $$ x $$ l) churchNil
cList :: [a] -> CList a
cList = foldr (.:) cNil
churchNatList :: [Integer] -> Term
churchNatList = churchList . map churchNat
cNatList :: [Integer] -> CList CNat
cNatList = cList . map cNat
churchSum :: Term
churchSum = lam "l" (v "l" $$ churchPlus $$ church0)
cSum :: CList CNat -> CNat
since CList is an instance of Foldable ; otherwise : \l - > cFoldR l ( + ) 0
churchIsNil :: Term
churchIsNil = lam "l" (v "l" $$ lams ["x", "a"] churchFalse $$ churchTrue)
cIsNil :: CList a -> CBool
cIsNil = \l -> cFoldR l (\_ _ -> cFalse) cTrue
churchHead :: Term
churchHead = lams ["l", "default"] (v "l" $$ lams ["x", "a"] (v "x") $$ v "default")
cHead :: CList a -> a -> a
cHead = \l d -> cFoldR l (\x _ -> x) d
churchTail :: Term
churchTail = lam "l" (churchFst $$
(v "l"
$$ lams ["x","p"] (lam "t" (churchPair $$ v "t" $$ (churchCons $$ v "x" $$ v "t"))
$$ (churchSnd $$ v "p"))
$$ (churchPair $$ churchNil $$ churchNil)
))
cTail :: CList a -> CList a
cTail = \l -> cFst $ cFoldR l (\x p -> (\t -> cPair t (x .: t)) (cSnd p)) (cPair cNil cNil)
cLength :: CList a -> CNat
cLength = \l -> cFoldR l (\_ n -> cS n) 0
fix :: Term
fix = lam "f" (lam "x" (v "f" $$ (v "x" $$ v "x")) $$ lam "x" (v "f" $$ (v "x" $$ v "x")))
divmod :: (Enum a, Num a, Ord b, Num b) => b -> b -> (a, b)
divmod m n = divmod' (0, 0)
where
divmod' (x, y)
| x' <= m = divmod' (x', succ y)
| otherwise = (y, m - x)
where x' = x + n
divmod' m n =
if n == 0 then (0, m)
else
Function.fix
(\f p ->
(\x' ->
if x' > 0 then f ((,) (succ (fst p)) x')
else if (<=) n (snd p) then ((,) (succ (fst p)) 0)
else p)
((-) (snd p) n))
(0, m)
churchDivMod' :: Term
churchDivMod' = lams ["m", "n"]
(churchIs0 $$ v "n"
$$ (churchPair $$ church0 $$ v "m")
$$ (fix
$$ lams ["f", "p"]
(lam "x"
(churchIs0 $$ v "x"
$$ (churchLte $$ v "n" $$ (churchSnd $$ v "p")
$$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ church0)
$$ v "p"
)
$$ (v "f" $$ (churchPair $$ (churchS $$ (churchFst $$ v "p")) $$ v "x"))
)
$$ (churchSub $$ (churchSnd $$ v "p") $$ v "n")
)
$$ (churchPair $$ church0 $$ v "m")
)
)
churchSudan :: Term
churchSudan = fix $$ lam "f" (lams ["n", "x", "y"]
(churchIs0 $$ v "n"
$$ (churchPlus $$ v "x" $$ v "y")
$$ (churchIs0 $$ v "y"
$$ v "x"
$$ (lam "fnpy"
(v "f" $$ (churchPred $$ v "n")
$$ v "fnpy"
$$ (churchPlus $$ v "fnpy" $$ v "y")
)
$$ (v "f" $$ v "n" $$ v "x" $$ (churchPred $$ v "y"))
)
)
))
churchAckermann :: Term
churchAckermann = fix $$ lam "A" (lams ["m", "n"]
(churchIs0 $$ v "m"
$$ (churchS $$ v "n")
$$ (churchIs0 $$ v "n"
$$ (v "A" $$ (churchPred $$ v "m") $$ church1)
$$ (v "A" $$ (churchPred $$ v "m")
$$ (v "A" $$ v "m" $$ (churchPred $$ v "n")))
)
)
)
|
d9c5da018d13bb875f6ed394788b5cedeca4027093c3c9bc361dff3585493218 | zeniuseducation/questdb | project.clj | (defproject zenedu.squest/questdb "0.2.2"
:description "A lightweight disk-persisted embedded
nosql db using edn inspired by couch"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[me.raynes/fs "1.4.6"]
[expectations "2.0.9"]
[org.clojure/core.async "0.1.338.0-5c5012-alpha"]]
:plugins [[codox "0.8.10"]
[lein-expectations "0.0.8"]
[lein-autoexpect "1.2.2"]]
:repositories [["releases" {:url ""
:creds :gpg}]])
| null | https://raw.githubusercontent.com/zeniuseducation/questdb/f54e8896cd6e2cf641374f6aded651c1f75dd521/project.clj | clojure | (defproject zenedu.squest/questdb "0.2.2"
:description "A lightweight disk-persisted embedded
nosql db using edn inspired by couch"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[me.raynes/fs "1.4.6"]
[expectations "2.0.9"]
[org.clojure/core.async "0.1.338.0-5c5012-alpha"]]
:plugins [[codox "0.8.10"]
[lein-expectations "0.0.8"]
[lein-autoexpect "1.2.2"]]
:repositories [["releases" {:url ""
:creds :gpg}]])
|
|
926e8e7ed942744f48985d4a9911ac59bdbc530b2a38dd3fec970ef578c4e0b3 | v0d1ch/plaid | Transactions.hs | module Data.Api.Transactions
( plaidGetTransactions
, plaidRefreshTransactions
, plaidCategoriesGet
) where
import Data.Common
plaidGetTransactions
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> PlaidBody PlaidTransactionsGet
-> m ByteString
plaidGetTransactions body = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/transactions/get") body
plaidRefreshTransactions
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> PlaidBody PlaidTransactionsRefresh
-> m ByteString
plaidRefreshTransactions body = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/transactions/refresh") body
plaidCategoriesGet
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> m ByteString
plaidCategoriesGet = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/categories/get") ("" :: String)
| null | https://raw.githubusercontent.com/v0d1ch/plaid/3450c2f4d1c494f2677554b5bd249828a78f370f/Data/Api/Transactions.hs | haskell | module Data.Api.Transactions
( plaidGetTransactions
, plaidRefreshTransactions
, plaidCategoriesGet
) where
import Data.Common
plaidGetTransactions
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> PlaidBody PlaidTransactionsGet
-> m ByteString
plaidGetTransactions body = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/transactions/get") body
plaidRefreshTransactions
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> PlaidBody PlaidTransactionsRefresh
-> m ByteString
plaidRefreshTransactions body = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/transactions/refresh") body
plaidCategoriesGet
:: ( MonadReader PlaidEnv m
, MonadThrow m
, PlaidHttp m
)
=> m ByteString
plaidCategoriesGet = do
env <- ask
let url = envUrl (env ^. plaidEnvEnvironment)
executePost (url <> "/categories/get") ("" :: String)
|
|
ce6f03da7471893f6abae6193de2a71a1478cb7ee431842ce51e924e12508ae0 | klarna/mnesia_eleveldb | mnesia_eleveldb_params.erl | %%----------------------------------------------------------------
Copyright ( c ) 2013 - 2016 Klarna AB
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%----------------------------------------------------------------
-module(mnesia_eleveldb_params).
-behaviour(gen_server).
-export([lookup/2,
store/2,
delete/1]).
-export([start_link/0,
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-include("mnesia_eleveldb_tuning.hrl").
-define(KB, 1024).
-define(MB, 1024 * 1024).
-define(GB, 1024 * 1024 * 1024).
-ifdef(DEBUG).
-define(dbg(Fmt, Args), io:fwrite(user,"~p:~p: "++(Fmt),[?MODULE,?LINE|Args])).
-else.
-define(dbg(Fmt, Args), ok).
-endif.
lookup(Tab, Default) ->
try ets:lookup(?MODULE, Tab) of
[{_, Params}] ->
Params;
[] ->
Default
catch error:badarg ->
Default
end.
store(Tab, Params) ->
ets:insert(?MODULE, {Tab, Params}).
delete(Tab) ->
ets:delete(?MODULE, Tab).
start_link() ->
case ets:info(?MODULE, name) of
undefined ->
ets:new(?MODULE, [ordered_set, public, named_table]),
load_tuning_parameters();
_ ->
ok
end,
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init(_) ->
{ok, []}.
handle_call(_, _, S) -> {reply, error, S}.
handle_cast(_, S) -> {noreply, S}.
handle_info(_, S) -> {noreply, S}.
terminate(_, _) -> ok.
code_change(_, S, _) -> {ok, S}.
load_tuning_parameters() ->
case application:get_env(mnesia_eleveldb, tuning_params) of
{ok, Ps} ->
case Ps of
{consult, F} -> consult(F);
{script, F} -> script(F);
_ when is_list(Ps) ->
store_params(Ps)
end;
_ ->
ok
end.
consult(F) ->
case file:consult(F) of
{ok, Terms} ->
store_params(Terms);
{error, Reason} ->
{error, {Reason, F}}
end.
script(F) ->
case file:script(F) of
{ok, Terms} ->
store_params(Terms);
{error, Reason} ->
{error, {Reason, F}}
end.
store_params(Params) ->
_ = lists:foreach(fun({_,S}) -> valid_size(S) end, Params),
NTabs = length(Params),
Env0= mnesia_eleveldb_tuning:describe_env(),
Env = Env0#tuning{n_tabs = NTabs},
?dbg("Env = ~p~n", [Env]),
TotalFiles = lists:sum([mnesia_eleveldb_tuning:max_files(Sz) ||
{_, Sz} <- Params]),
?dbg("TotalFiles = ~p~n", [TotalFiles]),
MaxFs = Env#tuning.max_files,
?dbg("MaxFs = ~p~n", [MaxFs]),
FsHeadroom = MaxFs * 0.6,
?dbg("FsHeadroom = ~p~n", [FsHeadroom]),
FilesFactor = if TotalFiles =< FsHeadroom ->
1; % don't have to scale down
true ->
FsHeadroom / TotalFiles
end,
Env1 = Env#tuning{files_factor = FilesFactor},
?dbg("Env1 = ~p~n", [Env1]),
lists:foreach(
fun({Tab, Sz}) when is_atom(Tab);
is_atom(element(1,Tab)),
is_integer(element(2,Tab)) ->
ets:insert(?MODULE, {Tab, ldb_params(Sz, Env1, Tab)})
end, Params).
ldb_params(Sz, Env, _Tab) ->
MaxFiles = mnesia_eleveldb_tuning:max_files(Sz) * Env#tuning.files_factor,
Gigabytes
[{write_buffer_size, mnesia_eleveldb_tuning:write_buffer(Sz)},
{cache_size, mnesia_eleveldb_tuning:cache(Sz)}];
true ->
[]
end,
[{max_open_files, MaxFiles} | Opts].
valid_size({I,U}) when is_number(I) ->
true = lists:member(U, [k,m,g]).
| null | https://raw.githubusercontent.com/klarna/mnesia_eleveldb/1bbeb9243cf0e7f3ef36a713bf657b3ebf31fb63/src/mnesia_eleveldb_params.erl | erlang | ----------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
----------------------------------------------------------------
don't have to scale down | Copyright ( c ) 2013 - 2016 Klarna AB
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(mnesia_eleveldb_params).
-behaviour(gen_server).
-export([lookup/2,
store/2,
delete/1]).
-export([start_link/0,
init/1,
handle_call/3,
handle_cast/2,
handle_info/2,
terminate/2,
code_change/3]).
-include("mnesia_eleveldb_tuning.hrl").
-define(KB, 1024).
-define(MB, 1024 * 1024).
-define(GB, 1024 * 1024 * 1024).
-ifdef(DEBUG).
-define(dbg(Fmt, Args), io:fwrite(user,"~p:~p: "++(Fmt),[?MODULE,?LINE|Args])).
-else.
-define(dbg(Fmt, Args), ok).
-endif.
lookup(Tab, Default) ->
try ets:lookup(?MODULE, Tab) of
[{_, Params}] ->
Params;
[] ->
Default
catch error:badarg ->
Default
end.
store(Tab, Params) ->
ets:insert(?MODULE, {Tab, Params}).
delete(Tab) ->
ets:delete(?MODULE, Tab).
start_link() ->
case ets:info(?MODULE, name) of
undefined ->
ets:new(?MODULE, [ordered_set, public, named_table]),
load_tuning_parameters();
_ ->
ok
end,
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init(_) ->
{ok, []}.
handle_call(_, _, S) -> {reply, error, S}.
handle_cast(_, S) -> {noreply, S}.
handle_info(_, S) -> {noreply, S}.
terminate(_, _) -> ok.
code_change(_, S, _) -> {ok, S}.
load_tuning_parameters() ->
case application:get_env(mnesia_eleveldb, tuning_params) of
{ok, Ps} ->
case Ps of
{consult, F} -> consult(F);
{script, F} -> script(F);
_ when is_list(Ps) ->
store_params(Ps)
end;
_ ->
ok
end.
consult(F) ->
case file:consult(F) of
{ok, Terms} ->
store_params(Terms);
{error, Reason} ->
{error, {Reason, F}}
end.
script(F) ->
case file:script(F) of
{ok, Terms} ->
store_params(Terms);
{error, Reason} ->
{error, {Reason, F}}
end.
store_params(Params) ->
_ = lists:foreach(fun({_,S}) -> valid_size(S) end, Params),
NTabs = length(Params),
Env0= mnesia_eleveldb_tuning:describe_env(),
Env = Env0#tuning{n_tabs = NTabs},
?dbg("Env = ~p~n", [Env]),
TotalFiles = lists:sum([mnesia_eleveldb_tuning:max_files(Sz) ||
{_, Sz} <- Params]),
?dbg("TotalFiles = ~p~n", [TotalFiles]),
MaxFs = Env#tuning.max_files,
?dbg("MaxFs = ~p~n", [MaxFs]),
FsHeadroom = MaxFs * 0.6,
?dbg("FsHeadroom = ~p~n", [FsHeadroom]),
FilesFactor = if TotalFiles =< FsHeadroom ->
true ->
FsHeadroom / TotalFiles
end,
Env1 = Env#tuning{files_factor = FilesFactor},
?dbg("Env1 = ~p~n", [Env1]),
lists:foreach(
fun({Tab, Sz}) when is_atom(Tab);
is_atom(element(1,Tab)),
is_integer(element(2,Tab)) ->
ets:insert(?MODULE, {Tab, ldb_params(Sz, Env1, Tab)})
end, Params).
ldb_params(Sz, Env, _Tab) ->
MaxFiles = mnesia_eleveldb_tuning:max_files(Sz) * Env#tuning.files_factor,
Gigabytes
[{write_buffer_size, mnesia_eleveldb_tuning:write_buffer(Sz)},
{cache_size, mnesia_eleveldb_tuning:cache(Sz)}];
true ->
[]
end,
[{max_open_files, MaxFiles} | Opts].
valid_size({I,U}) when is_number(I) ->
true = lists:member(U, [k,m,g]).
|
2e1df53f85a799a8ef9ed3379f4adeafeace759481cf927b34fe829ebed798c6 | onyx-platform/onyx-examples | core.clj | (ns terminal-reduce-task.core
(:require [clojure.core.async :refer [chan >!! <!! close!]]
[onyx.plugin.core-async :refer [take-segments!]]
[onyx.api])
(:gen-class))
(def input-segments
[{:n 21 :event-time #inst "2015-09-13T03:00:00.829-00:00"}
{:n 12 :event-time #inst "2015-09-13T03:04:00.829-00:00"}
{:n 60 :event-time #inst "2015-09-13T03:05:00.829-00:00"}
{:n 64 :event-time #inst "2015-09-13T03:06:00.829-00:00"}
{:n 53 :event-time #inst "2015-09-13T03:07:00.829-00:00"}
{:n 52 :event-time #inst "2015-09-13T03:08:00.829-00:00"}
{:n 24 :event-time #inst "2015-09-13T03:09:00.829-00:00"}
{:n 35 :event-time #inst "2015-09-13T03:15:00.829-00:00"}
{:n 49 :event-time #inst "2015-09-13T03:25:00.829-00:00"}
{:n 37 :event-time #inst "2015-09-13T03:45:00.829-00:00"}
{:n 15 :event-time #inst "2015-09-13T03:03:00.829-00:00"}
{:n 22 :event-time #inst "2015-09-13T03:56:00.829-00:00"}
{:n 83 :event-time #inst "2015-09-13T03:59:00.829-00:00"}
{:n 3 :event-time #inst "2015-09-13T03:32:00.829-00:00"}
{:n 35 :event-time #inst "2015-09-13T03:16:00.829-00:00"}])
(def input-chan (chan (count input-segments)))
(def input-buffer (atom {}))
(def window-state (atom {}))
(def workflow
;; When a reduce task is used as terminal node, an output plugin is no longer
;; required.
[[:in :reducer]])
(defn inject-in-ch [event lifecycle]
{:core.async/buffer input-buffer
:core.async/chan input-chan})
(def in-calls
{:lifecycle/before-task-start inject-in-ch})
(def batch-size 20)
(def catalog
[{:onyx/name :in
:onyx/plugin :onyx.plugin.core-async/input
:onyx/type :input
:onyx/medium :core.async
:onyx/batch-size batch-size
:onyx/max-peers 1
:onyx/doc "Reads segments from a core.async channel"}
{:onyx/name :reducer
:onyx/fn ::triple-n ;; executed for each segment
:onyx/type :reduce
:onyx/max-peers 1
:onyx/batch-size batch-size}])
(def windows
[{:window/id :collect-segments
:window/task :reducer
:window/type :global
:window/aggregation [:onyx.windowing.aggregation/min :n]
:window/window-key :event-time
:window/init 99}])
(def triggers
[{:trigger/window-id :collect-segments
:trigger/id :sync
:trigger/on :onyx.triggers/segment
:trigger/threshold [5 :elements]
:trigger/sync ::update-atom!}])
(def lifecycles
[{:lifecycle/task :in
:lifecycle/calls ::in-calls}])
(defn triple-n [segment]
(update segment :n (partial * 3)))
(defn update-atom!
[event window trigger {:keys [lower-bound upper-bound event-type] :as opts} extent-state]
(when-not (= :job-completed event-type)
(println "Trigger fired, the atom will be updated!")
(println (format "Window extent [%s - %s] contents: %s"
lower-bound upper-bound extent-state))
(swap! window-state assoc [lower-bound upper-bound] extent-state)))
(def id (java.util.UUID/randomUUID))
(def env-config
{:zookeeper/address "127.0.0.1:2188"
:zookeeper/server? true
:zookeeper.server/port 2188
:onyx/tenancy-id id})
(def peer-config
{:zookeeper/address "127.0.0.1:2188"
:onyx/tenancy-id id
:onyx.peer/job-scheduler :onyx.job-scheduler/balanced
:onyx.messaging/impl :aeron
:onyx.messaging/peer-port 40200
:onyx.messaging/bind-addr "localhost"})
(def env (onyx.api/start-env env-config))
(def peer-group (onyx.api/start-peer-group peer-config))
(def n-peers (count (set (mapcat identity workflow))))
(def v-peers (onyx.api/start-peers n-peers peer-group))
(defn -main
[& args]
(let [submission (onyx.api/submit-job peer-config
{:workflow workflow
:catalog catalog
:lifecycles lifecycles
:windows windows
:triggers triggers
:task-scheduler :onyx.task-scheduler/balanced})]
(doseq [i input-segments]
(>!! input-chan i))
(close! input-chan)
(onyx.api/await-job-completion peer-config (:job-id submission))
(println "Final window state: " @window-state)
(doseq [v-peer v-peers]
(onyx.api/shutdown-peer v-peer))
(onyx.api/shutdown-peer-group peer-group)
(onyx.api/shutdown-env env)))
| null | https://raw.githubusercontent.com/onyx-platform/onyx-examples/668fddd26bc6b692a478fb8dc0e6d3d329879396/terminal-reduce-task/src/terminal_reduce_task/core.clj | clojure | When a reduce task is used as terminal node, an output plugin is no longer
required.
executed for each segment | (ns terminal-reduce-task.core
(:require [clojure.core.async :refer [chan >!! <!! close!]]
[onyx.plugin.core-async :refer [take-segments!]]
[onyx.api])
(:gen-class))
(def input-segments
[{:n 21 :event-time #inst "2015-09-13T03:00:00.829-00:00"}
{:n 12 :event-time #inst "2015-09-13T03:04:00.829-00:00"}
{:n 60 :event-time #inst "2015-09-13T03:05:00.829-00:00"}
{:n 64 :event-time #inst "2015-09-13T03:06:00.829-00:00"}
{:n 53 :event-time #inst "2015-09-13T03:07:00.829-00:00"}
{:n 52 :event-time #inst "2015-09-13T03:08:00.829-00:00"}
{:n 24 :event-time #inst "2015-09-13T03:09:00.829-00:00"}
{:n 35 :event-time #inst "2015-09-13T03:15:00.829-00:00"}
{:n 49 :event-time #inst "2015-09-13T03:25:00.829-00:00"}
{:n 37 :event-time #inst "2015-09-13T03:45:00.829-00:00"}
{:n 15 :event-time #inst "2015-09-13T03:03:00.829-00:00"}
{:n 22 :event-time #inst "2015-09-13T03:56:00.829-00:00"}
{:n 83 :event-time #inst "2015-09-13T03:59:00.829-00:00"}
{:n 3 :event-time #inst "2015-09-13T03:32:00.829-00:00"}
{:n 35 :event-time #inst "2015-09-13T03:16:00.829-00:00"}])
(def input-chan (chan (count input-segments)))
(def input-buffer (atom {}))
(def window-state (atom {}))
(def workflow
[[:in :reducer]])
(defn inject-in-ch [event lifecycle]
{:core.async/buffer input-buffer
:core.async/chan input-chan})
(def in-calls
{:lifecycle/before-task-start inject-in-ch})
(def batch-size 20)
(def catalog
[{:onyx/name :in
:onyx/plugin :onyx.plugin.core-async/input
:onyx/type :input
:onyx/medium :core.async
:onyx/batch-size batch-size
:onyx/max-peers 1
:onyx/doc "Reads segments from a core.async channel"}
{:onyx/name :reducer
:onyx/type :reduce
:onyx/max-peers 1
:onyx/batch-size batch-size}])
(def windows
[{:window/id :collect-segments
:window/task :reducer
:window/type :global
:window/aggregation [:onyx.windowing.aggregation/min :n]
:window/window-key :event-time
:window/init 99}])
(def triggers
[{:trigger/window-id :collect-segments
:trigger/id :sync
:trigger/on :onyx.triggers/segment
:trigger/threshold [5 :elements]
:trigger/sync ::update-atom!}])
(def lifecycles
[{:lifecycle/task :in
:lifecycle/calls ::in-calls}])
(defn triple-n [segment]
(update segment :n (partial * 3)))
(defn update-atom!
[event window trigger {:keys [lower-bound upper-bound event-type] :as opts} extent-state]
(when-not (= :job-completed event-type)
(println "Trigger fired, the atom will be updated!")
(println (format "Window extent [%s - %s] contents: %s"
lower-bound upper-bound extent-state))
(swap! window-state assoc [lower-bound upper-bound] extent-state)))
(def id (java.util.UUID/randomUUID))
(def env-config
{:zookeeper/address "127.0.0.1:2188"
:zookeeper/server? true
:zookeeper.server/port 2188
:onyx/tenancy-id id})
(def peer-config
{:zookeeper/address "127.0.0.1:2188"
:onyx/tenancy-id id
:onyx.peer/job-scheduler :onyx.job-scheduler/balanced
:onyx.messaging/impl :aeron
:onyx.messaging/peer-port 40200
:onyx.messaging/bind-addr "localhost"})
(def env (onyx.api/start-env env-config))
(def peer-group (onyx.api/start-peer-group peer-config))
(def n-peers (count (set (mapcat identity workflow))))
(def v-peers (onyx.api/start-peers n-peers peer-group))
(defn -main
[& args]
(let [submission (onyx.api/submit-job peer-config
{:workflow workflow
:catalog catalog
:lifecycles lifecycles
:windows windows
:triggers triggers
:task-scheduler :onyx.task-scheduler/balanced})]
(doseq [i input-segments]
(>!! input-chan i))
(close! input-chan)
(onyx.api/await-job-completion peer-config (:job-id submission))
(println "Final window state: " @window-state)
(doseq [v-peer v-peers]
(onyx.api/shutdown-peer v-peer))
(onyx.api/shutdown-peer-group peer-group)
(onyx.api/shutdown-env env)))
|
ca6eb45b0db938dc54d03b8b0d8fc79918d9932d1ede7531a537dba181f9ddc1 | casidiablo/slack-rtm | core.clj | (ns slack-rtm.core
(:require [clj-slack.rtm :as rtm]
[clj-slack.core :refer [slack-request]]
[clojure.core.async :as async
:refer [chan pub sub go >! <! go-loop close! unsub unsub-all]]
[clojure.data.json :as json]
[clojure.test]
[gniazdo.core :as ws]))
;; private utility methods
(defn- loop-fn-until-nil
"Loop infinitely reading from the provided channel (creates an
unbuffered one if none provided), applying f to each item. Stops if
the channel provides nil. Returns the channel."
([f] (loop-fn-until-nil f (chan)))
([f ch]
(go-loop []
(when-let [val (<! ch)]
(do
(try
(f val)
(catch Exception e
(.printStackTrace e)
(println "Failed to call fn on " val (.getMessage e))))
(recur))))
ch))
(defn- ws-connect
"Connects to the provided WebSocket URL and forward all listener
events to the provided channel."
[url callback-ch]
(ws/connect
url
:on-connect #(go (>! callback-ch {:type :on-connect
:session %}))
:on-receive #(go (>! callback-ch {:type :on-receive
:message %}))
:on-binary #(go (>! callback-ch {:type :on-binary
:payload %1
:offset %2
:len %3}))
:on-close #(go (>! callback-ch {:type :on-close
:status-code %1
:reason %2}))
:on-error #(go (>! callback-ch {:type :on-error
:throwable %}))))
(defn- spin-dispatcher-channel
"Creates a channel that will forward a JSON version of its values to
the provided WebSocket client. If the message received is :close, it
will close the client and the channel."
[client]
(let [dispatcher-ch (chan)]
(loop-fn-until-nil
#(if (= :close %)
;; close connection and channel
(do
(close! dispatcher-ch)
(ws/close client))
;; send the message as a JSON string
(ws/send-msg client (json/write-str %)))
dispatcher-ch)))
(defn- parse-messages-chan
"Creates a channel that maps to JSON the messages of ch"
[ch]
(async/map
#(try
(-> % :message
(json/read-str :key-fn clojure.core/keyword))
(catch Throwable e
{:type "exception" :error e}))
[ch]))
(defn- apply-if
"If x matches predicate p, apply f and return. Otherwise return x as-is."
[x p f]
(if (p x) (f x) x))
(declare sub-to-event)
(defn- sub-initial-subscribers
"Subscribes the channels in initial-subs map to either
websocket-publication (for WebSocket events) or
events-publication (for slack events)"
[websocket-publication events-publication initial-subs]
(let [ws-topics [:on-connect :on-receive :on-binary :on-close :on-error]
ws-subs (select-keys initial-subs ws-topics)
non-ws-topics (remove (set ws-topics) (keys initial-subs))
non-ws-subs (select-keys initial-subs non-ws-topics)]
(doall (for [[topic subscriber] ws-subs]
(let [subscriber (apply-if subscriber clojure.test/function? loop-fn-until-nil)]
(sub websocket-publication topic subscriber))))
(doall (for [[topic subscriber] non-ws-subs]
(sub-to-event events-publication topic subscriber)))))
(defn- build-connection-map [token-or-map]
(if (string? token-or-map)
{:api-url ""
:token token-or-map}
token-or-map))
(defn- internal-connect
"Connects to a Real Time Messaging session via WebSockets using the provided connection,
which can be an API token or a map like this: {:api-url
\"\" :token token-or-map}.
Returns a map containing these properties:
- :events-publication a publication object you can subscribe to in order to
listen for slack events
- :dispatcher can be used to send events/messages to slack
- :websocket-publication a publication object you can subscribe to in order to
get raw callbacks from the websocket client
- :start the response from the Slack API rtm.start method, which contains data
about the current state of the team:
initial-subs can be provided as :topic ch-or-fn.
topic can be a websocket listener event (that will be subscribed
to :websocket-publication):
:on-connect :on-receive :on-binary :on-close :on-error
as well as a slack RTM event type (e.g. \"im_open\", :message, etc.)
which will be subscribed to :events-publication. Topics can be strings
or keywords.
ch-or-fn is the channel to subscribe or a function to invoke for each
event produced by the publication"
[conn-type connection & {:as initial-subs}]
(let [connection-map (build-connection-map connection)
;; create a publication of websocket raw callbacks
callback-ch (chan)
websocket-publication (pub callback-ch :type)
;; subscribe a channel to the :on-receive callbacks
;; and create a publication of parsed slack events
incoming-msg-ch (sub websocket-publication :on-receive (chan))
events-publication (pub (parse-messages-chan incoming-msg-ch)
#(or (:type %) (if-not (:ok %) "error")))
;; subscribe initial subscribers
_ (sub-initial-subscribers websocket-publication events-publication initial-subs)
;; save the response from rtm/start to pass back to caller
start (if (= conn-type :start-url) (rtm/start connection-map) (rtm/connect connection-map))
_ (when (start :error) (throw (new RuntimeException (str "Failed to start connection: " start))))
;; connect to the RTM API via websocket session and
;; get a channel that can be used to send data to slack
dispatcher (-> start
:url
(ws-connect callback-ch)
spin-dispatcher-channel)]
{:start start
:websocket-publication websocket-publication
:events-publication events-publication
:dispatcher dispatcher}))
(defn connect [connection & initial-subs]
(apply internal-connect :connect-url connection initial-subs))
(defn start [connection & initial-subs]
(apply internal-connect :start-url connection initial-subs))
(defn send-event
"Sends a RTM event to slack. Send :close to close the connection."
[dispatcher event]
(if (keyword? event)
;; if the event is a :keyword, just send it
(go (>! dispatcher event))
;; otherwise make sure it has an :id key
(go (>! dispatcher
;; add a random id if none provided
(update-in event [:id] #(or % (rand-int Integer/MAX_VALUE)))))))
(defn sub-to-event
"Subscribe to slack events with type type. If channel was specified
use it to subscribe. Otherwise create an unbuffered channel. An unary
function can be supplied instead of a channel, in which case it will
be called for every value received from the subscription."
([publication type]
(sub-to-event publication type (chan)))
([publication type ch-or-fn]
(let [ ;; this allows to use keywords as topics
type (apply-if type keyword? name)
taker (apply-if ch-or-fn clojure.test/function? loop-fn-until-nil)]
(sub publication type taker)
taker)))
(defn unsub-from-event
"Unsubscribe a channel from the provided event type."
[publication type ch]
(unsub publication type ch))
| null | https://raw.githubusercontent.com/casidiablo/slack-rtm/dad6b674f4a4eda92ed8528bf896df5d82fb32ad/src/slack_rtm/core.clj | clojure | private utility methods
close connection and channel
send the message as a JSON string
create a publication of websocket raw callbacks
subscribe a channel to the :on-receive callbacks
and create a publication of parsed slack events
subscribe initial subscribers
save the response from rtm/start to pass back to caller
connect to the RTM API via websocket session and
get a channel that can be used to send data to slack
if the event is a :keyword, just send it
otherwise make sure it has an :id key
add a random id if none provided
this allows to use keywords as topics | (ns slack-rtm.core
(:require [clj-slack.rtm :as rtm]
[clj-slack.core :refer [slack-request]]
[clojure.core.async :as async
:refer [chan pub sub go >! <! go-loop close! unsub unsub-all]]
[clojure.data.json :as json]
[clojure.test]
[gniazdo.core :as ws]))
(defn- loop-fn-until-nil
"Loop infinitely reading from the provided channel (creates an
unbuffered one if none provided), applying f to each item. Stops if
the channel provides nil. Returns the channel."
([f] (loop-fn-until-nil f (chan)))
([f ch]
(go-loop []
(when-let [val (<! ch)]
(do
(try
(f val)
(catch Exception e
(.printStackTrace e)
(println "Failed to call fn on " val (.getMessage e))))
(recur))))
ch))
(defn- ws-connect
"Connects to the provided WebSocket URL and forward all listener
events to the provided channel."
[url callback-ch]
(ws/connect
url
:on-connect #(go (>! callback-ch {:type :on-connect
:session %}))
:on-receive #(go (>! callback-ch {:type :on-receive
:message %}))
:on-binary #(go (>! callback-ch {:type :on-binary
:payload %1
:offset %2
:len %3}))
:on-close #(go (>! callback-ch {:type :on-close
:status-code %1
:reason %2}))
:on-error #(go (>! callback-ch {:type :on-error
:throwable %}))))
(defn- spin-dispatcher-channel
"Creates a channel that will forward a JSON version of its values to
the provided WebSocket client. If the message received is :close, it
will close the client and the channel."
[client]
(let [dispatcher-ch (chan)]
(loop-fn-until-nil
#(if (= :close %)
(do
(close! dispatcher-ch)
(ws/close client))
(ws/send-msg client (json/write-str %)))
dispatcher-ch)))
(defn- parse-messages-chan
"Creates a channel that maps to JSON the messages of ch"
[ch]
(async/map
#(try
(-> % :message
(json/read-str :key-fn clojure.core/keyword))
(catch Throwable e
{:type "exception" :error e}))
[ch]))
(defn- apply-if
"If x matches predicate p, apply f and return. Otherwise return x as-is."
[x p f]
(if (p x) (f x) x))
(declare sub-to-event)
(defn- sub-initial-subscribers
"Subscribes the channels in initial-subs map to either
websocket-publication (for WebSocket events) or
events-publication (for slack events)"
[websocket-publication events-publication initial-subs]
(let [ws-topics [:on-connect :on-receive :on-binary :on-close :on-error]
ws-subs (select-keys initial-subs ws-topics)
non-ws-topics (remove (set ws-topics) (keys initial-subs))
non-ws-subs (select-keys initial-subs non-ws-topics)]
(doall (for [[topic subscriber] ws-subs]
(let [subscriber (apply-if subscriber clojure.test/function? loop-fn-until-nil)]
(sub websocket-publication topic subscriber))))
(doall (for [[topic subscriber] non-ws-subs]
(sub-to-event events-publication topic subscriber)))))
(defn- build-connection-map [token-or-map]
(if (string? token-or-map)
{:api-url ""
:token token-or-map}
token-or-map))
(defn- internal-connect
"Connects to a Real Time Messaging session via WebSockets using the provided connection,
which can be an API token or a map like this: {:api-url
\"\" :token token-or-map}.
Returns a map containing these properties:
- :events-publication a publication object you can subscribe to in order to
listen for slack events
- :dispatcher can be used to send events/messages to slack
- :websocket-publication a publication object you can subscribe to in order to
get raw callbacks from the websocket client
- :start the response from the Slack API rtm.start method, which contains data
about the current state of the team:
initial-subs can be provided as :topic ch-or-fn.
topic can be a websocket listener event (that will be subscribed
to :websocket-publication):
:on-connect :on-receive :on-binary :on-close :on-error
as well as a slack RTM event type (e.g. \"im_open\", :message, etc.)
which will be subscribed to :events-publication. Topics can be strings
or keywords.
ch-or-fn is the channel to subscribe or a function to invoke for each
event produced by the publication"
[conn-type connection & {:as initial-subs}]
(let [connection-map (build-connection-map connection)
callback-ch (chan)
websocket-publication (pub callback-ch :type)
incoming-msg-ch (sub websocket-publication :on-receive (chan))
events-publication (pub (parse-messages-chan incoming-msg-ch)
#(or (:type %) (if-not (:ok %) "error")))
_ (sub-initial-subscribers websocket-publication events-publication initial-subs)
start (if (= conn-type :start-url) (rtm/start connection-map) (rtm/connect connection-map))
_ (when (start :error) (throw (new RuntimeException (str "Failed to start connection: " start))))
dispatcher (-> start
:url
(ws-connect callback-ch)
spin-dispatcher-channel)]
{:start start
:websocket-publication websocket-publication
:events-publication events-publication
:dispatcher dispatcher}))
(defn connect [connection & initial-subs]
(apply internal-connect :connect-url connection initial-subs))
(defn start [connection & initial-subs]
(apply internal-connect :start-url connection initial-subs))
(defn send-event
"Sends a RTM event to slack. Send :close to close the connection."
[dispatcher event]
(if (keyword? event)
(go (>! dispatcher event))
(go (>! dispatcher
(update-in event [:id] #(or % (rand-int Integer/MAX_VALUE)))))))
(defn sub-to-event
"Subscribe to slack events with type type. If channel was specified
use it to subscribe. Otherwise create an unbuffered channel. An unary
function can be supplied instead of a channel, in which case it will
be called for every value received from the subscription."
([publication type]
(sub-to-event publication type (chan)))
([publication type ch-or-fn]
type (apply-if type keyword? name)
taker (apply-if ch-or-fn clojure.test/function? loop-fn-until-nil)]
(sub publication type taker)
taker)))
(defn unsub-from-event
"Unsubscribe a channel from the provided event type."
[publication type ch]
(unsub publication type ch))
|
7635e8fec565a7113e95d3338237f9d89b8fbf4d568e7e62fa6d3ae9097ca837 | heidegger/JSConTest | effect.ml | type t =
| Default
| NoTrans
| OnlyEffect
| All
| null | https://raw.githubusercontent.com/heidegger/JSConTest/7c807a76af998da25775fba1f5cbe1cf8031d121/ocaml/effect.ml | ocaml | type t =
| Default
| NoTrans
| OnlyEffect
| All
|
|
07149e1c31a563b7130cda5ab87df1efbd5f113875319003f9db96e82aedd590 | ntoronto/pict3d | texture.rkt | #lang typed/racket/base
(require racket/match
racket/list
typed/opengl
(except-in typed/opengl/ffi cast ->)
"context.rkt"
"object.rkt")
(provide (all-defined-out))
;; ===================================================================================================
;; Managed textures
(: current-gl-active-texture (Parameterof Integer))
(define current-gl-active-texture (make-parameter GL_TEXTURE0))
(define-syntax-rule (with-gl-active-texture texnum-stx body ...)
(let ([texnum : Integer texnum-stx])
(call-with-gl-state (λ () body ...) current-gl-active-texture texnum glActiveTexture)))
(struct gl-texture gl-object ([target : Integer]) #:transparent)
(struct gl-texture-2d gl-texture
([width : Natural]
[height : Natural]
[internal-format : Integer]
[format : Integer]
[type : Integer]
[params : (HashTable Integer Integer)])
#:transparent)
(: make-gl-texture-2d (-> Integer Integer Integer Integer Integer (Listof (Pair Integer Integer))
gl-texture-2d))
(define (make-gl-texture-2d width height internal-format format type params)
(cond [(negative? width)
(raise-argument-error 'make-gl-texture-2d "Natural" 0
width height internal-format format type params)]
[(negative? height)
(raise-argument-error 'make-gl-texture-2d "Natural" 1
width height internal-format format type params)]
[else
(define tex (gl-texture-2d (u32vector-ref (glGenTextures 1) 0)
GL_TEXTURE_2D width height internal-format format type
(make-immutable-hasheqv params)))
(manage-gl-object tex (λ ([handle : Natural]) (glDeleteTextures 1 (u32vector handle))))
(with-gl-texture tex
(for ([param (in-list params)])
(match-define (cons key value) param)
(glTexParameteri GL_TEXTURE_2D key value))
(glTexImage2D GL_TEXTURE_2D 0 internal-format width height 0 format type 0))
tex]))
(define null-gl-texture (gl-texture 0 GL_TEXTURE_1D))
(: current-gl-textures (Parameterof (HashTable Integer gl-texture)))
(define current-gl-textures
(make-parameter ((inst make-immutable-hasheqv Integer gl-texture) empty)))
(: call-with-gl-texture (All (A) (-> (-> A) gl-texture A)))
(define (call-with-gl-texture body-thunk tex)
(get-current-managed-gl-context 'with-gl-texture)
(define old (hash-ref (current-gl-textures)
(current-gl-active-texture)
(λ () null-gl-texture)))
(cond [(eq? old tex) (body-thunk)]
[else (glBindTexture (gl-texture-target tex) (gl-object-handle tex))
(begin0
(parameterize ([current-gl-textures (hash-set (current-gl-textures)
(current-gl-active-texture)
tex)])
(body-thunk))
(glBindTexture (gl-texture-target old) (gl-object-handle old)))]))
(define-syntax-rule (with-gl-texture tex body ...)
(call-with-gl-texture (λ () body ...) tex))
| null | https://raw.githubusercontent.com/ntoronto/pict3d/09283c9d930c63b6a6a3f2caa43e029222091bdb/pict3d/private/gl/texture.rkt | racket | ===================================================================================================
Managed textures | #lang typed/racket/base
(require racket/match
racket/list
typed/opengl
(except-in typed/opengl/ffi cast ->)
"context.rkt"
"object.rkt")
(provide (all-defined-out))
(: current-gl-active-texture (Parameterof Integer))
(define current-gl-active-texture (make-parameter GL_TEXTURE0))
(define-syntax-rule (with-gl-active-texture texnum-stx body ...)
(let ([texnum : Integer texnum-stx])
(call-with-gl-state (λ () body ...) current-gl-active-texture texnum glActiveTexture)))
(struct gl-texture gl-object ([target : Integer]) #:transparent)
(struct gl-texture-2d gl-texture
([width : Natural]
[height : Natural]
[internal-format : Integer]
[format : Integer]
[type : Integer]
[params : (HashTable Integer Integer)])
#:transparent)
(: make-gl-texture-2d (-> Integer Integer Integer Integer Integer (Listof (Pair Integer Integer))
gl-texture-2d))
(define (make-gl-texture-2d width height internal-format format type params)
(cond [(negative? width)
(raise-argument-error 'make-gl-texture-2d "Natural" 0
width height internal-format format type params)]
[(negative? height)
(raise-argument-error 'make-gl-texture-2d "Natural" 1
width height internal-format format type params)]
[else
(define tex (gl-texture-2d (u32vector-ref (glGenTextures 1) 0)
GL_TEXTURE_2D width height internal-format format type
(make-immutable-hasheqv params)))
(manage-gl-object tex (λ ([handle : Natural]) (glDeleteTextures 1 (u32vector handle))))
(with-gl-texture tex
(for ([param (in-list params)])
(match-define (cons key value) param)
(glTexParameteri GL_TEXTURE_2D key value))
(glTexImage2D GL_TEXTURE_2D 0 internal-format width height 0 format type 0))
tex]))
(define null-gl-texture (gl-texture 0 GL_TEXTURE_1D))
(: current-gl-textures (Parameterof (HashTable Integer gl-texture)))
(define current-gl-textures
(make-parameter ((inst make-immutable-hasheqv Integer gl-texture) empty)))
(: call-with-gl-texture (All (A) (-> (-> A) gl-texture A)))
(define (call-with-gl-texture body-thunk tex)
(get-current-managed-gl-context 'with-gl-texture)
(define old (hash-ref (current-gl-textures)
(current-gl-active-texture)
(λ () null-gl-texture)))
(cond [(eq? old tex) (body-thunk)]
[else (glBindTexture (gl-texture-target tex) (gl-object-handle tex))
(begin0
(parameterize ([current-gl-textures (hash-set (current-gl-textures)
(current-gl-active-texture)
tex)])
(body-thunk))
(glBindTexture (gl-texture-target old) (gl-object-handle old)))]))
(define-syntax-rule (with-gl-texture tex body ...)
(call-with-gl-texture (λ () body ...) tex))
|
c23d02912d7345bb54ad14dbafcff156ac722441a83e0528c148590254fb281d | jasonkuhrt-archive/hpfp-answers | WhatKind.hs | module WhatKind where
1
-- For the signature of `a -> a` the type of `a` is `*`.
2
-- For the signature of `a -> f a` the type of `a` is `*` and the type of `f` is `* -> *` because `f` is being applied (to `a`).
| null | https://raw.githubusercontent.com/jasonkuhrt-archive/hpfp-answers/c03ae936f208cfa3ca1eb0e720a5527cebe4c034/chapter-12/WhatKind.hs | haskell | For the signature of `a -> a` the type of `a` is `*`.
For the signature of `a -> f a` the type of `a` is `*` and the type of `f` is `* -> *` because `f` is being applied (to `a`). | module WhatKind where
1
2
|
07db4df9c4f7f3ba2704f0b0b2dcd634e475d351734f819d9e9709a3d3d8f673 | mtgred/netrunner | installing.clj | (ns game.core.installing
(:require
[cond-plus.core :refer [cond+]]
[game.core.agendas :refer [update-advancement-requirement]]
[game.core.board :refer [all-installed get-remotes installable-servers server->zone all-installed-runner-type]]
[game.core.card :refer [agenda? asset? convert-to-condition-counter corp? event? get-card get-zone has-subtype? ice? operation? program? resource? rezzed? installed?]]
[game.core.card-defs :refer [card-def]]
[game.core.cost-fns :refer [ignore-install-cost? install-additional-cost-bonus install-cost]]
[game.core.eid :refer [complete-with-result effect-completed eid-set-defaults make-eid]]
[game.core.engine :refer [checkpoint register-pending-event pay queue-event register-events trigger-event-simult unregister-events]]
[game.core.effects :refer [register-constant-effects unregister-constant-effects]]
[game.core.flags :refer [turn-flag? zone-locked?]]
[game.core.hosting :refer [host]]
[game.core.ice :refer [update-breaker-strength]]
[game.core.initializing :refer [ability-init card-init corp-ability-init runner-ability-init]]
[game.core.memory :refer [sufficient-mu? update-mu]]
[game.core.moving :refer [move trash trash-cards]]
[game.core.payment :refer [build-spend-msg can-pay? merge-costs]]
[game.core.rezzing :refer [rez]]
[game.core.say :refer [play-sfx system-msg implementation-msg]]
[game.core.servers :refer [name-zone remote-num->name]]
[game.core.state :refer [make-rid]]
[game.core.to-string :refer [card-str]]
[game.core.toasts :refer [toast]]
[game.core.update :refer [update!]]
[game.macros :refer [continue-ability effect req wait-for]]
[game.utils :refer [dissoc-in in-coll? to-keyword]]))
(defn install-locked?
"Checks if installing is locked"
[state side]
(let [kw (keyword (str (name side) "-lock-install"))]
(or (seq (get-in @state [:stack :current-run kw]))
(seq (get-in @state [:stack :current-turn kw]))
(seq (get-in @state [:stack :persistent kw])))))
;;; Intalling a corp card
(defn- corp-can-install-reason
"Checks if the specified card can be installed.
Returns true if there are no problems
Returns :region if Region check fails
Returns :ice if ice check fails
!! NB: This should only be used in a check with `true?` as all return values are truthy"
[state side card slot]
(cond
;; Region check
(and (has-subtype? card "Region")
(some #(has-subtype? % "Region") (get-in @state (cons :corp slot))))
:region
;; ice install prevented by Unscheduled Maintenance
(and (ice? card)
(not (turn-flag? state side card :can-install-ice)))
:ice
;; Installing not locked
(install-locked? state :corp)
:lock-install
Earth station can not have more than one server
(and (= "Earth Station" (subs (:title (get-in @state [:corp :identity])) 0 (min 13 (count (:title (get-in @state [:corp :identity]))))))
(not (:disabled (get-in @state [:corp :identity])))
(pos? (count (get-remotes state)))
(not (in-coll? (conj (keys (get-remotes state)) :archives :rd :hq) (second slot))))
:earth-station
;; no restrictions
:else true))
(defn- corp-can-install?
"Checks `corp-can-install-reason` if not true, toasts reason and returns false"
[state side card slot {:keys [no-toast]}]
(let [reason (corp-can-install-reason state side card slot)
reason-toast #(do (when-not no-toast (toast state side % "warning")) false)
title (:title card)]
(case reason
;; failed region check
:region
(reason-toast (str "Cannot install " (:title card) ", limit of one Region per server"))
;; failed install lock check
:lock-install
(reason-toast (str "Unable to install " title ", installing is currently locked"))
;; failed ice check
:ice
(reason-toast (str "Unable to install " title ": can only install 1 piece of ice per turn"))
Earth station can not have more than one remote server
:earth-station
(reason-toast (str "Unable to install " title " in new remote: Earth Station limit"))
;; else
true)))
(defn- corp-install-asset-agenda
"Forces the corp to trash an existing asset or agenda if a second was just installed."
[state side eid card dest-zone server]
(let [prev-card (some #(when (or (asset? %) (agenda? %)) %) dest-zone)]
(if (and (or (asset? card) (agenda? card))
prev-card
(not (:host card)))
(continue-ability state side {:prompt (str "The " (:title prev-card) " in " server " will now be trashed.")
:choices ["OK"]
:async true
:effect (req (system-msg state :corp (str "trashes " (card-str state prev-card)))
(if (get-card state prev-card) ; make sure they didn't trash the card themselves
(trash state :corp eid prev-card {:keep-server-alive true})
(effect-completed state :corp eid)))}
nil nil)
(effect-completed state side eid))))
(defn- corp-install-message
"Prints the correct install message."
[state side card server install-state cost-str args]
(when (:display-message args true)
(let [card-name (if (or (= :rezzed-no-cost install-state)
(= :face-up install-state)
(rezzed? card))
(:title card)
(if (ice? card) "ice" "a card"))
server-name (if (= server "New remote")
(str (remote-num->name (dec (:rid @state))) " (new remote)")
server)]
(system-msg state side (str (build-spend-msg cost-str "install") card-name
(if (ice? card) " protecting " " in ") server-name))
(when (and (= :face-up install-state)
(agenda? card))
(implementation-msg state card)))))
(defn corp-install-list
"Returns a list of targets for where a given card can be installed."
[state card]
(let [hosts (filter #(when-let [can-host (:can-host (card-def %))]
(and (rezzed? %)
(can-host state :corp (make-eid state) % [card])))
(all-installed state :corp))]
(concat hosts (installable-servers state card))))
(defn- corp-install-continue
"Used by corp-install to actually install the card, rez it if it's supposed to be installed
rezzed, and calls :corp-install in an awaitable fashion."
[state side eid card server {:keys [install-state host-card front index display-message] :as args} slot cost-str]
(let [cdef (card-def card)
dest-zone (get-in @state (cons :corp slot))
install-state (or (:install-state cdef) install-state)
no-msg (not (if (nil? display-message) true display-message))
c (-> card
(assoc :advanceable (:advanceable cdef) :new true)
(dissoc :seen :disabled))]
(when-not host-card
(corp-install-message state side c server install-state cost-str args))
(play-sfx state side "install-corp")
(let [moved-card (if host-card
(host state side host-card (assoc c :installed true))
(move state side c slot {:front front
:index index}))
_ (when (agenda? c)
(update-advancement-requirement state moved-card))
moved-card (get-card state moved-card)]
Check to see if a second agenda / asset was installed .
(wait-for (corp-install-asset-agenda state side moved-card dest-zone server)
(let [eid (assoc eid :source moved-card :source-type :rez)]
(queue-event state :corp-install {:card (get-card state moved-card)
:install-state install-state})
(case install-state
;; Ignore all costs
:rezzed-no-cost
(if-not (agenda? moved-card)
(rez state side eid moved-card {:ignore-cost :all-costs
:no-msg no-msg})
(checkpoint state nil eid))
Ignore cost only
:rezzed-no-rez-cost
(rez state side eid moved-card {:ignore-cost :rez-costs
:no-msg no-msg})
;; Pay costs
:rezzed
(if-not (agenda? moved-card)
(rez state side eid moved-card {:no-msg no-msg})
(checkpoint state nil eid))
;; "Face-up" cards
:face-up
(let [moved-card (-> (get-card state moved-card)
(assoc :seen true)
(cond-> (not (agenda? card)) (assoc :rezzed true)))
moved-card (if (:install-state cdef)
(card-init state side moved-card {:resolve-effect false
:init-data true})
(update! state side moved-card))]
(wait-for (checkpoint state nil (make-eid state eid))
(complete-with-result state side eid (get-card state moved-card))))
;; All other cards
(wait-for (checkpoint state nil (make-eid state eid))
(when-let [dre (:derezzed-events cdef)]
(register-events state side moved-card (map #(assoc % :condition :derezzed) dre)))
(complete-with-result state side eid (get-card state moved-card)))))))))
(defn get-slot
[state card server {:keys [host-card]}]
(if host-card
(get-zone host-card)
(conj (server->zone state server) (if (ice? card) :ices :content))))
(defn corp-install-cost
[state side card server
{:keys [base-cost ignore-install-cost ignore-all-cost cost-bonus cached-costs] :as args}]
(or cached-costs
(let [slot (get-slot state card server args)
dest-zone (get-in @state (cons :corp slot))
ice-cost (if (and (ice? card)
(not ignore-install-cost)
(not ignore-all-cost)
(not (ignore-install-cost? state side card)))
(count dest-zone)
0)
cost (install-cost state side card
{:cost-bonus (+ (or cost-bonus 0) ice-cost)}
{:server server
:dest-zone dest-zone})]
(when-not ignore-all-cost
(merge-costs [base-cost [:credit cost]])))))
(defn corp-can-pay-and-install?
[state side eid card server args]
(let [slot (get-slot state card server (select-keys args [:host-card]))
costs (corp-install-cost state side card server args)]
(and (corp-can-install? state side card slot (select-keys args [:no-toast]))
(can-pay? state side eid card nil costs)
;; explicitly return true
true)))
(defn- corp-install-pay
"Used by corp-install to pay install costs"
[state side eid card server {:keys [action] :as args}]
(let [slot (get-slot state card server args)
costs (corp-install-cost state side card server (dissoc args :cached-costs))]
(if (corp-can-pay-and-install? state side eid card server (assoc args :cached-costs costs))
(wait-for (pay state side (make-eid state eid) card costs {:action action})
(if-let [payment-str (:msg async-result)]
(if (= server "New remote")
(wait-for (trigger-event-simult state side :server-created nil card)
(make-rid state)
(corp-install-continue state side eid card server args slot payment-str))
(corp-install-continue state side eid card server args slot payment-str))
(effect-completed state side eid)))
(effect-completed state side eid))))
(defn corp-install
"Installs a card in the chosen server. If server is nil, asks for server to install in.
The args input takes the following values:
:base-cost - Only used for click actions
:host-card - Card to host on
:ignore-all-cost - true if install costs should be ignored
:action - What type of action installed the card
:install-state - Can be :rezzed-no-cost, :rezzed-no-rez-cost, :rezzed, or :face-up
:display-message - Print descriptive text to the log window [default=true]
:index - which position for an installed piece of ice"
([state side eid card server] (corp-install state side eid card server nil))
([state side eid card server {:keys [host-card] :as args}]
(let [eid (eid-set-defaults eid :source nil :source-type :corp-install)]
(cond
;; No server selected; show prompt to select an install site (Interns, Lateral Growth, etc.)
(not server)
(continue-ability state side
{:prompt (str "Choose a location to install " (:title card))
:choices (corp-install-list state card)
:async true
:effect (effect (corp-install eid card target args))}
card nil)
;; A card was selected as the server; recurse, with the :host-card parameter set.
(and (map? server)
(not host-card))
(corp-install state side eid card server (assoc args :host-card server))
;; A server was selected
:else
(do (swap! state dissoc-in [:corp :install-list])
(corp-install-pay state side eid card server args))))))
;; Unused in the corp install system, necessary for card definitions
(defn corp-install-msg
"Gets a message describing where a card has been installed from. Example: Interns."
[card]
(str "install " (if (:seen card) (:title card) "an unseen card") " from " (name-zone :corp (:zone card))))
;;; Installing a runner card
(defn- runner-can-install-reason
"Checks if the specified card can be installed.
Checks uniqueness of card and installed console.
Returns true if there are no problems
Returns :req if card-def :req check fails
!! NB: This should only be used in a check with `true?` as all return values are truthy"
[state side card facedown]
(let [card-req (:req (card-def card))]
(cond
;; Can always install a card facedown
facedown true
;; Installing not locked
(install-locked? state :runner) :lock-install
;; Req check
(and card-req (not (card-req state side (make-eid state) card nil))) :req
;; The card's zone is locked
(zone-locked? state side (first (get-zone card))) :locked-zone
;; Nothing preventing install
:else true)))
(defn runner-can-install?
"Checks `runner-can-install-reason` if not true, toasts reason and returns false"
([state side card] (runner-can-install? state side card nil))
([state side card {:keys [facedown no-toast]}]
(let [reason (runner-can-install-reason state side card facedown)
reason-toast #(do (when-not no-toast (toast state side % "warning")) false)
title (:title card)]
(case reason
:lock-install
(reason-toast (str "Unable to install " title " since installing is currently locked"))
:req
(reason-toast (str "Installation requirements are not fulfilled for " title))
:locked-zone
(reason-toast (str "Unable to install " title " because it is currently in a locked zone"))
;; else
true))))
(defn- runner-install-message
"Prints the correct msg for the card install"
[state side card-title cost-str
{:keys [no-cost host-card facedown custom-message]}]
(if facedown
(system-msg state side "installs a card facedown")
(if custom-message
(system-msg state side (custom-message cost-str))
(system-msg state side
(str (build-spend-msg cost-str "install") card-title
(when host-card (str " on " (card-str state host-card)))
(when no-cost " at no cost"))))))
(defn runner-install-continue
[state side eid card
{:keys [previous-zone host-card facedown no-mu no-msg payment-str] :as args}]
(let [c (if host-card
(host state side host-card card)
(move state side card
[:rig (if facedown :facedown (to-keyword (:type card)))]))
c (assoc c
:installed :this-turn
:new true
:previous-zone previous-zone)
installed-card (if facedown
(update! state side c)
(card-init state side c {:resolve-effect false
:init-data true
:no-mu no-mu}))]
(when-not no-msg
(runner-install-message state side (:title installed-card) payment-str args))
(when-not facedown
(implementation-msg state card))
(play-sfx state side "install-runner")
(when (and (not facedown)
(resource? card))
(swap! state assoc-in [:runner :register :installed-resource] true))
(when (and (not facedown)
(has-subtype? installed-card "Icebreaker"))
(update-breaker-strength state side installed-card))
(queue-event state :runner-install {:card (get-card state installed-card)
:facedown facedown})
(when-let [on-install (and (not facedown)
(:on-install (card-def installed-card)))]
(register-pending-event state :runner-install installed-card on-install))
(wait-for (checkpoint state nil (make-eid state eid) nil)
(complete-with-result state side eid (get-card state installed-card)))))
(defn- runner-install-cost
"Get the total install cost for specified card"
[state side card
{:keys [base-cost ignore-install-cost ignore-all-cost facedown cost-bonus cached-costs]}]
(cond+
[cached-costs]
[(or ignore-all-cost facedown) [:credit 0]]
[:else
(let [cost (install-cost state side card {:cost-bonus cost-bonus} {:facedown facedown})
additional-costs (install-additional-cost-bonus state side card)]
(merge-costs
[base-cost
(when (and (not ignore-install-cost)
(not facedown))
[:credit cost])
additional-costs]))]))
(defn runner-can-pay-and-install?
[state side eid card {:keys [facedown] :as args}]
(let [costs (runner-install-cost state side (assoc card :facedown facedown) args)]
(and (runner-can-install? state side card args)
(can-pay? state side eid card nil costs)
;; explicitly return true
true)))
(defn runner-install-pay
[state side eid card {:keys [facedown] :as args}]
(let [costs (runner-install-cost state side (assoc card :facedown facedown) (dissoc args :cached-costs))]
(if-not (runner-can-pay-and-install? state side eid card (assoc args :cached-costs costs))
(effect-completed state side eid)
(if (and (program? card)
(not facedown)
(not (sufficient-mu? state card)))
(continue-ability
state side
{:prompt (format "Insufficient MU to install %s. Trash installed programs?" (:title card))
:choices {:max (count (all-installed-runner-type state :program))
:card #(and (installed? %)
(program? %))}
:async true
:effect (req (wait-for (trash-cards state side (make-eid state eid) targets {:game-trash true})
(update-mu state)
(runner-install-pay state side eid card args)))
:cancel-effect (effect (effect-completed eid))}
card nil)
(let [played-card (move state side (assoc card :facedown facedown) :play-area {:suppress-event true})]
(wait-for (pay state side (make-eid state eid) card costs)
(if-let [payment-str (:msg async-result)]
(runner-install-continue
state side eid
played-card (assoc args
:previous-zone (:zone card)
:payment-str payment-str))
(let [returned-card (move state :runner played-card (:zone card) {:suppress-event true})]
(update! state :runner
(assoc returned-card
:cid (:cid card)
:previous-zone (:previous-zone card)))
(effect-completed state side eid)))))))))
(defn runner-install
"Installs specified runner card if able"
([state side eid card] (runner-install state side eid card nil))
([state side eid card {:keys [host-card facedown] :as args}]
(let [eid (eid-set-defaults eid :source nil :source-type :runner-install)
hosting (and (not host-card)
(not facedown)
(:hosting (card-def card)))]
(if hosting
(continue-ability
state side
{:choices hosting
:prompt (str "Choose a card to host " (:title card) " on")
:async true
:effect (effect (runner-install-pay eid card (assoc args :host-card target)))}
card nil)
(runner-install-pay state side eid card args)))))
(defn install-as-condition-counter
"Install the event or operation onto the target as a condition counter."
[state side eid card target]
(assert (or (event? card) (operation? card)) "condition counter must be event or operation")
(let [cdef (card-def card)
abilities (ability-init cdef)
corp-abilities (corp-ability-init cdef)
runner-abilities (runner-ability-init cdef)
card (convert-to-condition-counter card)
events (filter #(= :hosted (:condition %)) (:events cdef))]
(if (corp? card)
(wait-for (corp-install state side (make-eid state eid)
card target {:host-card target
:ignore-all-cost true})
(let [card (update! state side (assoc async-result
:abilities abilities
:runner-abilities runner-abilities))]
(unregister-events state side card)
(unregister-constant-effects state side card)
(register-events state side card events)
(register-constant-effects state side card)
(complete-with-result state side eid card)))
(wait-for (runner-install state side (make-eid state eid)
card {:host-card target
:ignore-all-cost true})
(let [card (update! state side (assoc async-result
:abilities abilities
:corp-abilities corp-abilities))]
(unregister-events state side card)
(unregister-constant-effects state side card)
(register-events state side card events)
(register-constant-effects state side card)
(complete-with-result state side eid card))))))
| null | https://raw.githubusercontent.com/mtgred/netrunner/f92143720e7ec7e88e641445a1dc695aeb1ac7f0/src/clj/game/core/installing.clj | clojure | Intalling a corp card
Region check
ice install prevented by Unscheduled Maintenance
Installing not locked
no restrictions
failed region check
failed install lock check
failed ice check
else
make sure they didn't trash the card themselves
Ignore all costs
Pay costs
"Face-up" cards
All other cards
explicitly return true
No server selected; show prompt to select an install site (Interns, Lateral Growth, etc.)
A card was selected as the server; recurse, with the :host-card parameter set.
A server was selected
Unused in the corp install system, necessary for card definitions
Installing a runner card
Can always install a card facedown
Installing not locked
Req check
The card's zone is locked
Nothing preventing install
else
explicitly return true | (ns game.core.installing
(:require
[cond-plus.core :refer [cond+]]
[game.core.agendas :refer [update-advancement-requirement]]
[game.core.board :refer [all-installed get-remotes installable-servers server->zone all-installed-runner-type]]
[game.core.card :refer [agenda? asset? convert-to-condition-counter corp? event? get-card get-zone has-subtype? ice? operation? program? resource? rezzed? installed?]]
[game.core.card-defs :refer [card-def]]
[game.core.cost-fns :refer [ignore-install-cost? install-additional-cost-bonus install-cost]]
[game.core.eid :refer [complete-with-result effect-completed eid-set-defaults make-eid]]
[game.core.engine :refer [checkpoint register-pending-event pay queue-event register-events trigger-event-simult unregister-events]]
[game.core.effects :refer [register-constant-effects unregister-constant-effects]]
[game.core.flags :refer [turn-flag? zone-locked?]]
[game.core.hosting :refer [host]]
[game.core.ice :refer [update-breaker-strength]]
[game.core.initializing :refer [ability-init card-init corp-ability-init runner-ability-init]]
[game.core.memory :refer [sufficient-mu? update-mu]]
[game.core.moving :refer [move trash trash-cards]]
[game.core.payment :refer [build-spend-msg can-pay? merge-costs]]
[game.core.rezzing :refer [rez]]
[game.core.say :refer [play-sfx system-msg implementation-msg]]
[game.core.servers :refer [name-zone remote-num->name]]
[game.core.state :refer [make-rid]]
[game.core.to-string :refer [card-str]]
[game.core.toasts :refer [toast]]
[game.core.update :refer [update!]]
[game.macros :refer [continue-ability effect req wait-for]]
[game.utils :refer [dissoc-in in-coll? to-keyword]]))
(defn install-locked?
"Checks if installing is locked"
[state side]
(let [kw (keyword (str (name side) "-lock-install"))]
(or (seq (get-in @state [:stack :current-run kw]))
(seq (get-in @state [:stack :current-turn kw]))
(seq (get-in @state [:stack :persistent kw])))))
(defn- corp-can-install-reason
"Checks if the specified card can be installed.
Returns true if there are no problems
Returns :region if Region check fails
Returns :ice if ice check fails
!! NB: This should only be used in a check with `true?` as all return values are truthy"
[state side card slot]
(cond
(and (has-subtype? card "Region")
(some #(has-subtype? % "Region") (get-in @state (cons :corp slot))))
:region
(and (ice? card)
(not (turn-flag? state side card :can-install-ice)))
:ice
(install-locked? state :corp)
:lock-install
Earth station can not have more than one server
(and (= "Earth Station" (subs (:title (get-in @state [:corp :identity])) 0 (min 13 (count (:title (get-in @state [:corp :identity]))))))
(not (:disabled (get-in @state [:corp :identity])))
(pos? (count (get-remotes state)))
(not (in-coll? (conj (keys (get-remotes state)) :archives :rd :hq) (second slot))))
:earth-station
:else true))
(defn- corp-can-install?
"Checks `corp-can-install-reason` if not true, toasts reason and returns false"
[state side card slot {:keys [no-toast]}]
(let [reason (corp-can-install-reason state side card slot)
reason-toast #(do (when-not no-toast (toast state side % "warning")) false)
title (:title card)]
(case reason
:region
(reason-toast (str "Cannot install " (:title card) ", limit of one Region per server"))
:lock-install
(reason-toast (str "Unable to install " title ", installing is currently locked"))
:ice
(reason-toast (str "Unable to install " title ": can only install 1 piece of ice per turn"))
Earth station can not have more than one remote server
:earth-station
(reason-toast (str "Unable to install " title " in new remote: Earth Station limit"))
true)))
(defn- corp-install-asset-agenda
"Forces the corp to trash an existing asset or agenda if a second was just installed."
[state side eid card dest-zone server]
(let [prev-card (some #(when (or (asset? %) (agenda? %)) %) dest-zone)]
(if (and (or (asset? card) (agenda? card))
prev-card
(not (:host card)))
(continue-ability state side {:prompt (str "The " (:title prev-card) " in " server " will now be trashed.")
:choices ["OK"]
:async true
:effect (req (system-msg state :corp (str "trashes " (card-str state prev-card)))
(trash state :corp eid prev-card {:keep-server-alive true})
(effect-completed state :corp eid)))}
nil nil)
(effect-completed state side eid))))
(defn- corp-install-message
"Prints the correct install message."
[state side card server install-state cost-str args]
(when (:display-message args true)
(let [card-name (if (or (= :rezzed-no-cost install-state)
(= :face-up install-state)
(rezzed? card))
(:title card)
(if (ice? card) "ice" "a card"))
server-name (if (= server "New remote")
(str (remote-num->name (dec (:rid @state))) " (new remote)")
server)]
(system-msg state side (str (build-spend-msg cost-str "install") card-name
(if (ice? card) " protecting " " in ") server-name))
(when (and (= :face-up install-state)
(agenda? card))
(implementation-msg state card)))))
(defn corp-install-list
"Returns a list of targets for where a given card can be installed."
[state card]
(let [hosts (filter #(when-let [can-host (:can-host (card-def %))]
(and (rezzed? %)
(can-host state :corp (make-eid state) % [card])))
(all-installed state :corp))]
(concat hosts (installable-servers state card))))
(defn- corp-install-continue
"Used by corp-install to actually install the card, rez it if it's supposed to be installed
rezzed, and calls :corp-install in an awaitable fashion."
[state side eid card server {:keys [install-state host-card front index display-message] :as args} slot cost-str]
(let [cdef (card-def card)
dest-zone (get-in @state (cons :corp slot))
install-state (or (:install-state cdef) install-state)
no-msg (not (if (nil? display-message) true display-message))
c (-> card
(assoc :advanceable (:advanceable cdef) :new true)
(dissoc :seen :disabled))]
(when-not host-card
(corp-install-message state side c server install-state cost-str args))
(play-sfx state side "install-corp")
(let [moved-card (if host-card
(host state side host-card (assoc c :installed true))
(move state side c slot {:front front
:index index}))
_ (when (agenda? c)
(update-advancement-requirement state moved-card))
moved-card (get-card state moved-card)]
Check to see if a second agenda / asset was installed .
(wait-for (corp-install-asset-agenda state side moved-card dest-zone server)
(let [eid (assoc eid :source moved-card :source-type :rez)]
(queue-event state :corp-install {:card (get-card state moved-card)
:install-state install-state})
(case install-state
:rezzed-no-cost
(if-not (agenda? moved-card)
(rez state side eid moved-card {:ignore-cost :all-costs
:no-msg no-msg})
(checkpoint state nil eid))
Ignore cost only
:rezzed-no-rez-cost
(rez state side eid moved-card {:ignore-cost :rez-costs
:no-msg no-msg})
:rezzed
(if-not (agenda? moved-card)
(rez state side eid moved-card {:no-msg no-msg})
(checkpoint state nil eid))
:face-up
(let [moved-card (-> (get-card state moved-card)
(assoc :seen true)
(cond-> (not (agenda? card)) (assoc :rezzed true)))
moved-card (if (:install-state cdef)
(card-init state side moved-card {:resolve-effect false
:init-data true})
(update! state side moved-card))]
(wait-for (checkpoint state nil (make-eid state eid))
(complete-with-result state side eid (get-card state moved-card))))
(wait-for (checkpoint state nil (make-eid state eid))
(when-let [dre (:derezzed-events cdef)]
(register-events state side moved-card (map #(assoc % :condition :derezzed) dre)))
(complete-with-result state side eid (get-card state moved-card)))))))))
(defn get-slot
[state card server {:keys [host-card]}]
(if host-card
(get-zone host-card)
(conj (server->zone state server) (if (ice? card) :ices :content))))
(defn corp-install-cost
[state side card server
{:keys [base-cost ignore-install-cost ignore-all-cost cost-bonus cached-costs] :as args}]
(or cached-costs
(let [slot (get-slot state card server args)
dest-zone (get-in @state (cons :corp slot))
ice-cost (if (and (ice? card)
(not ignore-install-cost)
(not ignore-all-cost)
(not (ignore-install-cost? state side card)))
(count dest-zone)
0)
cost (install-cost state side card
{:cost-bonus (+ (or cost-bonus 0) ice-cost)}
{:server server
:dest-zone dest-zone})]
(when-not ignore-all-cost
(merge-costs [base-cost [:credit cost]])))))
(defn corp-can-pay-and-install?
[state side eid card server args]
(let [slot (get-slot state card server (select-keys args [:host-card]))
costs (corp-install-cost state side card server args)]
(and (corp-can-install? state side card slot (select-keys args [:no-toast]))
(can-pay? state side eid card nil costs)
true)))
(defn- corp-install-pay
"Used by corp-install to pay install costs"
[state side eid card server {:keys [action] :as args}]
(let [slot (get-slot state card server args)
costs (corp-install-cost state side card server (dissoc args :cached-costs))]
(if (corp-can-pay-and-install? state side eid card server (assoc args :cached-costs costs))
(wait-for (pay state side (make-eid state eid) card costs {:action action})
(if-let [payment-str (:msg async-result)]
(if (= server "New remote")
(wait-for (trigger-event-simult state side :server-created nil card)
(make-rid state)
(corp-install-continue state side eid card server args slot payment-str))
(corp-install-continue state side eid card server args slot payment-str))
(effect-completed state side eid)))
(effect-completed state side eid))))
(defn corp-install
"Installs a card in the chosen server. If server is nil, asks for server to install in.
The args input takes the following values:
:base-cost - Only used for click actions
:host-card - Card to host on
:ignore-all-cost - true if install costs should be ignored
:action - What type of action installed the card
:install-state - Can be :rezzed-no-cost, :rezzed-no-rez-cost, :rezzed, or :face-up
:display-message - Print descriptive text to the log window [default=true]
:index - which position for an installed piece of ice"
([state side eid card server] (corp-install state side eid card server nil))
([state side eid card server {:keys [host-card] :as args}]
(let [eid (eid-set-defaults eid :source nil :source-type :corp-install)]
(cond
(not server)
(continue-ability state side
{:prompt (str "Choose a location to install " (:title card))
:choices (corp-install-list state card)
:async true
:effect (effect (corp-install eid card target args))}
card nil)
(and (map? server)
(not host-card))
(corp-install state side eid card server (assoc args :host-card server))
:else
(do (swap! state dissoc-in [:corp :install-list])
(corp-install-pay state side eid card server args))))))
(defn corp-install-msg
"Gets a message describing where a card has been installed from. Example: Interns."
[card]
(str "install " (if (:seen card) (:title card) "an unseen card") " from " (name-zone :corp (:zone card))))
(defn- runner-can-install-reason
"Checks if the specified card can be installed.
Checks uniqueness of card and installed console.
Returns true if there are no problems
Returns :req if card-def :req check fails
!! NB: This should only be used in a check with `true?` as all return values are truthy"
[state side card facedown]
(let [card-req (:req (card-def card))]
(cond
facedown true
(install-locked? state :runner) :lock-install
(and card-req (not (card-req state side (make-eid state) card nil))) :req
(zone-locked? state side (first (get-zone card))) :locked-zone
:else true)))
(defn runner-can-install?
"Checks `runner-can-install-reason` if not true, toasts reason and returns false"
([state side card] (runner-can-install? state side card nil))
([state side card {:keys [facedown no-toast]}]
(let [reason (runner-can-install-reason state side card facedown)
reason-toast #(do (when-not no-toast (toast state side % "warning")) false)
title (:title card)]
(case reason
:lock-install
(reason-toast (str "Unable to install " title " since installing is currently locked"))
:req
(reason-toast (str "Installation requirements are not fulfilled for " title))
:locked-zone
(reason-toast (str "Unable to install " title " because it is currently in a locked zone"))
true))))
(defn- runner-install-message
"Prints the correct msg for the card install"
[state side card-title cost-str
{:keys [no-cost host-card facedown custom-message]}]
(if facedown
(system-msg state side "installs a card facedown")
(if custom-message
(system-msg state side (custom-message cost-str))
(system-msg state side
(str (build-spend-msg cost-str "install") card-title
(when host-card (str " on " (card-str state host-card)))
(when no-cost " at no cost"))))))
(defn runner-install-continue
[state side eid card
{:keys [previous-zone host-card facedown no-mu no-msg payment-str] :as args}]
(let [c (if host-card
(host state side host-card card)
(move state side card
[:rig (if facedown :facedown (to-keyword (:type card)))]))
c (assoc c
:installed :this-turn
:new true
:previous-zone previous-zone)
installed-card (if facedown
(update! state side c)
(card-init state side c {:resolve-effect false
:init-data true
:no-mu no-mu}))]
(when-not no-msg
(runner-install-message state side (:title installed-card) payment-str args))
(when-not facedown
(implementation-msg state card))
(play-sfx state side "install-runner")
(when (and (not facedown)
(resource? card))
(swap! state assoc-in [:runner :register :installed-resource] true))
(when (and (not facedown)
(has-subtype? installed-card "Icebreaker"))
(update-breaker-strength state side installed-card))
(queue-event state :runner-install {:card (get-card state installed-card)
:facedown facedown})
(when-let [on-install (and (not facedown)
(:on-install (card-def installed-card)))]
(register-pending-event state :runner-install installed-card on-install))
(wait-for (checkpoint state nil (make-eid state eid) nil)
(complete-with-result state side eid (get-card state installed-card)))))
(defn- runner-install-cost
"Get the total install cost for specified card"
[state side card
{:keys [base-cost ignore-install-cost ignore-all-cost facedown cost-bonus cached-costs]}]
(cond+
[cached-costs]
[(or ignore-all-cost facedown) [:credit 0]]
[:else
(let [cost (install-cost state side card {:cost-bonus cost-bonus} {:facedown facedown})
additional-costs (install-additional-cost-bonus state side card)]
(merge-costs
[base-cost
(when (and (not ignore-install-cost)
(not facedown))
[:credit cost])
additional-costs]))]))
(defn runner-can-pay-and-install?
[state side eid card {:keys [facedown] :as args}]
(let [costs (runner-install-cost state side (assoc card :facedown facedown) args)]
(and (runner-can-install? state side card args)
(can-pay? state side eid card nil costs)
true)))
(defn runner-install-pay
[state side eid card {:keys [facedown] :as args}]
(let [costs (runner-install-cost state side (assoc card :facedown facedown) (dissoc args :cached-costs))]
(if-not (runner-can-pay-and-install? state side eid card (assoc args :cached-costs costs))
(effect-completed state side eid)
(if (and (program? card)
(not facedown)
(not (sufficient-mu? state card)))
(continue-ability
state side
{:prompt (format "Insufficient MU to install %s. Trash installed programs?" (:title card))
:choices {:max (count (all-installed-runner-type state :program))
:card #(and (installed? %)
(program? %))}
:async true
:effect (req (wait-for (trash-cards state side (make-eid state eid) targets {:game-trash true})
(update-mu state)
(runner-install-pay state side eid card args)))
:cancel-effect (effect (effect-completed eid))}
card nil)
(let [played-card (move state side (assoc card :facedown facedown) :play-area {:suppress-event true})]
(wait-for (pay state side (make-eid state eid) card costs)
(if-let [payment-str (:msg async-result)]
(runner-install-continue
state side eid
played-card (assoc args
:previous-zone (:zone card)
:payment-str payment-str))
(let [returned-card (move state :runner played-card (:zone card) {:suppress-event true})]
(update! state :runner
(assoc returned-card
:cid (:cid card)
:previous-zone (:previous-zone card)))
(effect-completed state side eid)))))))))
(defn runner-install
"Installs specified runner card if able"
([state side eid card] (runner-install state side eid card nil))
([state side eid card {:keys [host-card facedown] :as args}]
(let [eid (eid-set-defaults eid :source nil :source-type :runner-install)
hosting (and (not host-card)
(not facedown)
(:hosting (card-def card)))]
(if hosting
(continue-ability
state side
{:choices hosting
:prompt (str "Choose a card to host " (:title card) " on")
:async true
:effect (effect (runner-install-pay eid card (assoc args :host-card target)))}
card nil)
(runner-install-pay state side eid card args)))))
(defn install-as-condition-counter
"Install the event or operation onto the target as a condition counter."
[state side eid card target]
(assert (or (event? card) (operation? card)) "condition counter must be event or operation")
(let [cdef (card-def card)
abilities (ability-init cdef)
corp-abilities (corp-ability-init cdef)
runner-abilities (runner-ability-init cdef)
card (convert-to-condition-counter card)
events (filter #(= :hosted (:condition %)) (:events cdef))]
(if (corp? card)
(wait-for (corp-install state side (make-eid state eid)
card target {:host-card target
:ignore-all-cost true})
(let [card (update! state side (assoc async-result
:abilities abilities
:runner-abilities runner-abilities))]
(unregister-events state side card)
(unregister-constant-effects state side card)
(register-events state side card events)
(register-constant-effects state side card)
(complete-with-result state side eid card)))
(wait-for (runner-install state side (make-eid state eid)
card {:host-card target
:ignore-all-cost true})
(let [card (update! state side (assoc async-result
:abilities abilities
:corp-abilities corp-abilities))]
(unregister-events state side card)
(unregister-constant-effects state side card)
(register-events state side card events)
(register-constant-effects state side card)
(complete-with-result state side eid card))))))
|
22d35727b7904cc2522940374b77069b0ea8b775feadebd20451767264980269 | apache/couchdb-rebar | rebar_subdirs.erl | -*- erlang - indent - level : 4;indent - tabs - mode : nil -*-
%% ex: ts=4 sw=4 et
%% -------------------------------------------------------------------
%%
rebar : Erlang Build Tools
%%
Copyright ( c ) 2009 ( )
%%
%% Permission is hereby granted, free of charge, to any person obtaining a copy
%% of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%% furnished to do so, subject to the following conditions:
%%
%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%% THE SOFTWARE.
%% -------------------------------------------------------------------
-module(rebar_subdirs).
-include("rebar.hrl").
-include_lib("kernel/include/file.hrl").
-export([preprocess/2]).
%% ===================================================================
%% Public API
%% ===================================================================
preprocess(Config, _) ->
%% Get the list of subdirs specified in the config (if any).
Cwd = rebar_utils:get_cwd(),
ListSubdirs = rebar_config:get_local(Config, sub_dirs, []),
Subdirs0 = lists:flatmap(fun filelib:wildcard/1, ListSubdirs),
case {rebar_config:is_skip_dir(Config, Cwd), Subdirs0} of
{true, []} ->
{ok, []};
{true, _} ->
?WARN("Ignoring sub_dirs for ~s~n", [Cwd]),
{ok, []};
{false, _} ->
Check = check_loop(Cwd),
ok = lists:foreach(Check, Subdirs0),
Subdirs = [filename:join(Cwd, Dir) || Dir <- Subdirs0],
{ok, Subdirs}
end.
%% ===================================================================
Internal functions
%% ===================================================================
check_loop(Cwd) ->
RebarConfig = filename:join(Cwd, "rebar.config"),
fun(Dir0) ->
IsSymlink = case file:read_link_info(Dir0) of
{ok, #file_info{type=symlink}} ->
{true, resolve_symlink(Dir0)};
_ ->
{false, Dir0}
end,
case IsSymlink of
{false, Dir="."} ->
?ERROR("infinite loop detected:~nsub_dirs"
" entry ~p in ~s~n", [Dir, RebarConfig]);
{true, Cwd} ->
?ERROR("infinite loop detected:~nsub_dirs"
" entry ~p in ~s is a symlink to \".\"~n",
[Dir0, RebarConfig]);
_ ->
ok
end
end.
resolve_symlink(Dir0) ->
{ok, Dir} = file:read_link(Dir0),
Dir.
| null | https://raw.githubusercontent.com/apache/couchdb-rebar/8578221c20d0caa3deb724e5622a924045ffa8bf/src/rebar_subdirs.erl | erlang | ex: ts=4 sw=4 et
-------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-------------------------------------------------------------------
===================================================================
Public API
===================================================================
Get the list of subdirs specified in the config (if any).
===================================================================
=================================================================== | -*- erlang - indent - level : 4;indent - tabs - mode : nil -*-
rebar : Erlang Build Tools
Copyright ( c ) 2009 ( )
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-module(rebar_subdirs).
-include("rebar.hrl").
-include_lib("kernel/include/file.hrl").
-export([preprocess/2]).
preprocess(Config, _) ->
Cwd = rebar_utils:get_cwd(),
ListSubdirs = rebar_config:get_local(Config, sub_dirs, []),
Subdirs0 = lists:flatmap(fun filelib:wildcard/1, ListSubdirs),
case {rebar_config:is_skip_dir(Config, Cwd), Subdirs0} of
{true, []} ->
{ok, []};
{true, _} ->
?WARN("Ignoring sub_dirs for ~s~n", [Cwd]),
{ok, []};
{false, _} ->
Check = check_loop(Cwd),
ok = lists:foreach(Check, Subdirs0),
Subdirs = [filename:join(Cwd, Dir) || Dir <- Subdirs0],
{ok, Subdirs}
end.
Internal functions
check_loop(Cwd) ->
RebarConfig = filename:join(Cwd, "rebar.config"),
fun(Dir0) ->
IsSymlink = case file:read_link_info(Dir0) of
{ok, #file_info{type=symlink}} ->
{true, resolve_symlink(Dir0)};
_ ->
{false, Dir0}
end,
case IsSymlink of
{false, Dir="."} ->
?ERROR("infinite loop detected:~nsub_dirs"
" entry ~p in ~s~n", [Dir, RebarConfig]);
{true, Cwd} ->
?ERROR("infinite loop detected:~nsub_dirs"
" entry ~p in ~s is a symlink to \".\"~n",
[Dir0, RebarConfig]);
_ ->
ok
end
end.
resolve_symlink(Dir0) ->
{ok, Dir} = file:read_link(Dir0),
Dir.
|
1b0942dd7e6e9ca7dccb3c88b2ef6c7ba999c6467355608f628459374a290c66 | zenspider/schemers | exercise.1.37.scm | #lang racket/base
Exercise 1.37 :
;; a. An infinite "continued fraction" is an expression of the form
;;
N[1 ]
;; f = ---------------------
;; N[2]
;; D[1] + ---------------
]
---------
;; D[3] + ...
;;
;; As an example, one can show that the infinite continued
fraction expansion with the n[i ] and the D[i ] all equal to 1
produces 1/[phi ] , where [ phi ] is the golden ratio ( described
in section * Note 1 - 2 - 2 : :) . One way to approximate an
;; infinite continued fraction is to truncate the expansion
;; after a given number of terms. Such a truncation--a
;; so-called finite continued fraction "k-term finite continued
;; fraction"--has the form
;;
N[1 ]
;; -----------------
;; N[2]
;; D[1] + -----------
;; ... N[K]
;; + -----
;; D[K]
;;
Suppose that ` n ' and ` d ' are procedures of one argument ( the
;; term index i) that return the n[i] and D[i] of the terms of the
;; continued fraction. Define a procedure `cont-frac' such that
;; evaluating `(cont-frac n d k)' computes the value of the
;; k-term finite continued fraction. Check your procedure by
approximating 1/[phi ] using
;;
( cont - frac ( lambda ( i ) 1.0 )
( lambda ( i ) 1.0 )
;; k)
;;
;; for successive values of `k'. How large must you make `k' in
order to get an approximation that is accurate to 4 decimal
;; places?
(define (cont-frac n d i)
(if (< i 1) 0
(/ (n i)
(+ (d i) (cont-frac n d (- i 1))))))
(define (phi-approx k)
(/ 1 (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) k)))
(define (cont-frac-test places)
(let ((error (expt 10 (- (+ places 1))))
(phi (/ (+ 1 (sqrt 5)) 2)))
(define (iterate n)
(if (< (abs (- phi (phi-approx n))) error)
n
(iterate (+ n 1))))
(iterate 1)))
13
1.6180257510729614
1.618033988749895
;; b. If your `cont-frac' procedure generates a recursive process,
;; write one that generates an iterative process. If it
;; generates an iterative process, write one that generates a
;; recursive process.
seriously ? are MIT students this bad at this ?
(define (cont-frac-i n d i)
(define (iterate i fraction)
(if (< i 1) fraction
(iterate (- i 1)
(/ (n i)
(+ (d i) fraction)))))
(iterate i 0))
(define (phi-approx-i k)
(/ 1 (cont-frac-i (lambda (i) 1.0) (lambda (i) 1.0) k)))
1.6180257510729614
| null | https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_1/exercise.1.37.scm | scheme | a. An infinite "continued fraction" is an expression of the form
f = ---------------------
N[2]
D[1] + ---------------
D[3] + ...
As an example, one can show that the infinite continued
infinite continued fraction is to truncate the expansion
after a given number of terms. Such a truncation--a
so-called finite continued fraction "k-term finite continued
fraction"--has the form
-----------------
N[2]
D[1] + -----------
... N[K]
+ -----
D[K]
term index i) that return the n[i] and D[i] of the terms of the
continued fraction. Define a procedure `cont-frac' such that
evaluating `(cont-frac n d k)' computes the value of the
k-term finite continued fraction. Check your procedure by
k)
for successive values of `k'. How large must you make `k' in
places?
b. If your `cont-frac' procedure generates a recursive process,
write one that generates an iterative process. If it
generates an iterative process, write one that generates a
recursive process. | #lang racket/base
Exercise 1.37 :
N[1 ]
]
---------
fraction expansion with the n[i ] and the D[i ] all equal to 1
produces 1/[phi ] , where [ phi ] is the golden ratio ( described
in section * Note 1 - 2 - 2 : :) . One way to approximate an
N[1 ]
Suppose that ` n ' and ` d ' are procedures of one argument ( the
approximating 1/[phi ] using
( cont - frac ( lambda ( i ) 1.0 )
( lambda ( i ) 1.0 )
order to get an approximation that is accurate to 4 decimal
(define (cont-frac n d i)
(if (< i 1) 0
(/ (n i)
(+ (d i) (cont-frac n d (- i 1))))))
(define (phi-approx k)
(/ 1 (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) k)))
(define (cont-frac-test places)
(let ((error (expt 10 (- (+ places 1))))
(phi (/ (+ 1 (sqrt 5)) 2)))
(define (iterate n)
(if (< (abs (- phi (phi-approx n))) error)
n
(iterate (+ n 1))))
(iterate 1)))
13
1.6180257510729614
1.618033988749895
seriously ? are MIT students this bad at this ?
(define (cont-frac-i n d i)
(define (iterate i fraction)
(if (< i 1) fraction
(iterate (- i 1)
(/ (n i)
(+ (d i) fraction)))))
(iterate i 0))
(define (phi-approx-i k)
(/ 1 (cont-frac-i (lambda (i) 1.0) (lambda (i) 1.0) k)))
1.6180257510729614
|
f1d8aa79c2f5a2cae94e3b16404fc8534c2c723635c0aed557139298aa67e6db | michalkonecny/aern2 | Optimisation.hs | module AERN2.BoxFun.Optimisation where
import qualified Prelude
import MixedTypesNumPrelude
import qualified Numeric.CollectErrors as CN
import AERN2.MP.Dyadic
import AERN2.MP.Ball
import AERN2.BoxFun.Box (Box)
import qualified AERN2.BoxFun.Box as Box
import AERN2.BoxFun.Type
import AERN2.Kleenean
import AERN2.Linear.Vector.Type as V
import AERN2.Linear.Matrix.Type
import AERN2.Linear.Matrix.Inverse
import qualified Data.List as List
import qualified AERN2.PQueue as Q
import AERN2.Util.Util
import Debug.Trace (trace)
globalMinimumGreaterThanN :: BoxFun -> Accuracy -> CN Rational -> Precision -> Bool
globalMinimumGreaterThanN f ac n initialPrecision =
trace (show x)
x !>! n
where x = globalMinimum f ac initialPrecision
minFun :: BoxFun -> Accuracy -> Precision -> (Integer, CN MPBall)
minFun f ac initialPrecision =
bestLocalMinimum f (domain f) ac initialPrecision
data SearchBox =
SearchBox
{
extents :: Box
, minimum :: CN MPBall
} deriving (Show)
instance
HasPrecision SearchBox
where
getPrecision (SearchBox b _) = getPrecision b
instance
CanSetPrecision SearchBox
where
setPrecision p (SearchBox b m) = SearchBox (setPrecision p b) m
instance Prelude.Eq SearchBox where
(==) (SearchBox _ _) (SearchBox _ _) =
False -- TODO: safe?
instance Prelude.Ord SearchBox where
(<=) (SearchBox _ min0) (SearchBox _ min1) =
case (CN.toEither $ (lowerBound min0 :: CN MPBall), CN.toEither $ (lowerBound min1 :: CN MPBall)) of
(Left _, Left _) -> True
(Left _, Right _ ) -> True
(Right _ , Left _) -> False
(Right m0, Right m1) ->
centre m0 - (dyadic $ radius m0) <= centre m1 - (dyadic $ radius m1) -- TODO: radius should be 0
---
globalMinimumWithCutoff :: BoxFun -> Accuracy -> CN MPBall -> Precision -> CN MPBall
globalMinimumWithCutoff f ac cutoff initialPrecision =
if dimension f == 1 then
let
fl = apply f (V.map lowerBound $ domain f)
fr = apply f (V.map upperBound $ domain f)
localMin = snd $ bestLocalMinimumWithCutoff f (domain f) ac cutoff initialPrecision
in
min fl $ min localMin fr
else
let
localMin = snd $ bestLocalMinimumWithCutoff f (domain f) ac cutoff initialPrecision
boundaryFuns = boundaryRestrictions f
boundaryMinima = List.map (\g -> globalMinimumWithCutoff g ac (min cutoff ((upperBound localMin :: CN MPBall))) initialPrecision) boundaryFuns
in
List.foldl' min localMin boundaryMinima
globalMinimum :: BoxFun -> Accuracy -> Precision -> CN MPBall
globalMinimum f ac initialPrecision =
globalMinimumWithCutoff f ac (apply f (centre boxp)) initialPrecision
where
boxp = setPrecision initialPrecision (domain f)
bestLocalMinimum :: BoxFun -> Box -> Accuracy -> Precision -> (Integer, CN MPBall)
bestLocalMinimum f box ac initialPrecision =
bestLocalMinimumWithCutoff f box ac (apply f (centre boxp)) initialPrecision
where
boxp = setPrecision initialPrecision box
bestLocalMinimumWithCutoff :: BoxFun -> Box -> Accuracy -> CN MPBall -> Precision -> (Integer, CN MPBall)
bestLocalMinimumWithCutoff f box ac initialCutoff initialPrecision =
aux initialQueue initialCutoff 0 dummyBox
where
boxp = setPrecision initialPrecision box
initialRange = apply f boxp
initialSearchBox = SearchBox boxp initialRange
initialQueue = Q.singleton initialSearchBox
dummyBox = SearchBox (V.fromList [cn $ mpBall $ 10^6]) initialRange -- TODO: hack...
aux q cutoff steps (SearchBox _lastBox rng) =
case Q.minView q of
Nothing -> trace ("no local minimum.") $ (steps, rng)
Just (minBox, q') ->
--trace ("value: "++ (show $ val)) $
trace ("min box: "++ (show $ minBox)) $
trace ( " box acc : " + + ( show $ getAccuracy $ ext ) ) $
trace ( show $ Box.width ( extents minBox ) ) $
trace ( " lower bound " + + ( show $ Box.lowerBound $ val ) ) $
--trace ("val' "++ (show $ val')) $
trace ("cutoff: "++ (show $ cutoff)) $
trace ("queue size: "++ (show $ Q.size q)) $
trace ( " cutoff = = 0 ? " + + ( show $ cutoff = = ( mpBall 0 ) ) ) $
--trace ("precision: "++ (show $ precision)) $
--trace ("dist to last "++ (show $ distToLast)) $
--trace ("accuracy: "++ (show $ getAccuracy val')) $
--trace ("precision centre: "++ (show $ fmap (getPrecision . centre) val)) $
if getAccuracy val' >= ac then
(steps, val')
else
aux q'' newCutoff (steps + 1) (SearchBox ext rng)
where
val' = fromEndpointsAsIntervals (lowerBound val) (cutoff)
SearchBox ext val = minBox
(newCutoff, newBoxes) =
processBox f ac cutoff minBox
q'' = foldr (Q.insert) q' newBoxes
lipschitzContraction :: BoxFun -> Box -> SearchBox -> SearchBox
lipschitzContraction f g (SearchBox box m) =
trace("fa : " + + ( show $ getAccuracy ( apply f box ) ) ) $
trace("la : " + + ( show $ getAccuracy $ dotProduct ) ) $
trace("ba : " + + ( show $ getAccuracy $ box ! int 0 ) ) $
trace("la: "++(show $ getAccuracy $ dotProduct)) $
trace("ba: "++(show $ getAccuracy $ box ! int 0)) $-}
if ( radius $ ( ~ ! ) ) < ( radius $ ( ~ ! ) $ m ) then
trace ( " better . " )
box m '
else
trace ("Lipschitz better.")
SearchBox box m'
else -}
SearchBox box m'
where
boxCentre = centre box
centreValue = apply f boxCentre
difference = box - boxCentre
dotProduct = g * difference
newRange = centreValue + dotProduct
m' = intersectCN m newRange
lipschitzRange :: BoxFun -> CN MPBall -> Box -> Box -> Box -> CN MPBall -> CN MPBall
lipschitzRange _f fc c g box m =
m'
where
difference = box - c
normG = Box.ellOneNorm g
normDiff = Box.inftyNorm difference
dotProduct = normG * normDiff
newRange = fc + (fromEndpointsAsIntervals (-dotProduct) dotProduct :: CN MPBall)
m' = intersectCN m newRange
applyLipschitz :: BoxFun -> Box -> CN MPBall
applyLipschitz f box =
lipschitzRange f fbc bc dfb' box fb
where
(fb, dfb') = valueGradient f box
bc = centre box
fbc = apply f bc
increasePrecision :: Precision -> Precision
increasePrecision p =
p + (prec $ (integer p) `Prelude.div` 2)
newtonStep :: BoxFun -> Accuracy -> Vector (CN MPBall) -> Vector (CN MPBall) -> Matrix (CN MPBall) -> SearchBox -> Bool -> Maybe (Bool, SearchBox)
newtonStep f ac c dfc hInv b@(SearchBox box m) newtonSuccesful =
--Just $ SearchBox box' m'
trace ( " precision m " + + ( show $ ( fmap getPrecision ) m ) ) $
trace ( " precision m ' " + + ( show $ ( fmap getPrecision ) m ' ) ) $
trace ( " precision box centre " + + ( show $ getPrecision c ) ) $
trace ( " precision box " + + ( show $ getPrecision box ) ) $
trace ( " precision box " + + ( show $ getPrecision newtonBox ) ) $
trace ( " precision box ' " + + ( show $ getPrecision box ' ) ) $
trace ( " precision " + + ( show $ getPrecision ( entries ! int 0 ) ) ) $
trace ("precision m' "++(show $ (fmap getPrecision) m')) $
trace ("precision box centre "++(show $ getPrecision c)) $
trace ("precision box "++(show $ getPrecision box)) $
trace ("precision newton box "++(show $ getPrecision newtonBox)) $
trace ("precision box' "++(show $ getPrecision box')) $
trace ("precision hInv "++(show $ getPrecision (entries hInv ! int 0))) $-}
if getAccuracy m >= ac then
Just (newtonSuccesful, b)
--else if not hInvDefined then
-- Just (newtonSuccesful, b)
else if Box.intersectionCertainlyEmpty box newtonBox then
Nothing
else if Box.width box' !<=! (dyadic $ 0.75) * Box.width box then
if getAccuracy m' > getAccuracy m then
newtonStep f ac c dfc hInv (SearchBox box' m') True
else
Just (True, SearchBox (setPrecision (increasePrecision $ getPrecision box') box') m')
else
Just (newtonSuccesful, SearchBox box' m')
where
{-c = centre box
dfc = gradient f c-}
hInvDefined = V.foldl ' ( & & ) ( True ) $ V.map ( isJust . fst . ensureNoCN ) ( entries )
newtonBox = c - hInv * (dfc)
box' = Box.nonEmptyIntersection box newtonBox
m' = apply f box'
processBox :: BoxFun -> Accuracy -> CN MPBall -> SearchBox -> (CN MPBall, [SearchBox])
processBox f ac cutoff box =
if getAccuracy ext < bits 10 then
split f (gradient f ext) cutoff ext
else
result
where
ext = extents box
(_fb, dfb, hfb) = valueGradientHessian f ext
c = centre ext
dfc = gradient f c
maybeHinv = inverse hfb
-- p = getPrecision box
box' = --Just (False, box)
case maybeHinv of
Nothing -> Just (False, box)
Just hInv -> newtonStep f ac c dfc hInv box False
result =
case box' of
Nothing -> (cutoff, [])
Just (newtonSuccesful, bx@(SearchBox bxe m)) ->
let
c' = min (upperBound $ apply f $ centre bxe :: CN MPBall) cutoff
in
if newtonSuccesful then
if getAccuracy m >= ac then
(c', [bx])
else
processBox f ac c' bx
else
split f dfb c' bxe
split :: BoxFun -> Vector (CN MPBall) -> CN MPBall -> Box -> (CN MPBall, [SearchBox])
split f dfb cutoff bxe =
let
diff = bxe - centre bxe
dir i = (fmap dyadic) $ (fmap radius) $ (dfb ! i) * (diff ! i) :: CN Dyadic
dirs = V.map dir $ V.enumFromTo 0 (V.length bxe - 1)
dirsDefined = V.foldl' (&&) True $ V.map (not . CN.hasError) dirs
aux k j d =
if k == V.length bxe then
j
else
let
d' = unCN $ dirs ! k
in
if d' > d then
aux (k + 1) k d'
else
aux (k + 1) j d
splittingIndex =
if dirsDefined then (aux 1 0 (unCN $ dirs ! 0)) else Box.widestDirection bxe
(a , b) = Box.bisect splittingIndex bxe
(fa, dfa') = valueGradient f a
(fb, dfb') = valueGradient f b
ac = centre a
bc = centre b
fac = apply f ac
fbc = apply f bc
fa' = lipschitzRange f fac ac dfa' a fa
fb' = lipschitzRange f fbc bc dfb' b fb
cutoff' = min (upperBound fac :: CN MPBall) $ min (upperBound fbc :: CN MPBall) cutoff
leftMonotone = V.foldl' (||) False $ V.map (!/=! 0) dfa'
rightMonotone = V.foldl' (||) False $ V.map (!/=! 0) dfb'
boxes =
case (leftMonotone || fa' !>! cutoff', rightMonotone || fb' !>! cutoff') of
(True, True) -> []
(True, False) -> [SearchBox b fb']
(False, True) -> [SearchBox a fa']
(False, False) -> [SearchBox a fa', SearchBox b fb']
in
(cutoff', boxes)
Precondition : f and must have the same domain
maxBoxFunGreaterThanN :: BoxFun -> BoxFun -> CN Rational -> Precision -> Bool
maxBoxFunGreaterThanN f g n initialPrecision =
case Box.getEndpoints fbox == Box.getEndpoints gbox of
CertainTrue ->
checkMaxAboveN f g ||
(Box.width fboxp !>! cutoff && Box.width gboxp !>! cutoff) &&
let
newBoxes = Box.fullBisect fboxp
updateDomain z = BoxFun (dimension z) (bf_eval z)
checkBoxes [] = True
checkBoxes (box : boxes) =
if checkMaxAboveN (updateDomain f box) (updateDomain g box)
then checkBoxes boxes
else maxBoxFunGreaterThanN f' g' n initialPrecision && checkBoxes boxes
where
f' = updateDomain f box
g' = updateDomain g box
in
checkBoxes newBoxes
_ ->
trace "Domain of f not equal to domain of g"
False
where
cutoff = 1/2^10
fbox = domain f
fboxp = setPrecision initialPrecision fbox
gbox = domain g
gboxp = setPrecision initialPrecision gbox
checkMaxAboveN h i = applyMinimum h !>! n || applyMinimum i !>! n
| null | https://raw.githubusercontent.com/michalkonecny/aern2/025005773f075280b89d8467b78cd74cb4e40cd5/aern2-mfun/src/AERN2/BoxFun/Optimisation.hs | haskell | TODO: safe?
TODO: radius should be 0
-
TODO: hack...
trace ("value: "++ (show $ val)) $
trace ("val' "++ (show $ val')) $
trace ("precision: "++ (show $ precision)) $
trace ("dist to last "++ (show $ distToLast)) $
trace ("accuracy: "++ (show $ getAccuracy val')) $
trace ("precision centre: "++ (show $ fmap (getPrecision . centre) val)) $
Just $ SearchBox box' m'
else if not hInvDefined then
Just (newtonSuccesful, b)
c = centre box
dfc = gradient f c
p = getPrecision box
Just (False, box) | module AERN2.BoxFun.Optimisation where
import qualified Prelude
import MixedTypesNumPrelude
import qualified Numeric.CollectErrors as CN
import AERN2.MP.Dyadic
import AERN2.MP.Ball
import AERN2.BoxFun.Box (Box)
import qualified AERN2.BoxFun.Box as Box
import AERN2.BoxFun.Type
import AERN2.Kleenean
import AERN2.Linear.Vector.Type as V
import AERN2.Linear.Matrix.Type
import AERN2.Linear.Matrix.Inverse
import qualified Data.List as List
import qualified AERN2.PQueue as Q
import AERN2.Util.Util
import Debug.Trace (trace)
globalMinimumGreaterThanN :: BoxFun -> Accuracy -> CN Rational -> Precision -> Bool
globalMinimumGreaterThanN f ac n initialPrecision =
trace (show x)
x !>! n
where x = globalMinimum f ac initialPrecision
minFun :: BoxFun -> Accuracy -> Precision -> (Integer, CN MPBall)
minFun f ac initialPrecision =
bestLocalMinimum f (domain f) ac initialPrecision
data SearchBox =
SearchBox
{
extents :: Box
, minimum :: CN MPBall
} deriving (Show)
instance
HasPrecision SearchBox
where
getPrecision (SearchBox b _) = getPrecision b
instance
CanSetPrecision SearchBox
where
setPrecision p (SearchBox b m) = SearchBox (setPrecision p b) m
instance Prelude.Eq SearchBox where
(==) (SearchBox _ _) (SearchBox _ _) =
instance Prelude.Ord SearchBox where
(<=) (SearchBox _ min0) (SearchBox _ min1) =
case (CN.toEither $ (lowerBound min0 :: CN MPBall), CN.toEither $ (lowerBound min1 :: CN MPBall)) of
(Left _, Left _) -> True
(Left _, Right _ ) -> True
(Right _ , Left _) -> False
(Right m0, Right m1) ->
globalMinimumWithCutoff :: BoxFun -> Accuracy -> CN MPBall -> Precision -> CN MPBall
globalMinimumWithCutoff f ac cutoff initialPrecision =
if dimension f == 1 then
let
fl = apply f (V.map lowerBound $ domain f)
fr = apply f (V.map upperBound $ domain f)
localMin = snd $ bestLocalMinimumWithCutoff f (domain f) ac cutoff initialPrecision
in
min fl $ min localMin fr
else
let
localMin = snd $ bestLocalMinimumWithCutoff f (domain f) ac cutoff initialPrecision
boundaryFuns = boundaryRestrictions f
boundaryMinima = List.map (\g -> globalMinimumWithCutoff g ac (min cutoff ((upperBound localMin :: CN MPBall))) initialPrecision) boundaryFuns
in
List.foldl' min localMin boundaryMinima
globalMinimum :: BoxFun -> Accuracy -> Precision -> CN MPBall
globalMinimum f ac initialPrecision =
globalMinimumWithCutoff f ac (apply f (centre boxp)) initialPrecision
where
boxp = setPrecision initialPrecision (domain f)
bestLocalMinimum :: BoxFun -> Box -> Accuracy -> Precision -> (Integer, CN MPBall)
bestLocalMinimum f box ac initialPrecision =
bestLocalMinimumWithCutoff f box ac (apply f (centre boxp)) initialPrecision
where
boxp = setPrecision initialPrecision box
bestLocalMinimumWithCutoff :: BoxFun -> Box -> Accuracy -> CN MPBall -> Precision -> (Integer, CN MPBall)
bestLocalMinimumWithCutoff f box ac initialCutoff initialPrecision =
aux initialQueue initialCutoff 0 dummyBox
where
boxp = setPrecision initialPrecision box
initialRange = apply f boxp
initialSearchBox = SearchBox boxp initialRange
initialQueue = Q.singleton initialSearchBox
aux q cutoff steps (SearchBox _lastBox rng) =
case Q.minView q of
Nothing -> trace ("no local minimum.") $ (steps, rng)
Just (minBox, q') ->
trace ("min box: "++ (show $ minBox)) $
trace ( " box acc : " + + ( show $ getAccuracy $ ext ) ) $
trace ( show $ Box.width ( extents minBox ) ) $
trace ( " lower bound " + + ( show $ Box.lowerBound $ val ) ) $
trace ("cutoff: "++ (show $ cutoff)) $
trace ("queue size: "++ (show $ Q.size q)) $
trace ( " cutoff = = 0 ? " + + ( show $ cutoff = = ( mpBall 0 ) ) ) $
if getAccuracy val' >= ac then
(steps, val')
else
aux q'' newCutoff (steps + 1) (SearchBox ext rng)
where
val' = fromEndpointsAsIntervals (lowerBound val) (cutoff)
SearchBox ext val = minBox
(newCutoff, newBoxes) =
processBox f ac cutoff minBox
q'' = foldr (Q.insert) q' newBoxes
lipschitzContraction :: BoxFun -> Box -> SearchBox -> SearchBox
lipschitzContraction f g (SearchBox box m) =
trace("fa : " + + ( show $ getAccuracy ( apply f box ) ) ) $
trace("la : " + + ( show $ getAccuracy $ dotProduct ) ) $
trace("ba : " + + ( show $ getAccuracy $ box ! int 0 ) ) $
trace("la: "++(show $ getAccuracy $ dotProduct)) $
trace("ba: "++(show $ getAccuracy $ box ! int 0)) $-}
if ( radius $ ( ~ ! ) ) < ( radius $ ( ~ ! ) $ m ) then
trace ( " better . " )
box m '
else
trace ("Lipschitz better.")
SearchBox box m'
else -}
SearchBox box m'
where
boxCentre = centre box
centreValue = apply f boxCentre
difference = box - boxCentre
dotProduct = g * difference
newRange = centreValue + dotProduct
m' = intersectCN m newRange
lipschitzRange :: BoxFun -> CN MPBall -> Box -> Box -> Box -> CN MPBall -> CN MPBall
lipschitzRange _f fc c g box m =
m'
where
difference = box - c
normG = Box.ellOneNorm g
normDiff = Box.inftyNorm difference
dotProduct = normG * normDiff
newRange = fc + (fromEndpointsAsIntervals (-dotProduct) dotProduct :: CN MPBall)
m' = intersectCN m newRange
applyLipschitz :: BoxFun -> Box -> CN MPBall
applyLipschitz f box =
lipschitzRange f fbc bc dfb' box fb
where
(fb, dfb') = valueGradient f box
bc = centre box
fbc = apply f bc
increasePrecision :: Precision -> Precision
increasePrecision p =
p + (prec $ (integer p) `Prelude.div` 2)
newtonStep :: BoxFun -> Accuracy -> Vector (CN MPBall) -> Vector (CN MPBall) -> Matrix (CN MPBall) -> SearchBox -> Bool -> Maybe (Bool, SearchBox)
newtonStep f ac c dfc hInv b@(SearchBox box m) newtonSuccesful =
trace ( " precision m " + + ( show $ ( fmap getPrecision ) m ) ) $
trace ( " precision m ' " + + ( show $ ( fmap getPrecision ) m ' ) ) $
trace ( " precision box centre " + + ( show $ getPrecision c ) ) $
trace ( " precision box " + + ( show $ getPrecision box ) ) $
trace ( " precision box " + + ( show $ getPrecision newtonBox ) ) $
trace ( " precision box ' " + + ( show $ getPrecision box ' ) ) $
trace ( " precision " + + ( show $ getPrecision ( entries ! int 0 ) ) ) $
trace ("precision m' "++(show $ (fmap getPrecision) m')) $
trace ("precision box centre "++(show $ getPrecision c)) $
trace ("precision box "++(show $ getPrecision box)) $
trace ("precision newton box "++(show $ getPrecision newtonBox)) $
trace ("precision box' "++(show $ getPrecision box')) $
trace ("precision hInv "++(show $ getPrecision (entries hInv ! int 0))) $-}
if getAccuracy m >= ac then
Just (newtonSuccesful, b)
else if Box.intersectionCertainlyEmpty box newtonBox then
Nothing
else if Box.width box' !<=! (dyadic $ 0.75) * Box.width box then
if getAccuracy m' > getAccuracy m then
newtonStep f ac c dfc hInv (SearchBox box' m') True
else
Just (True, SearchBox (setPrecision (increasePrecision $ getPrecision box') box') m')
else
Just (newtonSuccesful, SearchBox box' m')
where
hInvDefined = V.foldl ' ( & & ) ( True ) $ V.map ( isJust . fst . ensureNoCN ) ( entries )
newtonBox = c - hInv * (dfc)
box' = Box.nonEmptyIntersection box newtonBox
m' = apply f box'
processBox :: BoxFun -> Accuracy -> CN MPBall -> SearchBox -> (CN MPBall, [SearchBox])
processBox f ac cutoff box =
if getAccuracy ext < bits 10 then
split f (gradient f ext) cutoff ext
else
result
where
ext = extents box
(_fb, dfb, hfb) = valueGradientHessian f ext
c = centre ext
dfc = gradient f c
maybeHinv = inverse hfb
case maybeHinv of
Nothing -> Just (False, box)
Just hInv -> newtonStep f ac c dfc hInv box False
result =
case box' of
Nothing -> (cutoff, [])
Just (newtonSuccesful, bx@(SearchBox bxe m)) ->
let
c' = min (upperBound $ apply f $ centre bxe :: CN MPBall) cutoff
in
if newtonSuccesful then
if getAccuracy m >= ac then
(c', [bx])
else
processBox f ac c' bx
else
split f dfb c' bxe
split :: BoxFun -> Vector (CN MPBall) -> CN MPBall -> Box -> (CN MPBall, [SearchBox])
split f dfb cutoff bxe =
let
diff = bxe - centre bxe
dir i = (fmap dyadic) $ (fmap radius) $ (dfb ! i) * (diff ! i) :: CN Dyadic
dirs = V.map dir $ V.enumFromTo 0 (V.length bxe - 1)
dirsDefined = V.foldl' (&&) True $ V.map (not . CN.hasError) dirs
aux k j d =
if k == V.length bxe then
j
else
let
d' = unCN $ dirs ! k
in
if d' > d then
aux (k + 1) k d'
else
aux (k + 1) j d
splittingIndex =
if dirsDefined then (aux 1 0 (unCN $ dirs ! 0)) else Box.widestDirection bxe
(a , b) = Box.bisect splittingIndex bxe
(fa, dfa') = valueGradient f a
(fb, dfb') = valueGradient f b
ac = centre a
bc = centre b
fac = apply f ac
fbc = apply f bc
fa' = lipschitzRange f fac ac dfa' a fa
fb' = lipschitzRange f fbc bc dfb' b fb
cutoff' = min (upperBound fac :: CN MPBall) $ min (upperBound fbc :: CN MPBall) cutoff
leftMonotone = V.foldl' (||) False $ V.map (!/=! 0) dfa'
rightMonotone = V.foldl' (||) False $ V.map (!/=! 0) dfb'
boxes =
case (leftMonotone || fa' !>! cutoff', rightMonotone || fb' !>! cutoff') of
(True, True) -> []
(True, False) -> [SearchBox b fb']
(False, True) -> [SearchBox a fa']
(False, False) -> [SearchBox a fa', SearchBox b fb']
in
(cutoff', boxes)
Precondition : f and must have the same domain
maxBoxFunGreaterThanN :: BoxFun -> BoxFun -> CN Rational -> Precision -> Bool
maxBoxFunGreaterThanN f g n initialPrecision =
case Box.getEndpoints fbox == Box.getEndpoints gbox of
CertainTrue ->
checkMaxAboveN f g ||
(Box.width fboxp !>! cutoff && Box.width gboxp !>! cutoff) &&
let
newBoxes = Box.fullBisect fboxp
updateDomain z = BoxFun (dimension z) (bf_eval z)
checkBoxes [] = True
checkBoxes (box : boxes) =
if checkMaxAboveN (updateDomain f box) (updateDomain g box)
then checkBoxes boxes
else maxBoxFunGreaterThanN f' g' n initialPrecision && checkBoxes boxes
where
f' = updateDomain f box
g' = updateDomain g box
in
checkBoxes newBoxes
_ ->
trace "Domain of f not equal to domain of g"
False
where
cutoff = 1/2^10
fbox = domain f
fboxp = setPrecision initialPrecision fbox
gbox = domain g
gboxp = setPrecision initialPrecision gbox
checkMaxAboveN h i = applyMinimum h !>! n || applyMinimum i !>! n
|
84de414160823fab30b53f36d4949982c230de872a5c8867a23f2acab2b5ea14 | ucsd-progsys/liquidhaskell | Panic.hs | module GHC.Prim.Panic (module Exports) where
import "ghc-prim" GHC.Prim.Panic as Exports
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/5e9347ac719e0ca192b05ccde74617d0cbb05a85/liquid-ghc-prim/src/GHC/Prim/Panic.hs | haskell | module GHC.Prim.Panic (module Exports) where
import "ghc-prim" GHC.Prim.Panic as Exports
|
|
7f796329bf627819352bf89523dce5a927b9bd498c0bcbc69f691d8e87e59a40 | input-output-hk/cardano-sl | Ssc.hs | # LANGUAGE TypeFamilies #
| Richmen computation for SSC .
module Pos.DB.Lrc.Consumer.Ssc
(
* The ' RichmenComponent ' instance
sscRichmenComponent
-- * The consumer
, sscLrcConsumer
-- * Functions for getting richmen
, getSscRichmen
, tryGetSscRichmen
) where
import Universum
import Pos.Chain.Lrc (RichmenComponent (..), RichmenStakes)
import Pos.Chain.Update (BlockVersionData (..))
import Pos.Core (EpochIndex)
import Pos.DB (MonadDB, MonadDBRead, MonadGState)
import Pos.DB.Lrc.Consumer (LrcConsumer,
lrcConsumerFromComponentSimple)
import Pos.DB.Lrc.Context (HasLrcContext, lrcActionOnEpochReason)
import Pos.DB.Lrc.RichmenBase (getRichmen)
----------------------------------------------------------------------------
RichmenComponent
----------------------------------------------------------------------------
sscRichmenComponent :: BlockVersionData -> RichmenComponent RichmenStakes
sscRichmenComponent genesisBvd = RichmenComponent
{ rcToData = snd
, rcTag = "ssc"
, rcInitialThreshold = bvdMpcThd genesisBvd
, rcConsiderDelegated = True
}
----------------------------------------------------------------------------
-- The consumer
----------------------------------------------------------------------------
-- | Consumer will be called on every Richmen computation.
sscLrcConsumer :: (MonadGState m, MonadDB m) => BlockVersionData -> LrcConsumer m
sscLrcConsumer genesisBvd =
lrcConsumerFromComponentSimple (sscRichmenComponent genesisBvd) bvdMpcThd
----------------------------------------------------------------------------
-- Getting richmen
----------------------------------------------------------------------------
| Wait for LRC results to become available and then get the list of SSC
-- ricmen for the given epoch.
getSscRichmen
:: (MonadIO m, MonadDBRead m, MonadReader ctx m, HasLrcContext ctx)
=> BlockVersionData
-> Text -- ^ Function name (to include into error message)
-> EpochIndex -- ^ Epoch for which you want to know the richmen
-> m RichmenStakes
getSscRichmen genesisBvd fname epoch = lrcActionOnEpochReason
epoch
(fname <> ": couldn't get SSC richmen")
(tryGetSscRichmen genesisBvd)
-- | Like 'getSscRichmen', but doesn't wait and doesn't fail.
tryGetSscRichmen
:: MonadDBRead m
=> BlockVersionData
-> EpochIndex
-> m (Maybe RichmenStakes)
tryGetSscRichmen = getRichmen . sscRichmenComponent
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/db/src/Pos/DB/Lrc/Consumer/Ssc.hs | haskell | * The consumer
* Functions for getting richmen
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--------------------------------------------------------------------------
The consumer
--------------------------------------------------------------------------
| Consumer will be called on every Richmen computation.
--------------------------------------------------------------------------
Getting richmen
--------------------------------------------------------------------------
ricmen for the given epoch.
^ Function name (to include into error message)
^ Epoch for which you want to know the richmen
| Like 'getSscRichmen', but doesn't wait and doesn't fail. | # LANGUAGE TypeFamilies #
| Richmen computation for SSC .
module Pos.DB.Lrc.Consumer.Ssc
(
* The ' RichmenComponent ' instance
sscRichmenComponent
, sscLrcConsumer
, getSscRichmen
, tryGetSscRichmen
) where
import Universum
import Pos.Chain.Lrc (RichmenComponent (..), RichmenStakes)
import Pos.Chain.Update (BlockVersionData (..))
import Pos.Core (EpochIndex)
import Pos.DB (MonadDB, MonadDBRead, MonadGState)
import Pos.DB.Lrc.Consumer (LrcConsumer,
lrcConsumerFromComponentSimple)
import Pos.DB.Lrc.Context (HasLrcContext, lrcActionOnEpochReason)
import Pos.DB.Lrc.RichmenBase (getRichmen)
RichmenComponent
sscRichmenComponent :: BlockVersionData -> RichmenComponent RichmenStakes
sscRichmenComponent genesisBvd = RichmenComponent
{ rcToData = snd
, rcTag = "ssc"
, rcInitialThreshold = bvdMpcThd genesisBvd
, rcConsiderDelegated = True
}
sscLrcConsumer :: (MonadGState m, MonadDB m) => BlockVersionData -> LrcConsumer m
sscLrcConsumer genesisBvd =
lrcConsumerFromComponentSimple (sscRichmenComponent genesisBvd) bvdMpcThd
| Wait for LRC results to become available and then get the list of SSC
getSscRichmen
:: (MonadIO m, MonadDBRead m, MonadReader ctx m, HasLrcContext ctx)
=> BlockVersionData
-> m RichmenStakes
getSscRichmen genesisBvd fname epoch = lrcActionOnEpochReason
epoch
(fname <> ": couldn't get SSC richmen")
(tryGetSscRichmen genesisBvd)
tryGetSscRichmen
:: MonadDBRead m
=> BlockVersionData
-> EpochIndex
-> m (Maybe RichmenStakes)
tryGetSscRichmen = getRichmen . sscRichmenComponent
|
1038a75192ee8d85d62b438c0f43bf1924b6e51140aee5bc21927c7322120c3e | foshardware/lsc | HigherOrder.hs | Copyright 2018 - < >
SPDX - License - Identifier : GPL-3.0 - or - later
# LANGUAGE CPP #
{-# LANGUAGE BangPatterns #-}
-- | Assorted higher-order functions
--
module LSC.HigherOrder
( ifoldl'
#if !MIN_VERSION_base(4,13,0)
, foldMap'
#endif
, module Control.Applicative
, module Control.Monad
, module Data.Foldable
) where
import Control.Applicative (liftA2)
import Control.Monad (join, (<=<), when, unless)
import Data.Foldable
ifoldl' :: Foldable f => (Int -> b -> a -> b) -> b -> f a -> b
ifoldl' f y xs = foldl' (\ g x !i -> f i (g (i - 1)) x) (const y) xs (length xs - 1)
{-# INLINE ifoldl' #-}
#if !MIN_VERSION_base(4,13,0)
foldMap' :: (Foldable f, Monoid m) => (a -> m) -> f a -> m
foldMap' f = foldl' (\ acc a -> acc `mappend` f a) mempty
{-# INLINE foldMap' #-}
#endif
| null | https://raw.githubusercontent.com/foshardware/lsc/006c245a89b0a0056286205917438c7d031d04b9/src/LSC/HigherOrder.hs | haskell | # LANGUAGE BangPatterns #
| Assorted higher-order functions
# INLINE ifoldl' #
# INLINE foldMap' # | Copyright 2018 - < >
SPDX - License - Identifier : GPL-3.0 - or - later
# LANGUAGE CPP #
module LSC.HigherOrder
( ifoldl'
#if !MIN_VERSION_base(4,13,0)
, foldMap'
#endif
, module Control.Applicative
, module Control.Monad
, module Data.Foldable
) where
import Control.Applicative (liftA2)
import Control.Monad (join, (<=<), when, unless)
import Data.Foldable
ifoldl' :: Foldable f => (Int -> b -> a -> b) -> b -> f a -> b
ifoldl' f y xs = foldl' (\ g x !i -> f i (g (i - 1)) x) (const y) xs (length xs - 1)
#if !MIN_VERSION_base(4,13,0)
foldMap' :: (Foldable f, Monoid m) => (a -> m) -> f a -> m
foldMap' f = foldl' (\ acc a -> acc `mappend` f a) mempty
#endif
|
d51099f8b01528c6aecd2a089fca128fe4ae05b428815d885131455f5ded93b6 | uccmisl/dashc | adapt_algo.ml |
* dashc , client emulator for DASH video streaming
* Copyright ( c ) 2016 - 2018 , , University College Cork
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
* 02110 - 1301 , USA .
* dashc, client emulator for DASH video streaming
* Copyright (c) 2016-2018, Aleksandr Reviakin, University College Cork
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*)
open Core
open Async
open Representation
open Segm_result
(* Probe and Adapt: Rate Adaptation for HTTP Video Streaming At Scale:
*)
module Conv : sig
val next_representation_level :
representations:(int, representation) Hashtbl.t ->
results:segm_result List.t ->
int
end = struct
let moving_average = ref 0.
The main difference in TAPAS tool implementation
is conversion of the target rate to representation level ,
it also has buffer size of 60 seconds and
only the first segment is downloaded in the lowest quality .
This flag affects only conversion implementation .
The code of the TAPAS tool
could 've been found here ( ) during 08.2017 .
The default value is taps_impl = false , it was added for tests only .
is conversion of the target rate to representation level,
it also has buffer size of 60 seconds and
only the first segment is downloaded in the lowest quality.
This flag affects only conversion implementation.
The code of the TAPAS tool
could've been found here () during 08.2017.
The default value is taps_impl=false, it was added for tests only. *)
let tapas_impl = false
let next_representation_level ~representations ~results =
if List.length results < 2 then 1
else
let conv_weight = 0.85 in
let last_result = List.hd_exn results in
let throughput =
((float_of_int last_result.segment_size) *. 8. *. us_float *. us_float) /.
float_of_int (last_result.time_for_delivery) in
moving_average :=
if List.length results = 3 then throughput
else throughput *. 0.4 +. !moving_average *. 0.6;
if tapas_impl then
let level = last_result.repr_level in
let r_up = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if (data.bandwidth < int_of_float (conv_weight *. !moving_average) &&
data.bandwidth > (Hashtbl.find_exn representations acc).bandwidth) then
key else acc) in
let r_down = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if (data.bandwidth < int_of_float !moving_average &&
data.bandwidth > (Hashtbl.find_exn representations acc).bandwidth) then
key else acc) in
let new_level =
if level < r_up then r_up
else if r_up <= level && level <= r_down then level
else r_down
in
new_level
else
let next_repr = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if (data.bandwidth < int_of_float (conv_weight *. !moving_average) &&
data.bandwidth > (Hashtbl.find_exn representations acc).bandwidth) then
key else acc) in
next_repr
end
(* A Buffer-Based Approach to Rate Adaptation:
Evidence from a Large Video Streaming Service
/~nickm/papers/sigcomm2014-video.pdf
/~nickm/papers/ty-thesis.pdf *)
module BBA_0 = struct
type t = { maxb : float }
let create maxb = { maxb }
let next_representation_level ~algo ~representations ~results =
let buf_now =
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
(List.hd_exn results).representation_rate
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let reservoir = 90. in
let cushion = 126. in
let maxbuf = algo.maxb in
(* rate_prev is used for ~init below only as a start value,
there is no meaning in this particular value, but it cannot be less
than the lowest rate among representations *)
let rate_min = Hashtbl.fold representations ~init:rate_prev ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc then data.bandwidth else acc) in
let rate_max = Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc then data.bandwidth else acc) in
let f buf =
let slope = (float_of_int (rate_max -rate_min)) /.
(0.9 *. maxbuf -. reservoir) in
let target_rate = slope *. (buf -. reservoir) in
int_of_float target_rate
in
let f_buf = f buf_now in
let rate_plus =
if rate_prev = rate_max then rate_max
else (Hashtbl.find_exn representations (repr_prev + 1)).bandwidth in
let rate_minus =
if rate_prev = rate_min then rate_min
else (Hashtbl.find_exn representations (repr_prev - 1)).bandwidth in
let rate_next =
if buf_now <= reservoir then rate_min
else if buf_now >= (reservoir +. cushion) then rate_max
else if f_buf >= rate_plus then
Hashtbl.fold representations ~init:rate_min ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc &&
data.bandwidth < f_buf then data.bandwidth
else acc)
else if f_buf <= rate_minus then
Hashtbl.fold representations ~init:rate_max ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc &&
data.bandwidth > f_buf then data.bandwidth
else acc)
else rate_prev in
let repr_next = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_next then key else acc) in
repr_next
end
(* See papers from BBA_0 *)
module BBA_1 = struct
type t = {
maxb : float;
chunk_sizes_per_repr : (int, int List.t) Hashtbl.t;
average_chunk_size_per_repr : int List.t;
}
let calculate_reservoir
?(debug=false) ~algo ~representations ~results last_segment_index =
let segment_duration = ((Hashtbl.find_exn representations 1).segment_duration) in
let number_of_downloaded_segments = List.length results in
let last_window_segment =
if ((int_of_float algo.maxb) * 2) / segment_duration <
last_segment_index - number_of_downloaded_segments then
number_of_downloaded_segments + (int_of_float algo.maxb) * 2 / segment_duration
else
last_segment_index
in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 , so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000, so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let rate_min = Hashtbl.fold representations ~init:rate_prev ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc then data.bandwidth else acc) in
let average_chunk_size_per_min_rate = rate_min * segment_duration / 8 in
let rec look_ahead_for_chunk_sizes
~curr_index (large_chunks_size, small_chunks_size) =
check of equality to last_window_segment is made
because List.nth_exn counts starting from 0
because List.nth_exn counts starting from 0 *)
if curr_index = last_window_segment then (large_chunks_size, small_chunks_size)
else
curr_index because nth_exn starts to count from 0
let segm_size =
List.nth_exn (Hashtbl.find_exn algo.chunk_sizes_per_repr 1) curr_index in
(* equal chunk_sizes are included to small category *)
if average_chunk_size_per_min_rate < segm_size then
look_ahead_for_chunk_sizes
~curr_index:(curr_index + 1)
(large_chunks_size + segm_size, small_chunks_size)
else
look_ahead_for_chunk_sizes
~curr_index:(curr_index + 1)
(large_chunks_size, small_chunks_size + segm_size)
in
let large_chunks_size, small_chunks_size =
look_ahead_for_chunk_sizes ~curr_index:number_of_downloaded_segments (0, 0) in
reservoir in seconds
let reservoir = (large_chunks_size - small_chunks_size) / (rate_min / 8) in
let () =
if debug then begin
print_endline @@ "large_chunks_size: " ^ string_of_int large_chunks_size;
print_endline @@ "small_chunks_size: " ^ string_of_int small_chunks_size;
print_endline @@ "reservoir: " ^ string_of_int reservoir;
end
in
from paper : we bound the reservoir size to be between 8 and 140 seconds .
here the bound is between 2 segments and 35 segments
here the bound is between 2 segments and 35 segments *)
let reservoir_checked =
if reservoir < segment_duration * 2 then segment_duration * 2
else if reservoir > segment_duration * 35 then segment_duration * 35
else reservoir
in
reservoir_checked
(* the main difference from BBA_0 is usage of chunk map instead of rate map
and dynamic reservoir *)
let next_representation_level
?(debug=false) ~algo ~representations ~results last_segment_index =
let buf_now =
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum in
segm_number_next is next , if we agree that segment number begins from 0
let segm_number_next = List.length results in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 ,
so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000,
so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let () =
if debug then begin
print_endline @@ "rate_prev (BBA-1): " ^ string_of_int rate_prev;
print_endline @@ "repr_prev (BBA-1): " ^ string_of_int repr_prev;
end
in
let chunk_size_prev =
if (List.length results) = 0 then
List.nth_exn (Hashtbl.find_exn algo.chunk_sizes_per_repr 1) 0
else
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr repr_prev) (segm_number_next - 1)
in
(* update reservoir on each iteration *)
let reservoir =
float_of_int
(calculate_reservoir
~debug:debug ~algo:algo ~representations ~results last_segment_index) in
let maxbuf = algo.maxb in
(* rate_prev is used for ~init below only as a start value,
there is no meaning in this particular value, but it cannot be less
than the lowest rate among representations *)
let rate_min = Hashtbl.fold representations ~init:rate_prev ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc then data.bandwidth else acc) in
let rate_max = Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc then data.bandwidth else acc) in
let chunk_size_min = List.hd_exn algo.average_chunk_size_per_repr in
let chunk_size_max = List.last_exn algo.average_chunk_size_per_repr in
let rec get_chunk_sizes_per_segm_number ~curr_index ~chunk_sizes =
if curr_index > (Hashtbl.length representations) then
List.rev chunk_sizes
else
let chunk_size =
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr curr_index)
segm_number_next in
get_chunk_sizes_per_segm_number
~curr_index:(curr_index + 1)
~chunk_sizes:(chunk_size :: chunk_sizes)
in
(* chunk_sizes_per_segm_number is a list of chunk sizes
with the index as a representation number *)
let chunk_sizes_per_segm_number =
get_chunk_sizes_per_segm_number ~curr_index:1 ~chunk_sizes:[] in
let f buf =
let slope = (float_of_int (chunk_size_max - chunk_size_min)) /.
(0.9 *. maxbuf -. reservoir) in
let target_chunk_size = slope *. (buf -. reservoir) in
int_of_float target_chunk_size
in
let chunk_size_opt = f buf_now in
let () =
if debug then begin
print_endline @@ "chunk_size_opt (BBA-1): " ^ string_of_int chunk_size_opt;
end
in
let chunk_size_opt_discrete =
List.fold
chunk_sizes_per_segm_number
~init:(List.nth_exn chunk_sizes_per_segm_number 0) ~f:(fun acc x ->
let () =
if debug then begin
print_endline @@ "List.fold chunk_sizes_per_segm_number: " ^ string_of_int x;
end
in
if (x > acc) && (x < chunk_size_opt) then x
else acc
) in
let () =
if debug then begin
print_endline @@
"chunk_size_opt_discrete (BBA-1): " ^ string_of_int chunk_size_opt_discrete;
end
in
(* next highest chunk size for the next segment *)
let (chunk_size_plus, _) =
if rate_prev = rate_max then
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr repr_prev)
segm_number_next, repr_prev
else
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr (repr_prev + 1))
segm_number_next, repr_prev + 1
in
let chunk_size_minus, _ =
if rate_prev = rate_min then
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr 1) segm_number_next, repr_prev
else
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr (repr_prev - 1))
segm_number_next, repr_prev - 1
in
from ty - thesis , page 68 : the algorithm stays at the
current video rate as long as the chunk size suggested by the map
does not pass the size of
the next upcoming chunk at the next highest available video rate ( Rate + )
or the next lowest
available video rate ( Rate ) .
current video rate as long as the chunk size suggested by the map
does not pass the size of
the next upcoming chunk at the next highest available video rate (Rate + )
or the next lowest
available video rate (Rate ). *)
the returned repr_next here begins from 0 ,
but it should from 1 , so it is increased later
but it should from 1, so it is increased later *)
let _, repr_next =
the old version
if > chunk_size_plus then chunk_size_plus , repr_plus
else if < chunk_size_minus then chunk_size_minus , repr_minus
if chunk_size_opt > chunk_size_plus then chunk_size_plus,repr_plus
else if chunk_size_opt < chunk_size_minus then chunk_size_minus, repr_minus*)
if chunk_size_opt_discrete >= chunk_size_plus then
List.foldi
chunk_sizes_per_segm_number ~init:(chunk_size_plus, 0) ~f:(fun idx acc x ->
let chunk_size_curr, _ = acc in
if (x >= chunk_size_curr) && (x <= chunk_size_opt_discrete) then (x, idx)
else acc
)
else if chunk_size_opt_discrete <= chunk_size_minus then
List.foldi
chunk_sizes_per_segm_number ~init:(chunk_size_plus, 0) ~f:(fun idx acc x ->
let chunk_size_curr, _ = acc in
if (x <= chunk_size_curr) && (x <= chunk_size_opt_discrete) then (x, idx)
else acc
)
else chunk_size_prev, repr_prev - 1
in
(* repr_next *)
repr_next + 1
end
see papers from BBA_1
From sigcomm2014-video.pdf about BBA-2 .
Based on the preceding observation , BBA-2 works as fol-
lows . At time t = 0 , since the buffer is empty , BBA-2 only
picks the next highest video rate , if the ∆B increases by
more than 0.875V s. Since ∆B = V − ChunkSize / c[k ] ,
∆B > 0.875V also means that the chunk is downloaded
eight times faster than it is played . As the buffer grows , we
use the accumulated buffer to absorb the chunk size variation
and we let BBA-2 increase the video rate faster . Whereas at
the start , BBA-2 only increases the video rate if the chunk
downloads eight times faster than it is played , by the time
it fills the cushion , BBA-2 is prepared to step up the video
rate if the chunk downloads twice as fast as it is played . The
threshold decreases linearly , from the first chunk until the
cushion is full . The blue line in Figure 16 shows BBA-2
ramping up faster . BBA-2 continues to use this startup al-
gorithm until ( 1 ) the buffer is decreasing , or ( 2 ) the chunk
map suggests a higher rate . Afterwards , we use the f ( B )
defined in the BBA-1 algorithm to pick a rate .
Based on the preceding observation, BBA-2 works as fol-
lows. At time t = 0, since the buffer is empty, BBA-2 only
picks the next highest video rate, if the ∆B increases by
more than 0.875V s. Since ∆B = V − ChunkSize/c[k],
∆B > 0.875V also means that the chunk is downloaded
eight times faster than it is played. As the buffer grows, we
use the accumulated buffer to absorb the chunk size variation
and we let BBA-2 increase the video rate faster. Whereas at
the start, BBA-2 only increases the video rate if the chunk
downloads eight times faster than it is played, by the time
it fills the cushion, BBA-2 is prepared to step up the video
rate if the chunk downloads twice as fast as it is played. The
threshold decreases linearly, from the first chunk until the
cushion is full. The blue line in Figure 16 shows BBA-2
ramping up faster. BBA-2 continues to use this startup al-
gorithm until (1) the buffer is decreasing, or (2) the chunk
map suggests a higher rate. Afterwards, we use the f (B)
defined in the BBA-1 algorithm to pick a rate.
*)
module BBA_2 = struct
type t = BBA_1.t
The termination of the startup phase will happen in case of
1 ) the buffer is decreasing or 2 ) the chunk map suggests a higher rate .
After that even if cushion is not full ,
the algorithms will be in steady - state all the time .
1) the buffer is decreasing or 2) the chunk map suggests a higher rate.
After that even if cushion is not full,
the algorithms will be in steady-state all the time.*)
let startup_phase = ref true
let next_representation_level
?(debug=false) ~algo ~representations ~results last_segment_index =
let open BBA_1 in
let repr_next_bba_1 =
BBA_1.next_representation_level
~debug:debug
~algo:algo
~representations:representations
~results:results
last_segment_index in
if List.length results = 0 then
repr_next_bba_1
else
let buf_now =
(* this condition was already checked above,
but it will be checked again just in case this code maybe copy-pasted *)
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum
in
let segment_duration = ((Hashtbl.find_exn representations 1).segment_duration) in
(* time_for_delivery is stored in us *)
let prev_time_for_delivery =
float_of_int (List.hd_exn results).time_for_delivery /. (us_float *. us_float) in
(* positive delta_b means the buffer is increasing *)
let delta_b = float_of_int segment_duration -. prev_time_for_delivery in
let () =
if debug then begin
print_endline @@
"prev_time_for_delivery = " ^ string_of_float @@
float_of_int (List.hd_exn results).time_for_delivery /.
(us_float *. us_float);
print_endline @@ "delta_b = " ^ string_of_float delta_b;
end
in
BBA-2 continues to use this startup algorithm until
( 1 ) the buffer is decreasing , or ( 2 ) the chunk map suggests a higher rate .
If any of these conditions is false then switch to the steady - state forever .
(1) the buffer is decreasing, or (2) the chunk map suggests a higher rate.
If any of these conditions is false then switch to the steady-state forever. *)
if delta_b >= 0. && !startup_phase then
According to the BBA-2 paper ,
the bitrate increases only
if the chunk is downloaded 8x ( 0.875 coefficient ) faster than segment duration
and this condition linearly decreases to 2x ( 0.5 coefficient )
by the time cushion is full from the time when the first chunk was downloaded ,
so the coefficient can be calculated as a function of bitrate level .
the bitrate increases only
if the chunk is downloaded 8x (0.875 coefficient) faster than segment duration
and this condition linearly decreases to 2x (0.5 coefficient)
by the time cushion is full from the time when the first chunk was downloaded,
so the coefficient can be calculated as a function of bitrate level.*)
let f buf =
let slope =
(0.5 -. 0.875) /. (0.9 *. algo.maxb -. float_of_int segment_duration) in
let target_coefficient = 0.875 +. slope *. buf in
let () =
if debug then begin
print_endline @@
"target_coefficient = " ^ string_of_float target_coefficient;
end
in
target_coefficient
in
(* target coefficient depends on the current buffer level *)
let target_coefficient = f buf_now in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 ,
so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000,
so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let () =
if debug then begin
print_endline @@ "rate_prev (BBA-2): " ^ string_of_int rate_prev;
print_endline @@ "repr_prev (BBA-2): " ^ string_of_int repr_prev;
end
in
let rate_max = Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc then data.bandwidth else acc) in
let repr_plus =
if rate_prev = rate_max then repr_prev
else repr_prev + 1
in
(* suggessted repr depends on how fast the buffer is growing *)
let suggested_repr =
let () =
if debug then begin
print_endline @@
"target_coefficient *. (float_of_int segment_duration) = " ^
string_of_float @@ target_coefficient *. (float_of_int segment_duration);
end
in
if delta_b > target_coefficient *. (float_of_int segment_duration) then
let () =
if debug then begin
print_endline @@
"repr increase based on delta_b > target_coefficient *. \
(float_of_int segment_duration)";
end
in
repr_plus
else
repr_prev
in
if repr_next_bba_1 <= suggested_repr then
let () =
if debug then begin
print_endline @@ "suggested_repr (BBA-2): " ^ string_of_int suggested_repr;
end
in
suggested_repr
else begin
let () =
if debug then begin
print_endline @@
"repr_next_bba_1 (just switched to BBA-1): " ^
string_of_int repr_next_bba_1;
end
in
startup_phase := false;
repr_next_bba_1
end
else begin
let () =
if debug then begin
print_endline @@ "repr_next_bba_1: " ^ string_of_int repr_next_bba_1;
end
in
startup_phase := false;
repr_next_bba_1
end
end
(* ARBITER: Adaptive rate-based intelligent HTTP streaming algorithm
/ *)
module ARBITER : sig
type t = {
maxb : float;
chunk_sizes_per_repr : (int, int List.t) Hashtbl.t;
}
val next_representation_level :
?debug:bool ->
algo:t ->
representations:(int, representation) Hashtbl.t ->
results:segm_result List.t ->
int ->
int
end = struct
type t = {
maxb : float;
chunk_sizes_per_repr : (int, int List.t) Hashtbl.t;
}
let next_representation_level
?(debug=false) ~algo ~representations ~results last_segment_index =
if List.length results < 2 then 1
else
let total_number_of_downloaded_segments = List.length results in
(* estimation_window is static parameter according to the paper *)
let estimation_window = 10 in
let window_size =
if estimation_window < total_number_of_downloaded_segments then estimation_window
else total_number_of_downloaded_segments
in
let segm_number_prev = total_number_of_downloaded_segments - 1 in
(* exponential_weight is static parameter according to the paper *)
let exponential_weight = 0.4 in
let rec calculate_weights ~curr_index ~acc_weights =
if curr_index >= window_size then
List.rev acc_weights
else
let numerator =
exponential_weight *. (1. -. exponential_weight) ** float_of_int curr_index in
let denominator =
1. -. (1. -. exponential_weight) ** float_of_int estimation_window in
let () =
if debug then begin
print_endline @@ "numerator: " ^ string_of_float numerator;
print_endline @@ "denominator = " ^ string_of_float denominator;
end
in
calculate_weights
~curr_index:(curr_index + 1)
~acc_weights:(numerator /. denominator :: acc_weights)
in
let weights = calculate_weights ~curr_index:0 ~acc_weights:[] in
let rec calculate_weighted_throughput_mean ~curr_index ~acc =
if curr_index >= window_size then
acc
else
let result_ = List.nth_exn results curr_index in
let measured_throughput =
((float_of_int result_.segment_size) *. 8. *. us_float *. us_float) /.
float_of_int (result_.time_for_delivery) in
let product = (List.nth_exn weights curr_index) *. measured_throughput in
let () =
if debug then begin
print_endline @@ "segm_number_prev: " ^ string_of_int segm_number_prev;
print_endline @@ "curr_index: " ^ string_of_int curr_index;
print_endline @@
"result_.segment_number: " ^ string_of_int result_.segment_number;
print_endline @@
"(List.nth_exn weights curr_index): " ^
string_of_float (List.nth_exn weights curr_index);
print_endline @@
"measured_throughput = " ^ string_of_float measured_throughput;
end
in
calculate_weighted_throughput_mean
~curr_index:(curr_index + 1)
~acc:(acc +. product)
in
let weighted_throughput_mean =
calculate_weighted_throughput_mean ~curr_index:0 ~acc:0. in
let rec calculate_throughput_variance ~curr_index ~acc =
if curr_index >= window_size then
float_of_int estimation_window *. acc /. (float_of_int estimation_window -. 1.)
else
let result_ = List.nth_exn results curr_index in
let measured_throughput =
((float_of_int result_.segment_size) *. 8. *. us_float *. us_float) /.
float_of_int (result_.time_for_delivery) in
let () =
if debug then begin
print_endline @@
"(result_.segment_size * 8 * us * us): " ^
string_of_int (result_.segment_size * 8 * us * us);
print_endline @@
"result_.segment_size = " ^ string_of_int result_.segment_size;
print_endline @@
"result_.time_for_delivery = " ^ string_of_int result_.time_for_delivery;
print_endline @@
"measured_throughput = " ^ string_of_float measured_throughput;
end
in
let next_sum =
(List.nth_exn weights curr_index) *. ((measured_throughput -.
weighted_throughput_mean) ** 2.) in
calculate_throughput_variance
~curr_index:(curr_index + 1) ~acc:(acc +. next_sum)
in
let throughput_variance = calculate_throughput_variance ~curr_index:0 ~acc:0. in
let variation_coefficient_theta =
(sqrt throughput_variance) /.weighted_throughput_mean in
(* bw_safety_factor is static parameter according to the paper *)
let bw_safety_factor = 0.3 in
let throughput_variance_scaling_factor =
bw_safety_factor +.
(1. -. bw_safety_factor) *. ((1. -. (min variation_coefficient_theta 1.)) ** 2.)
in
let buf_now =
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum
in
lower_buffer_bound ,
upper_buffer_bound are static parameters according to the paper
upper_buffer_bound are static parameters according to the paper *)
let lower_buffer_bound, upper_buffer_bound = 0.5, 1.5 in
let buffer_based_scaling_factor =
lower_buffer_bound +.
(upper_buffer_bound -. lower_buffer_bound) *. (buf_now /. algo.maxb) in
let adaptive_throughput_estimate =
weighted_throughput_mean *.
throughput_variance_scaling_factor *.
buffer_based_scaling_factor in
let () =
if debug then begin
print_endline @@
"weighted_throughput_mean (the same unit as Del_Rate) = " ^ string_of_int @@
int_of_float @@ weighted_throughput_mean /. 1000.;
print_endline @@
"throughput_variance_scaling_factor = " ^
string_of_float throughput_variance_scaling_factor;
print_endline @@
"buffer_based_scaling_factor = " ^
string_of_float buffer_based_scaling_factor;
print_endline @@
"adaptive_throughput_estimate (the same unit as Del_Rate) = " ^
string_of_int @@ int_of_float @@ adaptive_throughput_estimate /. 1000.;
end
in
let rate_prev =
(* this should never happen *)
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 ,
so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000,
so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let () =
if debug then begin
print_endline @@ "rate_prev = " ^ string_of_int rate_prev;
end
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let () =
if debug then begin
print_endline @@ "repr_prev = " ^ string_of_int repr_prev;
end
in
let rate_min = (Hashtbl.find_exn representations 1).bandwidth in
let () =
if debug then begin
print_endline @@ "rate_min = " ^ string_of_int rate_min;
end
in
let s_rate = Hashtbl.fold representations ~init:rate_min ~f:(fun ~key:_ ~data acc ->
let () =
if debug then begin
print_endline @@ "data.bandwidth = " ^ string_of_int data.bandwidth;
end
in
if data.bandwidth > acc &&
data.bandwidth < int_of_float adaptive_throughput_estimate then
data.bandwidth
else
acc) in
let s_repr = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = s_rate then key else acc) in
let () =
if debug then begin
print_endline @@ "s_rate = " ^ string_of_int s_rate;
print_endline @@ "s_repr = " ^ string_of_int s_repr;
end
in
(* up_switch_limit is static parameter according to the paper *)
let up_switch_limit = 2 in
let next_repr =
if (s_repr - repr_prev) > up_switch_limit then
repr_prev + up_switch_limit
else
s_repr
in
(* look_ahead_window is static parameter according to the paper *)
let look_ahead_window =
if (last_segment_index - total_number_of_downloaded_segments) < 5 then
(last_segment_index - total_number_of_downloaded_segments)
else
5
in
let segment_duration = ((Hashtbl.find_exn representations 1).segment_duration) in
let rec calculate_actual_rate ~next_repr_candidate ~curr_index ~acc =
if curr_index > look_ahead_window then
acc * 8 / (look_ahead_window * segment_duration)
else
let next_segment_size =
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr next_repr_candidate)
(segm_number_prev + curr_index) in
calculate_actual_rate
~next_repr_candidate:next_repr_candidate
~curr_index:(curr_index + 1)
~acc:(acc + next_segment_size)
in
let rec highest_possible_actual_rate ~next_repr_candidate =
let actual_rate =
calculate_actual_rate
~next_repr_candidate:next_repr_candidate
~curr_index:1 ~acc:0 in
let () =
if debug then begin
print_endline @@ "actual_rate = " ^ string_of_int actual_rate;
end
in
if next_repr_candidate > 1 &&
not (actual_rate <= int_of_float adaptive_throughput_estimate) then
highest_possible_actual_rate ~next_repr_candidate:(next_repr_candidate - 1)
else
next_repr_candidate
in
let actual_next_rate =
highest_possible_actual_rate ~next_repr_candidate:next_repr in
actual_next_rate
end
type alg =
| Conv
| BBA_0 of BBA_0.t
| BBA_1 of BBA_1.t
| BBA_2 of BBA_1.t
| ARBITER of ARBITER.t
| null | https://raw.githubusercontent.com/uccmisl/dashc/8a97ceb2bdf6a74bde410be9a1d1432d5e11445a/src/adapt_algo.ml | ocaml | Probe and Adapt: Rate Adaptation for HTTP Video Streaming At Scale:
A Buffer-Based Approach to Rate Adaptation:
Evidence from a Large Video Streaming Service
/~nickm/papers/sigcomm2014-video.pdf
/~nickm/papers/ty-thesis.pdf
rate_prev is used for ~init below only as a start value,
there is no meaning in this particular value, but it cannot be less
than the lowest rate among representations
See papers from BBA_0
equal chunk_sizes are included to small category
the main difference from BBA_0 is usage of chunk map instead of rate map
and dynamic reservoir
update reservoir on each iteration
rate_prev is used for ~init below only as a start value,
there is no meaning in this particular value, but it cannot be less
than the lowest rate among representations
chunk_sizes_per_segm_number is a list of chunk sizes
with the index as a representation number
next highest chunk size for the next segment
repr_next
this condition was already checked above,
but it will be checked again just in case this code maybe copy-pasted
time_for_delivery is stored in us
positive delta_b means the buffer is increasing
target coefficient depends on the current buffer level
suggessted repr depends on how fast the buffer is growing
ARBITER: Adaptive rate-based intelligent HTTP streaming algorithm
/
estimation_window is static parameter according to the paper
exponential_weight is static parameter according to the paper
bw_safety_factor is static parameter according to the paper
this should never happen
up_switch_limit is static parameter according to the paper
look_ahead_window is static parameter according to the paper |
* dashc , client emulator for DASH video streaming
* Copyright ( c ) 2016 - 2018 , , University College Cork
*
* This program is free software ; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation ; either version 2
* of the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA
* 02110 - 1301 , USA .
* dashc, client emulator for DASH video streaming
* Copyright (c) 2016-2018, Aleksandr Reviakin, University College Cork
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*)
open Core
open Async
open Representation
open Segm_result
module Conv : sig
val next_representation_level :
representations:(int, representation) Hashtbl.t ->
results:segm_result List.t ->
int
end = struct
let moving_average = ref 0.
The main difference in TAPAS tool implementation
is conversion of the target rate to representation level ,
it also has buffer size of 60 seconds and
only the first segment is downloaded in the lowest quality .
This flag affects only conversion implementation .
The code of the TAPAS tool
could 've been found here ( ) during 08.2017 .
The default value is taps_impl = false , it was added for tests only .
is conversion of the target rate to representation level,
it also has buffer size of 60 seconds and
only the first segment is downloaded in the lowest quality.
This flag affects only conversion implementation.
The code of the TAPAS tool
could've been found here () during 08.2017.
The default value is taps_impl=false, it was added for tests only. *)
let tapas_impl = false
let next_representation_level ~representations ~results =
if List.length results < 2 then 1
else
let conv_weight = 0.85 in
let last_result = List.hd_exn results in
let throughput =
((float_of_int last_result.segment_size) *. 8. *. us_float *. us_float) /.
float_of_int (last_result.time_for_delivery) in
moving_average :=
if List.length results = 3 then throughput
else throughput *. 0.4 +. !moving_average *. 0.6;
if tapas_impl then
let level = last_result.repr_level in
let r_up = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if (data.bandwidth < int_of_float (conv_weight *. !moving_average) &&
data.bandwidth > (Hashtbl.find_exn representations acc).bandwidth) then
key else acc) in
let r_down = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if (data.bandwidth < int_of_float !moving_average &&
data.bandwidth > (Hashtbl.find_exn representations acc).bandwidth) then
key else acc) in
let new_level =
if level < r_up then r_up
else if r_up <= level && level <= r_down then level
else r_down
in
new_level
else
let next_repr = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if (data.bandwidth < int_of_float (conv_weight *. !moving_average) &&
data.bandwidth > (Hashtbl.find_exn representations acc).bandwidth) then
key else acc) in
next_repr
end
module BBA_0 = struct
type t = { maxb : float }
let create maxb = { maxb }
let next_representation_level ~algo ~representations ~results =
let buf_now =
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
(List.hd_exn results).representation_rate
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let reservoir = 90. in
let cushion = 126. in
let maxbuf = algo.maxb in
let rate_min = Hashtbl.fold representations ~init:rate_prev ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc then data.bandwidth else acc) in
let rate_max = Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc then data.bandwidth else acc) in
let f buf =
let slope = (float_of_int (rate_max -rate_min)) /.
(0.9 *. maxbuf -. reservoir) in
let target_rate = slope *. (buf -. reservoir) in
int_of_float target_rate
in
let f_buf = f buf_now in
let rate_plus =
if rate_prev = rate_max then rate_max
else (Hashtbl.find_exn representations (repr_prev + 1)).bandwidth in
let rate_minus =
if rate_prev = rate_min then rate_min
else (Hashtbl.find_exn representations (repr_prev - 1)).bandwidth in
let rate_next =
if buf_now <= reservoir then rate_min
else if buf_now >= (reservoir +. cushion) then rate_max
else if f_buf >= rate_plus then
Hashtbl.fold representations ~init:rate_min ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc &&
data.bandwidth < f_buf then data.bandwidth
else acc)
else if f_buf <= rate_minus then
Hashtbl.fold representations ~init:rate_max ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc &&
data.bandwidth > f_buf then data.bandwidth
else acc)
else rate_prev in
let repr_next = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_next then key else acc) in
repr_next
end
module BBA_1 = struct
type t = {
maxb : float;
chunk_sizes_per_repr : (int, int List.t) Hashtbl.t;
average_chunk_size_per_repr : int List.t;
}
let calculate_reservoir
?(debug=false) ~algo ~representations ~results last_segment_index =
let segment_duration = ((Hashtbl.find_exn representations 1).segment_duration) in
let number_of_downloaded_segments = List.length results in
let last_window_segment =
if ((int_of_float algo.maxb) * 2) / segment_duration <
last_segment_index - number_of_downloaded_segments then
number_of_downloaded_segments + (int_of_float algo.maxb) * 2 / segment_duration
else
last_segment_index
in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 , so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000, so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let rate_min = Hashtbl.fold representations ~init:rate_prev ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc then data.bandwidth else acc) in
let average_chunk_size_per_min_rate = rate_min * segment_duration / 8 in
let rec look_ahead_for_chunk_sizes
~curr_index (large_chunks_size, small_chunks_size) =
check of equality to last_window_segment is made
because List.nth_exn counts starting from 0
because List.nth_exn counts starting from 0 *)
if curr_index = last_window_segment then (large_chunks_size, small_chunks_size)
else
curr_index because nth_exn starts to count from 0
let segm_size =
List.nth_exn (Hashtbl.find_exn algo.chunk_sizes_per_repr 1) curr_index in
if average_chunk_size_per_min_rate < segm_size then
look_ahead_for_chunk_sizes
~curr_index:(curr_index + 1)
(large_chunks_size + segm_size, small_chunks_size)
else
look_ahead_for_chunk_sizes
~curr_index:(curr_index + 1)
(large_chunks_size, small_chunks_size + segm_size)
in
let large_chunks_size, small_chunks_size =
look_ahead_for_chunk_sizes ~curr_index:number_of_downloaded_segments (0, 0) in
reservoir in seconds
let reservoir = (large_chunks_size - small_chunks_size) / (rate_min / 8) in
let () =
if debug then begin
print_endline @@ "large_chunks_size: " ^ string_of_int large_chunks_size;
print_endline @@ "small_chunks_size: " ^ string_of_int small_chunks_size;
print_endline @@ "reservoir: " ^ string_of_int reservoir;
end
in
from paper : we bound the reservoir size to be between 8 and 140 seconds .
here the bound is between 2 segments and 35 segments
here the bound is between 2 segments and 35 segments *)
let reservoir_checked =
if reservoir < segment_duration * 2 then segment_duration * 2
else if reservoir > segment_duration * 35 then segment_duration * 35
else reservoir
in
reservoir_checked
let next_representation_level
?(debug=false) ~algo ~representations ~results last_segment_index =
let buf_now =
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum in
segm_number_next is next , if we agree that segment number begins from 0
let segm_number_next = List.length results in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 ,
so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000,
so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let () =
if debug then begin
print_endline @@ "rate_prev (BBA-1): " ^ string_of_int rate_prev;
print_endline @@ "repr_prev (BBA-1): " ^ string_of_int repr_prev;
end
in
let chunk_size_prev =
if (List.length results) = 0 then
List.nth_exn (Hashtbl.find_exn algo.chunk_sizes_per_repr 1) 0
else
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr repr_prev) (segm_number_next - 1)
in
let reservoir =
float_of_int
(calculate_reservoir
~debug:debug ~algo:algo ~representations ~results last_segment_index) in
let maxbuf = algo.maxb in
let rate_min = Hashtbl.fold representations ~init:rate_prev ~f:(fun ~key:_ ~data acc ->
if data.bandwidth < acc then data.bandwidth else acc) in
let rate_max = Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc then data.bandwidth else acc) in
let chunk_size_min = List.hd_exn algo.average_chunk_size_per_repr in
let chunk_size_max = List.last_exn algo.average_chunk_size_per_repr in
let rec get_chunk_sizes_per_segm_number ~curr_index ~chunk_sizes =
if curr_index > (Hashtbl.length representations) then
List.rev chunk_sizes
else
let chunk_size =
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr curr_index)
segm_number_next in
get_chunk_sizes_per_segm_number
~curr_index:(curr_index + 1)
~chunk_sizes:(chunk_size :: chunk_sizes)
in
let chunk_sizes_per_segm_number =
get_chunk_sizes_per_segm_number ~curr_index:1 ~chunk_sizes:[] in
let f buf =
let slope = (float_of_int (chunk_size_max - chunk_size_min)) /.
(0.9 *. maxbuf -. reservoir) in
let target_chunk_size = slope *. (buf -. reservoir) in
int_of_float target_chunk_size
in
let chunk_size_opt = f buf_now in
let () =
if debug then begin
print_endline @@ "chunk_size_opt (BBA-1): " ^ string_of_int chunk_size_opt;
end
in
let chunk_size_opt_discrete =
List.fold
chunk_sizes_per_segm_number
~init:(List.nth_exn chunk_sizes_per_segm_number 0) ~f:(fun acc x ->
let () =
if debug then begin
print_endline @@ "List.fold chunk_sizes_per_segm_number: " ^ string_of_int x;
end
in
if (x > acc) && (x < chunk_size_opt) then x
else acc
) in
let () =
if debug then begin
print_endline @@
"chunk_size_opt_discrete (BBA-1): " ^ string_of_int chunk_size_opt_discrete;
end
in
let (chunk_size_plus, _) =
if rate_prev = rate_max then
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr repr_prev)
segm_number_next, repr_prev
else
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr (repr_prev + 1))
segm_number_next, repr_prev + 1
in
let chunk_size_minus, _ =
if rate_prev = rate_min then
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr 1) segm_number_next, repr_prev
else
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr (repr_prev - 1))
segm_number_next, repr_prev - 1
in
from ty - thesis , page 68 : the algorithm stays at the
current video rate as long as the chunk size suggested by the map
does not pass the size of
the next upcoming chunk at the next highest available video rate ( Rate + )
or the next lowest
available video rate ( Rate ) .
current video rate as long as the chunk size suggested by the map
does not pass the size of
the next upcoming chunk at the next highest available video rate (Rate + )
or the next lowest
available video rate (Rate ). *)
the returned repr_next here begins from 0 ,
but it should from 1 , so it is increased later
but it should from 1, so it is increased later *)
let _, repr_next =
the old version
if > chunk_size_plus then chunk_size_plus , repr_plus
else if < chunk_size_minus then chunk_size_minus , repr_minus
if chunk_size_opt > chunk_size_plus then chunk_size_plus,repr_plus
else if chunk_size_opt < chunk_size_minus then chunk_size_minus, repr_minus*)
if chunk_size_opt_discrete >= chunk_size_plus then
List.foldi
chunk_sizes_per_segm_number ~init:(chunk_size_plus, 0) ~f:(fun idx acc x ->
let chunk_size_curr, _ = acc in
if (x >= chunk_size_curr) && (x <= chunk_size_opt_discrete) then (x, idx)
else acc
)
else if chunk_size_opt_discrete <= chunk_size_minus then
List.foldi
chunk_sizes_per_segm_number ~init:(chunk_size_plus, 0) ~f:(fun idx acc x ->
let chunk_size_curr, _ = acc in
if (x <= chunk_size_curr) && (x <= chunk_size_opt_discrete) then (x, idx)
else acc
)
else chunk_size_prev, repr_prev - 1
in
repr_next + 1
end
see papers from BBA_1
From sigcomm2014-video.pdf about BBA-2 .
Based on the preceding observation , BBA-2 works as fol-
lows . At time t = 0 , since the buffer is empty , BBA-2 only
picks the next highest video rate , if the ∆B increases by
more than 0.875V s. Since ∆B = V − ChunkSize / c[k ] ,
∆B > 0.875V also means that the chunk is downloaded
eight times faster than it is played . As the buffer grows , we
use the accumulated buffer to absorb the chunk size variation
and we let BBA-2 increase the video rate faster . Whereas at
the start , BBA-2 only increases the video rate if the chunk
downloads eight times faster than it is played , by the time
it fills the cushion , BBA-2 is prepared to step up the video
rate if the chunk downloads twice as fast as it is played . The
threshold decreases linearly , from the first chunk until the
cushion is full . The blue line in Figure 16 shows BBA-2
ramping up faster . BBA-2 continues to use this startup al-
gorithm until ( 1 ) the buffer is decreasing , or ( 2 ) the chunk
map suggests a higher rate . Afterwards , we use the f ( B )
defined in the BBA-1 algorithm to pick a rate .
Based on the preceding observation, BBA-2 works as fol-
lows. At time t = 0, since the buffer is empty, BBA-2 only
picks the next highest video rate, if the ∆B increases by
more than 0.875V s. Since ∆B = V − ChunkSize/c[k],
∆B > 0.875V also means that the chunk is downloaded
eight times faster than it is played. As the buffer grows, we
use the accumulated buffer to absorb the chunk size variation
and we let BBA-2 increase the video rate faster. Whereas at
the start, BBA-2 only increases the video rate if the chunk
downloads eight times faster than it is played, by the time
it fills the cushion, BBA-2 is prepared to step up the video
rate if the chunk downloads twice as fast as it is played. The
threshold decreases linearly, from the first chunk until the
cushion is full. The blue line in Figure 16 shows BBA-2
ramping up faster. BBA-2 continues to use this startup al-
gorithm until (1) the buffer is decreasing, or (2) the chunk
map suggests a higher rate. Afterwards, we use the f (B)
defined in the BBA-1 algorithm to pick a rate.
*)
module BBA_2 = struct
type t = BBA_1.t
The termination of the startup phase will happen in case of
1 ) the buffer is decreasing or 2 ) the chunk map suggests a higher rate .
After that even if cushion is not full ,
the algorithms will be in steady - state all the time .
1) the buffer is decreasing or 2) the chunk map suggests a higher rate.
After that even if cushion is not full,
the algorithms will be in steady-state all the time.*)
let startup_phase = ref true
let next_representation_level
?(debug=false) ~algo ~representations ~results last_segment_index =
let open BBA_1 in
let repr_next_bba_1 =
BBA_1.next_representation_level
~debug:debug
~algo:algo
~representations:representations
~results:results
last_segment_index in
if List.length results = 0 then
repr_next_bba_1
else
let buf_now =
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum
in
let segment_duration = ((Hashtbl.find_exn representations 1).segment_duration) in
let prev_time_for_delivery =
float_of_int (List.hd_exn results).time_for_delivery /. (us_float *. us_float) in
let delta_b = float_of_int segment_duration -. prev_time_for_delivery in
let () =
if debug then begin
print_endline @@
"prev_time_for_delivery = " ^ string_of_float @@
float_of_int (List.hd_exn results).time_for_delivery /.
(us_float *. us_float);
print_endline @@ "delta_b = " ^ string_of_float delta_b;
end
in
BBA-2 continues to use this startup algorithm until
( 1 ) the buffer is decreasing , or ( 2 ) the chunk map suggests a higher rate .
If any of these conditions is false then switch to the steady - state forever .
(1) the buffer is decreasing, or (2) the chunk map suggests a higher rate.
If any of these conditions is false then switch to the steady-state forever. *)
if delta_b >= 0. && !startup_phase then
According to the BBA-2 paper ,
the bitrate increases only
if the chunk is downloaded 8x ( 0.875 coefficient ) faster than segment duration
and this condition linearly decreases to 2x ( 0.5 coefficient )
by the time cushion is full from the time when the first chunk was downloaded ,
so the coefficient can be calculated as a function of bitrate level .
the bitrate increases only
if the chunk is downloaded 8x (0.875 coefficient) faster than segment duration
and this condition linearly decreases to 2x (0.5 coefficient)
by the time cushion is full from the time when the first chunk was downloaded,
so the coefficient can be calculated as a function of bitrate level.*)
let f buf =
let slope =
(0.5 -. 0.875) /. (0.9 *. algo.maxb -. float_of_int segment_duration) in
let target_coefficient = 0.875 +. slope *. buf in
let () =
if debug then begin
print_endline @@
"target_coefficient = " ^ string_of_float target_coefficient;
end
in
target_coefficient
in
let target_coefficient = f buf_now in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 ,
so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000,
so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let () =
if debug then begin
print_endline @@ "rate_prev (BBA-2): " ^ string_of_int rate_prev;
print_endline @@ "repr_prev (BBA-2): " ^ string_of_int repr_prev;
end
in
let rate_max = Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if data.bandwidth > acc then data.bandwidth else acc) in
let repr_plus =
if rate_prev = rate_max then repr_prev
else repr_prev + 1
in
let suggested_repr =
let () =
if debug then begin
print_endline @@
"target_coefficient *. (float_of_int segment_duration) = " ^
string_of_float @@ target_coefficient *. (float_of_int segment_duration);
end
in
if delta_b > target_coefficient *. (float_of_int segment_duration) then
let () =
if debug then begin
print_endline @@
"repr increase based on delta_b > target_coefficient *. \
(float_of_int segment_duration)";
end
in
repr_plus
else
repr_prev
in
if repr_next_bba_1 <= suggested_repr then
let () =
if debug then begin
print_endline @@ "suggested_repr (BBA-2): " ^ string_of_int suggested_repr;
end
in
suggested_repr
else begin
let () =
if debug then begin
print_endline @@
"repr_next_bba_1 (just switched to BBA-1): " ^
string_of_int repr_next_bba_1;
end
in
startup_phase := false;
repr_next_bba_1
end
else begin
let () =
if debug then begin
print_endline @@ "repr_next_bba_1: " ^ string_of_int repr_next_bba_1;
end
in
startup_phase := false;
repr_next_bba_1
end
end
module ARBITER : sig
type t = {
maxb : float;
chunk_sizes_per_repr : (int, int List.t) Hashtbl.t;
}
val next_representation_level :
?debug:bool ->
algo:t ->
representations:(int, representation) Hashtbl.t ->
results:segm_result List.t ->
int ->
int
end = struct
type t = {
maxb : float;
chunk_sizes_per_repr : (int, int List.t) Hashtbl.t;
}
let next_representation_level
?(debug=false) ~algo ~representations ~results last_segment_index =
if List.length results < 2 then 1
else
let total_number_of_downloaded_segments = List.length results in
let estimation_window = 10 in
let window_size =
if estimation_window < total_number_of_downloaded_segments then estimation_window
else total_number_of_downloaded_segments
in
let segm_number_prev = total_number_of_downloaded_segments - 1 in
let exponential_weight = 0.4 in
let rec calculate_weights ~curr_index ~acc_weights =
if curr_index >= window_size then
List.rev acc_weights
else
let numerator =
exponential_weight *. (1. -. exponential_weight) ** float_of_int curr_index in
let denominator =
1. -. (1. -. exponential_weight) ** float_of_int estimation_window in
let () =
if debug then begin
print_endline @@ "numerator: " ^ string_of_float numerator;
print_endline @@ "denominator = " ^ string_of_float denominator;
end
in
calculate_weights
~curr_index:(curr_index + 1)
~acc_weights:(numerator /. denominator :: acc_weights)
in
let weights = calculate_weights ~curr_index:0 ~acc_weights:[] in
let rec calculate_weighted_throughput_mean ~curr_index ~acc =
if curr_index >= window_size then
acc
else
let result_ = List.nth_exn results curr_index in
let measured_throughput =
((float_of_int result_.segment_size) *. 8. *. us_float *. us_float) /.
float_of_int (result_.time_for_delivery) in
let product = (List.nth_exn weights curr_index) *. measured_throughput in
let () =
if debug then begin
print_endline @@ "segm_number_prev: " ^ string_of_int segm_number_prev;
print_endline @@ "curr_index: " ^ string_of_int curr_index;
print_endline @@
"result_.segment_number: " ^ string_of_int result_.segment_number;
print_endline @@
"(List.nth_exn weights curr_index): " ^
string_of_float (List.nth_exn weights curr_index);
print_endline @@
"measured_throughput = " ^ string_of_float measured_throughput;
end
in
calculate_weighted_throughput_mean
~curr_index:(curr_index + 1)
~acc:(acc +. product)
in
let weighted_throughput_mean =
calculate_weighted_throughput_mean ~curr_index:0 ~acc:0. in
let rec calculate_throughput_variance ~curr_index ~acc =
if curr_index >= window_size then
float_of_int estimation_window *. acc /. (float_of_int estimation_window -. 1.)
else
let result_ = List.nth_exn results curr_index in
let measured_throughput =
((float_of_int result_.segment_size) *. 8. *. us_float *. us_float) /.
float_of_int (result_.time_for_delivery) in
let () =
if debug then begin
print_endline @@
"(result_.segment_size * 8 * us * us): " ^
string_of_int (result_.segment_size * 8 * us * us);
print_endline @@
"result_.segment_size = " ^ string_of_int result_.segment_size;
print_endline @@
"result_.time_for_delivery = " ^ string_of_int result_.time_for_delivery;
print_endline @@
"measured_throughput = " ^ string_of_float measured_throughput;
end
in
let next_sum =
(List.nth_exn weights curr_index) *. ((measured_throughput -.
weighted_throughput_mean) ** 2.) in
calculate_throughput_variance
~curr_index:(curr_index + 1) ~acc:(acc +. next_sum)
in
let throughput_variance = calculate_throughput_variance ~curr_index:0 ~acc:0. in
let variation_coefficient_theta =
(sqrt throughput_variance) /.weighted_throughput_mean in
let bw_safety_factor = 0.3 in
let throughput_variance_scaling_factor =
bw_safety_factor +.
(1. -. bw_safety_factor) *. ((1. -. (min variation_coefficient_theta 1.)) ** 2.)
in
let buf_now =
if (List.length results) = 0 then 0.
else (List.hd_exn results).buffer_level_in_momentum
in
lower_buffer_bound ,
upper_buffer_bound are static parameters according to the paper
upper_buffer_bound are static parameters according to the paper *)
let lower_buffer_bound, upper_buffer_bound = 0.5, 1.5 in
let buffer_based_scaling_factor =
lower_buffer_bound +.
(upper_buffer_bound -. lower_buffer_bound) *. (buf_now /. algo.maxb) in
let adaptive_throughput_estimate =
weighted_throughput_mean *.
throughput_variance_scaling_factor *.
buffer_based_scaling_factor in
let () =
if debug then begin
print_endline @@
"weighted_throughput_mean (the same unit as Del_Rate) = " ^ string_of_int @@
int_of_float @@ weighted_throughput_mean /. 1000.;
print_endline @@
"throughput_variance_scaling_factor = " ^
string_of_float throughput_variance_scaling_factor;
print_endline @@
"buffer_based_scaling_factor = " ^
string_of_float buffer_based_scaling_factor;
print_endline @@
"adaptive_throughput_estimate (the same unit as Del_Rate) = " ^
string_of_int @@ int_of_float @@ adaptive_throughput_estimate /. 1000.;
end
in
let rate_prev =
if (List.length results) = 0 then (Hashtbl.find_exn representations 1).bandwidth
else
when the representation rate is saved in a trace file ,
some level of precision will be lost ,
because original value of bit / s will be saved in kbit / s int type value ,
for example , 232385 will be saved as 232 , and when it is read in debug mode
it will look like 232000 ,
so the repr_prev will be chosen based on a wrong value .
To fix it this value 232000 ( for example ) will be converted into the closest
within 5 % the representation rate from the representations hash table
some level of precision will be lost,
because original value of bit/s will be saved in kbit/s int type value,
for example, 232385 will be saved as 232, and when it is read in debug mode
it will look like 232000,
so the repr_prev will be chosen based on a wrong value.
To fix it this value 232000 (for example) will be converted into the closest
within 5% the representation rate from the representations hash table *)
if debug then Hashtbl.fold representations ~init:1 ~f:(fun ~key:_ ~data acc ->
if (float_of_int data.bandwidth *. 0.95) <
float_of_int (List.hd_exn results).representation_rate &&
(float_of_int data.bandwidth *. 1.05) >
float_of_int (List.hd_exn results).representation_rate
then data.bandwidth
else acc
)
else (List.hd_exn results).representation_rate
in
let () =
if debug then begin
print_endline @@ "rate_prev = " ^ string_of_int rate_prev;
end
in
let repr_prev = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = rate_prev then key
else acc
) in
let () =
if debug then begin
print_endline @@ "repr_prev = " ^ string_of_int repr_prev;
end
in
let rate_min = (Hashtbl.find_exn representations 1).bandwidth in
let () =
if debug then begin
print_endline @@ "rate_min = " ^ string_of_int rate_min;
end
in
let s_rate = Hashtbl.fold representations ~init:rate_min ~f:(fun ~key:_ ~data acc ->
let () =
if debug then begin
print_endline @@ "data.bandwidth = " ^ string_of_int data.bandwidth;
end
in
if data.bandwidth > acc &&
data.bandwidth < int_of_float adaptive_throughput_estimate then
data.bandwidth
else
acc) in
let s_repr = Hashtbl.fold representations ~init:1 ~f:(fun ~key ~data acc ->
if data.bandwidth = s_rate then key else acc) in
let () =
if debug then begin
print_endline @@ "s_rate = " ^ string_of_int s_rate;
print_endline @@ "s_repr = " ^ string_of_int s_repr;
end
in
let up_switch_limit = 2 in
let next_repr =
if (s_repr - repr_prev) > up_switch_limit then
repr_prev + up_switch_limit
else
s_repr
in
let look_ahead_window =
if (last_segment_index - total_number_of_downloaded_segments) < 5 then
(last_segment_index - total_number_of_downloaded_segments)
else
5
in
let segment_duration = ((Hashtbl.find_exn representations 1).segment_duration) in
let rec calculate_actual_rate ~next_repr_candidate ~curr_index ~acc =
if curr_index > look_ahead_window then
acc * 8 / (look_ahead_window * segment_duration)
else
let next_segment_size =
List.nth_exn
(Hashtbl.find_exn algo.chunk_sizes_per_repr next_repr_candidate)
(segm_number_prev + curr_index) in
calculate_actual_rate
~next_repr_candidate:next_repr_candidate
~curr_index:(curr_index + 1)
~acc:(acc + next_segment_size)
in
let rec highest_possible_actual_rate ~next_repr_candidate =
let actual_rate =
calculate_actual_rate
~next_repr_candidate:next_repr_candidate
~curr_index:1 ~acc:0 in
let () =
if debug then begin
print_endline @@ "actual_rate = " ^ string_of_int actual_rate;
end
in
if next_repr_candidate > 1 &&
not (actual_rate <= int_of_float adaptive_throughput_estimate) then
highest_possible_actual_rate ~next_repr_candidate:(next_repr_candidate - 1)
else
next_repr_candidate
in
let actual_next_rate =
highest_possible_actual_rate ~next_repr_candidate:next_repr in
actual_next_rate
end
type alg =
| Conv
| BBA_0 of BBA_0.t
| BBA_1 of BBA_1.t
| BBA_2 of BBA_1.t
| ARBITER of ARBITER.t
|
bf8ef314f8fa657940fa57d5d8ae5f7b06fe487765c7ded77a7afbab80a64b14 | tfausak/monadoc-5 | Main.hs | module Monadoc.Main where
import qualified Control.Concurrent.Async as Async
import qualified Control.Monad as Monad
import qualified Control.Monad.Catch as Exception
import qualified Control.Monad.Trans.Class as Trans
import qualified Control.Monad.Trans.Reader as Reader
import qualified Database.SQLite.Simple as Sql
import qualified Monadoc.Data.Migrations as Migrations
import Monadoc.Prelude
import qualified Monadoc.Server.Main as Server
import qualified Monadoc.Type.App as App
import qualified Monadoc.Type.Config as Config
import qualified Monadoc.Type.Context as Context
import qualified Monadoc.Type.Migration as Migration
import qualified Monadoc.Type.MigrationMismatch as MigrationMismatch
import qualified Monadoc.Type.Service as Service
import qualified Monadoc.Type.Sha256 as Sha256
import qualified Monadoc.Type.Timestamp as Timestamp
import qualified Monadoc.Type.WithCallStack as WithCallStack
import qualified Monadoc.Utility.Console as Console
import qualified Monadoc.Utility.Time as Time
import qualified Monadoc.Worker.Main as Worker
run :: App.App request ()
run = do
runMigrations
context <- Reader.ask
Trans.lift
<<< Async.mapConcurrently_ (App.run context <<< runService)
<<< Config.services
<| Context.config context
runService :: Service.Service -> App.App request ()
runService service = case service of
Service.Server -> Server.run
Service.Worker -> Worker.run
runMigrations :: App.App request ()
runMigrations = do
Console.info "Running migrations ..."
App.sql_ "pragma journal_mode = wal" ()
App.sql_
"create table if not exists migrations (\
\iso8601 text not null primary key, \
\sha256 text not null)"
()
traverse_ ensureMigration Migrations.migrations
ensureMigration :: Migration.Migration -> App.App request ()
ensureMigration migration = do
maybeDigest <- getDigest <| Migration.timestamp migration
case maybeDigest of
Nothing -> runMigration migration
Just digest -> checkDigest migration digest
getDigest :: Timestamp.Timestamp -> App.App request (Maybe Sha256.Sha256)
getDigest timestamp = do
rows <- App.sql "select sha256 from migrations where iso8601 = ?" [timestamp]
pure <| case rows of
[] -> Nothing
Sql.Only sha256 : _ -> Just sha256
runMigration :: Migration.Migration -> App.App request ()
runMigration migration = do
Console.info <| unwords
[ "Running migration"
, Time.format "%Y-%m-%dT%H:%M:%S%3QZ"
<<< Timestamp.toUtcTime
<| Migration.timestamp migration
, "..."
]
App.sql_ (Migration.query migration) ()
App.sql_ "insert into migrations (iso8601, sha256) values (?, ?)" migration
checkDigest
:: Exception.MonadThrow m => Migration.Migration -> Sha256.Sha256 -> m ()
checkDigest migration expectedSha256 = do
let actualSha256 = Migration.sha256 migration
Monad.when (actualSha256 /= expectedSha256) <| WithCallStack.throw
MigrationMismatch.MigrationMismatch
{ MigrationMismatch.actual = actualSha256
, MigrationMismatch.expected = expectedSha256
, MigrationMismatch.timestamp = Migration.timestamp migration
}
| null | https://raw.githubusercontent.com/tfausak/monadoc-5/5361dd1870072cf2771857adbe92658118ddaa27/src/lib/Monadoc/Main.hs | haskell | module Monadoc.Main where
import qualified Control.Concurrent.Async as Async
import qualified Control.Monad as Monad
import qualified Control.Monad.Catch as Exception
import qualified Control.Monad.Trans.Class as Trans
import qualified Control.Monad.Trans.Reader as Reader
import qualified Database.SQLite.Simple as Sql
import qualified Monadoc.Data.Migrations as Migrations
import Monadoc.Prelude
import qualified Monadoc.Server.Main as Server
import qualified Monadoc.Type.App as App
import qualified Monadoc.Type.Config as Config
import qualified Monadoc.Type.Context as Context
import qualified Monadoc.Type.Migration as Migration
import qualified Monadoc.Type.MigrationMismatch as MigrationMismatch
import qualified Monadoc.Type.Service as Service
import qualified Monadoc.Type.Sha256 as Sha256
import qualified Monadoc.Type.Timestamp as Timestamp
import qualified Monadoc.Type.WithCallStack as WithCallStack
import qualified Monadoc.Utility.Console as Console
import qualified Monadoc.Utility.Time as Time
import qualified Monadoc.Worker.Main as Worker
run :: App.App request ()
run = do
runMigrations
context <- Reader.ask
Trans.lift
<<< Async.mapConcurrently_ (App.run context <<< runService)
<<< Config.services
<| Context.config context
runService :: Service.Service -> App.App request ()
runService service = case service of
Service.Server -> Server.run
Service.Worker -> Worker.run
runMigrations :: App.App request ()
runMigrations = do
Console.info "Running migrations ..."
App.sql_ "pragma journal_mode = wal" ()
App.sql_
"create table if not exists migrations (\
\iso8601 text not null primary key, \
\sha256 text not null)"
()
traverse_ ensureMigration Migrations.migrations
ensureMigration :: Migration.Migration -> App.App request ()
ensureMigration migration = do
maybeDigest <- getDigest <| Migration.timestamp migration
case maybeDigest of
Nothing -> runMigration migration
Just digest -> checkDigest migration digest
getDigest :: Timestamp.Timestamp -> App.App request (Maybe Sha256.Sha256)
getDigest timestamp = do
rows <- App.sql "select sha256 from migrations where iso8601 = ?" [timestamp]
pure <| case rows of
[] -> Nothing
Sql.Only sha256 : _ -> Just sha256
runMigration :: Migration.Migration -> App.App request ()
runMigration migration = do
Console.info <| unwords
[ "Running migration"
, Time.format "%Y-%m-%dT%H:%M:%S%3QZ"
<<< Timestamp.toUtcTime
<| Migration.timestamp migration
, "..."
]
App.sql_ (Migration.query migration) ()
App.sql_ "insert into migrations (iso8601, sha256) values (?, ?)" migration
checkDigest
:: Exception.MonadThrow m => Migration.Migration -> Sha256.Sha256 -> m ()
checkDigest migration expectedSha256 = do
let actualSha256 = Migration.sha256 migration
Monad.when (actualSha256 /= expectedSha256) <| WithCallStack.throw
MigrationMismatch.MigrationMismatch
{ MigrationMismatch.actual = actualSha256
, MigrationMismatch.expected = expectedSha256
, MigrationMismatch.timestamp = Migration.timestamp migration
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.