_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
|
---|---|---|---|---|---|---|---|---|
8170d0912c77aa75a9fffc78de0d640c2ecff6fdcfb11eb4ceab73d2191025da | yav/haskell-lexer | Lexer.hs | module Language.Haskell.Lexer
( PosToken
, Token(..)
, lexerPass0
, lexerPass0'
, lexerPass1
, rmSpace
, layoutPre
, module Language.Haskell.Lexer.Position
) where
import Language.Haskell.Lexer.Lex(haskellLex)
import Language.Haskell.Lexer.Utils
import Language.Haskell.Lexer.Layout(layoutPre,PosToken)
import Language.Haskell.Lexer.Position
import Data.List(mapAccumL)
default(Int)
-- | The function 'lexerPass1' handles the part of lexical analysis that
-- can be done independently of the parser---the tokenization and the
addition of the extra layout tokens \<n\ > and { n } , as specified in
section 9.3 of the revised Haskell 98 Report .
lexerPass1 :: String -> [PosToken]
lexerPass1 = lexerPass1Only . lexerPass0
lexerPass1Only :: [PosToken] -> [PosToken]
lexerPass1Only = layoutPre . rmSpace
-- | Remove token that are not meaningful (e.g., white space and comments).
rmSpace :: [PosToken] -> [PosToken]
rmSpace = filter (notWhite.fst)
notWhite :: Token -> Bool
notWhite t = t/=Whitespace &&
t/=Commentstart && t/=Comment &&
t/=NestedComment
-- | Tokenize and add position information. Preserves white space,
-- and does not insert extra tokens due to layout.
lexerPass0 :: String -> [PosToken]
lexerPass0 = lexerPass0' startPos
-- | Same as 'lexerPass0', except that it uses the given start position.
lexerPass0' :: Pos -> String -> [PosToken]
lexerPass0' pos0 = addPos . haskellLex . rmcr
where
addPos = snd . mapAccumL pos pos0
seq p '
where p' = nextPos p s
-- where s = reverse r
| Since # nextPos # examines one character at a time , it will increase the line
number by 2 if it sees \CR\LF , which can happen when reading DOS files on
-- a Unix like system.
-- Since the extra \CR characters can cause trouble later as well, we choose
-- to simply remove them here.
rmcr :: String -> String
rmcr ('\CR':'\LF':s) = '\LF':rmcr s
rmcr (c:s) = c:rmcr s
rmcr "" = ""
| null | https://raw.githubusercontent.com/yav/haskell-lexer/357df3d88fa6638703126ad6178380386944819e/Language/Haskell/Lexer.hs | haskell | | The function 'lexerPass1' handles the part of lexical analysis that
can be done independently of the parser---the tokenization and the
| Remove token that are not meaningful (e.g., white space and comments).
| Tokenize and add position information. Preserves white space,
and does not insert extra tokens due to layout.
| Same as 'lexerPass0', except that it uses the given start position.
where s = reverse r
a Unix like system.
Since the extra \CR characters can cause trouble later as well, we choose
to simply remove them here. | module Language.Haskell.Lexer
( PosToken
, Token(..)
, lexerPass0
, lexerPass0'
, lexerPass1
, rmSpace
, layoutPre
, module Language.Haskell.Lexer.Position
) where
import Language.Haskell.Lexer.Lex(haskellLex)
import Language.Haskell.Lexer.Utils
import Language.Haskell.Lexer.Layout(layoutPre,PosToken)
import Language.Haskell.Lexer.Position
import Data.List(mapAccumL)
default(Int)
addition of the extra layout tokens \<n\ > and { n } , as specified in
section 9.3 of the revised Haskell 98 Report .
lexerPass1 :: String -> [PosToken]
lexerPass1 = lexerPass1Only . lexerPass0
lexerPass1Only :: [PosToken] -> [PosToken]
lexerPass1Only = layoutPre . rmSpace
rmSpace :: [PosToken] -> [PosToken]
rmSpace = filter (notWhite.fst)
notWhite :: Token -> Bool
notWhite t = t/=Whitespace &&
t/=Commentstart && t/=Comment &&
t/=NestedComment
lexerPass0 :: String -> [PosToken]
lexerPass0 = lexerPass0' startPos
lexerPass0' :: Pos -> String -> [PosToken]
lexerPass0' pos0 = addPos . haskellLex . rmcr
where
addPos = snd . mapAccumL pos pos0
seq p '
where p' = nextPos p s
| Since # nextPos # examines one character at a time , it will increase the line
number by 2 if it sees \CR\LF , which can happen when reading DOS files on
rmcr :: String -> String
rmcr ('\CR':'\LF':s) = '\LF':rmcr s
rmcr (c:s) = c:rmcr s
rmcr "" = ""
|
def8c2050a24d6105f32a0ad92b951da885caad39222f2341b563b458f1b13e2 | vikram/lisplibraries | font-loader-interface.lisp | Copyright ( c ) 2006 , All Rights Reserved
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
Interface functions for creating , initializing , and closing a
;;; FONT-LOADER object.
;;;
font - loader - interface.lisp , v 1.6 2006/03/23 22:20:35 xach Exp
(in-package #:zpb-ttf)
(defun arrange-finalization (object stream)
(flet ((quietly-close (&optional object)
(declare (ignore object))
(ignore-errors (close stream))))
#+sbcl
(sb-ext:finalize object #'quietly-close)
#+cmucl
(ext:finalize object #'quietly-close)
#+clisp
(ext:finalize object #'quietly-close)
#+allegro
(excl:schedule-finalization object #'quietly-close)))
;;;
;;; FIXME: move most/all of this stuff into initialize-instance
;;;
(defun open-font-loader-from-file (font-file)
(let* ((input-stream (open font-file
:direction :input
:element-type '(unsigned-byte 8)))
(magic (read-uint32 input-stream)))
(when (/= magic #x00010000 #x74727565)
(error 'bad-magic
:location "font header"
:expected-values (list #x00010000 #x74727565)
:actual-value magic))
(let* ((table-count (read-uint16 input-stream))
(font-loader (make-instance 'font-loader
:input-stream input-stream
:table-count table-count)))
(arrange-finalization font-loader input-stream)
;; skip the unused stuff:
;; searchRange, entrySelector, rangeShift
(read-uint16 input-stream)
(read-uint16 input-stream)
(read-uint16 input-stream)
(loop repeat table-count
for tag = (read-uint32 input-stream)
for checksum = (read-uint32 input-stream)
for offset = (read-uint32 input-stream)
for size = (read-uint32 input-stream)
do (setf (gethash tag (tables font-loader))
(make-instance 'table-info
:offset offset
:name (number->tag tag)
:size size)))
(load-maxp-info font-loader)
(load-head-info font-loader)
(load-kern-info font-loader)
(load-loca-info font-loader)
(load-name-info font-loader)
(load-cmap-info font-loader)
(load-post-info font-loader)
(load-hhea-info font-loader)
(load-hmtx-info font-loader)
(setf (glyph-cache font-loader)
(make-array (glyph-count font-loader) :initial-element nil))
font-loader)))
(defun open-font-loader (thing)
(typecase thing
(font-loader
(unless (open-stream-p (input-stream thing))
(setf (input-stream thing) (open (input-stream thing))))
thing)
(t
(open-font-loader-from-file thing))))
(defun close-font-loader (loader)
(close (input-stream loader)))
(defmacro with-font-loader ((loader file) &body body)
`(let (,loader)
(unwind-protect
(progn
(setf ,loader (open-font-loader ,file))
,@body)
(when ,loader
(close-font-loader ,loader)))))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/zpb-ttf-0.7/font-loader-interface.lisp | lisp |
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
FONT-LOADER object.
FIXME: move most/all of this stuff into initialize-instance
skip the unused stuff:
searchRange, entrySelector, rangeShift | Copyright ( c ) 2006 , All Rights Reserved
DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY ,
Interface functions for creating , initializing , and closing a
font - loader - interface.lisp , v 1.6 2006/03/23 22:20:35 xach Exp
(in-package #:zpb-ttf)
(defun arrange-finalization (object stream)
(flet ((quietly-close (&optional object)
(declare (ignore object))
(ignore-errors (close stream))))
#+sbcl
(sb-ext:finalize object #'quietly-close)
#+cmucl
(ext:finalize object #'quietly-close)
#+clisp
(ext:finalize object #'quietly-close)
#+allegro
(excl:schedule-finalization object #'quietly-close)))
(defun open-font-loader-from-file (font-file)
(let* ((input-stream (open font-file
:direction :input
:element-type '(unsigned-byte 8)))
(magic (read-uint32 input-stream)))
(when (/= magic #x00010000 #x74727565)
(error 'bad-magic
:location "font header"
:expected-values (list #x00010000 #x74727565)
:actual-value magic))
(let* ((table-count (read-uint16 input-stream))
(font-loader (make-instance 'font-loader
:input-stream input-stream
:table-count table-count)))
(arrange-finalization font-loader input-stream)
(read-uint16 input-stream)
(read-uint16 input-stream)
(read-uint16 input-stream)
(loop repeat table-count
for tag = (read-uint32 input-stream)
for checksum = (read-uint32 input-stream)
for offset = (read-uint32 input-stream)
for size = (read-uint32 input-stream)
do (setf (gethash tag (tables font-loader))
(make-instance 'table-info
:offset offset
:name (number->tag tag)
:size size)))
(load-maxp-info font-loader)
(load-head-info font-loader)
(load-kern-info font-loader)
(load-loca-info font-loader)
(load-name-info font-loader)
(load-cmap-info font-loader)
(load-post-info font-loader)
(load-hhea-info font-loader)
(load-hmtx-info font-loader)
(setf (glyph-cache font-loader)
(make-array (glyph-count font-loader) :initial-element nil))
font-loader)))
(defun open-font-loader (thing)
(typecase thing
(font-loader
(unless (open-stream-p (input-stream thing))
(setf (input-stream thing) (open (input-stream thing))))
thing)
(t
(open-font-loader-from-file thing))))
(defun close-font-loader (loader)
(close (input-stream loader)))
(defmacro with-font-loader ((loader file) &body body)
`(let (,loader)
(unwind-protect
(progn
(setf ,loader (open-font-loader ,file))
,@body)
(when ,loader
(close-font-loader ,loader)))))
|
61fdc706b6a417ab03f7b9aeb7993c465b8d2afc76d2112028030a0e1a473de4 | adacapo21/plutusPioneerProgram | Maybe.hs | module Week04.Maybe where
import Text.Read (readMaybe)
import Week04.Monad
foo :: String -> String -> String -> Maybe Int -- YOU CAN RUN THIS IN REPL by typing:
foo " 1 " " 2 " " 3 "
3 values to be a type of Integers
Nothing -> Nothing -- FAILURE
Just k -> case readMaybe y of -- If K int succeeds
Nothing -> Nothing -- FAILURE
Just l -> case readMaybe z of -- If l int succeeds
Nothing -> Nothing -- FAILURE
Just m -> Just (k + l + m) -- if m int succeeds
-- the above way is too Noisy in HASKELL
bindMaybe :: Maybe a -> (a -> Maybe b) -> Maybe b -- a less NOISY WAY of of doing the completely same logic with above
bindMaybe Nothing _ = Nothing
bindMaybe (Just x) f = f x
-- YOU CAN RUN below example IN REPL by typing:
foo ' " 1 " " 2 " " 3 "
foo' :: String -> String -> String -> Maybe Int
foo' x y z = readMaybe x `bindMaybe` \k -> -- If k is an INT succeeds
readMaybe y `bindMaybe` \l -> -- If l is an INT succeeds
readMaybe z `bindMaybe` \m -> -- If m is an INT succeeds
Just (k + l + m) -- ADD THEM
foo'' :: String -> String -> String -> Maybe Int -- YOU CAN RUN THIS IN REPL by typing:
foo '' " 1 " " 2 " " 3 "
foo'' x y z = threeInts (readMaybe x) (readMaybe y) (readMaybe z) --
| null | https://raw.githubusercontent.com/adacapo21/plutusPioneerProgram/2994d6fd8c01a54c15dd19783b898aca71831c5a/week04/src/Week04/Maybe.hs | haskell | YOU CAN RUN THIS IN REPL by typing:
FAILURE
If K int succeeds
FAILURE
If l int succeeds
FAILURE
if m int succeeds
the above way is too Noisy in HASKELL
a less NOISY WAY of of doing the completely same logic with above
YOU CAN RUN below example IN REPL by typing:
If k is an INT succeeds
If l is an INT succeeds
If m is an INT succeeds
ADD THEM
YOU CAN RUN THIS IN REPL by typing:
| module Week04.Maybe where
import Text.Read (readMaybe)
import Week04.Monad
foo " 1 " " 2 " " 3 "
3 values to be a type of Integers
bindMaybe Nothing _ = Nothing
bindMaybe (Just x) f = f x
foo ' " 1 " " 2 " " 3 "
foo' :: String -> String -> String -> Maybe Int
foo '' " 1 " " 2 " " 3 "
|
6d530511480bfbf2e57e45f999a6e2bffb76150eaf6de68003c697cb61ca9f87 | ocaml-sf/learnocaml-cpge-public | test2.ml | open Test_lib
open Report
let success msg =
[Message ([Text msg], Success 1)]
let fail msg =
[Message ([Text msg], Failure)]
(******************************************************)
(* Some facilities to work with Binary Search Trees **)
(******************************************************)
let leaf x = Node (Empty, x, Empty)
let rec repeat n f accu =
if n = 0 then accu else repeat (n - 1) f (f accu)
let rec insert x = function
| Empty -> leaf x
| (Node (l, y, r)) as t ->
let c = compare x y in
if c = 0 then t
else if c > 0 then Node (l, y, insert x r)
else Node (insert x l, y, r)
let size = 20
let sample_bst sample_label () : Thing.t bst =
repeat (Random.int size) (fun bst ->
insert (sample_label ()) bst
) Empty
let rec elements = function
| Node (l, x, r) -> elements l @ x :: elements r
| Empty -> []
let pick l =
let es = elements l in
List.(nth es (Random.int (length es)))
let rec height = function
| Empty -> 0
| Node (l, x, r) -> 1 + max (height l) (height r)
(************************)
(* Actual testing code **)
(************************)
let sample_input () =
let t = sample_bst sample_thing () in
if t <> Empty && Random.int 2 = 0 then
(pick t, t)
else
(sample_thing (), t)
let before_user _ _ =
reset_comparison_counter ()
let after _ tree out exp =
if out <> exp then
fail "Le calcul est incorrect."
else if consumed_comparisons () > height tree then
fail "Le nombre de comparaisons ne peut pas être plus grand \
que la hauteur de l'arbre."
else
success "Bravo! Voici un calcul correct et efficace!"
let correct () =
test_function_2_against_solution
~gen:50 ~sampler:sample_input ~before_user ~after
[%ty : thing -> thing bst -> bool ] "mem"
[]
let () =
set_result @@
[ Section ([ Text "Question 1" ; Code "mem" ], correct ()) ]
| null | https://raw.githubusercontent.com/ocaml-sf/learnocaml-cpge-public/f903aaa78254c8397c8d138c13bb2976c1d9ef3d/exercises/bst/tests/test2.ml | ocaml | ****************************************************
Some facilities to work with Binary Search Trees *
****************************************************
**********************
Actual testing code *
********************** | open Test_lib
open Report
let success msg =
[Message ([Text msg], Success 1)]
let fail msg =
[Message ([Text msg], Failure)]
let leaf x = Node (Empty, x, Empty)
let rec repeat n f accu =
if n = 0 then accu else repeat (n - 1) f (f accu)
let rec insert x = function
| Empty -> leaf x
| (Node (l, y, r)) as t ->
let c = compare x y in
if c = 0 then t
else if c > 0 then Node (l, y, insert x r)
else Node (insert x l, y, r)
let size = 20
let sample_bst sample_label () : Thing.t bst =
repeat (Random.int size) (fun bst ->
insert (sample_label ()) bst
) Empty
let rec elements = function
| Node (l, x, r) -> elements l @ x :: elements r
| Empty -> []
let pick l =
let es = elements l in
List.(nth es (Random.int (length es)))
let rec height = function
| Empty -> 0
| Node (l, x, r) -> 1 + max (height l) (height r)
let sample_input () =
let t = sample_bst sample_thing () in
if t <> Empty && Random.int 2 = 0 then
(pick t, t)
else
(sample_thing (), t)
let before_user _ _ =
reset_comparison_counter ()
let after _ tree out exp =
if out <> exp then
fail "Le calcul est incorrect."
else if consumed_comparisons () > height tree then
fail "Le nombre de comparaisons ne peut pas être plus grand \
que la hauteur de l'arbre."
else
success "Bravo! Voici un calcul correct et efficace!"
let correct () =
test_function_2_against_solution
~gen:50 ~sampler:sample_input ~before_user ~after
[%ty : thing -> thing bst -> bool ] "mem"
[]
let () =
set_result @@
[ Section ([ Text "Question 1" ; Code "mem" ], correct ()) ]
|
a14df13678e6b28014154d132c1d6df5a33f2421ae01d4b35da76fa2d0f36555 | imandra-ai/fix-engine | message.mli | type t = (string * string) list [@@deriving show]
val checksum_string : string -> int
val valid_checksum : t -> bool
* Verifies the checksum ( sum of all bytes mod 256 ) of all bytes in
the message up to the CheckSum<10 > entry . Returns true if the computed
checksum is equal to the value of CheckSum<10 > .
the message up to the CheckSum<10> entry. Returns true if the computed
checksum is equal to the value of CheckSum<10>.
*)
val checksum : t -> int
(** A checksum in [[0..<256]] *)
val valid_body_length : t -> bool
* Checks that the message contains > field as a second entry
in the message . And that the value equals to the number of bytes between
BodyLength<9 > and CheckSum<10 > entries in the message .
in the message. And that the value equals to the number of bytes between
BodyLength<9> and CheckSum<10> entries in the message.
*)
| null | https://raw.githubusercontent.com/imandra-ai/fix-engine/42f3c4f3ca432469969e89e461ca76b52c21f282/fix-engine/src-core-utils-msg/message.mli | ocaml | * A checksum in [[0..<256]] | type t = (string * string) list [@@deriving show]
val checksum_string : string -> int
val valid_checksum : t -> bool
* Verifies the checksum ( sum of all bytes mod 256 ) of all bytes in
the message up to the CheckSum<10 > entry . Returns true if the computed
checksum is equal to the value of CheckSum<10 > .
the message up to the CheckSum<10> entry. Returns true if the computed
checksum is equal to the value of CheckSum<10>.
*)
val checksum : t -> int
val valid_body_length : t -> bool
* Checks that the message contains > field as a second entry
in the message . And that the value equals to the number of bytes between
BodyLength<9 > and CheckSum<10 > entries in the message .
in the message. And that the value equals to the number of bytes between
BodyLength<9> and CheckSum<10> entries in the message.
*)
|
b61c889086ea48cee8af9277f288e31fcc84d911c14c7d978e004676b1ee8aca | avsm/platform | core.mli |
RE - A regular expression library
Copyright ( C ) 2001
email :
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 , with
linking exception ; 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 .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
RE - A regular expression library
Copyright (C) 2001 Jerome Vouillon
email:
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, with
linking exception; 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.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
(** Module [Re]: regular expressions commons *)
type t
(** Regular expression *)
type re
(** Compiled regular expression *)
(** Manipulate matching groups. *)
module Group : sig
type t
(** Information about groups in a match. *)
val get : t -> int -> string
(** Raise [Not_found] if the group did not match *)
val offset : t -> int -> int * int
(** Raise [Not_found] if the group did not match *)
val start : t -> int -> int
(** Return the start of the match. Raise [Not_found] if the group did not match. *)
val stop : t -> int -> int
(** Return the end of the match. Raise [Not_found] if the group did not match. *)
val all : t -> string array
(** Return the empty string for each group which did not match *)
val all_offset : t -> (int * int) array
(** Return [(-1,-1)] for each group which did not match *)
val test : t -> int -> bool
(** Test whether a group matched *)
val nb_groups : t -> int
(** Returns the total number of groups defined - matched or not.
This function is experimental. *)
val pp : Format.formatter -> t -> unit
end
type groups = Group.t [@@ocaml.deprecated "Use Group.t"]
(** {2 Compilation and execution of a regular expression} *)
val compile : t -> re
(** Compile a regular expression into an executable version that can be
used to match strings, e.g. with {!exec}. *)
val exec :
Default : 0
?len:int -> (* Default: -1 (until end of string) *)
re -> string -> Group.t
(** [exec re str] matches [str] against the compiled expression [re],
and returns the matched groups if any.
@param pos optional beginning of the string (default 0)
@param len length of the substring of [str] that can be matched (default [-1],
meaning to the end of the string
@raise Not_found if the regular expression can't be found in [str]
*)
val exec_opt :
Default : 0
?len:int -> (* Default: -1 (until end of string) *)
re -> string -> Group.t option
(** Similar to {!exec}, but returns an option instead of using an exception. *)
val execp :
Default : 0
?len:int -> (* Default: -1 (until end of string) *)
re -> string -> bool
(** Similar to {!exec}, but returns [true] if the expression matches,
and [false] if it doesn't *)
val exec_partial :
Default : 0
?len:int -> (* Default: -1 (until end of string) *)
re -> string -> [ `Full | `Partial | `Mismatch ]
(** More detailed version of {!exec_p} *)
(** Marks *)
module Mark : sig
type t
*
val test : Group.t -> t -> bool
(** Tell if a mark was matched. *)
module Set : Set.S with type elt = t
val all : Group.t -> Set.t
(** Return all the mark matched. *)
val equal : t -> t -> bool
val compare : t -> t -> int
end
* { 2 High Level Operations }
type split_token =
[ `Text of string (** Text between delimiters *)
| `Delim of Group.t (** Delimiter *)
]
type 'a seq = 'a Seq.t
module Seq : sig
val all :
* Default : 0
?len:int ->
re -> string -> Group.t Seq.t
(** Same as {!all} but returns an iterator
@since NEXT_RELEASE *)
val matches :
* Default : 0
?len:int ->
re -> string -> string Seq.t
(** Same as {!matches}, but returns an iterator
@since NEXT_RELEASE *)
val split :
* Default : 0
?len:int ->
re -> string -> string Seq.t
(** @since NEXT_RELEASE *)
val split_full :
* Default : 0
?len:int ->
re -> string -> split_token Seq.t
(** @since NEXT_RELEASE *)
end
val all : ?pos:int -> ?len:int -> re -> string -> Group.t list
(** Repeatedly calls {!exec} on the given string, starting at given position and
length.*)
type 'a gen = unit -> 'a option
val all_gen : ?pos:int -> ?len:int -> re -> string -> Group.t gen
[@@ocaml.deprecated "Use Seq.all"]
val all_seq : ?pos:int -> ?len:int -> re -> string -> Group.t seq
[@@ocaml.deprecated "Use Seq.all"]
val matches : ?pos:int -> ?len:int -> re -> string -> string list
(** Same as {!all}, but extracts the matched substring rather than returning
the whole group. This basically iterates over matched strings *)
val matches_gen : ?pos:int -> ?len:int -> re -> string -> string gen
[@@ocaml.deprecated "Use Seq.matches"]
val matches_seq : ?pos:int -> ?len:int -> re -> string -> string seq
[@@ocaml.deprecated "Use Seq.matches"]
val split : ?pos:int -> ?len:int -> re -> string -> string list
(** [split re s] splits [s] into chunks separated by [re]. It yields the chunks
themselves, not the separator. For instance this can be used with a
whitespace-matching re such as ["[\t ]+"]. *)
val split_gen : ?pos:int -> ?len:int -> re -> string -> string gen
[@@ocaml.deprecated "Use Seq.split"]
val split_seq : ?pos:int -> ?len:int -> re -> string -> string seq
[@@ocaml.deprecated "Use Seq.split"]
val split_full : ?pos:int -> ?len:int -> re -> string -> split_token list
(** [split re s] splits [s] into chunks separated by [re]. It yields the chunks
along with the separators. For instance this can be used with a
whitespace-matching re such as ["[\t ]+"]. *)
val split_full_gen : ?pos:int -> ?len:int -> re -> string -> split_token gen
[@@ocaml.deprecated "Use Seq.split_full"]
val split_full_seq : ?pos:int -> ?len:int -> re -> string -> split_token seq
[@@ocaml.deprecated "Use Seq.split_full"]
val replace :
* Default : 0
?len:int ->
* Default : true . Otherwise only replace first occurrence
re -> (** matched groups *)
f:(Group.t -> string) -> (* how to replace *)
string -> (** string to replace in *)
string
* [ replace ~all re ~f s ] iterates on [ s ] , and replaces every occurrence
of [ re ] with [ f substring ] where [ substring ] is the current match .
If [ all = false ] , then only the first occurrence of [ re ] is replaced .
of [re] with [f substring] where [substring] is the current match.
If [all = false], then only the first occurrence of [re] is replaced. *)
val replace_string :
* Default : 0
?len:int ->
* Default : true . Otherwise only replace first occurrence
re -> (** matched groups *)
by:string -> (** replacement string *)
string -> (** string to replace in *)
string
* [ replace_string ~all re ~by s ] iterates on [ s ] , and replaces every
occurrence of [ re ] with [ by ] . If [ all = false ] , then only the first
occurrence of [ re ] is replaced .
occurrence of [re] with [by]. If [all = false], then only the first
occurrence of [re] is replaced. *)
* { 2 String expressions ( literal match ) }
val str : string -> t
val char : char -> t
* { 2 Basic operations on regular expressions }
val alt : t list -> t
(** Alternative *)
val seq : t list -> t
(** Sequence *)
val empty : t
(** Match nothing *)
val epsilon : t
(** Empty word *)
val rep : t -> t
(** 0 or more matches *)
val rep1 : t -> t
* 1 or more matches
val repn : t -> int -> int option -> t
* [ repn re i j ] matches [ re ] at least [ i ] times
and at most [ j ] times , bounds included .
[ j = None ] means no upper bound .
and at most [j] times, bounds included.
[j = None] means no upper bound.
*)
val opt : t -> t
* 0 or 1 matches
(** {2 String, line, word} *)
val bol : t
(** Beginning of line *)
val eol : t
(** End of line *)
val bow : t
(** Beginning of word *)
val eow : t
(** End of word *)
val bos : t
(** Beginning of string *)
val eos : t
(** End of string *)
val leol : t
(** Last end of line or end of string *)
val start : t
(** Initial position *)
val stop : t
(** Final position *)
val word : t -> t
(** Word *)
val not_boundary : t
(** Not at a word boundary *)
val whole_string : t -> t
(** Only matches the whole string *)
* { 2 Match semantics }
val longest : t -> t
(** Longest match *)
val shortest : t -> t
* Shortest match
val first : t -> t
* First match
* { 2 Repeated match modifiers }
val greedy : t -> t
(** Greedy *)
val non_greedy : t -> t
(** Non-greedy *)
* { 2 Groups ( or submatches ) }
val group : t -> t
* a group
val no_group : t -> t
(** Remove all groups *)
val nest : t -> t
(** when matching against [nest e], only the group matching in the
last match of e will be considered as matching *)
val mark : t -> Mark.t * t
* a regexp . the markid can then be used to know if this regexp was used .
* { 2 Character sets }
val set : string -> t
(** Any character of the string *)
val rg : char -> char -> t
(** Character ranges *)
val inter : t list -> t
(** Intersection of character sets *)
val diff : t -> t -> t
(** Difference of character sets *)
val compl : t list -> t
(** Complement of union *)
* { 2 Predefined character sets }
val any : t
(** Any character *)
val notnl : t
(** Any character but a newline *)
val alnum : t
val wordc : t
val alpha : t
val ascii : t
val blank : t
val cntrl : t
val digit : t
val graph : t
val lower : t
val print : t
val punct : t
val space : t
val upper : t
val xdigit : t
* { 2 Case modifiers }
val case : t -> t
(** Case sensitive matching *)
val no_case : t -> t
(** Case insensitive matching *)
(****)
* { 2 Internal debugging }
val pp : Format.formatter -> t -> unit
val pp_re : Format.formatter -> re -> unit
* for { ! pp_re } . Deprecated
val print_re : Format.formatter -> re -> unit
module View : sig
type outer
(** A view of the top-level of a regex. This type is unstable and may change *)
type t =
Set of Cset.t
| Sequence of outer list
| Alternative of outer list
| Repeat of outer * int * int option
| Beg_of_line | End_of_line
| Beg_of_word | End_of_word | Not_bound
| Beg_of_str | End_of_str
| Last_end_of_line | Start | Stop
| Sem of Automata.sem * outer
| Sem_greedy of Automata.rep_kind * outer
| Group of outer | No_group of outer | Nest of outer
| Case of outer | No_case of outer
| Intersection of outer list
| Complement of outer list
| Difference of outer * outer
| Pmark of Pmark.t * outer
val view : outer -> t
end with type outer := t
* { 2 Experimental functions } .
val witness : t -> string
(** [witness r] generates a string [s] such that [execp (compile r) s] is
true *)
* { 2 Deprecated functions }
type substrings = Group.t
[@@ocaml.deprecated "Use Group.t"]
* for { ! Group.t } . Deprecated
val get : Group.t -> int -> string
[@@ocaml.deprecated "Use Group.get"]
(** Same as {!Group.get}. Deprecated *)
val get_ofs : Group.t -> int -> int * int
[@@ocaml.deprecated "Use Group.offset"]
(** Same as {!Group.offset}. Deprecated *)
val get_all : Group.t -> string array
[@@ocaml.deprecated "Use Group.all"]
* Same as { ! } . Deprecated
val get_all_ofs : Group.t -> (int * int) array
[@@ocaml.deprecated "Use Group.all_offset"]
(** Same as {!Group.all_offset}. Deprecated *)
val test : Group.t -> int -> bool
[@@ocaml.deprecated "Use Group.test"]
(** Same as {!Group.test}. Deprecated *)
type markid = Mark.t
[@@ocaml.deprecated "Use Mark."]
* for { ! Mark.t } . Deprecated
val marked : Group.t -> Mark.t -> bool
[@@ocaml.deprecated "Use Mark.test"]
(** Same as {!Mark.test}. Deprecated *)
val mark_set : Group.t -> Mark.Set.t
[@@ocaml.deprecated "Use Mark.all"]
* Same as { ! } . Deprecated
| null | https://raw.githubusercontent.com/avsm/platform/b254e3c6b60f3c0c09dfdcde92eb1abdc267fa1c/duniverse/re.1.9.0/lib/core.mli | ocaml | * Module [Re]: regular expressions commons
* Regular expression
* Compiled regular expression
* Manipulate matching groups.
* Information about groups in a match.
* Raise [Not_found] if the group did not match
* Raise [Not_found] if the group did not match
* Return the start of the match. Raise [Not_found] if the group did not match.
* Return the end of the match. Raise [Not_found] if the group did not match.
* Return the empty string for each group which did not match
* Return [(-1,-1)] for each group which did not match
* Test whether a group matched
* Returns the total number of groups defined - matched or not.
This function is experimental.
* {2 Compilation and execution of a regular expression}
* Compile a regular expression into an executable version that can be
used to match strings, e.g. with {!exec}.
Default: -1 (until end of string)
* [exec re str] matches [str] against the compiled expression [re],
and returns the matched groups if any.
@param pos optional beginning of the string (default 0)
@param len length of the substring of [str] that can be matched (default [-1],
meaning to the end of the string
@raise Not_found if the regular expression can't be found in [str]
Default: -1 (until end of string)
* Similar to {!exec}, but returns an option instead of using an exception.
Default: -1 (until end of string)
* Similar to {!exec}, but returns [true] if the expression matches,
and [false] if it doesn't
Default: -1 (until end of string)
* More detailed version of {!exec_p}
* Marks
* Tell if a mark was matched.
* Return all the mark matched.
* Text between delimiters
* Delimiter
* Same as {!all} but returns an iterator
@since NEXT_RELEASE
* Same as {!matches}, but returns an iterator
@since NEXT_RELEASE
* @since NEXT_RELEASE
* @since NEXT_RELEASE
* Repeatedly calls {!exec} on the given string, starting at given position and
length.
* Same as {!all}, but extracts the matched substring rather than returning
the whole group. This basically iterates over matched strings
* [split re s] splits [s] into chunks separated by [re]. It yields the chunks
themselves, not the separator. For instance this can be used with a
whitespace-matching re such as ["[\t ]+"].
* [split re s] splits [s] into chunks separated by [re]. It yields the chunks
along with the separators. For instance this can be used with a
whitespace-matching re such as ["[\t ]+"].
* matched groups
how to replace
* string to replace in
* matched groups
* replacement string
* string to replace in
* Alternative
* Sequence
* Match nothing
* Empty word
* 0 or more matches
* {2 String, line, word}
* Beginning of line
* End of line
* Beginning of word
* End of word
* Beginning of string
* End of string
* Last end of line or end of string
* Initial position
* Final position
* Word
* Not at a word boundary
* Only matches the whole string
* Longest match
* Greedy
* Non-greedy
* Remove all groups
* when matching against [nest e], only the group matching in the
last match of e will be considered as matching
* Any character of the string
* Character ranges
* Intersection of character sets
* Difference of character sets
* Complement of union
* Any character
* Any character but a newline
* Case sensitive matching
* Case insensitive matching
**
* A view of the top-level of a regex. This type is unstable and may change
* [witness r] generates a string [s] such that [execp (compile r) s] is
true
* Same as {!Group.get}. Deprecated
* Same as {!Group.offset}. Deprecated
* Same as {!Group.all_offset}. Deprecated
* Same as {!Group.test}. Deprecated
* Same as {!Mark.test}. Deprecated |
RE - A regular expression library
Copyright ( C ) 2001
email :
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 , with
linking exception ; 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 .
You should have received a copy of the GNU Lesser General Public
License along with this library ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
RE - A regular expression library
Copyright (C) 2001 Jerome Vouillon
email:
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, with
linking exception; 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.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
type t
type re
module Group : sig
type t
val get : t -> int -> string
val offset : t -> int -> int * int
val start : t -> int -> int
val stop : t -> int -> int
val all : t -> string array
val all_offset : t -> (int * int) array
val test : t -> int -> bool
val nb_groups : t -> int
val pp : Format.formatter -> t -> unit
end
type groups = Group.t [@@ocaml.deprecated "Use Group.t"]
val compile : t -> re
val exec :
Default : 0
re -> string -> Group.t
val exec_opt :
Default : 0
re -> string -> Group.t option
val execp :
Default : 0
re -> string -> bool
val exec_partial :
Default : 0
re -> string -> [ `Full | `Partial | `Mismatch ]
module Mark : sig
type t
*
val test : Group.t -> t -> bool
module Set : Set.S with type elt = t
val all : Group.t -> Set.t
val equal : t -> t -> bool
val compare : t -> t -> int
end
* { 2 High Level Operations }
type split_token =
]
type 'a seq = 'a Seq.t
module Seq : sig
val all :
* Default : 0
?len:int ->
re -> string -> Group.t Seq.t
val matches :
* Default : 0
?len:int ->
re -> string -> string Seq.t
val split :
* Default : 0
?len:int ->
re -> string -> string Seq.t
val split_full :
* Default : 0
?len:int ->
re -> string -> split_token Seq.t
end
val all : ?pos:int -> ?len:int -> re -> string -> Group.t list
type 'a gen = unit -> 'a option
val all_gen : ?pos:int -> ?len:int -> re -> string -> Group.t gen
[@@ocaml.deprecated "Use Seq.all"]
val all_seq : ?pos:int -> ?len:int -> re -> string -> Group.t seq
[@@ocaml.deprecated "Use Seq.all"]
val matches : ?pos:int -> ?len:int -> re -> string -> string list
val matches_gen : ?pos:int -> ?len:int -> re -> string -> string gen
[@@ocaml.deprecated "Use Seq.matches"]
val matches_seq : ?pos:int -> ?len:int -> re -> string -> string seq
[@@ocaml.deprecated "Use Seq.matches"]
val split : ?pos:int -> ?len:int -> re -> string -> string list
val split_gen : ?pos:int -> ?len:int -> re -> string -> string gen
[@@ocaml.deprecated "Use Seq.split"]
val split_seq : ?pos:int -> ?len:int -> re -> string -> string seq
[@@ocaml.deprecated "Use Seq.split"]
val split_full : ?pos:int -> ?len:int -> re -> string -> split_token list
val split_full_gen : ?pos:int -> ?len:int -> re -> string -> split_token gen
[@@ocaml.deprecated "Use Seq.split_full"]
val split_full_seq : ?pos:int -> ?len:int -> re -> string -> split_token seq
[@@ocaml.deprecated "Use Seq.split_full"]
val replace :
* Default : 0
?len:int ->
* Default : true . Otherwise only replace first occurrence
string
* [ replace ~all re ~f s ] iterates on [ s ] , and replaces every occurrence
of [ re ] with [ f substring ] where [ substring ] is the current match .
If [ all = false ] , then only the first occurrence of [ re ] is replaced .
of [re] with [f substring] where [substring] is the current match.
If [all = false], then only the first occurrence of [re] is replaced. *)
val replace_string :
* Default : 0
?len:int ->
* Default : true . Otherwise only replace first occurrence
string
* [ replace_string ~all re ~by s ] iterates on [ s ] , and replaces every
occurrence of [ re ] with [ by ] . If [ all = false ] , then only the first
occurrence of [ re ] is replaced .
occurrence of [re] with [by]. If [all = false], then only the first
occurrence of [re] is replaced. *)
* { 2 String expressions ( literal match ) }
val str : string -> t
val char : char -> t
* { 2 Basic operations on regular expressions }
val alt : t list -> t
val seq : t list -> t
val empty : t
val epsilon : t
val rep : t -> t
val rep1 : t -> t
* 1 or more matches
val repn : t -> int -> int option -> t
* [ repn re i j ] matches [ re ] at least [ i ] times
and at most [ j ] times , bounds included .
[ j = None ] means no upper bound .
and at most [j] times, bounds included.
[j = None] means no upper bound.
*)
val opt : t -> t
* 0 or 1 matches
val bol : t
val eol : t
val bow : t
val eow : t
val bos : t
val eos : t
val leol : t
val start : t
val stop : t
val word : t -> t
val not_boundary : t
val whole_string : t -> t
* { 2 Match semantics }
val longest : t -> t
val shortest : t -> t
* Shortest match
val first : t -> t
* First match
* { 2 Repeated match modifiers }
val greedy : t -> t
val non_greedy : t -> t
* { 2 Groups ( or submatches ) }
val group : t -> t
* a group
val no_group : t -> t
val nest : t -> t
val mark : t -> Mark.t * t
* a regexp . the markid can then be used to know if this regexp was used .
* { 2 Character sets }
val set : string -> t
val rg : char -> char -> t
val inter : t list -> t
val diff : t -> t -> t
val compl : t list -> t
* { 2 Predefined character sets }
val any : t
val notnl : t
val alnum : t
val wordc : t
val alpha : t
val ascii : t
val blank : t
val cntrl : t
val digit : t
val graph : t
val lower : t
val print : t
val punct : t
val space : t
val upper : t
val xdigit : t
* { 2 Case modifiers }
val case : t -> t
val no_case : t -> t
* { 2 Internal debugging }
val pp : Format.formatter -> t -> unit
val pp_re : Format.formatter -> re -> unit
* for { ! pp_re } . Deprecated
val print_re : Format.formatter -> re -> unit
module View : sig
type outer
type t =
Set of Cset.t
| Sequence of outer list
| Alternative of outer list
| Repeat of outer * int * int option
| Beg_of_line | End_of_line
| Beg_of_word | End_of_word | Not_bound
| Beg_of_str | End_of_str
| Last_end_of_line | Start | Stop
| Sem of Automata.sem * outer
| Sem_greedy of Automata.rep_kind * outer
| Group of outer | No_group of outer | Nest of outer
| Case of outer | No_case of outer
| Intersection of outer list
| Complement of outer list
| Difference of outer * outer
| Pmark of Pmark.t * outer
val view : outer -> t
end with type outer := t
* { 2 Experimental functions } .
val witness : t -> string
* { 2 Deprecated functions }
type substrings = Group.t
[@@ocaml.deprecated "Use Group.t"]
* for { ! Group.t } . Deprecated
val get : Group.t -> int -> string
[@@ocaml.deprecated "Use Group.get"]
val get_ofs : Group.t -> int -> int * int
[@@ocaml.deprecated "Use Group.offset"]
val get_all : Group.t -> string array
[@@ocaml.deprecated "Use Group.all"]
* Same as { ! } . Deprecated
val get_all_ofs : Group.t -> (int * int) array
[@@ocaml.deprecated "Use Group.all_offset"]
val test : Group.t -> int -> bool
[@@ocaml.deprecated "Use Group.test"]
type markid = Mark.t
[@@ocaml.deprecated "Use Mark."]
* for { ! Mark.t } . Deprecated
val marked : Group.t -> Mark.t -> bool
[@@ocaml.deprecated "Use Mark.test"]
val mark_set : Group.t -> Mark.Set.t
[@@ocaml.deprecated "Use Mark.all"]
* Same as { ! } . Deprecated
|
e89a1cc739ef8b875e06ad22332d42c7ca1b2afc790a4cf10a92e8ac56b97a67 | haskell/win32 | HardLink.hs | # LANGUAGE CPP #
|
Module : System . Win32.HardLink
Copyright : 2013 shelarcy
License : BSD - style
Maintainer :
Stability : Provisional
Portability : Non - portable ( Win32 API )
Handling hard link using Win32 API . [ NTFS only ]
Note : You should worry about file system type when use this module 's function in your application :
* NTFS only supprts this functionality .
* ReFS does n't support hard link currently .
Module : System.Win32.HardLink
Copyright : 2013 shelarcy
License : BSD-style
Maintainer :
Stability : Provisional
Portability : Non-portable (Win32 API)
Handling hard link using Win32 API. [NTFS only]
Note: You should worry about file system type when use this module's function in your application:
* NTFS only supprts this functionality.
* ReFS doesn't support hard link currently.
-}
module System.Win32.WindowsString.HardLink
( createHardLink
, createHardLink'
) where
import System.Win32.HardLink.Internal
import System.Win32.WindowsString.File ( failIfFalseWithRetry_ )
import System.Win32.WindowsString.String ( withTString )
import System.Win32.WindowsString.Types ( nullPtr )
import System.OsPath.Windows
#include "windows_cconv.h"
-- | NOTE: createHardLink is /flipped arguments/ to provide compatibility for Unix.
--
-- If you want to create hard link by Windows way, use 'createHardLink'' instead.
createHardLink :: WindowsPath -- ^ Target file path
-> WindowsPath -- ^ Hard link name
-> IO ()
createHardLink = flip createHardLink'
createHardLink' :: WindowsPath -- ^ Hard link name
-> WindowsPath -- ^ Target file path
-> IO ()
createHardLink' link target =
withTString target $ \c_target ->
withTString link $ \c_link ->
failIfFalseWithRetry_ (unwords ["CreateHardLinkW",show link,show target]) $
c_CreateHardLink c_link c_target nullPtr
| null | https://raw.githubusercontent.com/haskell/win32/931497f7052f63cb5cfd4494a94e572c5c570642/System/Win32/WindowsString/HardLink.hs | haskell | | NOTE: createHardLink is /flipped arguments/ to provide compatibility for Unix.
If you want to create hard link by Windows way, use 'createHardLink'' instead.
^ Target file path
^ Hard link name
^ Hard link name
^ Target file path
| # LANGUAGE CPP #
|
Module : System . Win32.HardLink
Copyright : 2013 shelarcy
License : BSD - style
Maintainer :
Stability : Provisional
Portability : Non - portable ( Win32 API )
Handling hard link using Win32 API . [ NTFS only ]
Note : You should worry about file system type when use this module 's function in your application :
* NTFS only supprts this functionality .
* ReFS does n't support hard link currently .
Module : System.Win32.HardLink
Copyright : 2013 shelarcy
License : BSD-style
Maintainer :
Stability : Provisional
Portability : Non-portable (Win32 API)
Handling hard link using Win32 API. [NTFS only]
Note: You should worry about file system type when use this module's function in your application:
* NTFS only supprts this functionality.
* ReFS doesn't support hard link currently.
-}
module System.Win32.WindowsString.HardLink
( createHardLink
, createHardLink'
) where
import System.Win32.HardLink.Internal
import System.Win32.WindowsString.File ( failIfFalseWithRetry_ )
import System.Win32.WindowsString.String ( withTString )
import System.Win32.WindowsString.Types ( nullPtr )
import System.OsPath.Windows
#include "windows_cconv.h"
-> IO ()
createHardLink = flip createHardLink'
-> IO ()
createHardLink' link target =
withTString target $ \c_target ->
withTString link $ \c_link ->
failIfFalseWithRetry_ (unwords ["CreateHardLinkW",show link,show target]) $
c_CreateHardLink c_link c_target nullPtr
|
3136c54a9cd5abb426935bae4ffb2bc314e506d03ad20f305cce0c9e31780ee2 | ghc/testsuite | tcfail212.hs | # LANGUAGE ConstraintKinds , MagicHash #
module ShouldFail where
import GHC.Exts
-- If we turn on ConstraintKinds the typing rule for
-- tuple types is generalised. This test checks that
-- we get a reasonable error for unreasonable tuples.
f :: (Maybe, Either Int)
f = (Just 1, Left 1)
g :: (Int#, Int#)
g = (1#, 2#) | null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_fail/tcfail212.hs | haskell | If we turn on ConstraintKinds the typing rule for
tuple types is generalised. This test checks that
we get a reasonable error for unreasonable tuples. | # LANGUAGE ConstraintKinds , MagicHash #
module ShouldFail where
import GHC.Exts
f :: (Maybe, Either Int)
f = (Just 1, Left 1)
g :: (Int#, Int#)
g = (1#, 2#) |
33ae967d71e0cade39525b61ffe846fdfca8c2d28fd9ecdd4a644209cfae38e1 | donaldsonjw/bigloo | glo_def.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / comptime / Ast / glo_def.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Mon Jun 3 09:17:44 1996 * /
* Last change : Sun Jun 15 10:26:28 2014 ( serrano ) * /
;* ------------------------------------------------------------- */
;* This module implement the functions used to def (define) a */
;* global variable (i.e. in the module language compilation). */
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module ast_glo-def
(include "Tools/trace.sch")
(import type_type
backend_backend
ast_var
ast_node
ast_env
ast_ident
ast_glo-decl
ast_remove
type_env
type_cache
tools_args
tools_error
tools_shape
tools_location
tools_dsssl
object_class
engine_param)
(export (def-global-sfun-no-warning!::global id::symbol
args::obj
locals::obj
module::symbol
import::symbol
src::obj
removable::symbol
body)
(def-global-sfun!::global id::symbol
args::obj
locals::obj
module::symbol
import::symbol
src::obj
removable::symbol
body)
(def-global-svar!::global id::symbol
module::symbol
src::obj
removable::symbol)
(def-global-scnst!::global id::symbol
module::symbol
node
class::symbol
loc)
(check-method-definition::bool id args locals src)))
;*---------------------------------------------------------------------*/
;* def-global-sfun-no-warning! ... */
;* ------------------------------------------------------------- */
;* This function is a simple interface for DEF-GLOBAL-SFUN. It */
;* prevent the global declaration from emitting warning. */
;*---------------------------------------------------------------------*/
(define (def-global-sfun-no-warning! id args loc mod class src-exp rem node)
(let ((warning (bigloo-warning)))
(bigloo-warning-set! 0)
(let ((fun (def-global-sfun! id args loc mod class src-exp rem node)))
(bigloo-warning-set! warning)
fun)))
;*---------------------------------------------------------------------*/
;* def-global-sfun! ... */
;* ------------------------------------------------------------- */
;* This function defines a global sfunction. It is used only when */
;* compiling a define expression. */
;*---------------------------------------------------------------------*/
(define (def-global-sfun! id args locals module class src-exp rem node)
(trace (ast 3) "def-global-sfun!: "
(shape id) " " (shape args) " " (shape locals) #\Newline
" src: " src-exp #\Newline
" loc: " (shape (find-location src-exp)) #\newline)
(enter-function id)
(let* ((loc (find-location src-exp))
(id-type (parse-id id loc))
(type-res (cdr id-type))
(id (car id-type))
(import (if (and (>=fx *bdb-debug* 3)
(memq 'bdb (backend-debug-support (the-backend))))
'export
'static))
(old-global (find-global/module id module))
(global (cond
((not (global? old-global))
(declare-global-sfun! id #f args module
import class src-exp #f))
(else
(check-sfun-definition old-global type-res
args locals class src-exp))))
(def-loc (find-location src-exp)))
(if (sfun? (global-value global))
;; if global-value is not an sfun then it means that
;; check-sfun-definition has failed and so there is an error
;; (already reported) that will stop the compilation. we just
;; return the global variable without any additional check.
(begin
;; we set the type of the function
(most-defined-type! global type-res)
;; and the type of the formals
(if (=fx (length locals)
(length (sfun-args (global-value global))))
(let ((types (map (lambda (a)
(cond
((local? a)
(local-type a))
((type? a)
a)
(else
(internal-error
"check-method-definition"
"unexpected generic arg"
(shape a)))))
(sfun-args (global-value global)))))
(for-each most-defined-type! locals types)))
;; we set the removable field
(remove-var-from! rem global)
;; we set the body field
(sfun-body-set! (global-value global) node)
;; we set the arg field
(sfun-args-set! (global-value global) locals)
;; we set the define location for this function
(sfun-loc-set! (global-value global) def-loc)
;; and we return the global
(leave-function)))
global))
;*---------------------------------------------------------------------*/
;* check-sfun-definition ... */
;*---------------------------------------------------------------------*/
(define (check-sfun-definition::global old type-res args locals class src-exp)
(trace (ast 3) "check-sfun-definition: " (shape old) " "
(shape args) " " (shape locals) #\newline)
(let ((old-value (global-value old)))
(cond
((not (sfun? old-value))
(mismatch-error old src-exp "(not declared as function)"))
((not (eq? (sfun-class old-value) class))
(mismatch-error old src-exp "(declared as function of another class)"))
((not (=fx (sfun-arity old-value) (global-arity args)))
(mismatch-error old src-exp "(arity differs)"))
((not (compatible-type? (eq? 'sgfun class)
type-res
(global-type old)))
(mismatch-error old
src-exp
"(incompatible function type result)"))
((dsssl-prototype? args)
(cond
((dsssl-optional-only-prototype? args)
(if (equal? (dsssl-optionals args) (sfun-optionals old-value))
old
(mismatch-error
old src-exp
"(incompatible DSSSL #!optional prototype)")))
((dsssl-key-only-prototype? args)
(if (equal? (dsssl-keys args) (sfun-keys old-value))
old
(mismatch-error
old src-exp
"(incompatible DSSSL #!key prototype)")))
((not (equal? (sfun-dsssl-keywords old-value)
(dsssl-formals args)))
(mismatch-error old src-exp "(incompatible Dsssl prototype)"))))
(else
(let loop ((locals locals)
(types (map (lambda (a)
(cond
((local? a)
(local-type a))
((type? a)
a)
(else
(internal-error "check-method-definition"
"unexpected generic arg"
(shape a)))))
(sfun-args old-value))))
(cond
((null? locals)
;; we save the definition for a better location in
;; the source file.
(if (null? types)
(global-src-set! old src-exp)
(mismatch-error old src-exp "(arity differs)")))
((or (null? types)
(not (compatible-type? #f
(local-type (car locals))
(car types))))
(mismatch-error old src-exp "(incompatible formal type)"))
(else
(loop (cdr locals) (cdr types)))))))
old))
;*---------------------------------------------------------------------*/
;* def-global-scnst! ... */
;*---------------------------------------------------------------------*/
(define (def-global-scnst! id module node class loc)
(enter-function id)
(let* ((id-type (parse-id id loc))
(id-id (car id-type))
(old-global (find-global/module id-id module))
(global (declare-global-scnst! id #f module
'static node class loc)))
;; we set the removable field
(remove-var-from! 'now global)
;; and we return the global
(leave-function)
global))
;*---------------------------------------------------------------------*/
;* def-global-svar! ... */
;*---------------------------------------------------------------------*/
(define (def-global-svar! id module src-exp rem)
(let* ((loc (find-location src-exp))
(id-type (parse-id id loc))
(id-id (car id-type))
(old-global (find-global/module id-id module))
(import (if (and (>=fx *bdb-debug* 3)
(memq 'bdb (backend-debug-support (the-backend))))
'export
'static))
(type (let ((type (cdr id-type)))
;; we check that global exported variable are defined
;; without type or with the obj type.
(if (not (eq? (type-class type) 'bigloo))
(user-error id-id
"Illegal type for global variable"
(shape type))
type)))
(global (cond
((not (global? old-global))
(declare-global-svar! id #f module
import src-exp #f))
(else
(check-svar-definition old-global type src-exp))))
(def-loc (find-location src-exp)))
;; we set the type of the variable
(most-defined-type! global type)
;; we set the location
(if (svar? (global-value global))
;; because of errors `global-value' may not be an svar
(svar-loc-set! (global-value global) def-loc))
;; we set the removable field
(remove-var-from! rem global)
global))
;*---------------------------------------------------------------------*/
;* check-svar-definition ... */
;*---------------------------------------------------------------------*/
(define (check-svar-definition::global old type src-exp)
(let ((old-value (global-value old)))
(cond
((not (svar? old-value))
(mismatch-error old src-exp "(not declared as a variable)"))
((not (compatible-type? #f type (global-type old)))
(mismatch-error old src-exp "(incompatible variable type)"))
(else
old))))
;*---------------------------------------------------------------------*/
;* compatible-type? ... */
;*---------------------------------------------------------------------*/
(define (compatible-type? sub? new::type old::type)
(or (eq? new *_*)
(eq? old new)
(and sub?
(or (type-subclass? new old)
(and (tclass? new) (eq? old *obj*))))))
;*---------------------------------------------------------------------*/
;* mismatch-error ... */
;*---------------------------------------------------------------------*/
(define (mismatch-error::global global::global src-exp . add-msg)
(let ((msg "Prototype and definition don't match"))
(user-error (if (pair? add-msg)
(string-append msg " " (car add-msg))
msg)
(shape (global-src global))
src-exp
global)))
;*---------------------------------------------------------------------*/
;* most-defined-type! ... */
;*---------------------------------------------------------------------*/
(define (most-defined-type! var::variable new-type::type)
(let ((old-type (variable-type var)))
(if (eq? old-type *_*)
(variable-type-set! var new-type))))
;*---------------------------------------------------------------------*/
;* check-method-definition ... */
;*---------------------------------------------------------------------*/
(define (check-method-definition id args locals src)
(let* ((loc (find-location src))
(type-res (type-of-id id loc))
(method-id (id-of-id id loc))
(generic (find-global id)))
(cond
((null? args)
(user-error id (shape src) "argument missing")
#t)
((not (global? generic))
;; this error will be signaled later hence for now, we just
;; return #t, as for no error
#t)
(else
(let ((generic-value (global-value generic)))
(cond
((not (sfun? generic-value))
(mismatch-error generic src "(generic not found for method)")
#f)
((not (eq? (sfun-class generic-value) 'sgfun))
(mismatch-error generic src "(generic not found for method)")
#f)
((not (=fx (sfun-arity generic-value) (global-arity args)))
(mismatch-error generic src "(arity differs)")
#f)
((not (compatible-type? #t type-res (global-type generic)))
(mismatch-error generic
src
"(incompatible function type result)")
#f)
((let loop ((locals locals)
(types (map (lambda (a)
(cond
((local? a)
(local-type a))
((type? a)
a)
(else
(internal-error
"check-method-definition"
"unexpected generic arg"
(shape a)))))
(sfun-args generic-value)))
(sub? #t))
(cond
((null? locals)
#t)
((null? types)
(mismatch-error generic
src
"(incompatible formal type)"))
((not (compatible-type? sub?
(local-type (car locals))
(car types)))
(mismatch-error generic
src
"(incompatible formal type)")
#f)
(else
(loop (cdr locals)
(cdr types)
#f)))))
(else
#t)))))))
| null | https://raw.githubusercontent.com/donaldsonjw/bigloo/a4d06e409d0004e159ce92b9908719510a18aed5/comptime/Ast/glo_def.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
* This module implement the functions used to def (define) a */
* global variable (i.e. in the module language compilation). */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* def-global-sfun-no-warning! ... */
* ------------------------------------------------------------- */
* This function is a simple interface for DEF-GLOBAL-SFUN. It */
* prevent the global declaration from emitting warning. */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* def-global-sfun! ... */
* ------------------------------------------------------------- */
* This function defines a global sfunction. It is used only when */
* compiling a define expression. */
*---------------------------------------------------------------------*/
if global-value is not an sfun then it means that
check-sfun-definition has failed and so there is an error
(already reported) that will stop the compilation. we just
return the global variable without any additional check.
we set the type of the function
and the type of the formals
we set the removable field
we set the body field
we set the arg field
we set the define location for this function
and we return the global
*---------------------------------------------------------------------*/
* check-sfun-definition ... */
*---------------------------------------------------------------------*/
we save the definition for a better location in
the source file.
*---------------------------------------------------------------------*/
* def-global-scnst! ... */
*---------------------------------------------------------------------*/
we set the removable field
and we return the global
*---------------------------------------------------------------------*/
* def-global-svar! ... */
*---------------------------------------------------------------------*/
we check that global exported variable are defined
without type or with the obj type.
we set the type of the variable
we set the location
because of errors `global-value' may not be an svar
we set the removable field
*---------------------------------------------------------------------*/
* check-svar-definition ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* compatible-type? ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* mismatch-error ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* most-defined-type! ... */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* check-method-definition ... */
*---------------------------------------------------------------------*/
this error will be signaled later hence for now, we just
return #t, as for no error | * serrano / prgm / project / bigloo / comptime / Ast / glo_def.scm * /
* Author : * /
* Creation : Mon Jun 3 09:17:44 1996 * /
* Last change : Sun Jun 15 10:26:28 2014 ( serrano ) * /
(module ast_glo-def
(include "Tools/trace.sch")
(import type_type
backend_backend
ast_var
ast_node
ast_env
ast_ident
ast_glo-decl
ast_remove
type_env
type_cache
tools_args
tools_error
tools_shape
tools_location
tools_dsssl
object_class
engine_param)
(export (def-global-sfun-no-warning!::global id::symbol
args::obj
locals::obj
module::symbol
import::symbol
src::obj
removable::symbol
body)
(def-global-sfun!::global id::symbol
args::obj
locals::obj
module::symbol
import::symbol
src::obj
removable::symbol
body)
(def-global-svar!::global id::symbol
module::symbol
src::obj
removable::symbol)
(def-global-scnst!::global id::symbol
module::symbol
node
class::symbol
loc)
(check-method-definition::bool id args locals src)))
(define (def-global-sfun-no-warning! id args loc mod class src-exp rem node)
(let ((warning (bigloo-warning)))
(bigloo-warning-set! 0)
(let ((fun (def-global-sfun! id args loc mod class src-exp rem node)))
(bigloo-warning-set! warning)
fun)))
(define (def-global-sfun! id args locals module class src-exp rem node)
(trace (ast 3) "def-global-sfun!: "
(shape id) " " (shape args) " " (shape locals) #\Newline
" src: " src-exp #\Newline
" loc: " (shape (find-location src-exp)) #\newline)
(enter-function id)
(let* ((loc (find-location src-exp))
(id-type (parse-id id loc))
(type-res (cdr id-type))
(id (car id-type))
(import (if (and (>=fx *bdb-debug* 3)
(memq 'bdb (backend-debug-support (the-backend))))
'export
'static))
(old-global (find-global/module id module))
(global (cond
((not (global? old-global))
(declare-global-sfun! id #f args module
import class src-exp #f))
(else
(check-sfun-definition old-global type-res
args locals class src-exp))))
(def-loc (find-location src-exp)))
(if (sfun? (global-value global))
(begin
(most-defined-type! global type-res)
(if (=fx (length locals)
(length (sfun-args (global-value global))))
(let ((types (map (lambda (a)
(cond
((local? a)
(local-type a))
((type? a)
a)
(else
(internal-error
"check-method-definition"
"unexpected generic arg"
(shape a)))))
(sfun-args (global-value global)))))
(for-each most-defined-type! locals types)))
(remove-var-from! rem global)
(sfun-body-set! (global-value global) node)
(sfun-args-set! (global-value global) locals)
(sfun-loc-set! (global-value global) def-loc)
(leave-function)))
global))
(define (check-sfun-definition::global old type-res args locals class src-exp)
(trace (ast 3) "check-sfun-definition: " (shape old) " "
(shape args) " " (shape locals) #\newline)
(let ((old-value (global-value old)))
(cond
((not (sfun? old-value))
(mismatch-error old src-exp "(not declared as function)"))
((not (eq? (sfun-class old-value) class))
(mismatch-error old src-exp "(declared as function of another class)"))
((not (=fx (sfun-arity old-value) (global-arity args)))
(mismatch-error old src-exp "(arity differs)"))
((not (compatible-type? (eq? 'sgfun class)
type-res
(global-type old)))
(mismatch-error old
src-exp
"(incompatible function type result)"))
((dsssl-prototype? args)
(cond
((dsssl-optional-only-prototype? args)
(if (equal? (dsssl-optionals args) (sfun-optionals old-value))
old
(mismatch-error
old src-exp
"(incompatible DSSSL #!optional prototype)")))
((dsssl-key-only-prototype? args)
(if (equal? (dsssl-keys args) (sfun-keys old-value))
old
(mismatch-error
old src-exp
"(incompatible DSSSL #!key prototype)")))
((not (equal? (sfun-dsssl-keywords old-value)
(dsssl-formals args)))
(mismatch-error old src-exp "(incompatible Dsssl prototype)"))))
(else
(let loop ((locals locals)
(types (map (lambda (a)
(cond
((local? a)
(local-type a))
((type? a)
a)
(else
(internal-error "check-method-definition"
"unexpected generic arg"
(shape a)))))
(sfun-args old-value))))
(cond
((null? locals)
(if (null? types)
(global-src-set! old src-exp)
(mismatch-error old src-exp "(arity differs)")))
((or (null? types)
(not (compatible-type? #f
(local-type (car locals))
(car types))))
(mismatch-error old src-exp "(incompatible formal type)"))
(else
(loop (cdr locals) (cdr types)))))))
old))
(define (def-global-scnst! id module node class loc)
(enter-function id)
(let* ((id-type (parse-id id loc))
(id-id (car id-type))
(old-global (find-global/module id-id module))
(global (declare-global-scnst! id #f module
'static node class loc)))
(remove-var-from! 'now global)
(leave-function)
global))
(define (def-global-svar! id module src-exp rem)
(let* ((loc (find-location src-exp))
(id-type (parse-id id loc))
(id-id (car id-type))
(old-global (find-global/module id-id module))
(import (if (and (>=fx *bdb-debug* 3)
(memq 'bdb (backend-debug-support (the-backend))))
'export
'static))
(type (let ((type (cdr id-type)))
(if (not (eq? (type-class type) 'bigloo))
(user-error id-id
"Illegal type for global variable"
(shape type))
type)))
(global (cond
((not (global? old-global))
(declare-global-svar! id #f module
import src-exp #f))
(else
(check-svar-definition old-global type src-exp))))
(def-loc (find-location src-exp)))
(most-defined-type! global type)
(if (svar? (global-value global))
(svar-loc-set! (global-value global) def-loc))
(remove-var-from! rem global)
global))
(define (check-svar-definition::global old type src-exp)
(let ((old-value (global-value old)))
(cond
((not (svar? old-value))
(mismatch-error old src-exp "(not declared as a variable)"))
((not (compatible-type? #f type (global-type old)))
(mismatch-error old src-exp "(incompatible variable type)"))
(else
old))))
(define (compatible-type? sub? new::type old::type)
(or (eq? new *_*)
(eq? old new)
(and sub?
(or (type-subclass? new old)
(and (tclass? new) (eq? old *obj*))))))
(define (mismatch-error::global global::global src-exp . add-msg)
(let ((msg "Prototype and definition don't match"))
(user-error (if (pair? add-msg)
(string-append msg " " (car add-msg))
msg)
(shape (global-src global))
src-exp
global)))
(define (most-defined-type! var::variable new-type::type)
(let ((old-type (variable-type var)))
(if (eq? old-type *_*)
(variable-type-set! var new-type))))
(define (check-method-definition id args locals src)
(let* ((loc (find-location src))
(type-res (type-of-id id loc))
(method-id (id-of-id id loc))
(generic (find-global id)))
(cond
((null? args)
(user-error id (shape src) "argument missing")
#t)
((not (global? generic))
#t)
(else
(let ((generic-value (global-value generic)))
(cond
((not (sfun? generic-value))
(mismatch-error generic src "(generic not found for method)")
#f)
((not (eq? (sfun-class generic-value) 'sgfun))
(mismatch-error generic src "(generic not found for method)")
#f)
((not (=fx (sfun-arity generic-value) (global-arity args)))
(mismatch-error generic src "(arity differs)")
#f)
((not (compatible-type? #t type-res (global-type generic)))
(mismatch-error generic
src
"(incompatible function type result)")
#f)
((let loop ((locals locals)
(types (map (lambda (a)
(cond
((local? a)
(local-type a))
((type? a)
a)
(else
(internal-error
"check-method-definition"
"unexpected generic arg"
(shape a)))))
(sfun-args generic-value)))
(sub? #t))
(cond
((null? locals)
#t)
((null? types)
(mismatch-error generic
src
"(incompatible formal type)"))
((not (compatible-type? sub?
(local-type (car locals))
(car types)))
(mismatch-error generic
src
"(incompatible formal type)")
#f)
(else
(loop (cdr locals)
(cdr types)
#f)))))
(else
#t)))))))
|
6c51de76db3a5cc11931b219507206fa8a53300fe08bc8ae2664c0fe75efba78 | spurious/sagittarius-scheme-mirror | parser.scm | (import (rnrs)
(text yaml parser)
(text yaml nodes)
(srfi :127)
(srfi :39)
(srfi :64))
(test-begin "YAML parser")
(define (test-yaml-parser expected input)
(test-equal input expected
(map yaml-document->canonical-sexp
(parse-yaml (open-string-input-port input))))
(test-equal input expected
(map yaml-document->canonical-sexp
(map canonical-sexp->yaml-document
(map yaml-document->canonical-sexp
(parse-yaml (open-string-input-port input)))))))
(test-yaml-parser '((*yaml*
(*directives* (%YAML 1 1))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "bar")
("tag:yaml.org,2002:int" . "1234")
("tag:yaml.org,2002:null" . "~"))))))
"%YAML 1.1\n\
---\n\
foo:\n \
- bar\n \
- 1234\n \
- ~")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "bar"))))
" - bar")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo"))))
"[ foo ]")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))))
"[ foo, bar ]")
;; extra comma
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo"))))
"[ foo, ]")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))))
"[ foo, bar, ]")
;; mapping
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))))
"{ foo: bar }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))
(("tag:yaml.org,2002:str" . "buz")
("tag:yaml.org,2002:str" . "bla")))))
"{ foo: bar, buz: bla }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))))
"{ foo: bar, }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))
(("tag:yaml.org,2002:str" . "buz")
("tag:yaml.org,2002:str" . "bla")))))
"{ foo: bar, buz: bla, }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:null" . "")))))
"foo:")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:null" . "")
("tag:yaml.org,2002:null" . "")))))
"?")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))))
"---\n\
!!map {\n \
? !!str \"foo\"\n \
: !!str \"bar\",\n\
}")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "one")
("tag:yaml.org,2002:int" . "1")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "two")
("tag:yaml.org,2002:int" . "2")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "three")
("tag:yaml.org,2002:int" . "3"))))))
"[ one: 1, two: 2, three : 3 ]")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "one")
("tag:yaml.org,2002:null" . "")))))
"{ one: , }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "generic")
("tag:yaml.org,2002:binary" .
"R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=")))))
"generic: !!binary |
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=")
;; corner cases
;; we support null scalar only on explicit document (differ from PyYAML)
(test-yaml-parser '() "")
(test-yaml-parser '((*yaml* ("tag:yaml.org,2002:null" . ""))) "---")
;; resolver tests
;; float
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:float" . "1.2")
("tag:yaml.org,2002:float" . "6.8523015e+5")
("tag:yaml.org,2002:float" . "685.230_15e+03")
("tag:yaml.org,2002:float" . "685_230.15")
("tag:yaml.org,2002:float" . "190:20:30.15")
("tag:yaml.org,2002:float" . "+.inf")
("tag:yaml.org,2002:str" . "+.InF")
("tag:yaml.org,2002:float" . ".nan")
("tag:yaml.org,2002:str" . ".Nan"))))
"- 1.2\n\
- 6.8523015e+5\n\
- 685.230_15e+03\n\
- 685_230.15\n\
- 190:20:30.15\n\
- +.inf\n\
- +.InF # non fload\n\
- .nan\n\
- .Nan # non float")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:bool" . "ON")
("tag:yaml.org,2002:bool" . "OFF")
("tag:yaml.org,2002:str" . "y")
("tag:yaml.org,2002:str" . "n")
("tag:yaml.org,2002:bool" . "Yes")
("tag:yaml.org,2002:bool" . "No")
("tag:yaml.org,2002:bool" . "True")
("tag:yaml.org,2002:bool" . "False")
("tag:yaml.org,2002:str" . "TrUe"))))
"- ON\n\
- OFF\n\
- y\n\
- n\n\
- Yes\n\
- No\n\
- True\n\
- False\n\
- TrUe")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:int" . "685230")
("tag:yaml.org,2002:int" . "+685_230")
("tag:yaml.org,2002:int" . "02472256")
("tag:yaml.org,2002:int" . "0x_0A_74_AE")
("tag:yaml.org,2002:int" . "0b1010_0111_0100_1010_1110")
("tag:yaml.org,2002:int" . "190:20:30"))))
"- 685230\n\
- +685_230\n\
- 02472256\n\
- 0x_0A_74_AE\n\
- 0b1010_0111_0100_1010_1110\n\
- 190:20:30")
(test-yaml-parser '((*yaml* ("tag:yaml.org,2002:merge" . "<<"))) "<<")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:null" . "~")
("tag:yaml.org,2002:null" . "null")
("tag:yaml.org,2002:null" . "")
("tag:yaml.org,2002:null" . "Null")
("tag:yaml.org,2002:null" . "NULL")
("tag:yaml.org,2002:str" . "NuLL"))))
"- ~\n\
- null\n\
- \n\
- Null\n\
- NULL\n\
- NuLL")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:timestamp" .
"2001-12-15T02:59:43.1Z")
("tag:yaml.org,2002:timestamp" .
"2001-12-14t21:59:43.10-05:00")
("tag:yaml.org,2002:timestamp" .
"2001-12-14 21:59:43.10 -5")
("tag:yaml.org,2002:timestamp" . "2001-12-15 2:59:43.10")
("tag:yaml.org,2002:timestamp" . "2002-12-14"))))
"- 2001-12-15T02:59:43.1Z\n\
- 2001-12-14t21:59:43.10-05:00\n\
- 2001-12-14 21:59:43.10 -5\n\
- 2001-12-15 2:59:43.10\n\
- 2002-12-14")
(test-yaml-parser '((*yaml* ("tag:yaml.org,2002:value" . "="))) "=")
;; omap etc.
(test-yaml-parser '((*yaml*
(*directives* (%YAML 1 2))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
#("tag:yaml.org,2002:omap"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "boo")
("tag:yaml.org,2002:str" . "buz"))))))))
"%YAML 1.2\n\
---\n\
foo: !!omap\n\
- foo: bar\n\
- boo: buz")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:omap"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "one")
("tag:yaml.org,2002:int" . "1")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "two")
("tag:yaml.org,2002:int" . "2")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "three")
("tag:yaml.org,2002:int" . "3"))))))
"!!omap [ one: 1, two: 2, three : 3 ]")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "Block tasks")
#("tag:yaml.org,2002:pairs"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with team.")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with boss.")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "break")
("tag:yaml.org,2002:str" . "lunch.")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with client."))))))))
"Block tasks: !!pairs\n \
- meeting: with team.\n \
- meeting: with boss.\n \
- break: lunch.\n \
- meeting: with client.")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:pairs"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with team")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with boss"))))))
"!!pairs [ meeting: with team, meeting: with boss ]")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "baseball players")
("tag:yaml.org,2002:set"
(("tag:yaml.org,2002:str" . "Mark McGwire")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "Sammy Sosa")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "Ken Griffey")
("tag:yaml.org,2002:null" . "")))))))
"baseball players: !!set\n \
? Mark McGwire\n \
? Sammy Sosa\n \
? Ken Griffey")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:set"
(("tag:yaml.org,2002:str" . "Boston Red Sox")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "Detroit Tigers")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "New York Yankees")
("tag:yaml.org,2002:null" . "")))))
"!!set { Boston Red Sox, Detroit Tigers, New York Yankees }")
TODO test parser errors
(test-end)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/tests/text/yaml/parser.scm | scheme | extra comma
mapping
corner cases
we support null scalar only on explicit document (differ from PyYAML)
resolver tests
float
omap etc. | (import (rnrs)
(text yaml parser)
(text yaml nodes)
(srfi :127)
(srfi :39)
(srfi :64))
(test-begin "YAML parser")
(define (test-yaml-parser expected input)
(test-equal input expected
(map yaml-document->canonical-sexp
(parse-yaml (open-string-input-port input))))
(test-equal input expected
(map yaml-document->canonical-sexp
(map canonical-sexp->yaml-document
(map yaml-document->canonical-sexp
(parse-yaml (open-string-input-port input)))))))
(test-yaml-parser '((*yaml*
(*directives* (%YAML 1 1))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "bar")
("tag:yaml.org,2002:int" . "1234")
("tag:yaml.org,2002:null" . "~"))))))
"%YAML 1.1\n\
---\n\
foo:\n \
- bar\n \
- 1234\n \
- ~")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "bar"))))
" - bar")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo"))))
"[ foo ]")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))))
"[ foo, bar ]")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo"))))
"[ foo, ]")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))))
"[ foo, bar, ]")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))))
"{ foo: bar }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))
(("tag:yaml.org,2002:str" . "buz")
("tag:yaml.org,2002:str" . "bla")))))
"{ foo: bar, buz: bla }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))))
"{ foo: bar, }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar"))
(("tag:yaml.org,2002:str" . "buz")
("tag:yaml.org,2002:str" . "bla")))))
"{ foo: bar, buz: bla, }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:null" . "")))))
"foo:")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:null" . "")
("tag:yaml.org,2002:null" . "")))))
"?")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))))
"---\n\
!!map {\n \
? !!str \"foo\"\n \
: !!str \"bar\",\n\
}")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "one")
("tag:yaml.org,2002:int" . "1")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "two")
("tag:yaml.org,2002:int" . "2")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "three")
("tag:yaml.org,2002:int" . "3"))))))
"[ one: 1, two: 2, three : 3 ]")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "one")
("tag:yaml.org,2002:null" . "")))))
"{ one: , }")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "generic")
("tag:yaml.org,2002:binary" .
"R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=")))))
"generic: !!binary |
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=")
(test-yaml-parser '() "")
(test-yaml-parser '((*yaml* ("tag:yaml.org,2002:null" . ""))) "---")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:float" . "1.2")
("tag:yaml.org,2002:float" . "6.8523015e+5")
("tag:yaml.org,2002:float" . "685.230_15e+03")
("tag:yaml.org,2002:float" . "685_230.15")
("tag:yaml.org,2002:float" . "190:20:30.15")
("tag:yaml.org,2002:float" . "+.inf")
("tag:yaml.org,2002:str" . "+.InF")
("tag:yaml.org,2002:float" . ".nan")
("tag:yaml.org,2002:str" . ".Nan"))))
"- 1.2\n\
- 6.8523015e+5\n\
- 685.230_15e+03\n\
- 685_230.15\n\
- 190:20:30.15\n\
- +.inf\n\
- +.InF # non fload\n\
- .nan\n\
- .Nan # non float")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:bool" . "ON")
("tag:yaml.org,2002:bool" . "OFF")
("tag:yaml.org,2002:str" . "y")
("tag:yaml.org,2002:str" . "n")
("tag:yaml.org,2002:bool" . "Yes")
("tag:yaml.org,2002:bool" . "No")
("tag:yaml.org,2002:bool" . "True")
("tag:yaml.org,2002:bool" . "False")
("tag:yaml.org,2002:str" . "TrUe"))))
"- ON\n\
- OFF\n\
- y\n\
- n\n\
- Yes\n\
- No\n\
- True\n\
- False\n\
- TrUe")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:int" . "685230")
("tag:yaml.org,2002:int" . "+685_230")
("tag:yaml.org,2002:int" . "02472256")
("tag:yaml.org,2002:int" . "0x_0A_74_AE")
("tag:yaml.org,2002:int" . "0b1010_0111_0100_1010_1110")
("tag:yaml.org,2002:int" . "190:20:30"))))
"- 685230\n\
- +685_230\n\
- 02472256\n\
- 0x_0A_74_AE\n\
- 0b1010_0111_0100_1010_1110\n\
- 190:20:30")
(test-yaml-parser '((*yaml* ("tag:yaml.org,2002:merge" . "<<"))) "<<")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:null" . "~")
("tag:yaml.org,2002:null" . "null")
("tag:yaml.org,2002:null" . "")
("tag:yaml.org,2002:null" . "Null")
("tag:yaml.org,2002:null" . "NULL")
("tag:yaml.org,2002:str" . "NuLL"))))
"- ~\n\
- null\n\
- \n\
- Null\n\
- NULL\n\
- NuLL")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:seq"
("tag:yaml.org,2002:timestamp" .
"2001-12-15T02:59:43.1Z")
("tag:yaml.org,2002:timestamp" .
"2001-12-14t21:59:43.10-05:00")
("tag:yaml.org,2002:timestamp" .
"2001-12-14 21:59:43.10 -5")
("tag:yaml.org,2002:timestamp" . "2001-12-15 2:59:43.10")
("tag:yaml.org,2002:timestamp" . "2002-12-14"))))
"- 2001-12-15T02:59:43.1Z\n\
- 2001-12-14t21:59:43.10-05:00\n\
- 2001-12-14 21:59:43.10 -5\n\
- 2001-12-15 2:59:43.10\n\
- 2002-12-14")
(test-yaml-parser '((*yaml* ("tag:yaml.org,2002:value" . "="))) "=")
(test-yaml-parser '((*yaml*
(*directives* (%YAML 1 2))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
#("tag:yaml.org,2002:omap"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "foo")
("tag:yaml.org,2002:str" . "bar")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "boo")
("tag:yaml.org,2002:str" . "buz"))))))))
"%YAML 1.2\n\
---\n\
foo: !!omap\n\
- foo: bar\n\
- boo: buz")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:omap"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "one")
("tag:yaml.org,2002:int" . "1")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "two")
("tag:yaml.org,2002:int" . "2")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "three")
("tag:yaml.org,2002:int" . "3"))))))
"!!omap [ one: 1, two: 2, three : 3 ]")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "Block tasks")
#("tag:yaml.org,2002:pairs"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with team.")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with boss.")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "break")
("tag:yaml.org,2002:str" . "lunch.")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with client."))))))))
"Block tasks: !!pairs\n \
- meeting: with team.\n \
- meeting: with boss.\n \
- break: lunch.\n \
- meeting: with client.")
(test-yaml-parser '((*yaml*
#("tag:yaml.org,2002:pairs"
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with team")))
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "meeting")
("tag:yaml.org,2002:str" . "with boss"))))))
"!!pairs [ meeting: with team, meeting: with boss ]")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:map"
(("tag:yaml.org,2002:str" . "baseball players")
("tag:yaml.org,2002:set"
(("tag:yaml.org,2002:str" . "Mark McGwire")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "Sammy Sosa")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "Ken Griffey")
("tag:yaml.org,2002:null" . "")))))))
"baseball players: !!set\n \
? Mark McGwire\n \
? Sammy Sosa\n \
? Ken Griffey")
(test-yaml-parser '((*yaml*
("tag:yaml.org,2002:set"
(("tag:yaml.org,2002:str" . "Boston Red Sox")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "Detroit Tigers")
("tag:yaml.org,2002:null" . ""))
(("tag:yaml.org,2002:str" . "New York Yankees")
("tag:yaml.org,2002:null" . "")))))
"!!set { Boston Red Sox, Detroit Tigers, New York Yankees }")
TODO test parser errors
(test-end)
|
22673a37ae934c222572e85c14e4d75f2bc63df0e0df075a2b60839907ae78e6 | roddyyaga/opium-heroku-example | main.ml | open Opium
let handler req =
Printf.sprintf "Hello, %s!\n" (Router.param req "name")
|> Response.of_plain_text |> Lwt.return
let port =
Sys.getenv_opt "PORT" |> Option.value ~default:"3000" |> int_of_string
let () =
Logs.set_reporter (Logs_fmt.reporter ());
Logs.set_level (Some Logs.Info)
let () =
App.empty |> App.port port
|> App.middleware Middleware.logger
|> App.get "/hello/:name" handler
|> App.run_command
| null | https://raw.githubusercontent.com/roddyyaga/opium-heroku-example/30e0a441944b6d030d16a6591ffc96513a37b2d3/bin/main.ml | ocaml | open Opium
let handler req =
Printf.sprintf "Hello, %s!\n" (Router.param req "name")
|> Response.of_plain_text |> Lwt.return
let port =
Sys.getenv_opt "PORT" |> Option.value ~default:"3000" |> int_of_string
let () =
Logs.set_reporter (Logs_fmt.reporter ());
Logs.set_level (Some Logs.Info)
let () =
App.empty |> App.port port
|> App.middleware Middleware.logger
|> App.get "/hello/:name" handler
|> App.run_command
|
|
f87eb3d3286076745dfef023ad22933bc99f8ac1656e875a06c48222dc7637e6 | runeksvendsen/bitcoin-payment-channel | Value.hs | # LANGUAGE FlexibleInstances #
module PaymentChannel.Internal.Class.Value where
import PaymentChannel.Internal.Payment.Types
import PaymentChannel.Internal.Payment
import PaymentChannel.Internal.Receiver.Types
import Bitcoin.Types
class HasValue a where
valueOf :: a -> BtcAmount
instance HasValue SignedPayment where
valueOf SigSinglePair{..} =
btcInValue singleInput - nonDusty (btcAmount singleOutput)
instance HasValue (PayChanState BtcSig) where
valueOf = valueOf . pcsPayment
instance HasValue a => HasValue [a] where
valueOf = sum . map valueOf
| null | https://raw.githubusercontent.com/runeksvendsen/bitcoin-payment-channel/3d2ee56c027571d1a86092c317640e5eae7adde3/src/PaymentChannel/Internal/Class/Value.hs | haskell | # LANGUAGE FlexibleInstances #
module PaymentChannel.Internal.Class.Value where
import PaymentChannel.Internal.Payment.Types
import PaymentChannel.Internal.Payment
import PaymentChannel.Internal.Receiver.Types
import Bitcoin.Types
class HasValue a where
valueOf :: a -> BtcAmount
instance HasValue SignedPayment where
valueOf SigSinglePair{..} =
btcInValue singleInput - nonDusty (btcAmount singleOutput)
instance HasValue (PayChanState BtcSig) where
valueOf = valueOf . pcsPayment
instance HasValue a => HasValue [a] where
valueOf = sum . map valueOf
|
|
eefbe06fa0e93fed996087bfa80f1e2cc0486ebd38b3a6e5b0e6d0a851be42ba | randomseed-io/phone-number | net_code.clj | (ns
^{:doc "Global network calling codes handling for phone-number."
:author "Paweł Wilk"
:added "8.12.4-0"}
phone-number.net-code
(:require [clojure.set]
[phone-number.util :as util])
(:import [com.google.i18n.phonenumbers
PhoneNumberUtil
NumberParseException]))
;;
;; Supported Global Network Calling Codes
;;
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentHashSet}
all
"Set of supported global network calling codes."
(set (.getSupportedGlobalNetworkCallingCodes (util/instance))))
(def ^{:added "8.12.4-0"
:tag clojure.lang.PersistentHashSet}
all-arg
"Set of supported global network calling codes (to be used as arguments)."
all)
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentHashSet}
by-val
"Set of supported values of global network calling codes."
all)
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentHashSet}
by-val-arg
"Set of supported values of global network calling codes (to be used as method arguments)."
all-arg)
(def ^{:added "8.12.4-0"
:tag clojure.lang.PersistentVector}
all-vec
"Vector of all supported global network calling codes."
(vec all))
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentVector}
by-val-vec
"Vector of all supported global network calling codes."
(vec by-val))
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentVector}
all-arg-vec
"Vector of all supported global network calling codes (valid as args)."
(vec all-arg))
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentVector}
by-val-arg-vec
"Vector of all supported global network calling codes (valid as args)."
(vec by-val-arg))
(defn valid?
"Returns true if the given region-specification is a valid region code, false
otherwise."
{:added "8.12.4-0" :tag Boolean}
[^Integer calling-code]
(contains? all calling-code))
(defn valid-arg?
"Returns true if the given region-specification is a valid region code (to be used as
an argument), false otherwise."
{:added "8.12.16-1" :tag Boolean}
[^Integer calling-code]
(contains? all-arg calling-code))
(defn parse
"Parses a network calling code and returns a value that can be supplied to
Libphonenumber methods."
{:added "8.12.4-0" :tag Integer}
([^Integer calling-code]
(assert (valid-arg? calling-code)
(str "Global network calling code " calling-code " is not valid"))
calling-code))
(defn generate-sample
"Generates random global network calling code."
{:added "8.12.4-0" :tag Integer}
([] (rand-nth all-vec))
([^java.util.Random rng] (util/get-rand-nth all-vec rng)))
(defn generate-sample-val
"Generates random global network calling code."
{:added "8.12.16-1" :tag Integer}
([] (rand-nth by-val-vec))
([^java.util.Random rng] (util/get-rand-nth by-val-vec rng)))
(defn generate-arg-sample
"Generates random global network calling code."
{:added "8.12.16-1" :tag Integer}
([] (rand-nth all-arg-vec))
([^java.util.Random rng] (util/get-rand-nth all-arg-vec rng)))
(defn generate-arg-sample-val
"Generates random global network calling code."
{:added "8.12.16-1" :tag Integer}
([] (rand-nth by-val-arg-vec))
([^java.util.Random rng] (util/get-rand-nth by-val-arg-vec rng)))
| null | https://raw.githubusercontent.com/randomseed-io/phone-number/99ac91d5b89f3bca44db4d03b5e27e0999760908/src/phone_number/net_code.clj | clojure |
Supported Global Network Calling Codes
| (ns
^{:doc "Global network calling codes handling for phone-number."
:author "Paweł Wilk"
:added "8.12.4-0"}
phone-number.net-code
(:require [clojure.set]
[phone-number.util :as util])
(:import [com.google.i18n.phonenumbers
PhoneNumberUtil
NumberParseException]))
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentHashSet}
all
"Set of supported global network calling codes."
(set (.getSupportedGlobalNetworkCallingCodes (util/instance))))
(def ^{:added "8.12.4-0"
:tag clojure.lang.PersistentHashSet}
all-arg
"Set of supported global network calling codes (to be used as arguments)."
all)
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentHashSet}
by-val
"Set of supported values of global network calling codes."
all)
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentHashSet}
by-val-arg
"Set of supported values of global network calling codes (to be used as method arguments)."
all-arg)
(def ^{:added "8.12.4-0"
:tag clojure.lang.PersistentVector}
all-vec
"Vector of all supported global network calling codes."
(vec all))
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentVector}
by-val-vec
"Vector of all supported global network calling codes."
(vec by-val))
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentVector}
all-arg-vec
"Vector of all supported global network calling codes (valid as args)."
(vec all-arg))
(def ^{:added "8.12.16-1"
:tag clojure.lang.PersistentVector}
by-val-arg-vec
"Vector of all supported global network calling codes (valid as args)."
(vec by-val-arg))
(defn valid?
"Returns true if the given region-specification is a valid region code, false
otherwise."
{:added "8.12.4-0" :tag Boolean}
[^Integer calling-code]
(contains? all calling-code))
(defn valid-arg?
"Returns true if the given region-specification is a valid region code (to be used as
an argument), false otherwise."
{:added "8.12.16-1" :tag Boolean}
[^Integer calling-code]
(contains? all-arg calling-code))
(defn parse
"Parses a network calling code and returns a value that can be supplied to
Libphonenumber methods."
{:added "8.12.4-0" :tag Integer}
([^Integer calling-code]
(assert (valid-arg? calling-code)
(str "Global network calling code " calling-code " is not valid"))
calling-code))
(defn generate-sample
"Generates random global network calling code."
{:added "8.12.4-0" :tag Integer}
([] (rand-nth all-vec))
([^java.util.Random rng] (util/get-rand-nth all-vec rng)))
(defn generate-sample-val
"Generates random global network calling code."
{:added "8.12.16-1" :tag Integer}
([] (rand-nth by-val-vec))
([^java.util.Random rng] (util/get-rand-nth by-val-vec rng)))
(defn generate-arg-sample
"Generates random global network calling code."
{:added "8.12.16-1" :tag Integer}
([] (rand-nth all-arg-vec))
([^java.util.Random rng] (util/get-rand-nth all-arg-vec rng)))
(defn generate-arg-sample-val
"Generates random global network calling code."
{:added "8.12.16-1" :tag Integer}
([] (rand-nth by-val-arg-vec))
([^java.util.Random rng] (util/get-rand-nth by-val-arg-vec rng)))
|
999ca6bac07e863168f33b5136b05997e6d56a1067f490402743cc2a82e89d5c | sigscale/snmp-collector | snmp_collector_rest_accepted_content.erl | %%% snmp_collector_rest_accepted_content.erl
%%% vim: ts=3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2016 - 2019 SigScale Global Inc.
%%% @end
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%% -2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
-module(snmp_collector_rest_accepted_content).
-copyright('Copyright (c) 2016 - 2019 SigScale Global Inc.').
-export([do/1]).
-include_lib("inets/include/httpd.hrl").
-spec do(ModData) -> Result when
ModData :: #mod{},
Result :: {proceed, OldData} | {proceed, NewData} | {break, NewData} | done,
OldData :: list(),
NewData :: [{response,{StatusCode,Body}}] | [{response,{response,Head,Body}}]
| [{response,{already_sent,StatusCode,Size}}],
StatusCode :: integer(),
Body :: iolist() | nobody | {Fun, Arg},
Head :: [HeaderOption],
HeaderOption :: {Option, Value} | {code, StatusCode},
Option :: accept_ranges | allow
| cache_control | content_MD5
| content_encoding | content_language
| content_length | content_location
| content_range | content_type | date
| etag | expires | last_modified
| location | pragma | retry_after
| server | trailer | transfer_encoding,
Value :: string(),
Size :: term(),
Fun :: fun((Arg) -> sent| close | Body),
Arg :: [term()].
% @doc Erlang web server API callback function .
do(#mod{method = Method, parsed_header = Headers, request_uri = Uri,
data = Data} = _ModData) ->
case proplists:get_value(status, Data) of
{_StatusCode, _PhraseArgs, _Reason} ->
{proceed, Data};
undefined ->
case proplists:get_value(response, Data) of
undefined ->
Path = http_uri:decode(Uri),
case string:tokens(Path, "/?") of
["snmp", "v1", "mibs" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_mib, Data);
["partyManagement", "v1", "individual" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_user, Data);
["eventManagement", "v1", "event" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_event, Data);
["snmp", "v1", "log", "http" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_http, Data);
["counters", "v1", "snmp" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_counter, Data);
_ ->
{proceed, Data}
end;
_ ->
{proceed, Data}
end
end.
%% @hidden
check_content_type_header(Headers, Method, Module, Data) ->
case lists:keyfind("content-type", 1, Headers) of
false when Method == "DELETE"; Method == "GET" ->
check_accept_header(Headers, Module, [{resource, Module} | Data]);
{_, []} when Method == "DELETE"; Method == "GET" ->
check_accept_header(Headers, Module, [{resource, Module} | Data]);
{_, ProvidedType} ->
AcceptedTypes = Module:content_types_accepted(),
case lists:member(ProvidedType, AcceptedTypes) of
true ->
check_accept_header(Headers, Module, [{resource, Module},
{content_type, ProvidedType} | Data]);
false ->
Response = "<h2>HTTP Error 415 - Unsupported Media Type</h2>",
{break, [{response, {415, Response}}]}
end;
false ->
Response = "<h2>HTTP Error 400 - Bad Request</h2>",
{break, [{response, {400, Response}}]}
end.
%% @hidden
check_accept_header(Headers, Module, Data) ->
case lists:keyfind("accept", 1, Headers) of
{_, AcceptType} ->
Representations = Module:content_types_provided(),
case lists:member(AcceptType, Representations) of
true ->
{proceed, [{accept, AcceptType} | Data]};
false ->
Response = "<h2>HTTP Error 415 - Unsupported Media Type</h2>",
{break, [{response, {415, Response}}]}
end;
false ->
{proceed, Data}
end.
| null | https://raw.githubusercontent.com/sigscale/snmp-collector/cb6b95ed331abd6f258d8ea55bf34c57f2992444/src/snmp_collector_rest_accepted_content.erl | erlang | snmp_collector_rest_accepted_content.erl
vim: ts=3
@end
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc Erlang web server API callback function .
@hidden
@hidden | 2016 - 2019 SigScale Global Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(snmp_collector_rest_accepted_content).
-copyright('Copyright (c) 2016 - 2019 SigScale Global Inc.').
-export([do/1]).
-include_lib("inets/include/httpd.hrl").
-spec do(ModData) -> Result when
ModData :: #mod{},
Result :: {proceed, OldData} | {proceed, NewData} | {break, NewData} | done,
OldData :: list(),
NewData :: [{response,{StatusCode,Body}}] | [{response,{response,Head,Body}}]
| [{response,{already_sent,StatusCode,Size}}],
StatusCode :: integer(),
Body :: iolist() | nobody | {Fun, Arg},
Head :: [HeaderOption],
HeaderOption :: {Option, Value} | {code, StatusCode},
Option :: accept_ranges | allow
| cache_control | content_MD5
| content_encoding | content_language
| content_length | content_location
| content_range | content_type | date
| etag | expires | last_modified
| location | pragma | retry_after
| server | trailer | transfer_encoding,
Value :: string(),
Size :: term(),
Fun :: fun((Arg) -> sent| close | Body),
Arg :: [term()].
do(#mod{method = Method, parsed_header = Headers, request_uri = Uri,
data = Data} = _ModData) ->
case proplists:get_value(status, Data) of
{_StatusCode, _PhraseArgs, _Reason} ->
{proceed, Data};
undefined ->
case proplists:get_value(response, Data) of
undefined ->
Path = http_uri:decode(Uri),
case string:tokens(Path, "/?") of
["snmp", "v1", "mibs" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_mib, Data);
["partyManagement", "v1", "individual" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_user, Data);
["eventManagement", "v1", "event" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_event, Data);
["snmp", "v1", "log", "http" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_http, Data);
["counters", "v1", "snmp" | _] ->
check_content_type_header(Headers, Method, snmp_collector_rest_res_counter, Data);
_ ->
{proceed, Data}
end;
_ ->
{proceed, Data}
end
end.
check_content_type_header(Headers, Method, Module, Data) ->
case lists:keyfind("content-type", 1, Headers) of
false when Method == "DELETE"; Method == "GET" ->
check_accept_header(Headers, Module, [{resource, Module} | Data]);
{_, []} when Method == "DELETE"; Method == "GET" ->
check_accept_header(Headers, Module, [{resource, Module} | Data]);
{_, ProvidedType} ->
AcceptedTypes = Module:content_types_accepted(),
case lists:member(ProvidedType, AcceptedTypes) of
true ->
check_accept_header(Headers, Module, [{resource, Module},
{content_type, ProvidedType} | Data]);
false ->
Response = "<h2>HTTP Error 415 - Unsupported Media Type</h2>",
{break, [{response, {415, Response}}]}
end;
false ->
Response = "<h2>HTTP Error 400 - Bad Request</h2>",
{break, [{response, {400, Response}}]}
end.
check_accept_header(Headers, Module, Data) ->
case lists:keyfind("accept", 1, Headers) of
{_, AcceptType} ->
Representations = Module:content_types_provided(),
case lists:member(AcceptType, Representations) of
true ->
{proceed, [{accept, AcceptType} | Data]};
false ->
Response = "<h2>HTTP Error 415 - Unsupported Media Type</h2>",
{break, [{response, {415, Response}}]}
end;
false ->
{proceed, Data}
end.
|
fcb22c176926b94b5e51d3ee3789a63b512e61bcdef4a70026e93767e530acd4 | zkincaid/duet | dg.ml | (** Sequential dependence graphs *)
open Core
module Pack = Var.Set
module FS = Lattice.FunctionSpace.Make(Pack)(Lattice.LiftSubset(Def.Set))
module G = Afg.G
module S = Afg.Pack
let construct file pack uses =
(* Map access paths to their reaching definitions *)
(** Reaching definitions analysis *)
let module RDInterp = struct
include FS
let transfer def rd =
begin match Def.assigned_var def with
| Some v -> FS.update (pack v) (Def.Set.singleton def) rd
| None -> match def.dkind with
| Store (lhs, _) ->
let open PointerAnalysis in
let f memloc rd =
match memloc with
| (MAddr vi, offset) ->
let p = pack (vi, offset) in
FS.update p (Def.Set.add def (FS.eval rd p)) rd
| (_, _) -> rd
in
MemLoc.Set.fold f (resolve_ap lhs) rd
| Assume phi | Assert (phi, _) ->
let set_rd v rd = FS.update (pack v) (Def.Set.singleton def) rd in
Var.Set.fold set_rd (Bexpr.free_vars phi) rd
| _ -> rd
end
let widen = join
let name = "Reaching definitions"
let bottom = FS.const Def.Set.empty
end in
let module RD = Solve.MakeForwardCfgSolver(RDInterp) in
let dg = G.create () in
let (_, init_s) = Live.live_vars file uses in
let add_edge src lbl tgt = G.add_edge_e dg (G.E.create src lbl tgt) in
(* Add a vertex and its incoming edges to the G, and add v -> rd to
rd_map *)
let process_vertex (v, rd) =
let uses = uses v in
let go (pack, defs) =
if not (Var.Set.is_empty (Var.Set.inter uses pack))
then
let pack_edge =
let f var pair_set =
let v = Variable var in
S.PairSet.add (S.mk_pair v v) pair_set
in
Var.Set.fold f pack S.PairSet.empty
in
Def.Set.iter (fun def -> add_edge def pack_edge v) defs
in
G.add_vertex dg v;
BatEnum.iter go (FS.enum rd)
in
let init =
let init_def = Def.Set.singleton Def.initial in
Var.Set.fold
(fun s fs -> FS.update (pack s) init_def fs)
init_s
(FS.const Def.Set.empty)
in
let mk_init _ value = value in
(* add all the vertices of a cfg to the G *)
let process_result result =
BatEnum.iter process_vertex (RD.enum_input result)
in
RD.file_analysis file process_result init mk_init;
dg
(** Simplify a dependence graph *)
let simplify_dg afg =
let vertices = G.fold_vertex (fun v vs -> v::vs) afg [] in
let remove_copy v =
match v.dkind with
| Assign (_, AccessPath (Variable _)) ->
let f pe se =
let def_ap = S.fst (S.PairSet.choose (G.E.label pe)) in
let use_ap = S.snd (S.PairSet.choose (G.E.label se)) in
let lbl = S.PairSet.singleton (S.mk_pair def_ap use_ap) in
G.add_edge_e afg (G.E.create (G.E.src pe) lbl (G.E.dst se))
in
G.iter_pred_e (fun pe -> G.iter_succ_e (f pe) afg v) afg v;
G.remove_vertex afg v
| _ -> ()
in
(*
let split_vertex v = (* don't split asserts! *)
match v.dkind with
| Assume _ ->
if S.PowerSet.cardinal (G.inputs afg v) = 1 then begin
let add_copy e =
let new_v = clone_def v in
let pred_e = G.E.create (G.E.src e) (G.E.label e) new_v in
let add_succ_e se =
G.add_edge_e afg
(G.E.create new_v (G.E.label se) (G.E.dst se))
in
G.remove_edge_e afg e;
G.add_vertex afg new_v;
G.add_edge_e afg pred_e;
G.iter_succ_e add_succ_e afg v
in
List.iter add_copy (List.tl (G.pred_e afg v))
end
| _ -> ()
in
*)
let init_ap =
Variable (Var.mk (Varinfo.mk_global "init" (Concrete (Int unknown_width))))
in
let relabel e =
let ap = S.snd (S.PairSet.choose (G.E.label e)) in
let lbl = S.PairSet.singleton (S.mk_pair init_ap ap) in
G.remove_edge_e afg e;
G.add_edge_e afg (G.E.create Def.initial lbl (G.E.dst e))
in
(* reduce the dimension of initial_def *)
if G.mem_vertex afg Def.initial
then G.iter_succ_e relabel afg Def.initial;
List.iter remove_copy vertices
List.iter split_vertex ( G.fold_vertex ( fun v vs - > v::vs ) afg [ ] )
let compare_dg g h =
let compare_v d =
let cmp = compare (G.in_degree g d) (G.in_degree h d) in
if cmp < 0 then print_endline "<"
else if cmp > 0 then print_endline ">"
else print_endline "="
in
G.iter_vertex compare_v g
| null | https://raw.githubusercontent.com/zkincaid/duet/eb3dbfe6c51d5e1a11cb39ab8f70584aaaa309f9/duet/dg.ml | ocaml | * Sequential dependence graphs
Map access paths to their reaching definitions
* Reaching definitions analysis
Add a vertex and its incoming edges to the G, and add v -> rd to
rd_map
add all the vertices of a cfg to the G
* Simplify a dependence graph
let split_vertex v = (* don't split asserts!
reduce the dimension of initial_def |
open Core
module Pack = Var.Set
module FS = Lattice.FunctionSpace.Make(Pack)(Lattice.LiftSubset(Def.Set))
module G = Afg.G
module S = Afg.Pack
let construct file pack uses =
let module RDInterp = struct
include FS
let transfer def rd =
begin match Def.assigned_var def with
| Some v -> FS.update (pack v) (Def.Set.singleton def) rd
| None -> match def.dkind with
| Store (lhs, _) ->
let open PointerAnalysis in
let f memloc rd =
match memloc with
| (MAddr vi, offset) ->
let p = pack (vi, offset) in
FS.update p (Def.Set.add def (FS.eval rd p)) rd
| (_, _) -> rd
in
MemLoc.Set.fold f (resolve_ap lhs) rd
| Assume phi | Assert (phi, _) ->
let set_rd v rd = FS.update (pack v) (Def.Set.singleton def) rd in
Var.Set.fold set_rd (Bexpr.free_vars phi) rd
| _ -> rd
end
let widen = join
let name = "Reaching definitions"
let bottom = FS.const Def.Set.empty
end in
let module RD = Solve.MakeForwardCfgSolver(RDInterp) in
let dg = G.create () in
let (_, init_s) = Live.live_vars file uses in
let add_edge src lbl tgt = G.add_edge_e dg (G.E.create src lbl tgt) in
let process_vertex (v, rd) =
let uses = uses v in
let go (pack, defs) =
if not (Var.Set.is_empty (Var.Set.inter uses pack))
then
let pack_edge =
let f var pair_set =
let v = Variable var in
S.PairSet.add (S.mk_pair v v) pair_set
in
Var.Set.fold f pack S.PairSet.empty
in
Def.Set.iter (fun def -> add_edge def pack_edge v) defs
in
G.add_vertex dg v;
BatEnum.iter go (FS.enum rd)
in
let init =
let init_def = Def.Set.singleton Def.initial in
Var.Set.fold
(fun s fs -> FS.update (pack s) init_def fs)
init_s
(FS.const Def.Set.empty)
in
let mk_init _ value = value in
let process_result result =
BatEnum.iter process_vertex (RD.enum_input result)
in
RD.file_analysis file process_result init mk_init;
dg
let simplify_dg afg =
let vertices = G.fold_vertex (fun v vs -> v::vs) afg [] in
let remove_copy v =
match v.dkind with
| Assign (_, AccessPath (Variable _)) ->
let f pe se =
let def_ap = S.fst (S.PairSet.choose (G.E.label pe)) in
let use_ap = S.snd (S.PairSet.choose (G.E.label se)) in
let lbl = S.PairSet.singleton (S.mk_pair def_ap use_ap) in
G.add_edge_e afg (G.E.create (G.E.src pe) lbl (G.E.dst se))
in
G.iter_pred_e (fun pe -> G.iter_succ_e (f pe) afg v) afg v;
G.remove_vertex afg v
| _ -> ()
in
match v.dkind with
| Assume _ ->
if S.PowerSet.cardinal (G.inputs afg v) = 1 then begin
let add_copy e =
let new_v = clone_def v in
let pred_e = G.E.create (G.E.src e) (G.E.label e) new_v in
let add_succ_e se =
G.add_edge_e afg
(G.E.create new_v (G.E.label se) (G.E.dst se))
in
G.remove_edge_e afg e;
G.add_vertex afg new_v;
G.add_edge_e afg pred_e;
G.iter_succ_e add_succ_e afg v
in
List.iter add_copy (List.tl (G.pred_e afg v))
end
| _ -> ()
in
*)
let init_ap =
Variable (Var.mk (Varinfo.mk_global "init" (Concrete (Int unknown_width))))
in
let relabel e =
let ap = S.snd (S.PairSet.choose (G.E.label e)) in
let lbl = S.PairSet.singleton (S.mk_pair init_ap ap) in
G.remove_edge_e afg e;
G.add_edge_e afg (G.E.create Def.initial lbl (G.E.dst e))
in
if G.mem_vertex afg Def.initial
then G.iter_succ_e relabel afg Def.initial;
List.iter remove_copy vertices
List.iter split_vertex ( G.fold_vertex ( fun v vs - > v::vs ) afg [ ] )
let compare_dg g h =
let compare_v d =
let cmp = compare (G.in_degree g d) (G.in_degree h d) in
if cmp < 0 then print_endline "<"
else if cmp > 0 then print_endline ">"
else print_endline "="
in
G.iter_vertex compare_v g
|
52a286a70dc04c60797c6ed3fb265ed3eb6de150e5c5b88d5de3b0fbf95e5d8a | basho/riak_test | rt_util.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2013 Basho Technologies , Inc.
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(rt_util).
-include_lib("eunit/include/eunit.hrl").
-export([convert_to_atom/1,
convert_to_atom_list/1,
convert_to_string/1,
find_atom_or_string/2,
find_atom_or_string_dict/2,
pmap/2]).
%% @doc Look up values by both atom and by string
find_atom_or_string(Key, Table) ->
case {Key, proplists:get_value(Key, Table)} of
{_, undefined} when is_atom(Key) ->
proplists:get_value(atom_to_list(Key), Table);
{_, undefined} when is_list(Key) ->
proplists:get_value(list_to_atom(Key), Table);
{Key, Value} ->
Value
end.
%% @doc Look up values in an orddict by both atom and by string
-spec find_atom_or_string(term(), orddict:orddict()) -> term() | undefined.
find_atom_or_string_dict(Key, Dict) ->
case {Key, orddict:is_key(Key, Dict)} of
{_, false} when is_atom(Key) ->
case orddict:is_key(atom_to_list(Key), Dict) of
true -> orddict:fetch(atom_to_list(Key), Dict);
_ -> undefined
end;
{_, false} when is_list(Key) ->
case orddict:is_key(list_to_atom(Key), Dict) of
true -> orddict:fetch(list_to_atom(Key), Dict);
_ -> undefined
end;
{_, true} ->
orddict:fetch(Key, Dict)
end.
%% @doc: Convert an atom to a string if it is not already
-spec convert_to_string(string()|atom()) -> string().
convert_to_string(Val) when is_atom(Val) ->
atom_to_list(Val);
convert_to_string(Val) when is_list(Val) ->
Val.
%% @doc: Convert a string to an atom if it is not already
-spec convert_to_atom(string()|atom()) -> atom().
convert_to_atom(Val) when is_list(Val) ->
list_to_atom(Val);
convert_to_atom(Val) ->
Val.
%% @doc Convert string or atom to list of atoms
-spec convert_to_atom_list(atom()|string()) -> undefined | list().
convert_to_atom_list(undefined) ->
undefined;
convert_to_atom_list(Values) when is_atom(Values) ->
ListOfValues = atom_to_list(Values),
case lists:member($, , ListOfValues) of
true ->
[list_to_atom(X) || X <- string:tokens(ListOfValues, ", ")];
_ ->
[Values]
end;
convert_to_atom_list(Values) when is_list(Values) ->
case lists:member($, , Values) of
true ->
[list_to_atom(X) || X <- string:tokens(Values, ", ")];
_ ->
[list_to_atom(Values)]
end.
@doc Parallel Map : Runs function F for each item in list L , then
%% returns the list of results
-spec pmap(F :: fun(), L :: list()) -> list().
pmap(F, L) ->
Parent = self(),
lists:foldl(
fun(X, N) ->
spawn_link(fun() ->
Parent ! {pmap, N, F(X)}
end),
N+1
end, 0, L),
L2 = [receive {pmap, N, R} -> {N,R} end || _ <- L],
{_, L3} = lists:unzip(lists:keysort(1, L2)),
L3.
-ifdef(TEST).
%% Look up values in a proplist by either a string or atom
find_atom_to_string_test() ->
?assertEqual(undefined, find_atom_or_string(value, [{a,1},{b,2}])),
?assertEqual(undefined, find_atom_or_string("value", [{a,1},{b,2}])),
?assertEqual(1, find_atom_or_string(a, [{a,1},{b,2}])),
?assertEqual(1, find_atom_or_string("a", [{a,1},{b,2}])).
%% Look up values in an orddict by either a string or atom
find_atom_to_string_dict_test() ->
Dict = [{a,"a"},{"b",b}],
?assertEqual(undefined, find_atom_or_string_dict(value, Dict)),
?assertEqual(undefined, find_atom_or_string_dict("value", Dict)),
?assertEqual("a", find_atom_or_string(a, Dict)),
?assertEqual(b, find_atom_or_string("b", Dict)).
%% Convert a string to an atom, otherwise it remains unchanged
convert_to_atom_test() ->
?assertEqual(a, convert_to_atom(a)),
?assertEqual(a, convert_to_atom("a")),
?assertEqual(1, convert_to_atom(1)).
%% Properly covert backends to atoms
convert_to_atom_list_test() ->
?assertEqual(undefined, convert_to_atom_list(undefined)),
?assertEqual([memory], convert_to_atom_list(memory)),
?assertEqual([memory], convert_to_atom_list("memory")),
?assertEqual([bitcask, eleveldb, memory], lists:sort(convert_to_atom_list("memory, bitcask,eleveldb"))),
?assertEqual([bitcask, eleveldb, memory], lists:sort(convert_to_atom_list('memory, bitcask,eleveldb'))).
-endif.
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/src/rt_util.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.
-------------------------------------------------------------------
@doc Look up values by both atom and by string
@doc Look up values in an orddict by both atom and by string
@doc: Convert an atom to a string if it is not already
@doc: Convert a string to an atom if it is not already
@doc Convert string or atom to list of atoms
returns the list of results
Look up values in a proplist by either a string or atom
Look up values in an orddict by either a string or atom
Convert a string to an atom, otherwise it remains unchanged
Properly covert backends to atoms | Copyright ( c ) 2013 Basho Technologies , Inc.
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(rt_util).
-include_lib("eunit/include/eunit.hrl").
-export([convert_to_atom/1,
convert_to_atom_list/1,
convert_to_string/1,
find_atom_or_string/2,
find_atom_or_string_dict/2,
pmap/2]).
find_atom_or_string(Key, Table) ->
case {Key, proplists:get_value(Key, Table)} of
{_, undefined} when is_atom(Key) ->
proplists:get_value(atom_to_list(Key), Table);
{_, undefined} when is_list(Key) ->
proplists:get_value(list_to_atom(Key), Table);
{Key, Value} ->
Value
end.
-spec find_atom_or_string(term(), orddict:orddict()) -> term() | undefined.
find_atom_or_string_dict(Key, Dict) ->
case {Key, orddict:is_key(Key, Dict)} of
{_, false} when is_atom(Key) ->
case orddict:is_key(atom_to_list(Key), Dict) of
true -> orddict:fetch(atom_to_list(Key), Dict);
_ -> undefined
end;
{_, false} when is_list(Key) ->
case orddict:is_key(list_to_atom(Key), Dict) of
true -> orddict:fetch(list_to_atom(Key), Dict);
_ -> undefined
end;
{_, true} ->
orddict:fetch(Key, Dict)
end.
-spec convert_to_string(string()|atom()) -> string().
convert_to_string(Val) when is_atom(Val) ->
atom_to_list(Val);
convert_to_string(Val) when is_list(Val) ->
Val.
-spec convert_to_atom(string()|atom()) -> atom().
convert_to_atom(Val) when is_list(Val) ->
list_to_atom(Val);
convert_to_atom(Val) ->
Val.
-spec convert_to_atom_list(atom()|string()) -> undefined | list().
convert_to_atom_list(undefined) ->
undefined;
convert_to_atom_list(Values) when is_atom(Values) ->
ListOfValues = atom_to_list(Values),
case lists:member($, , ListOfValues) of
true ->
[list_to_atom(X) || X <- string:tokens(ListOfValues, ", ")];
_ ->
[Values]
end;
convert_to_atom_list(Values) when is_list(Values) ->
case lists:member($, , Values) of
true ->
[list_to_atom(X) || X <- string:tokens(Values, ", ")];
_ ->
[list_to_atom(Values)]
end.
@doc Parallel Map : Runs function F for each item in list L , then
-spec pmap(F :: fun(), L :: list()) -> list().
pmap(F, L) ->
Parent = self(),
lists:foldl(
fun(X, N) ->
spawn_link(fun() ->
Parent ! {pmap, N, F(X)}
end),
N+1
end, 0, L),
L2 = [receive {pmap, N, R} -> {N,R} end || _ <- L],
{_, L3} = lists:unzip(lists:keysort(1, L2)),
L3.
-ifdef(TEST).
find_atom_to_string_test() ->
?assertEqual(undefined, find_atom_or_string(value, [{a,1},{b,2}])),
?assertEqual(undefined, find_atom_or_string("value", [{a,1},{b,2}])),
?assertEqual(1, find_atom_or_string(a, [{a,1},{b,2}])),
?assertEqual(1, find_atom_or_string("a", [{a,1},{b,2}])).
find_atom_to_string_dict_test() ->
Dict = [{a,"a"},{"b",b}],
?assertEqual(undefined, find_atom_or_string_dict(value, Dict)),
?assertEqual(undefined, find_atom_or_string_dict("value", Dict)),
?assertEqual("a", find_atom_or_string(a, Dict)),
?assertEqual(b, find_atom_or_string("b", Dict)).
convert_to_atom_test() ->
?assertEqual(a, convert_to_atom(a)),
?assertEqual(a, convert_to_atom("a")),
?assertEqual(1, convert_to_atom(1)).
convert_to_atom_list_test() ->
?assertEqual(undefined, convert_to_atom_list(undefined)),
?assertEqual([memory], convert_to_atom_list(memory)),
?assertEqual([memory], convert_to_atom_list("memory")),
?assertEqual([bitcask, eleveldb, memory], lists:sort(convert_to_atom_list("memory, bitcask,eleveldb"))),
?assertEqual([bitcask, eleveldb, memory], lists:sort(convert_to_atom_list('memory, bitcask,eleveldb'))).
-endif.
|
e3a8a2f3c6d33194231f25cd8b5402174481ae956760ec9c354ae9518e2e685a | GaloisInc/msf-haskell | Scan.hs | -- |Extended functionality to interact with nmap. These functions
are n't exported directly by the Metasploit server , but rather work
-- by calling db_nmap on the console. Compose namp parameters thusly:
-- /db_nmap (tcpSynScan <> tcpConnectScan)/
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
module MSF.Scan (
db_nmap
, NmapOptions()
, customScan
, emptyScan
, serviceVersionScan
, tcpSynScan
, pingScan
, sctpInitScan
, tcpConnectScan
, udpScan
, tcpNullScan
, finScan
, xmasScan
, tcpAckScan
, tcpWindowScan
, tcpMaimonScan
, sctpCookieEchoScan
, ipProtocolScan
, zombieHostScan
, scanFlagsScan
, ftpRelayScan
) where
import MSF.Host
import MSF.Monad
import RPC.Console
import Data.Monoid (Monoid(..))
-- XXX don't export, this works in all contexts.
nmap_scan :: String -- ^ nmap options
-> MSF v ()
nmap_scan args = do
let command = ("db_nmap " ++ args ++ "\n")
k <- console
prim $ \ addr auth -> do
_ <- console_write addr auth k command
return ()
-- | Run an nmap scan. Use "MSF.Event" to handle callbacks like
-- 'MSF.Event.onHost'.
db_nmap :: ScanCxt t => NmapOptions s -> Target t -> MSF s ()
db_nmap flags tgt =
nmap_scan (unwords [getNmapOptions flags, foldTarget formatTargetRange "" tgt])
formatTargetRange :: TargetRange t -> String -> String
formatTargetRange range s = case range of
CIDR h n -> unwords [getHost h ++ "/" ++ show n, s]
-- host ranges aren't really applicable for nmap, they use a different
-- notation for that.
HostRange _ _ -> error "db_nmap: HostRange" -- XXX
SingleHost h -> unwords [getHost h,s]
-- | Options to be supplied to the db_nmap command.
newtype NmapOptions s = NmapOptions
{ getNmapOptions :: String
} deriving (Show)
instance QuietCxt s => Monoid (NmapOptions s) where
mempty = NmapOptions ""
mappend l r = NmapOptions (getNmapOptions l ++ " " ++ getNmapOptions r)
-- | User-supplied arguments to nmap are assumed to be loud by default.
customScan :: LoudCxt s => String -> NmapOptions s
customScan = NmapOptions
-- | User-supplied arguments to nmap are assumed to be loud by default.
emptyScan :: LoudCxt s => NmapOptions s
emptyScan = NmapOptions ""
-- | Service version scanning.
serviceVersionScan :: LoudCxt s => NmapOptions s
serviceVersionScan = NmapOptions "-sV"
| scanning .
tcpSynScan :: QuietCxt s => NmapOptions s
tcpSynScan = NmapOptions "-sS"
-- | SCTP Init scanning.
sctpInitScan :: QuietCxt s => NmapOptions s
sctpInitScan = NmapOptions "-sY"
| scanning .
tcpConnectScan :: LoudCxt s => NmapOptions s
tcpConnectScan = NmapOptions "-sT"
-- | UDP scanning.
udpScan :: LoudCxt s => NmapOptions s
udpScan = NmapOptions "-sU"
-- | Ping scan only. Don't perform a port scan.
pingScan :: QuietCxt s => NmapOptions s
pingScan = NmapOptions "-sP"
-- | Does not set any bits (TCP flag header is 0)
tcpNullScan :: LoudCxt s => NmapOptions s
tcpNullScan = NmapOptions "-sN"
-- | Sets just the TCP FIN bit.
finScan :: LoudCxt s => NmapOptions s
finScan = NmapOptions "-sF"
| Sets the FIN , PSH , and URG flags , lighting the packet up like a Christmas tree .
xmasScan :: LoudCxt s => NmapOptions s
xmasScan = NmapOptions "-sX"
-- | This never determines open (or even open|filtered) ports. It is
-- used to map out firewall rulesets, determining whether they are
-- stateful or not and which ports are filtered.
tcpAckScan :: LoudCxt s => NmapOptions s
tcpAckScan = NmapOptions "-sA"
-- | Window scan is exactly the same as ACK scan except that it
-- exploits an implementation detail of certain systems to
-- differentiate open ports from closed ones, rather than always
printing unfiltered when a RST is returned
tcpWindowScan :: LoudCxt s => NmapOptions s
tcpWindowScan = NmapOptions "-sW"
| This technique is exactly the same as NULL , FIN , and Xmas scans , except that the probe is FIN / ACK .
tcpMaimonScan :: LoudCxt s => NmapOptions s
tcpMaimonScan = NmapOptions "-sM"
-- | SCTP COOKIE ECHO scan is a more advanced SCTP scan. It takes
-- advantage of the fact that SCTP implementations should silently
-- drop packets containing COOKIE ECHO chunks on open ports, but send
-- an ABORT if the port is closed.
sctpCookieEchoScan :: LoudCxt s => NmapOptions s
sctpCookieEchoScan = NmapOptions "-sZ"
-- | IP protocol scan allows you to determine which IP protocols (TCP,
ICMP , IGMP , etc . ) are supported by target machines . This is n't
-- technically a port scan, since it cycles through IP protocol
numbers rather than TCP or UDP port numbers .
ipProtocolScan :: LoudCxt s => NmapOptions s
ipProtocolScan = NmapOptions "-sO"
-- | This advanced scan method allows for a truly blind TCP port scan
-- of the target (meaning no packets are sent to the target from your
-- real IP address). Instead, a unique side-channel attack exploits
-- predictable IP fragmentation ID sequence generation on the zombie
-- host to glean information about the open ports on the target.
--
-- Note set as quiet context due to use of side channel.
zombieHostScan :: QuietCxt s => Con Scannable -> NmapOptions s
zombieHostScan zombieHost = NmapOptions ("-sI " ++ (getCon zombieHost))
| This vulnerability was widespread in 1997 when Nmap was released ,
-- but has largely been fixed.
--
-- Note set as quiet context due to use of side channel.
ftpRelayScan :: QuietCxt s => Host Scannable -> NmapOptions s
ftpRelayScan relay = NmapOptions ("-sI " ++ (getHost relay))
-- | Custom scan flags
scanFlagsScan :: LoudCxt s => String -> NmapOptions s
scanFlagsScan flags = NmapOptions ("--scanflags " ++ flags)
| null | https://raw.githubusercontent.com/GaloisInc/msf-haskell/76cee10771f9e9d10aa3301198e09f08bde907be/src/MSF/Scan.hs | haskell | |Extended functionality to interact with nmap. These functions
by calling db_nmap on the console. Compose namp parameters thusly:
/db_nmap (tcpSynScan <> tcpConnectScan)/
XXX don't export, this works in all contexts.
^ nmap options
| Run an nmap scan. Use "MSF.Event" to handle callbacks like
'MSF.Event.onHost'.
host ranges aren't really applicable for nmap, they use a different
notation for that.
XXX
| Options to be supplied to the db_nmap command.
| User-supplied arguments to nmap are assumed to be loud by default.
| User-supplied arguments to nmap are assumed to be loud by default.
| Service version scanning.
| SCTP Init scanning.
| UDP scanning.
| Ping scan only. Don't perform a port scan.
| Does not set any bits (TCP flag header is 0)
| Sets just the TCP FIN bit.
| This never determines open (or even open|filtered) ports. It is
used to map out firewall rulesets, determining whether they are
stateful or not and which ports are filtered.
| Window scan is exactly the same as ACK scan except that it
exploits an implementation detail of certain systems to
differentiate open ports from closed ones, rather than always
| SCTP COOKIE ECHO scan is a more advanced SCTP scan. It takes
advantage of the fact that SCTP implementations should silently
drop packets containing COOKIE ECHO chunks on open ports, but send
an ABORT if the port is closed.
| IP protocol scan allows you to determine which IP protocols (TCP,
technically a port scan, since it cycles through IP protocol
| This advanced scan method allows for a truly blind TCP port scan
of the target (meaning no packets are sent to the target from your
real IP address). Instead, a unique side-channel attack exploits
predictable IP fragmentation ID sequence generation on the zombie
host to glean information about the open ports on the target.
Note set as quiet context due to use of side channel.
but has largely been fixed.
Note set as quiet context due to use of side channel.
| Custom scan flags | are n't exported directly by the Metasploit server , but rather work
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
module MSF.Scan (
db_nmap
, NmapOptions()
, customScan
, emptyScan
, serviceVersionScan
, tcpSynScan
, pingScan
, sctpInitScan
, tcpConnectScan
, udpScan
, tcpNullScan
, finScan
, xmasScan
, tcpAckScan
, tcpWindowScan
, tcpMaimonScan
, sctpCookieEchoScan
, ipProtocolScan
, zombieHostScan
, scanFlagsScan
, ftpRelayScan
) where
import MSF.Host
import MSF.Monad
import RPC.Console
import Data.Monoid (Monoid(..))
-> MSF v ()
nmap_scan args = do
let command = ("db_nmap " ++ args ++ "\n")
k <- console
prim $ \ addr auth -> do
_ <- console_write addr auth k command
return ()
db_nmap :: ScanCxt t => NmapOptions s -> Target t -> MSF s ()
db_nmap flags tgt =
nmap_scan (unwords [getNmapOptions flags, foldTarget formatTargetRange "" tgt])
formatTargetRange :: TargetRange t -> String -> String
formatTargetRange range s = case range of
CIDR h n -> unwords [getHost h ++ "/" ++ show n, s]
SingleHost h -> unwords [getHost h,s]
newtype NmapOptions s = NmapOptions
{ getNmapOptions :: String
} deriving (Show)
instance QuietCxt s => Monoid (NmapOptions s) where
mempty = NmapOptions ""
mappend l r = NmapOptions (getNmapOptions l ++ " " ++ getNmapOptions r)
customScan :: LoudCxt s => String -> NmapOptions s
customScan = NmapOptions
emptyScan :: LoudCxt s => NmapOptions s
emptyScan = NmapOptions ""
serviceVersionScan :: LoudCxt s => NmapOptions s
serviceVersionScan = NmapOptions "-sV"
| scanning .
tcpSynScan :: QuietCxt s => NmapOptions s
tcpSynScan = NmapOptions "-sS"
sctpInitScan :: QuietCxt s => NmapOptions s
sctpInitScan = NmapOptions "-sY"
| scanning .
tcpConnectScan :: LoudCxt s => NmapOptions s
tcpConnectScan = NmapOptions "-sT"
udpScan :: LoudCxt s => NmapOptions s
udpScan = NmapOptions "-sU"
pingScan :: QuietCxt s => NmapOptions s
pingScan = NmapOptions "-sP"
tcpNullScan :: LoudCxt s => NmapOptions s
tcpNullScan = NmapOptions "-sN"
finScan :: LoudCxt s => NmapOptions s
finScan = NmapOptions "-sF"
| Sets the FIN , PSH , and URG flags , lighting the packet up like a Christmas tree .
xmasScan :: LoudCxt s => NmapOptions s
xmasScan = NmapOptions "-sX"
tcpAckScan :: LoudCxt s => NmapOptions s
tcpAckScan = NmapOptions "-sA"
printing unfiltered when a RST is returned
tcpWindowScan :: LoudCxt s => NmapOptions s
tcpWindowScan = NmapOptions "-sW"
| This technique is exactly the same as NULL , FIN , and Xmas scans , except that the probe is FIN / ACK .
tcpMaimonScan :: LoudCxt s => NmapOptions s
tcpMaimonScan = NmapOptions "-sM"
sctpCookieEchoScan :: LoudCxt s => NmapOptions s
sctpCookieEchoScan = NmapOptions "-sZ"
ICMP , IGMP , etc . ) are supported by target machines . This is n't
numbers rather than TCP or UDP port numbers .
ipProtocolScan :: LoudCxt s => NmapOptions s
ipProtocolScan = NmapOptions "-sO"
zombieHostScan :: QuietCxt s => Con Scannable -> NmapOptions s
zombieHostScan zombieHost = NmapOptions ("-sI " ++ (getCon zombieHost))
| This vulnerability was widespread in 1997 when Nmap was released ,
ftpRelayScan :: QuietCxt s => Host Scannable -> NmapOptions s
ftpRelayScan relay = NmapOptions ("-sI " ++ (getHost relay))
scanFlagsScan :: LoudCxt s => String -> NmapOptions s
scanFlagsScan flags = NmapOptions ("--scanflags " ++ flags)
|
91ed846e847bdfc94fda3f00e41bb8038ebc0638056c3406dcbb416e2d0449c7 | rd--/hsc3 | rLoopSet.help.hs | ---
Concurrent loops at a signal buffer
Create a set of concurrent loops at a signal buffer . This is the
static and composed variant of RFreezer . There are five global
inputs , the buffer and then : left , right , gain and increment . The
first two are initialization rate , the second two control rate .
Each loop is defined by a quadruple : left , right , gain and
increment . The left and right values are in the range [ 0,1 ) and
refer to the segment of the buffer established by the group left
and right values , which are in the range [ 0,1 ) in relation to the
signal buffer .
Buffer Left Buffer Right
| |
| Group Left Group Right |
| | | |
|------|----|-----------------------|----|--------------|
| |
Loop Left Loop Right
Concurrent loops at a signal buffer
Create a set of concurrent loops at a signal buffer. This is the
static and composed variant of RFreezer. There are five global
inputs, the buffer and then: left, right, gain and increment. The
first two are initialization rate, the second two control rate.
Each loop is defined by a quadruple: left, right, gain and
increment. The left and right values are in the range [0,1) and
refer to the segment of the buffer established by the group left
and right values, which are in the range [0,1) in relation to the
signal buffer.
Buffer Left Buffer Right
| |
| Group Left Group Right |
| | | |
|------|----|-----------------------|----|--------------|
| |
Loop Left Loop Right
-}
| null | https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/rLoopSet.help.hs | haskell | -
----|----|-----------------------|----|--------------|
----|----|-----------------------|----|--------------| |
Concurrent loops at a signal buffer
Create a set of concurrent loops at a signal buffer . This is the
static and composed variant of RFreezer . There are five global
inputs , the buffer and then : left , right , gain and increment . The
first two are initialization rate , the second two control rate .
Each loop is defined by a quadruple : left , right , gain and
increment . The left and right values are in the range [ 0,1 ) and
refer to the segment of the buffer established by the group left
and right values , which are in the range [ 0,1 ) in relation to the
signal buffer .
Buffer Left Buffer Right
| |
| Group Left Group Right |
| | | |
| |
Loop Left Loop Right
Concurrent loops at a signal buffer
Create a set of concurrent loops at a signal buffer. This is the
static and composed variant of RFreezer. There are five global
inputs, the buffer and then: left, right, gain and increment. The
first two are initialization rate, the second two control rate.
Each loop is defined by a quadruple: left, right, gain and
increment. The left and right values are in the range [0,1) and
refer to the segment of the buffer established by the group left
and right values, which are in the range [0,1) in relation to the
signal buffer.
Buffer Left Buffer Right
| |
| Group Left Group Right |
| | | |
| |
Loop Left Loop Right
-}
|
47068275b21ed875a55b6f961f97eb4a3e21725a72613694c0f7de8b79f7ba4f | mirage/mirage | mirage_impl_tracing.mli | type tracing = Functoria.job
val tracing : tracing Functoria.typ
val mprof_trace : size:int -> unit -> tracing Functoria.impl
| null | https://raw.githubusercontent.com/mirage/mirage/479e40ae6aa1efe18fb1cd199cec0d5ee1f46f26/lib/mirage/impl/mirage_impl_tracing.mli | ocaml | type tracing = Functoria.job
val tracing : tracing Functoria.typ
val mprof_trace : size:int -> unit -> tracing Functoria.impl
|
|
c6ad98f280c0996196ae2793f562c46ecd0587a6fad997fae578be964b4a342f | chenyukang/eopl | classes.scm | (module classes (lib "eopl.ss" "eopl")
(require "store.scm")
(require "lang.scm")
;; object interface
(provide object object? new-object object->class-name object->fields)
;; method interface
(provide method method? a-method find-method)
;; class interface
(provide lookup-class initialize-class-env!)
;;;;;;;;;;;;;;;; objects ;;;;;;;;;;;;;;;;
;; an object consists of a symbol denoting its class, and a list of
;; references representing the managed storage for the all the fields.
(define identifier? symbol?)
(define-datatype object object?
(an-object
(class-name identifier?)
(fields (list-of reference?))))
;; new-object : ClassName -> Obj
Page 340
(define new-object
(lambda (class-name)
(an-object
class-name
(map
(lambda (field-name)
(newref (list 'uninitialized-field field-name)))
(class->field-names (lookup-class class-name))))))
;;;;;;;;;;;;;;;; methods and method environments ;;;;;;;;;;;;;;;;
(define-datatype method method?
(a-method
(vars (list-of symbol?))
(body expression?)
(super-name symbol?)
(field-names (list-of symbol?))))
;;;;;;;;;;;;;;;; method environments ;;;;;;;;;;;;;;;;
;; a method environment looks like ((method-name method) ...)
(define method-environment?
(list-of
(lambda (p)
(and
(pair? p)
(symbol? (car p))
(method? (cadr p))))))
;; method-env * id -> (maybe method)
(define assq-method-env
(lambda (m-env id)
(cond
((assq id m-env) => cadr)
(else #f))))
;; find-method : Sym * Sym -> Method
Page : 345
(define find-method
(lambda (c-name name)
(let ((m-env (class->method-env (lookup-class c-name))))
(let ((maybe-pair (assq name m-env)))
(if (pair? maybe-pair) (cadr maybe-pair)
(report-method-not-found name))))))
(define report-method-not-found
(lambda (name)
(eopl:error 'find-method "unknown method ~s" name)))
;; merge-method-envs : MethodEnv * MethodEnv -> MethodEnv
Page : 345
(define merge-method-envs
(lambda (super-m-env new-m-env)
(append new-m-env super-m-env)))
;; method-decls->method-env :
;; Listof(MethodDecl) * ClassName * Listof(FieldName) -> MethodEnv
Page : 345
(define method-decls->method-env
(lambda (m-decls super-name field-names)
(map
(lambda (m-decl)
(cases method-decl m-decl
(a-method-decl (method-name vars body)
(list method-name
(a-method vars body super-name field-names)))))
m-decls)))
;;;;;;;;;;;;;;;; classes ;;;;;;;;;;;;;;;;
(define-datatype class class?
(a-class
(super-name (maybe symbol?))
(field-names (list-of symbol?))
(method-env method-environment?)))
;;;;;;;;;;;;;;;; class environments ;;;;;;;;;;;;;;;;
;; the-class-env will look like ((class-name class) ...)
the - class - env : ClassEnv
Page : 343
(define the-class-env '())
;; add-to-class-env! : ClassName * Class -> Unspecified
Page : 343
(define add-to-class-env!
(lambda (class-name class)
(set! the-class-env
(cons
(list class-name class)
the-class-env))))
;; lookup-class : ClassName -> Class
(define lookup-class
(lambda (name)
(let ((maybe-pair (assq name the-class-env)))
(if maybe-pair (cadr maybe-pair)
(report-unknown-class name)))))
(define report-unknown-class
(lambda (name)
(eopl:error 'lookup-class "Unknown class ~s" name)))
;; constructing classes
;; initialize-class-env! : Listof(ClassDecl) -> Unspecified
Page : 344
(define initialize-class-env!
(lambda (c-decls)
(set! the-class-env
(list
(list 'object (a-class #f '() '()))))
(for-each initialize-class-decl! c-decls)))
;; initialize-class-decl! : ClassDecl -> Unspecified
(define initialize-class-decl!
(lambda (c-decl)
(cases class-decl c-decl
(a-class-decl (c-name s-name f-names m-decls)
(let ((f-names
(append-field-names
(class->field-names (lookup-class s-name))
f-names)))
(add-to-class-env!
c-name
(a-class s-name f-names
(merge-method-envs
(class->method-env (lookup-class s-name))
(method-decls->method-env
m-decls s-name f-names)))))))))
exercise : rewrite this so there 's only one set ! to the - class - env .
;; append-field-names : Listof(FieldName) * Listof(FieldName)
;; -> Listof(FieldName)
Page : 344
;; like append, except that any super-field that is shadowed by a
new - field is replaced by a
(define append-field-names
(lambda (super-fields new-fields)
(cond
((null? super-fields) new-fields)
(else
(cons
(if (memq (car super-fields) new-fields)
(fresh-identifier (car super-fields))
(car super-fields))
(append-field-names
(cdr super-fields) new-fields))))))
;;;;;;;;;;;;;;;; selectors ;;;;;;;;;;;;;;;;
(define class->super-name
(lambda (c-struct)
(cases class c-struct
(a-class (super-name field-names method-env)
super-name))))
(define class->field-names
(lambda (c-struct)
(cases class c-struct
(a-class (super-name field-names method-env)
field-names))))
(define class->method-env
(lambda (c-struct)
(cases class c-struct
(a-class (super-name field-names method-env)
method-env))))
(define object->class-name
(lambda (obj)
(cases object obj
(an-object (class-name fields)
class-name))))
(define object->fields
(lambda (obj)
(cases object obj
(an-object (class-decl fields)
fields))))
(define fresh-identifier
(let ((sn 0))
(lambda (identifier)
(set! sn (+ sn 1))
(string->symbol
(string-append
(symbol->string identifier)
"%" ; this can't appear in an input identifier
(number->string sn))))))
(define maybe
(lambda (pred)
(lambda (v)
(or (not v) (pred v)))))
) | null | https://raw.githubusercontent.com/chenyukang/eopl/0406ff23b993bfe020294fa70d2597b1ce4f9b78/base/chapter9/classes/classes.scm | scheme | object interface
method interface
class interface
objects ;;;;;;;;;;;;;;;;
an object consists of a symbol denoting its class, and a list of
references representing the managed storage for the all the fields.
new-object : ClassName -> Obj
methods and method environments ;;;;;;;;;;;;;;;;
method environments ;;;;;;;;;;;;;;;;
a method environment looks like ((method-name method) ...)
method-env * id -> (maybe method)
find-method : Sym * Sym -> Method
merge-method-envs : MethodEnv * MethodEnv -> MethodEnv
method-decls->method-env :
Listof(MethodDecl) * ClassName * Listof(FieldName) -> MethodEnv
classes ;;;;;;;;;;;;;;;;
class environments ;;;;;;;;;;;;;;;;
the-class-env will look like ((class-name class) ...)
add-to-class-env! : ClassName * Class -> Unspecified
lookup-class : ClassName -> Class
constructing classes
initialize-class-env! : Listof(ClassDecl) -> Unspecified
initialize-class-decl! : ClassDecl -> Unspecified
append-field-names : Listof(FieldName) * Listof(FieldName)
-> Listof(FieldName)
like append, except that any super-field that is shadowed by a
selectors ;;;;;;;;;;;;;;;;
this can't appear in an input identifier | (module classes (lib "eopl.ss" "eopl")
(require "store.scm")
(require "lang.scm")
(provide object object? new-object object->class-name object->fields)
(provide method method? a-method find-method)
(provide lookup-class initialize-class-env!)
(define identifier? symbol?)
(define-datatype object object?
(an-object
(class-name identifier?)
(fields (list-of reference?))))
Page 340
(define new-object
(lambda (class-name)
(an-object
class-name
(map
(lambda (field-name)
(newref (list 'uninitialized-field field-name)))
(class->field-names (lookup-class class-name))))))
(define-datatype method method?
(a-method
(vars (list-of symbol?))
(body expression?)
(super-name symbol?)
(field-names (list-of symbol?))))
(define method-environment?
(list-of
(lambda (p)
(and
(pair? p)
(symbol? (car p))
(method? (cadr p))))))
(define assq-method-env
(lambda (m-env id)
(cond
((assq id m-env) => cadr)
(else #f))))
Page : 345
(define find-method
(lambda (c-name name)
(let ((m-env (class->method-env (lookup-class c-name))))
(let ((maybe-pair (assq name m-env)))
(if (pair? maybe-pair) (cadr maybe-pair)
(report-method-not-found name))))))
(define report-method-not-found
(lambda (name)
(eopl:error 'find-method "unknown method ~s" name)))
Page : 345
(define merge-method-envs
(lambda (super-m-env new-m-env)
(append new-m-env super-m-env)))
Page : 345
(define method-decls->method-env
(lambda (m-decls super-name field-names)
(map
(lambda (m-decl)
(cases method-decl m-decl
(a-method-decl (method-name vars body)
(list method-name
(a-method vars body super-name field-names)))))
m-decls)))
(define-datatype class class?
(a-class
(super-name (maybe symbol?))
(field-names (list-of symbol?))
(method-env method-environment?)))
the - class - env : ClassEnv
Page : 343
(define the-class-env '())
Page : 343
(define add-to-class-env!
(lambda (class-name class)
(set! the-class-env
(cons
(list class-name class)
the-class-env))))
(define lookup-class
(lambda (name)
(let ((maybe-pair (assq name the-class-env)))
(if maybe-pair (cadr maybe-pair)
(report-unknown-class name)))))
(define report-unknown-class
(lambda (name)
(eopl:error 'lookup-class "Unknown class ~s" name)))
Page : 344
(define initialize-class-env!
(lambda (c-decls)
(set! the-class-env
(list
(list 'object (a-class #f '() '()))))
(for-each initialize-class-decl! c-decls)))
(define initialize-class-decl!
(lambda (c-decl)
(cases class-decl c-decl
(a-class-decl (c-name s-name f-names m-decls)
(let ((f-names
(append-field-names
(class->field-names (lookup-class s-name))
f-names)))
(add-to-class-env!
c-name
(a-class s-name f-names
(merge-method-envs
(class->method-env (lookup-class s-name))
(method-decls->method-env
m-decls s-name f-names)))))))))
exercise : rewrite this so there 's only one set ! to the - class - env .
Page : 344
new - field is replaced by a
(define append-field-names
(lambda (super-fields new-fields)
(cond
((null? super-fields) new-fields)
(else
(cons
(if (memq (car super-fields) new-fields)
(fresh-identifier (car super-fields))
(car super-fields))
(append-field-names
(cdr super-fields) new-fields))))))
(define class->super-name
(lambda (c-struct)
(cases class c-struct
(a-class (super-name field-names method-env)
super-name))))
(define class->field-names
(lambda (c-struct)
(cases class c-struct
(a-class (super-name field-names method-env)
field-names))))
(define class->method-env
(lambda (c-struct)
(cases class c-struct
(a-class (super-name field-names method-env)
method-env))))
(define object->class-name
(lambda (obj)
(cases object obj
(an-object (class-name fields)
class-name))))
(define object->fields
(lambda (obj)
(cases object obj
(an-object (class-decl fields)
fields))))
(define fresh-identifier
(let ((sn 0))
(lambda (identifier)
(set! sn (+ sn 1))
(string->symbol
(string-append
(symbol->string identifier)
(number->string sn))))))
(define maybe
(lambda (pred)
(lambda (v)
(or (not v) (pred v)))))
) |
8eb00ce8a8acb571bdca23ffac1418230a9ff5ce9a623054b6d3214d43f24106 | ocaml-batteries-team/batteries-included | batUref.ml |
* Uref -- unifiable references
* Copyright ( C ) 2011 Batteries Included Development Team
*
* 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 ,
* with the special exception on linking described in file LICENSE .
*
* 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 .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Uref -- unifiable references
* Copyright (C) 2011 Batteries Included Development Team
*
* 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,
* with the special exception on linking described in file LICENSE.
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
(* Implements union-find with ranks and path-compression *)
type 'a uref_contents =
| Ranked of 'a * int
| Ptr of 'a uref
and 'a uref = 'a uref_contents ref
type 'a t = 'a uref
let rec find ur =
match !ur with
| Ptr p ->
let vr = find p in
ur := Ptr vr ;
vr
| Ranked _ -> ur
let uref x = ref (Ranked (x, 0))
let uget ur =
match !(find ur) with
| Ptr _ -> assert false
| Ranked (x, _) -> x
let uset ur x =
let ur = find ur in
match !ur with
| Ptr _ -> assert false
| Ranked (_, r) -> ur := Ranked (x, r)
let equal ur vr =
find ur == find vr
let unite ?sel ur vr =
(* we use ?sel instead of ?(sel=(fun x _y -> x)) because we want to be
able to know whether a selection function was passed, for
optimization purposes: when sel is the default (expected common
case), we can take a short path in the (ur == vr) case. *)
let ur = find ur in
let vr = find vr in
if ur == vr then begin
match sel with
| None -> ()
| Some sel ->
(* even when ur and vr are the same reference, we need to apply
the selection function, as [sel x x] may be different from [x].
For example, [unite ~sel:(fun _ _ -> v) r r] would fail
to set the content of [r] to [v] otherwise. *)
match !ur with
| Ptr _ -> assert false
| Ranked (x, r) ->
let x' = sel x x in
ur := Ranked(x', r)
end
else
match !ur, !vr with
| _, Ptr _ | Ptr _, _ -> assert false
| Ranked (x, xr), Ranked (y, yr) ->
let z = match sel with
| None -> x (* in the default case, pick x *)
| Some sel -> sel x y in
if xr = yr then begin
ur := Ranked (z, xr + 1) ;
vr := Ptr ur
end else if xr < yr then begin
ur := Ranked (z, xr) ;
vr := Ptr ur
end else begin
vr := Ranked (z, yr) ;
ur := Ptr vr
end
let print elepr out ur =
match !(find ur) with
| Ptr _ -> assert false
| Ranked (x, _) ->
BatInnerIO.nwrite out "uref " ;
elepr out x
$ T print
let u1 = uref 2 and u2 = uref 3 in unite ~sel:(+ ) u1 u2 ; \
BatIO.to_string ( print BatInt.print ) u1 = " uref 5 " & & \
BatIO.to_string ( print BatInt.print ) u2 = " uref 5 "
let u1 = uref 2 and u2 = uref 3 in unite ~sel:(+) u1 u2; \
BatIO.to_string (print BatInt.print) u1 = "uref 5" && \
BatIO.to_string (print BatInt.print) u2 = "uref 5"
*)
| null | https://raw.githubusercontent.com/ocaml-batteries-team/batteries-included/f143ef5ec583d87d538b8f06f06d046d64555e90/src/batUref.ml | ocaml | Implements union-find with ranks and path-compression
we use ?sel instead of ?(sel=(fun x _y -> x)) because we want to be
able to know whether a selection function was passed, for
optimization purposes: when sel is the default (expected common
case), we can take a short path in the (ur == vr) case.
even when ur and vr are the same reference, we need to apply
the selection function, as [sel x x] may be different from [x].
For example, [unite ~sel:(fun _ _ -> v) r r] would fail
to set the content of [r] to [v] otherwise.
in the default case, pick x |
* Uref -- unifiable references
* Copyright ( C ) 2011 Batteries Included Development Team
*
* 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 ,
* with the special exception on linking described in file LICENSE .
*
* 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 .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Uref -- unifiable references
* Copyright (C) 2011 Batteries Included Development Team
*
* 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,
* with the special exception on linking described in file LICENSE.
*
* 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.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type 'a uref_contents =
| Ranked of 'a * int
| Ptr of 'a uref
and 'a uref = 'a uref_contents ref
type 'a t = 'a uref
let rec find ur =
match !ur with
| Ptr p ->
let vr = find p in
ur := Ptr vr ;
vr
| Ranked _ -> ur
let uref x = ref (Ranked (x, 0))
let uget ur =
match !(find ur) with
| Ptr _ -> assert false
| Ranked (x, _) -> x
let uset ur x =
let ur = find ur in
match !ur with
| Ptr _ -> assert false
| Ranked (_, r) -> ur := Ranked (x, r)
let equal ur vr =
find ur == find vr
let unite ?sel ur vr =
let ur = find ur in
let vr = find vr in
if ur == vr then begin
match sel with
| None -> ()
| Some sel ->
match !ur with
| Ptr _ -> assert false
| Ranked (x, r) ->
let x' = sel x x in
ur := Ranked(x', r)
end
else
match !ur, !vr with
| _, Ptr _ | Ptr _, _ -> assert false
| Ranked (x, xr), Ranked (y, yr) ->
let z = match sel with
| Some sel -> sel x y in
if xr = yr then begin
ur := Ranked (z, xr + 1) ;
vr := Ptr ur
end else if xr < yr then begin
ur := Ranked (z, xr) ;
vr := Ptr ur
end else begin
vr := Ranked (z, yr) ;
ur := Ptr vr
end
let print elepr out ur =
match !(find ur) with
| Ptr _ -> assert false
| Ranked (x, _) ->
BatInnerIO.nwrite out "uref " ;
elepr out x
$ T print
let u1 = uref 2 and u2 = uref 3 in unite ~sel:(+ ) u1 u2 ; \
BatIO.to_string ( print BatInt.print ) u1 = " uref 5 " & & \
BatIO.to_string ( print BatInt.print ) u2 = " uref 5 "
let u1 = uref 2 and u2 = uref 3 in unite ~sel:(+) u1 u2; \
BatIO.to_string (print BatInt.print) u1 = "uref 5" && \
BatIO.to_string (print BatInt.print) u2 = "uref 5"
*)
|
5ad5a6450317ae5600eef27e988bbc38cf40cf23c6069cb6b832bc9e8d3c1d83 | lykahb/groundhog | monadIntegration.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
import Control.Applicative (Applicative)
import Control.Monad (liftM)
import Control.Monad.Base (MonadBase (liftBase))
import Control.Monad.Fail (MonadFail (..))
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Logger (LoggingT, MonadLogger (..), runStdoutLoggingT)
import Control.Monad.Reader (MonadReader (..))
import Control.Monad.Trans.Control (MonadBaseControl (..))
import Control.Monad.Trans.Reader (ReaderT (..), runReaderT)
import Data.Pool
import Database.Groundhog.Core
import Database.Groundhog.Generic
import Database.Groundhog.Sqlite
main :: IO ()
main = withSqlitePool ":memory:" 5 $ \pconn -> do
let runMyMonadDB :: MyMonad a -> IO a
runMyMonadDB = flip runReaderT (ApplicationState pconn) . runStdoutLoggingT . runMyMonad
runMyMonadDB sqliteDbAction
It is connection agnostic ( runs both with Sqlite and )
sqliteDbAction :: (PersistBackend m, Conn m ~ Sqlite) => m ()
sqliteDbAction = do
-- here can be web business logics
runDb $ do
let runAndShow sql = queryRaw False sql [] >>= firstRow >>= liftIO . print
runAndShow "select 'Groundhog embedded in arbitrary monadic context'"
This can be Snaplet in Snap or foundation datatype in Yesod .
data ApplicationState = ApplicationState {getConnPool :: Pool Sqlite}
-- -- This instance extracts connection from our application state
instance ExtractConnection ApplicationState Sqlite where
extractConn f app = extractConn f ( getConnPool app )
This can be any application monad like Handler in Snap or in Yesod
newtype MyMonad a = MyMonad {runMyMonad :: LoggingT (ReaderT ApplicationState IO) a}
deriving (Applicative, Functor, Monad, MonadReader ApplicationState, MonadIO, MonadLogger)
instance MonadFail MyMonad where
fail = error
instance MonadBase IO MyMonad where
liftBase = liftIO
instance PersistBackend MyMonad where
type Conn MyMonad = Sqlite
getConnection = asks getConnPool
| null | https://raw.githubusercontent.com/lykahb/groundhog/146691a828db39932c8212cd68f732d74589e488/examples/monadIntegration.hs | haskell | here can be web business logics
-- This instance extracts connection from our application state | # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeFamilies #
import Control.Applicative (Applicative)
import Control.Monad (liftM)
import Control.Monad.Base (MonadBase (liftBase))
import Control.Monad.Fail (MonadFail (..))
import Control.Monad.IO.Class (MonadIO (..))
import Control.Monad.Logger (LoggingT, MonadLogger (..), runStdoutLoggingT)
import Control.Monad.Reader (MonadReader (..))
import Control.Monad.Trans.Control (MonadBaseControl (..))
import Control.Monad.Trans.Reader (ReaderT (..), runReaderT)
import Data.Pool
import Database.Groundhog.Core
import Database.Groundhog.Generic
import Database.Groundhog.Sqlite
main :: IO ()
main = withSqlitePool ":memory:" 5 $ \pconn -> do
let runMyMonadDB :: MyMonad a -> IO a
runMyMonadDB = flip runReaderT (ApplicationState pconn) . runStdoutLoggingT . runMyMonad
runMyMonadDB sqliteDbAction
It is connection agnostic ( runs both with Sqlite and )
sqliteDbAction :: (PersistBackend m, Conn m ~ Sqlite) => m ()
sqliteDbAction = do
runDb $ do
let runAndShow sql = queryRaw False sql [] >>= firstRow >>= liftIO . print
runAndShow "select 'Groundhog embedded in arbitrary monadic context'"
This can be Snaplet in Snap or foundation datatype in Yesod .
data ApplicationState = ApplicationState {getConnPool :: Pool Sqlite}
instance ExtractConnection ApplicationState Sqlite where
extractConn f app = extractConn f ( getConnPool app )
This can be any application monad like Handler in Snap or in Yesod
newtype MyMonad a = MyMonad {runMyMonad :: LoggingT (ReaderT ApplicationState IO) a}
deriving (Applicative, Functor, Monad, MonadReader ApplicationState, MonadIO, MonadLogger)
instance MonadFail MyMonad where
fail = error
instance MonadBase IO MyMonad where
liftBase = liftIO
instance PersistBackend MyMonad where
type Conn MyMonad = Sqlite
getConnection = asks getConnPool
|
6455cef1ec2a84f51d5ea1d55673b1cc95d7e8e7747e1ef863353be20d418900 | carl-eastlund/dracula | dracula-state.rkt | #lang racket
(require "../proof/proof.rkt"
"../acl2/acl2.rkt"
"../acl2/rep.rkt"
"../private/hash.rkt"
"proof-state.rkt")
;; ======================================================================
;;
;; DATA DEFINITION
;;
;; ======================================================================
;; A DraculaState is: (make-dracula-state Action ProofTable)
;; An Action is either:
;; - #f
;; - (make-error-action String)
;; - (make-normal-action String)
;; - (make-interrupt-action String)
;; A ProofTable is: (make-proof-table names current hash)
where names : ( )
;; and current : (Or Symbol #f)
;; and hash : (IHasheq Symbol ProofState)
(define-struct dracula-state (action table) #:prefab)
(define-struct action (desc) #:prefab)
(define-struct (error-action action) () #:prefab)
(define-struct (normal-action action) () #:prefab)
(define-struct (interrupt-action action) () #:prefab)
(define-struct proof-table (names current hash) #:prefab)
;; ======================================================================
;;
PREDICATES
;;
;; ======================================================================
;; dracula-state-active? : Any -> Boolean
Recognizes Dracula states with active computation .
(define (dracula-state-active? state)
(and (dracula-state? state)
(action? (dracula-state-action state))))
;; dracula-state-busy? : Any -> Boolean
Recognizes Dracula states with ongoing computation .
(define (dracula-state-busy? state)
(and (dracula-state? state)
(normal-action? (dracula-state-action state))))
;; dracula-state-error? : Any -> Boolean
Recognizes Dracula states with error in the computation .
(define (dracula-state-error? state)
(and (dracula-state? state)
(error-action? (dracula-state-action state))))
;; dracula-state-interrupt? : Any -> Boolean
Recognizes Dracula states with computation about to be interrupted .
(define (dracula-state-interrupt? state)
(and (dracula-state? state)
(interrupt-action? (dracula-state-action state))))
;; dracula-state-proof-chosen? : Any -> Boolean
Recognizes Dracula states with a selected proof .
(define (dracula-state-proof-chosen? state)
(and (dracula-state? state)
(symbol? (proof-table-current (dracula-state-table state)))))
;; dracula-state-acl2-open? : Any -> Boolean
Recognizes Dracula states with an ACL2 session for a selected proof .
(define (dracula-state-acl2-open? state)
(and (dracula-state-proof-chosen? state)
(proof-state-acl2-open? (dracula-state-current-proof state))))
;; ======================================================================
;;
;;
;; ======================================================================
(define initial-proof-table
(make-proof-table null #f (make-immutable-hasheq null)))
;; initial-dracula-state : DraculaState
;; A plain vanilla empty default initial state.
(define initial-dracula-state
(make-dracula-state #f initial-proof-table))
;; dracula-state-populate : DraculaState Proof -> DraculaState
Populates state with new proof text .
(define (dracula-state-populate state proof)
(make-dracula-state
(dracula-state-action state)
(proof-table-populate (dracula-state-table state) proof)))
(define (proof-table-populate table proof)
(match table
[(struct proof-table (old-names old-name old-hash))
(let* ([new-names (proof-parts proof)]
[new-name
(cond [(memq old-name new-names) old-name]
[else #f])]
[new-hash (proof-hash-populate old-hash proof)])
(make-proof-table new-names new-name new-hash))]))
(define (proof-hash-populate old-hash proof)
(for/fold
([hash old-hash])
([name (proof-parts proof)])
(let* ([part (proof-part proof name)]
[old-pstate (hash-ref/default hash name #f)]
[new-pstate (if old-pstate
(proof-state-populate old-pstate part)
(initial-proof-state part))])
(hash-set hash name new-pstate))))
;; ==================================================
;;
;; Activity updates
;;
;; ==================================================
;; dracula-state-pending : DraculaState String -> DraculaState
;; Report a pending operation in the current proof.
(define (dracula-state-pending state desc)
(make-dracula-state (make-normal-action desc) (dracula-state-table state)))
;; dracula-state-interrupt : DraculaState -> DraculaState
;; Report an interrupted operation in the current proof.
(define (dracula-state-interrupt state)
(make-dracula-state
(interrupt (dracula-state-action state))
(dracula-state-table state)))
(define (interrupt action)
(make-interrupt-action (action-desc action)))
;; dracula-state-error : DraculaState -> DraculaState
;; Report a failed operation in the current proof.
(define (dracula-state-error state)
(make-dracula-state
(if (dracula-state-action state)
(err (dracula-state-action state))
(make-error-action "internal failure"))
(dracula-state-table state)))
(define (err action)
(make-error-action (action-desc action)))
;; dracula-state-done : DraculaState -> DraculaState
;; Drop a pending or interrupted operation in the current proof.
(define (dracula-state-done state)
(make-dracula-state #f (dracula-state-table state)))
;; ==================================================
;;
;; Current proof updates
;;
;; ==================================================
;; dracula-state-choose : DraculaState (Or Symbol #f) -> DraculaState
;; Update the choice of current proof.
(define (dracula-state-choose state name)
(make-dracula-state
(dracula-state-action state)
(proof-table-choose (dracula-state-table state) name)))
(define (proof-table-choose table name)
(make-proof-table (proof-table-names table) name (proof-table-hash table)))
;; dracula-state-start-acl2 : DraculaState -> DraculaState
;; Records the start of ACL2 in the current proof.
(define (dracula-state-start-acl2 state acl2-state)
(dracula-state-update-current state proof-state-start-acl2 acl2-state))
;; dracula-state-update-acl2 : DraculaState ACL2State -> DraculaState
;; Records input from ACL2.
(define (dracula-state-update-acl2 state acl2-state)
(dracula-state-update-current state proof-state-update-acl2 acl2-state))
;; dracula-state-advance : DraculaState ACL2State (Or Sexp #f) -> DraculaState
;; Advance the current proof to the next term, saving the current state.
(define (dracula-state-advance state acl2-state saved)
(dracula-state-update-current state proof-state-advance acl2-state saved))
;; dracula-state-rewind : DraculaState -> DraculaState
;; Rewind the current proof.
(define (dracula-state-rewind state)
(dracula-state-update-current state proof-state-rewind))
;; dracula-state-edit : DraculaState -> DraculaState
Marks the current proof as edited .
(define (dracula-state-edit state)
(dracula-state-update-current state proof-state-edit))
;; dracula-state-stop-acl2 : DraculaState -> DraculaState
;; Records the termination of ACL2 in the current proof.
(define (dracula-state-stop-acl2 state)
(dracula-state-update-current
(dracula-state-done state)
proof-state-stop-acl2))
;; ======================================================================
;;
;; ACCESSORS
;;
;; ======================================================================
dracula - state - names : DraculaState - > ( )
;; Produces the set of names of proof parts.
(define (dracula-state-names state)
(proof-table-names (dracula-state-table state)))
;; dracula-state-activity : DraculaState -> String
Describes an active computation in a state .
(define (dracula-state-activity state)
(action-desc (dracula-state-action state)))
;; dracula-state-current-name : DraculaState -> Symbol
;; Reports the currently chosen proof part.
(define (dracula-state-current-name state)
(proof-table-current (dracula-state-table state)))
;; dracula-state-proof-tree : DraculaState -> String
;; Extracts the proof tree from ACL2 in the current proof.
(define (dracula-state-proof-tree state)
(proof-state-proof-tree (dracula-state-current-proof state)))
;; dracula-state-initial-prompt : DraculaState -> String
;; Extracts the prompt before the current term.
(define (dracula-state-initial-prompt state)
(proof-state-initial-prompt (dracula-state-current-proof state)))
;; dracula-state-acl2-input : DraculaState -> String
;; Extracts the input from ACL2 in the current proof.
(define (dracula-state-acl2-input state)
(proof-state-acl2-input (dracula-state-current-proof state)))
;; dracula-state-acl2-output : DraculaState -> String
;; Extracts the output from ACL2 in the current proof.
(define (dracula-state-acl2-output state)
(proof-state-acl2-output (dracula-state-current-proof state)))
;; dracula-state-final-prompt : DraculaState -> String
;; Extracts the prompt after the current term.
(define (dracula-state-final-prompt state)
(proof-state-final-prompt (dracula-state-current-proof state)))
;; dracula-state-total-output : DraculaState -> String
;; Returns all of ACL2's output for the current proof.
(define (dracula-state-total-output state)
(proof-state-total-output (dracula-state-current-proof state)))
;; dracula-state-start-of-proof? : DraculaState -> Boolean
;; Reports whether the current proof is at the start or not.
(define (dracula-state-start-of-proof? state)
(proof-state-start-of-proof? (dracula-state-current-proof state)))
;; dracula-state-end-of-proof? : DraculaState -> Boolean
;; Reports whether the current proof is at the end or not.
(define (dracula-state-end-of-proof? state)
(proof-state-end-of-proof? (dracula-state-current-proof state)))
dracula - state - at - first - term ? : DraculaState - > Boolean
;; Reports whether the current proof is at the start or not.
(define (dracula-state-at-first-term? state)
(proof-state-at-first-term? (dracula-state-current-proof state)))
;; dracula-state-at-last-term? : DraculaState -> Boolean
;; Reports whether the current proof is at the end or not.
(define (dracula-state-at-last-term? state)
(proof-state-at-last-term? (dracula-state-current-proof state)))
;; dracula-state-finished? : DraculaState -> Boolean
;; Reports whether the current term has been successfully finished yet.
(define (dracula-state-finished? state)
(proof-state-finished? (dracula-state-current-proof state)))
;; dracula-state-admitted? : DraculaState -> Boolean
;; Reports whether the current term has been successfully admitted yet.
(define (dracula-state-admitted? state)
(proof-state-admitted? (dracula-state-current-proof state)))
;; dracula-state-edited? : DraculaState -> Boolean
;; Reports whether the current term has been edited since it was sent to ACL2.
(define (dracula-state-edited? state)
(proof-state-edited? (dracula-state-current-proof state)))
;; dracula-state-next-sexp : DraculaState -> Sexp
;; Reports the next term to admit.
(define (dracula-state-next-sexp state)
(proof-state-next-sexp (dracula-state-current-proof state)))
;; dracula-state-save-before-next-sexp : DraculaState -> Sexp
;; Reports the expression to save the current state.
(define (dracula-state-save-before-next-sexp state)
(proof-state-save-before-next-sexp (dracula-state-current-proof state)))
;; dracula-state-restore-saved-sexp : DraculaState -> Sexp
;; Reports the event to restore the saved state.
(define (dracula-state-restore-saved-sexp state)
(proof-state-restore-saved-sexp (dracula-state-current-proof state)))
dracula - state - first - admitted - position : DraculaState - > Nat
(define (dracula-state-first-admitted-position state)
(proof-state-first-admitted-position (dracula-state-current-proof state)))
;; dracula-state-last-admitted-position : DraculaState -> Nat
(define (dracula-state-last-admitted-position state)
(proof-state-last-admitted-position (dracula-state-current-proof state)))
;; dracula-state-last-attempted-position : DraculaState -> Nat
(define (dracula-state-last-attempted-position state)
(proof-state-last-attempted-position (dracula-state-current-proof state)))
;; dracula-state-term-index : DraculaState -> Nat
(define (dracula-state-term-index state)
(proof-state-term-index (dracula-state-current-proof state)))
;; dracula-state-proof-size : DraculaState -> Nat
(define (dracula-state-proof-size state)
(proof-state-size (dracula-state-current-proof state)))
;; dracula-state-index-before-pos : DraculaState Nat -> Nat
(define (dracula-state-index-before-pos state pos)
(proof-state-index-before-pos (dracula-state-current-proof state) pos))
;; dracula-state-index-after-pos : DraculaState Nat -> Nat
(define (dracula-state-index-after-pos state pos)
(proof-state-index-after-pos (dracula-state-current-proof state) pos))
;; ======================================================================
;;
;; HELPERS
;;
;; ======================================================================
;; dracula-state-update-current :
;; DraculaState (ProofState T ... -> ProofState) T ... -> DraculaState
;; Transform the current proof state.
(define (dracula-state-update-current state update . args)
(make-dracula-state
(dracula-state-action state)
(apply proof-table-update-current (dracula-state-table state) update args)))
(define (proof-table-update-current table update . args)
(make-proof-table
(proof-table-names table)
(proof-table-current table)
(hash-update (proof-table-hash table)
(proof-table-current table)
(lambda (pstate) (apply update pstate args)))))
;; dracula-state-current-proof : DraculaState -> ProofState
;; Produce the current proof state.
(define (dracula-state-current-proof state)
(let* ([table (dracula-state-table state)]
[hash (proof-table-hash table)]
[current (proof-table-current table)])
(hash-ref/check hash current)))
;; ======================================================================
;;
;; EXPORTS
;;
;; ======================================================================
(provide/contract
;; ==================================================
;;
;; Predicates
;;
;; ==================================================
[dracula-state? (-> any/c boolean?)]
;; ==============================
;; Activity predicates
;; ==============================
[dracula-state-active? (-> any/c boolean?)] ;; any activity
[dracula-state-busy? (-> any/c boolean?)] ;; normal activity
[dracula-state-error? (-> any/c boolean?)] ;; error activity
[dracula-state-interrupt? (-> any/c boolean?)] ;; interrupted activity
;; ==============================
;; Current proof predicates.
;; ==============================
[dracula-state-proof-chosen? (-> any/c boolean?)]
[dracula-state-acl2-open? (-> any/c boolean?)] ;; implies previous
;; ==================================================
;;
;; Constructors
;;
;; ==================================================
[initial-dracula-state dracula-state?]
[dracula-state-populate (-> dracula-state? proof? dracula-state?)]
;; ==============================
;; Activity updates
;; ==============================
[dracula-state-pending
(-> (and/c dracula-state?
(not/c dracula-state-interrupt?)
(not/c dracula-state-error?))
string?
dracula-state-busy?)]
[dracula-state-error
(-> dracula-state-acl2-open? dracula-state-error?)]
[dracula-state-interrupt
(-> (and/c dracula-state? (not/c dracula-state-error?))
dracula-state-interrupt?)]
[dracula-state-done
(-> (and/c dracula-state-active? (not/c dracula-state-error?))
(and/c dracula-state? (not/c dracula-state-active?)))]
;; ==============================
;; Current proof updates
;; ==============================
[dracula-state-choose
(-> dracula-state? symbol? dracula-state-proof-chosen?)]
[dracula-state-start-acl2
(-> (and/c dracula-state-proof-chosen? (not/c dracula-state-acl2-open?)) acl2?
dracula-state-acl2-open?)]
[dracula-state-update-acl2
(-> dracula-state-acl2-open? acl2? dracula-state-acl2-open?)]
[dracula-state-advance
(-> (and/c dracula-state-acl2-open?
dracula-state-admitted?
(not/c dracula-state-at-last-term?))
acl2?
(or/c sexp/c #f)
dracula-state-acl2-open?)]
[dracula-state-rewind
(-> (and/c dracula-state-acl2-open? (not/c dracula-state-at-first-term?))
dracula-state-acl2-open?)]
[dracula-state-edit (-> dracula-state-acl2-open? dracula-state-acl2-open?)]
[dracula-state-stop-acl2
(-> dracula-state-acl2-open?
(and/c dracula-state-proof-chosen?
(not/c dracula-state-acl2-open?)
(not/c dracula-state-active?)))]
;; ==================================================
;;
;; Accessors
;;
;; ==================================================
[dracula-state-names (-> dracula-state? (listof symbol?))]
;; ==============================
;; Activity data
;; ==============================
[dracula-state-activity (-> dracula-state-active? string?)]
;; ==============================
;; Current proof data
;; ==============================
[dracula-state-at-first-term? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-at-last-term? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-current-name (-> dracula-state-proof-chosen? symbol?)]
[dracula-state-next-sexp
(-> (and/c dracula-state-acl2-open? (not/c dracula-state-at-last-term?))
sexp/c)]
[dracula-state-save-before-next-sexp
(-> (and/c dracula-state-acl2-open? (not/c dracula-state-at-last-term?))
sexp/c)]
[dracula-state-restore-saved-sexp
(-> (and/c dracula-state-admitted? (not/c dracula-state-at-first-term?))
sexp/c)]
[dracula-state-start-of-proof? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-end-of-proof? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-finished? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-admitted? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-edited? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-proof-tree (-> dracula-state-acl2-open? string?)]
[dracula-state-initial-prompt (-> dracula-state-acl2-open? string?)]
[dracula-state-acl2-input (-> dracula-state-acl2-open? string?)]
[dracula-state-acl2-output (-> dracula-state-acl2-open? string?)]
[dracula-state-final-prompt (-> dracula-state-acl2-open? string?)]
[dracula-state-total-output (-> dracula-state-acl2-open? string?)]
[dracula-state-proof-size
(-> dracula-state-proof-chosen? exact-nonnegative-integer?)]
[dracula-state-term-index
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-first-admitted-position
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-last-admitted-position
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-last-attempted-position
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-index-before-pos
(-> dracula-state-acl2-open? exact-nonnegative-integer?
exact-nonnegative-integer?)]
[dracula-state-index-after-pos
(-> dracula-state-acl2-open? exact-nonnegative-integer?
exact-nonnegative-integer?)]
)
| null | https://raw.githubusercontent.com/carl-eastlund/dracula/a937f4b40463779246e3544e4021c53744a33847/drscheme/dracula-state.rkt | racket | ======================================================================
DATA DEFINITION
======================================================================
A DraculaState is: (make-dracula-state Action ProofTable)
An Action is either:
- #f
- (make-error-action String)
- (make-normal-action String)
- (make-interrupt-action String)
A ProofTable is: (make-proof-table names current hash)
and current : (Or Symbol #f)
and hash : (IHasheq Symbol ProofState)
======================================================================
======================================================================
dracula-state-active? : Any -> Boolean
dracula-state-busy? : Any -> Boolean
dracula-state-error? : Any -> Boolean
dracula-state-interrupt? : Any -> Boolean
dracula-state-proof-chosen? : Any -> Boolean
dracula-state-acl2-open? : Any -> Boolean
======================================================================
======================================================================
initial-dracula-state : DraculaState
A plain vanilla empty default initial state.
dracula-state-populate : DraculaState Proof -> DraculaState
==================================================
Activity updates
==================================================
dracula-state-pending : DraculaState String -> DraculaState
Report a pending operation in the current proof.
dracula-state-interrupt : DraculaState -> DraculaState
Report an interrupted operation in the current proof.
dracula-state-error : DraculaState -> DraculaState
Report a failed operation in the current proof.
dracula-state-done : DraculaState -> DraculaState
Drop a pending or interrupted operation in the current proof.
==================================================
Current proof updates
==================================================
dracula-state-choose : DraculaState (Or Symbol #f) -> DraculaState
Update the choice of current proof.
dracula-state-start-acl2 : DraculaState -> DraculaState
Records the start of ACL2 in the current proof.
dracula-state-update-acl2 : DraculaState ACL2State -> DraculaState
Records input from ACL2.
dracula-state-advance : DraculaState ACL2State (Or Sexp #f) -> DraculaState
Advance the current proof to the next term, saving the current state.
dracula-state-rewind : DraculaState -> DraculaState
Rewind the current proof.
dracula-state-edit : DraculaState -> DraculaState
dracula-state-stop-acl2 : DraculaState -> DraculaState
Records the termination of ACL2 in the current proof.
======================================================================
ACCESSORS
======================================================================
Produces the set of names of proof parts.
dracula-state-activity : DraculaState -> String
dracula-state-current-name : DraculaState -> Symbol
Reports the currently chosen proof part.
dracula-state-proof-tree : DraculaState -> String
Extracts the proof tree from ACL2 in the current proof.
dracula-state-initial-prompt : DraculaState -> String
Extracts the prompt before the current term.
dracula-state-acl2-input : DraculaState -> String
Extracts the input from ACL2 in the current proof.
dracula-state-acl2-output : DraculaState -> String
Extracts the output from ACL2 in the current proof.
dracula-state-final-prompt : DraculaState -> String
Extracts the prompt after the current term.
dracula-state-total-output : DraculaState -> String
Returns all of ACL2's output for the current proof.
dracula-state-start-of-proof? : DraculaState -> Boolean
Reports whether the current proof is at the start or not.
dracula-state-end-of-proof? : DraculaState -> Boolean
Reports whether the current proof is at the end or not.
Reports whether the current proof is at the start or not.
dracula-state-at-last-term? : DraculaState -> Boolean
Reports whether the current proof is at the end or not.
dracula-state-finished? : DraculaState -> Boolean
Reports whether the current term has been successfully finished yet.
dracula-state-admitted? : DraculaState -> Boolean
Reports whether the current term has been successfully admitted yet.
dracula-state-edited? : DraculaState -> Boolean
Reports whether the current term has been edited since it was sent to ACL2.
dracula-state-next-sexp : DraculaState -> Sexp
Reports the next term to admit.
dracula-state-save-before-next-sexp : DraculaState -> Sexp
Reports the expression to save the current state.
dracula-state-restore-saved-sexp : DraculaState -> Sexp
Reports the event to restore the saved state.
dracula-state-last-admitted-position : DraculaState -> Nat
dracula-state-last-attempted-position : DraculaState -> Nat
dracula-state-term-index : DraculaState -> Nat
dracula-state-proof-size : DraculaState -> Nat
dracula-state-index-before-pos : DraculaState Nat -> Nat
dracula-state-index-after-pos : DraculaState Nat -> Nat
======================================================================
HELPERS
======================================================================
dracula-state-update-current :
DraculaState (ProofState T ... -> ProofState) T ... -> DraculaState
Transform the current proof state.
dracula-state-current-proof : DraculaState -> ProofState
Produce the current proof state.
======================================================================
EXPORTS
======================================================================
==================================================
Predicates
==================================================
==============================
Activity predicates
==============================
any activity
normal activity
error activity
interrupted activity
==============================
Current proof predicates.
==============================
implies previous
==================================================
Constructors
==================================================
==============================
Activity updates
==============================
==============================
Current proof updates
==============================
==================================================
Accessors
==================================================
==============================
Activity data
==============================
==============================
Current proof data
============================== | #lang racket
(require "../proof/proof.rkt"
"../acl2/acl2.rkt"
"../acl2/rep.rkt"
"../private/hash.rkt"
"proof-state.rkt")
where names : ( )
(define-struct dracula-state (action table) #:prefab)
(define-struct action (desc) #:prefab)
(define-struct (error-action action) () #:prefab)
(define-struct (normal-action action) () #:prefab)
(define-struct (interrupt-action action) () #:prefab)
(define-struct proof-table (names current hash) #:prefab)
PREDICATES
Recognizes Dracula states with active computation .
(define (dracula-state-active? state)
(and (dracula-state? state)
(action? (dracula-state-action state))))
Recognizes Dracula states with ongoing computation .
(define (dracula-state-busy? state)
(and (dracula-state? state)
(normal-action? (dracula-state-action state))))
Recognizes Dracula states with error in the computation .
(define (dracula-state-error? state)
(and (dracula-state? state)
(error-action? (dracula-state-action state))))
Recognizes Dracula states with computation about to be interrupted .
(define (dracula-state-interrupt? state)
(and (dracula-state? state)
(interrupt-action? (dracula-state-action state))))
Recognizes Dracula states with a selected proof .
(define (dracula-state-proof-chosen? state)
(and (dracula-state? state)
(symbol? (proof-table-current (dracula-state-table state)))))
Recognizes Dracula states with an ACL2 session for a selected proof .
(define (dracula-state-acl2-open? state)
(and (dracula-state-proof-chosen? state)
(proof-state-acl2-open? (dracula-state-current-proof state))))
(define initial-proof-table
(make-proof-table null #f (make-immutable-hasheq null)))
(define initial-dracula-state
(make-dracula-state #f initial-proof-table))
Populates state with new proof text .
(define (dracula-state-populate state proof)
(make-dracula-state
(dracula-state-action state)
(proof-table-populate (dracula-state-table state) proof)))
(define (proof-table-populate table proof)
(match table
[(struct proof-table (old-names old-name old-hash))
(let* ([new-names (proof-parts proof)]
[new-name
(cond [(memq old-name new-names) old-name]
[else #f])]
[new-hash (proof-hash-populate old-hash proof)])
(make-proof-table new-names new-name new-hash))]))
(define (proof-hash-populate old-hash proof)
(for/fold
([hash old-hash])
([name (proof-parts proof)])
(let* ([part (proof-part proof name)]
[old-pstate (hash-ref/default hash name #f)]
[new-pstate (if old-pstate
(proof-state-populate old-pstate part)
(initial-proof-state part))])
(hash-set hash name new-pstate))))
(define (dracula-state-pending state desc)
(make-dracula-state (make-normal-action desc) (dracula-state-table state)))
(define (dracula-state-interrupt state)
(make-dracula-state
(interrupt (dracula-state-action state))
(dracula-state-table state)))
(define (interrupt action)
(make-interrupt-action (action-desc action)))
(define (dracula-state-error state)
(make-dracula-state
(if (dracula-state-action state)
(err (dracula-state-action state))
(make-error-action "internal failure"))
(dracula-state-table state)))
(define (err action)
(make-error-action (action-desc action)))
(define (dracula-state-done state)
(make-dracula-state #f (dracula-state-table state)))
(define (dracula-state-choose state name)
(make-dracula-state
(dracula-state-action state)
(proof-table-choose (dracula-state-table state) name)))
(define (proof-table-choose table name)
(make-proof-table (proof-table-names table) name (proof-table-hash table)))
(define (dracula-state-start-acl2 state acl2-state)
(dracula-state-update-current state proof-state-start-acl2 acl2-state))
(define (dracula-state-update-acl2 state acl2-state)
(dracula-state-update-current state proof-state-update-acl2 acl2-state))
(define (dracula-state-advance state acl2-state saved)
(dracula-state-update-current state proof-state-advance acl2-state saved))
(define (dracula-state-rewind state)
(dracula-state-update-current state proof-state-rewind))
Marks the current proof as edited .
(define (dracula-state-edit state)
(dracula-state-update-current state proof-state-edit))
(define (dracula-state-stop-acl2 state)
(dracula-state-update-current
(dracula-state-done state)
proof-state-stop-acl2))
dracula - state - names : DraculaState - > ( )
(define (dracula-state-names state)
(proof-table-names (dracula-state-table state)))
Describes an active computation in a state .
(define (dracula-state-activity state)
(action-desc (dracula-state-action state)))
(define (dracula-state-current-name state)
(proof-table-current (dracula-state-table state)))
(define (dracula-state-proof-tree state)
(proof-state-proof-tree (dracula-state-current-proof state)))
(define (dracula-state-initial-prompt state)
(proof-state-initial-prompt (dracula-state-current-proof state)))
(define (dracula-state-acl2-input state)
(proof-state-acl2-input (dracula-state-current-proof state)))
(define (dracula-state-acl2-output state)
(proof-state-acl2-output (dracula-state-current-proof state)))
(define (dracula-state-final-prompt state)
(proof-state-final-prompt (dracula-state-current-proof state)))
(define (dracula-state-total-output state)
(proof-state-total-output (dracula-state-current-proof state)))
(define (dracula-state-start-of-proof? state)
(proof-state-start-of-proof? (dracula-state-current-proof state)))
(define (dracula-state-end-of-proof? state)
(proof-state-end-of-proof? (dracula-state-current-proof state)))
dracula - state - at - first - term ? : DraculaState - > Boolean
(define (dracula-state-at-first-term? state)
(proof-state-at-first-term? (dracula-state-current-proof state)))
(define (dracula-state-at-last-term? state)
(proof-state-at-last-term? (dracula-state-current-proof state)))
(define (dracula-state-finished? state)
(proof-state-finished? (dracula-state-current-proof state)))
(define (dracula-state-admitted? state)
(proof-state-admitted? (dracula-state-current-proof state)))
(define (dracula-state-edited? state)
(proof-state-edited? (dracula-state-current-proof state)))
(define (dracula-state-next-sexp state)
(proof-state-next-sexp (dracula-state-current-proof state)))
(define (dracula-state-save-before-next-sexp state)
(proof-state-save-before-next-sexp (dracula-state-current-proof state)))
(define (dracula-state-restore-saved-sexp state)
(proof-state-restore-saved-sexp (dracula-state-current-proof state)))
dracula - state - first - admitted - position : DraculaState - > Nat
(define (dracula-state-first-admitted-position state)
(proof-state-first-admitted-position (dracula-state-current-proof state)))
(define (dracula-state-last-admitted-position state)
(proof-state-last-admitted-position (dracula-state-current-proof state)))
(define (dracula-state-last-attempted-position state)
(proof-state-last-attempted-position (dracula-state-current-proof state)))
(define (dracula-state-term-index state)
(proof-state-term-index (dracula-state-current-proof state)))
(define (dracula-state-proof-size state)
(proof-state-size (dracula-state-current-proof state)))
(define (dracula-state-index-before-pos state pos)
(proof-state-index-before-pos (dracula-state-current-proof state) pos))
(define (dracula-state-index-after-pos state pos)
(proof-state-index-after-pos (dracula-state-current-proof state) pos))
(define (dracula-state-update-current state update . args)
(make-dracula-state
(dracula-state-action state)
(apply proof-table-update-current (dracula-state-table state) update args)))
(define (proof-table-update-current table update . args)
(make-proof-table
(proof-table-names table)
(proof-table-current table)
(hash-update (proof-table-hash table)
(proof-table-current table)
(lambda (pstate) (apply update pstate args)))))
(define (dracula-state-current-proof state)
(let* ([table (dracula-state-table state)]
[hash (proof-table-hash table)]
[current (proof-table-current table)])
(hash-ref/check hash current)))
(provide/contract
[dracula-state? (-> any/c boolean?)]
[dracula-state-proof-chosen? (-> any/c boolean?)]
[initial-dracula-state dracula-state?]
[dracula-state-populate (-> dracula-state? proof? dracula-state?)]
[dracula-state-pending
(-> (and/c dracula-state?
(not/c dracula-state-interrupt?)
(not/c dracula-state-error?))
string?
dracula-state-busy?)]
[dracula-state-error
(-> dracula-state-acl2-open? dracula-state-error?)]
[dracula-state-interrupt
(-> (and/c dracula-state? (not/c dracula-state-error?))
dracula-state-interrupt?)]
[dracula-state-done
(-> (and/c dracula-state-active? (not/c dracula-state-error?))
(and/c dracula-state? (not/c dracula-state-active?)))]
[dracula-state-choose
(-> dracula-state? symbol? dracula-state-proof-chosen?)]
[dracula-state-start-acl2
(-> (and/c dracula-state-proof-chosen? (not/c dracula-state-acl2-open?)) acl2?
dracula-state-acl2-open?)]
[dracula-state-update-acl2
(-> dracula-state-acl2-open? acl2? dracula-state-acl2-open?)]
[dracula-state-advance
(-> (and/c dracula-state-acl2-open?
dracula-state-admitted?
(not/c dracula-state-at-last-term?))
acl2?
(or/c sexp/c #f)
dracula-state-acl2-open?)]
[dracula-state-rewind
(-> (and/c dracula-state-acl2-open? (not/c dracula-state-at-first-term?))
dracula-state-acl2-open?)]
[dracula-state-edit (-> dracula-state-acl2-open? dracula-state-acl2-open?)]
[dracula-state-stop-acl2
(-> dracula-state-acl2-open?
(and/c dracula-state-proof-chosen?
(not/c dracula-state-acl2-open?)
(not/c dracula-state-active?)))]
[dracula-state-names (-> dracula-state? (listof symbol?))]
[dracula-state-activity (-> dracula-state-active? string?)]
[dracula-state-at-first-term? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-at-last-term? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-current-name (-> dracula-state-proof-chosen? symbol?)]
[dracula-state-next-sexp
(-> (and/c dracula-state-acl2-open? (not/c dracula-state-at-last-term?))
sexp/c)]
[dracula-state-save-before-next-sexp
(-> (and/c dracula-state-acl2-open? (not/c dracula-state-at-last-term?))
sexp/c)]
[dracula-state-restore-saved-sexp
(-> (and/c dracula-state-admitted? (not/c dracula-state-at-first-term?))
sexp/c)]
[dracula-state-start-of-proof? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-end-of-proof? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-finished? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-admitted? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-edited? (-> dracula-state-acl2-open? boolean?)]
[dracula-state-proof-tree (-> dracula-state-acl2-open? string?)]
[dracula-state-initial-prompt (-> dracula-state-acl2-open? string?)]
[dracula-state-acl2-input (-> dracula-state-acl2-open? string?)]
[dracula-state-acl2-output (-> dracula-state-acl2-open? string?)]
[dracula-state-final-prompt (-> dracula-state-acl2-open? string?)]
[dracula-state-total-output (-> dracula-state-acl2-open? string?)]
[dracula-state-proof-size
(-> dracula-state-proof-chosen? exact-nonnegative-integer?)]
[dracula-state-term-index
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-first-admitted-position
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-last-admitted-position
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-last-attempted-position
(-> dracula-state-acl2-open? exact-nonnegative-integer?)]
[dracula-state-index-before-pos
(-> dracula-state-acl2-open? exact-nonnegative-integer?
exact-nonnegative-integer?)]
[dracula-state-index-after-pos
(-> dracula-state-acl2-open? exact-nonnegative-integer?
exact-nonnegative-integer?)]
)
|
8bbc864506a60fecac440455700509371461bfffc01d52a4f9c43ef63b650edf | tek/ribosome | Text.hs | -- |Combinators for 'Text'.
module Ribosome.Text where
import Data.Char (toUpper)
import qualified Data.Text as Text
|Escape a single quote Neovim - style by replacing it with two single quotes .
escapeQuote :: Char -> Text
escapeQuote = \case
'\'' ->
"''"
a ->
Text.singleton a
|Escape all single quotes Neovim - style by replacing them with two single quotes .
escapeQuotes :: Text -> Text
escapeQuotes =
Text.concatMap escapeQuote
|Upcase the first letter of a ' Text ' , if any .
capitalize :: Text -> Text
capitalize a =
maybe "" run (Text.uncons a)
where
run (h, t) =
Text.cons (toUpper h) t
| null | https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/ribosome/lib/Ribosome/Text.hs | haskell | |Combinators for 'Text'. | module Ribosome.Text where
import Data.Char (toUpper)
import qualified Data.Text as Text
|Escape a single quote Neovim - style by replacing it with two single quotes .
escapeQuote :: Char -> Text
escapeQuote = \case
'\'' ->
"''"
a ->
Text.singleton a
|Escape all single quotes Neovim - style by replacing them with two single quotes .
escapeQuotes :: Text -> Text
escapeQuotes =
Text.concatMap escapeQuote
|Upcase the first letter of a ' Text ' , if any .
capitalize :: Text -> Text
capitalize a =
maybe "" run (Text.uncons a)
where
run (h, t) =
Text.cons (toUpper h) t
|
fcd1983954e2c5827efbe4eb54faebcb9a8986f92dbd6c7464e27cb4f9f545c0 | int-index/ether | T3.hs | module Regression.T3 (test3) where
import Ether
import qualified Control.Monad.Reader as T
import qualified Control.Monad.State as T
import Test.Tasty
import Test.Tasty.QuickCheck
data RTag
data STag
testMTL :: (T.MonadReader Int m, T.MonadState Int m) => m Int
testMTL = do
b <- T.get
a <- T.ask
T.put (a + b)
return (a * b)
testEther
:: (MonadReader STag Int m, MonadState STag Int m, MonadReader RTag Int m)
=> m (Int, Int, Int)
testEther = local @RTag (*2) $ do
a_mul_b <- tagAttach @STag testMTL
a_add_b <- get @STag
modify @STag negate
c <- ask @RTag
return (a_mul_b, a_add_b, c)
runner1 s r
= flip (runReader @RTag) (negate r)
. flip (runReaderT @STag) r
. flip (runStateT @STag) s
runner2 s r
= flip (runReader @RTag) (negate r)
. flip (runStateT @STag) s
. flip (runReaderT @STag) r
test3 :: TestTree
test3 = testGroup "T3: Tag attachement"
[ testProperty "runner₁ works"
$ \s r -> property
$ (==)
(runner1 s r testEther)
((s * r, s + r, negate r * 2), negate (s + r))
, testProperty "runner₂ works"
$ \s r -> property
$ (==)
(runner2 s r testEther)
((s * r, s + r, negate r * 2), negate (s + r))
, testProperty "runner₁ == runner₂"
$ \s r -> property
$ runner1 s r testEther == runner2 s r testEther
]
| null | https://raw.githubusercontent.com/int-index/ether/84c1d560da241c8111d1a3c98d9a896f0c62087b/test/Regression/T3.hs | haskell | module Regression.T3 (test3) where
import Ether
import qualified Control.Monad.Reader as T
import qualified Control.Monad.State as T
import Test.Tasty
import Test.Tasty.QuickCheck
data RTag
data STag
testMTL :: (T.MonadReader Int m, T.MonadState Int m) => m Int
testMTL = do
b <- T.get
a <- T.ask
T.put (a + b)
return (a * b)
testEther
:: (MonadReader STag Int m, MonadState STag Int m, MonadReader RTag Int m)
=> m (Int, Int, Int)
testEther = local @RTag (*2) $ do
a_mul_b <- tagAttach @STag testMTL
a_add_b <- get @STag
modify @STag negate
c <- ask @RTag
return (a_mul_b, a_add_b, c)
runner1 s r
= flip (runReader @RTag) (negate r)
. flip (runReaderT @STag) r
. flip (runStateT @STag) s
runner2 s r
= flip (runReader @RTag) (negate r)
. flip (runStateT @STag) s
. flip (runReaderT @STag) r
test3 :: TestTree
test3 = testGroup "T3: Tag attachement"
[ testProperty "runner₁ works"
$ \s r -> property
$ (==)
(runner1 s r testEther)
((s * r, s + r, negate r * 2), negate (s + r))
, testProperty "runner₂ works"
$ \s r -> property
$ (==)
(runner2 s r testEther)
((s * r, s + r, negate r * 2), negate (s + r))
, testProperty "runner₁ == runner₂"
$ \s r -> property
$ runner1 s r testEther == runner2 s r testEther
]
|
|
8453df59285e17da0907176d1deb381f0070ea6339b82661e1258b037c4a86dd | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | PortalSubscriptionUpdate.hs | {-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
| Contains the types generated from the schema PortalSubscriptionUpdate
module StripeAPI.Types.PortalSubscriptionUpdate where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import {-# SOURCE #-} StripeAPI.Types.PortalSubscriptionUpdateProduct
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.portal_subscription_update@ in the specification.
data PortalSubscriptionUpdate = PortalSubscriptionUpdate
{ -- | default_allowed_updates: The types of subscription updates that are supported for items listed in the \`products\` attribute. When empty, subscriptions are not updateable.
portalSubscriptionUpdateDefaultAllowedUpdates :: ([PortalSubscriptionUpdateDefaultAllowedUpdates']),
-- | enabled: Whether the feature is enabled.
portalSubscriptionUpdateEnabled :: GHC.Types.Bool,
-- | products: The list of products that support subscription updates.
portalSubscriptionUpdateProducts :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable ([PortalSubscriptionUpdateProduct]))),
| proration_behavior : Determines how to handle prorations resulting from subscription updates . Valid values are , \`create_prorations\ ` , and \`always_invoice\ ` .
portalSubscriptionUpdateProrationBehavior :: PortalSubscriptionUpdateProrationBehavior'
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON PortalSubscriptionUpdate where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["default_allowed_updates" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateDefaultAllowedUpdates obj] : ["enabled" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateEnabled obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("products" Data.Aeson.Types.ToJSON..=)) (portalSubscriptionUpdateProducts obj) : ["proration_behavior" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateProrationBehavior obj] : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["default_allowed_updates" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateDefaultAllowedUpdates obj] : ["enabled" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateEnabled obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("products" Data.Aeson.Types.ToJSON..=)) (portalSubscriptionUpdateProducts obj) : ["proration_behavior" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateProrationBehavior obj] : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON PortalSubscriptionUpdate where
parseJSON = Data.Aeson.Types.FromJSON.withObject "PortalSubscriptionUpdate" (\obj -> (((GHC.Base.pure PortalSubscriptionUpdate GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "default_allowed_updates")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "enabled")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "products")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "proration_behavior"))
| Create a new ' PortalSubscriptionUpdate ' with all required fields .
mkPortalSubscriptionUpdate ::
-- | 'portalSubscriptionUpdateDefaultAllowedUpdates'
[PortalSubscriptionUpdateDefaultAllowedUpdates'] ->
-- | 'portalSubscriptionUpdateEnabled'
GHC.Types.Bool ->
-- | 'portalSubscriptionUpdateProrationBehavior'
PortalSubscriptionUpdateProrationBehavior' ->
PortalSubscriptionUpdate
mkPortalSubscriptionUpdate portalSubscriptionUpdateDefaultAllowedUpdates portalSubscriptionUpdateEnabled portalSubscriptionUpdateProrationBehavior =
PortalSubscriptionUpdate
{ portalSubscriptionUpdateDefaultAllowedUpdates = portalSubscriptionUpdateDefaultAllowedUpdates,
portalSubscriptionUpdateEnabled = portalSubscriptionUpdateEnabled,
portalSubscriptionUpdateProducts = GHC.Maybe.Nothing,
portalSubscriptionUpdateProrationBehavior = portalSubscriptionUpdateProrationBehavior
}
-- | Defines the enum schema located at @components.schemas.portal_subscription_update.properties.default_allowed_updates.items@ in the specification.
data PortalSubscriptionUpdateDefaultAllowedUpdates'
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
PortalSubscriptionUpdateDefaultAllowedUpdates'Other Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
PortalSubscriptionUpdateDefaultAllowedUpdates'Typed Data.Text.Internal.Text
| -- | Represents the JSON value @"price"@
PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPrice
| -- | Represents the JSON value @"promotion_code"@
PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPromotionCode
| Represents the JSON value @"quantity"@
PortalSubscriptionUpdateDefaultAllowedUpdates'EnumQuantity
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON PortalSubscriptionUpdateDefaultAllowedUpdates' where
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'Other val) = val
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPrice) = "price"
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPromotionCode) = "promotion_code"
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'EnumQuantity) = "quantity"
instance Data.Aeson.Types.FromJSON.FromJSON PortalSubscriptionUpdateDefaultAllowedUpdates' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "price" -> PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPrice
| val GHC.Classes.== "promotion_code" -> PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPromotionCode
| val GHC.Classes.== "quantity" -> PortalSubscriptionUpdateDefaultAllowedUpdates'EnumQuantity
| GHC.Base.otherwise -> PortalSubscriptionUpdateDefaultAllowedUpdates'Other val
)
| Defines the enum schema located at @components.schemas.portal_subscription_update.properties.proration_behavior@ in the specification .
--
Determines how to handle prorations resulting from subscription updates . Valid values are , \`create_prorations\ ` , and \`always_invoice\ ` .
data PortalSubscriptionUpdateProrationBehavior'
= -- | This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
PortalSubscriptionUpdateProrationBehavior'Other Data.Aeson.Types.Internal.Value
| -- | This constructor can be used to send values to the server which are not present in the specification yet.
PortalSubscriptionUpdateProrationBehavior'Typed Data.Text.Internal.Text
| -- | Represents the JSON value @"always_invoice"@
PortalSubscriptionUpdateProrationBehavior'EnumAlwaysInvoice
| -- | Represents the JSON value @"create_prorations"@
PortalSubscriptionUpdateProrationBehavior'EnumCreateProrations
| -- | Represents the JSON value @"none"@
PortalSubscriptionUpdateProrationBehavior'EnumNone
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON PortalSubscriptionUpdateProrationBehavior' where
toJSON (PortalSubscriptionUpdateProrationBehavior'Other val) = val
toJSON (PortalSubscriptionUpdateProrationBehavior'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (PortalSubscriptionUpdateProrationBehavior'EnumAlwaysInvoice) = "always_invoice"
toJSON (PortalSubscriptionUpdateProrationBehavior'EnumCreateProrations) = "create_prorations"
toJSON (PortalSubscriptionUpdateProrationBehavior'EnumNone) = "none"
instance Data.Aeson.Types.FromJSON.FromJSON PortalSubscriptionUpdateProrationBehavior' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "always_invoice" -> PortalSubscriptionUpdateProrationBehavior'EnumAlwaysInvoice
| val GHC.Classes.== "create_prorations" -> PortalSubscriptionUpdateProrationBehavior'EnumCreateProrations
| val GHC.Classes.== "none" -> PortalSubscriptionUpdateProrationBehavior'EnumNone
| GHC.Base.otherwise -> PortalSubscriptionUpdateProrationBehavior'Other val
)
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/PortalSubscriptionUpdate.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
# SOURCE #
| Defines the object schema located at @components.schemas.portal_subscription_update@ in the specification.
| default_allowed_updates: The types of subscription updates that are supported for items listed in the \`products\` attribute. When empty, subscriptions are not updateable.
| enabled: Whether the feature is enabled.
| products: The list of products that support subscription updates.
| 'portalSubscriptionUpdateDefaultAllowedUpdates'
| 'portalSubscriptionUpdateEnabled'
| 'portalSubscriptionUpdateProrationBehavior'
| Defines the enum schema located at @components.schemas.portal_subscription_update.properties.default_allowed_updates.items@ in the specification.
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"price"@
| Represents the JSON value @"promotion_code"@
| This case is used if the value encountered during decoding does not match any of the provided cases in the specification.
| This constructor can be used to send values to the server which are not present in the specification yet.
| Represents the JSON value @"always_invoice"@
| Represents the JSON value @"create_prorations"@
| Represents the JSON value @"none"@ | CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
| Contains the types generated from the schema PortalSubscriptionUpdate
module StripeAPI.Types.PortalSubscriptionUpdate where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
data PortalSubscriptionUpdate = PortalSubscriptionUpdate
portalSubscriptionUpdateDefaultAllowedUpdates :: ([PortalSubscriptionUpdateDefaultAllowedUpdates']),
portalSubscriptionUpdateEnabled :: GHC.Types.Bool,
portalSubscriptionUpdateProducts :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable ([PortalSubscriptionUpdateProduct]))),
| proration_behavior : Determines how to handle prorations resulting from subscription updates . Valid values are , \`create_prorations\ ` , and \`always_invoice\ ` .
portalSubscriptionUpdateProrationBehavior :: PortalSubscriptionUpdateProrationBehavior'
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON PortalSubscriptionUpdate where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["default_allowed_updates" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateDefaultAllowedUpdates obj] : ["enabled" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateEnabled obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("products" Data.Aeson.Types.ToJSON..=)) (portalSubscriptionUpdateProducts obj) : ["proration_behavior" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateProrationBehavior obj] : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["default_allowed_updates" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateDefaultAllowedUpdates obj] : ["enabled" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateEnabled obj] : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("products" Data.Aeson.Types.ToJSON..=)) (portalSubscriptionUpdateProducts obj) : ["proration_behavior" Data.Aeson.Types.ToJSON..= portalSubscriptionUpdateProrationBehavior obj] : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON PortalSubscriptionUpdate where
parseJSON = Data.Aeson.Types.FromJSON.withObject "PortalSubscriptionUpdate" (\obj -> (((GHC.Base.pure PortalSubscriptionUpdate GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "default_allowed_updates")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "enabled")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "products")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "proration_behavior"))
| Create a new ' PortalSubscriptionUpdate ' with all required fields .
mkPortalSubscriptionUpdate ::
[PortalSubscriptionUpdateDefaultAllowedUpdates'] ->
GHC.Types.Bool ->
PortalSubscriptionUpdateProrationBehavior' ->
PortalSubscriptionUpdate
mkPortalSubscriptionUpdate portalSubscriptionUpdateDefaultAllowedUpdates portalSubscriptionUpdateEnabled portalSubscriptionUpdateProrationBehavior =
PortalSubscriptionUpdate
{ portalSubscriptionUpdateDefaultAllowedUpdates = portalSubscriptionUpdateDefaultAllowedUpdates,
portalSubscriptionUpdateEnabled = portalSubscriptionUpdateEnabled,
portalSubscriptionUpdateProducts = GHC.Maybe.Nothing,
portalSubscriptionUpdateProrationBehavior = portalSubscriptionUpdateProrationBehavior
}
data PortalSubscriptionUpdateDefaultAllowedUpdates'
PortalSubscriptionUpdateDefaultAllowedUpdates'Other Data.Aeson.Types.Internal.Value
PortalSubscriptionUpdateDefaultAllowedUpdates'Typed Data.Text.Internal.Text
PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPrice
PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPromotionCode
| Represents the JSON value @"quantity"@
PortalSubscriptionUpdateDefaultAllowedUpdates'EnumQuantity
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON PortalSubscriptionUpdateDefaultAllowedUpdates' where
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'Other val) = val
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPrice) = "price"
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPromotionCode) = "promotion_code"
toJSON (PortalSubscriptionUpdateDefaultAllowedUpdates'EnumQuantity) = "quantity"
instance Data.Aeson.Types.FromJSON.FromJSON PortalSubscriptionUpdateDefaultAllowedUpdates' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "price" -> PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPrice
| val GHC.Classes.== "promotion_code" -> PortalSubscriptionUpdateDefaultAllowedUpdates'EnumPromotionCode
| val GHC.Classes.== "quantity" -> PortalSubscriptionUpdateDefaultAllowedUpdates'EnumQuantity
| GHC.Base.otherwise -> PortalSubscriptionUpdateDefaultAllowedUpdates'Other val
)
| Defines the enum schema located at @components.schemas.portal_subscription_update.properties.proration_behavior@ in the specification .
Determines how to handle prorations resulting from subscription updates . Valid values are , \`create_prorations\ ` , and \`always_invoice\ ` .
data PortalSubscriptionUpdateProrationBehavior'
PortalSubscriptionUpdateProrationBehavior'Other Data.Aeson.Types.Internal.Value
PortalSubscriptionUpdateProrationBehavior'Typed Data.Text.Internal.Text
PortalSubscriptionUpdateProrationBehavior'EnumAlwaysInvoice
PortalSubscriptionUpdateProrationBehavior'EnumCreateProrations
PortalSubscriptionUpdateProrationBehavior'EnumNone
deriving (GHC.Show.Show, GHC.Classes.Eq)
instance Data.Aeson.Types.ToJSON.ToJSON PortalSubscriptionUpdateProrationBehavior' where
toJSON (PortalSubscriptionUpdateProrationBehavior'Other val) = val
toJSON (PortalSubscriptionUpdateProrationBehavior'Typed val) = Data.Aeson.Types.ToJSON.toJSON val
toJSON (PortalSubscriptionUpdateProrationBehavior'EnumAlwaysInvoice) = "always_invoice"
toJSON (PortalSubscriptionUpdateProrationBehavior'EnumCreateProrations) = "create_prorations"
toJSON (PortalSubscriptionUpdateProrationBehavior'EnumNone) = "none"
instance Data.Aeson.Types.FromJSON.FromJSON PortalSubscriptionUpdateProrationBehavior' where
parseJSON val =
GHC.Base.pure
( if
| val GHC.Classes.== "always_invoice" -> PortalSubscriptionUpdateProrationBehavior'EnumAlwaysInvoice
| val GHC.Classes.== "create_prorations" -> PortalSubscriptionUpdateProrationBehavior'EnumCreateProrations
| val GHC.Classes.== "none" -> PortalSubscriptionUpdateProrationBehavior'EnumNone
| GHC.Base.otherwise -> PortalSubscriptionUpdateProrationBehavior'Other val
)
|
beb4c3854dbba5d0fc47ad7b90322d023c0dd9393af59c209ae9e099c7e780c2 | ibabushkin/hapstone | StorableSpec.hs | module Internal.SystemZ.StorableSpec where
import Foreign
import Foreign.C.Types
import Test.Hspec
import Test.QuickCheck
import Hapstone.Internal.SystemZ
import Internal.SystemZ.Default
-- | main spec
spec :: Spec
spec = describe "Hapstone.Internal.SysZ" $ do
syszOpMemStructSpec
csSysZOpSpec
csSysZSpec
getSyszOpMemStruct :: IO SysZOpMemStruct
getSyszOpMemStruct = do
ptr <- mallocArray (sizeOf syszOpMemStruct) :: IO (Ptr Word8)
poke (castPtr ptr) (0x1 :: Word8)
poke (plusPtr ptr 1) (0x2 :: Word8)
poke (plusPtr ptr 8) (0x0123456789abcdef :: Word64)
poke (plusPtr ptr 16) (0x1032547698badcfe :: Word64)
peek (castPtr ptr) <* free ptr
syszOpMemStruct :: SysZOpMemStruct
syszOpMemStruct = SysZOpMemStruct 0x1 0x2 0x0123456789abcdef 0x1032547698badcfe
-- | SysZOpMemStruct spec
syszOpMemStructSpec :: Spec
syszOpMemStructSpec = describe "Storable SysZOpMemStruct" $ do
it "has a memory layout we can handle" $
sizeOf (undefined :: SysZOpMemStruct) == 2 + 6 + 8 * 2
it "has matching peek- and poke-implementations" $ property $
\s@SysZOpMemStruct{} ->
alloca (\p -> poke p s >> peek p) `shouldReturn` s
it "parses correctly" $ getSyszOpMemStruct `shouldReturn` syszOpMemStruct
getCsSyszOp :: IO CsSysZOp
getCsSyszOp = do
ptr <- mallocArray (sizeOf csSyszOp) :: IO (Ptr Word8)
poke (castPtr ptr) (fromIntegral $ fromEnum SyszOpImm :: Int32)
poke (plusPtr ptr 8) (19237 :: Int64)
peek (castPtr ptr) <* free ptr
csSyszOp :: CsSysZOp
csSyszOp = Imm 19237
| CsSysZipsOp spec
csSysZOpSpec :: Spec
csSysZOpSpec = describe "Storable CsSysZOp" $ do
it "has a memory layout we can handle" $
sizeOf (undefined :: CsSysZOp) == 4 + 4 + 24
it "has matching peek- and poke-implementations" $ property $
\s ->
alloca (\p -> poke p s >> (peek p :: IO CsSysZOp)) `shouldReturn` s
it "parses correctly" $ getCsSyszOp `shouldReturn` csSyszOp
getCsSysz :: IO CsSysZ
getCsSysz = do
ptr <- mallocArray (sizeOf csSysz) :: IO (Ptr Word8)
poke (castPtr ptr) (fromIntegral $ fromEnum SyszCcL :: Int32)
poke (plusPtr ptr 4) (1 :: Word8)
poke (plusPtr ptr 8) csSyszOp
peek (castPtr ptr) <* free ptr
csSysz :: CsSysZ
csSysz = CsSysZ SyszCcL [csSyszOp]
| CsSysZ spec
csSysZSpec :: Spec
csSysZSpec = describe "Storable CsSysZ" $ do
it "has a memory-layout we can handle" $
sizeOf (undefined :: CsSysZ) == 4 + 1 + 3 + 32 * 6
it "has matching peek- and poke-implementations" $ property $
\s@CsSysZ{} ->
alloca (\p -> poke p s >> peek p) `shouldReturn` s
it "parses correctly" $ getCsSysz `shouldReturn` csSysz
| null | https://raw.githubusercontent.com/ibabushkin/hapstone/4ac11f0a1e23e5a0f23351149c70bd541ddf5344/test/Internal/SystemZ/StorableSpec.hs | haskell | | main spec
| SysZOpMemStruct spec | module Internal.SystemZ.StorableSpec where
import Foreign
import Foreign.C.Types
import Test.Hspec
import Test.QuickCheck
import Hapstone.Internal.SystemZ
import Internal.SystemZ.Default
spec :: Spec
spec = describe "Hapstone.Internal.SysZ" $ do
syszOpMemStructSpec
csSysZOpSpec
csSysZSpec
getSyszOpMemStruct :: IO SysZOpMemStruct
getSyszOpMemStruct = do
ptr <- mallocArray (sizeOf syszOpMemStruct) :: IO (Ptr Word8)
poke (castPtr ptr) (0x1 :: Word8)
poke (plusPtr ptr 1) (0x2 :: Word8)
poke (plusPtr ptr 8) (0x0123456789abcdef :: Word64)
poke (plusPtr ptr 16) (0x1032547698badcfe :: Word64)
peek (castPtr ptr) <* free ptr
syszOpMemStruct :: SysZOpMemStruct
syszOpMemStruct = SysZOpMemStruct 0x1 0x2 0x0123456789abcdef 0x1032547698badcfe
syszOpMemStructSpec :: Spec
syszOpMemStructSpec = describe "Storable SysZOpMemStruct" $ do
it "has a memory layout we can handle" $
sizeOf (undefined :: SysZOpMemStruct) == 2 + 6 + 8 * 2
it "has matching peek- and poke-implementations" $ property $
\s@SysZOpMemStruct{} ->
alloca (\p -> poke p s >> peek p) `shouldReturn` s
it "parses correctly" $ getSyszOpMemStruct `shouldReturn` syszOpMemStruct
getCsSyszOp :: IO CsSysZOp
getCsSyszOp = do
ptr <- mallocArray (sizeOf csSyszOp) :: IO (Ptr Word8)
poke (castPtr ptr) (fromIntegral $ fromEnum SyszOpImm :: Int32)
poke (plusPtr ptr 8) (19237 :: Int64)
peek (castPtr ptr) <* free ptr
csSyszOp :: CsSysZOp
csSyszOp = Imm 19237
| CsSysZipsOp spec
csSysZOpSpec :: Spec
csSysZOpSpec = describe "Storable CsSysZOp" $ do
it "has a memory layout we can handle" $
sizeOf (undefined :: CsSysZOp) == 4 + 4 + 24
it "has matching peek- and poke-implementations" $ property $
\s ->
alloca (\p -> poke p s >> (peek p :: IO CsSysZOp)) `shouldReturn` s
it "parses correctly" $ getCsSyszOp `shouldReturn` csSyszOp
getCsSysz :: IO CsSysZ
getCsSysz = do
ptr <- mallocArray (sizeOf csSysz) :: IO (Ptr Word8)
poke (castPtr ptr) (fromIntegral $ fromEnum SyszCcL :: Int32)
poke (plusPtr ptr 4) (1 :: Word8)
poke (plusPtr ptr 8) csSyszOp
peek (castPtr ptr) <* free ptr
csSysz :: CsSysZ
csSysz = CsSysZ SyszCcL [csSyszOp]
| CsSysZ spec
csSysZSpec :: Spec
csSysZSpec = describe "Storable CsSysZ" $ do
it "has a memory-layout we can handle" $
sizeOf (undefined :: CsSysZ) == 4 + 1 + 3 + 32 * 6
it "has matching peek- and poke-implementations" $ property $
\s@CsSysZ{} ->
alloca (\p -> poke p s >> peek p) `shouldReturn` s
it "parses correctly" $ getCsSysz `shouldReturn` csSysz
|
983cbe89b20f370f888b6e8bf2f7742edf4a5833ef6cd0026df62a7bda809d21 | wlitwin/graphv | graphv_anim.mli | type repeat = Count of int | Infinite
type direction = Forward | Mirror of direction | Backward
type reason = Done | Canceled
type anim
module Ease = Ease
val create :
?delay:float ->
?ease:Ease.t ->
?complete:(int -> reason -> unit) ->
?repeat:repeat ->
?repeat_delay:float ->
?direction:direction -> float ->
(float -> unit) ->
anim
val serial :
?delay:float ->
?ease:Ease.t ->
?complete:(int -> reason -> unit) ->
?repeat:repeat ->
?repeat_delay:float ->
?direction:direction ->
anim list ->
anim
val parallel :
?delay:float ->
?ease:Ease.t ->
?complete:(int -> reason -> unit) ->
?repeat:repeat ->
?repeat_delay:float ->
?direction:direction ->
anim list ->
anim
module Driver :
sig
type t
val create : unit -> t
val start : t -> anim -> int
val start_ : t -> anim -> unit
val is_empty : t -> bool
val tick : t -> float -> unit
val cancel : t -> int -> unit
val cancel_all : t -> unit
val active_count : t -> int
val pending_count : t -> int
end
val lerp : float -> float -> float -> float
| null | https://raw.githubusercontent.com/wlitwin/graphv/1416fe1daaedc411e8b54e5458d6005d2d3678b5/graphv_anim/lib/graphv_anim.mli | ocaml | type repeat = Count of int | Infinite
type direction = Forward | Mirror of direction | Backward
type reason = Done | Canceled
type anim
module Ease = Ease
val create :
?delay:float ->
?ease:Ease.t ->
?complete:(int -> reason -> unit) ->
?repeat:repeat ->
?repeat_delay:float ->
?direction:direction -> float ->
(float -> unit) ->
anim
val serial :
?delay:float ->
?ease:Ease.t ->
?complete:(int -> reason -> unit) ->
?repeat:repeat ->
?repeat_delay:float ->
?direction:direction ->
anim list ->
anim
val parallel :
?delay:float ->
?ease:Ease.t ->
?complete:(int -> reason -> unit) ->
?repeat:repeat ->
?repeat_delay:float ->
?direction:direction ->
anim list ->
anim
module Driver :
sig
type t
val create : unit -> t
val start : t -> anim -> int
val start_ : t -> anim -> unit
val is_empty : t -> bool
val tick : t -> float -> unit
val cancel : t -> int -> unit
val cancel_all : t -> unit
val active_count : t -> int
val pending_count : t -> int
end
val lerp : float -> float -> float -> float
|
|
77dcb6acf3a1b605c7943fb158166cfe862d94977a691e6e1e8601fbb5faa604 | unclebob/AdventOfCode2022 | project.clj | (defproject day14-regolith-reservoir "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:main day14-regolith-reservoir.core
:dependencies [[org.clojure/clojure "1.8.0"]]
:profiles {:dev {:dependencies [[speclj "3.3.2"]]}}
:plugins [[speclj "3.3.2"]]
:test-paths ["spec"])
| null | https://raw.githubusercontent.com/unclebob/AdventOfCode2022/fa2eccadeca7be72db4ed4193e349ad18d5d533b/day14-regolith-reservoir/project.clj | clojure | (defproject day14-regolith-reservoir "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:main day14-regolith-reservoir.core
:dependencies [[org.clojure/clojure "1.8.0"]]
:profiles {:dev {:dependencies [[speclj "3.3.2"]]}}
:plugins [[speclj "3.3.2"]]
:test-paths ["spec"])
|
|
c3797eba983f4cd89d6234888d401b8c5540ba92bf14b8b058280178b2347cf0 | Stratus3D/programming_erlang_exercises | md5_cache.erl | -module(md5_cache).
-behaviour(gen_server).
-export([start_link/0, get_md5/1]).
-include_lib("kernel/include/file.hrl").
-define(SERVER, ?MODULE).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
get_md5(Filename) ->
gen_server:call(?SERVER, {get_md5, Filename}).
% Callbacks
init([]) -> {ok, []}.
handle_call({get_md5, Filename}, _From, State) ->
case proplists:lookup(Filename, State) of
none ->
% Compute MD5 hash
{ok, Data} = file:read_file(Filename),
Sum = erlang:md5(Data),
% Get the last modified date of the file
{ok, #file_info{mtime=ModifiedTime}} = file:read_file_info(Filename),
io:format("MD5 hash is not up to date~n", []),
% Update the server state with the cached MD5 sum and return the sum
% to the caller
{reply, {ok, Sum}, [{Filename, ModifiedTime, Sum}|State]};
{Filename, Time, Md5} ->
% Check if the last modified date has changed
{ok, #file_info{mtime=ModifiedTime}} = file:read_file_info(Filename),
{Days, _Time} = calendar:time_difference(ModifiedTime, Time),
Sum = case Days of
Days when Days =/= 0 ->
% If it has changed update the hash
io:format("MD5 hash is not up to date~n", []),
{ok, Data} = file:read_file(Filename),
erlang:md5(Data);
_ ->
% Otherwise return the cached MD5 hash
io:format("MD5 hash is up to date~n", []),
Md5
end,
NewState = lists:keyreplace(Filename, 1, State, {Filename, ModifiedTime, Sum}),
{reply, {ok, Md5}, NewState}
end.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
| null | https://raw.githubusercontent.com/Stratus3D/programming_erlang_exercises/e4fd01024812059d338facc20f551e7dff4dac7e/chapter_16/exercise_5/md5_cache.erl | erlang | gen_server callbacks
Callbacks
Compute MD5 hash
Get the last modified date of the file
Update the server state with the cached MD5 sum and return the sum
to the caller
Check if the last modified date has changed
If it has changed update the hash
Otherwise return the cached MD5 hash | -module(md5_cache).
-behaviour(gen_server).
-export([start_link/0, get_md5/1]).
-include_lib("kernel/include/file.hrl").
-define(SERVER, ?MODULE).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
get_md5(Filename) ->
gen_server:call(?SERVER, {get_md5, Filename}).
init([]) -> {ok, []}.
handle_call({get_md5, Filename}, _From, State) ->
case proplists:lookup(Filename, State) of
none ->
{ok, Data} = file:read_file(Filename),
Sum = erlang:md5(Data),
{ok, #file_info{mtime=ModifiedTime}} = file:read_file_info(Filename),
io:format("MD5 hash is not up to date~n", []),
{reply, {ok, Sum}, [{Filename, ModifiedTime, Sum}|State]};
{Filename, Time, Md5} ->
{ok, #file_info{mtime=ModifiedTime}} = file:read_file_info(Filename),
{Days, _Time} = calendar:time_difference(ModifiedTime, Time),
Sum = case Days of
Days when Days =/= 0 ->
io:format("MD5 hash is not up to date~n", []),
{ok, Data} = file:read_file(Filename),
erlang:md5(Data);
_ ->
io:format("MD5 hash is up to date~n", []),
Md5
end,
NewState = lists:keyreplace(Filename, 1, State, {Filename, ModifiedTime, Sum}),
{reply, {ok, Md5}, NewState}
end.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
|
63c56cffc47ce4eea333a4a2b48e983844d4351bded60e11bbb39d1bf1d4d391 | wenkokke/dep2con | Dep2Bin.hs | module Language.Conversion.Dep2Bin where
import Data.List (sortBy)
import Language.POS (POS (..), toXP)
import qualified Language.Structure.Binary as Bin
import qualified Language.Structure.Dependency as Dep
import Language.Word (Word (..))
-- |Convert dependency structures to binary constituency structures,
-- ensuring that only the minimal number of projections are made.
collinsToledo :: Dep.Tree -> Bin.Tree
collinsToledo (Dep.Node (Word "ROOT" (POS "ROOT") 0) [dep]) = collinsToledo dep
collinsToledo (Dep.Node gov []) = Bin.Leaf gov
collinsToledo (Dep.Node gov deps) = let
x = pos gov
xp = toXP x
sorted :: [Dep.Tree]
sorted = sortBy (flip $ Dep.nearestThenLeftMost (serial gov)) deps
asbin :: [Bin.Tree]
asbin = map collinsToledo sorted
asfunc :: Bin.Tree -> Bin.Tree
asfunc = foldr ((.) . Bin.node xp) id asbin
in asfunc (Bin.Leaf gov)
| null | https://raw.githubusercontent.com/wenkokke/dep2con/cd6cc985a9dbedd6b2991a85197481804a2a0d95/src/Language/Conversion/Dep2Bin.hs | haskell | |Convert dependency structures to binary constituency structures,
ensuring that only the minimal number of projections are made. | module Language.Conversion.Dep2Bin where
import Data.List (sortBy)
import Language.POS (POS (..), toXP)
import qualified Language.Structure.Binary as Bin
import qualified Language.Structure.Dependency as Dep
import Language.Word (Word (..))
collinsToledo :: Dep.Tree -> Bin.Tree
collinsToledo (Dep.Node (Word "ROOT" (POS "ROOT") 0) [dep]) = collinsToledo dep
collinsToledo (Dep.Node gov []) = Bin.Leaf gov
collinsToledo (Dep.Node gov deps) = let
x = pos gov
xp = toXP x
sorted :: [Dep.Tree]
sorted = sortBy (flip $ Dep.nearestThenLeftMost (serial gov)) deps
asbin :: [Bin.Tree]
asbin = map collinsToledo sorted
asfunc :: Bin.Tree -> Bin.Tree
asfunc = foldr ((.) . Bin.node xp) id asbin
in asfunc (Bin.Leaf gov)
|
9917e63695c2cec5b0ec5c9fa616cd7acc09702db8e7908b36dace81d607849a | fpco/stackage-server | Types.hs | # LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
module Stackage.Database.Types
( SnapName(..)
, isLts
, isNightly
, SnapshotBranch(..)
, snapshotPrettyName
, snapshotPrettyNameShort
, CompilerP(..)
, FlagNameP(..)
, StackageCron(..)
, PantryCabal(..)
, BlobKey(..)
, GenericPackageDescription
, toPackageIdentifierRevision
, PantryPackage(..)
, SnapshotFile(..)
, SnapshotPackageInfo(..)
, SnapshotPackagePageInfo(..)
, spiVersionRev
, HackageCabalInfo(..)
, PackageListingInfo(..)
, ModuleListingInfo(..)
, PackageNameP(..)
, VersionP(..)
, Revision(..)
, VersionRangeP(..)
, PackageIdentifierP(..)
, VersionRev(..)
, toRevMaybe
, toVersionRev
, toVersionMRev
, PackageVersionRev(..)
, dropVersionRev
, ModuleNameP(..)
, SafeFilePath
, Origin(..)
, LatestInfo(..)
, Deprecation(..)
, haddockBucketName
, Changelog(..)
, Readme(..)
, StackageCronOptions(..)
) where
import Data.Aeson
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Network.AWS (Env, HasEnv(..))
import Pantry (BlobKey(..), CabalFileInfo(..), FileSize(..),
HasPantryConfig(..), PantryConfig, PackageIdentifierRevision(..), TreeKey(..))
import Pantry.SHA256 (fromHexText)
import RIO
import RIO.Process (HasProcessContext(..), ProcessContext)
import RIO.Time (Day, utctDay)
import Stackage.Database.Github (GithubRepo(..))
import Stackage.Database.Schema
import Text.Blaze (ToMarkup(..))
import Types
haddockBucketName :: Text
haddockBucketName = "haddock.stackage.org"
data StackageCronOptions = StackageCronOptions
{ scoForceUpdate :: !Bool
, scoDownloadBucketName :: !Text
, scoUploadBucketName :: !Text
, scoDoNotUpload :: !Bool
, scoLogLevel :: !LogLevel
, scoSnapshotsRepo :: !GithubRepo
, scoReportProgress :: !Bool
, scoCacheCabalFiles :: !Bool
}
data StackageCron = StackageCron
{ scPantryConfig :: !PantryConfig
, scStackageRoot :: !FilePath
, scLogFunc :: !LogFunc
, scProcessContext :: !ProcessContext
, scForceFullUpdate :: !Bool
, scCachedGPD :: !(IORef (IntMap GenericPackageDescription))
, scEnvAWS :: !Env
, scDownloadBucketName :: !Text
, scUploadBucketName :: !Text
, scSnapshotsRepo :: !GithubRepo
, scReportProgress :: !Bool
, scCacheCabalFiles :: !Bool
, scHoogleVersionId :: !VersionId
}
instance HasEnv StackageCron where
environment = lens scEnvAWS (\c f -> c {scEnvAWS = f})
instance HasLogFunc StackageCron where
logFuncL = lens scLogFunc (\c f -> c {scLogFunc = f})
instance HasProcessContext StackageCron where
processContextL = lens scProcessContext (\c f -> c {scProcessContext = f})
instance HasPantryConfig StackageCron where
pantryConfigL = lens scPantryConfig (\c f -> c {scPantryConfig = f})
data SnapshotFile = SnapshotFile
{ sfCompiler :: !CompilerP
, sfPackages :: ![PantryPackage]
, sfHidden :: !(Map PackageNameP Bool)
, sfFlags :: !(Map PackageNameP (Map FlagNameP Bool))
, sfPublishDate :: !(Maybe Day)
} deriving (Show)
data PantryCabal = PantryCabal
{ pcPackageName :: !PackageNameP
, pcVersion :: !VersionP
, pcCabalKey :: !BlobKey
} deriving (Show)
instance Display PantryCabal where
display PantryCabal {..} =
display (PackageIdentifierP pcPackageName pcVersion) <> "@sha256:" <>
display pcCabalKey
instance ToMarkup PantryCabal where
toMarkup = toMarkup . textDisplay
data PantryPackage = PantryPackage
{ ppPantryCabal :: !PantryCabal
, ppPantryKey :: !TreeKey
} deriving (Show)
toPackageIdentifierRevision :: PantryCabal -> PackageIdentifierRevision
toPackageIdentifierRevision PantryCabal {..} =
PackageIdentifierRevision
(unPackageNameP pcPackageName)
(unVersionP pcVersion)
(CFIHash sha (Just size))
where
BlobKey sha size = pcCabalKey
-- QUESTION: Potentially switch to `parsePackageIdentifierRevision`:
PackageIdentifierRevision pn v ( CFIHash sha ( Just size ) ) < -
either ( fail . displayException ) pure $ parsePackageIdentifierRevision txt
-- return (PantryCabal pn v sha size)
-- Issues with such switch:
* CFILatest and CFIRevision do not make sense in stackage - snapshots
-- * Implementation below is faster
instance FromJSON PantryCabal where
parseJSON =
withText "PantryCabal" $ \txt -> do
let (packageTxt, hashWithSize) = T.break (== '@') txt
(hashTxtWithAlgo, sizeWithComma) = T.break (== ',') hashWithSize
-- Split package identifier foo-bar-0.1.2 into package name and version
(pkgNameTxt, pkgVersionTxt) <-
case T.breakOnEnd "-" packageTxt of
(pkgNameWithDashEnd, pkgVersionTxt)
| Just pkgName <- T.stripSuffix "-" pkgNameWithDashEnd ->
return (pkgName, pkgVersionTxt)
_ -> fail $ "Invalid package identifier format: " ++ T.unpack packageTxt
pcPackageName <- parseJSON $ String pkgNameTxt
pcVersion <- parseJSON $ String pkgVersionTxt
hashTxt <-
maybe (fail $ "Unrecognized hashing algorithm: " ++ T.unpack hashTxtWithAlgo) pure $
T.stripPrefix "@sha256:" hashTxtWithAlgo
pcSHA256 <- either (fail . displayException) pure $ fromHexText hashTxt
(pcFileSize, "") <-
either fail (pure . first FileSize) =<<
maybe
(fail $ "Wrong size format:" ++ show sizeWithComma)
(pure . decimal)
(T.stripPrefix "," sizeWithComma)
let pcCabalKey = BlobKey pcSHA256 pcFileSize
return PantryCabal {..}
instance FromJSON PantryPackage where
parseJSON =
withObject "PantryPackage" $ \obj ->
PantryPackage <$> obj .: "hackage" <*> obj .: "pantry-tree"
instance FromJSON SnapshotFile where
parseJSON =
withObject "SnapshotFile" $ \obj -> do
sfCompiler <-
obj .:? "resolver" >>= \case
Just resolverCompiler -> resolverCompiler .: "compiler"
Nothing -> obj .: "compiler"
sfPackages <- obj .: "packages"
sfHidden <- obj .:? "hidden" .!= mempty
sfFlags <- obj .:? "flags" .!= mempty
sfPublishDate <- fmap utctDay <$> obj .:? "publish-time"
pure SnapshotFile {..}
data PackageListingInfo = PackageListingInfo
{ pliName :: !PackageNameP
, pliVersion :: !VersionP
, pliSynopsis :: !Text
, pliOrigin :: !Origin
} deriving Show
instance ToJSON PackageListingInfo where
toJSON PackageListingInfo {..} =
object
[ "name" .= pliName
, "version" .= pliVersion
, "synopsis" .= pliSynopsis
, "origin" .= pliOrigin
]
data HackageCabalInfo = HackageCabalInfo
{ hciCabalId :: !HackageCabalId
, hciCabalBlobId :: !BlobId
, hciPackageName :: !PackageNameP
, hciVersionRev :: !VersionRev
} deriving (Show, Eq)
data SnapshotPackageInfo = SnapshotPackageInfo
{ spiSnapshotPackageId :: !SnapshotPackageId
, spiSnapshotId :: !SnapshotId
, spiCabalBlobId :: !(Maybe BlobId)
, spiSnapName :: !SnapName
, spiPackageName :: !PackageNameP
, spiVersion :: !VersionP
, spiRevision :: !(Maybe Revision)
, spiOrigin :: !Origin
, spiReadme :: !(Maybe TreeEntryId)
, spiChangelog :: !(Maybe TreeEntryId)
} deriving (Show, Eq)
data SnapshotPackagePageInfo = SnapshotPackagePageInfo
{ sppiSnapshotPackageInfo :: !SnapshotPackageInfo
-- ^ Info of the package on this page
, sppiLatestHackageCabalInfo :: !(Maybe HackageCabalInfo)
-- ^ If the package is available on hackage, show its latest info
, sppiForwardDeps :: ![(PackageNameP, VersionRangeP)]
-- ^ Limited list of packages in the snapshot that this package depends on
, sppiForwardDepsCount :: !Int
-- ^ Count of all packages in the snapshot that this package depends on
, sppiReverseDeps :: ![(PackageNameP, VersionRangeP)]
-- ^ Limited list of packages in the snapshot that depend on this package
, sppiReverseDepsCount :: !Int
-- ^ Count of all packages in the snapshot that depends on this package
, sppiLatestInfo :: ![LatestInfo]
, sppiModuleNames :: !(Map ModuleNameP Bool)
, sppiPantryCabal :: !(Maybe PantryCabal)
, sppiVersion :: !(Maybe VersionRev)
-- ^ Version on this page. Should be present only if different from latest
}
toRevMaybe :: Revision -> Maybe Revision
toRevMaybe rev = guard (rev /= Revision 0) >> Just rev
| Add revision only if it is non - zero
toVersionRev :: VersionP -> Revision -> VersionRev
toVersionRev v = VersionRev v . toRevMaybe
| Add revision only if it is present and is non - zero
toVersionMRev :: VersionP -> Maybe Revision -> VersionRev
toVersionMRev v mrev = VersionRev v (maybe Nothing toRevMaybe mrev)
spiVersionRev :: SnapshotPackageInfo -> VersionRev
spiVersionRev spi = VersionRev (spiVersion spi) (spiRevision spi >>= toRevMaybe)
dropVersionRev :: PackageVersionRev -> PackageNameP
dropVersionRev (PackageVersionRev pname _) = pname
data ModuleListingInfo = ModuleListingInfo
{ mliModuleName :: !ModuleNameP
, mliPackageIdentifier :: !PackageIdentifierP
} deriving Show
data LatestInfo = LatestInfo
{ liSnapName :: !SnapName
, liVersionRev :: !VersionRev
} deriving (Show, Eq)
data Deprecation = Deprecation
{ depPackage :: !PackageNameP
, depInFavourOf :: !(Set PackageNameP)
}
instance ToJSON Deprecation where
toJSON d = object
[ "deprecated-package" .= depPackage d
, "in-favour-of" .= depInFavourOf d
]
instance FromJSON Deprecation where
parseJSON = withObject "Deprecation" $ \o -> Deprecation
<$> o .: "deprecated-package"
<*> o .: "in-favour-of"
data Readme = Readme !ByteString !Bool
data Changelog = Changelog !ByteString !Bool
| null | https://raw.githubusercontent.com/fpco/stackage-server/b707b5a0d72c44a3134a305b628c3f0b28db2697/src/Stackage/Database/Types.hs | haskell | QUESTION: Potentially switch to `parsePackageIdentifierRevision`:
return (PantryCabal pn v sha size)
Issues with such switch:
* Implementation below is faster
Split package identifier foo-bar-0.1.2 into package name and version
^ Info of the package on this page
^ If the package is available on hackage, show its latest info
^ Limited list of packages in the snapshot that this package depends on
^ Count of all packages in the snapshot that this package depends on
^ Limited list of packages in the snapshot that depend on this package
^ Count of all packages in the snapshot that depends on this package
^ Version on this page. Should be present only if different from latest | # LANGUAGE LambdaCase #
# LANGUAGE NamedFieldPuns #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
module Stackage.Database.Types
( SnapName(..)
, isLts
, isNightly
, SnapshotBranch(..)
, snapshotPrettyName
, snapshotPrettyNameShort
, CompilerP(..)
, FlagNameP(..)
, StackageCron(..)
, PantryCabal(..)
, BlobKey(..)
, GenericPackageDescription
, toPackageIdentifierRevision
, PantryPackage(..)
, SnapshotFile(..)
, SnapshotPackageInfo(..)
, SnapshotPackagePageInfo(..)
, spiVersionRev
, HackageCabalInfo(..)
, PackageListingInfo(..)
, ModuleListingInfo(..)
, PackageNameP(..)
, VersionP(..)
, Revision(..)
, VersionRangeP(..)
, PackageIdentifierP(..)
, VersionRev(..)
, toRevMaybe
, toVersionRev
, toVersionMRev
, PackageVersionRev(..)
, dropVersionRev
, ModuleNameP(..)
, SafeFilePath
, Origin(..)
, LatestInfo(..)
, Deprecation(..)
, haddockBucketName
, Changelog(..)
, Readme(..)
, StackageCronOptions(..)
) where
import Data.Aeson
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Network.AWS (Env, HasEnv(..))
import Pantry (BlobKey(..), CabalFileInfo(..), FileSize(..),
HasPantryConfig(..), PantryConfig, PackageIdentifierRevision(..), TreeKey(..))
import Pantry.SHA256 (fromHexText)
import RIO
import RIO.Process (HasProcessContext(..), ProcessContext)
import RIO.Time (Day, utctDay)
import Stackage.Database.Github (GithubRepo(..))
import Stackage.Database.Schema
import Text.Blaze (ToMarkup(..))
import Types
haddockBucketName :: Text
haddockBucketName = "haddock.stackage.org"
data StackageCronOptions = StackageCronOptions
{ scoForceUpdate :: !Bool
, scoDownloadBucketName :: !Text
, scoUploadBucketName :: !Text
, scoDoNotUpload :: !Bool
, scoLogLevel :: !LogLevel
, scoSnapshotsRepo :: !GithubRepo
, scoReportProgress :: !Bool
, scoCacheCabalFiles :: !Bool
}
data StackageCron = StackageCron
{ scPantryConfig :: !PantryConfig
, scStackageRoot :: !FilePath
, scLogFunc :: !LogFunc
, scProcessContext :: !ProcessContext
, scForceFullUpdate :: !Bool
, scCachedGPD :: !(IORef (IntMap GenericPackageDescription))
, scEnvAWS :: !Env
, scDownloadBucketName :: !Text
, scUploadBucketName :: !Text
, scSnapshotsRepo :: !GithubRepo
, scReportProgress :: !Bool
, scCacheCabalFiles :: !Bool
, scHoogleVersionId :: !VersionId
}
instance HasEnv StackageCron where
environment = lens scEnvAWS (\c f -> c {scEnvAWS = f})
instance HasLogFunc StackageCron where
logFuncL = lens scLogFunc (\c f -> c {scLogFunc = f})
instance HasProcessContext StackageCron where
processContextL = lens scProcessContext (\c f -> c {scProcessContext = f})
instance HasPantryConfig StackageCron where
pantryConfigL = lens scPantryConfig (\c f -> c {scPantryConfig = f})
data SnapshotFile = SnapshotFile
{ sfCompiler :: !CompilerP
, sfPackages :: ![PantryPackage]
, sfHidden :: !(Map PackageNameP Bool)
, sfFlags :: !(Map PackageNameP (Map FlagNameP Bool))
, sfPublishDate :: !(Maybe Day)
} deriving (Show)
data PantryCabal = PantryCabal
{ pcPackageName :: !PackageNameP
, pcVersion :: !VersionP
, pcCabalKey :: !BlobKey
} deriving (Show)
instance Display PantryCabal where
display PantryCabal {..} =
display (PackageIdentifierP pcPackageName pcVersion) <> "@sha256:" <>
display pcCabalKey
instance ToMarkup PantryCabal where
toMarkup = toMarkup . textDisplay
data PantryPackage = PantryPackage
{ ppPantryCabal :: !PantryCabal
, ppPantryKey :: !TreeKey
} deriving (Show)
toPackageIdentifierRevision :: PantryCabal -> PackageIdentifierRevision
toPackageIdentifierRevision PantryCabal {..} =
PackageIdentifierRevision
(unPackageNameP pcPackageName)
(unVersionP pcVersion)
(CFIHash sha (Just size))
where
BlobKey sha size = pcCabalKey
PackageIdentifierRevision pn v ( CFIHash sha ( Just size ) ) < -
either ( fail . displayException ) pure $ parsePackageIdentifierRevision txt
* CFILatest and CFIRevision do not make sense in stackage - snapshots
instance FromJSON PantryCabal where
parseJSON =
withText "PantryCabal" $ \txt -> do
let (packageTxt, hashWithSize) = T.break (== '@') txt
(hashTxtWithAlgo, sizeWithComma) = T.break (== ',') hashWithSize
(pkgNameTxt, pkgVersionTxt) <-
case T.breakOnEnd "-" packageTxt of
(pkgNameWithDashEnd, pkgVersionTxt)
| Just pkgName <- T.stripSuffix "-" pkgNameWithDashEnd ->
return (pkgName, pkgVersionTxt)
_ -> fail $ "Invalid package identifier format: " ++ T.unpack packageTxt
pcPackageName <- parseJSON $ String pkgNameTxt
pcVersion <- parseJSON $ String pkgVersionTxt
hashTxt <-
maybe (fail $ "Unrecognized hashing algorithm: " ++ T.unpack hashTxtWithAlgo) pure $
T.stripPrefix "@sha256:" hashTxtWithAlgo
pcSHA256 <- either (fail . displayException) pure $ fromHexText hashTxt
(pcFileSize, "") <-
either fail (pure . first FileSize) =<<
maybe
(fail $ "Wrong size format:" ++ show sizeWithComma)
(pure . decimal)
(T.stripPrefix "," sizeWithComma)
let pcCabalKey = BlobKey pcSHA256 pcFileSize
return PantryCabal {..}
instance FromJSON PantryPackage where
parseJSON =
withObject "PantryPackage" $ \obj ->
PantryPackage <$> obj .: "hackage" <*> obj .: "pantry-tree"
instance FromJSON SnapshotFile where
parseJSON =
withObject "SnapshotFile" $ \obj -> do
sfCompiler <-
obj .:? "resolver" >>= \case
Just resolverCompiler -> resolverCompiler .: "compiler"
Nothing -> obj .: "compiler"
sfPackages <- obj .: "packages"
sfHidden <- obj .:? "hidden" .!= mempty
sfFlags <- obj .:? "flags" .!= mempty
sfPublishDate <- fmap utctDay <$> obj .:? "publish-time"
pure SnapshotFile {..}
data PackageListingInfo = PackageListingInfo
{ pliName :: !PackageNameP
, pliVersion :: !VersionP
, pliSynopsis :: !Text
, pliOrigin :: !Origin
} deriving Show
instance ToJSON PackageListingInfo where
toJSON PackageListingInfo {..} =
object
[ "name" .= pliName
, "version" .= pliVersion
, "synopsis" .= pliSynopsis
, "origin" .= pliOrigin
]
data HackageCabalInfo = HackageCabalInfo
{ hciCabalId :: !HackageCabalId
, hciCabalBlobId :: !BlobId
, hciPackageName :: !PackageNameP
, hciVersionRev :: !VersionRev
} deriving (Show, Eq)
data SnapshotPackageInfo = SnapshotPackageInfo
{ spiSnapshotPackageId :: !SnapshotPackageId
, spiSnapshotId :: !SnapshotId
, spiCabalBlobId :: !(Maybe BlobId)
, spiSnapName :: !SnapName
, spiPackageName :: !PackageNameP
, spiVersion :: !VersionP
, spiRevision :: !(Maybe Revision)
, spiOrigin :: !Origin
, spiReadme :: !(Maybe TreeEntryId)
, spiChangelog :: !(Maybe TreeEntryId)
} deriving (Show, Eq)
data SnapshotPackagePageInfo = SnapshotPackagePageInfo
{ sppiSnapshotPackageInfo :: !SnapshotPackageInfo
, sppiLatestHackageCabalInfo :: !(Maybe HackageCabalInfo)
, sppiForwardDeps :: ![(PackageNameP, VersionRangeP)]
, sppiForwardDepsCount :: !Int
, sppiReverseDeps :: ![(PackageNameP, VersionRangeP)]
, sppiReverseDepsCount :: !Int
, sppiLatestInfo :: ![LatestInfo]
, sppiModuleNames :: !(Map ModuleNameP Bool)
, sppiPantryCabal :: !(Maybe PantryCabal)
, sppiVersion :: !(Maybe VersionRev)
}
toRevMaybe :: Revision -> Maybe Revision
toRevMaybe rev = guard (rev /= Revision 0) >> Just rev
| Add revision only if it is non - zero
toVersionRev :: VersionP -> Revision -> VersionRev
toVersionRev v = VersionRev v . toRevMaybe
| Add revision only if it is present and is non - zero
toVersionMRev :: VersionP -> Maybe Revision -> VersionRev
toVersionMRev v mrev = VersionRev v (maybe Nothing toRevMaybe mrev)
spiVersionRev :: SnapshotPackageInfo -> VersionRev
spiVersionRev spi = VersionRev (spiVersion spi) (spiRevision spi >>= toRevMaybe)
dropVersionRev :: PackageVersionRev -> PackageNameP
dropVersionRev (PackageVersionRev pname _) = pname
data ModuleListingInfo = ModuleListingInfo
{ mliModuleName :: !ModuleNameP
, mliPackageIdentifier :: !PackageIdentifierP
} deriving Show
data LatestInfo = LatestInfo
{ liSnapName :: !SnapName
, liVersionRev :: !VersionRev
} deriving (Show, Eq)
data Deprecation = Deprecation
{ depPackage :: !PackageNameP
, depInFavourOf :: !(Set PackageNameP)
}
instance ToJSON Deprecation where
toJSON d = object
[ "deprecated-package" .= depPackage d
, "in-favour-of" .= depInFavourOf d
]
instance FromJSON Deprecation where
parseJSON = withObject "Deprecation" $ \o -> Deprecation
<$> o .: "deprecated-package"
<*> o .: "in-favour-of"
data Readme = Readme !ByteString !Bool
data Changelog = Changelog !ByteString !Bool
|
29cab1970be6c8bc6451347898a17989f1ec8cc1cd1f6a5bfd7094ea28b89d24 | whalliburton/academy | turtle-graphics.lisp | (in-package :academy)
(defvar *turtle*)
(defstruct turtle x y heading bitmap pen)
(defmacro with-turtle ((&optional (bitmap '*bitmap*)) &body body)
`(destructuring-bind (height width) (array-dimensions ,bitmap)
(let ((*turtle* (make-turtle :x (floor width 2) :y (floor height 2) :heading 0
:bitmap ,bitmap :pen :down)))
,@body)))
(defun pen-up (&optional (turtle *turtle*))
(setf (turtle-pen turtle) :up))
(defun pen-is-up (&optional (turtle *turtle*))
(eq (turtle-pen turtle) :up))
(defun pen-down (&optional (turtle *turtle*))
(setf (turtle-pen turtle) :down))
(defun pen-is-down (&optional (turtle *turtle*))
(eq (turtle-pen turtle) :down))
(defun left (degrees &optional (turtle *turtle*))
(setf (turtle-heading turtle)
(mod (- (turtle-heading turtle) degrees) 360)))
(defun right (degrees &optional (turtle *turtle*))
(setf (turtle-heading turtle)
(mod (+ (turtle-heading turtle) degrees) 360)))
(defmacro repeat (times &body body)
`(dotimes (,(gensym) ,times)
,@body))
(defun move-to (x y &optional (turtle *turtle*))
(when (pen-is-down turtle)
(draw-line (round (turtle-x turtle)) (round (turtle-y turtle)) (round x) (round y)
(turtle-bitmap turtle)))
(setf (turtle-x turtle) x
(turtle-y turtle) y))
(defun degrees-to-radians (degrees)
(/ (* degrees pi) 180))
(defun forward (steps &optional (turtle *turtle*))
(let ((x (turtle-x turtle))
(y (turtle-y turtle))
(heading (- (turtle-heading turtle) 90)))
(let* ((dx (* steps (cos (degrees-to-radians heading))))
(dy (* steps (sin (degrees-to-radians heading)))))
(move-to (+ x dx) (+ y dy) turtle))))
(defun backward (steps &optional (turtle *turtle*))
(forward (- steps) turtle))
(defmacro turtle-graphics ((&key (width 32) (height 32) x y) &body body)
`(with-bitmap (,width ,height)
(with-turtle ()
,@(when x `((setf (turtle-x *turtle*) ,x)))
,@(when y `((setf (turtle-y *turtle*) ,y)))
,@body
(draw))))
(defun turtle-race ()
"Sure and steady wins the race."
(macrolet ((races (&rest name-bodies)
`(progn
,@(loop for (name arguments . body) in name-bodies
collect `(format t "~(~A~)~%" ',name)
collect `(turtle-graphics ,arguments ,@body)
collect `(terpri)))))
(races
(squares
(:x 2 :y 30)
(loop for width from 2 to 24 by 4
do (repeat 4
(forward width)
(right 90))))
(squares-rotated
(:x 2 :y 16)
(right 45)
(loop for width from 2 to 20 by 4
do (repeat 4
(forward width)
(right 90))))
(triangle
(:x 2 :y 30)
(repeat 3
(forward 24)
(right 120)))
(circle
(:x 2 :y 20)
(repeat 26
(forward 3)
(right (/ 360 26))))
(spiral
(:x 13 :y 16)
(loop for size from 2 to 10 by 0.3
do (forward size)
(right 35)))
(box-spiral
(:width 64 :height 64)
(loop for a from 3 to 50 by 2
do (forward a)
(right 91)))
(star
(:width 64 :height 64 :x 20 :y 60)
(repeat 7
(forward 50)
(right (- 180 (/ 180 7))))))))
| null | https://raw.githubusercontent.com/whalliburton/academy/87a1a13ffbcd60d8553e42e647c59486c761e8cf/turtle-graphics.lisp | lisp | (in-package :academy)
(defvar *turtle*)
(defstruct turtle x y heading bitmap pen)
(defmacro with-turtle ((&optional (bitmap '*bitmap*)) &body body)
`(destructuring-bind (height width) (array-dimensions ,bitmap)
(let ((*turtle* (make-turtle :x (floor width 2) :y (floor height 2) :heading 0
:bitmap ,bitmap :pen :down)))
,@body)))
(defun pen-up (&optional (turtle *turtle*))
(setf (turtle-pen turtle) :up))
(defun pen-is-up (&optional (turtle *turtle*))
(eq (turtle-pen turtle) :up))
(defun pen-down (&optional (turtle *turtle*))
(setf (turtle-pen turtle) :down))
(defun pen-is-down (&optional (turtle *turtle*))
(eq (turtle-pen turtle) :down))
(defun left (degrees &optional (turtle *turtle*))
(setf (turtle-heading turtle)
(mod (- (turtle-heading turtle) degrees) 360)))
(defun right (degrees &optional (turtle *turtle*))
(setf (turtle-heading turtle)
(mod (+ (turtle-heading turtle) degrees) 360)))
(defmacro repeat (times &body body)
`(dotimes (,(gensym) ,times)
,@body))
(defun move-to (x y &optional (turtle *turtle*))
(when (pen-is-down turtle)
(draw-line (round (turtle-x turtle)) (round (turtle-y turtle)) (round x) (round y)
(turtle-bitmap turtle)))
(setf (turtle-x turtle) x
(turtle-y turtle) y))
(defun degrees-to-radians (degrees)
(/ (* degrees pi) 180))
(defun forward (steps &optional (turtle *turtle*))
(let ((x (turtle-x turtle))
(y (turtle-y turtle))
(heading (- (turtle-heading turtle) 90)))
(let* ((dx (* steps (cos (degrees-to-radians heading))))
(dy (* steps (sin (degrees-to-radians heading)))))
(move-to (+ x dx) (+ y dy) turtle))))
(defun backward (steps &optional (turtle *turtle*))
(forward (- steps) turtle))
(defmacro turtle-graphics ((&key (width 32) (height 32) x y) &body body)
`(with-bitmap (,width ,height)
(with-turtle ()
,@(when x `((setf (turtle-x *turtle*) ,x)))
,@(when y `((setf (turtle-y *turtle*) ,y)))
,@body
(draw))))
(defun turtle-race ()
"Sure and steady wins the race."
(macrolet ((races (&rest name-bodies)
`(progn
,@(loop for (name arguments . body) in name-bodies
collect `(format t "~(~A~)~%" ',name)
collect `(turtle-graphics ,arguments ,@body)
collect `(terpri)))))
(races
(squares
(:x 2 :y 30)
(loop for width from 2 to 24 by 4
do (repeat 4
(forward width)
(right 90))))
(squares-rotated
(:x 2 :y 16)
(right 45)
(loop for width from 2 to 20 by 4
do (repeat 4
(forward width)
(right 90))))
(triangle
(:x 2 :y 30)
(repeat 3
(forward 24)
(right 120)))
(circle
(:x 2 :y 20)
(repeat 26
(forward 3)
(right (/ 360 26))))
(spiral
(:x 13 :y 16)
(loop for size from 2 to 10 by 0.3
do (forward size)
(right 35)))
(box-spiral
(:width 64 :height 64)
(loop for a from 3 to 50 by 2
do (forward a)
(right 91)))
(star
(:width 64 :height 64 :x 20 :y 60)
(repeat 7
(forward 50)
(right (- 180 (/ 180 7))))))))
|
|
6d834bee88992414d73b1496c90c65dc1053cea5d0d6b13210af777c3bac70e9 | OCamlPro/ocp-build | buildOCPInterp.ml | (**************************************************************************)
(* *)
(* Typerex Tools *)
(* *)
Copyright 2011 - 2017 OCamlPro SAS
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU General Public License version 3 described in the file
(* LICENSE. *)
(* *)
(**************************************************************************)
open OcpCompat
open BuildValue.TYPES
open BuildOCPTree
module Eval(S: sig
type context
val filesubst : (string * env list) BuildSubst.t
val define_package :
location ->
context -> config ->
name:string ->
kind:string ->
unit
if not ! continue_on_ocp_error then exit 2 ;
val parse_error : unit -> unit
val new_file : context -> string -> string -> unit
end) = struct
In version 1 , [ a [ b c ] d ] is equivalent to [ a b c d ] . [ vlist_concat ]
merges inner lists into the current list .
merges inner lists into the current list. *)
let vlist_concat list =
VList (List.concat (List.map (fun v ->
match v with
VList list -> list
| _ -> [v]
) list))
type prim = env list -> env -> plist
let meta_options = [
"o", [ "dep"; "bytecomp"; "bytelink"; "asmcomp"; "asmlink" ];
"oc", [ "bytecomp"; "bytelink"; "asmcomp"; "asmlink" ];
"byte", [ "bytecomp"; "bytelink"; ];
"asm", [ "asmcomp"; "asmlink"; ];
"comp", [ "bytecomp"; "asmcomp"; ];
"link", [ "bytelink"; "asmlink"; ];
"debugflag", [ "debugflag"; "asmdebug"; "bytedebug"; ];
]
let configs = ref StringMap.empty
let define_config config config_name options =
configs := StringMap.add config_name options !configs;
config
let find_config config config_name =
try
StringMap.find config_name !configs
with Not_found ->
failwith (Printf.sprintf "Error: configuration %S not found\n" config_name)
let read_config_file filename =
try
let content = FileString.string_of_file filename in
let digest = Digest.string content in
Some (content, digest)
with
| _e ->
Printf.eprintf "Error: file %S does not exist.\n%!" filename;
None
module Primitives = BuildOCPPrims.Init(S)
let primitives_help = Primitives.primitives_help
let primitives = Primitives.primitives
let rec translate_toplevel_statements ctx config list =
match list with
[] -> config
| stmt :: list ->
let config = translate_toplevel_statement ctx config stmt in
translate_toplevel_statements ctx config list
and translate_toplevel_statement ctx config stmt =
match stmt with
| StmtDefineConfig (config_name, options) ->
let config_name = translate_string_expression ctx config [config.config_env] config_name in
define_config config config_name options
(* (fun old_options -> translate_options old_options options); *)
| StmtDefinePackage (package_type, library_name, simple_statements) ->
let library_name = translate_string_expression ctx config [config.config_env] library_name in
begin
try
let config = translate_statements ctx config simple_statements in
S.define_package (BuildValue.noloc config.config_filename) ctx config
~name:library_name
~kind:package_type
with e ->
Printf.eprintf "Error while interpreting package %S:\n%!" library_name;
raise e
end;
config
| StmtBlock statements ->
ignore (translate_toplevel_statements ctx config statements : config);
config
| StmtIfThenElse (cond, ifthen, ifelse) -> begin
if translate_condition ctx config [config.config_env] cond then
translate_toplevel_statements ctx config ifthen
else
match ifelse with
None -> config
| Some ifelse ->
translate_toplevel_statements ctx config ifelse
end
| StmtInclude (filename, ifthen, ifelse) ->
let filename = translate_string_expression ctx config [config.config_env] filename in
if Filename.check_suffix filename ".ocp" then begin
Printf.eprintf "Warning, file %S, 'include %S', file argument should not\n"
config.config_filename filename;
Printf.eprintf " have a .ocp extension, as it will be loaded independantly\n%!";
end;
let filename = BuildSubst.subst_global filename in
let filename = if Filename.is_relative filename then
Filename.concat (BuildValue.get_dirname config) filename
else filename
in
let (ast, digest) =
match read_config_file filename with
None -> None, None
| Some (content, digest) ->
S.new_file ctx filename digest;
Some (BuildOCPParse.read_ocamlconf filename content),
Some digest
in
let old_filename = config.config_filename in
let config = { config with
config_filenames = (filename, digest) :: config.config_filenames;
}
in
begin
match ast, ifelse with
| Some ast, _ ->
let config = translate_toplevel_statements ctx { config with config_filename = filename } ast in
translate_toplevel_statements ctx { config with config_filename = old_filename } ifthen
| None, None -> config
| None, Some ifelse ->
translate_toplevel_statements ctx config ifelse
end
| _ -> translate_simple_statement ctx config stmt
and translate_statements ctx config list =
match list with
[] -> config
| stmt :: list ->
let config = translate_statement ctx config stmt in
translate_statements ctx config list
and translate_statement ctx config stmt =
match stmt with
| StmtIfThenElse (cond, ifthen, ifelse) -> begin
if translate_condition ctx config [config.config_env] cond then
translate_statements ctx config ifthen
else
match ifelse with
None -> config
| Some ifelse ->
translate_statements ctx config ifelse
end
| _ -> translate_simple_statement ctx config stmt
and translate_simple_statement ctx config stmt =
match stmt with
| StmtOption option ->
{ config with config_env =
translate_option ctx config
[] config.config_env option }
( syntax_name , camlpN , extensions ) - > config
| StmtIfThenElse _
| StmtBlock _
| StmtInclude _
| StmtDefinePackage _
| StmtDefineConfig _ -> assert false
and translate_condition ctx config envs cond =
match cond with
| IsEqual (exp1, exp2) ->
let exp1 = translate_expression ctx config envs exp1 in
let exp2 = translate_expression ctx config envs exp2 in
exp1 = exp2 ||
begin match exp1, exp2 with
| VString (s1,_), VList [VString (s2,_)]
| VList [VString (s1,_)], VString (s2,_) -> s1 = s2
| _ -> false
end
| IsNonFalse exp ->
let exp = try
translate_expression ctx config envs exp
with _ -> VBool false
in
BuildValue.bool_of_plist exp
| Greater (e1,e2) ->
let e1 = translate_expression ctx config envs e1 in
let e2 = translate_expression ctx config envs e2 in
BuildValue.compare_values e1 e2 = 1
| GreaterEqual (e1,e2) ->
let e1 = translate_expression ctx config envs e1 in
let e2 = translate_expression ctx config envs e2 in
BuildValue.compare_values e1 e2 >= 0
| NotCondition cond -> not (translate_condition ctx config envs cond)
| AndConditions (cond1, cond2) ->
(translate_condition ctx config envs cond1)
&& (translate_condition ctx config envs cond2)
| OrConditions (cond1, cond2) ->
(translate_condition ctx config envs cond1)
|| (translate_condition ctx config envs cond2)
and translate_options ctx config envs env list =
match list with
[] -> env
| option :: list ->
let env = translate_option ctx config envs env option in
translate_options ctx config envs env list
and translate_option ctx config envs env op =
match op with
| OptionConfigUse config_name ->
let config_name = translate_string_expression ctx config (env :: envs) config_name in
translate_options ctx config envs env (find_config config config_name)
| OptionVariableSet (name, exp) ->
(* TODO: global options *)
let (exp : value) = translate_expression ctx config (env :: envs) exp in
let vars = try
List.assoc name meta_options
with Not_found -> [ name ]
in
List.fold_left (fun env name -> BuildValue.set env name exp) env vars
| OptionVariableAppend (name, exp) ->
(* TODO: global options *)
let exp2 = translate_expression ctx config (env :: envs) exp in
let vars = try
List.assoc name meta_options
with Not_found -> [ name ]
in
List.fold_left (fun env name ->
let exp1 = try BuildValue.get (env ::envs) name
with Var_not_found _ ->
failwith (Printf.sprintf "Variable %S is undefined (in +=)\n%!" name)
in
BuildValue.set env name (vlist_concat [exp1; exp2])
) env vars
| OptionIfThenElse (cond, ifthen, ifelse) ->
begin
if translate_condition ctx config (env :: envs) cond then
translate_option ctx config envs env ifthen
else
match ifelse with
None -> env
| Some ifelse ->
translate_option ctx config envs env ifelse
end
| OptionBlock list -> translate_options ctx config envs env list
and translate_string_expression ctx config envs exp =
match translate_expression ctx config envs exp with
VString (s,_) |
VList [VString (s,_)] |
VList [VTuple [VString (s,_); _]] -> s
| _ -> failwith "Single string expected"
and translate_expression ctx config envs exp =
Printf.eprintf " translate_expression\n% ! " ;
match exp with
| ExprBool bool -> VBool bool
| ExprString s -> VString (s, StringRaw)
| ExprPrimitive (s, args) ->
let (f, _) = try StringMap.find s !primitives with
Not_found ->
failwith (Printf.sprintf "Could not find primitive %S\n%!" s)
in
f envs (translate_options ctx config envs BuildValue.empty_env args)
| ExprVariable name ->
let exp = try BuildValue.get envs name
with Var_not_found _ ->
failwith (Printf.sprintf "Variable %S is undefined\n%!" name)
in
exp
| ExprList list ->
vlist_concat (List.map (translate_expression ctx config envs) list)
| ExprApply (exp, args) ->
let exp = translate_expression ctx config envs exp in
match exp with
| VTuple [s; VObject env] ->
VTuple [s; VObject (translate_options ctx config envs env args)]
| VList list ->
VList (List.map (fun exp ->
match exp with
| VTuple [s; VObject env] ->
VTuple [s; VObject (translate_options ctx config envs env args)]
| _ ->
VTuple [exp; VObject (translate_options ctx config envs BuildValue.empty_env args)]
) list)
| _ -> VTuple [exp; VObject (translate_options ctx config envs BuildValue.empty_env args)]
let read_ocamlconf filename =
let (filename, ast, digest) =
match read_config_file filename with
None -> filename, None, None
| Some (content, digest) ->
filename,
(try
Some (BuildOCPParse.read_ocamlconf filename content)
with BuildOCPParse.ParseError ->
S.parse_error ();
None),
Some digest
in
fun ctx config ->
begin match digest with
| None -> ()
| Some digest ->
S.new_file ctx filename digest;
end;
let config = {
config with
config_filename = filename;
config_filenames = (filename, digest) :: config.config_filenames;
}
in
let config = BuildValue.set_dirname config
(Filename.dirname filename) in
match ast with
| None -> config
| Some ast ->
try
translate_toplevel_statements ctx config ast
with e ->
Printf.eprintf "Error while interpreting file %S:\n%!" filename;
Printf.eprintf "\t%s\n%!" (Printexc.to_string e);
S.parse_error ();
config
end
| null | https://raw.githubusercontent.com/OCamlPro/ocp-build/56aff560bb438c12b2929feaf8379bc6f31b9840/tools/ocp-build/lang-ocp/buildOCPInterp.ml | ocaml | ************************************************************************
Typerex Tools
All rights reserved. This file is distributed under the terms of
LICENSE.
************************************************************************
(fun old_options -> translate_options old_options options);
TODO: global options
TODO: global options | Copyright 2011 - 2017 OCamlPro SAS
the GNU General Public License version 3 described in the file
open OcpCompat
open BuildValue.TYPES
open BuildOCPTree
module Eval(S: sig
type context
val filesubst : (string * env list) BuildSubst.t
val define_package :
location ->
context -> config ->
name:string ->
kind:string ->
unit
if not ! continue_on_ocp_error then exit 2 ;
val parse_error : unit -> unit
val new_file : context -> string -> string -> unit
end) = struct
In version 1 , [ a [ b c ] d ] is equivalent to [ a b c d ] . [ vlist_concat ]
merges inner lists into the current list .
merges inner lists into the current list. *)
let vlist_concat list =
VList (List.concat (List.map (fun v ->
match v with
VList list -> list
| _ -> [v]
) list))
type prim = env list -> env -> plist
let meta_options = [
"o", [ "dep"; "bytecomp"; "bytelink"; "asmcomp"; "asmlink" ];
"oc", [ "bytecomp"; "bytelink"; "asmcomp"; "asmlink" ];
"byte", [ "bytecomp"; "bytelink"; ];
"asm", [ "asmcomp"; "asmlink"; ];
"comp", [ "bytecomp"; "asmcomp"; ];
"link", [ "bytelink"; "asmlink"; ];
"debugflag", [ "debugflag"; "asmdebug"; "bytedebug"; ];
]
let configs = ref StringMap.empty
let define_config config config_name options =
configs := StringMap.add config_name options !configs;
config
let find_config config config_name =
try
StringMap.find config_name !configs
with Not_found ->
failwith (Printf.sprintf "Error: configuration %S not found\n" config_name)
let read_config_file filename =
try
let content = FileString.string_of_file filename in
let digest = Digest.string content in
Some (content, digest)
with
| _e ->
Printf.eprintf "Error: file %S does not exist.\n%!" filename;
None
module Primitives = BuildOCPPrims.Init(S)
let primitives_help = Primitives.primitives_help
let primitives = Primitives.primitives
let rec translate_toplevel_statements ctx config list =
match list with
[] -> config
| stmt :: list ->
let config = translate_toplevel_statement ctx config stmt in
translate_toplevel_statements ctx config list
and translate_toplevel_statement ctx config stmt =
match stmt with
| StmtDefineConfig (config_name, options) ->
let config_name = translate_string_expression ctx config [config.config_env] config_name in
define_config config config_name options
| StmtDefinePackage (package_type, library_name, simple_statements) ->
let library_name = translate_string_expression ctx config [config.config_env] library_name in
begin
try
let config = translate_statements ctx config simple_statements in
S.define_package (BuildValue.noloc config.config_filename) ctx config
~name:library_name
~kind:package_type
with e ->
Printf.eprintf "Error while interpreting package %S:\n%!" library_name;
raise e
end;
config
| StmtBlock statements ->
ignore (translate_toplevel_statements ctx config statements : config);
config
| StmtIfThenElse (cond, ifthen, ifelse) -> begin
if translate_condition ctx config [config.config_env] cond then
translate_toplevel_statements ctx config ifthen
else
match ifelse with
None -> config
| Some ifelse ->
translate_toplevel_statements ctx config ifelse
end
| StmtInclude (filename, ifthen, ifelse) ->
let filename = translate_string_expression ctx config [config.config_env] filename in
if Filename.check_suffix filename ".ocp" then begin
Printf.eprintf "Warning, file %S, 'include %S', file argument should not\n"
config.config_filename filename;
Printf.eprintf " have a .ocp extension, as it will be loaded independantly\n%!";
end;
let filename = BuildSubst.subst_global filename in
let filename = if Filename.is_relative filename then
Filename.concat (BuildValue.get_dirname config) filename
else filename
in
let (ast, digest) =
match read_config_file filename with
None -> None, None
| Some (content, digest) ->
S.new_file ctx filename digest;
Some (BuildOCPParse.read_ocamlconf filename content),
Some digest
in
let old_filename = config.config_filename in
let config = { config with
config_filenames = (filename, digest) :: config.config_filenames;
}
in
begin
match ast, ifelse with
| Some ast, _ ->
let config = translate_toplevel_statements ctx { config with config_filename = filename } ast in
translate_toplevel_statements ctx { config with config_filename = old_filename } ifthen
| None, None -> config
| None, Some ifelse ->
translate_toplevel_statements ctx config ifelse
end
| _ -> translate_simple_statement ctx config stmt
and translate_statements ctx config list =
match list with
[] -> config
| stmt :: list ->
let config = translate_statement ctx config stmt in
translate_statements ctx config list
and translate_statement ctx config stmt =
match stmt with
| StmtIfThenElse (cond, ifthen, ifelse) -> begin
if translate_condition ctx config [config.config_env] cond then
translate_statements ctx config ifthen
else
match ifelse with
None -> config
| Some ifelse ->
translate_statements ctx config ifelse
end
| _ -> translate_simple_statement ctx config stmt
and translate_simple_statement ctx config stmt =
match stmt with
| StmtOption option ->
{ config with config_env =
translate_option ctx config
[] config.config_env option }
( syntax_name , camlpN , extensions ) - > config
| StmtIfThenElse _
| StmtBlock _
| StmtInclude _
| StmtDefinePackage _
| StmtDefineConfig _ -> assert false
and translate_condition ctx config envs cond =
match cond with
| IsEqual (exp1, exp2) ->
let exp1 = translate_expression ctx config envs exp1 in
let exp2 = translate_expression ctx config envs exp2 in
exp1 = exp2 ||
begin match exp1, exp2 with
| VString (s1,_), VList [VString (s2,_)]
| VList [VString (s1,_)], VString (s2,_) -> s1 = s2
| _ -> false
end
| IsNonFalse exp ->
let exp = try
translate_expression ctx config envs exp
with _ -> VBool false
in
BuildValue.bool_of_plist exp
| Greater (e1,e2) ->
let e1 = translate_expression ctx config envs e1 in
let e2 = translate_expression ctx config envs e2 in
BuildValue.compare_values e1 e2 = 1
| GreaterEqual (e1,e2) ->
let e1 = translate_expression ctx config envs e1 in
let e2 = translate_expression ctx config envs e2 in
BuildValue.compare_values e1 e2 >= 0
| NotCondition cond -> not (translate_condition ctx config envs cond)
| AndConditions (cond1, cond2) ->
(translate_condition ctx config envs cond1)
&& (translate_condition ctx config envs cond2)
| OrConditions (cond1, cond2) ->
(translate_condition ctx config envs cond1)
|| (translate_condition ctx config envs cond2)
and translate_options ctx config envs env list =
match list with
[] -> env
| option :: list ->
let env = translate_option ctx config envs env option in
translate_options ctx config envs env list
and translate_option ctx config envs env op =
match op with
| OptionConfigUse config_name ->
let config_name = translate_string_expression ctx config (env :: envs) config_name in
translate_options ctx config envs env (find_config config config_name)
| OptionVariableSet (name, exp) ->
let (exp : value) = translate_expression ctx config (env :: envs) exp in
let vars = try
List.assoc name meta_options
with Not_found -> [ name ]
in
List.fold_left (fun env name -> BuildValue.set env name exp) env vars
| OptionVariableAppend (name, exp) ->
let exp2 = translate_expression ctx config (env :: envs) exp in
let vars = try
List.assoc name meta_options
with Not_found -> [ name ]
in
List.fold_left (fun env name ->
let exp1 = try BuildValue.get (env ::envs) name
with Var_not_found _ ->
failwith (Printf.sprintf "Variable %S is undefined (in +=)\n%!" name)
in
BuildValue.set env name (vlist_concat [exp1; exp2])
) env vars
| OptionIfThenElse (cond, ifthen, ifelse) ->
begin
if translate_condition ctx config (env :: envs) cond then
translate_option ctx config envs env ifthen
else
match ifelse with
None -> env
| Some ifelse ->
translate_option ctx config envs env ifelse
end
| OptionBlock list -> translate_options ctx config envs env list
and translate_string_expression ctx config envs exp =
match translate_expression ctx config envs exp with
VString (s,_) |
VList [VString (s,_)] |
VList [VTuple [VString (s,_); _]] -> s
| _ -> failwith "Single string expected"
and translate_expression ctx config envs exp =
Printf.eprintf " translate_expression\n% ! " ;
match exp with
| ExprBool bool -> VBool bool
| ExprString s -> VString (s, StringRaw)
| ExprPrimitive (s, args) ->
let (f, _) = try StringMap.find s !primitives with
Not_found ->
failwith (Printf.sprintf "Could not find primitive %S\n%!" s)
in
f envs (translate_options ctx config envs BuildValue.empty_env args)
| ExprVariable name ->
let exp = try BuildValue.get envs name
with Var_not_found _ ->
failwith (Printf.sprintf "Variable %S is undefined\n%!" name)
in
exp
| ExprList list ->
vlist_concat (List.map (translate_expression ctx config envs) list)
| ExprApply (exp, args) ->
let exp = translate_expression ctx config envs exp in
match exp with
| VTuple [s; VObject env] ->
VTuple [s; VObject (translate_options ctx config envs env args)]
| VList list ->
VList (List.map (fun exp ->
match exp with
| VTuple [s; VObject env] ->
VTuple [s; VObject (translate_options ctx config envs env args)]
| _ ->
VTuple [exp; VObject (translate_options ctx config envs BuildValue.empty_env args)]
) list)
| _ -> VTuple [exp; VObject (translate_options ctx config envs BuildValue.empty_env args)]
let read_ocamlconf filename =
let (filename, ast, digest) =
match read_config_file filename with
None -> filename, None, None
| Some (content, digest) ->
filename,
(try
Some (BuildOCPParse.read_ocamlconf filename content)
with BuildOCPParse.ParseError ->
S.parse_error ();
None),
Some digest
in
fun ctx config ->
begin match digest with
| None -> ()
| Some digest ->
S.new_file ctx filename digest;
end;
let config = {
config with
config_filename = filename;
config_filenames = (filename, digest) :: config.config_filenames;
}
in
let config = BuildValue.set_dirname config
(Filename.dirname filename) in
match ast with
| None -> config
| Some ast ->
try
translate_toplevel_statements ctx config ast
with e ->
Printf.eprintf "Error while interpreting file %S:\n%!" filename;
Printf.eprintf "\t%s\n%!" (Printexc.to_string e);
S.parse_error ();
config
end
|
08ca9900af80b0d3579e948b4f61e39c28d6af05dd79d6216710a95d4f399fb5 | Dasudian/DSDIN | dsdc_db.erl |
-module(dsdc_db).
-export([check_db/0, % called from setup hook
assumes started
called in dsdcore app start phase
tables/1, % for e.g. test database setup
clear_db/0, % mostly for test purposes
persisted_valid_genesis_block/0
]).
-export([transaction/1,
ensure_transaction/1,
write/2,
delete/2,
read/2]).
%% Mimicking the dsdc_persistence API used by dsdc_conductor_chain
-export([has_block/1,
write_block/1,
write_block_state/4,
write_genesis_hash/1,
write_top_block_hash/1,
find_block/1,
find_header/1,
find_headers_at_height/1,
get_block/1,
get_block_tx_hashes/1,
get_header/1,
get_genesis_hash/0,
get_signed_tx/1,
get_top_block_hash/0,
get_block_state/1
]).
%% Location of chain transactions
-export([ add_tx_location/2
, add_tx/1
, add_tx_hash_to_mempool/1
, is_in_tx_pool/1
, find_tx_location/1
, find_tx_with_location/1
, remove_tx_from_mempool/1
, remove_tx_location/1
]).
%% Only to be used from dsdc_tx_pool:init/1
-export([ fold_mempool/2
]).
%% MP trees backend
-export([ find_accounts_node/1
, find_calls_node/1
, find_channels_node/1
, find_contracts_node/1
, find_ns_node/1
, find_ns_cache_node/1
, find_oracles_node/1
, find_oracles_cache_node/1
, write_accounts_node/2
, write_calls_node/2
, write_channels_node/2
, write_contracts_node/2
, write_ns_node/2
, write_ns_cache_node/2
, write_oracles_node/2
, write_oracles_cache_node/2
]).
-export([ find_block_state/1
, find_block_difficulty/1
, find_block_fork_id/1
, find_block_state_and_data/1
]).
%% API for finding transactions related to account key
-export([transactions_by_account/3]).
%% indexing callbacks
-export([ ix_acct2tx/3
]).
-include("blocks.hrl").
-include("dsdc_db.hrl").
%% - transactions
%% - headers
%% - block [transaction_ids]
%% - oracle_state
%% - oracle_cache
%% - account_state
%% - channel_state
%% - name_service_state
%% - name_service_cache
%% - one per state tree
-define(TAB(Record),
{Record, tab(Mode, Record, record_info(fields, Record), [])}).
-define(TAB(Record, Extra),
{Record, tab(Mode, Record, record_info(fields, Record), Extra)}).
start a transaction if there is n't already one
-define(t(Expr), case get(mnesia_activity_state) of undefined ->
transaction(fun() -> Expr end);
_ -> Expr
end).
-define(TX_IN_MEMPOOL, []).
tables(Mode) ->
[?TAB(dsdc_blocks)
, ?TAB(dsdc_headers, [{index, [height]}])
, ?TAB(dsdc_chain_state)
, ?TAB(dsdc_contract_state)
, ?TAB(dsdc_call_state)
, ?TAB(dsdc_block_state)
, ?TAB(dsdc_oracle_cache)
, ?TAB(dsdc_oracle_state)
, ?TAB(dsdc_account_state)
, ?TAB(dsdc_channel_state)
, ?TAB(dsdc_name_service_cache)
, ?TAB(dsdc_name_service_state)
, ?TAB(dsdc_signed_tx, [{index, [{acct2tx}]}])
, ?TAB(dsdc_tx_location)
, ?TAB(dsdc_tx_pool)
].
tab(Mode, Record, Attributes, Extra) ->
[ tab_copies(Mode)
, {type, tab_type(Record)}
, {attributes, Attributes}
, {user_properties, [{vsn, tab_vsn(Record)}]}
| Extra].
tab_vsn(_) -> 1.
tab_type(_) -> set.
tab_copies(disc) -> {rocksdb_copies, [node()]};
tab_copies(ram ) -> {ram_copies , [node()]}.
clear_db() ->
?t([clear_table(T) || {T, _} <- tables(ram)]).
clear_table(Tab) ->
?t(begin
Keys = mnesia:all_keys(Tab),
[delete(Tab, K) || K <- Keys],
ok
end).
persisted_valid_genesis_block() ->
case application:get_env(dsdcore, persist, false) of
false ->
true;
true ->
{ok, ExpectedGH} = dsdc_headers:hash_header(dsdc_block_genesis:genesis_header()),
case dsdc_db:get_genesis_hash() of
undefined ->
lager:info("Loaded empty persisted chain"),
true;
ExpectedGH ->
true;
LoadedGH ->
lager:warning("Expected genesis block hash ~p, persisted genesis block hash ~p",
[ExpectedGH, LoadedGH]),
false
end
end.
transaction(Fun) when is_function(Fun, 0) ->
mnesia:activity(transaction, Fun).
ensure_transaction(Fun) when is_function(Fun, 0) ->
%% TODO: actually, some non-transactions also have an activity state
case get(mnesia_activity_state) of undefined ->
transaction(Fun);
_ -> Fun()
end.
read(Tab, Key) ->
mnesia:read(Tab, Key).
write(Tab, Obj) ->
mnesia:write(Tab, Obj, write).
delete(Tab, Key) ->
mnesia:delete(Tab, Key, write).
write_block(Block) ->
Header = dsdc_blocks:to_header(Block),
Height = dsdc_headers:height(Header),
Txs = dsdc_blocks:txs(Block),
{ok, Hash} = dsdc_headers:hash_header(Header),
?t(begin
TxHashes = [begin
STxHash = dsdtx_sign:hash(STx),
write_signed_tx(STxHash, STx),
STxHash
end
|| STx <- Txs],
mnesia:write(#dsdc_blocks{key = Hash,
txs = TxHashes}),
mnesia:write(#dsdc_headers{key = Hash,
value = Header,
height = Height})
end).
get_block(Hash) ->
?t(begin
[#dsdc_headers{value = Header}] =
mnesia:read(dsdc_headers, Hash),
[#dsdc_blocks{txs = TxHashes}] =
mnesia:read(dsdc_blocks, Hash),
Txs = [begin
[#dsdc_signed_tx{value = STx}] =
mnesia:read(dsdc_signed_tx, TxHash),
STx
end || TxHash <- TxHashes],
dsdc_blocks:from_header_and_txs(Header, Txs)
end).
get_block_tx_hashes(Hash) ->
?t(begin
[#dsdc_blocks{txs = TxHashes}] =
mnesia:read(dsdc_blocks, Hash),
TxHashes
end).
get_header(Hash) ->
?t(begin
[#dsdc_headers{value = Header}] =
mnesia:read(dsdc_headers, Hash),
Header
end).
has_block(Hash) ->
case ?t(mnesia:read(dsdc_headers, Hash)) of
[] -> false;
[_] -> true
end.
find_block(Hash) ->
?t(case mnesia:read(dsdc_blocks, Hash) of
[#dsdc_blocks{txs = TxHashes}] ->
Txs = [begin
[#dsdc_signed_tx{value = STx}] =
mnesia:read(dsdc_signed_tx, TxHash),
STx
end || TxHash <- TxHashes],
[#dsdc_headers{value = Header}] = mnesia:read(dsdc_headers, Hash),
{value, dsdc_blocks:from_header_and_txs(Header, Txs)};
[] -> none
end).
find_header(Hash) ->
case ?t(mnesia:read(dsdc_headers, Hash)) of
[#dsdc_headers{value = Header}] -> {value, Header};
[] -> none
end.
find_headers_at_height(Height) when is_integer(Height), Height >= 0 ->
?t([H || #dsdc_headers{value = H}
<- mnesia:index_read(dsdc_headers, Height, height)]).
write_block_state(Hash, Trees, AccDifficulty, ForkId) ->
?t(mnesia:write(#dsdc_block_state{key = Hash, value = Trees,
difficulty = AccDifficulty,
fork_id = ForkId
})).
write_accounts_node(Hash, Node) ->
?t(mnesia:write(#dsdc_account_state{key = Hash, value = Node})).
write_calls_node(Hash, Node) ->
?t(mnesia:write(#dsdc_call_state{key = Hash, value = Node})).
write_channels_node(Hash, Node) ->
?t(mnesia:write(#dsdc_channel_state{key = Hash, value = Node})).
write_contracts_node(Hash, Node) ->
?t(mnesia:write(#dsdc_contract_state{key = Hash, value = Node})).
write_ns_node(Hash, Node) ->
?t(mnesia:write(#dsdc_name_service_state{key = Hash, value = Node})).
write_ns_cache_node(Hash, Node) ->
?t(mnesia:write(#dsdc_name_service_cache{key = Hash, value = Node})).
write_oracles_node(Hash, Node) ->
?t(mnesia:write(#dsdc_oracle_state{key = Hash, value = Node})).
write_oracles_cache_node(Hash, Node) ->
?t(mnesia:write(#dsdc_oracle_cache{key = Hash, value = Node})).
write_genesis_hash(Hash) when is_binary(Hash) ->
?t(mnesia:write(#dsdc_chain_state{key = genesis_hash, value = Hash})).
write_top_block_hash(Hash) when is_binary(Hash) ->
?t(mnesia:write(#dsdc_chain_state{key = top_block_hash, value = Hash})).
get_genesis_hash() ->
get_chain_state_value(genesis_hash).
get_top_block_hash() ->
get_chain_state_value(top_block_hash).
get_block_state(Hash) ->
?t(begin
[#dsdc_block_state{value = Trees}] =
mnesia:read(dsdc_block_state, Hash),
Trees
end).
find_block_state(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{value = Trees}] -> {value, Trees};
[] -> none
end.
find_block_difficulty(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{difficulty = D}] -> {value, D};
[] -> none
end.
find_block_fork_id(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{fork_id = F}] -> {value, F};
[] -> none
end.
find_block_state_and_data(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{value = Trees, difficulty = D, fork_id = F}] ->
{value, Trees, D, F};
[] -> none
end.
find_oracles_node(Hash) ->
case ?t(mnesia:read(dsdc_oracle_state, Hash)) of
[#dsdc_oracle_state{value = Node}] -> {value, Node};
[] -> none
end.
find_oracles_cache_node(Hash) ->
case ?t(mnesia:read(dsdc_oracle_cache, Hash)) of
[#dsdc_oracle_cache{value = Node}] -> {value, Node};
[] -> none
end.
find_calls_node(Hash) ->
case ?t(mnesia:read(dsdc_call_state, Hash)) of
[#dsdc_call_state{value = Node}] -> {value, Node};
[] -> none
end.
find_channels_node(Hash) ->
case ?t(mnesia:read(dsdc_channel_state, Hash)) of
[#dsdc_channel_state{value = Node}] -> {value, Node};
[] -> none
end.
find_contracts_node(Hash) ->
case ?t(mnesia:read(dsdc_contract_state, Hash)) of
[#dsdc_contract_state{value = Node}] -> {value, Node};
[] -> none
end.
find_ns_node(Hash) ->
case ?t(mnesia:read(dsdc_name_service_state, Hash)) of
[#dsdc_name_service_state{value = Node}] -> {value, Node};
[] -> none
end.
find_ns_cache_node(Hash) ->
case ?t(mnesia:read(dsdc_name_service_cache, Hash)) of
[#dsdc_name_service_cache{value = Node}] -> {value, Node};
[] -> none
end.
find_accounts_node(Hash) ->
case ?t(mnesia:read(dsdc_account_state, Hash)) of
[#dsdc_account_state{value = Node}] -> {value, Node};
[] -> none
end.
get_chain_state_value(Key) ->
?t(case mnesia:read(dsdc_chain_state, Key) of
[#dsdc_chain_state{value = Value}] ->
Value;
_ ->
undefined
end).
write_signed_tx(Hash, STx) ->
?t(write(dsdc_signed_tx, #dsdc_signed_tx{key = Hash,
value = STx})).
get_signed_tx(Hash) ->
[#dsdc_signed_tx{value = STx}] = ?t(read(dsdc_signed_tx, Hash)),
STx.
add_tx_location(STxHash, BlockHash) when is_binary(STxHash),
is_binary(BlockHash) ->
Obj = #dsdc_tx_location{key = STxHash, value = BlockHash},
?t(write(dsdc_tx_location, Obj)).
remove_tx_location(TxHash) when is_binary(TxHash) ->
?t(delete(dsdc_tx_location, TxHash)).
find_tx_location(STxHash) ->
?t(case mnesia:read(dsdc_tx_location, STxHash) of
[] ->
case mnesia:read(dsdc_tx_pool, STxHash) of
[] -> none;
[_] -> mempool
end;
[#dsdc_tx_location{value = BlockHash}] -> BlockHash
end).
-spec find_tx_with_location(binary()) ->
'none'
| {'mempool', dsdtx_sign:signed_tx()}
| {binary(), dsdtx_sign:signed_tx()}.
find_tx_with_location(STxHash) ->
?t(case mnesia:read(dsdc_signed_tx, STxHash) of
[#dsdc_signed_tx{value = STx}] ->
case mnesia:read(dsdc_tx_location, STxHash) of
[] ->
case mnesia:read(dsdc_tx_pool, STxHash) of
[] -> none;
[_] -> {mempool, STx}
end;
[#dsdc_tx_location{value = BlockHash}] -> {BlockHash, STx}
end;
[] -> none
end).
add_tx(STx) ->
Hash = dsdtx_sign:hash(STx),
?t(case mnesia:read(dsdc_signed_tx, Hash) of
[_] -> {error, already_exists};
[] ->
Obj = #dsdc_signed_tx{key = Hash, value = STx},
write(dsdc_signed_tx, Obj),
add_tx_hash_to_mempool(Hash),
{ok, Hash}
end).
add_tx_hash_to_mempool(TxHash) when is_binary(TxHash) ->
Obj = #dsdc_tx_pool{key = TxHash, value = []},
?t(write(dsdc_tx_pool, Obj)).
is_in_tx_pool(TxHash) ->
?t(mnesia:read(dsdc_tx_pool, TxHash)) =/= [].
remove_tx_from_mempool(TxHash) when is_binary(TxHash) ->
?t(delete(dsdc_tx_pool, TxHash)).
fold_mempool(FunIn, InitAcc) ->
Fun = fun(#dsdc_tx_pool{key = Hash}, Acc) ->
FunIn(Hash, Acc)
end,
?t(mnesia:foldl(Fun, InitAcc, dsdc_tx_pool)).
For patches .
transactions_by_account(AcctPubKey, Filter, false =_ShowPending) ->
?t([{STxHash, T}
|| #dsdc_signed_tx{value = T, key = STxHash}
<- mnesia:index_read(dsdc_signed_tx, AcctPubKey, {acct2tx}),
mnesia:read(dsdc_tx_location, STxHash) =/= [],
Filter(T)
]);
transactions_by_account(AcctPubKey, Filter, true =_ShowPending) ->
?t([{STxHash, T}
|| #dsdc_signed_tx{key = STxHash, value = T}
<- mnesia:index_read(dsdc_signed_tx, AcctPubKey, {acct2tx}),
(mnesia:read(dsdc_tx_location, STxHash) =/= [])
orelse is_in_tx_pool(STxHash),
Filter(T)
]).
%% start phase hook to load the database
load_database() ->
lager:debug("load_database()", []),
try
wait_for_tables()
catch
error:E ->
erlang:error({E, erlang:get_stacktrace()});
exit:E ->
exit({E, erlang:get_stacktrace()})
end.
wait_for_tables() ->
Tabs = mnesia:system_info(tables) -- [schema],
lager:debug("wait_for_tables (~p)", [Tabs]),
case wait_for_tables(Tabs, 0, _TimePeriods = 5, _MaxWait = 60) of
ok -> ok;
{timeout, Mins, NotLoaded} ->
lager:error("Tables not loaded after ~p minutes: ~p",
[Mins, NotLoaded]),
init:stop()
end.
wait_for_tables(Tabs, Sofar, Period, Max) when Sofar < Max ->
case mnesia:wait_for_tables(Tabs, timer:minutes(Period)) of
ok ->
ok;
{timeout, NotLoaded} ->
lager:warning("Tables not loaded after ~p minutes: ~p",
[Period, NotLoaded]),
wait_for_tables(NotLoaded, Sofar + Period, Period, Max)
end;
wait_for_tables(Tabs, Sofar, _, _) ->
{timeout, Sofar, Tabs}.
%% Index callbacks
ix_acct2tx(dsdc_signed_tx, _Ix, #dsdc_signed_tx{value = SignedTx}) ->
try dsdtx_sign:tx(SignedTx) of
Tx ->
dsdtx:accounts(Tx)
catch
error:_ ->
[]
end.
%% Initialization routines
check_db() ->
try
Mode = case application:get_env(dsdcore, persist, false) of
true -> disc;
false -> ram
end,
Storage = ensure_schema_storage_mode(Mode),
ok = application:ensure_started(mnesia),
initialize_db(Mode, Storage)
catch
error:Reason ->
lager:error("CAUGHT error:~p / ~p",
[Reason, erlang:get_stacktrace()]),
error(Reason)
end.
%% Test interface
initialize_db(ram) ->
initialize_db(ram, ok).
initialize_db(Mode, Storage) ->
add_backend_plugins(Mode),
run_hooks('$dsdc_db_add_plugins', Mode),
add_index_plugins(),
run_hooks('$dsdc_db_add_index_plugins', Mode),
ensure_mnesia_tables(Mode, Storage),
ok.
run_hooks(Hook, Mode) ->
[M:F(Mode) || {_App, {M,F}} <- setup:find_env_vars(Hook)].
fold_hooks(Hook, Acc0) ->
lists:foldl(
fun({_App, {M,F}}, Acc) ->
M:F(Acc)
end, Acc0, setup:find_env_vars(Hook)).
add_backend_plugins(disc) ->
mnesia_rocksdb:register();
add_backend_plugins(_) ->
ok.
add_index_plugins() ->
mnesia_schema:add_index_plugin({acct2tx}, dsdc_db, ix_acct2tx).
ensure_mnesia_tables(Mode, Storage) ->
Tables = tables(Mode),
case Storage of
existing_schema ->
case check_mnesia_tables(Tables, []) of
[] -> ok;
Errors ->
lager:error("Database check failed: ~p", [Errors]),
error({table_check, Errors})
end;
ok ->
[{atomic,ok} = mnesia:create_table(T, Spec)
|| {T, Spec} <- Tables],
run_hooks('$dsdc_db_create_tables', Mode),
ok
end.
check_mnesia_tables([{Table, Spec}|Left], Acc) ->
NewAcc = try mnesia:table_info(Table, user_properties) of
[{vsn, Vsn}] ->
case proplists:get_value(user_properties, Spec) of
[{vsn, Vsn}] -> Acc;
[{vsn, Old}] -> [{vsn_fail, Table,
[{expected, Vsn},
{got, Old}]}
|Acc]
end;
Other -> [{missing_version, Table, Other}|Acc]
catch _:_ -> [{missing_table, Table}|Acc]
end,
check_mnesia_tables(Left, NewAcc);
check_mnesia_tables([], Acc) ->
fold_hooks('$dsdc_db_check_tables', Acc).
ensure_schema_storage_mode(ram) ->
case disc_db_exists() of
{true, Dir} ->
lager:warning("Will not use existing Mnesia db (~s)", [Dir]),
set_dummy_mnesia_dir(Dir);
false ->
ok
end;
ensure_schema_storage_mode(disc) ->
case mnesia:create_schema([node()]) of
{error, {_, {already_exists, _}}} -> existing_schema;
ok -> ok
end.
disc_db_exists() ->
Dir = default_dir(),
case f_exists(Dir) of
true ->
{true, Dir};
false ->
false
end.
f_exists(F) ->
case file:read_link_info(F) of
{ok, _} -> true;
_ -> false
end.
set_dummy_mnesia_dir(Dir) ->
TS = erlang:system_time(millisecond),
NewDir = find_nonexisting(filename:absname(Dir), TS),
application:set_env(mnesia, dir, NewDir).
find_nonexisting(Dir, N) ->
Path = Dir ++ "-" ++ integer_to_list(N),
case f_exists(Path) of
true ->
find_nonexisting(Dir, N+1);
false ->
Path
end.
default_dir() ->
case application:get_env(mnesia, dir) of
undefined ->
%% This is is how mnesia produces the default. The result will
%% be the same as long as the current working directory doesn't
change between now and when starts .
filename:absname(lists:concat(["Mnesia.", node()]));
{ok, Dir} ->
Dir
end.
| null | https://raw.githubusercontent.com/Dasudian/DSDIN/b27a437d8deecae68613604fffcbb9804a6f1729/apps/dsdcore/src/dsdc_db.erl | erlang | called from setup hook
for e.g. test database setup
mostly for test purposes
Mimicking the dsdc_persistence API used by dsdc_conductor_chain
Location of chain transactions
Only to be used from dsdc_tx_pool:init/1
MP trees backend
API for finding transactions related to account key
indexing callbacks
- transactions
- headers
- block [transaction_ids]
- oracle_state
- oracle_cache
- account_state
- channel_state
- name_service_state
- name_service_cache
- one per state tree
TODO: actually, some non-transactions also have an activity state
start phase hook to load the database
Index callbacks
Initialization routines
Test interface
This is is how mnesia produces the default. The result will
be the same as long as the current working directory doesn't |
-module(dsdc_db).
assumes started
called in dsdcore app start phase
persisted_valid_genesis_block/0
]).
-export([transaction/1,
ensure_transaction/1,
write/2,
delete/2,
read/2]).
-export([has_block/1,
write_block/1,
write_block_state/4,
write_genesis_hash/1,
write_top_block_hash/1,
find_block/1,
find_header/1,
find_headers_at_height/1,
get_block/1,
get_block_tx_hashes/1,
get_header/1,
get_genesis_hash/0,
get_signed_tx/1,
get_top_block_hash/0,
get_block_state/1
]).
-export([ add_tx_location/2
, add_tx/1
, add_tx_hash_to_mempool/1
, is_in_tx_pool/1
, find_tx_location/1
, find_tx_with_location/1
, remove_tx_from_mempool/1
, remove_tx_location/1
]).
-export([ fold_mempool/2
]).
-export([ find_accounts_node/1
, find_calls_node/1
, find_channels_node/1
, find_contracts_node/1
, find_ns_node/1
, find_ns_cache_node/1
, find_oracles_node/1
, find_oracles_cache_node/1
, write_accounts_node/2
, write_calls_node/2
, write_channels_node/2
, write_contracts_node/2
, write_ns_node/2
, write_ns_cache_node/2
, write_oracles_node/2
, write_oracles_cache_node/2
]).
-export([ find_block_state/1
, find_block_difficulty/1
, find_block_fork_id/1
, find_block_state_and_data/1
]).
-export([transactions_by_account/3]).
-export([ ix_acct2tx/3
]).
-include("blocks.hrl").
-include("dsdc_db.hrl").
-define(TAB(Record),
{Record, tab(Mode, Record, record_info(fields, Record), [])}).
-define(TAB(Record, Extra),
{Record, tab(Mode, Record, record_info(fields, Record), Extra)}).
start a transaction if there is n't already one
-define(t(Expr), case get(mnesia_activity_state) of undefined ->
transaction(fun() -> Expr end);
_ -> Expr
end).
-define(TX_IN_MEMPOOL, []).
tables(Mode) ->
[?TAB(dsdc_blocks)
, ?TAB(dsdc_headers, [{index, [height]}])
, ?TAB(dsdc_chain_state)
, ?TAB(dsdc_contract_state)
, ?TAB(dsdc_call_state)
, ?TAB(dsdc_block_state)
, ?TAB(dsdc_oracle_cache)
, ?TAB(dsdc_oracle_state)
, ?TAB(dsdc_account_state)
, ?TAB(dsdc_channel_state)
, ?TAB(dsdc_name_service_cache)
, ?TAB(dsdc_name_service_state)
, ?TAB(dsdc_signed_tx, [{index, [{acct2tx}]}])
, ?TAB(dsdc_tx_location)
, ?TAB(dsdc_tx_pool)
].
tab(Mode, Record, Attributes, Extra) ->
[ tab_copies(Mode)
, {type, tab_type(Record)}
, {attributes, Attributes}
, {user_properties, [{vsn, tab_vsn(Record)}]}
| Extra].
tab_vsn(_) -> 1.
tab_type(_) -> set.
tab_copies(disc) -> {rocksdb_copies, [node()]};
tab_copies(ram ) -> {ram_copies , [node()]}.
clear_db() ->
?t([clear_table(T) || {T, _} <- tables(ram)]).
clear_table(Tab) ->
?t(begin
Keys = mnesia:all_keys(Tab),
[delete(Tab, K) || K <- Keys],
ok
end).
persisted_valid_genesis_block() ->
case application:get_env(dsdcore, persist, false) of
false ->
true;
true ->
{ok, ExpectedGH} = dsdc_headers:hash_header(dsdc_block_genesis:genesis_header()),
case dsdc_db:get_genesis_hash() of
undefined ->
lager:info("Loaded empty persisted chain"),
true;
ExpectedGH ->
true;
LoadedGH ->
lager:warning("Expected genesis block hash ~p, persisted genesis block hash ~p",
[ExpectedGH, LoadedGH]),
false
end
end.
transaction(Fun) when is_function(Fun, 0) ->
mnesia:activity(transaction, Fun).
ensure_transaction(Fun) when is_function(Fun, 0) ->
case get(mnesia_activity_state) of undefined ->
transaction(Fun);
_ -> Fun()
end.
read(Tab, Key) ->
mnesia:read(Tab, Key).
write(Tab, Obj) ->
mnesia:write(Tab, Obj, write).
delete(Tab, Key) ->
mnesia:delete(Tab, Key, write).
write_block(Block) ->
Header = dsdc_blocks:to_header(Block),
Height = dsdc_headers:height(Header),
Txs = dsdc_blocks:txs(Block),
{ok, Hash} = dsdc_headers:hash_header(Header),
?t(begin
TxHashes = [begin
STxHash = dsdtx_sign:hash(STx),
write_signed_tx(STxHash, STx),
STxHash
end
|| STx <- Txs],
mnesia:write(#dsdc_blocks{key = Hash,
txs = TxHashes}),
mnesia:write(#dsdc_headers{key = Hash,
value = Header,
height = Height})
end).
get_block(Hash) ->
?t(begin
[#dsdc_headers{value = Header}] =
mnesia:read(dsdc_headers, Hash),
[#dsdc_blocks{txs = TxHashes}] =
mnesia:read(dsdc_blocks, Hash),
Txs = [begin
[#dsdc_signed_tx{value = STx}] =
mnesia:read(dsdc_signed_tx, TxHash),
STx
end || TxHash <- TxHashes],
dsdc_blocks:from_header_and_txs(Header, Txs)
end).
get_block_tx_hashes(Hash) ->
?t(begin
[#dsdc_blocks{txs = TxHashes}] =
mnesia:read(dsdc_blocks, Hash),
TxHashes
end).
get_header(Hash) ->
?t(begin
[#dsdc_headers{value = Header}] =
mnesia:read(dsdc_headers, Hash),
Header
end).
has_block(Hash) ->
case ?t(mnesia:read(dsdc_headers, Hash)) of
[] -> false;
[_] -> true
end.
find_block(Hash) ->
?t(case mnesia:read(dsdc_blocks, Hash) of
[#dsdc_blocks{txs = TxHashes}] ->
Txs = [begin
[#dsdc_signed_tx{value = STx}] =
mnesia:read(dsdc_signed_tx, TxHash),
STx
end || TxHash <- TxHashes],
[#dsdc_headers{value = Header}] = mnesia:read(dsdc_headers, Hash),
{value, dsdc_blocks:from_header_and_txs(Header, Txs)};
[] -> none
end).
find_header(Hash) ->
case ?t(mnesia:read(dsdc_headers, Hash)) of
[#dsdc_headers{value = Header}] -> {value, Header};
[] -> none
end.
find_headers_at_height(Height) when is_integer(Height), Height >= 0 ->
?t([H || #dsdc_headers{value = H}
<- mnesia:index_read(dsdc_headers, Height, height)]).
write_block_state(Hash, Trees, AccDifficulty, ForkId) ->
?t(mnesia:write(#dsdc_block_state{key = Hash, value = Trees,
difficulty = AccDifficulty,
fork_id = ForkId
})).
write_accounts_node(Hash, Node) ->
?t(mnesia:write(#dsdc_account_state{key = Hash, value = Node})).
write_calls_node(Hash, Node) ->
?t(mnesia:write(#dsdc_call_state{key = Hash, value = Node})).
write_channels_node(Hash, Node) ->
?t(mnesia:write(#dsdc_channel_state{key = Hash, value = Node})).
write_contracts_node(Hash, Node) ->
?t(mnesia:write(#dsdc_contract_state{key = Hash, value = Node})).
write_ns_node(Hash, Node) ->
?t(mnesia:write(#dsdc_name_service_state{key = Hash, value = Node})).
write_ns_cache_node(Hash, Node) ->
?t(mnesia:write(#dsdc_name_service_cache{key = Hash, value = Node})).
write_oracles_node(Hash, Node) ->
?t(mnesia:write(#dsdc_oracle_state{key = Hash, value = Node})).
write_oracles_cache_node(Hash, Node) ->
?t(mnesia:write(#dsdc_oracle_cache{key = Hash, value = Node})).
write_genesis_hash(Hash) when is_binary(Hash) ->
?t(mnesia:write(#dsdc_chain_state{key = genesis_hash, value = Hash})).
write_top_block_hash(Hash) when is_binary(Hash) ->
?t(mnesia:write(#dsdc_chain_state{key = top_block_hash, value = Hash})).
get_genesis_hash() ->
get_chain_state_value(genesis_hash).
get_top_block_hash() ->
get_chain_state_value(top_block_hash).
get_block_state(Hash) ->
?t(begin
[#dsdc_block_state{value = Trees}] =
mnesia:read(dsdc_block_state, Hash),
Trees
end).
find_block_state(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{value = Trees}] -> {value, Trees};
[] -> none
end.
find_block_difficulty(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{difficulty = D}] -> {value, D};
[] -> none
end.
find_block_fork_id(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{fork_id = F}] -> {value, F};
[] -> none
end.
find_block_state_and_data(Hash) ->
case ?t(mnesia:read(dsdc_block_state, Hash)) of
[#dsdc_block_state{value = Trees, difficulty = D, fork_id = F}] ->
{value, Trees, D, F};
[] -> none
end.
find_oracles_node(Hash) ->
case ?t(mnesia:read(dsdc_oracle_state, Hash)) of
[#dsdc_oracle_state{value = Node}] -> {value, Node};
[] -> none
end.
find_oracles_cache_node(Hash) ->
case ?t(mnesia:read(dsdc_oracle_cache, Hash)) of
[#dsdc_oracle_cache{value = Node}] -> {value, Node};
[] -> none
end.
find_calls_node(Hash) ->
case ?t(mnesia:read(dsdc_call_state, Hash)) of
[#dsdc_call_state{value = Node}] -> {value, Node};
[] -> none
end.
find_channels_node(Hash) ->
case ?t(mnesia:read(dsdc_channel_state, Hash)) of
[#dsdc_channel_state{value = Node}] -> {value, Node};
[] -> none
end.
find_contracts_node(Hash) ->
case ?t(mnesia:read(dsdc_contract_state, Hash)) of
[#dsdc_contract_state{value = Node}] -> {value, Node};
[] -> none
end.
find_ns_node(Hash) ->
case ?t(mnesia:read(dsdc_name_service_state, Hash)) of
[#dsdc_name_service_state{value = Node}] -> {value, Node};
[] -> none
end.
find_ns_cache_node(Hash) ->
case ?t(mnesia:read(dsdc_name_service_cache, Hash)) of
[#dsdc_name_service_cache{value = Node}] -> {value, Node};
[] -> none
end.
find_accounts_node(Hash) ->
case ?t(mnesia:read(dsdc_account_state, Hash)) of
[#dsdc_account_state{value = Node}] -> {value, Node};
[] -> none
end.
get_chain_state_value(Key) ->
?t(case mnesia:read(dsdc_chain_state, Key) of
[#dsdc_chain_state{value = Value}] ->
Value;
_ ->
undefined
end).
write_signed_tx(Hash, STx) ->
?t(write(dsdc_signed_tx, #dsdc_signed_tx{key = Hash,
value = STx})).
get_signed_tx(Hash) ->
[#dsdc_signed_tx{value = STx}] = ?t(read(dsdc_signed_tx, Hash)),
STx.
add_tx_location(STxHash, BlockHash) when is_binary(STxHash),
is_binary(BlockHash) ->
Obj = #dsdc_tx_location{key = STxHash, value = BlockHash},
?t(write(dsdc_tx_location, Obj)).
remove_tx_location(TxHash) when is_binary(TxHash) ->
?t(delete(dsdc_tx_location, TxHash)).
find_tx_location(STxHash) ->
?t(case mnesia:read(dsdc_tx_location, STxHash) of
[] ->
case mnesia:read(dsdc_tx_pool, STxHash) of
[] -> none;
[_] -> mempool
end;
[#dsdc_tx_location{value = BlockHash}] -> BlockHash
end).
-spec find_tx_with_location(binary()) ->
'none'
| {'mempool', dsdtx_sign:signed_tx()}
| {binary(), dsdtx_sign:signed_tx()}.
find_tx_with_location(STxHash) ->
?t(case mnesia:read(dsdc_signed_tx, STxHash) of
[#dsdc_signed_tx{value = STx}] ->
case mnesia:read(dsdc_tx_location, STxHash) of
[] ->
case mnesia:read(dsdc_tx_pool, STxHash) of
[] -> none;
[_] -> {mempool, STx}
end;
[#dsdc_tx_location{value = BlockHash}] -> {BlockHash, STx}
end;
[] -> none
end).
add_tx(STx) ->
Hash = dsdtx_sign:hash(STx),
?t(case mnesia:read(dsdc_signed_tx, Hash) of
[_] -> {error, already_exists};
[] ->
Obj = #dsdc_signed_tx{key = Hash, value = STx},
write(dsdc_signed_tx, Obj),
add_tx_hash_to_mempool(Hash),
{ok, Hash}
end).
add_tx_hash_to_mempool(TxHash) when is_binary(TxHash) ->
Obj = #dsdc_tx_pool{key = TxHash, value = []},
?t(write(dsdc_tx_pool, Obj)).
is_in_tx_pool(TxHash) ->
?t(mnesia:read(dsdc_tx_pool, TxHash)) =/= [].
remove_tx_from_mempool(TxHash) when is_binary(TxHash) ->
?t(delete(dsdc_tx_pool, TxHash)).
fold_mempool(FunIn, InitAcc) ->
Fun = fun(#dsdc_tx_pool{key = Hash}, Acc) ->
FunIn(Hash, Acc)
end,
?t(mnesia:foldl(Fun, InitAcc, dsdc_tx_pool)).
For patches .
transactions_by_account(AcctPubKey, Filter, false =_ShowPending) ->
?t([{STxHash, T}
|| #dsdc_signed_tx{value = T, key = STxHash}
<- mnesia:index_read(dsdc_signed_tx, AcctPubKey, {acct2tx}),
mnesia:read(dsdc_tx_location, STxHash) =/= [],
Filter(T)
]);
transactions_by_account(AcctPubKey, Filter, true =_ShowPending) ->
?t([{STxHash, T}
|| #dsdc_signed_tx{key = STxHash, value = T}
<- mnesia:index_read(dsdc_signed_tx, AcctPubKey, {acct2tx}),
(mnesia:read(dsdc_tx_location, STxHash) =/= [])
orelse is_in_tx_pool(STxHash),
Filter(T)
]).
load_database() ->
lager:debug("load_database()", []),
try
wait_for_tables()
catch
error:E ->
erlang:error({E, erlang:get_stacktrace()});
exit:E ->
exit({E, erlang:get_stacktrace()})
end.
wait_for_tables() ->
Tabs = mnesia:system_info(tables) -- [schema],
lager:debug("wait_for_tables (~p)", [Tabs]),
case wait_for_tables(Tabs, 0, _TimePeriods = 5, _MaxWait = 60) of
ok -> ok;
{timeout, Mins, NotLoaded} ->
lager:error("Tables not loaded after ~p minutes: ~p",
[Mins, NotLoaded]),
init:stop()
end.
wait_for_tables(Tabs, Sofar, Period, Max) when Sofar < Max ->
case mnesia:wait_for_tables(Tabs, timer:minutes(Period)) of
ok ->
ok;
{timeout, NotLoaded} ->
lager:warning("Tables not loaded after ~p minutes: ~p",
[Period, NotLoaded]),
wait_for_tables(NotLoaded, Sofar + Period, Period, Max)
end;
wait_for_tables(Tabs, Sofar, _, _) ->
{timeout, Sofar, Tabs}.
ix_acct2tx(dsdc_signed_tx, _Ix, #dsdc_signed_tx{value = SignedTx}) ->
try dsdtx_sign:tx(SignedTx) of
Tx ->
dsdtx:accounts(Tx)
catch
error:_ ->
[]
end.
check_db() ->
try
Mode = case application:get_env(dsdcore, persist, false) of
true -> disc;
false -> ram
end,
Storage = ensure_schema_storage_mode(Mode),
ok = application:ensure_started(mnesia),
initialize_db(Mode, Storage)
catch
error:Reason ->
lager:error("CAUGHT error:~p / ~p",
[Reason, erlang:get_stacktrace()]),
error(Reason)
end.
initialize_db(ram) ->
initialize_db(ram, ok).
initialize_db(Mode, Storage) ->
add_backend_plugins(Mode),
run_hooks('$dsdc_db_add_plugins', Mode),
add_index_plugins(),
run_hooks('$dsdc_db_add_index_plugins', Mode),
ensure_mnesia_tables(Mode, Storage),
ok.
run_hooks(Hook, Mode) ->
[M:F(Mode) || {_App, {M,F}} <- setup:find_env_vars(Hook)].
fold_hooks(Hook, Acc0) ->
lists:foldl(
fun({_App, {M,F}}, Acc) ->
M:F(Acc)
end, Acc0, setup:find_env_vars(Hook)).
add_backend_plugins(disc) ->
mnesia_rocksdb:register();
add_backend_plugins(_) ->
ok.
add_index_plugins() ->
mnesia_schema:add_index_plugin({acct2tx}, dsdc_db, ix_acct2tx).
ensure_mnesia_tables(Mode, Storage) ->
Tables = tables(Mode),
case Storage of
existing_schema ->
case check_mnesia_tables(Tables, []) of
[] -> ok;
Errors ->
lager:error("Database check failed: ~p", [Errors]),
error({table_check, Errors})
end;
ok ->
[{atomic,ok} = mnesia:create_table(T, Spec)
|| {T, Spec} <- Tables],
run_hooks('$dsdc_db_create_tables', Mode),
ok
end.
check_mnesia_tables([{Table, Spec}|Left], Acc) ->
NewAcc = try mnesia:table_info(Table, user_properties) of
[{vsn, Vsn}] ->
case proplists:get_value(user_properties, Spec) of
[{vsn, Vsn}] -> Acc;
[{vsn, Old}] -> [{vsn_fail, Table,
[{expected, Vsn},
{got, Old}]}
|Acc]
end;
Other -> [{missing_version, Table, Other}|Acc]
catch _:_ -> [{missing_table, Table}|Acc]
end,
check_mnesia_tables(Left, NewAcc);
check_mnesia_tables([], Acc) ->
fold_hooks('$dsdc_db_check_tables', Acc).
ensure_schema_storage_mode(ram) ->
case disc_db_exists() of
{true, Dir} ->
lager:warning("Will not use existing Mnesia db (~s)", [Dir]),
set_dummy_mnesia_dir(Dir);
false ->
ok
end;
ensure_schema_storage_mode(disc) ->
case mnesia:create_schema([node()]) of
{error, {_, {already_exists, _}}} -> existing_schema;
ok -> ok
end.
disc_db_exists() ->
Dir = default_dir(),
case f_exists(Dir) of
true ->
{true, Dir};
false ->
false
end.
f_exists(F) ->
case file:read_link_info(F) of
{ok, _} -> true;
_ -> false
end.
set_dummy_mnesia_dir(Dir) ->
TS = erlang:system_time(millisecond),
NewDir = find_nonexisting(filename:absname(Dir), TS),
application:set_env(mnesia, dir, NewDir).
find_nonexisting(Dir, N) ->
Path = Dir ++ "-" ++ integer_to_list(N),
case f_exists(Path) of
true ->
find_nonexisting(Dir, N+1);
false ->
Path
end.
default_dir() ->
case application:get_env(mnesia, dir) of
undefined ->
change between now and when starts .
filename:absname(lists:concat(["Mnesia.", node()]));
{ok, Dir} ->
Dir
end.
|
cfd5afa0dea899f24eb910b4ce57443463a89bba429f66111b5bf8931abe0d48 | esl/MongooseIM | mongoose_wpool_cassandra.erl | -module(mongoose_wpool_cassandra).
-behaviour(mongoose_wpool).
-export([init/0]).
-export([start/4]).
-export([stop/2]).
-ifdef(TEST).
-export([prepare_cqerl_opts/1]).
-endif.
%% --------------------------------------------------------------
%% mongoose_wpool callbacks
-spec init() -> ok.
init() ->
{ok, []} = application:ensure_all_started(cqerl),
application:set_env(cqerl, maps, true).
-spec start(mongooseim:host_type_or_global(), mongoose_wpool:tag(),
mongoose_wpool:pool_opts(), mongoose_wpool:conn_opts()) -> {ok, pid()} | {error, any()}.
start(HostType, Tag, WpoolOptsIn, ConnOpts) ->
PoolSize = proplists:get_value(workers, WpoolOptsIn),
application:set_env(cqerl, num_clients, PoolSize),
Servers = prepare_cqerl_servers(ConnOpts),
CqerlOpts = prepare_cqerl_opts(ConnOpts),
set_cluster_config(Tag, Servers, CqerlOpts),
Res = cqerl_cluster:add_nodes(Tag, Servers, CqerlOpts),
case lists:keyfind(error, 1, Res) of
false ->
ok;
_ ->
erlang:throw({not_all_nodes_added, Res})
end,
Name = mongoose_wpool:make_pool_name(cassandra, HostType, Tag),
Worker = {mongoose_cassandra_worker, [Tag]},
WpoolOpts = [{worker, Worker} | WpoolOptsIn],
mongoose_wpool:start_sup_pool(cassandra, Name, WpoolOpts).
-spec stop(mongooseim:host_type_or_global(), mongoose_wpool:tag()) -> ok.
stop(_, _) ->
ok.
%% --------------------------------------------------------------
Internal functions
prepare_cqerl_servers(#{servers := Servers}) ->
[cqerl_server(Server) || Server <- Servers].
cqerl_server(#{host := Host, port := Port}) -> {Host, Port};
cqerl_server(#{host := Host}) -> Host.
prepare_cqerl_opts(ConnOpts) ->
lists:flatmap(fun(Opt) -> cqerl_opts(Opt, ConnOpts) end, [keyspace, auth, tcp, tls]).
cqerl_opts(keyspace, #{keyspace := Keyspace}) ->
[{keyspace, Keyspace}];
cqerl_opts(auth, #{auth := #{plain := #{username := UserName, password := Password}}}) ->
[{auth, {cqerl_auth_plain_handler, [{UserName, Password}]}}];
cqerl_opts(tcp, #{}) ->
[{tcp_opts, [{keepalive, true}]}]; % always set
cqerl_opts(tls, #{tls := TLSOpts}) ->
[{ssl, just_tls:make_ssl_opts(TLSOpts)}];
cqerl_opts(_Opt, #{}) ->
[].
%% make the config survive the restart of 'cqerl_cluster' in case of a network failure
set_cluster_config(Tag, Servers, ExtConfig) ->
Clusters = application:get_env(cqerl, cassandra_clusters, []),
ClusterConfig = {Tag, {Servers, ExtConfig}},
NewClusters = lists:keystore(Tag, 1, Clusters, ClusterConfig),
application:set_env(cqerl, cassandra_clusters, NewClusters).
| null | https://raw.githubusercontent.com/esl/MongooseIM/65be9ea048cc2cd3f52abf3483246076fae08327/src/wpool/mongoose_wpool_cassandra.erl | erlang | --------------------------------------------------------------
mongoose_wpool callbacks
--------------------------------------------------------------
always set
make the config survive the restart of 'cqerl_cluster' in case of a network failure | -module(mongoose_wpool_cassandra).
-behaviour(mongoose_wpool).
-export([init/0]).
-export([start/4]).
-export([stop/2]).
-ifdef(TEST).
-export([prepare_cqerl_opts/1]).
-endif.
-spec init() -> ok.
init() ->
{ok, []} = application:ensure_all_started(cqerl),
application:set_env(cqerl, maps, true).
-spec start(mongooseim:host_type_or_global(), mongoose_wpool:tag(),
mongoose_wpool:pool_opts(), mongoose_wpool:conn_opts()) -> {ok, pid()} | {error, any()}.
start(HostType, Tag, WpoolOptsIn, ConnOpts) ->
PoolSize = proplists:get_value(workers, WpoolOptsIn),
application:set_env(cqerl, num_clients, PoolSize),
Servers = prepare_cqerl_servers(ConnOpts),
CqerlOpts = prepare_cqerl_opts(ConnOpts),
set_cluster_config(Tag, Servers, CqerlOpts),
Res = cqerl_cluster:add_nodes(Tag, Servers, CqerlOpts),
case lists:keyfind(error, 1, Res) of
false ->
ok;
_ ->
erlang:throw({not_all_nodes_added, Res})
end,
Name = mongoose_wpool:make_pool_name(cassandra, HostType, Tag),
Worker = {mongoose_cassandra_worker, [Tag]},
WpoolOpts = [{worker, Worker} | WpoolOptsIn],
mongoose_wpool:start_sup_pool(cassandra, Name, WpoolOpts).
-spec stop(mongooseim:host_type_or_global(), mongoose_wpool:tag()) -> ok.
stop(_, _) ->
ok.
Internal functions
prepare_cqerl_servers(#{servers := Servers}) ->
[cqerl_server(Server) || Server <- Servers].
cqerl_server(#{host := Host, port := Port}) -> {Host, Port};
cqerl_server(#{host := Host}) -> Host.
prepare_cqerl_opts(ConnOpts) ->
lists:flatmap(fun(Opt) -> cqerl_opts(Opt, ConnOpts) end, [keyspace, auth, tcp, tls]).
cqerl_opts(keyspace, #{keyspace := Keyspace}) ->
[{keyspace, Keyspace}];
cqerl_opts(auth, #{auth := #{plain := #{username := UserName, password := Password}}}) ->
[{auth, {cqerl_auth_plain_handler, [{UserName, Password}]}}];
cqerl_opts(tcp, #{}) ->
cqerl_opts(tls, #{tls := TLSOpts}) ->
[{ssl, just_tls:make_ssl_opts(TLSOpts)}];
cqerl_opts(_Opt, #{}) ->
[].
set_cluster_config(Tag, Servers, ExtConfig) ->
Clusters = application:get_env(cqerl, cassandra_clusters, []),
ClusterConfig = {Tag, {Servers, ExtConfig}},
NewClusters = lists:keystore(Tag, 1, Clusters, ClusterConfig),
application:set_env(cqerl, cassandra_clusters, NewClusters).
|
07dacaa1f8137b62491aa071f95b3eaf81a9b9df6d00a6c0d34a5182b44ce049 | tuura/centrifuge | Parser.hs | # LANGUAGE OverloadedStrings , TypeFamilies #
module Centrifuge.GraphML.Parser (parseGraphML) where
import qualified Data.ByteString as BS
import qualified Text.XML.Hexml as XML
import qualified Algebra.Graph.Class as C
import qualified Algebra.Graph.HigherKinded.Class as H
import qualified Algebra.Graph as G
import Data.List (partition)
| Parse GraphML file into a polymorphic graph expression
parseGraphML :: (C.Graph g, C.Vertex g ~ BS.ByteString) =>
BS.ByteString -> Either BS.ByteString g
parseGraphML input = do
-- retrieve xml root node
tree <- XML.parse input
dive two levels deeper , to the ' graph ' tag
graph <- extractGraphNode tree
-- partition graph's children into nodes ant the rest (edges)
let (rawVertices, rawEdges) =
partition (\x -> XML.name x == "node") . XML.children $ graph
turn xml entities into Haskell types
vertices <- traverse extractVertex rawVertices
edges <- traverse extractEdge rawEdges
-- construct the resulting graph
return $ C.overlay (C.vertices vertices) (C.edges edges)
where
extractGraphNode :: XML.Node -> Either BS.ByteString XML.Node
extractGraphNode root =
case XML.childrenBy root "graphml" of
[] -> Left "Invalid GraphML: no 'graphml' tag"
x:_ -> case XML.childrenBy x "graph" of
[] -> Left "Invalid GraphML: no 'graph' tag"
x:_ -> Right x
extractVertex :: XML.Node -> Either BS.ByteString BS.ByteString
extractVertex node =
case XML.attributeValue <$> XML.attributeBy node "id" of
Nothing -> Left "Invalid GraphML: a vertex doesn't have an 'id' \
\ attribute"
Just n -> Right n
extractEdge :: XML.Node ->
Either BS.ByteString (BS.ByteString, BS.ByteString)
extractEdge node =
case sequence . map (fmap XML.attributeValue . XML.attributeBy node) $
["source", "target"] of
Just [source, target] -> Right $ (source, target)
_ -> Left "Invalid GraphML: an edge doesn't have a 'source' or \
\'target' attribute"
| null | https://raw.githubusercontent.com/tuura/centrifuge/a89a1c9d6b60832d85dde6f0b747c7b5c54b91f5/src/Centrifuge/GraphML/Parser.hs | haskell | retrieve xml root node
partition graph's children into nodes ant the rest (edges)
construct the resulting graph | # LANGUAGE OverloadedStrings , TypeFamilies #
module Centrifuge.GraphML.Parser (parseGraphML) where
import qualified Data.ByteString as BS
import qualified Text.XML.Hexml as XML
import qualified Algebra.Graph.Class as C
import qualified Algebra.Graph.HigherKinded.Class as H
import qualified Algebra.Graph as G
import Data.List (partition)
| Parse GraphML file into a polymorphic graph expression
parseGraphML :: (C.Graph g, C.Vertex g ~ BS.ByteString) =>
BS.ByteString -> Either BS.ByteString g
parseGraphML input = do
tree <- XML.parse input
dive two levels deeper , to the ' graph ' tag
graph <- extractGraphNode tree
let (rawVertices, rawEdges) =
partition (\x -> XML.name x == "node") . XML.children $ graph
turn xml entities into Haskell types
vertices <- traverse extractVertex rawVertices
edges <- traverse extractEdge rawEdges
return $ C.overlay (C.vertices vertices) (C.edges edges)
where
extractGraphNode :: XML.Node -> Either BS.ByteString XML.Node
extractGraphNode root =
case XML.childrenBy root "graphml" of
[] -> Left "Invalid GraphML: no 'graphml' tag"
x:_ -> case XML.childrenBy x "graph" of
[] -> Left "Invalid GraphML: no 'graph' tag"
x:_ -> Right x
extractVertex :: XML.Node -> Either BS.ByteString BS.ByteString
extractVertex node =
case XML.attributeValue <$> XML.attributeBy node "id" of
Nothing -> Left "Invalid GraphML: a vertex doesn't have an 'id' \
\ attribute"
Just n -> Right n
extractEdge :: XML.Node ->
Either BS.ByteString (BS.ByteString, BS.ByteString)
extractEdge node =
case sequence . map (fmap XML.attributeValue . XML.attributeBy node) $
["source", "target"] of
Just [source, target] -> Right $ (source, target)
_ -> Left "Invalid GraphML: an edge doesn't have a 'source' or \
\'target' attribute"
|
855719f27c30c23632947191690dc2902f1f542fbb8feda9b59ed2c3fd5e2804 | input-output-hk/cardano-rt-view | Style.hs | module Cardano.RTView.GUI.CSS.Style
( ownCSS
) where
import Prelude hiding ((**))
import Clay
import qualified Clay.Media as M
import Clay.Selector (selectorFromText)
import Data.Text (pack, unpack)
import qualified Data.Text.Lazy as TL
import Cardano.RTView.GUI.Elements (HTMLClass (..))
ownCSS :: String
ownCSS = unpack . TL.toStrict . render $ do
importUrl "' Condensed'"
body ? do
fontFamily ["Roboto Condensed"] [sansSerif]
fontSizePx 20
backgroundColor whitesmoke
color "#1b2238"
h2 ? do
fontFamily ["Roboto Condensed"] [sansSerif]
fontSizePx 23
-- To avoid shifting "labels-values" on mobile screens (for Pane mode).
query M.screen [M.maxWidth (px 601)] $ ".w3-col.m6, .w3-half" ? widthPct 49.99
query M.screen [M.maxWidth (px 601)] $ ".w3-col.m4, .w3-third" ? widthPct 33.33
query M.screen [M.maxWidth (px 601)] $ ".w3-col.m8, .w3-twothird" ? widthPct 66.66
th ? do
important $
paddingPx 15
fontSizePct 110
td ? do
important $
paddingPx 15
a # link # hover ? do
color "#4b0082"
a # visited # hover ? do
color "#4b0082"
cl RequiredInput ? do
color red
fontWeight bold
paddingLeftPx 5
cl TopBar ? do
backgroundColor "#1b2238"
color whitesmoke
paddingTopPx 18
paddingBottomPx 15
cl TopBar ** cl W3DropdownHover ? do
paddingTopPx 10
fontSizePct 110
cl TopBar ** cl W3DropdownHover ** cl W3Button # hover ? do
important $
color cardanoLight
cl TopNavDropdownIcon ? do
widthPx 12
marginLeftPx 6
maxHeightPx 18
cl RTViewInfoIcon ? do
widthPx 25
paddingTopPx 9
cursor pointer
cl NotificationsIcon ? do
widthPx 23
paddingTopPx 9
marginLeftPx 4
cursor pointer
cl NotificationsIconSlash ? do
widthPx 31
paddingTopPx 9
cursor pointer
cl NotificationsEventsHeader ? do
fontSizePct 115
paddingBottomPx 8
cl NotificationsHR ? do
borderTop solid (px 2) "#ddd"
marginTopPx 17
marginBottomPx 10
cl NotificationsInput ? do
color "#444"
fontSizePct 98
cl NotificationsMainSwitch ? do
paddingTopPx 21
paddingBottomPx 17
cl NotificationsSwitch ? do
paddingTopPx 8
paddingBottomPx 8
cl NotificationsSwitches ? do
paddingLeftPx 13
cl NotificationsVSpacer ? do
paddingTopPx 22
cl RTViewInfoCopyPathIcon ? do
widthPx 12
marginLeftPx 10
marginBottomPx 4
cursor pointer
cl RTViewInfoClose ? do
widthPx 32
paddingRightPx 18
paddingTopPx 16
cursor pointer
cl RTViewInfoTop ? do
backgroundColor "#364679"
cl RTViewInfoContainer ? do
color black
fontSizePx 20
cl W3DropdownHover # hover |> cl W3Button # firstChild ? do
important $
color cardanoLight
important $
backgroundColor "#1b2238"
cl W3BarItem # hover ? do
important $
color cardanoLight
important $
backgroundColor "#1b2238"
cl W3DropdownContent ? do
important $
maxHeightPx 500
overflow auto
cl ServiceName ? do
fontSizePct 120
important $
color "#bcbcbc"
paddingTopPx 12
paddingRightPx 18
cl IdleNode ? do
fontWeight bold
color white
marginLeftPx 15
paddingTopPx 3
paddingBottomPx 1
paddingLeftPx 5
paddingRightPx 5
backgroundColor red
border solid (px 1) red
borderRadiusPx 8
cursor help
cl UnsupportedVersion ? do
color red
fontWeight bold
textDecorationLine underline
textDecorationStyle wavy
textDecorationColor red
cl NodeNameArea ? do
fontSizePct 110
paddingTopPx 10
paddingBottomPx 10
color "#555555"
cl NodeName ? do
fontWeight bold
color "#333333"
cl NodeBar ? do
important $
backgroundColor "#364679"
important $
color whitesmoke
cl NodeBar ** cl W3Button # hover ? do
important $
color cardanoLight
cl NotificationsBar ? do
important $
backgroundColor "#364679"
important $
color whitesmoke
fontSizePct 108
cl NotificationsBar ** cl W3Button # hover ? do
important $
color cardanoLight
cl ActiveTab ? do
important $
backgroundColor "#1b2238"
important $
color cardanoLight
fontWeight bold
cl TabContainer ? do
paddingTopPx 16
cl NotificationsTabContainer ? do
paddingTopPx 16
paddingBottomPx 16
color black
cl ErrorsSortIcon ? do
widthPx 15
marginLeftPx 10
maxHeightPx 19
cursor pointer
cl ErrorsFilterIcon ? do
widthPx 15
marginLeftPx 10
maxHeightPx 19
cl ErrorsFilterDropdownIcon ? do
widthPx 11
marginLeftPx 1
maxHeightPx 17
cl ErrorsDownloadIcon ? do
widthPx 15
marginLeftPx 10
maxHeightPx 17
cursor pointer
cl ErrorsRemoveIcon ? do
widthPx 15
maxHeightPx 19
cursor pointer
cl ErrorsBadge ? do
color white
backgroundColor red
fontSizePct 75
position absolute
marginLeftPx (-8)
marginTopPx (-7)
cl ErrorsTabHeader ? do
marginBottomPx 15
cl ErrorsTabList ? do
overflowY scroll
heightPx 260
cl ErrorRow ? do
marginBottomPx 10
cl ErrorTimestamp ? do
fontWeight bold
cl WarningMessage ? do
fontWeight normal
cl ErrorMessage ? do
fontWeight normal
cl CriticalMessage ? do
fontWeight normal
cl AlertMessage ? do
fontWeight normal
cl EmergencyMessage ? do
fontWeight normal
cl WarningMessageTag ? errorTag darkorange 2 2 help
cl ErrorMessageTag ? errorTag darkviolet 4 5 help
cl CriticalMessageTag ? errorTag deeppink 4 4 help
cl AlertMessageTag ? errorTag orangered 4 4 help
cl EmergencyMessageTag ? errorTag red 4 5 help
cl WarningMessageTagNoHelp ? errorTag darkorange 2 2 pointer
cl ErrorMessageTagNoHelp ? errorTag darkviolet 4 5 pointer
cl CriticalMessageTagNoHelp ? errorTag deeppink 4 4 pointer
cl AlertMessageTagNoHelp ? errorTag orangered 4 4 pointer
cl EmergencyMessageTagNoHelp ? errorTag red 4 5 pointer
cl NodeContainer ? do
minHeightPx 502
backgroundColor "#eeeeee"
cl NodeMenuIcon ? do
widthPx 26
cl ResourcesIcon ? do
widthPx 32
paddingRightPx 13
cl ResourcesDropdownIcon ? do
widthPx 15
marginLeftPx 3
maxHeightPx 19
cl ShowHideIcon ? do
widthPx 32
paddingRightPx 13
cl CardanoLogo ? do
widthPx 216
cl InfoMark ? do
paddingLeftPx 5
cursor help
cl InfoMarkImg ? do
maxWidthPx 18
cl DensityPercent ? do
fontWeight normal
cl ValueUnit ? do
color gray40
paddingLeftPx 5
cl ValueUnitPercent ? do
color gray40
cl TXsProcessed ? do
fontWeight bold
paddingLeftPx 16
cl BarValueUnit ? do
color whitesmoke
paddingLeftPx 5
cl CommitLink ? do
color "#4b0082"
cl HSpacer ? do
paddingLeftPx 10
cl PercentsSlashHSpacer ? do
paddingLeftPx 9
paddingRightPx 9
cl NodeInfoVSpacer ? do
paddingTopPx 18
cl NodeMetricsVSpacer ? do
paddingTopPx 15
cl NodeInfoValues ? do
fontWeight bold
cl NodeMetricsValues ? do
fontWeight bold
cl ChartArea ? do
important $
widthPct 100
cl SelectNodeCheckArea ? do
marginTopPx 8
marginBottomPx 8
marginLeftPx 16
cl SelectNodeCheck ? do
marginRightPx 10
cl SelectMetricCheckArea ? do
marginTopPx 8
marginBottomPx 8
marginLeftPx 16
marginRightPx 16
cl SelectMetricCheck ? do
marginRightPx 10
cl MetricsArea ? do
minWidthPx 300
cl ProgressBar ? progressBarColors greenDark white
cl ProgressBarBox ? progressBarColors greenLight white
cl SwitchContainer ? do
widthPx 68
cl Switch ? do
position relative
display inlineBlock
widthPx 52
heightPx 25
cl Switch ** input ? do
widthPx 0
heightPx 0
opacity 0
cl Slider ? do
position absolute
cursor pointer
topPx 0
leftPx 0
rightPx 0
bottomPx 0
backgroundColor "#ccc"
transition "" (sec 0.2) linear (sec 0)
cl Slider # before ? do
position absolute
content (stringContent "")
heightPx 18
widthPx 19
leftPx 4
bottomPx 4
backgroundColor white
transition "" (sec 0.2) linear (sec 0)
input # checked |+ cl Slider ? do
backgroundColor "#1fc1c3"
input # checked |+ cl Slider # before ? do
transform (translateX $ px 25)
cl Slider ? do
borderRadiusPx 34
cl Slider # before ? do
borderRadiusPct 50
cl TestEmailContainer ? do
marginTopPx 20
marginBottomPx 2
cl TestEmailButtonArea ? do
widthPx 120
cl TestEmailButton ? do
backgroundColor "#364679"
color whitesmoke
cl TestEmailDismiss ? do
cursor pointer
textDecoration underline
color "#364679"
fontSizePct 90
cl TestEmailResult ? do
marginTopPx 8
cl TestEmailResultSuccess ? do
color green
cl TestEmailResultError ? do
color red
cl AllTabsIcon ? do
widthPx 17
marginRightPx 13
marginBottomPx 3
cl SearchErrorArea ? do
marginBottomPx 19
marginTopPx 16
marginLeftPx (-4)
cl SearchErrorIcon ? do
widthPx 19
position absolute
marginTopPx 12
marginLeftPx 6
cl SearchErrorInput ? do
background transparent
fontSizePct 90
paddingLeftPx 33
maxWidthPct 50
position relative
zIndex 1
where
cardanoLight = rgb 31 193 195
gray40 = rgb 102 102 102
greenLight = rgb 108 202 108
greenDark = rgb 0 112 0
paddingPx v = padding (px v) (px v) (px v) (px v)
paddingTopPx = paddingTop . px
paddingBottomPx = paddingBottom . px
paddingLeftPx = paddingLeft . px
paddingRightPx = paddingRight . px
marginTopPx = marginTop . px
marginBottomPx = marginBottom . px
marginLeftPx = marginLeft . px
marginRightPx = marginRight . px
fontSizePx = fontSize . px
fontSizePct = fontSize . pct
heightPx = height . px
heightPct = height .
minHeightPx = minHeight . px
maxHeightPx = maxHeight . px
widthPx = width . px
widthPct = width . pct
minWidthPx = minWidth . px
maxWidthPx = maxWidth . px
maxWidthPct = maxWidth . pct
topPx = top . px
leftPx = left . px
rightPx = right . px
bottomPx = bottom . px
borderRadiusPx v = borderRadius (px v) (px v) (px v) (px v)
borderRadiusPct v = borderRadius (pct v) (pct v) (pct v) (pct v)
progressBarColors bg c = do
backgroundColor bg
important $ color c
errorTag aColor padLeft padRight cur = do
fontSizePct 85
color white
marginRightPx 15
paddingTopPx 2
paddingBottomPx 0
paddingLeftPx padLeft
paddingRightPx padRight
backgroundColor aColor
border solid (px 1) aColor
borderRadiusPx 4
cursor cur
-- | Convert class name as a constructor to 'Selector'.
cl :: HTMLClass -> Selector
cl className = selectorFromText $ "." <> pack (show className)
| null | https://raw.githubusercontent.com/input-output-hk/cardano-rt-view/0ff669a5acc8d81a35aa5a924cbb79978d0999a8/src/Cardano/RTView/GUI/CSS/Style.hs | haskell | To avoid shifting "labels-values" on mobile screens (for Pane mode).
| Convert class name as a constructor to 'Selector'. | module Cardano.RTView.GUI.CSS.Style
( ownCSS
) where
import Prelude hiding ((**))
import Clay
import qualified Clay.Media as M
import Clay.Selector (selectorFromText)
import Data.Text (pack, unpack)
import qualified Data.Text.Lazy as TL
import Cardano.RTView.GUI.Elements (HTMLClass (..))
ownCSS :: String
ownCSS = unpack . TL.toStrict . render $ do
importUrl "' Condensed'"
body ? do
fontFamily ["Roboto Condensed"] [sansSerif]
fontSizePx 20
backgroundColor whitesmoke
color "#1b2238"
h2 ? do
fontFamily ["Roboto Condensed"] [sansSerif]
fontSizePx 23
query M.screen [M.maxWidth (px 601)] $ ".w3-col.m6, .w3-half" ? widthPct 49.99
query M.screen [M.maxWidth (px 601)] $ ".w3-col.m4, .w3-third" ? widthPct 33.33
query M.screen [M.maxWidth (px 601)] $ ".w3-col.m8, .w3-twothird" ? widthPct 66.66
th ? do
important $
paddingPx 15
fontSizePct 110
td ? do
important $
paddingPx 15
a # link # hover ? do
color "#4b0082"
a # visited # hover ? do
color "#4b0082"
cl RequiredInput ? do
color red
fontWeight bold
paddingLeftPx 5
cl TopBar ? do
backgroundColor "#1b2238"
color whitesmoke
paddingTopPx 18
paddingBottomPx 15
cl TopBar ** cl W3DropdownHover ? do
paddingTopPx 10
fontSizePct 110
cl TopBar ** cl W3DropdownHover ** cl W3Button # hover ? do
important $
color cardanoLight
cl TopNavDropdownIcon ? do
widthPx 12
marginLeftPx 6
maxHeightPx 18
cl RTViewInfoIcon ? do
widthPx 25
paddingTopPx 9
cursor pointer
cl NotificationsIcon ? do
widthPx 23
paddingTopPx 9
marginLeftPx 4
cursor pointer
cl NotificationsIconSlash ? do
widthPx 31
paddingTopPx 9
cursor pointer
cl NotificationsEventsHeader ? do
fontSizePct 115
paddingBottomPx 8
cl NotificationsHR ? do
borderTop solid (px 2) "#ddd"
marginTopPx 17
marginBottomPx 10
cl NotificationsInput ? do
color "#444"
fontSizePct 98
cl NotificationsMainSwitch ? do
paddingTopPx 21
paddingBottomPx 17
cl NotificationsSwitch ? do
paddingTopPx 8
paddingBottomPx 8
cl NotificationsSwitches ? do
paddingLeftPx 13
cl NotificationsVSpacer ? do
paddingTopPx 22
cl RTViewInfoCopyPathIcon ? do
widthPx 12
marginLeftPx 10
marginBottomPx 4
cursor pointer
cl RTViewInfoClose ? do
widthPx 32
paddingRightPx 18
paddingTopPx 16
cursor pointer
cl RTViewInfoTop ? do
backgroundColor "#364679"
cl RTViewInfoContainer ? do
color black
fontSizePx 20
cl W3DropdownHover # hover |> cl W3Button # firstChild ? do
important $
color cardanoLight
important $
backgroundColor "#1b2238"
cl W3BarItem # hover ? do
important $
color cardanoLight
important $
backgroundColor "#1b2238"
cl W3DropdownContent ? do
important $
maxHeightPx 500
overflow auto
cl ServiceName ? do
fontSizePct 120
important $
color "#bcbcbc"
paddingTopPx 12
paddingRightPx 18
cl IdleNode ? do
fontWeight bold
color white
marginLeftPx 15
paddingTopPx 3
paddingBottomPx 1
paddingLeftPx 5
paddingRightPx 5
backgroundColor red
border solid (px 1) red
borderRadiusPx 8
cursor help
cl UnsupportedVersion ? do
color red
fontWeight bold
textDecorationLine underline
textDecorationStyle wavy
textDecorationColor red
cl NodeNameArea ? do
fontSizePct 110
paddingTopPx 10
paddingBottomPx 10
color "#555555"
cl NodeName ? do
fontWeight bold
color "#333333"
cl NodeBar ? do
important $
backgroundColor "#364679"
important $
color whitesmoke
cl NodeBar ** cl W3Button # hover ? do
important $
color cardanoLight
cl NotificationsBar ? do
important $
backgroundColor "#364679"
important $
color whitesmoke
fontSizePct 108
cl NotificationsBar ** cl W3Button # hover ? do
important $
color cardanoLight
cl ActiveTab ? do
important $
backgroundColor "#1b2238"
important $
color cardanoLight
fontWeight bold
cl TabContainer ? do
paddingTopPx 16
cl NotificationsTabContainer ? do
paddingTopPx 16
paddingBottomPx 16
color black
cl ErrorsSortIcon ? do
widthPx 15
marginLeftPx 10
maxHeightPx 19
cursor pointer
cl ErrorsFilterIcon ? do
widthPx 15
marginLeftPx 10
maxHeightPx 19
cl ErrorsFilterDropdownIcon ? do
widthPx 11
marginLeftPx 1
maxHeightPx 17
cl ErrorsDownloadIcon ? do
widthPx 15
marginLeftPx 10
maxHeightPx 17
cursor pointer
cl ErrorsRemoveIcon ? do
widthPx 15
maxHeightPx 19
cursor pointer
cl ErrorsBadge ? do
color white
backgroundColor red
fontSizePct 75
position absolute
marginLeftPx (-8)
marginTopPx (-7)
cl ErrorsTabHeader ? do
marginBottomPx 15
cl ErrorsTabList ? do
overflowY scroll
heightPx 260
cl ErrorRow ? do
marginBottomPx 10
cl ErrorTimestamp ? do
fontWeight bold
cl WarningMessage ? do
fontWeight normal
cl ErrorMessage ? do
fontWeight normal
cl CriticalMessage ? do
fontWeight normal
cl AlertMessage ? do
fontWeight normal
cl EmergencyMessage ? do
fontWeight normal
cl WarningMessageTag ? errorTag darkorange 2 2 help
cl ErrorMessageTag ? errorTag darkviolet 4 5 help
cl CriticalMessageTag ? errorTag deeppink 4 4 help
cl AlertMessageTag ? errorTag orangered 4 4 help
cl EmergencyMessageTag ? errorTag red 4 5 help
cl WarningMessageTagNoHelp ? errorTag darkorange 2 2 pointer
cl ErrorMessageTagNoHelp ? errorTag darkviolet 4 5 pointer
cl CriticalMessageTagNoHelp ? errorTag deeppink 4 4 pointer
cl AlertMessageTagNoHelp ? errorTag orangered 4 4 pointer
cl EmergencyMessageTagNoHelp ? errorTag red 4 5 pointer
cl NodeContainer ? do
minHeightPx 502
backgroundColor "#eeeeee"
cl NodeMenuIcon ? do
widthPx 26
cl ResourcesIcon ? do
widthPx 32
paddingRightPx 13
cl ResourcesDropdownIcon ? do
widthPx 15
marginLeftPx 3
maxHeightPx 19
cl ShowHideIcon ? do
widthPx 32
paddingRightPx 13
cl CardanoLogo ? do
widthPx 216
cl InfoMark ? do
paddingLeftPx 5
cursor help
cl InfoMarkImg ? do
maxWidthPx 18
cl DensityPercent ? do
fontWeight normal
cl ValueUnit ? do
color gray40
paddingLeftPx 5
cl ValueUnitPercent ? do
color gray40
cl TXsProcessed ? do
fontWeight bold
paddingLeftPx 16
cl BarValueUnit ? do
color whitesmoke
paddingLeftPx 5
cl CommitLink ? do
color "#4b0082"
cl HSpacer ? do
paddingLeftPx 10
cl PercentsSlashHSpacer ? do
paddingLeftPx 9
paddingRightPx 9
cl NodeInfoVSpacer ? do
paddingTopPx 18
cl NodeMetricsVSpacer ? do
paddingTopPx 15
cl NodeInfoValues ? do
fontWeight bold
cl NodeMetricsValues ? do
fontWeight bold
cl ChartArea ? do
important $
widthPct 100
cl SelectNodeCheckArea ? do
marginTopPx 8
marginBottomPx 8
marginLeftPx 16
cl SelectNodeCheck ? do
marginRightPx 10
cl SelectMetricCheckArea ? do
marginTopPx 8
marginBottomPx 8
marginLeftPx 16
marginRightPx 16
cl SelectMetricCheck ? do
marginRightPx 10
cl MetricsArea ? do
minWidthPx 300
cl ProgressBar ? progressBarColors greenDark white
cl ProgressBarBox ? progressBarColors greenLight white
cl SwitchContainer ? do
widthPx 68
cl Switch ? do
position relative
display inlineBlock
widthPx 52
heightPx 25
cl Switch ** input ? do
widthPx 0
heightPx 0
opacity 0
cl Slider ? do
position absolute
cursor pointer
topPx 0
leftPx 0
rightPx 0
bottomPx 0
backgroundColor "#ccc"
transition "" (sec 0.2) linear (sec 0)
cl Slider # before ? do
position absolute
content (stringContent "")
heightPx 18
widthPx 19
leftPx 4
bottomPx 4
backgroundColor white
transition "" (sec 0.2) linear (sec 0)
input # checked |+ cl Slider ? do
backgroundColor "#1fc1c3"
input # checked |+ cl Slider # before ? do
transform (translateX $ px 25)
cl Slider ? do
borderRadiusPx 34
cl Slider # before ? do
borderRadiusPct 50
cl TestEmailContainer ? do
marginTopPx 20
marginBottomPx 2
cl TestEmailButtonArea ? do
widthPx 120
cl TestEmailButton ? do
backgroundColor "#364679"
color whitesmoke
cl TestEmailDismiss ? do
cursor pointer
textDecoration underline
color "#364679"
fontSizePct 90
cl TestEmailResult ? do
marginTopPx 8
cl TestEmailResultSuccess ? do
color green
cl TestEmailResultError ? do
color red
cl AllTabsIcon ? do
widthPx 17
marginRightPx 13
marginBottomPx 3
cl SearchErrorArea ? do
marginBottomPx 19
marginTopPx 16
marginLeftPx (-4)
cl SearchErrorIcon ? do
widthPx 19
position absolute
marginTopPx 12
marginLeftPx 6
cl SearchErrorInput ? do
background transparent
fontSizePct 90
paddingLeftPx 33
maxWidthPct 50
position relative
zIndex 1
where
cardanoLight = rgb 31 193 195
gray40 = rgb 102 102 102
greenLight = rgb 108 202 108
greenDark = rgb 0 112 0
paddingPx v = padding (px v) (px v) (px v) (px v)
paddingTopPx = paddingTop . px
paddingBottomPx = paddingBottom . px
paddingLeftPx = paddingLeft . px
paddingRightPx = paddingRight . px
marginTopPx = marginTop . px
marginBottomPx = marginBottom . px
marginLeftPx = marginLeft . px
marginRightPx = marginRight . px
fontSizePx = fontSize . px
fontSizePct = fontSize . pct
heightPx = height . px
heightPct = height .
minHeightPx = minHeight . px
maxHeightPx = maxHeight . px
widthPx = width . px
widthPct = width . pct
minWidthPx = minWidth . px
maxWidthPx = maxWidth . px
maxWidthPct = maxWidth . pct
topPx = top . px
leftPx = left . px
rightPx = right . px
bottomPx = bottom . px
borderRadiusPx v = borderRadius (px v) (px v) (px v) (px v)
borderRadiusPct v = borderRadius (pct v) (pct v) (pct v) (pct v)
progressBarColors bg c = do
backgroundColor bg
important $ color c
errorTag aColor padLeft padRight cur = do
fontSizePct 85
color white
marginRightPx 15
paddingTopPx 2
paddingBottomPx 0
paddingLeftPx padLeft
paddingRightPx padRight
backgroundColor aColor
border solid (px 1) aColor
borderRadiusPx 4
cursor cur
cl :: HTMLClass -> Selector
cl className = selectorFromText $ "." <> pack (show className)
|
d9e677bfed683719d02c3cd2ac6649f0ba329096c6b598d8b6ba17440b2f258c | nervous-systems/fink-nottle | util.cljc | (ns fink-nottle.internal.util
(:require [clojure.walk :as walk]
[fink-nottle.internal.platform :as platform :refer [->int]]))
(defn attr-val-out [x]
(let [x (cond-> x (keyword? x) name)]
(cond
(string? x) [:string x]
(number? x) [:number (str x)]
(platform/byte-array? x) [:binary (platform/ba->b64-string x)]
:else (throw (ex-info "bad-attr-type"
{:type :bad-attr-type :value x})))))
(defn visit-values [x k->xform]
(if (map? x)
(into {}
(for [[k v] x]
(if-let [xform (k->xform k)]
[k (xform v)]
[k v])))
x))
(defn walk-values [form k->xform]
(walk/postwalk #(visit-values % k->xform) form))
(defn parse-numeric-keys [m ks]
(reduce
(fn [m k]
(if-let [v (m k)]
(assoc m k (->int v))
m))
m ks))
(def ->bool (partial = "true"))
| null | https://raw.githubusercontent.com/nervous-systems/fink-nottle/4fe25f2d89dc272e70b16742bca82455e3a43edb/src/fink_nottle/internal/util.cljc | clojure | (ns fink-nottle.internal.util
(:require [clojure.walk :as walk]
[fink-nottle.internal.platform :as platform :refer [->int]]))
(defn attr-val-out [x]
(let [x (cond-> x (keyword? x) name)]
(cond
(string? x) [:string x]
(number? x) [:number (str x)]
(platform/byte-array? x) [:binary (platform/ba->b64-string x)]
:else (throw (ex-info "bad-attr-type"
{:type :bad-attr-type :value x})))))
(defn visit-values [x k->xform]
(if (map? x)
(into {}
(for [[k v] x]
(if-let [xform (k->xform k)]
[k (xform v)]
[k v])))
x))
(defn walk-values [form k->xform]
(walk/postwalk #(visit-values % k->xform) form))
(defn parse-numeric-keys [m ks]
(reduce
(fn [m k]
(if-let [v (m k)]
(assoc m k (->int v))
m))
m ks))
(def ->bool (partial = "true"))
|
|
44b40b30b5ceaac106f8bee2160850665546b3ae853f030d8e19c3406e2c6374 | RunOrg/RunOrg | i.mli | (* © 2014 RunOrg *)
include Id.PHANTOM
module Assert : sig
val server_admin : 'a id -> [`ServerAdmin] id
val person : 'a id -> [`Person] id
end
| null | https://raw.githubusercontent.com/RunOrg/RunOrg/b53ee2357f4bcb919ac48577426d632dffc25062/server/tokenLib/i.mli | ocaml | © 2014 RunOrg |
include Id.PHANTOM
module Assert : sig
val server_admin : 'a id -> [`ServerAdmin] id
val person : 'a id -> [`Person] id
end
|
6fa4de7804b83997955541eef83a1c0a4e20c4599d7a22c837cdd3283062f012 | racket/racket7 | tethered-installer.rkt | #lang racket/base
(require setup/dirs
racket/file
compiler/embed
launcher)
(provide installer)
(define (installer path coll user? no-main?)
(unless (or user? no-main?)
(do-installer #f (find-config-tethered-console-bin-dir)))
(do-installer #t (find-addon-tethered-console-bin-dir)))
(define (do-installer user? dir)
(when dir
(make-directory* dir)
(define variants (available-racket-variants))
(for ([v (in-list variants)])
(parameterize ([current-launcher-variant v])
(create-embedding-executable
(racket-program-launcher-path "Racket" #:user? user? #:tethered? #t)
#:variant v
#:cmdline (append
(list "-X" (path->string (find-collects-dir))
"-G" (path->string (find-config-dir)))
(if user?
(list "-A" (path->string (find-system-path 'addon-dir)))
null))
#:launcher? #t
#:aux `((relative? . #f)))))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/racket/private/tethered-installer.rkt | racket | #lang racket/base
(require setup/dirs
racket/file
compiler/embed
launcher)
(provide installer)
(define (installer path coll user? no-main?)
(unless (or user? no-main?)
(do-installer #f (find-config-tethered-console-bin-dir)))
(do-installer #t (find-addon-tethered-console-bin-dir)))
(define (do-installer user? dir)
(when dir
(make-directory* dir)
(define variants (available-racket-variants))
(for ([v (in-list variants)])
(parameterize ([current-launcher-variant v])
(create-embedding-executable
(racket-program-launcher-path "Racket" #:user? user? #:tethered? #t)
#:variant v
#:cmdline (append
(list "-X" (path->string (find-collects-dir))
"-G" (path->string (find-config-dir)))
(if user?
(list "-A" (path->string (find-system-path 'addon-dir)))
null))
#:launcher? #t
#:aux `((relative? . #f)))))))
|
|
7dce8aff63cdbd0a55ca9d646c8d4c79b06349be402bc115c279c54e9332ece8 | AccelerateHS/accelerate | Complex.hs | {-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
{-# LANGUAGE MagicHash #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE PatternSynonyms #-}
# LANGUAGE RebindableSyntax #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - orphans #
-- |
-- Module : Data.Array.Accelerate.Data.Complex
Copyright : [ 2015 .. 2020 ] The Accelerate Team
-- License : BSD3
--
Maintainer : < >
-- Stability : experimental
Portability : non - portable ( GHC extensions )
--
-- Complex numbers, stored in the usual C-style array-of-struct representation,
-- for easy interoperability.
--
module Data.Array.Accelerate.Data.Complex (
-- * Rectangular from
Complex(..), pattern (::+),
real,
imag,
-- * Polar form
mkPolar,
cis,
polar,
magnitude, magnitude',
phase,
-- * Conjugate
conjugate,
) where
import Data.Array.Accelerate.Classes.Eq
import Data.Array.Accelerate.Classes.Floating
import Data.Array.Accelerate.Classes.Fractional
import Data.Array.Accelerate.Classes.FromIntegral
import Data.Array.Accelerate.Classes.Num
import Data.Array.Accelerate.Classes.Ord
import Data.Array.Accelerate.Classes.RealFloat
import Data.Array.Accelerate.Data.Functor
import Data.Array.Accelerate.Pattern
import Data.Array.Accelerate.Prelude
import Data.Array.Accelerate.Representation.Tag
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Representation.Vec
import Data.Array.Accelerate.Smart
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Vec
import Data.Array.Accelerate.Type
import Data.Primitive.Vec
import Data.Complex ( Complex(..) )
import Prelude ( ($) )
import qualified Data.Complex as C
import qualified Prelude as P
infix 6 ::+
pattern (::+) :: Elt a => Exp a -> Exp a -> Exp (Complex a)
pattern r ::+ i <- (deconstructComplex -> (r, i))
where (::+) = constructComplex
{-# COMPLETE (::+) #-}
-- Use an array-of-structs representation for complex numbers if possible.
-- This matches the standard C-style layout, but we can use this representation only at
-- specific types (not for any type 'a') as we can only have vectors of primitive type.
-- For other types, we use a structure-of-arrays representation. This is handled by the
ComplexR. We use the GADT ComplexR and function complexR to reconstruct
-- information on how the elements are represented.
--
instance Elt a => Elt (Complex a) where
type EltR (Complex a) = ComplexR (EltR a)
eltR = let tR = eltR @a
in case complexR tR of
ComplexVec s -> TupRsingle $ VectorScalarType $ VectorType 2 s
ComplexTup -> TupRunit `TupRpair` tR `TupRpair` tR
tagsR = let tR = eltR @a
in case complexR tR of
ComplexVec s -> [ TagRsingle (VectorScalarType (VectorType 2 s)) ]
ComplexTup -> let go :: TypeR t -> [TagR t]
go TupRunit = [TagRunit]
go (TupRsingle s) = [TagRsingle s]
go (TupRpair ta tb) = [TagRpair a b | a <- go ta, b <- go tb]
in
[ TagRunit `TagRpair` ta `TagRpair` tb | ta <- go tR, tb <- go tR ]
toElt = case complexR $ eltR @a of
ComplexVec _ -> \(Vec2 r i) -> toElt r :+ toElt i
ComplexTup -> \(((), r), i) -> toElt r :+ toElt i
fromElt (r :+ i) = case complexR $ eltR @a of
ComplexVec _ -> Vec2 (fromElt r) (fromElt i)
ComplexTup -> (((), fromElt r), fromElt i)
type family ComplexR a where
ComplexR Half = Vec2 Half
ComplexR Float = Vec2 Float
ComplexR Double = Vec2 Double
ComplexR Int = Vec2 Int
ComplexR Int8 = Vec2 Int8
ComplexR Int16 = Vec2 Int16
ComplexR Int32 = Vec2 Int32
ComplexR Int64 = Vec2 Int64
ComplexR Word = Vec2 Word
ComplexR Word8 = Vec2 Word8
ComplexR Word16 = Vec2 Word16
ComplexR Word32 = Vec2 Word32
ComplexR Word64 = Vec2 Word64
ComplexR a = (((), a), a)
-- This isn't ideal because we gather the evidence based on the
representation type , so we really get the evidence ( VecElt ( EltR a ) ) ,
-- which is not very useful...
- TLM 2020 - 07 - 16
data ComplexType a c where
ComplexVec :: VecElt a => SingleType a -> ComplexType a (Vec2 a)
ComplexTup :: ComplexType a (((), a), a)
complexR :: TypeR a -> ComplexType a (ComplexR a)
complexR = tuple
where
tuple :: TypeR a -> ComplexType a (ComplexR a)
tuple TupRunit = ComplexTup
tuple TupRpair{} = ComplexTup
tuple (TupRsingle s) = scalar s
scalar :: ScalarType a -> ComplexType a (ComplexR a)
scalar (SingleScalarType t) = single t
scalar VectorScalarType{} = ComplexTup
single :: SingleType a -> ComplexType a (ComplexR a)
single (NumSingleType t) = num t
num :: NumType a -> ComplexType a (ComplexR a)
num (IntegralNumType t) = integral t
num (FloatingNumType t) = floating t
integral :: IntegralType a -> ComplexType a (ComplexR a)
integral TypeInt = ComplexVec singleType
integral TypeInt8 = ComplexVec singleType
integral TypeInt16 = ComplexVec singleType
integral TypeInt32 = ComplexVec singleType
integral TypeInt64 = ComplexVec singleType
integral TypeWord = ComplexVec singleType
integral TypeWord8 = ComplexVec singleType
integral TypeWord16 = ComplexVec singleType
integral TypeWord32 = ComplexVec singleType
integral TypeWord64 = ComplexVec singleType
floating :: FloatingType a -> ComplexType a (ComplexR a)
floating TypeHalf = ComplexVec singleType
floating TypeFloat = ComplexVec singleType
floating TypeDouble = ComplexVec singleType
constructComplex :: forall a. Elt a => Exp a -> Exp a -> Exp (Complex a)
constructComplex r i =
case complexR (eltR @a) of
ComplexTup -> coerce $ T2 r i
ComplexVec _ -> V2 (coerce @a @(EltR a) r) (coerce @a @(EltR a) i)
deconstructComplex :: forall a. Elt a => Exp (Complex a) -> (Exp a, Exp a)
deconstructComplex c@(Exp c') =
case complexR (eltR @a) of
ComplexTup -> let T2 r i = coerce c in (r, i)
ComplexVec t -> let T2 r i = Exp (SmartExp (VecUnpack (VecRsucc (VecRsucc (VecRnil t))) c'))
in (r, i)
coerce :: EltR a ~ EltR b => Exp a -> Exp b
coerce (Exp e) = Exp e
instance (Lift Exp a, Elt (Plain a)) => Lift Exp (Complex a) where
type Plain (Complex a) = Complex (Plain a)
lift (r :+ i) = lift r ::+ lift i
instance Elt a => Unlift Exp (Complex (Exp a)) where
unlift (r ::+ i) = r :+ i
instance Eq a => Eq (Complex a) where
r1 ::+ c1 == r2 ::+ c2 = r1 == r2 && c1 == c2
r1 ::+ c1 /= r2 ::+ c2 = r1 /= r2 || c1 /= c2
instance RealFloat a => P.Num (Exp (Complex a)) where
(+) = lift2 ((+) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))
(-) = lift2 ((-) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))
(*) = lift2 ((*) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))
negate = lift1 (negate :: Complex (Exp a) -> Complex (Exp a))
signum z@(x ::+ y) =
if z == 0
then z
else let r = magnitude z
in x/r ::+ y/r
abs z = magnitude z ::+ 0
fromInteger n = fromInteger n ::+ 0
instance RealFloat a => P.Fractional (Exp (Complex a)) where
fromRational x = fromRational x ::+ 0
z / z' = (x*x''+y*y'') / d ::+ (y*x''-x*y'') / d
where
x :+ y = unlift z
x' :+ y' = unlift z'
--
x'' = scaleFloat k x'
y'' = scaleFloat k y'
k = - max (exponent x') (exponent y')
d = x'*x'' + y'*y''
instance RealFloat a => P.Floating (Exp (Complex a)) where
pi = pi ::+ 0
exp (x ::+ y) = let expx = exp x
in expx * cos y ::+ expx * sin y
log z = log (magnitude z) ::+ phase z
sqrt z@(x ::+ y) =
if z == 0
then 0
else u ::+ (y < 0 ? (-v, v))
where
T2 u v = x < 0 ? (T2 v' u', T2 u' v')
v' = abs y / (u'*2)
u' = sqrt ((magnitude z + abs x) / 2)
x ** y =
if y == 0 then 1 else
if x == 0 then if exp_r > 0 then 0 else
if exp_r < 0 then inf ::+ 0
else nan ::+ nan
else if isInfinite r || isInfinite i
then if exp_r > 0 then inf ::+ 0 else
if exp_r < 0 then 0
else nan ::+ nan
else exp (log x * y)
where
r ::+ i = x
exp_r ::+ _ = y
--
inf = 1 / 0
nan = 0 / 0
sin (x ::+ y) = sin x * cosh y ::+ cos x * sinh y
cos (x ::+ y) = cos x * cosh y ::+ (- sin x * sinh y)
tan (x ::+ y) = (sinx*coshy ::+ cosx*sinhy) / (cosx*coshy ::+ (-sinx*sinhy))
where
sinx = sin x
cosx = cos x
sinhy = sinh y
coshy = cosh y
sinh (x ::+ y) = cos y * sinh x ::+ sin y * cosh x
cosh (x ::+ y) = cos y * cosh x ::+ sin y * sinh x
tanh (x ::+ y) = (cosy*sinhx ::+ siny*coshx) / (cosy*coshx ::+ siny*sinhx)
where
siny = sin y
cosy = cos y
sinhx = sinh x
coshx = cosh x
asin z@(x ::+ y) = y' ::+ (-x')
where
x' ::+ y' = log (((-y) ::+ x) + sqrt (1 - z*z))
acos z = y'' ::+ (-x'')
where
x'' ::+ y'' = log (z + ((-y') ::+ x'))
x' ::+ y' = sqrt (1 - z*z)
atan z@(x ::+ y) = y' ::+ (-x')
where
x' ::+ y' = log (((1-y) ::+ x) / sqrt (1+z*z))
asinh z = log (z + sqrt (1+z*z))
acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
atanh z = 0.5 * log ((1.0+z) / (1.0-z))
instance (FromIntegral a b, Num b, Elt (Complex b)) => FromIntegral a (Complex b) where
fromIntegral x = fromIntegral x ::+ 0
| @since 1.2.0.0
--
instance Functor Complex where
fmap f (r ::+ i) = f r ::+ f i
-- | The non-negative magnitude of a complex number
--
magnitude :: RealFloat a => Exp (Complex a) -> Exp a
magnitude (r ::+ i) = scaleFloat k (sqrt (sqr (scaleFloat mk r) + sqr (scaleFloat mk i)))
where
k = max (exponent r) (exponent i)
mk = -k
sqr z = z * z
-- | As 'magnitude', but ignore floating point rounding and use the traditional
-- (simpler to evaluate) definition.
--
@since 1.3.0.0
--
magnitude' :: RealFloat a => Exp (Complex a) -> Exp a
magnitude' (r ::+ i) = sqrt (r*r + i*i)
-- | The phase of a complex number, in the range @(-'pi', 'pi']@. If the
magnitude is zero , then so is the phase .
--
phase :: RealFloat a => Exp (Complex a) -> Exp a
phase z@(r ::+ i) =
if z == 0
then 0
else atan2 i r
-- | The function 'polar' takes a complex number and returns a (magnitude,
-- phase) pair in canonical form: the magnitude is non-negative, and the phase
in the range @(-'pi ' , ' pi']@ ; if the magnitude is zero , then so is the phase .
--
polar :: RealFloat a => Exp (Complex a) -> Exp (a,a)
polar z = T2 (magnitude z) (phase z)
-- | Form a complex number from polar components of magnitude and phase.
--
mkPolar :: forall a. Floating a => Exp a -> Exp a -> Exp (Complex a)
mkPolar = lift2 (C.mkPolar :: Exp a -> Exp a -> Complex (Exp a))
-- | @'cis' t@ is a complex value with magnitude @1@ and phase @t@ (modulo
-- @2*'pi'@).
--
cis :: forall a. Floating a => Exp a -> Exp (Complex a)
cis = lift1 (C.cis :: Exp a -> Complex (Exp a))
-- | Return the real part of a complex number
--
real :: Elt a => Exp (Complex a) -> Exp a
real (r ::+ _) = r
-- | Return the imaginary part of a complex number
--
imag :: Elt a => Exp (Complex a) -> Exp a
imag (_ ::+ i) = i
-- | Return the complex conjugate of a complex number, defined as
--
-- > conjugate(Z) = X - iY
--
conjugate :: Num a => Exp (Complex a) -> Exp (Complex a)
conjugate z = real z ::+ (- imag z)
| null | https://raw.githubusercontent.com/AccelerateHS/accelerate/63e53be22aef32cd0b3b6f108e637716a92b72dc/src/Data/Array/Accelerate/Data/Complex.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE MagicHash #
# LANGUAGE PatternSynonyms #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeSynonymInstances #
|
Module : Data.Array.Accelerate.Data.Complex
License : BSD3
Stability : experimental
Complex numbers, stored in the usual C-style array-of-struct representation,
for easy interoperability.
* Rectangular from
* Polar form
* Conjugate
# COMPLETE (::+) #
Use an array-of-structs representation for complex numbers if possible.
This matches the standard C-style layout, but we can use this representation only at
specific types (not for any type 'a') as we can only have vectors of primitive type.
For other types, we use a structure-of-arrays representation. This is handled by the
information on how the elements are represented.
This isn't ideal because we gather the evidence based on the
which is not very useful...
| The non-negative magnitude of a complex number
| As 'magnitude', but ignore floating point rounding and use the traditional
(simpler to evaluate) definition.
| The phase of a complex number, in the range @(-'pi', 'pi']@. If the
| The function 'polar' takes a complex number and returns a (magnitude,
phase) pair in canonical form: the magnitude is non-negative, and the phase
| Form a complex number from polar components of magnitude and phase.
| @'cis' t@ is a complex value with magnitude @1@ and phase @t@ (modulo
@2*'pi'@).
| Return the real part of a complex number
| Return the imaginary part of a complex number
| Return the complex conjugate of a complex number, defined as
> conjugate(Z) = X - iY
| # LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE RebindableSyntax #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
# OPTIONS_GHC -fno - warn - orphans #
Copyright : [ 2015 .. 2020 ] The Accelerate Team
Maintainer : < >
Portability : non - portable ( GHC extensions )
module Data.Array.Accelerate.Data.Complex (
Complex(..), pattern (::+),
real,
imag,
mkPolar,
cis,
polar,
magnitude, magnitude',
phase,
conjugate,
) where
import Data.Array.Accelerate.Classes.Eq
import Data.Array.Accelerate.Classes.Floating
import Data.Array.Accelerate.Classes.Fractional
import Data.Array.Accelerate.Classes.FromIntegral
import Data.Array.Accelerate.Classes.Num
import Data.Array.Accelerate.Classes.Ord
import Data.Array.Accelerate.Classes.RealFloat
import Data.Array.Accelerate.Data.Functor
import Data.Array.Accelerate.Pattern
import Data.Array.Accelerate.Prelude
import Data.Array.Accelerate.Representation.Tag
import Data.Array.Accelerate.Representation.Type
import Data.Array.Accelerate.Representation.Vec
import Data.Array.Accelerate.Smart
import Data.Array.Accelerate.Sugar.Elt
import Data.Array.Accelerate.Sugar.Vec
import Data.Array.Accelerate.Type
import Data.Primitive.Vec
import Data.Complex ( Complex(..) )
import Prelude ( ($) )
import qualified Data.Complex as C
import qualified Prelude as P
infix 6 ::+
pattern (::+) :: Elt a => Exp a -> Exp a -> Exp (Complex a)
pattern r ::+ i <- (deconstructComplex -> (r, i))
where (::+) = constructComplex
ComplexR. We use the GADT ComplexR and function complexR to reconstruct
instance Elt a => Elt (Complex a) where
type EltR (Complex a) = ComplexR (EltR a)
eltR = let tR = eltR @a
in case complexR tR of
ComplexVec s -> TupRsingle $ VectorScalarType $ VectorType 2 s
ComplexTup -> TupRunit `TupRpair` tR `TupRpair` tR
tagsR = let tR = eltR @a
in case complexR tR of
ComplexVec s -> [ TagRsingle (VectorScalarType (VectorType 2 s)) ]
ComplexTup -> let go :: TypeR t -> [TagR t]
go TupRunit = [TagRunit]
go (TupRsingle s) = [TagRsingle s]
go (TupRpair ta tb) = [TagRpair a b | a <- go ta, b <- go tb]
in
[ TagRunit `TagRpair` ta `TagRpair` tb | ta <- go tR, tb <- go tR ]
toElt = case complexR $ eltR @a of
ComplexVec _ -> \(Vec2 r i) -> toElt r :+ toElt i
ComplexTup -> \(((), r), i) -> toElt r :+ toElt i
fromElt (r :+ i) = case complexR $ eltR @a of
ComplexVec _ -> Vec2 (fromElt r) (fromElt i)
ComplexTup -> (((), fromElt r), fromElt i)
type family ComplexR a where
ComplexR Half = Vec2 Half
ComplexR Float = Vec2 Float
ComplexR Double = Vec2 Double
ComplexR Int = Vec2 Int
ComplexR Int8 = Vec2 Int8
ComplexR Int16 = Vec2 Int16
ComplexR Int32 = Vec2 Int32
ComplexR Int64 = Vec2 Int64
ComplexR Word = Vec2 Word
ComplexR Word8 = Vec2 Word8
ComplexR Word16 = Vec2 Word16
ComplexR Word32 = Vec2 Word32
ComplexR Word64 = Vec2 Word64
ComplexR a = (((), a), a)
representation type , so we really get the evidence ( VecElt ( EltR a ) ) ,
- TLM 2020 - 07 - 16
data ComplexType a c where
ComplexVec :: VecElt a => SingleType a -> ComplexType a (Vec2 a)
ComplexTup :: ComplexType a (((), a), a)
complexR :: TypeR a -> ComplexType a (ComplexR a)
complexR = tuple
where
tuple :: TypeR a -> ComplexType a (ComplexR a)
tuple TupRunit = ComplexTup
tuple TupRpair{} = ComplexTup
tuple (TupRsingle s) = scalar s
scalar :: ScalarType a -> ComplexType a (ComplexR a)
scalar (SingleScalarType t) = single t
scalar VectorScalarType{} = ComplexTup
single :: SingleType a -> ComplexType a (ComplexR a)
single (NumSingleType t) = num t
num :: NumType a -> ComplexType a (ComplexR a)
num (IntegralNumType t) = integral t
num (FloatingNumType t) = floating t
integral :: IntegralType a -> ComplexType a (ComplexR a)
integral TypeInt = ComplexVec singleType
integral TypeInt8 = ComplexVec singleType
integral TypeInt16 = ComplexVec singleType
integral TypeInt32 = ComplexVec singleType
integral TypeInt64 = ComplexVec singleType
integral TypeWord = ComplexVec singleType
integral TypeWord8 = ComplexVec singleType
integral TypeWord16 = ComplexVec singleType
integral TypeWord32 = ComplexVec singleType
integral TypeWord64 = ComplexVec singleType
floating :: FloatingType a -> ComplexType a (ComplexR a)
floating TypeHalf = ComplexVec singleType
floating TypeFloat = ComplexVec singleType
floating TypeDouble = ComplexVec singleType
constructComplex :: forall a. Elt a => Exp a -> Exp a -> Exp (Complex a)
constructComplex r i =
case complexR (eltR @a) of
ComplexTup -> coerce $ T2 r i
ComplexVec _ -> V2 (coerce @a @(EltR a) r) (coerce @a @(EltR a) i)
deconstructComplex :: forall a. Elt a => Exp (Complex a) -> (Exp a, Exp a)
deconstructComplex c@(Exp c') =
case complexR (eltR @a) of
ComplexTup -> let T2 r i = coerce c in (r, i)
ComplexVec t -> let T2 r i = Exp (SmartExp (VecUnpack (VecRsucc (VecRsucc (VecRnil t))) c'))
in (r, i)
coerce :: EltR a ~ EltR b => Exp a -> Exp b
coerce (Exp e) = Exp e
instance (Lift Exp a, Elt (Plain a)) => Lift Exp (Complex a) where
type Plain (Complex a) = Complex (Plain a)
lift (r :+ i) = lift r ::+ lift i
instance Elt a => Unlift Exp (Complex (Exp a)) where
unlift (r ::+ i) = r :+ i
instance Eq a => Eq (Complex a) where
r1 ::+ c1 == r2 ::+ c2 = r1 == r2 && c1 == c2
r1 ::+ c1 /= r2 ::+ c2 = r1 /= r2 || c1 /= c2
instance RealFloat a => P.Num (Exp (Complex a)) where
(+) = lift2 ((+) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))
(-) = lift2 ((-) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))
(*) = lift2 ((*) :: Complex (Exp a) -> Complex (Exp a) -> Complex (Exp a))
negate = lift1 (negate :: Complex (Exp a) -> Complex (Exp a))
signum z@(x ::+ y) =
if z == 0
then z
else let r = magnitude z
in x/r ::+ y/r
abs z = magnitude z ::+ 0
fromInteger n = fromInteger n ::+ 0
instance RealFloat a => P.Fractional (Exp (Complex a)) where
fromRational x = fromRational x ::+ 0
z / z' = (x*x''+y*y'') / d ::+ (y*x''-x*y'') / d
where
x :+ y = unlift z
x' :+ y' = unlift z'
x'' = scaleFloat k x'
y'' = scaleFloat k y'
k = - max (exponent x') (exponent y')
d = x'*x'' + y'*y''
instance RealFloat a => P.Floating (Exp (Complex a)) where
pi = pi ::+ 0
exp (x ::+ y) = let expx = exp x
in expx * cos y ::+ expx * sin y
log z = log (magnitude z) ::+ phase z
sqrt z@(x ::+ y) =
if z == 0
then 0
else u ::+ (y < 0 ? (-v, v))
where
T2 u v = x < 0 ? (T2 v' u', T2 u' v')
v' = abs y / (u'*2)
u' = sqrt ((magnitude z + abs x) / 2)
x ** y =
if y == 0 then 1 else
if x == 0 then if exp_r > 0 then 0 else
if exp_r < 0 then inf ::+ 0
else nan ::+ nan
else if isInfinite r || isInfinite i
then if exp_r > 0 then inf ::+ 0 else
if exp_r < 0 then 0
else nan ::+ nan
else exp (log x * y)
where
r ::+ i = x
exp_r ::+ _ = y
inf = 1 / 0
nan = 0 / 0
sin (x ::+ y) = sin x * cosh y ::+ cos x * sinh y
cos (x ::+ y) = cos x * cosh y ::+ (- sin x * sinh y)
tan (x ::+ y) = (sinx*coshy ::+ cosx*sinhy) / (cosx*coshy ::+ (-sinx*sinhy))
where
sinx = sin x
cosx = cos x
sinhy = sinh y
coshy = cosh y
sinh (x ::+ y) = cos y * sinh x ::+ sin y * cosh x
cosh (x ::+ y) = cos y * cosh x ::+ sin y * sinh x
tanh (x ::+ y) = (cosy*sinhx ::+ siny*coshx) / (cosy*coshx ::+ siny*sinhx)
where
siny = sin y
cosy = cos y
sinhx = sinh x
coshx = cosh x
asin z@(x ::+ y) = y' ::+ (-x')
where
x' ::+ y' = log (((-y) ::+ x) + sqrt (1 - z*z))
acos z = y'' ::+ (-x'')
where
x'' ::+ y'' = log (z + ((-y') ::+ x'))
x' ::+ y' = sqrt (1 - z*z)
atan z@(x ::+ y) = y' ::+ (-x')
where
x' ::+ y' = log (((1-y) ::+ x) / sqrt (1+z*z))
asinh z = log (z + sqrt (1+z*z))
acosh z = log (z + (z+1) * sqrt ((z-1)/(z+1)))
atanh z = 0.5 * log ((1.0+z) / (1.0-z))
instance (FromIntegral a b, Num b, Elt (Complex b)) => FromIntegral a (Complex b) where
fromIntegral x = fromIntegral x ::+ 0
| @since 1.2.0.0
instance Functor Complex where
fmap f (r ::+ i) = f r ::+ f i
magnitude :: RealFloat a => Exp (Complex a) -> Exp a
magnitude (r ::+ i) = scaleFloat k (sqrt (sqr (scaleFloat mk r) + sqr (scaleFloat mk i)))
where
k = max (exponent r) (exponent i)
mk = -k
sqr z = z * z
@since 1.3.0.0
magnitude' :: RealFloat a => Exp (Complex a) -> Exp a
magnitude' (r ::+ i) = sqrt (r*r + i*i)
magnitude is zero , then so is the phase .
phase :: RealFloat a => Exp (Complex a) -> Exp a
phase z@(r ::+ i) =
if z == 0
then 0
else atan2 i r
in the range @(-'pi ' , ' pi']@ ; if the magnitude is zero , then so is the phase .
polar :: RealFloat a => Exp (Complex a) -> Exp (a,a)
polar z = T2 (magnitude z) (phase z)
mkPolar :: forall a. Floating a => Exp a -> Exp a -> Exp (Complex a)
mkPolar = lift2 (C.mkPolar :: Exp a -> Exp a -> Complex (Exp a))
cis :: forall a. Floating a => Exp a -> Exp (Complex a)
cis = lift1 (C.cis :: Exp a -> Complex (Exp a))
real :: Elt a => Exp (Complex a) -> Exp a
real (r ::+ _) = r
imag :: Elt a => Exp (Complex a) -> Exp a
imag (_ ::+ i) = i
conjugate :: Num a => Exp (Complex a) -> Exp (Complex a)
conjugate z = real z ::+ (- imag z)
|
e1cbc808a93d39f795c2e4fba28b2490288f7085f6db84553cee9606add4e6fe | cram2/cram | vector-mean.lisp | Regression test VECTOR - MEAN for GSLL , automatically generated
;;
Copyright 2009 , 2011
Distributed under the terms of the GNU General Public License
;;
;; This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
You should have received a copy of the GNU General Public License
;; along with this program. If not, see </>.
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST VECTOR-MEAN
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 3.9812498688697815d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'SINGLE-FLOAT :INITIAL-CONTENTS
'(-34.5f0 8.24f0 3.29f0 -8.93f0 34.12f0 -6.15f0 49.27f0 -13.49f0))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 3.98125d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'DOUBLE-FLOAT
:INITIAL-CONTENTS
'(-34.5d0 8.24d0 3.29d0 -8.93d0 34.12d0 -6.15d0 49.27d0 -13.49d0))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 8)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 8)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 16)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 16)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 32)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 32)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 64)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 64)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1)))))
| null | https://raw.githubusercontent.com/cram2/cram/dcb73031ee944d04215bbff9e98b9e8c210ef6c5/cram_3rdparty/gsll/src/tests/vector-mean.lisp | lisp |
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program. If not, see </>. | Regression test VECTOR - MEAN for GSLL , automatically generated
Copyright 2009 , 2011
Distributed under the terms of the GNU General Public License
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
(in-package :gsl)
(LISP-UNIT:DEFINE-TEST VECTOR-MEAN
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 3.9812498688697815d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'SINGLE-FLOAT :INITIAL-CONTENTS
'(-34.5f0 8.24f0 3.29f0 -8.93f0 34.12f0 -6.15f0 49.27f0 -13.49f0))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 3.98125d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'DOUBLE-FLOAT
:INITIAL-CONTENTS
'(-34.5d0 8.24d0 3.29d0 -8.93d0 34.12d0 -6.15d0 49.27d0 -13.49d0))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 8)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 8)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 16)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 16)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL
(LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 32)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 32)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST -5.25d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(SIGNED-BYTE 64)
:INITIAL-CONTENTS
'(-64 -68 71 -91 52 -10 73 -5))))
(MEAN V1))))
#+int64
(LISP-UNIT::ASSERT-NUMERICAL-EQUAL (LIST 136.875d0)
(MULTIPLE-VALUE-LIST
(LET ((V1
(GRID:MAKE-FOREIGN-ARRAY
'(UNSIGNED-BYTE 64)
:INITIAL-CONTENTS
'(67 44 189 116 163 140 161 215))))
(MEAN V1)))))
|
6921b00db134a5d1b8426583995baad211b4bbadd62fffb2bc237b1f6347d219 | boris-ci/boris | Schema.hs | # LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
module Test.IO.Boris.Http.Db.Schema where
import Control.Monad.Morph (hoist, lift)
import qualified Boris.Http.Db.Schema as Schema
import Boris.Prelude
import Hedgehog
import System.IO (IO)
import Test.IO.Boris.Http.Db.Test
prop_schema :: Property
prop_schema =
property $ do
pool <- mkPool
evalExceptT . hoist lift $ Schema.initialise pool
tests :: IO Bool
tests =
checkDb $$(discover)
| null | https://raw.githubusercontent.com/boris-ci/boris/c321187490afc889bf281442ac4ef9398b77b200/boris-http/test/Test/IO/Boris/Http/Db/Schema.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE NoImplicitPrelude #
# LANGUAGE TemplateHaskell #
module Test.IO.Boris.Http.Db.Schema where
import Control.Monad.Morph (hoist, lift)
import qualified Boris.Http.Db.Schema as Schema
import Boris.Prelude
import Hedgehog
import System.IO (IO)
import Test.IO.Boris.Http.Db.Test
prop_schema :: Property
prop_schema =
property $ do
pool <- mkPool
evalExceptT . hoist lift $ Schema.initialise pool
tests :: IO Bool
tests =
checkDb $$(discover)
|
c3471ae4033805e98dfa4e5864b5b8daa38334fcbdfe13eac84dacbf2f2e369a | grin-compiler/grin | BinaryIR.hs | # LANGUAGE LambdaCase , RecordWildCards , Strict #
module AbstractInterpretation.BinaryIR (encodeAbstractProgram) where
import Control.Monad.State
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString.Builder
import AbstractInterpretation.IR
data Env
= Env
{ envTagMap :: Map (Set Tag) Int32
, envBlockCount :: !Int
, envBuilder :: !Builder
, envBuilderMap :: Map Int (Int, Builder) -- block size, data
, envInstCount :: !Int
}
emptyEnv = Env
{ envTagMap = mempty
, envBlockCount = 0
, envBuilder = mempty
, envBuilderMap = mempty
, envInstCount = 0
}
type W = State Env
emit :: Builder -> W ()
emit b = modify' $ \env@Env{..} -> env {envBuilder = envBuilder <> b}
writeI32 :: Int32 -> W ()
writeI32 i = emit $ int32LE i
writeW32 :: Word32 -> W ()
writeW32 w = emit $ word32LE w
writeReg :: Reg -> W ()
writeReg (Reg r) = writeW32 r
writeMem :: Mem -> W ()
writeMem (Mem m) = writeW32 m
writeTagSet :: Set Tag -> W ()
writeTagSet s = do
tm <- gets envTagMap
let size = fromIntegral $ Map.size tm
case Map.lookup s tm of
Just idx -> writeI32 idx
Nothing -> do
modify' $ \env@Env{..} -> env {envTagMap = Map.insert s size envTagMap}
writeI32 size
writeBlock :: [Instruction] -> W ()
writeBlock il = do
let size = length il
blockIndex <- gets envBlockCount
modify' $ \env@Env{..} -> env {envInstCount = envInstCount + size, envBlockCount = succ blockIndex}
writeI32 $ fromIntegral blockIndex
savedBuilder <- gets envBuilder
modify' $ \env@Env{..} -> env {envBuilder = mempty}
mapM_ writeInstruction il
blockBuilder <- gets envBuilder
modify' $ \env@Env{..} -> env {envBuilder = savedBuilder, envBuilderMap = Map.insert blockIndex (size, blockBuilder) envBuilderMap}
-----------------------------------
writeRange :: Range -> W ()
writeRange Range{..} = do
writeI32 from
writeI32 to
writeType :: Int32 -> W ()
writeType = writeI32
writeTag :: Tag -> W ()
writeTag (Tag w) = writeW32 w
writePredicate :: Predicate -> W ()
writePredicate = \case
TagIn s -> do
writeType 100
writeTagSet s
TagNotIn s -> do
writeType 101
writeTagSet s
ValueIn r -> do
writeType 102
writeRange r
ValueNotIn r -> do
writeType 103
writeRange r
writeCondition :: Condition -> W ()
writeCondition = \case
NodeTypeExists t -> do
writeType 200
writeTag t
SimpleTypeExists st -> do
writeType 201
writeI32 st
AnyNotIn s -> do
writeType 202
writeTagSet s
Any p -> do
writeType 203
writePredicate p
writeSelector :: Selector -> W ()
writeSelector = \case
NodeItem t i -> do
writeType 300
writeTag t
writeI32 $ fromIntegral i
ConditionAsSelector c -> do
writeType 301
writeCondition c
AllFields -> do
writeType 302
writeConstant :: Constant -> W ()
writeConstant = \case
CSimpleType st -> do
writeType 400
writeI32 st
CHeapLocation m -> do
writeType 401
writeMem m
CNodeType t a -> do
writeType 402
writeTag t
writeI32 $ fromIntegral a
CNodeItem t i v -> do
writeType 403
writeTag t
writeI32 $ fromIntegral i
writeI32 v
writeInstruction :: Instruction -> W ()
writeInstruction = \case
If {..} -> do
writeType 500
writeCondition condition
writeReg srcReg
writeBlock instructions
Project {..} -> do
writeType 501
writeSelector srcSelector
writeReg srcReg
writeReg dstReg
Extend {..} -> do
writeType 502
writeReg srcReg
writeSelector dstSelector
writeReg dstReg
Move {..} -> do
writeType 503
writeReg srcReg
writeReg dstReg
RestrictedMove {..} -> do
writeType 504
writeReg srcReg
writeReg dstReg
ConditionalMove {..} -> do
writeType 505
writeReg srcReg
writePredicate predicate
writeReg dstReg
Fetch {..} -> do
writeType 506
writeReg addressReg
writeReg dstReg
Store {..} -> do
writeType 507
writeReg srcReg
writeMem address
Update {..} -> do
writeType 508
writeReg srcReg
writeReg addressReg
RestrictedUpdate {..} -> do
writeType 509
writeReg srcReg
writeReg addressReg
ConditionalUpdate {..} -> do
writeType 510
writeReg srcReg
writePredicate predicate
writeReg addressReg
Set {..} -> do
writeType 511
writeReg dstReg
writeConstant constant
memory count i32
register count i32
start block i d i32
cmd count i32
cmds ...
block count i32
blocks ( ranges ) ...
intset count i32
set size i32
set elems ... [ i32 ]
memory count i32
register count i32
start block id i32
cmd count i32
cmds ...
block count i32
blocks (ranges) ...
intset count i32
set size i32
set elems ... [i32]
-}
writeBlockItem :: Int32 -> Int -> W Int32
writeBlockItem offset size = do
let nextOffset = offset + fromIntegral size
writeI32 $ offset
writeI32 $ nextOffset
pure nextOffset
encodeAbstractProgram :: AbstractProgram -> LBS.ByteString
encodeAbstractProgram AbstractProgram {..} = toLazyByteString (envBuilder env) where
env = flip execState emptyEnv $ do
writeW32 _absMemoryCounter
writeW32 _absRegisterCounter
-- start block id
writeBlock _absInstructions
-- commands
cmdCount <- gets envInstCount
writeI32 $ fromIntegral cmdCount
(blockSizes, blocks) <- gets $ unzip . Map.elems . envBuilderMap
mapM emit blocks
bocks
blkCount <- gets envBlockCount
writeI32 $ fromIntegral blkCount
foldM_ writeBlockItem 0 blockSizes
-- intsets
setCount < - gets envTagSetCount
writeI32 $ fromIntegral setCount
sets < - gets envTagSets
setCount <- gets envTagSetCount
writeI32 $ fromIntegral setCount
sets <- gets envTagSets
-}
tagMap <- gets envTagMap
writeI32 $ fromIntegral $ Map.size tagMap
let sets = Map.elems $ Map.fromList [(i, s) | (s, i) <- Map.toList tagMap]
forM_ sets $ \s -> do
writeI32 $ fromIntegral $ Set.size s
forM_ (Set.toList s) (\(Tag t) -> writeI32 $ fromIntegral t)
| null | https://raw.githubusercontent.com/grin-compiler/grin/44ac2958810ecee969c8028d2d2a082d47fba51b/grin/src/AbstractInterpretation/BinaryIR.hs | haskell | block size, data
---------------------------------
start block id
commands
intsets | # LANGUAGE LambdaCase , RecordWildCards , Strict #
module AbstractInterpretation.BinaryIR (encodeAbstractProgram) where
import Control.Monad.State
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.ByteString.Lazy as LBS
import Data.ByteString.Builder
import AbstractInterpretation.IR
data Env
= Env
{ envTagMap :: Map (Set Tag) Int32
, envBlockCount :: !Int
, envBuilder :: !Builder
, envInstCount :: !Int
}
emptyEnv = Env
{ envTagMap = mempty
, envBlockCount = 0
, envBuilder = mempty
, envBuilderMap = mempty
, envInstCount = 0
}
type W = State Env
emit :: Builder -> W ()
emit b = modify' $ \env@Env{..} -> env {envBuilder = envBuilder <> b}
writeI32 :: Int32 -> W ()
writeI32 i = emit $ int32LE i
writeW32 :: Word32 -> W ()
writeW32 w = emit $ word32LE w
writeReg :: Reg -> W ()
writeReg (Reg r) = writeW32 r
writeMem :: Mem -> W ()
writeMem (Mem m) = writeW32 m
writeTagSet :: Set Tag -> W ()
writeTagSet s = do
tm <- gets envTagMap
let size = fromIntegral $ Map.size tm
case Map.lookup s tm of
Just idx -> writeI32 idx
Nothing -> do
modify' $ \env@Env{..} -> env {envTagMap = Map.insert s size envTagMap}
writeI32 size
writeBlock :: [Instruction] -> W ()
writeBlock il = do
let size = length il
blockIndex <- gets envBlockCount
modify' $ \env@Env{..} -> env {envInstCount = envInstCount + size, envBlockCount = succ blockIndex}
writeI32 $ fromIntegral blockIndex
savedBuilder <- gets envBuilder
modify' $ \env@Env{..} -> env {envBuilder = mempty}
mapM_ writeInstruction il
blockBuilder <- gets envBuilder
modify' $ \env@Env{..} -> env {envBuilder = savedBuilder, envBuilderMap = Map.insert blockIndex (size, blockBuilder) envBuilderMap}
writeRange :: Range -> W ()
writeRange Range{..} = do
writeI32 from
writeI32 to
writeType :: Int32 -> W ()
writeType = writeI32
writeTag :: Tag -> W ()
writeTag (Tag w) = writeW32 w
writePredicate :: Predicate -> W ()
writePredicate = \case
TagIn s -> do
writeType 100
writeTagSet s
TagNotIn s -> do
writeType 101
writeTagSet s
ValueIn r -> do
writeType 102
writeRange r
ValueNotIn r -> do
writeType 103
writeRange r
writeCondition :: Condition -> W ()
writeCondition = \case
NodeTypeExists t -> do
writeType 200
writeTag t
SimpleTypeExists st -> do
writeType 201
writeI32 st
AnyNotIn s -> do
writeType 202
writeTagSet s
Any p -> do
writeType 203
writePredicate p
writeSelector :: Selector -> W ()
writeSelector = \case
NodeItem t i -> do
writeType 300
writeTag t
writeI32 $ fromIntegral i
ConditionAsSelector c -> do
writeType 301
writeCondition c
AllFields -> do
writeType 302
writeConstant :: Constant -> W ()
writeConstant = \case
CSimpleType st -> do
writeType 400
writeI32 st
CHeapLocation m -> do
writeType 401
writeMem m
CNodeType t a -> do
writeType 402
writeTag t
writeI32 $ fromIntegral a
CNodeItem t i v -> do
writeType 403
writeTag t
writeI32 $ fromIntegral i
writeI32 v
writeInstruction :: Instruction -> W ()
writeInstruction = \case
If {..} -> do
writeType 500
writeCondition condition
writeReg srcReg
writeBlock instructions
Project {..} -> do
writeType 501
writeSelector srcSelector
writeReg srcReg
writeReg dstReg
Extend {..} -> do
writeType 502
writeReg srcReg
writeSelector dstSelector
writeReg dstReg
Move {..} -> do
writeType 503
writeReg srcReg
writeReg dstReg
RestrictedMove {..} -> do
writeType 504
writeReg srcReg
writeReg dstReg
ConditionalMove {..} -> do
writeType 505
writeReg srcReg
writePredicate predicate
writeReg dstReg
Fetch {..} -> do
writeType 506
writeReg addressReg
writeReg dstReg
Store {..} -> do
writeType 507
writeReg srcReg
writeMem address
Update {..} -> do
writeType 508
writeReg srcReg
writeReg addressReg
RestrictedUpdate {..} -> do
writeType 509
writeReg srcReg
writeReg addressReg
ConditionalUpdate {..} -> do
writeType 510
writeReg srcReg
writePredicate predicate
writeReg addressReg
Set {..} -> do
writeType 511
writeReg dstReg
writeConstant constant
memory count i32
register count i32
start block i d i32
cmd count i32
cmds ...
block count i32
blocks ( ranges ) ...
intset count i32
set size i32
set elems ... [ i32 ]
memory count i32
register count i32
start block id i32
cmd count i32
cmds ...
block count i32
blocks (ranges) ...
intset count i32
set size i32
set elems ... [i32]
-}
writeBlockItem :: Int32 -> Int -> W Int32
writeBlockItem offset size = do
let nextOffset = offset + fromIntegral size
writeI32 $ offset
writeI32 $ nextOffset
pure nextOffset
encodeAbstractProgram :: AbstractProgram -> LBS.ByteString
encodeAbstractProgram AbstractProgram {..} = toLazyByteString (envBuilder env) where
env = flip execState emptyEnv $ do
writeW32 _absMemoryCounter
writeW32 _absRegisterCounter
writeBlock _absInstructions
cmdCount <- gets envInstCount
writeI32 $ fromIntegral cmdCount
(blockSizes, blocks) <- gets $ unzip . Map.elems . envBuilderMap
mapM emit blocks
bocks
blkCount <- gets envBlockCount
writeI32 $ fromIntegral blkCount
foldM_ writeBlockItem 0 blockSizes
setCount < - gets envTagSetCount
writeI32 $ fromIntegral setCount
sets < - gets envTagSets
setCount <- gets envTagSetCount
writeI32 $ fromIntegral setCount
sets <- gets envTagSets
-}
tagMap <- gets envTagMap
writeI32 $ fromIntegral $ Map.size tagMap
let sets = Map.elems $ Map.fromList [(i, s) | (s, i) <- Map.toList tagMap]
forM_ sets $ \s -> do
writeI32 $ fromIntegral $ Set.size s
forM_ (Set.toList s) (\(Tag t) -> writeI32 $ fromIntegral t)
|
2ebbd7aa3d3779dbdede0364b52ecdcb00350e9da44c9e4bd91e9f5e28b51bee | kendroe/CoqRewriter | lex.ml | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.ml
*
* Implementation of lexical analysis module
*
* ( C ) 2017 ,
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
* will be provided when the work is complete .
*
* For a commercial license , contact Roe Mobile Development , LLC at
*
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.ml
*
* Implementation of lexical analysis module
*
* (C) 2017, Kenneth Roe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
* will be provided when the work is complete.
*
* For a commercial license, contact Roe Mobile Development, LLC at
*
*
*****************************************************************************)
(* require "list.sml" ; *)
require " intern.sml " ;
(* require "getfile.sml" ; *)
require " lex-s.sml " ;
(* require "basis.__integer" ; *)
open Getfile;;
type token = ID of string
| SYMBOL of string
| QUOTE of string
| C_QUOTE of char
| NUMBER of int
| RAT of int * int
| SPECIAL of string
| TVAR of string * string * int ;;
exception Failure of token list ;;
let rec print_tokens tl = match tl with
| [] -> ""
| ((ID s)::r) -> "ID(" ^ s ^")" ^ (print_tokens r)
| ((SYMBOL s)::r) -> "SYMBOL(" ^ s ^")" ^ (print_tokens r)
| ((QUOTE s)::r) -> "QUOTE(" ^ s ^")" ^ (print_tokens r)
| ((C_QUOTE s)::r) -> "C_QUOTE(" ^ (String.make 1 s) ^")" ^ (print_tokens r)
| ((NUMBER i)::r) -> "NUMBER(" ^ (string_of_int i) ^ ")" ^ (print_tokens r)
| ((RAT (i,j))::r) -> "RAT(" ^ (string_of_int i) ^ "/" ^ (string_of_int j) ^ ")" ^ (print_tokens r)
| ((SPECIAL s)::r) -> "SPECIAL(" ^ s ^")" ^ (print_tokens r)
| ((TVAR (a,b,i))::r) -> "TVAR(" ^ a ^ "," ^ b ^ "," ^ (string_of_int i) ^")" ^ (print_tokens r) ;;
let rec print_tokens2 tl = match tl with
| [] -> ""
| ((ID s,f,r1,c1,r2,c2)::r) -> "ID(" ^ s ^ ")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((SYMBOL s,f,r1,c1,r2,c2)::r) -> "SYMBOL(" ^ s ^ ")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((QUOTE s,f,r1,c1,r2,c2)::r) -> "QUOTE(" ^ s ^")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((NUMBER i,f,r1,c1,r2,c2)::r) -> "NUMBER(" ^ (string_of_int i) ^")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((RAT (i,j),f,r1,c1,r2,c2)::r) -> "RAT(" ^ (string_of_int i) ^ "/" ^ (string_of_int j) ^ ")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((SPECIAL s,f,r1,c1,r2,c2)::r) -> "SPECIAL(" ^ s ^")" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((TVAR (a,b,i),f,r1,c1,r2,c2)::r) -> "TVAR(" ^ a ^ "," ^ b ^ "," ^ (string_of_int i) ^")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r) ;;
let digit x = x >= '0' && x <= '9' ;;
let alpha x = (x >= 'a' && x <= 'z') ||
(x >= 'A' && x <= 'Z') ||
(x = '_') ;;
let rec tok file l row col = match l with
| [] -> []
| (' '::r) -> tok file r row (col+1)
| ('/':: '/':: '#'::r) -> (SPECIAL "//#",file,row,col,row,col+2)::(tok file r row (col+3))
| ('/':: '*':: '#'::r) -> (SPECIAL "/*#",file,row,col,row,col+2)::(tok file r row (col+3))
| ('/':: '/'::r) -> comment1 file r row col
| ('/':: '*'::r) -> comment2 file r row col 1
| ('\n':: '#'::r) -> new_file_line "" r
| ('\n'::r) -> tok file r (row+1) 0
| ('('::r) -> (SPECIAL "(",file,row,col,row,col) :: tok file r row (col + 1)
| (')'::r) -> (SPECIAL ")",file,row,col,row,col) :: tok file r row (col + 1)
| ('['::r) -> (SPECIAL "[",file,row,col,row,col) :: tok file r row (col + 1)
| (']'::r) -> (SPECIAL "]",file,row,col,row,col) :: tok file r row (col + 1)
| ('{'::r) -> (SPECIAL "{",file,row,col,row,col) :: tok file r row (col + 1)
| ('}'::r) -> (SPECIAL "}",file,row,col,row,col) :: tok file r row (col + 1)
| (':'::r) -> (SPECIAL ":",file,row,col,row,col) :: tok file r row (col + 1)
| (','::r) -> (SPECIAL ",",file,row,col,row,col) :: tok file r row (col + 1)
| ('\'':: '\\'::r) -> qbparse file r row (col + 2)
| ('\''::c:: '\''::r) -> (C_QUOTE c,file,row,col,row,col+2)::(tok file r row (col + 3))
| ('\''::r) -> (SPECIAL "'",file,row,col,row,col) :: tok file r row (col + 1)
| ('\\':: 'b'::r) -> (SPECIAL " ",file,row,col,row,col+1) :: tok file r row (col+2)
| (';'::r) -> (SPECIAL ";",file,row,col,row,col) :: tok file r row (col+1)
| ('\"'::r) -> qtok file "" '\"' r row col row col
| (x::r) -> if digit x then
tokenizeInt file ((int_of_char x) - (int_of_char '0')) r row col row (col+1)
else (if alpha x then
tokenizeAlpha file (String.make 1 x) r row col row (col+1)
else
tokenizeSymbol file (String.make 1 x) r row col row (col+1))
and comment1 file t row col = match t with
| ('\n'::r) -> tok file r (row+1) 0
| (x::r) -> comment1 file r row (col+1)
and comment2 file r row col n = match (r,n) with
| (r,0) -> tok file r row col
| (('/':: '*' ::r),n) -> comment2 file r row (col+2) (n+1)
| (('*' :: '/'::r),n) -> comment2 file r row (col+2) (n-1)
| (('\n'::r),n) -> comment2 file r (row+1) 0 n
| ((_::r),n) -> comment2 file r row (col+1) n
and new_file_line s tl = match tl with
| ('\n'::r) ->
(let line = (int_of_string (before_space (after_space s))) in
let file = before_space (after_space (after_space s)) in
let file = String.sub file 1 ((String.length file)-2) in
tok file r line 0)
| (l::r) -> new_file_line (s ^ (String.make 1 l)) r
and qbparse file (a::b::c::r) row col =
if a >= '0' && a <= '9' then
(if b >= '0' && b <= '9' then
(if c >= '0' && c <= '9' then
(C_QUOTE (char_of_int (((int_of_char a)-int_of_char('0'))*100+((int_of_char b)-(int_of_char '0'))*10+((int_of_char c)-(int_of_char '0')))),file,row,col-2,row,col+3)::(skip_quote file r row (col+3))
else
(C_QUOTE (char_of_int (((int_of_char a)-int_of_char('0'))*10+((int_of_char b)-(int_of_char '0')))),file,row,col-2,row,col+2)::(skip_quote file (c::r) row (col + 2)))
else
(C_QUOTE (char_of_int ((int_of_char a)-int_of_char('0'))),file,row,col-2,row,col+1)::(skip_quote file (b::c::r) row (col+1)))
else
(C_QUOTE
(if a= 'n' then '\n' else if a= 't' then '\t' else a),file,row,col-2,row,col+1
)::(skip_quote file (b::c::r) row (col+1))
and skip_quote file t row col = match t with
| ('\''::r) -> tok file r row (col+1)
| r -> tok file r row col
and qtok file s eq tl srow scol row col = match tl with
| ('\\'::a::b::c::r) ->
if a >= '0' && a <= '9' then
(if b >= '0' && b <= '9' then
(if c >= '0' && c <= '9' then
qtok file (s ^ (String.make 1 (char_of_int (((int_of_char a)-int_of_char('0'))*100+((int_of_char b)-(int_of_char '0'))*10+((int_of_char c)-(int_of_char '0')))))) eq r srow scol row (col+3)
else
qtok file (s ^ (String.make 1 (char_of_int (((int_of_char a)-int_of_char('0'))*10+((int_of_char b)-(int_of_char '0')))))) eq (c::r) srow scol row (col+2))
else
qtok file (s ^ (String.make 1 (char_of_int ((int_of_char a)-int_of_char('0'))))) eq (b::c::r) srow scol row (col+1))
else
qtok file (s ^ (String.make 1 (if a= 'n' then '\n' else if a='t' then '\t' else a))) eq (b::c::r) srow scol row (col+1)
| (f::r) ->
if f=eq then ((QUOTE s),file,srow,scol,row,col)::(tok file r row (col+1)) else qtok file (s ^ (String.make 1 f)) eq r srow scol row (col+1)
| [] -> [(QUOTE s,file,srow,scol,row,col)]
and tokenizeInt file v tl srow scol row col = match tl with
| [] -> [(NUMBER v,file,srow,scol,row,col)]
| (a::b) -> if digit a then
tokenizeInt file (v * 10 + ((int_of_char a) - (int_of_char '0')))
b srow scol row (col+1)
else if a= '#' then
startTokenizeNumber file v 0 b srow scol row (col+1)
else ((NUMBER v),file,srow,scol,row,col-1)::(tok file (a::b) row col)
and startTokenizeNumber file n v tl srow scol row col = match tl with
| (a::b) -> if digit a then tokenizeNumber file n v (a::b) srow scol row col
else (NUMBER n,file,srow,scol,row,col-2)::(tok file ('#'::a::b) row (col-1))
| [] -> (NUMBER n,file,srow,scol,row,col-2)::(tok file ['#'] row (col-1))
and tokenizeNumber file n v tl srow scol row col = match tl with
| [] -> [(RAT (n,v),file,srow,scol,row,col)]
| (a::b) -> if digit a then
tokenizeNumber file n (v * 10 + ((int_of_char a) - (int_of_char '0')))
b srow scol row (col+1)
else ((RAT (n,v)),file,srow,scol,row,col-1)::(tok file (a::b) row col)
and tokenizeAlpha file v tl srow scol row col = match tl with
| [] -> [(ID v,file,srow,scol,row,col)]
| (a::b) -> if (alpha a) || (digit a) then
tokenizeAlpha file (v ^ (String.make 1 a)) b srow scol row (col+1)
else
(ID v,file,srow,scol,row,col-1)::(tok file (a::b) row col)
and tokenizeSymbol file v tl srow scol row col = match tl with
| [] -> [(SYMBOL v,file,srow,scol,row,col)]
| (a::b) -> if (digit a) || (alpha a) ||
a = ' ' || a = '(' || a = '{'
|| a = '[' || a = ',' || a = ' ' ||
a = ':' || a = '\n' then
(SYMBOL v,file,srow,scol,row,col-1)::(tok file (a::b) row col)
else
tokenizeSymbol file (v ^ (String.make 1 a)) b srow scol row (col+1) ;;
let explode str =
let rec exp a b =
if a < 0 then b
else exp (a - 1) (str.[a] :: b)
in
exp (String.length str - 1) [];;
let tokenize_rc f s = tok f (explode s) 0 0 ;;
let tokenize s = List.map (fun (a,b,c,d,e,f) -> a) (tokenize_rc "" s) ;;
| null | https://raw.githubusercontent.com/kendroe/CoqRewriter/ddf5dc2ea51105d5a2dc87c99f0d364cf2b8ebf5/plugin/src/lex.ml | ocaml | require "list.sml" ;
require "getfile.sml" ;
require "basis.__integer" ; | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.ml
*
* Implementation of lexical analysis module
*
* ( C ) 2017 ,
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
* will be provided when the work is complete .
*
* For a commercial license , contact Roe Mobile Development , LLC at
*
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* REWRITELIB
*
* lex.ml
*
* Implementation of lexical analysis module
*
* (C) 2017, Kenneth Roe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
* will be provided when the work is complete.
*
* For a commercial license, contact Roe Mobile Development, LLC at
*
*
*****************************************************************************)
require " intern.sml " ;
require " lex-s.sml " ;
open Getfile;;
type token = ID of string
| SYMBOL of string
| QUOTE of string
| C_QUOTE of char
| NUMBER of int
| RAT of int * int
| SPECIAL of string
| TVAR of string * string * int ;;
exception Failure of token list ;;
let rec print_tokens tl = match tl with
| [] -> ""
| ((ID s)::r) -> "ID(" ^ s ^")" ^ (print_tokens r)
| ((SYMBOL s)::r) -> "SYMBOL(" ^ s ^")" ^ (print_tokens r)
| ((QUOTE s)::r) -> "QUOTE(" ^ s ^")" ^ (print_tokens r)
| ((C_QUOTE s)::r) -> "C_QUOTE(" ^ (String.make 1 s) ^")" ^ (print_tokens r)
| ((NUMBER i)::r) -> "NUMBER(" ^ (string_of_int i) ^ ")" ^ (print_tokens r)
| ((RAT (i,j))::r) -> "RAT(" ^ (string_of_int i) ^ "/" ^ (string_of_int j) ^ ")" ^ (print_tokens r)
| ((SPECIAL s)::r) -> "SPECIAL(" ^ s ^")" ^ (print_tokens r)
| ((TVAR (a,b,i))::r) -> "TVAR(" ^ a ^ "," ^ b ^ "," ^ (string_of_int i) ^")" ^ (print_tokens r) ;;
let rec print_tokens2 tl = match tl with
| [] -> ""
| ((ID s,f,r1,c1,r2,c2)::r) -> "ID(" ^ s ^ ")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((SYMBOL s,f,r1,c1,r2,c2)::r) -> "SYMBOL(" ^ s ^ ")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((QUOTE s,f,r1,c1,r2,c2)::r) -> "QUOTE(" ^ s ^")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((NUMBER i,f,r1,c1,r2,c2)::r) -> "NUMBER(" ^ (string_of_int i) ^")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((RAT (i,j),f,r1,c1,r2,c2)::r) -> "RAT(" ^ (string_of_int i) ^ "/" ^ (string_of_int j) ^ ")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((SPECIAL s,f,r1,c1,r2,c2)::r) -> "SPECIAL(" ^ s ^")" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r)
| ((TVAR (a,b,i),f,r1,c1,r2,c2)::r) -> "TVAR(" ^ a ^ "," ^ b ^ "," ^ (string_of_int i) ^")[" ^
f ^ "," ^ (string_of_int r1) ^ "," ^ (string_of_int c1) ^ "," ^ (string_of_int r2) ^ "," ^ (string_of_int c2) ^ "]" ^
(print_tokens2 r) ;;
let digit x = x >= '0' && x <= '9' ;;
let alpha x = (x >= 'a' && x <= 'z') ||
(x >= 'A' && x <= 'Z') ||
(x = '_') ;;
let rec tok file l row col = match l with
| [] -> []
| (' '::r) -> tok file r row (col+1)
| ('/':: '/':: '#'::r) -> (SPECIAL "//#",file,row,col,row,col+2)::(tok file r row (col+3))
| ('/':: '*':: '#'::r) -> (SPECIAL "/*#",file,row,col,row,col+2)::(tok file r row (col+3))
| ('/':: '/'::r) -> comment1 file r row col
| ('/':: '*'::r) -> comment2 file r row col 1
| ('\n':: '#'::r) -> new_file_line "" r
| ('\n'::r) -> tok file r (row+1) 0
| ('('::r) -> (SPECIAL "(",file,row,col,row,col) :: tok file r row (col + 1)
| (')'::r) -> (SPECIAL ")",file,row,col,row,col) :: tok file r row (col + 1)
| ('['::r) -> (SPECIAL "[",file,row,col,row,col) :: tok file r row (col + 1)
| (']'::r) -> (SPECIAL "]",file,row,col,row,col) :: tok file r row (col + 1)
| ('{'::r) -> (SPECIAL "{",file,row,col,row,col) :: tok file r row (col + 1)
| ('}'::r) -> (SPECIAL "}",file,row,col,row,col) :: tok file r row (col + 1)
| (':'::r) -> (SPECIAL ":",file,row,col,row,col) :: tok file r row (col + 1)
| (','::r) -> (SPECIAL ",",file,row,col,row,col) :: tok file r row (col + 1)
| ('\'':: '\\'::r) -> qbparse file r row (col + 2)
| ('\''::c:: '\''::r) -> (C_QUOTE c,file,row,col,row,col+2)::(tok file r row (col + 3))
| ('\''::r) -> (SPECIAL "'",file,row,col,row,col) :: tok file r row (col + 1)
| ('\\':: 'b'::r) -> (SPECIAL " ",file,row,col,row,col+1) :: tok file r row (col+2)
| (';'::r) -> (SPECIAL ";",file,row,col,row,col) :: tok file r row (col+1)
| ('\"'::r) -> qtok file "" '\"' r row col row col
| (x::r) -> if digit x then
tokenizeInt file ((int_of_char x) - (int_of_char '0')) r row col row (col+1)
else (if alpha x then
tokenizeAlpha file (String.make 1 x) r row col row (col+1)
else
tokenizeSymbol file (String.make 1 x) r row col row (col+1))
and comment1 file t row col = match t with
| ('\n'::r) -> tok file r (row+1) 0
| (x::r) -> comment1 file r row (col+1)
and comment2 file r row col n = match (r,n) with
| (r,0) -> tok file r row col
| (('/':: '*' ::r),n) -> comment2 file r row (col+2) (n+1)
| (('*' :: '/'::r),n) -> comment2 file r row (col+2) (n-1)
| (('\n'::r),n) -> comment2 file r (row+1) 0 n
| ((_::r),n) -> comment2 file r row (col+1) n
and new_file_line s tl = match tl with
| ('\n'::r) ->
(let line = (int_of_string (before_space (after_space s))) in
let file = before_space (after_space (after_space s)) in
let file = String.sub file 1 ((String.length file)-2) in
tok file r line 0)
| (l::r) -> new_file_line (s ^ (String.make 1 l)) r
and qbparse file (a::b::c::r) row col =
if a >= '0' && a <= '9' then
(if b >= '0' && b <= '9' then
(if c >= '0' && c <= '9' then
(C_QUOTE (char_of_int (((int_of_char a)-int_of_char('0'))*100+((int_of_char b)-(int_of_char '0'))*10+((int_of_char c)-(int_of_char '0')))),file,row,col-2,row,col+3)::(skip_quote file r row (col+3))
else
(C_QUOTE (char_of_int (((int_of_char a)-int_of_char('0'))*10+((int_of_char b)-(int_of_char '0')))),file,row,col-2,row,col+2)::(skip_quote file (c::r) row (col + 2)))
else
(C_QUOTE (char_of_int ((int_of_char a)-int_of_char('0'))),file,row,col-2,row,col+1)::(skip_quote file (b::c::r) row (col+1)))
else
(C_QUOTE
(if a= 'n' then '\n' else if a= 't' then '\t' else a),file,row,col-2,row,col+1
)::(skip_quote file (b::c::r) row (col+1))
and skip_quote file t row col = match t with
| ('\''::r) -> tok file r row (col+1)
| r -> tok file r row col
and qtok file s eq tl srow scol row col = match tl with
| ('\\'::a::b::c::r) ->
if a >= '0' && a <= '9' then
(if b >= '0' && b <= '9' then
(if c >= '0' && c <= '9' then
qtok file (s ^ (String.make 1 (char_of_int (((int_of_char a)-int_of_char('0'))*100+((int_of_char b)-(int_of_char '0'))*10+((int_of_char c)-(int_of_char '0')))))) eq r srow scol row (col+3)
else
qtok file (s ^ (String.make 1 (char_of_int (((int_of_char a)-int_of_char('0'))*10+((int_of_char b)-(int_of_char '0')))))) eq (c::r) srow scol row (col+2))
else
qtok file (s ^ (String.make 1 (char_of_int ((int_of_char a)-int_of_char('0'))))) eq (b::c::r) srow scol row (col+1))
else
qtok file (s ^ (String.make 1 (if a= 'n' then '\n' else if a='t' then '\t' else a))) eq (b::c::r) srow scol row (col+1)
| (f::r) ->
if f=eq then ((QUOTE s),file,srow,scol,row,col)::(tok file r row (col+1)) else qtok file (s ^ (String.make 1 f)) eq r srow scol row (col+1)
| [] -> [(QUOTE s,file,srow,scol,row,col)]
and tokenizeInt file v tl srow scol row col = match tl with
| [] -> [(NUMBER v,file,srow,scol,row,col)]
| (a::b) -> if digit a then
tokenizeInt file (v * 10 + ((int_of_char a) - (int_of_char '0')))
b srow scol row (col+1)
else if a= '#' then
startTokenizeNumber file v 0 b srow scol row (col+1)
else ((NUMBER v),file,srow,scol,row,col-1)::(tok file (a::b) row col)
and startTokenizeNumber file n v tl srow scol row col = match tl with
| (a::b) -> if digit a then tokenizeNumber file n v (a::b) srow scol row col
else (NUMBER n,file,srow,scol,row,col-2)::(tok file ('#'::a::b) row (col-1))
| [] -> (NUMBER n,file,srow,scol,row,col-2)::(tok file ['#'] row (col-1))
and tokenizeNumber file n v tl srow scol row col = match tl with
| [] -> [(RAT (n,v),file,srow,scol,row,col)]
| (a::b) -> if digit a then
tokenizeNumber file n (v * 10 + ((int_of_char a) - (int_of_char '0')))
b srow scol row (col+1)
else ((RAT (n,v)),file,srow,scol,row,col-1)::(tok file (a::b) row col)
and tokenizeAlpha file v tl srow scol row col = match tl with
| [] -> [(ID v,file,srow,scol,row,col)]
| (a::b) -> if (alpha a) || (digit a) then
tokenizeAlpha file (v ^ (String.make 1 a)) b srow scol row (col+1)
else
(ID v,file,srow,scol,row,col-1)::(tok file (a::b) row col)
and tokenizeSymbol file v tl srow scol row col = match tl with
| [] -> [(SYMBOL v,file,srow,scol,row,col)]
| (a::b) -> if (digit a) || (alpha a) ||
a = ' ' || a = '(' || a = '{'
|| a = '[' || a = ',' || a = ' ' ||
a = ':' || a = '\n' then
(SYMBOL v,file,srow,scol,row,col-1)::(tok file (a::b) row col)
else
tokenizeSymbol file (v ^ (String.make 1 a)) b srow scol row (col+1) ;;
let explode str =
let rec exp a b =
if a < 0 then b
else exp (a - 1) (str.[a] :: b)
in
exp (String.length str - 1) [];;
let tokenize_rc f s = tok f (explode s) 0 0 ;;
let tokenize s = List.map (fun (a,b,c,d,e,f) -> a) (tokenize_rc "" s) ;;
|
a0746d0f0c6ac137ebe7f0c70d74967bd686123e0989badcc2ed9c171620c467 | jwiegley/trade-journal | Closings.hs | # LANGUAGE BlockArguments #
# LANGUAGE DataKinds #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
module Journal.Closings where
import Control.Applicative
import Control.Arrow
import Control.Lens
import Control.Monad.State
import Data.Foldable
import Data.Functor.Classes
import Data.IntMap (IntMap)
import Data.List (intersperse, sortOn)
import Data.Map (Map)
import Data.Maybe (fromMaybe)
import Data.Sum
import Data.Sum.Lens
import Data.Text (Text)
import qualified Data.Text.Lazy as TL
import GHC.Generics hiding (to)
import Journal.Entry
import Journal.Parse
import Journal.Print
import Journal.Split
import Journal.Types
import qualified Text.Megaparsec.Char.Lexer as L
import Text.Show.Pretty hiding (Time)
import Prelude hiding (Double, Float)
data Disposition = Long | Short
deriving (Show, PrettyVal, Eq, Ord, Enum, Bounded, Generic)
data Position = Position
{ _posIdent :: Int,
_posLot :: Lot,
_posDisp :: Disposition
}
deriving
( Show,
Eq,
Ord,
Generic,
PrettyVal
)
data Closing = Closing
{ _closingPos :: Int,
_closingLot :: Lot
}
deriving
( Show,
Eq,
Ord,
Generic,
PrettyVal
)
makeLenses ''Position
makeLenses ''Closing
-- instance Splittable (Amount 6) Position where
-- howmuch = posLot . amount
-- instance Splittable (Amount 6) Closing where
-- howmuch = closingLot . amount
data PositionEvent
= Open Position -- open a position in the account
| Close Closing -- close a position in the account
deriving
( Show,
PrettyVal,
Eq,
Generic
)
makePrisms ''PositionEvent
class HasPositionEvent f where
_Event :: Traversal' (f v) PositionEvent
instance HasTraversal' HasPositionEvent fs => HasPositionEvent (Sum fs) where
_Event = traversing @HasPositionEvent _Event
instance HasPositionEvent (Const Deposit) where _Event _ = pure
instance HasPositionEvent (Const Income) where _Event _ = pure
instance HasPositionEvent (Const Options) where _Event _ = pure
instance HasPositionEvent (Const Trade) where _Event _ = pure
instance HasPositionEvent (Const PositionEvent) where
_Event f (Const s) = Const <$> f s
_EventLot :: Traversal' PositionEvent Lot
_EventLot f = \case
Open pos -> Open <$> (pos & posLot %%~ f)
Close cl -> Close <$> (cl & closingLot %%~ f)
instance HasLot (Const PositionEvent) where
_Lot f (Const s) = fmap Const $ s & _EventLot %%~ f
data Calculation a = FIFO | LIFO | forall b. Ord b => Custom (a -> b)
data BasicState a m = BasicState
{ _calc :: Calculation a,
_nextId :: Int,
_events :: m
}
deriving (Generic, Functor)
makeLenses ''BasicState
type ClosingState a = BasicState a (Map Text (IntMap a))
newClosingState :: Calculation a -> ClosingState a
newClosingState c =
BasicState
{ _calc = c,
_nextId = 0,
_events = mempty
}
type LocalState a = BasicState a (IntMap a)
localState :: Text -> Traversal' (ClosingState a) (LocalState a)
localState instrument f s =
f (view (at instrument . non' _Empty) <$> s)
<&> \m ->
s & calc .~ (m ^. calc)
& nextId .~ (m ^. nextId)
& events . at instrument ?~ (m ^. events)
closings ::
Const Trade :< r =>
Calculation (Annotated (Sum (Const PositionEvent ': r) v)) ->
[Annotated (Sum r v)] ->
( [Annotated (Sum (Const PositionEvent ': r) v)],
Map Text (IntMap (Annotated (Sum (Const PositionEvent ': r) v)))
)
closings mode =
(concat *** _events) . flip runState (newClosingState mode) . mapM go
where
go entry = do
gst <- get
case entry ^? item . projectedC . tradeLot . symbol of
Just sym -> do
let (results, gst') =
flip runState gst $
zoom (localState sym) $
untilDone handle entry
put gst'
pure (fmap weaken entry : results)
Nothing -> pure [fmap weaken entry]
handle ::
Const Trade :< r =>
Annotated (Sum r v) ->
State
(LocalState (Annotated (Sum (Const PositionEvent ': r) v)))
( [Annotated (Sum (Const PositionEvent ': r) v)],
Remainder (Annotated (Sum r v))
)
handle ann@(preview (item . projectedC) -> Just trade) = do
mode <- use calc
jww ( 2021 - 12 - 04 ): the buy / sell should be able to specify FIFO or LIFO ,
-- and the user should be able to set it as a default. In the case of LIFE,
-- this traversal needs to be reversed.
gets
( (case mode of
FIFO -> id
LIFO -> reverse
Custom f -> sortOn f)
. (^.. events . traverse)
)
>>= \case
open@(preview (item . projectedC . _Open . posDisp) -> Just disp) : _
| disp
== case trade ^?! tradeAction of
Sell -> Long
Buy -> Short -> do
events . at (open ^?! item . projectedC . _Open . posIdent) .= Nothing
closePosition open ann
_ -> (,Finished) <$> openPosition ann
handle _ = pure ([], Finished)
-- | Open a new position.
openPosition ::
Const Trade :< r =>
Annotated (Sum r v) ->
State
(LocalState (Annotated (Sum (Const PositionEvent ': r) v)))
[Annotated (Sum (Const PositionEvent ': r) v)]
openPosition open = do
nextId += 1
ident <- use nextId
let trade = open ^?! item . projectedC
event =
projectedC . _Open
# Position
{ _posIdent = ident,
_posLot = trade ^. tradeLot,
_posDisp =
case trade ^?! tradeAction of
Buy -> Long
Sell -> Short
}
<$ open
events . at ident ?= event
pure [event]
-- | Close an existing position. If the amount to close is more than what is
-- open, the remainder is considered a separate opening event.
closePosition ::
Const Trade :< r =>
Annotated (Sum (Const PositionEvent ': r) v) ->
Annotated (Sum r v) ->
State
(LocalState (Annotated (Sum (Const PositionEvent ': r) v)))
( [Annotated (Sum (Const PositionEvent ': r) v)],
Remainder (Annotated (Sum r v))
)
closePosition open close =
let o = open ^?! item . projectedC . _Open
in alignForClose
(o ^. posLot)
(close ^?! item . projectedC . tradeLot)
( \_su du ->
pure
[ projectedC . _Close
# Closing
{ _closingPos = o ^. posIdent,
_closingLot = du
}
<$ close
]
)
( \sk ->
events . at (open ^?! item . projectedC . _Open . posIdent)
?= (open & item . projectedC . _Open . posLot .~ sk)
)
(\dk -> pure $ close & item . projectedC . tradeLot .~ dk)
alignForClose ::
(Splittable n a, Splittable n b, Applicative m) =>
a ->
b ->
(a -> b -> m [x]) ->
(a -> m ()) ->
(b -> m z) ->
m ([x], Remainder z)
alignForClose l r f g h =
alignedA l r f g h
<&> fromMaybe []
*** \case
Remainder (Right r') -> Remainder r'
_ -> Finished
positions ::
( HasTraversal' HasPositionEvent r,
Apply Eq1 r,
Eq v,
Apply Show1 r,
Show v
) =>
[Annotated (Sum r v)] ->
Map Text (IntMap (Annotated (Sum r v)))
positions = foldl' positionsFromEntry mempty
positionsFromEntry ::
( HasTraversal' HasPositionEvent r,
Apply Eq1 r,
Eq v,
Apply Show1 r,
Show v
) =>
Map Text (IntMap (Annotated (Sum r v))) ->
Annotated (Sum r v) ->
Map Text (IntMap (Annotated (Sum r v)))
positionsFromEntry m = go
where
go o@((^? item . _Event . _Open) -> Just pos) =
m
& at (pos ^. posLot . symbol)
. non mempty
. at (pos ^. posIdent)
?~ o
go ((^? item . _Event . _Close) -> Just cl) =
flip execState m do
let loc ::
(Apply Eq1 r, Eq v) =>
Traversal'
(Map Text (IntMap (Annotated (Sum r v))))
(Maybe (Annotated (Sum r v)))
loc =
at (cl ^. closingLot . symbol)
. non mempty
. at (cl ^. closingPos)
preuse (loc . _Just) >>= \case
Nothing ->
error $
"Attempt to close non-open position:\n"
++ ppShow cl
++ "\n---- against open positions ----\n"
++ ppShow m
Just o ->
alignedA
(o ^?! item . _Event . _Open . posLot)
(cl ^. closingLot)
(\_ou _cu -> loc .= Nothing)
(\ok -> loc ?= (o & item . _Event . _Open . posLot .~ ok))
(\_ck -> error "Invalid closing")
go _ = m
instance Printable (Const PositionEvent) where
printItem = printEvent . getConst
printEvent :: PositionEvent -> TL.Text
printEvent = \case
Open pos -> printPosition pos
Close cl -> printClosing cl
printPosition :: Position -> TL.Text
printPosition Position {..} =
TL.pack (show _posIdent)
<> " "
<> printLot _posLot
<> " "
<> printDisposition _posDisp
where
printDisposition Long = "long"
printDisposition Short = "short"
printClosing :: Closing -> TL.Text
printClosing Closing {..} =
TL.concat $
intersperse
" "
[ TL.pack (show _closingPos),
printLot _closingLot
]
parsePosition :: Parser Position
parsePosition =
Position
<$> L.decimal <* whiteSpace
<*> parseLot
<*> parseDisposition
where
parseDisposition :: Parser Disposition
parseDisposition =
Long <$ keyword "long"
<|> Short <$ keyword "short"
jww ( 2021 - 12 - 03 ): A closing should display what it 's closing the open
position to , for example : FOO 100 @ < basis > - > 50 .
parseClosing :: Parser Closing
parseClosing =
Closing
<$> (L.decimal <* whiteSpace)
<*> parseLot
| null | https://raw.githubusercontent.com/jwiegley/trade-journal/a482dbcbc3ff97267d99e340845bf738545b9236/src/Journal/Closings.hs | haskell | # LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveTraversable #
# LANGUAGE GADTs #
# LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
instance Splittable (Amount 6) Position where
howmuch = posLot . amount
instance Splittable (Amount 6) Closing where
howmuch = closingLot . amount
open a position in the account
close a position in the account
and the user should be able to set it as a default. In the case of LIFE,
this traversal needs to be reversed.
| Open a new position.
| Close an existing position. If the amount to close is more than what is
open, the remainder is considered a separate opening event. | # LANGUAGE BlockArguments #
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
# LANGUAGE TemplateHaskell #
# LANGUAGE TupleSections #
# LANGUAGE TypeApplications #
# LANGUAGE TypeOperators #
# LANGUAGE UndecidableInstances #
# LANGUAGE ViewPatterns #
module Journal.Closings where
import Control.Applicative
import Control.Arrow
import Control.Lens
import Control.Monad.State
import Data.Foldable
import Data.Functor.Classes
import Data.IntMap (IntMap)
import Data.List (intersperse, sortOn)
import Data.Map (Map)
import Data.Maybe (fromMaybe)
import Data.Sum
import Data.Sum.Lens
import Data.Text (Text)
import qualified Data.Text.Lazy as TL
import GHC.Generics hiding (to)
import Journal.Entry
import Journal.Parse
import Journal.Print
import Journal.Split
import Journal.Types
import qualified Text.Megaparsec.Char.Lexer as L
import Text.Show.Pretty hiding (Time)
import Prelude hiding (Double, Float)
data Disposition = Long | Short
deriving (Show, PrettyVal, Eq, Ord, Enum, Bounded, Generic)
data Position = Position
{ _posIdent :: Int,
_posLot :: Lot,
_posDisp :: Disposition
}
deriving
( Show,
Eq,
Ord,
Generic,
PrettyVal
)
data Closing = Closing
{ _closingPos :: Int,
_closingLot :: Lot
}
deriving
( Show,
Eq,
Ord,
Generic,
PrettyVal
)
makeLenses ''Position
makeLenses ''Closing
data PositionEvent
deriving
( Show,
PrettyVal,
Eq,
Generic
)
makePrisms ''PositionEvent
class HasPositionEvent f where
_Event :: Traversal' (f v) PositionEvent
instance HasTraversal' HasPositionEvent fs => HasPositionEvent (Sum fs) where
_Event = traversing @HasPositionEvent _Event
instance HasPositionEvent (Const Deposit) where _Event _ = pure
instance HasPositionEvent (Const Income) where _Event _ = pure
instance HasPositionEvent (Const Options) where _Event _ = pure
instance HasPositionEvent (Const Trade) where _Event _ = pure
instance HasPositionEvent (Const PositionEvent) where
_Event f (Const s) = Const <$> f s
_EventLot :: Traversal' PositionEvent Lot
_EventLot f = \case
Open pos -> Open <$> (pos & posLot %%~ f)
Close cl -> Close <$> (cl & closingLot %%~ f)
instance HasLot (Const PositionEvent) where
_Lot f (Const s) = fmap Const $ s & _EventLot %%~ f
data Calculation a = FIFO | LIFO | forall b. Ord b => Custom (a -> b)
data BasicState a m = BasicState
{ _calc :: Calculation a,
_nextId :: Int,
_events :: m
}
deriving (Generic, Functor)
makeLenses ''BasicState
type ClosingState a = BasicState a (Map Text (IntMap a))
newClosingState :: Calculation a -> ClosingState a
newClosingState c =
BasicState
{ _calc = c,
_nextId = 0,
_events = mempty
}
type LocalState a = BasicState a (IntMap a)
localState :: Text -> Traversal' (ClosingState a) (LocalState a)
localState instrument f s =
f (view (at instrument . non' _Empty) <$> s)
<&> \m ->
s & calc .~ (m ^. calc)
& nextId .~ (m ^. nextId)
& events . at instrument ?~ (m ^. events)
closings ::
Const Trade :< r =>
Calculation (Annotated (Sum (Const PositionEvent ': r) v)) ->
[Annotated (Sum r v)] ->
( [Annotated (Sum (Const PositionEvent ': r) v)],
Map Text (IntMap (Annotated (Sum (Const PositionEvent ': r) v)))
)
closings mode =
(concat *** _events) . flip runState (newClosingState mode) . mapM go
where
go entry = do
gst <- get
case entry ^? item . projectedC . tradeLot . symbol of
Just sym -> do
let (results, gst') =
flip runState gst $
zoom (localState sym) $
untilDone handle entry
put gst'
pure (fmap weaken entry : results)
Nothing -> pure [fmap weaken entry]
handle ::
Const Trade :< r =>
Annotated (Sum r v) ->
State
(LocalState (Annotated (Sum (Const PositionEvent ': r) v)))
( [Annotated (Sum (Const PositionEvent ': r) v)],
Remainder (Annotated (Sum r v))
)
handle ann@(preview (item . projectedC) -> Just trade) = do
mode <- use calc
jww ( 2021 - 12 - 04 ): the buy / sell should be able to specify FIFO or LIFO ,
gets
( (case mode of
FIFO -> id
LIFO -> reverse
Custom f -> sortOn f)
. (^.. events . traverse)
)
>>= \case
open@(preview (item . projectedC . _Open . posDisp) -> Just disp) : _
| disp
== case trade ^?! tradeAction of
Sell -> Long
Buy -> Short -> do
events . at (open ^?! item . projectedC . _Open . posIdent) .= Nothing
closePosition open ann
_ -> (,Finished) <$> openPosition ann
handle _ = pure ([], Finished)
openPosition ::
Const Trade :< r =>
Annotated (Sum r v) ->
State
(LocalState (Annotated (Sum (Const PositionEvent ': r) v)))
[Annotated (Sum (Const PositionEvent ': r) v)]
openPosition open = do
nextId += 1
ident <- use nextId
let trade = open ^?! item . projectedC
event =
projectedC . _Open
# Position
{ _posIdent = ident,
_posLot = trade ^. tradeLot,
_posDisp =
case trade ^?! tradeAction of
Buy -> Long
Sell -> Short
}
<$ open
events . at ident ?= event
pure [event]
closePosition ::
Const Trade :< r =>
Annotated (Sum (Const PositionEvent ': r) v) ->
Annotated (Sum r v) ->
State
(LocalState (Annotated (Sum (Const PositionEvent ': r) v)))
( [Annotated (Sum (Const PositionEvent ': r) v)],
Remainder (Annotated (Sum r v))
)
closePosition open close =
let o = open ^?! item . projectedC . _Open
in alignForClose
(o ^. posLot)
(close ^?! item . projectedC . tradeLot)
( \_su du ->
pure
[ projectedC . _Close
# Closing
{ _closingPos = o ^. posIdent,
_closingLot = du
}
<$ close
]
)
( \sk ->
events . at (open ^?! item . projectedC . _Open . posIdent)
?= (open & item . projectedC . _Open . posLot .~ sk)
)
(\dk -> pure $ close & item . projectedC . tradeLot .~ dk)
alignForClose ::
(Splittable n a, Splittable n b, Applicative m) =>
a ->
b ->
(a -> b -> m [x]) ->
(a -> m ()) ->
(b -> m z) ->
m ([x], Remainder z)
alignForClose l r f g h =
alignedA l r f g h
<&> fromMaybe []
*** \case
Remainder (Right r') -> Remainder r'
_ -> Finished
positions ::
( HasTraversal' HasPositionEvent r,
Apply Eq1 r,
Eq v,
Apply Show1 r,
Show v
) =>
[Annotated (Sum r v)] ->
Map Text (IntMap (Annotated (Sum r v)))
positions = foldl' positionsFromEntry mempty
positionsFromEntry ::
( HasTraversal' HasPositionEvent r,
Apply Eq1 r,
Eq v,
Apply Show1 r,
Show v
) =>
Map Text (IntMap (Annotated (Sum r v))) ->
Annotated (Sum r v) ->
Map Text (IntMap (Annotated (Sum r v)))
positionsFromEntry m = go
where
go o@((^? item . _Event . _Open) -> Just pos) =
m
& at (pos ^. posLot . symbol)
. non mempty
. at (pos ^. posIdent)
?~ o
go ((^? item . _Event . _Close) -> Just cl) =
flip execState m do
let loc ::
(Apply Eq1 r, Eq v) =>
Traversal'
(Map Text (IntMap (Annotated (Sum r v))))
(Maybe (Annotated (Sum r v)))
loc =
at (cl ^. closingLot . symbol)
. non mempty
. at (cl ^. closingPos)
preuse (loc . _Just) >>= \case
Nothing ->
error $
"Attempt to close non-open position:\n"
++ ppShow cl
++ "\n---- against open positions ----\n"
++ ppShow m
Just o ->
alignedA
(o ^?! item . _Event . _Open . posLot)
(cl ^. closingLot)
(\_ou _cu -> loc .= Nothing)
(\ok -> loc ?= (o & item . _Event . _Open . posLot .~ ok))
(\_ck -> error "Invalid closing")
go _ = m
instance Printable (Const PositionEvent) where
printItem = printEvent . getConst
printEvent :: PositionEvent -> TL.Text
printEvent = \case
Open pos -> printPosition pos
Close cl -> printClosing cl
printPosition :: Position -> TL.Text
printPosition Position {..} =
TL.pack (show _posIdent)
<> " "
<> printLot _posLot
<> " "
<> printDisposition _posDisp
where
printDisposition Long = "long"
printDisposition Short = "short"
printClosing :: Closing -> TL.Text
printClosing Closing {..} =
TL.concat $
intersperse
" "
[ TL.pack (show _closingPos),
printLot _closingLot
]
parsePosition :: Parser Position
parsePosition =
Position
<$> L.decimal <* whiteSpace
<*> parseLot
<*> parseDisposition
where
parseDisposition :: Parser Disposition
parseDisposition =
Long <$ keyword "long"
<|> Short <$ keyword "short"
jww ( 2021 - 12 - 03 ): A closing should display what it 's closing the open
position to , for example : FOO 100 @ < basis > - > 50 .
parseClosing :: Parser Closing
parseClosing =
Closing
<$> (L.decimal <* whiteSpace)
<*> parseLot
|
62ae7425019c313243b5f80b54868630370d6663a1855d61984af6d72ab0f726 | jellelicht/guix | ocaml.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 < >
Copyright © 2014 , 2015 < >
Copyright © 2015 < >
Copyright © 2015 < >
Copyright © 2016 < >
Copyright © 2016 Jan Nieuwenhuizen < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages ocaml)
#:use-module ((guix licenses) #:hide (zlib))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix svn-download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (gnu packages gcc)
#:use-module (gnu packages gnome)
#:use-module (gnu packages gtk)
#:use-module (gnu packages base)
#:use-module (gnu packages emacs)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages compression)
#:use-module (gnu packages xorg)
#:use-module (gnu packages texlive)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages lynx)
#:use-module (gnu packages perl)
#:use-module (gnu packages python)
#:use-module (gnu packages m4)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages version-control)
#:use-module (gnu packages curl))
(define-public ocaml
(package
(name "ocaml")
(version "4.02.3")
(source (origin
(method url-fetch)
(uri (string-append
"-"
(version-major+minor version)
"/ocaml-" version ".tar.xz"))
(sha256
(base32
"1qwwvy8nzd87hk8rd9sm667nppakiapnx4ypdwcrlnav2dz6kil3"))))
(build-system gnu-build-system)
(native-search-paths
(list (search-path-specification
(variable "OCAMLPATH")
(files (list (string-append "lib/ocaml"))))))
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)))
(inputs
`(("libx11" ,libx11)
;; For libiberty, needed for objdump support.
("gcc:lib" ,(canonical-package gcc-4.9) "lib")
("zlib" ,zlib))) ;also needed for objdump support
(arguments
`(#:modules ((guix build gnu-build-system)
(guix build utils)
(web server))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-/bin/sh-references
(lambda* (#:key inputs #:allow-other-keys)
(let* ((sh (string-append (assoc-ref inputs "bash")
"/bin/sh"))
(quoted-sh (string-append "\"" sh "\"")))
(with-fluids ((%default-port-encoding #f))
(for-each (lambda (file)
(substitute* file
(("\"/bin/sh\"")
(begin
(format (current-error-port) "\
patch-/bin/sh-references: ~a: changing `\"/bin/sh\"' to `~a'~%"
file quoted-sh)
quoted-sh))))
(find-files "." "\\.ml$"))
#t))))
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(mandir (string-append out "/share/man")))
;; Custom configure script doesn't recognize
;; --prefix=<PREFIX> syntax (with equals sign).
(zero? (system* "./configure"
"--prefix" out
"--mandir" mandir)))))
(replace 'build
(lambda _
(zero? (system* "make" "-j" (number->string
(parallel-job-count))
"world.opt"))))
(delete 'check)
(add-after 'install 'check
(lambda _
(with-directory-excursion "testsuite"
(zero? (system* "make" "all")))))
(add-before 'check 'prepare-socket-test
(lambda _
(format (current-error-port)
"Spawning local test web server on port 8080~%")
(when (zero? (primitive-fork))
(run-server (lambda (request request-body)
(values '((content-type . (text/plain)))
"Hello!"))
'http '(#:port 8080)))
(let ((file "testsuite/tests/lib-threads/testsocket.ml"))
(format (current-error-port)
"Patching ~a to use localhost port 8080~%"
file)
(substitute* file
(("caml.inria.fr") "localhost")
(("80") "8080")
(("HTTP1.0") "HTTP/1.0"))
#t))))))
(home-page "/")
(synopsis "The OCaml programming language")
(description
"OCaml is a general purpose industrial-strength programming language with
an emphasis on expressiveness and safety. Developed for more than 20 years at
Inria it benefits from one of the most advanced type systems and supports
functional, imperative and object-oriented styles of programming.")
;; The compiler is distributed under qpl1.0 with a change to choice of
law : the license is governed by the laws of France . The library is
;; distributed under lgpl2.0.
(license (list qpl lgpl2.0))))
(define-public opam
(package
(name "opam")
(version "1.1.1")
(source (origin
(method url-fetch)
Use the ' -full ' version , which includes all the dependencies .
(uri (string-append
"/"
version "/opam-full-" version ".tar.gz")
;; (string-append "/"
;; version ".tar.gz")
)
(sha256
(base32
"1frzqkx6yn1pnyd9qz3bv3rbwv74bmc1xji8kl41r1dkqzfl3xqv"))))
(build-system gnu-build-system)
(arguments
'(;; Sometimes, 'make -jX' would fail right after ./configure with
;; "Fatal error: exception End_of_file".
#:parallel-build? #f
;; For some reason, 'ocp-build' needs $TERM to be set.
#:make-flags '("TERM=screen")
#:test-target "tests"
;; FIXME: There's an obscure test failure:
… /_obuild / opam / opam.asm install P1 ' failed .
#:tests? #f
#:phases (alist-cons-before
'build 'pre-build
(lambda* (#:key inputs #:allow-other-keys)
(let ((bash (assoc-ref inputs "bash")))
(substitute* "src/core/opamSystem.ml"
(("\"/bin/sh\"")
(string-append "\"" bash "/bin/sh\"")))))
(alist-cons-before
'check 'pre-check
(lambda _
(setenv "HOME" (getcwd))
(and (system "git config --global user.email ")
(system "git config --global user.name Guix")))
%standard-phases))))
(native-inputs
`(("git" ,git) ;for the tests
("python" ,python))) ;for the tests
(inputs
`(("ocaml" ,ocaml)
("ncurses" ,ncurses)
("curl" ,curl)))
(home-page "/")
(synopsis "Package manager for OCaml")
(description
"OPAM is a tool to manage OCaml packages. It supports multiple
simultaneous compiler installations, flexible package constraints, and a
Git-friendly development workflow.")
The ' LICENSE ' file waives some requirements compared to LGPLv3 .
(license lgpl3)))
(define-public camlp4
(package
(name "camlp4")
(version "4.02+6")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.gz"))
(sha256
(base32
"0icdfzhsbgf89925gc8gl3fm8z2xzszzlib0v9dj5wyzkyv3a342"))
(file-name (string-append name "-" version ".tar.gz"))))
(build-system gnu-build-system)
(native-inputs `(("ocaml" ,ocaml)
("which" ,which)))
(inputs `(("ocaml" ,ocaml)))
(arguments
'(#:tests? #f ;no documented test target
#:phases (modify-phases %standard-phases
(replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
;; This is a home-made 'configure' script.
(let ((out (assoc-ref outputs "out")))
(zero? (system* "./configure"
(string-append "--libdir=" out "/lib")
(string-append "--bindir=" out "/bin")
(string-append "--pkgdir=" out)))))))))
(home-page "")
(synopsis "Write parsers in OCaml")
(description
"Camlp4 is a software system for writing extensible parsers for
programming languages. It provides a set of OCaml libraries that are used to
define grammars as well as loadable syntax extensions of such grammars.
Camlp4 stands for Caml Preprocessor and Pretty-Printer and one of its most
important applications is the definition of domain-specific extensions of the
syntax of OCaml.")
;; This is LGPLv2 with an exception that allows packages statically-linked
;; against the library to be released under any terms.
(license lgpl2.0)))
(define-public camlp5
(package
(name "camlp5")
(version "6.14")
(source (origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tgz"))
(sha256
(base32
"1ql04iyvclpyy9805kpddc4ndjb5d0qg4shhi2fc6bixi49fvy89"))))
(build-system gnu-build-system)
(inputs
`(("ocaml" ,ocaml)))
(arguments
`(#:tests? #f ; XXX TODO figure out how to run the tests
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(mandir (string-append out "/share/man")))
;; Custom configure script doesn't recognize
;; --prefix=<PREFIX> syntax (with equals sign).
(zero? (system* "./configure"
"--prefix" out
"--mandir" mandir)))))
(replace 'build
(lambda _
(zero? (system* "make" "-j" (number->string
(parallel-job-count))
"world.opt")))))))
(home-page "/")
(synopsis "Pre-processor Pretty Printer for OCaml")
(description
"Camlp5 is a Pre-Processor-Pretty-Printer for Objective Caml. It offers
tools for syntax (Stream Parsers and Grammars) and the ability to modify the
concrete syntax of the language (Quotations, Syntax Extensions).")
;; Most files are distributed under bsd-3, but ocaml_stuff/* is under qpl.
(license (list bsd-3 qpl))))
(define-public hevea
(package
(name "hevea")
(version "2.28")
(source (origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.gz"))
(sha256
(base32
"14fns13wlnpiv9i05841kvi3cq4b9v2sw5x3ff6ziws28q701qnd"))))
(build-system gnu-build-system)
(inputs
`(("ocaml" ,ocaml)))
(arguments
`(#:tests? #f ; no test suite
#:make-flags (list (string-append "PREFIX=" %output))
#:phases (modify-phases %standard-phases
(delete 'configure)
(add-before 'build 'patch-/bin/sh
(lambda _
(substitute* "_tags"
(("/bin/sh") (which "sh")))
#t)))))
(home-page "/")
(synopsis "LaTeX to HTML translator")
(description
"HeVeA is a LaTeX to HTML translator that generates modern HTML 5. It is
written in Objective Caml.")
(license qpl)))
(define-public coq
(package
(name "coq")
(version "8.4pl6")
(source (origin
(method url-fetch)
(uri (string-append "" version
"/files/" name "-" version ".tar.gz"))
(sha256
(base32
"1mpbj4yf36kpjg2v2sln12i8dzqn8rag6fd07hslj2lpm4qs4h55"))))
(build-system gnu-build-system)
(native-inputs
`(("texlive" ,texlive)
("hevea" ,hevea)))
(inputs
`(("ocaml" ,ocaml)
("camlp5" ,camlp5)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(mandir (string-append out "/share/man"))
(browser "icecat -remote \"OpenURL(%s,new-tab)\""))
(zero? (system* "./configure"
"--prefix" out
"--mandir" mandir
"--browser" browser)))))
(replace 'build
(lambda _
(zero? (system* "make" "-j" (number->string
(parallel-job-count))
"world"))))
(delete 'check)
(add-after 'install 'check
(lambda _
(with-directory-excursion "test-suite"
(zero? (system* "make"))))))))
(home-page "")
(synopsis "Proof assistant for higher-order logic")
(description
"Coq is a proof assistant for higher-order logic, which allows the
development of computer programs consistent with their formal specification.
It is developed using Objective Caml and Camlp5.")
;; The code is distributed under lgpl2.1.
;; Some of the documentation is distributed under opl1.0+.
(license (list lgpl2.1 opl1.0+))))
(define-public proof-general
(package
(name "proof-general")
(version "4.2")
(source (origin
(method url-fetch)
(uri (string-append
"/"
"ProofGeneral-" version ".tgz"))
(sha256
(base32
"09qb0myq66fw17v4ziz401ilsb5xlxz1nl2wsp69d0vrfy0bcrrm"))))
(build-system gnu-build-system)
(native-inputs
`(("which" ,which)
("emacs" ,emacs-no-x)
("texinfo" ,texinfo)))
(inputs
`(("host-emacs" ,emacs)
("perl" ,perl)
("coq" ,coq)))
(arguments
`(#:tests? #f ; no check target
#:make-flags (list (string-append "PREFIX=" %output)
(string-append "DEST_PREFIX=" %output))
#:modules ((guix build gnu-build-system)
(guix build utils)
(guix build emacs-utils))
#:imported-modules (,@%gnu-build-system-modules
(guix build emacs-utils))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'disable-byte-compile-error-on-warn
(lambda _
(substitute* "Makefile"
(("\\(setq byte-compile-error-on-warn t\\)")
"(setq byte-compile-error-on-warn nil)"))
#t))
(add-after 'unpack 'patch-hardcoded-paths
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(coq (assoc-ref inputs "coq"))
(emacs (assoc-ref inputs "host-emacs")))
(define (coq-prog name)
(string-append coq "/bin/" name))
(emacs-substitute-variables "coq/coq.el"
("coq-prog-name" (coq-prog "coqtop"))
("coq-compiler" (coq-prog "coqc"))
("coq-dependency-analyzer" (coq-prog "coqdep")))
(substitute* "Makefile"
(("/sbin/install-info") "install-info"))
(substitute* "bin/proofgeneral"
(("^PGHOMEDEFAULT=.*" all)
(string-append all
"PGHOME=$PGHOMEDEFAULT\n"
"EMACS=" emacs "/bin/emacs")))
#t)))
(add-after 'unpack 'clean
(lambda _
Delete the pre - compiled elc files for Emacs 23 .
(zero? (system* "make" "clean"))))
(add-after 'install 'install-doc
(lambda* (#:key make-flags #:allow-other-keys)
;; XXX FIXME avoid building/installing pdf files,
;; due to unresolved errors building them.
(substitute* "Makefile"
((" [^ ]*\\.pdf") ""))
(zero? (apply system* "make" "install-doc"
make-flags)))))))
(home-page "/")
(synopsis "Generic front-end for proof assistants based on Emacs")
(description
"Proof General is a major mode to turn Emacs into an interactive proof
assistant to write formal mathematical proofs using a variety of theorem
provers.")
(license gpl2+)))
(define-public lablgtk
(package
(name "lablgtk")
(version "2.18.3")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"1479/lablgtk-2.18.3.tar.gz"))
(sha256
(base32
"1bybn3jafxf4cx25zvn8h2xj9agn1xjbn7j3ywxxqx6az7rfnnwp"))))
(build-system gnu-build-system)
(native-inputs
`(("camlp4" ,camlp4)
("ocaml" ,ocaml)
("pkg-config" ,pkg-config)))
;; FIXME: Add inputs gtkgl-2.0, libpanelapplet-2.0, gtkspell-2.0,
;; and gtk+-quartz-2.0 once available.
(inputs
`(("gtk+" ,gtk+-2)
("gtksourceview" ,gtksourceview-2)
("libgnomecanvas" ,libgnomecanvas)
("libgnomeui" ,libgnomeui)
("libglade" ,libglade)
("librsvg" ,librsvg)))
(arguments
`(#:tests? #f ; no check target
;; opt: also install cmxa files
#:make-flags (list "all" "opt")
Occasionally we would get " Error : Unbound module GtkThread " when
;; compiling 'gtkThInit.ml', with 'make -j'. So build sequentially.
#:parallel-build? #f
#:phases
(modify-phases %standard-phases
(replace 'install
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(ocaml (assoc-ref inputs "ocaml")))
;; Install into the output and not the ocaml directory.
(substitute* "config.make"
((ocaml) out))
(system* "make" "old-install")
#t))))))
(home-page "/")
(synopsis "GTK+ bindings for OCaml")
(description
"LablGtk is an OCaml interface to GTK+ 1.2 and 2.x. It provides
a strongly-typed object-oriented interface that is compatible with the
dynamic typing of GTK+. Most widgets and methods are available. LablGtk
also provides bindings to
gdk-pixbuf, the GLArea widget (in combination with LablGL), gnomecanvas,
gnomeui, gtksourceview, gtkspell,
libglade (and it an generate OCaml code from .glade files),
libpanel, librsvg and quartz.")
(license lgpl2.1)))
(define-public unison
(package
(name "unison")
(version "2.48.3")
(source
(origin
(method svn-fetch)
(uri (svn-reference
(url (string-append "/"
"unison/branches/"
(version-major+minor version)))
(revision 535)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"0486s53wyayicj9f2raj2dvwvk4xyzar219rccc1iczdwixm4x05"))
(modules '((guix build utils)
(ice-9 rdelim)
(ice-9 regex)
(srfi srfi-1)))
(snippet
`(begin
;; The svn revision in the release tarball appears to be
;; artificially manipulated in order to set the desired point
;; version number. Because the point version is calculated during
;; the build, we can offset pointVersionOrigin by the desired
;; point version and write that into "Rev: %d". We do this rather
;; than hardcoding the necessary revision number, for
;; maintainability.
(with-atomic-file-replacement "src/mkProjectInfo.ml"
(lambda (in out)
(let ((pt-ver (string->number (third (string-split ,version #\.))))
(pt-rx (make-regexp "^let pointVersionOrigin = ([0-9]+)"))
(rev-rx (make-regexp "Rev: [0-9]+")))
(let loop ((pt-origin #f))
(let ((line (read-line in 'concat)))
(cond
((regexp-exec pt-rx line)
=> (lambda (m)
(display line out)
(loop (string->number (match:substring m 1)))))
((regexp-exec rev-rx line)
=> (lambda (m)
(format out "~aRev: ~d~a"
(match:prefix m)
(+ pt-origin pt-ver)
(match:suffix m))
(dump-port in out))) ;done
(else
(display line out)
(loop pt-origin))))))))
;; Without the '-fix' argument, the html file produced does not
;; have functioning internal hyperlinks.
(substitute* "doc/Makefile"
(("hevea unison") "hevea -fix unison"))))))
(build-system gnu-build-system)
(outputs '("out"
1.9 MiB of documentation
(native-inputs
`(("ocaml" ,ocaml)
;; For documentation
("ghostscript" ,ghostscript)
("texlive" ,texlive)
("hevea" ,hevea)
("lynx" ,lynx)))
(arguments
`(#:parallel-build? #f
#:parallel-tests? #f
#:test-target "selftest"
#:tests? #f ; Tests require writing to $HOME.
; If some $HOME is provided, they fail with the message
; "Fatal error: Skipping some tests -- remove me!"
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-before 'install 'prepare-install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(mkdir-p bin)
(setenv "HOME" out) ; forces correct INSTALLDIR in Makefile
#t)))
(add-after 'install 'install-doc
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((doc (string-append (assoc-ref outputs "doc")
"/share/doc/unison")))
(mkdir-p doc)
;; This file needs write-permissions, because it's
;; overwritten by 'docs' during documentation generation.
(chmod "src/strings.ml" #o600)
(and (zero? (system* "make" "docs"
"TEXDIRECTIVES=\\\\draftfalse"))
(begin
(for-each (lambda (f)
(install-file f doc))
(map (lambda (ext)
(string-append
"doc/unison-manual." ext))
;; Install only html documentation,
;; since the build is currently
non - reproducible with the ps , pdf ,
;; and dvi docs.
'(;;"ps" "pdf" "dvi"
"html")))
#t))))))))
(home-page "/~bcpierce/unison/")
(synopsis "File synchronizer")
(description
"Unison is a file-synchronization tool. It allows two replicas of
a collection of files and directories to be stored on different hosts
(or different disks on the same host), modified separately, and then
brought up to date by propagating the changes in each replica
to the other.")
(license gpl3+)))
(define-public ocaml-findlib
(package
(name "ocaml-findlib")
(version "1.6.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
"findlib" "-" version ".tar.gz"))
(sha256
(base32
"02abg1lsnwvjg3igdyb8qjgr5kv1nbwl4gaf8mdinzfii5p82721"))
(patches
(list (search-patch "ocaml-findlib-make-install.patch")))))
(build-system gnu-build-system)
(native-inputs
`(("camlp4" ,camlp4)
("m4" ,m4)
("ocaml" ,ocaml)))
(arguments
`(#:tests? #f ; no test suite
#:parallel-build? #f
#:make-flags (list "all" "opt")
#:phases (modify-phases %standard-phases
(replace
'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(system*
"./configure"
"-bindir" (string-append out "/bin")
"-config" (string-append out "/etc/ocamfind.conf")
"-mandir" (string-append out "/share/man")
"-sitelib" (string-append out "/lib/ocaml/site-lib")
"-with-toolbox")))))))
(home-page "")
(synopsis "Management tool for OCaml libraries")
(description
"The \"findlib\" library provides a scheme to manage reusable software
components (packages), and includes tools that support this scheme. Packages
are collections of OCaml modules for which metainformation can be stored. The
packages are kept in the filesystem hierarchy, but with strict directory
structure. The library contains functions to look the directory up that
stores a package, to query metainformation about a package, and to retrieve
dependency information about multiple packages. There is also a tool that
allows the user to enter queries on the command-line. In order to simplify
compilation and linkage, there are new frontends of the various OCaml
compilers that can directly deal with packages.")
(license x11)))
| null | https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/gnu/packages/ocaml.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
For libiberty, needed for objdump support.
also needed for objdump support
Custom configure script doesn't recognize
--prefix=<PREFIX> syntax (with equals sign).
The compiler is distributed under qpl1.0 with a change to choice of
distributed under lgpl2.0.
(string-append "/"
version ".tar.gz")
Sometimes, 'make -jX' would fail right after ./configure with
"Fatal error: exception End_of_file".
For some reason, 'ocp-build' needs $TERM to be set.
FIXME: There's an obscure test failure:
for the tests
for the tests
no documented test target
This is a home-made 'configure' script.
This is LGPLv2 with an exception that allows packages statically-linked
against the library to be released under any terms.
XXX TODO figure out how to run the tests
Custom configure script doesn't recognize
--prefix=<PREFIX> syntax (with equals sign).
Most files are distributed under bsd-3, but ocaml_stuff/* is under qpl.
no test suite
The code is distributed under lgpl2.1.
Some of the documentation is distributed under opl1.0+.
no check target
XXX FIXME avoid building/installing pdf files,
due to unresolved errors building them.
FIXME: Add inputs gtkgl-2.0, libpanelapplet-2.0, gtkspell-2.0,
and gtk+-quartz-2.0 once available.
no check target
opt: also install cmxa files
compiling 'gtkThInit.ml', with 'make -j'. So build sequentially.
Install into the output and not the ocaml directory.
The svn revision in the release tarball appears to be
artificially manipulated in order to set the desired point
version number. Because the point version is calculated during
the build, we can offset pointVersionOrigin by the desired
point version and write that into "Rev: %d". We do this rather
than hardcoding the necessary revision number, for
maintainability.
done
Without the '-fix' argument, the html file produced does not
have functioning internal hyperlinks.
For documentation
Tests require writing to $HOME.
If some $HOME is provided, they fail with the message
"Fatal error: Skipping some tests -- remove me!"
forces correct INSTALLDIR in Makefile
This file needs write-permissions, because it's
overwritten by 'docs' during documentation generation.
Install only html documentation,
since the build is currently
and dvi docs.
"ps" "pdf" "dvi"
no test suite | Copyright © 2013 < >
Copyright © 2014 , 2015 < >
Copyright © 2015 < >
Copyright © 2015 < >
Copyright © 2016 < >
Copyright © 2016 Jan Nieuwenhuizen < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages ocaml)
#:use-module ((guix licenses) #:hide (zlib))
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix svn-download)
#:use-module (guix utils)
#:use-module (guix build-system gnu)
#:use-module (gnu packages)
#:use-module (gnu packages gcc)
#:use-module (gnu packages gnome)
#:use-module (gnu packages gtk)
#:use-module (gnu packages base)
#:use-module (gnu packages emacs)
#:use-module (gnu packages texinfo)
#:use-module (gnu packages pkg-config)
#:use-module (gnu packages compression)
#:use-module (gnu packages xorg)
#:use-module (gnu packages texlive)
#:use-module (gnu packages ghostscript)
#:use-module (gnu packages lynx)
#:use-module (gnu packages perl)
#:use-module (gnu packages python)
#:use-module (gnu packages m4)
#:use-module (gnu packages ncurses)
#:use-module (gnu packages version-control)
#:use-module (gnu packages curl))
(define-public ocaml
(package
(name "ocaml")
(version "4.02.3")
(source (origin
(method url-fetch)
(uri (string-append
"-"
(version-major+minor version)
"/ocaml-" version ".tar.xz"))
(sha256
(base32
"1qwwvy8nzd87hk8rd9sm667nppakiapnx4ypdwcrlnav2dz6kil3"))))
(build-system gnu-build-system)
(native-search-paths
(list (search-path-specification
(variable "OCAMLPATH")
(files (list (string-append "lib/ocaml"))))))
(native-inputs
`(("perl" ,perl)
("pkg-config" ,pkg-config)))
(inputs
`(("libx11" ,libx11)
("gcc:lib" ,(canonical-package gcc-4.9) "lib")
(arguments
`(#:modules ((guix build gnu-build-system)
(guix build utils)
(web server))
#:phases
(modify-phases %standard-phases
(add-after 'unpack 'patch-/bin/sh-references
(lambda* (#:key inputs #:allow-other-keys)
(let* ((sh (string-append (assoc-ref inputs "bash")
"/bin/sh"))
(quoted-sh (string-append "\"" sh "\"")))
(with-fluids ((%default-port-encoding #f))
(for-each (lambda (file)
(substitute* file
(("\"/bin/sh\"")
(begin
(format (current-error-port) "\
patch-/bin/sh-references: ~a: changing `\"/bin/sh\"' to `~a'~%"
file quoted-sh)
quoted-sh))))
(find-files "." "\\.ml$"))
#t))))
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(mandir (string-append out "/share/man")))
(zero? (system* "./configure"
"--prefix" out
"--mandir" mandir)))))
(replace 'build
(lambda _
(zero? (system* "make" "-j" (number->string
(parallel-job-count))
"world.opt"))))
(delete 'check)
(add-after 'install 'check
(lambda _
(with-directory-excursion "testsuite"
(zero? (system* "make" "all")))))
(add-before 'check 'prepare-socket-test
(lambda _
(format (current-error-port)
"Spawning local test web server on port 8080~%")
(when (zero? (primitive-fork))
(run-server (lambda (request request-body)
(values '((content-type . (text/plain)))
"Hello!"))
'http '(#:port 8080)))
(let ((file "testsuite/tests/lib-threads/testsocket.ml"))
(format (current-error-port)
"Patching ~a to use localhost port 8080~%"
file)
(substitute* file
(("caml.inria.fr") "localhost")
(("80") "8080")
(("HTTP1.0") "HTTP/1.0"))
#t))))))
(home-page "/")
(synopsis "The OCaml programming language")
(description
"OCaml is a general purpose industrial-strength programming language with
an emphasis on expressiveness and safety. Developed for more than 20 years at
Inria it benefits from one of the most advanced type systems and supports
functional, imperative and object-oriented styles of programming.")
law : the license is governed by the laws of France . The library is
(license (list qpl lgpl2.0))))
(define-public opam
(package
(name "opam")
(version "1.1.1")
(source (origin
(method url-fetch)
Use the ' -full ' version , which includes all the dependencies .
(uri (string-append
"/"
version "/opam-full-" version ".tar.gz")
)
(sha256
(base32
"1frzqkx6yn1pnyd9qz3bv3rbwv74bmc1xji8kl41r1dkqzfl3xqv"))))
(build-system gnu-build-system)
(arguments
#:parallel-build? #f
#:make-flags '("TERM=screen")
#:test-target "tests"
… /_obuild / opam / opam.asm install P1 ' failed .
#:tests? #f
#:phases (alist-cons-before
'build 'pre-build
(lambda* (#:key inputs #:allow-other-keys)
(let ((bash (assoc-ref inputs "bash")))
(substitute* "src/core/opamSystem.ml"
(("\"/bin/sh\"")
(string-append "\"" bash "/bin/sh\"")))))
(alist-cons-before
'check 'pre-check
(lambda _
(setenv "HOME" (getcwd))
(and (system "git config --global user.email ")
(system "git config --global user.name Guix")))
%standard-phases))))
(native-inputs
(inputs
`(("ocaml" ,ocaml)
("ncurses" ,ncurses)
("curl" ,curl)))
(home-page "/")
(synopsis "Package manager for OCaml")
(description
"OPAM is a tool to manage OCaml packages. It supports multiple
simultaneous compiler installations, flexible package constraints, and a
Git-friendly development workflow.")
The ' LICENSE ' file waives some requirements compared to LGPLv3 .
(license lgpl3)))
(define-public camlp4
(package
(name "camlp4")
(version "4.02+6")
(source (origin
(method url-fetch)
(uri (string-append "/"
version ".tar.gz"))
(sha256
(base32
"0icdfzhsbgf89925gc8gl3fm8z2xzszzlib0v9dj5wyzkyv3a342"))
(file-name (string-append name "-" version ".tar.gz"))))
(build-system gnu-build-system)
(native-inputs `(("ocaml" ,ocaml)
("which" ,which)))
(inputs `(("ocaml" ,ocaml)))
(arguments
#:phases (modify-phases %standard-phases
(replace
'configure
(lambda* (#:key outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(zero? (system* "./configure"
(string-append "--libdir=" out "/lib")
(string-append "--bindir=" out "/bin")
(string-append "--pkgdir=" out)))))))))
(home-page "")
(synopsis "Write parsers in OCaml")
(description
"Camlp4 is a software system for writing extensible parsers for
programming languages. It provides a set of OCaml libraries that are used to
define grammars as well as loadable syntax extensions of such grammars.
Camlp4 stands for Caml Preprocessor and Pretty-Printer and one of its most
important applications is the definition of domain-specific extensions of the
syntax of OCaml.")
(license lgpl2.0)))
(define-public camlp5
(package
(name "camlp5")
(version "6.14")
(source (origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tgz"))
(sha256
(base32
"1ql04iyvclpyy9805kpddc4ndjb5d0qg4shhi2fc6bixi49fvy89"))))
(build-system gnu-build-system)
(inputs
`(("ocaml" ,ocaml)))
(arguments
#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(mandir (string-append out "/share/man")))
(zero? (system* "./configure"
"--prefix" out
"--mandir" mandir)))))
(replace 'build
(lambda _
(zero? (system* "make" "-j" (number->string
(parallel-job-count))
"world.opt")))))))
(home-page "/")
(synopsis "Pre-processor Pretty Printer for OCaml")
(description
"Camlp5 is a Pre-Processor-Pretty-Printer for Objective Caml. It offers
tools for syntax (Stream Parsers and Grammars) and the ability to modify the
concrete syntax of the language (Quotations, Syntax Extensions).")
(license (list bsd-3 qpl))))
(define-public hevea
(package
(name "hevea")
(version "2.28")
(source (origin
(method url-fetch)
(uri (string-append "/"
name "-" version ".tar.gz"))
(sha256
(base32
"14fns13wlnpiv9i05841kvi3cq4b9v2sw5x3ff6ziws28q701qnd"))))
(build-system gnu-build-system)
(inputs
`(("ocaml" ,ocaml)))
(arguments
#:make-flags (list (string-append "PREFIX=" %output))
#:phases (modify-phases %standard-phases
(delete 'configure)
(add-before 'build 'patch-/bin/sh
(lambda _
(substitute* "_tags"
(("/bin/sh") (which "sh")))
#t)))))
(home-page "/")
(synopsis "LaTeX to HTML translator")
(description
"HeVeA is a LaTeX to HTML translator that generates modern HTML 5. It is
written in Objective Caml.")
(license qpl)))
(define-public coq
(package
(name "coq")
(version "8.4pl6")
(source (origin
(method url-fetch)
(uri (string-append "" version
"/files/" name "-" version ".tar.gz"))
(sha256
(base32
"1mpbj4yf36kpjg2v2sln12i8dzqn8rag6fd07hslj2lpm4qs4h55"))))
(build-system gnu-build-system)
(native-inputs
`(("texlive" ,texlive)
("hevea" ,hevea)))
(inputs
`(("ocaml" ,ocaml)
("camlp5" ,camlp5)))
(arguments
`(#:phases
(modify-phases %standard-phases
(replace 'configure
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(mandir (string-append out "/share/man"))
(browser "icecat -remote \"OpenURL(%s,new-tab)\""))
(zero? (system* "./configure"
"--prefix" out
"--mandir" mandir
"--browser" browser)))))
(replace 'build
(lambda _
(zero? (system* "make" "-j" (number->string
(parallel-job-count))
"world"))))
(delete 'check)
(add-after 'install 'check
(lambda _
(with-directory-excursion "test-suite"
(zero? (system* "make"))))))))
(home-page "")
(synopsis "Proof assistant for higher-order logic")
(description
"Coq is a proof assistant for higher-order logic, which allows the
development of computer programs consistent with their formal specification.
It is developed using Objective Caml and Camlp5.")
(license (list lgpl2.1 opl1.0+))))
(define-public proof-general
(package
(name "proof-general")
(version "4.2")
(source (origin
(method url-fetch)
(uri (string-append
"/"
"ProofGeneral-" version ".tgz"))
(sha256
(base32
"09qb0myq66fw17v4ziz401ilsb5xlxz1nl2wsp69d0vrfy0bcrrm"))))
(build-system gnu-build-system)
(native-inputs
`(("which" ,which)
("emacs" ,emacs-no-x)
("texinfo" ,texinfo)))
(inputs
`(("host-emacs" ,emacs)
("perl" ,perl)
("coq" ,coq)))
(arguments
#:make-flags (list (string-append "PREFIX=" %output)
(string-append "DEST_PREFIX=" %output))
#:modules ((guix build gnu-build-system)
(guix build utils)
(guix build emacs-utils))
#:imported-modules (,@%gnu-build-system-modules
(guix build emacs-utils))
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-after 'unpack 'disable-byte-compile-error-on-warn
(lambda _
(substitute* "Makefile"
(("\\(setq byte-compile-error-on-warn t\\)")
"(setq byte-compile-error-on-warn nil)"))
#t))
(add-after 'unpack 'patch-hardcoded-paths
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(coq (assoc-ref inputs "coq"))
(emacs (assoc-ref inputs "host-emacs")))
(define (coq-prog name)
(string-append coq "/bin/" name))
(emacs-substitute-variables "coq/coq.el"
("coq-prog-name" (coq-prog "coqtop"))
("coq-compiler" (coq-prog "coqc"))
("coq-dependency-analyzer" (coq-prog "coqdep")))
(substitute* "Makefile"
(("/sbin/install-info") "install-info"))
(substitute* "bin/proofgeneral"
(("^PGHOMEDEFAULT=.*" all)
(string-append all
"PGHOME=$PGHOMEDEFAULT\n"
"EMACS=" emacs "/bin/emacs")))
#t)))
(add-after 'unpack 'clean
(lambda _
Delete the pre - compiled elc files for Emacs 23 .
(zero? (system* "make" "clean"))))
(add-after 'install 'install-doc
(lambda* (#:key make-flags #:allow-other-keys)
(substitute* "Makefile"
((" [^ ]*\\.pdf") ""))
(zero? (apply system* "make" "install-doc"
make-flags)))))))
(home-page "/")
(synopsis "Generic front-end for proof assistants based on Emacs")
(description
"Proof General is a major mode to turn Emacs into an interactive proof
assistant to write formal mathematical proofs using a variety of theorem
provers.")
(license gpl2+)))
(define-public lablgtk
(package
(name "lablgtk")
(version "2.18.3")
(source
(origin
(method url-fetch)
(uri (string-append "/"
"1479/lablgtk-2.18.3.tar.gz"))
(sha256
(base32
"1bybn3jafxf4cx25zvn8h2xj9agn1xjbn7j3ywxxqx6az7rfnnwp"))))
(build-system gnu-build-system)
(native-inputs
`(("camlp4" ,camlp4)
("ocaml" ,ocaml)
("pkg-config" ,pkg-config)))
(inputs
`(("gtk+" ,gtk+-2)
("gtksourceview" ,gtksourceview-2)
("libgnomecanvas" ,libgnomecanvas)
("libgnomeui" ,libgnomeui)
("libglade" ,libglade)
("librsvg" ,librsvg)))
(arguments
#:make-flags (list "all" "opt")
Occasionally we would get " Error : Unbound module GtkThread " when
#:parallel-build? #f
#:phases
(modify-phases %standard-phases
(replace 'install
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out"))
(ocaml (assoc-ref inputs "ocaml")))
(substitute* "config.make"
((ocaml) out))
(system* "make" "old-install")
#t))))))
(home-page "/")
(synopsis "GTK+ bindings for OCaml")
(description
"LablGtk is an OCaml interface to GTK+ 1.2 and 2.x. It provides
a strongly-typed object-oriented interface that is compatible with the
dynamic typing of GTK+. Most widgets and methods are available. LablGtk
also provides bindings to
gdk-pixbuf, the GLArea widget (in combination with LablGL), gnomecanvas,
gnomeui, gtksourceview, gtkspell,
libglade (and it an generate OCaml code from .glade files),
libpanel, librsvg and quartz.")
(license lgpl2.1)))
(define-public unison
(package
(name "unison")
(version "2.48.3")
(source
(origin
(method svn-fetch)
(uri (svn-reference
(url (string-append "/"
"unison/branches/"
(version-major+minor version)))
(revision 535)))
(file-name (string-append name "-" version "-checkout"))
(sha256
(base32
"0486s53wyayicj9f2raj2dvwvk4xyzar219rccc1iczdwixm4x05"))
(modules '((guix build utils)
(ice-9 rdelim)
(ice-9 regex)
(srfi srfi-1)))
(snippet
`(begin
(with-atomic-file-replacement "src/mkProjectInfo.ml"
(lambda (in out)
(let ((pt-ver (string->number (third (string-split ,version #\.))))
(pt-rx (make-regexp "^let pointVersionOrigin = ([0-9]+)"))
(rev-rx (make-regexp "Rev: [0-9]+")))
(let loop ((pt-origin #f))
(let ((line (read-line in 'concat)))
(cond
((regexp-exec pt-rx line)
=> (lambda (m)
(display line out)
(loop (string->number (match:substring m 1)))))
((regexp-exec rev-rx line)
=> (lambda (m)
(format out "~aRev: ~d~a"
(match:prefix m)
(+ pt-origin pt-ver)
(match:suffix m))
(else
(display line out)
(loop pt-origin))))))))
(substitute* "doc/Makefile"
(("hevea unison") "hevea -fix unison"))))))
(build-system gnu-build-system)
(outputs '("out"
1.9 MiB of documentation
(native-inputs
`(("ocaml" ,ocaml)
("ghostscript" ,ghostscript)
("texlive" ,texlive)
("hevea" ,hevea)
("lynx" ,lynx)))
(arguments
`(#:parallel-build? #f
#:parallel-tests? #f
#:test-target "selftest"
#:phases
(modify-phases %standard-phases
(delete 'configure)
(add-before 'install 'prepare-install
(lambda* (#:key outputs #:allow-other-keys)
(let* ((out (assoc-ref outputs "out"))
(bin (string-append out "/bin")))
(mkdir-p bin)
#t)))
(add-after 'install 'install-doc
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((doc (string-append (assoc-ref outputs "doc")
"/share/doc/unison")))
(mkdir-p doc)
(chmod "src/strings.ml" #o600)
(and (zero? (system* "make" "docs"
"TEXDIRECTIVES=\\\\draftfalse"))
(begin
(for-each (lambda (f)
(install-file f doc))
(map (lambda (ext)
(string-append
"doc/unison-manual." ext))
non - reproducible with the ps , pdf ,
"html")))
#t))))))))
(home-page "/~bcpierce/unison/")
(synopsis "File synchronizer")
(description
"Unison is a file-synchronization tool. It allows two replicas of
a collection of files and directories to be stored on different hosts
(or different disks on the same host), modified separately, and then
brought up to date by propagating the changes in each replica
to the other.")
(license gpl3+)))
(define-public ocaml-findlib
(package
(name "ocaml-findlib")
(version "1.6.1")
(source (origin
(method url-fetch)
(uri (string-append "/"
"findlib" "-" version ".tar.gz"))
(sha256
(base32
"02abg1lsnwvjg3igdyb8qjgr5kv1nbwl4gaf8mdinzfii5p82721"))
(patches
(list (search-patch "ocaml-findlib-make-install.patch")))))
(build-system gnu-build-system)
(native-inputs
`(("camlp4" ,camlp4)
("m4" ,m4)
("ocaml" ,ocaml)))
(arguments
#:parallel-build? #f
#:make-flags (list "all" "opt")
#:phases (modify-phases %standard-phases
(replace
'configure
(lambda* (#:key inputs outputs #:allow-other-keys)
(let ((out (assoc-ref outputs "out")))
(system*
"./configure"
"-bindir" (string-append out "/bin")
"-config" (string-append out "/etc/ocamfind.conf")
"-mandir" (string-append out "/share/man")
"-sitelib" (string-append out "/lib/ocaml/site-lib")
"-with-toolbox")))))))
(home-page "")
(synopsis "Management tool for OCaml libraries")
(description
"The \"findlib\" library provides a scheme to manage reusable software
components (packages), and includes tools that support this scheme. Packages
are collections of OCaml modules for which metainformation can be stored. The
packages are kept in the filesystem hierarchy, but with strict directory
structure. The library contains functions to look the directory up that
stores a package, to query metainformation about a package, and to retrieve
dependency information about multiple packages. There is also a tool that
allows the user to enter queries on the command-line. In order to simplify
compilation and linkage, there are new frontends of the various OCaml
compilers that can directly deal with packages.")
(license x11)))
|
2aa532054d5046b91c527795f298b2411ee148db75c90da65783f8f37724d8f5 | tisnik/clojure-examples | project.clj | ;
( C ) Copyright 2018 , 2020 , 2021
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the Eclipse Public License v1.0
; which accompanies this distribution, and is available at
-v10.html
;
; Contributors:
;
(defproject cucumber+expect8 "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.1"]
[expectations "2.0.9"]]
:plugins [[lein-codox "0.10.7"]
[test2junit "1.1.0"]
[ lein - test - out " 0.3.1 " ]
[lein-cloverage "1.0.7-SNAPSHOT"]
[lein-kibit "0.1.8"]
[lein-clean-m2 "0.1.2"]
[lein-project-edn "0.3.0"]
[lein-marginalia "0.9.1"]
[com.siili/lein-cucumber "1.0.7"]
[lein-expectations "0.0.8"]]
:cucumber-feature-paths ["features/"]
:target-path "target/%s"
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[com.siili/lein-cucumber "1.0.7"]]}})
| null | https://raw.githubusercontent.com/tisnik/clojure-examples/78061b533c0755d0165002961334bbe98d994087/cucumber%2Bexpect8/project.clj | clojure |
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
Contributors:
| ( C ) Copyright 2018 , 2020 , 2021
-v10.html
(defproject cucumber+expect8 "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.10.1"]
[expectations "2.0.9"]]
:plugins [[lein-codox "0.10.7"]
[test2junit "1.1.0"]
[ lein - test - out " 0.3.1 " ]
[lein-cloverage "1.0.7-SNAPSHOT"]
[lein-kibit "0.1.8"]
[lein-clean-m2 "0.1.2"]
[lein-project-edn "0.3.0"]
[lein-marginalia "0.9.1"]
[com.siili/lein-cucumber "1.0.7"]
[lein-expectations "0.0.8"]]
:cucumber-feature-paths ["features/"]
:target-path "target/%s"
:profiles {:uberjar {:aot :all}
:dev {:dependencies [[com.siili/lein-cucumber "1.0.7"]]}})
|
f8fa4351f41e68ed8b6148c2536e0b0b79c4a357d1b6784ce04dd0b190011025 | MaskRay/OJHaskell | 53.hs | prob53 n = loop 0 [1] 0
where loop m l ans
| m > n = ans
| otherwise = loop (m+1) (zipWith (+) (0:l) $ reverse (0:l)) (ans + length (filter (> 1000000) l))
main = print . prob53 $ 100
| null | https://raw.githubusercontent.com/MaskRay/OJHaskell/ba24050b2480619f10daa7d37fca558182ba006c/Project%20Euler/53.hs | haskell | prob53 n = loop 0 [1] 0
where loop m l ans
| m > n = ans
| otherwise = loop (m+1) (zipWith (+) (0:l) $ reverse (0:l)) (ans + length (filter (> 1000000) l))
main = print . prob53 $ 100
|
|
b4489deab2668161fbb35bb7481e2e48dd4f29b09b4aadb30fc2cf908b36494d | Bogdanp/koyo | cors.rkt | #lang racket/base
(require koyo/cors
koyo/testing
rackunit
web-server/http)
(provide
cors-tests)
(define handler
(wrap-cors
(lambda (req)
(response/xexpr
#:headers (list (make-header #"X-Test" #"Custom"))
'(h1 "Hello")))))
(define cors-tests
(test-suite
"cors"
(test-suite
"wrap-cors"
(test-case "responds to all OPTIONS requests with a 200 OK and the appropriate CORS headers"
(define response
(handler (make-test-request #:method "OPTIONS")))
(check-equal? (response-code response) 200)
(check-equal? (response-headers response)
(list (make-header #"Content-Length" #"0")
(make-header #"Access-Control-Allow-Credentials" #"true")
(make-header #"Access-Control-Allow-Origin" #"")
(make-header #"Access-Control-Allow-Methods" #"HEAD,DELETE,GET,PATCH,POST,PUT,OPTIONS")
(make-header #"Access-Control-Allow-Headers" #"*")
(make-header #"Access-Control-Max-Age" #"86400"))))
(test-case "augments other requests with the appropriate CORS headers"
(define response
(handler (make-test-request)))
(check-equal? (response-code response) 200)
(check-equal? (response-headers response)
(list (make-header #"Access-Control-Allow-Origin" #"")
(make-header #"X-Test" #"Custom")))))))
(module+ test
(require rackunit/text-ui)
(run-tests cors-tests))
| null | https://raw.githubusercontent.com/Bogdanp/koyo/93f3fd06ee596a62bb0b286cb6290a800e911154/koyo-test/koyo/cors.rkt | racket | #lang racket/base
(require koyo/cors
koyo/testing
rackunit
web-server/http)
(provide
cors-tests)
(define handler
(wrap-cors
(lambda (req)
(response/xexpr
#:headers (list (make-header #"X-Test" #"Custom"))
'(h1 "Hello")))))
(define cors-tests
(test-suite
"cors"
(test-suite
"wrap-cors"
(test-case "responds to all OPTIONS requests with a 200 OK and the appropriate CORS headers"
(define response
(handler (make-test-request #:method "OPTIONS")))
(check-equal? (response-code response) 200)
(check-equal? (response-headers response)
(list (make-header #"Content-Length" #"0")
(make-header #"Access-Control-Allow-Credentials" #"true")
(make-header #"Access-Control-Allow-Origin" #"")
(make-header #"Access-Control-Allow-Methods" #"HEAD,DELETE,GET,PATCH,POST,PUT,OPTIONS")
(make-header #"Access-Control-Allow-Headers" #"*")
(make-header #"Access-Control-Max-Age" #"86400"))))
(test-case "augments other requests with the appropriate CORS headers"
(define response
(handler (make-test-request)))
(check-equal? (response-code response) 200)
(check-equal? (response-headers response)
(list (make-header #"Access-Control-Allow-Origin" #"")
(make-header #"X-Test" #"Custom")))))))
(module+ test
(require rackunit/text-ui)
(run-tests cors-tests))
|
|
e4d299f9b0a62b713535cde15a817ebf61cafcc27735e993f5885c6d552756a7 | eigenhombre/clj-org | util_test.clj | (ns clj-org.util-test
(:require [clojure.test :refer [are deftest is testing]]
[clj-org.test-util :refer [should=]]
[clj-org.util :refer :all]))
(deftest vec*-test
(are [inp expected]
(is (= expected (apply vec* inp)))
[:p ()] [:p]
[:p (range 4)] [:p 0 1 2 3]))
(defn- always [x] true)
(defn- never [x] false)
(defn- even-number? [x] (and (number? x) (even? x)))
(defn- odd-number? [x] (and (number? x) (odd? x)))
(defn- starts-w-nine? [x] (and (coll? x)
(number? (first x))
(not= 9 (first x))))
(defn- starts-w-pre? [x]
(and (coll? x) (not= (first x) :pre)))
(deftest selective-walk-test
(testing "changes values in a trivial tree"
(should= [2] (selective-walk inc always number? [1]))
(should= (type [2]) (type (selective-walk inc always number? [1])))
(should= [2 4 9] (selective-walk inc always number? [1 3 8]))
(should= [2 [4 1 [10 30]] 9]
(selective-walk inc always number? [1 [3 0 [9 29]] 8])))
(testing "allows me to specify when to transform"
(should= [1 3 9] (selective-walk inc always even-number? [1 3 8]))
(should= [2 [4 0 [10 30]] 8]
(selective-walk inc always odd-number? [1 [3 0 [9 29]] 8])))
(testing "allows me to specify when to descend"
(should= [2 [4 1 [9 29]] 9]
(selective-walk inc starts-w-nine? number? [1 [3 0 [9 29]] 8])))
(testing "allows me to avoid :pre sections of a hiccup parse tree"
(should= [:p "CAPS" [:pre "not caps"] "CAPS"]
(selective-walk clojure.string/upper-case starts-w-pre? string?
[:p "caps" [:pre "not caps"] "caps"])))
(testing "should directly transform toplevel form if asked to"
(should= "UPCASE"
(selective-walk clojure.string/upper-case
never
always
"upcase")))
(testing "shouldn't descend top form if I don't want it to"
(should= "locase"
(selective-walk clojure.string/upper-case
never
never
"locase"))))
(vec* :p ())
| null | https://raw.githubusercontent.com/eigenhombre/clj-org/46a1ead7ec28e931ff489c1d0b2b47d3d4a479be/test/clj_org/util_test.clj | clojure | (ns clj-org.util-test
(:require [clojure.test :refer [are deftest is testing]]
[clj-org.test-util :refer [should=]]
[clj-org.util :refer :all]))
(deftest vec*-test
(are [inp expected]
(is (= expected (apply vec* inp)))
[:p ()] [:p]
[:p (range 4)] [:p 0 1 2 3]))
(defn- always [x] true)
(defn- never [x] false)
(defn- even-number? [x] (and (number? x) (even? x)))
(defn- odd-number? [x] (and (number? x) (odd? x)))
(defn- starts-w-nine? [x] (and (coll? x)
(number? (first x))
(not= 9 (first x))))
(defn- starts-w-pre? [x]
(and (coll? x) (not= (first x) :pre)))
(deftest selective-walk-test
(testing "changes values in a trivial tree"
(should= [2] (selective-walk inc always number? [1]))
(should= (type [2]) (type (selective-walk inc always number? [1])))
(should= [2 4 9] (selective-walk inc always number? [1 3 8]))
(should= [2 [4 1 [10 30]] 9]
(selective-walk inc always number? [1 [3 0 [9 29]] 8])))
(testing "allows me to specify when to transform"
(should= [1 3 9] (selective-walk inc always even-number? [1 3 8]))
(should= [2 [4 0 [10 30]] 8]
(selective-walk inc always odd-number? [1 [3 0 [9 29]] 8])))
(testing "allows me to specify when to descend"
(should= [2 [4 1 [9 29]] 9]
(selective-walk inc starts-w-nine? number? [1 [3 0 [9 29]] 8])))
(testing "allows me to avoid :pre sections of a hiccup parse tree"
(should= [:p "CAPS" [:pre "not caps"] "CAPS"]
(selective-walk clojure.string/upper-case starts-w-pre? string?
[:p "caps" [:pre "not caps"] "caps"])))
(testing "should directly transform toplevel form if asked to"
(should= "UPCASE"
(selective-walk clojure.string/upper-case
never
always
"upcase")))
(testing "shouldn't descend top form if I don't want it to"
(should= "locase"
(selective-walk clojure.string/upper-case
never
never
"locase"))))
(vec* :p ())
|
|
45a8aef3de60cbb5b421e87a062ae1af3091b62acd3ebef659e83d60aeb6643e | andrejbauer/alg | cook.ml | (* A simple compiler from abstract syntax to the internal representation. *)
type env = {
const : (Theory.operation_name * Theory.operation) list ;
unary : (Theory.operation_name * Theory.operation) list ;
binary : (Theory.operation_name * Theory.operation) list ;
predicates : (Theory.relation_name * Theory.relation) list ;
relations : (Theory.relation_name * Theory.relation) list ;
}
let empty_env = { const = []; unary = []; binary = []; predicates = []; relations = []}
let fresh lst = 1 + List.fold_left (fun m (_,k) -> max m k) (-1) lst
let extend_const env c =
{ env with const = (c, fresh env.const) :: env.const }
let extend_unary env u =
{ env with unary = (u, fresh env.unary) :: env.unary }
let extend_binary env b =
{ env with binary = (b, fresh env.binary) :: env.binary }
let extend_predicate env p =
{ env with predicates = (p, fresh env.predicates) :: env.predicates }
let extend_relation env r =
{ env with relations = (r, fresh env.relations) :: env.relations }
let extend_var x vars =
let k = fresh vars in
(x,k) :: vars, k
let lookup_const {const=ec} x = Util.lookup x ec
let lookup_unary {unary=eu} x = Util.lookup x eu
let lookup_binary {binary=eb} x = Util.lookup x eb
let lookup_predicate {predicates=ep} x = Util.lookup x ep
let lookup_relation {relations=er} x = Util.lookup x er
let lookup_var vars x = Util.lookup x vars
let is_op {const=ec; unary=eu; binary=eb} x =
List.mem_assoc x ec || List.mem_assoc x eu || List.mem_assoc x eb
(* The free variables of a term, without repetitions. *)
let rec fv_term env (t, loc) =
match t with
| Input.Var x ->
if is_op env x then [] else [x]
| Input.UnaryOp (_, t) -> fv_term env t
| Input.BinaryOp (_, t1, t2) -> Util.union (fv_term env t1) (fv_term env t2)
(* The free variables of a formula, without repetitions. *)
let rec fv_formula env (f, loc) =
match f with
| Input.False -> []
| Input.True -> []
| Input.Equal (t1, t2)
| Input.NotEqual (t1, t2) ->
Util.union (fv_term env t1) (fv_term env t2)
| Input.UnaryPr (_, t) -> fv_term env t
| Input.BinaryPr (_, t1, t2) -> Util.union (fv_term env t1) (fv_term env t2)
| Input.Not f -> fv_formula env f
| Input.And (f1, f2)
| Input.Or (f1, f2)
| Input.Imply (f1, f2)
| Input.Iff (f1, f2) ->
Util.union (fv_formula env f1) (fv_formula env f2)
| Input.Forall (xs, f) | Input.Exists (xs, f) ->
Util.remove_many xs (fv_formula env f)
(* The depth of the formula is the maximum level of nesting of quantifiers. *)
let rec depth (f, _) =
match f with
| Input.False
| Input.True
| Input.UnaryPr _
| Input.BinaryPr _
| Input.Equal _
| Input.NotEqual _ -> 0
| Input.Not f -> depth f
| Input.And (f1, f2)
| Input.Or (f1, f2)
| Input.Imply (f1, f2)
| Input.Iff (f1, f2) -> max (depth f1) (depth f2)
| Input.Forall (xs, f) | Input.Exists (xs, f) -> List.length xs + depth f
let rec cook_term env vars (t,loc) =
match t with
| Input.Var x ->
begin match lookup_var vars x with
| Some k -> Theory.Var k
| None ->
begin match lookup_const env x with
| Some k -> Theory.Const k
| None -> Error.typing_error ~loc "unknown variable or constant %s" x
end
end
| Input.UnaryOp (op, t) ->
begin match lookup_unary env op with
| Some u -> Theory.Unary (u, cook_term env vars t)
| None -> Error.typing_error ~loc "%s is used as a unary operation but it is not" op
end
| Input.BinaryOp (op, t1, t2) ->
begin match lookup_binary env op with
| Some b -> Theory.Binary (b, cook_term env vars t1, cook_term env vars t2)
| None -> Error.typing_error ~loc "%s is used as a unary operation but it is not" op
end
let cook_equation env (t1, t2) =
let k, vars = Util.enum (Util.union (fv_term env t1) (fv_term env t2)) in
(k, (cook_term env vars t1, cook_term env vars t2))
let cook_formula env f =
let rec cook vars (f,loc) =
match f with
| Input.True -> Theory.True
| Input.False -> Theory.False
| Input.UnaryPr (op, t) ->
begin match lookup_predicate env op with
| Some u -> Theory.Predicate (u, cook_term env vars t)
| None -> Error.typing_error ~loc "%s is not a unary predicate" op
end
| Input.BinaryPr (op, t1, t2) ->
begin match lookup_relation env op with
| Some b -> Theory.Relation (b, cook_term env vars t1, cook_term env vars t2)
| None -> Error.typing_error ~loc "%s is not a binary relation" op
end
| Input.Equal (t1, t2) -> Theory.Equal (cook_term env vars t1, cook_term env vars t2)
| Input.NotEqual (t1, t2) ->
Theory.Not (Theory.Equal (cook_term env vars t1, cook_term env vars t2))
| Input.And (f1,f2) -> Theory.And (cook vars f1, cook vars f2)
| Input.Or (f1,f2) -> Theory.Or (cook vars f1, cook vars f2)
| Input.Imply (f1,f2) -> Theory.Imply (cook vars f1, cook vars f2)
| Input.Iff (f1,f2) -> Theory.Iff (cook vars f1, cook vars f2)
| Input.Not f -> Theory.Not (cook vars f)
| Input.Forall (xs, f) ->
begin match xs with
| [] -> cook vars f
| x :: xs ->
let vars, k = extend_var x vars in
Theory.Forall (k, cook vars (Input.Forall (xs, f), loc))
end
| Input.Exists (xs, f) ->
begin match xs with
| [] -> cook vars f
| x :: xs ->
let vars, k = extend_var x vars in
Theory.Exists (k, cook vars (Input.Exists (xs, f), loc))
end
in
let loc = snd f in
let xs = fv_formula env f in
let f = Input.Forall (xs, f), loc in
Array.make (depth f) (-1), cook [] f
let split_entries lst =
List.fold_left
(fun (env,eqs,axs) ->
fun (e, loc) -> match e with
| Input.Constant cs -> (List.fold_left extend_const env cs, eqs, axs)
| Input.Unary us -> (List.fold_left extend_unary env us, eqs, axs)
| Input.Binary bs -> (List.fold_left extend_binary env bs, eqs, axs)
| Input.Predicate ps -> (List.fold_left extend_predicate env ps, eqs, axs)
| Input.Relation rs -> (List.fold_left extend_relation env rs, eqs, axs)
| Input.Axiom (_,a) ->
begin match Input.as_equation a with
| None -> (env, eqs, a :: axs)
| Some (t1,t2) -> (env, (t1,t2) :: eqs, axs)
end)
(empty_env, [], [])
lst
let env_to_array lst =
let a = Array.make (List.length lst) "?" in
List.iter (fun (op,k) -> a.(k) <- op) lst ;
a
let cook_theory th_name lst =
let (env, eqs, axs) = split_entries lst in
match Util.find_duplicate (List.map fst (env.const @ env.unary @ env.binary)) with
| Some op -> Error.typing_error ~loc:Common.Nowhere "operation %s is declared more than once" op
| None ->
{
Theory.th_name = th_name;
Theory.th_const = env_to_array env.const;
Theory.th_unary = env_to_array env.unary;
Theory.th_binary = env_to_array env.binary;
Theory.th_predicates = env_to_array env.predicates;
Theory.th_relations = env_to_array env.relations;
Theory.th_equations = List.map (cook_equation env) eqs;
Theory.th_axioms = List.map (cook_formula env) axs;
}
| null | https://raw.githubusercontent.com/andrejbauer/alg/95715bb1bf93fcc534a8d6c7c96c8913dc03de0c/src/cook.ml | ocaml | A simple compiler from abstract syntax to the internal representation.
The free variables of a term, without repetitions.
The free variables of a formula, without repetitions.
The depth of the formula is the maximum level of nesting of quantifiers. |
type env = {
const : (Theory.operation_name * Theory.operation) list ;
unary : (Theory.operation_name * Theory.operation) list ;
binary : (Theory.operation_name * Theory.operation) list ;
predicates : (Theory.relation_name * Theory.relation) list ;
relations : (Theory.relation_name * Theory.relation) list ;
}
let empty_env = { const = []; unary = []; binary = []; predicates = []; relations = []}
let fresh lst = 1 + List.fold_left (fun m (_,k) -> max m k) (-1) lst
let extend_const env c =
{ env with const = (c, fresh env.const) :: env.const }
let extend_unary env u =
{ env with unary = (u, fresh env.unary) :: env.unary }
let extend_binary env b =
{ env with binary = (b, fresh env.binary) :: env.binary }
let extend_predicate env p =
{ env with predicates = (p, fresh env.predicates) :: env.predicates }
let extend_relation env r =
{ env with relations = (r, fresh env.relations) :: env.relations }
let extend_var x vars =
let k = fresh vars in
(x,k) :: vars, k
let lookup_const {const=ec} x = Util.lookup x ec
let lookup_unary {unary=eu} x = Util.lookup x eu
let lookup_binary {binary=eb} x = Util.lookup x eb
let lookup_predicate {predicates=ep} x = Util.lookup x ep
let lookup_relation {relations=er} x = Util.lookup x er
let lookup_var vars x = Util.lookup x vars
let is_op {const=ec; unary=eu; binary=eb} x =
List.mem_assoc x ec || List.mem_assoc x eu || List.mem_assoc x eb
let rec fv_term env (t, loc) =
match t with
| Input.Var x ->
if is_op env x then [] else [x]
| Input.UnaryOp (_, t) -> fv_term env t
| Input.BinaryOp (_, t1, t2) -> Util.union (fv_term env t1) (fv_term env t2)
let rec fv_formula env (f, loc) =
match f with
| Input.False -> []
| Input.True -> []
| Input.Equal (t1, t2)
| Input.NotEqual (t1, t2) ->
Util.union (fv_term env t1) (fv_term env t2)
| Input.UnaryPr (_, t) -> fv_term env t
| Input.BinaryPr (_, t1, t2) -> Util.union (fv_term env t1) (fv_term env t2)
| Input.Not f -> fv_formula env f
| Input.And (f1, f2)
| Input.Or (f1, f2)
| Input.Imply (f1, f2)
| Input.Iff (f1, f2) ->
Util.union (fv_formula env f1) (fv_formula env f2)
| Input.Forall (xs, f) | Input.Exists (xs, f) ->
Util.remove_many xs (fv_formula env f)
let rec depth (f, _) =
match f with
| Input.False
| Input.True
| Input.UnaryPr _
| Input.BinaryPr _
| Input.Equal _
| Input.NotEqual _ -> 0
| Input.Not f -> depth f
| Input.And (f1, f2)
| Input.Or (f1, f2)
| Input.Imply (f1, f2)
| Input.Iff (f1, f2) -> max (depth f1) (depth f2)
| Input.Forall (xs, f) | Input.Exists (xs, f) -> List.length xs + depth f
let rec cook_term env vars (t,loc) =
match t with
| Input.Var x ->
begin match lookup_var vars x with
| Some k -> Theory.Var k
| None ->
begin match lookup_const env x with
| Some k -> Theory.Const k
| None -> Error.typing_error ~loc "unknown variable or constant %s" x
end
end
| Input.UnaryOp (op, t) ->
begin match lookup_unary env op with
| Some u -> Theory.Unary (u, cook_term env vars t)
| None -> Error.typing_error ~loc "%s is used as a unary operation but it is not" op
end
| Input.BinaryOp (op, t1, t2) ->
begin match lookup_binary env op with
| Some b -> Theory.Binary (b, cook_term env vars t1, cook_term env vars t2)
| None -> Error.typing_error ~loc "%s is used as a unary operation but it is not" op
end
let cook_equation env (t1, t2) =
let k, vars = Util.enum (Util.union (fv_term env t1) (fv_term env t2)) in
(k, (cook_term env vars t1, cook_term env vars t2))
let cook_formula env f =
let rec cook vars (f,loc) =
match f with
| Input.True -> Theory.True
| Input.False -> Theory.False
| Input.UnaryPr (op, t) ->
begin match lookup_predicate env op with
| Some u -> Theory.Predicate (u, cook_term env vars t)
| None -> Error.typing_error ~loc "%s is not a unary predicate" op
end
| Input.BinaryPr (op, t1, t2) ->
begin match lookup_relation env op with
| Some b -> Theory.Relation (b, cook_term env vars t1, cook_term env vars t2)
| None -> Error.typing_error ~loc "%s is not a binary relation" op
end
| Input.Equal (t1, t2) -> Theory.Equal (cook_term env vars t1, cook_term env vars t2)
| Input.NotEqual (t1, t2) ->
Theory.Not (Theory.Equal (cook_term env vars t1, cook_term env vars t2))
| Input.And (f1,f2) -> Theory.And (cook vars f1, cook vars f2)
| Input.Or (f1,f2) -> Theory.Or (cook vars f1, cook vars f2)
| Input.Imply (f1,f2) -> Theory.Imply (cook vars f1, cook vars f2)
| Input.Iff (f1,f2) -> Theory.Iff (cook vars f1, cook vars f2)
| Input.Not f -> Theory.Not (cook vars f)
| Input.Forall (xs, f) ->
begin match xs with
| [] -> cook vars f
| x :: xs ->
let vars, k = extend_var x vars in
Theory.Forall (k, cook vars (Input.Forall (xs, f), loc))
end
| Input.Exists (xs, f) ->
begin match xs with
| [] -> cook vars f
| x :: xs ->
let vars, k = extend_var x vars in
Theory.Exists (k, cook vars (Input.Exists (xs, f), loc))
end
in
let loc = snd f in
let xs = fv_formula env f in
let f = Input.Forall (xs, f), loc in
Array.make (depth f) (-1), cook [] f
let split_entries lst =
List.fold_left
(fun (env,eqs,axs) ->
fun (e, loc) -> match e with
| Input.Constant cs -> (List.fold_left extend_const env cs, eqs, axs)
| Input.Unary us -> (List.fold_left extend_unary env us, eqs, axs)
| Input.Binary bs -> (List.fold_left extend_binary env bs, eqs, axs)
| Input.Predicate ps -> (List.fold_left extend_predicate env ps, eqs, axs)
| Input.Relation rs -> (List.fold_left extend_relation env rs, eqs, axs)
| Input.Axiom (_,a) ->
begin match Input.as_equation a with
| None -> (env, eqs, a :: axs)
| Some (t1,t2) -> (env, (t1,t2) :: eqs, axs)
end)
(empty_env, [], [])
lst
let env_to_array lst =
let a = Array.make (List.length lst) "?" in
List.iter (fun (op,k) -> a.(k) <- op) lst ;
a
let cook_theory th_name lst =
let (env, eqs, axs) = split_entries lst in
match Util.find_duplicate (List.map fst (env.const @ env.unary @ env.binary)) with
| Some op -> Error.typing_error ~loc:Common.Nowhere "operation %s is declared more than once" op
| None ->
{
Theory.th_name = th_name;
Theory.th_const = env_to_array env.const;
Theory.th_unary = env_to_array env.unary;
Theory.th_binary = env_to_array env.binary;
Theory.th_predicates = env_to_array env.predicates;
Theory.th_relations = env_to_array env.relations;
Theory.th_equations = List.map (cook_equation env) eqs;
Theory.th_axioms = List.map (cook_formula env) axs;
}
|
db3c8cfb3a0c41dfa9c4750dbe68861d74d8d80aa9a2d3556fbbde9bdc813d08 | Helium4Haskell/helium | RightSection.hs | module RightSection where
test :: [Int]
test = filter (False ==) [1..10]
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/typeerrors/Examples/RightSection.hs | haskell | module RightSection where
test :: [Int]
test = filter (False ==) [1..10]
|
|
2788e065f815de586c14310dea04121445f08a4316d6e52bbdb2ab59e25aab7f | ocaml/merlin | includemod.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Inclusion checks for the module language *)
open Misc
open Typedtree
open Types
type symptom =
Missing_field of Ident.t * Location.t * string (* kind *)
| Value_descriptions of Ident.t * value_description * value_description
* Includecore.value_mismatch
| Type_declarations of Ident.t * type_declaration
* type_declaration * Includecore.type_mismatch
| Extension_constructors of Ident.t * extension_constructor
* extension_constructor * Includecore.extension_constructor_mismatch
| Module_types of module_type * module_type
| Modtype_infos of Ident.t * modtype_declaration * modtype_declaration
| Modtype_permutation of Types.module_type * Typedtree.module_coercion
| Interface_mismatch of string * string
| Class_type_declarations of
Ident.t * class_type_declaration * class_type_declaration *
Ctype.class_match_failure list
| Class_declarations of
Ident.t * class_declaration * class_declaration *
Ctype.class_match_failure list
| Unbound_module_path of Path.t
| Invalid_module_alias of Path.t
type pos =
| Module of Ident.t
| Modtype of Ident.t
| Arg of functor_parameter
| Body of functor_parameter
module Error = struct
type functor_arg_descr =
| Anonymous
| Named of Path.t
| Unit
type ('a,'b) diff = {got:'a; expected:'a; symptom:'b}
type 'a core_diff =('a,unit) diff
let diff x y s = {got=x;expected=y; symptom=s}
let sdiff x y = {got=x; expected=y; symptom=()}
type core_sigitem_symptom =
| Value_descriptions of (value_description, Includecore.value_mismatch) diff
| Type_declarations of (type_declaration, Includecore.type_mismatch) diff
| Extension_constructors of
(extension_constructor, Includecore.extension_constructor_mismatch) diff
| Class_type_declarations of
(class_type_declaration, Ctype.class_match_failure list) diff
| Class_declarations of
(class_declaration, Ctype.class_match_failure list) diff
type core_module_type_symptom =
| Not_an_alias
| Not_an_identifier
| Incompatible_aliases
| Abstract_module_type
| Unbound_module_path of Path.t
type module_type_symptom =
| Mt_core of core_module_type_symptom
| Signature of signature_symptom
| Functor of functor_symptom
| Invalid_module_alias of Path.t
| After_alias_expansion of module_type_diff
and module_type_diff = (module_type, module_type_symptom) diff
and functor_symptom =
| Params of functor_params_diff
| Result of module_type_diff
and ('arg,'path) functor_param_symptom =
| Incompatible_params of 'arg * functor_parameter
| Mismatch of module_type_diff
and arg_functor_param_symptom =
(functor_parameter, Ident.t) functor_param_symptom
and functor_params_diff = (functor_parameter list * module_type) core_diff
and signature_symptom = {
env: Env.t;
missings: signature_item list;
incompatibles: (Ident.t * sigitem_symptom) list;
oks: (int * module_coercion) list;
leftovers: (signature_item * signature_item * int) list;
}
and sigitem_symptom =
| Core of core_sigitem_symptom
| Module_type_declaration of
(modtype_declaration, module_type_declaration_symptom) diff
| Module_type of module_type_diff
and module_type_declaration_symptom =
| Illegal_permutation of Typedtree.module_coercion
| Not_greater_than of module_type_diff
| Not_less_than of module_type_diff
| Incomparable of
{less_than:module_type_diff; greater_than: module_type_diff}
type all =
| In_Compilation_unit of (string, signature_symptom) diff
| In_Signature of signature_symptom
| In_Module_type of module_type_diff
| In_Module_type_substitution of
Ident.t * (Types.module_type,module_type_declaration_symptom) diff
| In_Type_declaration of Ident.t * core_sigitem_symptom
| In_Expansion of core_module_type_symptom
end
type mark =
| Mark_both
| Mark_positive
| Mark_negative
| Mark_neither
let negate_mark = function
| Mark_both -> Mark_both
| Mark_positive -> Mark_negative
| Mark_negative -> Mark_positive
| Mark_neither -> Mark_neither
let mark_positive = function
| Mark_both | Mark_positive -> true
| Mark_negative | Mark_neither -> false
(* All functions "blah env x1 x2" check that x1 is included in x2,
i.e. that x1 is the type of an implementation that fulfills the
specification x2. If not, Error is raised with a backtrace of the error. *)
(* Inclusion between value descriptions *)
let value_descriptions ~loc env ~mark subst id vd1 vd2 =
Cmt_format.record_value_dependency vd1 vd2;
if mark_positive mark then
Env.mark_value_used vd1.val_uid;
let vd2 = Subst.value_description subst vd2 in
try
Ok (Includecore.value_descriptions ~loc env (Ident.name id) vd1 vd2)
with Includecore.Dont_match err ->
Error Error.(Core (Value_descriptions (diff vd1 vd2 err)))
(* Inclusion between type declarations *)
let type_declarations ~loc env ~mark ?old_env:_ subst id decl1 decl2 =
let mark = mark_positive mark in
if mark then
Env.mark_type_used decl1.type_uid;
let decl2 = Subst.type_declaration subst decl2 in
match
Includecore.type_declarations ~loc env ~mark
(Ident.name id) decl1 (Path.Pident id) decl2
with
| None -> Ok Tcoerce_none
| Some err ->
Error Error.(Core(Type_declarations (diff decl1 decl2 err)))
(* Inclusion between extension constructors *)
let extension_constructors ~loc env ~mark subst id ext1 ext2 =
let mark = mark_positive mark in
let ext2 = Subst.extension_constructor subst ext2 in
match Includecore.extension_constructors ~loc env ~mark id ext1 ext2 with
| None -> Ok Tcoerce_none
| Some err ->
Error Error.(Core(Extension_constructors(diff ext1 ext2 err)))
(* Inclusion between class declarations *)
let class_type_declarations ~loc ~old_env:_ env subst decl1 decl2 =
let decl2 = Subst.cltype_declaration subst decl2 in
match Includeclass.class_type_declarations ~loc env decl1 decl2 with
[] -> Ok Tcoerce_none
| reason ->
Error Error.(Core(Class_type_declarations(diff decl1 decl2 reason)))
let class_declarations ~old_env:_ env subst decl1 decl2 =
let decl2 = Subst.class_declaration subst decl2 in
match Includeclass.class_declarations env decl1 decl2 with
[] -> Ok Tcoerce_none
| reason ->
Error Error.(Core(Class_declarations(diff decl1 decl2 reason)))
(* Expand a module type identifier when possible *)
let expand_modtype_path env path =
match Env.find_modtype_expansion path env with
| exception Not_found -> None
| x -> Some x
let expand_module_alias ~strengthen env path =
match
if strengthen then Env.find_strengthened_module ~aliasable:true path env
else (Env.find_module path env).md_type
with
| x -> Ok x
| exception Not_found -> Error (Error.Unbound_module_path path)
(* Extract name, kind and ident from a signature item *)
type field_kind =
| Field_value
| Field_type
| Field_exception
| Field_typext
| Field_module
| Field_modtype
| Field_class
| Field_classtype
type field_desc = { name: string; kind: field_kind }
let kind_of_field_desc fd = match fd.kind with
| Field_value -> "value"
| Field_type -> "type"
| Field_exception -> "exception"
| Field_typext -> "extension constructor"
| Field_module -> "module"
| Field_modtype -> "module type"
| Field_class -> "class"
| Field_classtype -> "class type"
let field_desc kind id = { kind; name = Ident.name id }
(** Map indexed by both field types and names.
This avoids name clashes between different sorts of fields
such as values and types. *)
module FieldMap = Map.Make(struct
type t = field_desc
let compare = Stdlib.compare
end)
let item_ident_name = function
Sig_value(id, d, _) -> (id, d.val_loc, field_desc Field_value id)
| Sig_type(id, d, _, _) -> (id, d.type_loc, field_desc Field_type id )
| Sig_typext(id, d, _, _) ->
let kind =
if Path.same d.ext_type_path Predef.path_exn
then Field_exception
else Field_typext
in
(id, d.ext_loc, field_desc kind id)
| Sig_module(id, _, d, _, _) -> (id, d.md_loc, field_desc Field_module id)
| Sig_modtype(id, d, _) -> (id, d.mtd_loc, field_desc Field_modtype id)
| Sig_class(id, d, _, _) -> (id, d.cty_loc, field_desc Field_class id)
| Sig_class_type(id, d, _, _) ->
(id, d.clty_loc, field_desc Field_classtype id)
let is_runtime_component = function
| Sig_value(_,{val_kind = Val_prim _}, _)
| Sig_type(_,_,_,_)
| Sig_module(_,Mp_absent,_,_,_)
| Sig_modtype(_,_,_)
| Sig_class_type(_,_,_,_) -> false
| Sig_value(_,_,_)
| Sig_typext(_,_,_,_)
| Sig_module(_,Mp_present,_,_,_)
| Sig_class(_,_,_,_) -> true
(* Print a coercion *)
let rec print_list pr ppf = function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; Format.fprintf ppf ";@ "; print_list pr ppf l
let print_list pr ppf l =
Format.fprintf ppf "[@[%a@]]" (print_list pr) l
let rec print_coercion ppf c =
let pr fmt = Format.fprintf ppf fmt in
match c with
Tcoerce_none -> pr "id"
| Tcoerce_structure (fl, nl) ->
pr "@[<2>struct@ %a@ %a@]"
(print_list print_coercion2) fl
(print_list print_coercion3) nl
| Tcoerce_functor (inp, out) ->
pr "@[<2>functor@ (%a)@ (%a)@]"
print_coercion inp
print_coercion out
| Tcoerce_primitive {pc_desc; pc_env = _; pc_type} ->
pr "prim %s@ (%a)" pc_desc.Primitive.prim_name
Printtyp.raw_type_expr pc_type
| Tcoerce_alias (_, p, c) ->
pr "@[<2>alias %a@ (%a)@]"
Printtyp.path p
print_coercion c
and print_coercion2 ppf (n, c) =
Format.fprintf ppf "@[%d,@ %a@]" n print_coercion c
and print_coercion3 ppf (i, n, c) =
Format.fprintf ppf "@[%s, %d,@ %a@]"
(Ident.unique_name i) n print_coercion c
(* Simplify a structure coercion *)
let equal_module_paths env p1 subst p2 =
Path.same p1 p2
|| Path.same (Env.normalize_module_path None env p1)
(Env.normalize_module_path None env
(Subst.module_path subst p2))
let equal_modtype_paths env p1 subst p2 =
Path.same p1 p2
|| Path.same (Env.normalize_modtype_path env p1)
(Env.normalize_modtype_path env
(Subst.modtype_path subst p2))
let simplify_structure_coercion cc id_pos_list =
let rec is_identity_coercion pos = function
| [] ->
true
| (n, c) :: rem ->
n = pos && c = Tcoerce_none && is_identity_coercion (pos + 1) rem in
if is_identity_coercion 0 cc
then Tcoerce_none
else Tcoerce_structure (cc, id_pos_list)
let retrieve_functor_params env mty =
let rec retrieve_functor_params before env =
function
| Mty_ident p as res ->
begin match expand_modtype_path env p with
| Some mty -> retrieve_functor_params before env mty
| None -> List.rev before, res
end
| Mty_alias p as res ->
begin match expand_module_alias ~strengthen:false env p with
| Ok mty -> retrieve_functor_params before env mty
| Error _ -> List.rev before, res
end
| Mty_functor (p, res) -> retrieve_functor_params (p :: before) env res
| Mty_signature _ as res -> List.rev before, res
| Mty_for_hole as res -> List.rev before, res
in
retrieve_functor_params [] env mty
(* Inclusion between module types.
Return the restriction that transforms a value of the smaller type
into a value of the bigger type. *)
(* When computing a signature difference, we need to distinguish between
recoverable errors at the value level and unrecoverable errors at the type
level that require us to stop the computation of the difference due to
incoherent types.
*)
type 'a recoverable_error = { error: 'a; recoverable:bool }
let mark_error_as_recoverable r =
Result.map_error (fun error -> { error; recoverable=true}) r
let mark_error_as_unrecoverable r =
Result.map_error (fun error -> { error; recoverable=false}) r
module Sign_diff = struct
type t = {
runtime_coercions: (int * Typedtree.module_coercion) list;
shape_map: Shape.Map.t;
deep_modifications:bool;
errors: (Ident.t * Error.sigitem_symptom) list;
leftovers: ((Types.signature_item as 'it) * 'it * int) list
}
let empty = {
runtime_coercions = [];
shape_map = Shape.Map.empty;
deep_modifications = false;
errors = [];
leftovers = []
}
let merge x y =
{
runtime_coercions = x.runtime_coercions @ y.runtime_coercions;
shape_map = y.shape_map;
(* the shape map is threaded the map during the difference computation,
the last shape map contains all previous elements. *)
deep_modifications = x.deep_modifications || y.deep_modifications;
errors = x.errors @ y.errors;
leftovers = x.leftovers @ y.leftovers
}
end
*
In the group of mutual functions below , the [ ~in_eq ] argument is [ true ] when
we are in fact checking equality of module types .
The module subtyping relation [ A < : B ] checks that [ A.T = B.T ] when [ A ]
and [ B ] define a module type [ T ] . The relation [ A.T = B.T ] is equivalent
to [ ( A.T < : B.T ) and ( B.T < : ) ] , but checking both recursively would lead
to an exponential slowdown ( see # 10598 and # 10616 ) .
To avoid this issue , when [ ~in_eq ] is [ true ] , we compute a coarser relation
[ A < < B ] which is the same as [ A < : B ] except that module types [ T ] are
checked only for [ A.T < < B.T ] and not the reverse .
Thus , we can implement a cheap module type equality check [ A.T = B.T ] by
computing [ ( A.T < < B.T ) and ( B.T < < A.T ) ] , avoiding the exponential slowdown
described above .
In the group of mutual functions below, the [~in_eq] argument is [true] when
we are in fact checking equality of module types.
The module subtyping relation [A <: B] checks that [A.T = B.T] when [A]
and [B] define a module type [T]. The relation [A.T = B.T] is equivalent
to [(A.T <: B.T) and (B.T <: A.T)], but checking both recursively would lead
to an exponential slowdown (see #10598 and #10616).
To avoid this issue, when [~in_eq] is [true], we compute a coarser relation
[A << B] which is the same as [A <: B] except that module types [T] are
checked only for [A.T << B.T] and not the reverse.
Thus, we can implement a cheap module type equality check [A.T = B.T] by
computing [(A.T << B.T) and (B.T << A.T)], avoiding the exponential slowdown
described above.
*)
let rec modtypes ~in_eq ~loc env ~mark subst mty1 mty2 shape =
match try_modtypes ~in_eq ~loc env ~mark subst mty1 mty2 shape with
| Ok _ as ok -> ok
| Error reason ->
let mty2 = Subst.modtype Make_local subst mty2 in
Error Error.(diff mty1 mty2 reason)
and try_modtypes ~in_eq ~loc env ~mark subst mty1 mty2 orig_shape =
match mty1, mty2 with
| (Mty_alias p1, Mty_alias p2) ->
if Env.is_functor_arg p2 env then
Error (Error.Invalid_module_alias p2)
else if not (equal_module_paths env p1 subst p2) then
Error Error.(Mt_core Incompatible_aliases)
else Ok (Tcoerce_none, orig_shape)
| (Mty_alias p1, _) -> begin
match
Env.normalize_module_path (Some Location.none) env p1
with
| exception Env.Error (Env.Missing_module (_, _, path)) ->
Error Error.(Mt_core(Unbound_module_path path))
| p1 ->
begin match expand_module_alias ~strengthen:false env p1 with
| Error e -> Error (Error.Mt_core e)
| Ok mty1 ->
match strengthened_modtypes ~in_eq ~loc ~aliasable:true env ~mark
subst mty1 p1 mty2 orig_shape
with
| Ok _ as x -> x
| Error reason -> Error (Error.After_alias_expansion reason)
end
end
| (Mty_ident p1, Mty_ident p2) ->
let p1 = Env.normalize_modtype_path env p1 in
let p2 = Env.normalize_modtype_path env (Subst.modtype_path subst p2) in
if Path.same p1 p2 then Ok (Tcoerce_none, orig_shape)
else
begin match expand_modtype_path env p1, expand_modtype_path env p2 with
| Some mty1, Some mty2 ->
try_modtypes ~in_eq ~loc env ~mark subst mty1 mty2 orig_shape
| None, _ | _, None -> Error (Error.Mt_core Abstract_module_type)
end
| (Mty_ident p1, _) ->
let p1 = Env.normalize_modtype_path env p1 in
begin match expand_modtype_path env p1 with
| Some p1 ->
try_modtypes ~in_eq ~loc env ~mark subst p1 mty2 orig_shape
| None -> Error (Error.Mt_core Abstract_module_type)
end
| (_, Mty_ident p2) ->
let p2 = Env.normalize_modtype_path env (Subst.modtype_path subst p2) in
begin match expand_modtype_path env p2 with
| Some p2 -> try_modtypes ~in_eq ~loc env ~mark subst mty1 p2 orig_shape
| None ->
begin match mty1 with
| Mty_functor _ ->
let params1 = retrieve_functor_params env mty1 in
let d = Error.sdiff params1 ([],mty2) in
Error Error.(Functor (Params d))
| _ -> Error Error.(Mt_core Not_an_identifier)
end
end
| (Mty_signature sig1, Mty_signature sig2) ->
begin match
signatures ~in_eq ~loc env ~mark subst sig1 sig2 orig_shape
with
| Ok _ as ok -> ok
| Error e -> Error (Error.Signature e)
end
| Mty_functor (param1, res1), Mty_functor (param2, res2) ->
let cc_arg, env, subst =
functor_param ~in_eq ~loc env ~mark:(negate_mark mark)
subst param1 param2
in
let var, res_shape =
match Shape.decompose_abs orig_shape with
| Some (var, res_shape) -> var, res_shape
| None ->
(* Using a fresh variable with a placeholder uid here is fine: users
will never try to jump to the definition of that variable.
If they try to jump to the parameter from inside the functor,
they will use the variable shape that is stored in the local
environment. *)
let var, shape_var =
Shape.fresh_var Uid.internal_not_actually_unique
in
var, Shape.app orig_shape ~arg:shape_var
in
let cc_res = modtypes ~in_eq ~loc env ~mark subst res1 res2 res_shape in
begin match cc_arg, cc_res with
| Ok Tcoerce_none, Ok (Tcoerce_none, final_res_shape) ->
let final_shape =
if final_res_shape == res_shape
then orig_shape
else Shape.abs var final_res_shape
in
Ok (Tcoerce_none, final_shape)
| Ok cc_arg, Ok (cc_res, final_res_shape) ->
let final_shape =
if final_res_shape == res_shape
then orig_shape
else Shape.abs var final_res_shape
in
Ok (Tcoerce_functor(cc_arg, cc_res), final_shape)
| _, Error {Error.symptom = Error.Functor Error.Params res; _} ->
let got_params, got_res = res.got in
let expected_params, expected_res = res.expected in
let d = Error.sdiff
(param1::got_params, got_res)
(param2::expected_params, expected_res) in
Error Error.(Functor (Params d))
| Error _, _ ->
let params1, res1 = retrieve_functor_params env res1 in
let params2, res2 = retrieve_functor_params env res2 in
let d = Error.sdiff (param1::params1, res1) (param2::params2, res2) in
Error Error.(Functor (Params d))
| Ok _, Error res ->
Error Error.(Functor (Result res))
end
| Mty_functor _, _
| _, Mty_functor _ ->
let params1 = retrieve_functor_params env mty1 in
let params2 = retrieve_functor_params env mty2 in
let d = Error.sdiff params1 params2 in
Error Error.(Functor (Params d))
| Mty_for_hole, _ | _, Mty_for_hole ->
Ok (Tcoerce_none, Shape.dummy_mod)
| _, Mty_alias _ ->
Error (Error.Mt_core Error.Not_an_alias)
(* Functor parameters *)
and functor_param ~in_eq ~loc env ~mark subst param1 param2 =
match param1, param2 with
| Unit, Unit ->
Ok Tcoerce_none, env, subst
| Named (name1, arg1), Named (name2, arg2) ->
let arg2' = Subst.modtype Keep subst arg2 in
let cc_arg =
match
modtypes ~in_eq ~loc env ~mark Subst.identity arg2' arg1
Shape.dummy_mod
with
| Ok (cc, _) -> Ok cc
| Error err -> Error (Error.Mismatch err)
in
let env, subst =
match name1, name2 with
| Some id1, Some id2 ->
Env.add_module id1 Mp_present arg2' env,
Subst.add_module id2 (Path.Pident id1) subst
| None, Some id2 ->
let id1 = Ident.rename id2 in
Env.add_module id1 Mp_present arg2' env,
Subst.add_module id2 (Path.Pident id1) subst
| Some id1, None ->
Env.add_module id1 Mp_present arg2' env, subst
| None, None ->
env, subst
in
cc_arg, env, subst
| _, _ ->
Error (Error.Incompatible_params (param1, param2)), env, subst
and strengthened_modtypes ~in_eq ~loc ~aliasable env ~mark
subst mty1 path1 mty2 shape =
match mty1, mty2 with
| Mty_ident p1, Mty_ident p2 when equal_modtype_paths env p1 subst p2 ->
Ok (Tcoerce_none, shape)
| _, _ ->
let mty1 = Mtype.strengthen ~aliasable env mty1 path1 in
modtypes ~in_eq ~loc env ~mark subst mty1 mty2 shape
and strengthened_module_decl ~loc ~aliasable env ~mark
subst md1 path1 md2 shape =
match md1.md_type, md2.md_type with
| Mty_ident p1, Mty_ident p2 when equal_modtype_paths env p1 subst p2 ->
Ok (Tcoerce_none, shape)
| _, _ ->
let md1 = Mtype.strengthen_decl ~aliasable env md1 path1 in
modtypes ~in_eq:false ~loc env ~mark subst md1.md_type md2.md_type shape
(* Inclusion between signatures *)
and signatures ~in_eq ~loc env ~mark subst sig1 sig2 mod_shape =
(* Environment used to check inclusion of components *)
let new_env =
Env.add_signature sig1 (Env.in_signature true env) in
(* Keep ids for module aliases *)
let (id_pos_list,_) =
List.fold_left
(fun (l,pos) -> function
Sig_module (id, Mp_present, _, _, _) ->
((id,pos,Tcoerce_none)::l , pos+1)
| item -> (l, if is_runtime_component item then pos+1 else pos))
([], 0) sig1 in
Build a table of the components of , along with their positions .
The table is indexed by kind and name of component
The table is indexed by kind and name of component *)
let rec build_component_table nb_exported pos tbl = function
[] -> nb_exported, pos, tbl
| item :: rem ->
let pos, nextpos =
if is_runtime_component item then pos, pos + 1
else -1, pos
in
match item_visibility item with
| Hidden ->
(* do not pair private items. *)
build_component_table nb_exported nextpos tbl rem
| Exported ->
let (id, _loc, name) = item_ident_name item in
build_component_table (nb_exported + 1) nextpos
(FieldMap.add name (id, item, pos) tbl) rem
in
let exported_len1, runtime_len1, comps1 =
build_component_table 0 0 FieldMap.empty sig1
in
let exported_len2, runtime_len2 =
List.fold_left (fun (el, rl) i ->
let el = match item_visibility i with Hidden -> el | Exported -> el + 1 in
let rl = if is_runtime_component i then rl + 1 else rl in
el, rl
) (0, 0) sig2
in
Pair each component of sig2 with a component of ,
identifying the names along the way .
Return a coercion list indicating , for all run - time components
of sig2 , the position of the matching run - time components of sig1
and the coercion to be applied to it .
identifying the names along the way.
Return a coercion list indicating, for all run-time components
of sig2, the position of the matching run-time components of sig1
and the coercion to be applied to it. *)
let rec pair_components subst paired unpaired = function
[] ->
let open Sign_diff in
let d =
signature_components ~in_eq ~loc env ~mark new_env subst mod_shape
Shape.Map.empty
(List.rev paired)
in
begin match unpaired, d.errors, d.runtime_coercions, d.leftovers with
| [], [], cc, [] ->
let shape =
if not d.deep_modifications && exported_len1 = exported_len2
then mod_shape
else Shape.str ?uid:mod_shape.Shape.uid d.shape_map
in
see PR#5098
Ok (simplify_structure_coercion cc id_pos_list, shape)
else
Ok (Tcoerce_structure (cc, id_pos_list), shape)
| missings, incompatibles, runtime_coercions, leftovers ->
Error {
Error.env=new_env;
missings;
incompatibles;
oks=runtime_coercions;
leftovers;
}
end
| item2 :: rem ->
let (id2, _loc, name2) = item_ident_name item2 in
let name2, report =
match item2, name2 with
Sig_type (_, {type_manifest=None}, _, _), {name=s; kind=Field_type}
when Btype.is_row_name s ->
(* Do not report in case of failure,
as the main type will generate an error *)
{ kind=Field_type; name=String.sub s 0 (String.length s - 4) },
false
| _ -> name2, true
in
begin match FieldMap.find name2 comps1 with
| (id1, item1, pos1) ->
let new_subst =
match item2 with
Sig_type _ ->
Subst.add_type id2 (Path.Pident id1) subst
| Sig_module _ ->
Subst.add_module id2 (Path.Pident id1) subst
| Sig_modtype _ ->
Subst.add_modtype id2 (Mty_ident (Path.Pident id1)) subst
| Sig_value _ | Sig_typext _
| Sig_class _ | Sig_class_type _ ->
subst
in
pair_components new_subst
((item1, item2, pos1) :: paired) unpaired rem
| exception Not_found ->
let unpaired =
if report then
item2 :: unpaired
else unpaired in
pair_components subst paired unpaired rem
end in
(* Do the pairing and checking, and return the final coercion *)
pair_components subst [] [] sig2
(* Inclusion between signature components *)
and signature_components ~in_eq ~loc old_env ~mark env subst
orig_shape shape_map paired =
match paired with
| [] -> Sign_diff.{ empty with shape_map }
| (sigi1, sigi2, pos) :: rem ->
let shape_modified = ref false in
let id, item, shape_map, present_at_runtime =
match sigi1, sigi2 with
| Sig_value(id1, valdecl1, _) ,Sig_value(_id2, valdecl2, _) ->
let item =
value_descriptions ~loc env ~mark subst id1 valdecl1 valdecl2
in
let item = mark_error_as_recoverable item in
let present_at_runtime = match valdecl2.val_kind with
| Val_prim _ -> false
| _ -> true
in
let shape_map = Shape.Map.add_value_proj shape_map id1 orig_shape in
id1, item, shape_map, present_at_runtime
| Sig_type(id1, tydec1, _, _), Sig_type(_id2, tydec2, _, _) ->
let item =
type_declarations ~loc ~old_env env ~mark subst id1 tydec1 tydec2
in
let item = mark_error_as_unrecoverable item in
let shape_map = Shape.Map.add_type_proj shape_map id1 orig_shape in
id1, item, shape_map, false
| Sig_typext(id1, ext1, _, _), Sig_typext(_id2, ext2, _, _) ->
let item =
extension_constructors ~loc env ~mark subst id1 ext1 ext2
in
let item = mark_error_as_unrecoverable item in
let shape_map =
Shape.Map.add_extcons_proj shape_map id1 orig_shape
in
id1, item, shape_map, true
| Sig_module(id1, pres1, mty1, _, _), Sig_module(_, pres2, mty2, _, _)
-> begin
let orig_shape =
Shape.(proj orig_shape (Item.module_ id1))
in
let item =
module_declarations ~in_eq ~loc env ~mark subst id1 mty1 mty2
orig_shape
in
let item, shape_map =
match item with
| Ok (cc, shape) ->
if shape != orig_shape then shape_modified := true;
let mod_shape = Shape.set_uid_if_none shape mty1.md_uid in
Ok cc, Shape.Map.add_module shape_map id1 mod_shape
| Error diff ->
Error (Error.Module_type diff),
We add the original shape to the map , even though
there is a type error .
It could still be useful for merlin .
there is a type error.
It could still be useful for merlin. *)
Shape.Map.add_module shape_map id1 orig_shape
in
let present_at_runtime, item =
match pres1, pres2, mty1.md_type with
| Mp_present, Mp_present, _ -> true, item
| _, Mp_absent, _ -> false, item
| Mp_absent, Mp_present, Mty_alias p1 ->
true, Result.map (fun i -> Tcoerce_alias (env, p1, i)) item
| Mp_absent, Mp_present, _ -> assert false
in
let item = mark_error_as_unrecoverable item in
id1, item, shape_map, present_at_runtime
end
| Sig_modtype(id1, info1, _), Sig_modtype(_id2, info2, _) ->
let item =
modtype_infos ~in_eq ~loc env ~mark subst id1 info1 info2
in
let shape_map =
Shape.Map.add_module_type_proj shape_map id1 orig_shape
in
let item = mark_error_as_unrecoverable item in
id1, item, shape_map, false
| Sig_class(id1, decl1, _, _), Sig_class(_id2, decl2, _, _) ->
let item =
class_declarations ~old_env env subst decl1 decl2
in
let shape_map =
Shape.Map.add_class_proj shape_map id1 orig_shape
in
let item = mark_error_as_unrecoverable item in
id1, item, shape_map, true
| Sig_class_type(id1, info1, _, _), Sig_class_type(_id2, info2, _, _) ->
let item =
class_type_declarations ~loc ~old_env env subst info1 info2
in
let item = mark_error_as_unrecoverable item in
let shape_map =
Shape.Map.add_class_type_proj shape_map id1 orig_shape
in
id1, item, shape_map, false
| _ ->
assert false
in
let deep_modifications = !shape_modified in
let first =
match item with
| Ok x ->
let runtime_coercions =
if present_at_runtime then [pos,x] else []
in
Sign_diff.{ empty with deep_modifications; runtime_coercions }
| Error { error; recoverable=_ } ->
Sign_diff.{ empty with errors=[id,error]; deep_modifications }
in
let continue = match item with
| Ok _ -> true
| Error x -> x.recoverable
in
let rest =
if continue then
signature_components ~in_eq ~loc old_env ~mark env subst
orig_shape shape_map rem
else Sign_diff.{ empty with leftovers=rem }
in
Sign_diff.merge first rest
and module_declarations ~in_eq ~loc env ~mark subst id1 md1 md2 orig_shape =
Builtin_attributes.check_alerts_inclusion
~def:md1.md_loc
~use:md2.md_loc
loc
md1.md_attributes md2.md_attributes
(Ident.name id1);
let p1 = Path.Pident id1 in
if mark_positive mark then
Env.mark_module_used md1.md_uid;
strengthened_modtypes ~in_eq ~loc ~aliasable:true env ~mark subst
md1.md_type p1 md2.md_type orig_shape
(* Inclusion between module type specifications *)
and modtype_infos ~in_eq ~loc env ~mark subst id info1 info2 =
Builtin_attributes.check_alerts_inclusion
~def:info1.mtd_loc
~use:info2.mtd_loc
loc
info1.mtd_attributes info2.mtd_attributes
(Ident.name id);
let info2 = Subst.modtype_declaration Keep subst info2 in
let r =
match (info1.mtd_type, info2.mtd_type) with
(None, None) -> Ok Tcoerce_none
| (Some _, None) -> Ok Tcoerce_none
| (Some mty1, Some mty2) ->
check_modtype_equiv ~in_eq ~loc env ~mark mty1 mty2
| (None, Some mty2) ->
let mty1 = Mty_ident(Path.Pident id) in
check_modtype_equiv ~in_eq ~loc env ~mark mty1 mty2 in
match r with
| Ok _ as ok -> ok
| Error e -> Error Error.(Module_type_declaration (diff info1 info2 e))
and check_modtype_equiv ~in_eq ~loc env ~mark mty1 mty2 =
let c1 =
modtypes ~in_eq:true ~loc env ~mark Subst.identity mty1 mty2 Shape.dummy_mod
in
let c2 =
For nested module type paths , we check only one side of the equivalence :
the outer module type is the one responsible for checking the other side
of the equivalence .
the outer module type is the one responsible for checking the other side
of the equivalence.
*)
if in_eq then None
else
let mark = negate_mark mark in
Some (
modtypes ~in_eq:true ~loc env ~mark Subst.identity
mty2 mty1 Shape.dummy_mod
)
in
match c1, c2 with
| Ok (Tcoerce_none, _), (Some Ok (Tcoerce_none, _)|None) -> Ok Tcoerce_none
| Ok (c1, _), (Some Ok _ | None) ->
(* Format.eprintf "@[c1 = %a@ c2 = %a@]@."
print_coercion _c1 print_coercion _c2; *)
Error Error.(Illegal_permutation c1)
| Ok _, Some Error e -> Error Error.(Not_greater_than e)
| Error e, (Some Ok _ | None) -> Error Error.(Not_less_than e)
| Error less_than, Some Error greater_than ->
Error Error.(Incomparable {less_than; greater_than})
(* Simplified inclusion check between module types (for Env) *)
let can_alias env path =
let rec no_apply = function
| Path.Pident _ -> true
| Path.Pdot(p, _) -> no_apply p
| Path.Papply _ -> false
in
no_apply path && not (Env.is_functor_arg path env)
type explanation = Env.t * Error.all
exception Error of explanation
exception Apply_error of {
loc : Location.t ;
env : Env.t ;
lid_app : Longident.t option ;
mty_f : module_type ;
args : (Error.functor_arg_descr * module_type) list ;
}
let check_modtype_inclusion_raw ~loc env mty1 path1 mty2 =
let aliasable = can_alias env path1 in
strengthened_modtypes ~in_eq:false ~loc ~aliasable env ~mark:Mark_both
Subst.identity mty1 path1 mty2 Shape.dummy_mod
|> Result.map fst
let check_modtype_inclusion ~loc env mty1 path1 mty2 =
match check_modtype_inclusion_raw ~loc env mty1 path1 mty2 with
| Ok _ -> None
| Error e -> Some (env, Error.In_Module_type e)
let check_functor_application_in_path
~errors ~loc ~lid_whole_app ~f0_path ~args
~arg_path ~arg_mty ~param_mty env =
match check_modtype_inclusion_raw ~loc env arg_mty arg_path param_mty with
| Ok _ -> ()
| Error _errs ->
if errors then
let prepare_arg (arg_path, arg_mty) =
let aliasable = can_alias env arg_path in
let smd = Mtype.strengthen ~aliasable env arg_mty arg_path in
(Error.Named arg_path, smd)
in
let mty_f = (Env.find_module f0_path env).md_type in
let args = List.map prepare_arg args in
let lid_app = Some lid_whole_app in
raise (Apply_error {loc; env; lid_app; mty_f; args})
else
raise Not_found
let () =
Env.check_functor_application := check_functor_application_in_path
(* Check that an implementation of a compilation unit meets its
interface. *)
let compunit env ~mark impl_name impl_sig intf_name intf_sig unit_shape =
match
signatures ~in_eq:false ~loc:(Location.in_file impl_name) env ~mark
Subst.identity impl_sig intf_sig unit_shape
with Result.Error reasons ->
let cdiff =
Error.In_Compilation_unit(Error.diff impl_name intf_name reasons) in
raise(Error(env, cdiff))
| Ok x -> x
(* Functor diffing computation:
The diffing computation uses the internal typing function
*)
module Functor_inclusion_diff = struct
module Defs = struct
type left = Types.functor_parameter
type right = left
type eq = Typedtree.module_coercion
type diff = (Types.functor_parameter, unit) Error.functor_param_symptom
type state = {
res: module_type option;
env: Env.t;
subst: Subst.t;
}
end
open Defs
module Diff = Diffing.Define(Defs)
let param_name = function
| Named(x,_) -> x
| Unit -> None
let weight: Diff.change -> _ = function
| Insert _ -> 10
| Delete _ -> 10
| Change _ -> 10
| Keep (param1, param2, _) -> begin
match param_name param1, param_name param2 with
| None, None
-> 0
| Some n1, Some n2
when String.equal (Ident.name n1) (Ident.name n2)
-> 0
| Some _, Some _ -> 1
| Some _, None | None, Some _ -> 1
end
let keep_expansible_param = function
| Mty_ident _ | Mty_alias _ as mty -> Some mty
| Mty_signature _ | Mty_functor _ | Mty_for_hole -> None
let lookup_expansion { env ; res ; _ } = match res with
| None -> None
| Some res ->
match retrieve_functor_params env res with
| [], _ -> None
| params, res ->
let more = Array.of_list params in
Some (keep_expansible_param res, more)
let expand_params state =
match lookup_expansion state with
| None -> state, [||]
| Some (res, expansion) -> { state with res }, expansion
let update (d:Diff.change) st = match d with
| Insert (Unit | Named (None,_))
| Delete (Unit | Named (None,_))
| Keep (Unit,_,_)
| Keep (_,Unit,_)
| Change (_,(Unit | Named (None,_)), _) ->
st, [||]
| Insert (Named (Some id, arg))
| Delete (Named (Some id, arg))
| Change (Unit, Named (Some id, arg), _) ->
let arg' = Subst.modtype Keep st.subst arg in
let env = Env.add_module id Mp_present arg' st.env in
expand_params { st with env }
| Keep (Named (name1, _), Named (name2, arg2), _)
| Change (Named (name1, _), Named (name2, arg2), _) -> begin
let arg' = Subst.modtype Keep st.subst arg2 in
match name1, name2 with
| Some id1, Some id2 ->
let env = Env.add_module id1 Mp_present arg' st.env in
let subst = Subst.add_module id2 (Path.Pident id1) st.subst in
expand_params { st with env; subst }
| None, Some id2 ->
let env = Env.add_module id2 Mp_present arg' st.env in
{ st with env }, [||]
| Some id1, None ->
let env = Env.add_module id1 Mp_present arg' st.env in
expand_params { st with env }
| None, None ->
st, [||]
end
let diff env (l1,res1) (l2,_) =
let module Compute = Diff.Left_variadic(struct
let test st mty1 mty2 =
let loc = Location.none in
let res, _, _ =
functor_param ~in_eq:false ~loc st.env ~mark:Mark_neither
st.subst mty1 mty2
in
res
let update = update
let weight = weight
end)
in
let param1 = Array.of_list l1 in
let param2 = Array.of_list l2 in
let state =
{ env; subst = Subst.identity; res = keep_expansible_param res1}
in
Compute.diff state param1 param2
end
module Functor_app_diff = struct
module I = Functor_inclusion_diff
module Defs= struct
type left = Error.functor_arg_descr * Types.module_type
type right = Types.functor_parameter
type eq = Typedtree.module_coercion
type diff = (Error.functor_arg_descr, unit) Error.functor_param_symptom
type state = I.Defs.state
end
module Diff = Diffing.Define(Defs)
let weight: Diff.change -> _ = function
| Insert _ -> 10
| Delete _ -> 10
| Change _ -> 10
| Keep (param1, param2, _) ->
(* We assign a small penalty to named arguments with
non-matching names *)
begin
let desc1 : Error.functor_arg_descr = fst param1 in
match desc1, I.param_name param2 with
| (Unit | Anonymous) , None
-> 0
| Named (Path.Pident n1), Some n2
when String.equal (Ident.name n1) (Ident.name n2)
-> 0
| Named _, Some _ -> 1
| Named _, None | (Unit | Anonymous), Some _ -> 1
end
let update (d: Diff.change) (st:Defs.state) =
let open Error in
match d with
| Insert _
| Delete _
| Keep ((Unit,_),_,_)
| Keep (_,Unit,_)
| Change (_,(Unit | Named (None,_)), _ )
| Change ((Unit,_), Named (Some _, _), _) ->
st, [||]
| Keep ((Named arg, _mty) , Named (param_name, _param), _)
| Change ((Named arg, _mty), Named (param_name, _param), _) ->
begin match param_name with
| Some param ->
let res =
Option.map (fun res ->
let scope = Ctype.create_scope () in
let subst = Subst.add_module param arg Subst.identity in
Subst.modtype (Rescope scope) subst res
)
st.res
in
let subst = Subst.add_module param arg st.subst in
I.expand_params { st with subst; res }
| None ->
st, [||]
end
| Keep ((Anonymous, mty) , Named (param_name, _param), _)
| Change ((Anonymous, mty), Named (param_name, _param), _) -> begin
begin match param_name with
| Some param ->
let mty' = Subst.modtype Keep st.subst mty in
let env =
Env.add_module ~arg:true param Mp_present mty' st.env in
let res =
Option.map (Mtype.nondep_supertype env [param]) st.res in
I.expand_params { st with env; res}
| None ->
st, [||]
end
end
let diff env ~f ~args =
let params, res = retrieve_functor_params env f in
let module Compute = Diff.Right_variadic(struct
let update = update
let test (state:Defs.state) (arg,arg_mty) param =
let loc = Location.none in
let res = match (arg:Error.functor_arg_descr), param with
| Unit, Unit -> Ok Tcoerce_none
| Unit, Named _ | (Anonymous | Named _), Unit ->
Result.Error (Error.Incompatible_params(arg,param))
| ( Anonymous | Named _ ) , Named (_, param) ->
match
modtypes ~in_eq:false ~loc state.env ~mark:Mark_neither
state.subst arg_mty param Shape.dummy_mod
with
| Error mty -> Result.Error (Error.Mismatch mty)
| Ok (cc, _) -> Ok cc
in
res
let weight = weight
end)
in
let args = Array.of_list args in
let params = Array.of_list params in
let state : Defs.state =
{ env; subst = Subst.identity; res = I.keep_expansible_param res }
in
Compute.diff state args params
end
(* Hide the context and substitution parameters to the outside world *)
let modtypes_with_shape ~shape ~loc env ~mark mty1 mty2 =
match modtypes ~in_eq:false ~loc env ~mark
Subst.identity mty1 mty2 shape
with
| Ok (cc, shape) -> cc, shape
| Error reason -> raise (Error (env, Error.(In_Module_type reason)))
let modtypes ~loc env ~mark mty1 mty2 =
match modtypes ~in_eq:false ~loc env ~mark
Subst.identity mty1 mty2 Shape.dummy_mod
with
| Ok (cc, _) -> cc
| Error reason -> raise (Error (env, Error.(In_Module_type reason)))
let signatures env ~mark sig1 sig2 =
match signatures ~in_eq:false ~loc:Location.none env ~mark
Subst.identity sig1 sig2 Shape.dummy_mod
with
| Ok (cc, _) -> cc
| Error reason -> raise (Error(env,Error.(In_Signature reason)))
let type_declarations ~loc env ~mark id decl1 decl2 =
match type_declarations ~loc env ~mark Subst.identity id decl1 decl2 with
| Ok _ -> ()
| Error (Error.Core reason) ->
raise (Error(env,Error.(In_Type_declaration(id,reason))))
| Error _ -> assert false
let strengthened_module_decl ~loc ~aliasable env ~mark md1 path1 md2 =
match strengthened_module_decl ~loc ~aliasable env ~mark Subst.identity
md1 path1 md2 Shape.dummy_mod with
| Ok (x, _shape) -> x
| Error mdiff ->
raise (Error(env,Error.(In_Module_type mdiff)))
let expand_module_alias ~strengthen env path =
match expand_module_alias ~strengthen env path with
| Ok x -> x
| Result.Error _ ->
raise (Error(env,In_Expansion(Error.Unbound_module_path path)))
let check_modtype_equiv ~loc env id mty1 mty2 =
match check_modtype_equiv ~in_eq:false ~loc env ~mark:Mark_both mty1 mty2 with
| Ok _ -> ()
| Error e ->
raise (Error(env,
Error.(In_Module_type_substitution (id,diff mty1 mty2 e)))
)
| null | https://raw.githubusercontent.com/ocaml/merlin/c447386d83522b26eb359d489eb6f5b7488203a5/src/ocaml/typing/includemod.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Inclusion checks for the module language
kind
All functions "blah env x1 x2" check that x1 is included in x2,
i.e. that x1 is the type of an implementation that fulfills the
specification x2. If not, Error is raised with a backtrace of the error.
Inclusion between value descriptions
Inclusion between type declarations
Inclusion between extension constructors
Inclusion between class declarations
Expand a module type identifier when possible
Extract name, kind and ident from a signature item
* Map indexed by both field types and names.
This avoids name clashes between different sorts of fields
such as values and types.
Print a coercion
Simplify a structure coercion
Inclusion between module types.
Return the restriction that transforms a value of the smaller type
into a value of the bigger type.
When computing a signature difference, we need to distinguish between
recoverable errors at the value level and unrecoverable errors at the type
level that require us to stop the computation of the difference due to
incoherent types.
the shape map is threaded the map during the difference computation,
the last shape map contains all previous elements.
Using a fresh variable with a placeholder uid here is fine: users
will never try to jump to the definition of that variable.
If they try to jump to the parameter from inside the functor,
they will use the variable shape that is stored in the local
environment.
Functor parameters
Inclusion between signatures
Environment used to check inclusion of components
Keep ids for module aliases
do not pair private items.
Do not report in case of failure,
as the main type will generate an error
Do the pairing and checking, and return the final coercion
Inclusion between signature components
Inclusion between module type specifications
Format.eprintf "@[c1 = %a@ c2 = %a@]@."
print_coercion _c1 print_coercion _c2;
Simplified inclusion check between module types (for Env)
Check that an implementation of a compilation unit meets its
interface.
Functor diffing computation:
The diffing computation uses the internal typing function
We assign a small penalty to named arguments with
non-matching names
Hide the context and substitution parameters to the outside world | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Misc
open Typedtree
open Types
type symptom =
| Value_descriptions of Ident.t * value_description * value_description
* Includecore.value_mismatch
| Type_declarations of Ident.t * type_declaration
* type_declaration * Includecore.type_mismatch
| Extension_constructors of Ident.t * extension_constructor
* extension_constructor * Includecore.extension_constructor_mismatch
| Module_types of module_type * module_type
| Modtype_infos of Ident.t * modtype_declaration * modtype_declaration
| Modtype_permutation of Types.module_type * Typedtree.module_coercion
| Interface_mismatch of string * string
| Class_type_declarations of
Ident.t * class_type_declaration * class_type_declaration *
Ctype.class_match_failure list
| Class_declarations of
Ident.t * class_declaration * class_declaration *
Ctype.class_match_failure list
| Unbound_module_path of Path.t
| Invalid_module_alias of Path.t
type pos =
| Module of Ident.t
| Modtype of Ident.t
| Arg of functor_parameter
| Body of functor_parameter
module Error = struct
type functor_arg_descr =
| Anonymous
| Named of Path.t
| Unit
type ('a,'b) diff = {got:'a; expected:'a; symptom:'b}
type 'a core_diff =('a,unit) diff
let diff x y s = {got=x;expected=y; symptom=s}
let sdiff x y = {got=x; expected=y; symptom=()}
type core_sigitem_symptom =
| Value_descriptions of (value_description, Includecore.value_mismatch) diff
| Type_declarations of (type_declaration, Includecore.type_mismatch) diff
| Extension_constructors of
(extension_constructor, Includecore.extension_constructor_mismatch) diff
| Class_type_declarations of
(class_type_declaration, Ctype.class_match_failure list) diff
| Class_declarations of
(class_declaration, Ctype.class_match_failure list) diff
type core_module_type_symptom =
| Not_an_alias
| Not_an_identifier
| Incompatible_aliases
| Abstract_module_type
| Unbound_module_path of Path.t
type module_type_symptom =
| Mt_core of core_module_type_symptom
| Signature of signature_symptom
| Functor of functor_symptom
| Invalid_module_alias of Path.t
| After_alias_expansion of module_type_diff
and module_type_diff = (module_type, module_type_symptom) diff
and functor_symptom =
| Params of functor_params_diff
| Result of module_type_diff
and ('arg,'path) functor_param_symptom =
| Incompatible_params of 'arg * functor_parameter
| Mismatch of module_type_diff
and arg_functor_param_symptom =
(functor_parameter, Ident.t) functor_param_symptom
and functor_params_diff = (functor_parameter list * module_type) core_diff
and signature_symptom = {
env: Env.t;
missings: signature_item list;
incompatibles: (Ident.t * sigitem_symptom) list;
oks: (int * module_coercion) list;
leftovers: (signature_item * signature_item * int) list;
}
and sigitem_symptom =
| Core of core_sigitem_symptom
| Module_type_declaration of
(modtype_declaration, module_type_declaration_symptom) diff
| Module_type of module_type_diff
and module_type_declaration_symptom =
| Illegal_permutation of Typedtree.module_coercion
| Not_greater_than of module_type_diff
| Not_less_than of module_type_diff
| Incomparable of
{less_than:module_type_diff; greater_than: module_type_diff}
type all =
| In_Compilation_unit of (string, signature_symptom) diff
| In_Signature of signature_symptom
| In_Module_type of module_type_diff
| In_Module_type_substitution of
Ident.t * (Types.module_type,module_type_declaration_symptom) diff
| In_Type_declaration of Ident.t * core_sigitem_symptom
| In_Expansion of core_module_type_symptom
end
type mark =
| Mark_both
| Mark_positive
| Mark_negative
| Mark_neither
let negate_mark = function
| Mark_both -> Mark_both
| Mark_positive -> Mark_negative
| Mark_negative -> Mark_positive
| Mark_neither -> Mark_neither
let mark_positive = function
| Mark_both | Mark_positive -> true
| Mark_negative | Mark_neither -> false
let value_descriptions ~loc env ~mark subst id vd1 vd2 =
Cmt_format.record_value_dependency vd1 vd2;
if mark_positive mark then
Env.mark_value_used vd1.val_uid;
let vd2 = Subst.value_description subst vd2 in
try
Ok (Includecore.value_descriptions ~loc env (Ident.name id) vd1 vd2)
with Includecore.Dont_match err ->
Error Error.(Core (Value_descriptions (diff vd1 vd2 err)))
let type_declarations ~loc env ~mark ?old_env:_ subst id decl1 decl2 =
let mark = mark_positive mark in
if mark then
Env.mark_type_used decl1.type_uid;
let decl2 = Subst.type_declaration subst decl2 in
match
Includecore.type_declarations ~loc env ~mark
(Ident.name id) decl1 (Path.Pident id) decl2
with
| None -> Ok Tcoerce_none
| Some err ->
Error Error.(Core(Type_declarations (diff decl1 decl2 err)))
let extension_constructors ~loc env ~mark subst id ext1 ext2 =
let mark = mark_positive mark in
let ext2 = Subst.extension_constructor subst ext2 in
match Includecore.extension_constructors ~loc env ~mark id ext1 ext2 with
| None -> Ok Tcoerce_none
| Some err ->
Error Error.(Core(Extension_constructors(diff ext1 ext2 err)))
let class_type_declarations ~loc ~old_env:_ env subst decl1 decl2 =
let decl2 = Subst.cltype_declaration subst decl2 in
match Includeclass.class_type_declarations ~loc env decl1 decl2 with
[] -> Ok Tcoerce_none
| reason ->
Error Error.(Core(Class_type_declarations(diff decl1 decl2 reason)))
let class_declarations ~old_env:_ env subst decl1 decl2 =
let decl2 = Subst.class_declaration subst decl2 in
match Includeclass.class_declarations env decl1 decl2 with
[] -> Ok Tcoerce_none
| reason ->
Error Error.(Core(Class_declarations(diff decl1 decl2 reason)))
let expand_modtype_path env path =
match Env.find_modtype_expansion path env with
| exception Not_found -> None
| x -> Some x
let expand_module_alias ~strengthen env path =
match
if strengthen then Env.find_strengthened_module ~aliasable:true path env
else (Env.find_module path env).md_type
with
| x -> Ok x
| exception Not_found -> Error (Error.Unbound_module_path path)
type field_kind =
| Field_value
| Field_type
| Field_exception
| Field_typext
| Field_module
| Field_modtype
| Field_class
| Field_classtype
type field_desc = { name: string; kind: field_kind }
let kind_of_field_desc fd = match fd.kind with
| Field_value -> "value"
| Field_type -> "type"
| Field_exception -> "exception"
| Field_typext -> "extension constructor"
| Field_module -> "module"
| Field_modtype -> "module type"
| Field_class -> "class"
| Field_classtype -> "class type"
let field_desc kind id = { kind; name = Ident.name id }
module FieldMap = Map.Make(struct
type t = field_desc
let compare = Stdlib.compare
end)
let item_ident_name = function
Sig_value(id, d, _) -> (id, d.val_loc, field_desc Field_value id)
| Sig_type(id, d, _, _) -> (id, d.type_loc, field_desc Field_type id )
| Sig_typext(id, d, _, _) ->
let kind =
if Path.same d.ext_type_path Predef.path_exn
then Field_exception
else Field_typext
in
(id, d.ext_loc, field_desc kind id)
| Sig_module(id, _, d, _, _) -> (id, d.md_loc, field_desc Field_module id)
| Sig_modtype(id, d, _) -> (id, d.mtd_loc, field_desc Field_modtype id)
| Sig_class(id, d, _, _) -> (id, d.cty_loc, field_desc Field_class id)
| Sig_class_type(id, d, _, _) ->
(id, d.clty_loc, field_desc Field_classtype id)
let is_runtime_component = function
| Sig_value(_,{val_kind = Val_prim _}, _)
| Sig_type(_,_,_,_)
| Sig_module(_,Mp_absent,_,_,_)
| Sig_modtype(_,_,_)
| Sig_class_type(_,_,_,_) -> false
| Sig_value(_,_,_)
| Sig_typext(_,_,_,_)
| Sig_module(_,Mp_present,_,_,_)
| Sig_class(_,_,_,_) -> true
let rec print_list pr ppf = function
[] -> ()
| [a] -> pr ppf a
| a :: l -> pr ppf a; Format.fprintf ppf ";@ "; print_list pr ppf l
let print_list pr ppf l =
Format.fprintf ppf "[@[%a@]]" (print_list pr) l
let rec print_coercion ppf c =
let pr fmt = Format.fprintf ppf fmt in
match c with
Tcoerce_none -> pr "id"
| Tcoerce_structure (fl, nl) ->
pr "@[<2>struct@ %a@ %a@]"
(print_list print_coercion2) fl
(print_list print_coercion3) nl
| Tcoerce_functor (inp, out) ->
pr "@[<2>functor@ (%a)@ (%a)@]"
print_coercion inp
print_coercion out
| Tcoerce_primitive {pc_desc; pc_env = _; pc_type} ->
pr "prim %s@ (%a)" pc_desc.Primitive.prim_name
Printtyp.raw_type_expr pc_type
| Tcoerce_alias (_, p, c) ->
pr "@[<2>alias %a@ (%a)@]"
Printtyp.path p
print_coercion c
and print_coercion2 ppf (n, c) =
Format.fprintf ppf "@[%d,@ %a@]" n print_coercion c
and print_coercion3 ppf (i, n, c) =
Format.fprintf ppf "@[%s, %d,@ %a@]"
(Ident.unique_name i) n print_coercion c
let equal_module_paths env p1 subst p2 =
Path.same p1 p2
|| Path.same (Env.normalize_module_path None env p1)
(Env.normalize_module_path None env
(Subst.module_path subst p2))
let equal_modtype_paths env p1 subst p2 =
Path.same p1 p2
|| Path.same (Env.normalize_modtype_path env p1)
(Env.normalize_modtype_path env
(Subst.modtype_path subst p2))
let simplify_structure_coercion cc id_pos_list =
let rec is_identity_coercion pos = function
| [] ->
true
| (n, c) :: rem ->
n = pos && c = Tcoerce_none && is_identity_coercion (pos + 1) rem in
if is_identity_coercion 0 cc
then Tcoerce_none
else Tcoerce_structure (cc, id_pos_list)
let retrieve_functor_params env mty =
let rec retrieve_functor_params before env =
function
| Mty_ident p as res ->
begin match expand_modtype_path env p with
| Some mty -> retrieve_functor_params before env mty
| None -> List.rev before, res
end
| Mty_alias p as res ->
begin match expand_module_alias ~strengthen:false env p with
| Ok mty -> retrieve_functor_params before env mty
| Error _ -> List.rev before, res
end
| Mty_functor (p, res) -> retrieve_functor_params (p :: before) env res
| Mty_signature _ as res -> List.rev before, res
| Mty_for_hole as res -> List.rev before, res
in
retrieve_functor_params [] env mty
type 'a recoverable_error = { error: 'a; recoverable:bool }
let mark_error_as_recoverable r =
Result.map_error (fun error -> { error; recoverable=true}) r
let mark_error_as_unrecoverable r =
Result.map_error (fun error -> { error; recoverable=false}) r
module Sign_diff = struct
type t = {
runtime_coercions: (int * Typedtree.module_coercion) list;
shape_map: Shape.Map.t;
deep_modifications:bool;
errors: (Ident.t * Error.sigitem_symptom) list;
leftovers: ((Types.signature_item as 'it) * 'it * int) list
}
let empty = {
runtime_coercions = [];
shape_map = Shape.Map.empty;
deep_modifications = false;
errors = [];
leftovers = []
}
let merge x y =
{
runtime_coercions = x.runtime_coercions @ y.runtime_coercions;
shape_map = y.shape_map;
deep_modifications = x.deep_modifications || y.deep_modifications;
errors = x.errors @ y.errors;
leftovers = x.leftovers @ y.leftovers
}
end
*
In the group of mutual functions below , the [ ~in_eq ] argument is [ true ] when
we are in fact checking equality of module types .
The module subtyping relation [ A < : B ] checks that [ A.T = B.T ] when [ A ]
and [ B ] define a module type [ T ] . The relation [ A.T = B.T ] is equivalent
to [ ( A.T < : B.T ) and ( B.T < : ) ] , but checking both recursively would lead
to an exponential slowdown ( see # 10598 and # 10616 ) .
To avoid this issue , when [ ~in_eq ] is [ true ] , we compute a coarser relation
[ A < < B ] which is the same as [ A < : B ] except that module types [ T ] are
checked only for [ A.T < < B.T ] and not the reverse .
Thus , we can implement a cheap module type equality check [ A.T = B.T ] by
computing [ ( A.T < < B.T ) and ( B.T < < A.T ) ] , avoiding the exponential slowdown
described above .
In the group of mutual functions below, the [~in_eq] argument is [true] when
we are in fact checking equality of module types.
The module subtyping relation [A <: B] checks that [A.T = B.T] when [A]
and [B] define a module type [T]. The relation [A.T = B.T] is equivalent
to [(A.T <: B.T) and (B.T <: A.T)], but checking both recursively would lead
to an exponential slowdown (see #10598 and #10616).
To avoid this issue, when [~in_eq] is [true], we compute a coarser relation
[A << B] which is the same as [A <: B] except that module types [T] are
checked only for [A.T << B.T] and not the reverse.
Thus, we can implement a cheap module type equality check [A.T = B.T] by
computing [(A.T << B.T) and (B.T << A.T)], avoiding the exponential slowdown
described above.
*)
let rec modtypes ~in_eq ~loc env ~mark subst mty1 mty2 shape =
match try_modtypes ~in_eq ~loc env ~mark subst mty1 mty2 shape with
| Ok _ as ok -> ok
| Error reason ->
let mty2 = Subst.modtype Make_local subst mty2 in
Error Error.(diff mty1 mty2 reason)
and try_modtypes ~in_eq ~loc env ~mark subst mty1 mty2 orig_shape =
match mty1, mty2 with
| (Mty_alias p1, Mty_alias p2) ->
if Env.is_functor_arg p2 env then
Error (Error.Invalid_module_alias p2)
else if not (equal_module_paths env p1 subst p2) then
Error Error.(Mt_core Incompatible_aliases)
else Ok (Tcoerce_none, orig_shape)
| (Mty_alias p1, _) -> begin
match
Env.normalize_module_path (Some Location.none) env p1
with
| exception Env.Error (Env.Missing_module (_, _, path)) ->
Error Error.(Mt_core(Unbound_module_path path))
| p1 ->
begin match expand_module_alias ~strengthen:false env p1 with
| Error e -> Error (Error.Mt_core e)
| Ok mty1 ->
match strengthened_modtypes ~in_eq ~loc ~aliasable:true env ~mark
subst mty1 p1 mty2 orig_shape
with
| Ok _ as x -> x
| Error reason -> Error (Error.After_alias_expansion reason)
end
end
| (Mty_ident p1, Mty_ident p2) ->
let p1 = Env.normalize_modtype_path env p1 in
let p2 = Env.normalize_modtype_path env (Subst.modtype_path subst p2) in
if Path.same p1 p2 then Ok (Tcoerce_none, orig_shape)
else
begin match expand_modtype_path env p1, expand_modtype_path env p2 with
| Some mty1, Some mty2 ->
try_modtypes ~in_eq ~loc env ~mark subst mty1 mty2 orig_shape
| None, _ | _, None -> Error (Error.Mt_core Abstract_module_type)
end
| (Mty_ident p1, _) ->
let p1 = Env.normalize_modtype_path env p1 in
begin match expand_modtype_path env p1 with
| Some p1 ->
try_modtypes ~in_eq ~loc env ~mark subst p1 mty2 orig_shape
| None -> Error (Error.Mt_core Abstract_module_type)
end
| (_, Mty_ident p2) ->
let p2 = Env.normalize_modtype_path env (Subst.modtype_path subst p2) in
begin match expand_modtype_path env p2 with
| Some p2 -> try_modtypes ~in_eq ~loc env ~mark subst mty1 p2 orig_shape
| None ->
begin match mty1 with
| Mty_functor _ ->
let params1 = retrieve_functor_params env mty1 in
let d = Error.sdiff params1 ([],mty2) in
Error Error.(Functor (Params d))
| _ -> Error Error.(Mt_core Not_an_identifier)
end
end
| (Mty_signature sig1, Mty_signature sig2) ->
begin match
signatures ~in_eq ~loc env ~mark subst sig1 sig2 orig_shape
with
| Ok _ as ok -> ok
| Error e -> Error (Error.Signature e)
end
| Mty_functor (param1, res1), Mty_functor (param2, res2) ->
let cc_arg, env, subst =
functor_param ~in_eq ~loc env ~mark:(negate_mark mark)
subst param1 param2
in
let var, res_shape =
match Shape.decompose_abs orig_shape with
| Some (var, res_shape) -> var, res_shape
| None ->
let var, shape_var =
Shape.fresh_var Uid.internal_not_actually_unique
in
var, Shape.app orig_shape ~arg:shape_var
in
let cc_res = modtypes ~in_eq ~loc env ~mark subst res1 res2 res_shape in
begin match cc_arg, cc_res with
| Ok Tcoerce_none, Ok (Tcoerce_none, final_res_shape) ->
let final_shape =
if final_res_shape == res_shape
then orig_shape
else Shape.abs var final_res_shape
in
Ok (Tcoerce_none, final_shape)
| Ok cc_arg, Ok (cc_res, final_res_shape) ->
let final_shape =
if final_res_shape == res_shape
then orig_shape
else Shape.abs var final_res_shape
in
Ok (Tcoerce_functor(cc_arg, cc_res), final_shape)
| _, Error {Error.symptom = Error.Functor Error.Params res; _} ->
let got_params, got_res = res.got in
let expected_params, expected_res = res.expected in
let d = Error.sdiff
(param1::got_params, got_res)
(param2::expected_params, expected_res) in
Error Error.(Functor (Params d))
| Error _, _ ->
let params1, res1 = retrieve_functor_params env res1 in
let params2, res2 = retrieve_functor_params env res2 in
let d = Error.sdiff (param1::params1, res1) (param2::params2, res2) in
Error Error.(Functor (Params d))
| Ok _, Error res ->
Error Error.(Functor (Result res))
end
| Mty_functor _, _
| _, Mty_functor _ ->
let params1 = retrieve_functor_params env mty1 in
let params2 = retrieve_functor_params env mty2 in
let d = Error.sdiff params1 params2 in
Error Error.(Functor (Params d))
| Mty_for_hole, _ | _, Mty_for_hole ->
Ok (Tcoerce_none, Shape.dummy_mod)
| _, Mty_alias _ ->
Error (Error.Mt_core Error.Not_an_alias)
and functor_param ~in_eq ~loc env ~mark subst param1 param2 =
match param1, param2 with
| Unit, Unit ->
Ok Tcoerce_none, env, subst
| Named (name1, arg1), Named (name2, arg2) ->
let arg2' = Subst.modtype Keep subst arg2 in
let cc_arg =
match
modtypes ~in_eq ~loc env ~mark Subst.identity arg2' arg1
Shape.dummy_mod
with
| Ok (cc, _) -> Ok cc
| Error err -> Error (Error.Mismatch err)
in
let env, subst =
match name1, name2 with
| Some id1, Some id2 ->
Env.add_module id1 Mp_present arg2' env,
Subst.add_module id2 (Path.Pident id1) subst
| None, Some id2 ->
let id1 = Ident.rename id2 in
Env.add_module id1 Mp_present arg2' env,
Subst.add_module id2 (Path.Pident id1) subst
| Some id1, None ->
Env.add_module id1 Mp_present arg2' env, subst
| None, None ->
env, subst
in
cc_arg, env, subst
| _, _ ->
Error (Error.Incompatible_params (param1, param2)), env, subst
and strengthened_modtypes ~in_eq ~loc ~aliasable env ~mark
subst mty1 path1 mty2 shape =
match mty1, mty2 with
| Mty_ident p1, Mty_ident p2 when equal_modtype_paths env p1 subst p2 ->
Ok (Tcoerce_none, shape)
| _, _ ->
let mty1 = Mtype.strengthen ~aliasable env mty1 path1 in
modtypes ~in_eq ~loc env ~mark subst mty1 mty2 shape
and strengthened_module_decl ~loc ~aliasable env ~mark
subst md1 path1 md2 shape =
match md1.md_type, md2.md_type with
| Mty_ident p1, Mty_ident p2 when equal_modtype_paths env p1 subst p2 ->
Ok (Tcoerce_none, shape)
| _, _ ->
let md1 = Mtype.strengthen_decl ~aliasable env md1 path1 in
modtypes ~in_eq:false ~loc env ~mark subst md1.md_type md2.md_type shape
and signatures ~in_eq ~loc env ~mark subst sig1 sig2 mod_shape =
let new_env =
Env.add_signature sig1 (Env.in_signature true env) in
let (id_pos_list,_) =
List.fold_left
(fun (l,pos) -> function
Sig_module (id, Mp_present, _, _, _) ->
((id,pos,Tcoerce_none)::l , pos+1)
| item -> (l, if is_runtime_component item then pos+1 else pos))
([], 0) sig1 in
Build a table of the components of , along with their positions .
The table is indexed by kind and name of component
The table is indexed by kind and name of component *)
let rec build_component_table nb_exported pos tbl = function
[] -> nb_exported, pos, tbl
| item :: rem ->
let pos, nextpos =
if is_runtime_component item then pos, pos + 1
else -1, pos
in
match item_visibility item with
| Hidden ->
build_component_table nb_exported nextpos tbl rem
| Exported ->
let (id, _loc, name) = item_ident_name item in
build_component_table (nb_exported + 1) nextpos
(FieldMap.add name (id, item, pos) tbl) rem
in
let exported_len1, runtime_len1, comps1 =
build_component_table 0 0 FieldMap.empty sig1
in
let exported_len2, runtime_len2 =
List.fold_left (fun (el, rl) i ->
let el = match item_visibility i with Hidden -> el | Exported -> el + 1 in
let rl = if is_runtime_component i then rl + 1 else rl in
el, rl
) (0, 0) sig2
in
Pair each component of sig2 with a component of ,
identifying the names along the way .
Return a coercion list indicating , for all run - time components
of sig2 , the position of the matching run - time components of sig1
and the coercion to be applied to it .
identifying the names along the way.
Return a coercion list indicating, for all run-time components
of sig2, the position of the matching run-time components of sig1
and the coercion to be applied to it. *)
let rec pair_components subst paired unpaired = function
[] ->
let open Sign_diff in
let d =
signature_components ~in_eq ~loc env ~mark new_env subst mod_shape
Shape.Map.empty
(List.rev paired)
in
begin match unpaired, d.errors, d.runtime_coercions, d.leftovers with
| [], [], cc, [] ->
let shape =
if not d.deep_modifications && exported_len1 = exported_len2
then mod_shape
else Shape.str ?uid:mod_shape.Shape.uid d.shape_map
in
see PR#5098
Ok (simplify_structure_coercion cc id_pos_list, shape)
else
Ok (Tcoerce_structure (cc, id_pos_list), shape)
| missings, incompatibles, runtime_coercions, leftovers ->
Error {
Error.env=new_env;
missings;
incompatibles;
oks=runtime_coercions;
leftovers;
}
end
| item2 :: rem ->
let (id2, _loc, name2) = item_ident_name item2 in
let name2, report =
match item2, name2 with
Sig_type (_, {type_manifest=None}, _, _), {name=s; kind=Field_type}
when Btype.is_row_name s ->
{ kind=Field_type; name=String.sub s 0 (String.length s - 4) },
false
| _ -> name2, true
in
begin match FieldMap.find name2 comps1 with
| (id1, item1, pos1) ->
let new_subst =
match item2 with
Sig_type _ ->
Subst.add_type id2 (Path.Pident id1) subst
| Sig_module _ ->
Subst.add_module id2 (Path.Pident id1) subst
| Sig_modtype _ ->
Subst.add_modtype id2 (Mty_ident (Path.Pident id1)) subst
| Sig_value _ | Sig_typext _
| Sig_class _ | Sig_class_type _ ->
subst
in
pair_components new_subst
((item1, item2, pos1) :: paired) unpaired rem
| exception Not_found ->
let unpaired =
if report then
item2 :: unpaired
else unpaired in
pair_components subst paired unpaired rem
end in
pair_components subst [] [] sig2
and signature_components ~in_eq ~loc old_env ~mark env subst
orig_shape shape_map paired =
match paired with
| [] -> Sign_diff.{ empty with shape_map }
| (sigi1, sigi2, pos) :: rem ->
let shape_modified = ref false in
let id, item, shape_map, present_at_runtime =
match sigi1, sigi2 with
| Sig_value(id1, valdecl1, _) ,Sig_value(_id2, valdecl2, _) ->
let item =
value_descriptions ~loc env ~mark subst id1 valdecl1 valdecl2
in
let item = mark_error_as_recoverable item in
let present_at_runtime = match valdecl2.val_kind with
| Val_prim _ -> false
| _ -> true
in
let shape_map = Shape.Map.add_value_proj shape_map id1 orig_shape in
id1, item, shape_map, present_at_runtime
| Sig_type(id1, tydec1, _, _), Sig_type(_id2, tydec2, _, _) ->
let item =
type_declarations ~loc ~old_env env ~mark subst id1 tydec1 tydec2
in
let item = mark_error_as_unrecoverable item in
let shape_map = Shape.Map.add_type_proj shape_map id1 orig_shape in
id1, item, shape_map, false
| Sig_typext(id1, ext1, _, _), Sig_typext(_id2, ext2, _, _) ->
let item =
extension_constructors ~loc env ~mark subst id1 ext1 ext2
in
let item = mark_error_as_unrecoverable item in
let shape_map =
Shape.Map.add_extcons_proj shape_map id1 orig_shape
in
id1, item, shape_map, true
| Sig_module(id1, pres1, mty1, _, _), Sig_module(_, pres2, mty2, _, _)
-> begin
let orig_shape =
Shape.(proj orig_shape (Item.module_ id1))
in
let item =
module_declarations ~in_eq ~loc env ~mark subst id1 mty1 mty2
orig_shape
in
let item, shape_map =
match item with
| Ok (cc, shape) ->
if shape != orig_shape then shape_modified := true;
let mod_shape = Shape.set_uid_if_none shape mty1.md_uid in
Ok cc, Shape.Map.add_module shape_map id1 mod_shape
| Error diff ->
Error (Error.Module_type diff),
We add the original shape to the map , even though
there is a type error .
It could still be useful for merlin .
there is a type error.
It could still be useful for merlin. *)
Shape.Map.add_module shape_map id1 orig_shape
in
let present_at_runtime, item =
match pres1, pres2, mty1.md_type with
| Mp_present, Mp_present, _ -> true, item
| _, Mp_absent, _ -> false, item
| Mp_absent, Mp_present, Mty_alias p1 ->
true, Result.map (fun i -> Tcoerce_alias (env, p1, i)) item
| Mp_absent, Mp_present, _ -> assert false
in
let item = mark_error_as_unrecoverable item in
id1, item, shape_map, present_at_runtime
end
| Sig_modtype(id1, info1, _), Sig_modtype(_id2, info2, _) ->
let item =
modtype_infos ~in_eq ~loc env ~mark subst id1 info1 info2
in
let shape_map =
Shape.Map.add_module_type_proj shape_map id1 orig_shape
in
let item = mark_error_as_unrecoverable item in
id1, item, shape_map, false
| Sig_class(id1, decl1, _, _), Sig_class(_id2, decl2, _, _) ->
let item =
class_declarations ~old_env env subst decl1 decl2
in
let shape_map =
Shape.Map.add_class_proj shape_map id1 orig_shape
in
let item = mark_error_as_unrecoverable item in
id1, item, shape_map, true
| Sig_class_type(id1, info1, _, _), Sig_class_type(_id2, info2, _, _) ->
let item =
class_type_declarations ~loc ~old_env env subst info1 info2
in
let item = mark_error_as_unrecoverable item in
let shape_map =
Shape.Map.add_class_type_proj shape_map id1 orig_shape
in
id1, item, shape_map, false
| _ ->
assert false
in
let deep_modifications = !shape_modified in
let first =
match item with
| Ok x ->
let runtime_coercions =
if present_at_runtime then [pos,x] else []
in
Sign_diff.{ empty with deep_modifications; runtime_coercions }
| Error { error; recoverable=_ } ->
Sign_diff.{ empty with errors=[id,error]; deep_modifications }
in
let continue = match item with
| Ok _ -> true
| Error x -> x.recoverable
in
let rest =
if continue then
signature_components ~in_eq ~loc old_env ~mark env subst
orig_shape shape_map rem
else Sign_diff.{ empty with leftovers=rem }
in
Sign_diff.merge first rest
and module_declarations ~in_eq ~loc env ~mark subst id1 md1 md2 orig_shape =
Builtin_attributes.check_alerts_inclusion
~def:md1.md_loc
~use:md2.md_loc
loc
md1.md_attributes md2.md_attributes
(Ident.name id1);
let p1 = Path.Pident id1 in
if mark_positive mark then
Env.mark_module_used md1.md_uid;
strengthened_modtypes ~in_eq ~loc ~aliasable:true env ~mark subst
md1.md_type p1 md2.md_type orig_shape
and modtype_infos ~in_eq ~loc env ~mark subst id info1 info2 =
Builtin_attributes.check_alerts_inclusion
~def:info1.mtd_loc
~use:info2.mtd_loc
loc
info1.mtd_attributes info2.mtd_attributes
(Ident.name id);
let info2 = Subst.modtype_declaration Keep subst info2 in
let r =
match (info1.mtd_type, info2.mtd_type) with
(None, None) -> Ok Tcoerce_none
| (Some _, None) -> Ok Tcoerce_none
| (Some mty1, Some mty2) ->
check_modtype_equiv ~in_eq ~loc env ~mark mty1 mty2
| (None, Some mty2) ->
let mty1 = Mty_ident(Path.Pident id) in
check_modtype_equiv ~in_eq ~loc env ~mark mty1 mty2 in
match r with
| Ok _ as ok -> ok
| Error e -> Error Error.(Module_type_declaration (diff info1 info2 e))
and check_modtype_equiv ~in_eq ~loc env ~mark mty1 mty2 =
let c1 =
modtypes ~in_eq:true ~loc env ~mark Subst.identity mty1 mty2 Shape.dummy_mod
in
let c2 =
For nested module type paths , we check only one side of the equivalence :
the outer module type is the one responsible for checking the other side
of the equivalence .
the outer module type is the one responsible for checking the other side
of the equivalence.
*)
if in_eq then None
else
let mark = negate_mark mark in
Some (
modtypes ~in_eq:true ~loc env ~mark Subst.identity
mty2 mty1 Shape.dummy_mod
)
in
match c1, c2 with
| Ok (Tcoerce_none, _), (Some Ok (Tcoerce_none, _)|None) -> Ok Tcoerce_none
| Ok (c1, _), (Some Ok _ | None) ->
Error Error.(Illegal_permutation c1)
| Ok _, Some Error e -> Error Error.(Not_greater_than e)
| Error e, (Some Ok _ | None) -> Error Error.(Not_less_than e)
| Error less_than, Some Error greater_than ->
Error Error.(Incomparable {less_than; greater_than})
let can_alias env path =
let rec no_apply = function
| Path.Pident _ -> true
| Path.Pdot(p, _) -> no_apply p
| Path.Papply _ -> false
in
no_apply path && not (Env.is_functor_arg path env)
type explanation = Env.t * Error.all
exception Error of explanation
exception Apply_error of {
loc : Location.t ;
env : Env.t ;
lid_app : Longident.t option ;
mty_f : module_type ;
args : (Error.functor_arg_descr * module_type) list ;
}
let check_modtype_inclusion_raw ~loc env mty1 path1 mty2 =
let aliasable = can_alias env path1 in
strengthened_modtypes ~in_eq:false ~loc ~aliasable env ~mark:Mark_both
Subst.identity mty1 path1 mty2 Shape.dummy_mod
|> Result.map fst
let check_modtype_inclusion ~loc env mty1 path1 mty2 =
match check_modtype_inclusion_raw ~loc env mty1 path1 mty2 with
| Ok _ -> None
| Error e -> Some (env, Error.In_Module_type e)
let check_functor_application_in_path
~errors ~loc ~lid_whole_app ~f0_path ~args
~arg_path ~arg_mty ~param_mty env =
match check_modtype_inclusion_raw ~loc env arg_mty arg_path param_mty with
| Ok _ -> ()
| Error _errs ->
if errors then
let prepare_arg (arg_path, arg_mty) =
let aliasable = can_alias env arg_path in
let smd = Mtype.strengthen ~aliasable env arg_mty arg_path in
(Error.Named arg_path, smd)
in
let mty_f = (Env.find_module f0_path env).md_type in
let args = List.map prepare_arg args in
let lid_app = Some lid_whole_app in
raise (Apply_error {loc; env; lid_app; mty_f; args})
else
raise Not_found
let () =
Env.check_functor_application := check_functor_application_in_path
let compunit env ~mark impl_name impl_sig intf_name intf_sig unit_shape =
match
signatures ~in_eq:false ~loc:(Location.in_file impl_name) env ~mark
Subst.identity impl_sig intf_sig unit_shape
with Result.Error reasons ->
let cdiff =
Error.In_Compilation_unit(Error.diff impl_name intf_name reasons) in
raise(Error(env, cdiff))
| Ok x -> x
module Functor_inclusion_diff = struct
module Defs = struct
type left = Types.functor_parameter
type right = left
type eq = Typedtree.module_coercion
type diff = (Types.functor_parameter, unit) Error.functor_param_symptom
type state = {
res: module_type option;
env: Env.t;
subst: Subst.t;
}
end
open Defs
module Diff = Diffing.Define(Defs)
let param_name = function
| Named(x,_) -> x
| Unit -> None
let weight: Diff.change -> _ = function
| Insert _ -> 10
| Delete _ -> 10
| Change _ -> 10
| Keep (param1, param2, _) -> begin
match param_name param1, param_name param2 with
| None, None
-> 0
| Some n1, Some n2
when String.equal (Ident.name n1) (Ident.name n2)
-> 0
| Some _, Some _ -> 1
| Some _, None | None, Some _ -> 1
end
let keep_expansible_param = function
| Mty_ident _ | Mty_alias _ as mty -> Some mty
| Mty_signature _ | Mty_functor _ | Mty_for_hole -> None
let lookup_expansion { env ; res ; _ } = match res with
| None -> None
| Some res ->
match retrieve_functor_params env res with
| [], _ -> None
| params, res ->
let more = Array.of_list params in
Some (keep_expansible_param res, more)
let expand_params state =
match lookup_expansion state with
| None -> state, [||]
| Some (res, expansion) -> { state with res }, expansion
let update (d:Diff.change) st = match d with
| Insert (Unit | Named (None,_))
| Delete (Unit | Named (None,_))
| Keep (Unit,_,_)
| Keep (_,Unit,_)
| Change (_,(Unit | Named (None,_)), _) ->
st, [||]
| Insert (Named (Some id, arg))
| Delete (Named (Some id, arg))
| Change (Unit, Named (Some id, arg), _) ->
let arg' = Subst.modtype Keep st.subst arg in
let env = Env.add_module id Mp_present arg' st.env in
expand_params { st with env }
| Keep (Named (name1, _), Named (name2, arg2), _)
| Change (Named (name1, _), Named (name2, arg2), _) -> begin
let arg' = Subst.modtype Keep st.subst arg2 in
match name1, name2 with
| Some id1, Some id2 ->
let env = Env.add_module id1 Mp_present arg' st.env in
let subst = Subst.add_module id2 (Path.Pident id1) st.subst in
expand_params { st with env; subst }
| None, Some id2 ->
let env = Env.add_module id2 Mp_present arg' st.env in
{ st with env }, [||]
| Some id1, None ->
let env = Env.add_module id1 Mp_present arg' st.env in
expand_params { st with env }
| None, None ->
st, [||]
end
let diff env (l1,res1) (l2,_) =
let module Compute = Diff.Left_variadic(struct
let test st mty1 mty2 =
let loc = Location.none in
let res, _, _ =
functor_param ~in_eq:false ~loc st.env ~mark:Mark_neither
st.subst mty1 mty2
in
res
let update = update
let weight = weight
end)
in
let param1 = Array.of_list l1 in
let param2 = Array.of_list l2 in
let state =
{ env; subst = Subst.identity; res = keep_expansible_param res1}
in
Compute.diff state param1 param2
end
module Functor_app_diff = struct
module I = Functor_inclusion_diff
module Defs= struct
type left = Error.functor_arg_descr * Types.module_type
type right = Types.functor_parameter
type eq = Typedtree.module_coercion
type diff = (Error.functor_arg_descr, unit) Error.functor_param_symptom
type state = I.Defs.state
end
module Diff = Diffing.Define(Defs)
let weight: Diff.change -> _ = function
| Insert _ -> 10
| Delete _ -> 10
| Change _ -> 10
| Keep (param1, param2, _) ->
begin
let desc1 : Error.functor_arg_descr = fst param1 in
match desc1, I.param_name param2 with
| (Unit | Anonymous) , None
-> 0
| Named (Path.Pident n1), Some n2
when String.equal (Ident.name n1) (Ident.name n2)
-> 0
| Named _, Some _ -> 1
| Named _, None | (Unit | Anonymous), Some _ -> 1
end
let update (d: Diff.change) (st:Defs.state) =
let open Error in
match d with
| Insert _
| Delete _
| Keep ((Unit,_),_,_)
| Keep (_,Unit,_)
| Change (_,(Unit | Named (None,_)), _ )
| Change ((Unit,_), Named (Some _, _), _) ->
st, [||]
| Keep ((Named arg, _mty) , Named (param_name, _param), _)
| Change ((Named arg, _mty), Named (param_name, _param), _) ->
begin match param_name with
| Some param ->
let res =
Option.map (fun res ->
let scope = Ctype.create_scope () in
let subst = Subst.add_module param arg Subst.identity in
Subst.modtype (Rescope scope) subst res
)
st.res
in
let subst = Subst.add_module param arg st.subst in
I.expand_params { st with subst; res }
| None ->
st, [||]
end
| Keep ((Anonymous, mty) , Named (param_name, _param), _)
| Change ((Anonymous, mty), Named (param_name, _param), _) -> begin
begin match param_name with
| Some param ->
let mty' = Subst.modtype Keep st.subst mty in
let env =
Env.add_module ~arg:true param Mp_present mty' st.env in
let res =
Option.map (Mtype.nondep_supertype env [param]) st.res in
I.expand_params { st with env; res}
| None ->
st, [||]
end
end
let diff env ~f ~args =
let params, res = retrieve_functor_params env f in
let module Compute = Diff.Right_variadic(struct
let update = update
let test (state:Defs.state) (arg,arg_mty) param =
let loc = Location.none in
let res = match (arg:Error.functor_arg_descr), param with
| Unit, Unit -> Ok Tcoerce_none
| Unit, Named _ | (Anonymous | Named _), Unit ->
Result.Error (Error.Incompatible_params(arg,param))
| ( Anonymous | Named _ ) , Named (_, param) ->
match
modtypes ~in_eq:false ~loc state.env ~mark:Mark_neither
state.subst arg_mty param Shape.dummy_mod
with
| Error mty -> Result.Error (Error.Mismatch mty)
| Ok (cc, _) -> Ok cc
in
res
let weight = weight
end)
in
let args = Array.of_list args in
let params = Array.of_list params in
let state : Defs.state =
{ env; subst = Subst.identity; res = I.keep_expansible_param res }
in
Compute.diff state args params
end
let modtypes_with_shape ~shape ~loc env ~mark mty1 mty2 =
match modtypes ~in_eq:false ~loc env ~mark
Subst.identity mty1 mty2 shape
with
| Ok (cc, shape) -> cc, shape
| Error reason -> raise (Error (env, Error.(In_Module_type reason)))
let modtypes ~loc env ~mark mty1 mty2 =
match modtypes ~in_eq:false ~loc env ~mark
Subst.identity mty1 mty2 Shape.dummy_mod
with
| Ok (cc, _) -> cc
| Error reason -> raise (Error (env, Error.(In_Module_type reason)))
let signatures env ~mark sig1 sig2 =
match signatures ~in_eq:false ~loc:Location.none env ~mark
Subst.identity sig1 sig2 Shape.dummy_mod
with
| Ok (cc, _) -> cc
| Error reason -> raise (Error(env,Error.(In_Signature reason)))
let type_declarations ~loc env ~mark id decl1 decl2 =
match type_declarations ~loc env ~mark Subst.identity id decl1 decl2 with
| Ok _ -> ()
| Error (Error.Core reason) ->
raise (Error(env,Error.(In_Type_declaration(id,reason))))
| Error _ -> assert false
let strengthened_module_decl ~loc ~aliasable env ~mark md1 path1 md2 =
match strengthened_module_decl ~loc ~aliasable env ~mark Subst.identity
md1 path1 md2 Shape.dummy_mod with
| Ok (x, _shape) -> x
| Error mdiff ->
raise (Error(env,Error.(In_Module_type mdiff)))
let expand_module_alias ~strengthen env path =
match expand_module_alias ~strengthen env path with
| Ok x -> x
| Result.Error _ ->
raise (Error(env,In_Expansion(Error.Unbound_module_path path)))
let check_modtype_equiv ~loc env id mty1 mty2 =
match check_modtype_equiv ~in_eq:false ~loc env ~mark:Mark_both mty1 mty2 with
| Ok _ -> ()
| Error e ->
raise (Error(env,
Error.(In_Module_type_substitution (id,diff mty1 mty2 e)))
)
|
2aacc7821889560bc5a5a328d392d329ff46b6a1011d2a039a288fdc9ab61359 | bjornbm/astro | Celestrak.hs | # LANGUAGE FlexibleContexts #
module Astro.Celestrak where
import Numeric.Units.Dimensional.Prelude
import Astro.Time
import Astro.Time.Interop
import Data.Char (isSpace)
import Data.Maybe (fromJust)
import Data.Ratio
import Data.List (isPrefixOf)
import Data.Time
import Data.Time.Clock.TAI
import qualified Prelude as P
import Data.Array.IArray
-- Celestrak
-- =========
| Datatype holding all the parameters given in Celestrak EOP data file
for a single day .
data EOPData a = EOPData
{ x :: Angle a
, y :: Angle a
, ut1MinusUTC :: Time a
, lod :: Time a
, dPsi :: Angle a
, dEpsilon :: Angle a
, dX :: Angle a
, dY :: Angle a
, deltaAT :: Integer
} deriving (Show, Eq)
| Aggregates of the above indexed / coupled with ' Day 's .
type EOPList a = [(Day, EOPData a)]
type EOPArray a = Array Day (EOPData a)
| Parses a single line of EOP data .
parseEOPLine :: (Read a, Floating a) => String -> (Day, EOPData a)
parseEOPLine s = ( ModifiedJulianDay (read mjd)
, EOPData (readAngle x) (readAngle y)
(readTime ut1MinusUTC) (readTime lod)
(readAngle dPsi) (readAngle dEpsilon)
(readAngle dX) (readAngle dY)
(read deltaAT)
)
where
[_, _, _, mjd, x, y, ut1MinusUTC, lod, dPsi, dEpsilon, dX, dY, deltaAT] = words s
readTime = (*~ second) . read
readAngle = (*~ arcsecond) . read
| Parse a file of Celestrak EOP data into a list .
parseEOPData :: (Read a, Floating a) => String -> EOPList a
parseEOPData file = map parseEOPLine (observed ++ predicted)
where
a = lines file
b = tail $ dropWhile (not . isPrefixOf "BEGIN OBSERVED") a
observed = takeWhile (not . isPrefixOf "END OBSERVED") b
c = tail $ dropWhile (not . isPrefixOf "BEGIN PREDICTED") b
predicted = takeWhile (not . isPrefixOf "END PREDICTED") c
| Creates and EOPArray from an EOPList . Assumes that the EOPList is
complete , i.e. there is one element per day and that the first and last
elements bound the days .
mkEOPArray :: EOPList a -> EOPArray a
mkEOPArray table = array (fst $ head table, fst $ last table) table
| Creates a ' Data . Time . Clock . TAI.LeapSecondMap ' from an ' EOPArray ' .
mkLeapSecondMap :: EOPArray a -> LeapSecondMap
mkLeapSecondMap a d = Just . fromIntegral
$ if d <= i then get i else if d >= j then get j else get d
TODO Is this sensible , or should Nothing be returned outside bounds ?
where
(i,j) = bounds a
get = deltaAT . (a!)
-- | Returns the UTC day that the epoch occurs on.
getUTCDay :: (Real a, Fractional a) => LeapSecondMap -> E TAI a -> Day
getUTCDay lst = utctDay . fromJust . taiToUTCTime lst . toAbsoluteTime
TODO ^^^^^^^^ error handling or fail in Astro ?
| Creates a ' UT1Table ' from an ' EOPArray ' .
TODO : The IERS explanatory supplement
< > says :
" There are short - periodic ( diurnal , semi - diurnal ) variations in UT1 due
to ocean tides that are treated similarly to polar motion ( the IERS
publishes the daily values from which these terms have been removed ,
and they are to be added back after the interpolation ) . "
Suitable interpolation method and addition of tides are described at
< -gaz13 > .
TODO: The IERS explanatory supplement
<> says:
"There are short-periodic (diurnal, semi-diurnal) variations in UT1 due
to ocean tides that are treated similarly to polar motion (the IERS
publishes the daily values from which these terms have been removed,
and they are to be added back after the interpolation)."
Suitable interpolation method and addition of tides are described at
<-gaz13>.
-}
mkUT1Table :: (Real a, Fractional a) => EOPArray a -> UT1MinusTAI a
mkUT1Table a t = if d < i then get i else if d >= j then get j
else interpolate (t0, get d) (t1, get $ succ d) t
where
lst = mkLeapSecondMap a
(i,j) = bounds a
d = getUTCDay lst t
t0 = utcDayToTAI d
t1 = utcDayToTAI (succ d)
utcDayToTAI d = fromAbsoluteTime $ fromJust $ utcToTAITime lst (UTCTime d 0)
TODO ^^^^^^^^ error handling or fail in Astro ?
get n = ut1MinusUTC (a!n) - fromInteger (deltaAT (a!n)) *~ second
-- The following are subject to extraction to a util module if they
-- turn out to be useful elsewhere.
Linear interpolation is obviously simplistic . Another method should be
used , see e.g. < -gaz13 > . This recommendation
is from 1997 . Verify that it is still relevant for IERS2003 ... perhaps
the CSSI paper on EOP addresses this ? Or AsA2009 ?
Linear interpolation is obviously simplistic. Another method should be
used, see e.g. <-gaz13>. This recommendation
is from 1997. Verify that it is still relevant for IERS2003... perhaps
the CSSI paper on EOP addresses this? Or AsA2009?
-}
| Linear interpolation between two points .
interpolate :: Fractional a => (E t a, Quantity d a) -> (E t a, Quantity d a) -> E t a -> Quantity d a
interpolate (t0, x0) (t1, x1) t = (t .- t0) / (t1 .- t0) * (x1 - x0) + x0
where (.-) = diffEpoch
| null | https://raw.githubusercontent.com/bjornbm/astro/f4fb2c4b739a0a8f68f51aa154285120d2230c30/src/Astro/Celestrak.hs | haskell | Celestrak
=========
| Returns the UTC day that the epoch occurs on.
The following are subject to extraction to a util module if they
turn out to be useful elsewhere. | # LANGUAGE FlexibleContexts #
module Astro.Celestrak where
import Numeric.Units.Dimensional.Prelude
import Astro.Time
import Astro.Time.Interop
import Data.Char (isSpace)
import Data.Maybe (fromJust)
import Data.Ratio
import Data.List (isPrefixOf)
import Data.Time
import Data.Time.Clock.TAI
import qualified Prelude as P
import Data.Array.IArray
| Datatype holding all the parameters given in Celestrak EOP data file
for a single day .
data EOPData a = EOPData
{ x :: Angle a
, y :: Angle a
, ut1MinusUTC :: Time a
, lod :: Time a
, dPsi :: Angle a
, dEpsilon :: Angle a
, dX :: Angle a
, dY :: Angle a
, deltaAT :: Integer
} deriving (Show, Eq)
| Aggregates of the above indexed / coupled with ' Day 's .
type EOPList a = [(Day, EOPData a)]
type EOPArray a = Array Day (EOPData a)
| Parses a single line of EOP data .
parseEOPLine :: (Read a, Floating a) => String -> (Day, EOPData a)
parseEOPLine s = ( ModifiedJulianDay (read mjd)
, EOPData (readAngle x) (readAngle y)
(readTime ut1MinusUTC) (readTime lod)
(readAngle dPsi) (readAngle dEpsilon)
(readAngle dX) (readAngle dY)
(read deltaAT)
)
where
[_, _, _, mjd, x, y, ut1MinusUTC, lod, dPsi, dEpsilon, dX, dY, deltaAT] = words s
readTime = (*~ second) . read
readAngle = (*~ arcsecond) . read
| Parse a file of Celestrak EOP data into a list .
parseEOPData :: (Read a, Floating a) => String -> EOPList a
parseEOPData file = map parseEOPLine (observed ++ predicted)
where
a = lines file
b = tail $ dropWhile (not . isPrefixOf "BEGIN OBSERVED") a
observed = takeWhile (not . isPrefixOf "END OBSERVED") b
c = tail $ dropWhile (not . isPrefixOf "BEGIN PREDICTED") b
predicted = takeWhile (not . isPrefixOf "END PREDICTED") c
| Creates and EOPArray from an EOPList . Assumes that the EOPList is
complete , i.e. there is one element per day and that the first and last
elements bound the days .
mkEOPArray :: EOPList a -> EOPArray a
mkEOPArray table = array (fst $ head table, fst $ last table) table
| Creates a ' Data . Time . Clock . TAI.LeapSecondMap ' from an ' EOPArray ' .
mkLeapSecondMap :: EOPArray a -> LeapSecondMap
mkLeapSecondMap a d = Just . fromIntegral
$ if d <= i then get i else if d >= j then get j else get d
TODO Is this sensible , or should Nothing be returned outside bounds ?
where
(i,j) = bounds a
get = deltaAT . (a!)
getUTCDay :: (Real a, Fractional a) => LeapSecondMap -> E TAI a -> Day
getUTCDay lst = utctDay . fromJust . taiToUTCTime lst . toAbsoluteTime
TODO ^^^^^^^^ error handling or fail in Astro ?
| Creates a ' UT1Table ' from an ' EOPArray ' .
TODO : The IERS explanatory supplement
< > says :
" There are short - periodic ( diurnal , semi - diurnal ) variations in UT1 due
to ocean tides that are treated similarly to polar motion ( the IERS
publishes the daily values from which these terms have been removed ,
and they are to be added back after the interpolation ) . "
Suitable interpolation method and addition of tides are described at
< -gaz13 > .
TODO: The IERS explanatory supplement
<> says:
"There are short-periodic (diurnal, semi-diurnal) variations in UT1 due
to ocean tides that are treated similarly to polar motion (the IERS
publishes the daily values from which these terms have been removed,
and they are to be added back after the interpolation)."
Suitable interpolation method and addition of tides are described at
<-gaz13>.
-}
mkUT1Table :: (Real a, Fractional a) => EOPArray a -> UT1MinusTAI a
mkUT1Table a t = if d < i then get i else if d >= j then get j
else interpolate (t0, get d) (t1, get $ succ d) t
where
lst = mkLeapSecondMap a
(i,j) = bounds a
d = getUTCDay lst t
t0 = utcDayToTAI d
t1 = utcDayToTAI (succ d)
utcDayToTAI d = fromAbsoluteTime $ fromJust $ utcToTAITime lst (UTCTime d 0)
TODO ^^^^^^^^ error handling or fail in Astro ?
get n = ut1MinusUTC (a!n) - fromInteger (deltaAT (a!n)) *~ second
Linear interpolation is obviously simplistic . Another method should be
used , see e.g. < -gaz13 > . This recommendation
is from 1997 . Verify that it is still relevant for IERS2003 ... perhaps
the CSSI paper on EOP addresses this ? Or AsA2009 ?
Linear interpolation is obviously simplistic. Another method should be
used, see e.g. <-gaz13>. This recommendation
is from 1997. Verify that it is still relevant for IERS2003... perhaps
the CSSI paper on EOP addresses this? Or AsA2009?
-}
| Linear interpolation between two points .
interpolate :: Fractional a => (E t a, Quantity d a) -> (E t a, Quantity d a) -> E t a -> Quantity d a
interpolate (t0, x0) (t1, x1) t = (t .- t0) / (t1 .- t0) * (x1 - x0) + x0
where (.-) = diffEpoch
|
87c98f1f34155134518f14035e7662cb92f32fe70cfa06bcd330bc8dbeb905ef | AvisoNovate/rook | arg_resolvers.clj | (ns io.aviso.rook.arg-resolvers
"Built-in implementations and support functions for argument resolver generators."
{:added "0.2.2"})
(defn non-nil-arg-resolver
"Returns an arg resolver that extracts a value nested in the context.
The value must be non-nil, or an exception is thrown.
sym
: The symbol for which the argument resolver was created; identified in the exception.
ks
: a sequence of keys."
[sym ks]
(fn [context]
(let [v (get-in context ks)]
(if (some? v)
v
(throw (ex-info "Resolved argument value was nil."
{:type ::nil-argument-value
:parameter sym
:context-key-path ks}))))))
(defn standard-arg-resolver
"Returns an arg resolver that extracts a value nested in the context.
ks
: A sequence of keys."
[ks]
(fn [context]
(get-in context ks)))
(defn meta-value-for-parameter
"Given a parameter symbol and a metadata key, returns the value for that metadata key.
It is presumed that the value is a keyword, though no check is made.
When the metadata value is explicitly true, the symbol is converted into a simple (not namespaced)
keyword."
[sym meta-key]
(let [meta-value (-> sym meta (get meta-key))]
;; This catches the typical default cause where the meta value is true,
;; typically meaning the ^:my-resolver format was used. In that situation,
;; convert the symbol name to an unqualified keyword.
(if (true? meta-value)
(-> sym name keyword)
meta-value)))
(defn ^:private request-resolver
[sym]
(non-nil-arg-resolver sym [:request (meta-value-for-parameter sym :request)]))
(defn ^:private path-param-resolver
[sym]
(non-nil-arg-resolver sym [:request :path-params (meta-value-for-parameter sym :path-param)]))
(defn ^:private query-param-resolver
[sym]
(standard-arg-resolver
[:request :query-params (meta-value-for-parameter sym :query-param)]))
(defn ^:private form-param-resolver
[sym]
(standard-arg-resolver [:request :form-params (meta-value-for-parameter sym :form-param)]))
(def default-arg-resolvers
"Defines the following argument resolvers:
:request
: The argument resolves to a key in the :request map.
: An exception is thrown if the resolved value is nil.
:path-param
: The argument resolves to a path parameter.
: An exception is thrown if the resolved value is nil.
:query-param
: The argument resolves to a query parameter, as applied by the
default io.pedestal.http.route/query-params interceptor.
:form-param
: As :query-param, but for the encoded form parameters.
Assumes the necessary middleware to process the body into form parameters
and keywordize the keys is present.
For these resolvers if the meta data value is exactly the value true
(e.g., just using ^:request),
then the effective value is a keyword generated from the parameter symbol."
{:request request-resolver
:path-param path-param-resolver
:query-param query-param-resolver
:form-param form-param-resolver})
(defn inject-resolver
"For a given meta-data key and map of injections, returns
an arg-resolver generator, wrapped in a map that can be
merged with [[default-arg-resolvers]].
Parameters are converted to keys into the injections map.
The injections map should use keyword keys.
Will throw an exception if a parameter symbol fails to match a non-nil
value in the injections map."
[meta-key injections]
(let [generator (fn [sym]
(if-let [value (->> (meta-value-for-parameter sym meta-key)
(get injections))]
(fn [_] value)
(throw (ex-info "Unknown injection key."
{:type ::unknown-injection
:symbol sym
:meta-key meta-key
:injection-keys (keys injections)}))))]
{meta-key generator}))
| null | https://raw.githubusercontent.com/AvisoNovate/rook/a752ce97f39a5c52301dd1866195f463817a1ed7/src/io/aviso/rook/arg_resolvers.clj | clojure | identified in the exception.
This catches the typical default cause where the meta value is true,
typically meaning the ^:my-resolver format was used. In that situation,
convert the symbol name to an unqualified keyword. | (ns io.aviso.rook.arg-resolvers
"Built-in implementations and support functions for argument resolver generators."
{:added "0.2.2"})
(defn non-nil-arg-resolver
"Returns an arg resolver that extracts a value nested in the context.
The value must be non-nil, or an exception is thrown.
sym
ks
: a sequence of keys."
[sym ks]
(fn [context]
(let [v (get-in context ks)]
(if (some? v)
v
(throw (ex-info "Resolved argument value was nil."
{:type ::nil-argument-value
:parameter sym
:context-key-path ks}))))))
(defn standard-arg-resolver
"Returns an arg resolver that extracts a value nested in the context.
ks
: A sequence of keys."
[ks]
(fn [context]
(get-in context ks)))
(defn meta-value-for-parameter
"Given a parameter symbol and a metadata key, returns the value for that metadata key.
It is presumed that the value is a keyword, though no check is made.
When the metadata value is explicitly true, the symbol is converted into a simple (not namespaced)
keyword."
[sym meta-key]
(let [meta-value (-> sym meta (get meta-key))]
(if (true? meta-value)
(-> sym name keyword)
meta-value)))
(defn ^:private request-resolver
[sym]
(non-nil-arg-resolver sym [:request (meta-value-for-parameter sym :request)]))
(defn ^:private path-param-resolver
[sym]
(non-nil-arg-resolver sym [:request :path-params (meta-value-for-parameter sym :path-param)]))
(defn ^:private query-param-resolver
[sym]
(standard-arg-resolver
[:request :query-params (meta-value-for-parameter sym :query-param)]))
(defn ^:private form-param-resolver
[sym]
(standard-arg-resolver [:request :form-params (meta-value-for-parameter sym :form-param)]))
(def default-arg-resolvers
"Defines the following argument resolvers:
:request
: The argument resolves to a key in the :request map.
: An exception is thrown if the resolved value is nil.
:path-param
: The argument resolves to a path parameter.
: An exception is thrown if the resolved value is nil.
:query-param
: The argument resolves to a query parameter, as applied by the
default io.pedestal.http.route/query-params interceptor.
:form-param
: As :query-param, but for the encoded form parameters.
Assumes the necessary middleware to process the body into form parameters
and keywordize the keys is present.
For these resolvers if the meta data value is exactly the value true
(e.g., just using ^:request),
then the effective value is a keyword generated from the parameter symbol."
{:request request-resolver
:path-param path-param-resolver
:query-param query-param-resolver
:form-param form-param-resolver})
(defn inject-resolver
"For a given meta-data key and map of injections, returns
an arg-resolver generator, wrapped in a map that can be
merged with [[default-arg-resolvers]].
Parameters are converted to keys into the injections map.
The injections map should use keyword keys.
Will throw an exception if a parameter symbol fails to match a non-nil
value in the injections map."
[meta-key injections]
(let [generator (fn [sym]
(if-let [value (->> (meta-value-for-parameter sym meta-key)
(get injections))]
(fn [_] value)
(throw (ex-info "Unknown injection key."
{:type ::unknown-injection
:symbol sym
:meta-key meta-key
:injection-keys (keys injections)}))))]
{meta-key generator}))
|
0a28017790202ba540cea12212fe83e5d410f668e83bf3010f4490080d8e58df | shiguredo/eryngii | conf.ml | open Core.Std
let version = "0.1"
let debug_mode = ref false
let verbose_mode = ref false
let debug f =
if !debug_mode then
printf ("# " ^^ f ^^ "\n")
else
Printf.ifprintf stderr f
let verbose f =
if !verbose_mode || !debug_mode then
printf ("# " ^^ f ^^ "\n")
else
Printf.ifprintf stderr f
| null | https://raw.githubusercontent.com/shiguredo/eryngii/6c70d9b28a45ed786c4847ee51bb03bfef35ac8d/conf.ml | ocaml | open Core.Std
let version = "0.1"
let debug_mode = ref false
let verbose_mode = ref false
let debug f =
if !debug_mode then
printf ("# " ^^ f ^^ "\n")
else
Printf.ifprintf stderr f
let verbose f =
if !verbose_mode || !debug_mode then
printf ("# " ^^ f ^^ "\n")
else
Printf.ifprintf stderr f
|
|
8159bea3f713f5a10ecc497bbc78467477c8be30889f6e147a5d1ada5e29ca60 | Liqwid-Labs/plutus-extra | Main.hs | { - # LANGUAGE TemplateHaskell # - }
module ( main ) where
import qualified as GHC
import PlutusCore . Data qualified as Data
import PlutusTx . IsCoexistingData ( makeCoexistingIsData )
import PlutusTx . IsData . Class ( fromData , toData )
import PlutusTx . Prelude
import Test . QuickCheck ( Property , forAllShrink , (= = =) )
-- import Test.QuickCheck.Arbitrary (Arbitrary (arbitrary, shrink))
-- import Test.QuickCheck.Gen qualified as Gen
-- import Test.QuickCheck.Instances.ByteString ()
import Test . Tasty ( TestTree , defaultMain , localOption , testGroup )
import Test . Tasty . HUnit ( Assertion , assertEqual , testCase )
-- import Test.Tasty.QuickCheck (QuickCheckTests (QuickCheckTests), testProperty)
import Prelude qualified
-- main :: Prelude.IO ()
-- main = defaultMain allTests
-- where
-- allTests :: TestTree
-- allTests =
-- testGroup
" IsData generators "
[ basicStructure
-- , roundTripping
-- ]
-- -- Helpers
data Foo = Bar | UNPACK # - } ! ByteString | Quux Integer Integer
deriving stock ( GHC.Generic , Prelude . Show , Prelude . Eq )
instance Arbitrary where
-- arbitrary =
-- Gen.oneof
-- [ Prelude.pure Bar
-- , Baz Prelude.<$> arbitrary
, Quux Prelude.<$ > arbitrary Prelude . < * > arbitrary
-- ]
-- shrink = \case
-- Bar -> []
( Bar :) $ Baz Prelude.<$ > shrink bs
Quux i j - > ( Bar :) $ Quux Prelude.<$ > shrink i Prelude . < * > shrink j
-- basicStructure :: TestTree
-- basicStructure =
-- testGroup
-- "Structure of output"
[ testCase " Representation , no arguments " barStructure
, " Representation , one argument "
, " Representation , two arguments " quuxStructure
-- ]
-- where
barStructure : : Assertion
barStructure =
-- assertEqual
-- ""
( Data . Constr 0 [ Data . I 8029713825859723597 ] )
-- (toData Bar)
: : Assertion
=
-- assertEqual
-- ""
( Data . Constr 1 [ Data . I 8029713825859723597 , Data . B " xyz " ] )
( toData . " xyz " )
-- quuxStructure :: Assertion
-- quuxStructure =
-- assertEqual
-- ""
( Data . Constr 2 [ Data . I 8029713825859723597 , Data . I 1 , Data . I 2 ] )
( toData . Quux 1 $ 2 )
-- roundTripping :: TestTree
-- roundTripping =
localOption ( QuickCheckTests 100000 )
.
-- "Round-tripping"
-- $ [ testProperty "toData >>> fromData"
-- . forAllShrink arbitrary shrink
-- $ toFrom
-- , testProperty "fromData >>> toData"
-- . forAllShrink arbitrary shrink
-- $ fromTo
-- ]
-- where
-- toFrom :: Foo -> Property
-- toFrom x = Just x === (fromData . toData $ x)
: : Foo - > Property
=
-- (Just . toData $ x) === (toData @Foo <$> (fromData . toData $ x))
-- makeCoexistingIsData ''Foo
| null | https://raw.githubusercontent.com/Liqwid-Labs/plutus-extra/347dd304e9b580d1747439a888bfaa79f1c5a25e/plutus-extra/test/is-data-tagged/Main.hs | haskell | import Test.QuickCheck.Arbitrary (Arbitrary (arbitrary, shrink))
import Test.QuickCheck.Gen qualified as Gen
import Test.QuickCheck.Instances.ByteString ()
import Test.Tasty.QuickCheck (QuickCheckTests (QuickCheckTests), testProperty)
main :: Prelude.IO ()
main = defaultMain allTests
where
allTests :: TestTree
allTests =
testGroup
, roundTripping
]
-- Helpers
arbitrary =
Gen.oneof
[ Prelude.pure Bar
, Baz Prelude.<$> arbitrary
]
shrink = \case
Bar -> []
basicStructure :: TestTree
basicStructure =
testGroup
"Structure of output"
]
where
assertEqual
""
(toData Bar)
assertEqual
""
quuxStructure :: Assertion
quuxStructure =
assertEqual
""
roundTripping :: TestTree
roundTripping =
"Round-tripping"
$ [ testProperty "toData >>> fromData"
. forAllShrink arbitrary shrink
$ toFrom
, testProperty "fromData >>> toData"
. forAllShrink arbitrary shrink
$ fromTo
]
where
toFrom :: Foo -> Property
toFrom x = Just x === (fromData . toData $ x)
(Just . toData $ x) === (toData @Foo <$> (fromData . toData $ x))
makeCoexistingIsData ''Foo | { - # LANGUAGE TemplateHaskell # - }
module ( main ) where
import qualified as GHC
import PlutusCore . Data qualified as Data
import PlutusTx . IsCoexistingData ( makeCoexistingIsData )
import PlutusTx . IsData . Class ( fromData , toData )
import PlutusTx . Prelude
import Test . QuickCheck ( Property , forAllShrink , (= = =) )
import Test . Tasty ( TestTree , defaultMain , localOption , testGroup )
import Test . Tasty . HUnit ( Assertion , assertEqual , testCase )
import Prelude qualified
" IsData generators "
[ basicStructure
data Foo = Bar | UNPACK # - } ! ByteString | Quux Integer Integer
deriving stock ( GHC.Generic , Prelude . Show , Prelude . Eq )
instance Arbitrary where
, Quux Prelude.<$ > arbitrary Prelude . < * > arbitrary
( Bar :) $ Baz Prelude.<$ > shrink bs
Quux i j - > ( Bar :) $ Quux Prelude.<$ > shrink i Prelude . < * > shrink j
[ testCase " Representation , no arguments " barStructure
, " Representation , one argument "
, " Representation , two arguments " quuxStructure
barStructure : : Assertion
barStructure =
( Data . Constr 0 [ Data . I 8029713825859723597 ] )
: : Assertion
=
( Data . Constr 1 [ Data . I 8029713825859723597 , Data . B " xyz " ] )
( toData . " xyz " )
( Data . Constr 2 [ Data . I 8029713825859723597 , Data . I 1 , Data . I 2 ] )
( toData . Quux 1 $ 2 )
localOption ( QuickCheckTests 100000 )
.
: : Foo - > Property
=
|
b631b8ee4710c727df778ef394dc954780456a30539776f740fca40d81f00787 | Tim-ats-d/Indigobi | backend.ml | open Import
module type S = sig
val get :
?bypass:Gemini.Request.bypass ->
url:string ->
host:string ->
port:int ->
cert:Tls.Config.own_cert option ->
float ->
(Mime.t * string, [> Err.back | Gemini.Status.err ]) Lwt_result.t
val cert_from_file :
string -> (Tls.Config.own_cert option, [> Common.Err.back ]) Lwt_result.t
end
module Make (Prompt : Prompt.S) (Requester : Requester.S) : S = struct
open Lwt.Syntax
let cert_from_file cert =
if cert = "" then Lwt_result.ok @@ Lwt.return None
else
try%lwt
let* cert_str = Lwt_io.with_file ~mode:Input cert Lwt_io.read in
let cert_re =
Str.regexp
{|\(-----BEGIN CERTIFICATE-----.+-----END CERTIFICATE-----\) \(-----BEGIN PRIVATE KEY-----.+-----END PRIVATE KEY-----\)|}
in
match
Str.replace_first cert_re "\\1" cert_str
|> Cstruct.of_string |> X509.Certificate.decode_pem_multiple
with
| Ok certificate -> (
match
Str.replace_first cert_re "\\2" cert_str
|> Cstruct.of_string |> X509.Private_key.decode_pem
with
| Ok priv_key ->
Lwt_result.ok @@ Lwt.return
@@ Some (`Single (certificate, priv_key))
| Error (`Msg e) -> Lwt_result.fail @@ `InvalidClientCertificate e)
| Error (`Msg e) -> Lwt_result.fail @@ `InvalidClientCertificate e
with Unix.Unix_error (Unix.ENOENT, "open", _) ->
Lwt_result.fail @@ `FileNotFound cert
let rec request timeout req =
let* socket_r = Requester.init req in
match socket_r with
| Ok socket -> (
let* header =
Requester.fetch_header socket @@ Gemini.Request.to_string req
in
match Gemini.Header.parse header with
| Error (`MalformedHeader | `TooLongHeader) ->
Lwt_result.fail `MalformedServerResponse
| Error (#Common.Err.status_code as err) -> Lwt_result.fail err
| Ok { status; meta } -> (
match status with
| `Input (meta, `Sensitive s) ->
let* input =
if s then Prompt.prompt_sensitive meta else Prompt.prompt meta
in
Lib.Url.encode input
|> Gemini.Request.attach_input req
|> request timeout
| `Success ->
let* body = Requester.parse_body socket in
let* () = Requester.close socket in
Lwt_result.ok @@ Lwt.return (Mime.parse meta, body)
| `Redirect (meta, _) ->
get ~bypass:req.bypass
~url:Lib.Url.(to_string @@ parse meta req.host)
~host:req.host ~port:req.port ~cert:req.cert timeout
| #Gemini.Status.err as err -> Lwt_result.fail err))
| Error err -> (
match err with
| `Tls (`Error (`AuthenticationFailure validation_error)) -> (
match validation_error with
| `LeafInvalidName _ ->
if%lwt
Prompt.prompt_bool
@@ Printf.sprintf
"Domain %s not present in certificate, proceed anyway?"
req.host
then
get
~bypass:{ req.bypass with host = true }
~url:req.uri ~host:req.host ~port:req.port ~cert:req.cert
timeout
else Lwt_result.fail @@ `DomainNameNotPresent req.host
| `LeafCertificateExpired _ ->
if%lwt Prompt.prompt_bool "Expired certificate, proceed anyway?"
then
get
~bypass:{ req.bypass with expiration = true }
~url:req.uri ~host:req.host ~port:req.port ~cert:req.cert
timeout
else Lwt_result.fail `ExpiredCertificate
| `InvalidFingerprint (cert, _, _) ->
if%lwt
Prompt.prompt_bool
"Untrusted certificate, replace trusted one with this new \
one?"
then
let* () =
Tofu.save_entry
{
Tofu.host = req.host;
fingerprint =
Cstruct.to_string
@@ X509.Certificate.fingerprint `SHA256 cert;
expiration_date =
Ptime.to_float_s @@ snd
@@ X509.Certificate.validity cert;
}
in
get ~bypass:req.bypass ~url:req.uri ~host:req.host
~port:req.port ~cert:req.cert timeout
else
if%lwt Prompt.prompt_bool "Proceed anyway?" then
get
~bypass:{ req.bypass with fingerprint = true }
~url:req.uri ~host:req.host ~port:req.port ~cert:req.cert
timeout
else Lwt_result.fail `UntrustedCertificate
| _ -> Lwt_result.fail @@ `SocketError err)
| _ -> Lwt_result.fail @@ `SocketError err)
and get ?(bypass = Gemini.Request.default_bypass) ~url ~host ~port ~cert
timeout =
match Gemini.Request.create url ~host ~port ~cert ~bypass with
| None -> Lwt_result.fail `MalformedLink
| Some r -> request timeout r
end
| null | https://raw.githubusercontent.com/Tim-ats-d/Indigobi/c936f8ad2e044cdce25ae631b86cdec818654696/src/backend.ml | ocaml | open Import
module type S = sig
val get :
?bypass:Gemini.Request.bypass ->
url:string ->
host:string ->
port:int ->
cert:Tls.Config.own_cert option ->
float ->
(Mime.t * string, [> Err.back | Gemini.Status.err ]) Lwt_result.t
val cert_from_file :
string -> (Tls.Config.own_cert option, [> Common.Err.back ]) Lwt_result.t
end
module Make (Prompt : Prompt.S) (Requester : Requester.S) : S = struct
open Lwt.Syntax
let cert_from_file cert =
if cert = "" then Lwt_result.ok @@ Lwt.return None
else
try%lwt
let* cert_str = Lwt_io.with_file ~mode:Input cert Lwt_io.read in
let cert_re =
Str.regexp
{|\(-----BEGIN CERTIFICATE-----.+-----END CERTIFICATE-----\) \(-----BEGIN PRIVATE KEY-----.+-----END PRIVATE KEY-----\)|}
in
match
Str.replace_first cert_re "\\1" cert_str
|> Cstruct.of_string |> X509.Certificate.decode_pem_multiple
with
| Ok certificate -> (
match
Str.replace_first cert_re "\\2" cert_str
|> Cstruct.of_string |> X509.Private_key.decode_pem
with
| Ok priv_key ->
Lwt_result.ok @@ Lwt.return
@@ Some (`Single (certificate, priv_key))
| Error (`Msg e) -> Lwt_result.fail @@ `InvalidClientCertificate e)
| Error (`Msg e) -> Lwt_result.fail @@ `InvalidClientCertificate e
with Unix.Unix_error (Unix.ENOENT, "open", _) ->
Lwt_result.fail @@ `FileNotFound cert
let rec request timeout req =
let* socket_r = Requester.init req in
match socket_r with
| Ok socket -> (
let* header =
Requester.fetch_header socket @@ Gemini.Request.to_string req
in
match Gemini.Header.parse header with
| Error (`MalformedHeader | `TooLongHeader) ->
Lwt_result.fail `MalformedServerResponse
| Error (#Common.Err.status_code as err) -> Lwt_result.fail err
| Ok { status; meta } -> (
match status with
| `Input (meta, `Sensitive s) ->
let* input =
if s then Prompt.prompt_sensitive meta else Prompt.prompt meta
in
Lib.Url.encode input
|> Gemini.Request.attach_input req
|> request timeout
| `Success ->
let* body = Requester.parse_body socket in
let* () = Requester.close socket in
Lwt_result.ok @@ Lwt.return (Mime.parse meta, body)
| `Redirect (meta, _) ->
get ~bypass:req.bypass
~url:Lib.Url.(to_string @@ parse meta req.host)
~host:req.host ~port:req.port ~cert:req.cert timeout
| #Gemini.Status.err as err -> Lwt_result.fail err))
| Error err -> (
match err with
| `Tls (`Error (`AuthenticationFailure validation_error)) -> (
match validation_error with
| `LeafInvalidName _ ->
if%lwt
Prompt.prompt_bool
@@ Printf.sprintf
"Domain %s not present in certificate, proceed anyway?"
req.host
then
get
~bypass:{ req.bypass with host = true }
~url:req.uri ~host:req.host ~port:req.port ~cert:req.cert
timeout
else Lwt_result.fail @@ `DomainNameNotPresent req.host
| `LeafCertificateExpired _ ->
if%lwt Prompt.prompt_bool "Expired certificate, proceed anyway?"
then
get
~bypass:{ req.bypass with expiration = true }
~url:req.uri ~host:req.host ~port:req.port ~cert:req.cert
timeout
else Lwt_result.fail `ExpiredCertificate
| `InvalidFingerprint (cert, _, _) ->
if%lwt
Prompt.prompt_bool
"Untrusted certificate, replace trusted one with this new \
one?"
then
let* () =
Tofu.save_entry
{
Tofu.host = req.host;
fingerprint =
Cstruct.to_string
@@ X509.Certificate.fingerprint `SHA256 cert;
expiration_date =
Ptime.to_float_s @@ snd
@@ X509.Certificate.validity cert;
}
in
get ~bypass:req.bypass ~url:req.uri ~host:req.host
~port:req.port ~cert:req.cert timeout
else
if%lwt Prompt.prompt_bool "Proceed anyway?" then
get
~bypass:{ req.bypass with fingerprint = true }
~url:req.uri ~host:req.host ~port:req.port ~cert:req.cert
timeout
else Lwt_result.fail `UntrustedCertificate
| _ -> Lwt_result.fail @@ `SocketError err)
| _ -> Lwt_result.fail @@ `SocketError err)
and get ?(bypass = Gemini.Request.default_bypass) ~url ~host ~port ~cert
timeout =
match Gemini.Request.create url ~host ~port ~cert ~bypass with
| None -> Lwt_result.fail `MalformedLink
| Some r -> request timeout r
end
|
|
5fa702e7afb5da427d18b436002ad8c9194687fe0ee560bafb30c1d4f18d74ab | ylgrgyq/resilience-for-clojure | interval_function_test.clj | (ns resilience.interval-function-test
(:require [clojure.test :refer :all]
[resilience.interval-function :refer :all])
(:import (java.util.concurrent ThreadLocalRandom)
(io.github.resilience4j.core IntervalFunction)))
(deftest test-default-interval-function
(is (= 500 (.apply (default-interval-function)
(.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)))))
(deftest test-fixed-interval-function
(testing "fixed interval"
(is (= 101 (.apply (create-interval-function 101)
(.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)))))
(testing "fixed interval with backoff function"
(let [interval-stream (.apply (create-interval-function 101 inc) (int 2))]
(is (= 102 interval-stream)))))
(deftest test-create-randomized-interval-function
(letfn [(calculate-bound [init factor]
(let [delta (* init factor)]
[(+ init delta) (- init delta)]))]
(testing "default interval function"
(let [attempt (.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)
[max-interval min-interval] (calculate-bound IntervalFunction/DEFAULT_INITIAL_INTERVAL
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-randomized-interval-function) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval millis"
(let [attempt (.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)
init-interval 1000
[max-interval min-interval] (calculate-bound init-interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-randomized-interval-function init-interval) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval and randomization factor"
(let [attempt (.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)
init-interval 1000
factor 0.5
[max-interval min-interval] (calculate-bound init-interval factor)
interval (.apply (create-randomized-interval-function init-interval factor) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))))
(deftest test-create-exponential-backoff
(testing "default function"
(let [interval (.apply (create-exponential-backoff) (int 2))]
(is (= 750 interval))))
(testing "with initial interval"
(let [interval (.apply (create-exponential-backoff 100) (int 2))]
(is (= 150 interval))))
(testing "with initial interval and multiplier"
(let [interval (.apply (create-exponential-backoff 100 2.5) (int 2))]
(is (= 250 interval)))))
(deftest test-create-exponential-randomized-interval-function
(letfn [(calculate-bound [init factor]
(let [delta (* init factor)]
[(+ init delta) (- init delta)]))]
(testing "default interval function"
(let [attempt (int 2)
interval (.apply (create-exponential-backoff IntervalFunction/DEFAULT_INITIAL_INTERVAL)
attempt)
[max-interval min-interval] (calculate-bound interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-exponential-randomized-interval-function) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval millis"
(let [attempt (int 2)
init-interval 1000
interval (.apply (create-exponential-backoff init-interval) attempt)
[max-interval min-interval] (calculate-bound interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-exponential-randomized-interval-function init-interval) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval and multiplier factor"
(let [attempt (int 2)
init-interval 1000
multiplier 3.5
interval (.apply (create-exponential-backoff init-interval multiplier) attempt)
[max-interval min-interval] (calculate-bound interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-exponential-randomized-interval-function init-interval multiplier) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval and multiplier factor and randomization factor"
(let [attempt (int 2)
init-interval 1000
multiplier 3.5
randomization-factor 0.05
interval (.apply (create-exponential-backoff init-interval multiplier) attempt)
[max-interval min-interval] (calculate-bound interval
randomization-factor)
interval (.apply (create-exponential-randomized-interval-function init-interval multiplier randomization-factor)
attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))))
| null | https://raw.githubusercontent.com/ylgrgyq/resilience-for-clojure/7b0532d1c72d416020402c15eb5699143be4b7bf/test/resilience/interval_function_test.clj | clojure | (ns resilience.interval-function-test
(:require [clojure.test :refer :all]
[resilience.interval-function :refer :all])
(:import (java.util.concurrent ThreadLocalRandom)
(io.github.resilience4j.core IntervalFunction)))
(deftest test-default-interval-function
(is (= 500 (.apply (default-interval-function)
(.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)))))
(deftest test-fixed-interval-function
(testing "fixed interval"
(is (= 101 (.apply (create-interval-function 101)
(.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)))))
(testing "fixed interval with backoff function"
(let [interval-stream (.apply (create-interval-function 101 inc) (int 2))]
(is (= 102 interval-stream)))))
(deftest test-create-randomized-interval-function
(letfn [(calculate-bound [init factor]
(let [delta (* init factor)]
[(+ init delta) (- init delta)]))]
(testing "default interval function"
(let [attempt (.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)
[max-interval min-interval] (calculate-bound IntervalFunction/DEFAULT_INITIAL_INTERVAL
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-randomized-interval-function) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval millis"
(let [attempt (.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)
init-interval 1000
[max-interval min-interval] (calculate-bound init-interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-randomized-interval-function init-interval) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval and randomization factor"
(let [attempt (.nextInt (ThreadLocalRandom/current) 1 Integer/MAX_VALUE)
init-interval 1000
factor 0.5
[max-interval min-interval] (calculate-bound init-interval factor)
interval (.apply (create-randomized-interval-function init-interval factor) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))))
(deftest test-create-exponential-backoff
(testing "default function"
(let [interval (.apply (create-exponential-backoff) (int 2))]
(is (= 750 interval))))
(testing "with initial interval"
(let [interval (.apply (create-exponential-backoff 100) (int 2))]
(is (= 150 interval))))
(testing "with initial interval and multiplier"
(let [interval (.apply (create-exponential-backoff 100 2.5) (int 2))]
(is (= 250 interval)))))
(deftest test-create-exponential-randomized-interval-function
(letfn [(calculate-bound [init factor]
(let [delta (* init factor)]
[(+ init delta) (- init delta)]))]
(testing "default interval function"
(let [attempt (int 2)
interval (.apply (create-exponential-backoff IntervalFunction/DEFAULT_INITIAL_INTERVAL)
attempt)
[max-interval min-interval] (calculate-bound interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-exponential-randomized-interval-function) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval millis"
(let [attempt (int 2)
init-interval 1000
interval (.apply (create-exponential-backoff init-interval) attempt)
[max-interval min-interval] (calculate-bound interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-exponential-randomized-interval-function init-interval) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval and multiplier factor"
(let [attempt (int 2)
init-interval 1000
multiplier 3.5
interval (.apply (create-exponential-backoff init-interval multiplier) attempt)
[max-interval min-interval] (calculate-bound interval
IntervalFunction/DEFAULT_RANDOMIZATION_FACTOR)
interval (.apply (create-exponential-randomized-interval-function init-interval multiplier) attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))
(testing "with initial interval and multiplier factor and randomization factor"
(let [attempt (int 2)
init-interval 1000
multiplier 3.5
randomization-factor 0.05
interval (.apply (create-exponential-backoff init-interval multiplier) attempt)
[max-interval min-interval] (calculate-bound interval
randomization-factor)
interval (.apply (create-exponential-randomized-interval-function init-interval multiplier randomization-factor)
attempt)]
(is (and (>= interval min-interval) (<= interval max-interval)))))))
|
|
61b3d165cc5241b284ecb2e12e4506a7d4d136286633a4ccf5e30d5ba910e1a7 | tvh/hasql-migration | MigrationTest.hs | -- |
-- Module : Database.PostgreSQL.Simple.MigrationTest
Copyright : ( c ) 2016 < > ,
( c ) 2014 < >
--
-- License : BSD-style
-- Maintainer :
-- Stability : experimental
Portability : GHC
--
-- A collection of hasql-migration specifications.
{-# LANGUAGE OverloadedStrings #-}
module Hasql.MigrationTest where
import Hasql.Session (run, QueryError)
import Hasql.Connection
import qualified Hasql.Transaction as Tx
import qualified Hasql.Transaction.Sessions as Tx
import Hasql.Migration
import Hasql.Migration.Util (existsTable)
import Test.Hspec (Spec, describe, it,
shouldBe, runIO)
runTx :: Connection -> Tx.Transaction a -> IO (Either QueryError a)
runTx con act = do
run (Tx.transaction Tx.ReadCommitted Tx.Write act) con
migrationSpec :: Connection -> Spec
migrationSpec con = describe "Migrations" $ do
let migrationScript = MigrationScript "test.sql" q
let migrationScriptAltered = MigrationScript "test.sql" ""
mds <- runIO $ loadMigrationsFromDirectory "share/test/scripts"
let migrationDir = head mds
migrationFile <- runIO $ loadMigrationFromFile "s.sql" "share/test/script.sql"
it "initializes a database" $ do
r <- runTx con $ runMigration $ MigrationInitialization
r `shouldBe` Right Nothing
it "creates the schema_migrations table" $ do
r <- runTx con $ existsTable "schema_migrations"
r `shouldBe` Right True
it "executes a migration script" $ do
r <- runTx con $ runMigration $ migrationScript
r `shouldBe` Right Nothing
it "creates the table from the executed script" $ do
r <- runTx con $ existsTable "t1"
r `shouldBe` Right True
it "skips execution of the same migration script" $ do
r <- runTx con $ runMigration $ migrationScript
r `shouldBe` Right Nothing
it "reports an error on a different checksum for the same script" $ do
r <- runTx con $ runMigration $ migrationScriptAltered
r `shouldBe` Right (Just (ScriptChanged "test.sql"))
it "executes migration scripts inside a folder" $ do
r <- runTx con $ runMigration $ migrationDir
r `shouldBe` Right Nothing
it "creates the table from the executed scripts" $ do
r <- runTx con $ existsTable "t2"
r `shouldBe` Right True
it "executes a file based migration script" $ do
r <- runTx con $ runMigration $ migrationFile
r `shouldBe` Right Nothing
it "creates the table from the executed scripts" $ do
r <- runTx con $ existsTable "t3"
r `shouldBe` Right True
it "validates initialization" $ do
r <- runTx con $ runMigration $ (MigrationValidation MigrationInitialization)
r `shouldBe` Right Nothing
it "validates an executed migration script" $ do
r <- runTx con $ runMigration $ (MigrationValidation migrationScript)
r `shouldBe` Right Nothing
it "validates all scripts inside a folder" $ do
r <- runTx con $ runMigration $ (MigrationValidation migrationDir)
r `shouldBe` Right Nothing
it "validates an executed migration file" $ do
r <- runTx con $ runMigration $ (MigrationValidation migrationFile)
r `shouldBe` Right Nothing
it "gets a list of executed migrations" $ do
r <- runTx con getMigrations
fmap (map schemaMigrationName) r `shouldBe` Right ["test.sql", "1.sql", "s.sql"]
where
q = "create table t1 (c1 varchar);"
| null | https://raw.githubusercontent.com/tvh/hasql-migration/58c90f7c5c0e829708c35db9d2c8bc47e86621eb/test/Hasql/MigrationTest.hs | haskell | |
Module : Database.PostgreSQL.Simple.MigrationTest
License : BSD-style
Maintainer :
Stability : experimental
A collection of hasql-migration specifications.
# LANGUAGE OverloadedStrings # | Copyright : ( c ) 2016 < > ,
( c ) 2014 < >
Portability : GHC
module Hasql.MigrationTest where
import Hasql.Session (run, QueryError)
import Hasql.Connection
import qualified Hasql.Transaction as Tx
import qualified Hasql.Transaction.Sessions as Tx
import Hasql.Migration
import Hasql.Migration.Util (existsTable)
import Test.Hspec (Spec, describe, it,
shouldBe, runIO)
runTx :: Connection -> Tx.Transaction a -> IO (Either QueryError a)
runTx con act = do
run (Tx.transaction Tx.ReadCommitted Tx.Write act) con
migrationSpec :: Connection -> Spec
migrationSpec con = describe "Migrations" $ do
let migrationScript = MigrationScript "test.sql" q
let migrationScriptAltered = MigrationScript "test.sql" ""
mds <- runIO $ loadMigrationsFromDirectory "share/test/scripts"
let migrationDir = head mds
migrationFile <- runIO $ loadMigrationFromFile "s.sql" "share/test/script.sql"
it "initializes a database" $ do
r <- runTx con $ runMigration $ MigrationInitialization
r `shouldBe` Right Nothing
it "creates the schema_migrations table" $ do
r <- runTx con $ existsTable "schema_migrations"
r `shouldBe` Right True
it "executes a migration script" $ do
r <- runTx con $ runMigration $ migrationScript
r `shouldBe` Right Nothing
it "creates the table from the executed script" $ do
r <- runTx con $ existsTable "t1"
r `shouldBe` Right True
it "skips execution of the same migration script" $ do
r <- runTx con $ runMigration $ migrationScript
r `shouldBe` Right Nothing
it "reports an error on a different checksum for the same script" $ do
r <- runTx con $ runMigration $ migrationScriptAltered
r `shouldBe` Right (Just (ScriptChanged "test.sql"))
it "executes migration scripts inside a folder" $ do
r <- runTx con $ runMigration $ migrationDir
r `shouldBe` Right Nothing
it "creates the table from the executed scripts" $ do
r <- runTx con $ existsTable "t2"
r `shouldBe` Right True
it "executes a file based migration script" $ do
r <- runTx con $ runMigration $ migrationFile
r `shouldBe` Right Nothing
it "creates the table from the executed scripts" $ do
r <- runTx con $ existsTable "t3"
r `shouldBe` Right True
it "validates initialization" $ do
r <- runTx con $ runMigration $ (MigrationValidation MigrationInitialization)
r `shouldBe` Right Nothing
it "validates an executed migration script" $ do
r <- runTx con $ runMigration $ (MigrationValidation migrationScript)
r `shouldBe` Right Nothing
it "validates all scripts inside a folder" $ do
r <- runTx con $ runMigration $ (MigrationValidation migrationDir)
r `shouldBe` Right Nothing
it "validates an executed migration file" $ do
r <- runTx con $ runMigration $ (MigrationValidation migrationFile)
r `shouldBe` Right Nothing
it "gets a list of executed migrations" $ do
r <- runTx con getMigrations
fmap (map schemaMigrationName) r `shouldBe` Right ["test.sql", "1.sql", "s.sql"]
where
q = "create table t1 (c1 varchar);"
|
bcd2d8e92a7ac28cd7df0c505fbec78519aff6a8011830881286367e5d47e177 | nominolo/lambdachine | Gc03.hs | # LANGUAGE NoImplicitPrelude , MagicHash , BangPatterns #
-- RUN: %bc_vm_chk
CHECK : @Result@ IND - > GHC.Bool . True`con_info
module Bc.Gc03 where
import GHC.Prim
import GHC.List
import GHC.Types
import GHC.Base
-- Tests GCing of PAPs.
# NOINLINE f #
f :: Int# -> [Box] -> [Box]
f 0# acc = acc
f n acc =
let !val = boxit n silly in
let !acc' = val : acc in
f (n -# 1#) acc'
data Box = Box !(Int -> Int#)
-- Creates a PAP
# NOINLINE #
boxit :: Int# -> (Int -> Int# -> Int -> Int#) -> Box
boxit n f = Box (f (I# n) n)
silly :: Int -> Int# -> Int -> Int#
silly (I# z) x (I# y) = z +# x *# y
check :: Int# -> Int# -> [Box] -> Bool
check len n [] = isTrue# (n ==# (len +# 1#))
check len n (Box f:xs) =
if isTrue# (f (I# 1#) ==# (n +# n)) then check len (n +# 1#) xs else False
test =
let !n = 3000# in check n 1# (f n [])
| null | https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/tests/Bc/Gc03.hs | haskell | RUN: %bc_vm_chk
Tests GCing of PAPs.
Creates a PAP | # LANGUAGE NoImplicitPrelude , MagicHash , BangPatterns #
CHECK : @Result@ IND - > GHC.Bool . True`con_info
module Bc.Gc03 where
import GHC.Prim
import GHC.List
import GHC.Types
import GHC.Base
# NOINLINE f #
f :: Int# -> [Box] -> [Box]
f 0# acc = acc
f n acc =
let !val = boxit n silly in
let !acc' = val : acc in
f (n -# 1#) acc'
data Box = Box !(Int -> Int#)
# NOINLINE #
boxit :: Int# -> (Int -> Int# -> Int -> Int#) -> Box
boxit n f = Box (f (I# n) n)
silly :: Int -> Int# -> Int -> Int#
silly (I# z) x (I# y) = z +# x *# y
check :: Int# -> Int# -> [Box] -> Bool
check len n [] = isTrue# (n ==# (len +# 1#))
check len n (Box f:xs) =
if isTrue# (f (I# 1#) ==# (n +# n)) then check len (n +# 1#) xs else False
test =
let !n = 3000# in check n 1# (f n [])
|
42886aba66b510973f211d56a4eacc32a3f4faf8cb50ae94e329a1d8eefa9f1b | finnishtransportagency/harja | palaute.cljs | (ns harja.tiedot.palaute
(:require [clojure.string :as string]
[harja.ui.ikonit :as ikonit]
[clojure.string :as str]
[reagent.core :refer [atom]]
[harja.tiedot.istunto :as istunto]
[harja.asiakas.tapahtumat :as t]
[harja.pvm :as pvm]))
(def sahkoposti-kehitystiimi "")
(def sahkoposti-paakayttaja "")
(def +linkki-koulutusvideot+ "/")
(defn mailto-kehitystiimi []
(str "mailto:" sahkoposti-kehitystiimi))
(def rivinvaihto "%0A")
(def koodiblokki "%7Bcode%7D")
(def valilyonti "%20")
(defn mailto-paakayttaja []
(str "mailto:" sahkoposti-paakayttaja))
Huomaa että rivinvaihto tulee mukaan
(def palaute-otsikko
"")
(def virhe-otsikko
"")
(defn tekniset-tiedot
([kayttaja url user-agent] (tekniset-tiedot kayttaja url user-agent nil))
([kayttaja url user-agent palautetyyppi]
(let [enc #(.encodeURIComponent js/window %)]
(str "\n---\n"
(when palautetyyppi (str "Palautetyyppi: " palautetyyppi "\n"))
"Sijainti Harjassa: " (enc url) "\n"
"Aika: " (pvm/pvm-aika-opt (pvm/nyt)) "\n"
"User agent: " (enc user-agent) "\n"
"Käyttäjä: " (enc (pr-str kayttaja))))))
(defn palaute-body-yleinen []
"Kirjoita palautteesi yläpuolelle.")
(defn palaute-body-kehitysidea []
(str "Kirjoita yläpuolelle ideasi. Ota mahdolliseen kuvakaappaukseen mukaan koko selainikkuna."))
(defn palaute-body-tekninen-ongelma []
(str "Kirjoita ylle, mitä yritit tehdä ja millaiseen ongelmaan törmäsit. Harkitse kuvakaappauksen "
"mukaan liittämistä, ne ovat meille erittäin hyödyllisiä. "
"Ota kuvakaappaukseen mukaan koko selainikkuna."))
(defn palaute-body-virhe [virheviesti]
(str
"\n---\n"
"Kirjoita ylle, mitä olit tekemässä, kun virhe tuli vastaan. Kuvakaappaukset ovat meille myös "
"hyvä apu. Ethän pyyhi alla olevia virheen teknisiä tietoja pois."
"\n---\nTekniset tiedot:\n"
virheviesti))
(defn- ilman-valimerkkeja [str]
(-> str
(string/replace " " valilyonti)
(string/replace "\n" rivinvaihto)))
(defn- lisaa-kentta
([kentta pohja lisays] (lisaa-kentta kentta pohja lisays "&"))
([kentta pohja lisays valimerkki] (if (empty? lisays)
pohja
(str pohja valimerkki kentta (ilman-valimerkkeja lisays)))))
(defn- subject
([pohja lisays] (lisaa-kentta "subject=" pohja lisays))
([pohja lisays valimerkki] (lisaa-kentta "subject=" pohja lisays valimerkki)))
(defn- body
([pohja lisays] (lisaa-kentta "body=" pohja lisays))
([pohja lisays valimerkki] (lisaa-kentta "body=" pohja lisays valimerkki)))
(defn mailto-linkki
([vastaanottaja sisalto] (mailto-linkki vastaanottaja sisalto nil))
([vastaanottaja sisalto palautetyyppi]
(-> vastaanottaja
(subject palaute-otsikko "?")
(body (str
{ code } varten
koodiblokki
rivinvaihto
sisalto
(tekniset-tiedot
@istunto/kayttaja
(-> js/window .-location .-href)
(-> js/window .-navigator .-userAgent)
palautetyyppi)
rivinvaihto
koodiblokki)
(if-not (empty? palaute-otsikko) "&" "?")))))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/b170a01ade578034392716f8ba91f08cfe130809/src/cljs/harja/tiedot/palaute.cljs | clojure | (ns harja.tiedot.palaute
(:require [clojure.string :as string]
[harja.ui.ikonit :as ikonit]
[clojure.string :as str]
[reagent.core :refer [atom]]
[harja.tiedot.istunto :as istunto]
[harja.asiakas.tapahtumat :as t]
[harja.pvm :as pvm]))
(def sahkoposti-kehitystiimi "")
(def sahkoposti-paakayttaja "")
(def +linkki-koulutusvideot+ "/")
(defn mailto-kehitystiimi []
(str "mailto:" sahkoposti-kehitystiimi))
(def rivinvaihto "%0A")
(def koodiblokki "%7Bcode%7D")
(def valilyonti "%20")
(defn mailto-paakayttaja []
(str "mailto:" sahkoposti-paakayttaja))
Huomaa että rivinvaihto tulee mukaan
(def palaute-otsikko
"")
(def virhe-otsikko
"")
(defn tekniset-tiedot
([kayttaja url user-agent] (tekniset-tiedot kayttaja url user-agent nil))
([kayttaja url user-agent palautetyyppi]
(let [enc #(.encodeURIComponent js/window %)]
(str "\n---\n"
(when palautetyyppi (str "Palautetyyppi: " palautetyyppi "\n"))
"Sijainti Harjassa: " (enc url) "\n"
"Aika: " (pvm/pvm-aika-opt (pvm/nyt)) "\n"
"User agent: " (enc user-agent) "\n"
"Käyttäjä: " (enc (pr-str kayttaja))))))
(defn palaute-body-yleinen []
"Kirjoita palautteesi yläpuolelle.")
(defn palaute-body-kehitysidea []
(str "Kirjoita yläpuolelle ideasi. Ota mahdolliseen kuvakaappaukseen mukaan koko selainikkuna."))
(defn palaute-body-tekninen-ongelma []
(str "Kirjoita ylle, mitä yritit tehdä ja millaiseen ongelmaan törmäsit. Harkitse kuvakaappauksen "
"mukaan liittämistä, ne ovat meille erittäin hyödyllisiä. "
"Ota kuvakaappaukseen mukaan koko selainikkuna."))
(defn palaute-body-virhe [virheviesti]
(str
"\n---\n"
"Kirjoita ylle, mitä olit tekemässä, kun virhe tuli vastaan. Kuvakaappaukset ovat meille myös "
"hyvä apu. Ethän pyyhi alla olevia virheen teknisiä tietoja pois."
"\n---\nTekniset tiedot:\n"
virheviesti))
(defn- ilman-valimerkkeja [str]
(-> str
(string/replace " " valilyonti)
(string/replace "\n" rivinvaihto)))
(defn- lisaa-kentta
([kentta pohja lisays] (lisaa-kentta kentta pohja lisays "&"))
([kentta pohja lisays valimerkki] (if (empty? lisays)
pohja
(str pohja valimerkki kentta (ilman-valimerkkeja lisays)))))
(defn- subject
([pohja lisays] (lisaa-kentta "subject=" pohja lisays))
([pohja lisays valimerkki] (lisaa-kentta "subject=" pohja lisays valimerkki)))
(defn- body
([pohja lisays] (lisaa-kentta "body=" pohja lisays))
([pohja lisays valimerkki] (lisaa-kentta "body=" pohja lisays valimerkki)))
(defn mailto-linkki
([vastaanottaja sisalto] (mailto-linkki vastaanottaja sisalto nil))
([vastaanottaja sisalto palautetyyppi]
(-> vastaanottaja
(subject palaute-otsikko "?")
(body (str
{ code } varten
koodiblokki
rivinvaihto
sisalto
(tekniset-tiedot
@istunto/kayttaja
(-> js/window .-location .-href)
(-> js/window .-navigator .-userAgent)
palautetyyppi)
rivinvaihto
koodiblokki)
(if-not (empty? palaute-otsikko) "&" "?")))))
|
|
0a8163d262cddb7b38d29f9f7562a59fc5d9abdbf79d41ddbc52c07dfb52c560 | susanemcg/pandoc-tufteLaTeX2GitBook | Org.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE GeneralizedNewtypeDeriving #
Copyright ( C ) 2014 >
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Copyright (C) 2014 Albert Krewinkel <>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
|
Module : Text . Pandoc . Readers . Org
Copyright : Copyright ( C ) 2014 License : GNU GPL , version 2 or above
Maintainer : >
Conversion of org - mode formatted plain text to ' Pandoc ' document .
Module : Text.Pandoc.Readers.Org
Copyright : Copyright (C) 2014 Albert Krewinkel
License : GNU GPL, version 2 or above
Maintainer : Albert Krewinkel <>
Conversion of org-mode formatted plain text to 'Pandoc' document.
-}
module Text.Pandoc.Readers.Org ( readOrg ) where
import qualified Text.Pandoc.Builder as B
import Text.Pandoc.Builder ( Inlines, Blocks, HasMeta(..), (<>)
, trimInlines )
import Text.Pandoc.Definition
import Text.Pandoc.Options
import qualified Text.Pandoc.Parsing as P
import Text.Pandoc.Parsing hiding ( F, unF, askF, asksF, runF
, newline, orderedListMarker
, parseFromString
, updateLastStrPos )
import Text.Pandoc.Shared (compactify', compactify'DL)
import Control.Applicative ( Applicative, pure
, (<$>), (<$), (<*>), (<*), (*>), (<**>) )
import Control.Arrow (first)
import Control.Monad (foldM, guard, liftM, liftM2, mzero, when)
import Control.Monad.Reader (Reader, runReader, ask, asks)
import Data.Char (isAlphaNum, toLower)
import Data.Default
import Data.List (intersperse, isPrefixOf, isSuffixOf)
import qualified Data.Map as M
import Data.Maybe (fromMaybe, isJust)
import Data.Monoid (Monoid, mconcat, mempty, mappend)
import Network.HTTP (urlEncode)
| Parse org - mode string and return a Pandoc document .
readOrg :: ReaderOptions -- ^ Reader options
-> String -- ^ String to parse (assuming @'\n'@ line endings)
-> Pandoc
readOrg opts s = readWith parseOrg def{ orgStateOptions = opts } (s ++ "\n\n")
type OrgParser = Parser [Char] OrgParserState
parseOrg :: OrgParser Pandoc
parseOrg = do
blocks' <- parseBlocks
st <- getState
let meta = runF (orgStateMeta' st) st
return $ Pandoc meta $ filter (/= Null) (B.toList $ runF blocks' st)
--
Parser State for Org
--
type OrgNoteRecord = (String, F Blocks)
type OrgNoteTable = [OrgNoteRecord]
type OrgBlockAttributes = M.Map String String
type OrgLinkFormatters = M.Map String (String -> String)
-- | Org-mode parser state
data OrgParserState = OrgParserState
{ orgStateOptions :: ReaderOptions
, orgStateAnchorIds :: [String]
, orgStateBlockAttributes :: OrgBlockAttributes
, orgStateEmphasisCharStack :: [Char]
, orgStateEmphasisNewlines :: Maybe Int
, orgStateLastForbiddenCharPos :: Maybe SourcePos
, orgStateLastPreCharPos :: Maybe SourcePos
, orgStateLastStrPos :: Maybe SourcePos
, orgStateLinkFormatters :: OrgLinkFormatters
, orgStateMeta :: Meta
, orgStateMeta' :: F Meta
, orgStateNotes' :: OrgNoteTable
}
instance HasReaderOptions OrgParserState where
extractReaderOptions = orgStateOptions
instance HasMeta OrgParserState where
setMeta field val st =
st{ orgStateMeta = setMeta field val $ orgStateMeta st }
deleteMeta field st =
st{ orgStateMeta = deleteMeta field $ orgStateMeta st }
instance HasLastStrPosition OrgParserState where
getLastStrPos = orgStateLastStrPos
setLastStrPos pos st = st{ orgStateLastStrPos = Just pos }
instance Default OrgParserState where
def = defaultOrgParserState
defaultOrgParserState :: OrgParserState
defaultOrgParserState = OrgParserState
{ orgStateOptions = def
, orgStateAnchorIds = []
, orgStateBlockAttributes = M.empty
, orgStateEmphasisCharStack = []
, orgStateEmphasisNewlines = Nothing
, orgStateLastForbiddenCharPos = Nothing
, orgStateLastPreCharPos = Nothing
, orgStateLastStrPos = Nothing
, orgStateLinkFormatters = M.empty
, orgStateMeta = nullMeta
, orgStateMeta' = return nullMeta
, orgStateNotes' = []
}
recordAnchorId :: String -> OrgParser ()
recordAnchorId i = updateState $ \s ->
s{ orgStateAnchorIds = i : (orgStateAnchorIds s) }
addBlockAttribute :: String -> String -> OrgParser ()
addBlockAttribute key val = updateState $ \s ->
let attrs = orgStateBlockAttributes s
in s{ orgStateBlockAttributes = M.insert key val attrs }
lookupBlockAttribute :: String -> OrgParser (Maybe String)
lookupBlockAttribute key =
M.lookup key . orgStateBlockAttributes <$> getState
resetBlockAttributes :: OrgParser ()
resetBlockAttributes = updateState $ \s ->
s{ orgStateBlockAttributes = orgStateBlockAttributes def }
updateLastStrPos :: OrgParser ()
updateLastStrPos = getPosition >>= \p ->
updateState $ \s -> s{ orgStateLastStrPos = Just p }
updateLastForbiddenCharPos :: OrgParser ()
updateLastForbiddenCharPos = getPosition >>= \p ->
updateState $ \s -> s{ orgStateLastForbiddenCharPos = Just p}
updateLastPreCharPos :: OrgParser ()
updateLastPreCharPos = getPosition >>= \p ->
updateState $ \s -> s{ orgStateLastPreCharPos = Just p}
pushToInlineCharStack :: Char -> OrgParser ()
pushToInlineCharStack c = updateState $ \s ->
s{ orgStateEmphasisCharStack = c:orgStateEmphasisCharStack s }
popInlineCharStack :: OrgParser ()
popInlineCharStack = updateState $ \s ->
s{ orgStateEmphasisCharStack = drop 1 . orgStateEmphasisCharStack $ s }
surroundingEmphasisChar :: OrgParser [Char]
surroundingEmphasisChar =
take 1 . drop 1 . orgStateEmphasisCharStack <$> getState
startEmphasisNewlinesCounting :: Int -> OrgParser ()
startEmphasisNewlinesCounting maxNewlines = updateState $ \s ->
s{ orgStateEmphasisNewlines = Just maxNewlines }
decEmphasisNewlinesCount :: OrgParser ()
decEmphasisNewlinesCount = updateState $ \s ->
s{ orgStateEmphasisNewlines = (\n -> n - 1) <$> orgStateEmphasisNewlines s }
newlinesCountWithinLimits :: OrgParser Bool
newlinesCountWithinLimits = do
st <- getState
return $ ((< 0) <$> orgStateEmphasisNewlines st) /= Just True
resetEmphasisNewlines :: OrgParser ()
resetEmphasisNewlines = updateState $ \s ->
s{ orgStateEmphasisNewlines = Nothing }
addLinkFormat :: String
-> (String -> String)
-> OrgParser ()
addLinkFormat key formatter = updateState $ \s ->
let fs = orgStateLinkFormatters s
in s{ orgStateLinkFormatters = M.insert key formatter fs }
addToNotesTable :: OrgNoteRecord -> OrgParser ()
addToNotesTable note = do
oldnotes <- orgStateNotes' <$> getState
updateState $ \s -> s{ orgStateNotes' = note:oldnotes }
-- The version Text.Pandoc.Parsing cannot be used, as we need additional parts
-- of the state saved and restored.
parseFromString :: OrgParser a -> String -> OrgParser a
parseFromString parser str' = do
oldLastPreCharPos <- orgStateLastPreCharPos <$> getState
updateState $ \s -> s{ orgStateLastPreCharPos = Nothing }
result <- P.parseFromString parser str'
updateState $ \s -> s{ orgStateLastPreCharPos = oldLastPreCharPos }
return result
--
-- Adaptions and specializations of parsing utilities
--
newtype F a = F { unF :: Reader OrgParserState a
} deriving (Monad, Applicative, Functor)
runF :: F a -> OrgParserState -> a
runF = runReader . unF
askF :: F OrgParserState
askF = F ask
asksF :: (OrgParserState -> a) -> F a
asksF f = F $ asks f
instance Monoid a => Monoid (F a) where
mempty = return mempty
mappend = liftM2 mappend
mconcat = fmap mconcat . sequence
trimInlinesF :: F Inlines -> F Inlines
trimInlinesF = liftM trimInlines
returnF :: a -> OrgParser (F a)
returnF = return . return
| Like @Text . Parsec . Char.newline@ , but causes additional state changes .
newline :: OrgParser Char
newline =
P.newline
<* updateLastPreCharPos
<* updateLastForbiddenCharPos
--
-- parsing blocks
--
parseBlocks :: OrgParser (F Blocks)
parseBlocks = mconcat <$> manyTill block eof
block :: OrgParser (F Blocks)
block = choice [ mempty <$ blanklines
, optionalAttributes $ choice
[ orgBlock
, figure
, table
]
, example
, drawer
, specialLine
, header
, return <$> hline
, list
, latexFragment
, noteBlock
, paraOrPlain
] <?> "block"
optionalAttributes :: OrgParser (F Blocks) -> OrgParser (F Blocks)
optionalAttributes parser = try $
resetBlockAttributes *> parseBlockAttributes *> parser
parseBlockAttributes :: OrgParser ()
parseBlockAttributes = do
attrs <- many attribute
() <$ mapM (uncurry parseAndAddAttribute) attrs
where
attribute :: OrgParser (String, String)
attribute = try $ do
key <- metaLineStart *> many1Till nonspaceChar (char ':')
val <- skipSpaces *> anyLine
return (map toLower key, val)
parseAndAddAttribute :: String -> String -> OrgParser ()
parseAndAddAttribute key value = do
let key' = map toLower key
() <$ addBlockAttribute key' value
lookupInlinesAttr :: String -> OrgParser (Maybe (F Inlines))
lookupInlinesAttr attr = try $ do
val <- lookupBlockAttribute attr
maybe (return Nothing)
(fmap Just . parseFromString parseInlines)
val
--
-- Org Blocks (#+BEGIN_... / #+END_...)
--
type BlockProperties = (Int, String) -- (Indentation, Block-Type)
orgBlock :: OrgParser (F Blocks)
orgBlock = try $ do
blockProp@(_, blkType) <- blockHeaderStart
($ blockProp) $
case blkType of
"comment" -> withRaw' (const mempty)
"html" -> withRaw' (return . (B.rawBlock blkType))
"latex" -> withRaw' (return . (B.rawBlock blkType))
"ascii" -> withRaw' (return . (B.rawBlock blkType))
"example" -> withRaw' (return . exampleCode)
"quote" -> withParsed (fmap B.blockQuote)
"verse" -> verseBlock
"src" -> codeBlock
_ -> withParsed (fmap $ divWithClass blkType)
blockHeaderStart :: OrgParser (Int, String)
blockHeaderStart = try $ (,) <$> indent <*> blockType
where
indent = length <$> many spaceChar
blockType = map toLower <$> (stringAnyCase "#+begin_" *> orgArgWord)
withRaw' :: (String -> F Blocks) -> BlockProperties -> OrgParser (F Blocks)
withRaw' f blockProp = (ignHeaders *> (f <$> rawBlockContent blockProp))
withParsed :: (F Blocks -> F Blocks) -> BlockProperties -> OrgParser (F Blocks)
withParsed f blockProp = (ignHeaders *> (f <$> parsedBlockContent blockProp))
ignHeaders :: OrgParser ()
ignHeaders = (() <$ newline) <|> (() <$ anyLine)
divWithClass :: String -> Blocks -> Blocks
divWithClass cls = B.divWith ("", [cls], [])
verseBlock :: BlockProperties -> OrgParser (F Blocks)
verseBlock blkProp = try $ do
ignHeaders
content <- rawBlockContent blkProp
fmap B.para . mconcat . intersperse (pure B.linebreak)
<$> mapM (parseFromString parseInlines) (lines content)
codeBlock :: BlockProperties -> OrgParser (F Blocks)
codeBlock blkProp = do
skipSpaces
(classes, kv) <- codeHeaderArgs <|> (mempty <$ ignHeaders)
id' <- fromMaybe "" <$> lookupBlockAttribute "name"
content <- rawBlockContent blkProp
let codeBlck = B.codeBlockWith ( id', classes, kv ) content
maybe (pure codeBlck) (labelDiv codeBlck) <$> lookupInlinesAttr "caption"
where
labelDiv blk value =
B.divWith nullAttr <$> (mappend <$> labelledBlock value
<*> pure blk)
labelledBlock = fmap (B.plain . B.spanWith ("", ["label"], []))
rawBlockContent :: BlockProperties -> OrgParser String
rawBlockContent (indent, blockType) = try $
unlines . map commaEscaped <$> manyTill indentedLine blockEnder
where
indentedLine = try $ ("" <$ blankline) <|> (indentWith indent *> anyLine)
blockEnder = try $ indentWith indent *> stringAnyCase ("#+end_" <> blockType)
parsedBlockContent :: BlockProperties -> OrgParser (F Blocks)
parsedBlockContent blkProps = try $ do
raw <- rawBlockContent blkProps
parseFromString parseBlocks (raw ++ "\n")
-- indent by specified number of spaces (or equiv. tabs)
indentWith :: Int -> OrgParser String
indentWith num = do
tabStop <- getOption readerTabStop
if num < tabStop
then count num (char ' ')
else choice [ try (count num (char ' '))
, try (char '\t' >> count (num - tabStop) (char ' ')) ]
type SwitchOption = (Char, Maybe String)
orgArgWord :: OrgParser String
orgArgWord = many1 orgArgWordChar
-- | Parse code block arguments
-- TODO: We currently don't handle switches.
codeHeaderArgs :: OrgParser ([String], [(String, String)])
codeHeaderArgs = try $ do
language <- skipSpaces *> orgArgWord
_ <- skipSpaces *> (try $ switch `sepBy` (many1 spaceChar))
parameters <- manyTill blockOption newline
let pandocLang = translateLang language
return $
if hasRundocParameters parameters
then ( [ pandocLang, rundocBlockClass ]
, map toRundocAttrib (("language", language) : parameters)
)
else ([ pandocLang ], parameters)
where hasRundocParameters = not . null
switch :: OrgParser SwitchOption
switch = try $ simpleSwitch <|> lineNumbersSwitch
where
simpleSwitch = (\c -> (c, Nothing)) <$> (oneOf "-+" *> letter)
lineNumbersSwitch = (\ls -> ('l', Just ls)) <$>
(string "-l \"" *> many1Till nonspaceChar (char '"'))
translateLang :: String -> String
translateLang "C" = "c"
translateLang "C++" = "cpp"
translateLang "emacs-lisp" = "commonlisp" -- emacs lisp is not supported
translateLang "js" = "javascript"
translateLang "lisp" = "commonlisp"
translateLang "R" = "r"
translateLang "sh" = "bash"
translateLang "sqlite" = "sql"
translateLang cs = cs
-- | Prefix used for Rundoc classes and arguments.
rundocPrefix :: String
rundocPrefix = "rundoc-"
-- | The class-name used to mark rundoc blocks.
rundocBlockClass :: String
rundocBlockClass = rundocPrefix ++ "block"
blockOption :: OrgParser (String, String)
blockOption = try $ (,) <$> orgArgKey <*> orgParamValue
inlineBlockOption :: OrgParser (String, String)
inlineBlockOption = try $ (,) <$> orgArgKey <*> orgInlineParamValue
orgArgKey :: OrgParser String
orgArgKey = try $
skipSpaces *> char ':'
*> many1 orgArgWordChar
orgParamValue :: OrgParser String
orgParamValue = try $
skipSpaces *> many1 (noneOf "\t\n\r ") <* skipSpaces
orgInlineParamValue :: OrgParser String
orgInlineParamValue = try $
skipSpaces *> many1 (noneOf "\t\n\r ]") <* skipSpaces
orgArgWordChar :: OrgParser Char
orgArgWordChar = alphaNum <|> oneOf "-_"
toRundocAttrib :: (String, String) -> (String, String)
toRundocAttrib = first ("rundoc-" ++)
commaEscaped :: String -> String
commaEscaped (',':cs@('*':_)) = cs
commaEscaped (',':cs@('#':'+':_)) = cs
commaEscaped cs = cs
example :: OrgParser (F Blocks)
example = try $ do
return . return . exampleCode =<< unlines <$> many1 exampleLine
exampleCode :: String -> Blocks
exampleCode = B.codeBlockWith ("", ["example"], [])
exampleLine :: OrgParser String
exampleLine = try $ string ": " *> anyLine
-- Drawers for properties or a logbook
drawer :: OrgParser (F Blocks)
drawer = try $ do
drawerStart
manyTill drawerLine (try drawerEnd)
return mempty
drawerStart :: OrgParser String
drawerStart = try $
skipSpaces *> drawerName <* skipSpaces <* P.newline
where drawerName = try $ char ':' *> validDrawerName <* char ':'
validDrawerName = stringAnyCase "PROPERTIES"
<|> stringAnyCase "LOGBOOK"
drawerLine :: OrgParser String
drawerLine = try anyLine
drawerEnd :: OrgParser String
drawerEnd = try $
skipSpaces *> stringAnyCase ":END:" <* skipSpaces <* P.newline
--
-- Figures
--
-- Figures (Image on a line by itself, preceded by name and/or caption)
figure :: OrgParser (F Blocks)
figure = try $ do
(cap, nam) <- nameAndCaption
src <- skipSpaces *> selfTarget <* skipSpaces <* P.newline
guard (isImageFilename src)
return $ do
cap' <- cap
return $ B.para $ B.image src nam cap'
where
nameAndCaption =
do
maybeCap <- lookupInlinesAttr "caption"
maybeNam <- lookupBlockAttribute "name"
guard $ isJust maybeCap || isJust maybeNam
return ( fromMaybe mempty maybeCap
, maybe mempty withFigPrefix maybeNam )
withFigPrefix cs =
if "fig:" `isPrefixOf` cs
then cs
else "fig:" ++ cs
--
-- Comments, Options and Metadata
specialLine :: OrgParser (F Blocks)
specialLine = fmap return . try $ metaLine <|> commentLine
metaLine :: OrgParser Blocks
metaLine = try $ mempty
<$ (metaLineStart *> (optionLine <|> declarationLine))
commentLine :: OrgParser Blocks
commentLine = try $ commentLineStart *> anyLine *> pure mempty
-- The order, in which blocks are tried, makes sure that we're not looking at
-- the beginning of a block, so we don't need to check for it
metaLineStart :: OrgParser String
metaLineStart = try $ mappend <$> many spaceChar <*> string "#+"
commentLineStart :: OrgParser String
commentLineStart = try $ mappend <$> many spaceChar <*> string "# "
declarationLine :: OrgParser ()
declarationLine = try $ do
key <- metaKey
inlinesF <- metaInlines
updateState $ \st ->
let meta' = B.setMeta <$> pure key <*> inlinesF <*> pure nullMeta
in st { orgStateMeta' = orgStateMeta' st <> meta' }
return ()
metaInlines :: OrgParser (F MetaValue)
metaInlines = fmap (MetaInlines . B.toList) <$> inlinesTillNewline
metaKey :: OrgParser String
metaKey = map toLower <$> many1 (noneOf ": \n\r")
<* char ':'
<* skipSpaces
optionLine :: OrgParser ()
optionLine = try $ do
key <- metaKey
case key of
"link" -> parseLinkFormat >>= uncurry addLinkFormat
_ -> mzero
parseLinkFormat :: OrgParser ((String, String -> String))
parseLinkFormat = try $ do
linkType <- (:) <$> letter <*> many (alphaNum <|> oneOf "-_") <* skipSpaces
linkSubst <- parseFormat
return (linkType, linkSubst)
-- | An ad-hoc, single-argument-only implementation of a printf-style format
-- parser.
parseFormat :: OrgParser (String -> String)
parseFormat = try $ do
replacePlain <|> replaceUrl <|> justAppend
where
-- inefficient, but who cares
replacePlain = try $ (\x -> concat . flip intersperse x)
<$> sequence [tillSpecifier 's', rest]
replaceUrl = try $ (\x -> concat . flip intersperse x . urlEncode)
<$> sequence [tillSpecifier 'h', rest]
justAppend = try $ (++) <$> rest
rest = manyTill anyChar (eof <|> () <$ oneOf "\n\r")
tillSpecifier c = manyTill (noneOf "\n\r") (try $ string ('%':c:""))
--
-- Headers
--
-- | Headers
header :: OrgParser (F Blocks)
header = try $ do
level <- headerStart
title <- inlinesTillNewline
return $ B.header level <$> title
headerStart :: OrgParser Int
headerStart = try $
(length <$> many1 (char '*')) <* many1 (char ' ')
-- Don't use (or need) the reader wrapper here, we want hline to be
-- @show@able. Otherwise we can't use it with @notFollowedBy'@.
| Horizontal Line ( five -- dashes or more )
hline :: OrgParser Blocks
hline = try $ do
skipSpaces
string "-----"
many (char '-')
skipSpaces
newline
return B.horizontalRule
--
-- Tables
--
data OrgTableRow = OrgContentRow (F [Blocks])
| OrgAlignRow [Alignment]
| OrgHlineRow
data OrgTable = OrgTable
{ orgTableColumns :: Int
, orgTableAlignments :: [Alignment]
, orgTableHeader :: [Blocks]
, orgTableRows :: [[Blocks]]
}
table :: OrgParser (F Blocks)
table = try $ do
lookAhead tableStart
do
rows <- tableRows
cptn <- fromMaybe (pure "") <$> lookupInlinesAttr "caption"
return $ (<$> cptn) . orgToPandocTable . normalizeTable =<< rowsToTable rows
orgToPandocTable :: OrgTable
-> Inlines
-> Blocks
orgToPandocTable (OrgTable _ aligns heads lns) caption =
B.table caption (zip aligns $ repeat 0) heads lns
tableStart :: OrgParser Char
tableStart = try $ skipSpaces *> char '|'
tableRows :: OrgParser [OrgTableRow]
tableRows = try $ many (tableAlignRow <|> tableHline <|> tableContentRow)
tableContentRow :: OrgParser OrgTableRow
tableContentRow = try $
OrgContentRow . sequence <$> (tableStart *> manyTill tableContentCell newline)
tableContentCell :: OrgParser (F Blocks)
tableContentCell = try $
fmap B.plain . trimInlinesF . mconcat <$> many1Till inline endOfCell
endOfCell :: OrgParser Char
endOfCell = try $ char '|' <|> lookAhead newline
tableAlignRow :: OrgParser OrgTableRow
tableAlignRow = try $
OrgAlignRow <$> (tableStart *> manyTill tableAlignCell newline)
tableAlignCell :: OrgParser Alignment
tableAlignCell =
choice [ try $ emptyCell *> return AlignDefault
, try $ skipSpaces
*> char '<'
*> tableAlignFromChar
<* many digit
<* char '>'
<* emptyCell
] <?> "alignment info"
where emptyCell = try $ skipSpaces *> endOfCell
tableAlignFromChar :: OrgParser Alignment
tableAlignFromChar = try $ choice [ char 'l' *> return AlignLeft
, char 'c' *> return AlignCenter
, char 'r' *> return AlignRight
]
tableHline :: OrgParser OrgTableRow
tableHline = try $
OrgHlineRow <$ (tableStart *> char '-' *> anyLine)
rowsToTable :: [OrgTableRow]
-> F OrgTable
rowsToTable = foldM (flip rowToContent) zeroTable
where zeroTable = OrgTable 0 mempty mempty mempty
normalizeTable :: OrgTable
-> OrgTable
normalizeTable (OrgTable cols aligns heads lns) =
let aligns' = fillColumns aligns AlignDefault
heads' = if heads == mempty
then mempty
else fillColumns heads (B.plain mempty)
lns' = map (`fillColumns` B.plain mempty) lns
fillColumns base padding = take cols $ base ++ repeat padding
in OrgTable cols aligns' heads' lns'
One or more horizontal rules after the first content line mark the previous
-- line as a header. All other horizontal lines are discarded.
rowToContent :: OrgTableRow
-> OrgTable
-> F OrgTable
rowToContent OrgHlineRow t = maybeBodyToHeader t
rowToContent (OrgAlignRow as) t = setLongestRow as =<< setAligns as t
rowToContent (OrgContentRow rf) t = do
rs <- rf
setLongestRow rs =<< appendToBody rs t
setLongestRow :: [a]
-> OrgTable
-> F OrgTable
setLongestRow rs t =
return t{ orgTableColumns = max (length rs) (orgTableColumns t) }
maybeBodyToHeader :: OrgTable
-> F OrgTable
maybeBodyToHeader t = case t of
OrgTable{ orgTableHeader = [], orgTableRows = b:[] } ->
return t{ orgTableHeader = b , orgTableRows = [] }
_ -> return t
appendToBody :: [Blocks]
-> OrgTable
-> F OrgTable
appendToBody r t = return t{ orgTableRows = orgTableRows t ++ [r] }
setAligns :: [Alignment]
-> OrgTable
-> F OrgTable
setAligns aligns t = return $ t{ orgTableAlignments = aligns }
--
LaTeX fragments
--
latexFragment :: OrgParser (F Blocks)
latexFragment = try $ do
envName <- latexEnvStart
content <- mconcat <$> manyTill anyLineNewline (latexEnd envName)
return . return $ B.rawBlock "latex" (content `inLatexEnv` envName)
where
c `inLatexEnv` e = mconcat [ "\\begin{", e, "}\n"
, c
, "\\end{", e, "}\n"
]
latexEnvStart :: OrgParser String
latexEnvStart = try $ do
skipSpaces *> string "\\begin{"
*> latexEnvName
<* string "}"
<* blankline
latexEnd :: String -> OrgParser ()
latexEnd envName = try $
() <$ skipSpaces
<* string ("\\end{" ++ envName ++ "}")
<* blankline
-- | Parses a LaTeX environment name.
latexEnvName :: OrgParser String
latexEnvName = try $ do
mappend <$> many1 alphaNum
<*> option "" (string "*")
--
-- Footnote defintions
--
noteBlock :: OrgParser (F Blocks)
noteBlock = try $ do
ref <- noteMarker <* skipSpaces
content <- mconcat <$> blocksTillHeaderOrNote
addToNotesTable (ref, content)
return mempty
where
blocksTillHeaderOrNote =
many1Till block (eof <|> () <$ lookAhead noteMarker
<|> () <$ lookAhead headerStart)
-- Paragraphs or Plain text
paraOrPlain :: OrgParser (F Blocks)
paraOrPlain = try $
parseInlines <**> (fmap <$> option B.plain (try $ newline *> pure B.para))
inlinesTillNewline :: OrgParser (F Inlines)
inlinesTillNewline = trimInlinesF . mconcat <$> manyTill inline newline
--
-- list blocks
--
list :: OrgParser (F Blocks)
list = choice [ definitionList, bulletList, orderedList ] <?> "list"
definitionList :: OrgParser (F Blocks)
definitionList = fmap B.definitionList . fmap compactify'DL . sequence
<$> many1 (definitionListItem bulletListStart)
bulletList :: OrgParser (F Blocks)
bulletList = fmap B.bulletList . fmap compactify' . sequence
<$> many1 (listItem bulletListStart)
orderedList :: OrgParser (F Blocks)
orderedList = fmap B.orderedList . fmap compactify' . sequence
<$> many1 (listItem orderedListStart)
genericListStart :: OrgParser String
-> OrgParser Int
genericListStart listMarker = try $
(+) <$> (length <$> many spaceChar)
<*> (length <$> listMarker <* many1 spaceChar)
-- parses bullet list start and returns its length (excl. following whitespace)
bulletListStart :: OrgParser Int
bulletListStart = genericListStart bulletListMarker
where bulletListMarker = pure <$> oneOf "*-+"
orderedListStart :: OrgParser Int
orderedListStart = genericListStart orderedListMarker
-- Ordered list markers allowed in org-mode
where orderedListMarker = mappend <$> many1 digit <*> (pure <$> oneOf ".)")
definitionListItem :: OrgParser Int
-> OrgParser (F (Inlines, [Blocks]))
definitionListItem parseMarkerGetLength = try $ do
markerLength <- parseMarkerGetLength
term <- manyTill (noneOf "\n\r") (try $ string "::")
line1 <- anyLineNewline
blank <- option "" ("\n" <$ blankline)
cont <- concat <$> many (listContinuation markerLength)
term' <- parseFromString inline term
contents' <- parseFromString parseBlocks $ line1 ++ blank ++ cont
return $ (,) <$> term' <*> fmap (:[]) contents'
parse raw text for one list item , excluding start marker and continuations
listItem :: OrgParser Int
-> OrgParser (F Blocks)
listItem start = try $ do
markerLength <- try start
firstLine <- anyLineNewline
blank <- option "" ("\n" <$ blankline)
rest <- concat <$> many (listContinuation markerLength)
parseFromString parseBlocks $ firstLine ++ blank ++ rest
continuation of a list item - indented and separated by or endline .
-- Note: nested lists are parsed as continuations.
listContinuation :: Int
-> OrgParser String
listContinuation markerLength = try $
notFollowedBy' blankline
*> (mappend <$> (concat <$> many1 listLine)
<*> many blankline)
where listLine = try $ indentWith markerLength *> anyLineNewline
anyLineNewline :: OrgParser String
anyLineNewline = (++ "\n") <$> anyLine
--
-- inline
--
inline :: OrgParser (F Inlines)
inline =
choice [ whitespace
, linebreak
, cite
, footnote
, linkOrImage
, anchor
, inlineCodeBlock
, str
, endline
, emph
, strong
, strikeout
, underline
, code
, math
, displayMath
, verbatim
, subscript
, superscript
, symbol
] <* (guard =<< newlinesCountWithinLimits)
<?> "inline"
parseInlines :: OrgParser (F Inlines)
parseInlines = trimInlinesF . mconcat <$> many1 inline
-- treat these as potentially non-text when parsing inline:
specialChars :: [Char]
specialChars = "\"$'()*+-./:<=>[\\]^_{|}~"
whitespace :: OrgParser (F Inlines)
whitespace = pure B.space <$ skipMany1 spaceChar
<* updateLastPreCharPos
<* updateLastForbiddenCharPos
<?> "whitespace"
linebreak :: OrgParser (F Inlines)
linebreak = try $ pure B.linebreak <$ string "\\\\" <* skipSpaces <* newline
str :: OrgParser (F Inlines)
str = return . B.str <$> many1 (noneOf $ specialChars ++ "\n\r ")
<* updateLastStrPos
-- | An endline character that can be treated as a space, not a structural
break . This should reflect the values of the Emacs variable
-- @org-element-pagaraph-separate@.
endline :: OrgParser (F Inlines)
endline = try $ do
newline
notFollowedBy blankline
notFollowedBy' exampleLine
notFollowedBy' hline
notFollowedBy' noteMarker
notFollowedBy' tableStart
notFollowedBy' drawerStart
notFollowedBy' headerStart
notFollowedBy' metaLineStart
notFollowedBy' latexEnvStart
notFollowedBy' commentLineStart
notFollowedBy' bulletListStart
notFollowedBy' orderedListStart
decEmphasisNewlinesCount
guard =<< newlinesCountWithinLimits
updateLastPreCharPos
return . return $ B.space
cite :: OrgParser (F Inlines)
cite = try $ do
guardEnabled Ext_citations
(cs, raw) <- withRaw normalCite
return $ (flip B.cite (B.text raw)) <$> cs
normalCite :: OrgParser (F [Citation])
normalCite = try $ char '['
*> skipSpaces
*> citeList
<* skipSpaces
<* char ']'
citeList :: OrgParser (F [Citation])
citeList = sequence <$> sepBy1 citation (try $ char ';' *> skipSpaces)
citation :: OrgParser (F Citation)
citation = try $ do
pref <- prefix
(suppress_author, key) <- citeKey
suff <- suffix
return $ do
x <- pref
y <- suff
return $ Citation{ citationId = key
, citationPrefix = B.toList x
, citationSuffix = B.toList y
, citationMode = if suppress_author
then SuppressAuthor
else NormalCitation
, citationNoteNum = 0
, citationHash = 0
}
where
prefix = trimInlinesF . mconcat <$>
manyTill inline (char ']' <|> (']' <$ lookAhead citeKey))
suffix = try $ do
hasSpace <- option False (notFollowedBy nonspaceChar >> return True)
skipSpaces
rest <- trimInlinesF . mconcat <$>
many (notFollowedBy (oneOf ";]") *> inline)
return $ if hasSpace
then (B.space <>) <$> rest
else rest
footnote :: OrgParser (F Inlines)
footnote = try $ inlineNote <|> referencedNote
inlineNote :: OrgParser (F Inlines)
inlineNote = try $ do
string "[fn:"
ref <- many alphaNum
char ':'
note <- fmap B.para . trimInlinesF . mconcat <$> many1Till inline (char ']')
when (not $ null ref) $
addToNotesTable ("fn:" ++ ref, note)
return $ B.note <$> note
referencedNote :: OrgParser (F Inlines)
referencedNote = try $ do
ref <- noteMarker
return $ do
notes <- asksF orgStateNotes'
case lookup ref notes of
Nothing -> return $ B.str $ "[" ++ ref ++ "]"
Just contents -> do
st <- askF
let contents' = runF contents st{ orgStateNotes' = [] }
return $ B.note contents'
noteMarker :: OrgParser String
noteMarker = try $ do
char '['
choice [ many1Till digit (char ']')
, (++) <$> string "fn:"
<*> many1Till (noneOf "\n\r\t ") (char ']')
]
linkOrImage :: OrgParser (F Inlines)
linkOrImage = explicitOrImageLink
<|> selflinkOrImage
<|> angleLink
<|> plainLink
<?> "link or image"
explicitOrImageLink :: OrgParser (F Inlines)
explicitOrImageLink = try $ do
char '['
srcF <- applyCustomLinkFormat =<< linkTarget
title <- enclosedRaw (char '[') (char ']')
title' <- parseFromString (mconcat <$> many inline) title
char ']'
return $ do
src <- srcF
if isImageFilename src && isImageFilename title
then pure $ B.link src "" $ B.image title mempty mempty
else linkToInlinesF src =<< title'
selflinkOrImage :: OrgParser (F Inlines)
selflinkOrImage = try $ do
src <- char '[' *> linkTarget <* char ']'
return $ linkToInlinesF src (B.str src)
plainLink :: OrgParser (F Inlines)
plainLink = try $ do
(orig, src) <- uri
returnF $ B.link src "" (B.str orig)
angleLink :: OrgParser (F Inlines)
angleLink = try $ do
char '<'
link <- plainLink
char '>'
return link
selfTarget :: OrgParser String
selfTarget = try $ char '[' *> linkTarget <* char ']'
linkTarget :: OrgParser String
linkTarget = enclosedByPair '[' ']' (noneOf "\n\r[]")
applyCustomLinkFormat :: String -> OrgParser (F String)
applyCustomLinkFormat link = do
let (linkType, rest) = break (== ':') link
return $ do
formatter <- M.lookup linkType <$> asksF orgStateLinkFormatters
return $ maybe link ($ drop 1 rest) formatter
linkToInlinesF :: String -> Inlines -> F Inlines
linkToInlinesF s@('#':_) = pure . B.link s ""
linkToInlinesF s
| isImageFilename s = const . pure $ B.image s "" ""
| isUri s = pure . B.link s ""
| isRelativeUrl s = pure . B.link s ""
linkToInlinesF s = \title -> do
anchorB <- (s `elem`) <$> asksF orgStateAnchorIds
if anchorB
then pure $ B.link ('#':s) "" title
else pure $ B.emph title
isRelativeUrl :: String -> Bool
isRelativeUrl s = (':' `notElem` s) && ("./" `isPrefixOf` s)
isUri :: String -> Bool
isUri s = let (scheme, path) = break (== ':') s
in all (\c -> isAlphaNum c || c `elem` ".-") scheme
&& not (null path)
isImageFilename :: String -> Bool
isImageFilename filename =
any (\x -> ('.':x) `isSuffixOf` filename) imageExtensions &&
(any (\x -> (x++":") `isPrefixOf` filename) protocols ||
':' `notElem` filename)
where
imageExtensions = [ "jpeg" , "jpg" , "png" , "gif" , "svg" ]
protocols = [ "file", "http", "https" ]
-- | Parse an anchor like @<<anchor-id>>@ and return an empty span with
-- @anchor-id@ set as id. Legal anchors in org-mode are defined through
-- @org-target-regexp@, which is fairly liberal. Since no link is created if
-- @anchor-id@ contains spaces, we are more restrictive in what is accepted as
-- an anchor.
anchor :: OrgParser (F Inlines)
anchor = try $ do
anchorId <- parseAnchor
recordAnchorId anchorId
returnF $ B.spanWith (solidify anchorId, [], []) mempty
where
parseAnchor = string "<<"
*> many1 (noneOf "\t\n\r<>\"' ")
<* string ">>"
<* skipSpaces
-- | Replace every char but [a-zA-Z0-9_.-:] with a hypen '-'. This mirrors
-- the org function @org-export-solidify-link-text@.
solidify :: String -> String
solidify = map replaceSpecialChar
where replaceSpecialChar c
| isAlphaNum c = c
| c `elem` "_.-:" = c
| otherwise = '-'
-- | Parses an inline code block and marks it as an babel block.
inlineCodeBlock :: OrgParser (F Inlines)
inlineCodeBlock = try $ do
string "src_"
lang <- many1 orgArgWordChar
opts <- option [] $ enclosedByPair '[' ']' inlineBlockOption
inlineCode <- enclosedByPair '{' '}' (noneOf "\n\r")
let attrClasses = [translateLang lang, rundocBlockClass]
let attrKeyVal = map toRundocAttrib (("language", lang) : opts)
returnF $ B.codeWith ("", attrClasses, attrKeyVal) inlineCode
enclosedByPair :: Char -- ^ opening char
-> Char -- ^ closing char
-> OrgParser a -- ^ parser
-> OrgParser [a]
enclosedByPair s e p = char s *> many1Till p (char e)
emph :: OrgParser (F Inlines)
emph = fmap B.emph <$> emphasisBetween '/'
strong :: OrgParser (F Inlines)
strong = fmap B.strong <$> emphasisBetween '*'
strikeout :: OrgParser (F Inlines)
strikeout = fmap B.strikeout <$> emphasisBetween '+'
-- There is no underline, so we use strong instead.
underline :: OrgParser (F Inlines)
underline = fmap B.strong <$> emphasisBetween '_'
code :: OrgParser (F Inlines)
code = return . B.code <$> verbatimBetween '='
verbatim :: OrgParser (F Inlines)
verbatim = return . B.rawInline "" <$> verbatimBetween '~'
subscript :: OrgParser (F Inlines)
subscript = fmap B.subscript <$> try (char '_' *> subOrSuperExpr)
superscript :: OrgParser (F Inlines)
superscript = fmap B.superscript <$> try (char '^' *> subOrSuperExpr)
math :: OrgParser (F Inlines)
math = return . B.math <$> choice [ math1CharBetween '$'
, mathStringBetween '$'
, rawMathBetween "\\(" "\\)"
]
displayMath :: OrgParser (F Inlines)
displayMath = return . B.displayMath <$> choice [ rawMathBetween "\\[" "\\]"
, rawMathBetween "$$" "$$"
]
symbol :: OrgParser (F Inlines)
symbol = return . B.str . (: "") <$> (oneOf specialChars >>= updatePositions)
where updatePositions c
| c `elem` emphasisPreChars = c <$ updateLastPreCharPos
| c `elem` emphasisForbiddenBorderChars = c <$ updateLastForbiddenCharPos
| otherwise = return c
emphasisBetween :: Char
-> OrgParser (F Inlines)
emphasisBetween c = try $ do
startEmphasisNewlinesCounting emphasisAllowedNewlines
res <- enclosedInlines (emphasisStart c) (emphasisEnd c)
isTopLevelEmphasis <- null . orgStateEmphasisCharStack <$> getState
when isTopLevelEmphasis
resetEmphasisNewlines
return res
verbatimBetween :: Char
-> OrgParser String
verbatimBetween c = try $
emphasisStart c *>
many1TillNOrLessNewlines 1 (noneOf "\n\r") (emphasisEnd c)
| Parses a raw string delimited by @c@ using Org 's math rules
mathStringBetween :: Char
-> OrgParser String
mathStringBetween c = try $ do
mathStart c
body <- many1TillNOrLessNewlines mathAllowedNewlines
(noneOf (c:"\n\r"))
(lookAhead $ mathEnd c)
final <- mathEnd c
return $ body ++ [final]
-- | Parse a single character between @c@ using math rules
math1CharBetween :: Char
-> OrgParser String
math1CharBetween c = try $ do
char c
res <- noneOf $ c:mathForbiddenBorderChars
char c
eof <|> () <$ lookAhead (oneOf mathPostChars)
return [res]
rawMathBetween :: String
-> String
-> OrgParser String
rawMathBetween s e = try $ string s *> manyTill anyChar (try $ string e)
-- | Parses the start (opening character) of emphasis
emphasisStart :: Char -> OrgParser Char
emphasisStart c = try $ do
guard =<< afterEmphasisPreChar
guard =<< notAfterString
char c
lookAhead (noneOf emphasisForbiddenBorderChars)
pushToInlineCharStack c
return c
-- | Parses the closing character of emphasis
emphasisEnd :: Char -> OrgParser Char
emphasisEnd c = try $ do
guard =<< notAfterForbiddenBorderChar
char c
eof <|> () <$ lookAhead acceptablePostChars
updateLastStrPos
popInlineCharStack
return c
where acceptablePostChars =
surroundingEmphasisChar >>= \x -> oneOf (x ++ emphasisPostChars)
mathStart :: Char -> OrgParser Char
mathStart c = try $
char c <* notFollowedBy' (oneOf (c:mathForbiddenBorderChars))
mathEnd :: Char -> OrgParser Char
mathEnd c = try $ do
res <- noneOf (c:mathForbiddenBorderChars)
char c
eof <|> () <$ lookAhead (oneOf mathPostChars)
return res
enclosedInlines :: OrgParser a
-> OrgParser b
-> OrgParser (F Inlines)
enclosedInlines start end = try $
trimInlinesF . mconcat <$> enclosed start end inline
enclosedRaw :: OrgParser a
-> OrgParser b
-> OrgParser String
enclosedRaw start end = try $
start *> (onSingleLine <|> spanningTwoLines)
where onSingleLine = try $ many1Till (noneOf "\n\r") end
spanningTwoLines = try $
anyLine >>= \f -> mappend (f <> " ") <$> onSingleLine
| Like many1Till , but parses at most @n+1@ lines . @p@ must not consume
-- newlines.
many1TillNOrLessNewlines :: Int
-> OrgParser Char
-> OrgParser a
-> OrgParser String
many1TillNOrLessNewlines n p end = try $
nMoreLines (Just n) mempty >>= oneOrMore
where
nMoreLines Nothing cs = return cs
nMoreLines (Just 0) cs = try $ (cs ++) <$> finalLine
nMoreLines k cs = try $ (final k cs <|> rest k cs)
>>= uncurry nMoreLines
final _ cs = (\x -> (Nothing, cs ++ x)) <$> try finalLine
rest m cs = (\x -> (minus1 <$> m, cs ++ x ++ "\n")) <$> try (manyTill p P.newline)
finalLine = try $ manyTill p end
minus1 k = k - 1
oneOrMore cs = guard (not $ null cs) *> return cs
-- Org allows customization of the way it reads emphasis. We use the defaults
-- here (see, e.g., the Emacs Lisp variable `org-emphasis-regexp-components`
-- for details).
-- | Chars allowed to occur before emphasis (spaces and newlines are ok, too)
emphasisPreChars :: [Char]
emphasisPreChars = "\t \"'({"
-- | Chars allowed at after emphasis
emphasisPostChars :: [Char]
emphasisPostChars = "\t\n !\"'),-.:;?\\}"
not allowed at the ( inner ) border of emphasis
emphasisForbiddenBorderChars :: [Char]
emphasisForbiddenBorderChars = "\t\n\r \"',"
-- | The maximum number of newlines within
emphasisAllowedNewlines :: Int
emphasisAllowedNewlines = 1
-- LaTeX-style math: see `org-latex-regexps` for details
-- | Chars allowed after an inline ($...$) math statement
mathPostChars :: [Char]
mathPostChars = "\t\n \"'),-.:;?"
not allowed at the ( inner ) border of math
mathForbiddenBorderChars :: [Char]
mathForbiddenBorderChars = "\t\n\r ,;.$"
-- | Maximum number of newlines in an inline math statement
mathAllowedNewlines :: Int
mathAllowedNewlines = 2
-- | Whether we are right behind a char allowed before emphasis
afterEmphasisPreChar :: OrgParser Bool
afterEmphasisPreChar = do
pos <- getPosition
lastPrePos <- orgStateLastPreCharPos <$> getState
return . fromMaybe True $ (== pos) <$> lastPrePos
-- | Whether the parser is right after a forbidden border char
notAfterForbiddenBorderChar :: OrgParser Bool
notAfterForbiddenBorderChar = do
pos <- getPosition
lastFBCPos <- orgStateLastForbiddenCharPos <$> getState
return $ lastFBCPos /= Just pos
-- | Read a sub- or superscript expression
subOrSuperExpr :: OrgParser (F Inlines)
subOrSuperExpr = try $
choice [ id <$> charsInBalanced '{' '}' (noneOf "\n\r")
, enclosing ('(', ')') <$> charsInBalanced '(' ')' (noneOf "\n\r")
, simpleSubOrSuperString
] >>= parseFromString (mconcat <$> many inline)
where enclosing (left, right) s = left : s ++ [right]
simpleSubOrSuperString :: OrgParser String
simpleSubOrSuperString = try $
choice [ string "*"
, mappend <$> option [] ((:[]) <$> oneOf "+-")
<*> many1 alphaNum
]
| null | https://raw.githubusercontent.com/susanemcg/pandoc-tufteLaTeX2GitBook/00c34b4299dd89c4e339e1cde006061918b559ab/pandoc-1.12.4.2/src/Text/Pandoc/Readers/Org.hs | haskell | # LANGUAGE OverloadedStrings #
^ Reader options
^ String to parse (assuming @'\n'@ line endings)
| Org-mode parser state
The version Text.Pandoc.Parsing cannot be used, as we need additional parts
of the state saved and restored.
Adaptions and specializations of parsing utilities
parsing blocks
Org Blocks (#+BEGIN_... / #+END_...)
(Indentation, Block-Type)
indent by specified number of spaces (or equiv. tabs)
| Parse code block arguments
TODO: We currently don't handle switches.
emacs lisp is not supported
| Prefix used for Rundoc classes and arguments.
| The class-name used to mark rundoc blocks.
Drawers for properties or a logbook
Figures
Figures (Image on a line by itself, preceded by name and/or caption)
Comments, Options and Metadata
The order, in which blocks are tried, makes sure that we're not looking at
the beginning of a block, so we don't need to check for it
| An ad-hoc, single-argument-only implementation of a printf-style format
parser.
inefficient, but who cares
Headers
| Headers
Don't use (or need) the reader wrapper here, we want hline to be
@show@able. Otherwise we can't use it with @notFollowedBy'@.
dashes or more )
Tables
line as a header. All other horizontal lines are discarded.
| Parses a LaTeX environment name.
Footnote defintions
Paragraphs or Plain text
list blocks
parses bullet list start and returns its length (excl. following whitespace)
Ordered list markers allowed in org-mode
Note: nested lists are parsed as continuations.
inline
treat these as potentially non-text when parsing inline:
| An endline character that can be treated as a space, not a structural
@org-element-pagaraph-separate@.
| Parse an anchor like @<<anchor-id>>@ and return an empty span with
@anchor-id@ set as id. Legal anchors in org-mode are defined through
@org-target-regexp@, which is fairly liberal. Since no link is created if
@anchor-id@ contains spaces, we are more restrictive in what is accepted as
an anchor.
| Replace every char but [a-zA-Z0-9_.-:] with a hypen '-'. This mirrors
the org function @org-export-solidify-link-text@.
| Parses an inline code block and marks it as an babel block.
^ opening char
^ closing char
^ parser
There is no underline, so we use strong instead.
| Parse a single character between @c@ using math rules
| Parses the start (opening character) of emphasis
| Parses the closing character of emphasis
newlines.
Org allows customization of the way it reads emphasis. We use the defaults
here (see, e.g., the Emacs Lisp variable `org-emphasis-regexp-components`
for details).
| Chars allowed to occur before emphasis (spaces and newlines are ok, too)
| Chars allowed at after emphasis
| The maximum number of newlines within
LaTeX-style math: see `org-latex-regexps` for details
| Chars allowed after an inline ($...$) math statement
| Maximum number of newlines in an inline math statement
| Whether we are right behind a char allowed before emphasis
| Whether the parser is right after a forbidden border char
| Read a sub- or superscript expression | # LANGUAGE GeneralizedNewtypeDeriving #
Copyright ( C ) 2014 >
This program is free software ; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
( at your option ) any later version .
This program is distributed in the hope that it will be useful ,
but WITHOUT ANY WARRANTY ; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
GNU General Public License for more details .
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
Copyright (C) 2014 Albert Krewinkel <>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
|
Module : Text . Pandoc . Readers . Org
Copyright : Copyright ( C ) 2014 License : GNU GPL , version 2 or above
Maintainer : >
Conversion of org - mode formatted plain text to ' Pandoc ' document .
Module : Text.Pandoc.Readers.Org
Copyright : Copyright (C) 2014 Albert Krewinkel
License : GNU GPL, version 2 or above
Maintainer : Albert Krewinkel <>
Conversion of org-mode formatted plain text to 'Pandoc' document.
-}
module Text.Pandoc.Readers.Org ( readOrg ) where
import qualified Text.Pandoc.Builder as B
import Text.Pandoc.Builder ( Inlines, Blocks, HasMeta(..), (<>)
, trimInlines )
import Text.Pandoc.Definition
import Text.Pandoc.Options
import qualified Text.Pandoc.Parsing as P
import Text.Pandoc.Parsing hiding ( F, unF, askF, asksF, runF
, newline, orderedListMarker
, parseFromString
, updateLastStrPos )
import Text.Pandoc.Shared (compactify', compactify'DL)
import Control.Applicative ( Applicative, pure
, (<$>), (<$), (<*>), (<*), (*>), (<**>) )
import Control.Arrow (first)
import Control.Monad (foldM, guard, liftM, liftM2, mzero, when)
import Control.Monad.Reader (Reader, runReader, ask, asks)
import Data.Char (isAlphaNum, toLower)
import Data.Default
import Data.List (intersperse, isPrefixOf, isSuffixOf)
import qualified Data.Map as M
import Data.Maybe (fromMaybe, isJust)
import Data.Monoid (Monoid, mconcat, mempty, mappend)
import Network.HTTP (urlEncode)
| Parse org - mode string and return a Pandoc document .
-> Pandoc
readOrg opts s = readWith parseOrg def{ orgStateOptions = opts } (s ++ "\n\n")
type OrgParser = Parser [Char] OrgParserState
parseOrg :: OrgParser Pandoc
parseOrg = do
blocks' <- parseBlocks
st <- getState
let meta = runF (orgStateMeta' st) st
return $ Pandoc meta $ filter (/= Null) (B.toList $ runF blocks' st)
Parser State for Org
type OrgNoteRecord = (String, F Blocks)
type OrgNoteTable = [OrgNoteRecord]
type OrgBlockAttributes = M.Map String String
type OrgLinkFormatters = M.Map String (String -> String)
data OrgParserState = OrgParserState
{ orgStateOptions :: ReaderOptions
, orgStateAnchorIds :: [String]
, orgStateBlockAttributes :: OrgBlockAttributes
, orgStateEmphasisCharStack :: [Char]
, orgStateEmphasisNewlines :: Maybe Int
, orgStateLastForbiddenCharPos :: Maybe SourcePos
, orgStateLastPreCharPos :: Maybe SourcePos
, orgStateLastStrPos :: Maybe SourcePos
, orgStateLinkFormatters :: OrgLinkFormatters
, orgStateMeta :: Meta
, orgStateMeta' :: F Meta
, orgStateNotes' :: OrgNoteTable
}
instance HasReaderOptions OrgParserState where
extractReaderOptions = orgStateOptions
instance HasMeta OrgParserState where
setMeta field val st =
st{ orgStateMeta = setMeta field val $ orgStateMeta st }
deleteMeta field st =
st{ orgStateMeta = deleteMeta field $ orgStateMeta st }
instance HasLastStrPosition OrgParserState where
getLastStrPos = orgStateLastStrPos
setLastStrPos pos st = st{ orgStateLastStrPos = Just pos }
instance Default OrgParserState where
def = defaultOrgParserState
defaultOrgParserState :: OrgParserState
defaultOrgParserState = OrgParserState
{ orgStateOptions = def
, orgStateAnchorIds = []
, orgStateBlockAttributes = M.empty
, orgStateEmphasisCharStack = []
, orgStateEmphasisNewlines = Nothing
, orgStateLastForbiddenCharPos = Nothing
, orgStateLastPreCharPos = Nothing
, orgStateLastStrPos = Nothing
, orgStateLinkFormatters = M.empty
, orgStateMeta = nullMeta
, orgStateMeta' = return nullMeta
, orgStateNotes' = []
}
recordAnchorId :: String -> OrgParser ()
recordAnchorId i = updateState $ \s ->
s{ orgStateAnchorIds = i : (orgStateAnchorIds s) }
addBlockAttribute :: String -> String -> OrgParser ()
addBlockAttribute key val = updateState $ \s ->
let attrs = orgStateBlockAttributes s
in s{ orgStateBlockAttributes = M.insert key val attrs }
lookupBlockAttribute :: String -> OrgParser (Maybe String)
lookupBlockAttribute key =
M.lookup key . orgStateBlockAttributes <$> getState
resetBlockAttributes :: OrgParser ()
resetBlockAttributes = updateState $ \s ->
s{ orgStateBlockAttributes = orgStateBlockAttributes def }
updateLastStrPos :: OrgParser ()
updateLastStrPos = getPosition >>= \p ->
updateState $ \s -> s{ orgStateLastStrPos = Just p }
updateLastForbiddenCharPos :: OrgParser ()
updateLastForbiddenCharPos = getPosition >>= \p ->
updateState $ \s -> s{ orgStateLastForbiddenCharPos = Just p}
updateLastPreCharPos :: OrgParser ()
updateLastPreCharPos = getPosition >>= \p ->
updateState $ \s -> s{ orgStateLastPreCharPos = Just p}
pushToInlineCharStack :: Char -> OrgParser ()
pushToInlineCharStack c = updateState $ \s ->
s{ orgStateEmphasisCharStack = c:orgStateEmphasisCharStack s }
popInlineCharStack :: OrgParser ()
popInlineCharStack = updateState $ \s ->
s{ orgStateEmphasisCharStack = drop 1 . orgStateEmphasisCharStack $ s }
surroundingEmphasisChar :: OrgParser [Char]
surroundingEmphasisChar =
take 1 . drop 1 . orgStateEmphasisCharStack <$> getState
startEmphasisNewlinesCounting :: Int -> OrgParser ()
startEmphasisNewlinesCounting maxNewlines = updateState $ \s ->
s{ orgStateEmphasisNewlines = Just maxNewlines }
decEmphasisNewlinesCount :: OrgParser ()
decEmphasisNewlinesCount = updateState $ \s ->
s{ orgStateEmphasisNewlines = (\n -> n - 1) <$> orgStateEmphasisNewlines s }
newlinesCountWithinLimits :: OrgParser Bool
newlinesCountWithinLimits = do
st <- getState
return $ ((< 0) <$> orgStateEmphasisNewlines st) /= Just True
resetEmphasisNewlines :: OrgParser ()
resetEmphasisNewlines = updateState $ \s ->
s{ orgStateEmphasisNewlines = Nothing }
addLinkFormat :: String
-> (String -> String)
-> OrgParser ()
addLinkFormat key formatter = updateState $ \s ->
let fs = orgStateLinkFormatters s
in s{ orgStateLinkFormatters = M.insert key formatter fs }
addToNotesTable :: OrgNoteRecord -> OrgParser ()
addToNotesTable note = do
oldnotes <- orgStateNotes' <$> getState
updateState $ \s -> s{ orgStateNotes' = note:oldnotes }
parseFromString :: OrgParser a -> String -> OrgParser a
parseFromString parser str' = do
oldLastPreCharPos <- orgStateLastPreCharPos <$> getState
updateState $ \s -> s{ orgStateLastPreCharPos = Nothing }
result <- P.parseFromString parser str'
updateState $ \s -> s{ orgStateLastPreCharPos = oldLastPreCharPos }
return result
newtype F a = F { unF :: Reader OrgParserState a
} deriving (Monad, Applicative, Functor)
runF :: F a -> OrgParserState -> a
runF = runReader . unF
askF :: F OrgParserState
askF = F ask
asksF :: (OrgParserState -> a) -> F a
asksF f = F $ asks f
instance Monoid a => Monoid (F a) where
mempty = return mempty
mappend = liftM2 mappend
mconcat = fmap mconcat . sequence
trimInlinesF :: F Inlines -> F Inlines
trimInlinesF = liftM trimInlines
returnF :: a -> OrgParser (F a)
returnF = return . return
| Like @Text . Parsec . Char.newline@ , but causes additional state changes .
newline :: OrgParser Char
newline =
P.newline
<* updateLastPreCharPos
<* updateLastForbiddenCharPos
parseBlocks :: OrgParser (F Blocks)
parseBlocks = mconcat <$> manyTill block eof
block :: OrgParser (F Blocks)
block = choice [ mempty <$ blanklines
, optionalAttributes $ choice
[ orgBlock
, figure
, table
]
, example
, drawer
, specialLine
, header
, return <$> hline
, list
, latexFragment
, noteBlock
, paraOrPlain
] <?> "block"
optionalAttributes :: OrgParser (F Blocks) -> OrgParser (F Blocks)
optionalAttributes parser = try $
resetBlockAttributes *> parseBlockAttributes *> parser
parseBlockAttributes :: OrgParser ()
parseBlockAttributes = do
attrs <- many attribute
() <$ mapM (uncurry parseAndAddAttribute) attrs
where
attribute :: OrgParser (String, String)
attribute = try $ do
key <- metaLineStart *> many1Till nonspaceChar (char ':')
val <- skipSpaces *> anyLine
return (map toLower key, val)
parseAndAddAttribute :: String -> String -> OrgParser ()
parseAndAddAttribute key value = do
let key' = map toLower key
() <$ addBlockAttribute key' value
lookupInlinesAttr :: String -> OrgParser (Maybe (F Inlines))
lookupInlinesAttr attr = try $ do
val <- lookupBlockAttribute attr
maybe (return Nothing)
(fmap Just . parseFromString parseInlines)
val
orgBlock :: OrgParser (F Blocks)
orgBlock = try $ do
blockProp@(_, blkType) <- blockHeaderStart
($ blockProp) $
case blkType of
"comment" -> withRaw' (const mempty)
"html" -> withRaw' (return . (B.rawBlock blkType))
"latex" -> withRaw' (return . (B.rawBlock blkType))
"ascii" -> withRaw' (return . (B.rawBlock blkType))
"example" -> withRaw' (return . exampleCode)
"quote" -> withParsed (fmap B.blockQuote)
"verse" -> verseBlock
"src" -> codeBlock
_ -> withParsed (fmap $ divWithClass blkType)
blockHeaderStart :: OrgParser (Int, String)
blockHeaderStart = try $ (,) <$> indent <*> blockType
where
indent = length <$> many spaceChar
blockType = map toLower <$> (stringAnyCase "#+begin_" *> orgArgWord)
withRaw' :: (String -> F Blocks) -> BlockProperties -> OrgParser (F Blocks)
withRaw' f blockProp = (ignHeaders *> (f <$> rawBlockContent blockProp))
withParsed :: (F Blocks -> F Blocks) -> BlockProperties -> OrgParser (F Blocks)
withParsed f blockProp = (ignHeaders *> (f <$> parsedBlockContent blockProp))
ignHeaders :: OrgParser ()
ignHeaders = (() <$ newline) <|> (() <$ anyLine)
divWithClass :: String -> Blocks -> Blocks
divWithClass cls = B.divWith ("", [cls], [])
verseBlock :: BlockProperties -> OrgParser (F Blocks)
verseBlock blkProp = try $ do
ignHeaders
content <- rawBlockContent blkProp
fmap B.para . mconcat . intersperse (pure B.linebreak)
<$> mapM (parseFromString parseInlines) (lines content)
codeBlock :: BlockProperties -> OrgParser (F Blocks)
codeBlock blkProp = do
skipSpaces
(classes, kv) <- codeHeaderArgs <|> (mempty <$ ignHeaders)
id' <- fromMaybe "" <$> lookupBlockAttribute "name"
content <- rawBlockContent blkProp
let codeBlck = B.codeBlockWith ( id', classes, kv ) content
maybe (pure codeBlck) (labelDiv codeBlck) <$> lookupInlinesAttr "caption"
where
labelDiv blk value =
B.divWith nullAttr <$> (mappend <$> labelledBlock value
<*> pure blk)
labelledBlock = fmap (B.plain . B.spanWith ("", ["label"], []))
rawBlockContent :: BlockProperties -> OrgParser String
rawBlockContent (indent, blockType) = try $
unlines . map commaEscaped <$> manyTill indentedLine blockEnder
where
indentedLine = try $ ("" <$ blankline) <|> (indentWith indent *> anyLine)
blockEnder = try $ indentWith indent *> stringAnyCase ("#+end_" <> blockType)
parsedBlockContent :: BlockProperties -> OrgParser (F Blocks)
parsedBlockContent blkProps = try $ do
raw <- rawBlockContent blkProps
parseFromString parseBlocks (raw ++ "\n")
indentWith :: Int -> OrgParser String
indentWith num = do
tabStop <- getOption readerTabStop
if num < tabStop
then count num (char ' ')
else choice [ try (count num (char ' '))
, try (char '\t' >> count (num - tabStop) (char ' ')) ]
type SwitchOption = (Char, Maybe String)
orgArgWord :: OrgParser String
orgArgWord = many1 orgArgWordChar
codeHeaderArgs :: OrgParser ([String], [(String, String)])
codeHeaderArgs = try $ do
language <- skipSpaces *> orgArgWord
_ <- skipSpaces *> (try $ switch `sepBy` (many1 spaceChar))
parameters <- manyTill blockOption newline
let pandocLang = translateLang language
return $
if hasRundocParameters parameters
then ( [ pandocLang, rundocBlockClass ]
, map toRundocAttrib (("language", language) : parameters)
)
else ([ pandocLang ], parameters)
where hasRundocParameters = not . null
switch :: OrgParser SwitchOption
switch = try $ simpleSwitch <|> lineNumbersSwitch
where
simpleSwitch = (\c -> (c, Nothing)) <$> (oneOf "-+" *> letter)
lineNumbersSwitch = (\ls -> ('l', Just ls)) <$>
(string "-l \"" *> many1Till nonspaceChar (char '"'))
translateLang :: String -> String
translateLang "C" = "c"
translateLang "C++" = "cpp"
translateLang "js" = "javascript"
translateLang "lisp" = "commonlisp"
translateLang "R" = "r"
translateLang "sh" = "bash"
translateLang "sqlite" = "sql"
translateLang cs = cs
rundocPrefix :: String
rundocPrefix = "rundoc-"
rundocBlockClass :: String
rundocBlockClass = rundocPrefix ++ "block"
blockOption :: OrgParser (String, String)
blockOption = try $ (,) <$> orgArgKey <*> orgParamValue
inlineBlockOption :: OrgParser (String, String)
inlineBlockOption = try $ (,) <$> orgArgKey <*> orgInlineParamValue
orgArgKey :: OrgParser String
orgArgKey = try $
skipSpaces *> char ':'
*> many1 orgArgWordChar
orgParamValue :: OrgParser String
orgParamValue = try $
skipSpaces *> many1 (noneOf "\t\n\r ") <* skipSpaces
orgInlineParamValue :: OrgParser String
orgInlineParamValue = try $
skipSpaces *> many1 (noneOf "\t\n\r ]") <* skipSpaces
orgArgWordChar :: OrgParser Char
orgArgWordChar = alphaNum <|> oneOf "-_"
toRundocAttrib :: (String, String) -> (String, String)
toRundocAttrib = first ("rundoc-" ++)
commaEscaped :: String -> String
commaEscaped (',':cs@('*':_)) = cs
commaEscaped (',':cs@('#':'+':_)) = cs
commaEscaped cs = cs
example :: OrgParser (F Blocks)
example = try $ do
return . return . exampleCode =<< unlines <$> many1 exampleLine
exampleCode :: String -> Blocks
exampleCode = B.codeBlockWith ("", ["example"], [])
exampleLine :: OrgParser String
exampleLine = try $ string ": " *> anyLine
drawer :: OrgParser (F Blocks)
drawer = try $ do
drawerStart
manyTill drawerLine (try drawerEnd)
return mempty
drawerStart :: OrgParser String
drawerStart = try $
skipSpaces *> drawerName <* skipSpaces <* P.newline
where drawerName = try $ char ':' *> validDrawerName <* char ':'
validDrawerName = stringAnyCase "PROPERTIES"
<|> stringAnyCase "LOGBOOK"
drawerLine :: OrgParser String
drawerLine = try anyLine
drawerEnd :: OrgParser String
drawerEnd = try $
skipSpaces *> stringAnyCase ":END:" <* skipSpaces <* P.newline
figure :: OrgParser (F Blocks)
figure = try $ do
(cap, nam) <- nameAndCaption
src <- skipSpaces *> selfTarget <* skipSpaces <* P.newline
guard (isImageFilename src)
return $ do
cap' <- cap
return $ B.para $ B.image src nam cap'
where
nameAndCaption =
do
maybeCap <- lookupInlinesAttr "caption"
maybeNam <- lookupBlockAttribute "name"
guard $ isJust maybeCap || isJust maybeNam
return ( fromMaybe mempty maybeCap
, maybe mempty withFigPrefix maybeNam )
withFigPrefix cs =
if "fig:" `isPrefixOf` cs
then cs
else "fig:" ++ cs
specialLine :: OrgParser (F Blocks)
specialLine = fmap return . try $ metaLine <|> commentLine
metaLine :: OrgParser Blocks
metaLine = try $ mempty
<$ (metaLineStart *> (optionLine <|> declarationLine))
commentLine :: OrgParser Blocks
commentLine = try $ commentLineStart *> anyLine *> pure mempty
metaLineStart :: OrgParser String
metaLineStart = try $ mappend <$> many spaceChar <*> string "#+"
commentLineStart :: OrgParser String
commentLineStart = try $ mappend <$> many spaceChar <*> string "# "
declarationLine :: OrgParser ()
declarationLine = try $ do
key <- metaKey
inlinesF <- metaInlines
updateState $ \st ->
let meta' = B.setMeta <$> pure key <*> inlinesF <*> pure nullMeta
in st { orgStateMeta' = orgStateMeta' st <> meta' }
return ()
metaInlines :: OrgParser (F MetaValue)
metaInlines = fmap (MetaInlines . B.toList) <$> inlinesTillNewline
metaKey :: OrgParser String
metaKey = map toLower <$> many1 (noneOf ": \n\r")
<* char ':'
<* skipSpaces
optionLine :: OrgParser ()
optionLine = try $ do
key <- metaKey
case key of
"link" -> parseLinkFormat >>= uncurry addLinkFormat
_ -> mzero
parseLinkFormat :: OrgParser ((String, String -> String))
parseLinkFormat = try $ do
linkType <- (:) <$> letter <*> many (alphaNum <|> oneOf "-_") <* skipSpaces
linkSubst <- parseFormat
return (linkType, linkSubst)
parseFormat :: OrgParser (String -> String)
parseFormat = try $ do
replacePlain <|> replaceUrl <|> justAppend
where
replacePlain = try $ (\x -> concat . flip intersperse x)
<$> sequence [tillSpecifier 's', rest]
replaceUrl = try $ (\x -> concat . flip intersperse x . urlEncode)
<$> sequence [tillSpecifier 'h', rest]
justAppend = try $ (++) <$> rest
rest = manyTill anyChar (eof <|> () <$ oneOf "\n\r")
tillSpecifier c = manyTill (noneOf "\n\r") (try $ string ('%':c:""))
header :: OrgParser (F Blocks)
header = try $ do
level <- headerStart
title <- inlinesTillNewline
return $ B.header level <$> title
headerStart :: OrgParser Int
headerStart = try $
(length <$> many1 (char '*')) <* many1 (char ' ')
hline :: OrgParser Blocks
hline = try $ do
skipSpaces
string "-----"
many (char '-')
skipSpaces
newline
return B.horizontalRule
data OrgTableRow = OrgContentRow (F [Blocks])
| OrgAlignRow [Alignment]
| OrgHlineRow
data OrgTable = OrgTable
{ orgTableColumns :: Int
, orgTableAlignments :: [Alignment]
, orgTableHeader :: [Blocks]
, orgTableRows :: [[Blocks]]
}
table :: OrgParser (F Blocks)
table = try $ do
lookAhead tableStart
do
rows <- tableRows
cptn <- fromMaybe (pure "") <$> lookupInlinesAttr "caption"
return $ (<$> cptn) . orgToPandocTable . normalizeTable =<< rowsToTable rows
orgToPandocTable :: OrgTable
-> Inlines
-> Blocks
orgToPandocTable (OrgTable _ aligns heads lns) caption =
B.table caption (zip aligns $ repeat 0) heads lns
tableStart :: OrgParser Char
tableStart = try $ skipSpaces *> char '|'
tableRows :: OrgParser [OrgTableRow]
tableRows = try $ many (tableAlignRow <|> tableHline <|> tableContentRow)
tableContentRow :: OrgParser OrgTableRow
tableContentRow = try $
OrgContentRow . sequence <$> (tableStart *> manyTill tableContentCell newline)
tableContentCell :: OrgParser (F Blocks)
tableContentCell = try $
fmap B.plain . trimInlinesF . mconcat <$> many1Till inline endOfCell
endOfCell :: OrgParser Char
endOfCell = try $ char '|' <|> lookAhead newline
tableAlignRow :: OrgParser OrgTableRow
tableAlignRow = try $
OrgAlignRow <$> (tableStart *> manyTill tableAlignCell newline)
tableAlignCell :: OrgParser Alignment
tableAlignCell =
choice [ try $ emptyCell *> return AlignDefault
, try $ skipSpaces
*> char '<'
*> tableAlignFromChar
<* many digit
<* char '>'
<* emptyCell
] <?> "alignment info"
where emptyCell = try $ skipSpaces *> endOfCell
tableAlignFromChar :: OrgParser Alignment
tableAlignFromChar = try $ choice [ char 'l' *> return AlignLeft
, char 'c' *> return AlignCenter
, char 'r' *> return AlignRight
]
tableHline :: OrgParser OrgTableRow
tableHline = try $
OrgHlineRow <$ (tableStart *> char '-' *> anyLine)
rowsToTable :: [OrgTableRow]
-> F OrgTable
rowsToTable = foldM (flip rowToContent) zeroTable
where zeroTable = OrgTable 0 mempty mempty mempty
normalizeTable :: OrgTable
-> OrgTable
normalizeTable (OrgTable cols aligns heads lns) =
let aligns' = fillColumns aligns AlignDefault
heads' = if heads == mempty
then mempty
else fillColumns heads (B.plain mempty)
lns' = map (`fillColumns` B.plain mempty) lns
fillColumns base padding = take cols $ base ++ repeat padding
in OrgTable cols aligns' heads' lns'
One or more horizontal rules after the first content line mark the previous
rowToContent :: OrgTableRow
-> OrgTable
-> F OrgTable
rowToContent OrgHlineRow t = maybeBodyToHeader t
rowToContent (OrgAlignRow as) t = setLongestRow as =<< setAligns as t
rowToContent (OrgContentRow rf) t = do
rs <- rf
setLongestRow rs =<< appendToBody rs t
setLongestRow :: [a]
-> OrgTable
-> F OrgTable
setLongestRow rs t =
return t{ orgTableColumns = max (length rs) (orgTableColumns t) }
maybeBodyToHeader :: OrgTable
-> F OrgTable
maybeBodyToHeader t = case t of
OrgTable{ orgTableHeader = [], orgTableRows = b:[] } ->
return t{ orgTableHeader = b , orgTableRows = [] }
_ -> return t
appendToBody :: [Blocks]
-> OrgTable
-> F OrgTable
appendToBody r t = return t{ orgTableRows = orgTableRows t ++ [r] }
setAligns :: [Alignment]
-> OrgTable
-> F OrgTable
setAligns aligns t = return $ t{ orgTableAlignments = aligns }
LaTeX fragments
latexFragment :: OrgParser (F Blocks)
latexFragment = try $ do
envName <- latexEnvStart
content <- mconcat <$> manyTill anyLineNewline (latexEnd envName)
return . return $ B.rawBlock "latex" (content `inLatexEnv` envName)
where
c `inLatexEnv` e = mconcat [ "\\begin{", e, "}\n"
, c
, "\\end{", e, "}\n"
]
latexEnvStart :: OrgParser String
latexEnvStart = try $ do
skipSpaces *> string "\\begin{"
*> latexEnvName
<* string "}"
<* blankline
latexEnd :: String -> OrgParser ()
latexEnd envName = try $
() <$ skipSpaces
<* string ("\\end{" ++ envName ++ "}")
<* blankline
latexEnvName :: OrgParser String
latexEnvName = try $ do
mappend <$> many1 alphaNum
<*> option "" (string "*")
noteBlock :: OrgParser (F Blocks)
noteBlock = try $ do
ref <- noteMarker <* skipSpaces
content <- mconcat <$> blocksTillHeaderOrNote
addToNotesTable (ref, content)
return mempty
where
blocksTillHeaderOrNote =
many1Till block (eof <|> () <$ lookAhead noteMarker
<|> () <$ lookAhead headerStart)
paraOrPlain :: OrgParser (F Blocks)
paraOrPlain = try $
parseInlines <**> (fmap <$> option B.plain (try $ newline *> pure B.para))
inlinesTillNewline :: OrgParser (F Inlines)
inlinesTillNewline = trimInlinesF . mconcat <$> manyTill inline newline
list :: OrgParser (F Blocks)
list = choice [ definitionList, bulletList, orderedList ] <?> "list"
definitionList :: OrgParser (F Blocks)
definitionList = fmap B.definitionList . fmap compactify'DL . sequence
<$> many1 (definitionListItem bulletListStart)
bulletList :: OrgParser (F Blocks)
bulletList = fmap B.bulletList . fmap compactify' . sequence
<$> many1 (listItem bulletListStart)
orderedList :: OrgParser (F Blocks)
orderedList = fmap B.orderedList . fmap compactify' . sequence
<$> many1 (listItem orderedListStart)
genericListStart :: OrgParser String
-> OrgParser Int
genericListStart listMarker = try $
(+) <$> (length <$> many spaceChar)
<*> (length <$> listMarker <* many1 spaceChar)
bulletListStart :: OrgParser Int
bulletListStart = genericListStart bulletListMarker
where bulletListMarker = pure <$> oneOf "*-+"
orderedListStart :: OrgParser Int
orderedListStart = genericListStart orderedListMarker
where orderedListMarker = mappend <$> many1 digit <*> (pure <$> oneOf ".)")
definitionListItem :: OrgParser Int
-> OrgParser (F (Inlines, [Blocks]))
definitionListItem parseMarkerGetLength = try $ do
markerLength <- parseMarkerGetLength
term <- manyTill (noneOf "\n\r") (try $ string "::")
line1 <- anyLineNewline
blank <- option "" ("\n" <$ blankline)
cont <- concat <$> many (listContinuation markerLength)
term' <- parseFromString inline term
contents' <- parseFromString parseBlocks $ line1 ++ blank ++ cont
return $ (,) <$> term' <*> fmap (:[]) contents'
parse raw text for one list item , excluding start marker and continuations
listItem :: OrgParser Int
-> OrgParser (F Blocks)
listItem start = try $ do
markerLength <- try start
firstLine <- anyLineNewline
blank <- option "" ("\n" <$ blankline)
rest <- concat <$> many (listContinuation markerLength)
parseFromString parseBlocks $ firstLine ++ blank ++ rest
continuation of a list item - indented and separated by or endline .
listContinuation :: Int
-> OrgParser String
listContinuation markerLength = try $
notFollowedBy' blankline
*> (mappend <$> (concat <$> many1 listLine)
<*> many blankline)
where listLine = try $ indentWith markerLength *> anyLineNewline
anyLineNewline :: OrgParser String
anyLineNewline = (++ "\n") <$> anyLine
inline :: OrgParser (F Inlines)
inline =
choice [ whitespace
, linebreak
, cite
, footnote
, linkOrImage
, anchor
, inlineCodeBlock
, str
, endline
, emph
, strong
, strikeout
, underline
, code
, math
, displayMath
, verbatim
, subscript
, superscript
, symbol
] <* (guard =<< newlinesCountWithinLimits)
<?> "inline"
parseInlines :: OrgParser (F Inlines)
parseInlines = trimInlinesF . mconcat <$> many1 inline
specialChars :: [Char]
specialChars = "\"$'()*+-./:<=>[\\]^_{|}~"
whitespace :: OrgParser (F Inlines)
whitespace = pure B.space <$ skipMany1 spaceChar
<* updateLastPreCharPos
<* updateLastForbiddenCharPos
<?> "whitespace"
linebreak :: OrgParser (F Inlines)
linebreak = try $ pure B.linebreak <$ string "\\\\" <* skipSpaces <* newline
str :: OrgParser (F Inlines)
str = return . B.str <$> many1 (noneOf $ specialChars ++ "\n\r ")
<* updateLastStrPos
break . This should reflect the values of the Emacs variable
endline :: OrgParser (F Inlines)
endline = try $ do
newline
notFollowedBy blankline
notFollowedBy' exampleLine
notFollowedBy' hline
notFollowedBy' noteMarker
notFollowedBy' tableStart
notFollowedBy' drawerStart
notFollowedBy' headerStart
notFollowedBy' metaLineStart
notFollowedBy' latexEnvStart
notFollowedBy' commentLineStart
notFollowedBy' bulletListStart
notFollowedBy' orderedListStart
decEmphasisNewlinesCount
guard =<< newlinesCountWithinLimits
updateLastPreCharPos
return . return $ B.space
cite :: OrgParser (F Inlines)
cite = try $ do
guardEnabled Ext_citations
(cs, raw) <- withRaw normalCite
return $ (flip B.cite (B.text raw)) <$> cs
normalCite :: OrgParser (F [Citation])
normalCite = try $ char '['
*> skipSpaces
*> citeList
<* skipSpaces
<* char ']'
citeList :: OrgParser (F [Citation])
citeList = sequence <$> sepBy1 citation (try $ char ';' *> skipSpaces)
citation :: OrgParser (F Citation)
citation = try $ do
pref <- prefix
(suppress_author, key) <- citeKey
suff <- suffix
return $ do
x <- pref
y <- suff
return $ Citation{ citationId = key
, citationPrefix = B.toList x
, citationSuffix = B.toList y
, citationMode = if suppress_author
then SuppressAuthor
else NormalCitation
, citationNoteNum = 0
, citationHash = 0
}
where
prefix = trimInlinesF . mconcat <$>
manyTill inline (char ']' <|> (']' <$ lookAhead citeKey))
suffix = try $ do
hasSpace <- option False (notFollowedBy nonspaceChar >> return True)
skipSpaces
rest <- trimInlinesF . mconcat <$>
many (notFollowedBy (oneOf ";]") *> inline)
return $ if hasSpace
then (B.space <>) <$> rest
else rest
footnote :: OrgParser (F Inlines)
footnote = try $ inlineNote <|> referencedNote
inlineNote :: OrgParser (F Inlines)
inlineNote = try $ do
string "[fn:"
ref <- many alphaNum
char ':'
note <- fmap B.para . trimInlinesF . mconcat <$> many1Till inline (char ']')
when (not $ null ref) $
addToNotesTable ("fn:" ++ ref, note)
return $ B.note <$> note
referencedNote :: OrgParser (F Inlines)
referencedNote = try $ do
ref <- noteMarker
return $ do
notes <- asksF orgStateNotes'
case lookup ref notes of
Nothing -> return $ B.str $ "[" ++ ref ++ "]"
Just contents -> do
st <- askF
let contents' = runF contents st{ orgStateNotes' = [] }
return $ B.note contents'
noteMarker :: OrgParser String
noteMarker = try $ do
char '['
choice [ many1Till digit (char ']')
, (++) <$> string "fn:"
<*> many1Till (noneOf "\n\r\t ") (char ']')
]
linkOrImage :: OrgParser (F Inlines)
linkOrImage = explicitOrImageLink
<|> selflinkOrImage
<|> angleLink
<|> plainLink
<?> "link or image"
explicitOrImageLink :: OrgParser (F Inlines)
explicitOrImageLink = try $ do
char '['
srcF <- applyCustomLinkFormat =<< linkTarget
title <- enclosedRaw (char '[') (char ']')
title' <- parseFromString (mconcat <$> many inline) title
char ']'
return $ do
src <- srcF
if isImageFilename src && isImageFilename title
then pure $ B.link src "" $ B.image title mempty mempty
else linkToInlinesF src =<< title'
selflinkOrImage :: OrgParser (F Inlines)
selflinkOrImage = try $ do
src <- char '[' *> linkTarget <* char ']'
return $ linkToInlinesF src (B.str src)
plainLink :: OrgParser (F Inlines)
plainLink = try $ do
(orig, src) <- uri
returnF $ B.link src "" (B.str orig)
angleLink :: OrgParser (F Inlines)
angleLink = try $ do
char '<'
link <- plainLink
char '>'
return link
selfTarget :: OrgParser String
selfTarget = try $ char '[' *> linkTarget <* char ']'
linkTarget :: OrgParser String
linkTarget = enclosedByPair '[' ']' (noneOf "\n\r[]")
applyCustomLinkFormat :: String -> OrgParser (F String)
applyCustomLinkFormat link = do
let (linkType, rest) = break (== ':') link
return $ do
formatter <- M.lookup linkType <$> asksF orgStateLinkFormatters
return $ maybe link ($ drop 1 rest) formatter
linkToInlinesF :: String -> Inlines -> F Inlines
linkToInlinesF s@('#':_) = pure . B.link s ""
linkToInlinesF s
| isImageFilename s = const . pure $ B.image s "" ""
| isUri s = pure . B.link s ""
| isRelativeUrl s = pure . B.link s ""
linkToInlinesF s = \title -> do
anchorB <- (s `elem`) <$> asksF orgStateAnchorIds
if anchorB
then pure $ B.link ('#':s) "" title
else pure $ B.emph title
isRelativeUrl :: String -> Bool
isRelativeUrl s = (':' `notElem` s) && ("./" `isPrefixOf` s)
isUri :: String -> Bool
isUri s = let (scheme, path) = break (== ':') s
in all (\c -> isAlphaNum c || c `elem` ".-") scheme
&& not (null path)
isImageFilename :: String -> Bool
isImageFilename filename =
any (\x -> ('.':x) `isSuffixOf` filename) imageExtensions &&
(any (\x -> (x++":") `isPrefixOf` filename) protocols ||
':' `notElem` filename)
where
imageExtensions = [ "jpeg" , "jpg" , "png" , "gif" , "svg" ]
protocols = [ "file", "http", "https" ]
anchor :: OrgParser (F Inlines)
anchor = try $ do
anchorId <- parseAnchor
recordAnchorId anchorId
returnF $ B.spanWith (solidify anchorId, [], []) mempty
where
parseAnchor = string "<<"
*> many1 (noneOf "\t\n\r<>\"' ")
<* string ">>"
<* skipSpaces
solidify :: String -> String
solidify = map replaceSpecialChar
where replaceSpecialChar c
| isAlphaNum c = c
| c `elem` "_.-:" = c
| otherwise = '-'
inlineCodeBlock :: OrgParser (F Inlines)
inlineCodeBlock = try $ do
string "src_"
lang <- many1 orgArgWordChar
opts <- option [] $ enclosedByPair '[' ']' inlineBlockOption
inlineCode <- enclosedByPair '{' '}' (noneOf "\n\r")
let attrClasses = [translateLang lang, rundocBlockClass]
let attrKeyVal = map toRundocAttrib (("language", lang) : opts)
returnF $ B.codeWith ("", attrClasses, attrKeyVal) inlineCode
-> OrgParser [a]
enclosedByPair s e p = char s *> many1Till p (char e)
emph :: OrgParser (F Inlines)
emph = fmap B.emph <$> emphasisBetween '/'
strong :: OrgParser (F Inlines)
strong = fmap B.strong <$> emphasisBetween '*'
strikeout :: OrgParser (F Inlines)
strikeout = fmap B.strikeout <$> emphasisBetween '+'
underline :: OrgParser (F Inlines)
underline = fmap B.strong <$> emphasisBetween '_'
code :: OrgParser (F Inlines)
code = return . B.code <$> verbatimBetween '='
verbatim :: OrgParser (F Inlines)
verbatim = return . B.rawInline "" <$> verbatimBetween '~'
subscript :: OrgParser (F Inlines)
subscript = fmap B.subscript <$> try (char '_' *> subOrSuperExpr)
superscript :: OrgParser (F Inlines)
superscript = fmap B.superscript <$> try (char '^' *> subOrSuperExpr)
math :: OrgParser (F Inlines)
math = return . B.math <$> choice [ math1CharBetween '$'
, mathStringBetween '$'
, rawMathBetween "\\(" "\\)"
]
displayMath :: OrgParser (F Inlines)
displayMath = return . B.displayMath <$> choice [ rawMathBetween "\\[" "\\]"
, rawMathBetween "$$" "$$"
]
symbol :: OrgParser (F Inlines)
symbol = return . B.str . (: "") <$> (oneOf specialChars >>= updatePositions)
where updatePositions c
| c `elem` emphasisPreChars = c <$ updateLastPreCharPos
| c `elem` emphasisForbiddenBorderChars = c <$ updateLastForbiddenCharPos
| otherwise = return c
emphasisBetween :: Char
-> OrgParser (F Inlines)
emphasisBetween c = try $ do
startEmphasisNewlinesCounting emphasisAllowedNewlines
res <- enclosedInlines (emphasisStart c) (emphasisEnd c)
isTopLevelEmphasis <- null . orgStateEmphasisCharStack <$> getState
when isTopLevelEmphasis
resetEmphasisNewlines
return res
verbatimBetween :: Char
-> OrgParser String
verbatimBetween c = try $
emphasisStart c *>
many1TillNOrLessNewlines 1 (noneOf "\n\r") (emphasisEnd c)
| Parses a raw string delimited by @c@ using Org 's math rules
mathStringBetween :: Char
-> OrgParser String
mathStringBetween c = try $ do
mathStart c
body <- many1TillNOrLessNewlines mathAllowedNewlines
(noneOf (c:"\n\r"))
(lookAhead $ mathEnd c)
final <- mathEnd c
return $ body ++ [final]
math1CharBetween :: Char
-> OrgParser String
math1CharBetween c = try $ do
char c
res <- noneOf $ c:mathForbiddenBorderChars
char c
eof <|> () <$ lookAhead (oneOf mathPostChars)
return [res]
rawMathBetween :: String
-> String
-> OrgParser String
rawMathBetween s e = try $ string s *> manyTill anyChar (try $ string e)
emphasisStart :: Char -> OrgParser Char
emphasisStart c = try $ do
guard =<< afterEmphasisPreChar
guard =<< notAfterString
char c
lookAhead (noneOf emphasisForbiddenBorderChars)
pushToInlineCharStack c
return c
emphasisEnd :: Char -> OrgParser Char
emphasisEnd c = try $ do
guard =<< notAfterForbiddenBorderChar
char c
eof <|> () <$ lookAhead acceptablePostChars
updateLastStrPos
popInlineCharStack
return c
where acceptablePostChars =
surroundingEmphasisChar >>= \x -> oneOf (x ++ emphasisPostChars)
mathStart :: Char -> OrgParser Char
mathStart c = try $
char c <* notFollowedBy' (oneOf (c:mathForbiddenBorderChars))
mathEnd :: Char -> OrgParser Char
mathEnd c = try $ do
res <- noneOf (c:mathForbiddenBorderChars)
char c
eof <|> () <$ lookAhead (oneOf mathPostChars)
return res
enclosedInlines :: OrgParser a
-> OrgParser b
-> OrgParser (F Inlines)
enclosedInlines start end = try $
trimInlinesF . mconcat <$> enclosed start end inline
enclosedRaw :: OrgParser a
-> OrgParser b
-> OrgParser String
enclosedRaw start end = try $
start *> (onSingleLine <|> spanningTwoLines)
where onSingleLine = try $ many1Till (noneOf "\n\r") end
spanningTwoLines = try $
anyLine >>= \f -> mappend (f <> " ") <$> onSingleLine
| Like many1Till , but parses at most @n+1@ lines . @p@ must not consume
many1TillNOrLessNewlines :: Int
-> OrgParser Char
-> OrgParser a
-> OrgParser String
many1TillNOrLessNewlines n p end = try $
nMoreLines (Just n) mempty >>= oneOrMore
where
nMoreLines Nothing cs = return cs
nMoreLines (Just 0) cs = try $ (cs ++) <$> finalLine
nMoreLines k cs = try $ (final k cs <|> rest k cs)
>>= uncurry nMoreLines
final _ cs = (\x -> (Nothing, cs ++ x)) <$> try finalLine
rest m cs = (\x -> (minus1 <$> m, cs ++ x ++ "\n")) <$> try (manyTill p P.newline)
finalLine = try $ manyTill p end
minus1 k = k - 1
oneOrMore cs = guard (not $ null cs) *> return cs
emphasisPreChars :: [Char]
emphasisPreChars = "\t \"'({"
emphasisPostChars :: [Char]
emphasisPostChars = "\t\n !\"'),-.:;?\\}"
not allowed at the ( inner ) border of emphasis
emphasisForbiddenBorderChars :: [Char]
emphasisForbiddenBorderChars = "\t\n\r \"',"
emphasisAllowedNewlines :: Int
emphasisAllowedNewlines = 1
mathPostChars :: [Char]
mathPostChars = "\t\n \"'),-.:;?"
not allowed at the ( inner ) border of math
mathForbiddenBorderChars :: [Char]
mathForbiddenBorderChars = "\t\n\r ,;.$"
mathAllowedNewlines :: Int
mathAllowedNewlines = 2
afterEmphasisPreChar :: OrgParser Bool
afterEmphasisPreChar = do
pos <- getPosition
lastPrePos <- orgStateLastPreCharPos <$> getState
return . fromMaybe True $ (== pos) <$> lastPrePos
notAfterForbiddenBorderChar :: OrgParser Bool
notAfterForbiddenBorderChar = do
pos <- getPosition
lastFBCPos <- orgStateLastForbiddenCharPos <$> getState
return $ lastFBCPos /= Just pos
subOrSuperExpr :: OrgParser (F Inlines)
subOrSuperExpr = try $
choice [ id <$> charsInBalanced '{' '}' (noneOf "\n\r")
, enclosing ('(', ')') <$> charsInBalanced '(' ')' (noneOf "\n\r")
, simpleSubOrSuperString
] >>= parseFromString (mconcat <$> many inline)
where enclosing (left, right) s = left : s ++ [right]
simpleSubOrSuperString :: OrgParser String
simpleSubOrSuperString = try $
choice [ string "*"
, mappend <$> option [] ((:[]) <$> oneOf "+-")
<*> many1 alphaNum
]
|
8e03d985257c69541fd08d53d0e559a3984c30c1de7c49b3834c3c6326c05bc5 | SimulaVR/godot-haskell | NetworkedMultiplayerPeer.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.NetworkedMultiplayerPeer
(Godot.Core.NetworkedMultiplayerPeer._CONNECTION_DISCONNECTED,
Godot.Core.NetworkedMultiplayerPeer._TRANSFER_MODE_UNRELIABLE,
Godot.Core.NetworkedMultiplayerPeer._CONNECTION_CONNECTED,
Godot.Core.NetworkedMultiplayerPeer._TARGET_PEER_SERVER,
Godot.Core.NetworkedMultiplayerPeer._TARGET_PEER_BROADCAST,
Godot.Core.NetworkedMultiplayerPeer._CONNECTION_CONNECTING,
Godot.Core.NetworkedMultiplayerPeer._TRANSFER_MODE_RELIABLE,
Godot.Core.NetworkedMultiplayerPeer._TRANSFER_MODE_UNRELIABLE_ORDERED,
Godot.Core.NetworkedMultiplayerPeer.sig_connection_failed,
Godot.Core.NetworkedMultiplayerPeer.sig_connection_succeeded,
Godot.Core.NetworkedMultiplayerPeer.sig_peer_connected,
Godot.Core.NetworkedMultiplayerPeer.sig_peer_disconnected,
Godot.Core.NetworkedMultiplayerPeer.sig_server_disconnected,
Godot.Core.NetworkedMultiplayerPeer.get_connection_status,
Godot.Core.NetworkedMultiplayerPeer.get_packet_peer,
Godot.Core.NetworkedMultiplayerPeer.get_transfer_mode,
Godot.Core.NetworkedMultiplayerPeer.get_unique_id,
Godot.Core.NetworkedMultiplayerPeer.is_refusing_new_connections,
Godot.Core.NetworkedMultiplayerPeer.poll,
Godot.Core.NetworkedMultiplayerPeer.set_refuse_new_connections,
Godot.Core.NetworkedMultiplayerPeer.set_target_peer,
Godot.Core.NetworkedMultiplayerPeer.set_transfer_mode)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.PacketPeer()
_CONNECTION_DISCONNECTED :: Int
_CONNECTION_DISCONNECTED = 0
_TRANSFER_MODE_UNRELIABLE :: Int
_TRANSFER_MODE_UNRELIABLE = 0
_CONNECTION_CONNECTED :: Int
_CONNECTION_CONNECTED = 2
_TARGET_PEER_SERVER :: Int
_TARGET_PEER_SERVER = 1
_TARGET_PEER_BROADCAST :: Int
_TARGET_PEER_BROADCAST = 0
_CONNECTION_CONNECTING :: Int
_CONNECTION_CONNECTING = 1
_TRANSFER_MODE_RELIABLE :: Int
_TRANSFER_MODE_RELIABLE = 2
_TRANSFER_MODE_UNRELIABLE_ORDERED :: Int
_TRANSFER_MODE_UNRELIABLE_ORDERED = 1
-- | Emitted when a connection attempt fails.
sig_connection_failed ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_connection_failed
= Godot.Internal.Dispatch.Signal "connection_failed"
instance NodeSignal NetworkedMultiplayerPeer "connection_failed"
'[]
-- | Emitted when a connection attempt succeeds.
sig_connection_succeeded ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_connection_succeeded
= Godot.Internal.Dispatch.Signal "connection_succeeded"
instance NodeSignal NetworkedMultiplayerPeer "connection_succeeded"
'[]
-- | Emitted by the server when a client connects.
sig_peer_connected ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_peer_connected
= Godot.Internal.Dispatch.Signal "peer_connected"
instance NodeSignal NetworkedMultiplayerPeer "peer_connected"
'[Int]
-- | Emitted by the server when a client disconnects.
sig_peer_disconnected ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_peer_disconnected
= Godot.Internal.Dispatch.Signal "peer_disconnected"
instance NodeSignal NetworkedMultiplayerPeer "peer_disconnected"
'[Int]
-- | Emitted by clients when the server disconnects.
sig_server_disconnected ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_server_disconnected
= Godot.Internal.Dispatch.Signal "server_disconnected"
instance NodeSignal NetworkedMultiplayerPeer "server_disconnected"
'[]
instance NodeProperty NetworkedMultiplayerPeer
"refuse_new_connections"
Bool
'False
where
nodeProperty
= (is_refusing_new_connections,
wrapDroppingSetter set_refuse_new_connections, Nothing)
instance NodeProperty NetworkedMultiplayerPeer "transfer_mode" Int
'False
where
nodeProperty
= (get_transfer_mode, wrapDroppingSetter set_transfer_mode,
Nothing)
# NOINLINE bindNetworkedMultiplayerPeer_get_connection_status #
| Returns the current state of the connection . See @enum ConnectionStatus@.
bindNetworkedMultiplayerPeer_get_connection_status :: MethodBind
bindNetworkedMultiplayerPeer_get_connection_status
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_connection_status" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the current state of the connection . See @enum ConnectionStatus@.
get_connection_status ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_connection_status cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_get_connection_status
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer
"get_connection_status"
'[]
(IO Int)
where
nodeMethod
= Godot.Core.NetworkedMultiplayerPeer.get_connection_status
# NOINLINE bindNetworkedMultiplayerPeer_get_packet_peer #
-- | Returns the ID of the @NetworkedMultiplayerPeer@ who sent the most recent packet.
bindNetworkedMultiplayerPeer_get_packet_peer :: MethodBind
bindNetworkedMultiplayerPeer_get_packet_peer
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_packet_peer" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the ID of the @NetworkedMultiplayerPeer@ who sent the most recent packet.
get_packet_peer ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_packet_peer cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_get_packet_peer
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "get_packet_peer" '[]
(IO Int)
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.get_packet_peer
# NOINLINE bindNetworkedMultiplayerPeer_get_transfer_mode #
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
bindNetworkedMultiplayerPeer_get_transfer_mode :: MethodBind
bindNetworkedMultiplayerPeer_get_transfer_mode
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_transfer_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
get_transfer_mode ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_transfer_mode cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_get_transfer_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "get_transfer_mode"
'[]
(IO Int)
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.get_transfer_mode
# NOINLINE bindNetworkedMultiplayerPeer_get_unique_id #
-- | Returns the ID of this @NetworkedMultiplayerPeer@.
bindNetworkedMultiplayerPeer_get_unique_id :: MethodBind
bindNetworkedMultiplayerPeer_get_unique_id
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_unique_id" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Returns the ID of this @NetworkedMultiplayerPeer@.
get_unique_id ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_unique_id cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_get_unique_id
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "get_unique_id" '[]
(IO Int)
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.get_unique_id
# NOINLINE bindNetworkedMultiplayerPeer_is_refusing_new_connections
#
#-}
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
bindNetworkedMultiplayerPeer_is_refusing_new_connections ::
MethodBind
bindNetworkedMultiplayerPeer_is_refusing_new_connections
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "is_refusing_new_connections" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
is_refusing_new_connections ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Bool
is_refusing_new_connections cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_is_refusing_new_connections
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer
"is_refusing_new_connections"
'[]
(IO Bool)
where
nodeMethod
= Godot.Core.NetworkedMultiplayerPeer.is_refusing_new_connections
# NOINLINE bindNetworkedMultiplayerPeer_poll #
-- | Waits up to 1 second to receive a new network event.
bindNetworkedMultiplayerPeer_poll :: MethodBind
bindNetworkedMultiplayerPeer_poll
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "poll" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Waits up to 1 second to receive a new network event.
poll ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO ()
poll cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_poll
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "poll" '[] (IO ())
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.poll
# NOINLINE bindNetworkedMultiplayerPeer_set_refuse_new_connections
#
#-}
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
bindNetworkedMultiplayerPeer_set_refuse_new_connections ::
MethodBind
bindNetworkedMultiplayerPeer_set_refuse_new_connections
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "set_refuse_new_connections" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
set_refuse_new_connections ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) =>
cls -> Bool -> IO ()
set_refuse_new_connections cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_set_refuse_new_connections
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer
"set_refuse_new_connections"
'[Bool]
(IO ())
where
nodeMethod
= Godot.Core.NetworkedMultiplayerPeer.set_refuse_new_connections
# NOINLINE bindNetworkedMultiplayerPeer_set_target_peer #
-- | Sets the peer to which packets will be sent.
The @id@ can be one of : @TARGET_PEER_BROADCAST@ to send to all connected peers , @TARGET_PEER_SERVER@ to send to the peer acting as server , a valid peer ID to send to that specific peer , a negative peer ID to send to all peers except that one . By default , the target peer is @TARGET_PEER_BROADCAST@.
bindNetworkedMultiplayerPeer_set_target_peer :: MethodBind
bindNetworkedMultiplayerPeer_set_target_peer
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "set_target_peer" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
-- | Sets the peer to which packets will be sent.
The @id@ can be one of : @TARGET_PEER_BROADCAST@ to send to all connected peers , @TARGET_PEER_SERVER@ to send to the peer acting as server , a valid peer ID to send to that specific peer , a negative peer ID to send to all peers except that one . By default , the target peer is @TARGET_PEER_BROADCAST@.
set_target_peer ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) =>
cls -> Int -> IO ()
set_target_peer cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_set_target_peer
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "set_target_peer"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.set_target_peer
# NOINLINE bindNetworkedMultiplayerPeer_set_transfer_mode #
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
bindNetworkedMultiplayerPeer_set_transfer_mode :: MethodBind
bindNetworkedMultiplayerPeer_set_transfer_mode
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "set_transfer_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
set_transfer_mode ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) =>
cls -> Int -> IO ()
set_transfer_mode cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_set_transfer_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "set_transfer_mode"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.set_transfer_mode | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/NetworkedMultiplayerPeer.hs | haskell | | Emitted when a connection attempt fails.
| Emitted when a connection attempt succeeds.
| Emitted by the server when a client connects.
| Emitted by the server when a client disconnects.
| Emitted by clients when the server disconnects.
| Returns the ID of the @NetworkedMultiplayerPeer@ who sent the most recent packet.
| Returns the ID of the @NetworkedMultiplayerPeer@ who sent the most recent packet.
| Returns the ID of this @NetworkedMultiplayerPeer@.
| Returns the ID of this @NetworkedMultiplayerPeer@.
| Waits up to 1 second to receive a new network event.
| Waits up to 1 second to receive a new network event.
| Sets the peer to which packets will be sent.
| Sets the peer to which packets will be sent. | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.NetworkedMultiplayerPeer
(Godot.Core.NetworkedMultiplayerPeer._CONNECTION_DISCONNECTED,
Godot.Core.NetworkedMultiplayerPeer._TRANSFER_MODE_UNRELIABLE,
Godot.Core.NetworkedMultiplayerPeer._CONNECTION_CONNECTED,
Godot.Core.NetworkedMultiplayerPeer._TARGET_PEER_SERVER,
Godot.Core.NetworkedMultiplayerPeer._TARGET_PEER_BROADCAST,
Godot.Core.NetworkedMultiplayerPeer._CONNECTION_CONNECTING,
Godot.Core.NetworkedMultiplayerPeer._TRANSFER_MODE_RELIABLE,
Godot.Core.NetworkedMultiplayerPeer._TRANSFER_MODE_UNRELIABLE_ORDERED,
Godot.Core.NetworkedMultiplayerPeer.sig_connection_failed,
Godot.Core.NetworkedMultiplayerPeer.sig_connection_succeeded,
Godot.Core.NetworkedMultiplayerPeer.sig_peer_connected,
Godot.Core.NetworkedMultiplayerPeer.sig_peer_disconnected,
Godot.Core.NetworkedMultiplayerPeer.sig_server_disconnected,
Godot.Core.NetworkedMultiplayerPeer.get_connection_status,
Godot.Core.NetworkedMultiplayerPeer.get_packet_peer,
Godot.Core.NetworkedMultiplayerPeer.get_transfer_mode,
Godot.Core.NetworkedMultiplayerPeer.get_unique_id,
Godot.Core.NetworkedMultiplayerPeer.is_refusing_new_connections,
Godot.Core.NetworkedMultiplayerPeer.poll,
Godot.Core.NetworkedMultiplayerPeer.set_refuse_new_connections,
Godot.Core.NetworkedMultiplayerPeer.set_target_peer,
Godot.Core.NetworkedMultiplayerPeer.set_transfer_mode)
where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.PacketPeer()
_CONNECTION_DISCONNECTED :: Int
_CONNECTION_DISCONNECTED = 0
_TRANSFER_MODE_UNRELIABLE :: Int
_TRANSFER_MODE_UNRELIABLE = 0
_CONNECTION_CONNECTED :: Int
_CONNECTION_CONNECTED = 2
_TARGET_PEER_SERVER :: Int
_TARGET_PEER_SERVER = 1
_TARGET_PEER_BROADCAST :: Int
_TARGET_PEER_BROADCAST = 0
_CONNECTION_CONNECTING :: Int
_CONNECTION_CONNECTING = 1
_TRANSFER_MODE_RELIABLE :: Int
_TRANSFER_MODE_RELIABLE = 2
_TRANSFER_MODE_UNRELIABLE_ORDERED :: Int
_TRANSFER_MODE_UNRELIABLE_ORDERED = 1
sig_connection_failed ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_connection_failed
= Godot.Internal.Dispatch.Signal "connection_failed"
instance NodeSignal NetworkedMultiplayerPeer "connection_failed"
'[]
sig_connection_succeeded ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_connection_succeeded
= Godot.Internal.Dispatch.Signal "connection_succeeded"
instance NodeSignal NetworkedMultiplayerPeer "connection_succeeded"
'[]
sig_peer_connected ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_peer_connected
= Godot.Internal.Dispatch.Signal "peer_connected"
instance NodeSignal NetworkedMultiplayerPeer "peer_connected"
'[Int]
sig_peer_disconnected ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_peer_disconnected
= Godot.Internal.Dispatch.Signal "peer_disconnected"
instance NodeSignal NetworkedMultiplayerPeer "peer_disconnected"
'[Int]
sig_server_disconnected ::
Godot.Internal.Dispatch.Signal NetworkedMultiplayerPeer
sig_server_disconnected
= Godot.Internal.Dispatch.Signal "server_disconnected"
instance NodeSignal NetworkedMultiplayerPeer "server_disconnected"
'[]
instance NodeProperty NetworkedMultiplayerPeer
"refuse_new_connections"
Bool
'False
where
nodeProperty
= (is_refusing_new_connections,
wrapDroppingSetter set_refuse_new_connections, Nothing)
instance NodeProperty NetworkedMultiplayerPeer "transfer_mode" Int
'False
where
nodeProperty
= (get_transfer_mode, wrapDroppingSetter set_transfer_mode,
Nothing)
# NOINLINE bindNetworkedMultiplayerPeer_get_connection_status #
| Returns the current state of the connection . See @enum ConnectionStatus@.
bindNetworkedMultiplayerPeer_get_connection_status :: MethodBind
bindNetworkedMultiplayerPeer_get_connection_status
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_connection_status" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| Returns the current state of the connection . See @enum ConnectionStatus@.
get_connection_status ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_connection_status cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_get_connection_status
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer
"get_connection_status"
'[]
(IO Int)
where
nodeMethod
= Godot.Core.NetworkedMultiplayerPeer.get_connection_status
# NOINLINE bindNetworkedMultiplayerPeer_get_packet_peer #
bindNetworkedMultiplayerPeer_get_packet_peer :: MethodBind
bindNetworkedMultiplayerPeer_get_packet_peer
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_packet_peer" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_packet_peer ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_packet_peer cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_get_packet_peer
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "get_packet_peer" '[]
(IO Int)
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.get_packet_peer
# NOINLINE bindNetworkedMultiplayerPeer_get_transfer_mode #
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
bindNetworkedMultiplayerPeer_get_transfer_mode :: MethodBind
bindNetworkedMultiplayerPeer_get_transfer_mode
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_transfer_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
get_transfer_mode ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_transfer_mode cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_get_transfer_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "get_transfer_mode"
'[]
(IO Int)
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.get_transfer_mode
# NOINLINE bindNetworkedMultiplayerPeer_get_unique_id #
bindNetworkedMultiplayerPeer_get_unique_id :: MethodBind
bindNetworkedMultiplayerPeer_get_unique_id
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "get_unique_id" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
get_unique_id ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Int
get_unique_id cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_get_unique_id
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "get_unique_id" '[]
(IO Int)
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.get_unique_id
# NOINLINE bindNetworkedMultiplayerPeer_is_refusing_new_connections
#
#-}
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
bindNetworkedMultiplayerPeer_is_refusing_new_connections ::
MethodBind
bindNetworkedMultiplayerPeer_is_refusing_new_connections
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "is_refusing_new_connections" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
is_refusing_new_connections ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO Bool
is_refusing_new_connections cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_is_refusing_new_connections
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer
"is_refusing_new_connections"
'[]
(IO Bool)
where
nodeMethod
= Godot.Core.NetworkedMultiplayerPeer.is_refusing_new_connections
# NOINLINE bindNetworkedMultiplayerPeer_poll #
bindNetworkedMultiplayerPeer_poll :: MethodBind
bindNetworkedMultiplayerPeer_poll
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "poll" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
poll ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) => cls -> IO ()
poll cls
= withVariantArray []
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_poll
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "poll" '[] (IO ())
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.poll
# NOINLINE bindNetworkedMultiplayerPeer_set_refuse_new_connections
#
#-}
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
bindNetworkedMultiplayerPeer_set_refuse_new_connections ::
MethodBind
bindNetworkedMultiplayerPeer_set_refuse_new_connections
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "set_refuse_new_connections" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| If @true@ , this @NetworkedMultiplayerPeer@ refuses new connections .
set_refuse_new_connections ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) =>
cls -> Bool -> IO ()
set_refuse_new_connections cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_set_refuse_new_connections
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer
"set_refuse_new_connections"
'[Bool]
(IO ())
where
nodeMethod
= Godot.Core.NetworkedMultiplayerPeer.set_refuse_new_connections
# NOINLINE bindNetworkedMultiplayerPeer_set_target_peer #
The @id@ can be one of : @TARGET_PEER_BROADCAST@ to send to all connected peers , @TARGET_PEER_SERVER@ to send to the peer acting as server , a valid peer ID to send to that specific peer , a negative peer ID to send to all peers except that one . By default , the target peer is @TARGET_PEER_BROADCAST@.
bindNetworkedMultiplayerPeer_set_target_peer :: MethodBind
bindNetworkedMultiplayerPeer_set_target_peer
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "set_target_peer" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
The @id@ can be one of : @TARGET_PEER_BROADCAST@ to send to all connected peers , @TARGET_PEER_SERVER@ to send to the peer acting as server , a valid peer ID to send to that specific peer , a negative peer ID to send to all peers except that one . By default , the target peer is @TARGET_PEER_BROADCAST@.
set_target_peer ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) =>
cls -> Int -> IO ()
set_target_peer cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call bindNetworkedMultiplayerPeer_set_target_peer
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "set_target_peer"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.set_target_peer
# NOINLINE bindNetworkedMultiplayerPeer_set_transfer_mode #
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
bindNetworkedMultiplayerPeer_set_transfer_mode :: MethodBind
bindNetworkedMultiplayerPeer_set_transfer_mode
= unsafePerformIO $
withCString "NetworkedMultiplayerPeer" $
\ clsNamePtr ->
withCString "set_transfer_mode" $
\ methodNamePtr ->
godot_method_bind_get_method clsNamePtr methodNamePtr
| The manner in which to send packets to the @target_peer@. See @enum TransferMode@.
set_transfer_mode ::
(NetworkedMultiplayerPeer :< cls, Object :< cls) =>
cls -> Int -> IO ()
set_transfer_mode cls arg1
= withVariantArray [toVariant arg1]
(\ (arrPtr, len) ->
godot_method_bind_call
bindNetworkedMultiplayerPeer_set_transfer_mode
(upcast cls)
arrPtr
len
>>= \ (err, res) -> throwIfErr err >> fromGodotVariant res)
instance NodeMethod NetworkedMultiplayerPeer "set_transfer_mode"
'[Int]
(IO ())
where
nodeMethod = Godot.Core.NetworkedMultiplayerPeer.set_transfer_mode |
e84f67e6141665febc35315e3afbde1f8f6c18acb57d9e85b7f6017c2d56dc6d | Verites/verigraph | FindCospanCommuterTest.hs | module Data.TypedGraph.Morphism.FindMorphismSpec.FindCospanCommuterTest (findCospanCommuterTest) where
import Abstract.Category
import Abstract.Category.FindMorphism
import Category.TypedGraph ()
import Data.Graphs
import qualified Data.Graphs.Morphism as GM
import qualified Data.TypedGraph.Morphism as TGM
import Test.Hspec
type TGM a b = TGM.TypedGraphMorphism a b
type GM a b = GM.GraphMorphism (Maybe a) (Maybe b)
type G a b = Graph (Maybe a) (Maybe b)
findCospanCommuterTest :: Spec
findCospanCommuterTest =
it "Should return the same value as the exhaustive method" $ do
-- | Tests with only nodes
genericTest tgm1 tgm1
genericTest tgm3 tgm2
genericTest tgm2 tgm3
genericTest tgm3 tgm1
genericTest tgm1 tgm3
| Not a valid Cospan : @B - > A@ and @A ' < - C@
genericTest tgm4 tgm1
genericTest tgm1 tgm4
genericTest tgm5 tgm1
genericTest tgm1 tgm5
-- | Tests with edges
genericTest tgm6 tgm6
genericTest tgm7 tgm6
genericTest tgm6 tgm7
genericTest tgm9 tgm8
genericTest tgm8 tgm9
-- | Tests with loops
genericTest tgm10 tgm11
genericTest tgm11 tgm10
-- | TypedGraphMorphism instances. Digraphs with only nodes
tgm1 :: TGM a b
tgm1 = TGM.buildTypedGraphMorphism g2 g2 $ GM.buildGraphMorphism g2' g2' [(1,1),(2,2)] []
tgm2 :: TGM a b
tgm2 = TGM.buildTypedGraphMorphism g2 g1 $ GM.buildGraphMorphism g2' g1' [(1,1),(2,1)] []
tgm3 :: TGM a b
tgm3 = TGM.buildTypedGraphMorphism g1 g1 $ GM.buildGraphMorphism g1' g1' [(1,1)] []
tgm4 :: TGM a b
tgm4 = TGM.buildTypedGraphMorphism g1 g2 $ GM.buildGraphMorphism g1' g2' [(1,1)] []
tgm5 :: TGM a b
tgm5 = TGM.buildTypedGraphMorphism g3 g2 $ GM.buildGraphMorphism g3' g2' [(1,1),(2,2),(3,2)] []
-- | TypedGraphMorphism instances. Digraphs with only nodes
tgm6 :: TGM a b
tgm6 = TGM.buildTypedGraphMorphism g4 g4 $ GM.buildGraphMorphism g4' g4' [(1,1),(2,2)] [(1,1)]
tgm7 :: TGM a b
tgm7 = TGM.buildTypedGraphMorphism g5 g4 $ GM.buildGraphMorphism g5' g4' [(1,1),(2,2)][(1,1),(2,1)]
tgm8 :: TGM a b
tgm8 = TGM.buildTypedGraphMorphism g5 g5 $ GM.buildGraphMorphism g5' g5' [(1,1),(2,2)][(1,1),(2,2)]
tgm9 :: TGM a b
tgm9 = TGM.buildTypedGraphMorphism g6 g5 $ GM.buildGraphMorphism g6' g5' [(1,1),(2,2)][(1,1),(2,2),(3,1)]
-- | TypedGraphMorphism instances. Digraphs with loops
tgm10 :: TGM a b
tgm10 = TGM.buildTypedGraphMorphism g7 g7 $ GM.buildGraphMorphism g7' g7' [(1,1)] [(1,1)]
tgm11 :: TGM a b
tgm11 = TGM.buildTypedGraphMorphism g8 g7 $ GM.buildGraphMorphism g8' g7' [(1,1),(2,1)][(1,1),(2,1)]
-- | Graphs instances for tests
typegraph :: Graph (Maybe a) (Maybe b)
typegraph = build [1,2] [(1,1,2)]
-- | Digraphs with only nodes
|digraph G1 {
-- 1 [shape = circle];
-- }
g1 :: GM a b
g1 = GM.buildGraphMorphism g1' typegraph [(1,1)] []
g1' :: G a b
g1' = build [1] []
|digraph G2 {
-- 1 [shape = circle];
-- 2 [shape = circle];
-- }
g2 :: GM a b
g2 = GM.buildGraphMorphism g2' typegraph [(1,1),(2,1)] []
g2' :: G a b
g2' = build [1,2] []
|digraph G3 {
-- 1 [shape = circle];
-- 2 [shape = box];
-- 3 [shape = circle];
-- }
g3 :: GM a b
g3 = GM.buildGraphMorphism g3' typegraph [(1,1),(2,1),(3,1)] []
g3' :: G a b
g3' = build [1,2,3] []
-- | Digraphs with edges
|digraph G4 {
-- 1 [shape = circle];
-- 2 [shape = circle];
--
1 - > 2 ;
--
-- }
g4 :: GM a b
g4 = GM.buildGraphMorphism g4' typegraph [(1,1),(2,1)] [(1,1)]
g4' :: G a b
g4' = build [1,2] [(1,1,2)]
|digraph G5 {
-- 1 [shape = circle];
-- 2 [shape = circle];
--
1 - > 2 ;
1 - > 2 ;
--
-- }
g5 :: GM a b
g5 = GM.buildGraphMorphism g5' typegraph [(1,1),(2,1)] [(1,1),(2,1)]
g5' :: G a b
g5' = build [1,2] [(1,1,2),(2,1,2)]
|digraph G6 {
-- 1 [shape = circle];
-- 2 [shape = circle];
--
1 - > 2 ;
1 - > 2 ;
1 - > 2 ;
--
-- }
g6 :: GM a b
g6 = GM.buildGraphMorphism g6' typegraph [(1,1),(2,1)] [(1,1),(2,1),(3,1)]
g6' :: G a b
g6' = build [1,2] [(1,1,2),(2,1,2),(3,1,2)]
-- | Digraphs with loops for validity tests
-- | digraph G7 {
1 [ shape = circle ] ;
--
1 - > 1 ;
--
-- }
g7 :: GM a b
g7 = GM.buildGraphMorphism g7' typegraph [(1,1)] [(1,1)]
g7' :: G a b
g7' = build [1] [(1,1,1)]
-- | digraph G8 {
1 [ shape = circle ] ;
2 [ shape = circle ] ;
--
1 - > 1 ;
2 - > 2 ;
--
-- }
g8 :: GM a b
g8 = GM.buildGraphMorphism g8' typegraph [(1,1),(2,1)] [(1,1),(2,1)]
g8' :: G a b
g8' = build [1,2] [(1,1,1),(2,2,2)]
-- | Auxiliary functions to tests
genericTest :: TGM a b -> TGM a b -> Expectation
genericTest morphismOne morphismTwo =
do
genericCompare anyMorphism morphismOne morphismTwo
genericCompare monic morphismOne morphismTwo
genericCompare epic morphismOne morphismTwo
genericCompare iso morphismOne morphismTwo
genericCompare :: MorphismClass (TGM a b) -> TGM a b -> TGM a b -> Expectation
genericCompare conf morphismOne morphismTwo =
findCospanCommuters conf morphismOne morphismTwo
`shouldBe` genericCommuter conf morphismOne morphismTwo
genericCommuter :: MorphismClass (TGM a b) -> TGM a b -> TGM a b -> [TGM a b]
genericCommuter conf morphismOne morphismTwo =
filter commutes $ findMorphisms conf (domain morphismOne) (domain morphismTwo)
where commutes x = morphismOne == morphismTwo <&> x
| null | https://raw.githubusercontent.com/Verites/verigraph/754ec08bf4a55ea7402d8cd0705e58b1d2c9cd67/tests/Data/TypedGraph/Morphism/FindMorphismSpec/FindCospanCommuterTest.hs | haskell | | Tests with only nodes
| Tests with edges
| Tests with loops
| TypedGraphMorphism instances. Digraphs with only nodes
| TypedGraphMorphism instances. Digraphs with only nodes
| TypedGraphMorphism instances. Digraphs with loops
| Graphs instances for tests
| Digraphs with only nodes
1 [shape = circle];
}
1 [shape = circle];
2 [shape = circle];
}
1 [shape = circle];
2 [shape = box];
3 [shape = circle];
}
| Digraphs with edges
1 [shape = circle];
2 [shape = circle];
}
1 [shape = circle];
2 [shape = circle];
}
1 [shape = circle];
2 [shape = circle];
}
| Digraphs with loops for validity tests
| digraph G7 {
}
| digraph G8 {
}
| Auxiliary functions to tests | module Data.TypedGraph.Morphism.FindMorphismSpec.FindCospanCommuterTest (findCospanCommuterTest) where
import Abstract.Category
import Abstract.Category.FindMorphism
import Category.TypedGraph ()
import Data.Graphs
import qualified Data.Graphs.Morphism as GM
import qualified Data.TypedGraph.Morphism as TGM
import Test.Hspec
type TGM a b = TGM.TypedGraphMorphism a b
type GM a b = GM.GraphMorphism (Maybe a) (Maybe b)
type G a b = Graph (Maybe a) (Maybe b)
findCospanCommuterTest :: Spec
findCospanCommuterTest =
it "Should return the same value as the exhaustive method" $ do
genericTest tgm1 tgm1
genericTest tgm3 tgm2
genericTest tgm2 tgm3
genericTest tgm3 tgm1
genericTest tgm1 tgm3
| Not a valid Cospan : @B - > A@ and @A ' < - C@
genericTest tgm4 tgm1
genericTest tgm1 tgm4
genericTest tgm5 tgm1
genericTest tgm1 tgm5
genericTest tgm6 tgm6
genericTest tgm7 tgm6
genericTest tgm6 tgm7
genericTest tgm9 tgm8
genericTest tgm8 tgm9
genericTest tgm10 tgm11
genericTest tgm11 tgm10
tgm1 :: TGM a b
tgm1 = TGM.buildTypedGraphMorphism g2 g2 $ GM.buildGraphMorphism g2' g2' [(1,1),(2,2)] []
tgm2 :: TGM a b
tgm2 = TGM.buildTypedGraphMorphism g2 g1 $ GM.buildGraphMorphism g2' g1' [(1,1),(2,1)] []
tgm3 :: TGM a b
tgm3 = TGM.buildTypedGraphMorphism g1 g1 $ GM.buildGraphMorphism g1' g1' [(1,1)] []
tgm4 :: TGM a b
tgm4 = TGM.buildTypedGraphMorphism g1 g2 $ GM.buildGraphMorphism g1' g2' [(1,1)] []
tgm5 :: TGM a b
tgm5 = TGM.buildTypedGraphMorphism g3 g2 $ GM.buildGraphMorphism g3' g2' [(1,1),(2,2),(3,2)] []
tgm6 :: TGM a b
tgm6 = TGM.buildTypedGraphMorphism g4 g4 $ GM.buildGraphMorphism g4' g4' [(1,1),(2,2)] [(1,1)]
tgm7 :: TGM a b
tgm7 = TGM.buildTypedGraphMorphism g5 g4 $ GM.buildGraphMorphism g5' g4' [(1,1),(2,2)][(1,1),(2,1)]
tgm8 :: TGM a b
tgm8 = TGM.buildTypedGraphMorphism g5 g5 $ GM.buildGraphMorphism g5' g5' [(1,1),(2,2)][(1,1),(2,2)]
tgm9 :: TGM a b
tgm9 = TGM.buildTypedGraphMorphism g6 g5 $ GM.buildGraphMorphism g6' g5' [(1,1),(2,2)][(1,1),(2,2),(3,1)]
tgm10 :: TGM a b
tgm10 = TGM.buildTypedGraphMorphism g7 g7 $ GM.buildGraphMorphism g7' g7' [(1,1)] [(1,1)]
tgm11 :: TGM a b
tgm11 = TGM.buildTypedGraphMorphism g8 g7 $ GM.buildGraphMorphism g8' g7' [(1,1),(2,1)][(1,1),(2,1)]
typegraph :: Graph (Maybe a) (Maybe b)
typegraph = build [1,2] [(1,1,2)]
|digraph G1 {
g1 :: GM a b
g1 = GM.buildGraphMorphism g1' typegraph [(1,1)] []
g1' :: G a b
g1' = build [1] []
|digraph G2 {
g2 :: GM a b
g2 = GM.buildGraphMorphism g2' typegraph [(1,1),(2,1)] []
g2' :: G a b
g2' = build [1,2] []
|digraph G3 {
g3 :: GM a b
g3 = GM.buildGraphMorphism g3' typegraph [(1,1),(2,1),(3,1)] []
g3' :: G a b
g3' = build [1,2,3] []
|digraph G4 {
1 - > 2 ;
g4 :: GM a b
g4 = GM.buildGraphMorphism g4' typegraph [(1,1),(2,1)] [(1,1)]
g4' :: G a b
g4' = build [1,2] [(1,1,2)]
|digraph G5 {
1 - > 2 ;
1 - > 2 ;
g5 :: GM a b
g5 = GM.buildGraphMorphism g5' typegraph [(1,1),(2,1)] [(1,1),(2,1)]
g5' :: G a b
g5' = build [1,2] [(1,1,2),(2,1,2)]
|digraph G6 {
1 - > 2 ;
1 - > 2 ;
1 - > 2 ;
g6 :: GM a b
g6 = GM.buildGraphMorphism g6' typegraph [(1,1),(2,1)] [(1,1),(2,1),(3,1)]
g6' :: G a b
g6' = build [1,2] [(1,1,2),(2,1,2),(3,1,2)]
1 [ shape = circle ] ;
1 - > 1 ;
g7 :: GM a b
g7 = GM.buildGraphMorphism g7' typegraph [(1,1)] [(1,1)]
g7' :: G a b
g7' = build [1] [(1,1,1)]
1 [ shape = circle ] ;
2 [ shape = circle ] ;
1 - > 1 ;
2 - > 2 ;
g8 :: GM a b
g8 = GM.buildGraphMorphism g8' typegraph [(1,1),(2,1)] [(1,1),(2,1)]
g8' :: G a b
g8' = build [1,2] [(1,1,1),(2,2,2)]
genericTest :: TGM a b -> TGM a b -> Expectation
genericTest morphismOne morphismTwo =
do
genericCompare anyMorphism morphismOne morphismTwo
genericCompare monic morphismOne morphismTwo
genericCompare epic morphismOne morphismTwo
genericCompare iso morphismOne morphismTwo
genericCompare :: MorphismClass (TGM a b) -> TGM a b -> TGM a b -> Expectation
genericCompare conf morphismOne morphismTwo =
findCospanCommuters conf morphismOne morphismTwo
`shouldBe` genericCommuter conf morphismOne morphismTwo
genericCommuter :: MorphismClass (TGM a b) -> TGM a b -> TGM a b -> [TGM a b]
genericCommuter conf morphismOne morphismTwo =
filter commutes $ findMorphisms conf (domain morphismOne) (domain morphismTwo)
where commutes x = morphismOne == morphismTwo <&> x
|
9b989a8df15c737bb24df35e3d70ec8666caa6cbe0ee66e99f763f8acc35156d | k16shikano/hpdft | Outlines.hs | {-# LANGUAGE OverloadedStrings #-}
|
Module : PDF.Outlines
Description : Function to get /Outlines object
Copyright : ( c ) , 2016
License : MIT
Maintainer :
Function to grub /Outlines in PDF trailer . It mainly provides texts for Table of Contents .
Module : PDF.Outlines
Description : Function to get /Outlines object
Copyright : (c) Keiichiro Shikano, 2016
License : MIT
Maintainer :
Function to grub /Outlines in PDF trailer. It mainly provides texts for Table of Contents.
-}
module PDF.Outlines
( getOutlines
) where
import Debug.Trace
import Data.List (find)
import Data.Attoparsec.ByteString hiding (inClass, notInClass, satisfy)
import Data.Attoparsec.ByteString.Char8
import Data.Attoparsec.Combinator
import qualified Data.ByteString.Char8 as BS
import PDF.Definition hiding (toString)
import PDF.DocumentStructure
import PDF.Object (parseRefsArray, parsePdfLetters)
import PDF.PDFIO
data PDFOutlines = PDFOutlinesTree [PDFOutlines]
| PDFOutlinesEntry { dest :: Int
, text :: String
, subs :: PDFOutlines
}
| PDFOutlinesNE
instance Show PDFOutlines where
show = toString 0
toString :: Int -> PDFOutlines -> String
toString depth PDFOutlinesEntry {dest=d, text=t, subs=s} = (replicate depth ' ' ++ t) ++ toString (depth+1) s
toString depth (PDFOutlinesTree os) = concatMap (toString depth) os
toString depth PDFOutlinesNE = ""
| Get information of \/Outlines from ' filename '
getOutlines :: FilePath -> IO PDFOutlines
getOutlines filename = do
dict <- outlineObjFromFile filename
objs <- getPDFObjFromFile filename
firstref <- case findFirst dict of
Just r -> return r
Nothing -> error "No top level outline entry."
firstdict <- case findObjsByRef firstref objs of
Just [PdfDict d] -> return d
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error $ "No Object with Ref " ++ show firstref
return $ gatherOutlines firstdict objs
gatherChildren dict objs = case findFirst dict of
Just r -> case findObjsByRef r objs of
Just [PdfDict d] -> gatherOutlines d objs
Just s -> error $ "Unknown Object at " ++ show r
Nothing -> error $ "No Object with Ref " ++ show r
Nothing -> PDFOutlinesNE
gatherOutlines dict objs =
let c = gatherChildren dict objs
in case findNext dict of
Just r -> case findObjsByRef r objs of
Just [PdfDict d] -> PDFOutlinesTree (PDFOutlinesEntry { dest = head $ findDest dict
, text = findTitle dict objs ++ "\n"
, subs = c}
: [gatherOutlines d objs])
Just s -> error $ "Unknown Object at " ++ show r
Nothing -> error $ "No Object with Ref " ++ show r
Nothing -> PDFOutlinesEntry { dest = head $ findDest dict
, text = findTitle dict objs ++ "\n"
, subs = c}
outlines :: Dict -> Int
outlines dict = case find isOutlinesRef dict of
Just (_, ObjRef x) -> x
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error "There seems no /Outlines in the root"
where
isOutlinesRef (PdfName "/Outlines", ObjRef x) = True
isOutlinesRef (_,_) = False
outlineObjFromFile :: String -> IO Dict
outlineObjFromFile filename = do
objs <- getPDFObjFromFile filename
rootref <- getRootRef filename
rootobj <- case findObjsByRef rootref objs of
Just os -> return os
Nothing -> error "Could not get root object."
outlineref <- case findDict rootobj of
Just dict -> return $ outlines dict
Nothing -> error "Something wrong..."
case findObjsByRef outlineref objs of
Just [PdfDict d] -> return d
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error "Could not get outlines object"
findTitle dict objs =
case findObjFromDict dict "/Title" of
Just (PdfText s) -> case parseOnly parsePdfLetters (BS.pack s) of
Right t -> t
Left err -> s
Just (ObjRef r) -> case findObjsByRef r objs of
Just [PdfText s] -> s
Just s -> error $ "Unknown Object at " ++ show r
Nothing -> error $ "No title object in " ++ show r
Just x -> show x
Nothing -> error "No title object."
findDest dict =
case findObjFromDict dict "/Dest" of
Just (PdfArray a) -> parseRefsArray a
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error "No destination object."
findNext dict =
case findObjFromDict dict "/Next" of
Just (ObjRef x) -> Just x
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> Nothing
findFirst dict =
case findObjFromDict dict "/First" of
Just (ObjRef x) -> Just x
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> Nothing
| null | https://raw.githubusercontent.com/k16shikano/hpdft/20d5b0a89d144c72a56ec8b4adb1b7735e7cd66c/src/PDF/Outlines.hs | haskell | # LANGUAGE OverloadedStrings # |
|
Module : PDF.Outlines
Description : Function to get /Outlines object
Copyright : ( c ) , 2016
License : MIT
Maintainer :
Function to grub /Outlines in PDF trailer . It mainly provides texts for Table of Contents .
Module : PDF.Outlines
Description : Function to get /Outlines object
Copyright : (c) Keiichiro Shikano, 2016
License : MIT
Maintainer :
Function to grub /Outlines in PDF trailer. It mainly provides texts for Table of Contents.
-}
module PDF.Outlines
( getOutlines
) where
import Debug.Trace
import Data.List (find)
import Data.Attoparsec.ByteString hiding (inClass, notInClass, satisfy)
import Data.Attoparsec.ByteString.Char8
import Data.Attoparsec.Combinator
import qualified Data.ByteString.Char8 as BS
import PDF.Definition hiding (toString)
import PDF.DocumentStructure
import PDF.Object (parseRefsArray, parsePdfLetters)
import PDF.PDFIO
data PDFOutlines = PDFOutlinesTree [PDFOutlines]
| PDFOutlinesEntry { dest :: Int
, text :: String
, subs :: PDFOutlines
}
| PDFOutlinesNE
instance Show PDFOutlines where
show = toString 0
toString :: Int -> PDFOutlines -> String
toString depth PDFOutlinesEntry {dest=d, text=t, subs=s} = (replicate depth ' ' ++ t) ++ toString (depth+1) s
toString depth (PDFOutlinesTree os) = concatMap (toString depth) os
toString depth PDFOutlinesNE = ""
| Get information of \/Outlines from ' filename '
getOutlines :: FilePath -> IO PDFOutlines
getOutlines filename = do
dict <- outlineObjFromFile filename
objs <- getPDFObjFromFile filename
firstref <- case findFirst dict of
Just r -> return r
Nothing -> error "No top level outline entry."
firstdict <- case findObjsByRef firstref objs of
Just [PdfDict d] -> return d
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error $ "No Object with Ref " ++ show firstref
return $ gatherOutlines firstdict objs
gatherChildren dict objs = case findFirst dict of
Just r -> case findObjsByRef r objs of
Just [PdfDict d] -> gatherOutlines d objs
Just s -> error $ "Unknown Object at " ++ show r
Nothing -> error $ "No Object with Ref " ++ show r
Nothing -> PDFOutlinesNE
gatherOutlines dict objs =
let c = gatherChildren dict objs
in case findNext dict of
Just r -> case findObjsByRef r objs of
Just [PdfDict d] -> PDFOutlinesTree (PDFOutlinesEntry { dest = head $ findDest dict
, text = findTitle dict objs ++ "\n"
, subs = c}
: [gatherOutlines d objs])
Just s -> error $ "Unknown Object at " ++ show r
Nothing -> error $ "No Object with Ref " ++ show r
Nothing -> PDFOutlinesEntry { dest = head $ findDest dict
, text = findTitle dict objs ++ "\n"
, subs = c}
outlines :: Dict -> Int
outlines dict = case find isOutlinesRef dict of
Just (_, ObjRef x) -> x
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error "There seems no /Outlines in the root"
where
isOutlinesRef (PdfName "/Outlines", ObjRef x) = True
isOutlinesRef (_,_) = False
outlineObjFromFile :: String -> IO Dict
outlineObjFromFile filename = do
objs <- getPDFObjFromFile filename
rootref <- getRootRef filename
rootobj <- case findObjsByRef rootref objs of
Just os -> return os
Nothing -> error "Could not get root object."
outlineref <- case findDict rootobj of
Just dict -> return $ outlines dict
Nothing -> error "Something wrong..."
case findObjsByRef outlineref objs of
Just [PdfDict d] -> return d
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error "Could not get outlines object"
findTitle dict objs =
case findObjFromDict dict "/Title" of
Just (PdfText s) -> case parseOnly parsePdfLetters (BS.pack s) of
Right t -> t
Left err -> s
Just (ObjRef r) -> case findObjsByRef r objs of
Just [PdfText s] -> s
Just s -> error $ "Unknown Object at " ++ show r
Nothing -> error $ "No title object in " ++ show r
Just x -> show x
Nothing -> error "No title object."
findDest dict =
case findObjFromDict dict "/Dest" of
Just (PdfArray a) -> parseRefsArray a
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> error "No destination object."
findNext dict =
case findObjFromDict dict "/Next" of
Just (ObjRef x) -> Just x
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> Nothing
findFirst dict =
case findObjFromDict dict "/First" of
Just (ObjRef x) -> Just x
Just s -> error $ "Unknown Object: " ++ show s
Nothing -> Nothing
|
56d20ed939d32b005110fc4bbbea6f8691a1f473cf85661aff253a7567794d36 | gedge-platform/gedge-platform | syslog_monitor.erl | %%%=============================================================================
Copyright 2013 - 2017 , < >
%%%
%%% Permission to use, copy, modify, and/or distribute this software for any
%%% purpose with or without fee is hereby granted, provided that the above
%%% copyright notice and this permission notice appear in all copies.
%%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
%%%
%%% @doc
%%% A server responsible for event handler registrations. The server will attach
%%% and re-attach event handlers at requested event managers monitoring their
%%% registration. This has the nice side-effect that as soon as this server gets
%%% shutdown the registered event handlers will be removed automatically.
%%%
%%% @see syslog_error_h
%%% @end
%%%=============================================================================
-module(syslog_monitor).
-behaviour(gen_server).
%% API
-export([start_link/0]).
%% gen_server callbacks
-export([init/1,
handle_cast/2,
handle_call/3,
handle_info/2,
code_change/3,
terminate/2]).
-define(REGISTRATIONS,
[
%% Manager Handler
{error_logger, syslog_error_h}
]).
-include("syslog.hrl").
%%%=============================================================================
%%% API
%%%=============================================================================
%%------------------------------------------------------------------------------
%% @doc
%% Start a monitor server which in turn will attach the {@link syslog_error_h}
%% event handler at the appropriate event manager (`error_logger').
%% @end
%%------------------------------------------------------------------------------
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() -> gen_server:start_link(?MODULE, [], []).
%%%=============================================================================
%%% gen_server callbacks
%%%=============================================================================
-record(state, {}).
%%------------------------------------------------------------------------------
@private
%%------------------------------------------------------------------------------
init([]) ->
UseErrLogger = syslog_lib:get_property(syslog_error_logger, true),
Regs = [R || R = {M, _} <- ?REGISTRATIONS,
M =/= error_logger orelse UseErrLogger],
ok = lists:foreach(fun add_handler/1, Regs),
{ok, #state{}}.
%%------------------------------------------------------------------------------
@private
%%------------------------------------------------------------------------------
handle_call(_Request, _From, State) -> {reply, undef, State}.
%%------------------------------------------------------------------------------
@private
%%------------------------------------------------------------------------------
handle_cast(_Request, State) -> {noreply, State}.
%%------------------------------------------------------------------------------
@private
%%------------------------------------------------------------------------------
handle_info({gen_event_EXIT, _Handler, shutdown}, State) ->
%% the respective event manager was shutdown properly, we can also RIP
{stop, normal, State};
handle_info({gen_event_EXIT, Handler, Reason}, State) ->
%% accidential unregistration, try to re-subscribe the event handler
ok = ?ERR("~s - handler ~w exited with ~w~n", [?MODULE, Handler, Reason]),
ok = add_handler(lists:keyfind(Handler, 2, ?REGISTRATIONS)),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
%%------------------------------------------------------------------------------
@private
%%------------------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) -> {ok, State}.
%%------------------------------------------------------------------------------
@private
%%------------------------------------------------------------------------------
terminate(_Reason, _State) -> ok.
%%%=============================================================================
%%% internal functions
%%%=============================================================================
%%------------------------------------------------------------------------------
@private
%%------------------------------------------------------------------------------
add_handler({Manager, Handler}) ->
ok = gen_event:add_sup_handler(Manager, Handler, []),
?ERR("~s - added handler ~w to manager ~s~n", [?MODULE, Handler, Manager]).
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/syslog/src/syslog_monitor.erl | erlang | =============================================================================
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
@doc
A server responsible for event handler registrations. The server will attach
and re-attach event handlers at requested event managers monitoring their
registration. This has the nice side-effect that as soon as this server gets
shutdown the registered event handlers will be removed automatically.
@see syslog_error_h
@end
=============================================================================
API
gen_server callbacks
Manager Handler
=============================================================================
API
=============================================================================
------------------------------------------------------------------------------
@doc
Start a monitor server which in turn will attach the {@link syslog_error_h}
event handler at the appropriate event manager (`error_logger').
@end
------------------------------------------------------------------------------
=============================================================================
gen_server callbacks
=============================================================================
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
the respective event manager was shutdown properly, we can also RIP
accidential unregistration, try to re-subscribe the event handler
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
=============================================================================
internal functions
=============================================================================
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | Copyright 2013 - 2017 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(syslog_monitor).
-behaviour(gen_server).
-export([start_link/0]).
-export([init/1,
handle_cast/2,
handle_call/3,
handle_info/2,
code_change/3,
terminate/2]).
-define(REGISTRATIONS,
[
{error_logger, syslog_error_h}
]).
-include("syslog.hrl").
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() -> gen_server:start_link(?MODULE, [], []).
-record(state, {}).
@private
init([]) ->
UseErrLogger = syslog_lib:get_property(syslog_error_logger, true),
Regs = [R || R = {M, _} <- ?REGISTRATIONS,
M =/= error_logger orelse UseErrLogger],
ok = lists:foreach(fun add_handler/1, Regs),
{ok, #state{}}.
@private
handle_call(_Request, _From, State) -> {reply, undef, State}.
@private
handle_cast(_Request, State) -> {noreply, State}.
@private
handle_info({gen_event_EXIT, _Handler, shutdown}, State) ->
{stop, normal, State};
handle_info({gen_event_EXIT, Handler, Reason}, State) ->
ok = ?ERR("~s - handler ~w exited with ~w~n", [?MODULE, Handler, Reason]),
ok = add_handler(lists:keyfind(Handler, 2, ?REGISTRATIONS)),
{noreply, State};
handle_info(_Info, State) ->
{noreply, State}.
@private
code_change(_OldVsn, State, _Extra) -> {ok, State}.
@private
terminate(_Reason, _State) -> ok.
@private
add_handler({Manager, Handler}) ->
ok = gen_event:add_sup_handler(Manager, Handler, []),
?ERR("~s - added handler ~w to manager ~s~n", [?MODULE, Handler, Manager]).
|
a762c40c1a6a351b47aed72aa62463ce040029434c1bd75105741113c6382c99 | wdhowe/clojure-snippets | infinite_seqs.clj | ;; Using infinite sequences.
; repeat - return a lazy infinite seq
(println "Using repeat\n"
(concat (take 3 (repeat "eckee")) ["pakang zoop boing!"]))
; repeatedly - call provided function lazily (as many times as needed)
(println "\nGet random numbers with repeatedly\n"
(take 5 (repeatedly (fn [] (rand-int 100)))))
| null | https://raw.githubusercontent.com/wdhowe/clojure-snippets/0c3247ce99a563312b549d03f080b8cf449b541d/seq_col_funcs/infinite_seqs.clj | clojure | Using infinite sequences.
repeat - return a lazy infinite seq
repeatedly - call provided function lazily (as many times as needed) |
(println "Using repeat\n"
(concat (take 3 (repeat "eckee")) ["pakang zoop boing!"]))
(println "\nGet random numbers with repeatedly\n"
(take 5 (repeatedly (fn [] (rand-int 100)))))
|
02428d1c7f217d9276c7ed0a1e7cf426bf387afa7b1a70390d356f4ad6b98ec7 | nionita/Barbarossa | FileParams.hs | module Eval.FileParams (
makeEvalState,
fileToState
) where
import Data . ( isSpace )
import Data.List (tails, intersperse)
import System.Directory
import Struct.Status(EvalState)
import Struct.Config
import Eval.Eval (initEvalState)
Opens a parameter file for eval , read it and create an eval state
makeEvalState :: Maybe FilePath -> [(String, Double)] -> String -> String -> IO (FilePath, EvalState)
makeEvalState argfile assigns pver psuff = do
-- putStrLn $ "makeEvalState: " ++ show argfile
case argfile of
Just afn -> do -- config file as argument
fex <- doesFileExist afn
if fex then filState afn afn assigns else error $ "makeEvalState: no such file: " ++ afn
Nothing -> go $ configFileNames pver psuff
where defState = return ("", initEvalState assigns)
go [] = defState
go (f:fs) = do
fex <- doesFileExist f
if fex then filState f "" assigns else go fs
filState :: FilePath -> String -> [(String, Double)] -> IO (String, EvalState)
filState fn ident ass = do
est <- fileToState fn ass
return (ident, est)
fileToState :: FilePath -> [(String, Double)] -> IO EvalState
fileToState fn ass = do
fCont <- readFile fn
-- putStrLn $ "This is the file " ++ fn ++ ":" ++ fCont
let ies = initEvalState $ ass ++ fileToParams fCont
-- putStrLn $ "This is state: " ++ show ies
return ies
-- This produces a list of config file names depending on
-- program version and programm version suffix
The most specific will be first , the most general last
configFileNames :: String -> String -> [String]
configFileNames pver psuff = map cfname $ tails [psuff, pver]
where fnprf = "evalParams"
fnsuf = ".txt"
cfname = concat . (++ [fnsuf]) . intersperse "-" . (fnprf :) . reverse
| null | https://raw.githubusercontent.com/nionita/Barbarossa/81032b17ac36dc01771cbcfaaae88c30e7661d7b/Eval/FileParams.hs | haskell | putStrLn $ "makeEvalState: " ++ show argfile
config file as argument
putStrLn $ "This is the file " ++ fn ++ ":" ++ fCont
putStrLn $ "This is state: " ++ show ies
This produces a list of config file names depending on
program version and programm version suffix
| module Eval.FileParams (
makeEvalState,
fileToState
) where
import Data . ( isSpace )
import Data.List (tails, intersperse)
import System.Directory
import Struct.Status(EvalState)
import Struct.Config
import Eval.Eval (initEvalState)
Opens a parameter file for eval , read it and create an eval state
makeEvalState :: Maybe FilePath -> [(String, Double)] -> String -> String -> IO (FilePath, EvalState)
makeEvalState argfile assigns pver psuff = do
case argfile of
fex <- doesFileExist afn
if fex then filState afn afn assigns else error $ "makeEvalState: no such file: " ++ afn
Nothing -> go $ configFileNames pver psuff
where defState = return ("", initEvalState assigns)
go [] = defState
go (f:fs) = do
fex <- doesFileExist f
if fex then filState f "" assigns else go fs
filState :: FilePath -> String -> [(String, Double)] -> IO (String, EvalState)
filState fn ident ass = do
est <- fileToState fn ass
return (ident, est)
fileToState :: FilePath -> [(String, Double)] -> IO EvalState
fileToState fn ass = do
fCont <- readFile fn
let ies = initEvalState $ ass ++ fileToParams fCont
return ies
The most specific will be first , the most general last
configFileNames :: String -> String -> [String]
configFileNames pver psuff = map cfname $ tails [psuff, pver]
where fnprf = "evalParams"
fnsuf = ".txt"
cfname = concat . (++ [fnsuf]) . intersperse "-" . (fnprf :) . reverse
|
9b1517b889c57d229030fdd6bd5604342893e9059910491a4ef9504e724f9b35 | takikawa/racket-ppa | front.rkt | #lang racket/base
(require (prefix-in is: data/integer-set)
racket/list
syntax/stx
"util.rkt"
"stx.rkt"
"re.rkt"
"deriv.rkt")
(provide build-lexer)
(define-syntax time-label
(syntax-rules ()
((_ l e ...)
(begin
(printf "~a: " l)
(time (begin e ...))))))
;; A table is either
;; - (vector-of (union #f nat))
- ( vector - of ( vector - of ( vector ) ) )
(define loc:integer-set-contents is:integer-set-contents)
;; dfa->1d-table : dfa -> (same as build-lexer)
(define (dfa->1d-table dfa)
(let ((state-table (make-vector (dfa-num-states dfa) #f))
(transition-cache (make-hash)))
(for-each
(lambda (trans)
(let* ((from-state (car trans))
(all-chars/to (cdr trans))
(flat-all-chars/to
(sort
(apply append
(map (lambda (chars/to)
(let ((char-ranges (loc:integer-set-contents (car chars/to)))
(to (cdr chars/to)))
(map (lambda (char-range)
(let ((entry (vector (car char-range) (cdr char-range) to)))
(hash-ref transition-cache entry
(lambda ()
(hash-set! transition-cache
entry
entry)
entry))))
char-ranges)))
all-chars/to))
(lambda (a b)
(< (vector-ref a 0) (vector-ref b 0))))))
(vector-set! state-table from-state (list->vector flat-all-chars/to))))
(dfa-transitions dfa))
state-table))
(define loc:foldr is:foldr)
dfa->2d - table : dfa - > ( same as build - lexer )
(define (dfa->2d-table dfa)
(let (
;; char-table : (vector-of (union #f nat))
The lexer table , one entry per state per char .
;; Each entry specifies a state to transition to.
;; #f indicates no transition
(char-table (make-vector (* 256 (dfa-num-states dfa)) #f)))
;; Fill the char-table vector
(for-each
(lambda (trans)
(let ((from-state (car trans)))
(for-each (lambda (chars/to)
(let ((to-state (cdr chars/to)))
(loc:foldr (lambda (char _)
(vector-set! char-table
(bitwise-ior
char
(arithmetic-shift from-state 8))
to-state))
(void)
(car chars/to))))
(cdr trans))))
(dfa-transitions dfa))
char-table))
;; dfa->actions : dfa -> (vector-of (union #f syntax-object))
;; The action for each final state, #f if the state isn't final
(define (dfa->actions dfa)
(let ((actions (make-vector (dfa-num-states dfa) #f)))
(for-each (lambda (state/action)
(vector-set! actions (car state/action) (cdr state/action)))
(dfa-final-states/actions dfa))
actions))
;; dfa->no-look : dfa -> (vector-of bool)
;; For each state whether the lexer can ignore the next input.
;; It can do this only if there are no transitions out of the
;; current state.
(define (dfa->no-look dfa)
(let ((no-look (make-vector (dfa-num-states dfa) #t)))
(for-each (lambda (trans)
(vector-set! no-look (car trans) #f))
(dfa-transitions dfa))
no-look))
(test-block ((d1 (make-dfa 1 1 (list) (list)))
(d2 (make-dfa 4 1 (list (cons 2 2) (cons 3 3))
(list (cons 1 (list (cons (is:make-range 49 50) 1)
(cons (is:make-range 51) 2)))
(cons 2 (list (cons (is:make-range 49) 3))))))
(d3 (make-dfa 4 1 (list (cons 2 2) (cons 3 3))
(list (cons 1 (list (cons (is:make-range 100 200) 0)
(cons (is:make-range 49 50) 1)
(cons (is:make-range 51) 2)))
(cons 2 (list (cons (is:make-range 49) 3)))))))
((dfa->2d-table d1) (make-vector 256 #f))
((dfa->2d-table d2) (let ((v (make-vector 1024 #f)))
(vector-set! v 305 1)
(vector-set! v 306 1)
(vector-set! v 307 2)
(vector-set! v 561 3)
v))
((dfa->1d-table d1) (make-vector 1 #f))
((dfa->1d-table d2) #(#f
#(#(49 50 1) #(51 51 2))
#(#(49 49 3))
#f))
((dfa->1d-table d3) #(#f
#(#(49 50 1) #(51 51 2) #(100 200 0))
#(#(49 49 3))
#f))
((dfa->actions d1) (vector #f))
((dfa->actions d2) (vector #f #f 2 3))
((dfa->no-look d1) (vector #t))
((dfa->no-look d2) (vector #t #f #f #t)))
;; build-lexer : syntax-object list ->
( values table ( vector - of ( union # f syntax - object ) ) ( vector - of bool ) ( list - of syntax - object ) )
;; each syntax object has the form (re action)
(define (build-lexer sos)
(let* ((disappeared-uses (box null))
(s-re-acts (map (lambda (so)
(cons (parse (stx-car so) disappeared-uses)
(stx-car (stx-cdr so))))
sos))
(cache (make-cache))
(re-acts (map (lambda (s-re-act)
(cons (->re (car s-re-act) cache)
(cdr s-re-act)))
s-re-acts))
(dfa (build-dfa re-acts cache))
(table (dfa->1d-table dfa)))
( print - )
#;(let ((num-states (vector-length table))
(num-vectors (length (filter values (vector->list table))))
(num-entries (apply + (map
(lambda (x) (if x (vector-length x) 0))
(vector->list table))))
(num-different-entries
(let ((ht (make-hasheq)))
(for-each
(lambda (x)
(when x
(for-each
(lambda (y)
(hash-set! ht y #t))
(vector->list x))))
(vector->list table))
(length (hash-map ht cons)))))
(printf "~a states, ~aKB\n"
num-states
(/ (* 4.0 (+ 2 num-states (* 2 num-vectors) num-entries
(* 5 num-different-entries))) 1024)))
(values table (dfa-start-state dfa) (dfa->actions dfa) (dfa->no-look dfa)
(unbox disappeared-uses))))
| null | https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/share/pkgs/parser-tools-lib/parser-tools/private-lex/front.rkt | racket | A table is either
- (vector-of (union #f nat))
dfa->1d-table : dfa -> (same as build-lexer)
char-table : (vector-of (union #f nat))
Each entry specifies a state to transition to.
#f indicates no transition
Fill the char-table vector
dfa->actions : dfa -> (vector-of (union #f syntax-object))
The action for each final state, #f if the state isn't final
dfa->no-look : dfa -> (vector-of bool)
For each state whether the lexer can ignore the next input.
It can do this only if there are no transitions out of the
current state.
build-lexer : syntax-object list ->
each syntax object has the form (re action)
(let ((num-states (vector-length table)) | #lang racket/base
(require (prefix-in is: data/integer-set)
racket/list
syntax/stx
"util.rkt"
"stx.rkt"
"re.rkt"
"deriv.rkt")
(provide build-lexer)
(define-syntax time-label
(syntax-rules ()
((_ l e ...)
(begin
(printf "~a: " l)
(time (begin e ...))))))
- ( vector - of ( vector - of ( vector ) ) )
(define loc:integer-set-contents is:integer-set-contents)
(define (dfa->1d-table dfa)
(let ((state-table (make-vector (dfa-num-states dfa) #f))
(transition-cache (make-hash)))
(for-each
(lambda (trans)
(let* ((from-state (car trans))
(all-chars/to (cdr trans))
(flat-all-chars/to
(sort
(apply append
(map (lambda (chars/to)
(let ((char-ranges (loc:integer-set-contents (car chars/to)))
(to (cdr chars/to)))
(map (lambda (char-range)
(let ((entry (vector (car char-range) (cdr char-range) to)))
(hash-ref transition-cache entry
(lambda ()
(hash-set! transition-cache
entry
entry)
entry))))
char-ranges)))
all-chars/to))
(lambda (a b)
(< (vector-ref a 0) (vector-ref b 0))))))
(vector-set! state-table from-state (list->vector flat-all-chars/to))))
(dfa-transitions dfa))
state-table))
(define loc:foldr is:foldr)
dfa->2d - table : dfa - > ( same as build - lexer )
(define (dfa->2d-table dfa)
(let (
The lexer table , one entry per state per char .
(char-table (make-vector (* 256 (dfa-num-states dfa)) #f)))
(for-each
(lambda (trans)
(let ((from-state (car trans)))
(for-each (lambda (chars/to)
(let ((to-state (cdr chars/to)))
(loc:foldr (lambda (char _)
(vector-set! char-table
(bitwise-ior
char
(arithmetic-shift from-state 8))
to-state))
(void)
(car chars/to))))
(cdr trans))))
(dfa-transitions dfa))
char-table))
(define (dfa->actions dfa)
(let ((actions (make-vector (dfa-num-states dfa) #f)))
(for-each (lambda (state/action)
(vector-set! actions (car state/action) (cdr state/action)))
(dfa-final-states/actions dfa))
actions))
(define (dfa->no-look dfa)
(let ((no-look (make-vector (dfa-num-states dfa) #t)))
(for-each (lambda (trans)
(vector-set! no-look (car trans) #f))
(dfa-transitions dfa))
no-look))
(test-block ((d1 (make-dfa 1 1 (list) (list)))
(d2 (make-dfa 4 1 (list (cons 2 2) (cons 3 3))
(list (cons 1 (list (cons (is:make-range 49 50) 1)
(cons (is:make-range 51) 2)))
(cons 2 (list (cons (is:make-range 49) 3))))))
(d3 (make-dfa 4 1 (list (cons 2 2) (cons 3 3))
(list (cons 1 (list (cons (is:make-range 100 200) 0)
(cons (is:make-range 49 50) 1)
(cons (is:make-range 51) 2)))
(cons 2 (list (cons (is:make-range 49) 3)))))))
((dfa->2d-table d1) (make-vector 256 #f))
((dfa->2d-table d2) (let ((v (make-vector 1024 #f)))
(vector-set! v 305 1)
(vector-set! v 306 1)
(vector-set! v 307 2)
(vector-set! v 561 3)
v))
((dfa->1d-table d1) (make-vector 1 #f))
((dfa->1d-table d2) #(#f
#(#(49 50 1) #(51 51 2))
#(#(49 49 3))
#f))
((dfa->1d-table d3) #(#f
#(#(49 50 1) #(51 51 2) #(100 200 0))
#(#(49 49 3))
#f))
((dfa->actions d1) (vector #f))
((dfa->actions d2) (vector #f #f 2 3))
((dfa->no-look d1) (vector #t))
((dfa->no-look d2) (vector #t #f #f #t)))
( values table ( vector - of ( union # f syntax - object ) ) ( vector - of bool ) ( list - of syntax - object ) )
(define (build-lexer sos)
(let* ((disappeared-uses (box null))
(s-re-acts (map (lambda (so)
(cons (parse (stx-car so) disappeared-uses)
(stx-car (stx-cdr so))))
sos))
(cache (make-cache))
(re-acts (map (lambda (s-re-act)
(cons (->re (car s-re-act) cache)
(cdr s-re-act)))
s-re-acts))
(dfa (build-dfa re-acts cache))
(table (dfa->1d-table dfa)))
( print - )
(num-vectors (length (filter values (vector->list table))))
(num-entries (apply + (map
(lambda (x) (if x (vector-length x) 0))
(vector->list table))))
(num-different-entries
(let ((ht (make-hasheq)))
(for-each
(lambda (x)
(when x
(for-each
(lambda (y)
(hash-set! ht y #t))
(vector->list x))))
(vector->list table))
(length (hash-map ht cons)))))
(printf "~a states, ~aKB\n"
num-states
(/ (* 4.0 (+ 2 num-states (* 2 num-vectors) num-entries
(* 5 num-different-entries))) 1024)))
(values table (dfa-start-state dfa) (dfa->actions dfa) (dfa->no-look dfa)
(unbox disappeared-uses))))
|
2fa506fd2c620e78ede470d29b71014c1f6d58d3719775ddaba1e07db30dc82c | qkrgud55/ocamlmulti | io.ml | (* Test a file copy function *)
let test msg funct f1 f2 =
print_string msg; print_newline();
funct f1 f2;
if Sys.command ("cmp " ^ f1 ^ " " ^ f2) = 0
then print_string "passed"
else print_string "FAILED";
print_newline()
(* File copy with constant-sized chunks *)
let copy_file sz infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
let buffer = String.create sz in
let rec copy () =
let n = input ic buffer 0 sz in
if n = 0 then () else begin
output oc buffer 0 n;
copy ()
end in
copy();
close_in ic;
close_out oc
(* File copy with random-sized chunks *)
let copy_random sz infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
let buffer = String.create sz in
let rec copy () =
let s = 1 + Random.int sz in
let n = input ic buffer 0 s in
if n = 0 then () else begin
output oc buffer 0 n;
copy ()
end in
copy();
close_in ic;
close_out oc
(* File copy line per line *)
let copy_line infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
try
while true do
output_string oc (input_line ic); output_char oc '\n'
done
with End_of_file ->
close_in ic;
close_out oc
(* Backward copy, with lots of seeks *)
let copy_seek chunksize infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
let size = in_channel_length ic in
let buffer = String.create chunksize in
for i = (size - 1) / chunksize downto 0 do
seek_in ic (i * chunksize);
seek_out oc (i * chunksize);
let n = input ic buffer 0 chunksize in
output oc buffer 0 n
done;
close_in ic;
close_out oc
(* Create long lines of text *)
let make_lines ofile =
let oc = open_out_bin ofile in
for i = 1 to 256 do
output_string oc (String.make (i*64) '.'); output_char oc '\n'
done;
close_out oc
(* The test *)
let _ =
let src = Sys.argv.(1) in
let testio = Filename.temp_file "testio" "" in
let lines = Filename.temp_file "lines" "" in
test "16-byte chunks" (copy_file 16) src testio;
test "256-byte chunks" (copy_file 256) src testio;
test "4096-byte chunks" (copy_file 4096) src testio;
test "65536-byte chunks" (copy_file 65536) src testio;
test "19-byte chunks" (copy_file 19) src testio;
test "263-byte chunks" (copy_file 263) src testio;
test "4011-byte chunks" (copy_file 4011) src testio;
test "0...8192 byte chunks" (copy_random 8192) src testio;
test "line per line, short lines" copy_line "/etc/hosts" testio;
make_lines lines;
test "line per line, short and long lines" copy_line lines testio;
test "backwards, 4096-byte chunks" (copy_seek 4096) src testio;
test "backwards, 64-byte chunks" (copy_seek 64) src testio;
Sys.remove lines;
Sys.remove testio;
exit 0
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/testsuite/tests/basic-io-2/io.ml | ocaml | Test a file copy function
File copy with constant-sized chunks
File copy with random-sized chunks
File copy line per line
Backward copy, with lots of seeks
Create long lines of text
The test |
let test msg funct f1 f2 =
print_string msg; print_newline();
funct f1 f2;
if Sys.command ("cmp " ^ f1 ^ " " ^ f2) = 0
then print_string "passed"
else print_string "FAILED";
print_newline()
let copy_file sz infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
let buffer = String.create sz in
let rec copy () =
let n = input ic buffer 0 sz in
if n = 0 then () else begin
output oc buffer 0 n;
copy ()
end in
copy();
close_in ic;
close_out oc
let copy_random sz infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
let buffer = String.create sz in
let rec copy () =
let s = 1 + Random.int sz in
let n = input ic buffer 0 s in
if n = 0 then () else begin
output oc buffer 0 n;
copy ()
end in
copy();
close_in ic;
close_out oc
let copy_line infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
try
while true do
output_string oc (input_line ic); output_char oc '\n'
done
with End_of_file ->
close_in ic;
close_out oc
let copy_seek chunksize infile ofile =
let ic = open_in_bin infile in
let oc = open_out_bin ofile in
let size = in_channel_length ic in
let buffer = String.create chunksize in
for i = (size - 1) / chunksize downto 0 do
seek_in ic (i * chunksize);
seek_out oc (i * chunksize);
let n = input ic buffer 0 chunksize in
output oc buffer 0 n
done;
close_in ic;
close_out oc
let make_lines ofile =
let oc = open_out_bin ofile in
for i = 1 to 256 do
output_string oc (String.make (i*64) '.'); output_char oc '\n'
done;
close_out oc
let _ =
let src = Sys.argv.(1) in
let testio = Filename.temp_file "testio" "" in
let lines = Filename.temp_file "lines" "" in
test "16-byte chunks" (copy_file 16) src testio;
test "256-byte chunks" (copy_file 256) src testio;
test "4096-byte chunks" (copy_file 4096) src testio;
test "65536-byte chunks" (copy_file 65536) src testio;
test "19-byte chunks" (copy_file 19) src testio;
test "263-byte chunks" (copy_file 263) src testio;
test "4011-byte chunks" (copy_file 4011) src testio;
test "0...8192 byte chunks" (copy_random 8192) src testio;
test "line per line, short lines" copy_line "/etc/hosts" testio;
make_lines lines;
test "line per line, short and long lines" copy_line lines testio;
test "backwards, 4096-byte chunks" (copy_seek 4096) src testio;
test "backwards, 64-byte chunks" (copy_seek 64) src testio;
Sys.remove lines;
Sys.remove testio;
exit 0
|
bcb698568885ae01ccdcd1e13de1c985487602f05405b344863a40f0793ba723 | cndreisbach/clojure-web-dev-workshop | views.clj | (ns we-owe.views
(:require [clojure.pprint :refer [pprint]]
[we-owe.debts :refer [simplify balances]]))
(defn- pstr [obj]
(with-out-str (pprint obj)))
(defn index-page [db]
(let [debts (:debts @db)]
(str "Balances:\n"
(pstr (balances debts))
"\n\nAll debts: \n"
(pstr (simplify debts)))))
(defn person-page [db person]
(let [debts (simplify (:debts @db))
owed (->> debts
(filter (fn [[[_ owed] amount]]
(= owed person)))
(map (fn [[[owes _] amount]] (vector owes amount))))
owes (->> debts
(filter (fn [[[owes _] amount]]
(= owes person)))
(map (fn [[[_ owed] amount]] (vector owed amount))))]
(str "You owe:\n" (pstr owes)
"\n\nYou are owed:\n" (pstr owed))))
| null | https://raw.githubusercontent.com/cndreisbach/clojure-web-dev-workshop/95d9fdf94b39f8a1e408b8bf75a81b92899ee7d9/code/02-compojure/src/we_owe/views.clj | clojure | (ns we-owe.views
(:require [clojure.pprint :refer [pprint]]
[we-owe.debts :refer [simplify balances]]))
(defn- pstr [obj]
(with-out-str (pprint obj)))
(defn index-page [db]
(let [debts (:debts @db)]
(str "Balances:\n"
(pstr (balances debts))
"\n\nAll debts: \n"
(pstr (simplify debts)))))
(defn person-page [db person]
(let [debts (simplify (:debts @db))
owed (->> debts
(filter (fn [[[_ owed] amount]]
(= owed person)))
(map (fn [[[owes _] amount]] (vector owes amount))))
owes (->> debts
(filter (fn [[[owes _] amount]]
(= owes person)))
(map (fn [[[_ owed] amount]] (vector owed amount))))]
(str "You owe:\n" (pstr owes)
"\n\nYou are owed:\n" (pstr owed))))
|
|
8cf601b29e297c87709f3b5cd162f3791592d98f8857d405c270e8ed28cc623a | ServiceNow/picard | Pets1.hs | {-# LANGUAGE OverloadedStrings #-}
module Language.SQL.SpiderSQL.Pets1 where
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import Language.SQL.SpiderSQL.TestItem (TestItem (..))
import Picard.Types (ColumnType (..), SQLSchema (..))
pets1Schema :: SQLSchema
pets1Schema =
let columnNames = HashMap.fromList [("1", "StuID"), ("10", "PetID"), ("11", "PetID"), ("12", "PetType"), ("13", "pet_age"), ("14", "weight"), ("2", "LName"), ("3", "Fname"), ("4", "Age"), ("5", "Sex"), ("6", "Major"), ("7", "Advisor"), ("8", "city_code"), ("9", "StuID")]
columnTypes = HashMap.fromList [("1", ColumnType_NUMBER), ("10", ColumnType_NUMBER), ("11", ColumnType_NUMBER), ("12", ColumnType_TEXT), ("13", ColumnType_NUMBER), ("14", ColumnType_NUMBER), ("2", ColumnType_TEXT), ("3", ColumnType_TEXT), ("4", ColumnType_NUMBER), ("5", ColumnType_TEXT), ("6", ColumnType_NUMBER), ("7", ColumnType_NUMBER), ("8", ColumnType_TEXT), ("9", ColumnType_NUMBER)]
tableNames = HashMap.fromList [("0", "Student"), ("1", "Has_Pet"), ("2", "Pets")]
columnToTable = HashMap.fromList [("1", "0"), ("10", "1"), ("11", "2"), ("12", "2"), ("13", "2"), ("14", "2"), ("2", "0"), ("3", "0"), ("4", "0"), ("5", "0"), ("6", "0"), ("7", "0"), ("8", "0"), ("9", "1")]
tableToColumns = HashMap.fromList [("0", ["1", "2", "3", "4", "5", "6", "7", "8"]), ("1", ["9", "10"]), ("2", ["11", "12", "13", "14"])]
foreignKeys = HashMap.fromList [("10", "11"), ("9", "1")]
primaryKeys = ["1", "11"]
in SQLSchema {sQLSchema_columnNames = columnNames, sQLSchema_columnTypes = columnTypes, sQLSchema_tableNames = tableNames, sQLSchema_columnToTable = columnToTable, sQLSchema_tableToColumns = tableToColumns, sQLSchema_foreignKeys = foreignKeys, sQLSchema_primaryKeys = primaryKeys}
pets1Queries :: [Text.Text]
pets1Queries =
[ "SELECT count(*) FROM pets WHERE weight > 10",
"SELECT weight FROM pets ORDER BY pet_age LIMIT 1",
"SELECT max(weight) , petType FROM pets GROUP BY petType",
"SELECT count(*) FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid WHERE T1.age > 20",
"SELECT count(*) FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T2.petid = T3.petid WHERE T1.sex = 'F' AND T3.pettype = 'dog'",
"SELECT count(DISTINCT pettype) FROM pets",
"SELECT DISTINCT T1.Fname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat' OR T3.pettype = 'dog'",
"select t1.fname from student as t1 join has_pet as t2 on t1.stuid = t2.stuid join pets as t3 on t3.petid = t2.petid where t3.pettype = 'cat' intersect select t1.fname from student as t1 join has_pet as t2 on t1.stuid = t2.stuid join pets as t3 on t3.petid = t2.petid where t3.pettype = 'dog'",
"SELECT T1.Fname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat' INTERSECT SELECT T1.Fname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'dog'",
"SELECT major , age FROM student WHERE stuid NOT IN (SELECT T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat')",
"SELECT stuid FROM student EXCEPT SELECT T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat'",
"SELECT T1.fname , T1.age FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'dog' AND T1.stuid NOT IN (SELECT T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat')",
"SELECT pettype , weight FROM pets ORDER BY pet_age LIMIT 1",
"SELECT petid , weight FROM pets WHERE pet_age > 1",
"SELECT avg(pet_age) , max(pet_age) , pettype FROM pets GROUP BY pettype",
"SELECT avg(weight) , pettype FROM pets GROUP BY pettype",
"SELECT DISTINCT T1.fname , T1.age FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid",
"SELECT T2.petid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid WHERE T1.Lname = 'Smith'",
"SELECT count(*) , T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid GROUP BY T1.stuid",
"select count(*) , t1.stuid from student as t1 join has_pet as t2 on t1.stuid = t2.stuid group by t1.stuid",
"SELECT T1.fname , T1.sex FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid GROUP BY T1.stuid HAVING count(*) > 1",
"SELECT T1.lname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pet_age = 3 AND T3.pettype = 'cat'",
"select avg(age) from student where stuid not in (select stuid from has_pet)"
]
pets1ParserTests :: TestItem
pets1ParserTests =
Group "pets_1" $
(ParseQueryExprWithGuardsAndTypeChecking pets1Schema <$> pets1Queries)
<> (ParseQueryExprWithGuards pets1Schema <$> pets1Queries)
<> (ParseQueryExprWithoutGuards pets1Schema <$> pets1Queries)
<> (ParseQueryExprFails pets1Schema <$> [])
pets1LexerTests :: TestItem
pets1LexerTests =
Group "pets_1" $ LexQueryExpr pets1Schema <$> pets1Queries
| null | https://raw.githubusercontent.com/ServiceNow/picard/6a252386bed6d4233f0f13f4562d8ae8608e7445/picard/tests/Language/SQL/SpiderSQL/Pets1.hs | haskell | # LANGUAGE OverloadedStrings # |
module Language.SQL.SpiderSQL.Pets1 where
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import Language.SQL.SpiderSQL.TestItem (TestItem (..))
import Picard.Types (ColumnType (..), SQLSchema (..))
pets1Schema :: SQLSchema
pets1Schema =
let columnNames = HashMap.fromList [("1", "StuID"), ("10", "PetID"), ("11", "PetID"), ("12", "PetType"), ("13", "pet_age"), ("14", "weight"), ("2", "LName"), ("3", "Fname"), ("4", "Age"), ("5", "Sex"), ("6", "Major"), ("7", "Advisor"), ("8", "city_code"), ("9", "StuID")]
columnTypes = HashMap.fromList [("1", ColumnType_NUMBER), ("10", ColumnType_NUMBER), ("11", ColumnType_NUMBER), ("12", ColumnType_TEXT), ("13", ColumnType_NUMBER), ("14", ColumnType_NUMBER), ("2", ColumnType_TEXT), ("3", ColumnType_TEXT), ("4", ColumnType_NUMBER), ("5", ColumnType_TEXT), ("6", ColumnType_NUMBER), ("7", ColumnType_NUMBER), ("8", ColumnType_TEXT), ("9", ColumnType_NUMBER)]
tableNames = HashMap.fromList [("0", "Student"), ("1", "Has_Pet"), ("2", "Pets")]
columnToTable = HashMap.fromList [("1", "0"), ("10", "1"), ("11", "2"), ("12", "2"), ("13", "2"), ("14", "2"), ("2", "0"), ("3", "0"), ("4", "0"), ("5", "0"), ("6", "0"), ("7", "0"), ("8", "0"), ("9", "1")]
tableToColumns = HashMap.fromList [("0", ["1", "2", "3", "4", "5", "6", "7", "8"]), ("1", ["9", "10"]), ("2", ["11", "12", "13", "14"])]
foreignKeys = HashMap.fromList [("10", "11"), ("9", "1")]
primaryKeys = ["1", "11"]
in SQLSchema {sQLSchema_columnNames = columnNames, sQLSchema_columnTypes = columnTypes, sQLSchema_tableNames = tableNames, sQLSchema_columnToTable = columnToTable, sQLSchema_tableToColumns = tableToColumns, sQLSchema_foreignKeys = foreignKeys, sQLSchema_primaryKeys = primaryKeys}
pets1Queries :: [Text.Text]
pets1Queries =
[ "SELECT count(*) FROM pets WHERE weight > 10",
"SELECT weight FROM pets ORDER BY pet_age LIMIT 1",
"SELECT max(weight) , petType FROM pets GROUP BY petType",
"SELECT count(*) FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid WHERE T1.age > 20",
"SELECT count(*) FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T2.petid = T3.petid WHERE T1.sex = 'F' AND T3.pettype = 'dog'",
"SELECT count(DISTINCT pettype) FROM pets",
"SELECT DISTINCT T1.Fname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat' OR T3.pettype = 'dog'",
"select t1.fname from student as t1 join has_pet as t2 on t1.stuid = t2.stuid join pets as t3 on t3.petid = t2.petid where t3.pettype = 'cat' intersect select t1.fname from student as t1 join has_pet as t2 on t1.stuid = t2.stuid join pets as t3 on t3.petid = t2.petid where t3.pettype = 'dog'",
"SELECT T1.Fname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat' INTERSECT SELECT T1.Fname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'dog'",
"SELECT major , age FROM student WHERE stuid NOT IN (SELECT T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat')",
"SELECT stuid FROM student EXCEPT SELECT T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat'",
"SELECT T1.fname , T1.age FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'dog' AND T1.stuid NOT IN (SELECT T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pettype = 'cat')",
"SELECT pettype , weight FROM pets ORDER BY pet_age LIMIT 1",
"SELECT petid , weight FROM pets WHERE pet_age > 1",
"SELECT avg(pet_age) , max(pet_age) , pettype FROM pets GROUP BY pettype",
"SELECT avg(weight) , pettype FROM pets GROUP BY pettype",
"SELECT DISTINCT T1.fname , T1.age FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid",
"SELECT T2.petid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid WHERE T1.Lname = 'Smith'",
"SELECT count(*) , T1.stuid FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid GROUP BY T1.stuid",
"select count(*) , t1.stuid from student as t1 join has_pet as t2 on t1.stuid = t2.stuid group by t1.stuid",
"SELECT T1.fname , T1.sex FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid GROUP BY T1.stuid HAVING count(*) > 1",
"SELECT T1.lname FROM student AS T1 JOIN has_pet AS T2 ON T1.stuid = T2.stuid JOIN pets AS T3 ON T3.petid = T2.petid WHERE T3.pet_age = 3 AND T3.pettype = 'cat'",
"select avg(age) from student where stuid not in (select stuid from has_pet)"
]
pets1ParserTests :: TestItem
pets1ParserTests =
Group "pets_1" $
(ParseQueryExprWithGuardsAndTypeChecking pets1Schema <$> pets1Queries)
<> (ParseQueryExprWithGuards pets1Schema <$> pets1Queries)
<> (ParseQueryExprWithoutGuards pets1Schema <$> pets1Queries)
<> (ParseQueryExprFails pets1Schema <$> [])
pets1LexerTests :: TestItem
pets1LexerTests =
Group "pets_1" $ LexQueryExpr pets1Schema <$> pets1Queries
|
9a60d0f09d2638c94b3b9df0a2644c3e971399535b993f9f5c355c490eb0025d | andrejbauer/kmeans | algorithms.ml | open Distances
let rec select key k lst = match lst with
| [] -> []
| x :: xs -> let ys, zs = List.partition (key x) xs in
let l = List.length ys in
if k < l then
select key k ys
else if k > l then
(x::ys) @ (select key (k-l-1) zs)
else
ys
let kneighs dista distc k mean tset sample =
let pomo x = (min (1./.(calculate dista sample (fst x))) 999999., x) in
let mapped = List.map pomo tset in
let key x y = (fst x) < (fst y) in
let neighs = select key k mapped in
mean dista distc neighs sample
let medoid da dc set sample =
let f x = (snd (snd x), fst x) in
let temp = List.map f set in
let rec count (a,b) xs = match xs with
| [] -> (a,b,[])
| (c,d) :: sez ->
let (x,y,z) = count (a,b) sez in
if a = c
then (a,y+.b+.d,z)
else (a,y+.b,(c,d)::z)
in
let rec combine lst = match lst with
| [] -> []
| l::ls -> let (a,b,c) = count l ls in (a,b) :: (combine c)
in
let temp2 = combine temp in
let pomo (a,b) (c,d) = if b > d then (a,b) else (c,d) in
fst (List.fold_left pomo ((Set []),0.) temp2)
let mean da dc set sample =
let sum = ref 0. in
let f s x =
let w = fst x in match snd (snd x) with
| Numerical a -> sum := !sum +. w; s +. w *. a
| _ -> raise (Failure "Not a number in mean")
in
let total = List.fold_left f 0. set in
Numerical (total /. !sum)
let randomize stratify data =
let randomized = List.sort (fun x y -> 1 - Random.int 3) data in
if stratify
then List.sort (fun x y -> compare (snd x) (snd y)) randomized
else randomized
let generate_sets data folds fold =
let filter i x =
i := !i + 1;
!i mod folds = (fold -1)
in
List.partition (filter (ref (-1))) data
let update_schema s tset =
let rec bounds d1 d2 = match d1,d2 with
| Discrete a , Discrete b - > Discrete a
| ( Numerical a ) , Numerical b - > Numerical ( a+.b )
| Missing , x - > x
| x , Missing - > x
| Tuple lst1 , Tuple lst2 - > Tuple ( List.map2 add_data lst1 lst2 )
| Set lst1 , Set lst2 - >
let rec bounds d1 d2 = match d1,d2 with
| Discrete a, Discrete b -> Discrete a
| (Numerical a), Numerical b -> Numerical (a+.b)
| Missing, x -> x
| x, Missing -> x
| Tuple lst1, Tuple lst2 -> Tuple (List.map2 add_data lst1 lst2)
| Set lst1, Set lst2 -> *)
let evaluate folds cshema da dc k podatki = match cshema with
| N _ -> begin
let unpack dat = match dat with
| Numerical a -> a
| _ -> raise (Failure "Not a number in unpack.")
in
let coef = ref (float_of_int folds) in
let randomized = randomize false podatki in
(for j = 1 to folds do
let (test,train) = generate_sets randomized folds j in
let knn x = kneighs da dc k mean train (fst x) in
let rezultati = List.map (fun x -> unpack (knn x)) test in
let resitve = List.map (fun x -> unpack (snd x)) test in
let nn = float_of_int (List.length test) in
let avg = (List.fold_left (+.) 0. resitve) /. nn in
let s_tot = List.fold_left (fun s y -> s +. (avg -. y)**2.) 0. resitve in
let s_res = List.fold_left2 (fun s y x -> s +. (x -. y)**2.) 0. resitve rezultati in
coef := !coef -. (s_res/.s_tot)
done);
!coef /. (float_of_int folds)
end
| _ -> begin
let accuracy = ref 0. in
let randomized = randomize true podatki in
(for j = 1 to folds do
let (test,train) = generate_sets randomized folds j in
let knn x = kneighs da dc k medoid train (fst x) in
let rezultati = List.map knn test in
let resitve = List.map snd test in
let count a b c = if a=b then c+.1. else c in
let hits = List.fold_right2 count resitve rezultati 0. in
let acc = hits/.(float_of_int (List.length test)) in
accuracy := !accuracy +. acc
done);
!accuracy /. (float_of_int folds)
end | null | https://raw.githubusercontent.com/andrejbauer/kmeans/9d4de9b6261b4e18ee486e36badbb8cc8ea3b224/alpha2/algorithms.ml | ocaml | open Distances
let rec select key k lst = match lst with
| [] -> []
| x :: xs -> let ys, zs = List.partition (key x) xs in
let l = List.length ys in
if k < l then
select key k ys
else if k > l then
(x::ys) @ (select key (k-l-1) zs)
else
ys
let kneighs dista distc k mean tset sample =
let pomo x = (min (1./.(calculate dista sample (fst x))) 999999., x) in
let mapped = List.map pomo tset in
let key x y = (fst x) < (fst y) in
let neighs = select key k mapped in
mean dista distc neighs sample
let medoid da dc set sample =
let f x = (snd (snd x), fst x) in
let temp = List.map f set in
let rec count (a,b) xs = match xs with
| [] -> (a,b,[])
| (c,d) :: sez ->
let (x,y,z) = count (a,b) sez in
if a = c
then (a,y+.b+.d,z)
else (a,y+.b,(c,d)::z)
in
let rec combine lst = match lst with
| [] -> []
| l::ls -> let (a,b,c) = count l ls in (a,b) :: (combine c)
in
let temp2 = combine temp in
let pomo (a,b) (c,d) = if b > d then (a,b) else (c,d) in
fst (List.fold_left pomo ((Set []),0.) temp2)
let mean da dc set sample =
let sum = ref 0. in
let f s x =
let w = fst x in match snd (snd x) with
| Numerical a -> sum := !sum +. w; s +. w *. a
| _ -> raise (Failure "Not a number in mean")
in
let total = List.fold_left f 0. set in
Numerical (total /. !sum)
let randomize stratify data =
let randomized = List.sort (fun x y -> 1 - Random.int 3) data in
if stratify
then List.sort (fun x y -> compare (snd x) (snd y)) randomized
else randomized
let generate_sets data folds fold =
let filter i x =
i := !i + 1;
!i mod folds = (fold -1)
in
List.partition (filter (ref (-1))) data
let update_schema s tset =
let rec bounds d1 d2 = match d1,d2 with
| Discrete a , Discrete b - > Discrete a
| ( Numerical a ) , Numerical b - > Numerical ( a+.b )
| Missing , x - > x
| x , Missing - > x
| Tuple lst1 , Tuple lst2 - > Tuple ( List.map2 add_data lst1 lst2 )
| Set lst1 , Set lst2 - >
let rec bounds d1 d2 = match d1,d2 with
| Discrete a, Discrete b -> Discrete a
| (Numerical a), Numerical b -> Numerical (a+.b)
| Missing, x -> x
| x, Missing -> x
| Tuple lst1, Tuple lst2 -> Tuple (List.map2 add_data lst1 lst2)
| Set lst1, Set lst2 -> *)
let evaluate folds cshema da dc k podatki = match cshema with
| N _ -> begin
let unpack dat = match dat with
| Numerical a -> a
| _ -> raise (Failure "Not a number in unpack.")
in
let coef = ref (float_of_int folds) in
let randomized = randomize false podatki in
(for j = 1 to folds do
let (test,train) = generate_sets randomized folds j in
let knn x = kneighs da dc k mean train (fst x) in
let rezultati = List.map (fun x -> unpack (knn x)) test in
let resitve = List.map (fun x -> unpack (snd x)) test in
let nn = float_of_int (List.length test) in
let avg = (List.fold_left (+.) 0. resitve) /. nn in
let s_tot = List.fold_left (fun s y -> s +. (avg -. y)**2.) 0. resitve in
let s_res = List.fold_left2 (fun s y x -> s +. (x -. y)**2.) 0. resitve rezultati in
coef := !coef -. (s_res/.s_tot)
done);
!coef /. (float_of_int folds)
end
| _ -> begin
let accuracy = ref 0. in
let randomized = randomize true podatki in
(for j = 1 to folds do
let (test,train) = generate_sets randomized folds j in
let knn x = kneighs da dc k medoid train (fst x) in
let rezultati = List.map knn test in
let resitve = List.map snd test in
let count a b c = if a=b then c+.1. else c in
let hits = List.fold_right2 count resitve rezultati 0. in
let acc = hits/.(float_of_int (List.length test)) in
accuracy := !accuracy +. acc
done);
!accuracy /. (float_of_int folds)
end |
|
53dc3114a2e6904185bab3fb141a5a0be9b38557bca42f68496cad14cc2b79ef | Octachron/codept | a.ml | type t = Space
| null | https://raw.githubusercontent.com/Octachron/codept/2d2a95fde3f67cdd0f5a1b68d8b8b47aefef9290/tests/complex/alias_values/a.ml | ocaml | type t = Space
|
|
85eb0e3f3fd953aeef862e0e6d4fba9be7acb2a56598a560aceeb4cca04cc75e | fourmolu/fourmolu | default-signatures-simple-four-out.hs | module Main where
-- | Something.
class Foo a where
-- | Foo
foo :: a -> String
default foo :: (Show a) => a -> String
foo = show
| null | https://raw.githubusercontent.com/fourmolu/fourmolu/f47860f01cb3cac3b973c5df6ecbae48bbb4c295/data/examples/declaration/class/default-signatures-simple-four-out.hs | haskell | | Something.
| Foo | module Main where
class Foo a where
foo :: a -> String
default foo :: (Show a) => a -> String
foo = show
|
b057de9128b049cfb5c2467b88135bbb81eb5ee431e58bfa7067949d3fb2177c | nnichols/nature | core.cljc | (ns nature.core
(:require [nature.initialization-operators :as io]
[nature.population-operators :as po]
[nature.monitors :as monitors]))
(defn evolve
"Create and evolve a population under the specified conditions until a termination criteria is reached
`allele-set` is a collection of legal genome values
`genome-length` is the enforced size of each genetic sequence
`population-size` is the enforced number of individuals that will be created
`generations` is the number of iterations the algorithm will cycle through
`fitness-function` is a partial function accepting generated sequences to evaluate solution qualities
`binary-operators` is a collection of partial functions accepting and returning 1 or more individuals
`unary-operators` is a collection of partial functions accepting and returning exactly 1 individual
`options` an optional map of pre-specified keywords to values that further tune the behavior of nature.
Current examples follow:
`:carry-over` an integer representing the top n individuals to be carried over between each generation. Default is 1
`:solutions` an integer representing the top n individuals to return after evolution completes. Default is 1
`:monitors` a sequence of functions, assumed to be side-effectful, to be executed against `population` and `current-genration` for run-time stats. Default is nil"
([allele-set genome-length population-size generations fitness-function binary-operators unary-operators]
(evolve allele-set genome-length population-size generations fitness-function binary-operators unary-operators {:solutions 1, :carry-over 1}))
TODO - Curry the genetic operators one more level , so the fitness - function can be pressed in
{:pre [(and (every? coll? [allele-set binary-operators unary-operators])
(every? int? [genome-length population-size generations])
(fn? fitness-function))]}
(let [solutions (max 1 (:solutions options))
carry-over (max 1 (:carry-over options))
monitors (:monitors options)]
(loop [population (io/build-population population-size allele-set genome-length fitness-function)
current-generation 0]
(when monitors (monitors/apply-monitors monitors population current-generation))
(if (>= current-generation generations)
(take solutions (sort-by :fitness-score #(> %1 %2) population))
(recur (po/advance-generation population population-size binary-operators unary-operators {:carry-over carry-over}) (inc current-generation)))))))
| null | https://raw.githubusercontent.com/nnichols/nature/6cc1e9f0627b330245602773313b8c60630d3330/src/nature/core.cljc | clojure | (ns nature.core
(:require [nature.initialization-operators :as io]
[nature.population-operators :as po]
[nature.monitors :as monitors]))
(defn evolve
"Create and evolve a population under the specified conditions until a termination criteria is reached
`allele-set` is a collection of legal genome values
`genome-length` is the enforced size of each genetic sequence
`population-size` is the enforced number of individuals that will be created
`generations` is the number of iterations the algorithm will cycle through
`fitness-function` is a partial function accepting generated sequences to evaluate solution qualities
`binary-operators` is a collection of partial functions accepting and returning 1 or more individuals
`unary-operators` is a collection of partial functions accepting and returning exactly 1 individual
`options` an optional map of pre-specified keywords to values that further tune the behavior of nature.
Current examples follow:
`:carry-over` an integer representing the top n individuals to be carried over between each generation. Default is 1
`:solutions` an integer representing the top n individuals to return after evolution completes. Default is 1
`:monitors` a sequence of functions, assumed to be side-effectful, to be executed against `population` and `current-genration` for run-time stats. Default is nil"
([allele-set genome-length population-size generations fitness-function binary-operators unary-operators]
(evolve allele-set genome-length population-size generations fitness-function binary-operators unary-operators {:solutions 1, :carry-over 1}))
TODO - Curry the genetic operators one more level , so the fitness - function can be pressed in
{:pre [(and (every? coll? [allele-set binary-operators unary-operators])
(every? int? [genome-length population-size generations])
(fn? fitness-function))]}
(let [solutions (max 1 (:solutions options))
carry-over (max 1 (:carry-over options))
monitors (:monitors options)]
(loop [population (io/build-population population-size allele-set genome-length fitness-function)
current-generation 0]
(when monitors (monitors/apply-monitors monitors population current-generation))
(if (>= current-generation generations)
(take solutions (sort-by :fitness-score #(> %1 %2) population))
(recur (po/advance-generation population population-size binary-operators unary-operators {:carry-over carry-over}) (inc current-generation)))))))
|
|
2af135e1aee8e5df4f1d1190d63d14ca23013d356e1988075681977e10aedfb3 | smeruelo/mooc-ocaml | w5_6.1_mutable_lists.ml | type 'a xlist =
{ mutable pointer : 'a cell }
and 'a cell =
| Nil
| List of 'a * 'a xlist ;;
let nil () =
{ pointer = Nil } ;;
let cons elt rest =
{ pointer = List (elt, rest) } ;;
exception Empty_xlist ;;
let head l =
match l.pointer with
| Nil -> raise Empty_xlist
| List (hd, tl) -> hd
let tail l =
match l.pointer with
| Nil -> raise Empty_xlist
| List (hd, tl) -> tl
let add a l =
l.pointer <- List (a, { pointer = l.pointer })
(* Using the provided functions *)
let add a l =
match l.pointer with
| Nil -> l.pointer <- List (a, nil ())
| List (hd, tl) -> l.pointer <- List (a, cons hd tl)
let chop l =
match l.pointer with
| Nil -> raise Empty_xlist
| List (hd, tl) -> l.pointer <- tl.pointer
let rec append l1 l2 =
match l1.pointer with
| Nil -> l1.pointer <- l2.pointer
| List (hd, tl) -> append tl l2
let rec filter p l =
match l.pointer with
| Nil -> ()
| List (hd, tl) when p hd -> filter p tl
| List (hd, tl) -> l.pointer <- tl.pointer; filter p l
let xl = { pointer = List ( 1 , { pointer = List ( 2 , { pointer = List ( 3 , { pointer = Nil } ) } ) } ) }
let even a = a mod 2 = = 0
let xl = { pointer = List (1, { pointer = List (2, { pointer = List (3, { pointer = Nil }) }) }) }
let even a = a mod 2 == 0
*)
| null | https://raw.githubusercontent.com/smeruelo/mooc-ocaml/8e2efb1632ec9dd381489a08465d5341a6c727c9/week5/w5_6.1_mutable_lists.ml | ocaml | Using the provided functions | type 'a xlist =
{ mutable pointer : 'a cell }
and 'a cell =
| Nil
| List of 'a * 'a xlist ;;
let nil () =
{ pointer = Nil } ;;
let cons elt rest =
{ pointer = List (elt, rest) } ;;
exception Empty_xlist ;;
let head l =
match l.pointer with
| Nil -> raise Empty_xlist
| List (hd, tl) -> hd
let tail l =
match l.pointer with
| Nil -> raise Empty_xlist
| List (hd, tl) -> tl
let add a l =
l.pointer <- List (a, { pointer = l.pointer })
let add a l =
match l.pointer with
| Nil -> l.pointer <- List (a, nil ())
| List (hd, tl) -> l.pointer <- List (a, cons hd tl)
let chop l =
match l.pointer with
| Nil -> raise Empty_xlist
| List (hd, tl) -> l.pointer <- tl.pointer
let rec append l1 l2 =
match l1.pointer with
| Nil -> l1.pointer <- l2.pointer
| List (hd, tl) -> append tl l2
let rec filter p l =
match l.pointer with
| Nil -> ()
| List (hd, tl) when p hd -> filter p tl
| List (hd, tl) -> l.pointer <- tl.pointer; filter p l
let xl = { pointer = List ( 1 , { pointer = List ( 2 , { pointer = List ( 3 , { pointer = Nil } ) } ) } ) }
let even a = a mod 2 = = 0
let xl = { pointer = List (1, { pointer = List (2, { pointer = List (3, { pointer = Nil }) }) }) }
let even a = a mod 2 == 0
*)
|
99c77f1d679405d4de567c31b53a9de95b2a7facd073ed247606bd7f8c9b9f4e | csabahruska/jhc-components | Numeric.hs | module Numeric(fromRat,
showSigned, showIntAtBase,
showInt, showOct, showHex,
readSigned, readInt,
readDec, readOct, readHex,
floatToDigits,
showEFloat, showFFloat, showGFloat, showFloat,
readFloat, lexDigits) where
import Data.Ratio ( (%), numerator, denominator )
import Jhc.Basics
import Jhc.Enum
import Jhc.Float
import Jhc.IO
import Jhc.List
import Jhc.Num
import Jhc.Numeric
import Jhc.Order
import Jhc.Text.Read
import Prelude.CType(isDigit,isOctDigit,isHexDigit,digitToInt,intToDigit)
import Prelude.Text
import Jhc.Class.Real
-- This converts a rational to a floating. This should be used in the
-- Fractional instances of Float and Double.
fromRat :: (RealFloat a) => Rational -> a
fromRat = error "fromRat not implemented yet"
fromRat : : ( RealFloat a ) = > Rational - > a
fromRat x =
if x = = 0 then encodeFloat 0 0 -- Handle exceptional cases
else if x < 0 then - fromRat ' ( -x ) -- first .
else fromRat ' x
-- Conversion process :
-- Scale the rational number by the RealFloat base until
-- it lies in the range of the mantissa ( as used by decodeFloat / encodeFloat ) .
-- Then round the rational to an Integer and encode it with the exponent
-- that we got from the scaling .
-- To speed up the scaling process we compute the log2 of the number to get
-- a first guess of the exponent .
fromRat ' : : ( RealFloat a ) = > Rational - > a
fromRat ' x = fromRat '' x undefined
fromRat '' : : ( RealFloat a ) = > Rational - > a - > a
fromRat '' x _ x = r
where b = floatRadix r
p = floatDigits r
( minExp0 , _ ) = floatRange r
minExp = minExp0 - p -- the real minimum exponent
= toRational ( expt b ( p-1 ) )
= toRational ( expt b p )
p0 = ( integerLogBase b ( numerator x ) -
integerLogBase b ( denominator x ) - p ) ` max ` minExp
f = if p0 < 0 then 1 % expt b ( -p0 ) else expt b p0 % 1
( x ' , p ' ) = scaleRat ( toRational b ) minExp p0 ( x / f )
r = encodeFloat ( round x ' ) p ' ` asTypeOf ` _ x
-- Scale x until < = x < , or p ( the exponent ) < = minExp .
scaleRat : : Rational - > Int - > Rational - > Rational - >
Int - > Rational - > ( Rational , Int )
scaleRat b minExp p x =
if p < = minExp then
( x , p )
else if x > = xMax then
scaleRat b minExp ( p+1 ) ( x / b )
else if x < then
scaleRat b minExp ( p-1 ) ( x*b )
else
( x , p )
fromRat :: (RealFloat a) => Rational -> a
fromRat x =
if x == 0 then encodeFloat 0 0 -- Handle exceptional cases
else if x < 0 then - fromRat' (-x) -- first.
else fromRat' x
-- Conversion process:
-- Scale the rational number by the RealFloat base until
-- it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
-- Then round the rational to an Integer and encode it with the exponent
-- that we got from the scaling.
-- To speed up the scaling process we compute the log2 of the number to get
-- a first guess of the exponent.
fromRat' :: (RealFloat a) => Rational -> a
fromRat' x = fromRat'' x undefined
fromRat'' :: (RealFloat a) => Rational -> a -> a
fromRat'' x _x = r
where b = floatRadix r
p = floatDigits r
(minExp0, _) = floatRange r
minExp = minExp0 - p -- the real minimum exponent
xMin = toRational (expt b (p-1))
xMax = toRational (expt b p)
p0 = (integerLogBase b (numerator x) -
integerLogBase b (denominator x) - p) `max` minExp
f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
(x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
r = encodeFloat (round x') p' `asTypeOf` _x
-- Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
scaleRat :: Rational -> Int -> Rational -> Rational ->
Int -> Rational -> (Rational, Int)
scaleRat b minExp xMin xMax p x =
if p <= minExp then
(x, p)
else if x >= xMax then
scaleRat b minExp xMin xMax (p+1) (x/b)
else if x < xMin then
scaleRat b minExp xMin xMax (p-1) (x*b)
else
(x, p)
-}
-- Exponentiation with a cache for the most common numbers.
minExpt = 0::Int
maxExpt = 1100::Int
expt :: Integer -> Int -> Integer
expt base n = base^n
expt base n =
if base = = 2 & & n > = minExpt & & n < = maxExpt then
expts!n
else
base^n
expts : : Array Int Integer
expts = array ( minExpt , maxExpt ) [ ( ) | n < - [ minExpt .. maxExpt ] ]
expt base n =
if base == 2 && n >= minExpt && n <= maxExpt then
expts!n
else
base^n
expts :: Array Int Integer
expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
-}
-- Compute the (floor of the) log of i in base b.
-- Simplest way would be just divide i by b until it's smaller then b,
-- but that would be very slow! We are just slightly more clever.
integerLogBase :: Integer -> Integer -> Int
integerLogBase b i =
if i < b then
0
else
Try squaring the base first to cut down the number of divisions .
let l = 2 * integerLogBase (b*b) i
doDiv :: Integer -> Int -> Int
doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
in doDiv (i `div` (b^l)) l
-- Misc utilities to show integers and floats
# SPECIALIZE showSigned : : ( Int - > ShowS ) - > Int - > Int - > ShowS #
# SPECIALIZE showSigned : : ( Integer - > ShowS ) - > Int - > Integer - > ShowS #
showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
showSigned showPos p x
| x < 0 = showParen (p > 6) (showChar '-' . showPos (negate x))
| otherwise = showPos x
# INLINE showInt #
-- showInt, showOct, showHex are used for positive numbers only
showInt, showOct, showHex :: Integral a => a -> ShowS
showOct = showIntAtBase 8 intToDigit
showInt = showIntAtBase 10 intToDigit
showHex = showIntAtBase 16 intToDigit
# SPECIALIZE showIntAtBase : : Word - > ( Int - > ) - > Word - > ShowS #
# SPECIALIZE showIntAtBase : : - > ( Int - > ) - > - > ShowS #
showIntAtBase :: Integral a
=> a -- base
-> (Int -> Char) -- digit to char
-> a -- number to show
-> ShowS
showIntAtBase base intToDig n rest
| n < 0 = error $ "Numeric.showIntAtBase: can't show negative numbers " ++ show n
| n' == 0 = rest'
| otherwise = showIntAtBase base intToDig n' rest'
where
(n',d) = quotRem n base
rest' = intToDig (fromIntegral d) : rest
readSigned :: (Real a) => ReadS a -> ReadS a
readSigned readPos = readParen False read'
where read' r = read'' r ++
[(-x,t) | ("-",s) <- lex r,
(x,t) <- read'' s]
read'' r = [(n,s) | (str,s) <- lex r,
(n,"") <- readPos str]
showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
showFloat :: (RealFloat a) => a -> ShowS
showEFloat d x = showString (formatRealFloat FFExponent d x)
showFFloat d x = showString (formatRealFloat FFFixed d x)
showGFloat d x = showString (formatRealFloat FFGeneric d x)
showFloat = showGFloat Nothing
-- These are the format types. This type is not exported.
data FFFormat = FFExponent | FFFixed | FFGeneric
formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
formatRealFloat fmt decs x = s where
base = 10
s = if isNaN x then "NaN"
else if isInfinite x then
if x < 0 then "-Infinity" else "Infinity"
else if x < 0 || isNegativeZero x then
'-' : doFmt fmt (floatToDigits (toInteger base) (-x))
else
doFmt fmt (floatToDigits (toInteger base) x)
doFmt fmt (is, e) = let ds = map intToDigit is in case fmt of
FFGeneric ->
doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
(is, e)
FFExponent ->
case decs of
Nothing ->
case ds of
[] -> "0.0e0"
[d] -> d : ".0e" ++ show (e-1)
d:ds -> d : '.' : ds ++ 'e':show (e-1)
Just dec ->
let dec' = max dec 1 in
case is of
[] -> '0':'.':replicate dec' '0' ++ "e0"
_ ->
let (ei, is') = roundTo base (dec'+1) is
d:ds = map intToDigit
(if ei then init is' else is')
in d:'.':ds ++ "e" ++ show (e-1+fromEnum ei)
FFFixed ->
case decs of
Nothing -- Always prints a decimal point
| e > 0 -> take e (ds ++ repeat '0')
++ '.' : mk0 (drop e ds)
| otherwise -> "0." ++ mk0 (replicate (-e) '0' ++ ds)
Print decimal point iff dec > 0
let dec' = max dec 0 in
if e >= 0 then
let (ei, is') = roundTo base (dec' + e) is
(ls, rs) = splitAt (e+fromEnum ei)
(map intToDigit is')
in mk0 ls ++ mkdot0 rs
else
let (ei, is') = roundTo base dec'
(replicate (-e) 0 ++ is)
d : ds = map intToDigit
(if ei then is' else 0:is')
in d : mkdot0 ds
where
mk0 "" = "0" -- Print 0.34, not .34
mk0 s = s
Print 34 , not 34 .
mkdot0 s = '.' : s -- when the format specifies no
-- digits after the decimal point
roundTo :: Int -> Int -> [Int] -> (Bool, [Int])
roundTo base d is | base `seq` d `seq` True = case f d is of
(False, is) -> (False, is)
(True, is) -> (True, 1 : is)
where b2 = base `div` 2
f n [] = (False, replicate n 0)
f 0 (i:_) = (i >= b2, [])
f d (i:is) =
let (c, ds) = f (d-1) is
i' = fromEnum c + i
in if i' == base then (True, 0:ds) else (False, i':ds)
--
Based on " Printing Floating - Point Numbers Quickly and Accurately "
by R.G. Burger and , in PLDI 96 .
-- The version here uses a much slower logarithm estimator.
-- It should be improved.
This function returns a non - empty list of digits ( Ints in [ 0 .. base-1 ] )
-- and an exponent. In general, if
-- floatToDigits r = ([a, b, ... z], e)
-- then
r = 0.ab .. z *
--
floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
floatToDigits _ 0 = ([], 0)
floatToDigits base x =
let (f0, e0) = decodeFloat x
(minExp0, _) = floatRange x
p = floatDigits x
b = floatRadix x
minExp = minExp0 - p -- the real minimum exponent
-- Haskell requires that f be adjusted so denormalized numbers
-- will have an impossibly low exponent. Adjust for this.
f :: Integer
e :: Int
(f, e) = let n = minExp - e0
in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
(r, s, mUp, mDn) =
if e >= 0 then
let be = b^e in
if f == b^(p-1) then
(f*be*b*2, 2*b, be*b, b)
else
(f*be*2, 2, be, be)
else
if e > minExp && f == b^(p-1) then
(f*b*2, b^(-e+1)*2, b, 1)
else
(f*2, b^(-e)*2, 1, 1)
k =
let k0 =
if b==2 && base==10 then
logBase 10 2 is slightly bigger than 3/10 so
-- the following will err on the low side. Ignoring
-- the fraction will make it err even more.
promises that p-1 < = logBase b f < p.
(p - 1 + e0) * 3 `div` 10
else
ceiling ((log ((fromInteger (f+1))::Double) +
fromIntegral e * log (fromInteger b)) /
log (fromInteger base))
fixup n =
if n >= 0 then
if r + mUp <= expt base n * s then n else fixup (n+1)
else
if expt base (-n) * (r + mUp) <= s then n
else fixup (n+1)
in fixup (k0::Int)
gen ds rn sN mUpN mDnN =
let (dn, rn') = (rn * base) `divMod` sN
mUpN' = mUpN * base
mDnN' = mDnN * base
in case (rn' < mDnN', rn' + mUpN' > sN) of
(True, False) -> dn : ds
(False, True) -> dn+1 : ds
(True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
(False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
rds =
if k >= 0 then
gen [] r (s * expt base k) mUp mDn
else
let bk = expt base (-k)
in gen [] (r * bk) s (mUp * bk) (mDn * bk)
in (map fromIntegral (reverse rds), k)
-- This floating point reader uses a less restrictive syntax for floating
point than the lexer . The ` . ' is optional .
readFloat :: (RealFrac a) => ReadS a
readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
(k,t) <- readExp s] ++
[ (0/0, t) | ("NaN",t) <- lex r] ++
[ (1/0, t) | ("Infinity",t) <- lex r]
where
readFix r = [(read (ds++ds'), length ds', t)
| (ds,d) <- lexDigits r,
(ds',t) <- lexFrac d ]
lexFrac ('.':ds) = lexDigits ds
lexFrac s = [("",s)]
readExp (e:s) | e `elem` "eE" = readExp' s
readExp s = [(0,s)]
readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
readExp' ('+':s) = readDec s
readExp' s = readDec s
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/lib/jhc/Numeric.hs | haskell | This converts a rational to a floating. This should be used in the
Fractional instances of Float and Double.
Handle exceptional cases
first .
Conversion process :
Scale the rational number by the RealFloat base until
it lies in the range of the mantissa ( as used by decodeFloat / encodeFloat ) .
Then round the rational to an Integer and encode it with the exponent
that we got from the scaling .
To speed up the scaling process we compute the log2 of the number to get
a first guess of the exponent .
the real minimum exponent
Scale x until < = x < , or p ( the exponent ) < = minExp .
Handle exceptional cases
first.
Conversion process:
Scale the rational number by the RealFloat base until
it lies in the range of the mantissa (as used by decodeFloat/encodeFloat).
Then round the rational to an Integer and encode it with the exponent
that we got from the scaling.
To speed up the scaling process we compute the log2 of the number to get
a first guess of the exponent.
the real minimum exponent
Scale x until xMin <= x < xMax, or p (the exponent) <= minExp.
Exponentiation with a cache for the most common numbers.
Compute the (floor of the) log of i in base b.
Simplest way would be just divide i by b until it's smaller then b,
but that would be very slow! We are just slightly more clever.
Misc utilities to show integers and floats
showInt, showOct, showHex are used for positive numbers only
base
digit to char
number to show
These are the format types. This type is not exported.
Always prints a decimal point
Print 0.34, not .34
when the format specifies no
digits after the decimal point
The version here uses a much slower logarithm estimator.
It should be improved.
and an exponent. In general, if
floatToDigits r = ([a, b, ... z], e)
then
the real minimum exponent
Haskell requires that f be adjusted so denormalized numbers
will have an impossibly low exponent. Adjust for this.
the following will err on the low side. Ignoring
the fraction will make it err even more.
This floating point reader uses a less restrictive syntax for floating | module Numeric(fromRat,
showSigned, showIntAtBase,
showInt, showOct, showHex,
readSigned, readInt,
readDec, readOct, readHex,
floatToDigits,
showEFloat, showFFloat, showGFloat, showFloat,
readFloat, lexDigits) where
import Data.Ratio ( (%), numerator, denominator )
import Jhc.Basics
import Jhc.Enum
import Jhc.Float
import Jhc.IO
import Jhc.List
import Jhc.Num
import Jhc.Numeric
import Jhc.Order
import Jhc.Text.Read
import Prelude.CType(isDigit,isOctDigit,isHexDigit,digitToInt,intToDigit)
import Prelude.Text
import Jhc.Class.Real
fromRat :: (RealFloat a) => Rational -> a
fromRat = error "fromRat not implemented yet"
fromRat : : ( RealFloat a ) = > Rational - > a
fromRat x =
else fromRat ' x
fromRat ' : : ( RealFloat a ) = > Rational - > a
fromRat ' x = fromRat '' x undefined
fromRat '' : : ( RealFloat a ) = > Rational - > a - > a
fromRat '' x _ x = r
where b = floatRadix r
p = floatDigits r
( minExp0 , _ ) = floatRange r
= toRational ( expt b ( p-1 ) )
= toRational ( expt b p )
p0 = ( integerLogBase b ( numerator x ) -
integerLogBase b ( denominator x ) - p ) ` max ` minExp
f = if p0 < 0 then 1 % expt b ( -p0 ) else expt b p0 % 1
( x ' , p ' ) = scaleRat ( toRational b ) minExp p0 ( x / f )
r = encodeFloat ( round x ' ) p ' ` asTypeOf ` _ x
scaleRat : : Rational - > Int - > Rational - > Rational - >
Int - > Rational - > ( Rational , Int )
scaleRat b minExp p x =
if p < = minExp then
( x , p )
else if x > = xMax then
scaleRat b minExp ( p+1 ) ( x / b )
else if x < then
scaleRat b minExp ( p-1 ) ( x*b )
else
( x , p )
fromRat :: (RealFloat a) => Rational -> a
fromRat x =
else fromRat' x
fromRat' :: (RealFloat a) => Rational -> a
fromRat' x = fromRat'' x undefined
fromRat'' :: (RealFloat a) => Rational -> a -> a
fromRat'' x _x = r
where b = floatRadix r
p = floatDigits r
(minExp0, _) = floatRange r
xMin = toRational (expt b (p-1))
xMax = toRational (expt b p)
p0 = (integerLogBase b (numerator x) -
integerLogBase b (denominator x) - p) `max` minExp
f = if p0 < 0 then 1 % expt b (-p0) else expt b p0 % 1
(x', p') = scaleRat (toRational b) minExp xMin xMax p0 (x / f)
r = encodeFloat (round x') p' `asTypeOf` _x
scaleRat :: Rational -> Int -> Rational -> Rational ->
Int -> Rational -> (Rational, Int)
scaleRat b minExp xMin xMax p x =
if p <= minExp then
(x, p)
else if x >= xMax then
scaleRat b minExp xMin xMax (p+1) (x/b)
else if x < xMin then
scaleRat b minExp xMin xMax (p-1) (x*b)
else
(x, p)
-}
minExpt = 0::Int
maxExpt = 1100::Int
expt :: Integer -> Int -> Integer
expt base n = base^n
expt base n =
if base = = 2 & & n > = minExpt & & n < = maxExpt then
expts!n
else
base^n
expts : : Array Int Integer
expts = array ( minExpt , maxExpt ) [ ( ) | n < - [ minExpt .. maxExpt ] ]
expt base n =
if base == 2 && n >= minExpt && n <= maxExpt then
expts!n
else
base^n
expts :: Array Int Integer
expts = array (minExpt,maxExpt) [(n,2^n) | n <- [minExpt .. maxExpt]]
-}
integerLogBase :: Integer -> Integer -> Int
integerLogBase b i =
if i < b then
0
else
Try squaring the base first to cut down the number of divisions .
let l = 2 * integerLogBase (b*b) i
doDiv :: Integer -> Int -> Int
doDiv i l = if i < b then l else doDiv (i `div` b) (l+1)
in doDiv (i `div` (b^l)) l
# SPECIALIZE showSigned : : ( Int - > ShowS ) - > Int - > Int - > ShowS #
# SPECIALIZE showSigned : : ( Integer - > ShowS ) - > Int - > Integer - > ShowS #
showSigned :: Real a => (a -> ShowS) -> Int -> a -> ShowS
showSigned showPos p x
| x < 0 = showParen (p > 6) (showChar '-' . showPos (negate x))
| otherwise = showPos x
# INLINE showInt #
showInt, showOct, showHex :: Integral a => a -> ShowS
showOct = showIntAtBase 8 intToDigit
showInt = showIntAtBase 10 intToDigit
showHex = showIntAtBase 16 intToDigit
# SPECIALIZE showIntAtBase : : Word - > ( Int - > ) - > Word - > ShowS #
# SPECIALIZE showIntAtBase : : - > ( Int - > ) - > - > ShowS #
showIntAtBase :: Integral a
-> ShowS
showIntAtBase base intToDig n rest
| n < 0 = error $ "Numeric.showIntAtBase: can't show negative numbers " ++ show n
| n' == 0 = rest'
| otherwise = showIntAtBase base intToDig n' rest'
where
(n',d) = quotRem n base
rest' = intToDig (fromIntegral d) : rest
readSigned :: (Real a) => ReadS a -> ReadS a
readSigned readPos = readParen False read'
where read' r = read'' r ++
[(-x,t) | ("-",s) <- lex r,
(x,t) <- read'' s]
read'' r = [(n,s) | (str,s) <- lex r,
(n,"") <- readPos str]
showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS
showFloat :: (RealFloat a) => a -> ShowS
showEFloat d x = showString (formatRealFloat FFExponent d x)
showFFloat d x = showString (formatRealFloat FFFixed d x)
showGFloat d x = showString (formatRealFloat FFGeneric d x)
showFloat = showGFloat Nothing
data FFFormat = FFExponent | FFFixed | FFGeneric
formatRealFloat :: (RealFloat a) => FFFormat -> Maybe Int -> a -> String
formatRealFloat fmt decs x = s where
base = 10
s = if isNaN x then "NaN"
else if isInfinite x then
if x < 0 then "-Infinity" else "Infinity"
else if x < 0 || isNegativeZero x then
'-' : doFmt fmt (floatToDigits (toInteger base) (-x))
else
doFmt fmt (floatToDigits (toInteger base) x)
doFmt fmt (is, e) = let ds = map intToDigit is in case fmt of
FFGeneric ->
doFmt (if e < 0 || e > 7 then FFExponent else FFFixed)
(is, e)
FFExponent ->
case decs of
Nothing ->
case ds of
[] -> "0.0e0"
[d] -> d : ".0e" ++ show (e-1)
d:ds -> d : '.' : ds ++ 'e':show (e-1)
Just dec ->
let dec' = max dec 1 in
case is of
[] -> '0':'.':replicate dec' '0' ++ "e0"
_ ->
let (ei, is') = roundTo base (dec'+1) is
d:ds = map intToDigit
(if ei then init is' else is')
in d:'.':ds ++ "e" ++ show (e-1+fromEnum ei)
FFFixed ->
case decs of
| e > 0 -> take e (ds ++ repeat '0')
++ '.' : mk0 (drop e ds)
| otherwise -> "0." ++ mk0 (replicate (-e) '0' ++ ds)
Print decimal point iff dec > 0
let dec' = max dec 0 in
if e >= 0 then
let (ei, is') = roundTo base (dec' + e) is
(ls, rs) = splitAt (e+fromEnum ei)
(map intToDigit is')
in mk0 ls ++ mkdot0 rs
else
let (ei, is') = roundTo base dec'
(replicate (-e) 0 ++ is)
d : ds = map intToDigit
(if ei then is' else 0:is')
in d : mkdot0 ds
where
mk0 s = s
Print 34 , not 34 .
roundTo :: Int -> Int -> [Int] -> (Bool, [Int])
roundTo base d is | base `seq` d `seq` True = case f d is of
(False, is) -> (False, is)
(True, is) -> (True, 1 : is)
where b2 = base `div` 2
f n [] = (False, replicate n 0)
f 0 (i:_) = (i >= b2, [])
f d (i:is) =
let (c, ds) = f (d-1) is
i' = fromEnum c + i
in if i' == base then (True, 0:ds) else (False, i':ds)
Based on " Printing Floating - Point Numbers Quickly and Accurately "
by R.G. Burger and , in PLDI 96 .
This function returns a non - empty list of digits ( Ints in [ 0 .. base-1 ] )
r = 0.ab .. z *
floatToDigits :: (RealFloat a) => Integer -> a -> ([Int], Int)
floatToDigits _ 0 = ([], 0)
floatToDigits base x =
let (f0, e0) = decodeFloat x
(minExp0, _) = floatRange x
p = floatDigits x
b = floatRadix x
f :: Integer
e :: Int
(f, e) = let n = minExp - e0
in if n > 0 then (f0 `div` (b^n), e0+n) else (f0, e0)
(r, s, mUp, mDn) =
if e >= 0 then
let be = b^e in
if f == b^(p-1) then
(f*be*b*2, 2*b, be*b, b)
else
(f*be*2, 2, be, be)
else
if e > minExp && f == b^(p-1) then
(f*b*2, b^(-e+1)*2, b, 1)
else
(f*2, b^(-e)*2, 1, 1)
k =
let k0 =
if b==2 && base==10 then
logBase 10 2 is slightly bigger than 3/10 so
promises that p-1 < = logBase b f < p.
(p - 1 + e0) * 3 `div` 10
else
ceiling ((log ((fromInteger (f+1))::Double) +
fromIntegral e * log (fromInteger b)) /
log (fromInteger base))
fixup n =
if n >= 0 then
if r + mUp <= expt base n * s then n else fixup (n+1)
else
if expt base (-n) * (r + mUp) <= s then n
else fixup (n+1)
in fixup (k0::Int)
gen ds rn sN mUpN mDnN =
let (dn, rn') = (rn * base) `divMod` sN
mUpN' = mUpN * base
mDnN' = mDnN * base
in case (rn' < mDnN', rn' + mUpN' > sN) of
(True, False) -> dn : ds
(False, True) -> dn+1 : ds
(True, True) -> if rn' * 2 < sN then dn : ds else dn+1 : ds
(False, False) -> gen (dn:ds) rn' sN mUpN' mDnN'
rds =
if k >= 0 then
gen [] r (s * expt base k) mUp mDn
else
let bk = expt base (-k)
in gen [] (r * bk) s (mUp * bk) (mDn * bk)
in (map fromIntegral (reverse rds), k)
point than the lexer . The ` . ' is optional .
readFloat :: (RealFrac a) => ReadS a
readFloat r = [(fromRational ((n%1)*10^^(k-d)),t) | (n,d,s) <- readFix r,
(k,t) <- readExp s] ++
[ (0/0, t) | ("NaN",t) <- lex r] ++
[ (1/0, t) | ("Infinity",t) <- lex r]
where
readFix r = [(read (ds++ds'), length ds', t)
| (ds,d) <- lexDigits r,
(ds',t) <- lexFrac d ]
lexFrac ('.':ds) = lexDigits ds
lexFrac s = [("",s)]
readExp (e:s) | e `elem` "eE" = readExp' s
readExp s = [(0,s)]
readExp' ('-':s) = [(-k,t) | (k,t) <- readDec s]
readExp' ('+':s) = readDec s
readExp' s = readDec s
|
f30fcd098538d89aa9abedeb557218b5293ad2c7ed6630566aeff8807c769ecb | AbstractMachinesLab/rebar3_caramel | caramel_readme_app.erl | %%%-------------------------------------------------------------------
%% @doc caramel_readme public API
%% @end
%%%-------------------------------------------------------------------
-module(caramel_readme_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
caramel_readme_sup:start_link().
stop(_State) ->
ok.
%% internal functions
| null | https://raw.githubusercontent.com/AbstractMachinesLab/rebar3_caramel/79370f504599d6bc040b8da02642c8f7fcd365cb/examples/caramel_readme/apps/caramel_readme/src/caramel_readme_app.erl | erlang | -------------------------------------------------------------------
@doc caramel_readme public API
@end
-------------------------------------------------------------------
internal functions |
-module(caramel_readme_app).
-behaviour(application).
-export([start/2, stop/1]).
start(_StartType, _StartArgs) ->
caramel_readme_sup:start_link().
stop(_State) ->
ok.
|
72a0f46f98163f89fd13cc9d9202883a8b3ab705069034fa7d93806b614b5dab | reactiveml/rml | viewer_js.ml | Graph viewer
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
type rect = {x : int; y : int; width : int; height: int}
module Html = Dom_html
let create_canvas w h =
let c = Html.createCanvas Html.document in
c##width <- w; c##height <- h; c
module Common = Viewer_common.F (struct
type font = Js.js_string Js.t
type color = Js.js_string Js.t
type text = Js.js_string Js.t
let white = Js.string "white"
type ctx = Html.canvasRenderingContext2D Js.t
let save ctx = ctx##save ()
let restore ctx = ctx##restore ()
let scale ctx ~sx ~sy = ctx##scale (sx, sy)
let translate ctx ~tx ~ty = ctx##translate (tx, ty)
let set_line_width ctx w = ctx##lineWidth <- w
let begin_path ctx = ctx##beginPath ()
let close_path ctx = ctx##closePath ()
let move_to ctx ~x ~y = ctx##moveTo (x, y)
let line_to ctx ~x ~y = ctx##lineTo (x, y)
let curve_to ctx ~x1 ~y1 ~x2 ~y2 ~x3 ~y3 =
ctx##bezierCurveTo (x1, y1, x2, y2, x3, y3)
let arc ctx ~xc ~yc ~radius ~angle1 ~angle2 =
ctx##arc (xc, yc, radius, angle1, angle2, Js._true)
let rectangle ctx ~x ~y ~width ~height = ctx##rect (x, y, width, height)
let fill ctx c = ctx##fillStyle <- c; ctx##fill ()
let stroke ctx c = ctx##strokeStyle <- c; ctx##stroke ()
let clip ctx = ctx##clip ()
let draw_text (ctx:ctx) x y txt font fill_color stroke_color =
ctx##font <- font;
ctx##textAlign <- Js.string "center";
ctx##textBaseline <- Js.string "middle";
begin match fill_color with
Some c -> ctx##fillStyle <- c; ctx##fillText (txt, x, y)
| None -> ()
end;
begin match stroke_color with
Some c -> ctx##strokeStyle <- c; ctx##strokeText (txt, x, y)
| None -> ()
end
type window = Html.canvasElement Js.t
type drawable = window * ctx
type pixmap = drawable
let get_drawable w =
let ctx = w##getContext(Html._2d_) in
ctx##lineWidth <- 2.;
(w, ctx)
let make_pixmap _ width height =
let c = Html.createCanvas Html.document in
c##width <- width; c##height <- height;
get_drawable c
let drawable_of_pixmap p = p
let get_context (p, c) = c
let put_pixmap ~dst:((p, c) :drawable) ~x ~y ~xsrc ~ysrc ~width ~height ((p, _) : pixmap)=
c##drawImage_fullFromCanvas (p, float xsrc, float ysrc, float width, float height, float x, float y, float width, float height)
(****)
type rectangle = rect = {x : int; y : int; width : int; height: int}
let compute_extents _ = assert false
end)
open Common
let redraw st s h v (canvas : Html.canvasElement Js.t) =
let width = canvas##width in
let height = canvas##height in
Firebug.console##time ( Js.string " draw " ) ;
redraw st s h v canvas
{x = 0; y = 0; width = width; height = height} 0 0 width height
; Firebug.console##timeEnd ( Js.string " draw " )
; Firebug.console##log_2 ( Js.string " draw " , ( ) )
;Firebug.console##timeEnd (Js.string "draw")
;Firebug.console##log_2 (Js.string "draw", Js.date##now())
*)
let (>>=) = Lwt.bind
let http_get url =
XmlHttpRequest.get url
>>= fun {XmlHttpRequest.code = cod; content = msg} ->
if cod = 0 || cod = 200
then Lwt.return msg
else fst (Lwt.wait ())
let json : < parse : Js.js_string Js.t -> 'a> Js.t = Js.Unsafe.variable "JSON"
class adjustment
?(value=0.) ?(lower=0.) ?(upper=100.)
?(step_incr=1.) ?(page_incr = 10.) ?(page_size = 10.) () =
object
val mutable _value = value method value = _value
val mutable _lower = lower method lower = _lower
val mutable _upper = upper method upper = _upper
val mutable _step_incr = step_incr method step_increment = _step_incr
val mutable _page_incr = page_incr method page_increment = _page_incr
val mutable _page_size = page_size method page_size = _page_size
method set_value v = _value <- v
method set_bounds ?lower ?upper ?step_incr ?page_incr ?page_size () =
begin match lower with Some v -> _lower <- v | None -> () end;
begin match upper with Some v -> _upper <- v | None -> () end;
begin match step_incr with Some v -> _step_incr <- v | None -> () end;
begin match page_incr with Some v -> _page_incr <- v | None -> () end;
begin match page_size with Some v -> _page_size <- v | None -> () end
end
let handle_drag element f =
let mx = ref 0 in
let my = ref 0 in
element##onmousedown <- Html.handler
(fun ev ->
mx := ev##clientX; my := ev##clientY;
element##style##cursor <- Js.string "move";
let c1 =
Html.addEventListener Html.document Html.Event.mousemove
(Html.handler
(fun ev ->
let x = ev##clientX and y = ev##clientY in
let x' = !mx and y' = !my in
mx := x; my := y;
f (x - x') (y - y');
Js._true))
Js._true
in
let c2 = ref Js.null in
c2 := Js.some
(Html.addEventListener Html.document Html.Event.mouseup
(Html.handler
(fun _ ->
Html.removeEventListener c1;
Js.Opt.iter !c2 Html.removeEventListener;
element##style##cursor <- Js.string "";
Js._true))
Js._true);
(* We do not want to disable the default action on mouse down
(here, keyboard focus)
in this example. *)
Js._true)
let start () =
let doc = Html.document in
let page = doc##documentElement in
page##style##overflow <- Js.string "hidden";
doc##body##style##overflow <- Js.string "hidden";
doc##body##style##margin <- Js.string "0px";
let started = ref false in
let p = Html.createP doc in
p##innerHTML <- Js.string "Loading graph...";
p##style##display <- Js.string "none";
Dom.appendChild doc##body p;
ignore
(Lwt_js.sleep 0.5 >>= fun () ->
if not !started then p##style##display <- Js.string "inline";
Lwt.return ());
(*
Firebug.console##time(Js.string "loading");
*)
http_get "scene.json" >>= fun s ->
(*
Firebug.console##timeEnd(Js.string "loading");
Firebug.console##time(Js.string "parsing");
*)
let ((x1, y1, x2, y2), bboxes, scene) = json##parse (Js.string s) in
(*
Firebug.console##timeEnd(Js.string "parsing");
Firebug.console##time(Js.string "init");
*)
started := true;
Dom.removeChild doc##body p;
let st =
{ bboxes = bboxes;
scene = scene;
zoom_factor = 1. /. 20.;
st_x = x1; st_y = y1; st_width = x2 -. x1; st_height = y2 -. y1;
st_pixmap = Common.make_pixmap () }
in
let canvas = create_canvas (page##clientWidth) (page##clientHeight) in
Dom.appendChild doc##body canvas;
let allocation () =
{x = 0; y = 0; width = canvas##width; height = canvas##height} in
let hadj = new adjustment () in
let vadj = new adjustment () in
let sadj =
new adjustment ~upper:20. ~step_incr:1. ~page_incr:0. ~page_size:0. () in
Number of steps to get a factor of 2
let set_zoom_factor f =
let count = ceil (log f /. log 2. *. zoom_steps) in
let f = 2. ** (count /. zoom_steps) in
sadj#set_bounds ~upper:count ();
st.zoom_factor <- f
in
let get_scale () = 2. ** (sadj#value /. zoom_steps) /. st.zoom_factor in
let redraw_queued = ref false in
let update_view force =
Firebug.console##log_2(Js.string " update " , Js.date##now ( ) ) ;
Firebug.console##log_2(Js.string "update", Js.date##now());
*)
let a = allocation () in
let scale = get_scale () in
let aw = ceil (float a.width /. scale) in
let ah = ceil (float a.height /. scale) in
hadj#set_bounds ~step_incr:(aw /. 20.) ~page_incr:(aw /. 2.)
~page_size:(min aw st.st_width) ~upper:st.st_width ();
let mv = st.st_width -. hadj#page_size in
if hadj#value < 0. then hadj#set_value 0.;
if hadj#value > mv then hadj#set_value mv;
vadj#set_bounds ~step_incr:(ah /. 20.) ~page_incr:(ah /. 2.)
~page_size:(min ah st.st_height) ~upper:st.st_height ();
let mv = st.st_height -. vadj#page_size in
if vadj#value < 0. then vadj#set_value 0.;
if vadj#value > mv then vadj#set_value mv;
if not !redraw_queued then begin
redraw_queued := true;
Html._requestAnimationFrame
(Js.wrap_callback (fun () ->
redraw_queued := false;
redraw st (get_scale ()) hadj#value vadj#value canvas))
end
if force then redraw st ( ( ) ) hadj#value vadj#value canvas else
if not ! redraw_queued then
ignore ( redraw_queued : = true ;
( *
Firebug.console##log(Js.string " sleep " ) ;
if force then redraw st (get_scale ()) hadj#value vadj#value canvas else
if not !redraw_queued then
ignore (redraw_queued := true;
(*
Firebug.console##log(Js.string "sleep");
*)
Lwt_js.yield() >>= fun () ->
redraw_queued := false;
redraw st (get_scale ()) hadj#value vadj#value canvas;
Lwt.return ())
*)
in
let a = allocation () in
let zoom_factor =
max (st.st_width /. float a.width)
(st.st_height /. float a.height)
in
set_zoom_factor zoom_factor;
let prev_scale = ref (get_scale ()) in
let rescale x y =
let scale = get_scale () in
let r = (1. -. !prev_scale /. scale) in
hadj#set_value (hadj#value +. hadj#page_size *. r *. x);
vadj#set_value (vadj#value +. vadj#page_size *. r *. y);
prev_scale := scale;
invalidate_pixmap st.st_pixmap;
update_view false
in
let size = 16 in
let height = 300 - size in
let points d = Js.string (Printf.sprintf "%dpx" d) in
let size_px = points size in
let pos = ref height in
let thumb = Html.createDiv doc in
let style = thumb##style in
style##position <- Js.string "absolute";
style##width <- size_px;
style##height <- size_px;
style##top <- points !pos;
style##left <- Js.string "0px";
style##margin <- Js.string "1px";
style##backgroundColor <- Js.string "black";
let slider = Html.createDiv doc in
let style = slider##style in
style##position <- Js.string "absolute";
style##width <- size_px;
style##height <- points (height + size);
style##border <- Js.string "2px solid black";
style##padding <- Js.string "1px";
style##top <- Js.string "10px";
style##left <- Js.string "10px";
Dom.appendChild slider thumb;
Dom.appendChild doc##body slider;
let set_slider_position pos' =
if pos' <> !pos then begin
thumb##style##top <- points pos';
pos := pos';
sadj#set_value (float (height - pos') *. sadj#upper /. float height);
rescale 0.5 0.5
end
in
handle_drag thumb
(fun dx dy ->
set_slider_position (min height (max 0 (!pos + dy))));
slider##onmousedown <- Html.handler
(fun ev ->
let ey = ev##clientY in
let (_, sy) = Dom_html.elementClientPosition slider in
set_slider_position (max 0 (min height (ey - sy - size / 2)));
Js._false);
let adjust_slider () =
let pos' =
height - truncate (sadj#value *. float height /. sadj#upper +. 0.5) in
thumb##style##top <- points pos';
pos := pos'
in
Html.window##onresize <- Html.handler
(fun _ ->
let page = doc##documentElement in
canvas##width <- page##clientWidth;
canvas##height <- page##clientHeight;
update_view true;
Js._true);
(* Drag the graph using the mouse *)
handle_drag canvas
(fun dx dy ->
let scale = get_scale () in
let offset a d =
a#set_value
(min (a#value -. float d /. scale) (a#upper -. a#page_size)) in
offset hadj dx;
offset vadj dy;
update_view true);
let bump_scale x y v =
let a = allocation () in
let x = x /. float a.width in
let y = y /. float a.height in
let prev = sadj#value in
let vl =
min (sadj#upper) (max (sadj#lower) (prev +. v *. sadj#step_increment)) in
if vl <> prev then begin
sadj#set_value vl;
adjust_slider ();
if x >= 0. && x <= 1. && y >= 0. && y <= 1. then
rescale x y
else
rescale 0.5 0.5
end;
Js._false
in
(* Zoom using the mouse wheel *)
ignore (Html.addMousewheelEventListener canvas
(fun ev ~dx ~dy ->
let (ex, ey) = Dom_html.elementClientPosition canvas in
let x = float (ev##clientX - ex) in
let y = float (ev##clientY - ey) in
if dy < 0 then
bump_scale x y 1.
else if dy > 0 then
bump_scale x y (-1.)
else
Js._false)
Js._true);
(*
Html.addEventListener Html.document Html.Event.keydown
(Html.handler
(fun e -> Firebug.console##log(e##keyCode);
Js._true))
Js._true;
*)
Html.addEventListener Html.document Html.Event.keypress
( Html.handler
( fun e - >
Firebug.console##log(Js.string " press " ) ;
match e##keyCode with
| 37 - > ( * left
Html.addEventListener Html.document Html.Event.keypress
(Html.handler
(fun e ->
Firebug.console##log(Js.string "press");
match e##keyCode with
| 37 -> (* left *)
Js._false
| 38 -> (* up *)
Js._false
| 39 -> (* right *)
Js._false
| 40 -> (* down *)
Js._false
| _ ->
Firebug.console##log(- 1- e##keyCode);
Js._true))
Js._true;
*)
let handle_key_event ev =
match ev##keyCode with
37 -> (* left *)
hadj#set_value (hadj#value -. hadj#step_increment);
update_view false;
Js._false
| 38 -> (* up *)
vadj#set_value (vadj#value -. vadj#step_increment);
update_view false;
Js._false
| 39 -> (* right *)
hadj#set_value (hadj#value +. hadj#step_increment);
update_view false;
Js._false
| 40 -> (* down *)
vadj#set_value (vadj#value +. vadj#step_increment);
update_view false;
Js._false
| _ ->
(*
Firebug.console##log_2(Js.string "keycode:", ev##keyCode);
*)
Js._true
in
let ignored_keycode = ref (-1) in
Html.document##onkeydown <-
(Html.handler
(fun e ->
ignored_keycode := e##keyCode;
handle_key_event e));
Html.document##onkeypress <-
(Html.handler
(fun e ->
let k = !ignored_keycode in
ignored_keycode := -1;
if e##keyCode = k then Js._true else handle_key_event e));
(*
Firebug.console##time(Js.string "initial drawing");
*)
update_view true;
(*
Firebug.console##timeEnd(Js.string "initial drawing");
Firebug.console##timeEnd(Js.string "init");
*)
Lwt.return ()
let _ =
Html.window##onload <- Html.handler (fun _ -> ignore (start ()); Js._false)
| null | https://raw.githubusercontent.com/reactiveml/rml/d178d49ed923290fa7eee642541bdff3ee90b3b4/toplevel-alt/js/js-of-ocaml/examples/graph_viewer/viewer_js.ml | ocaml | **
We do not want to disable the default action on mouse down
(here, keyboard focus)
in this example.
Firebug.console##time(Js.string "loading");
Firebug.console##timeEnd(Js.string "loading");
Firebug.console##time(Js.string "parsing");
Firebug.console##timeEnd(Js.string "parsing");
Firebug.console##time(Js.string "init");
Firebug.console##log(Js.string "sleep");
Drag the graph using the mouse
Zoom using the mouse wheel
Html.addEventListener Html.document Html.Event.keydown
(Html.handler
(fun e -> Firebug.console##log(e##keyCode);
Js._true))
Js._true;
left
up
right
down
left
up
right
down
Firebug.console##log_2(Js.string "keycode:", ev##keyCode);
Firebug.console##time(Js.string "initial drawing");
Firebug.console##timeEnd(Js.string "initial drawing");
Firebug.console##timeEnd(Js.string "init");
| Graph viewer
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
type rect = {x : int; y : int; width : int; height: int}
module Html = Dom_html
let create_canvas w h =
let c = Html.createCanvas Html.document in
c##width <- w; c##height <- h; c
module Common = Viewer_common.F (struct
type font = Js.js_string Js.t
type color = Js.js_string Js.t
type text = Js.js_string Js.t
let white = Js.string "white"
type ctx = Html.canvasRenderingContext2D Js.t
let save ctx = ctx##save ()
let restore ctx = ctx##restore ()
let scale ctx ~sx ~sy = ctx##scale (sx, sy)
let translate ctx ~tx ~ty = ctx##translate (tx, ty)
let set_line_width ctx w = ctx##lineWidth <- w
let begin_path ctx = ctx##beginPath ()
let close_path ctx = ctx##closePath ()
let move_to ctx ~x ~y = ctx##moveTo (x, y)
let line_to ctx ~x ~y = ctx##lineTo (x, y)
let curve_to ctx ~x1 ~y1 ~x2 ~y2 ~x3 ~y3 =
ctx##bezierCurveTo (x1, y1, x2, y2, x3, y3)
let arc ctx ~xc ~yc ~radius ~angle1 ~angle2 =
ctx##arc (xc, yc, radius, angle1, angle2, Js._true)
let rectangle ctx ~x ~y ~width ~height = ctx##rect (x, y, width, height)
let fill ctx c = ctx##fillStyle <- c; ctx##fill ()
let stroke ctx c = ctx##strokeStyle <- c; ctx##stroke ()
let clip ctx = ctx##clip ()
let draw_text (ctx:ctx) x y txt font fill_color stroke_color =
ctx##font <- font;
ctx##textAlign <- Js.string "center";
ctx##textBaseline <- Js.string "middle";
begin match fill_color with
Some c -> ctx##fillStyle <- c; ctx##fillText (txt, x, y)
| None -> ()
end;
begin match stroke_color with
Some c -> ctx##strokeStyle <- c; ctx##strokeText (txt, x, y)
| None -> ()
end
type window = Html.canvasElement Js.t
type drawable = window * ctx
type pixmap = drawable
let get_drawable w =
let ctx = w##getContext(Html._2d_) in
ctx##lineWidth <- 2.;
(w, ctx)
let make_pixmap _ width height =
let c = Html.createCanvas Html.document in
c##width <- width; c##height <- height;
get_drawable c
let drawable_of_pixmap p = p
let get_context (p, c) = c
let put_pixmap ~dst:((p, c) :drawable) ~x ~y ~xsrc ~ysrc ~width ~height ((p, _) : pixmap)=
c##drawImage_fullFromCanvas (p, float xsrc, float ysrc, float width, float height, float x, float y, float width, float height)
type rectangle = rect = {x : int; y : int; width : int; height: int}
let compute_extents _ = assert false
end)
open Common
let redraw st s h v (canvas : Html.canvasElement Js.t) =
let width = canvas##width in
let height = canvas##height in
Firebug.console##time ( Js.string " draw " ) ;
redraw st s h v canvas
{x = 0; y = 0; width = width; height = height} 0 0 width height
; Firebug.console##timeEnd ( Js.string " draw " )
; Firebug.console##log_2 ( Js.string " draw " , ( ) )
;Firebug.console##timeEnd (Js.string "draw")
;Firebug.console##log_2 (Js.string "draw", Js.date##now())
*)
let (>>=) = Lwt.bind
let http_get url =
XmlHttpRequest.get url
>>= fun {XmlHttpRequest.code = cod; content = msg} ->
if cod = 0 || cod = 200
then Lwt.return msg
else fst (Lwt.wait ())
let json : < parse : Js.js_string Js.t -> 'a> Js.t = Js.Unsafe.variable "JSON"
class adjustment
?(value=0.) ?(lower=0.) ?(upper=100.)
?(step_incr=1.) ?(page_incr = 10.) ?(page_size = 10.) () =
object
val mutable _value = value method value = _value
val mutable _lower = lower method lower = _lower
val mutable _upper = upper method upper = _upper
val mutable _step_incr = step_incr method step_increment = _step_incr
val mutable _page_incr = page_incr method page_increment = _page_incr
val mutable _page_size = page_size method page_size = _page_size
method set_value v = _value <- v
method set_bounds ?lower ?upper ?step_incr ?page_incr ?page_size () =
begin match lower with Some v -> _lower <- v | None -> () end;
begin match upper with Some v -> _upper <- v | None -> () end;
begin match step_incr with Some v -> _step_incr <- v | None -> () end;
begin match page_incr with Some v -> _page_incr <- v | None -> () end;
begin match page_size with Some v -> _page_size <- v | None -> () end
end
let handle_drag element f =
let mx = ref 0 in
let my = ref 0 in
element##onmousedown <- Html.handler
(fun ev ->
mx := ev##clientX; my := ev##clientY;
element##style##cursor <- Js.string "move";
let c1 =
Html.addEventListener Html.document Html.Event.mousemove
(Html.handler
(fun ev ->
let x = ev##clientX and y = ev##clientY in
let x' = !mx and y' = !my in
mx := x; my := y;
f (x - x') (y - y');
Js._true))
Js._true
in
let c2 = ref Js.null in
c2 := Js.some
(Html.addEventListener Html.document Html.Event.mouseup
(Html.handler
(fun _ ->
Html.removeEventListener c1;
Js.Opt.iter !c2 Html.removeEventListener;
element##style##cursor <- Js.string "";
Js._true))
Js._true);
Js._true)
let start () =
let doc = Html.document in
let page = doc##documentElement in
page##style##overflow <- Js.string "hidden";
doc##body##style##overflow <- Js.string "hidden";
doc##body##style##margin <- Js.string "0px";
let started = ref false in
let p = Html.createP doc in
p##innerHTML <- Js.string "Loading graph...";
p##style##display <- Js.string "none";
Dom.appendChild doc##body p;
ignore
(Lwt_js.sleep 0.5 >>= fun () ->
if not !started then p##style##display <- Js.string "inline";
Lwt.return ());
http_get "scene.json" >>= fun s ->
let ((x1, y1, x2, y2), bboxes, scene) = json##parse (Js.string s) in
started := true;
Dom.removeChild doc##body p;
let st =
{ bboxes = bboxes;
scene = scene;
zoom_factor = 1. /. 20.;
st_x = x1; st_y = y1; st_width = x2 -. x1; st_height = y2 -. y1;
st_pixmap = Common.make_pixmap () }
in
let canvas = create_canvas (page##clientWidth) (page##clientHeight) in
Dom.appendChild doc##body canvas;
let allocation () =
{x = 0; y = 0; width = canvas##width; height = canvas##height} in
let hadj = new adjustment () in
let vadj = new adjustment () in
let sadj =
new adjustment ~upper:20. ~step_incr:1. ~page_incr:0. ~page_size:0. () in
Number of steps to get a factor of 2
let set_zoom_factor f =
let count = ceil (log f /. log 2. *. zoom_steps) in
let f = 2. ** (count /. zoom_steps) in
sadj#set_bounds ~upper:count ();
st.zoom_factor <- f
in
let get_scale () = 2. ** (sadj#value /. zoom_steps) /. st.zoom_factor in
let redraw_queued = ref false in
let update_view force =
Firebug.console##log_2(Js.string " update " , Js.date##now ( ) ) ;
Firebug.console##log_2(Js.string "update", Js.date##now());
*)
let a = allocation () in
let scale = get_scale () in
let aw = ceil (float a.width /. scale) in
let ah = ceil (float a.height /. scale) in
hadj#set_bounds ~step_incr:(aw /. 20.) ~page_incr:(aw /. 2.)
~page_size:(min aw st.st_width) ~upper:st.st_width ();
let mv = st.st_width -. hadj#page_size in
if hadj#value < 0. then hadj#set_value 0.;
if hadj#value > mv then hadj#set_value mv;
vadj#set_bounds ~step_incr:(ah /. 20.) ~page_incr:(ah /. 2.)
~page_size:(min ah st.st_height) ~upper:st.st_height ();
let mv = st.st_height -. vadj#page_size in
if vadj#value < 0. then vadj#set_value 0.;
if vadj#value > mv then vadj#set_value mv;
if not !redraw_queued then begin
redraw_queued := true;
Html._requestAnimationFrame
(Js.wrap_callback (fun () ->
redraw_queued := false;
redraw st (get_scale ()) hadj#value vadj#value canvas))
end
if force then redraw st ( ( ) ) hadj#value vadj#value canvas else
if not ! redraw_queued then
ignore ( redraw_queued : = true ;
( *
Firebug.console##log(Js.string " sleep " ) ;
if force then redraw st (get_scale ()) hadj#value vadj#value canvas else
if not !redraw_queued then
ignore (redraw_queued := true;
Lwt_js.yield() >>= fun () ->
redraw_queued := false;
redraw st (get_scale ()) hadj#value vadj#value canvas;
Lwt.return ())
*)
in
let a = allocation () in
let zoom_factor =
max (st.st_width /. float a.width)
(st.st_height /. float a.height)
in
set_zoom_factor zoom_factor;
let prev_scale = ref (get_scale ()) in
let rescale x y =
let scale = get_scale () in
let r = (1. -. !prev_scale /. scale) in
hadj#set_value (hadj#value +. hadj#page_size *. r *. x);
vadj#set_value (vadj#value +. vadj#page_size *. r *. y);
prev_scale := scale;
invalidate_pixmap st.st_pixmap;
update_view false
in
let size = 16 in
let height = 300 - size in
let points d = Js.string (Printf.sprintf "%dpx" d) in
let size_px = points size in
let pos = ref height in
let thumb = Html.createDiv doc in
let style = thumb##style in
style##position <- Js.string "absolute";
style##width <- size_px;
style##height <- size_px;
style##top <- points !pos;
style##left <- Js.string "0px";
style##margin <- Js.string "1px";
style##backgroundColor <- Js.string "black";
let slider = Html.createDiv doc in
let style = slider##style in
style##position <- Js.string "absolute";
style##width <- size_px;
style##height <- points (height + size);
style##border <- Js.string "2px solid black";
style##padding <- Js.string "1px";
style##top <- Js.string "10px";
style##left <- Js.string "10px";
Dom.appendChild slider thumb;
Dom.appendChild doc##body slider;
let set_slider_position pos' =
if pos' <> !pos then begin
thumb##style##top <- points pos';
pos := pos';
sadj#set_value (float (height - pos') *. sadj#upper /. float height);
rescale 0.5 0.5
end
in
handle_drag thumb
(fun dx dy ->
set_slider_position (min height (max 0 (!pos + dy))));
slider##onmousedown <- Html.handler
(fun ev ->
let ey = ev##clientY in
let (_, sy) = Dom_html.elementClientPosition slider in
set_slider_position (max 0 (min height (ey - sy - size / 2)));
Js._false);
let adjust_slider () =
let pos' =
height - truncate (sadj#value *. float height /. sadj#upper +. 0.5) in
thumb##style##top <- points pos';
pos := pos'
in
Html.window##onresize <- Html.handler
(fun _ ->
let page = doc##documentElement in
canvas##width <- page##clientWidth;
canvas##height <- page##clientHeight;
update_view true;
Js._true);
handle_drag canvas
(fun dx dy ->
let scale = get_scale () in
let offset a d =
a#set_value
(min (a#value -. float d /. scale) (a#upper -. a#page_size)) in
offset hadj dx;
offset vadj dy;
update_view true);
let bump_scale x y v =
let a = allocation () in
let x = x /. float a.width in
let y = y /. float a.height in
let prev = sadj#value in
let vl =
min (sadj#upper) (max (sadj#lower) (prev +. v *. sadj#step_increment)) in
if vl <> prev then begin
sadj#set_value vl;
adjust_slider ();
if x >= 0. && x <= 1. && y >= 0. && y <= 1. then
rescale x y
else
rescale 0.5 0.5
end;
Js._false
in
ignore (Html.addMousewheelEventListener canvas
(fun ev ~dx ~dy ->
let (ex, ey) = Dom_html.elementClientPosition canvas in
let x = float (ev##clientX - ex) in
let y = float (ev##clientY - ey) in
if dy < 0 then
bump_scale x y 1.
else if dy > 0 then
bump_scale x y (-1.)
else
Js._false)
Js._true);
Html.addEventListener Html.document Html.Event.keypress
( Html.handler
( fun e - >
Firebug.console##log(Js.string " press " ) ;
match e##keyCode with
| 37 - > ( * left
Html.addEventListener Html.document Html.Event.keypress
(Html.handler
(fun e ->
Firebug.console##log(Js.string "press");
match e##keyCode with
Js._false
Js._false
Js._false
Js._false
| _ ->
Firebug.console##log(- 1- e##keyCode);
Js._true))
Js._true;
*)
let handle_key_event ev =
match ev##keyCode with
hadj#set_value (hadj#value -. hadj#step_increment);
update_view false;
Js._false
vadj#set_value (vadj#value -. vadj#step_increment);
update_view false;
Js._false
hadj#set_value (hadj#value +. hadj#step_increment);
update_view false;
Js._false
vadj#set_value (vadj#value +. vadj#step_increment);
update_view false;
Js._false
| _ ->
Js._true
in
let ignored_keycode = ref (-1) in
Html.document##onkeydown <-
(Html.handler
(fun e ->
ignored_keycode := e##keyCode;
handle_key_event e));
Html.document##onkeypress <-
(Html.handler
(fun e ->
let k = !ignored_keycode in
ignored_keycode := -1;
if e##keyCode = k then Js._true else handle_key_event e));
update_view true;
Lwt.return ()
let _ =
Html.window##onload <- Html.handler (fun _ -> ignore (start ()); Js._false)
|
bf89ea9009cef50853e1c98ff3474daad35cda4535da41f4b7ae3bd0edaf4125 | haskell-tools/haskell-tools | InCompStmt.hs | # LANGUAGE ParallelListComp #
module InCompStmt where
{-# ANN module "HLint: ignore Redundant list comprehension" #-}
xs = [ [ (x,y) | x <- [1..10] | y <- [1..10] ] | z <- [1..10] ] {-* ParallelListComp *-}
ys = [ z | z <- [ (x,y) | x <- [1..10] | y <- [1..10] ] ] {-* ParallelListComp *-}
zs = [ [ (x,y) | x <- [1..10] | y <- [1..10] ] | z <- [ (x,y) | x <- [1..10] | y <- [1..10] ] ] {-* ParallelListComp, ParallelListComp *-}
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/test/ExtensionOrganizerTest/ParallelListCompTest/InCompStmt.hs | haskell | # ANN module "HLint: ignore Redundant list comprehension" #
* ParallelListComp *
* ParallelListComp *
* ParallelListComp, ParallelListComp * | # LANGUAGE ParallelListComp #
module InCompStmt where
|
1b67884ec3235a652f8ff79d81977ed8a2f5ba8f492c33d6d76131fdcae02072 | wireapp/wire-server | Event_user.hs | # LANGUAGE OverloadedLists #
-- 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 Test.Wire.API.Golden.Generated.Event_user where
import Data.Domain
import Data.Id (ClientId (ClientId, client), Id (Id))
import Data.Misc (Milliseconds (Ms, ms))
import Data.Qualified
import Data.Range (unsafeRange)
import qualified Data.Set as Set
import Data.Text.Ascii (validate)
import qualified Data.UUID as UUID (fromString)
import Imports
import Wire.API.Conversation
import Wire.API.Conversation.Code (Key (..), Value (..))
import Wire.API.Conversation.Protocol
import Wire.API.Conversation.Role (parseRoleName)
import Wire.API.Conversation.Typing
import Wire.API.Event.Conversation
import Wire.API.Provider.Service (ServiceRef (ServiceRef, _serviceRefId, _serviceRefProvider))
domain :: Domain
domain = Domain "golden.example.com"
testObject_Event_user_1 :: Event
testObject_Event_user_1 =
Event
(Qualified (Id (fromJust (UUID.fromString "00005d81-0000-0d71-0000-1d8f00007d32"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00003b8b-0000-3395-0000-076a00007830"))) (Domain "faraway.example.com"))
(read "1864-05-22 09:51:07.104 UTC")
EdConvDelete
testObject_Event_user_2 :: Event
testObject_Event_user_2 =
Event
(Qualified (Id (fromJust (UUID.fromString "0000064d-0000-7a7f-0000-5749000029e1"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00006a88-0000-2acb-0000-6aa0000061b2"))) (Domain "faraway.example.com"))
(read "1864-06-05 23:01:18.769 UTC")
( EdConvAccessUpdate
( ConversationAccessData
{ cupAccess = [InviteAccess, LinkAccess, PrivateAccess, InviteAccess, InviteAccess],
cupAccessRoles = Set.fromList [TeamMemberAccessRole, GuestAccessRole]
}
)
)
testObject_Event_user_3 :: Event
testObject_Event_user_3 =
Event
(Qualified (Id (fromJust (UUID.fromString "00006f8c-0000-00d6-0000-1568000001e9"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00004b11-0000-5504-0000-55d800002188"))) (Domain "faraway.example.com"))
(read "1864-04-27 15:44:23.844 UTC")
( EdOtrMessage
( OtrMessage
{ otrSender = ClientId {client = "c"},
otrRecipient = ClientId {client = "f"},
otrCiphertext = "",
otrData = Just ">\33032\SI\30584"
}
)
)
testObject_Event_user_4 :: Event
testObject_Event_user_4 =
Event
(Qualified (Id (fromJust (UUID.fromString "00004f04-0000-3939-0000-472d0000316b"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00007c90-0000-766a-0000-01b700002ab7"))) (Domain "faraway.example.com"))
(read "1864-05-12 00:59:09.2 UTC")
EdConvCodeDelete
testObject_Event_user_5 :: Event
testObject_Event_user_5 =
Event
(Qualified (Id (fromJust (UUID.fromString "00003c8c-0000-6394-0000-294b0000098b"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00002a12-0000-73e1-0000-71f700002ec9"))) (Domain "faraway.example.com"))
(read "1864-04-12 03:04:00.298 UTC")
( EdMemberUpdate
( MemberUpdateData
{ misTarget =
Qualified
(Id (fromJust (UUID.fromString "afb0e5b1-c554-4ce4-98f5-3e1671f22485")))
(Domain "target.example.com"),
misOtrMutedStatus = Nothing,
misOtrMutedRef = Just "\94957",
misOtrArchived = Just False,
misOtrArchivedRef = Just "\SOHJ",
misHidden = Nothing,
misHiddenRef = Just "\b\t\CAN",
misConvRoleName =
Just
( fromJust
(parseRoleName "_smrwzjjyq92t3t9u1pettcfiga699uz98rpzdt4lviu8x9iv1di4uiebz2gmrxor2_g0mfzzsfonqvc")
)
}
)
)
testObject_Event_user_6 :: Event
testObject_Event_user_6 =
Event
(Qualified (Id (fromJust (UUID.fromString "00001fdb-0000-3127-0000-23ef00007183"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000705a-0000-0b62-0000-425c000049c8"))) (Domain "faraway.example.com"))
(read "1864-05-09 05:44:41.382 UTC")
(EdConvMessageTimerUpdate (ConversationMessageTimerUpdate {cupMessageTimer = Just (Ms {ms = 5029817038083912})}))
testObject_Event_user_7 :: Event
testObject_Event_user_7 =
Event
(Qualified (Id (fromJust (UUID.fromString "00006ac1-0000-543e-0000-7c8f00000be7"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000355a-0000-2979-0000-083000002d5e"))) (Domain "faraway.example.com"))
(read "1864-04-18 05:01:13.761 UTC")
(EdTyping StoppedTyping)
testObject_Event_user_8 :: Event
testObject_Event_user_8 =
Event
(Qualified (Id (fromJust (UUID.fromString "000019e1-0000-1dc6-0000-68de0000246d"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00000457-0000-0689-0000-77a00000021c"))) (Domain "faraway.example.com"))
(read "1864-05-29 19:31:31.226 UTC")
( EdConversation
( Conversation
{ cnvQualifiedId = Qualified (Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000100000001"))) (Domain "golden.example.com"),
cnvMetadata =
ConversationMetadata
{ cnvmType = RegularConv,
cnvmCreator = Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000200000001")),
cnvmAccess =
[InviteAccess, PrivateAccess, LinkAccess, InviteAccess, InviteAccess, InviteAccess, LinkAccess],
cnvmAccessRoles = Set.fromList [TeamMemberAccessRole, GuestAccessRole, ServiceAccessRole],
cnvmName = Just "\a\SO\r",
cnvmTeam = Just (Id (fromJust (UUID.fromString "00000000-0000-0002-0000-000100000001"))),
cnvmMessageTimer = Just (Ms {ms = 283898987885780}),
cnvmReceiptMode = Just (ReceiptMode {unReceiptMode = -1})
},
cnvProtocol = ProtocolProteus,
cnvMembers =
ConvMembers
{ cmSelf =
Member
{ memId = Qualified (Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000000000001"))) (Domain "golden.example.com"),
memService =
Just
( ServiceRef
{ _serviceRefId =
Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000000000001")),
_serviceRefProvider =
Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000100000001"))
}
),
memOtrMutedStatus = Just (MutedStatus {fromMutedStatus = 0}),
memOtrMutedRef = Just "",
memOtrArchived = True,
memOtrArchivedRef = Just "",
memHidden = True,
memHiddenRef = Just "",
memConvRoleName =
fromJust
(parseRoleName "kf_7rcnb2oilvdmd9nelmwf52gikr4aqkhktyn5vjzg7lq1dnzym812q1innmegmx9a")
},
cmOthers =
[ OtherMember
{ omQualifiedId =
Qualified (Id (fromJust (UUID.fromString "00000000-0000-0001-0000-000100000001"))) domain,
omService = Nothing,
omConvRoleName =
fromJust
( parseRoleName
"4190csbyn6n7ooa8w4d7y9na9_a4m5hgvvmfnowu9zib_29nepamxsxl0gvq2hrfzp7obu_mtj43j0rd38jyd9r5j7xvf2ujge7s0pnt43g9cyal_ak2alwyf8uda"
)
}
]
}
}
)
)
testObject_Event_user_9 :: Event
testObject_Event_user_9 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000b98-0000-618d-0000-19e200004651"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00004bee-0000-45a0-0000-2c0300005726"))) (Domain "faraway.example.com"))
(read "1864-05-01 11:57:35.123 UTC")
(EdConvReceiptModeUpdate (ConversationReceiptModeUpdate {cruReceiptMode = ReceiptMode {unReceiptMode = -10505}}))
testObject_Event_user_10 :: Event
testObject_Event_user_10 =
Event
(Qualified (Id (fromJust (UUID.fromString "00005e43-0000-3b56-0000-7c270000538c"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00007f28-0000-40b1-0000-56ab0000748d"))) (Domain "faraway.example.com"))
(read "1864-05-25 01:31:49.802 UTC")
( EdConnect
( Connect
{ cRecipient =
Qualified
(Id (fromJust (UUID.fromString "00000008-0000-0000-0000-000600000001")))
(Domain "faraway.example.com"),
cMessage = Just "L",
cName = Just "fq",
cEmail = Just "\992986"
}
)
)
testObject_Event_user_11 :: Event
testObject_Event_user_11 =
Event
(Qualified (Id (fromJust (UUID.fromString "0000303b-0000-23a9-0000-25de00002f80"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "000043a6-0000-1627-0000-490300002017"))) (Domain "faraway.example.com"))
(read "1864-04-12 01:28:25.705 UTC")
( EdMembersLeave
( QualifiedUserIdList
{ qualifiedUserIdList =
[ Qualified (Id (fromJust (UUID.fromString "00003fab-0000-40b8-0000-3b0c000014ef"))) (Domain "faraway.example.com"),
Qualified (Id (fromJust (UUID.fromString "00001c48-0000-29ae-0000-62fc00001479"))) (Domain "faraway.example.com")
]
}
)
)
testObject_Event_user_12 :: Event
testObject_Event_user_12 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000838-0000-1bc6-0000-686d00003565"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000114a-0000-7da8-0000-40cb00007fcf"))) (Domain "faraway.example.com"))
(read "1864-05-12 20:29:47.483 UTC")
( EdMembersJoin
( SimpleMembers
{ mMembers =
[ SimpleMember
{ smQualifiedId = Qualified (Id (fromJust (UUID.fromString "00000055-0000-004d-0000-005100000037"))) (Domain "faraway.example.com"),
smConvRoleName = fromJust (parseRoleName "dlkagbmicz0f95d")
},
SimpleMember
{ smQualifiedId = Qualified (Id (fromJust (UUID.fromString "00000001-0000-001f-0000-001500000009"))) (Domain "faraway.example.com"),
smConvRoleName = fromJust (parseRoleName "2e")
}
]
}
)
)
testObject_Event_user_13 :: Event
testObject_Event_user_13 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000838-0000-1bc6-0000-686d00003565"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000114a-0000-7da8-0000-40cb00007fcf"))) (Domain "faraway.example.com"))
(read "1864-05-12 20:29:47.483 UTC")
(EdConvRename (ConversationRename "New conversation name"))
testObject_Event_user_14 :: Event
testObject_Event_user_14 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000838-0000-1bc6-0000-686d00003565"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000114a-0000-7da8-0000-40cb00007fcf"))) (Domain "faraway.example.com"))
(read "1864-05-12 20:29:47.483 UTC")
(EdConvCodeUpdate cc)
where
cc =
ConversationCode
{ conversationKey = Key {asciiKey = unsafeRange (fromRight undefined (validate "NEN=eLUWHXclTp=_2Nap"))},
conversationCode = Value {asciiValue = unsafeRange (fromRight undefined (validate "lLz-9vR8ENum0kI-xWJs"))},
conversationUri = Nothing
}
testObject_Event_user_15 :: Event
testObject_Event_user_15 =
Event
(Qualified (Id (fromJust (UUID.fromString "7cd50991-3cdd-40ec-bb0f-63ae17b2309d"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "04e68c50-027e-4e84-a33a-e2e28a7b8ea3"))) (Domain "faraway.example.com"))
(read "2021-11-10 05:39:44.297 UTC")
(EdMLSMessage "hello world")
testObject_Event_user_16 :: Event
testObject_Event_user_16 =
Event
(Qualified (Id (fromJust (UUID.fromString "6ec1c834-9ae6-4825-8809-61dde80be5ea"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "e8f48b8f-fad3-4f60-98e3-a6df082c328d"))) (Domain "faraway.example.com"))
(read "2021-05-12 13:12:01.005 UTC")
(EdMLSWelcome "welcome message content")
| null | https://raw.githubusercontent.com/wireapp/wire-server/9ab536b4c4915c9a0442c7643f8f78eb953a0217/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/Event_user.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 </>. | # LANGUAGE OverloadedLists #
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 Test.Wire.API.Golden.Generated.Event_user where
import Data.Domain
import Data.Id (ClientId (ClientId, client), Id (Id))
import Data.Misc (Milliseconds (Ms, ms))
import Data.Qualified
import Data.Range (unsafeRange)
import qualified Data.Set as Set
import Data.Text.Ascii (validate)
import qualified Data.UUID as UUID (fromString)
import Imports
import Wire.API.Conversation
import Wire.API.Conversation.Code (Key (..), Value (..))
import Wire.API.Conversation.Protocol
import Wire.API.Conversation.Role (parseRoleName)
import Wire.API.Conversation.Typing
import Wire.API.Event.Conversation
import Wire.API.Provider.Service (ServiceRef (ServiceRef, _serviceRefId, _serviceRefProvider))
domain :: Domain
domain = Domain "golden.example.com"
testObject_Event_user_1 :: Event
testObject_Event_user_1 =
Event
(Qualified (Id (fromJust (UUID.fromString "00005d81-0000-0d71-0000-1d8f00007d32"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00003b8b-0000-3395-0000-076a00007830"))) (Domain "faraway.example.com"))
(read "1864-05-22 09:51:07.104 UTC")
EdConvDelete
testObject_Event_user_2 :: Event
testObject_Event_user_2 =
Event
(Qualified (Id (fromJust (UUID.fromString "0000064d-0000-7a7f-0000-5749000029e1"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00006a88-0000-2acb-0000-6aa0000061b2"))) (Domain "faraway.example.com"))
(read "1864-06-05 23:01:18.769 UTC")
( EdConvAccessUpdate
( ConversationAccessData
{ cupAccess = [InviteAccess, LinkAccess, PrivateAccess, InviteAccess, InviteAccess],
cupAccessRoles = Set.fromList [TeamMemberAccessRole, GuestAccessRole]
}
)
)
testObject_Event_user_3 :: Event
testObject_Event_user_3 =
Event
(Qualified (Id (fromJust (UUID.fromString "00006f8c-0000-00d6-0000-1568000001e9"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00004b11-0000-5504-0000-55d800002188"))) (Domain "faraway.example.com"))
(read "1864-04-27 15:44:23.844 UTC")
( EdOtrMessage
( OtrMessage
{ otrSender = ClientId {client = "c"},
otrRecipient = ClientId {client = "f"},
otrCiphertext = "",
otrData = Just ">\33032\SI\30584"
}
)
)
testObject_Event_user_4 :: Event
testObject_Event_user_4 =
Event
(Qualified (Id (fromJust (UUID.fromString "00004f04-0000-3939-0000-472d0000316b"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00007c90-0000-766a-0000-01b700002ab7"))) (Domain "faraway.example.com"))
(read "1864-05-12 00:59:09.2 UTC")
EdConvCodeDelete
testObject_Event_user_5 :: Event
testObject_Event_user_5 =
Event
(Qualified (Id (fromJust (UUID.fromString "00003c8c-0000-6394-0000-294b0000098b"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00002a12-0000-73e1-0000-71f700002ec9"))) (Domain "faraway.example.com"))
(read "1864-04-12 03:04:00.298 UTC")
( EdMemberUpdate
( MemberUpdateData
{ misTarget =
Qualified
(Id (fromJust (UUID.fromString "afb0e5b1-c554-4ce4-98f5-3e1671f22485")))
(Domain "target.example.com"),
misOtrMutedStatus = Nothing,
misOtrMutedRef = Just "\94957",
misOtrArchived = Just False,
misOtrArchivedRef = Just "\SOHJ",
misHidden = Nothing,
misHiddenRef = Just "\b\t\CAN",
misConvRoleName =
Just
( fromJust
(parseRoleName "_smrwzjjyq92t3t9u1pettcfiga699uz98rpzdt4lviu8x9iv1di4uiebz2gmrxor2_g0mfzzsfonqvc")
)
}
)
)
testObject_Event_user_6 :: Event
testObject_Event_user_6 =
Event
(Qualified (Id (fromJust (UUID.fromString "00001fdb-0000-3127-0000-23ef00007183"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000705a-0000-0b62-0000-425c000049c8"))) (Domain "faraway.example.com"))
(read "1864-05-09 05:44:41.382 UTC")
(EdConvMessageTimerUpdate (ConversationMessageTimerUpdate {cupMessageTimer = Just (Ms {ms = 5029817038083912})}))
testObject_Event_user_7 :: Event
testObject_Event_user_7 =
Event
(Qualified (Id (fromJust (UUID.fromString "00006ac1-0000-543e-0000-7c8f00000be7"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000355a-0000-2979-0000-083000002d5e"))) (Domain "faraway.example.com"))
(read "1864-04-18 05:01:13.761 UTC")
(EdTyping StoppedTyping)
testObject_Event_user_8 :: Event
testObject_Event_user_8 =
Event
(Qualified (Id (fromJust (UUID.fromString "000019e1-0000-1dc6-0000-68de0000246d"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00000457-0000-0689-0000-77a00000021c"))) (Domain "faraway.example.com"))
(read "1864-05-29 19:31:31.226 UTC")
( EdConversation
( Conversation
{ cnvQualifiedId = Qualified (Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000100000001"))) (Domain "golden.example.com"),
cnvMetadata =
ConversationMetadata
{ cnvmType = RegularConv,
cnvmCreator = Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000200000001")),
cnvmAccess =
[InviteAccess, PrivateAccess, LinkAccess, InviteAccess, InviteAccess, InviteAccess, LinkAccess],
cnvmAccessRoles = Set.fromList [TeamMemberAccessRole, GuestAccessRole, ServiceAccessRole],
cnvmName = Just "\a\SO\r",
cnvmTeam = Just (Id (fromJust (UUID.fromString "00000000-0000-0002-0000-000100000001"))),
cnvmMessageTimer = Just (Ms {ms = 283898987885780}),
cnvmReceiptMode = Just (ReceiptMode {unReceiptMode = -1})
},
cnvProtocol = ProtocolProteus,
cnvMembers =
ConvMembers
{ cmSelf =
Member
{ memId = Qualified (Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000000000001"))) (Domain "golden.example.com"),
memService =
Just
( ServiceRef
{ _serviceRefId =
Id (fromJust (UUID.fromString "00000001-0000-0000-0000-000000000001")),
_serviceRefProvider =
Id (fromJust (UUID.fromString "00000000-0000-0000-0000-000100000001"))
}
),
memOtrMutedStatus = Just (MutedStatus {fromMutedStatus = 0}),
memOtrMutedRef = Just "",
memOtrArchived = True,
memOtrArchivedRef = Just "",
memHidden = True,
memHiddenRef = Just "",
memConvRoleName =
fromJust
(parseRoleName "kf_7rcnb2oilvdmd9nelmwf52gikr4aqkhktyn5vjzg7lq1dnzym812q1innmegmx9a")
},
cmOthers =
[ OtherMember
{ omQualifiedId =
Qualified (Id (fromJust (UUID.fromString "00000000-0000-0001-0000-000100000001"))) domain,
omService = Nothing,
omConvRoleName =
fromJust
( parseRoleName
"4190csbyn6n7ooa8w4d7y9na9_a4m5hgvvmfnowu9zib_29nepamxsxl0gvq2hrfzp7obu_mtj43j0rd38jyd9r5j7xvf2ujge7s0pnt43g9cyal_ak2alwyf8uda"
)
}
]
}
}
)
)
testObject_Event_user_9 :: Event
testObject_Event_user_9 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000b98-0000-618d-0000-19e200004651"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00004bee-0000-45a0-0000-2c0300005726"))) (Domain "faraway.example.com"))
(read "1864-05-01 11:57:35.123 UTC")
(EdConvReceiptModeUpdate (ConversationReceiptModeUpdate {cruReceiptMode = ReceiptMode {unReceiptMode = -10505}}))
testObject_Event_user_10 :: Event
testObject_Event_user_10 =
Event
(Qualified (Id (fromJust (UUID.fromString "00005e43-0000-3b56-0000-7c270000538c"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "00007f28-0000-40b1-0000-56ab0000748d"))) (Domain "faraway.example.com"))
(read "1864-05-25 01:31:49.802 UTC")
( EdConnect
( Connect
{ cRecipient =
Qualified
(Id (fromJust (UUID.fromString "00000008-0000-0000-0000-000600000001")))
(Domain "faraway.example.com"),
cMessage = Just "L",
cName = Just "fq",
cEmail = Just "\992986"
}
)
)
testObject_Event_user_11 :: Event
testObject_Event_user_11 =
Event
(Qualified (Id (fromJust (UUID.fromString "0000303b-0000-23a9-0000-25de00002f80"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "000043a6-0000-1627-0000-490300002017"))) (Domain "faraway.example.com"))
(read "1864-04-12 01:28:25.705 UTC")
( EdMembersLeave
( QualifiedUserIdList
{ qualifiedUserIdList =
[ Qualified (Id (fromJust (UUID.fromString "00003fab-0000-40b8-0000-3b0c000014ef"))) (Domain "faraway.example.com"),
Qualified (Id (fromJust (UUID.fromString "00001c48-0000-29ae-0000-62fc00001479"))) (Domain "faraway.example.com")
]
}
)
)
testObject_Event_user_12 :: Event
testObject_Event_user_12 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000838-0000-1bc6-0000-686d00003565"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000114a-0000-7da8-0000-40cb00007fcf"))) (Domain "faraway.example.com"))
(read "1864-05-12 20:29:47.483 UTC")
( EdMembersJoin
( SimpleMembers
{ mMembers =
[ SimpleMember
{ smQualifiedId = Qualified (Id (fromJust (UUID.fromString "00000055-0000-004d-0000-005100000037"))) (Domain "faraway.example.com"),
smConvRoleName = fromJust (parseRoleName "dlkagbmicz0f95d")
},
SimpleMember
{ smQualifiedId = Qualified (Id (fromJust (UUID.fromString "00000001-0000-001f-0000-001500000009"))) (Domain "faraway.example.com"),
smConvRoleName = fromJust (parseRoleName "2e")
}
]
}
)
)
testObject_Event_user_13 :: Event
testObject_Event_user_13 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000838-0000-1bc6-0000-686d00003565"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000114a-0000-7da8-0000-40cb00007fcf"))) (Domain "faraway.example.com"))
(read "1864-05-12 20:29:47.483 UTC")
(EdConvRename (ConversationRename "New conversation name"))
testObject_Event_user_14 :: Event
testObject_Event_user_14 =
Event
(Qualified (Id (fromJust (UUID.fromString "00000838-0000-1bc6-0000-686d00003565"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "0000114a-0000-7da8-0000-40cb00007fcf"))) (Domain "faraway.example.com"))
(read "1864-05-12 20:29:47.483 UTC")
(EdConvCodeUpdate cc)
where
cc =
ConversationCode
{ conversationKey = Key {asciiKey = unsafeRange (fromRight undefined (validate "NEN=eLUWHXclTp=_2Nap"))},
conversationCode = Value {asciiValue = unsafeRange (fromRight undefined (validate "lLz-9vR8ENum0kI-xWJs"))},
conversationUri = Nothing
}
testObject_Event_user_15 :: Event
testObject_Event_user_15 =
Event
(Qualified (Id (fromJust (UUID.fromString "7cd50991-3cdd-40ec-bb0f-63ae17b2309d"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "04e68c50-027e-4e84-a33a-e2e28a7b8ea3"))) (Domain "faraway.example.com"))
(read "2021-11-10 05:39:44.297 UTC")
(EdMLSMessage "hello world")
testObject_Event_user_16 :: Event
testObject_Event_user_16 =
Event
(Qualified (Id (fromJust (UUID.fromString "6ec1c834-9ae6-4825-8809-61dde80be5ea"))) (Domain "faraway.example.com"))
Nothing
(Qualified (Id (fromJust (UUID.fromString "e8f48b8f-fad3-4f60-98e3-a6df082c328d"))) (Domain "faraway.example.com"))
(read "2021-05-12 13:12:01.005 UTC")
(EdMLSWelcome "welcome message content")
|
5bfc7b1211cc068ad939f935da26fd47c52c6b86156391ca747f15ff2ade5ca7 | rabbitmq/rabbitmq-erlang-client | amqp_selective_consumer.erl | 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 /.
%%
Copyright ( c ) 2011 - 2020 VMware , Inc. or its affiliates . All rights reserved .
%%
%% @doc This module is an implementation of the amqp_gen_consumer
behaviour and can be used as part of the Consumer parameter when
%% opening AMQP channels. This is the default implementation selected
%% by channel. <br/>
%% <br/>
%% The Consumer parameter for this implementation is {{@module}, []@}<br/>
%% This consumer implementation keeps track of consumer tags and sends
%% the subscription-relevant messages to the registered consumers, according
%% to an internal tag dictionary.<br/>
%% <br/>
Send a # basic.consume { } message to the channel to subscribe a
consumer to a queue and send a # basic.cancel { } message to cancel a
%% subscription.<br/>
%% <br/>
%% The channel will send to the relevant registered consumers the
basic.consume_ok , basic.cancel_ok , basic.cancel and basic.deliver messages
%% received from the server.<br/>
%% <br/>
%% If a consumer is not registered for a given consumer tag, the message
%% is sent to the default consumer registered with
%% {@module}:register_default_consumer. If there is no default consumer
%% registered in this case, an exception occurs and the channel is abruptly
%% terminated.<br/>
-module(amqp_selective_consumer).
-include("amqp_gen_consumer_spec.hrl").
-behaviour(amqp_gen_consumer).
-export([register_default_consumer/2]).
-export([init/1, handle_consume_ok/3, handle_consume/3, handle_cancel_ok/3,
handle_cancel/2, handle_server_cancel/2,
handle_deliver/3, handle_deliver/4,
handle_info/2, handle_call/3, terminate/2]).
Tag - > ConsumerPid
Pid
monitors = #{}, %% Pid -> {Count, MRef}
default_consumer = none}).
%%---------------------------------------------------------------------------
Interface
%%---------------------------------------------------------------------------
( ChannelPid , ConsumerPid ) - > ok
%% where
%% ChannelPid = pid()
ConsumerPid = pid ( )
%% @doc This function registers a default consumer with the channel. A
%% default consumer is used when a subscription is made via
amqp_channel : call(ChannelPid , # ' basic.consume ' { } ) ( rather than
%% {@module}:subscribe/3) and hence there is no consumer pid
%% registered with the consumer tag. In this case, the relevant
%% deliveries will be sent to the default consumer.
register_default_consumer(ChannelPid, ConsumerPid) ->
amqp_channel:call_consumer(ChannelPid,
{register_default_consumer, ConsumerPid}).
%%---------------------------------------------------------------------------
%% amqp_gen_consumer callbacks
%%---------------------------------------------------------------------------
@private
init([]) ->
{ok, #state{}}.
@private
handle_consume(#'basic.consume'{consumer_tag = Tag,
nowait = NoWait},
Pid, State = #state{consumers = Consumers,
monitors = Monitors}) ->
Result = case NoWait of
true when Tag =:= undefined orelse size(Tag) == 0 ->
no_consumer_tag_specified;
_ when is_binary(Tag) andalso size(Tag) >= 0 ->
case resolve_consumer(Tag, State) of
{consumer, _} -> consumer_tag_in_use;
_ -> ok
end;
_ ->
ok
end,
case {Result, NoWait} of
{ok, true} ->
{ok, State#state
{consumers = maps:put(Tag, Pid, Consumers),
monitors = add_to_monitor_dict(Pid, Monitors)}};
{ok, false} ->
{ok, State#state{unassigned = Pid}};
{Err, true} ->
{error, Err, State};
{_Err, false} ->
%% Don't do anything (don't override existing
%% consumers), the server will close the channel with an error.
{ok, State}
end.
@private
handle_consume_ok(BasicConsumeOk, _BasicConsume,
State = #state{unassigned = Pid,
consumers = Consumers,
monitors = Monitors})
when is_pid(Pid) ->
State1 =
State#state{
consumers = maps:put(tag(BasicConsumeOk), Pid, Consumers),
monitors = add_to_monitor_dict(Pid, Monitors),
unassigned = undefined},
deliver(BasicConsumeOk, State1),
{ok, State1}.
@private
We sent a basic.cancel .
handle_cancel(#'basic.cancel'{nowait = true},
#state{default_consumer = none}) ->
exit(cancel_nowait_requires_default_consumer);
handle_cancel(Cancel = #'basic.cancel'{nowait = NoWait}, State) ->
State1 = case NoWait of
true -> do_cancel(Cancel, State);
false -> State
end,
{ok, State1}.
@private
We sent a basic.cancel and now receive the ok .
handle_cancel_ok(CancelOk, _Cancel, State) ->
State1 = do_cancel(CancelOk, State),
%% Use old state
deliver(CancelOk, State),
{ok, State1}.
@private
The server sent a basic.cancel .
handle_server_cancel(Cancel = #'basic.cancel'{nowait = true}, State) ->
State1 = do_cancel(Cancel, State),
%% Use old state
deliver(Cancel, State),
{ok, State1}.
@private
handle_deliver(Method, Message, State) ->
deliver(Method, Message, State),
{ok, State}.
@private
handle_deliver(Method, Message, DeliveryCtx, State) ->
deliver(Method, Message, DeliveryCtx, State),
{ok, State}.
@private
handle_info({'DOWN', _MRef, process, Pid, _Info},
State = #state{monitors = Monitors,
consumers = Consumers,
default_consumer = DConsumer }) ->
case maps:find(Pid, Monitors) of
{ok, _CountMRef} ->
{ok, State#state{monitors = maps:remove(Pid, Monitors),
consumers =
maps:filter(
fun (_, Pid1) when Pid1 =:= Pid -> false;
(_, _) -> true
end, Consumers)}};
error ->
case Pid of
DConsumer -> {ok, State#state{
monitors = maps:remove(Pid, Monitors),
default_consumer = none}};
_ -> {ok, State} %% unnamed consumer went down
%% before receiving consume_ok
end
end;
handle_info(#'basic.credit_drained'{} = Method, State) ->
deliver_to_consumer_or_die(Method, Method, State),
{ok, State}.
@private
handle_call({register_default_consumer, Pid}, _From,
State = #state{default_consumer = PrevPid,
monitors = Monitors}) ->
Monitors1 = case PrevPid of
none -> Monitors;
_ -> remove_from_monitor_dict(PrevPid, Monitors)
end,
{reply, ok,
State#state{default_consumer = Pid,
monitors = add_to_monitor_dict(Pid, Monitors1)}}.
@private
terminate(_Reason, State) ->
State.
%%---------------------------------------------------------------------------
Internal plumbing
%%---------------------------------------------------------------------------
deliver_to_consumer_or_die(Method, Msg, State) ->
case resolve_consumer(tag(Method), State) of
{consumer, Pid} -> Pid ! Msg;
{default, Pid} -> Pid ! Msg;
error -> exit(unexpected_delivery_and_no_default_consumer)
end.
deliver(Method, State) ->
deliver(Method, undefined, State).
deliver(Method, Message, State) ->
Combined = if Message =:= undefined -> Method;
true -> {Method, Message}
end,
deliver_to_consumer_or_die(Method, Combined, State).
deliver(Method, Message, DeliveryCtx, State) ->
Combined = if Message =:= undefined -> Method;
true -> {Method, Message, DeliveryCtx}
end,
deliver_to_consumer_or_die(Method, Combined, State).
do_cancel(Cancel, State = #state{consumers = Consumers,
monitors = Monitors}) ->
Tag = tag(Cancel),
case maps:find(Tag, Consumers) of
{ok, Pid} -> State#state{
consumers = maps:remove(Tag, Consumers),
monitors = remove_from_monitor_dict(Pid, Monitors)};
error -> %% Untracked consumer. Do nothing.
State
end.
resolve_consumer(Tag, #state{consumers = Consumers,
default_consumer = DefaultConsumer}) ->
case maps:find(Tag, Consumers) of
{ok, ConsumerPid} -> {consumer, ConsumerPid};
error -> case DefaultConsumer of
none -> error;
_ -> {default, DefaultConsumer}
end
end.
tag(#'basic.consume'{consumer_tag = Tag}) -> Tag;
tag(#'basic.consume_ok'{consumer_tag = Tag}) -> Tag;
tag(#'basic.cancel'{consumer_tag = Tag}) -> Tag;
tag(#'basic.cancel_ok'{consumer_tag = Tag}) -> Tag;
tag(#'basic.deliver'{consumer_tag = Tag}) -> Tag;
tag(#'basic.credit_drained'{consumer_tag = Tag}) -> Tag.
add_to_monitor_dict(Pid, Monitors) ->
case maps:find(Pid, Monitors) of
error -> maps:put(Pid,
{1, erlang:monitor(process, Pid)},
Monitors);
{ok, {Count, MRef}} -> maps:put(Pid, {Count + 1, MRef}, Monitors)
end.
remove_from_monitor_dict(Pid, Monitors) ->
case maps:get(Pid, Monitors) of
{1, MRef} -> erlang:demonitor(MRef),
maps:remove(Pid, Monitors);
{Count, MRef} -> maps:put(Pid, {Count - 1, MRef}, Monitors)
end.
| null | https://raw.githubusercontent.com/rabbitmq/rabbitmq-erlang-client/2022e01c515d93ed1883e9e9e987be2e58fe15c9/src/amqp_selective_consumer.erl | erlang |
@doc This module is an implementation of the amqp_gen_consumer
opening AMQP channels. This is the default implementation selected
by channel. <br/>
<br/>
The Consumer parameter for this implementation is {{@module}, []@}<br/>
This consumer implementation keeps track of consumer tags and sends
the subscription-relevant messages to the registered consumers, according
to an internal tag dictionary.<br/>
<br/>
subscription.<br/>
<br/>
The channel will send to the relevant registered consumers the
received from the server.<br/>
<br/>
If a consumer is not registered for a given consumer tag, the message
is sent to the default consumer registered with
{@module}:register_default_consumer. If there is no default consumer
registered in this case, an exception occurs and the channel is abruptly
terminated.<br/>
Pid -> {Count, MRef}
---------------------------------------------------------------------------
---------------------------------------------------------------------------
where
ChannelPid = pid()
@doc This function registers a default consumer with the channel. A
default consumer is used when a subscription is made via
{@module}:subscribe/3) and hence there is no consumer pid
registered with the consumer tag. In this case, the relevant
deliveries will be sent to the default consumer.
---------------------------------------------------------------------------
amqp_gen_consumer callbacks
---------------------------------------------------------------------------
Don't do anything (don't override existing
consumers), the server will close the channel with an error.
Use old state
Use old state
unnamed consumer went down
before receiving consume_ok
---------------------------------------------------------------------------
---------------------------------------------------------------------------
Untracked consumer. Do nothing. | 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 /.
Copyright ( c ) 2011 - 2020 VMware , Inc. or its affiliates . All rights reserved .
behaviour and can be used as part of the Consumer parameter when
Send a # basic.consume { } message to the channel to subscribe a
consumer to a queue and send a # basic.cancel { } message to cancel a
basic.consume_ok , basic.cancel_ok , basic.cancel and basic.deliver messages
-module(amqp_selective_consumer).
-include("amqp_gen_consumer_spec.hrl").
-behaviour(amqp_gen_consumer).
-export([register_default_consumer/2]).
-export([init/1, handle_consume_ok/3, handle_consume/3, handle_cancel_ok/3,
handle_cancel/2, handle_server_cancel/2,
handle_deliver/3, handle_deliver/4,
handle_info/2, handle_call/3, terminate/2]).
Tag - > ConsumerPid
Pid
default_consumer = none}).
Interface
( ChannelPid , ConsumerPid ) - > ok
ConsumerPid = pid ( )
amqp_channel : call(ChannelPid , # ' basic.consume ' { } ) ( rather than
register_default_consumer(ChannelPid, ConsumerPid) ->
amqp_channel:call_consumer(ChannelPid,
{register_default_consumer, ConsumerPid}).
@private
init([]) ->
{ok, #state{}}.
@private
handle_consume(#'basic.consume'{consumer_tag = Tag,
nowait = NoWait},
Pid, State = #state{consumers = Consumers,
monitors = Monitors}) ->
Result = case NoWait of
true when Tag =:= undefined orelse size(Tag) == 0 ->
no_consumer_tag_specified;
_ when is_binary(Tag) andalso size(Tag) >= 0 ->
case resolve_consumer(Tag, State) of
{consumer, _} -> consumer_tag_in_use;
_ -> ok
end;
_ ->
ok
end,
case {Result, NoWait} of
{ok, true} ->
{ok, State#state
{consumers = maps:put(Tag, Pid, Consumers),
monitors = add_to_monitor_dict(Pid, Monitors)}};
{ok, false} ->
{ok, State#state{unassigned = Pid}};
{Err, true} ->
{error, Err, State};
{_Err, false} ->
{ok, State}
end.
@private
handle_consume_ok(BasicConsumeOk, _BasicConsume,
State = #state{unassigned = Pid,
consumers = Consumers,
monitors = Monitors})
when is_pid(Pid) ->
State1 =
State#state{
consumers = maps:put(tag(BasicConsumeOk), Pid, Consumers),
monitors = add_to_monitor_dict(Pid, Monitors),
unassigned = undefined},
deliver(BasicConsumeOk, State1),
{ok, State1}.
@private
We sent a basic.cancel .
handle_cancel(#'basic.cancel'{nowait = true},
#state{default_consumer = none}) ->
exit(cancel_nowait_requires_default_consumer);
handle_cancel(Cancel = #'basic.cancel'{nowait = NoWait}, State) ->
State1 = case NoWait of
true -> do_cancel(Cancel, State);
false -> State
end,
{ok, State1}.
@private
We sent a basic.cancel and now receive the ok .
handle_cancel_ok(CancelOk, _Cancel, State) ->
State1 = do_cancel(CancelOk, State),
deliver(CancelOk, State),
{ok, State1}.
@private
The server sent a basic.cancel .
handle_server_cancel(Cancel = #'basic.cancel'{nowait = true}, State) ->
State1 = do_cancel(Cancel, State),
deliver(Cancel, State),
{ok, State1}.
@private
handle_deliver(Method, Message, State) ->
deliver(Method, Message, State),
{ok, State}.
@private
handle_deliver(Method, Message, DeliveryCtx, State) ->
deliver(Method, Message, DeliveryCtx, State),
{ok, State}.
@private
handle_info({'DOWN', _MRef, process, Pid, _Info},
State = #state{monitors = Monitors,
consumers = Consumers,
default_consumer = DConsumer }) ->
case maps:find(Pid, Monitors) of
{ok, _CountMRef} ->
{ok, State#state{monitors = maps:remove(Pid, Monitors),
consumers =
maps:filter(
fun (_, Pid1) when Pid1 =:= Pid -> false;
(_, _) -> true
end, Consumers)}};
error ->
case Pid of
DConsumer -> {ok, State#state{
monitors = maps:remove(Pid, Monitors),
default_consumer = none}};
end
end;
handle_info(#'basic.credit_drained'{} = Method, State) ->
deliver_to_consumer_or_die(Method, Method, State),
{ok, State}.
@private
handle_call({register_default_consumer, Pid}, _From,
State = #state{default_consumer = PrevPid,
monitors = Monitors}) ->
Monitors1 = case PrevPid of
none -> Monitors;
_ -> remove_from_monitor_dict(PrevPid, Monitors)
end,
{reply, ok,
State#state{default_consumer = Pid,
monitors = add_to_monitor_dict(Pid, Monitors1)}}.
@private
terminate(_Reason, State) ->
State.
Internal plumbing
deliver_to_consumer_or_die(Method, Msg, State) ->
case resolve_consumer(tag(Method), State) of
{consumer, Pid} -> Pid ! Msg;
{default, Pid} -> Pid ! Msg;
error -> exit(unexpected_delivery_and_no_default_consumer)
end.
deliver(Method, State) ->
deliver(Method, undefined, State).
deliver(Method, Message, State) ->
Combined = if Message =:= undefined -> Method;
true -> {Method, Message}
end,
deliver_to_consumer_or_die(Method, Combined, State).
deliver(Method, Message, DeliveryCtx, State) ->
Combined = if Message =:= undefined -> Method;
true -> {Method, Message, DeliveryCtx}
end,
deliver_to_consumer_or_die(Method, Combined, State).
do_cancel(Cancel, State = #state{consumers = Consumers,
monitors = Monitors}) ->
Tag = tag(Cancel),
case maps:find(Tag, Consumers) of
{ok, Pid} -> State#state{
consumers = maps:remove(Tag, Consumers),
monitors = remove_from_monitor_dict(Pid, Monitors)};
State
end.
resolve_consumer(Tag, #state{consumers = Consumers,
default_consumer = DefaultConsumer}) ->
case maps:find(Tag, Consumers) of
{ok, ConsumerPid} -> {consumer, ConsumerPid};
error -> case DefaultConsumer of
none -> error;
_ -> {default, DefaultConsumer}
end
end.
tag(#'basic.consume'{consumer_tag = Tag}) -> Tag;
tag(#'basic.consume_ok'{consumer_tag = Tag}) -> Tag;
tag(#'basic.cancel'{consumer_tag = Tag}) -> Tag;
tag(#'basic.cancel_ok'{consumer_tag = Tag}) -> Tag;
tag(#'basic.deliver'{consumer_tag = Tag}) -> Tag;
tag(#'basic.credit_drained'{consumer_tag = Tag}) -> Tag.
add_to_monitor_dict(Pid, Monitors) ->
case maps:find(Pid, Monitors) of
error -> maps:put(Pid,
{1, erlang:monitor(process, Pid)},
Monitors);
{ok, {Count, MRef}} -> maps:put(Pid, {Count + 1, MRef}, Monitors)
end.
remove_from_monitor_dict(Pid, Monitors) ->
case maps:get(Pid, Monitors) of
{1, MRef} -> erlang:demonitor(MRef),
maps:remove(Pid, Monitors);
{Count, MRef} -> maps:put(Pid, {Count - 1, MRef}, Monitors)
end.
|
5ab4b34d18c50af9b53eb4bed3b3fc6e9fcabdde8f212fbff4bf2aaf92e9e8b2 | aiya000/hs-character-cases | Cases.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE QuasiQuotes #
-- | Exposes naming cases.
module Data.String.Cases where
import Cases.Megaparsec
import Data.Char.Cases
import qualified Data.String as String
import Data.Text.Prettyprint.Doc (Pretty(..))
import Language.Haskell.TH
import Language.Haskell.TH.Quote (QuasiQuoter(..))
import qualified Text.Megaparsec as P
-- $setup
-- >>> :set -XQuasiQuotes
| Non empty PascalCase names " [ A - Z][a - zA - Z0 - 9 ] * "
data Pascal = Pascal UpperChar [AlphaNumChar]
deriving (Show, Eq)
instance Pretty Pascal where
pretty = String.fromString . unPascal
unPascal :: Pascal -> String
unPascal (Pascal x xs) =
upperToChar x : map alphaNumToChar xs
parsePascal :: CodeParsing m => m Pascal
parsePascal =
Pascal <$> upperChar <*> P.many alphaNumChar
-- |
to ' nonEmptyQ ' ,
but naming outsides of ' ' will be rejected .
--
-- >>> [pascalQ|Pascal|]
Pascal P [ AlphaNumAlpha ( AlphaLower A_),AlphaNumAlpha ( AlphaLower S_),AlphaNumAlpha ( AlphaLower C_),AlphaNumAlpha ( AlphaLower A_),AlphaNumAlpha ( AlphaLower L _ ) ]
pascalQ :: QuasiQuoter
pascalQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "pascalQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp upperCharQ) [x]
zs <- mapM (quoteExp alphaNumCharQ) $ map (: []) xs
pure $ ConE (mkName "Pascal") `AppE` z `AppE` ListE zs
-- | Non empty names ".+"
data NonEmpty = NonEmpty Char String
deriving (Show, Eq)
instance Pretty NonEmpty where
pretty = String.fromString . unNonEmpty
unNonEmpty :: NonEmpty -> String
unNonEmpty (NonEmpty x xs) = x : xs
parseNonEmpty :: CodeParsing m => m NonEmpty
parseNonEmpty =
NonEmpty <$> P.anySingle <*> P.many P.anySingle
fromString :: String -> Maybe NonEmpty
fromString "" = Nothing
fromString (x : xs) = Just $ NonEmpty x xs
-- |
-- Makes a non empty string from String on the compile time.
-- Also throws compile error if the empty string is passed.
--
-- >>> [nonEmptyQ|x|]
NonEmpty ' x ' " "
--
-- >>> [nonEmptyQ|foo|]
NonEmpty ' f ' " oo "
--
-- >>> [nonEmptyQ|Bar|]
NonEmpty ' B ' " ar "
nonEmptyQ :: QuasiQuoter
nonEmptyQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "nonEmptyQ required a non empty string, but the empty string is specified."
expQ (x : xs) =
pure $ ConE (mkName "NonEmpty")
`AppE` LitE (CharL x)
`AppE` ListE (map (LitE . CharL) xs)
-- | Non empty camelCase names "[a-zA-Z][a-zA-Z0-9]*"
data Camel = Camel AlphaChar [AlphaNumChar]
deriving (Show, Eq)
instance Pretty Camel where
pretty = String.fromString . unCamel
unCamel :: Camel -> String
unCamel (Camel x xs) = alphaToChar x : map alphaNumToChar xs
parseCamel :: CodeParsing m => m Camel
parseCamel =
Camel <$> alphaChar <*> P.many alphaNumChar
-- |
to ' nonEmptyQ ' ,
but naming outsides of ' Camel ' will be rejected .
--
-- >>> [camelQ|camel|]
-- "camel"
--
-- >>> [camelQ|Pascal|]
" "
camelQ :: QuasiQuoter
camelQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "camelQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp alphaCharQ) [x]
zs <- mapM (quoteExp alphaNumCharQ) $ map (: []) xs
pure $ ConE (mkName "Camel") `AppE` z `AppE` ListE zs
-- | Non empty snake_case names "[a-zA-Z_][a-zA-Z0-9_]*"
data Snake = Snake SnakeHeadChar [SnakeChar]
deriving (Show, Eq)
instance Pretty Snake where
pretty = String.fromString . unSnake
unSnake :: Snake -> String
unSnake (Snake x xs) =
snakeHeadToChar x : map snakeToChar xs
parseSnake :: CodeParsing m => m Snake
parseSnake =
Snake <$>
snakeHeadChar <*>
P.many snakeChar
-- |
to ' nonEmptyQ ' ,
-- but naming outsides of 'Data.String.Cases.Snake' will be rejected.
--
-- >>> [snakeQ|foo_bar|]
Snake ( SnakeHeadAlpha ( AlphaLower F _ ) ) [ SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeUnderscore , ( AlphaNumAlpha ( AlphaLower B_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower A_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower R _ ) ) ]
--
-- >>> [snakeQ|__constructor|]
Snake SnakeHeadUnderscore [ SnakeUnderscore , SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower C_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower N_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower S_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower T_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower R_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower U_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower C_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower T_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower R _ ) ) ]
--
-- >>> [snakeQ|FOO_MEE_9|]
Snake ( SnakeHeadAlpha ( AlphaUpper F ) ) [ SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper O)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper O)),SnakeUnderscore , SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper M)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper E)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper E)),SnakeUnderscore , ( ) ]
snakeQ :: QuasiQuoter
snakeQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "snakeQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp snakeHeadCharQ) [x]
zs <- mapM (quoteExp snakeCharQ) $ map (: []) xs
pure $ ConE (mkName "Snake") `AppE` z `AppE` ListE zs
| A kind of ' Data . String . Cases ' . @[A - Z_][A - Z0 - 9_]*@
data UpperSnake = UpperSnake UpperSnakeHeadChar [UpperSnakeChar]
deriving (Show, Eq)
instance Pretty UpperSnake where
pretty = String.fromString . unUpperSnake
unUpperSnake :: UpperSnake -> String
unUpperSnake (UpperSnake x xs) =
upperSnakeHeadToChar x : map upperSnakeToChar xs
parseUpperSnake :: CodeParsing m => m UpperSnake
parseUpperSnake =
UpperSnake <$>
upperSnakeHeadChar <*>
P.many upperSnakeChar
-- |
-- >>> [upperSnakeQ|FOO_BAR|]
-- UpperSnake (UpperSnakeHeadUpper F) [UpperSnakeUpper O,UpperSnakeUpper O,UpperSnakeUnderscore,UpperSnakeUpper B,UpperSnakeUpper A,UpperSnakeUpper R]
--
-- >>> [upperSnakeQ|__CONSTRUCTOR|]
-- UpperSnake UpperSnakeHeadUnderscore [UpperSnakeUnderscore,UpperSnakeUpper C,UpperSnakeUpper O,UpperSnakeUpper N,UpperSnakeUpper S,UpperSnakeUpper T,UpperSnakeUpper R,UpperSnakeUpper U,UpperSnakeUpper C,UpperSnakeUpper T,UpperSnakeUpper O,UpperSnakeUpper R]
--
-- >>> [upperSnakeQ|__FOO_MEE_9|]
UpperSnake UpperSnakeHeadUnderscore [ UpperSnakeUnderscore , UpperSnakeUpper F , UpperSnakeUpper O , UpperSnakeUpper O , UpperSnakeUnderscore , UpperSnakeUpper M , UpperSnakeUpper E , UpperSnakeUpper E , UpperSnakeUnderscore , UpperSnakeDigit D9 ]
--
-- >>> [upperSnakeQ|FOO_MEE_9|]
UpperSnake ( UpperSnakeHeadUpper F ) [ UpperSnakeUpper O , UpperSnakeUpper O , UpperSnakeUnderscore , UpperSnakeUpper M , UpperSnakeUpper E , UpperSnakeUpper E , UpperSnakeUnderscore , UpperSnakeDigit D9 ]
upperSnakeQ :: QuasiQuoter
upperSnakeQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "upperSnakeQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp upperSnakeHeadCharQ) [x]
zs <- mapM (quoteExp upperSnakeCharQ) $ map (: []) xs
pure $ ConE (mkName "UpperSnake") `AppE` z `AppE` ListE zs
| Non empty " veryflatten " names [ a - z]+
data LowerString = LowerString LowerChar [LowerChar]
deriving (Show, Eq)
instance Pretty LowerString where
pretty (LowerString x xs) = String.fromString $ map lowerToChar (x : xs)
unLowerString :: LowerString -> String
unLowerString (LowerString x xs) = lowerToChar x : map lowerToChar xs
parseLowerString :: CodeParsing m => m LowerString
parseLowerString = LowerString <$> lowerChar <*> P.many lowerChar
-- |
to ' nonEmptyQ ' ,
-- but naming outsides of 'LowerString' will be rejected.
--
-- >>> [lowerStringQ|imavimmer|]
-- LowerString I_ [M_,A_,V_,I_,M_,M_,E_,R_]
lowerStringQ :: QuasiQuoter
lowerStringQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "lowerStringQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp lowerCharQ) [x]
zs <- mapM (quoteExp lowerCharQ) $ map (: []) xs
pure $ ConE (mkName "LowerString") `AppE` z `AppE` ListE zs
| null | https://raw.githubusercontent.com/aiya000/hs-character-cases/3b6156310e7a68ee1ad514f8bc6f590c3c1000a3/src/Data/String/Cases.hs | haskell | # LANGUAGE ConstraintKinds #
| Exposes naming cases.
$setup
>>> :set -XQuasiQuotes
|
>>> [pascalQ|Pascal|]
| Non empty names ".+"
|
Makes a non empty string from String on the compile time.
Also throws compile error if the empty string is passed.
>>> [nonEmptyQ|x|]
>>> [nonEmptyQ|foo|]
>>> [nonEmptyQ|Bar|]
| Non empty camelCase names "[a-zA-Z][a-zA-Z0-9]*"
|
>>> [camelQ|camel|]
"camel"
>>> [camelQ|Pascal|]
| Non empty snake_case names "[a-zA-Z_][a-zA-Z0-9_]*"
|
but naming outsides of 'Data.String.Cases.Snake' will be rejected.
>>> [snakeQ|foo_bar|]
>>> [snakeQ|__constructor|]
>>> [snakeQ|FOO_MEE_9|]
|
>>> [upperSnakeQ|FOO_BAR|]
UpperSnake (UpperSnakeHeadUpper F) [UpperSnakeUpper O,UpperSnakeUpper O,UpperSnakeUnderscore,UpperSnakeUpper B,UpperSnakeUpper A,UpperSnakeUpper R]
>>> [upperSnakeQ|__CONSTRUCTOR|]
UpperSnake UpperSnakeHeadUnderscore [UpperSnakeUnderscore,UpperSnakeUpper C,UpperSnakeUpper O,UpperSnakeUpper N,UpperSnakeUpper S,UpperSnakeUpper T,UpperSnakeUpper R,UpperSnakeUpper U,UpperSnakeUpper C,UpperSnakeUpper T,UpperSnakeUpper O,UpperSnakeUpper R]
>>> [upperSnakeQ|__FOO_MEE_9|]
>>> [upperSnakeQ|FOO_MEE_9|]
|
but naming outsides of 'LowerString' will be rejected.
>>> [lowerStringQ|imavimmer|]
LowerString I_ [M_,A_,V_,I_,M_,M_,E_,R_] | # LANGUAGE PatternSynonyms #
# LANGUAGE QuasiQuotes #
module Data.String.Cases where
import Cases.Megaparsec
import Data.Char.Cases
import qualified Data.String as String
import Data.Text.Prettyprint.Doc (Pretty(..))
import Language.Haskell.TH
import Language.Haskell.TH.Quote (QuasiQuoter(..))
import qualified Text.Megaparsec as P
| Non empty PascalCase names " [ A - Z][a - zA - Z0 - 9 ] * "
data Pascal = Pascal UpperChar [AlphaNumChar]
deriving (Show, Eq)
instance Pretty Pascal where
pretty = String.fromString . unPascal
unPascal :: Pascal -> String
unPascal (Pascal x xs) =
upperToChar x : map alphaNumToChar xs
parsePascal :: CodeParsing m => m Pascal
parsePascal =
Pascal <$> upperChar <*> P.many alphaNumChar
to ' nonEmptyQ ' ,
but naming outsides of ' ' will be rejected .
Pascal P [ AlphaNumAlpha ( AlphaLower A_),AlphaNumAlpha ( AlphaLower S_),AlphaNumAlpha ( AlphaLower C_),AlphaNumAlpha ( AlphaLower A_),AlphaNumAlpha ( AlphaLower L _ ) ]
pascalQ :: QuasiQuoter
pascalQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "pascalQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp upperCharQ) [x]
zs <- mapM (quoteExp alphaNumCharQ) $ map (: []) xs
pure $ ConE (mkName "Pascal") `AppE` z `AppE` ListE zs
data NonEmpty = NonEmpty Char String
deriving (Show, Eq)
instance Pretty NonEmpty where
pretty = String.fromString . unNonEmpty
unNonEmpty :: NonEmpty -> String
unNonEmpty (NonEmpty x xs) = x : xs
parseNonEmpty :: CodeParsing m => m NonEmpty
parseNonEmpty =
NonEmpty <$> P.anySingle <*> P.many P.anySingle
fromString :: String -> Maybe NonEmpty
fromString "" = Nothing
fromString (x : xs) = Just $ NonEmpty x xs
NonEmpty ' x ' " "
NonEmpty ' f ' " oo "
NonEmpty ' B ' " ar "
nonEmptyQ :: QuasiQuoter
nonEmptyQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "nonEmptyQ required a non empty string, but the empty string is specified."
expQ (x : xs) =
pure $ ConE (mkName "NonEmpty")
`AppE` LitE (CharL x)
`AppE` ListE (map (LitE . CharL) xs)
data Camel = Camel AlphaChar [AlphaNumChar]
deriving (Show, Eq)
instance Pretty Camel where
pretty = String.fromString . unCamel
unCamel :: Camel -> String
unCamel (Camel x xs) = alphaToChar x : map alphaNumToChar xs
parseCamel :: CodeParsing m => m Camel
parseCamel =
Camel <$> alphaChar <*> P.many alphaNumChar
to ' nonEmptyQ ' ,
but naming outsides of ' Camel ' will be rejected .
" "
camelQ :: QuasiQuoter
camelQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "camelQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp alphaCharQ) [x]
zs <- mapM (quoteExp alphaNumCharQ) $ map (: []) xs
pure $ ConE (mkName "Camel") `AppE` z `AppE` ListE zs
data Snake = Snake SnakeHeadChar [SnakeChar]
deriving (Show, Eq)
instance Pretty Snake where
pretty = String.fromString . unSnake
unSnake :: Snake -> String
unSnake (Snake x xs) =
snakeHeadToChar x : map snakeToChar xs
parseSnake :: CodeParsing m => m Snake
parseSnake =
Snake <$>
snakeHeadChar <*>
P.many snakeChar
to ' nonEmptyQ ' ,
Snake ( SnakeHeadAlpha ( AlphaLower F _ ) ) [ SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeUnderscore , ( AlphaNumAlpha ( AlphaLower B_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower A_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower R _ ) ) ]
Snake SnakeHeadUnderscore [ SnakeUnderscore , SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower C_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower N_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower S_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower T_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower R_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower U_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower C_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower T_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower O_)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaLower R _ ) ) ]
Snake ( SnakeHeadAlpha ( AlphaUpper F ) ) [ SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper O)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper O)),SnakeUnderscore , SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper M)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper E)),SnakeAlphaNum ( AlphaNumAlpha ( AlphaUpper E)),SnakeUnderscore , ( ) ]
snakeQ :: QuasiQuoter
snakeQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "snakeQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp snakeHeadCharQ) [x]
zs <- mapM (quoteExp snakeCharQ) $ map (: []) xs
pure $ ConE (mkName "Snake") `AppE` z `AppE` ListE zs
| A kind of ' Data . String . Cases ' . @[A - Z_][A - Z0 - 9_]*@
data UpperSnake = UpperSnake UpperSnakeHeadChar [UpperSnakeChar]
deriving (Show, Eq)
instance Pretty UpperSnake where
pretty = String.fromString . unUpperSnake
unUpperSnake :: UpperSnake -> String
unUpperSnake (UpperSnake x xs) =
upperSnakeHeadToChar x : map upperSnakeToChar xs
parseUpperSnake :: CodeParsing m => m UpperSnake
parseUpperSnake =
UpperSnake <$>
upperSnakeHeadChar <*>
P.many upperSnakeChar
UpperSnake UpperSnakeHeadUnderscore [ UpperSnakeUnderscore , UpperSnakeUpper F , UpperSnakeUpper O , UpperSnakeUpper O , UpperSnakeUnderscore , UpperSnakeUpper M , UpperSnakeUpper E , UpperSnakeUpper E , UpperSnakeUnderscore , UpperSnakeDigit D9 ]
UpperSnake ( UpperSnakeHeadUpper F ) [ UpperSnakeUpper O , UpperSnakeUpper O , UpperSnakeUnderscore , UpperSnakeUpper M , UpperSnakeUpper E , UpperSnakeUpper E , UpperSnakeUnderscore , UpperSnakeDigit D9 ]
upperSnakeQ :: QuasiQuoter
upperSnakeQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "upperSnakeQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp upperSnakeHeadCharQ) [x]
zs <- mapM (quoteExp upperSnakeCharQ) $ map (: []) xs
pure $ ConE (mkName "UpperSnake") `AppE` z `AppE` ListE zs
| Non empty " veryflatten " names [ a - z]+
data LowerString = LowerString LowerChar [LowerChar]
deriving (Show, Eq)
instance Pretty LowerString where
pretty (LowerString x xs) = String.fromString $ map lowerToChar (x : xs)
unLowerString :: LowerString -> String
unLowerString (LowerString x xs) = lowerToChar x : map lowerToChar xs
parseLowerString :: CodeParsing m => m LowerString
parseLowerString = LowerString <$> lowerChar <*> P.many lowerChar
to ' nonEmptyQ ' ,
lowerStringQ :: QuasiQuoter
lowerStringQ = QuasiQuoter
{ quoteExp = expQ
, quotePat = error "not supported"
, quoteType = error "not supported"
, quoteDec = error "not supported"
}
where
expQ :: String -> Q Exp
expQ [] = fail "lowerStringQ required a non empty string, but the empty string is specified."
expQ (x : xs) = do
z <- (quoteExp lowerCharQ) [x]
zs <- mapM (quoteExp lowerCharQ) $ map (: []) xs
pure $ ConE (mkName "LowerString") `AppE` z `AppE` ListE zs
|
701c4ff791658ecff442af7967c3089d499e0f7a0567dba35069900f886ce5a0 | fccm/glMLite | stencil.ml | Copyright ( c ) , 1994 .
( c ) Copyright 1993 , Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use , copy , modify , and distribute this software for
* any purpose and without fee is hereby granted , provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation , and that
* the name of Silicon Graphics , Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific ,
* written prior permission .
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS "
* AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE ,
* INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON
* GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT ,
* SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION ,
* LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF
* THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE .
*
* US Government Users Restricted Rights
* Use , duplication , or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph
* ( c)(1)(ii ) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227 - 7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement .
* Unpublished-- rights reserved under the copyright laws of the
* United States . Contractor / manufacturer is Silicon Graphics ,
* Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 .
*
* OpenGL(TM ) is a trademark of Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*)
stencil.ml
* This program draws two rotated tori in a window .
* A diamond in the center of the window masks out part
* of the scene . Within this mask , a different model
* ( a sphere ) is drawn in a different color .
* This program draws two rotated tori in a window.
* A diamond in the center of the window masks out part
* of the scene. Within this mask, a different model
* (a sphere) is drawn in a different color.
*)
(* !!! NOTE !!!
*
* This demo is poorly written. The stencil buffer should be
* redrawn in display(), not in the reshape() function.
* The reason is if the window gets "damaged" then the stencil buffer
* contents will be in an undefined state (reshape is not called when
* a window is damaged and needs to be redrawn). If the stencil buffer
* contents are undefined, the results of display() are unpredictable.
*
* -Brian
*)
OCaml version by
open GL
open Glu
open Glut
let yellow_mat = 1
let blue_mat = 2
let myinit () =
let yellow_diffuse = (0.7, 0.7, 0.0, 1.0)
and yellow_specular = (1.0, 1.0, 1.0, 1.0)
and blue_diffuse = (0.1, 0.1, 0.7, 1.0)
and blue_specular = (0.1, 1.0, 1.0, 1.0)
and position_one = (1.0, 1.0, 1.0, 0.0) in
glNewList yellow_mat GL_COMPILE;
glMaterial GL_FRONT (Material.GL_DIFFUSE yellow_diffuse);
glMaterial GL_FRONT (Material.GL_SPECULAR yellow_specular);
glMaterial GL_FRONT (Material.GL_SHININESS 64.0);
glEndList();
glNewList blue_mat GL_COMPILE;
glMaterial GL_FRONT (Material.GL_DIFFUSE blue_diffuse);
glMaterial GL_FRONT (Material.GL_SPECULAR blue_specular);
glMaterial GL_FRONT (Material.GL_SHININESS 45.0);
glEndList();
glLight (GL_LIGHT 0) (Light.GL_POSITION position_one);
glEnable GL_LIGHT0;
glEnable GL_LIGHTING;
glDepthFunc GL_LESS;
glEnable GL_DEPTH_TEST;
glClearStencil 0x0;
glEnable GL_STENCIL_TEST;
;;
Draw a sphere in a diamond - shaped section in the
* middle of a window with 2 tori .
* middle of a window with 2 tori.
*)
let display() =
glClear[GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
glStencilOp GL_KEEP GL_KEEP GL_KEEP;
draw blue sphere where the stencil is 1
glStencilFunc GL_EQUAL 0x1 0x1;
glCallList blue_mat;
glutSolidSphere 0.5 15 15;
draw the tori where the stencil is not 1
glStencilFunc GL_NOTEQUAL 0x1 0x1;
glPushMatrix();
glRotate 45.0 0.0 0.0 1.0;
glRotate 45.0 0.0 1.0 0.0;
glCallList yellow_mat;
glutSolidTorus 0.275 0.85 15 15;
glPushMatrix();
glRotate 90.0 1.0 0.0 0.0;
glutSolidTorus 0.275 0.85 15 15;
glPopMatrix();
glPopMatrix();
glFlush();
glutSwapBuffers();
;;
(* Whenever the window is reshaped, redefine the
* coordinate system and redraw the stencil area.
*)
let reshape ~width:w ~height:h =
glViewport 0 0 w h;
glClear [GL_STENCIL_BUFFER_BIT];
(* create a diamond shaped stencil area *)
glMatrixMode GL_PROJECTION;
glLoadIdentity();
glOrtho(-3.0) (3.0) (-3.0) (3.0) (-1.0) (1.0);
glMatrixMode GL_MODELVIEW;
glLoadIdentity();
glStencilFunc GL_ALWAYS 0x1 0x1;
glStencilOp GL_REPLACE GL_REPLACE GL_REPLACE;
glBegin GL_QUADS;
glVertex2 (-1.0) ( 0.0);
glVertex2 ( 0.0) ( 1.0);
glVertex2 ( 1.0) ( 0.0);
glVertex2 ( 0.0) (-1.0);
glEnd();
glMatrixMode GL_PROJECTION;
glLoadIdentity();
gluPerspective 45.0 ((float w)/.(float h)) 3.0 7.0;
glMatrixMode GL_MODELVIEW;
glLoadIdentity();
glTranslate 0.0 0.0 (-5.0);
;;
let keyboard ~key ~x ~y =
begin match key with
| '\027' -> (* Escape *)
exit 0;
| _ -> ()
end;
glutPostRedisplay();
;;
Main Loop
* Open window with initial window size , title bar ,
* RGBA display mode , and handle input events .
* Open window with initial window size, title bar,
* RGBA display mode, and handle input events.
*)
let () =
ignore(glutInit Sys.argv);
glutInitDisplayMode [GLUT_DOUBLE; GLUT_RGB; GLUT_DEPTH; GLUT_STENCIL];
glutInitWindowSize 400 400;
ignore(glutCreateWindow Sys.argv.(0));
myinit();
glutReshapeFunc ~reshape;
glutDisplayFunc ~display;
glutKeyboardFunc ~keyboard;
glutMainLoop();
;;
| null | https://raw.githubusercontent.com/fccm/glMLite/c52cd806909581e49d9b660195576c8a932f6d33/RedBook-Samples/stencil.ml | ocaml | !!! NOTE !!!
*
* This demo is poorly written. The stencil buffer should be
* redrawn in display(), not in the reshape() function.
* The reason is if the window gets "damaged" then the stencil buffer
* contents will be in an undefined state (reshape is not called when
* a window is damaged and needs to be redrawn). If the stencil buffer
* contents are undefined, the results of display() are unpredictable.
*
* -Brian
Whenever the window is reshaped, redefine the
* coordinate system and redraw the stencil area.
create a diamond shaped stencil area
Escape | Copyright ( c ) , 1994 .
( c ) Copyright 1993 , Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use , copy , modify , and distribute this software for
* any purpose and without fee is hereby granted , provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation , and that
* the name of Silicon Graphics , Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific ,
* written prior permission .
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU " AS - IS "
* AND WITHOUT WARRANTY OF ANY KIND , EXPRESS , IMPLIED OR OTHERWISE ,
* INCLUDING WITHOUT LIMITATION , ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE . IN NO EVENT SHALL SILICON
* GRAPHICS , INC . BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT ,
* SPECIAL , INCIDENTAL , INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND , OR ANY DAMAGES WHATSOEVER , INCLUDING WITHOUT LIMITATION ,
* LOSS OF PROFIT , LOSS OF USE , SAVINGS OR REVENUE , OR THE CLAIMS OF
* THIRD PARTIES , WHETHER OR NOT SILICON GRAPHICS , INC . HAS * ADVISED OF THE POSSIBILITY OF SUCH LOSS , HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY , ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION , USE OR PERFORMANCE OF THIS SOFTWARE .
*
* US Government Users Restricted Rights
* Use , duplication , or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2 ) or subparagraph
* ( c)(1)(ii ) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227 - 7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement .
* Unpublished-- rights reserved under the copyright laws of the
* United States . Contractor / manufacturer is Silicon Graphics ,
* Inc. , 2011 N. Shoreline Blvd . , Mountain View , CA 94039 - 7311 .
*
* OpenGL(TM ) is a trademark of Silicon Graphics , Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*)
stencil.ml
* This program draws two rotated tori in a window .
* A diamond in the center of the window masks out part
* of the scene . Within this mask , a different model
* ( a sphere ) is drawn in a different color .
* This program draws two rotated tori in a window.
* A diamond in the center of the window masks out part
* of the scene. Within this mask, a different model
* (a sphere) is drawn in a different color.
*)
OCaml version by
open GL
open Glu
open Glut
let yellow_mat = 1
let blue_mat = 2
let myinit () =
let yellow_diffuse = (0.7, 0.7, 0.0, 1.0)
and yellow_specular = (1.0, 1.0, 1.0, 1.0)
and blue_diffuse = (0.1, 0.1, 0.7, 1.0)
and blue_specular = (0.1, 1.0, 1.0, 1.0)
and position_one = (1.0, 1.0, 1.0, 0.0) in
glNewList yellow_mat GL_COMPILE;
glMaterial GL_FRONT (Material.GL_DIFFUSE yellow_diffuse);
glMaterial GL_FRONT (Material.GL_SPECULAR yellow_specular);
glMaterial GL_FRONT (Material.GL_SHININESS 64.0);
glEndList();
glNewList blue_mat GL_COMPILE;
glMaterial GL_FRONT (Material.GL_DIFFUSE blue_diffuse);
glMaterial GL_FRONT (Material.GL_SPECULAR blue_specular);
glMaterial GL_FRONT (Material.GL_SHININESS 45.0);
glEndList();
glLight (GL_LIGHT 0) (Light.GL_POSITION position_one);
glEnable GL_LIGHT0;
glEnable GL_LIGHTING;
glDepthFunc GL_LESS;
glEnable GL_DEPTH_TEST;
glClearStencil 0x0;
glEnable GL_STENCIL_TEST;
;;
Draw a sphere in a diamond - shaped section in the
* middle of a window with 2 tori .
* middle of a window with 2 tori.
*)
let display() =
glClear[GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
glStencilOp GL_KEEP GL_KEEP GL_KEEP;
draw blue sphere where the stencil is 1
glStencilFunc GL_EQUAL 0x1 0x1;
glCallList blue_mat;
glutSolidSphere 0.5 15 15;
draw the tori where the stencil is not 1
glStencilFunc GL_NOTEQUAL 0x1 0x1;
glPushMatrix();
glRotate 45.0 0.0 0.0 1.0;
glRotate 45.0 0.0 1.0 0.0;
glCallList yellow_mat;
glutSolidTorus 0.275 0.85 15 15;
glPushMatrix();
glRotate 90.0 1.0 0.0 0.0;
glutSolidTorus 0.275 0.85 15 15;
glPopMatrix();
glPopMatrix();
glFlush();
glutSwapBuffers();
;;
let reshape ~width:w ~height:h =
glViewport 0 0 w h;
glClear [GL_STENCIL_BUFFER_BIT];
glMatrixMode GL_PROJECTION;
glLoadIdentity();
glOrtho(-3.0) (3.0) (-3.0) (3.0) (-1.0) (1.0);
glMatrixMode GL_MODELVIEW;
glLoadIdentity();
glStencilFunc GL_ALWAYS 0x1 0x1;
glStencilOp GL_REPLACE GL_REPLACE GL_REPLACE;
glBegin GL_QUADS;
glVertex2 (-1.0) ( 0.0);
glVertex2 ( 0.0) ( 1.0);
glVertex2 ( 1.0) ( 0.0);
glVertex2 ( 0.0) (-1.0);
glEnd();
glMatrixMode GL_PROJECTION;
glLoadIdentity();
gluPerspective 45.0 ((float w)/.(float h)) 3.0 7.0;
glMatrixMode GL_MODELVIEW;
glLoadIdentity();
glTranslate 0.0 0.0 (-5.0);
;;
let keyboard ~key ~x ~y =
begin match key with
exit 0;
| _ -> ()
end;
glutPostRedisplay();
;;
Main Loop
* Open window with initial window size , title bar ,
* RGBA display mode , and handle input events .
* Open window with initial window size, title bar,
* RGBA display mode, and handle input events.
*)
let () =
ignore(glutInit Sys.argv);
glutInitDisplayMode [GLUT_DOUBLE; GLUT_RGB; GLUT_DEPTH; GLUT_STENCIL];
glutInitWindowSize 400 400;
ignore(glutCreateWindow Sys.argv.(0));
myinit();
glutReshapeFunc ~reshape;
glutDisplayFunc ~display;
glutKeyboardFunc ~keyboard;
glutMainLoop();
;;
|
4f92ad2866e219377721318b50bf3b3195d807c9e3973fbea03de9cfd3f2e57b | juspay/atlas | Main.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import App (runMockSms)
import EulerHS.Prelude
main :: IO ()
main = runMockSms id
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/mock-sms/server/Main.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import App (runMockSms)
import EulerHS.Prelude
main :: IO ()
main = runMockSms id
|
|
e1a5ac65610f8037340394c4c74b04b5976322ed6928c8ddca4335f11c73e052 | potapenko/playphraseme-site | delete_user.clj | (ns playphraseme.api.route-functions.user.delete-user
(:require [playphraseme.api.queries.user.registered-user :as users]
[ring.util.http-response :as respond]))
(defn delete-user
"Delete a user by ID"
[id]
(let [deleted-user (users/delete-registered-user! {:id id})]
(if (not= 0 deleted-user)
(respond/ok {:message (format "User id %s successfully removed" id)})
(respond/not-found {:error "Userid does not exist"}))))
(defn delete-user-response
"Generate response for user deletion"
[request id]
(let [auth (get-in request [:identity :permissions])
deleting-self? (= (str id) (get-in request [:identity :id]))]
(if (or (.contains auth "admin") deleting-self?)
(delete-user id)
(respond/unauthorized {:error "Not authorized"}))))
| null | https://raw.githubusercontent.com/potapenko/playphraseme-site/d50a62a6bc8f463e08365dca96b3a6e5dde4fb12/src/clj/playphraseme/api/route_functions/user/delete_user.clj | clojure | (ns playphraseme.api.route-functions.user.delete-user
(:require [playphraseme.api.queries.user.registered-user :as users]
[ring.util.http-response :as respond]))
(defn delete-user
"Delete a user by ID"
[id]
(let [deleted-user (users/delete-registered-user! {:id id})]
(if (not= 0 deleted-user)
(respond/ok {:message (format "User id %s successfully removed" id)})
(respond/not-found {:error "Userid does not exist"}))))
(defn delete-user-response
"Generate response for user deletion"
[request id]
(let [auth (get-in request [:identity :permissions])
deleting-self? (= (str id) (get-in request [:identity :id]))]
(if (or (.contains auth "admin") deleting-self?)
(delete-user id)
(respond/unauthorized {:error "Not authorized"}))))
|
|
bbb7319f7c616c70d25fa2266c9e6dd550e4b038cd52815aaf2525f7d75c2a82 | shayan-najd/NativeMetaprogramming | T11824.hs | import Type
main :: IO ()
main = return ()
| null | https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/testsuite/tests/typecheck/T11824/T11824.hs | haskell | import Type
main :: IO ()
main = return ()
|
|
1839d050a3473ffb93413b089d04d79134ec40d1b8fe82b693b53cbd64c6d440 | nyu-acsys/drift | repeat4.ml |
let succ sx = sx + 1
let rec repeat (rf: int -> int) rn =
if rn = 0
then 0
else rf (repeat rf (rn - 1))
let main_p (n:int) =
assert (repeat succ n = n)
let main (w:unit) =
let _ = main_p 15 in
let _ =
for i = 1 to 1000000 do
main ( Random.int 1000 )
done
for i = 1 to 1000000 do
main (Random.int 1000)
done *)
()
let _ = main () | null | https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks_call/r_type/high/repeat4.ml | ocaml |
let succ sx = sx + 1
let rec repeat (rf: int -> int) rn =
if rn = 0
then 0
else rf (repeat rf (rn - 1))
let main_p (n:int) =
assert (repeat succ n = n)
let main (w:unit) =
let _ = main_p 15 in
let _ =
for i = 1 to 1000000 do
main ( Random.int 1000 )
done
for i = 1 to 1000000 do
main (Random.int 1000)
done *)
()
let _ = main () |
|
d884e0a90789911e89c69072e88b1ae193f80e35e708afa5cfb2335551cf3e3e | avisi/rsync | core.clj | (ns avisi.rsync.core
(:require [avisi.rsync.location :as l]
[avisi.rsync.local-dir :as dir]
[avisi.rsync.s3-bucket :as s3]
[amazonica.aws.s3 :as aws-s3]
[clojure.tools.logging :as log]
[clojure.data :as data]
[clojure.string :as str]))
(defn contains-path?
[path coll]
(true? (some #(= path (:path %)) coll)))
(defmulti location (fn [url] (keyword (first (str/split url #"://")))))
(defmethod location :s3
[url]
(s3/new-s3-location (s3/s3-url->bucket-name url) (s3/s3-url->key url)))
(defmethod location :file
[url]
(dir/new-directory-location (dir/file-url->file-name url)))
(defn left-to-right
[paths left-location right-location]
(doseq [path paths]
(log/debug "copying file" path)
(with-open [input-stream (l/read left-location path)]
(l/write right-location path input-stream))))
(defn delete
[paths location]
(doseq [path paths]
(l/delete location path)))
(defn dry-run?
[options]
(true? (:dry-run options)))
(defn sync!
"sync two folders, one or both possibly being remote"
[from-url to-url options]
(let [from-location (location from-url)
to-location (location to-url)
_ (log/debug "analysing from location")
from-set (l/analyse from-location)
_ (log/debug "analysing to location")
to-set (l/analyse to-location)
_ (log/debug "diffing results")
diff (data/diff from-set to-set)
to-be-deleted (filter #(not (contains-path? (:path %) (first diff))) (second diff))
to-be-copied (filter #(not (contains-path? (:path %) (second diff))) (first diff))
to-be-updated (filter #(contains-path? (:path %) (second diff)) (first diff))]
(if (not (dry-run? options))
(do
(log/debug "copying new files")
(left-to-right to-be-copied from-location to-location)
(log/debug "updating existing files")
(left-to-right to-be-updated from-location to-location)
(log/debug "deleting redundant files")
(delete to-be-deleted to-location)))
{:deleted to-be-deleted
:copied to-be-copied
:updated to-be-updated}))
| null | https://raw.githubusercontent.com/avisi/rsync/e8b6b440b6a51bf7001fa602d6dc367f13942699/src/avisi/rsync/core.clj | clojure | (ns avisi.rsync.core
(:require [avisi.rsync.location :as l]
[avisi.rsync.local-dir :as dir]
[avisi.rsync.s3-bucket :as s3]
[amazonica.aws.s3 :as aws-s3]
[clojure.tools.logging :as log]
[clojure.data :as data]
[clojure.string :as str]))
(defn contains-path?
[path coll]
(true? (some #(= path (:path %)) coll)))
(defmulti location (fn [url] (keyword (first (str/split url #"://")))))
(defmethod location :s3
[url]
(s3/new-s3-location (s3/s3-url->bucket-name url) (s3/s3-url->key url)))
(defmethod location :file
[url]
(dir/new-directory-location (dir/file-url->file-name url)))
(defn left-to-right
[paths left-location right-location]
(doseq [path paths]
(log/debug "copying file" path)
(with-open [input-stream (l/read left-location path)]
(l/write right-location path input-stream))))
(defn delete
[paths location]
(doseq [path paths]
(l/delete location path)))
(defn dry-run?
[options]
(true? (:dry-run options)))
(defn sync!
"sync two folders, one or both possibly being remote"
[from-url to-url options]
(let [from-location (location from-url)
to-location (location to-url)
_ (log/debug "analysing from location")
from-set (l/analyse from-location)
_ (log/debug "analysing to location")
to-set (l/analyse to-location)
_ (log/debug "diffing results")
diff (data/diff from-set to-set)
to-be-deleted (filter #(not (contains-path? (:path %) (first diff))) (second diff))
to-be-copied (filter #(not (contains-path? (:path %) (second diff))) (first diff))
to-be-updated (filter #(contains-path? (:path %) (second diff)) (first diff))]
(if (not (dry-run? options))
(do
(log/debug "copying new files")
(left-to-right to-be-copied from-location to-location)
(log/debug "updating existing files")
(left-to-right to-be-updated from-location to-location)
(log/debug "deleting redundant files")
(delete to-be-deleted to-location)))
{:deleted to-be-deleted
:copied to-be-copied
:updated to-be-updated}))
|
|
cbc5c1e0d293553100ca6a0720ddef29976da052a64b4637b9ece12e563de404 | mzp/scheme-abc | link.ml | open Base
open Swflib.AbcType
let method_sigs n ms =
List.map (fun m -> {m with method_sig= n + m.method_sig} ) ms
let link a1 a2 =
let ctx = {|
int = (+) @@ List.length a1.cpool.int;
uint = (+) @@ List.length a1.cpool.uint;
double = (+) @@ List.length a1.cpool.double;
string = (+) @@ List.length a1.cpool.string;
namespace = (+) @@ List.length a1.cpool.namespace;
namespace_set = (+) @@ List.length a1.cpool.namespace_set;
multiname = (fun i -> if i = 0 then 0 else i + List.length a1.cpool.multiname);
methods = (+) @@ List.length a1.method_info;
classes = (+) @@ List.length a1.classes
|} in
let a2 =
Reloc.do_abc ctx a2 in
{a1 with
cpool = {
int = a1.cpool.int @ a2.cpool.int;
uint = a1.cpool.uint @ a2.cpool.uint;
double = a1.cpool.double @ a2.cpool.double;
string = a1.cpool.string @ a2.cpool.string;
namespace = a1.cpool.namespace @ a2.cpool.namespace;
namespace_set = a1.cpool.namespace_set @ a2.cpool.namespace_set;
multiname = a1.cpool.multiname @ a2.cpool.multiname
};
method_info = a1.method_info @ a2.method_info;
method_bodies = a1.method_bodies @ method_sigs (List.length a1.method_info) a2.method_bodies;
scripts = a1.scripts @ a2.scripts;
classes = a1.classes @ a2.classes;
instances = a1.instances @ a2.instances;
}
| null | https://raw.githubusercontent.com/mzp/scheme-abc/2cb541159bcc32ae4d033793dea6e6828566d503/link/link.ml | ocaml | open Base
open Swflib.AbcType
let method_sigs n ms =
List.map (fun m -> {m with method_sig= n + m.method_sig} ) ms
let link a1 a2 =
let ctx = {|
int = (+) @@ List.length a1.cpool.int;
uint = (+) @@ List.length a1.cpool.uint;
double = (+) @@ List.length a1.cpool.double;
string = (+) @@ List.length a1.cpool.string;
namespace = (+) @@ List.length a1.cpool.namespace;
namespace_set = (+) @@ List.length a1.cpool.namespace_set;
multiname = (fun i -> if i = 0 then 0 else i + List.length a1.cpool.multiname);
methods = (+) @@ List.length a1.method_info;
classes = (+) @@ List.length a1.classes
|} in
let a2 =
Reloc.do_abc ctx a2 in
{a1 with
cpool = {
int = a1.cpool.int @ a2.cpool.int;
uint = a1.cpool.uint @ a2.cpool.uint;
double = a1.cpool.double @ a2.cpool.double;
string = a1.cpool.string @ a2.cpool.string;
namespace = a1.cpool.namespace @ a2.cpool.namespace;
namespace_set = a1.cpool.namespace_set @ a2.cpool.namespace_set;
multiname = a1.cpool.multiname @ a2.cpool.multiname
};
method_info = a1.method_info @ a2.method_info;
method_bodies = a1.method_bodies @ method_sigs (List.length a1.method_info) a2.method_bodies;
scripts = a1.scripts @ a2.scripts;
classes = a1.classes @ a2.classes;
instances = a1.instances @ a2.instances;
}
|
|
f23fb1e4b2653ecc8f99fe9193930bdd06dae3abbff893c7c90efe6c0686a75c | klarna-incubator/bec | bec_project_t.erl | %%==============================================================================
Type definition for the Project data structure
%%==============================================================================
-module(bec_project_t).
%%==============================================================================
%% Exports
%%==============================================================================
-export([ from_map/1, to_map/1]).
-include("bitbucket.hrl").
%%==============================================================================
%% Types
%%==============================================================================
-type project() :: #{ }.
%%==============================================================================
%% Export Types
%%==============================================================================
-export_type([ project/0
]).
%%==============================================================================
%% API
%%==============================================================================
-spec from_map(map()) -> project().
from_map(#{}) ->
#{}.
-spec to_map(project()) -> map().
to_map(#{}) ->
#{}.
| null | https://raw.githubusercontent.com/klarna-incubator/bec/b090bfbeeff298b4fc40e16a9da217f2ce404844/src/bec_project_t.erl | erlang | ==============================================================================
==============================================================================
==============================================================================
Exports
==============================================================================
==============================================================================
Types
==============================================================================
==============================================================================
Export Types
==============================================================================
==============================================================================
API
============================================================================== | Type definition for the Project data structure
-module(bec_project_t).
-export([ from_map/1, to_map/1]).
-include("bitbucket.hrl").
-type project() :: #{ }.
-export_type([ project/0
]).
-spec from_map(map()) -> project().
from_map(#{}) ->
#{}.
-spec to_map(project()) -> map().
to_map(#{}) ->
#{}.
|
06c4b716d40e31660950f09b573068e00fddfe8bbf6c388b8f2fd3f9bb426558 | tmcgilchrist/airship | Headers.hs | {-# LANGUAGE RankNTypes #-}
module Airship.Headers
( addResponseHeader
, modifyResponseHeaders
) where
import Airship.Types (Webmachine, ResponseState(..))
import Control.Monad.State.Class (modify)
import Network.HTTP.Types (ResponseHeaders, Header)
-- | Applies the given function to the 'ResponseHeaders' present in this handlers 'ResponseState'.
modifyResponseHeaders :: Monad m => (ResponseHeaders -> ResponseHeaders) -> Webmachine m ()
modifyResponseHeaders f = modify updateHeaders
where updateHeaders rs@ResponseState{stateHeaders = h} = rs { stateHeaders = f h }
| Adds a given ' Header ' to this handler 's ' ResponseState ' .
addResponseHeader :: Monad m => Header -> Webmachine m ()
addResponseHeader h = modifyResponseHeaders (h :)
| null | https://raw.githubusercontent.com/tmcgilchrist/airship/e946ac322f5f9ec0ceebcee593caacc9ea0b05ec/airship/src/Airship/Headers.hs | haskell | # LANGUAGE RankNTypes #
| Applies the given function to the 'ResponseHeaders' present in this handlers 'ResponseState'. |
module Airship.Headers
( addResponseHeader
, modifyResponseHeaders
) where
import Airship.Types (Webmachine, ResponseState(..))
import Control.Monad.State.Class (modify)
import Network.HTTP.Types (ResponseHeaders, Header)
modifyResponseHeaders :: Monad m => (ResponseHeaders -> ResponseHeaders) -> Webmachine m ()
modifyResponseHeaders f = modify updateHeaders
where updateHeaders rs@ResponseState{stateHeaders = h} = rs { stateHeaders = f h }
| Adds a given ' Header ' to this handler 's ' ResponseState ' .
addResponseHeader :: Monad m => Header -> Webmachine m ()
addResponseHeader h = modifyResponseHeaders (h :)
|
d53f2ce217d9ae9a0dbd426fafd338de2011699ee5f0f490b73c21de2129cb2f | logicmoo/wam_common_lisp | dlap.lisp | -*-Mode : LISP ; Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*-
;;;
;;; *************************************************************************
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
;;; All rights reserved.
;;;
;;; Use and copying of this software and preparation of derivative works
;;; based upon this software are permitted. Any distribution of this
software or derivative works must comply with all applicable United
;;; States export control laws.
;;;
This software is made available AS IS , and Xerox Corporation makes no
;;; warranty about the software, its performance or its conformity to any
;;; specification.
;;;
;;; Any person obtaining a copy of this software is requested to send their
;;; name and post office or electronic mail address to:
CommonLoops Coordinator
Xerox PARC
3333 Coyote Hill Rd .
Palo Alto , CA 94304
( or send Arpanet mail to )
;;;
;;; Suggestions, comments and requests for improvements are also welcome.
;;; *************************************************************************
;;;
(in-package 'pcl)
(defun emit-one-class-reader (class-slot-p) (emit-reader/writer :reader 1 class-slot-p))
(defun emit-one-class-writer (class-slot-p) (emit-reader/writer :writer 1 class-slot-p))
(defun emit-two-class-reader (class-slot-p) (emit-reader/writer :reader 2 class-slot-p))
(defun emit-two-class-writer (class-slot-p) (emit-reader/writer :writer 2 class-slot-p))
(defun emit-reader/writer (reader/writer 1-or-2-class class-slot-p)
(declare (type index 1-or-2-class)
(type boolean class-slot-p))
(let ((instance nil)
(arglist ())
(closure-variables ())
(field (first-wrapper-cache-number-index))) ;we need some field to do
;the fast obsolete check
(ecase reader/writer
(:reader (setq instance (dfun-arg-symbol 0)
arglist (list instance)))
(:writer (setq instance (dfun-arg-symbol 1)
arglist (list (dfun-arg-symbol 0) instance))))
(ecase 1-or-2-class
(1 (setq closure-variables '(wrapper-0 index miss-fn)))
(2 (setq closure-variables '(wrapper-0 wrapper-1 index miss-fn))))
(generating-lap closure-variables
arglist
(with-lap-registers ((inst t) ;reg for the instance
(wrapper #-structure-wrapper vector ;reg for the wrapper
#+structure-wrapper t)
#+structure-wrapper (cnv fixnum-vector)
(cache-no index)) ;reg for the cache no
(let ((index cache-no) ;This register is used
;for different values at
;different times.
(slots (and (null class-slot-p)
(allocate-register 'vector)))
(csv (and class-slot-p
(allocate-register t))))
(prog1 (flatten-lap
(opcode :move (operand :arg instance) inst) ;get the instance
(opcode :std-instance-p inst 'std-instance) ;if not either std-inst
or fsc - instance then
#+pcl-user-instances
(opcode :user-instance-p inst 'user-instance) ;if not either std-inst
(opcode :go 'trap) ;we lose
#+pcl-user-instances
(opcode :label 'user-instance)
#+pcl-user-instances
(opcode :move (operand :user-wrapper inst) wrapper)
#+pcl-user-instances
(and slots
(opcode :move (operand :user-slots inst) slots))
#+pcl-user-instances
(opcode :go 'have-wrapper)
(opcode :label 'fsc-instance)
(opcode :move (operand :fsc-wrapper inst) wrapper)
(and slots
(opcode :move (operand :fsc-slots inst) slots))
(opcode :go 'have-wrapper)
(opcode :label 'std-instance)
(opcode :move (operand :std-wrapper inst) wrapper)
(and slots
(opcode :move (operand :std-slots inst) slots))
(opcode :label 'have-wrapper)
#-structure-wrapper
(opcode :move (operand :cref wrapper field) cache-no)
#+structure-wrapper
(opcode :move (emit-wrapper-cache-number-vector wrapper) cnv)
#+structure-wrapper
(opcode :move (operand :cref cnv field) cache-no)
(opcode :izerop cache-no 'trap) ;obsolete wrapper?
(ecase 1-or-2-class
(1 (emit-check-1-class-wrapper wrapper 'wrapper-0 'trap))
(2 (emit-check-2-class-wrapper wrapper 'wrapper-0 'wrapper-1 'trap)))
(if class-slot-p
(flatten-lap
(opcode :move (operand :cvar 'index) csv)
(ecase reader/writer
(:reader (emit-get-class-slot csv 'trap inst))
(:writer (emit-set-class-slot csv (car arglist) inst))))
(flatten-lap
(opcode :move (operand :cvar 'index) index)
(ecase reader/writer
(:reader (emit-get-slot slots index 'trap inst))
(:writer (emit-set-slot slots index (car arglist) inst)))))
(opcode :label 'trap)
(emit-miss 'miss-fn))
(when slots (deallocate-register slots))
(when csv (deallocate-register csv))))))))
(defun emit-one-index-readers (class-slot-p)
(declare (type boolean class-slot-p))
(let ((arglist (list (dfun-arg-symbol 0))))
(generating-lap '(field cache-vector mask size index miss-fn)
arglist
(with-lap-registers ((slots vector))
(emit-dlap arglist
'(standard-instance)
'trap
(with-lap-registers ((index index))
(flatten-lap
(opcode :move (operand :cvar 'index) index)
(if class-slot-p
(emit-get-class-slot index 'trap slots)
(emit-get-slot slots index 'trap))))
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
nil
(and (null class-slot-p) (list slots)))))))
(defun emit-one-index-writers (class-slot-p)
(declare (type boolean class-slot-p))
(let ((arglist (list (dfun-arg-symbol 0) (dfun-arg-symbol 1))))
(generating-lap '(field cache-vector mask size index miss-fn)
arglist
(with-lap-registers ((slots vector))
(emit-dlap arglist
'(t standard-instance)
'trap
(with-lap-registers ((index index))
(flatten-lap
(opcode :move (operand :cvar 'index) index)
(if class-slot-p
(emit-set-class-slot index (dfun-arg-symbol 0) slots)
(emit-set-slot slots index (dfun-arg-symbol 0)))))
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
nil
(and (null class-slot-p) (list nil slots)))))))
(defun emit-n-n-readers ()
(let ((arglist (list (dfun-arg-symbol 0))))
(generating-lap '(field cache-vector mask size miss-fn)
arglist
(with-lap-registers ((slots vector)
(index index))
(emit-dlap arglist
'(standard-instance)
'trap
(emit-get-slot slots index 'trap)
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
index
(list slots))))))
(defun emit-n-n-writers ()
(let ((arglist (list (dfun-arg-symbol 0) (dfun-arg-symbol 1))))
(generating-lap '(field cache-vector mask size miss-fn)
arglist
(with-lap-registers ((slots vector)
(index index))
(flatten-lap
(emit-dlap arglist
'(t standard-instance)
'trap
(emit-set-slot slots index (dfun-arg-symbol 0))
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
index
(list nil slots)))))))
(defun emit-checking (metatypes applyp)
(let ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)))
(generating-lap '(field cache-vector mask size function miss-fn)
dlap-lambda-list
(emit-dlap (remove '&rest dlap-lambda-list)
metatypes
'trap
(with-lap-registers ((function t))
(flatten-lap
(opcode :move (operand :cvar 'function) function)
(opcode :jmp function)))
(with-lap-registers ((miss-function t))
(flatten-lap
(opcode :label 'trap)
(opcode :move (operand :cvar 'miss-fn) miss-function)
(opcode :jmp miss-function)))
nil))))
(defun emit-caching (metatypes applyp)
(let ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)))
(generating-lap '(field cache-vector mask size miss-fn)
dlap-lambda-list
(with-lap-registers ((function t))
(emit-dlap (remove '&rest dlap-lambda-list)
metatypes
'trap
(flatten-lap (opcode :jmp function))
(with-lap-registers ((miss-function t))
(flatten-lap
(opcode :label 'trap)
(opcode :move (operand :cvar 'miss-fn) miss-function)
(opcode :jmp miss-function)))
function)))))
(defun emit-constant-value (metatypes)
(let ((dlap-lambda-list (make-dlap-lambda-list metatypes nil)))
(generating-lap '(field cache-vector mask size miss-fn)
dlap-lambda-list
(with-lap-registers ((value t))
(emit-dlap dlap-lambda-list
metatypes
'trap
(flatten-lap
(opcode :return value))
(with-lap-registers ((miss-function t))
(flatten-lap
(opcode :label 'trap)
(opcode :move (operand :cvar 'miss-fn) miss-function)
(opcode :jmp miss-function)))
value)))))
(defun emit-check-1-class-wrapper (wrapper cwrapper-0 miss-label)
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :move (operand :cvar cwrapper-0) cwrapper)
(opcode :neq wrapper cwrapper miss-label)))) ;wrappers not eq, trap
(defun emit-check-2-class-wrapper (wrapper cwrapper-0 cwrapper-1 miss-label)
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :move (operand :cvar cwrapper-0) cwrapper) ;This is an OR. Isn't
(opcode :eq wrapper cwrapper 'hit-internal) ;assembly code fun
(opcode :move (operand :cvar cwrapper-1) cwrapper) ;
(opcode :neq wrapper cwrapper miss-label) ;
(opcode :label 'hit-internal))))
(defun emit-get-slot (slots index trap-label &optional temp)
(let ((slot-unbound (operand :constant *slot-unbound*)))
(with-lap-registers ((val t :reuse temp))
(flatten-lap
(opcode :move (operand :iref slots index) val) ;get slot value
(opcode :eq val slot-unbound trap-label) ;is the slot unbound?
(opcode :return val))))) ;return the slot value
(defun emit-set-slot (slots index new-value-arg &optional temp)
(with-lap-registers ((new-val t :reuse temp))
(flatten-lap
(opcode :move (operand :arg new-value-arg) new-val) ;get new value into a reg
(opcode :move new-val (operand :iref slots index)) ;set slot value
(opcode :return new-val))))
(defun emit-get-class-slot (index trap-label &optional temp)
(let ((slot-unbound (operand :constant *slot-unbound*)))
(with-lap-registers ((val t :reuse temp))
(flatten-lap
(opcode :move (operand :cdr index) val)
(opcode :eq val slot-unbound trap-label)
(opcode :return val)))))
(defun emit-set-class-slot (index new-value-arg &optional temp)
(with-lap-registers ((new-val t :reuse temp))
(flatten-lap
(opcode :move (operand :arg new-value-arg) new-val)
(opcode :move new-val (operand :cdr index))
(opcode :return new-val))))
(defun emit-miss (miss-fn)
(with-lap-registers ((miss-fn-reg t))
(flatten-lap
(opcode :move (operand :cvar miss-fn) miss-fn-reg) ;get the miss function
(opcode :jmp miss-fn-reg)))) ;and call it
(defun dlap-wrappers (metatypes)
(mapcar #'(lambda (x) (and (neq x 't)
(allocate-register #-structure-wrapper 'vector
#+structure-wrapper t)))
metatypes))
(defun dlap-wrapper-moves (wrappers args metatypes miss-label slot-regs)
(gathering1 (collecting)
(iterate ((mt (list-elements metatypes))
(arg (list-elements args))
(wrapper (list-elements wrappers))
(i (interval :from 0)))
(when wrapper
(gather1
(emit-fetch-wrapper mt arg wrapper miss-label (nth i slot-regs)))))))
(defun emit-dlap (args metatypes miss-label hit miss value-reg &optional slot-regs)
(let* ((wrappers (dlap-wrappers metatypes))
(nwrappers (remove nil wrappers))
(wrapper-moves (dlap-wrapper-moves wrappers args metatypes miss-label slot-regs)))
(prog1 (emit-dlap-internal nwrappers
wrapper-moves
hit
miss
miss-label
value-reg)
(mapc #'deallocate-register nwrappers))))
(defun emit-dlap-internal (wrapper-regs wrapper-moves hit miss miss-label value-reg)
(cond ((cdr wrapper-regs)
(emit-greater-than-1-dlap
wrapper-regs wrapper-moves hit miss miss-label value-reg))
((null value-reg)
(emit-1-nil-dlap
(car wrapper-regs) (car wrapper-moves) hit miss miss-label))
(t
(emit-1-t-dlap
(car wrapper-regs) (car wrapper-moves) hit miss miss-label value-reg))))
(defun emit-1-nil-dlap (wrapper wrapper-move hit miss miss-label)
(with-lap-registers ((location index)
(primary index)
(cache-vector vector))
(flatten-lap
wrapper-move
(opcode :move (operand :cvar 'cache-vector) cache-vector)
(with-lap-registers ((wrapper-cache-no index))
(flatten-lap
(emit-1-wrapper-compute-primary-cache-location wrapper primary wrapper-cache-no)
(opcode :move primary location)
(emit-check-1-wrapper-in-cache cache-vector location wrapper hit) ;inline hit code
(opcode :izerop wrapper-cache-no miss-label)))
(with-lap-registers ((size index))
(flatten-lap
(opcode :move (operand :cvar 'size) size)
(opcode :label 'loop)
(opcode :move (operand :i1+ location) location)
(opcode :fix= location primary miss-label)
(opcode :fix= location size 'set-location-to-min)
(opcode :label 'continue)
(emit-check-1-wrapper-in-cache cache-vector location wrapper hit)
(opcode :go 'loop)
(opcode :label 'set-location-to-min)
(opcode :izerop primary miss-label)
(opcode :move (operand :constant (index-value->index 0)) location)
(opcode :go 'continue)))
miss)))
;;;
The function below implements CACHE - VECTOR - LOCK - COUNT as the first entry
;;; in a cache (svref cache-vector 0). This should probably be abstracted.
;;;
(defun emit-1-t-dlap (wrapper wrapper-move hit miss miss-label value)
(with-lap-registers ((location index)
(primary index)
(cache-vector vector)
(initial-lock-count t))
(flatten-lap
wrapper-move
(opcode :move (operand :cvar 'cache-vector) cache-vector)
(with-lap-registers ((wrapper-cache-no index))
(flatten-lap
(emit-1-wrapper-compute-primary-cache-location wrapper primary wrapper-cache-no)
(opcode :move primary location)
(opcode :move (operand :cref cache-vector 0) initial-lock-count) ;get lock-count
(emit-check-cache-entry cache-vector location wrapper 'hit-internal)
(opcode :izerop wrapper-cache-no miss-label))) ;check for obsolescence
(with-lap-registers ((size index))
(flatten-lap
(opcode :move (operand :cvar 'size) size)
(opcode :label 'loop)
(opcode :move (operand :i1+ location) location)
(opcode :move (operand :i1+ location) location)
(opcode :label 'continue)
(opcode :fix= location primary miss-label)
(opcode :fix= location size 'set-location-to-min)
(emit-check-cache-entry cache-vector location wrapper 'hit-internal)
(opcode :go 'loop)
(opcode :label 'set-location-to-min)
(opcode :izerop primary miss-label)
(opcode :move (operand :constant (index-value->index 2)) location)
(opcode :go 'continue)))
(opcode :label 'hit-internal)
(opcode :move (operand :i1+ location) location) ;position for getting value
(opcode :move (emit-cache-vector-ref cache-vector location) value)
(emit-lock-count-test initial-lock-count cache-vector 'hit)
miss
(opcode :label 'hit)
hit)))
(defun emit-greater-than-1-dlap (wrappers wrapper-moves hit miss miss-label value)
(declare (list wrappers))
(let ((cache-line-size (compute-line-size
(if value
(the index (1+ (the index (length wrappers))))
(length wrappers)))))
(declare (type index cache-line-size))
(with-lap-registers ((location index)
(primary index)
(cache-vector vector)
(initial-lock-count t)
(next-location index)
(line-size index)) ;Line size holds a constant
;that can be folded in if there was
;a way to add a constant to
;an index register
(flatten-lap
(apply #'flatten-lap wrapper-moves)
(opcode :move (operand :constant cache-line-size) line-size)
(opcode :move (operand :cvar 'cache-vector) cache-vector)
(emit-n-wrapper-compute-primary-cache-location wrappers primary miss-label)
(opcode :move primary location)
(opcode :move location next-location)
(opcode :move (operand :cref cache-vector 0) initial-lock-count) ;get the lock-count
(with-lap-registers ((size index))
(flatten-lap
(opcode :move (operand :cvar 'size) size)
(opcode :label 'continue)
(opcode :move (operand :i+ location line-size) next-location)
(emit-check-cache-line cache-vector location wrappers 'hit)
(emit-adjust-location location next-location primary size 'continue miss-label)
(opcode :label 'hit)
(and value (opcode :move (emit-cache-vector-ref cache-vector location) value))
(emit-lock-count-test initial-lock-count cache-vector 'hit-internal)
miss
(opcode :label 'hit-internal)
hit))))))
;;;
Cache related lap code
;;;
(defun emit-check-1-wrapper-in-cache (cache-vector location wrapper hit-code)
(let ((exit-emit-check-1-wrapper-in-cache
(make-symbol "exit-emit-check-1-wrapper-in-cache")))
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :move (emit-cache-vector-ref cache-vector location) cwrapper)
(opcode :neq cwrapper wrapper exit-emit-check-1-wrapper-in-cache)
hit-code
(opcode :label exit-emit-check-1-wrapper-in-cache)))))
(defun emit-check-cache-entry (cache-vector location wrapper hit-label)
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :move (emit-cache-vector-ref cache-vector location) cwrapper)
(opcode :eq cwrapper wrapper hit-label))))
(defun emit-check-cache-line (cache-vector location wrappers hit-label)
(let ((checks
(flatten-lap
(gathering1 (flattening-lap)
(iterate ((wrapper (list-elements wrappers)))
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(gather1
(flatten-lap
(opcode :move (emit-cache-vector-ref cache-vector location) cwrapper)
(opcode :neq cwrapper wrapper 'exit-emit-check-cache-line)
(opcode :move (operand :i1+ location) location)))))))))
(flatten-lap
checks
(opcode :go hit-label)
(opcode :label 'exit-emit-check-cache-line))))
(defun emit-lock-count-test (initial-lock-count cache-vector hit-label)
;;
;; jumps to hit-label if cache-vector-lock-count consistent, otherwise, continues
;;
(with-lap-registers ((new-lock-count t))
(flatten-lap
(opcode :move (operand :cref cache-vector 0) new-lock-count) ;get new cache-vector-lock-count
(opcode :fix= new-lock-count initial-lock-count hit-label))))
(defun emit-adjust-location (location next-location primary size cont-label miss-label)
(flatten-lap
(opcode :move next-location location)
(opcode :fix= location size 'at-end-of-cache)
(opcode :fix= location primary miss-label)
(opcode :go cont-label)
(opcode :label 'at-end-of-cache)
(opcode :fix= primary (operand :constant (index-value->index 1)) miss-label)
(opcode :move (operand :constant (index-value->index 1)) location)
(opcode :go cont-label)))
| null | https://raw.githubusercontent.com/logicmoo/wam_common_lisp/4396d9e26b050f68182d65c9a2d5a939557616dd/prolog/wam_cl/src/pcl/dlap.lisp | lisp | Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*-
*************************************************************************
All rights reserved.
Use and copying of this software and preparation of derivative works
based upon this software are permitted. Any distribution of this
States export control laws.
warranty about the software, its performance or its conformity to any
specification.
Any person obtaining a copy of this software is requested to send their
name and post office or electronic mail address to:
Suggestions, comments and requests for improvements are also welcome.
*************************************************************************
we need some field to do
the fast obsolete check
reg for the instance
reg for the wrapper
reg for the cache no
This register is used
for different values at
different times.
get the instance
if not either std-inst
if not either std-inst
we lose
obsolete wrapper?
wrappers not eq, trap
This is an OR. Isn't
assembly code fun
get slot value
is the slot unbound?
return the slot value
get new value into a reg
set slot value
get the miss function
and call it
inline hit code
in a cache (svref cache-vector 0). This should probably be abstracted.
get lock-count
check for obsolescence
position for getting value
Line size holds a constant
that can be folded in if there was
a way to add a constant to
an index register
get the lock-count
jumps to hit-label if cache-vector-lock-count consistent, otherwise, continues
get new cache-vector-lock-count | Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation .
software or derivative works must comply with all applicable United
This software is made available AS IS , and Xerox Corporation makes no
CommonLoops Coordinator
Xerox PARC
3333 Coyote Hill Rd .
Palo Alto , CA 94304
( or send Arpanet mail to )
(in-package 'pcl)
(defun emit-one-class-reader (class-slot-p) (emit-reader/writer :reader 1 class-slot-p))
(defun emit-one-class-writer (class-slot-p) (emit-reader/writer :writer 1 class-slot-p))
(defun emit-two-class-reader (class-slot-p) (emit-reader/writer :reader 2 class-slot-p))
(defun emit-two-class-writer (class-slot-p) (emit-reader/writer :writer 2 class-slot-p))
(defun emit-reader/writer (reader/writer 1-or-2-class class-slot-p)
(declare (type index 1-or-2-class)
(type boolean class-slot-p))
(let ((instance nil)
(arglist ())
(closure-variables ())
(ecase reader/writer
(:reader (setq instance (dfun-arg-symbol 0)
arglist (list instance)))
(:writer (setq instance (dfun-arg-symbol 1)
arglist (list (dfun-arg-symbol 0) instance))))
(ecase 1-or-2-class
(1 (setq closure-variables '(wrapper-0 index miss-fn)))
(2 (setq closure-variables '(wrapper-0 wrapper-1 index miss-fn))))
(generating-lap closure-variables
arglist
#+structure-wrapper t)
#+structure-wrapper (cnv fixnum-vector)
(slots (and (null class-slot-p)
(allocate-register 'vector)))
(csv (and class-slot-p
(allocate-register t))))
(prog1 (flatten-lap
or fsc - instance then
#+pcl-user-instances
#+pcl-user-instances
(opcode :label 'user-instance)
#+pcl-user-instances
(opcode :move (operand :user-wrapper inst) wrapper)
#+pcl-user-instances
(and slots
(opcode :move (operand :user-slots inst) slots))
#+pcl-user-instances
(opcode :go 'have-wrapper)
(opcode :label 'fsc-instance)
(opcode :move (operand :fsc-wrapper inst) wrapper)
(and slots
(opcode :move (operand :fsc-slots inst) slots))
(opcode :go 'have-wrapper)
(opcode :label 'std-instance)
(opcode :move (operand :std-wrapper inst) wrapper)
(and slots
(opcode :move (operand :std-slots inst) slots))
(opcode :label 'have-wrapper)
#-structure-wrapper
(opcode :move (operand :cref wrapper field) cache-no)
#+structure-wrapper
(opcode :move (emit-wrapper-cache-number-vector wrapper) cnv)
#+structure-wrapper
(opcode :move (operand :cref cnv field) cache-no)
(ecase 1-or-2-class
(1 (emit-check-1-class-wrapper wrapper 'wrapper-0 'trap))
(2 (emit-check-2-class-wrapper wrapper 'wrapper-0 'wrapper-1 'trap)))
(if class-slot-p
(flatten-lap
(opcode :move (operand :cvar 'index) csv)
(ecase reader/writer
(:reader (emit-get-class-slot csv 'trap inst))
(:writer (emit-set-class-slot csv (car arglist) inst))))
(flatten-lap
(opcode :move (operand :cvar 'index) index)
(ecase reader/writer
(:reader (emit-get-slot slots index 'trap inst))
(:writer (emit-set-slot slots index (car arglist) inst)))))
(opcode :label 'trap)
(emit-miss 'miss-fn))
(when slots (deallocate-register slots))
(when csv (deallocate-register csv))))))))
(defun emit-one-index-readers (class-slot-p)
(declare (type boolean class-slot-p))
(let ((arglist (list (dfun-arg-symbol 0))))
(generating-lap '(field cache-vector mask size index miss-fn)
arglist
(with-lap-registers ((slots vector))
(emit-dlap arglist
'(standard-instance)
'trap
(with-lap-registers ((index index))
(flatten-lap
(opcode :move (operand :cvar 'index) index)
(if class-slot-p
(emit-get-class-slot index 'trap slots)
(emit-get-slot slots index 'trap))))
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
nil
(and (null class-slot-p) (list slots)))))))
(defun emit-one-index-writers (class-slot-p)
(declare (type boolean class-slot-p))
(let ((arglist (list (dfun-arg-symbol 0) (dfun-arg-symbol 1))))
(generating-lap '(field cache-vector mask size index miss-fn)
arglist
(with-lap-registers ((slots vector))
(emit-dlap arglist
'(t standard-instance)
'trap
(with-lap-registers ((index index))
(flatten-lap
(opcode :move (operand :cvar 'index) index)
(if class-slot-p
(emit-set-class-slot index (dfun-arg-symbol 0) slots)
(emit-set-slot slots index (dfun-arg-symbol 0)))))
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
nil
(and (null class-slot-p) (list nil slots)))))))
(defun emit-n-n-readers ()
(let ((arglist (list (dfun-arg-symbol 0))))
(generating-lap '(field cache-vector mask size miss-fn)
arglist
(with-lap-registers ((slots vector)
(index index))
(emit-dlap arglist
'(standard-instance)
'trap
(emit-get-slot slots index 'trap)
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
index
(list slots))))))
(defun emit-n-n-writers ()
(let ((arglist (list (dfun-arg-symbol 0) (dfun-arg-symbol 1))))
(generating-lap '(field cache-vector mask size miss-fn)
arglist
(with-lap-registers ((slots vector)
(index index))
(flatten-lap
(emit-dlap arglist
'(t standard-instance)
'trap
(emit-set-slot slots index (dfun-arg-symbol 0))
(flatten-lap
(opcode :label 'trap)
(emit-miss 'miss-fn))
index
(list nil slots)))))))
(defun emit-checking (metatypes applyp)
(let ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)))
(generating-lap '(field cache-vector mask size function miss-fn)
dlap-lambda-list
(emit-dlap (remove '&rest dlap-lambda-list)
metatypes
'trap
(with-lap-registers ((function t))
(flatten-lap
(opcode :move (operand :cvar 'function) function)
(opcode :jmp function)))
(with-lap-registers ((miss-function t))
(flatten-lap
(opcode :label 'trap)
(opcode :move (operand :cvar 'miss-fn) miss-function)
(opcode :jmp miss-function)))
nil))))
(defun emit-caching (metatypes applyp)
(let ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)))
(generating-lap '(field cache-vector mask size miss-fn)
dlap-lambda-list
(with-lap-registers ((function t))
(emit-dlap (remove '&rest dlap-lambda-list)
metatypes
'trap
(flatten-lap (opcode :jmp function))
(with-lap-registers ((miss-function t))
(flatten-lap
(opcode :label 'trap)
(opcode :move (operand :cvar 'miss-fn) miss-function)
(opcode :jmp miss-function)))
function)))))
(defun emit-constant-value (metatypes)
(let ((dlap-lambda-list (make-dlap-lambda-list metatypes nil)))
(generating-lap '(field cache-vector mask size miss-fn)
dlap-lambda-list
(with-lap-registers ((value t))
(emit-dlap dlap-lambda-list
metatypes
'trap
(flatten-lap
(opcode :return value))
(with-lap-registers ((miss-function t))
(flatten-lap
(opcode :label 'trap)
(opcode :move (operand :cvar 'miss-fn) miss-function)
(opcode :jmp miss-function)))
value)))))
(defun emit-check-1-class-wrapper (wrapper cwrapper-0 miss-label)
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :move (operand :cvar cwrapper-0) cwrapper)
(defun emit-check-2-class-wrapper (wrapper cwrapper-0 cwrapper-1 miss-label)
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :label 'hit-internal))))
(defun emit-get-slot (slots index trap-label &optional temp)
(let ((slot-unbound (operand :constant *slot-unbound*)))
(with-lap-registers ((val t :reuse temp))
(flatten-lap
(defun emit-set-slot (slots index new-value-arg &optional temp)
(with-lap-registers ((new-val t :reuse temp))
(flatten-lap
(opcode :return new-val))))
(defun emit-get-class-slot (index trap-label &optional temp)
(let ((slot-unbound (operand :constant *slot-unbound*)))
(with-lap-registers ((val t :reuse temp))
(flatten-lap
(opcode :move (operand :cdr index) val)
(opcode :eq val slot-unbound trap-label)
(opcode :return val)))))
(defun emit-set-class-slot (index new-value-arg &optional temp)
(with-lap-registers ((new-val t :reuse temp))
(flatten-lap
(opcode :move (operand :arg new-value-arg) new-val)
(opcode :move new-val (operand :cdr index))
(opcode :return new-val))))
(defun emit-miss (miss-fn)
(with-lap-registers ((miss-fn-reg t))
(flatten-lap
(defun dlap-wrappers (metatypes)
(mapcar #'(lambda (x) (and (neq x 't)
(allocate-register #-structure-wrapper 'vector
#+structure-wrapper t)))
metatypes))
(defun dlap-wrapper-moves (wrappers args metatypes miss-label slot-regs)
(gathering1 (collecting)
(iterate ((mt (list-elements metatypes))
(arg (list-elements args))
(wrapper (list-elements wrappers))
(i (interval :from 0)))
(when wrapper
(gather1
(emit-fetch-wrapper mt arg wrapper miss-label (nth i slot-regs)))))))
(defun emit-dlap (args metatypes miss-label hit miss value-reg &optional slot-regs)
(let* ((wrappers (dlap-wrappers metatypes))
(nwrappers (remove nil wrappers))
(wrapper-moves (dlap-wrapper-moves wrappers args metatypes miss-label slot-regs)))
(prog1 (emit-dlap-internal nwrappers
wrapper-moves
hit
miss
miss-label
value-reg)
(mapc #'deallocate-register nwrappers))))
(defun emit-dlap-internal (wrapper-regs wrapper-moves hit miss miss-label value-reg)
(cond ((cdr wrapper-regs)
(emit-greater-than-1-dlap
wrapper-regs wrapper-moves hit miss miss-label value-reg))
((null value-reg)
(emit-1-nil-dlap
(car wrapper-regs) (car wrapper-moves) hit miss miss-label))
(t
(emit-1-t-dlap
(car wrapper-regs) (car wrapper-moves) hit miss miss-label value-reg))))
(defun emit-1-nil-dlap (wrapper wrapper-move hit miss miss-label)
(with-lap-registers ((location index)
(primary index)
(cache-vector vector))
(flatten-lap
wrapper-move
(opcode :move (operand :cvar 'cache-vector) cache-vector)
(with-lap-registers ((wrapper-cache-no index))
(flatten-lap
(emit-1-wrapper-compute-primary-cache-location wrapper primary wrapper-cache-no)
(opcode :move primary location)
(opcode :izerop wrapper-cache-no miss-label)))
(with-lap-registers ((size index))
(flatten-lap
(opcode :move (operand :cvar 'size) size)
(opcode :label 'loop)
(opcode :move (operand :i1+ location) location)
(opcode :fix= location primary miss-label)
(opcode :fix= location size 'set-location-to-min)
(opcode :label 'continue)
(emit-check-1-wrapper-in-cache cache-vector location wrapper hit)
(opcode :go 'loop)
(opcode :label 'set-location-to-min)
(opcode :izerop primary miss-label)
(opcode :move (operand :constant (index-value->index 0)) location)
(opcode :go 'continue)))
miss)))
The function below implements CACHE - VECTOR - LOCK - COUNT as the first entry
(defun emit-1-t-dlap (wrapper wrapper-move hit miss miss-label value)
(with-lap-registers ((location index)
(primary index)
(cache-vector vector)
(initial-lock-count t))
(flatten-lap
wrapper-move
(opcode :move (operand :cvar 'cache-vector) cache-vector)
(with-lap-registers ((wrapper-cache-no index))
(flatten-lap
(emit-1-wrapper-compute-primary-cache-location wrapper primary wrapper-cache-no)
(opcode :move primary location)
(emit-check-cache-entry cache-vector location wrapper 'hit-internal)
(with-lap-registers ((size index))
(flatten-lap
(opcode :move (operand :cvar 'size) size)
(opcode :label 'loop)
(opcode :move (operand :i1+ location) location)
(opcode :move (operand :i1+ location) location)
(opcode :label 'continue)
(opcode :fix= location primary miss-label)
(opcode :fix= location size 'set-location-to-min)
(emit-check-cache-entry cache-vector location wrapper 'hit-internal)
(opcode :go 'loop)
(opcode :label 'set-location-to-min)
(opcode :izerop primary miss-label)
(opcode :move (operand :constant (index-value->index 2)) location)
(opcode :go 'continue)))
(opcode :label 'hit-internal)
(opcode :move (emit-cache-vector-ref cache-vector location) value)
(emit-lock-count-test initial-lock-count cache-vector 'hit)
miss
(opcode :label 'hit)
hit)))
(defun emit-greater-than-1-dlap (wrappers wrapper-moves hit miss miss-label value)
(declare (list wrappers))
(let ((cache-line-size (compute-line-size
(if value
(the index (1+ (the index (length wrappers))))
(length wrappers)))))
(declare (type index cache-line-size))
(with-lap-registers ((location index)
(primary index)
(cache-vector vector)
(initial-lock-count t)
(next-location index)
(flatten-lap
(apply #'flatten-lap wrapper-moves)
(opcode :move (operand :constant cache-line-size) line-size)
(opcode :move (operand :cvar 'cache-vector) cache-vector)
(emit-n-wrapper-compute-primary-cache-location wrappers primary miss-label)
(opcode :move primary location)
(opcode :move location next-location)
(with-lap-registers ((size index))
(flatten-lap
(opcode :move (operand :cvar 'size) size)
(opcode :label 'continue)
(opcode :move (operand :i+ location line-size) next-location)
(emit-check-cache-line cache-vector location wrappers 'hit)
(emit-adjust-location location next-location primary size 'continue miss-label)
(opcode :label 'hit)
(and value (opcode :move (emit-cache-vector-ref cache-vector location) value))
(emit-lock-count-test initial-lock-count cache-vector 'hit-internal)
miss
(opcode :label 'hit-internal)
hit))))))
Cache related lap code
(defun emit-check-1-wrapper-in-cache (cache-vector location wrapper hit-code)
(let ((exit-emit-check-1-wrapper-in-cache
(make-symbol "exit-emit-check-1-wrapper-in-cache")))
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :move (emit-cache-vector-ref cache-vector location) cwrapper)
(opcode :neq cwrapper wrapper exit-emit-check-1-wrapper-in-cache)
hit-code
(opcode :label exit-emit-check-1-wrapper-in-cache)))))
(defun emit-check-cache-entry (cache-vector location wrapper hit-label)
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(flatten-lap
(opcode :move (emit-cache-vector-ref cache-vector location) cwrapper)
(opcode :eq cwrapper wrapper hit-label))))
(defun emit-check-cache-line (cache-vector location wrappers hit-label)
(let ((checks
(flatten-lap
(gathering1 (flattening-lap)
(iterate ((wrapper (list-elements wrappers)))
(with-lap-registers ((cwrapper #-structure-wrapper vector
#+structure-wrapper t))
(gather1
(flatten-lap
(opcode :move (emit-cache-vector-ref cache-vector location) cwrapper)
(opcode :neq cwrapper wrapper 'exit-emit-check-cache-line)
(opcode :move (operand :i1+ location) location)))))))))
(flatten-lap
checks
(opcode :go hit-label)
(opcode :label 'exit-emit-check-cache-line))))
(defun emit-lock-count-test (initial-lock-count cache-vector hit-label)
(with-lap-registers ((new-lock-count t))
(flatten-lap
(opcode :fix= new-lock-count initial-lock-count hit-label))))
(defun emit-adjust-location (location next-location primary size cont-label miss-label)
(flatten-lap
(opcode :move next-location location)
(opcode :fix= location size 'at-end-of-cache)
(opcode :fix= location primary miss-label)
(opcode :go cont-label)
(opcode :label 'at-end-of-cache)
(opcode :fix= primary (operand :constant (index-value->index 1)) miss-label)
(opcode :move (operand :constant (index-value->index 1)) location)
(opcode :go cont-label)))
|
26bd6c6cc9223914609f24623fe473b6eeff87f6e99ef7557e16fc81ddddf7f4 | input-output-hk/cardano-sl | BiSerialize.hs | {-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE TemplateHaskell #
module Test.Pos.Binary.BiSerialize
( tests
) where
import Universum
import Hedgehog (Property)
import qualified Hedgehog as H
import Pos.Binary.Class (Cons (..), Field (..), cborError,
deriveIndexedBi)
import Test.Pos.Binary.Helpers.GoldenRoundTrip (goldenTestBi)
import Test.Pos.Util.Golden (discoverGolden)
--------------------------------------------------------------------------------
-- Since `deriveSimpleBi` no longer works on sum types, we cannot do a simple
-- comparison property between `deriveSimpleBi` and `deriveIndexedBi`. Instead,
-- this module contains golden tests. The tests were generated by the following
-- process (done before sumtypes were disallowed from `deriveSimpleBi`):
--
1 . Generate values of type TestSimple ( either by hand or via ` genTestSimple ` )
2 . Use ` deriveSimpleBi ` Bi instance to serialize the value to a file
3 . Translate the value to type TestIndexed via ` simpleToIndexed `
4 . Hardcode the result of ( 3 . ) into a golden test , which checks equivalence
with the output of ( 2 . )
--
-- This ensures that our encoding scheme was preserved, at least on a set of
points which exercise all the constructors of ` TestIndexed ` .
--------------------------------------------------------------------------------
data TestIndexed
= TiInt Int
| TiIntList [Int]
| TiChar2 Char Char
| TiInteger Integer
| TiMaybeInt (Maybe Int)
| TiChar2Permuted Char Char
| TiPair TestIndexed TestIndexed
deriving (Eq, Show, Typeable)
deriveIndexedBi ''TestIndexed [
Cons 'TiInt [
Field [| 0 :: Int |]
],
Cons 'TiIntList [
Field [| 0 :: [Int] |]
],
Cons 'TiChar2 [
Field [| 0 :: Char |],
Field [| 1 :: Char |]
],
Cons 'TiInteger [
Field [| 0 :: Integer |]
],
Cons 'TiMaybeInt [
Field [| 0 :: Maybe Int |]
],
Cons 'TiChar2Permuted [
Field [| 1 :: Char |],
Field [| 0 :: Char |]
],
Cons 'TiPair [
Field [| 0 :: TestIndexed |],
Field [| 1 :: TestIndexed |]
]
]
--------------------------------------------------------------------------------
-- Golden tests
--------------------------------------------------------------------------------
golden_TestSimpleIndexed1 :: Property
golden_TestSimpleIndexed1 = goldenTestBi ti "test/golden/TestSimpleIndexed1"
where
ti = TiPair
(TiPair
(TiChar2 '\154802' '\268555')
(TiMaybeInt (Just 3110389958050278305)))
(TiChar2 '\622348' '\696570')
golden_TestSimpleIndexed2 :: Property
golden_TestSimpleIndexed2 = goldenTestBi ti "test/golden/TestSimpleIndexed2"
where
ti = TiPair
(TiPair
(TiChar2 '\817168' '\1089248')
(TiPair
(TiChar2 '\230385' '\1065928')
(TiIntList [518227513268840239,3102008451401682492
,3028399834958998823,-1792258639827871709
,-4045193945739409444])))
(TiChar2Permuted '\427120' '\104794')
golden_TestSimpleIndexed3 :: Property
golden_TestSimpleIndexed3 = goldenTestBi ti "test/golden/TestSimpleIndexed3"
where
ti = TiPair (TiInteger (-515200628427138351744076))
(TiInt 4238472394723423)
golden_TestSimpleIndexed4 :: Property
golden_TestSimpleIndexed4 = goldenTestBi ti "test/golden/TestSimpleIndexed4"
where
ti = TiPair
(TiChar2 '\118580' '\1076905')
(TiPair
(TiMaybeInt (Just 2108646761465188277))
(TiPair
(TiInteger (-736109340637048771303587))
(TiPair
(TiInt 5991005317022714617)
(TiInt (-7567206666529693526)))))
golden_TestSimpleIndexed5 :: Property
golden_TestSimpleIndexed5 = goldenTestBi ti "test/golden/TestSimpleIndexed5"
where
ti = TiPair
(TiPair
(TiMaybeInt (Just 2108646761465188277))
(TiPair
(TiInteger (-736109340637048771303587))
(TiPair
(TiInt 5991005317022714617)
(TiInt (-7567206666529693526)))))
(TiPair
(TiChar2Permuted 'a' 'q')
(TiPair
(TiIntList [1..100])
(TiChar2 'f' 'z')))
--------------------------------------------------------------------------------
-- Main test export
--------------------------------------------------------------------------------
tests :: IO Bool
tests =
H.checkParallel $$discoverGolden
--------------------------------------------------------------------------------
Old code for TestSimple
--------------------------------------------------------------------------------
data TestSimple
= TsInt
{ unTsInt : : Int }
| TsIntList
{ unTsIntList : : [ Int ] }
| TsChar2
{ unTsChar2L : :
, unTsChar2R : : | TsInteger
{ unTsInteger : : Integer }
| TsMaybeInt
{ unTsMaybeInt : : Maybe Int }
| TsChar2Permuted
{ unTsChar2PermutedL : :
, unTsChar2PermutedR : : | TsPair
{ : : TestSimple
, unTsPairR : : TestSimple }
deriving ( Eq , Show , )
deriveSimpleBi '' TestSimple [
Cons ' TsInt [
Field [ | unTsInt : : Int | ]
] ,
Cons ' TsIntList [
Field [ | unTsIntList : : [ Int ] | ]
] ,
Cons ' TsChar2 [
Field [ | unTsChar2L : : | ] ,
Field [ | unTsChar2R : : | ]
] ,
Cons ' [
Field [ | unTsInteger : : Integer | ]
] ,
Cons ' TsMaybeInt [
Field [ | unTsMaybeInt : : Maybe Int | ]
] ,
Cons ' TsChar2Permuted [
Field [ | unTsChar2PermutedR : : | ] ,
Field [ | unTsChar2PermutedL : : | ]
] ,
Cons ' TsPair [
Field [ | : : TestSimple | ] ,
Field [ | unTsPairR : : TestSimple | ]
]
]
-- The validity of our comparison tests relies on this function . Fortunately ,
-- it 's a pretty straightforward translation .
simpleToIndexed : : TestSimple - > TestIndexed
simpleToIndexed ( TsInt i ) = TiInt i
simpleToIndexed ( TsIntList is ) = TiIntList is
simpleToIndexed ( TsChar2 l r ) = TiChar2 l r
simpleToIndexed ( i ) = TiInteger i
simpleToIndexed ( TsMaybeInt mi ) = TiMaybeInt mi
simpleToIndexed ( TsChar2Permuted l r ) = TiChar2Permuted l r
simpleToIndexed ( TsPair l r ) ( simpleToIndexed l )
( simpleToIndexed r )
--------------------------------------------------------------------------------
genTestSimple : : Range . Size - > Gen TestSimple
genTestSimple sz
| sz > 0 = Gen.choice ( pairType : flatTypes )
| otherwise = Gen.choice flatTypes
where
pairType = TsPair < $ > genTestSimple ( sz ` div ` 2 )
< * > genTestSimple ( sz ` div ` 2 )
flatTypes =
[ TsInt < $ > Gen.int Range.constantBounded
, TsIntList < $ > Gen.list ( Range.linear 0 20 ) ( Gen.int Range.constantBounded )
, TsChar2 < $ > Gen.unicode < * > Gen.unicode
, < $ > Gen.integral ( Range.linear ( - bignum ) bignum )
, TsMaybeInt < $ > Gen.maybe ( Gen.int Range.constantBounded )
, TsChar2Permuted < $ > Gen.unicode < * > Gen.unicode
]
bignum = 2 ^ ( 80 : : Integer )
data TestSimple
= TsInt
{ unTsInt :: Int }
| TsIntList
{ unTsIntList :: [Int] }
| TsChar2
{ unTsChar2L :: Char
, unTsChar2R :: Char }
| TsInteger
{ unTsInteger :: Integer }
| TsMaybeInt
{ unTsMaybeInt :: Maybe Int }
| TsChar2Permuted
{ unTsChar2PermutedL :: Char
, unTsChar2PermutedR :: Char }
| TsPair
{ unTsPairL :: TestSimple
, unTsPairR :: TestSimple }
deriving (Eq, Show, Typeable)
deriveSimpleBi ''TestSimple [
Cons 'TsInt [
Field [| unTsInt :: Int |]
],
Cons 'TsIntList [
Field [| unTsIntList :: [Int] |]
],
Cons 'TsChar2 [
Field [| unTsChar2L :: Char |],
Field [| unTsChar2R :: Char |]
],
Cons 'TsInteger [
Field [| unTsInteger :: Integer |]
],
Cons 'TsMaybeInt [
Field [| unTsMaybeInt :: Maybe Int |]
],
Cons 'TsChar2Permuted [
Field [| unTsChar2PermutedR :: Char |],
Field [| unTsChar2PermutedL :: Char |]
],
Cons 'TsPair [
Field [| unTsPairL :: TestSimple |],
Field [| unTsPairR :: TestSimple |]
]
]
-- The validity of our comparison tests relies on this function. Fortunately,
-- it's a pretty straightforward translation.
simpleToIndexed :: TestSimple -> TestIndexed
simpleToIndexed (TsInt i) = TiInt i
simpleToIndexed (TsIntList is) = TiIntList is
simpleToIndexed (TsChar2 l r) = TiChar2 l r
simpleToIndexed (TsInteger i) = TiInteger i
simpleToIndexed (TsMaybeInt mi) = TiMaybeInt mi
simpleToIndexed (TsChar2Permuted l r) = TiChar2Permuted l r
simpleToIndexed (TsPair l r) = TiPair (simpleToIndexed l)
(simpleToIndexed r)
--------------------------------------------------------------------------------
genTestSimple :: Range.Size -> Gen TestSimple
genTestSimple sz
| sz > 0 = Gen.choice (pairType : flatTypes)
| otherwise = Gen.choice flatTypes
where
pairType = TsPair <$> genTestSimple (sz `div` 2)
<*> genTestSimple (sz `div` 2)
flatTypes =
[ TsInt <$> Gen.int Range.constantBounded
, TsIntList <$> Gen.list (Range.linear 0 20) (Gen.int Range.constantBounded)
, TsChar2 <$> Gen.unicode <*> Gen.unicode
, TsInteger <$> Gen.integral (Range.linear (- bignum) bignum)
, TsMaybeInt <$> Gen.maybe (Gen.int Range.constantBounded)
, TsChar2Permuted <$> Gen.unicode <*> Gen.unicode
]
bignum = 2 ^ (80 :: Integer)
-}
| null | https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/binary/test/Test/Pos/Binary/BiSerialize.hs | haskell | # LANGUAGE DeriveAnyClass #
------------------------------------------------------------------------------
Since `deriveSimpleBi` no longer works on sum types, we cannot do a simple
comparison property between `deriveSimpleBi` and `deriveIndexedBi`. Instead,
this module contains golden tests. The tests were generated by the following
process (done before sumtypes were disallowed from `deriveSimpleBi`):
This ensures that our encoding scheme was preserved, at least on a set of
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Golden tests
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Main test export
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
The validity of our comparison tests relies on this function . Fortunately ,
it 's a pretty straightforward translation .
------------------------------------------------------------------------------
The validity of our comparison tests relies on this function. Fortunately,
it's a pretty straightforward translation.
------------------------------------------------------------------------------ | # LANGUAGE TemplateHaskell #
module Test.Pos.Binary.BiSerialize
( tests
) where
import Universum
import Hedgehog (Property)
import qualified Hedgehog as H
import Pos.Binary.Class (Cons (..), Field (..), cborError,
deriveIndexedBi)
import Test.Pos.Binary.Helpers.GoldenRoundTrip (goldenTestBi)
import Test.Pos.Util.Golden (discoverGolden)
1 . Generate values of type TestSimple ( either by hand or via ` genTestSimple ` )
2 . Use ` deriveSimpleBi ` Bi instance to serialize the value to a file
3 . Translate the value to type TestIndexed via ` simpleToIndexed `
4 . Hardcode the result of ( 3 . ) into a golden test , which checks equivalence
with the output of ( 2 . )
points which exercise all the constructors of ` TestIndexed ` .
data TestIndexed
= TiInt Int
| TiIntList [Int]
| TiChar2 Char Char
| TiInteger Integer
| TiMaybeInt (Maybe Int)
| TiChar2Permuted Char Char
| TiPair TestIndexed TestIndexed
deriving (Eq, Show, Typeable)
deriveIndexedBi ''TestIndexed [
Cons 'TiInt [
Field [| 0 :: Int |]
],
Cons 'TiIntList [
Field [| 0 :: [Int] |]
],
Cons 'TiChar2 [
Field [| 0 :: Char |],
Field [| 1 :: Char |]
],
Cons 'TiInteger [
Field [| 0 :: Integer |]
],
Cons 'TiMaybeInt [
Field [| 0 :: Maybe Int |]
],
Cons 'TiChar2Permuted [
Field [| 1 :: Char |],
Field [| 0 :: Char |]
],
Cons 'TiPair [
Field [| 0 :: TestIndexed |],
Field [| 1 :: TestIndexed |]
]
]
golden_TestSimpleIndexed1 :: Property
golden_TestSimpleIndexed1 = goldenTestBi ti "test/golden/TestSimpleIndexed1"
where
ti = TiPair
(TiPair
(TiChar2 '\154802' '\268555')
(TiMaybeInt (Just 3110389958050278305)))
(TiChar2 '\622348' '\696570')
golden_TestSimpleIndexed2 :: Property
golden_TestSimpleIndexed2 = goldenTestBi ti "test/golden/TestSimpleIndexed2"
where
ti = TiPair
(TiPair
(TiChar2 '\817168' '\1089248')
(TiPair
(TiChar2 '\230385' '\1065928')
(TiIntList [518227513268840239,3102008451401682492
,3028399834958998823,-1792258639827871709
,-4045193945739409444])))
(TiChar2Permuted '\427120' '\104794')
golden_TestSimpleIndexed3 :: Property
golden_TestSimpleIndexed3 = goldenTestBi ti "test/golden/TestSimpleIndexed3"
where
ti = TiPair (TiInteger (-515200628427138351744076))
(TiInt 4238472394723423)
golden_TestSimpleIndexed4 :: Property
golden_TestSimpleIndexed4 = goldenTestBi ti "test/golden/TestSimpleIndexed4"
where
ti = TiPair
(TiChar2 '\118580' '\1076905')
(TiPair
(TiMaybeInt (Just 2108646761465188277))
(TiPair
(TiInteger (-736109340637048771303587))
(TiPair
(TiInt 5991005317022714617)
(TiInt (-7567206666529693526)))))
golden_TestSimpleIndexed5 :: Property
golden_TestSimpleIndexed5 = goldenTestBi ti "test/golden/TestSimpleIndexed5"
where
ti = TiPair
(TiPair
(TiMaybeInt (Just 2108646761465188277))
(TiPair
(TiInteger (-736109340637048771303587))
(TiPair
(TiInt 5991005317022714617)
(TiInt (-7567206666529693526)))))
(TiPair
(TiChar2Permuted 'a' 'q')
(TiPair
(TiIntList [1..100])
(TiChar2 'f' 'z')))
tests :: IO Bool
tests =
H.checkParallel $$discoverGolden
Old code for TestSimple
data TestSimple
= TsInt
{ unTsInt : : Int }
| TsIntList
{ unTsIntList : : [ Int ] }
| TsChar2
{ unTsChar2L : :
, unTsChar2R : : | TsInteger
{ unTsInteger : : Integer }
| TsMaybeInt
{ unTsMaybeInt : : Maybe Int }
| TsChar2Permuted
{ unTsChar2PermutedL : :
, unTsChar2PermutedR : : | TsPair
{ : : TestSimple
, unTsPairR : : TestSimple }
deriving ( Eq , Show , )
deriveSimpleBi '' TestSimple [
Cons ' TsInt [
Field [ | unTsInt : : Int | ]
] ,
Cons ' TsIntList [
Field [ | unTsIntList : : [ Int ] | ]
] ,
Cons ' TsChar2 [
Field [ | unTsChar2L : : | ] ,
Field [ | unTsChar2R : : | ]
] ,
Cons ' [
Field [ | unTsInteger : : Integer | ]
] ,
Cons ' TsMaybeInt [
Field [ | unTsMaybeInt : : Maybe Int | ]
] ,
Cons ' TsChar2Permuted [
Field [ | unTsChar2PermutedR : : | ] ,
Field [ | unTsChar2PermutedL : : | ]
] ,
Cons ' TsPair [
Field [ | : : TestSimple | ] ,
Field [ | unTsPairR : : TestSimple | ]
]
]
simpleToIndexed : : TestSimple - > TestIndexed
simpleToIndexed ( TsInt i ) = TiInt i
simpleToIndexed ( TsIntList is ) = TiIntList is
simpleToIndexed ( TsChar2 l r ) = TiChar2 l r
simpleToIndexed ( i ) = TiInteger i
simpleToIndexed ( TsMaybeInt mi ) = TiMaybeInt mi
simpleToIndexed ( TsChar2Permuted l r ) = TiChar2Permuted l r
simpleToIndexed ( TsPair l r ) ( simpleToIndexed l )
( simpleToIndexed r )
genTestSimple : : Range . Size - > Gen TestSimple
genTestSimple sz
| sz > 0 = Gen.choice ( pairType : flatTypes )
| otherwise = Gen.choice flatTypes
where
pairType = TsPair < $ > genTestSimple ( sz ` div ` 2 )
< * > genTestSimple ( sz ` div ` 2 )
flatTypes =
[ TsInt < $ > Gen.int Range.constantBounded
, TsIntList < $ > Gen.list ( Range.linear 0 20 ) ( Gen.int Range.constantBounded )
, TsChar2 < $ > Gen.unicode < * > Gen.unicode
, < $ > Gen.integral ( Range.linear ( - bignum ) bignum )
, TsMaybeInt < $ > Gen.maybe ( Gen.int Range.constantBounded )
, TsChar2Permuted < $ > Gen.unicode < * > Gen.unicode
]
bignum = 2 ^ ( 80 : : Integer )
data TestSimple
= TsInt
{ unTsInt :: Int }
| TsIntList
{ unTsIntList :: [Int] }
| TsChar2
{ unTsChar2L :: Char
, unTsChar2R :: Char }
| TsInteger
{ unTsInteger :: Integer }
| TsMaybeInt
{ unTsMaybeInt :: Maybe Int }
| TsChar2Permuted
{ unTsChar2PermutedL :: Char
, unTsChar2PermutedR :: Char }
| TsPair
{ unTsPairL :: TestSimple
, unTsPairR :: TestSimple }
deriving (Eq, Show, Typeable)
deriveSimpleBi ''TestSimple [
Cons 'TsInt [
Field [| unTsInt :: Int |]
],
Cons 'TsIntList [
Field [| unTsIntList :: [Int] |]
],
Cons 'TsChar2 [
Field [| unTsChar2L :: Char |],
Field [| unTsChar2R :: Char |]
],
Cons 'TsInteger [
Field [| unTsInteger :: Integer |]
],
Cons 'TsMaybeInt [
Field [| unTsMaybeInt :: Maybe Int |]
],
Cons 'TsChar2Permuted [
Field [| unTsChar2PermutedR :: Char |],
Field [| unTsChar2PermutedL :: Char |]
],
Cons 'TsPair [
Field [| unTsPairL :: TestSimple |],
Field [| unTsPairR :: TestSimple |]
]
]
simpleToIndexed :: TestSimple -> TestIndexed
simpleToIndexed (TsInt i) = TiInt i
simpleToIndexed (TsIntList is) = TiIntList is
simpleToIndexed (TsChar2 l r) = TiChar2 l r
simpleToIndexed (TsInteger i) = TiInteger i
simpleToIndexed (TsMaybeInt mi) = TiMaybeInt mi
simpleToIndexed (TsChar2Permuted l r) = TiChar2Permuted l r
simpleToIndexed (TsPair l r) = TiPair (simpleToIndexed l)
(simpleToIndexed r)
genTestSimple :: Range.Size -> Gen TestSimple
genTestSimple sz
| sz > 0 = Gen.choice (pairType : flatTypes)
| otherwise = Gen.choice flatTypes
where
pairType = TsPair <$> genTestSimple (sz `div` 2)
<*> genTestSimple (sz `div` 2)
flatTypes =
[ TsInt <$> Gen.int Range.constantBounded
, TsIntList <$> Gen.list (Range.linear 0 20) (Gen.int Range.constantBounded)
, TsChar2 <$> Gen.unicode <*> Gen.unicode
, TsInteger <$> Gen.integral (Range.linear (- bignum) bignum)
, TsMaybeInt <$> Gen.maybe (Gen.int Range.constantBounded)
, TsChar2Permuted <$> Gen.unicode <*> Gen.unicode
]
bignum = 2 ^ (80 :: Integer)
-}
|
11e84b343a70522a45c4f5d7f6bad8e8f90a9201b088b5c7c54fdae3ff92e2fa | YouyouCong/ppl-summer-school-2022 | everyone.ml | (* 単語の意味 *)
let john = "john" ;;
let mary = "mary" ;;
let love obj sbj = "love(" ^ sbj ^ ", " ^ obj ^ ")" ;;
let know obj sbj = "know(" ^ sbj ^ ", " ^ obj ^ ")" ;;
let everyone x = ... ;;
テスト
loves everyone
let test1 =
reset (fun () -> love (everyone "x") john) = "forall x. love(john, x)" ;;
knows everyone
let test2 =
reset (fun () -> know (everyone "y") mary) = "forall y. know(mary, y)" ;; | null | https://raw.githubusercontent.com/YouyouCong/ppl-summer-school-2022/876e70d40a1cb7f8b16fb4985fd6dccb50f48601/cong/exercise/everyone.ml | ocaml | 単語の意味 | let john = "john" ;;
let mary = "mary" ;;
let love obj sbj = "love(" ^ sbj ^ ", " ^ obj ^ ")" ;;
let know obj sbj = "know(" ^ sbj ^ ", " ^ obj ^ ")" ;;
let everyone x = ... ;;
テスト
loves everyone
let test1 =
reset (fun () -> love (everyone "x") john) = "forall x. love(john, x)" ;;
knows everyone
let test2 =
reset (fun () -> know (everyone "y") mary) = "forall y. know(mary, y)" ;; |
023f314b3a5fd701f90a43209315e972db3a93e7a7ab774e399e59d22844226e | LeventErkok/sbv | IteTest.hs | -----------------------------------------------------------------------------
-- |
Module : TestSuite . Basics . IteTest
Copyright : ( c )
-- License : BSD3
-- Maintainer:
-- Stability : experimental
--
Test various incarnations of laziness in ite
-----------------------------------------------------------------------------
{-# OPTIONS_GHC -Wall -Werror #-}
module TestSuite.Basics.IteTest(tests) where
import Data.SBV.Internals (Result)
import Utils.SBVTestFramework
chk1 :: (SBool -> SBool -> SBool -> SBool) -> SWord8 -> SBool
chk1 cond x = cond (x .== x) sTrue undefined
chk2 :: (SBool -> [SBool] -> [SBool] -> [SBool]) -> SWord8 -> SBool
chk2 cond x = head (cond (x .== x) [sTrue] [undefined])
chk3 :: (SBool -> (SBool, SBool) -> (SBool, SBool) -> (SBool, SBool)) -> SWord8 -> SBool
chk3 cond x = fst (cond (x .== x) (sTrue, undefined::SBool) (undefined, undefined))
-- Test suite
tests :: TestTree
tests =
testGroup "Basics.Ite"
[ goldenVsStringShow "iteTest1" (rs (chk1 ite))
, goldenVsStringShow "iteTest2" (rs (chk2 ite))
, goldenVsStringShow "iteTest3" (rs (chk3 ite))
, testCase "iteTest4" (assertIsThm (chk1 iteLazy))
, testCase "iteTest5" (assertIsThm (chk2 iteLazy))
, testCase "iteTest6" (assertIsThm (chk3 iteLazy))
]
where rs :: (SWord8 -> SBool) -> IO Result
rs f = runSAT $ universal ["x"] f
| null | https://raw.githubusercontent.com/LeventErkok/sbv/0d791d9f4d1de6bd915b6d7d3f9a550385cb27a5/SBVTestSuite/TestSuite/Basics/IteTest.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Maintainer:
Stability : experimental
---------------------------------------------------------------------------
# OPTIONS_GHC -Wall -Werror #
Test suite | Module : TestSuite . Basics . IteTest
Copyright : ( c )
Test various incarnations of laziness in ite
module TestSuite.Basics.IteTest(tests) where
import Data.SBV.Internals (Result)
import Utils.SBVTestFramework
chk1 :: (SBool -> SBool -> SBool -> SBool) -> SWord8 -> SBool
chk1 cond x = cond (x .== x) sTrue undefined
chk2 :: (SBool -> [SBool] -> [SBool] -> [SBool]) -> SWord8 -> SBool
chk2 cond x = head (cond (x .== x) [sTrue] [undefined])
chk3 :: (SBool -> (SBool, SBool) -> (SBool, SBool) -> (SBool, SBool)) -> SWord8 -> SBool
chk3 cond x = fst (cond (x .== x) (sTrue, undefined::SBool) (undefined, undefined))
tests :: TestTree
tests =
testGroup "Basics.Ite"
[ goldenVsStringShow "iteTest1" (rs (chk1 ite))
, goldenVsStringShow "iteTest2" (rs (chk2 ite))
, goldenVsStringShow "iteTest3" (rs (chk3 ite))
, testCase "iteTest4" (assertIsThm (chk1 iteLazy))
, testCase "iteTest5" (assertIsThm (chk2 iteLazy))
, testCase "iteTest6" (assertIsThm (chk3 iteLazy))
]
where rs :: (SWord8 -> SBool) -> IO Result
rs f = runSAT $ universal ["x"] f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.