_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
|
---|---|---|---|---|---|---|---|---|
dea4d5f28f2f3ec530a103b231b5a0abaa526a97a7f07bc461fc2b21d2a23166 | eugeneia/athens | trivial-utf-8.lisp | ;;; Minimal utf-8 decoding and encoding library.
;;;
;;; See -lisp.net/project/trivial-utf-8/
(defpackage :cl-postgres-trivial-utf-8
(:use :common-lisp)
(:export #:utf-8-byte-length
#:string-to-utf-8-bytes
#:write-utf-8-bytes
#:utf-8-group-size
#:utf-8-bytes-to-string
#:read-utf-8-string
#:utf-8-decoding-error))
(in-package :cl-postgres-trivial-utf-8)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *optimize*
'(optimize
(speed 3)
#-ecl(safety 0) #+ecl(safety 1)
(space 0)
(debug 1)
(compilation-speed 0))))
(defun utf-8-byte-length (string)
"Calculate the amount of bytes needed to encode a string."
(declare (type string string)
#'*optimize*)
(let ((length (length string))
(string (coerce string 'simple-string)))
(loop :for char :across string
:do (let ((code (char-code char)))
(when (> code 127)
(incf length
(cond ((< code 2048) 1)
((< code 65536) 2)
(t 3))))))
length))
(defmacro as-utf-8-bytes (char writer)
"Given a character, calls the writer function for every byte in the
encoded form of that character."
(let ((char-code (gensym)))
`(let ((,char-code (char-code ,char)))
(declare (type fixnum ,char-code))
(cond ((< ,char-code 128)
(,writer ,char-code))
((< ,char-code 2048)
(,writer (logior #b11000000 (ldb (byte 5 6) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 0) ,char-code))))
((< ,char-code 65536)
(,writer (logior #b11100000 (ldb (byte 4 12) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 6) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 0) ,char-code))))
(t
(,writer (logior #b11110000 (ldb (byte 3 18) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 12) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 6) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 0) ,char-code))))))))
(defun string-to-utf-8-bytes (string &key null-terminate)
"Convert a string into an array of unsigned bytes containing its
utf-8 representation."
(declare (type string string)
#.*optimize*)
(let ((buffer (make-array (+ (the fixnum (utf-8-byte-length string))
(if null-terminate 1 0))
:element-type '(unsigned-byte 8)))
(position 0)
(string (coerce string 'simple-string)))
(declare (type (array (unsigned-byte 8)) buffer)
(type fixnum position))
(macrolet ((add-byte (byte)
`(progn (setf (aref buffer position) ,byte)
(incf position))))
(loop :for char :across string
:do (as-utf-8-bytes char add-byte)))
(when null-terminate
(setf (elt buffer (1- (length buffer))) 0))
buffer))
(defun write-utf-8-bytes (string output &key null-terminate)
"Write a string to a byte-stream, encoding it as utf-8."
(declare (type string string)
(type stream output)
#.*optimize*)
(macrolet ((byte-out (byte)
`(write-byte ,byte output)))
(let ((string (coerce string 'simple-string)))
(loop :for char :across string
:do (as-utf-8-bytes char byte-out))))
(when null-terminate
(write-byte 0 output)))
(define-condition utf-8-decoding-error (simple-error)
((message :initarg :message)
(byte :initarg :byte :initform nil))
(:report (lambda (err stream)
(format stream (slot-value err 'message)
(slot-value err 'byte)))))
(declaim (inline utf-8-group-size))
(defun utf-8-group-size (byte)
"Determine the amount of bytes that are part of the character
starting with a given byte."
(declare (type fixnum byte)
#.*optimize*)
(cond ((zerop (logand byte #b10000000)) 1)
((= (logand byte #b11100000) #b11000000) 2)
((= (logand byte #b11110000) #b11100000) 3)
((= (logand byte #b11111000) #b11110000) 4)
(t (error 'utf-8-decoding-error :byte byte
:message "Invalid byte at start of character: 0x~X"))))
(defun utf-8-string-length (bytes &key (start 0) (end (length bytes)))
"Calculate the length of the string encoded by the given bytes."
(declare (type (simple-array (unsigned-byte 8) (*)) bytes)
(type fixnum start end)
#.*optimize*)
(loop :with i :of-type fixnum = start
:with string-length = 0
:while (< i end)
:do (progn
(incf (the fixnum string-length) 1)
(incf i (utf-8-group-size (elt bytes i))))
:finally (return string-length)))
(defun get-utf-8-character (bytes group-size &optional (start 0))
"Given an array of bytes and the amount of bytes to use,
extract the character starting at the given start position."
(declare (type (simple-array (unsigned-byte 8) (*)) bytes)
(type fixnum group-size start)
#.*optimize*)
(labels ((next-byte ()
(prog1 (elt bytes start)
(incf start)))
(six-bits (byte)
(unless (= (logand byte #b11000000) #b10000000)
(error 'utf-8-decoding-error :byte byte
:message "Invalid byte 0x~X inside a character."))
(ldb (byte 6 0) byte)))
(case group-size
(1 (next-byte))
(2 (logior (ash (ldb (byte 5 0) (next-byte)) 6)
(six-bits (next-byte))))
(3 (logior (ash (ldb (byte 4 0) (next-byte)) 12)
(ash (six-bits (next-byte)) 6)
(six-bits (next-byte))))
(4 (logior (ash (ldb (byte 3 0) (next-byte)) 18)
(ash (six-bits (next-byte)) 12)
(ash (six-bits (next-byte)) 6)
(six-bits (next-byte)))))))
(defun utf-8-bytes-to-string (bytes-in &key (start 0) (end (length bytes-in)))
"Convert a byte array containing utf-8 encoded characters into
the string it encodes."
(declare (type vector bytes-in)
(type fixnum start end)
#.*optimize*)
(loop :with bytes = (coerce bytes-in '(simple-array (unsigned-byte 8) (*)))
:with buffer = (make-string (utf-8-string-length bytes :start start :end end) :element-type 'character)
:with array-position :of-type fixnum = start
:with string-position :of-type fixnum = 0
:while (< array-position end)
:do (let* ((char (elt bytes array-position))
(current-group (utf-8-group-size char)))
(when (> (+ current-group array-position) end)
(error 'utf-8-decoding-error
:message "Unfinished character at end of byte array."))
(setf (char buffer string-position)
(code-char (get-utf-8-character bytes current-group
array-position)))
(incf string-position 1)
(incf array-position current-group))
:finally (return buffer)))
(defun read-utf-8-string (input &key null-terminated stop-at-eof
(char-length -1) (byte-length -1))
"Read utf-8 encoded data from a byte stream and construct a
string with the characters found. When null-terminated is given
it will stop reading at a null character, stop-at-eof tells it to
stop at the end of file without raising an error, and the
char-length and byte-length parameters can be used to specify the
max amount of characters or bytes to read."
(declare (type stream input)
(type fixnum byte-length char-length)
#.*optimize*)
(let ((buffer (make-array 4 :element-type '(unsigned-byte 8)))
(bytes-read 0)
(string (make-array 64 :element-type 'character
:adjustable t :fill-pointer 0)))
(declare (type fixnum bytes-read))
(loop
(when (or (and (/= -1 byte-length) (>= bytes-read byte-length))
(and (/= -1 char-length) (= char-length (length string))))
(return))
(let ((next-char (read-byte input (not stop-at-eof) :eof)))
(when (or (eq next-char :eof)
(and null-terminated (eq next-char 0)))
(return))
(let ((current-group (utf-8-group-size next-char)))
(incf bytes-read current-group)
(cond ((= current-group 1)
(vector-push-extend (code-char next-char) string))
(t
(setf (elt buffer 0) next-char)
(loop :for i :from 1 :below current-group
:for next-char = (read-byte input nil :eof)
:do (when (eq next-char :eof)
(error 'utf-8-decoding-error
:message "Unfinished character at end of input."))
:do (setf (elt buffer i) next-char))
(vector-push-extend (code-char (get-utf-8-character
buffer current-group))
string))))))
string))
| null | https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/postmodern-20180711-git/cl-postgres/trivial-utf-8.lisp | lisp | Minimal utf-8 decoding and encoding library.
See -lisp.net/project/trivial-utf-8/ |
(defpackage :cl-postgres-trivial-utf-8
(:use :common-lisp)
(:export #:utf-8-byte-length
#:string-to-utf-8-bytes
#:write-utf-8-bytes
#:utf-8-group-size
#:utf-8-bytes-to-string
#:read-utf-8-string
#:utf-8-decoding-error))
(in-package :cl-postgres-trivial-utf-8)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *optimize*
'(optimize
(speed 3)
#-ecl(safety 0) #+ecl(safety 1)
(space 0)
(debug 1)
(compilation-speed 0))))
(defun utf-8-byte-length (string)
"Calculate the amount of bytes needed to encode a string."
(declare (type string string)
#'*optimize*)
(let ((length (length string))
(string (coerce string 'simple-string)))
(loop :for char :across string
:do (let ((code (char-code char)))
(when (> code 127)
(incf length
(cond ((< code 2048) 1)
((< code 65536) 2)
(t 3))))))
length))
(defmacro as-utf-8-bytes (char writer)
"Given a character, calls the writer function for every byte in the
encoded form of that character."
(let ((char-code (gensym)))
`(let ((,char-code (char-code ,char)))
(declare (type fixnum ,char-code))
(cond ((< ,char-code 128)
(,writer ,char-code))
((< ,char-code 2048)
(,writer (logior #b11000000 (ldb (byte 5 6) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 0) ,char-code))))
((< ,char-code 65536)
(,writer (logior #b11100000 (ldb (byte 4 12) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 6) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 0) ,char-code))))
(t
(,writer (logior #b11110000 (ldb (byte 3 18) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 12) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 6) ,char-code)))
(,writer (logior #b10000000 (ldb (byte 6 0) ,char-code))))))))
(defun string-to-utf-8-bytes (string &key null-terminate)
"Convert a string into an array of unsigned bytes containing its
utf-8 representation."
(declare (type string string)
#.*optimize*)
(let ((buffer (make-array (+ (the fixnum (utf-8-byte-length string))
(if null-terminate 1 0))
:element-type '(unsigned-byte 8)))
(position 0)
(string (coerce string 'simple-string)))
(declare (type (array (unsigned-byte 8)) buffer)
(type fixnum position))
(macrolet ((add-byte (byte)
`(progn (setf (aref buffer position) ,byte)
(incf position))))
(loop :for char :across string
:do (as-utf-8-bytes char add-byte)))
(when null-terminate
(setf (elt buffer (1- (length buffer))) 0))
buffer))
(defun write-utf-8-bytes (string output &key null-terminate)
"Write a string to a byte-stream, encoding it as utf-8."
(declare (type string string)
(type stream output)
#.*optimize*)
(macrolet ((byte-out (byte)
`(write-byte ,byte output)))
(let ((string (coerce string 'simple-string)))
(loop :for char :across string
:do (as-utf-8-bytes char byte-out))))
(when null-terminate
(write-byte 0 output)))
(define-condition utf-8-decoding-error (simple-error)
((message :initarg :message)
(byte :initarg :byte :initform nil))
(:report (lambda (err stream)
(format stream (slot-value err 'message)
(slot-value err 'byte)))))
(declaim (inline utf-8-group-size))
(defun utf-8-group-size (byte)
"Determine the amount of bytes that are part of the character
starting with a given byte."
(declare (type fixnum byte)
#.*optimize*)
(cond ((zerop (logand byte #b10000000)) 1)
((= (logand byte #b11100000) #b11000000) 2)
((= (logand byte #b11110000) #b11100000) 3)
((= (logand byte #b11111000) #b11110000) 4)
(t (error 'utf-8-decoding-error :byte byte
:message "Invalid byte at start of character: 0x~X"))))
(defun utf-8-string-length (bytes &key (start 0) (end (length bytes)))
"Calculate the length of the string encoded by the given bytes."
(declare (type (simple-array (unsigned-byte 8) (*)) bytes)
(type fixnum start end)
#.*optimize*)
(loop :with i :of-type fixnum = start
:with string-length = 0
:while (< i end)
:do (progn
(incf (the fixnum string-length) 1)
(incf i (utf-8-group-size (elt bytes i))))
:finally (return string-length)))
(defun get-utf-8-character (bytes group-size &optional (start 0))
"Given an array of bytes and the amount of bytes to use,
extract the character starting at the given start position."
(declare (type (simple-array (unsigned-byte 8) (*)) bytes)
(type fixnum group-size start)
#.*optimize*)
(labels ((next-byte ()
(prog1 (elt bytes start)
(incf start)))
(six-bits (byte)
(unless (= (logand byte #b11000000) #b10000000)
(error 'utf-8-decoding-error :byte byte
:message "Invalid byte 0x~X inside a character."))
(ldb (byte 6 0) byte)))
(case group-size
(1 (next-byte))
(2 (logior (ash (ldb (byte 5 0) (next-byte)) 6)
(six-bits (next-byte))))
(3 (logior (ash (ldb (byte 4 0) (next-byte)) 12)
(ash (six-bits (next-byte)) 6)
(six-bits (next-byte))))
(4 (logior (ash (ldb (byte 3 0) (next-byte)) 18)
(ash (six-bits (next-byte)) 12)
(ash (six-bits (next-byte)) 6)
(six-bits (next-byte)))))))
(defun utf-8-bytes-to-string (bytes-in &key (start 0) (end (length bytes-in)))
"Convert a byte array containing utf-8 encoded characters into
the string it encodes."
(declare (type vector bytes-in)
(type fixnum start end)
#.*optimize*)
(loop :with bytes = (coerce bytes-in '(simple-array (unsigned-byte 8) (*)))
:with buffer = (make-string (utf-8-string-length bytes :start start :end end) :element-type 'character)
:with array-position :of-type fixnum = start
:with string-position :of-type fixnum = 0
:while (< array-position end)
:do (let* ((char (elt bytes array-position))
(current-group (utf-8-group-size char)))
(when (> (+ current-group array-position) end)
(error 'utf-8-decoding-error
:message "Unfinished character at end of byte array."))
(setf (char buffer string-position)
(code-char (get-utf-8-character bytes current-group
array-position)))
(incf string-position 1)
(incf array-position current-group))
:finally (return buffer)))
(defun read-utf-8-string (input &key null-terminated stop-at-eof
(char-length -1) (byte-length -1))
"Read utf-8 encoded data from a byte stream and construct a
string with the characters found. When null-terminated is given
it will stop reading at a null character, stop-at-eof tells it to
stop at the end of file without raising an error, and the
char-length and byte-length parameters can be used to specify the
max amount of characters or bytes to read."
(declare (type stream input)
(type fixnum byte-length char-length)
#.*optimize*)
(let ((buffer (make-array 4 :element-type '(unsigned-byte 8)))
(bytes-read 0)
(string (make-array 64 :element-type 'character
:adjustable t :fill-pointer 0)))
(declare (type fixnum bytes-read))
(loop
(when (or (and (/= -1 byte-length) (>= bytes-read byte-length))
(and (/= -1 char-length) (= char-length (length string))))
(return))
(let ((next-char (read-byte input (not stop-at-eof) :eof)))
(when (or (eq next-char :eof)
(and null-terminated (eq next-char 0)))
(return))
(let ((current-group (utf-8-group-size next-char)))
(incf bytes-read current-group)
(cond ((= current-group 1)
(vector-push-extend (code-char next-char) string))
(t
(setf (elt buffer 0) next-char)
(loop :for i :from 1 :below current-group
:for next-char = (read-byte input nil :eof)
:do (when (eq next-char :eof)
(error 'utf-8-decoding-error
:message "Unfinished character at end of input."))
:do (setf (elt buffer i) next-char))
(vector-push-extend (code-char (get-utf-8-character
buffer current-group))
string))))))
string))
|
d6ce97c9b58b5db76cfbf93123785f5ce981eaced3f8b0b842cf26b53b8a49a6 | facebook/infer | loc.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(** Source code debug locations *)
type t = {dir: string; file: string; line: int; col: int}
[@@deriving compare, equal, sexp]
val pp : t pp
val none : t
val mk :
dir:string option
-> file:string option
-> line:int option
-> col:int option
-> t
val root : string option ref
(** Pathnames are printed relative to [root] if set. *)
| null | https://raw.githubusercontent.com/facebook/infer/b3a229f872003fe020455807668bc7a8edd22d5c/sledge/src/llair/loc.mli | ocaml | * Source code debug locations
* Pathnames are printed relative to [root] if set. |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
type t = {dir: string; file: string; line: int; col: int}
[@@deriving compare, equal, sexp]
val pp : t pp
val none : t
val mk :
dir:string option
-> file:string option
-> line:int option
-> col:int option
-> t
val root : string option ref
|
531f1f3bb9b9f9f88cf05d46a4e32b59ac86ad4bc7cbf82a8f250241a97169c6 | ssadler/piped | BenchPipes.hs | {-# LANGUAGE BangPatterns #-}
module BenchPipes where
import Data.Function (fix)
import Control.Monad
import Piped
import Piped.Internal
import Piped.Prelude as P
import Gauge.Main
import Prelude hiding (scanl, foldl, dropWhile, takeWhile)
benchPipes = bgroup "pipes"
[ bgroup "sinkNull" [ bench "monadic" $ whnfAppIO (runSink sinkNullM) 1000
, bench "yielding" $ whnfAppIO (runSink sinkNull) 1000
]
, bgroup "sinkList" [ bench "monadic" $ nfAppIO (runSink sinkListM) 1000
, bench "yielding" $ nfAppIO (runSink sinkList) 1000
]
, bgroup "foldl" [ bench "monadic" $ nfAppIO bFoldlM 10000
, bench "yielding" $ nfAppIO bFoldlY 10000
]
, bgroup "scanl" [ bench "monadic" $ nfAppIO bScanlM 10000
, bench "yielding" $ nfAppIO bScanlY 10000
]
, bgroup "dropWhile" [ bench "monadic" $ nfAppIO (bDoWhile dropWhile) 10000
, bench "yielding" $ nfAppIO (bDoWhile dropWhileY) 10000
]
, bgroup "takeWhile" [ bench "monadic" $ nfAppIO (bDoWhile takeWhile) 10000
, bench "yielding" $ nfAppIO (bDoWhile takeWhileY) 10000
]
, bgroup "identity" [ bench "monadic" $ nfAppIO (bIdentity identity) 1000
, bench "yielding" $ nfAppIO (bIdentity identityY) 1000
]
, bgroup " maybes " [ bench " awaitMaybe " $ nfAppIO ( bMaybes $ ) 10000
, bench " awaitJust " $ nfAppIO ( bMaybes $ awaitJust ) 10000
-- ]
, bgroup "map" [ bench "monadic" $ nfAppIO (bSimple $ P.map (+1)) 10000
, bench "yielding" $ nfAppIO (bSimple $ pmapMon (+1)) 10000
]
, bgroup "filter" [ bench "monadic" $ nfAppIO (bSimple $ P.filter even) 10000
, bench "yielding" $ nfAppIO (bSimple $ pFilter even) 10000
]
]
source :: Int -> Pipe () Int IO ()
source n = Prelude.mapM_ yield [0..n]
runSink :: Pipe Int Void IO a -> Int -> IO a
runSink sink n =
runPipe $ source n .| sink
sinkNullM :: Monad m => Pipe i Void m ()
sinkNullM = awaitForever (\_ -> pure ())
sinkListM :: Monad m => Pipe i Void m [i]
sinkListM = let f = awaitMaybe (pure []) (\i -> (i:) <$> f) in f
# INLINE sinkListM #
bFoldl p n = runPipe $ source n .| (p (+) 0 >> pure ())
bFoldlM n = runPipe $ source n .| (foldl' (+) 0 >> pure ())
bFoldlY n = runPipe $ source n .| (foldl (+) 0 >> pure ())
foldl' :: Monad m => (a -> i -> a) -> a -> Pipe i o m a
foldl' f s =
let next !s = awaitMaybe (pure s) (next . f s) in next s
{-# INLINE foldl' #-}
foldl ' : : = > ( a - > i - > a ) - > a - > Pipe i o m a
-- foldl' f start = Pipe $
-- \rest ->
-- fix1 start $
-- \next !s l r ->
-- runAwait l (rest termLeft r s) $
-- \i l -> next (f s i) l r
{ - # INLINE foldl ' # - }
bScanlM = runSink $ scanlM (+) 0 .| sinkNull
bScanlY = runSink $ scanl (+) 0 .| sinkNull
scanlM :: Monad m => (a -> b -> a) -> a -> Pipe b a m ()
scanlM f =
fix $ \next !s ->
yield s >> awaitJust (\i -> next $ f s i)
# INLINE scanlM #
bDoWhile p n = runPipe $ source n .| p (\_ -> True) .| sinkNull
dropWhileY :: Monad m => (i -> Bool) -> Pipe i i m ()
dropWhileY f = Pipe $
\rest ->
fix $ \next l r ->
runAwait l (rest termLeft r ()) $ \i l ->
if f i
then next l r
else let l' = addLeftover i l
in unPipe identity rest l' r
# INLINE dropWhileY #
takeWhileY :: Monad m => (i -> Bool) -> Pipe i i m ()
takeWhileY f = Pipe $
\rest ->
fix $ \next l r ->
runAwait l (rest termLeft r ()) $ \i l ->
if f i
then runYield r i $ next l
else rest l r ()
# INLINE takeWhileY #
bIdentity :: Pipe Int Int IO () -> Int -> IO ()
bIdentity p n = runPipe $ source n .| ((iterate (.| p) p) !! 10) .| sinkNull
identityY :: Pipe i i m ()
identityY = Pipe $
\rest ->
fix $ \next l r ->
runAwait l (rest termLeft r ()) $ \i l ->
runYield r i $ next l
# INLINE identityY #
bMaybes p n = runPipe $ source n .| go
where go = p $ (\_ -> go :: Pipe Int Void IO ())
bSimple p n = runPipe $ source n .| p .| sinkNull
pFilter :: (i -> Bool) -> Pipe i i m ()
pFilter f = Pipe $
\rest -> fix $
\next l r ->
runAwait l (rest termLeft r ()) $
\i l -> if f i
then runYield r i $ \r -> next l r
else next l r
# INLINE pFilter #
pmapMon :: (i -> o) -> Pipe i o m ()
pmapMon f = Pipe $
\rest -> fix $
\next l r ->
runAwait l (rest termLeft r ()) $
\i l -> runYield r (f i) $ \r -> next l r
| null | https://raw.githubusercontent.com/ssadler/piped/036c064d93f3d37f834c522a6e59c5baf44fdb6e/piped/test-bench/BenchPipes.hs | haskell | # LANGUAGE BangPatterns #
]
# INLINE foldl' #
foldl' f start = Pipe $
\rest ->
fix1 start $
\next !s l r ->
runAwait l (rest termLeft r s) $
\i l -> next (f s i) l r |
module BenchPipes where
import Data.Function (fix)
import Control.Monad
import Piped
import Piped.Internal
import Piped.Prelude as P
import Gauge.Main
import Prelude hiding (scanl, foldl, dropWhile, takeWhile)
benchPipes = bgroup "pipes"
[ bgroup "sinkNull" [ bench "monadic" $ whnfAppIO (runSink sinkNullM) 1000
, bench "yielding" $ whnfAppIO (runSink sinkNull) 1000
]
, bgroup "sinkList" [ bench "monadic" $ nfAppIO (runSink sinkListM) 1000
, bench "yielding" $ nfAppIO (runSink sinkList) 1000
]
, bgroup "foldl" [ bench "monadic" $ nfAppIO bFoldlM 10000
, bench "yielding" $ nfAppIO bFoldlY 10000
]
, bgroup "scanl" [ bench "monadic" $ nfAppIO bScanlM 10000
, bench "yielding" $ nfAppIO bScanlY 10000
]
, bgroup "dropWhile" [ bench "monadic" $ nfAppIO (bDoWhile dropWhile) 10000
, bench "yielding" $ nfAppIO (bDoWhile dropWhileY) 10000
]
, bgroup "takeWhile" [ bench "monadic" $ nfAppIO (bDoWhile takeWhile) 10000
, bench "yielding" $ nfAppIO (bDoWhile takeWhileY) 10000
]
, bgroup "identity" [ bench "monadic" $ nfAppIO (bIdentity identity) 1000
, bench "yielding" $ nfAppIO (bIdentity identityY) 1000
]
, bgroup " maybes " [ bench " awaitMaybe " $ nfAppIO ( bMaybes $ ) 10000
, bench " awaitJust " $ nfAppIO ( bMaybes $ awaitJust ) 10000
, bgroup "map" [ bench "monadic" $ nfAppIO (bSimple $ P.map (+1)) 10000
, bench "yielding" $ nfAppIO (bSimple $ pmapMon (+1)) 10000
]
, bgroup "filter" [ bench "monadic" $ nfAppIO (bSimple $ P.filter even) 10000
, bench "yielding" $ nfAppIO (bSimple $ pFilter even) 10000
]
]
source :: Int -> Pipe () Int IO ()
source n = Prelude.mapM_ yield [0..n]
runSink :: Pipe Int Void IO a -> Int -> IO a
runSink sink n =
runPipe $ source n .| sink
sinkNullM :: Monad m => Pipe i Void m ()
sinkNullM = awaitForever (\_ -> pure ())
sinkListM :: Monad m => Pipe i Void m [i]
sinkListM = let f = awaitMaybe (pure []) (\i -> (i:) <$> f) in f
# INLINE sinkListM #
bFoldl p n = runPipe $ source n .| (p (+) 0 >> pure ())
bFoldlM n = runPipe $ source n .| (foldl' (+) 0 >> pure ())
bFoldlY n = runPipe $ source n .| (foldl (+) 0 >> pure ())
foldl' :: Monad m => (a -> i -> a) -> a -> Pipe i o m a
foldl' f s =
let next !s = awaitMaybe (pure s) (next . f s) in next s
foldl ' : : = > ( a - > i - > a ) - > a - > Pipe i o m a
{ - # INLINE foldl ' # - }
bScanlM = runSink $ scanlM (+) 0 .| sinkNull
bScanlY = runSink $ scanl (+) 0 .| sinkNull
scanlM :: Monad m => (a -> b -> a) -> a -> Pipe b a m ()
scanlM f =
fix $ \next !s ->
yield s >> awaitJust (\i -> next $ f s i)
# INLINE scanlM #
bDoWhile p n = runPipe $ source n .| p (\_ -> True) .| sinkNull
dropWhileY :: Monad m => (i -> Bool) -> Pipe i i m ()
dropWhileY f = Pipe $
\rest ->
fix $ \next l r ->
runAwait l (rest termLeft r ()) $ \i l ->
if f i
then next l r
else let l' = addLeftover i l
in unPipe identity rest l' r
# INLINE dropWhileY #
takeWhileY :: Monad m => (i -> Bool) -> Pipe i i m ()
takeWhileY f = Pipe $
\rest ->
fix $ \next l r ->
runAwait l (rest termLeft r ()) $ \i l ->
if f i
then runYield r i $ next l
else rest l r ()
# INLINE takeWhileY #
bIdentity :: Pipe Int Int IO () -> Int -> IO ()
bIdentity p n = runPipe $ source n .| ((iterate (.| p) p) !! 10) .| sinkNull
identityY :: Pipe i i m ()
identityY = Pipe $
\rest ->
fix $ \next l r ->
runAwait l (rest termLeft r ()) $ \i l ->
runYield r i $ next l
# INLINE identityY #
bMaybes p n = runPipe $ source n .| go
where go = p $ (\_ -> go :: Pipe Int Void IO ())
bSimple p n = runPipe $ source n .| p .| sinkNull
pFilter :: (i -> Bool) -> Pipe i i m ()
pFilter f = Pipe $
\rest -> fix $
\next l r ->
runAwait l (rest termLeft r ()) $
\i l -> if f i
then runYield r i $ \r -> next l r
else next l r
# INLINE pFilter #
pmapMon :: (i -> o) -> Pipe i o m ()
pmapMon f = Pipe $
\rest -> fix $
\next l r ->
runAwait l (rest termLeft r ()) $
\i l -> runYield r (f i) $ \r -> next l r
|
b5be2a71d5e85fb6bd550bb7377f7aa91a0fa0b432915c4157beee06af29b30c | rtoy/ansi-cl-tests | hash-table-test.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Fri Nov 28 05:56:22 2003
;;;; Contains: Tests for HASH-TABLE-TEST
(in-package :cl-test)
(deftest hash-table-test.1
(hash-table-test (make-hash-table))
eql)
(deftest hash-table-test.2
(loop for test in '(eq eql equal equalp)
unless (eq (hash-table-test (make-hash-table :test test)) test)
collect test)
nil)
(deftest hash-table-test.3
(loop for test in '(eq eql equal equalp)
unless (eq (hash-table-test (make-hash-table
:test (symbol-function test)))
test)
collect test)
nil)
(deftest hash-table-test.4
(loop for test in '(eq eql equal equalp)
unless (eq (hash-table-test (make-hash-table
:test (eval `(function ,test))))
test)
collect test)
nil)
;;; Error cases
(deftest hash-table-test.error.1
(signals-error (hash-table-test) program-error)
t)
(deftest hash-table-test.error.2
(signals-error (hash-table-test (make-hash-table) nil) program-error)
t)
(deftest hash-table-test.error.3
(check-type-error #'hash-table-test #'hash-table-p)
nil)
| null | https://raw.githubusercontent.com/rtoy/ansi-cl-tests/9708f3977220c46def29f43bb237e97d62033c1d/hash-table-test.lsp | lisp | -*- Mode: Lisp -*-
Contains: Tests for HASH-TABLE-TEST
Error cases | Author :
Created : Fri Nov 28 05:56:22 2003
(in-package :cl-test)
(deftest hash-table-test.1
(hash-table-test (make-hash-table))
eql)
(deftest hash-table-test.2
(loop for test in '(eq eql equal equalp)
unless (eq (hash-table-test (make-hash-table :test test)) test)
collect test)
nil)
(deftest hash-table-test.3
(loop for test in '(eq eql equal equalp)
unless (eq (hash-table-test (make-hash-table
:test (symbol-function test)))
test)
collect test)
nil)
(deftest hash-table-test.4
(loop for test in '(eq eql equal equalp)
unless (eq (hash-table-test (make-hash-table
:test (eval `(function ,test))))
test)
collect test)
nil)
(deftest hash-table-test.error.1
(signals-error (hash-table-test) program-error)
t)
(deftest hash-table-test.error.2
(signals-error (hash-table-test (make-hash-table) nil) program-error)
t)
(deftest hash-table-test.error.3
(check-type-error #'hash-table-test #'hash-table-p)
nil)
|
67eab7e2b7d683c570edcc8638c9b2aea3606a826513483e4f3b9650b72d540e | naveensundarg/prover | jepd-relations.lisp | ;;; -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*-
File : jepd-relations.lisp
The contents of this file are subject to the Mozilla Public License
;;; Version 1.1 (the "License"); you may not use this file except in
;;; compliance with the License. You may obtain a copy of the License at
;;; /
;;;
Software distributed under the License is distributed on an " AS IS "
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
;;; License for the specific language governing rights and limitations
;;; under the License.
;;;
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 .
All Rights Reserved .
;;;
Contributor(s ): < > .
(in-package :snark)
;;; reasoning facilities for jointly-exhaustive and pairwise-disjoint sets of binary relations
;;; including
spatial regions ( RCC8 )
time intervals ( )
;;; time points
;;; that use composition tables to derive consequences and determine local consistency
;;; for theories implemented here, the main functions are
;;; declare-rcc8-relations
;;; declare-time-relations
;;; these declare the appropriate relation symbols
;;; (determined by the values of rcc8-jepd-relation-names, rcc8-more-relation-names, etc.)
;;; and declare procedural attachments for composing and intersecting disjunctions of
;;; jepd binary relations
;;; in the following encodings,
a primitive relation allowed to be true is signified by the constant 1
;;; a primitive relation required to be false is signified by a variable
;;; encoding "no" by variables this way makes factoring and subsumption do the right thing
;;; for example, here is the encoding of time interval-interval relations
;;; they are all translated to positive occurrences of time-ii-relation
0 ( before a b ) ( $ $ time - ii a b ( list 1 ? ? ? ? ? ? ? ? ? ? ? ? ) )
1 ( during a b ) ( $ $ time - ii a b ( list ? 1 ? ? ? ? ? ? ? ? ? ? ? ) )
2 ( overlaps a b ) ( $ $ time - ii a b ( list ? ? 1 ? ? ? ? ? ? ? ? ? ? ) )
3 ( meets a b ) ( $ $ time - ii a b ( list ? ? ? 1 ? ? ? ? ? ? ? ? ? ) )
4 ( starts a b ) ( $ $ time - ii a b ( list ? ? ? ? 1 ? ? ? ? ? ? ? ? ) )
5 ( finishes a b ) ( $ $ time - ii a b ( list ? ? ? ? ? 1 ? ? ? ? ? ? ? ) )
6 ( equal a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? 1 ? ? ? ? ? ? ) )
7 ( finished - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? 1 ? ? ? ? ? ) )
8 ( started - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? 1 ? ? ? ? ) )
9 ( met - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? 1 ? ? ? ) )
10 ( overlapped - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? ? 1 ? ? ) )
11 ( contains a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? ? ? 1 ? ) )
12 ( after a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? ? ? ? 1 ) )
( disjoint a b ) ( $ $ time - ii a b ( list 1 ? ? 1 ? ? ? ? ? 1 ? ? 1 ) )
( not ( before a b ) ) ( $ $ time - ii a b ( list ? 1 1 1 1 1 1 1 1 1 1 1 1 ) )
( not ( during a b ) ) ( $ $ time - ii a b ( list 1 ? 1 1 1 1 1 1 1 1 1 1 1 ) )
;;; etc.
these SNARK options can be used to specify the sort and relation names to be used
by setting them BEFORE executing ( declare - rcc8 - relations ) or ( declare - time - relations )
(declare-snark-option rcc8-region-sort-name 'region 'region)
(declare-snark-option time-interval-sort-name 'time-interval 'time-interval)
(declare-snark-option time-point-sort-name 'time-point 'time-point)
(defparameter rcc8-jepd-relation-names
0 tangential proper part - inverse of 7
1 nontangential proper part - inverse of 6
2 disconnected - self inverse
3 externally connected - self inverse
4 partially overlaps - self inverse
5 equality - self inverse
6 nontangential proper part inverse
7 tangential proper part inverse
(defparameter rcc8-more-relation-names ;composite relations and aliases
'($$rcc8-dr (2 3) ; discrete (complement of overlaps)
$$rcc8-pp (0 1) ; proper part
$$rcc8-p (0 1 5) ; part
$$rcc8-ppi (6 7) ; proper part inverse
$$rcc8-pi (5 6 7) ; part inverse
$$rcc8-o (0 1 4 5 6 7) ; overlaps (complement of discrete)
$$rcc8-c (0 1 3 4 5 6 7) ; connected (complement of disconnected)
$$rcc8-tp (0 5) ; tangential part
$$rcc8-tpi (5 7) ; tangential part inverse
;; rcc8-not-tpp etc. are unnecessary for input
;; since (not (rcc8-tpp ...)) etc. can be written instead
;; they are used to improve output using only positive literals
$$rcc8-not-tpp (1 2 3 4 5 6 7)
$$rcc8-not-ntpp (0 2 3 4 5 6 7)
$$rcc8-not-ec (0 1 2 4 5 6 7)
$$rcc8-not-po (0 1 2 3 5 6 7)
$$rcc8-not-eq (0 1 2 3 4 6 7)
$$rcc8-not-ntppi (0 1 2 3 4 5 7)
$$rcc8-not-tppi (0 1 2 3 4 5 6)
$$rcc8-not-pp (2 3 4 5 6 7)
$$rcc8-not-p (2 3 4 6 7)
$$rcc8-not-ppi (0 1 2 3 4 5)
$$rcc8-not-pi (0 1 2 3 4)
$$rcc8-not-tp (1 2 3 4 6 7)
$$rcc8-not-tpi (0 1 2 3 4 6)
))
(defparameter time-ii-jepd-relation-names
0 - inverse of 12
1 - inverse of 11
2 - inverse of 10
3 - inverse of 9
4 - inverse of 8
5 - inverse of 7
6 - self inverse
7
8
9
10
11
12
(defparameter time-ii-more-relation-names ;composite relations and aliases
'($$time-ii-starts-before (0 2 3 7 11)
$$time-ii-starts-equal (4 6 8)
$$time-ii-starts-after (1 5 9 10 12)
$$time-ii-finishes-before (0 1 2 3 4)
$$time-ii-finishes-equal (5 6 7)
$$time-ii-finishes-after (8 9 10 11 12)
$$time-ii-subsumes (6 7 8 11)
$$time-ii-subsumed-by (1 4 5 6)
$$time-ii-disjoint (0 3 9 12)
$$time-ii-intersects (1 2 4 5 6 7 8 10 11) ;complement of disjoint
;; time-ii-not-before etc. are unnecessary for input
;; since (not (before ...)) etc. can be written instead
;; they are used to improve output using only positive literals
$$time-ii-not-before (1 2 3 4 5 6 7 8 9 10 11 12)
$$time-ii-not-during (0 2 3 4 5 6 7 8 9 10 11 12)
$$time-ii-not-overlaps (0 1 3 4 5 6 7 8 9 10 11 12)
$$time-ii-not-meets (0 1 2 4 5 6 7 8 9 10 11 12)
$$time-ii-not-starts (0 1 2 3 5 6 7 8 9 10 11 12)
$$time-ii-not-finishes (0 1 2 3 4 6 7 8 9 10 11 12)
$$time-ii-not-equal (0 1 2 3 4 5 7 8 9 10 11 12)
$$time-ii-not-finished-by (0 1 2 3 4 5 6 8 9 10 11 12)
$$time-ii-not-started-by (0 1 2 3 4 5 6 7 9 10 11 12)
$$time-ii-not-met-by (0 1 2 3 4 5 6 7 8 10 11 12)
$$time-ii-not-overlapped-by (0 1 2 3 4 5 6 7 8 9 11 12)
$$time-ii-not-contains (0 1 2 3 4 5 6 7 8 9 10 12)
$$time-ii-not-after (0 1 2 3 4 5 6 7 8 9 10 11)
$$time-ii-not-starts-before (1 4 5 6 8 9 10 12)
$$time-ii-not-starts-equal (0 1 2 3 5 7 9 10 11 12)
$$time-ii-not-starts-after (0 2 3 4 6 7 8 11)
$$time-ii-not-finishes-before (5 6 7 8 9 10 11 12)
$$time-ii-not-finishes-equal (0 1 2 3 4 8 9 10 11 12)
$$time-ii-not-finishes-after (0 1 2 3 4 5 7 7)
$$time-ii-not-subsumes (0 1 2 3 4 5 9 10 12)
$$time-ii-not-subsumed-by (0 2 3 7 8 9 10 11 12)
$$time-ii-contained-by (1) ;alias of time-ii-during
))
(defparameter time-pp-jepd-relation-names
0 - inverse of 2
1 - self inverse
2
(defparameter time-pp-more-relation-names ;composite relations and aliases
'($$time-pp-not-before (1 2)
$$time-pp-not-equal (0 2)
$$time-pp-not-after (0 1)
))
(defparameter time-pi-jepd-relation-names
0
1
2
3
4
(defparameter time-pi-more-relation-names ;composite relations and aliases
'($$time-pi-disjoint (0 4)
$$time-pi-intersects (1 2 3) ;complement of disjoint
$$time-pi-not-before (1 2 3 4)
$$time-pi-not-starts (0 2 3 4)
$$time-pi-not-during (0 1 3 4)
$$time-pi-not-finishes (0 1 2 4)
$$time-pi-not-after (0 1 2 3)
$$time-pi-contained-by (2) ;alias of time-pi-during
))
;;; interval-point relations are converted to point-interval relations
(defparameter time-ip-jepd-relation-names
0
1
2
3
4
(defparameter time-ip-more-relation-names ;composite relations and aliases
'($$time-ip-disjoint (0 4)
$$time-ip-intersects (1 2 3) ;complement of disjoint
$$time-ip-not-after (1 2 3 4)
$$time-ip-not-started-by (0 2 3 4)
$$time-ip-not-contains (0 1 3 4)
$$time-ip-not-finished-by (0 1 2 4)
$$time-ip-not-before (0 1 2 3)
))
(defun jepd-relation-input-function (head args polarity rel reverse n i)
(cond
((eq :both polarity)
(throw 'needs-strict-polarity nil))
(t
(require-n-arguments head args polarity 2)
(let ((atom `(,rel ,@(if reverse (reverse args) args) ($$list ,@(1-or-?s n i polarity)))))
(input-wff1 (if (eq :pos polarity) atom `(not ,atom)) polarity)))))
(defun 1-or-?s (n i &optional (polarity :pos))
(let ((l nil) l-last)
(dotimes (k n)
(collect (if (if (consp i) (member k i) (eql i k))
(if (eq :pos polarity) 1 (make-variable))
(if (eq :pos polarity) (make-variable) 1))
l))
l))
(defun 1s-count (x &optional subst)
(dereference
x subst
:if-variable 0
:if-constant 0
:if-compound-appl 0
:if-compound-cons (let ((x1 (carc x)))
(if (dereference x1 subst :if-constant (eql 1 x1))
(+ (1s-count (cdrc x)) 1)
(1s-count (cdrc x))))))
(defun 1-indexes (x &optional subst (n 0))
(dereference
x subst
:if-variable nil
:if-constant nil
:if-compound-appl nil
:if-compound-cons (let ((x1 (carc x)))
(if (dereference x1 subst :if-constant (eql 1 x1))
(cons n (1-indexes (cdrc x) subst (+ n 1)))
(1-indexes (cdrc x) subst (+ n 1))))))
(defun jepd-relation-composition-rewriter (atom subst fun)
(let* ((args (args atom))
(l1 (pop args))
(l2 (pop args))
(x (pop args))
(y (pop args))
(z (first args)))
(cond
((or (equal-p x y subst) ;don't compose (r1 a a) and (r2 a b)
(equal-p y z subst) ;don't compose (r1 a b) and (r2 b b)
(and (test-option17?)
(equal-p x z subst))) ;don't compose (r1 a b) and (r2 b a)
true)
((and (dereference l1 subst :if-compound-cons t)
(dereference l2 subst :if-compound-cons t))
(funcall fun l1 l2 x y z subst)) ;get result using theory's composition table
(t
none)))) ;useless consequences of the axioms?
(defun jepd-relation-composition-rewriter1 (atom subst rel table &optional (n (first (array-dimensions table))))
(jepd-relation-composition-rewriter
atom
subst
(lambda (l1 l2 x y z subst)
(declare (ignore y))
(let ((result (make-array n :initial-element nil))
(i 0))
(dolist (v l1)
(when (dereference v subst :if-constant t)
(let ((j 0))
(dolist (v l2)
(when (dereference v subst :if-constant t)
(dolist (v (aref table i j))
(setf (svref result v) t)))
(incf j))))
(incf i))
(cond
((every #'identity result)
true)
(t
(make-compound
rel
x
z
(let ((l nil) l-last)
(dotimes (i n)
(collect (if (svref result i) 1 (make-and-freeze-variable)) l))
l))))))))
(defun reversem (l m &optional (n (length l)))
(nconc (nreverse (subseq l (- n m) n))
(subseq l m (- n m))
(nreverse (subseq l 0 m))))
(defun xx-intersection (l1 l2 subst)
;; fresh variables returned
(dereference l1 subst)
(dereference l2 subst)
(if (null l1)
nil
(cons (or (let ((x (first l1))) (dereference x subst :if-variable (make-and-freeze-variable)))
(let ((x (first l2))) (dereference x subst :if-variable (make-and-freeze-variable)))
1)
(xx-intersection (rest l1) (rest l2) subst))))
(defun jepd-relation-intersection-rewriter1 (rel atom subst invert)
(let* ((args (args atom))
(l1 (pop args))
(l2 (pop args)))
(cond
((and (dereference l1 subst :if-compound-cons t)
(dereference l2 subst :if-compound-cons t))
(let ((l (xx-intersection l1 l2 subst)))
(cond
((not (member 1 l))
false)
((and invert (test-option17?))
(make-compound rel (second args) (first args) (reversem l invert)))
(t
(make-compound rel (first args) (second args) l)))))
((and (dereference l1 subst :if-variable t)
(dereference l2 subst :if-variable t)
(eq l1 l2))
true) ;useless consequences of the axioms?
(t
none))))
(defun jepd-relation-atom-weight (x &optional subst)
(let ((args (args x)))
(+ (weight (pop args) subst)
(weight (pop args) subst)
(1s-count (first args) subst)
(function-weight (head x)))))
(defun declare-jepd-relation (relname sort names more-names invert)
(let ((use-special-unification (and invert (not (test-option17?)))))
(declare-relation1
relname 3
:rewrite-code 'jepd-relation-atom-rewriter
:sort sort
:equal-code (and use-special-unification
(lambda (x y subst)
(equal-jepd-relation-atom-args-p (args x) (args y) subst invert)))
:variant-code (and use-special-unification
(lambda (cc x y subst matches)
(variant-jepd-relation-atom-args cc (args x) (args y) subst matches invert)))
:unify-code (and use-special-unification
(lambda (cc x y subst)
(unify-jepd-relation-atom-args cc (args x) (args y) subst invert)))
:index-type (and use-special-unification :jepd)
:ordering-status (if use-special-unification :commutative :left-to-right)
:to-lisp-code #'(lambda (head args subst) (jepd-atom-to-lisp head args subst names more-names))
:weight-code 'jepd-relation-atom-weight)))
(defun declare-jepd-relation-input (relname names more-names n reverse)
(let ((i 0))
(dolist (name names)
(declare-relation1
name :any
:macro t
:input-code (let ((i i))
(lambda (head args polarity)
(jepd-relation-input-function head args polarity relname reverse n i))))
(incf i)))
(do ((l more-names (cddr l)))
((endp l)
)
(declare-relation1
(first l) :any
:macro t
:input-code (let ((i (second l)))
(lambda (head args polarity)
(jepd-relation-input-function head args polarity relname reverse n i))))))
(defun declare-equality-jepd-relation (relname sort n equality)
(when equality
(cl:assert (same-sort? (first sort) (second sort)))
(assert `(forall ((?x :sort ,(first sort)))
(,relname ?x ?x ($$list ,@(1-or-?s n equality))))
:name (intern (to-string relname :-equality) :keyword)
:supported nil)))
(defun declare-jepd-relation-intersection (relname rel sort invert)
(let ((intersection (intern (to-string relname :-intersection) :snark)))
(declare-relation1
intersection 4
:rewrite-code (list
(lambda (atom subst)
(jepd-relation-intersection-rewriter1 rel atom subst invert))))
(assert `(forall ((?x :sort ,(first sort))
(?y :sort ,(second sort))
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) (,relname ?x ?y ?l2))
(,intersection ?l1 ?l2 ?x ?y)))
:name (intern (symbol-name intersection) :keyword)
:supported nil)))
(defun declare-jepd-relations (relname sort composition invert equality names more-names)
three operations may be necessary :
;; intersection: (r1 a b) & (r2 a b) -> (r1&r2 a b)
;; inverse: (r1 a b) -> (r1' b a)
;; composition: (r1 a b) & (r2 b c) -> (r3 a c)
;;
;; if inverse is necessary, it is incorporated into the intersection operation:
;; intersection: (r1 a b) & (r2 a b) -> (r1&r2 b a)
;; so that only composition and (possibly inverting) intersection are used
(let ((n (length names))
(rel (declare-jepd-relation relname sort names more-names invert)))
(declare-jepd-relation-input relname names more-names n nil)
(declare-equality-jepd-relation relname sort n equality)
(declare-jepd-relation-intersection relname rel sort invert)
(let ((table composition)
(composition (intern (to-string relname :-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table))))
(assert `(forall ((?x :sort ,(first sort))
(?y :sort ,(second sort)) ;sorts should be the same
(?z :sort ,(second sort))
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) (,relname ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))))
(defun jepd-relation-code (x alist)
(let ((v (assoc x alist)))
(cl:assert v)
(cdr v)))
(defun make-composition-table (tab ocode &optional (icode1 ocode) (icode2 ocode))
(let* ((nrows (length icode1))
(ncols (length icode2))
(table (make-array (list nrows ncols) :initial-element nil)))
(dolist (x tab)
(let ((i (jepd-relation-code (first x) icode1))
(j (jepd-relation-code (second x) icode2)))
(cl:assert (null (aref table i j)))
(setf (aref table i j) (mapcar (lambda (x) (jepd-relation-code x ocode)) (cddr x)))))
(dotimes (i nrows)
(dotimes (j ncols)
(cl:assert (not (null (aref table i j))))))
table))
(defvar *rcc8-composition-table* nil)
(defvar *time-iii-composition-table* nil)
(defvar *time-ipi-composition-table* nil)
(defvar *time-pii-composition-table* nil)
(defvar *time-pip-composition-table* nil)
(defvar *time-ppi-composition-table* nil)
(defvar *time-ppp-composition-table* nil)
(defun firsta (x)
(if (consp x) (first x) x))
(defun resta (x)
(if (consp x) (rest x) nil))
(defun declare-rcc8-relations ()
;; this function should not be done more than once after (initialize)
(let ((region-sort (rcc8-region-sort-name?)))
(unless (sort-name? region-sort)
(let ((l (resta region-sort)))
(apply 'declare-sort (setf region-sort (firsta region-sort)) l)))
(declare-jepd-relations
'$$rcc8
(list region-sort region-sort)
(or *rcc8-composition-table*
(setf *rcc8-composition-table* (make-composition-table
$rcc8-composition-table
$rcc8-relation-code)))
2
(jepd-relation-code 'eq $rcc8-relation-code)
rcc8-jepd-relation-names
rcc8-more-relation-names)))
(defun declare-time-relations (&key intervals points dates)
;; this function should not be done more than once after (initialize)
(unless (or intervals points)
(setf intervals t points t))
(when dates
(setf points t))
(let ((interval-sort (time-interval-sort-name?))
(point-sort (time-point-sort-name?)))
(when intervals
(unless (sort-name? interval-sort)
(let ((l (resta interval-sort)))
(apply 'declare-sort (setf interval-sort (firsta interval-sort)) l)))
(declare-jepd-relations
'$$time-ii
(list interval-sort interval-sort)
(or *time-iii-composition-table*
(setf *time-iii-composition-table* (make-composition-table
$time-iii-composition-table
$time-ii-relation-code)))
6
(jepd-relation-code '= $time-ii-relation-code)
time-ii-jepd-relation-names
time-ii-more-relation-names))
(when points
(unless (sort-name? point-sort)
(let ((l (resta point-sort)))
(apply 'declare-sort (setf point-sort (firsta point-sort)) l)))
(declare-jepd-relations
'$$time-pp
(list point-sort point-sort)
(or *time-ppp-composition-table*
(setf *time-ppp-composition-table* (make-composition-table
$time-ppp-composition-table
$time-pp-relation-code)))
1
(jepd-relation-code 'p=p $time-pp-relation-code)
time-pp-jepd-relation-names
time-pp-more-relation-names))
(when (and intervals points)
(unless (or (top-sort-name? interval-sort) (top-sort-name? point-sort))
(declare-sorts-incompatible interval-sort point-sort))
(let* ((relname '$$time-pi)
(sort (list point-sort interval-sort))
(names time-pi-jepd-relation-names)
(more-names time-pi-more-relation-names)
(n (length names))
(rel (declare-jepd-relation relname sort names more-names nil)))
(declare-jepd-relation-input relname names more-names n nil)
;; convert interval-point relations to point-interval relations
(setf names time-ip-jepd-relation-names)
(cl:assert (eql n (length names)))
(declare-jepd-relation-input relname names time-ip-more-relation-names n t)
(declare-jepd-relation-intersection relname rel sort nil)
;;; PI * II -> PI composition
(let ((composition (intern (to-string relname :-ii-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((table (or *time-pii-composition-table*
(setf *time-pii-composition-table* (make-composition-table
$time-pii-composition-table
$time-pi-relation-code
$time-pi-relation-code
$time-ii-relation-code))))
(n (length $time-pi-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,point-sort)
(?y :sort ,interval-sort)
(?z :sort ,interval-sort)
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) ($$time-ii ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))
;;; PP * PI -> PI composition
(let ((composition (intern (to-string relname :-pp-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((table (or *time-ppi-composition-table*
(setf *time-ppi-composition-table* (make-composition-table
$time-ppi-composition-table
$time-pi-relation-code
$time-pp-relation-code
$time-pi-relation-code))))
(n (length $time-pi-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,point-sort)
(?y :sort ,point-sort)
(?z :sort ,interval-sort)
?l1
?l2)
(implies (and ($$time-pp ?x ?y ?l1) (,relname ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))
;;; PI * IP -> PP composition
(let ((composition (intern (to-string relname :-pi-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((rel (input-relation-symbol '$$time-pp 3))
(table (or *time-pip-composition-table*
(setf *time-pip-composition-table* (make-composition-table
$time-pip-composition-table
$time-pp-relation-code
$time-pi-relation-code
$time-ip-relation-code))))
(n (length $time-pp-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,point-sort)
(?y :sort ,interval-sort)
(?z :sort ,point-sort)
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) (,relname ?z ?y ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))
;;; IP * PI -> II composition
(let ((composition (intern (to-string relname :-pi-composition2) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((rel (input-relation-symbol '$$time-ii 3))
(table (or *time-ipi-composition-table*
(setf *time-ipi-composition-table* (make-composition-table
$time-ipi-composition-table
$time-ii-relation-code
$time-ip-relation-code
$time-pi-relation-code))))
(n (length $time-ii-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,interval-sort)
(?y :sort ,point-sort)
(?z :sort ,interval-sort)
?l1
?l2)
(implies (and (,relname ?y ?x ?l1) (,relname ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))))
(when dates
(declare-date-functions :intervals intervals :points points))
nil))
(defun jepd-atom-to-lisp (head args subst &optional names more-names)
(let* ((arg1 (term-to-lisp (pop args) subst))
(arg2 (term-to-lisp (pop args) subst))
(arg3 (first args))
(rels (and names (1-indexes arg3 subst))))
(cond
((null rels)
(list (function-name head) arg1 arg2 (term-to-lisp arg3 subst)))
((null (rest rels))
(list (function-name (input-relation-symbol (nth (first rels) names) 2)) arg1 arg2))
((do ((l more-names (cddr l)))
((null l)
nil)
(when (equal rels (second l))
(return (list (function-name (input-relation-symbol (first l) 2)) arg1 arg2)))))
(t
(let ((l nil) l-last)
(dolist (rel rels)
(collect (list (function-name (input-relation-symbol (nth rel names) 2)) arg1 arg2) l))
(cons 'or-jepd l))))))
(defun equal-jepd-relation-atom-args-p (args1 args2 subst invert)
lists of possible relations in third argument are compared by variant - p instead of equal - p
;; after inversion; all the variables in a list of possible relations are required to be unique,
;; so their exact identity is unimportant
(let ((x1 (pop args1)) (y1 (pop args1)) (rels1 (first args1))
(x2 (pop args2)) (y2 (pop args2)) (rels2 (first args2)))
(or (and (equal-p x1 x2 subst)
(equal-p y1 y2 subst)
(equal-p rels1 rels2 subst))
(and (dereference rels1 subst :if-compound-cons t)
(dereference rels2 subst :if-compound-cons t)
(and (equal-p x1 y2 subst)
(equal-p y1 x2 subst)
(variant-p rels1 (reversem rels2 invert) subst))))))
(defun variant-jepd-relation-atom-args (cc args1 args2 subst matches invert)
(let ((x1 (pop args1)) (y1 (pop args1)) (rels1 (first args1))
(x2 (pop args2)) (y2 (pop args2)) (rels2 (first args2)))
(prog->
(variant x1 x2 subst matches ->* matches)
(variant y1 y2 subst matches ->* matches)
(variant rels1 rels2 subst matches ->* matches)
(funcall cc matches))
(when (and (dereference rels1 subst :if-compound-cons t)
(dereference rels2 subst :if-compound-cons t))
(prog->
(quote nil -> rels2*)
(variant x1 y2 subst matches ->* matches)
(variant y1 x2 subst matches ->* matches)
(variant rels1 (or rels2* (setf rels2* (reversem rels2 invert))) subst matches ->* matches)
(funcall cc matches)))))
(defun unify-jepd-relation-atom-args (cc args1 args2 subst invert)
(let ((x1 (pop args1)) (y1 (pop args1)) (rels1 (first args1))
(x2 (pop args2)) (y2 (pop args2)) (rels2 (first args2)))
(prog->
(unify x1 x2 subst ->* subst)
(unify y1 y2 subst ->* subst)
(unify rels1 rels2 subst ->* subst)
(funcall cc subst))
(cond
((dereference rels2 subst :if-compound-cons t)
(prog->
(quote nil -> rels2*)
(unify x1 y2 subst ->* subst)
(unify y1 x2 subst ->* subst)
(unify rels1 (or rels2* (setf rels2* (reversem rels2 invert))) subst ->* subst)
(funcall cc subst)))
((dereference rels1 subst :if-compound-cons t)
(prog->
(quote nil -> rels1*)
(unify y1 x2 subst ->* subst)
(unify x1 y2 subst ->* subst)
(unify (or rels1* (setf rels1* (reversem rels1 invert))) rels2 subst ->* subst)
(funcall cc subst))))))
(defun jepd-relation-atom-rewriter (atom subst)
;; replace by true
;; atoms like (time-pp-relation a b (list 1 1 1))
;; that can be produced by factoring
(let ((v (third (args atom))))
(if (dereference
v subst
:if-compound-cons (dolist (x v t)
(dereference x subst :if-variable (return nil))))
true
none)))
jepd-relations.lisp
| null | https://raw.githubusercontent.com/naveensundarg/prover/812baf098d8bf77e4d634cef4d12de94dcd1e113/snark-20120808r02/src/jepd-relations.lisp | lisp | -*- Mode: Lisp; Syntax: Common-Lisp; Package: snark -*-
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
reasoning facilities for jointly-exhaustive and pairwise-disjoint sets of binary relations
including
time points
that use composition tables to derive consequences and determine local consistency
for theories implemented here, the main functions are
declare-rcc8-relations
declare-time-relations
these declare the appropriate relation symbols
(determined by the values of rcc8-jepd-relation-names, rcc8-more-relation-names, etc.)
and declare procedural attachments for composing and intersecting disjunctions of
jepd binary relations
in the following encodings,
a primitive relation required to be false is signified by a variable
encoding "no" by variables this way makes factoring and subsumption do the right thing
for example, here is the encoding of time interval-interval relations
they are all translated to positive occurrences of time-ii-relation
etc.
composite relations and aliases
discrete (complement of overlaps)
proper part
part
proper part inverse
part inverse
overlaps (complement of discrete)
connected (complement of disconnected)
tangential part
tangential part inverse
rcc8-not-tpp etc. are unnecessary for input
since (not (rcc8-tpp ...)) etc. can be written instead
they are used to improve output using only positive literals
composite relations and aliases
complement of disjoint
time-ii-not-before etc. are unnecessary for input
since (not (before ...)) etc. can be written instead
they are used to improve output using only positive literals
alias of time-ii-during
composite relations and aliases
composite relations and aliases
complement of disjoint
alias of time-pi-during
interval-point relations are converted to point-interval relations
composite relations and aliases
complement of disjoint
don't compose (r1 a a) and (r2 a b)
don't compose (r1 a b) and (r2 b b)
don't compose (r1 a b) and (r2 b a)
get result using theory's composition table
useless consequences of the axioms?
fresh variables returned
useless consequences of the axioms?
intersection: (r1 a b) & (r2 a b) -> (r1&r2 a b)
inverse: (r1 a b) -> (r1' b a)
composition: (r1 a b) & (r2 b c) -> (r3 a c)
if inverse is necessary, it is incorporated into the intersection operation:
intersection: (r1 a b) & (r2 a b) -> (r1&r2 b a)
so that only composition and (possibly inverting) intersection are used
sorts should be the same
this function should not be done more than once after (initialize)
this function should not be done more than once after (initialize)
convert interval-point relations to point-interval relations
PI * II -> PI composition
PP * PI -> PI composition
PI * IP -> PP composition
IP * PI -> II composition
after inversion; all the variables in a list of possible relations are required to be unique,
so their exact identity is unimportant
replace by true
atoms like (time-pp-relation a b (list 1 1 1))
that can be produced by factoring | File : jepd-relations.lisp
The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is SNARK .
The Initial Developer of the Original Code is SRI International .
Portions created by the Initial Developer are Copyright ( C ) 1981 - 2011 .
All Rights Reserved .
Contributor(s ): < > .
(in-package :snark)
spatial regions ( RCC8 )
time intervals ( )
a primitive relation allowed to be true is signified by the constant 1
0 ( before a b ) ( $ $ time - ii a b ( list 1 ? ? ? ? ? ? ? ? ? ? ? ? ) )
1 ( during a b ) ( $ $ time - ii a b ( list ? 1 ? ? ? ? ? ? ? ? ? ? ? ) )
2 ( overlaps a b ) ( $ $ time - ii a b ( list ? ? 1 ? ? ? ? ? ? ? ? ? ? ) )
3 ( meets a b ) ( $ $ time - ii a b ( list ? ? ? 1 ? ? ? ? ? ? ? ? ? ) )
4 ( starts a b ) ( $ $ time - ii a b ( list ? ? ? ? 1 ? ? ? ? ? ? ? ? ) )
5 ( finishes a b ) ( $ $ time - ii a b ( list ? ? ? ? ? 1 ? ? ? ? ? ? ? ) )
6 ( equal a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? 1 ? ? ? ? ? ? ) )
7 ( finished - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? 1 ? ? ? ? ? ) )
8 ( started - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? 1 ? ? ? ? ) )
9 ( met - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? 1 ? ? ? ) )
10 ( overlapped - by a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? ? 1 ? ? ) )
11 ( contains a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? ? ? 1 ? ) )
12 ( after a b ) ( $ $ time - ii a b ( list ? ? ? ? ? ? ? ? ? ? ? ? 1 ) )
( disjoint a b ) ( $ $ time - ii a b ( list 1 ? ? 1 ? ? ? ? ? 1 ? ? 1 ) )
( not ( before a b ) ) ( $ $ time - ii a b ( list ? 1 1 1 1 1 1 1 1 1 1 1 1 ) )
( not ( during a b ) ) ( $ $ time - ii a b ( list 1 ? 1 1 1 1 1 1 1 1 1 1 1 ) )
these SNARK options can be used to specify the sort and relation names to be used
by setting them BEFORE executing ( declare - rcc8 - relations ) or ( declare - time - relations )
(declare-snark-option rcc8-region-sort-name 'region 'region)
(declare-snark-option time-interval-sort-name 'time-interval 'time-interval)
(declare-snark-option time-point-sort-name 'time-point 'time-point)
(defparameter rcc8-jepd-relation-names
0 tangential proper part - inverse of 7
1 nontangential proper part - inverse of 6
2 disconnected - self inverse
3 externally connected - self inverse
4 partially overlaps - self inverse
5 equality - self inverse
6 nontangential proper part inverse
7 tangential proper part inverse
$$rcc8-not-tpp (1 2 3 4 5 6 7)
$$rcc8-not-ntpp (0 2 3 4 5 6 7)
$$rcc8-not-ec (0 1 2 4 5 6 7)
$$rcc8-not-po (0 1 2 3 5 6 7)
$$rcc8-not-eq (0 1 2 3 4 6 7)
$$rcc8-not-ntppi (0 1 2 3 4 5 7)
$$rcc8-not-tppi (0 1 2 3 4 5 6)
$$rcc8-not-pp (2 3 4 5 6 7)
$$rcc8-not-p (2 3 4 6 7)
$$rcc8-not-ppi (0 1 2 3 4 5)
$$rcc8-not-pi (0 1 2 3 4)
$$rcc8-not-tp (1 2 3 4 6 7)
$$rcc8-not-tpi (0 1 2 3 4 6)
))
(defparameter time-ii-jepd-relation-names
0 - inverse of 12
1 - inverse of 11
2 - inverse of 10
3 - inverse of 9
4 - inverse of 8
5 - inverse of 7
6 - self inverse
7
8
9
10
11
12
'($$time-ii-starts-before (0 2 3 7 11)
$$time-ii-starts-equal (4 6 8)
$$time-ii-starts-after (1 5 9 10 12)
$$time-ii-finishes-before (0 1 2 3 4)
$$time-ii-finishes-equal (5 6 7)
$$time-ii-finishes-after (8 9 10 11 12)
$$time-ii-subsumes (6 7 8 11)
$$time-ii-subsumed-by (1 4 5 6)
$$time-ii-disjoint (0 3 9 12)
$$time-ii-not-before (1 2 3 4 5 6 7 8 9 10 11 12)
$$time-ii-not-during (0 2 3 4 5 6 7 8 9 10 11 12)
$$time-ii-not-overlaps (0 1 3 4 5 6 7 8 9 10 11 12)
$$time-ii-not-meets (0 1 2 4 5 6 7 8 9 10 11 12)
$$time-ii-not-starts (0 1 2 3 5 6 7 8 9 10 11 12)
$$time-ii-not-finishes (0 1 2 3 4 6 7 8 9 10 11 12)
$$time-ii-not-equal (0 1 2 3 4 5 7 8 9 10 11 12)
$$time-ii-not-finished-by (0 1 2 3 4 5 6 8 9 10 11 12)
$$time-ii-not-started-by (0 1 2 3 4 5 6 7 9 10 11 12)
$$time-ii-not-met-by (0 1 2 3 4 5 6 7 8 10 11 12)
$$time-ii-not-overlapped-by (0 1 2 3 4 5 6 7 8 9 11 12)
$$time-ii-not-contains (0 1 2 3 4 5 6 7 8 9 10 12)
$$time-ii-not-after (0 1 2 3 4 5 6 7 8 9 10 11)
$$time-ii-not-starts-before (1 4 5 6 8 9 10 12)
$$time-ii-not-starts-equal (0 1 2 3 5 7 9 10 11 12)
$$time-ii-not-starts-after (0 2 3 4 6 7 8 11)
$$time-ii-not-finishes-before (5 6 7 8 9 10 11 12)
$$time-ii-not-finishes-equal (0 1 2 3 4 8 9 10 11 12)
$$time-ii-not-finishes-after (0 1 2 3 4 5 7 7)
$$time-ii-not-subsumes (0 1 2 3 4 5 9 10 12)
$$time-ii-not-subsumed-by (0 2 3 7 8 9 10 11 12)
))
(defparameter time-pp-jepd-relation-names
0 - inverse of 2
1 - self inverse
2
'($$time-pp-not-before (1 2)
$$time-pp-not-equal (0 2)
$$time-pp-not-after (0 1)
))
(defparameter time-pi-jepd-relation-names
0
1
2
3
4
'($$time-pi-disjoint (0 4)
$$time-pi-not-before (1 2 3 4)
$$time-pi-not-starts (0 2 3 4)
$$time-pi-not-during (0 1 3 4)
$$time-pi-not-finishes (0 1 2 4)
$$time-pi-not-after (0 1 2 3)
))
(defparameter time-ip-jepd-relation-names
0
1
2
3
4
'($$time-ip-disjoint (0 4)
$$time-ip-not-after (1 2 3 4)
$$time-ip-not-started-by (0 2 3 4)
$$time-ip-not-contains (0 1 3 4)
$$time-ip-not-finished-by (0 1 2 4)
$$time-ip-not-before (0 1 2 3)
))
(defun jepd-relation-input-function (head args polarity rel reverse n i)
(cond
((eq :both polarity)
(throw 'needs-strict-polarity nil))
(t
(require-n-arguments head args polarity 2)
(let ((atom `(,rel ,@(if reverse (reverse args) args) ($$list ,@(1-or-?s n i polarity)))))
(input-wff1 (if (eq :pos polarity) atom `(not ,atom)) polarity)))))
(defun 1-or-?s (n i &optional (polarity :pos))
(let ((l nil) l-last)
(dotimes (k n)
(collect (if (if (consp i) (member k i) (eql i k))
(if (eq :pos polarity) 1 (make-variable))
(if (eq :pos polarity) (make-variable) 1))
l))
l))
(defun 1s-count (x &optional subst)
(dereference
x subst
:if-variable 0
:if-constant 0
:if-compound-appl 0
:if-compound-cons (let ((x1 (carc x)))
(if (dereference x1 subst :if-constant (eql 1 x1))
(+ (1s-count (cdrc x)) 1)
(1s-count (cdrc x))))))
(defun 1-indexes (x &optional subst (n 0))
(dereference
x subst
:if-variable nil
:if-constant nil
:if-compound-appl nil
:if-compound-cons (let ((x1 (carc x)))
(if (dereference x1 subst :if-constant (eql 1 x1))
(cons n (1-indexes (cdrc x) subst (+ n 1)))
(1-indexes (cdrc x) subst (+ n 1))))))
(defun jepd-relation-composition-rewriter (atom subst fun)
(let* ((args (args atom))
(l1 (pop args))
(l2 (pop args))
(x (pop args))
(y (pop args))
(z (first args)))
(cond
(and (test-option17?)
true)
((and (dereference l1 subst :if-compound-cons t)
(dereference l2 subst :if-compound-cons t))
(t
(defun jepd-relation-composition-rewriter1 (atom subst rel table &optional (n (first (array-dimensions table))))
(jepd-relation-composition-rewriter
atom
subst
(lambda (l1 l2 x y z subst)
(declare (ignore y))
(let ((result (make-array n :initial-element nil))
(i 0))
(dolist (v l1)
(when (dereference v subst :if-constant t)
(let ((j 0))
(dolist (v l2)
(when (dereference v subst :if-constant t)
(dolist (v (aref table i j))
(setf (svref result v) t)))
(incf j))))
(incf i))
(cond
((every #'identity result)
true)
(t
(make-compound
rel
x
z
(let ((l nil) l-last)
(dotimes (i n)
(collect (if (svref result i) 1 (make-and-freeze-variable)) l))
l))))))))
(defun reversem (l m &optional (n (length l)))
(nconc (nreverse (subseq l (- n m) n))
(subseq l m (- n m))
(nreverse (subseq l 0 m))))
(defun xx-intersection (l1 l2 subst)
(dereference l1 subst)
(dereference l2 subst)
(if (null l1)
nil
(cons (or (let ((x (first l1))) (dereference x subst :if-variable (make-and-freeze-variable)))
(let ((x (first l2))) (dereference x subst :if-variable (make-and-freeze-variable)))
1)
(xx-intersection (rest l1) (rest l2) subst))))
(defun jepd-relation-intersection-rewriter1 (rel atom subst invert)
(let* ((args (args atom))
(l1 (pop args))
(l2 (pop args)))
(cond
((and (dereference l1 subst :if-compound-cons t)
(dereference l2 subst :if-compound-cons t))
(let ((l (xx-intersection l1 l2 subst)))
(cond
((not (member 1 l))
false)
((and invert (test-option17?))
(make-compound rel (second args) (first args) (reversem l invert)))
(t
(make-compound rel (first args) (second args) l)))))
((and (dereference l1 subst :if-variable t)
(dereference l2 subst :if-variable t)
(eq l1 l2))
(t
none))))
(defun jepd-relation-atom-weight (x &optional subst)
(let ((args (args x)))
(+ (weight (pop args) subst)
(weight (pop args) subst)
(1s-count (first args) subst)
(function-weight (head x)))))
(defun declare-jepd-relation (relname sort names more-names invert)
(let ((use-special-unification (and invert (not (test-option17?)))))
(declare-relation1
relname 3
:rewrite-code 'jepd-relation-atom-rewriter
:sort sort
:equal-code (and use-special-unification
(lambda (x y subst)
(equal-jepd-relation-atom-args-p (args x) (args y) subst invert)))
:variant-code (and use-special-unification
(lambda (cc x y subst matches)
(variant-jepd-relation-atom-args cc (args x) (args y) subst matches invert)))
:unify-code (and use-special-unification
(lambda (cc x y subst)
(unify-jepd-relation-atom-args cc (args x) (args y) subst invert)))
:index-type (and use-special-unification :jepd)
:ordering-status (if use-special-unification :commutative :left-to-right)
:to-lisp-code #'(lambda (head args subst) (jepd-atom-to-lisp head args subst names more-names))
:weight-code 'jepd-relation-atom-weight)))
(defun declare-jepd-relation-input (relname names more-names n reverse)
(let ((i 0))
(dolist (name names)
(declare-relation1
name :any
:macro t
:input-code (let ((i i))
(lambda (head args polarity)
(jepd-relation-input-function head args polarity relname reverse n i))))
(incf i)))
(do ((l more-names (cddr l)))
((endp l)
)
(declare-relation1
(first l) :any
:macro t
:input-code (let ((i (second l)))
(lambda (head args polarity)
(jepd-relation-input-function head args polarity relname reverse n i))))))
(defun declare-equality-jepd-relation (relname sort n equality)
(when equality
(cl:assert (same-sort? (first sort) (second sort)))
(assert `(forall ((?x :sort ,(first sort)))
(,relname ?x ?x ($$list ,@(1-or-?s n equality))))
:name (intern (to-string relname :-equality) :keyword)
:supported nil)))
(defun declare-jepd-relation-intersection (relname rel sort invert)
(let ((intersection (intern (to-string relname :-intersection) :snark)))
(declare-relation1
intersection 4
:rewrite-code (list
(lambda (atom subst)
(jepd-relation-intersection-rewriter1 rel atom subst invert))))
(assert `(forall ((?x :sort ,(first sort))
(?y :sort ,(second sort))
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) (,relname ?x ?y ?l2))
(,intersection ?l1 ?l2 ?x ?y)))
:name (intern (symbol-name intersection) :keyword)
:supported nil)))
(defun declare-jepd-relations (relname sort composition invert equality names more-names)
three operations may be necessary :
(let ((n (length names))
(rel (declare-jepd-relation relname sort names more-names invert)))
(declare-jepd-relation-input relname names more-names n nil)
(declare-equality-jepd-relation relname sort n equality)
(declare-jepd-relation-intersection relname rel sort invert)
(let ((table composition)
(composition (intern (to-string relname :-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table))))
(assert `(forall ((?x :sort ,(first sort))
(?z :sort ,(second sort))
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) (,relname ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))))
(defun jepd-relation-code (x alist)
(let ((v (assoc x alist)))
(cl:assert v)
(cdr v)))
(defun make-composition-table (tab ocode &optional (icode1 ocode) (icode2 ocode))
(let* ((nrows (length icode1))
(ncols (length icode2))
(table (make-array (list nrows ncols) :initial-element nil)))
(dolist (x tab)
(let ((i (jepd-relation-code (first x) icode1))
(j (jepd-relation-code (second x) icode2)))
(cl:assert (null (aref table i j)))
(setf (aref table i j) (mapcar (lambda (x) (jepd-relation-code x ocode)) (cddr x)))))
(dotimes (i nrows)
(dotimes (j ncols)
(cl:assert (not (null (aref table i j))))))
table))
(defvar *rcc8-composition-table* nil)
(defvar *time-iii-composition-table* nil)
(defvar *time-ipi-composition-table* nil)
(defvar *time-pii-composition-table* nil)
(defvar *time-pip-composition-table* nil)
(defvar *time-ppi-composition-table* nil)
(defvar *time-ppp-composition-table* nil)
(defun firsta (x)
(if (consp x) (first x) x))
(defun resta (x)
(if (consp x) (rest x) nil))
(defun declare-rcc8-relations ()
(let ((region-sort (rcc8-region-sort-name?)))
(unless (sort-name? region-sort)
(let ((l (resta region-sort)))
(apply 'declare-sort (setf region-sort (firsta region-sort)) l)))
(declare-jepd-relations
'$$rcc8
(list region-sort region-sort)
(or *rcc8-composition-table*
(setf *rcc8-composition-table* (make-composition-table
$rcc8-composition-table
$rcc8-relation-code)))
2
(jepd-relation-code 'eq $rcc8-relation-code)
rcc8-jepd-relation-names
rcc8-more-relation-names)))
(defun declare-time-relations (&key intervals points dates)
(unless (or intervals points)
(setf intervals t points t))
(when dates
(setf points t))
(let ((interval-sort (time-interval-sort-name?))
(point-sort (time-point-sort-name?)))
(when intervals
(unless (sort-name? interval-sort)
(let ((l (resta interval-sort)))
(apply 'declare-sort (setf interval-sort (firsta interval-sort)) l)))
(declare-jepd-relations
'$$time-ii
(list interval-sort interval-sort)
(or *time-iii-composition-table*
(setf *time-iii-composition-table* (make-composition-table
$time-iii-composition-table
$time-ii-relation-code)))
6
(jepd-relation-code '= $time-ii-relation-code)
time-ii-jepd-relation-names
time-ii-more-relation-names))
(when points
(unless (sort-name? point-sort)
(let ((l (resta point-sort)))
(apply 'declare-sort (setf point-sort (firsta point-sort)) l)))
(declare-jepd-relations
'$$time-pp
(list point-sort point-sort)
(or *time-ppp-composition-table*
(setf *time-ppp-composition-table* (make-composition-table
$time-ppp-composition-table
$time-pp-relation-code)))
1
(jepd-relation-code 'p=p $time-pp-relation-code)
time-pp-jepd-relation-names
time-pp-more-relation-names))
(when (and intervals points)
(unless (or (top-sort-name? interval-sort) (top-sort-name? point-sort))
(declare-sorts-incompatible interval-sort point-sort))
(let* ((relname '$$time-pi)
(sort (list point-sort interval-sort))
(names time-pi-jepd-relation-names)
(more-names time-pi-more-relation-names)
(n (length names))
(rel (declare-jepd-relation relname sort names more-names nil)))
(declare-jepd-relation-input relname names more-names n nil)
(setf names time-ip-jepd-relation-names)
(cl:assert (eql n (length names)))
(declare-jepd-relation-input relname names time-ip-more-relation-names n t)
(declare-jepd-relation-intersection relname rel sort nil)
(let ((composition (intern (to-string relname :-ii-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((table (or *time-pii-composition-table*
(setf *time-pii-composition-table* (make-composition-table
$time-pii-composition-table
$time-pi-relation-code
$time-pi-relation-code
$time-ii-relation-code))))
(n (length $time-pi-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,point-sort)
(?y :sort ,interval-sort)
(?z :sort ,interval-sort)
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) ($$time-ii ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))
(let ((composition (intern (to-string relname :-pp-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((table (or *time-ppi-composition-table*
(setf *time-ppi-composition-table* (make-composition-table
$time-ppi-composition-table
$time-pi-relation-code
$time-pp-relation-code
$time-pi-relation-code))))
(n (length $time-pi-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,point-sort)
(?y :sort ,point-sort)
(?z :sort ,interval-sort)
?l1
?l2)
(implies (and ($$time-pp ?x ?y ?l1) (,relname ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))
(let ((composition (intern (to-string relname :-pi-composition) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((rel (input-relation-symbol '$$time-pp 3))
(table (or *time-pip-composition-table*
(setf *time-pip-composition-table* (make-composition-table
$time-pip-composition-table
$time-pp-relation-code
$time-pi-relation-code
$time-ip-relation-code))))
(n (length $time-pp-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,point-sort)
(?y :sort ,interval-sort)
(?z :sort ,point-sort)
?l1
?l2)
(implies (and (,relname ?x ?y ?l1) (,relname ?z ?y ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))
(let ((composition (intern (to-string relname :-pi-composition2) :snark)))
(declare-relation1
composition 5
:rewrite-code (let ((rel (input-relation-symbol '$$time-ii 3))
(table (or *time-ipi-composition-table*
(setf *time-ipi-composition-table* (make-composition-table
$time-ipi-composition-table
$time-ii-relation-code
$time-ip-relation-code
$time-pi-relation-code))))
(n (length $time-ii-relation-code)))
(list
(lambda (atom subst)
(jepd-relation-composition-rewriter1 atom subst rel table n)))))
(assert `(forall ((?x :sort ,interval-sort)
(?y :sort ,point-sort)
(?z :sort ,interval-sort)
?l1
?l2)
(implies (and (,relname ?y ?x ?l1) (,relname ?y ?z ?l2))
(,composition ?l1 ?l2 ?x ?y ?z)))
:name (intern (symbol-name composition) :keyword)
:supported nil))))
(when dates
(declare-date-functions :intervals intervals :points points))
nil))
(defun jepd-atom-to-lisp (head args subst &optional names more-names)
(let* ((arg1 (term-to-lisp (pop args) subst))
(arg2 (term-to-lisp (pop args) subst))
(arg3 (first args))
(rels (and names (1-indexes arg3 subst))))
(cond
((null rels)
(list (function-name head) arg1 arg2 (term-to-lisp arg3 subst)))
((null (rest rels))
(list (function-name (input-relation-symbol (nth (first rels) names) 2)) arg1 arg2))
((do ((l more-names (cddr l)))
((null l)
nil)
(when (equal rels (second l))
(return (list (function-name (input-relation-symbol (first l) 2)) arg1 arg2)))))
(t
(let ((l nil) l-last)
(dolist (rel rels)
(collect (list (function-name (input-relation-symbol (nth rel names) 2)) arg1 arg2) l))
(cons 'or-jepd l))))))
(defun equal-jepd-relation-atom-args-p (args1 args2 subst invert)
lists of possible relations in third argument are compared by variant - p instead of equal - p
(let ((x1 (pop args1)) (y1 (pop args1)) (rels1 (first args1))
(x2 (pop args2)) (y2 (pop args2)) (rels2 (first args2)))
(or (and (equal-p x1 x2 subst)
(equal-p y1 y2 subst)
(equal-p rels1 rels2 subst))
(and (dereference rels1 subst :if-compound-cons t)
(dereference rels2 subst :if-compound-cons t)
(and (equal-p x1 y2 subst)
(equal-p y1 x2 subst)
(variant-p rels1 (reversem rels2 invert) subst))))))
(defun variant-jepd-relation-atom-args (cc args1 args2 subst matches invert)
(let ((x1 (pop args1)) (y1 (pop args1)) (rels1 (first args1))
(x2 (pop args2)) (y2 (pop args2)) (rels2 (first args2)))
(prog->
(variant x1 x2 subst matches ->* matches)
(variant y1 y2 subst matches ->* matches)
(variant rels1 rels2 subst matches ->* matches)
(funcall cc matches))
(when (and (dereference rels1 subst :if-compound-cons t)
(dereference rels2 subst :if-compound-cons t))
(prog->
(quote nil -> rels2*)
(variant x1 y2 subst matches ->* matches)
(variant y1 x2 subst matches ->* matches)
(variant rels1 (or rels2* (setf rels2* (reversem rels2 invert))) subst matches ->* matches)
(funcall cc matches)))))
(defun unify-jepd-relation-atom-args (cc args1 args2 subst invert)
(let ((x1 (pop args1)) (y1 (pop args1)) (rels1 (first args1))
(x2 (pop args2)) (y2 (pop args2)) (rels2 (first args2)))
(prog->
(unify x1 x2 subst ->* subst)
(unify y1 y2 subst ->* subst)
(unify rels1 rels2 subst ->* subst)
(funcall cc subst))
(cond
((dereference rels2 subst :if-compound-cons t)
(prog->
(quote nil -> rels2*)
(unify x1 y2 subst ->* subst)
(unify y1 x2 subst ->* subst)
(unify rels1 (or rels2* (setf rels2* (reversem rels2 invert))) subst ->* subst)
(funcall cc subst)))
((dereference rels1 subst :if-compound-cons t)
(prog->
(quote nil -> rels1*)
(unify y1 x2 subst ->* subst)
(unify x1 y2 subst ->* subst)
(unify (or rels1* (setf rels1* (reversem rels1 invert))) rels2 subst ->* subst)
(funcall cc subst))))))
(defun jepd-relation-atom-rewriter (atom subst)
(let ((v (third (args atom))))
(if (dereference
v subst
:if-compound-cons (dolist (x v t)
(dereference x subst :if-variable (return nil))))
true
none)))
jepd-relations.lisp
|
8e93e208f4974b1b436d0152ca3328271e1eb5c4ab98dcbb23d9327ca4c4c56e | cyverse-archive/DiscoveryEnvironmentBackend | constants.clj | (ns mescal.agave-de-v2.constants)
(def hpc-app-type "External")
(def hpc-group-description "Apps that run on HPC resources.")
(def hpc-group-name "High-Performance Computing")
(def hpc-group-id "00000000-0000-0000-0000-000000000001")
(def unknown-value "UNKNOWN")
(def hpc-group-overview
{:id hpc-group-id
:name hpc-group-name})
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/libs/mescal/src/mescal/agave_de_v2/constants.clj | clojure | (ns mescal.agave-de-v2.constants)
(def hpc-app-type "External")
(def hpc-group-description "Apps that run on HPC resources.")
(def hpc-group-name "High-Performance Computing")
(def hpc-group-id "00000000-0000-0000-0000-000000000001")
(def unknown-value "UNKNOWN")
(def hpc-group-overview
{:id hpc-group-id
:name hpc-group-name})
|
|
ff50e722c52e7ab0714f178044e0523e0d525335a82614bffc21aa06accae18f | mveety/lispmake | options.lisp | (in-package :lispmake)
lispmake , written by , et al .
( c ) 2012 - 2021 . Under BSD License .
(defvar *cmd-options* nil)
(defvar *lmfname* *lmakefile*)
(defparameter *variables*
(list 'prefix "/usr/local"
'bindir ""
'libdir ""
'etcdir ""
'target ""
'cwd ""
'default-mode '(:user-read :user-exec :user-write
:group-read :group-exec
:other-read :other-exec)))
(defparameter *varhdlrs* nil)
(defun split-equal (string)
(let* ((bf (split-sequence:split-sequence #\= string)))
(if (equal (length bf) 2)
bf
nil)))
(defun parg (arg)
(if (symbolp arg)
(getf *variables* arg)
arg))
(defun string-to-symbol (string)
(if (stringp string)
(intern (string-upcase string))
nil))
(defun string-to-keyword (string)
(if (stringp string)
(intern (string-upcase string) "KEYWORD")
nil))
(defun symbol-to-keyword (symbol)
(if (symbolp symbol)
(let* ((s (string symbol)))
(intern (string-upcase s) "KEYWORD"))
nil))
(defun perms-to-number (perms-list)
(let ((user 0)
(group 0)
(other 0))
(dolist (x perms-list)
(cond
((equal x :user-read) (incf user 4))
((equal x :user-write) (incf user 2))
((equal x :user-exec) (incf user 1))
((equal x :group-read) (incf group 4))
((equal x :group-write) (incf group 2))
((equal x :group-exec) (incf group 1))
((equal x :other-read) (incf other 4))
((equal x :other-write) (incf other 2))
((equal x :other-exec) (incf other 1))))
(format nil "~A~A~A" user group other)))
(defun number-to-perms (perms-str)
(let ((rperms (list (parse-integer (subseq perms-str 0 1) :radix 8)
(parse-integer (subseq perms-str 1 2) :radix 8)
(parse-integer (subseq perms-str 2 3) :radix 8)))
(state 0)
(unixread 4)
(unixwrite 2)
(unixexec 1)
(perms nil))
(dolist (x rperms)
(if (not (< (- x unixread) 0))
(setf perms (append perms
(case state
(0 (list :user-read))
(1 (list :group-read))
(2 (list :other-read))))
x (- x unixread)))
(if (not (< (- x unixwrite) 0))
(setf perms (append perms
(case state
(0 (list :user-write))
(1 (list :group-write))
(2 (list :other-write))))
x (- x unixwrite)))
(if (equal x unixexec)
(setf perms (append perms
(case state
(0 (list :user-exec))
(1 (list :group-exec))
(2 (list :other-exec))))))
(incf state))
perms))
(defun get-var (varname)
(getf *variables* varname))
(defun set-var (varname value)
(let* ((vstat (getf *variables* varname)))
(if (equal vstat nil)
(progn
(pushnew value *variables*)
(pushnew varname *variables*))
(progn
(if (getf *varhdlrs* varname)
(funcall (getf *varhdlrs* varname) value)
(setf (getf *variables* varname) value))))))
(defun set-var-handler (varname handler)
(setf (getf *varhdlrs* varname) handler))
(defun var-defined-p (varname)
(if (find varname *variables*)
t
nil))
(defmacro true-mess (value)
;; this is still a shitshow, but a bit more contained.
`(or (equal ,value "true")
(equal ,value "TRUE")
(equal ,value "yes")
(equal ,value "YES")
(equal ,value "y")
(equal ,value "t")
(equal ,value "T")
(equal ,value "Y")
(equal ,value "1")))
(defun handle-options ()
(setf *cmd-options* (unix-options:cli-options))
(dolist (x *cmd-options*)
(let* ((bf (split-equal x)))
(if (not (equal bf nil))
(let* ((var (car bf))
(value (cadr bf)))
(cond
((equal var "target")
(setf *target* value)
(set-var 'target *target*))
((equal var "lisp")
(setf *lisp-executable* value))
((equal var "file")
(setf *lmfname* value))
((equal var "dobuild")
(setf *do-build-override* t)
(if (true-mess value)
(setf *do-build* T)
(setf *do-build* nil)))
((equal var "debug")
(if (true-mess value)
(setf *debugging* T)
(setf *debugging* nil)))
(T (set-var (string-to-symbol var) value))))
;;; if the arg doesn't have an = sign, then assume it's a target
(progn
(set-var 'target x)
(setf *target* x)))))
(if (equal *target* nil)
(setf *lmakefile* *lmfname*)
(setf *lmakefile*
(concatenate 'string *lmakefile* "." *target*)))
(if *debugging*
(progn
(format
t
"lispmake: debug: handle-options: lmakefile=~A~%"
*lmakefile*)
(format t "lmakefile=~A~%target=~A~%file=~A~%"
*lmakefile* *target* *lmfname*)))
nil)
(defun varhdl (form)
(if (symbolp form)
(let ((bf (getf *variables* form)))
(if (not (equal bf nil))
bf
form))
form))
(defmacro nilp (form)
`(equal ,form nil))
(defun pl-fn (args)
(if (not (listp args))
(lm-abort "fn args should by type list"))
(if (not (keywordp (car args)))
(lm-abort "fn name needs to be type keyword"))
(install-fn-plugin (car args) (cdr args)))
(defun configure-string (varname)
(tagbody
start
(format t "lispmake: configure: Input value for (string) ~A: " varname)
(force-output)
(let* ((bf nil))
(setf bf (read))
(if (not (stringp bf))
(progn
(format t "lispmake: configure: error: invalid type~%")
(force-output)
(go start)))
(set-var varname bf))))
(defun configure-boolean (varname)
(tagbody
start
(format t "lispmake: configure: Enable option (y/n)~A" varname)
(force-output)
(let* ((bf nil))
(setf bf (read))
(setf bf (string-upcase bf))
(if (or
(equal bf "Y")
(equal bf "YES")
(equal bf "TRUE"))
(set-var varname (not nil))
(if (or
(equal bf "N")
(equal bf "NO")
(equal bf "FALSE"))
(set-var varname nil)
(progn
(format t "lispmake: configure: error: invalid input~%")
(force-output)
(go start)))))))
(defun configure-number (varname)
(tagbody
start
(format t "lispmake: configure: Input value for (number)~A: " varname)
(force-output)
(let* ((bf nil))
(setf bf (read))
(if (not (numberp bf))
(progn
(format t "lispmake: configure: error: invalid input~%")
(force-output)
(go start)))
(set-var varname bf))))
(defun pl-configure (args)
(dolist (x args)
(if (not (listp x))
(lm-abort "must be a list of lists"))
(let* ((type (cadr x))
(name (car x)))
(cond
((equal type :string) (configure-string name))
((equal type :boolean) (configure-boolean name))
((equal type :number) (configure-number name))))))
(defun set-default-mode (value)
(cond
((typep value 'cons)
(setf (getf *variables* 'default-mode) value))
((or (typep value 'string)
(typep value 'number))
(let ((tmpperm nil))
(if (typep value 'number)
(setf tmpperm (format nil "~A" value))
(setf tmpperm value))
(setf (getf *variables* 'default-mode) (number-to-perms tmpperm))))
(t (lm-error "handler: default-mode" "invalid type"))))
(defun initialize-vars (&key (apply-prefix nil))
(let* ((prefix (get-var 'prefix))
(prefix-changed nil)
(cwdstr (format nil "~A" (osicat:current-directory)))
bindir libdir etcdir)
;; remove trailing slash from prefix if it exists
(if (equal (subseq prefix (1- (length prefix))) "/")
(setf prefix (subseq prefix 0 (1- (length prefix)))
prefix-changed t))
(setf bindir (concatenate 'string prefix "/bin")
libdir (concatenate 'string prefix "/lib")
etcdir (concatenate 'string prefix "/etc"))
(if prefix-changed
(set-var 'prefix prefix))
(if (or (equal (get-var 'bindir) "") apply-prefix)
(set-var 'bindir bindir))
(if (or (equal (get-var 'libdir) "") apply-prefix)
(set-var 'libdir libdir))
(if (or (equal (get-var 'etcdir) "") apply-prefix)
(set-var 'etcdir etcdir))
(if (nilp apply-prefix)
(progn
(if (equal (subseq cwdstr (1- (length cwdstr))) "/")
(setf cwdstr (subseq cwdstr 0 (1- (length cwdstr)))))
(if (equal (get-var 'target) "")
(set-var 'target "build"))
(set-var 'cwd cwdstr)
(set-var-handler 'default-mode #'set-default-mode)))))
(defun pl-apply-prefix (args)
(declare (ignore args))
(initialize-vars :apply-prefix t))
| null | https://raw.githubusercontent.com/mveety/lispmake/3eb4e8ac280de3c31b4826424093b11c7dbbf289/options.lisp | lisp | this is still a shitshow, but a bit more contained.
if the arg doesn't have an = sign, then assume it's a target
remove trailing slash from prefix if it exists | (in-package :lispmake)
lispmake , written by , et al .
( c ) 2012 - 2021 . Under BSD License .
(defvar *cmd-options* nil)
(defvar *lmfname* *lmakefile*)
(defparameter *variables*
(list 'prefix "/usr/local"
'bindir ""
'libdir ""
'etcdir ""
'target ""
'cwd ""
'default-mode '(:user-read :user-exec :user-write
:group-read :group-exec
:other-read :other-exec)))
(defparameter *varhdlrs* nil)
(defun split-equal (string)
(let* ((bf (split-sequence:split-sequence #\= string)))
(if (equal (length bf) 2)
bf
nil)))
(defun parg (arg)
(if (symbolp arg)
(getf *variables* arg)
arg))
(defun string-to-symbol (string)
(if (stringp string)
(intern (string-upcase string))
nil))
(defun string-to-keyword (string)
(if (stringp string)
(intern (string-upcase string) "KEYWORD")
nil))
(defun symbol-to-keyword (symbol)
(if (symbolp symbol)
(let* ((s (string symbol)))
(intern (string-upcase s) "KEYWORD"))
nil))
(defun perms-to-number (perms-list)
(let ((user 0)
(group 0)
(other 0))
(dolist (x perms-list)
(cond
((equal x :user-read) (incf user 4))
((equal x :user-write) (incf user 2))
((equal x :user-exec) (incf user 1))
((equal x :group-read) (incf group 4))
((equal x :group-write) (incf group 2))
((equal x :group-exec) (incf group 1))
((equal x :other-read) (incf other 4))
((equal x :other-write) (incf other 2))
((equal x :other-exec) (incf other 1))))
(format nil "~A~A~A" user group other)))
(defun number-to-perms (perms-str)
(let ((rperms (list (parse-integer (subseq perms-str 0 1) :radix 8)
(parse-integer (subseq perms-str 1 2) :radix 8)
(parse-integer (subseq perms-str 2 3) :radix 8)))
(state 0)
(unixread 4)
(unixwrite 2)
(unixexec 1)
(perms nil))
(dolist (x rperms)
(if (not (< (- x unixread) 0))
(setf perms (append perms
(case state
(0 (list :user-read))
(1 (list :group-read))
(2 (list :other-read))))
x (- x unixread)))
(if (not (< (- x unixwrite) 0))
(setf perms (append perms
(case state
(0 (list :user-write))
(1 (list :group-write))
(2 (list :other-write))))
x (- x unixwrite)))
(if (equal x unixexec)
(setf perms (append perms
(case state
(0 (list :user-exec))
(1 (list :group-exec))
(2 (list :other-exec))))))
(incf state))
perms))
(defun get-var (varname)
(getf *variables* varname))
(defun set-var (varname value)
(let* ((vstat (getf *variables* varname)))
(if (equal vstat nil)
(progn
(pushnew value *variables*)
(pushnew varname *variables*))
(progn
(if (getf *varhdlrs* varname)
(funcall (getf *varhdlrs* varname) value)
(setf (getf *variables* varname) value))))))
(defun set-var-handler (varname handler)
(setf (getf *varhdlrs* varname) handler))
(defun var-defined-p (varname)
(if (find varname *variables*)
t
nil))
(defmacro true-mess (value)
`(or (equal ,value "true")
(equal ,value "TRUE")
(equal ,value "yes")
(equal ,value "YES")
(equal ,value "y")
(equal ,value "t")
(equal ,value "T")
(equal ,value "Y")
(equal ,value "1")))
(defun handle-options ()
(setf *cmd-options* (unix-options:cli-options))
(dolist (x *cmd-options*)
(let* ((bf (split-equal x)))
(if (not (equal bf nil))
(let* ((var (car bf))
(value (cadr bf)))
(cond
((equal var "target")
(setf *target* value)
(set-var 'target *target*))
((equal var "lisp")
(setf *lisp-executable* value))
((equal var "file")
(setf *lmfname* value))
((equal var "dobuild")
(setf *do-build-override* t)
(if (true-mess value)
(setf *do-build* T)
(setf *do-build* nil)))
((equal var "debug")
(if (true-mess value)
(setf *debugging* T)
(setf *debugging* nil)))
(T (set-var (string-to-symbol var) value))))
(progn
(set-var 'target x)
(setf *target* x)))))
(if (equal *target* nil)
(setf *lmakefile* *lmfname*)
(setf *lmakefile*
(concatenate 'string *lmakefile* "." *target*)))
(if *debugging*
(progn
(format
t
"lispmake: debug: handle-options: lmakefile=~A~%"
*lmakefile*)
(format t "lmakefile=~A~%target=~A~%file=~A~%"
*lmakefile* *target* *lmfname*)))
nil)
(defun varhdl (form)
(if (symbolp form)
(let ((bf (getf *variables* form)))
(if (not (equal bf nil))
bf
form))
form))
(defmacro nilp (form)
`(equal ,form nil))
(defun pl-fn (args)
(if (not (listp args))
(lm-abort "fn args should by type list"))
(if (not (keywordp (car args)))
(lm-abort "fn name needs to be type keyword"))
(install-fn-plugin (car args) (cdr args)))
(defun configure-string (varname)
(tagbody
start
(format t "lispmake: configure: Input value for (string) ~A: " varname)
(force-output)
(let* ((bf nil))
(setf bf (read))
(if (not (stringp bf))
(progn
(format t "lispmake: configure: error: invalid type~%")
(force-output)
(go start)))
(set-var varname bf))))
(defun configure-boolean (varname)
(tagbody
start
(format t "lispmake: configure: Enable option (y/n)~A" varname)
(force-output)
(let* ((bf nil))
(setf bf (read))
(setf bf (string-upcase bf))
(if (or
(equal bf "Y")
(equal bf "YES")
(equal bf "TRUE"))
(set-var varname (not nil))
(if (or
(equal bf "N")
(equal bf "NO")
(equal bf "FALSE"))
(set-var varname nil)
(progn
(format t "lispmake: configure: error: invalid input~%")
(force-output)
(go start)))))))
(defun configure-number (varname)
(tagbody
start
(format t "lispmake: configure: Input value for (number)~A: " varname)
(force-output)
(let* ((bf nil))
(setf bf (read))
(if (not (numberp bf))
(progn
(format t "lispmake: configure: error: invalid input~%")
(force-output)
(go start)))
(set-var varname bf))))
(defun pl-configure (args)
(dolist (x args)
(if (not (listp x))
(lm-abort "must be a list of lists"))
(let* ((type (cadr x))
(name (car x)))
(cond
((equal type :string) (configure-string name))
((equal type :boolean) (configure-boolean name))
((equal type :number) (configure-number name))))))
(defun set-default-mode (value)
(cond
((typep value 'cons)
(setf (getf *variables* 'default-mode) value))
((or (typep value 'string)
(typep value 'number))
(let ((tmpperm nil))
(if (typep value 'number)
(setf tmpperm (format nil "~A" value))
(setf tmpperm value))
(setf (getf *variables* 'default-mode) (number-to-perms tmpperm))))
(t (lm-error "handler: default-mode" "invalid type"))))
(defun initialize-vars (&key (apply-prefix nil))
(let* ((prefix (get-var 'prefix))
(prefix-changed nil)
(cwdstr (format nil "~A" (osicat:current-directory)))
bindir libdir etcdir)
(if (equal (subseq prefix (1- (length prefix))) "/")
(setf prefix (subseq prefix 0 (1- (length prefix)))
prefix-changed t))
(setf bindir (concatenate 'string prefix "/bin")
libdir (concatenate 'string prefix "/lib")
etcdir (concatenate 'string prefix "/etc"))
(if prefix-changed
(set-var 'prefix prefix))
(if (or (equal (get-var 'bindir) "") apply-prefix)
(set-var 'bindir bindir))
(if (or (equal (get-var 'libdir) "") apply-prefix)
(set-var 'libdir libdir))
(if (or (equal (get-var 'etcdir) "") apply-prefix)
(set-var 'etcdir etcdir))
(if (nilp apply-prefix)
(progn
(if (equal (subseq cwdstr (1- (length cwdstr))) "/")
(setf cwdstr (subseq cwdstr 0 (1- (length cwdstr)))))
(if (equal (get-var 'target) "")
(set-var 'target "build"))
(set-var 'cwd cwdstr)
(set-var-handler 'default-mode #'set-default-mode)))))
(defun pl-apply-prefix (args)
(declare (ignore args))
(initialize-vars :apply-prefix t))
|
96891f6a93ba0b7313153de0080be2487487071fac4c99cdc1fc4a74c2fa747c | fyquah/hardcaml_zprize | controller.ml | open! Base
open! Hardcaml
module Make (Config : Core_config.S) = struct
module Var = Always.Variable
let logn = Config.logn
let support_4step_twiddle = Config.support_4step_twiddle
module I = struct
type 'a t =
{ clock : 'a
; clear : 'a
; start : 'a
; first_iter : 'a
; first_4step_pass : 'a
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ done_ : 'a
; i : 'a [@bits Int.ceil_log2 (logn + 1)]
; j : 'a [@bits logn]
; k : 'a [@bits logn]
; m : 'a [@bits logn]
; addr1 : 'a [@bits logn]
; addr2 : 'a [@bits logn]
; omegas : 'a list
[@bits Gf.Signal.num_bits] [@length Twiddle_factor_stream.pipe_length]
; start_twiddles : 'a
; first_stage : 'a
; last_stage : 'a
; twiddle_stage : 'a
; twiddle_update : 'a Twiddle_update.t
; read_write_enable : 'a
; flip : 'a
}
[@@deriving sexp_of, hardcaml]
end
module State = struct
type t =
| Idle
| Looping
| Sync
| Twiddle
| Sync_twiddles
[@@deriving compare, enumerate, sexp_of, variants]
end
let create scope (inputs : _ I.t) =
let open Signal in
let ( -- ) = Scope.naming scope in
let spec = Reg_spec.create ~clock:inputs.clock ~clear:inputs.clear () in
let sm = Always.State_machine.create (module State) spec in
ignore (sm.current -- "STATE" : Signal.t);
let done_ = Var.reg (Reg_spec.override spec ~clear_to:vdd) ~width:1 in
let i = Var.reg spec ~width:(Int.ceil_log2 (logn + 1)) in
ignore (i.value -- "i" : Signal.t);
let i_next = i.value +:. 1 in
let j = Var.reg spec ~width:logn in
ignore (j.value -- "j" : Signal.t);
let j_next = j.value +:. 1 in
let k = Var.reg spec ~width:logn in
ignore (k.value -- "k" : Signal.t);
let m = Var.reg spec ~width:logn in
ignore (m.value -- "m" : Signal.t);
let m_next = sll m.value 1 in
let k_next = k.value +: m_next in
let addr1 = Var.reg spec ~width:logn in
let addr2 = Var.reg spec ~width:logn in
let addr2_plus1 = addr2.value +:. 1 in
let omegas =
List.init logn ~f:(fun i -> Twiddle_factor_stream.initial_pipeline_factors (i + 1))
|> List.transpose_exn
|> List.map ~f:(mux i.value)
|> Array.of_list
in
let start_twiddles = Var.reg spec ~width:1 in
let first_stage = Var.reg spec ~width:1 in
let last_stage = Var.reg spec ~width:1 in
let twiddle_stage = Var.reg spec ~width:1 in
let twiddle_update = Var.reg spec ~width:1 in
let sync_count = Var.reg spec ~width:Twiddle_update.sync_cycles_width in
let sync_count_next = sync_count.value +:. 1 in
let flip = Var.wire ~default:gnd in
let read_write_enable = Var.wire ~default:gnd in
let if_twiddle_supported ((s : State.t), p) =
if support_4step_twiddle then s, p else s, []
in
Always.(
compile
[ start_twiddles <--. 0
; sm.switch
[ ( Idle
, [ when_
inputs.start
[ i <--. 0
; j <--. 0
; k <--. 0
; m <--. 1
; addr1 <--. 0
; addr2 <--. 1
; done_ <--. 0
; start_twiddles <--. 1
; first_stage <--. 1
; last_stage <--. 0
; twiddle_stage <--. 0
; twiddle_update <--. 0
; sm.set_next Looping
]
] )
; ( Looping
, [ j <-- j_next
; read_write_enable <-- vdd
; addr1 <-- addr1.value +:. 1
; addr2 <-- addr2_plus1
; when_
(j_next ==: m.value)
[ if_
(k_next ==:. 0)
[ sm.set_next Sync ]
[ j <--. 0
; start_twiddles <--. 1
; k <-- k_next
; addr1 <-- k_next
; addr2 <-- k_next +: m.value
]
]
] )
; ( Sync
, [ sync_count <-- sync_count_next
; when_
(sync_count.value ==:. Twiddle_update.sync_cycles - 1)
[ sm.set_next Looping
; sync_count <--. 0
; start_twiddles <--. 1
; flip <-- vdd
; first_stage <--. 0
; i <-- i_next
; j <--. 0
; k <-- k_next
; m <-- m_next
; addr1 <-- k_next
; addr2 <-- k_next +: m_next
; when_
(i_next ==:. logn - 1)
[ last_stage <-- ~:(inputs.first_4step_pass) ]
; when_
(i_next ==:. logn)
[ last_stage <--. 0
; (if support_4step_twiddle
then
proc
[ if_
inputs.first_4step_pass
[ last_stage <--. 1
; twiddle_stage <--. 1
; addr2 <--. 0
; sm.set_next Twiddle
]
[ done_ <--. 1; sm.set_next Idle ]
]
else proc [ done_ <--. 1; sm.set_next Idle ])
]
]
] )
; if_twiddle_supported
( Twiddle
, [ addr2 <-- addr2_plus1
; read_write_enable <-- vdd
; when_
(addr2.value ==:. -1)
[ addr2 <--. 0
; twiddle_update <--. 1
; twiddle_stage <--. 0
; sm.set_next Sync_twiddles
]
] )
; if_twiddle_supported
( Sync_twiddles
, [ sync_count <-- sync_count_next
; when_
(sync_count.value ==:. Twiddle_factor_stream.pipe_length - 1)
[ twiddle_update <--. 0 ]
; when_
(sync_count.value ==:. Twiddle_update.sync_cycles - 1)
[ twiddle_stage <--. 0
; twiddle_update <--. 0
; last_stage <-- gnd
; done_ <--. 1
; sm.set_next Idle
]
] )
]
]);
{ O.done_ = done_.value
; i = i.value
; j = j.value
; k = k.value
; m = m.value
; addr1 = addr1.value
; addr2 = addr2.value
; omegas = List.init Twiddle_factor_stream.pipe_length ~f:(fun idx -> omegas.(idx))
; start_twiddles = start_twiddles.value
; first_stage = first_stage.value
; last_stage = last_stage.value
; twiddle_stage = twiddle_stage.value
; twiddle_update = { valid = twiddle_update.value; index = sync_count.value }
; read_write_enable = read_write_enable.value
; flip = flip.value
}
;;
let hierarchy scope =
let module Hier = Hierarchy.In_scope (I) (O) in
Hier.hierarchical ~name:"ctrl" ~scope create
;;
end
| null | https://raw.githubusercontent.com/fyquah/hardcaml_zprize/553b1be10ae9b977decbca850df6ee2d0595e7ff/libs/hardcaml_ntt/src/controller.ml | ocaml | open! Base
open! Hardcaml
module Make (Config : Core_config.S) = struct
module Var = Always.Variable
let logn = Config.logn
let support_4step_twiddle = Config.support_4step_twiddle
module I = struct
type 'a t =
{ clock : 'a
; clear : 'a
; start : 'a
; first_iter : 'a
; first_4step_pass : 'a
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t =
{ done_ : 'a
; i : 'a [@bits Int.ceil_log2 (logn + 1)]
; j : 'a [@bits logn]
; k : 'a [@bits logn]
; m : 'a [@bits logn]
; addr1 : 'a [@bits logn]
; addr2 : 'a [@bits logn]
; omegas : 'a list
[@bits Gf.Signal.num_bits] [@length Twiddle_factor_stream.pipe_length]
; start_twiddles : 'a
; first_stage : 'a
; last_stage : 'a
; twiddle_stage : 'a
; twiddle_update : 'a Twiddle_update.t
; read_write_enable : 'a
; flip : 'a
}
[@@deriving sexp_of, hardcaml]
end
module State = struct
type t =
| Idle
| Looping
| Sync
| Twiddle
| Sync_twiddles
[@@deriving compare, enumerate, sexp_of, variants]
end
let create scope (inputs : _ I.t) =
let open Signal in
let ( -- ) = Scope.naming scope in
let spec = Reg_spec.create ~clock:inputs.clock ~clear:inputs.clear () in
let sm = Always.State_machine.create (module State) spec in
ignore (sm.current -- "STATE" : Signal.t);
let done_ = Var.reg (Reg_spec.override spec ~clear_to:vdd) ~width:1 in
let i = Var.reg spec ~width:(Int.ceil_log2 (logn + 1)) in
ignore (i.value -- "i" : Signal.t);
let i_next = i.value +:. 1 in
let j = Var.reg spec ~width:logn in
ignore (j.value -- "j" : Signal.t);
let j_next = j.value +:. 1 in
let k = Var.reg spec ~width:logn in
ignore (k.value -- "k" : Signal.t);
let m = Var.reg spec ~width:logn in
ignore (m.value -- "m" : Signal.t);
let m_next = sll m.value 1 in
let k_next = k.value +: m_next in
let addr1 = Var.reg spec ~width:logn in
let addr2 = Var.reg spec ~width:logn in
let addr2_plus1 = addr2.value +:. 1 in
let omegas =
List.init logn ~f:(fun i -> Twiddle_factor_stream.initial_pipeline_factors (i + 1))
|> List.transpose_exn
|> List.map ~f:(mux i.value)
|> Array.of_list
in
let start_twiddles = Var.reg spec ~width:1 in
let first_stage = Var.reg spec ~width:1 in
let last_stage = Var.reg spec ~width:1 in
let twiddle_stage = Var.reg spec ~width:1 in
let twiddle_update = Var.reg spec ~width:1 in
let sync_count = Var.reg spec ~width:Twiddle_update.sync_cycles_width in
let sync_count_next = sync_count.value +:. 1 in
let flip = Var.wire ~default:gnd in
let read_write_enable = Var.wire ~default:gnd in
let if_twiddle_supported ((s : State.t), p) =
if support_4step_twiddle then s, p else s, []
in
Always.(
compile
[ start_twiddles <--. 0
; sm.switch
[ ( Idle
, [ when_
inputs.start
[ i <--. 0
; j <--. 0
; k <--. 0
; m <--. 1
; addr1 <--. 0
; addr2 <--. 1
; done_ <--. 0
; start_twiddles <--. 1
; first_stage <--. 1
; last_stage <--. 0
; twiddle_stage <--. 0
; twiddle_update <--. 0
; sm.set_next Looping
]
] )
; ( Looping
, [ j <-- j_next
; read_write_enable <-- vdd
; addr1 <-- addr1.value +:. 1
; addr2 <-- addr2_plus1
; when_
(j_next ==: m.value)
[ if_
(k_next ==:. 0)
[ sm.set_next Sync ]
[ j <--. 0
; start_twiddles <--. 1
; k <-- k_next
; addr1 <-- k_next
; addr2 <-- k_next +: m.value
]
]
] )
; ( Sync
, [ sync_count <-- sync_count_next
; when_
(sync_count.value ==:. Twiddle_update.sync_cycles - 1)
[ sm.set_next Looping
; sync_count <--. 0
; start_twiddles <--. 1
; flip <-- vdd
; first_stage <--. 0
; i <-- i_next
; j <--. 0
; k <-- k_next
; m <-- m_next
; addr1 <-- k_next
; addr2 <-- k_next +: m_next
; when_
(i_next ==:. logn - 1)
[ last_stage <-- ~:(inputs.first_4step_pass) ]
; when_
(i_next ==:. logn)
[ last_stage <--. 0
; (if support_4step_twiddle
then
proc
[ if_
inputs.first_4step_pass
[ last_stage <--. 1
; twiddle_stage <--. 1
; addr2 <--. 0
; sm.set_next Twiddle
]
[ done_ <--. 1; sm.set_next Idle ]
]
else proc [ done_ <--. 1; sm.set_next Idle ])
]
]
] )
; if_twiddle_supported
( Twiddle
, [ addr2 <-- addr2_plus1
; read_write_enable <-- vdd
; when_
(addr2.value ==:. -1)
[ addr2 <--. 0
; twiddle_update <--. 1
; twiddle_stage <--. 0
; sm.set_next Sync_twiddles
]
] )
; if_twiddle_supported
( Sync_twiddles
, [ sync_count <-- sync_count_next
; when_
(sync_count.value ==:. Twiddle_factor_stream.pipe_length - 1)
[ twiddle_update <--. 0 ]
; when_
(sync_count.value ==:. Twiddle_update.sync_cycles - 1)
[ twiddle_stage <--. 0
; twiddle_update <--. 0
; last_stage <-- gnd
; done_ <--. 1
; sm.set_next Idle
]
] )
]
]);
{ O.done_ = done_.value
; i = i.value
; j = j.value
; k = k.value
; m = m.value
; addr1 = addr1.value
; addr2 = addr2.value
; omegas = List.init Twiddle_factor_stream.pipe_length ~f:(fun idx -> omegas.(idx))
; start_twiddles = start_twiddles.value
; first_stage = first_stage.value
; last_stage = last_stage.value
; twiddle_stage = twiddle_stage.value
; twiddle_update = { valid = twiddle_update.value; index = sync_count.value }
; read_write_enable = read_write_enable.value
; flip = flip.value
}
;;
let hierarchy scope =
let module Hier = Hierarchy.In_scope (I) (O) in
Hier.hierarchical ~name:"ctrl" ~scope create
;;
end
|
|
d45f9ad4582e30266d7ad16220ca1436a07f29786b4f249d1a7c0033c53aed0b | snowleopard/alga | Generic.hs | # LANGUAGE RecordWildCards , ViewPatterns #
-----------------------------------------------------------------------------
-- |
-- Module : Algebra.Graph.Test.Generic
Copyright : ( c ) 2016 - 2022
License : MIT ( see the file LICENSE )
-- Maintainer :
-- Stability : experimental
--
-- Generic graph API testing.
-----------------------------------------------------------------------------
module Algebra.Graph.Test.Generic where
import Control.Monad (when)
import Data.Either
import Data.List (nub, sort)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Tree
import Data.Tuple
import qualified Data.List as List
import Algebra.Graph.Test
import Algebra.Graph.Test.API
import qualified Algebra.Graph as G
import qualified Algebra.Graph.AdjacencyMap as AM
import qualified Algebra.Graph.AdjacencyMap.Algorithm as AM
import qualified Algebra.Graph.AdjacencyIntMap as AIM
import qualified Data.Set as Set
import qualified Data.IntSet as IntSet
type ModulePrefix = String
type Testsuite g c = (ModulePrefix, API g c)
type TestsuiteInt g = (ModulePrefix, API g ((~) Int))
testBasicPrimitives :: TestsuiteInt g -> IO ()
testBasicPrimitives = mconcat [ testOrd
, testEmpty
, testVertex
, testEdge
, testOverlay
, testConnect
, testVertices
, testEdges
, testOverlays
, testConnects ]
testSymmetricBasicPrimitives :: TestsuiteInt g -> IO ()
testSymmetricBasicPrimitives = mconcat [ testSymmetricOrd
, testEmpty
, testVertex
, testSymmetricEdge
, testOverlay
, testSymmetricConnect
, testVertices
, testSymmetricEdges
, testOverlays
, testSymmetricConnects ]
testToGraph :: TestsuiteInt g -> IO ()
testToGraph = mconcat [ testToGraphDefault
, testFoldg
, testIsEmpty
, testHasVertex
, testHasEdge
, testVertexCount
, testEdgeCount
, testVertexList
, testVertexSet
, testVertexIntSet
, testEdgeList
, testEdgeSet
, testAdjacencyList
, testPreSet
, testPreIntSet
, testPostSet
, testPostIntSet ]
testSymmetricToGraph :: TestsuiteInt g -> IO ()
testSymmetricToGraph = mconcat [ testSymmetricToGraphDefault
, testIsEmpty
, testHasVertex
, testSymmetricHasEdge
, testVertexCount
, testEdgeCount
, testVertexList
, testVertexSet
, testVertexIntSet
, testSymmetricEdgeList
, testSymmetricEdgeSet
, testSymmetricAdjacencyList
, testNeighbours ]
testRelational :: TestsuiteInt g -> IO ()
testRelational = mconcat [ testCompose
, testClosure
, testReflexiveClosure
, testSymmetricClosure
, testTransitiveClosure ]
testGraphFamilies :: TestsuiteInt g -> IO ()
testGraphFamilies = mconcat [ testPath
, testCircuit
, testClique
, testBiclique
, testStar
, testStars
, testTree
, testForest ]
testSymmetricGraphFamilies :: TestsuiteInt g -> IO ()
testSymmetricGraphFamilies = mconcat [ testSymmetricPath
, testSymmetricCircuit
, testSymmetricClique
, testBiclique
, testStar
, testStars
, testTree
, testForest ]
testTransformations :: TestsuiteInt g -> IO ()
testTransformations = mconcat [ testRemoveVertex
, testRemoveEdge
, testReplaceVertex
, testMergeVertices
, testTranspose
, testGmap
, testInduce ]
testSymmetricTransformations :: TestsuiteInt g -> IO ()
testSymmetricTransformations = mconcat [ testRemoveVertex
, testSymmetricRemoveEdge
, testReplaceVertex
, testMergeVertices
, testGmap
, testInduce ]
testConsistent :: TestsuiteInt g -> IO ()
testConsistent (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "consistent ============"
test "Consistency of the Arbitrary instance" $ \x -> consistent x
putStrLn ""
test "consistent empty == True" $
consistent empty == True
test "consistent (vertex x) == True" $ \x ->
consistent (vertex x) == True
test "consistent (overlay x y) == True" $ \x y ->
consistent (overlay x y) == True
test "consistent (connect x y) == True" $ \x y ->
consistent (connect x y) == True
test "consistent (edge x y) == True" $ \x y ->
consistent (edge x y) == True
test "consistent (edges xs) == True" $ \xs ->
consistent (edges xs) == True
test "consistent (stars xs) == True" $ \xs ->
consistent (stars xs) == True
testShow :: TestsuiteInt g -> IO ()
testShow (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "Show ============"
test "show (empty ) == \"empty\"" $
show (empty ) == "empty"
test "show (1 ) == \"vertex 1\"" $
show (1 `asTypeOf` empty) == "vertex 1"
test "show (1 + 2 ) == \"vertices [1,2]\"" $
show (1 + 2 `asTypeOf` empty) == "vertices [1,2]"
test "show (1 * 2 ) == \"edge 1 2\"" $
show (1 * 2 `asTypeOf` empty) == "edge 1 2"
test "show (1 * 2 * 3) == \"edges [(1,2),(1,3),(2,3)]\"" $
show (1 * 2 * 3 `asTypeOf` empty) == "edges [(1,2),(1,3),(2,3)]"
test "show (1 * 2 + 3) == \"overlay (vertex 3) (edge 1 2)\"" $
show (1 * 2 + 3 `asTypeOf` empty) == "overlay (vertex 3) (edge 1 2)"
putStrLn ""
test "show (vertex (-1) ) == \"vertex (-1)\"" $
show (vertex (-1) ) == "vertex (-1)"
test "show (vertex (-1) + vertex (-2) ) == \"vertices [-2,-1]\"" $
show (vertex (-1) + vertex (-2) ) == "vertices [-2,-1]"
test "show (vertex (-2) * vertex (-1) ) == \"edge (-2) (-1)\"" $
show (vertex (-2) * vertex (-1) ) == "edge (-2) (-1)"
test "show (vertex (-3) * vertex (-2) * vertex (-1)) == \"edges [(-3,-2),(-3,-1),(-2,-1)]\"" $
show (vertex (-3) * vertex (-2) * vertex (-1)) == "edges [(-3,-2),(-3,-1),(-2,-1)]"
test "show (vertex (-3) * vertex (-2) + vertex (-1)) == \"overlay (vertex (-1)) (edge (-3) (-2))\"" $
show (vertex (-3) * vertex (-2) + vertex (-1)) == "overlay (vertex (-1)) (edge (-3) (-2))"
testSymmetricShow :: TestsuiteInt g -> IO ()
testSymmetricShow t@(_, API{..}) = do
testShow t
putStrLn ""
test "show (2 * 1 ) == \"edge 1 2\"" $
show (2 * 1 `asTypeOf` empty) == "edge 1 2"
test "show (1 * 2 * 1) == \"edges [(1,1),(1,2)]\"" $
show (1 * 2 * 1 `asTypeOf` empty) == "edges [(1,1),(1,2)]"
test "show (3 * 2 * 1) == \"edges [(1,2),(1,3),(2,3)]\"" $
show (3 * 2 * 1 `asTypeOf` empty) == "edges [(1,2),(1,3),(2,3)]"
testOrd :: TestsuiteInt g -> IO ()
testOrd (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "Ord ============"
test "vertex 1 < vertex 2" $
vertex 1 < vertex 2
test "vertex 3 < edge 1 2" $
vertex 3 < edge 1 2
test "vertex 1 < edge 1 1" $
vertex 1 < edge 1 1
test "edge 1 1 < edge 1 2" $
edge 1 1 < edge 1 2
test "edge 1 2 < edge 1 1 + edge 2 2" $
edge 1 2 < edge 1 1 + edge 2 2
test "edge 1 2 < edge 1 3" $
edge 1 2 < edge 1 3
test "x <= x + y" $ \x y ->
x <= x + (y `asTypeOf` empty)
test "x + y <= x * y" $ \x y ->
x + y <= x * (y `asTypeOf` empty)
testSymmetricOrd :: TestsuiteInt g -> IO ()
testSymmetricOrd (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "Ord ============"
test "vertex 1 < vertex 2" $
vertex 1 < vertex 2
test "vertex 3 < edge 1 2" $
vertex 3 < edge 1 2
test "vertex 1 < edge 1 1" $
vertex 1 < edge 1 1
test "edge 1 1 < edge 1 2" $
edge 1 1 < edge 1 2
test "edge 1 2 < edge 1 1 + edge 2 2" $
edge 1 2 < edge 1 1 + edge 2 2
test "edge 2 1 < edge 1 3" $
edge 2 1 < edge 1 3
test "edge 1 2 == edge 2 1" $
edge 1 2 == edge 2 1
test "x <= x + y" $ \x y ->
x <= x + (y `asTypeOf` empty)
test "x + y <= x * y" $ \x y ->
x + y <= x * (y `asTypeOf` empty)
testEmpty :: TestsuiteInt g -> IO ()
testEmpty (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "empty ============"
test "isEmpty empty == True" $
isEmpty empty == True
test "hasVertex x empty == False" $ \x ->
hasVertex x empty == False
test "vertexCount empty == 0" $
vertexCount empty == 0
test "edgeCount empty == 0" $
edgeCount empty == 0
testVertex :: TestsuiteInt g -> IO ()
testVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertex ============"
test "isEmpty (vertex x) == False" $ \x ->
isEmpty (vertex x) == False
test "hasVertex x (vertex y) == (x == y)" $ \x y ->
hasVertex x (vertex y) == (x == y)
test "vertexCount (vertex x) == 1" $ \x ->
vertexCount (vertex x) == 1
test "edgeCount (vertex x) == 0" $ \x ->
edgeCount (vertex x) == 0
testEdge :: TestsuiteInt g -> IO ()
testEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edge ============"
test "edge x y == connect (vertex x) (vertex y)" $ \x y ->
edge x y == connect (vertex x) (vertex y)
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "edgeCount (edge x y) == 1" $ \x y ->
edgeCount (edge x y) == 1
test "vertexCount (edge 1 1) == 1" $
vertexCount (edge 1 1) == 1
test "vertexCount (edge 1 2) == 2" $
vertexCount (edge 1 2) == 2
testSymmetricEdge :: TestsuiteInt g -> IO ()
testSymmetricEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edge ============"
test "edge x y == connect (vertex x) (vertex y)" $ \x y ->
edge x y == connect (vertex x) (vertex y)
test "edge x y == edge y x" $ \x y ->
edge x y == edge y x
test "edge x y == edges [(x,y), (y,x)]" $ \x y ->
edge x y == edges [(x,y), (y,x)]
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "edgeCount (edge x y) == 1" $ \x y ->
edgeCount (edge x y) == 1
test "vertexCount (edge 1 1) == 1" $
vertexCount (edge 1 1) == 1
test "vertexCount (edge 1 2) == 2" $
vertexCount (edge 1 2) == 2
testOverlay :: TestsuiteInt g -> IO ()
testOverlay (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "overlay ============"
test "isEmpty (overlay x y) == isEmpty x && isEmpty y" $ \x y ->
isEmpty (overlay x y) ==(isEmpty x && isEmpty y)
test "hasVertex z (overlay x y) == hasVertex z x || hasVertex z y" $ \x y z ->
hasVertex z (overlay x y) ==(hasVertex z x || hasVertex z y)
test "vertexCount (overlay x y) >= vertexCount x" $ \x y ->
vertexCount (overlay x y) >= vertexCount x
test "vertexCount (overlay x y) <= vertexCount x + vertexCount y" $ \x y ->
vertexCount (overlay x y) <= vertexCount x + vertexCount y
test "edgeCount (overlay x y) >= edgeCount x" $ \x y ->
edgeCount (overlay x y) >= edgeCount x
test "edgeCount (overlay x y) <= edgeCount x + edgeCount y" $ \x y ->
edgeCount (overlay x y) <= edgeCount x + edgeCount y
test "vertexCount (overlay 1 2) == 2" $
vertexCount (overlay 1 2) == 2
test "edgeCount (overlay 1 2) == 0" $
edgeCount (overlay 1 2) == 0
testConnect :: TestsuiteInt g -> IO ()
testConnect (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "connect ============"
test "isEmpty (connect x y) == isEmpty x && isEmpty y" $ \x y ->
isEmpty (connect x y) ==(isEmpty x && isEmpty y)
test "hasVertex z (connect x y) == hasVertex z x || hasVertex z y" $ \x y z ->
hasVertex z (connect x y) ==(hasVertex z x || hasVertex z y)
test "vertexCount (connect x y) >= vertexCount x" $ \x y ->
vertexCount (connect x y) >= vertexCount x
test "vertexCount (connect x y) <= vertexCount x + vertexCount y" $ \x y ->
vertexCount (connect x y) <= vertexCount x + vertexCount y
test "edgeCount (connect x y) >= edgeCount x" $ \x y ->
edgeCount (connect x y) >= edgeCount x
test "edgeCount (connect x y) >= edgeCount y" $ \x y ->
edgeCount (connect x y) >= edgeCount y
test "edgeCount (connect x y) >= vertexCount x * vertexCount y" $ \x y ->
edgeCount (connect x y) >= vertexCount x * vertexCount y
test "edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y" $ \x y ->
edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y
test "vertexCount (connect 1 2) == 2" $
vertexCount (connect 1 2) == 2
test "edgeCount (connect 1 2) == 1" $
edgeCount (connect 1 2) == 1
testSymmetricConnect :: TestsuiteInt g -> IO ()
testSymmetricConnect (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "connect ============"
test "connect x y == connect y x" $ \x y ->
connect x y == connect y x
test "isEmpty (connect x y) == isEmpty x && isEmpty y" $ \x y ->
isEmpty (connect x y) ==(isEmpty x && isEmpty y)
test "hasVertex z (connect x y) == hasVertex z x || hasVertex z y" $ \x y z ->
hasVertex z (connect x y) ==(hasVertex z x || hasVertex z y)
test "vertexCount (connect x y) >= vertexCount x" $ \x y ->
vertexCount (connect x y) >= vertexCount x
test "vertexCount (connect x y) <= vertexCount x + vertexCount y" $ \x y ->
vertexCount (connect x y) <= vertexCount x + vertexCount y
test "edgeCount (connect x y) >= edgeCount x" $ \x y ->
edgeCount (connect x y) >= edgeCount x
test "edgeCount (connect x y) >= edgeCount y" $ \x y ->
edgeCount (connect x y) >= edgeCount y
test "edgeCount (connect x y) >= vertexCount x * vertexCount y `div` 2" $ \x y ->
edgeCount (connect x y) >= vertexCount x * vertexCount y `div` 2
test "edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y" $ \x y ->
edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y
test "vertexCount (connect 1 2) == 2" $
vertexCount (connect 1 2) == 2
test "edgeCount (connect 1 2) == 1" $
edgeCount (connect 1 2) == 1
testVertices :: TestsuiteInt g -> IO ()
testVertices (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertices ============"
test "vertices [] == empty" $
vertices [] == empty
test "vertices [x] == vertex x" $ \x ->
vertices [x] == vertex x
test "vertices == overlays . map vertex" $ \xs ->
vertices xs ==(overlays . map vertex) xs
test "hasVertex x . vertices == elem x" $ \x xs ->
(hasVertex x . vertices) xs == elem x xs
test "vertexCount . vertices == length . nub" $ \xs ->
(vertexCount . vertices) xs == (length . nubOrd) xs
test "vertexSet . vertices == Set.fromList" $ \xs ->
(vertexSet . vertices) xs == Set.fromList xs
testEdges :: TestsuiteInt g -> IO ()
testEdges (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edges ============"
test "edges [] == empty" $
edges [] == empty
test "edges [(x,y)] == edge x y" $ \x y ->
edges [(x,y)] == edge x y
test "edges == overlays . map (uncurry edge)" $ \xs ->
edges xs == (overlays . map (uncurry edge)) xs
test "edgeCount . edges == length . nub" $ \xs ->
(edgeCount . edges) xs == (length . nubOrd) xs
testSymmetricEdges :: TestsuiteInt g -> IO ()
testSymmetricEdges (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edges ============"
test "edges [] == empty" $
edges [] == empty
test "edges [(x,y)] == edge x y" $ \x y ->
edges [(x,y)] == edge x y
test "edges [(x,y), (y,x)] == edge x y" $ \x y ->
edges [(x,y), (y,x)] == edge x y
testOverlays :: TestsuiteInt g -> IO ()
testOverlays (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "overlays ============"
test "overlays [] == empty" $
overlays [] == empty
test "overlays [x] == x" $ \x ->
overlays [x] == x
test "overlays [x,y] == overlay x y" $ \x y ->
overlays [x,y] == overlay x y
test "overlays == foldr overlay empty" $ size10 $ \xs ->
overlays xs == foldr overlay empty xs
test "isEmpty . overlays == all isEmpty" $ size10 $ \xs ->
(isEmpty . overlays) xs == all isEmpty xs
testConnects :: TestsuiteInt g -> IO ()
testConnects (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "connects ============"
test "connects [] == empty" $
connects [] == empty
test "connects [x] == x" $ \x ->
connects [x] == x
test "connects [x,y] == connect x y" $ \x y ->
connects [x,y] == connect x y
test "connects == foldr connect empty" $ size10 $ \xs ->
connects xs == foldr connect empty xs
test "isEmpty . connects == all isEmpty" $ size10 $ \xs ->
(isEmpty . connects) xs == all isEmpty xs
testSymmetricConnects :: TestsuiteInt g -> IO ()
testSymmetricConnects t@(_, API{..}) = do
testConnects t
test "connects == connects . reverse" $ size10 $ \xs ->
connects xs == connects (reverse xs)
testStars :: TestsuiteInt g -> IO ()
testStars (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "stars ============"
test "stars [] == empty" $
stars [] == empty
test "stars [(x, [])] == vertex x" $ \x ->
stars [(x, [])] == vertex x
test "stars [(x, [y])] == edge x y" $ \x y ->
stars [(x, [y])] == edge x y
test "stars [(x, ys)] == star x ys" $ \x ys ->
stars [(x, ys)] == star x ys
test "stars == overlays . map (uncurry star)" $ \xs ->
stars xs == overlays (map (uncurry star) xs)
test "stars . adjacencyList == id" $ \x ->
(stars . adjacencyList) x == id x
test "overlay (stars xs) (stars ys) == stars (xs ++ ys)" $ \xs ys ->
overlay (stars xs) (stars ys) == stars (xs ++ ys)
testFromAdjacencySets :: TestsuiteInt g -> IO ()
testFromAdjacencySets (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "fromAdjacencySets ============"
test "fromAdjacencySets [] == empty" $
fromAdjacencySets [] == empty
test "fromAdjacencySets [(x, Set.empty)] == vertex x" $ \x ->
fromAdjacencySets [(x, Set.empty)] == vertex x
test "fromAdjacencySets [(x, Set.singleton y)] == edge x y" $ \x y ->
fromAdjacencySets [(x, Set.singleton y)] == edge x y
test "fromAdjacencySets . map (fmap Set.fromList) == stars" $ \x ->
(fromAdjacencySets . map (fmap Set.fromList)) x == stars x
test "overlay (fromAdjacencySets xs) (fromAdjacencySets ys) == fromAdjacencySets (xs ++ ys)" $ \xs ys ->
overlay (fromAdjacencySets xs) (fromAdjacencySets ys) == fromAdjacencySets (xs ++ ys)
testFromAdjacencyIntSets :: TestsuiteInt g -> IO ()
testFromAdjacencyIntSets (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "fromAdjacencyIntSets ============"
test "fromAdjacencyIntSets [] == empty" $
fromAdjacencyIntSets [] == empty
test "fromAdjacencyIntSets [(x, IntSet.empty)] == vertex x" $ \x ->
fromAdjacencyIntSets [(x, IntSet.empty)] == vertex x
test "fromAdjacencyIntSets [(x, IntSet.singleton y)] == edge x y" $ \x y ->
fromAdjacencyIntSets [(x, IntSet.singleton y)] == edge x y
test "fromAdjacencyIntSets . map (fmap IntSet.fromList) == stars" $ \x ->
(fromAdjacencyIntSets . map (fmap IntSet.fromList)) x == stars x
test "overlay (fromAdjacencyIntSets xs) (fromAdjacencyIntSets ys) == fromAdjacencyIntSets (xs ++ ys)" $ \xs ys ->
overlay (fromAdjacencyIntSets xs) (fromAdjacencyIntSets ys) == fromAdjacencyIntSets (xs ++ ys)
testIsSubgraphOf :: TestsuiteInt g -> IO ()
testIsSubgraphOf (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isSubgraphOf ============"
test "isSubgraphOf empty x == True" $ \x ->
isSubgraphOf empty x == True
test "isSubgraphOf (vertex x) empty == False" $ \x ->
isSubgraphOf (vertex x) empty == False
test "isSubgraphOf x (overlay x y) == True" $ \x y ->
isSubgraphOf x (overlay x y) == True
test "isSubgraphOf (overlay x y) (connect x y) == True" $ \x y ->
isSubgraphOf (overlay x y) (connect x y) == True
test "isSubgraphOf (path xs) (circuit xs) == True" $ \xs ->
isSubgraphOf (path xs) (circuit xs) == True
test "isSubgraphOf x y ==> x <= y" $ \x z ->
let y = x + z -- Make sure we hit the precondition
in isSubgraphOf x y ==> x <= y
testSymmetricIsSubgraphOf :: TestsuiteInt g -> IO ()
testSymmetricIsSubgraphOf t@(_, API{..}) = do
testIsSubgraphOf t
test "isSubgraphOf (edge x y) (edge y x) == True" $ \x y ->
isSubgraphOf (edge x y) (edge y x) == True
testToGraphDefault :: TestsuiteInt g -> IO ()
testToGraphDefault (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "toGraph et al. ============"
test "toGraph == foldg Empty Vertex Overlay Connect" $ \x ->
toGraph x == foldg G.Empty G.Vertex G.Overlay G.Connect x
test "foldg == Algebra.Graph.foldg . toGraph" $ \e (apply -> v) (applyFun2 -> o) (applyFun2 -> c) x ->
foldg e v o c x == (G.foldg (e :: Int) v o c . toGraph) x
test "isEmpty == foldg True (const False) (&&) (&&)" $ \x ->
isEmpty x == foldg True (const False) (&&) (&&) x
test "size == foldg 1 (const 1) (+) (+)" $ \x ->
size x == foldg 1 (const 1) (+) (+) x
test "hasVertex x == foldg False (==x) (||) (||)" $ \x y ->
hasVertex x y == foldg False (==x) (||) (||) y
test "hasEdge x y == Algebra.Graph.hasEdge x y . toGraph" $ \x y z ->
hasEdge x y z == (G.hasEdge x y . toGraph) z
test "vertexCount == Set.size . vertexSet" $ \x ->
vertexCount x == (Set.size . vertexSet) x
test "edgeCount == Set.size . edgeSet" $ \x ->
edgeCount x == (Set.size . edgeSet) x
test "vertexList == Set.toAscList . vertexSet" $ \x ->
vertexList x == (Set.toAscList . vertexSet) x
test "edgeList == Set.toAscList . edgeSet" $ \x ->
edgeList x == (Set.toAscList . edgeSet) x
test "vertexSet == foldg Set.empty Set.singleton Set.union Set.union" $ \x ->
vertexSet x == foldg Set.empty Set.singleton Set.union Set.union x
test "vertexIntSet == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union" $ \x ->
vertexIntSet x == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union x
test "edgeSet == Algebra.Graph.AdjacencyMap.edgeSet . foldg empty vertex overlay connect" $ \x ->
edgeSet x == (AM.edgeSet . foldg AM.empty AM.vertex AM.overlay AM.connect) x
test "preSet x == Algebra.Graph.AdjacencyMap.preSet x . toAdjacencyMap" $ \x y ->
preSet x y == (AM.preSet x . toAdjacencyMap) y
test "preIntSet x == Algebra.Graph.AdjacencyIntMap.preIntSet x . toAdjacencyIntMap" $ \x y ->
preIntSet x y == (AIM.preIntSet x . toAdjacencyIntMap) y
test "postSet x == Algebra.Graph.AdjacencyMap.postSet x . toAdjacencyMap" $ \x y ->
postSet x y == (AM.postSet x . toAdjacencyMap) y
test "postIntSet x == Algebra.Graph.AdjacencyIntMap.postIntSet x . toAdjacencyIntMap" $ \x y ->
postIntSet x y == (AIM.postIntSet x . toAdjacencyIntMap) y
test "adjacencyList == Algebra.Graph.AdjacencyMap.adjacencyList . toAdjacencyMap" $ \x ->
adjacencyList x == (AM.adjacencyList . toAdjacencyMap) x
test "adjacencyMap == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMap" $ \x ->
adjacencyMap x == (AM.adjacencyMap . toAdjacencyMap) x
test "adjacencyIntMap == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMap" $ \x ->
adjacencyIntMap x == (AIM.adjacencyIntMap . toAdjacencyIntMap) x
test "adjacencyMapTranspose == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMapTranspose" $ \x ->
adjacencyMapTranspose x == (AM.adjacencyMap . toAdjacencyMapTranspose) x
test "adjacencyIntMapTranspose == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMapTranspose" $ \x ->
adjacencyIntMapTranspose x == (AIM.adjacencyIntMap . toAdjacencyIntMapTranspose) x
test "dfsForest == Algebra.Graph.AdjacencyMap.dfsForest . toAdjacencyMap" $ \x ->
dfsForest x == (AM.dfsForest . toAdjacencyMap) x
test "dfsForestFrom == Algebra.Graph.AdjacencyMap.dfsForestFrom . toAdjacencyMap" $ \x vs ->
dfsForestFrom x vs == (AM.dfsForestFrom . toAdjacencyMap) x vs
test "dfs == Algebra.Graph.AdjacencyMap.dfs . toAdjacencyMap" $ \x vs ->
dfs x vs == (AM.dfs . toAdjacencyMap) x vs
test "reachable == Algebra.Graph.AdjacencyMap.reachable . toAdjacencyMap" $ \x y ->
reachable x y == (AM.reachable . toAdjacencyMap) x y
test "topSort == Algebra.Graph.AdjacencyMap.topSort . toAdjacencyMap" $ \x ->
topSort x == (AM.topSort . toAdjacencyMap) x
test "isAcyclic == Algebra.Graph.AdjacencyMap.isAcyclic . toAdjacencyMap" $ \x ->
isAcyclic x == (AM.isAcyclic . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
test "toAdjacencyMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyMap x == foldg AM.empty AM.vertex AM.overlay AM.connect x
test "toAdjacencyMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyMapTranspose x == foldg AM.empty AM.vertex AM.overlay (flip AM.connect) x
test "toAdjacencyIntMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyIntMap x == foldg AIM.empty AIM.vertex AIM.overlay AIM.connect x
test "toAdjacencyIntMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyIntMapTranspose x == foldg AIM.empty AIM.vertex AIM.overlay (flip AIM.connect) x
test "isDfsForestOf f == Algebra.Graph.AdjacencyMap.isDfsForestOf f . toAdjacencyMap" $ \f x ->
isDfsForestOf f x == (AM.isDfsForestOf f . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
-- TODO: We currently do not test 'edgeSet'.
testSymmetricToGraphDefault :: TestsuiteInt g -> IO ()
testSymmetricToGraphDefault (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "toGraph et al. ============"
test "toGraph == foldg Empty Vertex Overlay Connect" $ \x ->
toGraph x == foldg G.Empty G.Vertex G.Overlay G.Connect x
test "foldg == Algebra.Graph.foldg . toGraph" $ \e (apply -> v) (applyFun2 -> o) (applyFun2 -> c) x ->
foldg e v o c x == (G.foldg (e :: Int) v o c . toGraph) x
test "isEmpty == foldg True (const False) (&&) (&&)" $ \x ->
isEmpty x == foldg True (const False) (&&) (&&) x
test "size == foldg 1 (const 1) (+) (+)" $ \x ->
size x == foldg 1 (const 1) (+) (+) x
test "hasVertex x == foldg False (==x) (||) (||)" $ \x y ->
hasVertex x y == foldg False (==x) (||) (||) y
test "hasEdge x y == Algebra.Graph.hasEdge x y . toGraph" $ \x y z ->
hasEdge x y z == (G.hasEdge x y . toGraph) z
test "vertexCount == Set.size . vertexSet" $ \x ->
vertexCount x == (Set.size . vertexSet) x
test "edgeCount == Set.size . edgeSet" $ \x ->
edgeCount x == (Set.size . edgeSet) x
test "vertexList == Set.toAscList . vertexSet" $ \x ->
vertexList x == (Set.toAscList . vertexSet) x
test "edgeList == Set.toAscList . edgeSet" $ \x ->
edgeList x == (Set.toAscList . edgeSet) x
test "vertexSet == foldg Set.empty Set.singleton Set.union Set.union" $ \x ->
vertexSet x == foldg Set.empty Set.singleton Set.union Set.union x
test "vertexIntSet == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union" $ \x ->
vertexIntSet x == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union x
test "adjacencyList == Algebra.Graph.AdjacencyMap.adjacencyList . toAdjacencyMap" $ \x ->
adjacencyList x == (AM.adjacencyList . toAdjacencyMap) x
test "adjacencyMap == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMap" $ \x ->
adjacencyMap x == (AM.adjacencyMap . toAdjacencyMap) x
test "adjacencyIntMap == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMap" $ \x ->
adjacencyIntMap x == (AIM.adjacencyIntMap . toAdjacencyIntMap) x
test "adjacencyMapTranspose == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMapTranspose" $ \x ->
adjacencyMapTranspose x == (AM.adjacencyMap . toAdjacencyMapTranspose) x
test "adjacencyIntMapTranspose == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMapTranspose" $ \x ->
adjacencyIntMapTranspose x == (AIM.adjacencyIntMap . toAdjacencyIntMapTranspose) x
test "dfsForest == Algebra.Graph.AdjacencyMap.dfsForest . toAdjacencyMap" $ \x ->
dfsForest x == (AM.dfsForest . toAdjacencyMap) x
test "dfsForestFrom == Algebra.Graph.AdjacencyMap.dfsForestFrom . toAdjacencyMap" $ \x vs ->
dfsForestFrom x vs == (AM.dfsForestFrom . toAdjacencyMap) x vs
test "dfs == Algebra.Graph.AdjacencyMap.dfs . toAdjacencyMap" $ \x vs ->
dfs x vs == (AM.dfs . toAdjacencyMap) x vs
test "reachable == Algebra.Graph.AdjacencyMap.reachable . toAdjacencyMap" $ \x y ->
reachable x y == (AM.reachable . toAdjacencyMap) x y
test "topSort == Algebra.Graph.AdjacencyMap.topSort . toAdjacencyMap" $ \x ->
topSort x == (AM.topSort . toAdjacencyMap) x
test "isAcyclic == Algebra.Graph.AdjacencyMap.isAcyclic . toAdjacencyMap" $ \x ->
isAcyclic x == (AM.isAcyclic . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
test "toAdjacencyMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyMap x == foldg AM.empty AM.vertex AM.overlay AM.connect x
test "toAdjacencyMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyMapTranspose x == foldg AM.empty AM.vertex AM.overlay (flip AM.connect) x
test "toAdjacencyIntMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyIntMap x == foldg AIM.empty AIM.vertex AIM.overlay AIM.connect x
test "toAdjacencyIntMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyIntMapTranspose x == foldg AIM.empty AIM.vertex AIM.overlay (flip AIM.connect) x
test "isDfsForestOf f == Algebra.Graph.AdjacencyMap.isDfsForestOf f . toAdjacencyMap" $ \f x ->
isDfsForestOf f x == (AM.isDfsForestOf f . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
testFoldg :: TestsuiteInt g -> IO ()
testFoldg (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "foldg ============"
test "foldg empty vertex overlay connect == id" $ \x ->
foldg empty vertex overlay connect x == id x
test "foldg empty vertex overlay (flip connect) == transpose" $ \x ->
foldg empty vertex overlay (flip connect) x == transpose x
test "foldg 1 (const 1) (+) (+) == size" $ \x ->
foldg 1 (const 1) (+) (+) x == size x
test "foldg True (const False) (&&) (&&) == isEmpty" $ \x ->
foldg True (const False) (&&) (&&) x == isEmpty x
testIsEmpty :: TestsuiteInt g -> IO ()
testIsEmpty (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isEmpty ============"
test "isEmpty empty == True" $
isEmpty empty == True
test "isEmpty (overlay empty empty) == True" $
isEmpty (overlay empty empty) == True
test "isEmpty (vertex x) == False" $ \x ->
isEmpty (vertex x) == False
test "isEmpty (removeVertex x $ vertex x) == True" $ \x ->
isEmpty (removeVertex x $ vertex x) == True
test "isEmpty (removeEdge x y $ edge x y) == False" $ \x y ->
isEmpty (removeEdge x y $ edge x y) == False
testSize :: TestsuiteInt g -> IO ()
testSize (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "size ============"
test "size empty == 1" $
size empty == 1
test "size (vertex x) == 1" $ \x ->
size (vertex x) == 1
test "size (overlay x y) == size x + size y" $ \x y ->
size (overlay x y) == size x + size y
test "size (connect x y) == size x + size y" $ \x y ->
size (connect x y) == size x + size y
test "size x >= 1" $ \x ->
size x >= 1
test "size x >= vertexCount x" $ \x ->
size x >= vertexCount x
testHasVertex :: TestsuiteInt g -> IO ()
testHasVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "hasVertex ============"
test "hasVertex x empty == False" $ \x ->
hasVertex x empty == False
test "hasVertex x (vertex y) == (x == y)" $ \x y ->
hasVertex x (vertex y) == (x == y)
test "hasVertex x . removeVertex x == const False" $ \x y ->
(hasVertex x . removeVertex x) y == const False y
testHasEdge :: TestsuiteInt g -> IO ()
testHasEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "hasEdge ============"
test "hasEdge x y empty == False" $ \x y ->
hasEdge x y empty == False
test "hasEdge x y (vertex z) == False" $ \x y z ->
hasEdge x y (vertex z) == False
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "hasEdge x y . removeEdge x y == const False" $ \x y z ->
(hasEdge x y . removeEdge x y) z == const False z
test "hasEdge x y == elem (x,y) . edgeList" $ \x y z -> do
let es = edgeList z
(x, y) <- elements ((x, y) : es)
return $ hasEdge x y z == elem (x, y) es
testSymmetricHasEdge :: TestsuiteInt g -> IO ()
testSymmetricHasEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "hasEdge ============"
test "hasEdge x y empty == False" $ \x y ->
hasEdge x y empty == False
test "hasEdge x y (vertex z) == False" $ \x y z ->
hasEdge x y (vertex z) == False
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "hasEdge x y (edge y x) == True" $ \x y ->
hasEdge x y (edge y x) == True
test "hasEdge x y . removeEdge x y == const False" $ \x y z ->
(hasEdge x y . removeEdge x y) z == const False z
test "hasEdge x y == elem (min x y, max x y) . edgeList" $ \x y z -> do
(u, v) <- elements ((x, y) : edgeList z)
return $ hasEdge u v z == elem (min u v, max u v) (edgeList z)
testVertexCount :: TestsuiteInt g -> IO ()
testVertexCount (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexCount ============"
test "vertexCount empty == 0" $
vertexCount empty == 0
test "vertexCount (vertex x) == 1" $ \x ->
vertexCount (vertex x) == 1
test "vertexCount == length . vertexList" $ \x ->
vertexCount x == (length . vertexList) x
test "vertexCount x < vertexCount y ==> x < y" $ \x y ->
if vertexCount x < vertexCount y
then property (x < y)
else (vertexCount x > vertexCount y ==> x > y)
testEdgeCount :: TestsuiteInt g -> IO ()
testEdgeCount (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeCount ============"
test "edgeCount empty == 0" $
edgeCount empty == 0
test "edgeCount (vertex x) == 0" $ \x ->
edgeCount (vertex x) == 0
test "edgeCount (edge x y) == 1" $ \x y ->
edgeCount (edge x y) == 1
test "edgeCount == length . edgeList" $ \x ->
edgeCount x == (length . edgeList) x
testVertexList :: TestsuiteInt g -> IO ()
testVertexList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexList ============"
test "vertexList empty == []" $
vertexList empty == []
test "vertexList (vertex x) == [x]" $ \x ->
vertexList (vertex x) == [x]
test "vertexList . vertices == nub . sort" $ \xs ->
(vertexList . vertices) xs == (nubOrd . sort) xs
testEdgeList :: TestsuiteInt g -> IO ()
testEdgeList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeList ============"
test "edgeList empty == []" $
edgeList empty == []
test "edgeList (vertex x) == []" $ \x ->
edgeList (vertex x) == []
test "edgeList (edge x y) == [(x,y)]" $ \x y ->
edgeList (edge x y) == [(x,y)]
test "edgeList (star 2 [3,1]) == [(2,1), (2,3)]" $
edgeList (star 2 [3,1]) == [(2,1), (2,3)]
test "edgeList . edges == nub . sort" $ \xs ->
(edgeList . edges) xs == (nubOrd . sort) xs
testSymmetricEdgeList :: TestsuiteInt g -> IO ()
testSymmetricEdgeList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeList ============"
test "edgeList empty == []" $
edgeList empty == []
test "edgeList (vertex x) == []" $ \x ->
edgeList (vertex x) == []
test "edgeList (edge x y) == [(min x y, max y x)]" $ \x y ->
edgeList (edge x y) == [(min x y, max y x)]
test "edgeList (star 2 [3,1]) == [(1,2), (2,3)]" $
edgeList (star 2 [3,1]) == [(1,2), (2,3)]
testAdjacencyList :: TestsuiteInt g -> IO ()
testAdjacencyList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "adjacencyList ============"
test "adjacencyList empty == []" $
adjacencyList empty == []
test "adjacencyList (vertex x) == [(x, [])]" $ \x ->
adjacencyList (vertex x) == [(x, [])]
test "adjacencyList (edge 1 2) == [(1, [2]), (2, [])]" $
adjacencyList (edge 1 2) == [(1, [2]), (2, [])]
test "adjacencyList (star 2 [3,1]) == [(1, []), (2, [1,3]), (3, [])]" $
adjacencyList (star 2 [3,1]) == [(1, []), (2, [1,3]), (3, [])]
testSymmetricAdjacencyList :: TestsuiteInt g -> IO ()
testSymmetricAdjacencyList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "adjacencyList ============"
test "adjacencyList empty == []" $
adjacencyList empty == []
test "adjacencyList (vertex x) == [(x, [])]" $ \x ->
adjacencyList (vertex x) == [(x, [])]
test "adjacencyList (edge 1 2) == [(1, [2]), (2, [1])]" $
adjacencyList (edge 1 2) == [(1, [2]), (2, [1])]
test "adjacencyList (star 2 [3,1]) == [(1, [2]), (2, [1,3]), (3, [2])]" $
adjacencyList (star 2 [3,1]) == [(1, [2]), (2, [1,3]), (3, [2])]
testVertexSet :: TestsuiteInt g -> IO ()
testVertexSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexSet ============"
test "vertexSet empty == Set.empty" $
vertexSet empty == Set.empty
test "vertexSet . vertex == Set.singleton" $ \x ->
(vertexSet . vertex) x == Set.singleton x
test "vertexSet . vertices == Set.fromList" $ \xs ->
(vertexSet . vertices) xs == Set.fromList xs
testVertexIntSet :: TestsuiteInt g -> IO ()
testVertexIntSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexIntSet ============"
test "vertexIntSet empty == IntSet.empty" $
vertexIntSet empty == IntSet.empty
test "vertexIntSet . vertex == IntSet.singleton" $ \x ->
(vertexIntSet . vertex) x == IntSet.singleton x
test "vertexIntSet . vertices == IntSet.fromList" $ \xs ->
(vertexIntSet . vertices) xs == IntSet.fromList xs
test "vertexIntSet . clique == IntSet.fromList" $ \xs ->
(vertexIntSet . clique) xs == IntSet.fromList xs
testEdgeSet :: TestsuiteInt g -> IO ()
testEdgeSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeSet ============"
test "edgeSet empty == Set.empty" $
edgeSet empty == Set.empty
test "edgeSet (vertex x) == Set.empty" $ \x ->
edgeSet (vertex x) == Set.empty
test "edgeSet (edge x y) == Set.singleton (x,y)" $ \x y ->
edgeSet (edge x y) == Set.singleton (x,y)
test "edgeSet . edges == Set.fromList" $ \xs ->
(edgeSet . edges) xs == Set.fromList xs
testSymmetricEdgeSet :: TestsuiteInt g -> IO ()
testSymmetricEdgeSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeSet ============"
test "edgeSet empty == Set.empty" $
edgeSet empty == Set.empty
test "edgeSet (vertex x) == Set.empty" $ \x ->
edgeSet (vertex x) == Set.empty
test "edgeSet (edge x y) == Set.singleton (min x y, max x y)" $ \x y ->
edgeSet (edge x y) == Set.singleton (min x y, max x y)
testPreSet :: TestsuiteInt g -> IO ()
testPreSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "preSet ============"
test "preSet x empty == Set.empty" $ \x ->
preSet x empty == Set.empty
test "preSet x (vertex x) == Set.empty" $ \x ->
preSet x (vertex x) == Set.empty
test "preSet 1 (edge 1 2) == Set.empty" $
preSet 1 (edge 1 2) == Set.empty
test "preSet y (edge x y) == Set.fromList [x]" $ \x y ->
preSet y (edge x y) == Set.fromList [x]
testPostSet :: TestsuiteInt g -> IO ()
testPostSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "postSet ============"
test "postSet x empty == Set.empty" $ \x ->
postSet x empty == Set.empty
test "postSet x (vertex x) == Set.empty" $ \x ->
postSet x (vertex x) == Set.empty
test "postSet x (edge x y) == Set.fromList [y]" $ \x y ->
postSet x (edge x y) == Set.fromList [y]
test "postSet 2 (edge 1 2) == Set.empty" $
postSet 2 (edge 1 2) == Set.empty
testPreIntSet :: TestsuiteInt g -> IO ()
testPreIntSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "preIntSet ============"
test "preIntSet x empty == IntSet.empty" $ \x ->
preIntSet x empty == IntSet.empty
test "preIntSet x (vertex x) == IntSet.empty" $ \x ->
preIntSet x (vertex x) == IntSet.empty
test "preIntSet 1 (edge 1 2) == IntSet.empty" $
preIntSet 1 (edge 1 2) == IntSet.empty
test "preIntSet y (edge x y) == IntSet.fromList [x]" $ \x y ->
preIntSet y (edge x y) == IntSet.fromList [x]
testPostIntSet :: TestsuiteInt g -> IO ()
testPostIntSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "postIntSet ============"
test "postIntSet x empty == IntSet.empty" $ \x ->
postIntSet x empty == IntSet.empty
test "postIntSet x (vertex x) == IntSet.empty" $ \x ->
postIntSet x (vertex x) == IntSet.empty
test "postIntSet 2 (edge 1 2) == IntSet.empty" $
postIntSet 2 (edge 1 2) == IntSet.empty
test "postIntSet x (edge x y) == IntSet.fromList [y]" $ \x y ->
postIntSet x (edge x y) == IntSet.fromList [y]
testNeighbours :: TestsuiteInt g -> IO ()
testNeighbours (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "neighbours ============"
test "neighbours x empty == Set.empty" $ \x ->
neighbours x empty == Set.empty
test "neighbours x (vertex x) == Set.empty" $ \x ->
neighbours x (vertex x) == Set.empty
test "neighbours x (edge x y) == Set.fromList [y]" $ \x y ->
neighbours x (edge x y) == Set.fromList [y]
test "neighbours y (edge x y) == Set.fromList [x]" $ \x y ->
neighbours y (edge x y) == Set.fromList [x]
testPath :: TestsuiteInt g -> IO ()
testPath (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "path ============"
test "path [] == empty" $
path [] == empty
test "path [x] == vertex x" $ \x ->
path [x] == vertex x
test "path [x,y] == edge x y" $ \x y ->
path [x,y] == edge x y
testSymmetricPath :: TestsuiteInt g -> IO ()
testSymmetricPath t@(_, API{..}) = do
testPath t
test "path == path . reverse" $ \xs ->
path xs ==(path . reverse) xs
testCircuit :: TestsuiteInt g -> IO ()
testCircuit (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "circuit ============"
test "circuit [] == empty" $
circuit [] == empty
test "circuit [x] == edge x x" $ \x ->
circuit [x] == edge x x
test "circuit [x,y] == edges [(x,y), (y,x)]" $ \x y ->
circuit [x,y] == edges [(x,y), (y,x)]
testSymmetricCircuit :: TestsuiteInt g -> IO ()
testSymmetricCircuit t@(_, API{..}) = do
testCircuit t
test "circuit == circuit . reverse" $ \xs ->
circuit xs ==(circuit . reverse) xs
testClique :: TestsuiteInt g -> IO ()
testClique (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "clique ============"
test "clique [] == empty" $
clique [] == empty
test "clique [x] == vertex x" $ \x ->
clique [x] == vertex x
test "clique [x,y] == edge x y" $ \x y ->
clique [x,y] == edge x y
test "clique [x,y,z] == edges [(x,y), (x,z), (y,z)]" $ \x y z ->
clique [x,y,z] == edges [(x,y), (x,z), (y,z)]
test "clique (xs ++ ys) == connect (clique xs) (clique ys)" $ \xs ys ->
clique (xs ++ ys) == connect (clique xs) (clique ys)
testSymmetricClique :: TestsuiteInt g -> IO ()
testSymmetricClique t@(_, API{..}) = do
testClique t
test "clique == clique . reverse" $ \xs->
clique xs ==(clique . reverse) xs
testBiclique :: TestsuiteInt g -> IO ()
testBiclique (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "biclique ============"
test "biclique [] [] == empty" $
biclique [] [] == empty
test "biclique [x] [] == vertex x" $ \x ->
biclique [x] [] == vertex x
test "biclique [] [y] == vertex y" $ \y ->
biclique [] [y] == vertex y
test "biclique [x1,x2] [y1,y2] == edges [(x1,y1), (x1,y2), (x2,y1), (x2,y2)]" $ \x1 x2 y1 y2 ->
biclique [x1,x2] [y1,y2] == edges [(x1,y1), (x1,y2), (x2,y1), (x2,y2)]
test "biclique xs ys == connect (vertices xs) (vertices ys)" $ \xs ys ->
biclique xs ys == connect (vertices xs) (vertices ys)
testStar :: TestsuiteInt g -> IO ()
testStar (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "star ============"
test "star x [] == vertex x" $ \x ->
star x [] == vertex x
test "star x [y] == edge x y" $ \x y ->
star x [y] == edge x y
test "star x [y,z] == edges [(x,y), (x,z)]" $ \x y z ->
star x [y,z] == edges [(x,y), (x,z)]
test "star x ys == connect (vertex x) (vertices ys)" $ \x ys ->
star x ys == connect (vertex x) (vertices ys)
testTree :: TestsuiteInt g -> IO ()
testTree (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "tree ============"
test "tree (Node x []) == vertex x" $ \x ->
tree (Node x []) == vertex x
test "tree (Node x [Node y [Node z []]]) == path [x,y,z]" $ \x y z ->
tree (Node x [Node y [Node z []]]) == path [x,y,z]
test "tree (Node x [Node y [], Node z []]) == star x [y,z]" $ \x y z ->
tree (Node x [Node y [], Node z []]) == star x [y,z]
test "tree (Node 1 [Node 2 [], Node 3 [Node 4 [], Node 5 []]]) == edges [(1,2), (1,3), (3,4), (3,5)]" $
tree (Node 1 [Node 2 [], Node 3 [Node 4 [], Node 5 []]]) == edges [(1,2), (1,3), (3,4), (3,5)]
testForest :: TestsuiteInt g -> IO ()
testForest (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "forest ============"
test "forest [] == empty" $
forest [] == empty
test "forest [x] == tree x" $ \x ->
forest [x] == tree x
test "forest [Node 1 [Node 2 [], Node 3 []], Node 4 [Node 5 []]] == edges [(1,2), (1,3), (4,5)]" $
forest [Node 1 [Node 2 [], Node 3 []], Node 4 [Node 5 []]] == edges [(1,2), (1,3), (4,5)]
test "forest == overlays . map tree" $ \x ->
forest x ==(overlays . map tree) x
testMesh :: Testsuite g Ord -> IO ()
testMesh (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "mesh ============"
test "mesh xs [] == empty" $ \(xs :: [Int]) ->
mesh xs ([] :: [Int]) == empty
test "mesh [] ys == empty" $ \(ys :: [Int]) ->
mesh ([] :: [Int]) ys == empty
test "mesh [x] [y] == vertex (x, y)" $ \(x :: Int) (y :: Int) ->
mesh [x] [y] == vertex (x, y)
test "mesh xs ys == box (path xs) (path ys)" $ \(xs :: [Int]) (ys :: [Int]) ->
mesh xs ys == box (path xs) (path ys)
test "mesh [1..3] \"ab\" == <correct result>" $
mesh [1..3] "ab" == edges [ ((1,'a'),(1,'b')), ((1,'a'),(2,'a')), ((1,'b'),(2,'b')), ((2,'a'),(2,'b'))
, ((2,'a'),(3,'a')), ((2,'b'),(3,'b')), ((3,'a'),(3 :: Int,'b')) ]
test "size (mesh xs ys) == max 1 (3 * length xs * length ys - length xs - length ys -1)" $ \(xs :: [Int]) (ys :: [Int]) ->
size (mesh xs ys) == max 1 (3 * length xs * length ys - length xs - length ys -1)
testTorus :: Testsuite g Ord -> IO ()
testTorus (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "torus ============"
test "torus xs [] == empty" $ \(xs :: [Int]) ->
torus xs ([] :: [Int]) == empty
test "torus [] ys == empty" $ \(ys :: [Int]) ->
torus ([] :: [Int]) ys == empty
test "torus [x] [y] == edge (x,y) (x,y)" $ \(x :: Int) (y :: Int) ->
torus [x] [y] == edge (x,y) (x,y)
test "torus xs ys == box (circuit xs) (circuit ys)" $ \(xs :: [Int]) (ys :: [Int]) ->
torus xs ys == box (circuit xs) (circuit ys)
test "torus [1,2] \"ab\" == <correct result>" $
torus [1,2] "ab" == edges [ ((1,'a'),(1,'b')), ((1,'a'),(2,'a')), ((1,'b'),(1,'a')), ((1,'b'),(2,'b'))
, ((2,'a'),(1,'a')), ((2,'a'),(2,'b')), ((2,'b'),(1,'b')), ((2,'b'),(2 :: Int,'a')) ]
test "size (torus xs ys) == max 1 (3 * length xs * length ys)" $ \(xs :: [Int]) (ys :: [Int]) ->
size (torus xs ys) == max 1 (3 * length xs * length ys)
testDeBruijn :: Testsuite g Ord -> IO ()
testDeBruijn (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "deBruijn ============"
test " deBruijn 0 xs == edge [] []" $ \(xs :: [Int]) ->
deBruijn 0 xs == edge [] []
test "n > 0 ==> deBruijn n [] == empty" $ \n ->
n > 0 ==> deBruijn n ([] :: [Int]) == empty
test " deBruijn 1 [0,1] == edges [ ([0],[0]), ([0],[1]), ([1],[0]), ([1],[1]) ]" $
deBruijn 1 [0,1::Int] == edges [ ([0],[0]), ([0],[1]), ([1],[0]), ([1],[1]) ]
test " deBruijn 2 \"0\" == edge \"00\" \"00\"" $
deBruijn 2 "0" == edge "00" "00"
test " deBruijn 2 \"01\" == <correct result>" $
deBruijn 2 "01" == edges [ ("00","00"), ("00","01"), ("01","10"), ("01","11")
, ("10","00"), ("10","01"), ("11","10"), ("11","11") ]
test " transpose (deBruijn n xs) == gmap reverse $ deBruijn n xs" $ mapSize (min 5) $ \(NonNegative n) (xs :: [Int]) ->
transpose (deBruijn n xs) == gmap reverse (deBruijn n xs)
test " vertexCount (deBruijn n xs) == (length $ nub xs)^n" $ mapSize (min 5) $ \(NonNegative n) (xs :: [Int]) ->
vertexCount (deBruijn n xs) == (length $ nubOrd xs)^n
test "n > 0 ==> edgeCount (deBruijn n xs) == (length $ nub xs)^(n + 1)" $ mapSize (min 5) $ \(NonNegative n) (xs :: [Int]) ->
n > 0 ==> edgeCount (deBruijn n xs) == (length $ nubOrd xs)^(n + 1)
testBox :: Testsuite g Ord -> IO ()
testBox (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "box ============"
let unit = gmap $ \(a :: Int, () ) -> a
comm = gmap $ \(a :: Int, b :: Int) -> (b, a)
test "box x y ~~ box y x" $ mapSize (min 10) $ \x y ->
comm (box x y) == box y x
test "box x (overlay y z) == overlay (box x y) (box x z)" $ mapSize (min 10) $ \x y z ->
let _ = x + y + z + vertex (0 :: Int) in
box x (overlay y z) == overlay (box x y) (box x z)
test "box x (vertex ()) ~~ x" $ mapSize (min 10) $ \x ->
unit(box x (vertex ())) == (x `asTypeOf` empty)
test "box x empty ~~ empty" $ mapSize (min 10) $ \x ->
unit(box x empty) == empty
let assoc = gmap $ \(a :: Int, (b :: Int, c :: Int)) -> ((a, b), c)
test "box x (box y z) ~~ box (box x y) z" $ mapSize (min 10) $ \x y z ->
assoc (box x (box y z)) == box (box x y) z
test "transpose (box x y) == box (transpose x) (transpose y)" $ mapSize (min 10) $ \x y ->
let _ = x + y + vertex (0 :: Int) in
transpose (box x y) == box (transpose x) (transpose y)
test "vertexCount (box x y) == vertexCount x * vertexCount y" $ mapSize (min 10) $ \x y ->
let _ = x + y + vertex (0 :: Int) in
vertexCount (box x y) == vertexCount x * vertexCount y
test "edgeCount (box x y) <= vertexCount x * edgeCount y + edgeCount x * vertexCount y" $ mapSize (min 10) $ \x y ->
let _ = x + y + vertex (0 :: Int) in
edgeCount (box x y) <= vertexCount x * edgeCount y + edgeCount x * vertexCount y
testRemoveVertex :: TestsuiteInt g -> IO ()
testRemoveVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "removeVertex ============"
test "removeVertex x (vertex x) == empty" $ \x ->
removeVertex x (vertex x) == empty
test "removeVertex 1 (vertex 2) == vertex 2" $
removeVertex 1 (vertex 2) == vertex 2
test "removeVertex x (edge x x) == empty" $ \x ->
removeVertex x (edge x x) == empty
test "removeVertex 1 (edge 1 2) == vertex 2" $
removeVertex 1 (edge 1 2) == vertex 2
test "removeVertex x . removeVertex x == removeVertex x" $ \x y ->
(removeVertex x . removeVertex x) y == removeVertex x y
testRemoveEdge :: TestsuiteInt g -> IO ()
testRemoveEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "removeEdge ============"
test "removeEdge x y (edge x y) == vertices [x,y]" $ \x y ->
removeEdge x y (edge x y) == vertices [x,y]
test "removeEdge x y . removeEdge x y == removeEdge x y" $ \x y z ->
(removeEdge x y . removeEdge x y) z == removeEdge x y z
test "removeEdge x y . removeVertex x == removeVertex x" $ \x y z ->
(removeEdge x y . removeVertex x) z == removeVertex x z
test "removeEdge 1 1 (1 * 1 * 2 * 2) == 1 * 2 * 2" $
removeEdge 1 1 (1 * 1 * 2 * 2) == 1 * 2 * 2
test "removeEdge 1 2 (1 * 1 * 2 * 2) == 1 * 1 + 2 * 2" $
removeEdge 1 2 (1 * 1 * 2 * 2) == 1 * 1 + 2 * 2
-- TODO: Ouch. Generic tests are becoming awkward. We need a better way.
when (prefix == "Fold." || prefix == "Graph.") $ do
test "size (removeEdge x y z) <= 3 * size z" $ \x y z ->
size (removeEdge x y z) <= 3 * size z
testSymmetricRemoveEdge :: TestsuiteInt g -> IO ()
testSymmetricRemoveEdge t@(_, API{..}) = do
testRemoveEdge t
test "removeEdge x y == removeEdge y x" $ \x y z ->
removeEdge x y z == removeEdge y x z
testReplaceVertex :: TestsuiteInt g -> IO ()
testReplaceVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "replaceVertex ============"
test "replaceVertex x x == id" $ \x y ->
replaceVertex x x y == id y
test "replaceVertex x y (vertex x) == vertex y" $ \x y ->
replaceVertex x y (vertex x) == vertex y
test "replaceVertex x y == mergeVertices (== x) y" $ \x y z ->
replaceVertex x y z == mergeVertices (== x) y z
testMergeVertices :: TestsuiteInt g -> IO ()
testMergeVertices (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "mergeVertices ============"
test "mergeVertices (const False) x == id" $ \x y ->
mergeVertices (const False) x y == id y
test "mergeVertices (== x) y == replaceVertex x y" $ \x y z ->
mergeVertices (== x) y z == replaceVertex x y z
test "mergeVertices even 1 (0 * 2) == 1 * 1" $
mergeVertices even 1 (0 * 2) == 1 * 1
test "mergeVertices odd 1 (3 + 4 * 5) == 4 * 1" $
mergeVertices odd 1 (3 + 4 * 5) == 4 * 1
testTranspose :: TestsuiteInt g -> IO ()
testTranspose (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "transpose ============"
test "transpose empty == empty" $
transpose empty == empty
test "transpose (vertex x) == vertex x" $ \x ->
transpose (vertex x) == vertex x
test "transpose (edge x y) == edge y x" $ \x y ->
transpose (edge x y) == edge y x
test "transpose . transpose == id" $ size10 $ \x ->
(transpose . transpose) x == id x
test "edgeList . transpose == sort . map swap . edgeList" $ \x ->
(edgeList . transpose) x == (sort . map swap . edgeList) x
testGmap :: TestsuiteInt g -> IO ()
testGmap (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "gmap ============"
test "gmap f empty == empty" $ \(apply -> f) ->
gmap f empty == empty
test "gmap f (vertex x) == vertex (f x)" $ \(apply -> f) x ->
gmap f (vertex x) == vertex (f x)
test "gmap f (edge x y) == edge (f x) (f y)" $ \(apply -> f) x y ->
gmap f (edge x y) == edge (f x) (f y)
test "gmap id == id" $ \x ->
gmap id x == id x
test "gmap f . gmap g == gmap (f . g)" $ \(apply -> f :: Int -> Int) (apply -> g :: Int -> Int) x ->
(gmap f . gmap g) x == gmap (f . g) x
testInduce :: TestsuiteInt g -> IO ()
testInduce (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "induce ============"
test "induce (const True ) x == x" $ \x ->
induce (const True ) x == x
test "induce (const False) x == empty" $ \x ->
induce (const False) x == empty
test "induce (/= x) == removeVertex x" $ \x y ->
induce (/= x) y == removeVertex x y
test "induce p . induce q == induce (\\x -> p x && q x)" $ \(apply -> p) (apply -> q) y ->
(induce p . induce q) y == induce (\x -> p x && q x) y
test "isSubgraphOf (induce p x) x == True" $ \(apply -> p) x ->
isSubgraphOf (induce p x) x == True
testInduceJust :: Testsuite g Ord -> IO ()
testInduceJust (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "induceJust ============"
test "induceJust (vertex Nothing) == empty" $
induceJust (vertex (Nothing :: Maybe Int)) == empty
test "induceJust (edge (Just x) Nothing) == vertex x" $ \x ->
induceJust (edge (Just x) (Nothing :: Maybe Int)) == vertex x
test "induceJust . gmap Just == id" $ \(x :: g Int) ->
(induceJust . gmap Just) x == id x
test "induceJust . gmap (\\x -> if p x then Just x else Nothing) == induce p" $ \(x :: g Int) (apply -> p) ->
(induceJust . gmap (\x -> if p x then Just x else Nothing)) x == induce p x
testCompose :: TestsuiteInt g -> IO ()
testCompose (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "compose ============"
test "compose empty x == empty" $ \x ->
compose empty x == empty
test "compose x empty == empty" $ \x ->
compose x empty == empty
test "compose (vertex x) y == empty" $ \x y ->
compose (vertex x) y == empty
test "compose x (vertex y) == empty" $ \x y ->
compose x (vertex y) == empty
test "compose x (compose y z) == compose (compose x y) z" $ size10 $ \x y z ->
compose x (compose y z) == compose (compose x y) z
test "compose x (overlay y z) == overlay (compose x y) (compose x z)" $ size10 $ \x y z ->
compose x (overlay y z) == overlay (compose x y) (compose x z)
test "compose (overlay x y) z == overlay (compose x z) (compose y z)" $ size10 $ \x y z ->
compose (overlay x y) z == overlay (compose x z) (compose y z)
test "compose (edge x y) (edge y z) == edge x z" $ \x y z ->
compose (edge x y) (edge y z) == edge x z
test "compose (path [1..5]) (path [1..5]) == edges [(1,3),(2,4),(3,5)]" $
compose (path [1..5]) (path [1..5]) == edges [(1,3),(2,4),(3,5)]
test "compose (circuit [1..5]) (circuit [1..5]) == circuit [1,3,5,2,4]" $
compose (circuit [1..5]) (circuit [1..5]) == circuit [1,3,5,2,4]
testClosure :: TestsuiteInt g -> IO ()
testClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "closure ============"
test "closure empty == empty" $
closure empty == empty
test "closure (vertex x) == edge x x" $ \x ->
closure (vertex x) == edge x x
test "closure (edge x x) == edge x x" $ \x ->
closure (edge x x) == edge x x
test "closure (edge x y) == edges [(x,x), (x,y), (y,y)]" $ \x y ->
closure (edge x y) == edges [(x,x), (x,y), (y,y)]
test "closure (path $ nub xs) == reflexiveClosure (clique $ nub xs)" $ \xs ->
closure (path $ nubOrd xs) == reflexiveClosure (clique $ nubOrd xs)
test "closure == reflexiveClosure . transitiveClosure" $ size10 $ \x ->
closure x == (reflexiveClosure . transitiveClosure) x
test "closure == transitiveClosure . reflexiveClosure" $ size10 $ \x ->
closure x == (transitiveClosure . reflexiveClosure) x
test "closure . closure == closure" $ size10 $ \x ->
(closure . closure) x == closure x
test "postSet x (closure y) == Set.fromList (reachable y x)" $ size10 $ \x y ->
postSet x (closure y) == Set.fromList (reachable y x)
testReflexiveClosure :: TestsuiteInt g -> IO ()
testReflexiveClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "reflexiveClosure ============"
test "reflexiveClosure empty == empty" $
reflexiveClosure empty == empty
test "reflexiveClosure (vertex x) == edge x x" $ \x ->
reflexiveClosure (vertex x) == edge x x
test "reflexiveClosure (edge x x) == edge x x" $ \x ->
reflexiveClosure (edge x x) == edge x x
test "reflexiveClosure (edge x y) == edges [(x,x), (x,y), (y,y)]" $ \x y ->
reflexiveClosure (edge x y) == edges [(x,x), (x,y), (y,y)]
test "reflexiveClosure . reflexiveClosure == reflexiveClosure" $ \x ->
(reflexiveClosure . reflexiveClosure) x == reflexiveClosure x
testSymmetricClosure :: TestsuiteInt g -> IO ()
testSymmetricClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "symmetricClosure ============"
test "symmetricClosure empty == empty" $
symmetricClosure empty == empty
test "symmetricClosure (vertex x) == vertex x" $ \x ->
symmetricClosure (vertex x) == vertex x
test "symmetricClosure (edge x y) == edges [(x,y), (y,x)]" $ \x y ->
symmetricClosure (edge x y) == edges [(x,y), (y,x)]
test "symmetricClosure x == overlay x (transpose x)" $ \x ->
symmetricClosure x == overlay x (transpose x)
test "symmetricClosure . symmetricClosure == symmetricClosure" $ \x ->
(symmetricClosure . symmetricClosure) x == symmetricClosure x
testTransitiveClosure :: TestsuiteInt g -> IO ()
testTransitiveClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "transitiveClosure ============"
test "transitiveClosure empty == empty" $
transitiveClosure empty == empty
test "transitiveClosure (vertex x) == vertex x" $ \x ->
transitiveClosure (vertex x) == vertex x
test "transitiveClosure (edge x y) == edge x y" $ \x y ->
transitiveClosure (edge x y) == edge x y
test "transitiveClosure (path $ nub xs) == clique (nub $ xs)" $ \xs ->
transitiveClosure (path $ nubOrd xs) == clique (nubOrd xs)
test "transitiveClosure . transitiveClosure == transitiveClosure" $ size10 $ \x ->
(transitiveClosure . transitiveClosure) x == transitiveClosure x
testSplitVertex :: TestsuiteInt g -> IO ()
testSplitVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "splitVertex ============"
test "splitVertex x [] == removeVertex x" $ \x y ->
splitVertex x [] y == removeVertex x y
test "splitVertex x [x] == id" $ \x y ->
splitVertex x [x] y == id y
test "splitVertex x [y] == replaceVertex x y" $ \x y z ->
splitVertex x [y] z == replaceVertex x y z
test "splitVertex 1 [0, 1] $ 1 * (2 + 3) == (0 + 1) * (2 + 3)" $
splitVertex 1 [0, 1] (1 * (2 + 3)) == (0 + 1) * (2 + 3)
testBind :: TestsuiteInt g -> IO ()
testBind (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "bind ============"
test "bind empty f == empty" $ \(apply -> f) ->
bind empty f == empty
test "bind (vertex x) f == f x" $ \(apply -> f) x ->
bind (vertex x) f == f x
test "bind (edge x y) f == connect (f x) (f y)" $ \(apply -> f) x y ->
bind (edge x y) f == connect (f x) (f y)
test "bind (vertices xs) f == overlays (map f xs)" $ size10 $ \xs (apply -> f) ->
bind (vertices xs) f == overlays (map f xs)
test "bind x (const empty) == empty" $ \x ->
bind x (const empty) == empty
test "bind x vertex == x" $ \x ->
bind x vertex == x
test "bind (bind x f) g == bind x (\\y -> bind (f y) g)" $ size10 $ \x (apply -> f) (apply -> g) ->
bind (bind x f) g == bind x (\y -> bind (f y) g)
testSimplify :: TestsuiteInt g -> IO ()
testSimplify (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "simplify ============"
test "simplify == id" $ \x ->
simplify x == id x
test "size (simplify x) <= size x" $ \x ->
size (simplify x) <= size x
testBfsForest :: TestsuiteInt g -> IO ()
testBfsForest (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "bfsForest ============"
test "forest $ bfsForest (edge 1 2) [0] == empty" $
(forest $ bfsForest (edge 1 2) [0]) == empty
test "forest $ bfsForest (edge 1 2) [1] == edge 1 2" $
(forest $ bfsForest (edge 1 2) [1]) == edge 1 2
test "forest $ bfsForest (edge 1 2) [2] == vertex 2" $
(forest $ bfsForest (edge 1 2) [2]) == vertex 2
test "forest $ bfsForest (edge 1 2) [0,1,2] == vertices [1,2]" $
(forest $ bfsForest (edge 1 2) [0,1,2]) == vertices [1,2]
test "forest $ bfsForest (edge 1 2) [2,1,0] == vertices [1,2]" $
(forest $ bfsForest (edge 1 2) [2,1,0]) == vertices [1,2]
test "forest $ bfsForest (edge 1 1) [1] == vertex 1" $
(forest $ bfsForest (edge 1 1) [1]) == vertex 1
test "isSubgraphOf (forest $ bfsForest x vs) x == True" $ \x vs ->
isSubgraphOf (forest $ bfsForest x vs) x == True
test "bfsForest x (vertexList x) == map (\v -> Node v []) (nub $ vertexList x)" $ \x ->
bfsForest x (vertexList x) == map (\v -> Node v []) (nub $ vertexList x)
test "bfsForest x [] == []" $ \x ->
bfsForest x [] == []
test "bfsForest empty vs == []" $ \vs ->
bfsForest empty vs == []
test "bfsForest (3 * (1 + 4) * (1 + 5)) [1,4] == <correct result>" $
bfsForest (3 * (1 + 4) * (1 + 5)) [1,4] == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 4
, subForest = [] }]
test "forest $ bfsForest (circuit [1..5] + circuit [5,4..1]) [3] == path [3,2,1] + path [3,4,5]" $
(forest $ bfsForest (circuit [1..5] + circuit [5,4..1]) [3])== path [3,2,1] + path [3,4,5]
testBfs :: TestsuiteInt g -> IO ()
testBfs (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "bfs ============"
test "bfs (edge 1 2) [0] == []" $
bfs (edge 1 2) [0] == []
test "bfs (edge 1 2) [1] == [[1], [2]]" $
bfs (edge 1 2) [1] == [[1], [2]]
test "bfs (edge 1 2) [2] == [[2]]" $
bfs (edge 1 2) [2] == [[2]]
test "bfs (edge 1 2) [1,2] == [[1,2]]" $
bfs (edge 1 2) [1,2] == [[1,2]]
test "bfs (edge 1 2) [2,1] == [[2,1]]" $
bfs (edge 1 2) [2,1] == [[2,1]]
test "bfs (edge 1 1) [1] == [[1]]" $
bfs (edge 1 1) [1] == [[1]]
test "bfs empty vs == []" $ \vs ->
bfs empty vs == []
test "bfs x [] == []" $ \x ->
bfs x [] == []
test "bfs (1 * 2 + 3 * 4 + 5 * 6) [1,2] == [[1,2]]" $
bfs (1 * 2 + 3 * 4 + 5 * 6) [1,2] == [[1,2]]
test "bfs (1 * 2 + 3 * 4 + 5 * 6) [1,3] == [[1,3], [2,4]]" $
bfs (1 * 2 + 3 * 4 + 5 * 6) [1,3] == [[1,3], [2,4]]
test "bfs (3 * (1 + 4) * (1 + 5)) [3] == [[3], [1,4,5]]" $
bfs (3 * (1 + 4) * (1 + 5)) [3] == [[3], [1,4,5]]
test "bfs (circuit [1..5] + circuit [5,4..1]) [2] == [[2], [1,3], [5,4]]" $
bfs (circuit [1..5] + circuit [5,4..1]) [2] == [[2], [1,3], [5,4]]
test "concat $ bfs (circuit [1..5] + circuit [5,4..1]) [3] == [3,2,4,1,5]" $
(concat $ bfs (circuit [1..5] + circuit [5,4..1]) [3])== [3,2,4,1,5]
test "map concat . transpose . map levels . bfsForest x == bfs x" $ \x vs ->
(map concat . List.transpose . map levels . bfsForest x) vs == bfs x vs
testDfsForest :: TestsuiteInt g -> IO ()
testDfsForest (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfsForest ============"
test "forest $ dfsForest empty == empty" $
(forest $ dfsForest empty) == empty
test "forest $ dfsForest (edge 1 1) == vertex 1" $
(forest $ dfsForest (edge 1 1)) == vertex 1
test "forest $ dfsForest (edge 1 2) == edge 1 2" $
(forest $ dfsForest (edge 1 2)) == edge 1 2
test "forest $ dfsForest (edge 2 1) == vertices [1,2]" $
(forest $ dfsForest (edge 2 1)) == vertices [1,2]
test "isSubgraphOf (forest $ dfsForest x) x == True" $ \x ->
isSubgraphOf (forest $ dfsForest x) x == True
test "isDfsForestOf (dfsForest x) x == True" $ \x ->
isDfsForestOf (dfsForest x) x == True
test "dfsForest . forest . dfsForest == dfsForest" $ \x ->
(dfsForest . forest . dfsForest) x == dfsForest x
test "dfsForest (vertices vs) == map (\\v -> Node v []) (nub $ sort vs)" $ \vs ->
dfsForest (vertices vs) == map (\v -> Node v []) (nub $ sort vs)
test "dfsForest $ 3 * (1 + 4) * (1 + 5) == <correct result>" $
(dfsForest $ 3 * (1 + 4) * (1 + 5)) == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 3
, subForest = [ Node { rootLabel = 4
, subForest = [] }]}]
test "forest (dfsForest $ circuit [1..5] + circuit [5,4..1]) == path [1,2,3,4,5]" $
forest (dfsForest $ circuit [1..5] + circuit [5,4..1]) == path [1,2,3,4,5]
testDfsForestFrom :: TestsuiteInt g -> IO ()
testDfsForestFrom (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfsForestFrom ============"
test "forest $ dfsForestFrom empty vs == empty" $ \vs ->
(forest $ dfsForestFrom empty vs) == empty
test "forest $ dfsForestFrom (edge 1 1) [1] == vertex 1" $
(forest $ dfsForestFrom (edge 1 1) [1]) == vertex 1
test "forest $ dfsForestFrom (edge 1 2) [0] == empty" $
(forest $ dfsForestFrom (edge 1 2) [0]) == empty
test "forest $ dfsForestFrom (edge 1 2) [1] == edge 1 2" $
(forest $ dfsForestFrom (edge 1 2) [1]) == edge 1 2
test "forest $ dfsForestFrom (edge 1 2) [2] == vertex 2" $
(forest $ dfsForestFrom (edge 1 2) [2]) == vertex 2
test "forest $ dfsForestFrom (edge 1 2) [1,2] == edge 1 2" $
(forest $ dfsForestFrom (edge 1 2) [1,2]) == edge 1 2
test "forest $ dfsForestFrom (edge 1 2) [2,1] == vertices [1,2]" $
(forest $ dfsForestFrom (edge 1 2) [2,1]) == vertices [1,2]
test "isSubgraphOf (forest $ dfsForestFrom x vs) x == True" $ \x vs ->
isSubgraphOf (forest $ dfsForestFrom x vs) x == True
test "isDfsForestOf (dfsForestFrom x (vertexList x)) x == True" $ \x ->
isDfsForestOf (dfsForestFrom x (vertexList x)) x == True
test "dfsForestFrom x (vertexList x) == dfsForest x" $ \x ->
dfsForestFrom x (vertexList x) == dfsForest x
test "dfsForestFrom x [] == []" $ \x ->
dfsForestFrom x [] == []
test "dfsForestFrom (3 * (1 + 4) * (1 + 5)) [1,4] == <correct result>" $
dfsForestFrom (3 * (1 + 4) * (1 + 5)) [1,4] == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 4
, subForest = [] }]
test "forest $ dfsForestFrom (circuit [1..5] + circuit [5,4..1]) [3] == path [3,2,1,5,4]" $
(forest $ dfsForestFrom (circuit [1..5] + circuit [5,4..1]) [3])== path [3,2,1,5,4]
testDfs :: TestsuiteInt g -> IO ()
testDfs (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfs ============"
test "dfs empty vs == []" $ \vs ->
dfs empty vs == []
test "dfs (edge 1 1) [1] == [1]" $
dfs (edge 1 1) [1] == [1]
test "dfs (edge 1 2) [0] == []" $
dfs (edge 1 2) [0] == []
test "dfs (edge 1 2) [1] == [1,2]" $
dfs (edge 1 2) [1] == [1,2]
test "dfs (edge 1 2) [2] == [2]" $
dfs (edge 1 2) [2] == [2]
test "dfs (edge 1 2) [1,2] == [1,2]" $
dfs (edge 1 2) [1,2] == [1,2]
test "dfs (edge 1 2) [2,1] == [2,1]" $
dfs (edge 1 2) [2,1] == [2,1]
test "dfs x [] == []" $ \x ->
dfs x [] == []
putStrLn ""
test "and [ hasVertex v x | v <- dfs x vs ] == True" $ \x vs ->
and [ hasVertex v x | v <- dfs x vs ] == True
test "dfs (3 * (1 + 4) * (1 + 5)) [1,4] == [1,5,4]" $
dfs (3 * (1 + 4) * (1 + 5)) [1,4] == [1,5,4]
test "dfs (circuit [1..5] + circuit [5,4..1]) [3] == [3,2,1,5,4]" $
dfs (circuit [1..5] + circuit [5,4..1]) [3] == [3,2,1,5,4]
testReachable :: TestsuiteInt g -> IO ()
testReachable (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfs ============"
test "reachable empty x == []" $ \x ->
reachable empty x == []
test "reachable (vertex 1) 1 == [1]" $
reachable (vertex 1) 1 == [1]
test "reachable (edge 1 1) 1 == [1]" $
reachable (edge 1 1) 1 == [1]
test "reachable (edge 1 2) 0 == []" $
reachable (edge 1 2) 0 == []
test "reachable (edge 1 2) 1 == [1,2]" $
reachable (edge 1 2) 1 == [1,2]
test "reachable (edge 1 2) 2 == [2]" $
reachable (edge 1 2) 2 == [2]
test "reachable (path [1..8] ) 4 == [4..8]" $
reachable (path [1..8] ) 4 == [4..8]
test "reachable (circuit [1..8] ) 4 == [4..8] ++ [1..3]" $
reachable (circuit [1..8] ) 4 == [4..8] ++ [1..3]
test "reachable (clique [8,7..1]) 8 == [8] ++ [1..7]" $
reachable (clique [8,7..1]) 8 == [8] ++ [1..7]
putStrLn ""
test "and [ hasVertex v x | v <- reachable x y ] == True" $ \x y ->
and [ hasVertex v x | v <- reachable x y ] == True
testTopSort :: TestsuiteInt g -> IO ()
testTopSort (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "topSort ============"
test "topSort (1 * 2 + 3 * 1) == Right [3,1,2]" $
topSort (1 * 2 + 3 * 1) == Right [3,1,2]
test "topSort (path [1..5]) == Right [1..5]" $
topSort (path [1..5]) == Right [1..5]
test "topSort (3 * (1 * 4 + 2 * 5)) == Right [3,1,2,4,5]" $
topSort (3 * (1 * 4 + 2 * 5)) == Right [3,1,2,4,5]
test "topSort (1 * 2 + 2 * 1) == Left (2 :| [1])" $
topSort (1 * 2 + 2 * 1) == Left (2 :| [1])
test "topSort (path [5,4..1] + edge 2 4) == Left (4 :| [3,2])" $
topSort (path [5,4..1] + edge 2 4) == Left (4 :| [3,2])
test "topSort (circuit [1..5]) == Left (3 :| [1,2])" $
topSort (circuit [1..3]) == Left (3 :| [1,2])
test "topSort (circuit [1..3] + circuit [3,2,1]) == Left (3 :| [2])" $
topSort (circuit [1..3] + circuit [3,2,1]) == Left (3 :| [2])
test "topSort (1 * 2 + (5 + 2) * 1 + 3 * 4 * 3) == Left (1 :| [2])" $
topSort (1 * 2 + (5 + 2) * 1 + 3 * 4 * 3) == Left (1 :| [2])
test "fmap (flip isTopSortOf x) (topSort x) /= Right False" $ \x ->
fmap (flip isTopSortOf x) (topSort x) /= Right False
test "topSort . vertices == Right . nub . sort" $ \vs ->
(topSort . vertices) vs == (Right . nubOrd . sort) vs
testIsAcyclic :: TestsuiteInt g -> IO ()
testIsAcyclic (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "testIsAcyclic ============"
test "isAcyclic (1 * 2 + 3 * 1) == True" $
isAcyclic (1 * 2 + 3 * 1) == True
test "isAcyclic (1 * 2 + 2 * 1) == False" $
isAcyclic (1 * 2 + 2 * 1) == False
test "isAcyclic . circuit == null" $ \xs ->
(isAcyclic . circuit) xs == null xs
test "isAcyclic == isRight . topSort" $ \x ->
isAcyclic x == isRight (topSort x)
testIsDfsForestOf :: TestsuiteInt g -> IO ()
testIsDfsForestOf (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isDfsForestOf ============"
test "isDfsForestOf [] empty == True" $
isDfsForestOf [] empty == True
test "isDfsForestOf [] (vertex 1) == False" $
isDfsForestOf [] (vertex 1) == False
test "isDfsForestOf [Node 1 []] (vertex 1) == True" $
isDfsForestOf [Node 1 []] (vertex 1) == True
test "isDfsForestOf [Node 1 []] (vertex 2) == False" $
isDfsForestOf [Node 1 []] (vertex 2) == False
test "isDfsForestOf [Node 1 [], Node 1 []] (vertex 1) == False" $
isDfsForestOf [Node 1 [], Node 1 []] (vertex 1) == False
test "isDfsForestOf [Node 1 []] (edge 1 1) == True" $
isDfsForestOf [Node 1 []] (edge 1 1) == True
test "isDfsForestOf [Node 1 []] (edge 1 2) == False" $
isDfsForestOf [Node 1 []] (edge 1 2) == False
test "isDfsForestOf [Node 1 [], Node 2 []] (edge 1 2) == False" $
isDfsForestOf [Node 1 [], Node 2 []] (edge 1 2) == False
test "isDfsForestOf [Node 2 [], Node 1 []] (edge 1 2) == True" $
isDfsForestOf [Node 2 [], Node 1 []] (edge 1 2) == True
test "isDfsForestOf [Node 1 [Node 2 []]] (edge 1 2) == True" $
isDfsForestOf [Node 1 [Node 2 []]] (edge 1 2) == True
test "isDfsForestOf [Node 1 [], Node 2 []] (vertices [1,2]) == True" $
isDfsForestOf [Node 1 [], Node 2 []] (vertices [1,2]) == True
test "isDfsForestOf [Node 2 [], Node 1 []] (vertices [1,2]) == True" $
isDfsForestOf [Node 2 [], Node 1 []] (vertices [1,2]) == True
test "isDfsForestOf [Node 1 [Node 2 []]] (vertices [1,2]) == False" $
isDfsForestOf [Node 1 [Node 2 []]] (vertices [1,2]) == False
test "isDfsForestOf [Node 1 [Node 2 [Node 3 []]]] (path [1,2,3]) == True" $
isDfsForestOf [Node 1 [Node 2 [Node 3 []]]] (path [1,2,3]) == True
test "isDfsForestOf [Node 1 [Node 3 [Node 2 []]]] (path [1,2,3]) == False" $
isDfsForestOf [Node 1 [Node 3 [Node 2 []]]] (path [1,2,3]) == False
test "isDfsForestOf [Node 3 [], Node 1 [Node 2 []]] (path [1,2,3]) == True" $
isDfsForestOf [Node 3 [], Node 1 [Node 2 []]] (path [1,2,3]) == True
test "isDfsForestOf [Node 2 [Node 3 []], Node 1 []] (path [1,2,3]) == True" $
isDfsForestOf [Node 2 [Node 3 []], Node 1 []] (path [1,2,3]) == True
test "isDfsForestOf [Node 1 [], Node 2 [Node 3 []]] (path [1,2,3]) == False" $
isDfsForestOf [Node 1 [], Node 2 [Node 3 []]] (path [1,2,3]) == False
testIsTopSortOf :: TestsuiteInt g -> IO ()
testIsTopSortOf (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isTopSortOf ============"
test "isTopSortOf [3,1,2] (1 * 2 + 3 * 1) == True" $
isTopSortOf [3,1,2] (1 * 2 + 3 * 1) == True
test "isTopSortOf [1,2,3] (1 * 2 + 3 * 1) == False" $
isTopSortOf [1,2,3] (1 * 2 + 3 * 1) == False
test "isTopSortOf [] (1 * 2 + 3 * 1) == False" $
isTopSortOf [] (1 * 2 + 3 * 1) == False
test "isTopSortOf [] empty == True" $
isTopSortOf [] empty == True
test "isTopSortOf [x] (vertex x) == True" $ \x ->
isTopSortOf [x] (vertex x) == True
test "isTopSortOf [x] (edge x x) == False" $ \x ->
isTopSortOf [x] (edge x x) == False
| null | https://raw.githubusercontent.com/snowleopard/alga/32b1dbe8b76aea6b042b1ec4508d67564700186f/test/Algebra/Graph/Test/Generic.hs | haskell | ---------------------------------------------------------------------------
|
Module : Algebra.Graph.Test.Generic
Maintainer :
Stability : experimental
Generic graph API testing.
---------------------------------------------------------------------------
Make sure we hit the precondition
TODO: We currently do not test 'edgeSet'.
TODO: Ouch. Generic tests are becoming awkward. We need a better way. | # LANGUAGE RecordWildCards , ViewPatterns #
Copyright : ( c ) 2016 - 2022
License : MIT ( see the file LICENSE )
module Algebra.Graph.Test.Generic where
import Control.Monad (when)
import Data.Either
import Data.List (nub, sort)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Tree
import Data.Tuple
import qualified Data.List as List
import Algebra.Graph.Test
import Algebra.Graph.Test.API
import qualified Algebra.Graph as G
import qualified Algebra.Graph.AdjacencyMap as AM
import qualified Algebra.Graph.AdjacencyMap.Algorithm as AM
import qualified Algebra.Graph.AdjacencyIntMap as AIM
import qualified Data.Set as Set
import qualified Data.IntSet as IntSet
type ModulePrefix = String
type Testsuite g c = (ModulePrefix, API g c)
type TestsuiteInt g = (ModulePrefix, API g ((~) Int))
testBasicPrimitives :: TestsuiteInt g -> IO ()
testBasicPrimitives = mconcat [ testOrd
, testEmpty
, testVertex
, testEdge
, testOverlay
, testConnect
, testVertices
, testEdges
, testOverlays
, testConnects ]
testSymmetricBasicPrimitives :: TestsuiteInt g -> IO ()
testSymmetricBasicPrimitives = mconcat [ testSymmetricOrd
, testEmpty
, testVertex
, testSymmetricEdge
, testOverlay
, testSymmetricConnect
, testVertices
, testSymmetricEdges
, testOverlays
, testSymmetricConnects ]
testToGraph :: TestsuiteInt g -> IO ()
testToGraph = mconcat [ testToGraphDefault
, testFoldg
, testIsEmpty
, testHasVertex
, testHasEdge
, testVertexCount
, testEdgeCount
, testVertexList
, testVertexSet
, testVertexIntSet
, testEdgeList
, testEdgeSet
, testAdjacencyList
, testPreSet
, testPreIntSet
, testPostSet
, testPostIntSet ]
testSymmetricToGraph :: TestsuiteInt g -> IO ()
testSymmetricToGraph = mconcat [ testSymmetricToGraphDefault
, testIsEmpty
, testHasVertex
, testSymmetricHasEdge
, testVertexCount
, testEdgeCount
, testVertexList
, testVertexSet
, testVertexIntSet
, testSymmetricEdgeList
, testSymmetricEdgeSet
, testSymmetricAdjacencyList
, testNeighbours ]
testRelational :: TestsuiteInt g -> IO ()
testRelational = mconcat [ testCompose
, testClosure
, testReflexiveClosure
, testSymmetricClosure
, testTransitiveClosure ]
testGraphFamilies :: TestsuiteInt g -> IO ()
testGraphFamilies = mconcat [ testPath
, testCircuit
, testClique
, testBiclique
, testStar
, testStars
, testTree
, testForest ]
testSymmetricGraphFamilies :: TestsuiteInt g -> IO ()
testSymmetricGraphFamilies = mconcat [ testSymmetricPath
, testSymmetricCircuit
, testSymmetricClique
, testBiclique
, testStar
, testStars
, testTree
, testForest ]
testTransformations :: TestsuiteInt g -> IO ()
testTransformations = mconcat [ testRemoveVertex
, testRemoveEdge
, testReplaceVertex
, testMergeVertices
, testTranspose
, testGmap
, testInduce ]
testSymmetricTransformations :: TestsuiteInt g -> IO ()
testSymmetricTransformations = mconcat [ testRemoveVertex
, testSymmetricRemoveEdge
, testReplaceVertex
, testMergeVertices
, testGmap
, testInduce ]
testConsistent :: TestsuiteInt g -> IO ()
testConsistent (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "consistent ============"
test "Consistency of the Arbitrary instance" $ \x -> consistent x
putStrLn ""
test "consistent empty == True" $
consistent empty == True
test "consistent (vertex x) == True" $ \x ->
consistent (vertex x) == True
test "consistent (overlay x y) == True" $ \x y ->
consistent (overlay x y) == True
test "consistent (connect x y) == True" $ \x y ->
consistent (connect x y) == True
test "consistent (edge x y) == True" $ \x y ->
consistent (edge x y) == True
test "consistent (edges xs) == True" $ \xs ->
consistent (edges xs) == True
test "consistent (stars xs) == True" $ \xs ->
consistent (stars xs) == True
testShow :: TestsuiteInt g -> IO ()
testShow (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "Show ============"
test "show (empty ) == \"empty\"" $
show (empty ) == "empty"
test "show (1 ) == \"vertex 1\"" $
show (1 `asTypeOf` empty) == "vertex 1"
test "show (1 + 2 ) == \"vertices [1,2]\"" $
show (1 + 2 `asTypeOf` empty) == "vertices [1,2]"
test "show (1 * 2 ) == \"edge 1 2\"" $
show (1 * 2 `asTypeOf` empty) == "edge 1 2"
test "show (1 * 2 * 3) == \"edges [(1,2),(1,3),(2,3)]\"" $
show (1 * 2 * 3 `asTypeOf` empty) == "edges [(1,2),(1,3),(2,3)]"
test "show (1 * 2 + 3) == \"overlay (vertex 3) (edge 1 2)\"" $
show (1 * 2 + 3 `asTypeOf` empty) == "overlay (vertex 3) (edge 1 2)"
putStrLn ""
test "show (vertex (-1) ) == \"vertex (-1)\"" $
show (vertex (-1) ) == "vertex (-1)"
test "show (vertex (-1) + vertex (-2) ) == \"vertices [-2,-1]\"" $
show (vertex (-1) + vertex (-2) ) == "vertices [-2,-1]"
test "show (vertex (-2) * vertex (-1) ) == \"edge (-2) (-1)\"" $
show (vertex (-2) * vertex (-1) ) == "edge (-2) (-1)"
test "show (vertex (-3) * vertex (-2) * vertex (-1)) == \"edges [(-3,-2),(-3,-1),(-2,-1)]\"" $
show (vertex (-3) * vertex (-2) * vertex (-1)) == "edges [(-3,-2),(-3,-1),(-2,-1)]"
test "show (vertex (-3) * vertex (-2) + vertex (-1)) == \"overlay (vertex (-1)) (edge (-3) (-2))\"" $
show (vertex (-3) * vertex (-2) + vertex (-1)) == "overlay (vertex (-1)) (edge (-3) (-2))"
testSymmetricShow :: TestsuiteInt g -> IO ()
testSymmetricShow t@(_, API{..}) = do
testShow t
putStrLn ""
test "show (2 * 1 ) == \"edge 1 2\"" $
show (2 * 1 `asTypeOf` empty) == "edge 1 2"
test "show (1 * 2 * 1) == \"edges [(1,1),(1,2)]\"" $
show (1 * 2 * 1 `asTypeOf` empty) == "edges [(1,1),(1,2)]"
test "show (3 * 2 * 1) == \"edges [(1,2),(1,3),(2,3)]\"" $
show (3 * 2 * 1 `asTypeOf` empty) == "edges [(1,2),(1,3),(2,3)]"
testOrd :: TestsuiteInt g -> IO ()
testOrd (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "Ord ============"
test "vertex 1 < vertex 2" $
vertex 1 < vertex 2
test "vertex 3 < edge 1 2" $
vertex 3 < edge 1 2
test "vertex 1 < edge 1 1" $
vertex 1 < edge 1 1
test "edge 1 1 < edge 1 2" $
edge 1 1 < edge 1 2
test "edge 1 2 < edge 1 1 + edge 2 2" $
edge 1 2 < edge 1 1 + edge 2 2
test "edge 1 2 < edge 1 3" $
edge 1 2 < edge 1 3
test "x <= x + y" $ \x y ->
x <= x + (y `asTypeOf` empty)
test "x + y <= x * y" $ \x y ->
x + y <= x * (y `asTypeOf` empty)
testSymmetricOrd :: TestsuiteInt g -> IO ()
testSymmetricOrd (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "Ord ============"
test "vertex 1 < vertex 2" $
vertex 1 < vertex 2
test "vertex 3 < edge 1 2" $
vertex 3 < edge 1 2
test "vertex 1 < edge 1 1" $
vertex 1 < edge 1 1
test "edge 1 1 < edge 1 2" $
edge 1 1 < edge 1 2
test "edge 1 2 < edge 1 1 + edge 2 2" $
edge 1 2 < edge 1 1 + edge 2 2
test "edge 2 1 < edge 1 3" $
edge 2 1 < edge 1 3
test "edge 1 2 == edge 2 1" $
edge 1 2 == edge 2 1
test "x <= x + y" $ \x y ->
x <= x + (y `asTypeOf` empty)
test "x + y <= x * y" $ \x y ->
x + y <= x * (y `asTypeOf` empty)
testEmpty :: TestsuiteInt g -> IO ()
testEmpty (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "empty ============"
test "isEmpty empty == True" $
isEmpty empty == True
test "hasVertex x empty == False" $ \x ->
hasVertex x empty == False
test "vertexCount empty == 0" $
vertexCount empty == 0
test "edgeCount empty == 0" $
edgeCount empty == 0
testVertex :: TestsuiteInt g -> IO ()
testVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertex ============"
test "isEmpty (vertex x) == False" $ \x ->
isEmpty (vertex x) == False
test "hasVertex x (vertex y) == (x == y)" $ \x y ->
hasVertex x (vertex y) == (x == y)
test "vertexCount (vertex x) == 1" $ \x ->
vertexCount (vertex x) == 1
test "edgeCount (vertex x) == 0" $ \x ->
edgeCount (vertex x) == 0
testEdge :: TestsuiteInt g -> IO ()
testEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edge ============"
test "edge x y == connect (vertex x) (vertex y)" $ \x y ->
edge x y == connect (vertex x) (vertex y)
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "edgeCount (edge x y) == 1" $ \x y ->
edgeCount (edge x y) == 1
test "vertexCount (edge 1 1) == 1" $
vertexCount (edge 1 1) == 1
test "vertexCount (edge 1 2) == 2" $
vertexCount (edge 1 2) == 2
testSymmetricEdge :: TestsuiteInt g -> IO ()
testSymmetricEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edge ============"
test "edge x y == connect (vertex x) (vertex y)" $ \x y ->
edge x y == connect (vertex x) (vertex y)
test "edge x y == edge y x" $ \x y ->
edge x y == edge y x
test "edge x y == edges [(x,y), (y,x)]" $ \x y ->
edge x y == edges [(x,y), (y,x)]
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "edgeCount (edge x y) == 1" $ \x y ->
edgeCount (edge x y) == 1
test "vertexCount (edge 1 1) == 1" $
vertexCount (edge 1 1) == 1
test "vertexCount (edge 1 2) == 2" $
vertexCount (edge 1 2) == 2
testOverlay :: TestsuiteInt g -> IO ()
testOverlay (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "overlay ============"
test "isEmpty (overlay x y) == isEmpty x && isEmpty y" $ \x y ->
isEmpty (overlay x y) ==(isEmpty x && isEmpty y)
test "hasVertex z (overlay x y) == hasVertex z x || hasVertex z y" $ \x y z ->
hasVertex z (overlay x y) ==(hasVertex z x || hasVertex z y)
test "vertexCount (overlay x y) >= vertexCount x" $ \x y ->
vertexCount (overlay x y) >= vertexCount x
test "vertexCount (overlay x y) <= vertexCount x + vertexCount y" $ \x y ->
vertexCount (overlay x y) <= vertexCount x + vertexCount y
test "edgeCount (overlay x y) >= edgeCount x" $ \x y ->
edgeCount (overlay x y) >= edgeCount x
test "edgeCount (overlay x y) <= edgeCount x + edgeCount y" $ \x y ->
edgeCount (overlay x y) <= edgeCount x + edgeCount y
test "vertexCount (overlay 1 2) == 2" $
vertexCount (overlay 1 2) == 2
test "edgeCount (overlay 1 2) == 0" $
edgeCount (overlay 1 2) == 0
testConnect :: TestsuiteInt g -> IO ()
testConnect (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "connect ============"
test "isEmpty (connect x y) == isEmpty x && isEmpty y" $ \x y ->
isEmpty (connect x y) ==(isEmpty x && isEmpty y)
test "hasVertex z (connect x y) == hasVertex z x || hasVertex z y" $ \x y z ->
hasVertex z (connect x y) ==(hasVertex z x || hasVertex z y)
test "vertexCount (connect x y) >= vertexCount x" $ \x y ->
vertexCount (connect x y) >= vertexCount x
test "vertexCount (connect x y) <= vertexCount x + vertexCount y" $ \x y ->
vertexCount (connect x y) <= vertexCount x + vertexCount y
test "edgeCount (connect x y) >= edgeCount x" $ \x y ->
edgeCount (connect x y) >= edgeCount x
test "edgeCount (connect x y) >= edgeCount y" $ \x y ->
edgeCount (connect x y) >= edgeCount y
test "edgeCount (connect x y) >= vertexCount x * vertexCount y" $ \x y ->
edgeCount (connect x y) >= vertexCount x * vertexCount y
test "edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y" $ \x y ->
edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y
test "vertexCount (connect 1 2) == 2" $
vertexCount (connect 1 2) == 2
test "edgeCount (connect 1 2) == 1" $
edgeCount (connect 1 2) == 1
testSymmetricConnect :: TestsuiteInt g -> IO ()
testSymmetricConnect (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "connect ============"
test "connect x y == connect y x" $ \x y ->
connect x y == connect y x
test "isEmpty (connect x y) == isEmpty x && isEmpty y" $ \x y ->
isEmpty (connect x y) ==(isEmpty x && isEmpty y)
test "hasVertex z (connect x y) == hasVertex z x || hasVertex z y" $ \x y z ->
hasVertex z (connect x y) ==(hasVertex z x || hasVertex z y)
test "vertexCount (connect x y) >= vertexCount x" $ \x y ->
vertexCount (connect x y) >= vertexCount x
test "vertexCount (connect x y) <= vertexCount x + vertexCount y" $ \x y ->
vertexCount (connect x y) <= vertexCount x + vertexCount y
test "edgeCount (connect x y) >= edgeCount x" $ \x y ->
edgeCount (connect x y) >= edgeCount x
test "edgeCount (connect x y) >= edgeCount y" $ \x y ->
edgeCount (connect x y) >= edgeCount y
test "edgeCount (connect x y) >= vertexCount x * vertexCount y `div` 2" $ \x y ->
edgeCount (connect x y) >= vertexCount x * vertexCount y `div` 2
test "edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y" $ \x y ->
edgeCount (connect x y) <= vertexCount x * vertexCount y + edgeCount x + edgeCount y
test "vertexCount (connect 1 2) == 2" $
vertexCount (connect 1 2) == 2
test "edgeCount (connect 1 2) == 1" $
edgeCount (connect 1 2) == 1
testVertices :: TestsuiteInt g -> IO ()
testVertices (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertices ============"
test "vertices [] == empty" $
vertices [] == empty
test "vertices [x] == vertex x" $ \x ->
vertices [x] == vertex x
test "vertices == overlays . map vertex" $ \xs ->
vertices xs ==(overlays . map vertex) xs
test "hasVertex x . vertices == elem x" $ \x xs ->
(hasVertex x . vertices) xs == elem x xs
test "vertexCount . vertices == length . nub" $ \xs ->
(vertexCount . vertices) xs == (length . nubOrd) xs
test "vertexSet . vertices == Set.fromList" $ \xs ->
(vertexSet . vertices) xs == Set.fromList xs
testEdges :: TestsuiteInt g -> IO ()
testEdges (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edges ============"
test "edges [] == empty" $
edges [] == empty
test "edges [(x,y)] == edge x y" $ \x y ->
edges [(x,y)] == edge x y
test "edges == overlays . map (uncurry edge)" $ \xs ->
edges xs == (overlays . map (uncurry edge)) xs
test "edgeCount . edges == length . nub" $ \xs ->
(edgeCount . edges) xs == (length . nubOrd) xs
testSymmetricEdges :: TestsuiteInt g -> IO ()
testSymmetricEdges (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edges ============"
test "edges [] == empty" $
edges [] == empty
test "edges [(x,y)] == edge x y" $ \x y ->
edges [(x,y)] == edge x y
test "edges [(x,y), (y,x)] == edge x y" $ \x y ->
edges [(x,y), (y,x)] == edge x y
testOverlays :: TestsuiteInt g -> IO ()
testOverlays (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "overlays ============"
test "overlays [] == empty" $
overlays [] == empty
test "overlays [x] == x" $ \x ->
overlays [x] == x
test "overlays [x,y] == overlay x y" $ \x y ->
overlays [x,y] == overlay x y
test "overlays == foldr overlay empty" $ size10 $ \xs ->
overlays xs == foldr overlay empty xs
test "isEmpty . overlays == all isEmpty" $ size10 $ \xs ->
(isEmpty . overlays) xs == all isEmpty xs
testConnects :: TestsuiteInt g -> IO ()
testConnects (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "connects ============"
test "connects [] == empty" $
connects [] == empty
test "connects [x] == x" $ \x ->
connects [x] == x
test "connects [x,y] == connect x y" $ \x y ->
connects [x,y] == connect x y
test "connects == foldr connect empty" $ size10 $ \xs ->
connects xs == foldr connect empty xs
test "isEmpty . connects == all isEmpty" $ size10 $ \xs ->
(isEmpty . connects) xs == all isEmpty xs
testSymmetricConnects :: TestsuiteInt g -> IO ()
testSymmetricConnects t@(_, API{..}) = do
testConnects t
test "connects == connects . reverse" $ size10 $ \xs ->
connects xs == connects (reverse xs)
testStars :: TestsuiteInt g -> IO ()
testStars (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "stars ============"
test "stars [] == empty" $
stars [] == empty
test "stars [(x, [])] == vertex x" $ \x ->
stars [(x, [])] == vertex x
test "stars [(x, [y])] == edge x y" $ \x y ->
stars [(x, [y])] == edge x y
test "stars [(x, ys)] == star x ys" $ \x ys ->
stars [(x, ys)] == star x ys
test "stars == overlays . map (uncurry star)" $ \xs ->
stars xs == overlays (map (uncurry star) xs)
test "stars . adjacencyList == id" $ \x ->
(stars . adjacencyList) x == id x
test "overlay (stars xs) (stars ys) == stars (xs ++ ys)" $ \xs ys ->
overlay (stars xs) (stars ys) == stars (xs ++ ys)
testFromAdjacencySets :: TestsuiteInt g -> IO ()
testFromAdjacencySets (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "fromAdjacencySets ============"
test "fromAdjacencySets [] == empty" $
fromAdjacencySets [] == empty
test "fromAdjacencySets [(x, Set.empty)] == vertex x" $ \x ->
fromAdjacencySets [(x, Set.empty)] == vertex x
test "fromAdjacencySets [(x, Set.singleton y)] == edge x y" $ \x y ->
fromAdjacencySets [(x, Set.singleton y)] == edge x y
test "fromAdjacencySets . map (fmap Set.fromList) == stars" $ \x ->
(fromAdjacencySets . map (fmap Set.fromList)) x == stars x
test "overlay (fromAdjacencySets xs) (fromAdjacencySets ys) == fromAdjacencySets (xs ++ ys)" $ \xs ys ->
overlay (fromAdjacencySets xs) (fromAdjacencySets ys) == fromAdjacencySets (xs ++ ys)
testFromAdjacencyIntSets :: TestsuiteInt g -> IO ()
testFromAdjacencyIntSets (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "fromAdjacencyIntSets ============"
test "fromAdjacencyIntSets [] == empty" $
fromAdjacencyIntSets [] == empty
test "fromAdjacencyIntSets [(x, IntSet.empty)] == vertex x" $ \x ->
fromAdjacencyIntSets [(x, IntSet.empty)] == vertex x
test "fromAdjacencyIntSets [(x, IntSet.singleton y)] == edge x y" $ \x y ->
fromAdjacencyIntSets [(x, IntSet.singleton y)] == edge x y
test "fromAdjacencyIntSets . map (fmap IntSet.fromList) == stars" $ \x ->
(fromAdjacencyIntSets . map (fmap IntSet.fromList)) x == stars x
test "overlay (fromAdjacencyIntSets xs) (fromAdjacencyIntSets ys) == fromAdjacencyIntSets (xs ++ ys)" $ \xs ys ->
overlay (fromAdjacencyIntSets xs) (fromAdjacencyIntSets ys) == fromAdjacencyIntSets (xs ++ ys)
testIsSubgraphOf :: TestsuiteInt g -> IO ()
testIsSubgraphOf (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isSubgraphOf ============"
test "isSubgraphOf empty x == True" $ \x ->
isSubgraphOf empty x == True
test "isSubgraphOf (vertex x) empty == False" $ \x ->
isSubgraphOf (vertex x) empty == False
test "isSubgraphOf x (overlay x y) == True" $ \x y ->
isSubgraphOf x (overlay x y) == True
test "isSubgraphOf (overlay x y) (connect x y) == True" $ \x y ->
isSubgraphOf (overlay x y) (connect x y) == True
test "isSubgraphOf (path xs) (circuit xs) == True" $ \xs ->
isSubgraphOf (path xs) (circuit xs) == True
test "isSubgraphOf x y ==> x <= y" $ \x z ->
in isSubgraphOf x y ==> x <= y
testSymmetricIsSubgraphOf :: TestsuiteInt g -> IO ()
testSymmetricIsSubgraphOf t@(_, API{..}) = do
testIsSubgraphOf t
test "isSubgraphOf (edge x y) (edge y x) == True" $ \x y ->
isSubgraphOf (edge x y) (edge y x) == True
testToGraphDefault :: TestsuiteInt g -> IO ()
testToGraphDefault (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "toGraph et al. ============"
test "toGraph == foldg Empty Vertex Overlay Connect" $ \x ->
toGraph x == foldg G.Empty G.Vertex G.Overlay G.Connect x
test "foldg == Algebra.Graph.foldg . toGraph" $ \e (apply -> v) (applyFun2 -> o) (applyFun2 -> c) x ->
foldg e v o c x == (G.foldg (e :: Int) v o c . toGraph) x
test "isEmpty == foldg True (const False) (&&) (&&)" $ \x ->
isEmpty x == foldg True (const False) (&&) (&&) x
test "size == foldg 1 (const 1) (+) (+)" $ \x ->
size x == foldg 1 (const 1) (+) (+) x
test "hasVertex x == foldg False (==x) (||) (||)" $ \x y ->
hasVertex x y == foldg False (==x) (||) (||) y
test "hasEdge x y == Algebra.Graph.hasEdge x y . toGraph" $ \x y z ->
hasEdge x y z == (G.hasEdge x y . toGraph) z
test "vertexCount == Set.size . vertexSet" $ \x ->
vertexCount x == (Set.size . vertexSet) x
test "edgeCount == Set.size . edgeSet" $ \x ->
edgeCount x == (Set.size . edgeSet) x
test "vertexList == Set.toAscList . vertexSet" $ \x ->
vertexList x == (Set.toAscList . vertexSet) x
test "edgeList == Set.toAscList . edgeSet" $ \x ->
edgeList x == (Set.toAscList . edgeSet) x
test "vertexSet == foldg Set.empty Set.singleton Set.union Set.union" $ \x ->
vertexSet x == foldg Set.empty Set.singleton Set.union Set.union x
test "vertexIntSet == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union" $ \x ->
vertexIntSet x == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union x
test "edgeSet == Algebra.Graph.AdjacencyMap.edgeSet . foldg empty vertex overlay connect" $ \x ->
edgeSet x == (AM.edgeSet . foldg AM.empty AM.vertex AM.overlay AM.connect) x
test "preSet x == Algebra.Graph.AdjacencyMap.preSet x . toAdjacencyMap" $ \x y ->
preSet x y == (AM.preSet x . toAdjacencyMap) y
test "preIntSet x == Algebra.Graph.AdjacencyIntMap.preIntSet x . toAdjacencyIntMap" $ \x y ->
preIntSet x y == (AIM.preIntSet x . toAdjacencyIntMap) y
test "postSet x == Algebra.Graph.AdjacencyMap.postSet x . toAdjacencyMap" $ \x y ->
postSet x y == (AM.postSet x . toAdjacencyMap) y
test "postIntSet x == Algebra.Graph.AdjacencyIntMap.postIntSet x . toAdjacencyIntMap" $ \x y ->
postIntSet x y == (AIM.postIntSet x . toAdjacencyIntMap) y
test "adjacencyList == Algebra.Graph.AdjacencyMap.adjacencyList . toAdjacencyMap" $ \x ->
adjacencyList x == (AM.adjacencyList . toAdjacencyMap) x
test "adjacencyMap == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMap" $ \x ->
adjacencyMap x == (AM.adjacencyMap . toAdjacencyMap) x
test "adjacencyIntMap == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMap" $ \x ->
adjacencyIntMap x == (AIM.adjacencyIntMap . toAdjacencyIntMap) x
test "adjacencyMapTranspose == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMapTranspose" $ \x ->
adjacencyMapTranspose x == (AM.adjacencyMap . toAdjacencyMapTranspose) x
test "adjacencyIntMapTranspose == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMapTranspose" $ \x ->
adjacencyIntMapTranspose x == (AIM.adjacencyIntMap . toAdjacencyIntMapTranspose) x
test "dfsForest == Algebra.Graph.AdjacencyMap.dfsForest . toAdjacencyMap" $ \x ->
dfsForest x == (AM.dfsForest . toAdjacencyMap) x
test "dfsForestFrom == Algebra.Graph.AdjacencyMap.dfsForestFrom . toAdjacencyMap" $ \x vs ->
dfsForestFrom x vs == (AM.dfsForestFrom . toAdjacencyMap) x vs
test "dfs == Algebra.Graph.AdjacencyMap.dfs . toAdjacencyMap" $ \x vs ->
dfs x vs == (AM.dfs . toAdjacencyMap) x vs
test "reachable == Algebra.Graph.AdjacencyMap.reachable . toAdjacencyMap" $ \x y ->
reachable x y == (AM.reachable . toAdjacencyMap) x y
test "topSort == Algebra.Graph.AdjacencyMap.topSort . toAdjacencyMap" $ \x ->
topSort x == (AM.topSort . toAdjacencyMap) x
test "isAcyclic == Algebra.Graph.AdjacencyMap.isAcyclic . toAdjacencyMap" $ \x ->
isAcyclic x == (AM.isAcyclic . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
test "toAdjacencyMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyMap x == foldg AM.empty AM.vertex AM.overlay AM.connect x
test "toAdjacencyMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyMapTranspose x == foldg AM.empty AM.vertex AM.overlay (flip AM.connect) x
test "toAdjacencyIntMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyIntMap x == foldg AIM.empty AIM.vertex AIM.overlay AIM.connect x
test "toAdjacencyIntMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyIntMapTranspose x == foldg AIM.empty AIM.vertex AIM.overlay (flip AIM.connect) x
test "isDfsForestOf f == Algebra.Graph.AdjacencyMap.isDfsForestOf f . toAdjacencyMap" $ \f x ->
isDfsForestOf f x == (AM.isDfsForestOf f . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
testSymmetricToGraphDefault :: TestsuiteInt g -> IO ()
testSymmetricToGraphDefault (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "toGraph et al. ============"
test "toGraph == foldg Empty Vertex Overlay Connect" $ \x ->
toGraph x == foldg G.Empty G.Vertex G.Overlay G.Connect x
test "foldg == Algebra.Graph.foldg . toGraph" $ \e (apply -> v) (applyFun2 -> o) (applyFun2 -> c) x ->
foldg e v o c x == (G.foldg (e :: Int) v o c . toGraph) x
test "isEmpty == foldg True (const False) (&&) (&&)" $ \x ->
isEmpty x == foldg True (const False) (&&) (&&) x
test "size == foldg 1 (const 1) (+) (+)" $ \x ->
size x == foldg 1 (const 1) (+) (+) x
test "hasVertex x == foldg False (==x) (||) (||)" $ \x y ->
hasVertex x y == foldg False (==x) (||) (||) y
test "hasEdge x y == Algebra.Graph.hasEdge x y . toGraph" $ \x y z ->
hasEdge x y z == (G.hasEdge x y . toGraph) z
test "vertexCount == Set.size . vertexSet" $ \x ->
vertexCount x == (Set.size . vertexSet) x
test "edgeCount == Set.size . edgeSet" $ \x ->
edgeCount x == (Set.size . edgeSet) x
test "vertexList == Set.toAscList . vertexSet" $ \x ->
vertexList x == (Set.toAscList . vertexSet) x
test "edgeList == Set.toAscList . edgeSet" $ \x ->
edgeList x == (Set.toAscList . edgeSet) x
test "vertexSet == foldg Set.empty Set.singleton Set.union Set.union" $ \x ->
vertexSet x == foldg Set.empty Set.singleton Set.union Set.union x
test "vertexIntSet == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union" $ \x ->
vertexIntSet x == foldg IntSet.empty IntSet.singleton IntSet.union IntSet.union x
test "adjacencyList == Algebra.Graph.AdjacencyMap.adjacencyList . toAdjacencyMap" $ \x ->
adjacencyList x == (AM.adjacencyList . toAdjacencyMap) x
test "adjacencyMap == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMap" $ \x ->
adjacencyMap x == (AM.adjacencyMap . toAdjacencyMap) x
test "adjacencyIntMap == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMap" $ \x ->
adjacencyIntMap x == (AIM.adjacencyIntMap . toAdjacencyIntMap) x
test "adjacencyMapTranspose == Algebra.Graph.AdjacencyMap.adjacencyMap . toAdjacencyMapTranspose" $ \x ->
adjacencyMapTranspose x == (AM.adjacencyMap . toAdjacencyMapTranspose) x
test "adjacencyIntMapTranspose == Algebra.Graph.AdjacencyIntMap.adjacencyIntMap . toAdjacencyIntMapTranspose" $ \x ->
adjacencyIntMapTranspose x == (AIM.adjacencyIntMap . toAdjacencyIntMapTranspose) x
test "dfsForest == Algebra.Graph.AdjacencyMap.dfsForest . toAdjacencyMap" $ \x ->
dfsForest x == (AM.dfsForest . toAdjacencyMap) x
test "dfsForestFrom == Algebra.Graph.AdjacencyMap.dfsForestFrom . toAdjacencyMap" $ \x vs ->
dfsForestFrom x vs == (AM.dfsForestFrom . toAdjacencyMap) x vs
test "dfs == Algebra.Graph.AdjacencyMap.dfs . toAdjacencyMap" $ \x vs ->
dfs x vs == (AM.dfs . toAdjacencyMap) x vs
test "reachable == Algebra.Graph.AdjacencyMap.reachable . toAdjacencyMap" $ \x y ->
reachable x y == (AM.reachable . toAdjacencyMap) x y
test "topSort == Algebra.Graph.AdjacencyMap.topSort . toAdjacencyMap" $ \x ->
topSort x == (AM.topSort . toAdjacencyMap) x
test "isAcyclic == Algebra.Graph.AdjacencyMap.isAcyclic . toAdjacencyMap" $ \x ->
isAcyclic x == (AM.isAcyclic . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
test "toAdjacencyMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyMap x == foldg AM.empty AM.vertex AM.overlay AM.connect x
test "toAdjacencyMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyMapTranspose x == foldg AM.empty AM.vertex AM.overlay (flip AM.connect) x
test "toAdjacencyIntMap == foldg empty vertex overlay connect" $ \x ->
toAdjacencyIntMap x == foldg AIM.empty AIM.vertex AIM.overlay AIM.connect x
test "toAdjacencyIntMapTranspose == foldg empty vertex overlay (flip connect)" $ \x ->
toAdjacencyIntMapTranspose x == foldg AIM.empty AIM.vertex AIM.overlay (flip AIM.connect) x
test "isDfsForestOf f == Algebra.Graph.AdjacencyMap.isDfsForestOf f . toAdjacencyMap" $ \f x ->
isDfsForestOf f x == (AM.isDfsForestOf f . toAdjacencyMap) x
test "isTopSortOf vs == Algebra.Graph.AdjacencyMap.isTopSortOf vs . toAdjacencyMap" $ \vs x ->
isTopSortOf vs x == (AM.isTopSortOf vs . toAdjacencyMap) x
testFoldg :: TestsuiteInt g -> IO ()
testFoldg (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "foldg ============"
test "foldg empty vertex overlay connect == id" $ \x ->
foldg empty vertex overlay connect x == id x
test "foldg empty vertex overlay (flip connect) == transpose" $ \x ->
foldg empty vertex overlay (flip connect) x == transpose x
test "foldg 1 (const 1) (+) (+) == size" $ \x ->
foldg 1 (const 1) (+) (+) x == size x
test "foldg True (const False) (&&) (&&) == isEmpty" $ \x ->
foldg True (const False) (&&) (&&) x == isEmpty x
testIsEmpty :: TestsuiteInt g -> IO ()
testIsEmpty (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isEmpty ============"
test "isEmpty empty == True" $
isEmpty empty == True
test "isEmpty (overlay empty empty) == True" $
isEmpty (overlay empty empty) == True
test "isEmpty (vertex x) == False" $ \x ->
isEmpty (vertex x) == False
test "isEmpty (removeVertex x $ vertex x) == True" $ \x ->
isEmpty (removeVertex x $ vertex x) == True
test "isEmpty (removeEdge x y $ edge x y) == False" $ \x y ->
isEmpty (removeEdge x y $ edge x y) == False
testSize :: TestsuiteInt g -> IO ()
testSize (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "size ============"
test "size empty == 1" $
size empty == 1
test "size (vertex x) == 1" $ \x ->
size (vertex x) == 1
test "size (overlay x y) == size x + size y" $ \x y ->
size (overlay x y) == size x + size y
test "size (connect x y) == size x + size y" $ \x y ->
size (connect x y) == size x + size y
test "size x >= 1" $ \x ->
size x >= 1
test "size x >= vertexCount x" $ \x ->
size x >= vertexCount x
testHasVertex :: TestsuiteInt g -> IO ()
testHasVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "hasVertex ============"
test "hasVertex x empty == False" $ \x ->
hasVertex x empty == False
test "hasVertex x (vertex y) == (x == y)" $ \x y ->
hasVertex x (vertex y) == (x == y)
test "hasVertex x . removeVertex x == const False" $ \x y ->
(hasVertex x . removeVertex x) y == const False y
testHasEdge :: TestsuiteInt g -> IO ()
testHasEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "hasEdge ============"
test "hasEdge x y empty == False" $ \x y ->
hasEdge x y empty == False
test "hasEdge x y (vertex z) == False" $ \x y z ->
hasEdge x y (vertex z) == False
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "hasEdge x y . removeEdge x y == const False" $ \x y z ->
(hasEdge x y . removeEdge x y) z == const False z
test "hasEdge x y == elem (x,y) . edgeList" $ \x y z -> do
let es = edgeList z
(x, y) <- elements ((x, y) : es)
return $ hasEdge x y z == elem (x, y) es
testSymmetricHasEdge :: TestsuiteInt g -> IO ()
testSymmetricHasEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "hasEdge ============"
test "hasEdge x y empty == False" $ \x y ->
hasEdge x y empty == False
test "hasEdge x y (vertex z) == False" $ \x y z ->
hasEdge x y (vertex z) == False
test "hasEdge x y (edge x y) == True" $ \x y ->
hasEdge x y (edge x y) == True
test "hasEdge x y (edge y x) == True" $ \x y ->
hasEdge x y (edge y x) == True
test "hasEdge x y . removeEdge x y == const False" $ \x y z ->
(hasEdge x y . removeEdge x y) z == const False z
test "hasEdge x y == elem (min x y, max x y) . edgeList" $ \x y z -> do
(u, v) <- elements ((x, y) : edgeList z)
return $ hasEdge u v z == elem (min u v, max u v) (edgeList z)
testVertexCount :: TestsuiteInt g -> IO ()
testVertexCount (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexCount ============"
test "vertexCount empty == 0" $
vertexCount empty == 0
test "vertexCount (vertex x) == 1" $ \x ->
vertexCount (vertex x) == 1
test "vertexCount == length . vertexList" $ \x ->
vertexCount x == (length . vertexList) x
test "vertexCount x < vertexCount y ==> x < y" $ \x y ->
if vertexCount x < vertexCount y
then property (x < y)
else (vertexCount x > vertexCount y ==> x > y)
testEdgeCount :: TestsuiteInt g -> IO ()
testEdgeCount (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeCount ============"
test "edgeCount empty == 0" $
edgeCount empty == 0
test "edgeCount (vertex x) == 0" $ \x ->
edgeCount (vertex x) == 0
test "edgeCount (edge x y) == 1" $ \x y ->
edgeCount (edge x y) == 1
test "edgeCount == length . edgeList" $ \x ->
edgeCount x == (length . edgeList) x
testVertexList :: TestsuiteInt g -> IO ()
testVertexList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexList ============"
test "vertexList empty == []" $
vertexList empty == []
test "vertexList (vertex x) == [x]" $ \x ->
vertexList (vertex x) == [x]
test "vertexList . vertices == nub . sort" $ \xs ->
(vertexList . vertices) xs == (nubOrd . sort) xs
testEdgeList :: TestsuiteInt g -> IO ()
testEdgeList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeList ============"
test "edgeList empty == []" $
edgeList empty == []
test "edgeList (vertex x) == []" $ \x ->
edgeList (vertex x) == []
test "edgeList (edge x y) == [(x,y)]" $ \x y ->
edgeList (edge x y) == [(x,y)]
test "edgeList (star 2 [3,1]) == [(2,1), (2,3)]" $
edgeList (star 2 [3,1]) == [(2,1), (2,3)]
test "edgeList . edges == nub . sort" $ \xs ->
(edgeList . edges) xs == (nubOrd . sort) xs
testSymmetricEdgeList :: TestsuiteInt g -> IO ()
testSymmetricEdgeList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeList ============"
test "edgeList empty == []" $
edgeList empty == []
test "edgeList (vertex x) == []" $ \x ->
edgeList (vertex x) == []
test "edgeList (edge x y) == [(min x y, max y x)]" $ \x y ->
edgeList (edge x y) == [(min x y, max y x)]
test "edgeList (star 2 [3,1]) == [(1,2), (2,3)]" $
edgeList (star 2 [3,1]) == [(1,2), (2,3)]
testAdjacencyList :: TestsuiteInt g -> IO ()
testAdjacencyList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "adjacencyList ============"
test "adjacencyList empty == []" $
adjacencyList empty == []
test "adjacencyList (vertex x) == [(x, [])]" $ \x ->
adjacencyList (vertex x) == [(x, [])]
test "adjacencyList (edge 1 2) == [(1, [2]), (2, [])]" $
adjacencyList (edge 1 2) == [(1, [2]), (2, [])]
test "adjacencyList (star 2 [3,1]) == [(1, []), (2, [1,3]), (3, [])]" $
adjacencyList (star 2 [3,1]) == [(1, []), (2, [1,3]), (3, [])]
testSymmetricAdjacencyList :: TestsuiteInt g -> IO ()
testSymmetricAdjacencyList (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "adjacencyList ============"
test "adjacencyList empty == []" $
adjacencyList empty == []
test "adjacencyList (vertex x) == [(x, [])]" $ \x ->
adjacencyList (vertex x) == [(x, [])]
test "adjacencyList (edge 1 2) == [(1, [2]), (2, [1])]" $
adjacencyList (edge 1 2) == [(1, [2]), (2, [1])]
test "adjacencyList (star 2 [3,1]) == [(1, [2]), (2, [1,3]), (3, [2])]" $
adjacencyList (star 2 [3,1]) == [(1, [2]), (2, [1,3]), (3, [2])]
testVertexSet :: TestsuiteInt g -> IO ()
testVertexSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexSet ============"
test "vertexSet empty == Set.empty" $
vertexSet empty == Set.empty
test "vertexSet . vertex == Set.singleton" $ \x ->
(vertexSet . vertex) x == Set.singleton x
test "vertexSet . vertices == Set.fromList" $ \xs ->
(vertexSet . vertices) xs == Set.fromList xs
testVertexIntSet :: TestsuiteInt g -> IO ()
testVertexIntSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "vertexIntSet ============"
test "vertexIntSet empty == IntSet.empty" $
vertexIntSet empty == IntSet.empty
test "vertexIntSet . vertex == IntSet.singleton" $ \x ->
(vertexIntSet . vertex) x == IntSet.singleton x
test "vertexIntSet . vertices == IntSet.fromList" $ \xs ->
(vertexIntSet . vertices) xs == IntSet.fromList xs
test "vertexIntSet . clique == IntSet.fromList" $ \xs ->
(vertexIntSet . clique) xs == IntSet.fromList xs
testEdgeSet :: TestsuiteInt g -> IO ()
testEdgeSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeSet ============"
test "edgeSet empty == Set.empty" $
edgeSet empty == Set.empty
test "edgeSet (vertex x) == Set.empty" $ \x ->
edgeSet (vertex x) == Set.empty
test "edgeSet (edge x y) == Set.singleton (x,y)" $ \x y ->
edgeSet (edge x y) == Set.singleton (x,y)
test "edgeSet . edges == Set.fromList" $ \xs ->
(edgeSet . edges) xs == Set.fromList xs
testSymmetricEdgeSet :: TestsuiteInt g -> IO ()
testSymmetricEdgeSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "edgeSet ============"
test "edgeSet empty == Set.empty" $
edgeSet empty == Set.empty
test "edgeSet (vertex x) == Set.empty" $ \x ->
edgeSet (vertex x) == Set.empty
test "edgeSet (edge x y) == Set.singleton (min x y, max x y)" $ \x y ->
edgeSet (edge x y) == Set.singleton (min x y, max x y)
testPreSet :: TestsuiteInt g -> IO ()
testPreSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "preSet ============"
test "preSet x empty == Set.empty" $ \x ->
preSet x empty == Set.empty
test "preSet x (vertex x) == Set.empty" $ \x ->
preSet x (vertex x) == Set.empty
test "preSet 1 (edge 1 2) == Set.empty" $
preSet 1 (edge 1 2) == Set.empty
test "preSet y (edge x y) == Set.fromList [x]" $ \x y ->
preSet y (edge x y) == Set.fromList [x]
testPostSet :: TestsuiteInt g -> IO ()
testPostSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "postSet ============"
test "postSet x empty == Set.empty" $ \x ->
postSet x empty == Set.empty
test "postSet x (vertex x) == Set.empty" $ \x ->
postSet x (vertex x) == Set.empty
test "postSet x (edge x y) == Set.fromList [y]" $ \x y ->
postSet x (edge x y) == Set.fromList [y]
test "postSet 2 (edge 1 2) == Set.empty" $
postSet 2 (edge 1 2) == Set.empty
testPreIntSet :: TestsuiteInt g -> IO ()
testPreIntSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "preIntSet ============"
test "preIntSet x empty == IntSet.empty" $ \x ->
preIntSet x empty == IntSet.empty
test "preIntSet x (vertex x) == IntSet.empty" $ \x ->
preIntSet x (vertex x) == IntSet.empty
test "preIntSet 1 (edge 1 2) == IntSet.empty" $
preIntSet 1 (edge 1 2) == IntSet.empty
test "preIntSet y (edge x y) == IntSet.fromList [x]" $ \x y ->
preIntSet y (edge x y) == IntSet.fromList [x]
testPostIntSet :: TestsuiteInt g -> IO ()
testPostIntSet (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "postIntSet ============"
test "postIntSet x empty == IntSet.empty" $ \x ->
postIntSet x empty == IntSet.empty
test "postIntSet x (vertex x) == IntSet.empty" $ \x ->
postIntSet x (vertex x) == IntSet.empty
test "postIntSet 2 (edge 1 2) == IntSet.empty" $
postIntSet 2 (edge 1 2) == IntSet.empty
test "postIntSet x (edge x y) == IntSet.fromList [y]" $ \x y ->
postIntSet x (edge x y) == IntSet.fromList [y]
testNeighbours :: TestsuiteInt g -> IO ()
testNeighbours (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "neighbours ============"
test "neighbours x empty == Set.empty" $ \x ->
neighbours x empty == Set.empty
test "neighbours x (vertex x) == Set.empty" $ \x ->
neighbours x (vertex x) == Set.empty
test "neighbours x (edge x y) == Set.fromList [y]" $ \x y ->
neighbours x (edge x y) == Set.fromList [y]
test "neighbours y (edge x y) == Set.fromList [x]" $ \x y ->
neighbours y (edge x y) == Set.fromList [x]
testPath :: TestsuiteInt g -> IO ()
testPath (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "path ============"
test "path [] == empty" $
path [] == empty
test "path [x] == vertex x" $ \x ->
path [x] == vertex x
test "path [x,y] == edge x y" $ \x y ->
path [x,y] == edge x y
testSymmetricPath :: TestsuiteInt g -> IO ()
testSymmetricPath t@(_, API{..}) = do
testPath t
test "path == path . reverse" $ \xs ->
path xs ==(path . reverse) xs
testCircuit :: TestsuiteInt g -> IO ()
testCircuit (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "circuit ============"
test "circuit [] == empty" $
circuit [] == empty
test "circuit [x] == edge x x" $ \x ->
circuit [x] == edge x x
test "circuit [x,y] == edges [(x,y), (y,x)]" $ \x y ->
circuit [x,y] == edges [(x,y), (y,x)]
testSymmetricCircuit :: TestsuiteInt g -> IO ()
testSymmetricCircuit t@(_, API{..}) = do
testCircuit t
test "circuit == circuit . reverse" $ \xs ->
circuit xs ==(circuit . reverse) xs
testClique :: TestsuiteInt g -> IO ()
testClique (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "clique ============"
test "clique [] == empty" $
clique [] == empty
test "clique [x] == vertex x" $ \x ->
clique [x] == vertex x
test "clique [x,y] == edge x y" $ \x y ->
clique [x,y] == edge x y
test "clique [x,y,z] == edges [(x,y), (x,z), (y,z)]" $ \x y z ->
clique [x,y,z] == edges [(x,y), (x,z), (y,z)]
test "clique (xs ++ ys) == connect (clique xs) (clique ys)" $ \xs ys ->
clique (xs ++ ys) == connect (clique xs) (clique ys)
testSymmetricClique :: TestsuiteInt g -> IO ()
testSymmetricClique t@(_, API{..}) = do
testClique t
test "clique == clique . reverse" $ \xs->
clique xs ==(clique . reverse) xs
testBiclique :: TestsuiteInt g -> IO ()
testBiclique (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "biclique ============"
test "biclique [] [] == empty" $
biclique [] [] == empty
test "biclique [x] [] == vertex x" $ \x ->
biclique [x] [] == vertex x
test "biclique [] [y] == vertex y" $ \y ->
biclique [] [y] == vertex y
test "biclique [x1,x2] [y1,y2] == edges [(x1,y1), (x1,y2), (x2,y1), (x2,y2)]" $ \x1 x2 y1 y2 ->
biclique [x1,x2] [y1,y2] == edges [(x1,y1), (x1,y2), (x2,y1), (x2,y2)]
test "biclique xs ys == connect (vertices xs) (vertices ys)" $ \xs ys ->
biclique xs ys == connect (vertices xs) (vertices ys)
testStar :: TestsuiteInt g -> IO ()
testStar (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "star ============"
test "star x [] == vertex x" $ \x ->
star x [] == vertex x
test "star x [y] == edge x y" $ \x y ->
star x [y] == edge x y
test "star x [y,z] == edges [(x,y), (x,z)]" $ \x y z ->
star x [y,z] == edges [(x,y), (x,z)]
test "star x ys == connect (vertex x) (vertices ys)" $ \x ys ->
star x ys == connect (vertex x) (vertices ys)
testTree :: TestsuiteInt g -> IO ()
testTree (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "tree ============"
test "tree (Node x []) == vertex x" $ \x ->
tree (Node x []) == vertex x
test "tree (Node x [Node y [Node z []]]) == path [x,y,z]" $ \x y z ->
tree (Node x [Node y [Node z []]]) == path [x,y,z]
test "tree (Node x [Node y [], Node z []]) == star x [y,z]" $ \x y z ->
tree (Node x [Node y [], Node z []]) == star x [y,z]
test "tree (Node 1 [Node 2 [], Node 3 [Node 4 [], Node 5 []]]) == edges [(1,2), (1,3), (3,4), (3,5)]" $
tree (Node 1 [Node 2 [], Node 3 [Node 4 [], Node 5 []]]) == edges [(1,2), (1,3), (3,4), (3,5)]
testForest :: TestsuiteInt g -> IO ()
testForest (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "forest ============"
test "forest [] == empty" $
forest [] == empty
test "forest [x] == tree x" $ \x ->
forest [x] == tree x
test "forest [Node 1 [Node 2 [], Node 3 []], Node 4 [Node 5 []]] == edges [(1,2), (1,3), (4,5)]" $
forest [Node 1 [Node 2 [], Node 3 []], Node 4 [Node 5 []]] == edges [(1,2), (1,3), (4,5)]
test "forest == overlays . map tree" $ \x ->
forest x ==(overlays . map tree) x
testMesh :: Testsuite g Ord -> IO ()
testMesh (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "mesh ============"
test "mesh xs [] == empty" $ \(xs :: [Int]) ->
mesh xs ([] :: [Int]) == empty
test "mesh [] ys == empty" $ \(ys :: [Int]) ->
mesh ([] :: [Int]) ys == empty
test "mesh [x] [y] == vertex (x, y)" $ \(x :: Int) (y :: Int) ->
mesh [x] [y] == vertex (x, y)
test "mesh xs ys == box (path xs) (path ys)" $ \(xs :: [Int]) (ys :: [Int]) ->
mesh xs ys == box (path xs) (path ys)
test "mesh [1..3] \"ab\" == <correct result>" $
mesh [1..3] "ab" == edges [ ((1,'a'),(1,'b')), ((1,'a'),(2,'a')), ((1,'b'),(2,'b')), ((2,'a'),(2,'b'))
, ((2,'a'),(3,'a')), ((2,'b'),(3,'b')), ((3,'a'),(3 :: Int,'b')) ]
test "size (mesh xs ys) == max 1 (3 * length xs * length ys - length xs - length ys -1)" $ \(xs :: [Int]) (ys :: [Int]) ->
size (mesh xs ys) == max 1 (3 * length xs * length ys - length xs - length ys -1)
testTorus :: Testsuite g Ord -> IO ()
testTorus (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "torus ============"
test "torus xs [] == empty" $ \(xs :: [Int]) ->
torus xs ([] :: [Int]) == empty
test "torus [] ys == empty" $ \(ys :: [Int]) ->
torus ([] :: [Int]) ys == empty
test "torus [x] [y] == edge (x,y) (x,y)" $ \(x :: Int) (y :: Int) ->
torus [x] [y] == edge (x,y) (x,y)
test "torus xs ys == box (circuit xs) (circuit ys)" $ \(xs :: [Int]) (ys :: [Int]) ->
torus xs ys == box (circuit xs) (circuit ys)
test "torus [1,2] \"ab\" == <correct result>" $
torus [1,2] "ab" == edges [ ((1,'a'),(1,'b')), ((1,'a'),(2,'a')), ((1,'b'),(1,'a')), ((1,'b'),(2,'b'))
, ((2,'a'),(1,'a')), ((2,'a'),(2,'b')), ((2,'b'),(1,'b')), ((2,'b'),(2 :: Int,'a')) ]
test "size (torus xs ys) == max 1 (3 * length xs * length ys)" $ \(xs :: [Int]) (ys :: [Int]) ->
size (torus xs ys) == max 1 (3 * length xs * length ys)
testDeBruijn :: Testsuite g Ord -> IO ()
testDeBruijn (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "deBruijn ============"
test " deBruijn 0 xs == edge [] []" $ \(xs :: [Int]) ->
deBruijn 0 xs == edge [] []
test "n > 0 ==> deBruijn n [] == empty" $ \n ->
n > 0 ==> deBruijn n ([] :: [Int]) == empty
test " deBruijn 1 [0,1] == edges [ ([0],[0]), ([0],[1]), ([1],[0]), ([1],[1]) ]" $
deBruijn 1 [0,1::Int] == edges [ ([0],[0]), ([0],[1]), ([1],[0]), ([1],[1]) ]
test " deBruijn 2 \"0\" == edge \"00\" \"00\"" $
deBruijn 2 "0" == edge "00" "00"
test " deBruijn 2 \"01\" == <correct result>" $
deBruijn 2 "01" == edges [ ("00","00"), ("00","01"), ("01","10"), ("01","11")
, ("10","00"), ("10","01"), ("11","10"), ("11","11") ]
test " transpose (deBruijn n xs) == gmap reverse $ deBruijn n xs" $ mapSize (min 5) $ \(NonNegative n) (xs :: [Int]) ->
transpose (deBruijn n xs) == gmap reverse (deBruijn n xs)
test " vertexCount (deBruijn n xs) == (length $ nub xs)^n" $ mapSize (min 5) $ \(NonNegative n) (xs :: [Int]) ->
vertexCount (deBruijn n xs) == (length $ nubOrd xs)^n
test "n > 0 ==> edgeCount (deBruijn n xs) == (length $ nub xs)^(n + 1)" $ mapSize (min 5) $ \(NonNegative n) (xs :: [Int]) ->
n > 0 ==> edgeCount (deBruijn n xs) == (length $ nubOrd xs)^(n + 1)
testBox :: Testsuite g Ord -> IO ()
testBox (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "box ============"
let unit = gmap $ \(a :: Int, () ) -> a
comm = gmap $ \(a :: Int, b :: Int) -> (b, a)
test "box x y ~~ box y x" $ mapSize (min 10) $ \x y ->
comm (box x y) == box y x
test "box x (overlay y z) == overlay (box x y) (box x z)" $ mapSize (min 10) $ \x y z ->
let _ = x + y + z + vertex (0 :: Int) in
box x (overlay y z) == overlay (box x y) (box x z)
test "box x (vertex ()) ~~ x" $ mapSize (min 10) $ \x ->
unit(box x (vertex ())) == (x `asTypeOf` empty)
test "box x empty ~~ empty" $ mapSize (min 10) $ \x ->
unit(box x empty) == empty
let assoc = gmap $ \(a :: Int, (b :: Int, c :: Int)) -> ((a, b), c)
test "box x (box y z) ~~ box (box x y) z" $ mapSize (min 10) $ \x y z ->
assoc (box x (box y z)) == box (box x y) z
test "transpose (box x y) == box (transpose x) (transpose y)" $ mapSize (min 10) $ \x y ->
let _ = x + y + vertex (0 :: Int) in
transpose (box x y) == box (transpose x) (transpose y)
test "vertexCount (box x y) == vertexCount x * vertexCount y" $ mapSize (min 10) $ \x y ->
let _ = x + y + vertex (0 :: Int) in
vertexCount (box x y) == vertexCount x * vertexCount y
test "edgeCount (box x y) <= vertexCount x * edgeCount y + edgeCount x * vertexCount y" $ mapSize (min 10) $ \x y ->
let _ = x + y + vertex (0 :: Int) in
edgeCount (box x y) <= vertexCount x * edgeCount y + edgeCount x * vertexCount y
testRemoveVertex :: TestsuiteInt g -> IO ()
testRemoveVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "removeVertex ============"
test "removeVertex x (vertex x) == empty" $ \x ->
removeVertex x (vertex x) == empty
test "removeVertex 1 (vertex 2) == vertex 2" $
removeVertex 1 (vertex 2) == vertex 2
test "removeVertex x (edge x x) == empty" $ \x ->
removeVertex x (edge x x) == empty
test "removeVertex 1 (edge 1 2) == vertex 2" $
removeVertex 1 (edge 1 2) == vertex 2
test "removeVertex x . removeVertex x == removeVertex x" $ \x y ->
(removeVertex x . removeVertex x) y == removeVertex x y
testRemoveEdge :: TestsuiteInt g -> IO ()
testRemoveEdge (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "removeEdge ============"
test "removeEdge x y (edge x y) == vertices [x,y]" $ \x y ->
removeEdge x y (edge x y) == vertices [x,y]
test "removeEdge x y . removeEdge x y == removeEdge x y" $ \x y z ->
(removeEdge x y . removeEdge x y) z == removeEdge x y z
test "removeEdge x y . removeVertex x == removeVertex x" $ \x y z ->
(removeEdge x y . removeVertex x) z == removeVertex x z
test "removeEdge 1 1 (1 * 1 * 2 * 2) == 1 * 2 * 2" $
removeEdge 1 1 (1 * 1 * 2 * 2) == 1 * 2 * 2
test "removeEdge 1 2 (1 * 1 * 2 * 2) == 1 * 1 + 2 * 2" $
removeEdge 1 2 (1 * 1 * 2 * 2) == 1 * 1 + 2 * 2
when (prefix == "Fold." || prefix == "Graph.") $ do
test "size (removeEdge x y z) <= 3 * size z" $ \x y z ->
size (removeEdge x y z) <= 3 * size z
testSymmetricRemoveEdge :: TestsuiteInt g -> IO ()
testSymmetricRemoveEdge t@(_, API{..}) = do
testRemoveEdge t
test "removeEdge x y == removeEdge y x" $ \x y z ->
removeEdge x y z == removeEdge y x z
testReplaceVertex :: TestsuiteInt g -> IO ()
testReplaceVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "replaceVertex ============"
test "replaceVertex x x == id" $ \x y ->
replaceVertex x x y == id y
test "replaceVertex x y (vertex x) == vertex y" $ \x y ->
replaceVertex x y (vertex x) == vertex y
test "replaceVertex x y == mergeVertices (== x) y" $ \x y z ->
replaceVertex x y z == mergeVertices (== x) y z
testMergeVertices :: TestsuiteInt g -> IO ()
testMergeVertices (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "mergeVertices ============"
test "mergeVertices (const False) x == id" $ \x y ->
mergeVertices (const False) x y == id y
test "mergeVertices (== x) y == replaceVertex x y" $ \x y z ->
mergeVertices (== x) y z == replaceVertex x y z
test "mergeVertices even 1 (0 * 2) == 1 * 1" $
mergeVertices even 1 (0 * 2) == 1 * 1
test "mergeVertices odd 1 (3 + 4 * 5) == 4 * 1" $
mergeVertices odd 1 (3 + 4 * 5) == 4 * 1
testTranspose :: TestsuiteInt g -> IO ()
testTranspose (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "transpose ============"
test "transpose empty == empty" $
transpose empty == empty
test "transpose (vertex x) == vertex x" $ \x ->
transpose (vertex x) == vertex x
test "transpose (edge x y) == edge y x" $ \x y ->
transpose (edge x y) == edge y x
test "transpose . transpose == id" $ size10 $ \x ->
(transpose . transpose) x == id x
test "edgeList . transpose == sort . map swap . edgeList" $ \x ->
(edgeList . transpose) x == (sort . map swap . edgeList) x
testGmap :: TestsuiteInt g -> IO ()
testGmap (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "gmap ============"
test "gmap f empty == empty" $ \(apply -> f) ->
gmap f empty == empty
test "gmap f (vertex x) == vertex (f x)" $ \(apply -> f) x ->
gmap f (vertex x) == vertex (f x)
test "gmap f (edge x y) == edge (f x) (f y)" $ \(apply -> f) x y ->
gmap f (edge x y) == edge (f x) (f y)
test "gmap id == id" $ \x ->
gmap id x == id x
test "gmap f . gmap g == gmap (f . g)" $ \(apply -> f :: Int -> Int) (apply -> g :: Int -> Int) x ->
(gmap f . gmap g) x == gmap (f . g) x
testInduce :: TestsuiteInt g -> IO ()
testInduce (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "induce ============"
test "induce (const True ) x == x" $ \x ->
induce (const True ) x == x
test "induce (const False) x == empty" $ \x ->
induce (const False) x == empty
test "induce (/= x) == removeVertex x" $ \x y ->
induce (/= x) y == removeVertex x y
test "induce p . induce q == induce (\\x -> p x && q x)" $ \(apply -> p) (apply -> q) y ->
(induce p . induce q) y == induce (\x -> p x && q x) y
test "isSubgraphOf (induce p x) x == True" $ \(apply -> p) x ->
isSubgraphOf (induce p x) x == True
testInduceJust :: Testsuite g Ord -> IO ()
testInduceJust (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "induceJust ============"
test "induceJust (vertex Nothing) == empty" $
induceJust (vertex (Nothing :: Maybe Int)) == empty
test "induceJust (edge (Just x) Nothing) == vertex x" $ \x ->
induceJust (edge (Just x) (Nothing :: Maybe Int)) == vertex x
test "induceJust . gmap Just == id" $ \(x :: g Int) ->
(induceJust . gmap Just) x == id x
test "induceJust . gmap (\\x -> if p x then Just x else Nothing) == induce p" $ \(x :: g Int) (apply -> p) ->
(induceJust . gmap (\x -> if p x then Just x else Nothing)) x == induce p x
testCompose :: TestsuiteInt g -> IO ()
testCompose (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "compose ============"
test "compose empty x == empty" $ \x ->
compose empty x == empty
test "compose x empty == empty" $ \x ->
compose x empty == empty
test "compose (vertex x) y == empty" $ \x y ->
compose (vertex x) y == empty
test "compose x (vertex y) == empty" $ \x y ->
compose x (vertex y) == empty
test "compose x (compose y z) == compose (compose x y) z" $ size10 $ \x y z ->
compose x (compose y z) == compose (compose x y) z
test "compose x (overlay y z) == overlay (compose x y) (compose x z)" $ size10 $ \x y z ->
compose x (overlay y z) == overlay (compose x y) (compose x z)
test "compose (overlay x y) z == overlay (compose x z) (compose y z)" $ size10 $ \x y z ->
compose (overlay x y) z == overlay (compose x z) (compose y z)
test "compose (edge x y) (edge y z) == edge x z" $ \x y z ->
compose (edge x y) (edge y z) == edge x z
test "compose (path [1..5]) (path [1..5]) == edges [(1,3),(2,4),(3,5)]" $
compose (path [1..5]) (path [1..5]) == edges [(1,3),(2,4),(3,5)]
test "compose (circuit [1..5]) (circuit [1..5]) == circuit [1,3,5,2,4]" $
compose (circuit [1..5]) (circuit [1..5]) == circuit [1,3,5,2,4]
testClosure :: TestsuiteInt g -> IO ()
testClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "closure ============"
test "closure empty == empty" $
closure empty == empty
test "closure (vertex x) == edge x x" $ \x ->
closure (vertex x) == edge x x
test "closure (edge x x) == edge x x" $ \x ->
closure (edge x x) == edge x x
test "closure (edge x y) == edges [(x,x), (x,y), (y,y)]" $ \x y ->
closure (edge x y) == edges [(x,x), (x,y), (y,y)]
test "closure (path $ nub xs) == reflexiveClosure (clique $ nub xs)" $ \xs ->
closure (path $ nubOrd xs) == reflexiveClosure (clique $ nubOrd xs)
test "closure == reflexiveClosure . transitiveClosure" $ size10 $ \x ->
closure x == (reflexiveClosure . transitiveClosure) x
test "closure == transitiveClosure . reflexiveClosure" $ size10 $ \x ->
closure x == (transitiveClosure . reflexiveClosure) x
test "closure . closure == closure" $ size10 $ \x ->
(closure . closure) x == closure x
test "postSet x (closure y) == Set.fromList (reachable y x)" $ size10 $ \x y ->
postSet x (closure y) == Set.fromList (reachable y x)
testReflexiveClosure :: TestsuiteInt g -> IO ()
testReflexiveClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "reflexiveClosure ============"
test "reflexiveClosure empty == empty" $
reflexiveClosure empty == empty
test "reflexiveClosure (vertex x) == edge x x" $ \x ->
reflexiveClosure (vertex x) == edge x x
test "reflexiveClosure (edge x x) == edge x x" $ \x ->
reflexiveClosure (edge x x) == edge x x
test "reflexiveClosure (edge x y) == edges [(x,x), (x,y), (y,y)]" $ \x y ->
reflexiveClosure (edge x y) == edges [(x,x), (x,y), (y,y)]
test "reflexiveClosure . reflexiveClosure == reflexiveClosure" $ \x ->
(reflexiveClosure . reflexiveClosure) x == reflexiveClosure x
testSymmetricClosure :: TestsuiteInt g -> IO ()
testSymmetricClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "symmetricClosure ============"
test "symmetricClosure empty == empty" $
symmetricClosure empty == empty
test "symmetricClosure (vertex x) == vertex x" $ \x ->
symmetricClosure (vertex x) == vertex x
test "symmetricClosure (edge x y) == edges [(x,y), (y,x)]" $ \x y ->
symmetricClosure (edge x y) == edges [(x,y), (y,x)]
test "symmetricClosure x == overlay x (transpose x)" $ \x ->
symmetricClosure x == overlay x (transpose x)
test "symmetricClosure . symmetricClosure == symmetricClosure" $ \x ->
(symmetricClosure . symmetricClosure) x == symmetricClosure x
testTransitiveClosure :: TestsuiteInt g -> IO ()
testTransitiveClosure (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "transitiveClosure ============"
test "transitiveClosure empty == empty" $
transitiveClosure empty == empty
test "transitiveClosure (vertex x) == vertex x" $ \x ->
transitiveClosure (vertex x) == vertex x
test "transitiveClosure (edge x y) == edge x y" $ \x y ->
transitiveClosure (edge x y) == edge x y
test "transitiveClosure (path $ nub xs) == clique (nub $ xs)" $ \xs ->
transitiveClosure (path $ nubOrd xs) == clique (nubOrd xs)
test "transitiveClosure . transitiveClosure == transitiveClosure" $ size10 $ \x ->
(transitiveClosure . transitiveClosure) x == transitiveClosure x
testSplitVertex :: TestsuiteInt g -> IO ()
testSplitVertex (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "splitVertex ============"
test "splitVertex x [] == removeVertex x" $ \x y ->
splitVertex x [] y == removeVertex x y
test "splitVertex x [x] == id" $ \x y ->
splitVertex x [x] y == id y
test "splitVertex x [y] == replaceVertex x y" $ \x y z ->
splitVertex x [y] z == replaceVertex x y z
test "splitVertex 1 [0, 1] $ 1 * (2 + 3) == (0 + 1) * (2 + 3)" $
splitVertex 1 [0, 1] (1 * (2 + 3)) == (0 + 1) * (2 + 3)
testBind :: TestsuiteInt g -> IO ()
testBind (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "bind ============"
test "bind empty f == empty" $ \(apply -> f) ->
bind empty f == empty
test "bind (vertex x) f == f x" $ \(apply -> f) x ->
bind (vertex x) f == f x
test "bind (edge x y) f == connect (f x) (f y)" $ \(apply -> f) x y ->
bind (edge x y) f == connect (f x) (f y)
test "bind (vertices xs) f == overlays (map f xs)" $ size10 $ \xs (apply -> f) ->
bind (vertices xs) f == overlays (map f xs)
test "bind x (const empty) == empty" $ \x ->
bind x (const empty) == empty
test "bind x vertex == x" $ \x ->
bind x vertex == x
test "bind (bind x f) g == bind x (\\y -> bind (f y) g)" $ size10 $ \x (apply -> f) (apply -> g) ->
bind (bind x f) g == bind x (\y -> bind (f y) g)
testSimplify :: TestsuiteInt g -> IO ()
testSimplify (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "simplify ============"
test "simplify == id" $ \x ->
simplify x == id x
test "size (simplify x) <= size x" $ \x ->
size (simplify x) <= size x
testBfsForest :: TestsuiteInt g -> IO ()
testBfsForest (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "bfsForest ============"
test "forest $ bfsForest (edge 1 2) [0] == empty" $
(forest $ bfsForest (edge 1 2) [0]) == empty
test "forest $ bfsForest (edge 1 2) [1] == edge 1 2" $
(forest $ bfsForest (edge 1 2) [1]) == edge 1 2
test "forest $ bfsForest (edge 1 2) [2] == vertex 2" $
(forest $ bfsForest (edge 1 2) [2]) == vertex 2
test "forest $ bfsForest (edge 1 2) [0,1,2] == vertices [1,2]" $
(forest $ bfsForest (edge 1 2) [0,1,2]) == vertices [1,2]
test "forest $ bfsForest (edge 1 2) [2,1,0] == vertices [1,2]" $
(forest $ bfsForest (edge 1 2) [2,1,0]) == vertices [1,2]
test "forest $ bfsForest (edge 1 1) [1] == vertex 1" $
(forest $ bfsForest (edge 1 1) [1]) == vertex 1
test "isSubgraphOf (forest $ bfsForest x vs) x == True" $ \x vs ->
isSubgraphOf (forest $ bfsForest x vs) x == True
test "bfsForest x (vertexList x) == map (\v -> Node v []) (nub $ vertexList x)" $ \x ->
bfsForest x (vertexList x) == map (\v -> Node v []) (nub $ vertexList x)
test "bfsForest x [] == []" $ \x ->
bfsForest x [] == []
test "bfsForest empty vs == []" $ \vs ->
bfsForest empty vs == []
test "bfsForest (3 * (1 + 4) * (1 + 5)) [1,4] == <correct result>" $
bfsForest (3 * (1 + 4) * (1 + 5)) [1,4] == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 4
, subForest = [] }]
test "forest $ bfsForest (circuit [1..5] + circuit [5,4..1]) [3] == path [3,2,1] + path [3,4,5]" $
(forest $ bfsForest (circuit [1..5] + circuit [5,4..1]) [3])== path [3,2,1] + path [3,4,5]
testBfs :: TestsuiteInt g -> IO ()
testBfs (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "bfs ============"
test "bfs (edge 1 2) [0] == []" $
bfs (edge 1 2) [0] == []
test "bfs (edge 1 2) [1] == [[1], [2]]" $
bfs (edge 1 2) [1] == [[1], [2]]
test "bfs (edge 1 2) [2] == [[2]]" $
bfs (edge 1 2) [2] == [[2]]
test "bfs (edge 1 2) [1,2] == [[1,2]]" $
bfs (edge 1 2) [1,2] == [[1,2]]
test "bfs (edge 1 2) [2,1] == [[2,1]]" $
bfs (edge 1 2) [2,1] == [[2,1]]
test "bfs (edge 1 1) [1] == [[1]]" $
bfs (edge 1 1) [1] == [[1]]
test "bfs empty vs == []" $ \vs ->
bfs empty vs == []
test "bfs x [] == []" $ \x ->
bfs x [] == []
test "bfs (1 * 2 + 3 * 4 + 5 * 6) [1,2] == [[1,2]]" $
bfs (1 * 2 + 3 * 4 + 5 * 6) [1,2] == [[1,2]]
test "bfs (1 * 2 + 3 * 4 + 5 * 6) [1,3] == [[1,3], [2,4]]" $
bfs (1 * 2 + 3 * 4 + 5 * 6) [1,3] == [[1,3], [2,4]]
test "bfs (3 * (1 + 4) * (1 + 5)) [3] == [[3], [1,4,5]]" $
bfs (3 * (1 + 4) * (1 + 5)) [3] == [[3], [1,4,5]]
test "bfs (circuit [1..5] + circuit [5,4..1]) [2] == [[2], [1,3], [5,4]]" $
bfs (circuit [1..5] + circuit [5,4..1]) [2] == [[2], [1,3], [5,4]]
test "concat $ bfs (circuit [1..5] + circuit [5,4..1]) [3] == [3,2,4,1,5]" $
(concat $ bfs (circuit [1..5] + circuit [5,4..1]) [3])== [3,2,4,1,5]
test "map concat . transpose . map levels . bfsForest x == bfs x" $ \x vs ->
(map concat . List.transpose . map levels . bfsForest x) vs == bfs x vs
testDfsForest :: TestsuiteInt g -> IO ()
testDfsForest (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfsForest ============"
test "forest $ dfsForest empty == empty" $
(forest $ dfsForest empty) == empty
test "forest $ dfsForest (edge 1 1) == vertex 1" $
(forest $ dfsForest (edge 1 1)) == vertex 1
test "forest $ dfsForest (edge 1 2) == edge 1 2" $
(forest $ dfsForest (edge 1 2)) == edge 1 2
test "forest $ dfsForest (edge 2 1) == vertices [1,2]" $
(forest $ dfsForest (edge 2 1)) == vertices [1,2]
test "isSubgraphOf (forest $ dfsForest x) x == True" $ \x ->
isSubgraphOf (forest $ dfsForest x) x == True
test "isDfsForestOf (dfsForest x) x == True" $ \x ->
isDfsForestOf (dfsForest x) x == True
test "dfsForest . forest . dfsForest == dfsForest" $ \x ->
(dfsForest . forest . dfsForest) x == dfsForest x
test "dfsForest (vertices vs) == map (\\v -> Node v []) (nub $ sort vs)" $ \vs ->
dfsForest (vertices vs) == map (\v -> Node v []) (nub $ sort vs)
test "dfsForest $ 3 * (1 + 4) * (1 + 5) == <correct result>" $
(dfsForest $ 3 * (1 + 4) * (1 + 5)) == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 3
, subForest = [ Node { rootLabel = 4
, subForest = [] }]}]
test "forest (dfsForest $ circuit [1..5] + circuit [5,4..1]) == path [1,2,3,4,5]" $
forest (dfsForest $ circuit [1..5] + circuit [5,4..1]) == path [1,2,3,4,5]
testDfsForestFrom :: TestsuiteInt g -> IO ()
testDfsForestFrom (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfsForestFrom ============"
test "forest $ dfsForestFrom empty vs == empty" $ \vs ->
(forest $ dfsForestFrom empty vs) == empty
test "forest $ dfsForestFrom (edge 1 1) [1] == vertex 1" $
(forest $ dfsForestFrom (edge 1 1) [1]) == vertex 1
test "forest $ dfsForestFrom (edge 1 2) [0] == empty" $
(forest $ dfsForestFrom (edge 1 2) [0]) == empty
test "forest $ dfsForestFrom (edge 1 2) [1] == edge 1 2" $
(forest $ dfsForestFrom (edge 1 2) [1]) == edge 1 2
test "forest $ dfsForestFrom (edge 1 2) [2] == vertex 2" $
(forest $ dfsForestFrom (edge 1 2) [2]) == vertex 2
test "forest $ dfsForestFrom (edge 1 2) [1,2] == edge 1 2" $
(forest $ dfsForestFrom (edge 1 2) [1,2]) == edge 1 2
test "forest $ dfsForestFrom (edge 1 2) [2,1] == vertices [1,2]" $
(forest $ dfsForestFrom (edge 1 2) [2,1]) == vertices [1,2]
test "isSubgraphOf (forest $ dfsForestFrom x vs) x == True" $ \x vs ->
isSubgraphOf (forest $ dfsForestFrom x vs) x == True
test "isDfsForestOf (dfsForestFrom x (vertexList x)) x == True" $ \x ->
isDfsForestOf (dfsForestFrom x (vertexList x)) x == True
test "dfsForestFrom x (vertexList x) == dfsForest x" $ \x ->
dfsForestFrom x (vertexList x) == dfsForest x
test "dfsForestFrom x [] == []" $ \x ->
dfsForestFrom x [] == []
test "dfsForestFrom (3 * (1 + 4) * (1 + 5)) [1,4] == <correct result>" $
dfsForestFrom (3 * (1 + 4) * (1 + 5)) [1,4] == [ Node { rootLabel = 1
, subForest = [ Node { rootLabel = 5
, subForest = [] }]}
, Node { rootLabel = 4
, subForest = [] }]
test "forest $ dfsForestFrom (circuit [1..5] + circuit [5,4..1]) [3] == path [3,2,1,5,4]" $
(forest $ dfsForestFrom (circuit [1..5] + circuit [5,4..1]) [3])== path [3,2,1,5,4]
testDfs :: TestsuiteInt g -> IO ()
testDfs (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfs ============"
test "dfs empty vs == []" $ \vs ->
dfs empty vs == []
test "dfs (edge 1 1) [1] == [1]" $
dfs (edge 1 1) [1] == [1]
test "dfs (edge 1 2) [0] == []" $
dfs (edge 1 2) [0] == []
test "dfs (edge 1 2) [1] == [1,2]" $
dfs (edge 1 2) [1] == [1,2]
test "dfs (edge 1 2) [2] == [2]" $
dfs (edge 1 2) [2] == [2]
test "dfs (edge 1 2) [1,2] == [1,2]" $
dfs (edge 1 2) [1,2] == [1,2]
test "dfs (edge 1 2) [2,1] == [2,1]" $
dfs (edge 1 2) [2,1] == [2,1]
test "dfs x [] == []" $ \x ->
dfs x [] == []
putStrLn ""
test "and [ hasVertex v x | v <- dfs x vs ] == True" $ \x vs ->
and [ hasVertex v x | v <- dfs x vs ] == True
test "dfs (3 * (1 + 4) * (1 + 5)) [1,4] == [1,5,4]" $
dfs (3 * (1 + 4) * (1 + 5)) [1,4] == [1,5,4]
test "dfs (circuit [1..5] + circuit [5,4..1]) [3] == [3,2,1,5,4]" $
dfs (circuit [1..5] + circuit [5,4..1]) [3] == [3,2,1,5,4]
testReachable :: TestsuiteInt g -> IO ()
testReachable (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "dfs ============"
test "reachable empty x == []" $ \x ->
reachable empty x == []
test "reachable (vertex 1) 1 == [1]" $
reachable (vertex 1) 1 == [1]
test "reachable (edge 1 1) 1 == [1]" $
reachable (edge 1 1) 1 == [1]
test "reachable (edge 1 2) 0 == []" $
reachable (edge 1 2) 0 == []
test "reachable (edge 1 2) 1 == [1,2]" $
reachable (edge 1 2) 1 == [1,2]
test "reachable (edge 1 2) 2 == [2]" $
reachable (edge 1 2) 2 == [2]
test "reachable (path [1..8] ) 4 == [4..8]" $
reachable (path [1..8] ) 4 == [4..8]
test "reachable (circuit [1..8] ) 4 == [4..8] ++ [1..3]" $
reachable (circuit [1..8] ) 4 == [4..8] ++ [1..3]
test "reachable (clique [8,7..1]) 8 == [8] ++ [1..7]" $
reachable (clique [8,7..1]) 8 == [8] ++ [1..7]
putStrLn ""
test "and [ hasVertex v x | v <- reachable x y ] == True" $ \x y ->
and [ hasVertex v x | v <- reachable x y ] == True
testTopSort :: TestsuiteInt g -> IO ()
testTopSort (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "topSort ============"
test "topSort (1 * 2 + 3 * 1) == Right [3,1,2]" $
topSort (1 * 2 + 3 * 1) == Right [3,1,2]
test "topSort (path [1..5]) == Right [1..5]" $
topSort (path [1..5]) == Right [1..5]
test "topSort (3 * (1 * 4 + 2 * 5)) == Right [3,1,2,4,5]" $
topSort (3 * (1 * 4 + 2 * 5)) == Right [3,1,2,4,5]
test "topSort (1 * 2 + 2 * 1) == Left (2 :| [1])" $
topSort (1 * 2 + 2 * 1) == Left (2 :| [1])
test "topSort (path [5,4..1] + edge 2 4) == Left (4 :| [3,2])" $
topSort (path [5,4..1] + edge 2 4) == Left (4 :| [3,2])
test "topSort (circuit [1..5]) == Left (3 :| [1,2])" $
topSort (circuit [1..3]) == Left (3 :| [1,2])
test "topSort (circuit [1..3] + circuit [3,2,1]) == Left (3 :| [2])" $
topSort (circuit [1..3] + circuit [3,2,1]) == Left (3 :| [2])
test "topSort (1 * 2 + (5 + 2) * 1 + 3 * 4 * 3) == Left (1 :| [2])" $
topSort (1 * 2 + (5 + 2) * 1 + 3 * 4 * 3) == Left (1 :| [2])
test "fmap (flip isTopSortOf x) (topSort x) /= Right False" $ \x ->
fmap (flip isTopSortOf x) (topSort x) /= Right False
test "topSort . vertices == Right . nub . sort" $ \vs ->
(topSort . vertices) vs == (Right . nubOrd . sort) vs
testIsAcyclic :: TestsuiteInt g -> IO ()
testIsAcyclic (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "testIsAcyclic ============"
test "isAcyclic (1 * 2 + 3 * 1) == True" $
isAcyclic (1 * 2 + 3 * 1) == True
test "isAcyclic (1 * 2 + 2 * 1) == False" $
isAcyclic (1 * 2 + 2 * 1) == False
test "isAcyclic . circuit == null" $ \xs ->
(isAcyclic . circuit) xs == null xs
test "isAcyclic == isRight . topSort" $ \x ->
isAcyclic x == isRight (topSort x)
testIsDfsForestOf :: TestsuiteInt g -> IO ()
testIsDfsForestOf (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isDfsForestOf ============"
test "isDfsForestOf [] empty == True" $
isDfsForestOf [] empty == True
test "isDfsForestOf [] (vertex 1) == False" $
isDfsForestOf [] (vertex 1) == False
test "isDfsForestOf [Node 1 []] (vertex 1) == True" $
isDfsForestOf [Node 1 []] (vertex 1) == True
test "isDfsForestOf [Node 1 []] (vertex 2) == False" $
isDfsForestOf [Node 1 []] (vertex 2) == False
test "isDfsForestOf [Node 1 [], Node 1 []] (vertex 1) == False" $
isDfsForestOf [Node 1 [], Node 1 []] (vertex 1) == False
test "isDfsForestOf [Node 1 []] (edge 1 1) == True" $
isDfsForestOf [Node 1 []] (edge 1 1) == True
test "isDfsForestOf [Node 1 []] (edge 1 2) == False" $
isDfsForestOf [Node 1 []] (edge 1 2) == False
test "isDfsForestOf [Node 1 [], Node 2 []] (edge 1 2) == False" $
isDfsForestOf [Node 1 [], Node 2 []] (edge 1 2) == False
test "isDfsForestOf [Node 2 [], Node 1 []] (edge 1 2) == True" $
isDfsForestOf [Node 2 [], Node 1 []] (edge 1 2) == True
test "isDfsForestOf [Node 1 [Node 2 []]] (edge 1 2) == True" $
isDfsForestOf [Node 1 [Node 2 []]] (edge 1 2) == True
test "isDfsForestOf [Node 1 [], Node 2 []] (vertices [1,2]) == True" $
isDfsForestOf [Node 1 [], Node 2 []] (vertices [1,2]) == True
test "isDfsForestOf [Node 2 [], Node 1 []] (vertices [1,2]) == True" $
isDfsForestOf [Node 2 [], Node 1 []] (vertices [1,2]) == True
test "isDfsForestOf [Node 1 [Node 2 []]] (vertices [1,2]) == False" $
isDfsForestOf [Node 1 [Node 2 []]] (vertices [1,2]) == False
test "isDfsForestOf [Node 1 [Node 2 [Node 3 []]]] (path [1,2,3]) == True" $
isDfsForestOf [Node 1 [Node 2 [Node 3 []]]] (path [1,2,3]) == True
test "isDfsForestOf [Node 1 [Node 3 [Node 2 []]]] (path [1,2,3]) == False" $
isDfsForestOf [Node 1 [Node 3 [Node 2 []]]] (path [1,2,3]) == False
test "isDfsForestOf [Node 3 [], Node 1 [Node 2 []]] (path [1,2,3]) == True" $
isDfsForestOf [Node 3 [], Node 1 [Node 2 []]] (path [1,2,3]) == True
test "isDfsForestOf [Node 2 [Node 3 []], Node 1 []] (path [1,2,3]) == True" $
isDfsForestOf [Node 2 [Node 3 []], Node 1 []] (path [1,2,3]) == True
test "isDfsForestOf [Node 1 [], Node 2 [Node 3 []]] (path [1,2,3]) == False" $
isDfsForestOf [Node 1 [], Node 2 [Node 3 []]] (path [1,2,3]) == False
testIsTopSortOf :: TestsuiteInt g -> IO ()
testIsTopSortOf (prefix, API{..}) = do
putStrLn $ "\n============ " ++ prefix ++ "isTopSortOf ============"
test "isTopSortOf [3,1,2] (1 * 2 + 3 * 1) == True" $
isTopSortOf [3,1,2] (1 * 2 + 3 * 1) == True
test "isTopSortOf [1,2,3] (1 * 2 + 3 * 1) == False" $
isTopSortOf [1,2,3] (1 * 2 + 3 * 1) == False
test "isTopSortOf [] (1 * 2 + 3 * 1) == False" $
isTopSortOf [] (1 * 2 + 3 * 1) == False
test "isTopSortOf [] empty == True" $
isTopSortOf [] empty == True
test "isTopSortOf [x] (vertex x) == True" $ \x ->
isTopSortOf [x] (vertex x) == True
test "isTopSortOf [x] (edge x x) == False" $ \x ->
isTopSortOf [x] (edge x x) == False
|
e9cc44a925d6d8f4ad1974c46e4adcdbcadfc2b3683ef21131eea4f2d07c60f1 | KavehYousefi/Esoteric-programming-languages | main.lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; This program implements an interpreter for the esoteric programming
language " Jackass " , presented by the Esolang user " Phase " in the year
2015 , being , while inspired by Urban Mueller 's " brainfuck " , composed
;; of hexadecimal tokens only which apply themselves to the manipulation
;; of a stack.
;;
;;
;; Instructions
;; ============
Jackass 's competence founds upon fifteen instructions reponsible for
;; a global stack's manipulation, each represented by a hexadecimal code
compact of one or more base-16 digits .
;;
;; The instruction set's circumference registers a wide gamut of
;; capabilities:
;;
;; - Pushing and popping stack elements.
;; - Swapping, rotating, and duplicating stack elements.
;; - Basic arithmetics in the form of addition, subtraction,
;; multiplication, division, and remainder computation.
;; - Character-based and numeric input and output facilities.
;; - A goto contruct for steering the control flow.
;;
;; ------------------------------------------------------------------
;; Command | Effect
;; --------+---------------------------------------------------------
;; 01 | Pushes the next hexadecimal token to the top of the
;; | stack.
;; ..................................................................
;; 02 | Pops the top stack element.
;; ..................................................................
03 | Swaps the two top stack elements ' positions .
;; ..................................................................
04 | Rotates the three stack elements , that is , relocates
| the third highest element to the top of the stack , thus
| effectively shifting down the two items previously above
;; | it.
;; ..................................................................
;; 05 | Pops the top stack element and relocates the instruction
| pointer to the instruction at the zero - based position
;; | equal to the deleted element's value.
;; ..................................................................
;; 06 | Pushes a copy of the top stack element unto the top.
;; ..................................................................
;; 07 | Peeks without removing the top stack element a and the
;; | element b previously below it, and pushes the sum
;; | a + b
;; | unto the stack.
;; ..................................................................
;; 08 | Peeks without removing the top stack element a and the
;; | element b previously below it, and pushes the difference
;; | a - b
;; | unto the stack.
;; ..................................................................
;; 09 | Peeks without removing the top stack element a and the
;; | element b previously below it, and pushes the product
;; | a * b
;; | unto the stack.
;; ..................................................................
;; 0a | Peeks without removing the top stack element a and the
;; | element b previously below it, and pushes the
;; | contingently rounded quotient
;; | a / b
;; | unto the stack.
;; ..................................................................
;; 0b | Peeks without removing the top stack element a and the
;; | element b previously below it, and pushes the remainder
;; | r obtained by the division
;; | r = a mod b
;; | unto the stack.
;; ..................................................................
;; 0c | Prints the top stack element as a decimal integer.
;; ..................................................................
;; 0d | Prints the character associated with the top stack
;; | element, construed as an ASCII code.
;; ..................................................................
;; 0e | Queries the user for an unsigned decimal integer and
;; | pushes it unto the stack.
;; ..................................................................
;; 0f | Queries the user for a string and, starting from its
;; | left to its right end, pushes each of its characters'
;; | ASCII codes unto the stack.
;; ------------------------------------------------------------------
;;
;; --------------------------------------------------------------------
;;
Author :
Date : 2022 - 12 - 21
;;
;; Sources:
- > " "
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Declaration of types. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftype list-of (&optional (element-type T))
"The ``list-of'' type defines a list of zero or more elements, each
member of which conforms to the ELEMENT-TYPE, defaulting to the
comprehensive ``T''."
(let ((predicate (gensym)))
(declare (type symbol predicate))
(setf (symbol-function predicate)
#'(lambda (candidate)
(declare (type T candidate))
(and
(listp candidate)
(every
#'(lambda (element)
(declare (type T element))
(typep element element-type))
(the list candidate)))))
`(satisfies ,predicate)))
;;; -------------------------------------------------------
(deftype token ()
"The ``token'' type defines a token as an unsigned non-negative
integer."
'(integer 0 *))
;;; -------------------------------------------------------
(deftype stack ()
"The ``stack'' type defines a last-in first-out collection based upon
a list of signed integer objects."
'(list-of integer))
;;; -------------------------------------------------------
(deftype command ()
"The ``command'' type enumerates the recognized operation types."
'(member
:push-next-value
:pop
:swap
:rotate
:goto
:clone
:add
:subtract
:multiply
:divide
:modulus
:print-number
:print-character
:input-number
:input-string))
;;; -------------------------------------------------------
(deftype jackass-program ()
"The ``jackass-program'' type defines a Jackass program as a vector
of zero or more ``Instruction'' objects."
'(vector Instruction *))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Implementation of character operations. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun whitespace-character-p (candidate)
"Checks whether the CANDIDATE represents a whitespace, returning on
confirmation a ``boolean'' value of ``T'', otherwise ``NIL''."
(declare (type character candidate))
(the boolean
(not (null
(member candidate '(#\Space #\Tab #\Newline #\Return #\Linefeed)
:test #'char=)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-- Implementation of class " " . -- ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass Lexer ()
((source
:initarg :source
:initform (error "Missing lexer source.")
:type string
:documentation "The piece of Jackass source code to analyze.")
(position
:initarg :position
:initform 0
:type fixnum
:documentation "The position into the SOURCE's current CHARACTER.")
(character
:initarg :character
:initform NIL
:type (or null character)
:documentation "The character at the current POSITION into the
SOURCE."))
(:documentation
"The ``Lexer'' class' contribution encompasses the perception and
extraction of significant elements from a piece of Jackass code,
which are returned as a stream of tokens."))
;;; -------------------------------------------------------
(defmethod initialize-instance :after ((lexer Lexer) &key)
(declare (type Lexer lexer))
(with-slots (source position character) lexer
(declare (type string source))
(declare (type fixnum position))
(declare (type (or null character) character))
(setf character
(when (array-in-bounds-p source position)
(char source position))))
(the Lexer lexer))
;;; -------------------------------------------------------
(defun make-lexer (source)
"Creates and returns a new ``Lexer'' which serves to analyze the
SOURCE."
(declare (type string source))
(the Lexer
(make-instance 'Lexer :source source)))
;;; -------------------------------------------------------
(defun lexer-advance (lexer)
"Moves the LEXER's position cursor to the next character in its
source, if possible, updates its internal state, and returns the
modified LEXER."
(declare (type Lexer lexer))
(with-slots (source position character) lexer
(declare (type string source))
(declare (type fixnum position))
(declare (type (or null character) character))
(setf character
(when (array-in-bounds-p source (1+ position))
(char source (incf position)))))
(the Lexer lexer))
;;; -------------------------------------------------------
(defun lexer-skip-whitespaces (lexer)
"Starting at the current position into the LEXER's source, skips a
sequence of zero or more adjacent whitespaces and returns the
modified LEXER."
(declare (type Lexer lexer))
(with-slots (character) lexer
(declare (type (or null character) character))
(loop while (and character (whitespace-character-p character)) do
(lexer-advance lexer)))
(the Lexer lexer))
;;; -------------------------------------------------------
(defun lexer-expect-command-separator (lexer)
"Expects the LEXER's current character to be either a whitespace, in
which case all adjacent instances of the same are skipped, or the end
of the source (EOF), on confirmation returning the contingently
modified LEXER; otherwise signaling an error of an unspecified type."
(declare (type Lexer lexer))
(with-slots (character position) lexer
(declare (type (or null character) character))
(declare (type fixnum position))
(declare (ignorable position))
(cond
((null character)
NIL)
((whitespace-character-p character)
(lexer-skip-whitespaces lexer))
(T
(error "Expected whitespace or end of file, ~
but encountered ~s at position ~d."
character position))))
(the Lexer lexer))
;;; -------------------------------------------------------
(defun lexer-read-hexadecimal-number (lexer)
"Starting at the current position into the LEXER's source, consumes an
unsigned hexadecimal integer, parses the same, and returns its
decimal value as a ``token''."
(declare (type Lexer lexer))
(with-slots (character) lexer
(declare (type (or null character) character))
(the token
(parse-integer
(with-output-to-string (digits)
(declare (type string-stream digits))
(loop while (and character (digit-char-p character 16)) do
(write-char character digits)
(lexer-advance lexer)))
:radix 16))))
;;; -------------------------------------------------------
(defun lexer-get-next-token (lexer)
"Returns the next token from the LEXER.
---
Upon its source's exhaustion, the LEXER responds to each request with
the ``NIL'' value."
(declare (type Lexer lexer))
(with-slots (character position) lexer
(declare (type (or null character) character))
(declare (type fixnum position))
(declare (ignorable position))
(the (or null token)
(cond
((null character)
NIL)
((whitespace-character-p character)
(lexer-skip-whitespaces lexer)
(lexer-get-next-token lexer))
((digit-char-p character 16)
(lexer-read-hexadecimal-number lexer))
(T
(error "Unexpected character ~s at position ~d."
character position))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Implementation of class "Instruction". -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct (Instruction
(:constructor make-instruction (type &optional (operand NIL))))
"The ``Instruction'' class encapsulates the pertinent information for
executing a Jackass operation, including an identifying command type
specifier and an optional argument."
(type (error "Missing instruction type.") :type command)
(operand NIL :type (or null token)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Implementation of parser. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun parse-tokens (lexer)
"Assembles the LEXER's tokens into a one-dimensional simple array of
Jackass instructions, which are subsequently returned."
(declare (type Lexer lexer))
(let ((instructions NIL)
(token (lexer-get-next-token lexer)))
(declare (type list instructions))
(declare (type (or null token) token))
(flet
((advance ()
"Requests the next token from the LEXER, stores it in the
TOKEN, and returns no value."
(setf token (lexer-get-next-token lexer))
(values))
(add-instruction (type &optional (operand NIL))
"Creates a new ``Instruction'' of the specified type,
optionally affiliated with an OPERAND, prepends it to the
INSTRUCTIONS list, and returns no value."
(push (make-instruction type operand) instructions)
(values)))
(loop while token do
(case token
(#x01
(advance)
(if token
(add-instruction :push-next-value token)
(error "Expected a number, but encountered EOF.")))
(#x02
(add-instruction :pop))
(#x03
(add-instruction :swap))
(#x04
(add-instruction :rotate))
(#x05
(add-instruction :goto))
(#x06
(add-instruction :clone))
(#x07
(add-instruction :add))
(#x08
(add-instruction :subtract))
(#x09
(add-instruction :multiply))
(#x0a
(add-instruction :divide))
(#x0b
(add-instruction :modulus))
(#x0c
(add-instruction :print-number))
(#x0d
(add-instruction :print-character))
(#x0e
(add-instruction :input-number))
(#x0f
(add-instruction :input-string))
(otherwise
(error "Invalid command code: ~x." token)))
(advance)))
(the (simple-array Instruction (*))
(coerce (nreverse instructions)
'(simple-array Instruction (*))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Implementation of class "Interpreter". -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass Interpreter ()
((instructions
:initarg :instructions
:initform (error "Missing interpreter instructions.")
:type jackass-program
:documentation "The Jackass instructions to evaluate.")
(ip
:initarg :ip
:initform 0
:type fixnum
:documentation "The instruction pointer (IP), serving as the index
into the INSTRUCTIONS' currently active entry.")
(current-instruction
:initarg :current-instruction
:initform NIL
:type (or null Instruction)
:documentation "The instruction under the instruction pointer (IP)
in the INSTRUCTIONS sequence.")
(stack
:initarg :stack
:initform NIL
:accessor interpreter-stack
:type stack
:documentation "A stack of signed integer numbers."))
(:documentation
"Appropriating the wike of a Jackass program evaluator, the
``Interpreter'' class processes a sequence of instructions,
inducing actual effect into them."))
;;; -------------------------------------------------------
(defmethod initialize-instance :after ((interpreter Interpreter) &key)
(declare (type Interpreter interpreter))
(with-slots (instructions ip current-instruction) interpreter
(declare (type jackass-program instructions))
(declare (type fixnum ip))
(declare (type (or null Instruction) current-instruction))
(setf current-instruction
(when (array-in-bounds-p instructions ip)
(aref instructions ip))))
(the Interpreter interpreter))
;;; -------------------------------------------------------
(defun make-interpreter (instructions)
"Creates and returns a new ``Interpreter'' whose responsibility
assigns it to the evaluation of the Jackass INSTRUCTIONS."
(declare (type jackass-program instructions))
(the Interpreter
(make-instance 'Interpreter :instructions instructions)))
;;; -------------------------------------------------------
(defun interpreter-advance (interpreter)
"Moves the INTERPRETER's instruction pointer to the next instruction,
if possible, updates its internal state, and returns the modified
INTERPRETER."
(declare (type Interpreter interpreter))
(with-slots (instructions ip current-instruction) interpreter
(declare (type jackass-program instructions))
(declare (type fixnum ip))
(declare (type (or null Instruction) current-instruction))
(setf current-instruction
(when (array-in-bounds-p instructions (1+ ip))
(aref instructions (incf ip)))))
(the Interpreter interpreter))
;;; -------------------------------------------------------
(defun interpreter-goto (interpreter target)
"Relocates the INTERPRETER's instruction pointer to the TARGET,
updates its state, and returns the modified INTERPRETER."
(declare (type Interpreter interpreter))
(declare (type fixnum target))
(with-slots (instructions ip current-instruction) interpreter
(declare (type jackass-program instructions))
(declare (type fixnum ip))
(declare (type (or null Instruction) current-instruction))
(setf ip target)
(setf current-instruction
(when (array-in-bounds-p instructions ip)
(aref instructions ip))))
(the Interpreter interpreter))
;;; -------------------------------------------------------
(defgeneric interpreter-dispatch-instruction (interpreter
instruction-type
instruction)
(:documentation
"Processes the INSTRUCTION, identified by and dispatched on the
INSTRUCTION-TYPE, by the INTERPRETER and returns no value."))
;;; -------------------------------------------------------
(defun interpreter-process-instruction (interpreter instruction)
"Invokes the appropriate implementation of the generic function
``interpreter-dispatch-instruction'' by applying the INTERPRETER and
the INSTRUCTINO, utilizing the INSTRUCTION type as the paravaunt
dispatch criterion, and returns no value."
(declare (type Interpreter interpreter))
(declare (type Instruction instruction))
(interpreter-dispatch-instruction interpreter
(instruction-type instruction) instruction)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :push-next-value))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(push (instruction-operand instruction)
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :pop))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(pop (interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :swap))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(rotatef
(first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :rotate))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(rotatef
(first (interpreter-stack interpreter))
(third (interpreter-stack interpreter)))
(rotatef
(second (interpreter-stack interpreter))
(third (interpreter-stack interpreter)))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :goto))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(interpreter-goto interpreter
(pop (interpreter-stack interpreter)))
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :clone))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (first (interpreter-stack interpreter))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :add))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (+ (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :subtract))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (- (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :multiply))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (* (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :divide))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (round (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :modulus))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (mod (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :print-number))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~d "
(first
(interpreter-stack interpreter)))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :print-character))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~d"
(code-char
(first
(interpreter-stack interpreter))))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :input-number))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~&Please input a number: ")
(push (parse-integer (read-line))
(interpreter-stack interpreter))
(clear-input)
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :input-string))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~&Please input a string: ")
(let ((input (read-line)))
(declare (type string input))
(clear-input)
(loop for character of-type character across input do
(push (char-code character)
(interpreter-stack interpreter))))
(interpreter-advance interpreter)
(values))
;;; -------------------------------------------------------
(defun interpreter-interpret (interpreter)
"Interprets the Jackass program stored in the INTERPRETER and returns
no value."
(declare (type Interpreter interpreter))
(loop while (slot-value interpreter 'current-instruction) do
(interpreter-process-instruction interpreter
(slot-value interpreter 'current-instruction)))
(values))
;;; -------------------------------------------------------
(defun interpret-Jackass (code)
"Interprets the piece of Jackass CODE and returns no value."
(declare (type string code))
(interpreter-interpret
(make-interpreter
(parse-tokens
(make-lexer code))))
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; -- Test cases. -- ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
One - time numeric cat program .
(interpret-Jackass "0e 0c")
;;; -------------------------------------------------------
;; Infinitely repeating numeric cat program.
(interpret-Jackass "0e 0c 01 00 05")
;;; -------------------------------------------------------
Print the message " Hello , World ! " by pushing each character 's ASCII
;; code, printing its character representation, and subsequently popping
;; it.
(interpret-Jackass
"
01 48 0d 02
01 65 0d 02
01 6C 0d 02
01 6C 0d 02
01 6F 0d 02
01 2C 0d 02
01 20 0d 02
01 57 0d 02
01 6F 0d 02
01 72 0d 02
01 6C 0d 02
01 64 0d 02
01 21 0d 02
")
;;; -------------------------------------------------------
;; Truth-machine.
;;
Apostils concerning the concept :
;;
Instruction indices occupy the range [ 0 , 12 ] .
= > REDUCER = 12 = RETURN_POS - 1 .
= > RETURN_POS = 13 .
;;
;; ------------------------------------------------------------------------------------------------
;; # | Instruction | Annotation | Stack (top element is on the left)
;; ---+-----------------+-----------------------------------+--------------------------------------
;; 0 | input | | [input]
1 | output | | [ input ]
2 | push REDUCER | | [ REDUCER input ]
;; 3 | multiply | product = REDUCER * input | [product REDUCER input]
4 | swap | product < - > REDUCER | [ REDUCER product input ]
;; 5 | pop | REDUCER | [product input]
6 | push RETURN_POS | | [ RETURN_POS product input ]
7 | subtract | difference = RETURN_POS - product | [ difference RETURN_POS product input ]
8 | swap | | [ RETURN_POS difference product input ]
9 | pop | | [ difference product input ]
;; 10 | swap | | [product difference input]
;; 11 | pop | | [difference input]
;; 12 | goto | difference | [input]
;; ------------------------------------------------------------------------------------------------
(interpret-Jackass
"
0e
0c
01 0c
09
03
02
01 0d
08
03
02
03
02
05
")
| null | https://raw.githubusercontent.com/KavehYousefi/Esoteric-programming-languages/0545c5eb03da2ac067dfe32a35df0bc6ce019cea/Jackass/Jackass_001/main.lisp | lisp |
This program implements an interpreter for the esoteric programming
of hexadecimal tokens only which apply themselves to the manipulation
of a stack.
Instructions
============
a global stack's manipulation, each represented by a hexadecimal code
The instruction set's circumference registers a wide gamut of
capabilities:
- Pushing and popping stack elements.
- Swapping, rotating, and duplicating stack elements.
- Basic arithmetics in the form of addition, subtraction,
multiplication, division, and remainder computation.
- Character-based and numeric input and output facilities.
- A goto contruct for steering the control flow.
------------------------------------------------------------------
Command | Effect
--------+---------------------------------------------------------
01 | Pushes the next hexadecimal token to the top of the
| stack.
..................................................................
02 | Pops the top stack element.
..................................................................
..................................................................
| it.
..................................................................
05 | Pops the top stack element and relocates the instruction
| equal to the deleted element's value.
..................................................................
06 | Pushes a copy of the top stack element unto the top.
..................................................................
07 | Peeks without removing the top stack element a and the
| element b previously below it, and pushes the sum
| a + b
| unto the stack.
..................................................................
08 | Peeks without removing the top stack element a and the
| element b previously below it, and pushes the difference
| a - b
| unto the stack.
..................................................................
09 | Peeks without removing the top stack element a and the
| element b previously below it, and pushes the product
| a * b
| unto the stack.
..................................................................
0a | Peeks without removing the top stack element a and the
| element b previously below it, and pushes the
| contingently rounded quotient
| a / b
| unto the stack.
..................................................................
0b | Peeks without removing the top stack element a and the
| element b previously below it, and pushes the remainder
| r obtained by the division
| r = a mod b
| unto the stack.
..................................................................
0c | Prints the top stack element as a decimal integer.
..................................................................
0d | Prints the character associated with the top stack
| element, construed as an ASCII code.
..................................................................
0e | Queries the user for an unsigned decimal integer and
| pushes it unto the stack.
..................................................................
0f | Queries the user for a string and, starting from its
| left to its right end, pushes each of its characters'
| ASCII codes unto the stack.
------------------------------------------------------------------
--------------------------------------------------------------------
Sources:
-- Declaration of types. -- ;;
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-- Implementation of character operations. -- ;;
;
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
otherwise signaling an error of an unspecified type."
-------------------------------------------------------
-------------------------------------------------------
-- Implementation of class "Instruction". -- ;;
-- Implementation of parser. -- ;;
-- Implementation of class "Interpreter". -- ;;
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-------------------------------------------------------
-- Test cases. -- ;;
-------------------------------------------------------
Infinitely repeating numeric cat program.
-------------------------------------------------------
code, printing its character representation, and subsequently popping
it.
-------------------------------------------------------
Truth-machine.
------------------------------------------------------------------------------------------------
# | Instruction | Annotation | Stack (top element is on the left)
---+-----------------+-----------------------------------+--------------------------------------
0 | input | | [input]
3 | multiply | product = REDUCER * input | [product REDUCER input]
5 | pop | REDUCER | [product input]
10 | swap | | [product difference input]
11 | pop | | [difference input]
12 | goto | difference | [input]
------------------------------------------------------------------------------------------------ | language " Jackass " , presented by the Esolang user " Phase " in the year
2015 , being , while inspired by Urban Mueller 's " brainfuck " , composed
Jackass 's competence founds upon fifteen instructions reponsible for
compact of one or more base-16 digits .
03 | Swaps the two top stack elements ' positions .
04 | Rotates the three stack elements , that is , relocates
| the third highest element to the top of the stack , thus
| effectively shifting down the two items previously above
| pointer to the instruction at the zero - based position
Author :
Date : 2022 - 12 - 21
- > " "
(deftype list-of (&optional (element-type T))
"The ``list-of'' type defines a list of zero or more elements, each
member of which conforms to the ELEMENT-TYPE, defaulting to the
comprehensive ``T''."
(let ((predicate (gensym)))
(declare (type symbol predicate))
(setf (symbol-function predicate)
#'(lambda (candidate)
(declare (type T candidate))
(and
(listp candidate)
(every
#'(lambda (element)
(declare (type T element))
(typep element element-type))
(the list candidate)))))
`(satisfies ,predicate)))
(deftype token ()
"The ``token'' type defines a token as an unsigned non-negative
integer."
'(integer 0 *))
(deftype stack ()
"The ``stack'' type defines a last-in first-out collection based upon
a list of signed integer objects."
'(list-of integer))
(deftype command ()
"The ``command'' type enumerates the recognized operation types."
'(member
:push-next-value
:pop
:swap
:rotate
:goto
:clone
:add
:subtract
:multiply
:divide
:modulus
:print-number
:print-character
:input-number
:input-string))
(deftype jackass-program ()
"The ``jackass-program'' type defines a Jackass program as a vector
of zero or more ``Instruction'' objects."
'(vector Instruction *))
(defun whitespace-character-p (candidate)
"Checks whether the CANDIDATE represents a whitespace, returning on
confirmation a ``boolean'' value of ``T'', otherwise ``NIL''."
(declare (type character candidate))
(the boolean
(not (null
(member candidate '(#\Space #\Tab #\Newline #\Return #\Linefeed)
:test #'char=)))))
(defclass Lexer ()
((source
:initarg :source
:initform (error "Missing lexer source.")
:type string
:documentation "The piece of Jackass source code to analyze.")
(position
:initarg :position
:initform 0
:type fixnum
:documentation "The position into the SOURCE's current CHARACTER.")
(character
:initarg :character
:initform NIL
:type (or null character)
:documentation "The character at the current POSITION into the
SOURCE."))
(:documentation
"The ``Lexer'' class' contribution encompasses the perception and
extraction of significant elements from a piece of Jackass code,
which are returned as a stream of tokens."))
(defmethod initialize-instance :after ((lexer Lexer) &key)
(declare (type Lexer lexer))
(with-slots (source position character) lexer
(declare (type string source))
(declare (type fixnum position))
(declare (type (or null character) character))
(setf character
(when (array-in-bounds-p source position)
(char source position))))
(the Lexer lexer))
(defun make-lexer (source)
"Creates and returns a new ``Lexer'' which serves to analyze the
SOURCE."
(declare (type string source))
(the Lexer
(make-instance 'Lexer :source source)))
(defun lexer-advance (lexer)
"Moves the LEXER's position cursor to the next character in its
source, if possible, updates its internal state, and returns the
modified LEXER."
(declare (type Lexer lexer))
(with-slots (source position character) lexer
(declare (type string source))
(declare (type fixnum position))
(declare (type (or null character) character))
(setf character
(when (array-in-bounds-p source (1+ position))
(char source (incf position)))))
(the Lexer lexer))
(defun lexer-skip-whitespaces (lexer)
"Starting at the current position into the LEXER's source, skips a
sequence of zero or more adjacent whitespaces and returns the
modified LEXER."
(declare (type Lexer lexer))
(with-slots (character) lexer
(declare (type (or null character) character))
(loop while (and character (whitespace-character-p character)) do
(lexer-advance lexer)))
(the Lexer lexer))
(defun lexer-expect-command-separator (lexer)
"Expects the LEXER's current character to be either a whitespace, in
which case all adjacent instances of the same are skipped, or the end
of the source (EOF), on confirmation returning the contingently
(declare (type Lexer lexer))
(with-slots (character position) lexer
(declare (type (or null character) character))
(declare (type fixnum position))
(declare (ignorable position))
(cond
((null character)
NIL)
((whitespace-character-p character)
(lexer-skip-whitespaces lexer))
(T
(error "Expected whitespace or end of file, ~
but encountered ~s at position ~d."
character position))))
(the Lexer lexer))
(defun lexer-read-hexadecimal-number (lexer)
"Starting at the current position into the LEXER's source, consumes an
unsigned hexadecimal integer, parses the same, and returns its
decimal value as a ``token''."
(declare (type Lexer lexer))
(with-slots (character) lexer
(declare (type (or null character) character))
(the token
(parse-integer
(with-output-to-string (digits)
(declare (type string-stream digits))
(loop while (and character (digit-char-p character 16)) do
(write-char character digits)
(lexer-advance lexer)))
:radix 16))))
(defun lexer-get-next-token (lexer)
"Returns the next token from the LEXER.
---
Upon its source's exhaustion, the LEXER responds to each request with
the ``NIL'' value."
(declare (type Lexer lexer))
(with-slots (character position) lexer
(declare (type (or null character) character))
(declare (type fixnum position))
(declare (ignorable position))
(the (or null token)
(cond
((null character)
NIL)
((whitespace-character-p character)
(lexer-skip-whitespaces lexer)
(lexer-get-next-token lexer))
((digit-char-p character 16)
(lexer-read-hexadecimal-number lexer))
(T
(error "Unexpected character ~s at position ~d."
character position))))))
(defstruct (Instruction
(:constructor make-instruction (type &optional (operand NIL))))
"The ``Instruction'' class encapsulates the pertinent information for
executing a Jackass operation, including an identifying command type
specifier and an optional argument."
(type (error "Missing instruction type.") :type command)
(operand NIL :type (or null token)))
(defun parse-tokens (lexer)
"Assembles the LEXER's tokens into a one-dimensional simple array of
Jackass instructions, which are subsequently returned."
(declare (type Lexer lexer))
(let ((instructions NIL)
(token (lexer-get-next-token lexer)))
(declare (type list instructions))
(declare (type (or null token) token))
(flet
((advance ()
"Requests the next token from the LEXER, stores it in the
TOKEN, and returns no value."
(setf token (lexer-get-next-token lexer))
(values))
(add-instruction (type &optional (operand NIL))
"Creates a new ``Instruction'' of the specified type,
optionally affiliated with an OPERAND, prepends it to the
INSTRUCTIONS list, and returns no value."
(push (make-instruction type operand) instructions)
(values)))
(loop while token do
(case token
(#x01
(advance)
(if token
(add-instruction :push-next-value token)
(error "Expected a number, but encountered EOF.")))
(#x02
(add-instruction :pop))
(#x03
(add-instruction :swap))
(#x04
(add-instruction :rotate))
(#x05
(add-instruction :goto))
(#x06
(add-instruction :clone))
(#x07
(add-instruction :add))
(#x08
(add-instruction :subtract))
(#x09
(add-instruction :multiply))
(#x0a
(add-instruction :divide))
(#x0b
(add-instruction :modulus))
(#x0c
(add-instruction :print-number))
(#x0d
(add-instruction :print-character))
(#x0e
(add-instruction :input-number))
(#x0f
(add-instruction :input-string))
(otherwise
(error "Invalid command code: ~x." token)))
(advance)))
(the (simple-array Instruction (*))
(coerce (nreverse instructions)
'(simple-array Instruction (*))))))
(defclass Interpreter ()
((instructions
:initarg :instructions
:initform (error "Missing interpreter instructions.")
:type jackass-program
:documentation "The Jackass instructions to evaluate.")
(ip
:initarg :ip
:initform 0
:type fixnum
:documentation "The instruction pointer (IP), serving as the index
into the INSTRUCTIONS' currently active entry.")
(current-instruction
:initarg :current-instruction
:initform NIL
:type (or null Instruction)
:documentation "The instruction under the instruction pointer (IP)
in the INSTRUCTIONS sequence.")
(stack
:initarg :stack
:initform NIL
:accessor interpreter-stack
:type stack
:documentation "A stack of signed integer numbers."))
(:documentation
"Appropriating the wike of a Jackass program evaluator, the
``Interpreter'' class processes a sequence of instructions,
inducing actual effect into them."))
(defmethod initialize-instance :after ((interpreter Interpreter) &key)
(declare (type Interpreter interpreter))
(with-slots (instructions ip current-instruction) interpreter
(declare (type jackass-program instructions))
(declare (type fixnum ip))
(declare (type (or null Instruction) current-instruction))
(setf current-instruction
(when (array-in-bounds-p instructions ip)
(aref instructions ip))))
(the Interpreter interpreter))
(defun make-interpreter (instructions)
"Creates and returns a new ``Interpreter'' whose responsibility
assigns it to the evaluation of the Jackass INSTRUCTIONS."
(declare (type jackass-program instructions))
(the Interpreter
(make-instance 'Interpreter :instructions instructions)))
(defun interpreter-advance (interpreter)
"Moves the INTERPRETER's instruction pointer to the next instruction,
if possible, updates its internal state, and returns the modified
INTERPRETER."
(declare (type Interpreter interpreter))
(with-slots (instructions ip current-instruction) interpreter
(declare (type jackass-program instructions))
(declare (type fixnum ip))
(declare (type (or null Instruction) current-instruction))
(setf current-instruction
(when (array-in-bounds-p instructions (1+ ip))
(aref instructions (incf ip)))))
(the Interpreter interpreter))
(defun interpreter-goto (interpreter target)
"Relocates the INTERPRETER's instruction pointer to the TARGET,
updates its state, and returns the modified INTERPRETER."
(declare (type Interpreter interpreter))
(declare (type fixnum target))
(with-slots (instructions ip current-instruction) interpreter
(declare (type jackass-program instructions))
(declare (type fixnum ip))
(declare (type (or null Instruction) current-instruction))
(setf ip target)
(setf current-instruction
(when (array-in-bounds-p instructions ip)
(aref instructions ip))))
(the Interpreter interpreter))
(defgeneric interpreter-dispatch-instruction (interpreter
instruction-type
instruction)
(:documentation
"Processes the INSTRUCTION, identified by and dispatched on the
INSTRUCTION-TYPE, by the INTERPRETER and returns no value."))
(defun interpreter-process-instruction (interpreter instruction)
"Invokes the appropriate implementation of the generic function
``interpreter-dispatch-instruction'' by applying the INTERPRETER and
the INSTRUCTINO, utilizing the INSTRUCTION type as the paravaunt
dispatch criterion, and returns no value."
(declare (type Interpreter interpreter))
(declare (type Instruction instruction))
(interpreter-dispatch-instruction interpreter
(instruction-type instruction) instruction)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :push-next-value))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(push (instruction-operand instruction)
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :pop))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(pop (interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :swap))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(rotatef
(first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :rotate))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(rotatef
(first (interpreter-stack interpreter))
(third (interpreter-stack interpreter)))
(rotatef
(second (interpreter-stack interpreter))
(third (interpreter-stack interpreter)))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :goto))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(interpreter-goto interpreter
(pop (interpreter-stack interpreter)))
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :clone))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (first (interpreter-stack interpreter))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :add))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (+ (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :subtract))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (- (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :multiply))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (* (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :divide))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (round (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :modulus))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(push (mod (first (interpreter-stack interpreter))
(second (interpreter-stack interpreter)))
(interpreter-stack interpreter))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :print-number))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~d "
(first
(interpreter-stack interpreter)))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :print-character))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~d"
(code-char
(first
(interpreter-stack interpreter))))
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :input-number))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~&Please input a number: ")
(push (parse-integer (read-line))
(interpreter-stack interpreter))
(clear-input)
(interpreter-advance interpreter)
(values))
(defmethod interpreter-dispatch-instruction
((interpreter Interpreter)
(instruction-type (eql :input-string))
(instruction Instruction))
(declare (type Interpreter interpreter))
(declare (type command instruction-type))
(declare (type Instruction instruction))
(declare (ignore instruction-type))
(declare (ignore instruction))
(format T "~&Please input a string: ")
(let ((input (read-line)))
(declare (type string input))
(clear-input)
(loop for character of-type character across input do
(push (char-code character)
(interpreter-stack interpreter))))
(interpreter-advance interpreter)
(values))
(defun interpreter-interpret (interpreter)
"Interprets the Jackass program stored in the INTERPRETER and returns
no value."
(declare (type Interpreter interpreter))
(loop while (slot-value interpreter 'current-instruction) do
(interpreter-process-instruction interpreter
(slot-value interpreter 'current-instruction)))
(values))
(defun interpret-Jackass (code)
"Interprets the piece of Jackass CODE and returns no value."
(declare (type string code))
(interpreter-interpret
(make-interpreter
(parse-tokens
(make-lexer code))))
(values))
One - time numeric cat program .
(interpret-Jackass "0e 0c")
(interpret-Jackass "0e 0c 01 00 05")
Print the message " Hello , World ! " by pushing each character 's ASCII
(interpret-Jackass
"
01 48 0d 02
01 65 0d 02
01 6C 0d 02
01 6C 0d 02
01 6F 0d 02
01 2C 0d 02
01 20 0d 02
01 57 0d 02
01 6F 0d 02
01 72 0d 02
01 6C 0d 02
01 64 0d 02
01 21 0d 02
")
Apostils concerning the concept :
Instruction indices occupy the range [ 0 , 12 ] .
= > REDUCER = 12 = RETURN_POS - 1 .
= > RETURN_POS = 13 .
1 | output | | [ input ]
2 | push REDUCER | | [ REDUCER input ]
4 | swap | product < - > REDUCER | [ REDUCER product input ]
6 | push RETURN_POS | | [ RETURN_POS product input ]
7 | subtract | difference = RETURN_POS - product | [ difference RETURN_POS product input ]
8 | swap | | [ RETURN_POS difference product input ]
9 | pop | | [ difference product input ]
(interpret-Jackass
"
0e
0c
01 0c
09
03
02
01 0d
08
03
02
03
02
05
")
|
afb2d85b713192bd1aae6a5b42547aee8dbbc37109b44f466c0089286b1c01a5 | erlang-ls/erlang_ls | els_prepare_rename_provider.erl | -module(els_prepare_rename_provider).
-behaviour(els_provider).
-export([
handle_request/1
]).
%%==============================================================================
%% Includes
%%==============================================================================
-include_lib("kernel/include/logger.hrl").
%%==============================================================================
%% Defines
%%==============================================================================
%%==============================================================================
%% Types
%%==============================================================================
%%==============================================================================
%% els_provider functions
%%==============================================================================
-spec handle_request(any()) -> {response, any()}.
handle_request({prepare_rename, Params0}) ->
#{
<<"textDocument">> := #{<<"uri">> := Uri},
<<"position">> := #{
<<"line">> := Line,
<<"character">> := Character
}
} = Params0,
case els_utils:lookup_document(Uri) of
{ok, Document} ->
Params = Params0#{<<"newName">> => <<"newName">>},
POIs = els_dt_document:get_element_at_pos(
Document,
Line + 1,
Character + 1
),
case POIs of
[POI | _] ->
try
els_provider:handle_request(
els_rename_provider,
{rename, Params}
)
of
{response, null} ->
{response, null};
{response, _} ->
{response, els_protocol:range(rename_range(POI))}
catch
Class:Reason:Stacktrace ->
?LOG_ERROR(
"prepareRenamed failed: ~p:~p\n"
"Stacktrace:\n~p\n",
[Class, Reason, Stacktrace]
),
{response, null}
end;
_ ->
{response, null}
end;
{error, Error} ->
?LOG_WARNING("Failed to read uri: ~p ~p", [Error, Uri]),
{response, null}
end.
%%==============================================================================
Internal functions
%%==============================================================================
-spec rename_range(els_poi:poi()) -> els_poi:poi_range().
rename_range(#{data := #{name_range := Range}}) ->
Range;
rename_range(#{kind := Kind, range := #{from := {FromL, FromC}, to := To}}) when
Kind =:= macro;
Kind =:= record_expr
->
%% Don't include # or ? in name..
#{from => {FromL, FromC + 1}, to => To};
rename_range(#{range := Range}) ->
Range.
| null | https://raw.githubusercontent.com/erlang-ls/erlang_ls/fc00bd4c0fd3793270aca59d861299ced0fdb648/apps/els_lsp/src/els_prepare_rename_provider.erl | erlang | ==============================================================================
Includes
==============================================================================
==============================================================================
Defines
==============================================================================
==============================================================================
Types
==============================================================================
==============================================================================
els_provider functions
==============================================================================
==============================================================================
==============================================================================
Don't include # or ? in name.. | -module(els_prepare_rename_provider).
-behaviour(els_provider).
-export([
handle_request/1
]).
-include_lib("kernel/include/logger.hrl").
-spec handle_request(any()) -> {response, any()}.
handle_request({prepare_rename, Params0}) ->
#{
<<"textDocument">> := #{<<"uri">> := Uri},
<<"position">> := #{
<<"line">> := Line,
<<"character">> := Character
}
} = Params0,
case els_utils:lookup_document(Uri) of
{ok, Document} ->
Params = Params0#{<<"newName">> => <<"newName">>},
POIs = els_dt_document:get_element_at_pos(
Document,
Line + 1,
Character + 1
),
case POIs of
[POI | _] ->
try
els_provider:handle_request(
els_rename_provider,
{rename, Params}
)
of
{response, null} ->
{response, null};
{response, _} ->
{response, els_protocol:range(rename_range(POI))}
catch
Class:Reason:Stacktrace ->
?LOG_ERROR(
"prepareRenamed failed: ~p:~p\n"
"Stacktrace:\n~p\n",
[Class, Reason, Stacktrace]
),
{response, null}
end;
_ ->
{response, null}
end;
{error, Error} ->
?LOG_WARNING("Failed to read uri: ~p ~p", [Error, Uri]),
{response, null}
end.
Internal functions
-spec rename_range(els_poi:poi()) -> els_poi:poi_range().
rename_range(#{data := #{name_range := Range}}) ->
Range;
rename_range(#{kind := Kind, range := #{from := {FromL, FromC}, to := To}}) when
Kind =:= macro;
Kind =:= record_expr
->
#{from => {FromL, FromC + 1}, to => To};
rename_range(#{range := Range}) ->
Range.
|
d0dac8169ff68088e1d124159866017f59034267df87651406079747a029ff4e | incoherentsoftware/defect-process | Audio.hs | module Configs.All.Settings.Audio
( AudioConfig(..)
) where
import Data.Aeson.Types (FromJSON, genericParseJSON, parseJSON)
import GHC.Generics (Generic)
import Audio.Volume
import Util
import World.Audio.LayeredMusic.Types
data AudioConfig = AudioConfig
{ _soundsEnabled :: Bool
, _musicEnabled :: Bool
, _soundVolume :: Volume
, _musicVolume :: Volume
, _battleMusicInitialVolumePercent :: Float
, _explorationMusic :: LayeredMusicType
, _battleMusic :: LayeredMusicType
}
deriving Generic
instance FromJSON AudioConfig where
parseJSON = genericParseJSON aesonFieldDropUnderscore
| null | https://raw.githubusercontent.com/incoherentsoftware/defect-process/15f2569e7d0e481c2e28c0ca3a5e72d2c049b667/src/Configs/All/Settings/Audio.hs | haskell | module Configs.All.Settings.Audio
( AudioConfig(..)
) where
import Data.Aeson.Types (FromJSON, genericParseJSON, parseJSON)
import GHC.Generics (Generic)
import Audio.Volume
import Util
import World.Audio.LayeredMusic.Types
data AudioConfig = AudioConfig
{ _soundsEnabled :: Bool
, _musicEnabled :: Bool
, _soundVolume :: Volume
, _musicVolume :: Volume
, _battleMusicInitialVolumePercent :: Float
, _explorationMusic :: LayeredMusicType
, _battleMusic :: LayeredMusicType
}
deriving Generic
instance FromJSON AudioConfig where
parseJSON = genericParseJSON aesonFieldDropUnderscore
|
|
79c29ea4c2b4db69ffc6c4dccc6ed00272cae3a4b09ad998f67d6c12d426384b | mmottl/postgresql-ocaml | discover.ml | open Printf
let find_number ~pos str =
let len = String.length str in
let rec skip_other ~pos =
if pos = len then pos
else
match str.[pos] with
| '0'..'9' -> pos
| _ -> skip_other ~pos:(pos + 1)
in
let pos = skip_other ~pos in
let rec loop ~pos =
if pos = len then [], pos
else match str.[pos] with
| '0'..'9' as c ->
let acc, next = loop ~pos:(pos + 1) in
String.make 1 c :: acc, next
| _ -> [], pos
in
let number_lst, next = loop ~pos in
String.concat "" number_lst, next
let () =
let module C = Configurator.V1 in
C.main ~name:"postgresql" (fun _c ->
let cmd = "pg_config --includedir --libdir --version" in
let ic =
try Unix.open_process_in cmd
with exc -> eprintf "could not open pg_config, cmd: '%s'" cmd; raise exc
in
Fun.protect ~finally:(fun () -> close_in ic) (fun () ->
let pgsql_includedir = "-I" ^ input_line ic in
let pgsql_libdir = "-L" ^ input_line ic in
let major, minor =
let line = input_line ic in
let print_fail () =
eprintf "Unable to find versions from line '%s', cmd: '%s'" line cmd
in
let exit_fail () = print_fail (); exit 1 in
try
let first_space = String.index line ' ' in
let major, next = find_number ~pos:first_space line in
let minor =
(* Can also handle release candidates *)
let c = line.[next] in
if c = '.' then fst (find_number ~pos:next line)
else if c <> 'r' || line.[next + 1] <> 'c' then exit_fail ()
else "0"
in
if major = "" || minor = "" then exit_fail ()
else
"-DPG_OCAML_MAJOR_VERSION=" ^ major,
"-DPG_OCAML_MINOR_VERSION=" ^ minor
with exn -> print_fail (); raise exn
in
let conf = {
C.Pkg_config.
cflags = [pgsql_includedir; major; minor];
libs = [pgsql_libdir; "-lpq"];
} in
C.Flags.write_sexp "c_flags.sexp" conf.cflags;
C.Flags.write_sexp "c_library_flags.sexp" conf.libs))
| null | https://raw.githubusercontent.com/mmottl/postgresql-ocaml/7c0c90119d09cc72d6296538b40d312c81486732/src/config/discover.ml | ocaml | Can also handle release candidates | open Printf
let find_number ~pos str =
let len = String.length str in
let rec skip_other ~pos =
if pos = len then pos
else
match str.[pos] with
| '0'..'9' -> pos
| _ -> skip_other ~pos:(pos + 1)
in
let pos = skip_other ~pos in
let rec loop ~pos =
if pos = len then [], pos
else match str.[pos] with
| '0'..'9' as c ->
let acc, next = loop ~pos:(pos + 1) in
String.make 1 c :: acc, next
| _ -> [], pos
in
let number_lst, next = loop ~pos in
String.concat "" number_lst, next
let () =
let module C = Configurator.V1 in
C.main ~name:"postgresql" (fun _c ->
let cmd = "pg_config --includedir --libdir --version" in
let ic =
try Unix.open_process_in cmd
with exc -> eprintf "could not open pg_config, cmd: '%s'" cmd; raise exc
in
Fun.protect ~finally:(fun () -> close_in ic) (fun () ->
let pgsql_includedir = "-I" ^ input_line ic in
let pgsql_libdir = "-L" ^ input_line ic in
let major, minor =
let line = input_line ic in
let print_fail () =
eprintf "Unable to find versions from line '%s', cmd: '%s'" line cmd
in
let exit_fail () = print_fail (); exit 1 in
try
let first_space = String.index line ' ' in
let major, next = find_number ~pos:first_space line in
let minor =
let c = line.[next] in
if c = '.' then fst (find_number ~pos:next line)
else if c <> 'r' || line.[next + 1] <> 'c' then exit_fail ()
else "0"
in
if major = "" || minor = "" then exit_fail ()
else
"-DPG_OCAML_MAJOR_VERSION=" ^ major,
"-DPG_OCAML_MINOR_VERSION=" ^ minor
with exn -> print_fail (); raise exn
in
let conf = {
C.Pkg_config.
cflags = [pgsql_includedir; major; minor];
libs = [pgsql_libdir; "-lpq"];
} in
C.Flags.write_sexp "c_flags.sexp" conf.cflags;
C.Flags.write_sexp "c_library_flags.sexp" conf.libs))
|
23a82b6320f944b99be6d255cdec4a27a99c3c835cd57c8a4db8923cc46d258e | slepher/astranaut | sample_plus.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2020 ,
%%% @doc
%%%
%%% @end
Created : 9 Jul 2020 by < >
%%%-------------------------------------------------------------------
-module(sample_plus).
%% API
-export([plus/2]).
plus(A, B) ->
A + B.
%%--------------------------------------------------------------------
%% @doc
%% @end
%%--------------------------------------------------------------------
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/slepher/astranaut/7d832eb4f8b71346caa37c9f081c7d73900d7135/test/astranaut_uniplate_SUITE_data/sample_plus.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
--------------------------------------------------------------------
@doc
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | @author < >
( C ) 2020 ,
Created : 9 Jul 2020 by < >
-module(sample_plus).
-export([plus/2]).
plus(A, B) ->
A + B.
Internal functions
|
d60576399c756f5c87a51a79e9d1e14708c0d468e3ccb285585e1a7ce4f06252 | kmicinski/htltl2mc | program.ml | type id = string
type exp =
| Const of int
| Id of id
| Plus of exp * exp
| Sub of exp * exp
| Mul of exp * exp
| Div of exp * exp
| Lt of exp * exp
| Gt of exp * exp
| Eq of exp * exp
| Not of exp
| And of exp * exp
type cmd =
| Skip
| Asn of id * exp
| Seq of cmd * cmd
| If of exp * cmd * cmd
| While of exp * cmd
| Choice of cmd list
type level = H | L
type init =
| Any
| Specific of int
type var_configuration =
id * level * int * init
type configuration =
var_configuration list
let empty_configuration = []
(* Enumeration of the store: id, level, width, value *)
type store =
(id * level * int * int) list
(* A program is a list of variables associated with levels and widths *)
type program =
configuration * cmd
let starting_program = function cmd -> (empty_configuration, cmd)
let mk_program cfg p = cfg,p
exception NoId of string
| null | https://raw.githubusercontent.com/kmicinski/htltl2mc/5b949db7f3d849d3f9b943f84c3ce065ccfaa7e3/src/program.ml | ocaml | Enumeration of the store: id, level, width, value
A program is a list of variables associated with levels and widths | type id = string
type exp =
| Const of int
| Id of id
| Plus of exp * exp
| Sub of exp * exp
| Mul of exp * exp
| Div of exp * exp
| Lt of exp * exp
| Gt of exp * exp
| Eq of exp * exp
| Not of exp
| And of exp * exp
type cmd =
| Skip
| Asn of id * exp
| Seq of cmd * cmd
| If of exp * cmd * cmd
| While of exp * cmd
| Choice of cmd list
type level = H | L
type init =
| Any
| Specific of int
type var_configuration =
id * level * int * init
type configuration =
var_configuration list
let empty_configuration = []
type store =
(id * level * int * int) list
type program =
configuration * cmd
let starting_program = function cmd -> (empty_configuration, cmd)
let mk_program cfg p = cfg,p
exception NoId of string
|
03ae5e4756e9475d69cd33f4262695a824b8216798ba71dc0f936d93b9eb4abc | inhabitedtype/bigstringaf | discover.ml | open Configurator.V1
let get_warning_flags t =
match ocaml_config_var t "ccomp_type" with
| Some "msvc" -> ["/Wall"; "/W3"]
| _ -> ["-Wall"; "-Wextra"; "-Wpedantic"]
let () =
main ~name:"discover" (fun t ->
let wflags = get_warning_flags t in
Flags.write_sexp "cflags.sexp" wflags)
| null | https://raw.githubusercontent.com/inhabitedtype/bigstringaf/800885f4d1df2fe3cc478ba1007c77cf511cca8b/lib/config/discover.ml | ocaml | open Configurator.V1
let get_warning_flags t =
match ocaml_config_var t "ccomp_type" with
| Some "msvc" -> ["/Wall"; "/W3"]
| _ -> ["-Wall"; "-Wextra"; "-Wpedantic"]
let () =
main ~name:"discover" (fun t ->
let wflags = get_warning_flags t in
Flags.write_sexp "cflags.sexp" wflags)
|
|
554eb4ad04c3b3818d552ad9a258cfcd75a6eee81fac54f373b3c5c482b20e48 | exercism/babashka | project.clj | (defproject elyses-destructured-enchantments "0.1.0-SNAPSHOT"
:description "elyses-destructured-enchantments exercise."
:url "-destructured-enchantments"
:dependencies [[org.clojure/clojure "1.10.0"]]) | null | https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/concept/elyses-destructured-enchantments/project.clj | clojure | (defproject elyses-destructured-enchantments "0.1.0-SNAPSHOT"
:description "elyses-destructured-enchantments exercise."
:url "-destructured-enchantments"
:dependencies [[org.clojure/clojure "1.10.0"]]) |
|
457770ecd94f78a090a8b643d0d454c8a593931dc14beab74ab266a4dcd32f30 | ghcjs/ghcjs-boot | Enum.hs | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash #
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
Module :
Copyright : ( c ) The University of Glasgow , 1992 - 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer :
-- Stability : internal
Portability : non - portable ( GHC extensions )
--
The ' ' and ' Bounded ' classes .
--
-----------------------------------------------------------------------------
#include "MachDeps.h"
module GHC.Enum(
Bounded(..), Enum(..),
boundedEnumFrom, boundedEnumFromThen,
toEnumError, fromEnumError, succError, predError,
Instances for Bounded and : ( ) , , Int
) where
import GHC.Base hiding ( many )
import GHC.Char
import GHC.Integer
import GHC.Num
import GHC.Show
default () -- Double isn't available yet
-- | The 'Bounded' class is used to name the upper and lower limits of a
type . ' ' is not a superclass of ' Bounded ' since types that are not
-- totally ordered may also have upper and lower bounds.
--
The ' Bounded ' class may be derived for any enumeration type ;
' ' is the first constructor listed in the @data@ declaration
and ' maxBound ' is the last .
-- 'Bounded' may also be derived for single-constructor datatypes whose
-- constituent types are in 'Bounded'.
class Bounded a where
minBound, maxBound :: a
| Class ' ' defines operations on sequentially ordered types .
--
The @enumFrom@ ... methods are used in 's translation of
-- arithmetic sequences.
--
Instances of ' ' may be derived for any enumeration type ( types
-- whose constructors have no fields). The nullary constructors are
assumed to be numbered left - to - right by ' fromEnum ' from @0@ through @n-1@.
See Chapter 10 of the /Haskell Report/ for more details .
--
For any type that is an instance of class ' Bounded ' as well as ' ' ,
-- the following should hold:
--
* The calls @'succ ' ' maxBound'@ and @'pred ' ' minBound'@ should result in
-- a runtime error.
--
-- * 'fromEnum' and 'toEnum' should give a runtime error if the
-- result value is not representable in the result type.
For example , @'toEnum ' 7 : : ' Bool'@ is an error .
--
-- * 'enumFrom' and 'enumFromThen' should be defined with an implicit bound,
-- thus:
--
> enumFrom x = enumFromTo x maxBound
> enumFromThen x y = enumFromThenTo x y bound
-- > where
> bound | fromEnum y > = fromEnum x = maxBound
> | otherwise =
--
class Enum a where
| the successor of a value . For numeric types , ' succ ' adds 1 .
succ :: a -> a
| the predecessor of a value . For numeric types , ' pred ' subtracts 1 .
pred :: a -> a
-- | Convert from an 'Int'.
toEnum :: Int -> a
-- | Convert to an 'Int'.
-- It is implementation-dependent what 'fromEnum' returns when
-- applied to a value that is too large to fit in an 'Int'.
fromEnum :: a -> Int
| Used in Haskell 's translation of @[n .. ]@.
enumFrom :: a -> [a]
| Used in Haskell 's translation of @[n , n' .. ]@.
enumFromThen :: a -> a -> [a]
| Used in Haskell 's translation of @[n .. m]@.
enumFromTo :: a -> a -> [a]
| Used in Haskell 's translation of @[n , n' .. m]@.
enumFromThenTo :: a -> a -> a -> [a]
succ = toEnum . (+ 1) . fromEnum
pred = toEnum . (subtract 1) . fromEnum
enumFrom x = map toEnum [fromEnum x ..]
enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..]
enumFromTo x y = map toEnum [fromEnum x .. fromEnum y]
enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]
-- Default methods for bounded enumerations
boundedEnumFrom :: (Enum a, Bounded a) => a -> [a]
boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)]
boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a]
boundedEnumFromThen n1 n2
| i_n2 >= i_n1 = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)]
| otherwise = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)]
where
i_n1 = fromEnum n1
i_n2 = fromEnum n2
------------------------------------------------------------------------
-- Helper functions
------------------------------------------------------------------------
{-# NOINLINE toEnumError #-}
toEnumError :: (Show a) => String -> Int -> (a,a) -> b
toEnumError inst_ty i bnds =
error $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++
show i ++
") is outside of bounds " ++
show bnds
{-# NOINLINE fromEnumError #-}
fromEnumError :: (Show a) => String -> a -> b
fromEnumError inst_ty x =
error $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++
show x ++
") is outside of Int's bounds " ++
show (minBound::Int, maxBound::Int)
# NOINLINE succError #
succError :: String -> a
succError inst_ty =
error $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound"
# NOINLINE predError #
predError :: String -> a
predError inst_ty =
error $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound"
------------------------------------------------------------------------
Tuples
------------------------------------------------------------------------
instance Bounded () where
minBound = ()
maxBound = ()
instance Enum () where
succ _ = error "Prelude.Enum.().succ: bad argument"
pred _ = error "Prelude.Enum.().pred: bad argument"
toEnum x | x == 0 = ()
| otherwise = error "Prelude.Enum.().toEnum: bad argument"
fromEnum () = 0
enumFrom () = [()]
enumFromThen () () = let many = ():many in many
enumFromTo () () = [()]
enumFromThenTo () () () = let many = ():many in many
Report requires instances up to 15
instance (Bounded a, Bounded b) => Bounded (a,b) where
minBound = (minBound, minBound)
maxBound = (maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where
minBound = (minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where
minBound = (minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a,b,c,d,e) where
minBound = (minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f)
=> Bounded (a,b,c,d,e,f) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g)
=> Bounded (a,b,c,d,e,f,g) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h)
=> Bounded (a,b,c,d,e,f,g,h) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i)
=> Bounded (a,b,c,d,e,f,g,h,i) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j)
=> Bounded (a,b,c,d,e,f,g,h,i,j) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
------------------------------------------------------------------------
-- Bool
------------------------------------------------------------------------
instance Bounded Bool where
minBound = False
maxBound = True
instance Enum Bool where
succ False = True
succ True = error "Prelude.Enum.Bool.succ: bad argument"
pred True = False
pred False = error "Prelude.Enum.Bool.pred: bad argument"
toEnum n | n == 0 = False
| n == 1 = True
| otherwise = error "Prelude.Enum.Bool.toEnum: bad argument"
fromEnum False = 0
fromEnum True = 1
-- Use defaults for the rest
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
------------------------------------------------------------------------
-- Ordering
------------------------------------------------------------------------
instance Bounded Ordering where
minBound = LT
maxBound = GT
instance Enum Ordering where
succ LT = EQ
succ EQ = GT
succ GT = error "Prelude.Enum.Ordering.succ: bad argument"
pred GT = EQ
pred EQ = LT
pred LT = error "Prelude.Enum.Ordering.pred: bad argument"
toEnum n | n == 0 = LT
| n == 1 = EQ
| n == 2 = GT
toEnum _ = error "Prelude.Enum.Ordering.toEnum: bad argument"
fromEnum LT = 0
fromEnum EQ = 1
fromEnum GT = 2
-- Use defaults for the rest
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
------------------------------------------------------------------------
-- Char
------------------------------------------------------------------------
instance Bounded Char where
minBound = '\0'
maxBound = '\x10FFFF'
instance Enum Char where
succ (C# c#)
| isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#))
| otherwise = error ("Prelude.Enum.Char.succ: bad argument")
pred (C# c#)
| isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#))
| otherwise = error ("Prelude.Enum.Char.pred: bad argument")
toEnum = chr
fromEnum = ord
# INLINE enumFrom #
enumFrom (C# x) = eftChar (ord# x) 0x10FFFF#
-- Blarg: technically I guess enumFrom isn't strict!
# INLINE enumFromTo #
enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y)
# INLINE enumFromThen #
enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2)
{-# INLINE enumFromThenTo #-}
enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y)
# RULES
" eftChar " [ ~1 ] forall x y. eftChar x y = build ( \c n - > eftCharFB c n x y )
" efdChar " [ ~1 ] forall x1 x2 . efdChar x1 x2 = build ( \ c n - > efdCharFB c n x1 x2 )
" efdtChar " [ ~1 ] forall x1 x2 l. efdtChar x1 x2 l = build ( \ c n - > efdtCharFB c n x1 x2 l )
" eftCharList " [ 1 ] eftCharFB ( :) [ ] = eftChar
" efdCharList " [ 1 ] efdCharFB ( :) [ ] = efdChar
" efdtCharList " [ 1 ] efdtCharFB ( :) [ ] = efdtChar
#
"eftChar" [~1] forall x y. eftChar x y = build (\c n -> eftCharFB c n x y)
"efdChar" [~1] forall x1 x2. efdChar x1 x2 = build (\ c n -> efdCharFB c n x1 x2)
"efdtChar" [~1] forall x1 x2 l. efdtChar x1 x2 l = build (\ c n -> efdtCharFB c n x1 x2 l)
"eftCharList" [1] eftCharFB (:) [] = eftChar
"efdCharList" [1] efdCharFB (:) [] = efdChar
"efdtCharList" [1] efdtCharFB (:) [] = efdtChar
#-}
We can do better than for because we do n't
have hassles about arithmetic overflow at maxBound
{-# INLINE [0] eftCharFB #-}
eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
eftCharFB c n x0 y = go x0
where
go x | isTrue# (x ># y) = n
| otherwise = C# (chr# x) `c` go (x +# 1#)
# NOINLINE [ 1 ] eftChar #
eftChar :: Int# -> Int# -> String
eftChar x y | isTrue# (x ># y ) = []
| otherwise = C# (chr# x) : eftChar (x +# 1#) y
-- For enumFromThenTo we give up on inlining
{-# NOINLINE [0] efdCharFB #-}
efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
efdCharFB c n x1 x2
| isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF#
| otherwise = go_dn_char_fb c n x1 delta 0#
where
!delta = x2 -# x1
# NOINLINE [ 1 ] efdChar #
efdChar :: Int# -> Int# -> String
efdChar x1 x2
| isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF#
| otherwise = go_dn_char_list x1 delta 0#
where
!delta = x2 -# x1
{-# NOINLINE [0] efdtCharFB #-}
efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
efdtCharFB c n x1 x2 lim
| isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim
| otherwise = go_dn_char_fb c n x1 delta lim
where
!delta = x2 -# x1
{-# NOINLINE [1] efdtChar #-}
efdtChar :: Int# -> Int# -> Int# -> String
efdtChar x1 x2 lim
| isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim
| otherwise = go_dn_char_list x1 delta lim
where
!delta = x2 -# x1
go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
go_up_char_fb c n x0 delta lim
= go_up x0
where
go_up x | isTrue# (x ># lim) = n
| otherwise = C# (chr# x) `c` go_up (x +# delta)
go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
go_dn_char_fb c n x0 delta lim
= go_dn x0
where
go_dn x | isTrue# (x <# lim) = n
| otherwise = C# (chr# x) `c` go_dn (x +# delta)
go_up_char_list :: Int# -> Int# -> Int# -> String
go_up_char_list x0 delta lim
= go_up x0
where
go_up x | isTrue# (x ># lim) = []
| otherwise = C# (chr# x) : go_up (x +# delta)
go_dn_char_list :: Int# -> Int# -> Int# -> String
go_dn_char_list x0 delta lim
= go_dn x0
where
go_dn x | isTrue# (x <# lim) = []
| otherwise = C# (chr# x) : go_dn (x +# delta)
------------------------------------------------------------------------
-- Int
------------------------------------------------------------------------
Be careful about these instances .
( a ) remember that you have to count down as well as up e.g. [ 13,12 .. 0 ]
( b ) be careful of Int overflow
( c ) remember that is bounded , so [ 1 .. ] terminates at maxInt
Be careful about these instances.
(a) remember that you have to count down as well as up e.g. [13,12..0]
(b) be careful of Int overflow
(c) remember that Int is bounded, so [1..] terminates at maxInt
-}
instance Bounded Int where
minBound = minInt
maxBound = maxInt
instance Enum Int where
succ x
| x == maxBound = error "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound"
| otherwise = x + 1
pred x
| x == minBound = error "Prelude.Enum.pred{Int}: tried to take `pred' of minBound"
| otherwise = x - 1
toEnum x = x
fromEnum x = x
# INLINE enumFrom #
enumFrom (I# x) = eftInt x maxInt#
where !(I# maxInt#) = maxInt
-- Blarg: technically I guess enumFrom isn't strict!
# INLINE enumFromTo #
enumFromTo (I# x) (I# y) = eftInt x y
# INLINE enumFromThen #
enumFromThen (I# x1) (I# x2) = efdInt x1 x2
{-# INLINE enumFromThenTo #-}
enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y
-----------------------------------------------------
eftInt and eftIntFB deal with [ a .. b ] , which is the
-- most common form, so we take a lot of care
-- In particular, we have rules for deforestation
# RULES
" eftInt " [ ~1 ] forall x y. eftInt x y = build ( \ c n - > eftIntFB c n x y )
" eftIntList " [ 1 ] eftIntFB ( :) [ ] = eftInt
#
"eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
"eftIntList" [1] eftIntFB (:) [] = eftInt
#-}
# NOINLINE [ 1 ] eftInt #
eftInt :: Int# -> Int# -> [Int]
-- [x1..x2]
eftInt x0 y | isTrue# (x0 ># y) = []
| otherwise = go x0
where
go x = I# x : if isTrue# (x ==# y)
then []
else go (x +# 1#)
{-# INLINE [0] eftIntFB #-}
eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
eftIntFB c n x0 y | isTrue# (x0 ># y) = n
| otherwise = go x0
where
go x = I# x `c` if isTrue# (x ==# y)
then n
else go (x +# 1#)
Watch out for y = maxBound ; hence = = , not >
Be very careful not to have more than one " c "
-- so that when eftInfFB is inlined we can inline
-- whatever is bound to "c"
-----------------------------------------------------
-- efdInt and efdtInt deal with [a,b..] and [a,b..c].
-- The code is more complicated because of worries about Int overflow.
# RULES
" efdtInt " [ ~1 ] forall x1 x2 y.
efdtInt x1 x2 y = build ( \ c n - > efdtIntFB c n x1 x2 y )
" efdtIntUpList " [ 1 ] efdtIntFB ( :) [ ] = efdtInt
#
"efdtInt" [~1] forall x1 x2 y.
efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y)
"efdtIntUpList" [1] efdtIntFB (:) [] = efdtInt
#-}
efdInt :: Int# -> Int# -> [Int]
[ x1,x2 .. maxInt ]
efdInt x1 x2
| isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y
| otherwise = case minInt of I# y -> efdtIntDn x1 x2 y
# NOINLINE [ 1 ] efdtInt #
efdtInt :: Int# -> Int# -> Int# -> [Int]
[ .. y ]
efdtInt x1 x2 y
| isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y
| otherwise = efdtIntDn x1 x2 y
{-# INLINE [0] efdtIntFB #-}
efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
efdtIntFB c n x1 x2 y
| isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y
| otherwise = efdtIntDnFB c n x1 x2 y
-- Requires x2 >= x1
efdtIntUp :: Int# -> Int# -> Int# -> [Int]
efdtIntUp x1 x2 y -- Be careful about overflow!
| isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1]
| otherwise = -- Common case: x1 <= x2 <= y
> = 0
!y' = y -# delta -- x1 <= y' <= y; hence y' is representable
-- Invariant: x <= y
-- Note that: z <= y' => z + delta won't overflow
-- so we are guaranteed not to overflow if/when we recurse
go_up x | isTrue# (x ># y') = [I# x]
| otherwise = I# x : go_up (x +# delta)
in I# x1 : go_up x2
-- Requires x2 >= x1
efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
efdtIntUpFB c n x1 x2 y -- Be careful about overflow!
| isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n
| otherwise = -- Common case: x1 <= x2 <= y
> = 0
!y' = y -# delta -- x1 <= y' <= y; hence y' is representable
-- Invariant: x <= y
-- Note that: z <= y' => z + delta won't overflow
-- so we are guaranteed not to overflow if/when we recurse
go_up x | isTrue# (x ># y') = I# x `c` n
| otherwise = I# x `c` go_up (x +# delta)
in I# x1 `c` go_up x2
-- Requires x2 <= x1
efdtIntDn :: Int# -> Int# -> Int# -> [Int]
efdtIntDn x1 x2 y -- Be careful about underflow!
| isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1]
| otherwise = -- Common case: x1 >= x2 >= y
< = 0
!y' = y -# delta -- y <= y' <= x1; hence y' is representable
-- Invariant: x >= y
-- Note that: z >= y' => z + delta won't underflow
-- so we are guaranteed not to underflow if/when we recurse
go_dn x | isTrue# (x <# y') = [I# x]
| otherwise = I# x : go_dn (x +# delta)
in I# x1 : go_dn x2
-- Requires x2 <= x1
efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
efdtIntDnFB c n x1 x2 y -- Be careful about underflow!
| isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n
| otherwise = -- Common case: x1 >= x2 >= y
< = 0
!y' = y -# delta -- y <= y' <= x1; hence y' is representable
-- Invariant: x >= y
-- Note that: z >= y' => z + delta won't underflow
-- so we are guaranteed not to underflow if/when we recurse
go_dn x | isTrue# (x <# y') = I# x `c` n
| otherwise = I# x `c` go_dn (x +# delta)
in I# x1 `c` go_dn x2
------------------------------------------------------------------------
Word
------------------------------------------------------------------------
instance Bounded Word where
minBound = 0
use unboxed literals for maxBound , because GHC does n't optimise
( fromInteger 0xffffffff : : Word ) .
#if WORD_SIZE_IN_BITS == 32
maxBound = W# (int2Word# 0xFFFFFFFF#)
#elif WORD_SIZE_IN_BITS == 64
maxBound = W# (int2Word# 0xFFFFFFFFFFFFFFFF#)
#else
#error Unhandled value for WORD_SIZE_IN_BITS
#endif
instance Enum Word where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word"
toEnum i@(I# i#)
| i >= 0 = W# (int2Word# i#)
| otherwise = toEnumError "Word" i (minBound::Word, maxBound::Word)
fromEnum x@(W# x#)
| x <= maxIntWord = I# (word2Int# x#)
| otherwise = fromEnumError "Word" x
enumFrom n = map integerToWordX [wordToIntegerX n .. wordToIntegerX (maxBound :: Word)]
enumFromTo n1 n2 = map integerToWordX [wordToIntegerX n1 .. wordToIntegerX n2]
enumFromThenTo n1 n2 m = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX m]
enumFromThen n1 n2 = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX limit]
where
limit :: Word
limit | n2 >= n1 = maxBound
| otherwise = minBound
maxIntWord :: Word
-- The biggest word representable as an Int
maxIntWord = W# (case maxInt of I# i -> int2Word# i)
-- For some reason integerToWord and wordToInteger (GHC.Integer.Type)
-- work over Word#
integerToWordX :: Integer -> Word
integerToWordX i = W# (integerToWord i)
wordToIntegerX :: Word -> Integer
wordToIntegerX (W# x#) = wordToInteger x#
------------------------------------------------------------------------
Integer
------------------------------------------------------------------------
instance Enum Integer where
succ x = x + 1
pred x = x - 1
toEnum (I# n) = smallInteger n
fromEnum n = I# (integerToInt n)
# INLINE enumFrom #
# INLINE enumFromThen #
# INLINE enumFromTo #
{-# INLINE enumFromThenTo #-}
enumFrom x = enumDeltaInteger x 1
enumFromThen x y = enumDeltaInteger x (y-x)
enumFromTo x lim = enumDeltaToInteger x 1 lim
enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
# RULES
" enumDeltaInteger " [ ~1 ] forall x y. enumDeltaInteger x y = build ( \c _ - > enumDeltaIntegerFB c x y )
" efdtInteger " [ ~1 ] forall x y l.enumDeltaToInteger x y l = build ( \c n - > enumDeltaToIntegerFB c n x y l )
" enumDeltaInteger " [ 1 ] enumDeltaIntegerFB ( :) = enumDeltaInteger
" enumDeltaToInteger " [ 1 ] enumDeltaToIntegerFB ( :) [ ] = enumDeltaToInteger
#
"enumDeltaInteger" [~1] forall x y. enumDeltaInteger x y = build (\c _ -> enumDeltaIntegerFB c x y)
"efdtInteger" [~1] forall x y l.enumDeltaToInteger x y l = build (\c n -> enumDeltaToIntegerFB c n x y l)
"enumDeltaInteger" [1] enumDeltaIntegerFB (:) = enumDeltaInteger
"enumDeltaToInteger" [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger
#-}
{-# NOINLINE [0] enumDeltaIntegerFB #-}
enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b
enumDeltaIntegerFB c x d = x `seq` (x `c` enumDeltaIntegerFB c (x+d) d)
# NOINLINE [ 1 ] enumDeltaInteger #
enumDeltaInteger :: Integer -> Integer -> [Integer]
enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d)
-- strict accumulator, so
head ( drop 1000000 [ 1 .. ]
-- works
{-# NOINLINE [0] enumDeltaToIntegerFB #-}
-- Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
enumDeltaToIntegerFB :: (Integer -> a -> a) -> a
-> Integer -> Integer -> Integer -> a
enumDeltaToIntegerFB c n x delta lim
| delta >= 0 = up_fb c n x delta lim
| otherwise = dn_fb c n x delta lim
# RULES
" enumDeltaToInteger1 " [ 0 ] forall c n x . enumDeltaToIntegerFB c n x 1 = up_fb c n x 1
#
"enumDeltaToInteger1" [0] forall c n x . enumDeltaToIntegerFB c n x 1 = up_fb c n x 1
#-}
This rule ensures that in the common case ( delta = 1 ) , we do not do the check here ,
-- and also that we have the chance to inline up_fb, which would allow the constructor to be
-- inlined and good things to happen.
-- We do not do it for Int this way because hand-tuned code already exists, and
-- the special case varies more from the general case, due to the issue of overflows.
# NOINLINE [ 1 ] enumDeltaToInteger #
enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer]
enumDeltaToInteger x delta lim
| delta >= 0 = up_list x delta lim
| otherwise = dn_list x delta lim
up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
up_fb c n x0 delta lim = go (x0 :: Integer)
where
go x | x > lim = n
| otherwise = x `c` go (x+delta)
dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
dn_fb c n x0 delta lim = go (x0 :: Integer)
where
go x | x < lim = n
| otherwise = x `c` go (x+delta)
up_list :: Integer -> Integer -> Integer -> [Integer]
up_list x0 delta lim = go (x0 :: Integer)
where
go x | x > lim = []
| otherwise = x : go (x+delta)
dn_list :: Integer -> Integer -> Integer -> [Integer]
dn_list x0 delta lim = go (x0 :: Integer)
where
go x | x < lim = []
| otherwise = x : go (x+delta)
| null | https://raw.githubusercontent.com/ghcjs/ghcjs-boot/8c549931da27ba9e607f77195208ec156c840c8a/boot/base/GHC/Enum.hs | haskell | # OPTIONS_HADDOCK hide #
---------------------------------------------------------------------------
|
License : see libraries/base/LICENSE
Maintainer :
Stability : internal
---------------------------------------------------------------------------
Double isn't available yet
| The 'Bounded' class is used to name the upper and lower limits of a
totally ordered may also have upper and lower bounds.
'Bounded' may also be derived for single-constructor datatypes whose
constituent types are in 'Bounded'.
arithmetic sequences.
whose constructors have no fields). The nullary constructors are
the following should hold:
a runtime error.
* 'fromEnum' and 'toEnum' should give a runtime error if the
result value is not representable in the result type.
* 'enumFrom' and 'enumFromThen' should be defined with an implicit bound,
thus:
> where
| Convert from an 'Int'.
| Convert to an 'Int'.
It is implementation-dependent what 'fromEnum' returns when
applied to a value that is too large to fit in an 'Int'.
Default methods for bounded enumerations
----------------------------------------------------------------------
Helper functions
----------------------------------------------------------------------
# NOINLINE toEnumError #
# NOINLINE fromEnumError #
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Bool
----------------------------------------------------------------------
Use defaults for the rest
----------------------------------------------------------------------
Ordering
----------------------------------------------------------------------
Use defaults for the rest
----------------------------------------------------------------------
Char
----------------------------------------------------------------------
Blarg: technically I guess enumFrom isn't strict!
# INLINE enumFromThenTo #
# INLINE [0] eftCharFB #
For enumFromThenTo we give up on inlining
# NOINLINE [0] efdCharFB #
# NOINLINE [0] efdtCharFB #
# NOINLINE [1] efdtChar #
----------------------------------------------------------------------
Int
----------------------------------------------------------------------
Blarg: technically I guess enumFrom isn't strict!
# INLINE enumFromThenTo #
---------------------------------------------------
most common form, so we take a lot of care
In particular, we have rules for deforestation
[x1..x2]
# INLINE [0] eftIntFB #
so that when eftInfFB is inlined we can inline
whatever is bound to "c"
---------------------------------------------------
efdInt and efdtInt deal with [a,b..] and [a,b..c].
The code is more complicated because of worries about Int overflow.
# INLINE [0] efdtIntFB #
Requires x2 >= x1
Be careful about overflow!
Common case: x1 <= x2 <= y
x1 <= y' <= y; hence y' is representable
Invariant: x <= y
Note that: z <= y' => z + delta won't overflow
so we are guaranteed not to overflow if/when we recurse
Requires x2 >= x1
Be careful about overflow!
Common case: x1 <= x2 <= y
x1 <= y' <= y; hence y' is representable
Invariant: x <= y
Note that: z <= y' => z + delta won't overflow
so we are guaranteed not to overflow if/when we recurse
Requires x2 <= x1
Be careful about underflow!
Common case: x1 >= x2 >= y
y <= y' <= x1; hence y' is representable
Invariant: x >= y
Note that: z >= y' => z + delta won't underflow
so we are guaranteed not to underflow if/when we recurse
Requires x2 <= x1
Be careful about underflow!
Common case: x1 >= x2 >= y
y <= y' <= x1; hence y' is representable
Invariant: x >= y
Note that: z >= y' => z + delta won't underflow
so we are guaranteed not to underflow if/when we recurse
----------------------------------------------------------------------
----------------------------------------------------------------------
The biggest word representable as an Int
For some reason integerToWord and wordToInteger (GHC.Integer.Type)
work over Word#
----------------------------------------------------------------------
----------------------------------------------------------------------
# INLINE enumFromThenTo #
# NOINLINE [0] enumDeltaIntegerFB #
strict accumulator, so
works
# NOINLINE [0] enumDeltaToIntegerFB #
Don't inline this until RULE "enumDeltaToInteger" has had a chance to fire
and also that we have the chance to inline up_fb, which would allow the constructor to be
inlined and good things to happen.
We do not do it for Int this way because hand-tuned code already exists, and
the special case varies more from the general case, due to the issue of overflows. | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , BangPatterns , MagicHash #
Module :
Copyright : ( c ) The University of Glasgow , 1992 - 2002
Portability : non - portable ( GHC extensions )
The ' ' and ' Bounded ' classes .
#include "MachDeps.h"
module GHC.Enum(
Bounded(..), Enum(..),
boundedEnumFrom, boundedEnumFromThen,
toEnumError, fromEnumError, succError, predError,
Instances for Bounded and : ( ) , , Int
) where
import GHC.Base hiding ( many )
import GHC.Char
import GHC.Integer
import GHC.Num
import GHC.Show
type . ' ' is not a superclass of ' Bounded ' since types that are not
The ' Bounded ' class may be derived for any enumeration type ;
' ' is the first constructor listed in the @data@ declaration
and ' maxBound ' is the last .
class Bounded a where
minBound, maxBound :: a
| Class ' ' defines operations on sequentially ordered types .
The @enumFrom@ ... methods are used in 's translation of
Instances of ' ' may be derived for any enumeration type ( types
assumed to be numbered left - to - right by ' fromEnum ' from @0@ through @n-1@.
See Chapter 10 of the /Haskell Report/ for more details .
For any type that is an instance of class ' Bounded ' as well as ' ' ,
* The calls @'succ ' ' maxBound'@ and @'pred ' ' minBound'@ should result in
For example , @'toEnum ' 7 : : ' Bool'@ is an error .
> enumFrom x = enumFromTo x maxBound
> enumFromThen x y = enumFromThenTo x y bound
> bound | fromEnum y > = fromEnum x = maxBound
> | otherwise =
class Enum a where
| the successor of a value . For numeric types , ' succ ' adds 1 .
succ :: a -> a
| the predecessor of a value . For numeric types , ' pred ' subtracts 1 .
pred :: a -> a
toEnum :: Int -> a
fromEnum :: a -> Int
| Used in Haskell 's translation of @[n .. ]@.
enumFrom :: a -> [a]
| Used in Haskell 's translation of @[n , n' .. ]@.
enumFromThen :: a -> a -> [a]
| Used in Haskell 's translation of @[n .. m]@.
enumFromTo :: a -> a -> [a]
| Used in Haskell 's translation of @[n , n' .. m]@.
enumFromThenTo :: a -> a -> a -> [a]
succ = toEnum . (+ 1) . fromEnum
pred = toEnum . (subtract 1) . fromEnum
enumFrom x = map toEnum [fromEnum x ..]
enumFromThen x y = map toEnum [fromEnum x, fromEnum y ..]
enumFromTo x y = map toEnum [fromEnum x .. fromEnum y]
enumFromThenTo x1 x2 y = map toEnum [fromEnum x1, fromEnum x2 .. fromEnum y]
boundedEnumFrom :: (Enum a, Bounded a) => a -> [a]
boundedEnumFrom n = map toEnum [fromEnum n .. fromEnum (maxBound `asTypeOf` n)]
boundedEnumFromThen :: (Enum a, Bounded a) => a -> a -> [a]
boundedEnumFromThen n1 n2
| i_n2 >= i_n1 = map toEnum [i_n1, i_n2 .. fromEnum (maxBound `asTypeOf` n1)]
| otherwise = map toEnum [i_n1, i_n2 .. fromEnum (minBound `asTypeOf` n1)]
where
i_n1 = fromEnum n1
i_n2 = fromEnum n2
toEnumError :: (Show a) => String -> Int -> (a,a) -> b
toEnumError inst_ty i bnds =
error $ "Enum.toEnum{" ++ inst_ty ++ "}: tag (" ++
show i ++
") is outside of bounds " ++
show bnds
fromEnumError :: (Show a) => String -> a -> b
fromEnumError inst_ty x =
error $ "Enum.fromEnum{" ++ inst_ty ++ "}: value (" ++
show x ++
") is outside of Int's bounds " ++
show (minBound::Int, maxBound::Int)
# NOINLINE succError #
succError :: String -> a
succError inst_ty =
error $ "Enum.succ{" ++ inst_ty ++ "}: tried to take `succ' of maxBound"
# NOINLINE predError #
predError :: String -> a
predError inst_ty =
error $ "Enum.pred{" ++ inst_ty ++ "}: tried to take `pred' of minBound"
Tuples
instance Bounded () where
minBound = ()
maxBound = ()
instance Enum () where
succ _ = error "Prelude.Enum.().succ: bad argument"
pred _ = error "Prelude.Enum.().pred: bad argument"
toEnum x | x == 0 = ()
| otherwise = error "Prelude.Enum.().toEnum: bad argument"
fromEnum () = 0
enumFrom () = [()]
enumFromThen () () = let many = ():many in many
enumFromTo () () = [()]
enumFromThenTo () () () = let many = ():many in many
Report requires instances up to 15
instance (Bounded a, Bounded b) => Bounded (a,b) where
minBound = (minBound, minBound)
maxBound = (maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where
minBound = (minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where
minBound = (minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e) => Bounded (a,b,c,d,e) where
minBound = (minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f)
=> Bounded (a,b,c,d,e,f) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g)
=> Bounded (a,b,c,d,e,f,g) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h)
=> Bounded (a,b,c,d,e,f,g,h) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i)
=> Bounded (a,b,c,d,e,f,g,h,i) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j)
=> Bounded (a,b,c,d,e,f,g,h,i,j) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance (Bounded a, Bounded b, Bounded c, Bounded d, Bounded e, Bounded f, Bounded g,
Bounded h, Bounded i, Bounded j, Bounded k, Bounded l, Bounded m, Bounded n, Bounded o)
=> Bounded (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o) where
minBound = (minBound, minBound, minBound, minBound, minBound, minBound, minBound, minBound,
minBound, minBound, minBound, minBound, minBound, minBound, minBound)
maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound,
maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
instance Bounded Bool where
minBound = False
maxBound = True
instance Enum Bool where
succ False = True
succ True = error "Prelude.Enum.Bool.succ: bad argument"
pred True = False
pred False = error "Prelude.Enum.Bool.pred: bad argument"
toEnum n | n == 0 = False
| n == 1 = True
| otherwise = error "Prelude.Enum.Bool.toEnum: bad argument"
fromEnum False = 0
fromEnum True = 1
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Bounded Ordering where
minBound = LT
maxBound = GT
instance Enum Ordering where
succ LT = EQ
succ EQ = GT
succ GT = error "Prelude.Enum.Ordering.succ: bad argument"
pred GT = EQ
pred EQ = LT
pred LT = error "Prelude.Enum.Ordering.pred: bad argument"
toEnum n | n == 0 = LT
| n == 1 = EQ
| n == 2 = GT
toEnum _ = error "Prelude.Enum.Ordering.toEnum: bad argument"
fromEnum LT = 0
fromEnum EQ = 1
fromEnum GT = 2
enumFrom = boundedEnumFrom
enumFromThen = boundedEnumFromThen
instance Bounded Char where
minBound = '\0'
maxBound = '\x10FFFF'
instance Enum Char where
succ (C# c#)
| isTrue# (ord# c# /=# 0x10FFFF#) = C# (chr# (ord# c# +# 1#))
| otherwise = error ("Prelude.Enum.Char.succ: bad argument")
pred (C# c#)
| isTrue# (ord# c# /=# 0#) = C# (chr# (ord# c# -# 1#))
| otherwise = error ("Prelude.Enum.Char.pred: bad argument")
toEnum = chr
fromEnum = ord
# INLINE enumFrom #
enumFrom (C# x) = eftChar (ord# x) 0x10FFFF#
# INLINE enumFromTo #
enumFromTo (C# x) (C# y) = eftChar (ord# x) (ord# y)
# INLINE enumFromThen #
enumFromThen (C# x1) (C# x2) = efdChar (ord# x1) (ord# x2)
enumFromThenTo (C# x1) (C# x2) (C# y) = efdtChar (ord# x1) (ord# x2) (ord# y)
# RULES
" eftChar " [ ~1 ] forall x y. eftChar x y = build ( \c n - > eftCharFB c n x y )
" efdChar " [ ~1 ] forall x1 x2 . efdChar x1 x2 = build ( \ c n - > efdCharFB c n x1 x2 )
" efdtChar " [ ~1 ] forall x1 x2 l. efdtChar x1 x2 l = build ( \ c n - > efdtCharFB c n x1 x2 l )
" eftCharList " [ 1 ] eftCharFB ( :) [ ] = eftChar
" efdCharList " [ 1 ] efdCharFB ( :) [ ] = efdChar
" efdtCharList " [ 1 ] efdtCharFB ( :) [ ] = efdtChar
#
"eftChar" [~1] forall x y. eftChar x y = build (\c n -> eftCharFB c n x y)
"efdChar" [~1] forall x1 x2. efdChar x1 x2 = build (\ c n -> efdCharFB c n x1 x2)
"efdtChar" [~1] forall x1 x2 l. efdtChar x1 x2 l = build (\ c n -> efdtCharFB c n x1 x2 l)
"eftCharList" [1] eftCharFB (:) [] = eftChar
"efdCharList" [1] efdCharFB (:) [] = efdChar
"efdtCharList" [1] efdtCharFB (:) [] = efdtChar
#-}
We can do better than for because we do n't
have hassles about arithmetic overflow at maxBound
eftCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
eftCharFB c n x0 y = go x0
where
go x | isTrue# (x ># y) = n
| otherwise = C# (chr# x) `c` go (x +# 1#)
# NOINLINE [ 1 ] eftChar #
eftChar :: Int# -> Int# -> String
eftChar x y | isTrue# (x ># y ) = []
| otherwise = C# (chr# x) : eftChar (x +# 1#) y
efdCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> a
efdCharFB c n x1 x2
| isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta 0x10FFFF#
| otherwise = go_dn_char_fb c n x1 delta 0#
where
!delta = x2 -# x1
# NOINLINE [ 1 ] efdChar #
efdChar :: Int# -> Int# -> String
efdChar x1 x2
| isTrue# (delta >=# 0#) = go_up_char_list x1 delta 0x10FFFF#
| otherwise = go_dn_char_list x1 delta 0#
where
!delta = x2 -# x1
efdtCharFB :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
efdtCharFB c n x1 x2 lim
| isTrue# (delta >=# 0#) = go_up_char_fb c n x1 delta lim
| otherwise = go_dn_char_fb c n x1 delta lim
where
!delta = x2 -# x1
efdtChar :: Int# -> Int# -> Int# -> String
efdtChar x1 x2 lim
| isTrue# (delta >=# 0#) = go_up_char_list x1 delta lim
| otherwise = go_dn_char_list x1 delta lim
where
!delta = x2 -# x1
go_up_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
go_up_char_fb c n x0 delta lim
= go_up x0
where
go_up x | isTrue# (x ># lim) = n
| otherwise = C# (chr# x) `c` go_up (x +# delta)
go_dn_char_fb :: (Char -> a -> a) -> a -> Int# -> Int# -> Int# -> a
go_dn_char_fb c n x0 delta lim
= go_dn x0
where
go_dn x | isTrue# (x <# lim) = n
| otherwise = C# (chr# x) `c` go_dn (x +# delta)
go_up_char_list :: Int# -> Int# -> Int# -> String
go_up_char_list x0 delta lim
= go_up x0
where
go_up x | isTrue# (x ># lim) = []
| otherwise = C# (chr# x) : go_up (x +# delta)
go_dn_char_list :: Int# -> Int# -> Int# -> String
go_dn_char_list x0 delta lim
= go_dn x0
where
go_dn x | isTrue# (x <# lim) = []
| otherwise = C# (chr# x) : go_dn (x +# delta)
Be careful about these instances .
( a ) remember that you have to count down as well as up e.g. [ 13,12 .. 0 ]
( b ) be careful of Int overflow
( c ) remember that is bounded , so [ 1 .. ] terminates at maxInt
Be careful about these instances.
(a) remember that you have to count down as well as up e.g. [13,12..0]
(b) be careful of Int overflow
(c) remember that Int is bounded, so [1..] terminates at maxInt
-}
instance Bounded Int where
minBound = minInt
maxBound = maxInt
instance Enum Int where
succ x
| x == maxBound = error "Prelude.Enum.succ{Int}: tried to take `succ' of maxBound"
| otherwise = x + 1
pred x
| x == minBound = error "Prelude.Enum.pred{Int}: tried to take `pred' of minBound"
| otherwise = x - 1
toEnum x = x
fromEnum x = x
# INLINE enumFrom #
enumFrom (I# x) = eftInt x maxInt#
where !(I# maxInt#) = maxInt
# INLINE enumFromTo #
enumFromTo (I# x) (I# y) = eftInt x y
# INLINE enumFromThen #
enumFromThen (I# x1) (I# x2) = efdInt x1 x2
enumFromThenTo (I# x1) (I# x2) (I# y) = efdtInt x1 x2 y
eftInt and eftIntFB deal with [ a .. b ] , which is the
# RULES
" eftInt " [ ~1 ] forall x y. eftInt x y = build ( \ c n - > eftIntFB c n x y )
" eftIntList " [ 1 ] eftIntFB ( :) [ ] = eftInt
#
"eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
"eftIntList" [1] eftIntFB (:) [] = eftInt
#-}
# NOINLINE [ 1 ] eftInt #
eftInt :: Int# -> Int# -> [Int]
eftInt x0 y | isTrue# (x0 ># y) = []
| otherwise = go x0
where
go x = I# x : if isTrue# (x ==# y)
then []
else go (x +# 1#)
eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
eftIntFB c n x0 y | isTrue# (x0 ># y) = n
| otherwise = go x0
where
go x = I# x `c` if isTrue# (x ==# y)
then n
else go (x +# 1#)
Watch out for y = maxBound ; hence = = , not >
Be very careful not to have more than one " c "
# RULES
" efdtInt " [ ~1 ] forall x1 x2 y.
efdtInt x1 x2 y = build ( \ c n - > efdtIntFB c n x1 x2 y )
" efdtIntUpList " [ 1 ] efdtIntFB ( :) [ ] = efdtInt
#
"efdtInt" [~1] forall x1 x2 y.
efdtInt x1 x2 y = build (\ c n -> efdtIntFB c n x1 x2 y)
"efdtIntUpList" [1] efdtIntFB (:) [] = efdtInt
#-}
efdInt :: Int# -> Int# -> [Int]
[ x1,x2 .. maxInt ]
efdInt x1 x2
| isTrue# (x2 >=# x1) = case maxInt of I# y -> efdtIntUp x1 x2 y
| otherwise = case minInt of I# y -> efdtIntDn x1 x2 y
# NOINLINE [ 1 ] efdtInt #
efdtInt :: Int# -> Int# -> Int# -> [Int]
[ .. y ]
efdtInt x1 x2 y
| isTrue# (x2 >=# x1) = efdtIntUp x1 x2 y
| otherwise = efdtIntDn x1 x2 y
efdtIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
efdtIntFB c n x1 x2 y
| isTrue# (x2 >=# x1) = efdtIntUpFB c n x1 x2 y
| otherwise = efdtIntDnFB c n x1 x2 y
efdtIntUp :: Int# -> Int# -> Int# -> [Int]
| isTrue# (y <# x2) = if isTrue# (y <# x1) then [] else [I# x1]
> = 0
go_up x | isTrue# (x ># y') = [I# x]
| otherwise = I# x : go_up (x +# delta)
in I# x1 : go_up x2
efdtIntUpFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
| isTrue# (y <# x2) = if isTrue# (y <# x1) then n else I# x1 `c` n
> = 0
go_up x | isTrue# (x ># y') = I# x `c` n
| otherwise = I# x `c` go_up (x +# delta)
in I# x1 `c` go_up x2
efdtIntDn :: Int# -> Int# -> Int# -> [Int]
| isTrue# (y ># x2) = if isTrue# (y ># x1) then [] else [I# x1]
< = 0
go_dn x | isTrue# (x <# y') = [I# x]
| otherwise = I# x : go_dn (x +# delta)
in I# x1 : go_dn x2
efdtIntDnFB :: (Int -> r -> r) -> r -> Int# -> Int# -> Int# -> r
| isTrue# (y ># x2) = if isTrue# (y ># x1) then n else I# x1 `c` n
< = 0
go_dn x | isTrue# (x <# y') = I# x `c` n
| otherwise = I# x `c` go_dn (x +# delta)
in I# x1 `c` go_dn x2
Word
instance Bounded Word where
minBound = 0
use unboxed literals for maxBound , because GHC does n't optimise
( fromInteger 0xffffffff : : Word ) .
#if WORD_SIZE_IN_BITS == 32
maxBound = W# (int2Word# 0xFFFFFFFF#)
#elif WORD_SIZE_IN_BITS == 64
maxBound = W# (int2Word# 0xFFFFFFFFFFFFFFFF#)
#else
#error Unhandled value for WORD_SIZE_IN_BITS
#endif
instance Enum Word where
succ x
| x /= maxBound = x + 1
| otherwise = succError "Word"
pred x
| x /= minBound = x - 1
| otherwise = predError "Word"
toEnum i@(I# i#)
| i >= 0 = W# (int2Word# i#)
| otherwise = toEnumError "Word" i (minBound::Word, maxBound::Word)
fromEnum x@(W# x#)
| x <= maxIntWord = I# (word2Int# x#)
| otherwise = fromEnumError "Word" x
enumFrom n = map integerToWordX [wordToIntegerX n .. wordToIntegerX (maxBound :: Word)]
enumFromTo n1 n2 = map integerToWordX [wordToIntegerX n1 .. wordToIntegerX n2]
enumFromThenTo n1 n2 m = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX m]
enumFromThen n1 n2 = map integerToWordX [wordToIntegerX n1, wordToIntegerX n2 .. wordToIntegerX limit]
where
limit :: Word
limit | n2 >= n1 = maxBound
| otherwise = minBound
maxIntWord :: Word
maxIntWord = W# (case maxInt of I# i -> int2Word# i)
integerToWordX :: Integer -> Word
integerToWordX i = W# (integerToWord i)
wordToIntegerX :: Word -> Integer
wordToIntegerX (W# x#) = wordToInteger x#
Integer
instance Enum Integer where
succ x = x + 1
pred x = x - 1
toEnum (I# n) = smallInteger n
fromEnum n = I# (integerToInt n)
# INLINE enumFrom #
# INLINE enumFromThen #
# INLINE enumFromTo #
enumFrom x = enumDeltaInteger x 1
enumFromThen x y = enumDeltaInteger x (y-x)
enumFromTo x lim = enumDeltaToInteger x 1 lim
enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
# RULES
" enumDeltaInteger " [ ~1 ] forall x y. enumDeltaInteger x y = build ( \c _ - > enumDeltaIntegerFB c x y )
" efdtInteger " [ ~1 ] forall x y l.enumDeltaToInteger x y l = build ( \c n - > enumDeltaToIntegerFB c n x y l )
" enumDeltaInteger " [ 1 ] enumDeltaIntegerFB ( :) = enumDeltaInteger
" enumDeltaToInteger " [ 1 ] enumDeltaToIntegerFB ( :) [ ] = enumDeltaToInteger
#
"enumDeltaInteger" [~1] forall x y. enumDeltaInteger x y = build (\c _ -> enumDeltaIntegerFB c x y)
"efdtInteger" [~1] forall x y l.enumDeltaToInteger x y l = build (\c n -> enumDeltaToIntegerFB c n x y l)
"enumDeltaInteger" [1] enumDeltaIntegerFB (:) = enumDeltaInteger
"enumDeltaToInteger" [1] enumDeltaToIntegerFB (:) [] = enumDeltaToInteger
#-}
enumDeltaIntegerFB :: (Integer -> b -> b) -> Integer -> Integer -> b
enumDeltaIntegerFB c x d = x `seq` (x `c` enumDeltaIntegerFB c (x+d) d)
# NOINLINE [ 1 ] enumDeltaInteger #
enumDeltaInteger :: Integer -> Integer -> [Integer]
enumDeltaInteger x d = x `seq` (x : enumDeltaInteger (x+d) d)
head ( drop 1000000 [ 1 .. ]
enumDeltaToIntegerFB :: (Integer -> a -> a) -> a
-> Integer -> Integer -> Integer -> a
enumDeltaToIntegerFB c n x delta lim
| delta >= 0 = up_fb c n x delta lim
| otherwise = dn_fb c n x delta lim
# RULES
" enumDeltaToInteger1 " [ 0 ] forall c n x . enumDeltaToIntegerFB c n x 1 = up_fb c n x 1
#
"enumDeltaToInteger1" [0] forall c n x . enumDeltaToIntegerFB c n x 1 = up_fb c n x 1
#-}
This rule ensures that in the common case ( delta = 1 ) , we do not do the check here ,
# NOINLINE [ 1 ] enumDeltaToInteger #
enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer]
enumDeltaToInteger x delta lim
| delta >= 0 = up_list x delta lim
| otherwise = dn_list x delta lim
up_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
up_fb c n x0 delta lim = go (x0 :: Integer)
where
go x | x > lim = n
| otherwise = x `c` go (x+delta)
dn_fb :: (Integer -> a -> a) -> a -> Integer -> Integer -> Integer -> a
dn_fb c n x0 delta lim = go (x0 :: Integer)
where
go x | x < lim = n
| otherwise = x `c` go (x+delta)
up_list :: Integer -> Integer -> Integer -> [Integer]
up_list x0 delta lim = go (x0 :: Integer)
where
go x | x > lim = []
| otherwise = x : go (x+delta)
dn_list :: Integer -> Integer -> Integer -> [Integer]
dn_list x0 delta lim = go (x0 :: Integer)
where
go x | x < lim = []
| otherwise = x : go (x+delta)
|
648f03cc29987a68f7eb8ce47d593159efefc4eefcebb289f3e4681ec0d2323b | evilmartians/foundry | pa_utf8str.ml | open Camlp4
module Id = struct
let name = "pa_utf8str"
let version = "1.0"
end
module Make (Syntax : Sig.Camlp4Syntax) = struct
open Sig
include Syntax
EXTEND Gram
GLOBAL: expr;
expr: LEVEL "simple"
[ [ s = STRING ->
<:expr< (Unicode.assert_utf8s $str:s$) >>
| c = CHAR ->
<:expr< (Unicode.utf32_of_utf8s (Unicode.assert_utf8s $str:c$)) >>
] ]
;
END
end
let module M = Register.OCamlSyntaxExtension(Id) (Make) in ()
| null | https://raw.githubusercontent.com/evilmartians/foundry/ce947c7dcca79ab7a7ce25870e9fc0eb15e9c2bd/vendor/ucs/lib/pa_utf8str.ml | ocaml | open Camlp4
module Id = struct
let name = "pa_utf8str"
let version = "1.0"
end
module Make (Syntax : Sig.Camlp4Syntax) = struct
open Sig
include Syntax
EXTEND Gram
GLOBAL: expr;
expr: LEVEL "simple"
[ [ s = STRING ->
<:expr< (Unicode.assert_utf8s $str:s$) >>
| c = CHAR ->
<:expr< (Unicode.utf32_of_utf8s (Unicode.assert_utf8s $str:c$)) >>
] ]
;
END
end
let module M = Register.OCamlSyntaxExtension(Id) (Make) in ()
|
|
6157a9cb3b93c931a27bcfb901e123bf7dca12dbed8769b3c0b30d5b6ca76f1c | clojurians-org/haskell-example | APICommon.hs | --
MinIO Haskell SDK , ( C ) 2018 MinIO , Inc.
--
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 Network.Minio.APICommon where
import Data.Conduit.Binary (sourceHandleRange)
import qualified Network.HTTP.Conduit as NC
import qualified Network.HTTP.Types as HT
import Lib.Prelude
import Network.Minio.Data
import Network.Minio.Data.Crypto
sha256Header :: ByteString -> HT.Header
sha256Header = ("x-amz-content-sha256", )
getPayloadSHA256Hash :: (MonadIO m) => Payload -> m ByteString
getPayloadSHA256Hash (PayloadBS bs) = return $ hashSHA256 bs
getPayloadSHA256Hash (PayloadH h off size) = hashSHA256FromSource $
sourceHandleRange h
(return . fromIntegral $ off)
(return . fromIntegral $ size)
getRequestBody :: Payload -> NC.RequestBody
getRequestBody (PayloadBS bs) = NC.RequestBodyBS bs
getRequestBody (PayloadH h off size) =
NC.requestBodySource (fromIntegral size) $
sourceHandleRange h
(return . fromIntegral $ off)
(return . fromIntegral $ size)
| null | https://raw.githubusercontent.com/clojurians-org/haskell-example/c96b021bdef52a121e04ea203c8c3e458770a25a/minio-migration/src/Network/Minio/APICommon.hs | haskell |
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.
| MinIO Haskell SDK , ( C ) 2018 MinIO , Inc.
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
module Network.Minio.APICommon where
import Data.Conduit.Binary (sourceHandleRange)
import qualified Network.HTTP.Conduit as NC
import qualified Network.HTTP.Types as HT
import Lib.Prelude
import Network.Minio.Data
import Network.Minio.Data.Crypto
sha256Header :: ByteString -> HT.Header
sha256Header = ("x-amz-content-sha256", )
getPayloadSHA256Hash :: (MonadIO m) => Payload -> m ByteString
getPayloadSHA256Hash (PayloadBS bs) = return $ hashSHA256 bs
getPayloadSHA256Hash (PayloadH h off size) = hashSHA256FromSource $
sourceHandleRange h
(return . fromIntegral $ off)
(return . fromIntegral $ size)
getRequestBody :: Payload -> NC.RequestBody
getRequestBody (PayloadBS bs) = NC.RequestBodyBS bs
getRequestBody (PayloadH h off size) =
NC.requestBodySource (fromIntegral size) $
sourceHandleRange h
(return . fromIntegral $ off)
(return . fromIntegral $ size)
|
05ab1364173d0a0ba1d16af33f0bfa53be784208885766e9bebe7cc0d684ec96 | RyanGlScott/text-show-instances | Haskeline.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
|
Module : TextShow . System . Console . Haskeline
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
' TextShow ' instances for data types in the @haskeline@ library .
/Since : 2/
Module: TextShow.System.Console.Haskeline
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
'TextShow' instances for data types in the @haskeline@ library.
/Since: 2/
-}
module TextShow.System.Console.Haskeline () where
import System.Console.Haskeline (Interrupt, Prefs)
import System.Console.Haskeline.Completion (Completion)
import System.Console.Haskeline.History (History, historyLines)
import TextShow (TextShow(..), FromStringShow(..))
import TextShow.TH (deriveTextShow)
import TextShow.Utils (showbUnaryListWith)
| /Since : 2/
$(deriveTextShow ''Interrupt)
| /Since : 2/
instance TextShow Prefs where
showbPrec p = showbPrec p . FromStringShow
# INLINE showbPrec #
| /Since : 2/
$(deriveTextShow ''Completion)
| /Since : 2/
instance TextShow History where
showb = showbUnaryListWith showb 0 . historyLines
# INLINE showb #
| null | https://raw.githubusercontent.com/RyanGlScott/text-show-instances/b08f4b46466cdc3c3f3c979b7a0abf5590fa2916/src/TextShow/System/Console/Haskeline.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE TemplateHaskell #
# OPTIONS_GHC -Wno - orphans #
|
Module : TextShow . System . Console . Haskeline
Copyright : ( C ) 2014 - 2017
License : BSD - style ( see the file LICENSE )
Maintainer :
Stability : Provisional
Portability : GHC
' TextShow ' instances for data types in the @haskeline@ library .
/Since : 2/
Module: TextShow.System.Console.Haskeline
Copyright: (C) 2014-2017 Ryan Scott
License: BSD-style (see the file LICENSE)
Maintainer: Ryan Scott
Stability: Provisional
Portability: GHC
'TextShow' instances for data types in the @haskeline@ library.
/Since: 2/
-}
module TextShow.System.Console.Haskeline () where
import System.Console.Haskeline (Interrupt, Prefs)
import System.Console.Haskeline.Completion (Completion)
import System.Console.Haskeline.History (History, historyLines)
import TextShow (TextShow(..), FromStringShow(..))
import TextShow.TH (deriveTextShow)
import TextShow.Utils (showbUnaryListWith)
| /Since : 2/
$(deriveTextShow ''Interrupt)
| /Since : 2/
instance TextShow Prefs where
showbPrec p = showbPrec p . FromStringShow
# INLINE showbPrec #
| /Since : 2/
$(deriveTextShow ''Completion)
| /Since : 2/
instance TextShow History where
showb = showbUnaryListWith showb 0 . historyLines
# INLINE showb #
|
0767f502d7a3e6eeda288302c1fd17c35e5f95424cf96626ac8f61467067da13 | clojusc/meson | shell.clj | (ns meson.util.shell
"Some convenience/utility functions used for making calls in the system
shell."
(:require [clojure.java.shell :as shell]
[clojure.string :as string]
[taoensso.timbre :as log]))
(defn shell
([cmd-str]
(shell cmd-str nil nil))
([cmd-str out-fn err-fn]
(log/debug "Got command string:" cmd-str)
(let [args (string/split cmd-str #"\s")
{:keys [out err]} (apply shell/sh args)
formatted-out (str "Shell output:\n" out)
formatted-err (str "Shell error:\n" err)]
(when-not (or (nil? out) (empty? out))
(if out-fn
(out-fn formatted-out)
(log/info formatted-out)))
(when-not (or (nil? err) (empty? err))
(if err-fn
(err-fn formatted-err)
(log/error formatted-err)))
out)))
(defn shellf
[cmd-str-tmpl & format-args]
(shell (apply format (concat [cmd-str-tmpl] format-args))))
(defn shellf-silent
[cmd-str-tmpl & format-args]
(shell (apply format (concat [cmd-str-tmpl] format-args))
(constantly nil)
(constantly nil)))
| null | https://raw.githubusercontent.com/clojusc/meson/a690135bf64c967a70fd45e88bdfed1e7b847317/src/meson/util/shell.clj | clojure | (ns meson.util.shell
"Some convenience/utility functions used for making calls in the system
shell."
(:require [clojure.java.shell :as shell]
[clojure.string :as string]
[taoensso.timbre :as log]))
(defn shell
([cmd-str]
(shell cmd-str nil nil))
([cmd-str out-fn err-fn]
(log/debug "Got command string:" cmd-str)
(let [args (string/split cmd-str #"\s")
{:keys [out err]} (apply shell/sh args)
formatted-out (str "Shell output:\n" out)
formatted-err (str "Shell error:\n" err)]
(when-not (or (nil? out) (empty? out))
(if out-fn
(out-fn formatted-out)
(log/info formatted-out)))
(when-not (or (nil? err) (empty? err))
(if err-fn
(err-fn formatted-err)
(log/error formatted-err)))
out)))
(defn shellf
[cmd-str-tmpl & format-args]
(shell (apply format (concat [cmd-str-tmpl] format-args))))
(defn shellf-silent
[cmd-str-tmpl & format-args]
(shell (apply format (concat [cmd-str-tmpl] format-args))
(constantly nil)
(constantly nil)))
|
|
a6740cf4d7dd249a5f58f43986070fd691332e60b8b0f935b3ab7922120e077a | purescript/purescript | ModuleDependencies.hs | -- | Provides the ability to sort modules based on module dependencies
module Language.PureScript.ModuleDependencies
( DependencyDepth(..)
, sortModules
, ModuleGraph
, ModuleSignature(..)
, moduleSignature
) where
import Protolude hiding (head)
import Data.Array ((!))
import Data.Graph
import qualified Data.Set as S
import Language.PureScript.AST
import qualified Language.PureScript.Constants.Prim as C
import Language.PureScript.Crash
import Language.PureScript.Errors hiding (nonEmpty)
import Language.PureScript.Names
-- | A list of modules with their transitive dependencies
type ModuleGraph = [(ModuleName, [ModuleName])]
-- | A module signature for sorting dependencies.
data ModuleSignature = ModuleSignature
{ sigSourceSpan :: SourceSpan
, sigModuleName :: ModuleName
, sigImports :: [(ModuleName, SourceSpan)]
}
data DependencyDepth = Direct | Transitive
-- | Sort a collection of modules based on module dependencies.
--
-- Reports an error if the module graph contains a cycle.
sortModules
:: forall m a
. MonadError MultipleErrors m
=> DependencyDepth
-> (a -> ModuleSignature)
-> [a]
-> m ([a], ModuleGraph)
sortModules dependencyDepth toSig ms = do
let
ms' = (\m -> (m, toSig m)) <$> ms
mns = S.fromList $ map (sigModuleName . snd) ms'
verts <- parU ms' (toGraphNode mns)
ms'' <- parU (stronglyConnComp verts) toModule
let (graph, fromVertex, toVertex) = graphFromEdges verts
moduleGraph = do (_, mn, _) <- verts
let v = fromMaybe (internalError "sortModules: vertex not found") (toVertex mn)
deps = case dependencyDepth of
Direct -> graph ! v
Transitive -> reachable graph v
toKey i = case fromVertex i of (_, key, _) -> key
return (mn, filter (/= mn) (map toKey deps))
return (fst <$> ms'', moduleGraph)
where
toGraphNode :: S.Set ModuleName -> (a, ModuleSignature) -> m ((a, ModuleSignature), ModuleName, [ModuleName])
toGraphNode mns m@(_, ModuleSignature _ mn deps) = do
void . parU deps $ \(dep, pos) ->
when (dep `notElem` C.primModules && S.notMember dep mns) .
throwError
. addHint (ErrorInModule mn)
. errorMessage' pos
$ ModuleNotFound dep
pure (m, mn, map fst deps)
-- | Calculate a list of used modules based on explicit imports and qualified names.
usedModules :: Declaration -> Maybe (ModuleName, SourceSpan)
-- Regardless of whether an imported module is qualified we still need to
-- take into account its import to build an accurate list of dependencies.
usedModules (ImportDeclaration (ss, _) mn _ _) = pure (mn, ss)
usedModules _ = Nothing
-- | Convert a strongly connected component of the module graph to a module
toModule :: MonadError MultipleErrors m => SCC (a, ModuleSignature) -> m (a, ModuleSignature)
toModule (AcyclicSCC m) = return m
toModule (CyclicSCC ms) =
case nonEmpty ms of
Nothing ->
internalError "toModule: empty CyclicSCC"
Just ms' ->
throwError
. errorMessage'' (fmap (sigSourceSpan . snd) ms')
$ CycleInModules (map (sigModuleName . snd) ms')
moduleSignature :: Module -> ModuleSignature
moduleSignature (Module ss _ mn ds _) = ModuleSignature ss mn (ordNub (mapMaybe usedModules ds))
| null | https://raw.githubusercontent.com/purescript/purescript/7767c9fe45d465c8fbe18c85ae2bb62c91822c0d/src/Language/PureScript/ModuleDependencies.hs | haskell | | Provides the ability to sort modules based on module dependencies
| A list of modules with their transitive dependencies
| A module signature for sorting dependencies.
| Sort a collection of modules based on module dependencies.
Reports an error if the module graph contains a cycle.
| Calculate a list of used modules based on explicit imports and qualified names.
Regardless of whether an imported module is qualified we still need to
take into account its import to build an accurate list of dependencies.
| Convert a strongly connected component of the module graph to a module | module Language.PureScript.ModuleDependencies
( DependencyDepth(..)
, sortModules
, ModuleGraph
, ModuleSignature(..)
, moduleSignature
) where
import Protolude hiding (head)
import Data.Array ((!))
import Data.Graph
import qualified Data.Set as S
import Language.PureScript.AST
import qualified Language.PureScript.Constants.Prim as C
import Language.PureScript.Crash
import Language.PureScript.Errors hiding (nonEmpty)
import Language.PureScript.Names
type ModuleGraph = [(ModuleName, [ModuleName])]
data ModuleSignature = ModuleSignature
{ sigSourceSpan :: SourceSpan
, sigModuleName :: ModuleName
, sigImports :: [(ModuleName, SourceSpan)]
}
data DependencyDepth = Direct | Transitive
sortModules
:: forall m a
. MonadError MultipleErrors m
=> DependencyDepth
-> (a -> ModuleSignature)
-> [a]
-> m ([a], ModuleGraph)
sortModules dependencyDepth toSig ms = do
let
ms' = (\m -> (m, toSig m)) <$> ms
mns = S.fromList $ map (sigModuleName . snd) ms'
verts <- parU ms' (toGraphNode mns)
ms'' <- parU (stronglyConnComp verts) toModule
let (graph, fromVertex, toVertex) = graphFromEdges verts
moduleGraph = do (_, mn, _) <- verts
let v = fromMaybe (internalError "sortModules: vertex not found") (toVertex mn)
deps = case dependencyDepth of
Direct -> graph ! v
Transitive -> reachable graph v
toKey i = case fromVertex i of (_, key, _) -> key
return (mn, filter (/= mn) (map toKey deps))
return (fst <$> ms'', moduleGraph)
where
toGraphNode :: S.Set ModuleName -> (a, ModuleSignature) -> m ((a, ModuleSignature), ModuleName, [ModuleName])
toGraphNode mns m@(_, ModuleSignature _ mn deps) = do
void . parU deps $ \(dep, pos) ->
when (dep `notElem` C.primModules && S.notMember dep mns) .
throwError
. addHint (ErrorInModule mn)
. errorMessage' pos
$ ModuleNotFound dep
pure (m, mn, map fst deps)
usedModules :: Declaration -> Maybe (ModuleName, SourceSpan)
usedModules (ImportDeclaration (ss, _) mn _ _) = pure (mn, ss)
usedModules _ = Nothing
toModule :: MonadError MultipleErrors m => SCC (a, ModuleSignature) -> m (a, ModuleSignature)
toModule (AcyclicSCC m) = return m
toModule (CyclicSCC ms) =
case nonEmpty ms of
Nothing ->
internalError "toModule: empty CyclicSCC"
Just ms' ->
throwError
. errorMessage'' (fmap (sigSourceSpan . snd) ms')
$ CycleInModules (map (sigModuleName . snd) ms')
moduleSignature :: Module -> ModuleSignature
moduleSignature (Module ss _ mn ds _) = ModuleSignature ss mn (ordNub (mapMaybe usedModules ds))
|
e03df2840fee10fff655d4d3e5f4db0a9fbeeb8f4380a665b167f1a312c3d66c | khmelevskii/emotion-cljs | helpers.cljs | (ns emotion.helpers
(:require
[cljs-bean.core :refer [->js ->clj]]
["@emotion/react" :as emotion-react]
["@emotion/styled" :as styled]
["@emotion/cache" :default create-cache]
["@emotion/server/create-instance" :default create-emotion-server]
["react" :as react]
["react-dom/server" :as server]))
(defn render-styles [styles]
(let [cache' (create-cache #js {:key "css"})
emotion-server (create-emotion-server cache')
html (.renderToString
server
(react/createElement
(.-CacheProvider emotion-react)
(->js
{:value cache'
:children (react/createElement
(.div (.-default styled) styles))})))]
(->> html
(.extractCritical emotion-server)
.-css)))
(defn render-component [component props]
(let [cache' (create-cache #js {:key "css"})
emotion-server (create-emotion-server cache')
html (.renderToString
server
(react/createElement
(.-CacheProvider emotion-react)
(->js
{:value cache'
:children (react/createElement
component
(->js props))})))]
(->clj
(.extractCritical emotion-server html))))
| null | https://raw.githubusercontent.com/khmelevskii/emotion-cljs/4baaccfa19c0808e11f3a8e838f62ac6382b8860/test/emotion/helpers.cljs | clojure | (ns emotion.helpers
(:require
[cljs-bean.core :refer [->js ->clj]]
["@emotion/react" :as emotion-react]
["@emotion/styled" :as styled]
["@emotion/cache" :default create-cache]
["@emotion/server/create-instance" :default create-emotion-server]
["react" :as react]
["react-dom/server" :as server]))
(defn render-styles [styles]
(let [cache' (create-cache #js {:key "css"})
emotion-server (create-emotion-server cache')
html (.renderToString
server
(react/createElement
(.-CacheProvider emotion-react)
(->js
{:value cache'
:children (react/createElement
(.div (.-default styled) styles))})))]
(->> html
(.extractCritical emotion-server)
.-css)))
(defn render-component [component props]
(let [cache' (create-cache #js {:key "css"})
emotion-server (create-emotion-server cache')
html (.renderToString
server
(react/createElement
(.-CacheProvider emotion-react)
(->js
{:value cache'
:children (react/createElement
component
(->js props))})))]
(->clj
(.extractCritical emotion-server html))))
|
|
bae01f2481531c8a2bab670571ef61fa139af4d19106c9dfc94204892feb61fc | wireless-net/erlang-nommu | snmp_conf.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%----------------------------------------------------------------------
%% Purpose: Basic module for reading and verifying config files
%%----------------------------------------------------------------------
-module(snmp_conf).
%% External exports
Avoid warning for local function error/1 clashing with autoimported BIF .
-compile({no_auto_import,[error/1]}).
-export([read_files/2, read/2]).
%% Basic (type) check functions
-export([check_mandatory/2,
check_integer/1, check_integer/2,
check_string/1, check_string/2,
check_atom/2,
check_timer/1,
all_domains/0,
check_domain/1,
all_tdomains/0,
check_tdomain/1,
mk_tdomain/1,
which_domain/1,
check_ip/1, check_ip/2,
check_taddress/1, check_taddress/2,
mk_taddress/3,
check_packet_size/1,
check_oid/1,
check_imask/1, check_emask/1,
check_mp_model/1,
check_sec_model/1, check_sec_model/2, check_sec_model/3,
check_sec_level/1,
all_integer/1
]).
-define(SNMP_USE_V3, true).
-include_lib("snmp/include/snmp_types.hrl").
-include_lib("snmp/include/SNMP-FRAMEWORK-MIB.hrl").
-include_lib("snmp/include/TRANSPORT-ADDRESS-MIB.hrl").
-include_lib("snmp/include/SNMPv2-TM.hrl").
-define(VMODULE,"CONF").
-include("snmp_verbosity.hrl").
%%-----------------------------------------------------------------
%% read_files(Dir, Files) -> Configs
%% Dir - string() - Full path to the config dir.
%% Files - [{Gen, Filter, Check, FileName}]
%% Gen - function/2 - In case of failure when reading the config file,
%% this function is called to either generate a
%% default file or issue the error.
%% Filter - function/1 - Filters all the config entries read from the file
%% Check - function/1 - Check each entry as they are read from the file.
%% FileName - string() - Name of the config file.
config_entry ( ) ]
%% config_entry() - term()
read_files(Dir, Files) when is_list(Dir) andalso is_list(Files) ->
read_files(Dir, Files, []).
read_files(_Dir, [], Res) ->
lists:reverse(Res);
read_files(Dir, [{Gen, Filter, Check, FileName}|Files], Res)
when is_function(Filter) andalso
is_function(Check) andalso
is_list(FileName) ->
?vdebug("read_files -> entry with"
"~n FileName: ~p", [FileName]),
File = filename:join(Dir, FileName),
case file:read_file_info(File) of
{ok, _} ->
Confs = read(File, Check),
read_files(Dir, Files, [Filter(Confs)|Res]);
{error, R} ->
?vlog("failed reading file info for ~s: "
"~n ~p", [FileName, R]),
Gen(Dir, R),
read_files(Dir, Files, [Filter([])|Res])
end.
Ret . Res | exit(Reason )
read(File, Check) when is_function(Check) ->
?vdebug("read -> entry with"
"~n File: ~p", [File]),
Fd = open_file(File),
case loop(Fd, [], Check, 1, File) of
{error, Reason} ->
file:close(Fd),
error(Reason);
{ok, Res} ->
file:close(Fd),
Res
end.
open_file(File) ->
case file:open(File, [read]) of
{ok, Fd} ->
Fd;
{error, Reason} ->
error({failed_open, File, Reason})
end.
loop(Fd, Res, Check, StartLine, File) ->
case do_read(Fd, "", StartLine) of
{ok, Row, EndLine} ->
?vtrace("loop -> "
"~n Row: ~p"
"~n EndLine: ~p", [Row, EndLine]),
case (catch Check(Row)) of
ok ->
?vtrace("loop -> ok", []),
loop(Fd, [Row | Res], Check, EndLine, File);
{ok, NewRow} ->
?vtrace("loop -> ok: "
"~n NewRow: ~p", [NewRow]),
loop(Fd, [NewRow | Res], Check, EndLine, File);
{error, Reason} ->
?vtrace("loop -> check error: "
"~n Reason: ~p", [Reason]),
{error, {failed_check, File, StartLine, EndLine, Reason}};
Error ->
?vtrace("loop -> check failure: "
"~n Error: ~p", [Error]),
{error, {failed_check, File, StartLine, EndLine, Error}}
end;
{error, EndLine, Error} ->
?vtrace("loop -> read failure: "
"~n Error: ~p", [Error]),
{error, {failed_reading, File, StartLine, EndLine, Error}};
eof ->
{ok, Res}
end.
do_read(Io, Prompt, StartLine) ->
case io:request(Io, {get_until,Prompt,erl_scan,tokens,[StartLine]}) of
{ok, Toks, EndLine} ->
case erl_parse:parse_term(Toks) of
{ok, Term} ->
{ok, Term, EndLine};
{error, {Line, erl_parse, Error}} ->
{error, Line, {parse_error, Error}}
end;
{error,E,EndLine} ->
{error, EndLine, E};
{eof, _EndLine} ->
eof;
Other ->
Other
end.
%%-----------------------------------------------------------------
check_mandatory(L, [{Key, Value}|T]) ->
case lists:keymember(Key, 1, L) of
true ->
check_mandatory(L, T);
false when Value == mandatory ->
error({missing_mandatory, Key});
false ->
{value, V} = Value,
check_mandatory([{Key, V} | L], T)
end;
check_mandatory(L, []) ->
{ok, L}.
%% ---------
check_integer(I) -> check_integer(I, any).
check_integer(I, any) when is_integer(I) -> ok;
check_integer(I, pos) when is_integer(I), I > 0 -> ok;
check_integer(I, neg) when is_integer(I), I < 0 -> ok;
check_integer(I1, {gt, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 > I2) -> ok;
check_integer(I1, {gte, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 >= I2) -> ok;
check_integer(I1, {lt, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 < I2) -> ok;
check_integer(I1, {lte, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 =< I2) -> ok;
check_integer(I1, {eq, I1})
when is_integer(I1) -> ok;
check_integer(I, {range, L, U})
when (is_integer(I) andalso
is_integer(L) andalso
is_integer(U) andalso
(I >= L) andalso (I =< U)) -> ok;
check_integer(I, _) -> error({invalid_integer, I}).
check_packet_size(S) ->
case (catch check_integer(S, {range, 484, 2147483647})) of
ok ->
ok;
{error, _} ->
error({invalid_packet_size, S})
end.
%% ---------
check_string(X) when is_list(X) -> ok;
check_string(X) -> error({invalid_string, X}).
check_string(X, any)
when is_list(X) -> ok;
check_string(X, {gt, Len})
when is_list(X) andalso (length(X) > Len) -> ok;
check_string(X, {gt, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, {gte, Len})
when is_list(X) andalso (length(X) >= Len) -> ok;
check_string(X, {gte, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, {lt, Len})
when is_list(X) andalso (length(X) < Len) -> ok;
check_string(X, {lt, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, {lte, Len})
when is_list(X) andalso (length(X) =< Len) -> ok;
check_string(X, {lte, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, Len)
when is_list(X) andalso is_integer(Len) andalso (length(X) =:= Len) -> ok;
check_string(X, _Len) when is_list(X) -> error({invalid_length, X});
check_string(X, _Len) -> error({invalid_string, X}).
check_atom(X, Atoms) ->
case lists:keysearch(X, 1, Atoms) of
{value, {X, Val}} ->
{ok, Val};
_ ->
error({invalid_atom, X, Atoms})
end.
%% ---------
check_mp_model(MPModel) when is_atom(MPModel) ->
All = [{v1, ?MP_V1}, {v2c, ?MP_V2C}, {v3, ?MP_V3}],
check_atom(MPModel, All);
check_mp_model(?MP_V1) ->
{ok, ?MP_V1};
check_mp_model(?MP_V2C) ->
{ok, ?MP_V2C};
check_mp_model(?MP_V3) ->
{ok, ?MP_V3};
check_mp_model(BadMpModel) ->
error({invalid_mp_model, BadMpModel}).
%% ---------
check_sec_model(SecModel) when is_atom(SecModel) ->
check_sec_model(SecModel, []);
check_sec_model(?SEC_ANY) ->
{ok, ?SEC_ANY};
check_sec_model(?SEC_V1) ->
{ok, ?SEC_V1};
check_sec_model(?SEC_V2C) ->
{ok, ?SEC_V2C};
check_sec_model(?SEC_USM) ->
{ok, ?SEC_USM};
check_sec_model(BadSecModel) ->
error({invalid_sec_model, BadSecModel}).
check_sec_model(SecModel, Exclude) when is_atom(SecModel) ->
All = [{any, ?SEC_ANY},
{v1, ?SEC_V1},
{v2c, ?SEC_V2C},
{usm, ?SEC_USM}],
Alt = [{X, Y} || {X, Y} <- All, not lists:member(X, Exclude)],
case (catch check_atom(SecModel, Alt) ) of
{error, _} ->
error({invalid_sec_model, SecModel});
OK ->
OK
end;
check_sec_model(BadSecModel, _Exclude) ->
error({invalid_sec_model, BadSecModel}).
check_sec_model(v1, v1, Exclude) ->
check_sec_model2(v1, ?SEC_V1, Exclude);
check_sec_model(v1, SecModel, _Exclude) ->
error({invalid_sec_model, v1, SecModel});
check_sec_model(v2c, v2c, Exclude) ->
check_sec_model2(v2c, ?SEC_V2C, Exclude);
check_sec_model(v2c, SecModel, _Exclude) ->
error({invalid_sec_model, v2c, SecModel});
check_sec_model(v3, usm, Exclude) ->
check_sec_model2(v3, ?SEC_USM, Exclude);
check_sec_model(v3, SecModel, _Exclude) ->
error({invalid_sec_model, v3, SecModel});
check_sec_model(M1, M2, _Exclude) ->
error({invalid_sec_model, M1, M2}).
check_sec_model2(SecModel, SM, Exclude) ->
case lists:member(SecModel, Exclude) of
false ->
{ok, SM};
true ->
error({invalid_sec_model, SecModel})
end.
%% ---------
check_sec_level(SecLevel) when is_atom(SecLevel) ->
All = [{noAuthNoPriv, ?'SnmpSecurityLevel_noAuthNoPriv'},
{authNoPriv, ?'SnmpSecurityLevel_authNoPriv'},
{authPriv, ?'SnmpSecurityLevel_authPriv'}],
case (catch check_atom(SecLevel, All)) of
{error, _} ->
error({invalid_sec_level, SecLevel});
OK ->
OK
end;
check_sec_level(?'SnmpSecurityLevel_noAuthNoPriv' = SL) ->
{ok, SL};
check_sec_level(?'SnmpSecurityLevel_authNoPriv' = SL) ->
{ok, SL};
check_sec_level(?'SnmpSecurityLevel_authPriv' = SL) ->
{ok, SL};
check_sec_level(BadSecLevel) ->
error({invalid_sec_level, BadSecLevel}).
%% ---------
all_tdomains() ->
[
?transportDomainUdpIpv4,
?transportDomainUdpIpv6,
?transportDomainUdpIpv4z,
?transportDomainUdpIpv6z,
?transportDomainTcpIpv4,
?transportDomainTcpIpv6,
?transportDomainTcpIpv4z,
?transportDomainTcpIpv6z,
?transportDomainSctpIpv4,
?transportDomainSctpIpv6,
?transportDomainSctpIpv4z,
?transportDomainSctpIpv6z,
?transportDomainLocal,
?transportDomainUdpDns,
?transportDomainTcpDns,
?transportDomainSctpDns
].
check_tdomain(TDomain) ->
SupportedTDomains =
[
?snmpUDPDomain,
?transportDomainUdpIpv4,
?transportDomainUdpIpv6
],
AllTDomains = all_tdomains(),
case lists:member(TDomain, SupportedTDomains) of
true ->
ok;
false ->
case lists:member(TDomain, AllTDomains) of
true ->
error({unsupported_tdomain, TDomain});
false ->
error({unknown_tdomain, TDomain})
end
end.
%% ---------
mk_tdomain(snmpUDPDomain) ->
mk_tdomain(transportDomainUdpIpv4);
mk_tdomain(transportDomainUdpIpv4) ->
?transportDomainUdpIpv4;
mk_tdomain(transportDomainUdpIpv6) ->
?transportDomainUdpIpv6;
mk_tdomain(BadDomain) ->
error({bad_domain, BadDomain}).
%% ---------
check_taddress(X) ->
check_taddress(snmpUDPDomain, X).
check_taddress(?snmpUDPDomain, X) ->
check_taddress(transportDomainUdpIpv4, X);
check_taddress(snmpUDPDomain, X) ->
check_taddress(transportDomainUdpIpv4, X);
check_taddress(?transportDomainUdpIpv4, X) ->
check_taddress(transportDomainUdpIpv4, X);
check_taddress(transportDomainUdpIpv4, X)
when is_list(X) andalso (length(X) =:= 6) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_taddress, X})
end;
check_taddress(transportDomainUdpIpv4, X) ->
error({invalid_taddress, X});
check_taddress(?transportDomainUdpIpv6, X) ->
check_taddress(transportDomainUdpIpv6, X);
check_taddress(transportDomainUdpIpv6, X)
when is_list(X) andalso (length(X) =:= 10) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_taddress, X})
end;
check_taddress(transportDomainUdpIpv6, X) ->
error({invalid_taddress, X});
check_taddress(BadDomain, _X) ->
error({invalid_tdomain, BadDomain}).
%% ---------
check_timer(infinity) ->
{ok, infinity};
check_timer(T) when is_record(T, snmp_incr_timer) ->
{ok, T};
check_timer({WaitFor, Factor, Incr, Retry} = T) ->
case (catch do_check_timer(WaitFor, Factor, Incr, Retry)) of
ok ->
{ok, #snmp_incr_timer{wait_for = WaitFor,
factor = Factor,
incr = Incr,
max_retries = Retry}};
_Err ->
error({invalid_timer, T})
end;
check_timer(Timeout) ->
case (catch check_integer(Timeout, {gt, 0})) of
ok ->
{ok, #snmp_incr_timer{wait_for = Timeout,
factor = 1,
incr = 0,
max_retries = 0}};
_Err ->
error({invalid_timer, Timeout})
end.
do_check_timer(WaitFor, Factor, Incr, Retry) ->
check_integer(WaitFor, {gt, 0}),
check_integer(Factor, {gt, 0}),
check_integer(Incr, {gte, 0}),
check_integer(Retry, {gte, 0}),
ok.
%% ---------
all_domains() ->
[
transportDomainUdpIpv4,
transportDomainUdpIpv6,
transportDomainUdpIpv4z,
transportDomainUdpIpv6z,
transportDomainTcpIpv4,
transportDomainTcpIpv6,
transportDomainTcpIpv4z,
transportDomainTcpIpv6z,
transportDomainSctpIpv4,
transportDomainSctpIpv6,
transportDomainSctpIpv4z,
transportDomainSctpIpv6z,
transportDomainLocal,
transportDomainUdpDns,
transportDomainTcpDns,
transportDomainSctpDns
].
check_domain(Domain) ->
SupportedDomains =
[
snmpUDPDomain,
transportDomainUdpIpv4,
transportDomainUdpIpv6
],
AllDomains = all_domains(),
case lists:member(Domain, SupportedDomains) of
true ->
ok;
false ->
case lists:member(Domain, AllDomains) of
true ->
error({unsupported_domain, Domain});
false ->
error({unknown_domain, Domain})
end
end.
%% ---------
%% The values of Ip and Port has both been checked at this
%% point, so we dont need to do that again.
mk_taddress(snmpUDPDomain, Ip, Port) ->
mk_taddress(transportDomainUdpIpv4, Ip, Port);
mk_taddress(transportDomainUdpIpv4, Ip, Port) when is_list(Ip) ->
Ip ++ [Port div 256, Port rem 256];
mk_taddress(transportDomainUdpIpv4 = Domain, Ip, Port) when is_tuple(Ip) ->
mk_taddress(Domain, tuple_to_list(Ip), Port);
mk_taddress(transportDomainUdpIpv6, Ip, Port) when is_list(Ip) ->
Ip ++ [Port div 256, Port rem 256];
mk_taddress(transportDomainUdpIpv6 = Domain, Ip, Port) when is_tuple(Ip) ->
mk_taddress(Domain, tuple_to_list(Ip), Port);
%% These are just for convenience
mk_taddress(?snmpUDPDomain, Ip, Port) ->
mk_taddress(snmpUDPDomain, Ip, Port);
mk_taddress(?transportDomainUdpIpv4, Ip, Port) ->
mk_taddress(transportDomainUdpIpv4, Ip, Port);
mk_taddress(?transportDomainUdpIpv6, Ip, Port) ->
mk_taddress(transportDomainUdpIpv6, Ip, Port);
%% Bad domain
mk_taddress(BadDomain, _Ip, _Port) ->
error({bad_domain, BadDomain}).
%% ---------
which_domain(Ip) when is_list(Ip) andalso (length(Ip) =:= 4) ->
transportDomainUdpIpv4;
which_domain(Ip) when is_tuple(Ip) andalso (size(Ip) =:= 4) ->
transportDomainUdpIpv4;
which_domain(Ip) when is_list(Ip) andalso (length(Ip) =:= 8) ->
transportDomainUdpIpv6;
which_domain(Ip) when is_tuple(Ip) andalso (size(Ip) =:= 8) ->
transportDomainUdpIpv6.
%% ---------
check_ip(X) ->
check_ip(snmpUDPDomain, X).
check_ip(snmpUDPDomain, X) ->
check_ip(transportDomainUdpIpv4, X);
check_ip(transportDomainUdpIpv4, X) when is_list(X) andalso (length(X) =:= 4) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_ip_address, X})
end;
check_ip(transportDomainUdpIpv4, X) ->
error({invalid_ip_address, X});
check_ip(transportDomainUdpIpv6, X) when is_list(X) andalso (length(X) =:= 8) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_ip_address, X})
end;
check_ip(transportDomainUdpIpv6, X) ->
error({invalid_ip_address, X});
check_ip(BadDomain, _X) ->
error({invalid_domain, BadDomain}).
%% ---------
check_oid([E1,E2|_] = X) when E1 * 40 + E2 =< 255 ->
case all_integer(X) of
true ->
ok;
_ ->
error({invalid_object_identifier, X})
end;
check_oid(X) ->
error({invalid_object_identifier, X}).
%% ---------
Check a ( view ) mask in the internal form ( all 0 and 1 ):
check_imask(null) ->
{ok, []};
check_imask(IMask) when is_list(IMask) ->
do_check_imask(IMask),
{ok, IMask}.
do_check_imask([0|IMask]) ->
do_check_imask(IMask);
do_check_imask([1|IMask]) ->
do_check_imask(IMask);
do_check_imask([X|_]) ->
error({invalid_internal_mask_element, X}).
Check a ( view ) mask in the external form ( according to MIB ,
an OCTET STRING of at most length 16 ) .
check_emask(EMask) when is_list(EMask) andalso (length(EMask) =< 16) ->
do_check_emask(EMask).
do_check_emask([]) ->
ok;
do_check_emask([X|EMask])
when is_integer(X) andalso (X >= 16#00) andalso (X =< 16#FF) ->
do_check_emask(EMask);
do_check_emask([X|_]) ->
error({invalid_external_mask_element, X}).
%% ---------
all_integer([H|T]) when is_integer(H) -> all_integer(T);
all_integer([_H|_T]) -> false;
all_integer([]) -> true.
%% ---------
error(Reason) ->
throw({error, Reason}).
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/snmp/src/misc/snmp_conf.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
----------------------------------------------------------------------
Purpose: Basic module for reading and verifying config files
----------------------------------------------------------------------
External exports
Basic (type) check functions
-----------------------------------------------------------------
read_files(Dir, Files) -> Configs
Dir - string() - Full path to the config dir.
Files - [{Gen, Filter, Check, FileName}]
Gen - function/2 - In case of failure when reading the config file,
this function is called to either generate a
default file or issue the error.
Filter - function/1 - Filters all the config entries read from the file
Check - function/1 - Check each entry as they are read from the file.
FileName - string() - Name of the config file.
config_entry() - term()
-----------------------------------------------------------------
---------
---------
---------
---------
---------
---------
---------
---------
---------
---------
---------
The values of Ip and Port has both been checked at this
point, so we dont need to do that again.
These are just for convenience
Bad domain
---------
---------
---------
---------
---------
--------- | Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(snmp_conf).
Avoid warning for local function error/1 clashing with autoimported BIF .
-compile({no_auto_import,[error/1]}).
-export([read_files/2, read/2]).
-export([check_mandatory/2,
check_integer/1, check_integer/2,
check_string/1, check_string/2,
check_atom/2,
check_timer/1,
all_domains/0,
check_domain/1,
all_tdomains/0,
check_tdomain/1,
mk_tdomain/1,
which_domain/1,
check_ip/1, check_ip/2,
check_taddress/1, check_taddress/2,
mk_taddress/3,
check_packet_size/1,
check_oid/1,
check_imask/1, check_emask/1,
check_mp_model/1,
check_sec_model/1, check_sec_model/2, check_sec_model/3,
check_sec_level/1,
all_integer/1
]).
-define(SNMP_USE_V3, true).
-include_lib("snmp/include/snmp_types.hrl").
-include_lib("snmp/include/SNMP-FRAMEWORK-MIB.hrl").
-include_lib("snmp/include/TRANSPORT-ADDRESS-MIB.hrl").
-include_lib("snmp/include/SNMPv2-TM.hrl").
-define(VMODULE,"CONF").
-include("snmp_verbosity.hrl").
config_entry ( ) ]
read_files(Dir, Files) when is_list(Dir) andalso is_list(Files) ->
read_files(Dir, Files, []).
read_files(_Dir, [], Res) ->
lists:reverse(Res);
read_files(Dir, [{Gen, Filter, Check, FileName}|Files], Res)
when is_function(Filter) andalso
is_function(Check) andalso
is_list(FileName) ->
?vdebug("read_files -> entry with"
"~n FileName: ~p", [FileName]),
File = filename:join(Dir, FileName),
case file:read_file_info(File) of
{ok, _} ->
Confs = read(File, Check),
read_files(Dir, Files, [Filter(Confs)|Res]);
{error, R} ->
?vlog("failed reading file info for ~s: "
"~n ~p", [FileName, R]),
Gen(Dir, R),
read_files(Dir, Files, [Filter([])|Res])
end.
Ret . Res | exit(Reason )
read(File, Check) when is_function(Check) ->
?vdebug("read -> entry with"
"~n File: ~p", [File]),
Fd = open_file(File),
case loop(Fd, [], Check, 1, File) of
{error, Reason} ->
file:close(Fd),
error(Reason);
{ok, Res} ->
file:close(Fd),
Res
end.
open_file(File) ->
case file:open(File, [read]) of
{ok, Fd} ->
Fd;
{error, Reason} ->
error({failed_open, File, Reason})
end.
loop(Fd, Res, Check, StartLine, File) ->
case do_read(Fd, "", StartLine) of
{ok, Row, EndLine} ->
?vtrace("loop -> "
"~n Row: ~p"
"~n EndLine: ~p", [Row, EndLine]),
case (catch Check(Row)) of
ok ->
?vtrace("loop -> ok", []),
loop(Fd, [Row | Res], Check, EndLine, File);
{ok, NewRow} ->
?vtrace("loop -> ok: "
"~n NewRow: ~p", [NewRow]),
loop(Fd, [NewRow | Res], Check, EndLine, File);
{error, Reason} ->
?vtrace("loop -> check error: "
"~n Reason: ~p", [Reason]),
{error, {failed_check, File, StartLine, EndLine, Reason}};
Error ->
?vtrace("loop -> check failure: "
"~n Error: ~p", [Error]),
{error, {failed_check, File, StartLine, EndLine, Error}}
end;
{error, EndLine, Error} ->
?vtrace("loop -> read failure: "
"~n Error: ~p", [Error]),
{error, {failed_reading, File, StartLine, EndLine, Error}};
eof ->
{ok, Res}
end.
do_read(Io, Prompt, StartLine) ->
case io:request(Io, {get_until,Prompt,erl_scan,tokens,[StartLine]}) of
{ok, Toks, EndLine} ->
case erl_parse:parse_term(Toks) of
{ok, Term} ->
{ok, Term, EndLine};
{error, {Line, erl_parse, Error}} ->
{error, Line, {parse_error, Error}}
end;
{error,E,EndLine} ->
{error, EndLine, E};
{eof, _EndLine} ->
eof;
Other ->
Other
end.
check_mandatory(L, [{Key, Value}|T]) ->
case lists:keymember(Key, 1, L) of
true ->
check_mandatory(L, T);
false when Value == mandatory ->
error({missing_mandatory, Key});
false ->
{value, V} = Value,
check_mandatory([{Key, V} | L], T)
end;
check_mandatory(L, []) ->
{ok, L}.
check_integer(I) -> check_integer(I, any).
check_integer(I, any) when is_integer(I) -> ok;
check_integer(I, pos) when is_integer(I), I > 0 -> ok;
check_integer(I, neg) when is_integer(I), I < 0 -> ok;
check_integer(I1, {gt, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 > I2) -> ok;
check_integer(I1, {gte, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 >= I2) -> ok;
check_integer(I1, {lt, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 < I2) -> ok;
check_integer(I1, {lte, I2})
when is_integer(I1) andalso is_integer(I2) andalso (I1 =< I2) -> ok;
check_integer(I1, {eq, I1})
when is_integer(I1) -> ok;
check_integer(I, {range, L, U})
when (is_integer(I) andalso
is_integer(L) andalso
is_integer(U) andalso
(I >= L) andalso (I =< U)) -> ok;
check_integer(I, _) -> error({invalid_integer, I}).
check_packet_size(S) ->
case (catch check_integer(S, {range, 484, 2147483647})) of
ok ->
ok;
{error, _} ->
error({invalid_packet_size, S})
end.
check_string(X) when is_list(X) -> ok;
check_string(X) -> error({invalid_string, X}).
check_string(X, any)
when is_list(X) -> ok;
check_string(X, {gt, Len})
when is_list(X) andalso (length(X) > Len) -> ok;
check_string(X, {gt, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, {gte, Len})
when is_list(X) andalso (length(X) >= Len) -> ok;
check_string(X, {gte, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, {lt, Len})
when is_list(X) andalso (length(X) < Len) -> ok;
check_string(X, {lt, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, {lte, Len})
when is_list(X) andalso (length(X) =< Len) -> ok;
check_string(X, {lte, _Len})
when is_list(X) -> error({invalid_length, X});
check_string(X, Len)
when is_list(X) andalso is_integer(Len) andalso (length(X) =:= Len) -> ok;
check_string(X, _Len) when is_list(X) -> error({invalid_length, X});
check_string(X, _Len) -> error({invalid_string, X}).
check_atom(X, Atoms) ->
case lists:keysearch(X, 1, Atoms) of
{value, {X, Val}} ->
{ok, Val};
_ ->
error({invalid_atom, X, Atoms})
end.
check_mp_model(MPModel) when is_atom(MPModel) ->
All = [{v1, ?MP_V1}, {v2c, ?MP_V2C}, {v3, ?MP_V3}],
check_atom(MPModel, All);
check_mp_model(?MP_V1) ->
{ok, ?MP_V1};
check_mp_model(?MP_V2C) ->
{ok, ?MP_V2C};
check_mp_model(?MP_V3) ->
{ok, ?MP_V3};
check_mp_model(BadMpModel) ->
error({invalid_mp_model, BadMpModel}).
check_sec_model(SecModel) when is_atom(SecModel) ->
check_sec_model(SecModel, []);
check_sec_model(?SEC_ANY) ->
{ok, ?SEC_ANY};
check_sec_model(?SEC_V1) ->
{ok, ?SEC_V1};
check_sec_model(?SEC_V2C) ->
{ok, ?SEC_V2C};
check_sec_model(?SEC_USM) ->
{ok, ?SEC_USM};
check_sec_model(BadSecModel) ->
error({invalid_sec_model, BadSecModel}).
check_sec_model(SecModel, Exclude) when is_atom(SecModel) ->
All = [{any, ?SEC_ANY},
{v1, ?SEC_V1},
{v2c, ?SEC_V2C},
{usm, ?SEC_USM}],
Alt = [{X, Y} || {X, Y} <- All, not lists:member(X, Exclude)],
case (catch check_atom(SecModel, Alt) ) of
{error, _} ->
error({invalid_sec_model, SecModel});
OK ->
OK
end;
check_sec_model(BadSecModel, _Exclude) ->
error({invalid_sec_model, BadSecModel}).
check_sec_model(v1, v1, Exclude) ->
check_sec_model2(v1, ?SEC_V1, Exclude);
check_sec_model(v1, SecModel, _Exclude) ->
error({invalid_sec_model, v1, SecModel});
check_sec_model(v2c, v2c, Exclude) ->
check_sec_model2(v2c, ?SEC_V2C, Exclude);
check_sec_model(v2c, SecModel, _Exclude) ->
error({invalid_sec_model, v2c, SecModel});
check_sec_model(v3, usm, Exclude) ->
check_sec_model2(v3, ?SEC_USM, Exclude);
check_sec_model(v3, SecModel, _Exclude) ->
error({invalid_sec_model, v3, SecModel});
check_sec_model(M1, M2, _Exclude) ->
error({invalid_sec_model, M1, M2}).
check_sec_model2(SecModel, SM, Exclude) ->
case lists:member(SecModel, Exclude) of
false ->
{ok, SM};
true ->
error({invalid_sec_model, SecModel})
end.
check_sec_level(SecLevel) when is_atom(SecLevel) ->
All = [{noAuthNoPriv, ?'SnmpSecurityLevel_noAuthNoPriv'},
{authNoPriv, ?'SnmpSecurityLevel_authNoPriv'},
{authPriv, ?'SnmpSecurityLevel_authPriv'}],
case (catch check_atom(SecLevel, All)) of
{error, _} ->
error({invalid_sec_level, SecLevel});
OK ->
OK
end;
check_sec_level(?'SnmpSecurityLevel_noAuthNoPriv' = SL) ->
{ok, SL};
check_sec_level(?'SnmpSecurityLevel_authNoPriv' = SL) ->
{ok, SL};
check_sec_level(?'SnmpSecurityLevel_authPriv' = SL) ->
{ok, SL};
check_sec_level(BadSecLevel) ->
error({invalid_sec_level, BadSecLevel}).
all_tdomains() ->
[
?transportDomainUdpIpv4,
?transportDomainUdpIpv6,
?transportDomainUdpIpv4z,
?transportDomainUdpIpv6z,
?transportDomainTcpIpv4,
?transportDomainTcpIpv6,
?transportDomainTcpIpv4z,
?transportDomainTcpIpv6z,
?transportDomainSctpIpv4,
?transportDomainSctpIpv6,
?transportDomainSctpIpv4z,
?transportDomainSctpIpv6z,
?transportDomainLocal,
?transportDomainUdpDns,
?transportDomainTcpDns,
?transportDomainSctpDns
].
check_tdomain(TDomain) ->
SupportedTDomains =
[
?snmpUDPDomain,
?transportDomainUdpIpv4,
?transportDomainUdpIpv6
],
AllTDomains = all_tdomains(),
case lists:member(TDomain, SupportedTDomains) of
true ->
ok;
false ->
case lists:member(TDomain, AllTDomains) of
true ->
error({unsupported_tdomain, TDomain});
false ->
error({unknown_tdomain, TDomain})
end
end.
mk_tdomain(snmpUDPDomain) ->
mk_tdomain(transportDomainUdpIpv4);
mk_tdomain(transportDomainUdpIpv4) ->
?transportDomainUdpIpv4;
mk_tdomain(transportDomainUdpIpv6) ->
?transportDomainUdpIpv6;
mk_tdomain(BadDomain) ->
error({bad_domain, BadDomain}).
check_taddress(X) ->
check_taddress(snmpUDPDomain, X).
check_taddress(?snmpUDPDomain, X) ->
check_taddress(transportDomainUdpIpv4, X);
check_taddress(snmpUDPDomain, X) ->
check_taddress(transportDomainUdpIpv4, X);
check_taddress(?transportDomainUdpIpv4, X) ->
check_taddress(transportDomainUdpIpv4, X);
check_taddress(transportDomainUdpIpv4, X)
when is_list(X) andalso (length(X) =:= 6) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_taddress, X})
end;
check_taddress(transportDomainUdpIpv4, X) ->
error({invalid_taddress, X});
check_taddress(?transportDomainUdpIpv6, X) ->
check_taddress(transportDomainUdpIpv6, X);
check_taddress(transportDomainUdpIpv6, X)
when is_list(X) andalso (length(X) =:= 10) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_taddress, X})
end;
check_taddress(transportDomainUdpIpv6, X) ->
error({invalid_taddress, X});
check_taddress(BadDomain, _X) ->
error({invalid_tdomain, BadDomain}).
check_timer(infinity) ->
{ok, infinity};
check_timer(T) when is_record(T, snmp_incr_timer) ->
{ok, T};
check_timer({WaitFor, Factor, Incr, Retry} = T) ->
case (catch do_check_timer(WaitFor, Factor, Incr, Retry)) of
ok ->
{ok, #snmp_incr_timer{wait_for = WaitFor,
factor = Factor,
incr = Incr,
max_retries = Retry}};
_Err ->
error({invalid_timer, T})
end;
check_timer(Timeout) ->
case (catch check_integer(Timeout, {gt, 0})) of
ok ->
{ok, #snmp_incr_timer{wait_for = Timeout,
factor = 1,
incr = 0,
max_retries = 0}};
_Err ->
error({invalid_timer, Timeout})
end.
do_check_timer(WaitFor, Factor, Incr, Retry) ->
check_integer(WaitFor, {gt, 0}),
check_integer(Factor, {gt, 0}),
check_integer(Incr, {gte, 0}),
check_integer(Retry, {gte, 0}),
ok.
all_domains() ->
[
transportDomainUdpIpv4,
transportDomainUdpIpv6,
transportDomainUdpIpv4z,
transportDomainUdpIpv6z,
transportDomainTcpIpv4,
transportDomainTcpIpv6,
transportDomainTcpIpv4z,
transportDomainTcpIpv6z,
transportDomainSctpIpv4,
transportDomainSctpIpv6,
transportDomainSctpIpv4z,
transportDomainSctpIpv6z,
transportDomainLocal,
transportDomainUdpDns,
transportDomainTcpDns,
transportDomainSctpDns
].
check_domain(Domain) ->
SupportedDomains =
[
snmpUDPDomain,
transportDomainUdpIpv4,
transportDomainUdpIpv6
],
AllDomains = all_domains(),
case lists:member(Domain, SupportedDomains) of
true ->
ok;
false ->
case lists:member(Domain, AllDomains) of
true ->
error({unsupported_domain, Domain});
false ->
error({unknown_domain, Domain})
end
end.
mk_taddress(snmpUDPDomain, Ip, Port) ->
mk_taddress(transportDomainUdpIpv4, Ip, Port);
mk_taddress(transportDomainUdpIpv4, Ip, Port) when is_list(Ip) ->
Ip ++ [Port div 256, Port rem 256];
mk_taddress(transportDomainUdpIpv4 = Domain, Ip, Port) when is_tuple(Ip) ->
mk_taddress(Domain, tuple_to_list(Ip), Port);
mk_taddress(transportDomainUdpIpv6, Ip, Port) when is_list(Ip) ->
Ip ++ [Port div 256, Port rem 256];
mk_taddress(transportDomainUdpIpv6 = Domain, Ip, Port) when is_tuple(Ip) ->
mk_taddress(Domain, tuple_to_list(Ip), Port);
mk_taddress(?snmpUDPDomain, Ip, Port) ->
mk_taddress(snmpUDPDomain, Ip, Port);
mk_taddress(?transportDomainUdpIpv4, Ip, Port) ->
mk_taddress(transportDomainUdpIpv4, Ip, Port);
mk_taddress(?transportDomainUdpIpv6, Ip, Port) ->
mk_taddress(transportDomainUdpIpv6, Ip, Port);
mk_taddress(BadDomain, _Ip, _Port) ->
error({bad_domain, BadDomain}).
which_domain(Ip) when is_list(Ip) andalso (length(Ip) =:= 4) ->
transportDomainUdpIpv4;
which_domain(Ip) when is_tuple(Ip) andalso (size(Ip) =:= 4) ->
transportDomainUdpIpv4;
which_domain(Ip) when is_list(Ip) andalso (length(Ip) =:= 8) ->
transportDomainUdpIpv6;
which_domain(Ip) when is_tuple(Ip) andalso (size(Ip) =:= 8) ->
transportDomainUdpIpv6.
check_ip(X) ->
check_ip(snmpUDPDomain, X).
check_ip(snmpUDPDomain, X) ->
check_ip(transportDomainUdpIpv4, X);
check_ip(transportDomainUdpIpv4, X) when is_list(X) andalso (length(X) =:= 4) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_ip_address, X})
end;
check_ip(transportDomainUdpIpv4, X) ->
error({invalid_ip_address, X});
check_ip(transportDomainUdpIpv6, X) when is_list(X) andalso (length(X) =:= 8) ->
case (catch all_integer(X)) of
true ->
ok;
false ->
error({invalid_ip_address, X})
end;
check_ip(transportDomainUdpIpv6, X) ->
error({invalid_ip_address, X});
check_ip(BadDomain, _X) ->
error({invalid_domain, BadDomain}).
check_oid([E1,E2|_] = X) when E1 * 40 + E2 =< 255 ->
case all_integer(X) of
true ->
ok;
_ ->
error({invalid_object_identifier, X})
end;
check_oid(X) ->
error({invalid_object_identifier, X}).
Check a ( view ) mask in the internal form ( all 0 and 1 ):
check_imask(null) ->
{ok, []};
check_imask(IMask) when is_list(IMask) ->
do_check_imask(IMask),
{ok, IMask}.
do_check_imask([0|IMask]) ->
do_check_imask(IMask);
do_check_imask([1|IMask]) ->
do_check_imask(IMask);
do_check_imask([X|_]) ->
error({invalid_internal_mask_element, X}).
Check a ( view ) mask in the external form ( according to MIB ,
an OCTET STRING of at most length 16 ) .
check_emask(EMask) when is_list(EMask) andalso (length(EMask) =< 16) ->
do_check_emask(EMask).
do_check_emask([]) ->
ok;
do_check_emask([X|EMask])
when is_integer(X) andalso (X >= 16#00) andalso (X =< 16#FF) ->
do_check_emask(EMask);
do_check_emask([X|_]) ->
error({invalid_external_mask_element, X}).
all_integer([H|T]) when is_integer(H) -> all_integer(T);
all_integer([_H|_T]) -> false;
all_integer([]) -> true.
error(Reason) ->
throw({error, Reason}).
|
08e483c5b6ade7e03ff963ee66c150ee70c313d6a4b1a1a50e52339ac65b450d | mstksg/advent-of-code-2022 | Day15.hs | {-# OPTIONS_GHC -Wno-unused-imports #-}
{-# OPTIONS_GHC -Wno-unused-top-binds #-}
-- |
-- Module : AOC.Challenge.Day15
-- License : BSD3
--
-- Stability : experimental
-- Portability : non-portable
--
Day 15 . See " AOC.Solver " for the types used in this module !
--
-- After completing the challenge, it is recommended to:
--
-- * Replace "AOC.Prelude" imports to specific modules (with explicit
-- imports) for readability.
-- * Remove the @-Wno-unused-imports@ and @-Wno-unused-top-binds@
-- pragmas.
-- * Replace the partial type signatures underscores in the solution
-- types @_ :~> _@ with the actual types of inputs and outputs of the
solution . You can delete the type signatures completely and GHC
-- will recommend what should go in place of the underscores.
module AOC.Challenge.Day15
(
)
where
-- day15a
-- , day15b
import AOC.Prelude
import qualified Data.Graph.Inductive as G
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List.NonEmpty as NE
import qualified Data.List.PointedList as PL
import qualified Data.List.PointedList.Circular as PLC
import qualified Data.Map as M
import qualified Data.OrdPSQ as PSQ
import qualified Data.Sequence as Seq
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Vector as V
import qualified Linear as L
import qualified Text.Megaparsec as P
import qualified Text.Megaparsec.Char as P
import qualified Text.Megaparsec.Char.Lexer as PP
day15a :: _ :~> _
day15a =
MkSol
{ sParse = Just . lines
, sShow = show
, sSolve = Just
}
day15b :: _ :~> _
day15b =
MkSol
{ sParse = sParse day15a
, sShow = show
, sSolve = Just
}
| null | https://raw.githubusercontent.com/mstksg/advent-of-code-2022/de9ceee002d3a62746468492c746b8d7ca3fc8a0/src/AOC/Challenge/Day15.hs | haskell | # OPTIONS_GHC -Wno-unused-imports #
# OPTIONS_GHC -Wno-unused-top-binds #
|
Module : AOC.Challenge.Day15
License : BSD3
Stability : experimental
Portability : non-portable
After completing the challenge, it is recommended to:
* Replace "AOC.Prelude" imports to specific modules (with explicit
imports) for readability.
* Remove the @-Wno-unused-imports@ and @-Wno-unused-top-binds@
pragmas.
* Replace the partial type signatures underscores in the solution
types @_ :~> _@ with the actual types of inputs and outputs of the
will recommend what should go in place of the underscores.
day15a
, day15b |
Day 15 . See " AOC.Solver " for the types used in this module !
solution . You can delete the type signatures completely and GHC
module AOC.Challenge.Day15
(
)
where
import AOC.Prelude
import qualified Data.Graph.Inductive as G
import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List.NonEmpty as NE
import qualified Data.List.PointedList as PL
import qualified Data.List.PointedList.Circular as PLC
import qualified Data.Map as M
import qualified Data.OrdPSQ as PSQ
import qualified Data.Sequence as Seq
import qualified Data.Set as S
import qualified Data.Text as T
import qualified Data.Vector as V
import qualified Linear as L
import qualified Text.Megaparsec as P
import qualified Text.Megaparsec.Char as P
import qualified Text.Megaparsec.Char.Lexer as PP
day15a :: _ :~> _
day15a =
MkSol
{ sParse = Just . lines
, sShow = show
, sSolve = Just
}
day15b :: _ :~> _
day15b =
MkSol
{ sParse = sParse day15a
, sShow = show
, sSolve = Just
}
|
76f8314e23c02425b564f76da63ac86f201c0f6b5df5c41a80bb1cc8cb7745b3 | well-typed-lightbulbs/ocaml-esp32 | ccomp.mli | (**************************************************************************)
(* *)
(* 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. *)
(* *)
(**************************************************************************)
(** Compiling C files and building C libraries
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
*)
val command: string -> int
val run_command: string -> unit
val compile_file:
?output:string -> ?opt:string -> ?stable_name:string -> string -> int
val create_archive: string -> string list -> int
val expand_libname: string -> string
val quote_files: string list -> string
val quote_optfile: string option -> string
make_link_options : string list - > string
type link_mode =
| Exe
| Dll
| MainDll
| Partial
val call_linker: link_mode -> string -> string list -> string -> bool
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/utils/ccomp.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Compiling C files and building C libraries
{b Warning:} this module is unstable and part of
{{!Compiler_libs}compiler-libs}.
| , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
val command: string -> int
val run_command: string -> unit
val compile_file:
?output:string -> ?opt:string -> ?stable_name:string -> string -> int
val create_archive: string -> string list -> int
val expand_libname: string -> string
val quote_files: string list -> string
val quote_optfile: string option -> string
make_link_options : string list - > string
type link_mode =
| Exe
| Dll
| MainDll
| Partial
val call_linker: link_mode -> string -> string list -> string -> bool
|
2a820ade3fee0c2ce4b382a8818ce4f84bc19f104bbd86d40ce415ec493fc4a3 | LeventErkok/sbv | Deduce.hs | -----------------------------------------------------------------------------
-- |
Module : . Uninterpreted . Deduce
Copyright : ( c )
-- License : BSD3
-- Maintainer:
-- Stability : experimental
--
Bench suite for Documentation . SBV.Examples . Uninterpreted . Deduce
-----------------------------------------------------------------------------
# OPTIONS_GHC -Wall -Werror -fno - warn - orphans #
# LANGUAGE ScopedTypeVariables #
module BenchSuite.Uninterpreted.Deduce(benchmarks) where
import Documentation.SBV.Examples.Uninterpreted.Deduce
import Data.SBV
import Prelude hiding (not, or, and)
import BenchSuite.Bench.Bench
benchmarks :: Runner
benchmarks = rGroup
[ run "test" t `using` runner proveWith
]
where t = do addAxiom "OR distributes over AND" $ \p q r -> (p `or` q) `and` (p `or` r) .== p `or` (q `and` r)
addAxiom "de Morgan" $ \p q -> not (p `or` q) .== not p `and` not q
addAxiom "double negation" $ \p -> not (not p) .== p
p <- free "p"
q <- free "q"
r <- free "r"
return $ not (p `or` (q `and` r))
.== (not p `and` not q) `or` (not p `and` not r)
| null | https://raw.githubusercontent.com/LeventErkok/sbv/be4d7260187067a71ef8af18006e74698e2a565b/SBVBenchSuite/BenchSuite/Uninterpreted/Deduce.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Maintainer:
Stability : experimental
--------------------------------------------------------------------------- | Module : . Uninterpreted . Deduce
Copyright : ( c )
Bench suite for Documentation . SBV.Examples . Uninterpreted . Deduce
# OPTIONS_GHC -Wall -Werror -fno - warn - orphans #
# LANGUAGE ScopedTypeVariables #
module BenchSuite.Uninterpreted.Deduce(benchmarks) where
import Documentation.SBV.Examples.Uninterpreted.Deduce
import Data.SBV
import Prelude hiding (not, or, and)
import BenchSuite.Bench.Bench
benchmarks :: Runner
benchmarks = rGroup
[ run "test" t `using` runner proveWith
]
where t = do addAxiom "OR distributes over AND" $ \p q r -> (p `or` q) `and` (p `or` r) .== p `or` (q `and` r)
addAxiom "de Morgan" $ \p q -> not (p `or` q) .== not p `and` not q
addAxiom "double negation" $ \p -> not (not p) .== p
p <- free "p"
q <- free "q"
r <- free "r"
return $ not (p `or` (q `and` r))
.== (not p `and` not q) `or` (not p `and` not r)
|
e619be9e382a35b4442b5f943ef2fd5b36c91bfe63fb112a286663f093b74f1c | haskell-works/hw-dsv | ColumnDesc.hs | {-# LANGUAGE DataKinds #-}
# LANGUAGE DeriveFunctor #
{-# LANGUAGE DeriveGeneric #-}
# LANGUAGE DuplicateRecordFields #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeApplications #
module App.Data.ColumnDesc
( ColumnDesc(..)
, realiseColumnDescLazy
, realiseColumnDescStrict
, columnDescToTuple
) where
import Control.Lens
import Data.Generics.Product.Any
import Data.Text
import GHC.Generics
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified HaskellWorks.Data.Network.Ip.Ipv4 as IPv4
import qualified Text.Appar.String as TAS
data ColumnDesc a = ColumnDesc
{ number :: Int
, conversion :: a
} deriving (Eq, Show, Generic, Functor)
ipv4ToWord32 :: LBS.ByteString -> LBS.ByteString
ipv4ToWord32 lbs = case TAS.parse IPv4.parseIpAddress (T.unpack (T.decodeUtf8 (LBS.toStrict lbs))) of
Just ipv4Address -> LBS.fromStrict (T.encodeUtf8 (T.pack (show (ipv4Address ^. the @"word"))))
Nothing -> lbs
realiseColumnDescLazy :: ColumnDesc Text -> ColumnDesc (LBS.ByteString -> LBS.ByteString)
realiseColumnDescLazy = fmap realise
where realise :: Text -> LBS.ByteString -> LBS.ByteString
realise t = case t of
"id" -> id
"ipv4-to-word32" -> ipv4ToWord32
_ -> const "BAD"
realiseColumnDescStrict :: ColumnDesc Text -> ColumnDesc (BS.ByteString -> BS.ByteString)
realiseColumnDescStrict cd = fmap (\f -> LBS.toStrict . f . LBS.fromStrict) (realiseColumnDescLazy cd)
columnDescToTuple :: ColumnDesc a -> (Int, a)
columnDescToTuple cd = (cd ^. the @1, cd ^. the @2)
| null | https://raw.githubusercontent.com/haskell-works/hw-dsv/4f1274af383281589165232186f99219479d7898/app/App/Data/ColumnDesc.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric # | # LANGUAGE DeriveFunctor #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeApplications #
module App.Data.ColumnDesc
( ColumnDesc(..)
, realiseColumnDescLazy
, realiseColumnDescStrict
, columnDescToTuple
) where
import Control.Lens
import Data.Generics.Product.Any
import Data.Text
import GHC.Generics
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified HaskellWorks.Data.Network.Ip.Ipv4 as IPv4
import qualified Text.Appar.String as TAS
data ColumnDesc a = ColumnDesc
{ number :: Int
, conversion :: a
} deriving (Eq, Show, Generic, Functor)
ipv4ToWord32 :: LBS.ByteString -> LBS.ByteString
ipv4ToWord32 lbs = case TAS.parse IPv4.parseIpAddress (T.unpack (T.decodeUtf8 (LBS.toStrict lbs))) of
Just ipv4Address -> LBS.fromStrict (T.encodeUtf8 (T.pack (show (ipv4Address ^. the @"word"))))
Nothing -> lbs
realiseColumnDescLazy :: ColumnDesc Text -> ColumnDesc (LBS.ByteString -> LBS.ByteString)
realiseColumnDescLazy = fmap realise
where realise :: Text -> LBS.ByteString -> LBS.ByteString
realise t = case t of
"id" -> id
"ipv4-to-word32" -> ipv4ToWord32
_ -> const "BAD"
realiseColumnDescStrict :: ColumnDesc Text -> ColumnDesc (BS.ByteString -> BS.ByteString)
realiseColumnDescStrict cd = fmap (\f -> LBS.toStrict . f . LBS.fromStrict) (realiseColumnDescLazy cd)
columnDescToTuple :: ColumnDesc a -> (Int, a)
columnDescToTuple cd = (cd ^. the @1, cd ^. the @2)
|
32a40029d89b4327d9696f6c55fb2772cd1ee2ac271c91788f70b45592873c7b | arttuka/reagent-material-ui | folder_copy_outlined.cljs | (ns reagent-mui.icons.folder-copy-outlined
"Imports @mui/icons-material/FolderCopyOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def folder-copy-outlined (create-svg-icon (e "path" #js {"d" "M3 19h17v2H3c-1.1 0-2-.9-2-2V6h2v13zM23 6v9c0 1.1-.9 2-2 2H7c-1.1 0-2-.9-2-2l.01-11c0-1.1.89-2 1.99-2h5l2 2h7c1.1 0 2 .9 2 2zM7 15h14V6h-7.83l-2-2H7v11z"})
"FolderCopyOutlined"))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/c7cd0d7c661ab9df5b0aed0213a6653a9a3f28ea/src/icons/reagent_mui/icons/folder_copy_outlined.cljs | clojure | (ns reagent-mui.icons.folder-copy-outlined
"Imports @mui/icons-material/FolderCopyOutlined as a Reagent component."
(:require-macros [reagent-mui.util :refer [create-svg-icon e]])
(:require [react :as react]
["@mui/material/SvgIcon" :as SvgIcon]
[reagent-mui.util]))
(def folder-copy-outlined (create-svg-icon (e "path" #js {"d" "M3 19h17v2H3c-1.1 0-2-.9-2-2V6h2v13zM23 6v9c0 1.1-.9 2-2 2H7c-1.1 0-2-.9-2-2l.01-11c0-1.1.89-2 1.99-2h5l2 2h7c1.1 0 2 .9 2 2zM7 15h14V6h-7.83l-2-2H7v11z"})
"FolderCopyOutlined"))
|
|
87a46e71f39b8ae3b246404fc17bd4966fe4ccc599f43b0341d339ddcfbe8395 | clojerl/clojerl | rbdict.erl | Copyright ( c ) 2008 . All rights reserved .
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions
%% are met:
%%
1 . Redistributions of source code must retain the above copyright
%% notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
%% notice, this list of conditions and the following disclaimer in the
%% documentation and/or other materials provided with the distribution.
%%
%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
%% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
%% FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDERS OR 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.
%% @doc Dictionary implementation using a red-black tree.
@private
-module(rbdict).
-include("clojerl.hrl").
%% Standard interface.
-export([ new/0
, new/1
, compare_fun/1
, is_key/2
, to_list/1
, to_list/2
, to_list_from/3
, from_list/1
, from_list/2
, size/1
]).
-export([ fetch/2
, find/2
, fetch_keys/1
, fetch_keys/2
, fetch_keys_from/3
, erase/2
]).
-export([ store/3
, append/3
, append_list/3
]).
-export([ update_val/3
, update/3
, update/4
, update_counter/3
]).
-export([ fold/3
, map/2
, filter/2
, merge/3
]).
-export([default_compare/2]).
-type dict() :: {empty, fun()} | {r | b, dict(), any(), any(), dict(), fun()}.
-export_type([dict/0]).
The algorithms here are taken directly from Okasaki and in
ML / Scheme . The interface is compatible with the standard dict
%% interface.
%%
%% The following structures are used to build the the RB-dict:
%%
{ r , Left , Key , , Right }
{ b , Left , Key , , Right }
%% empty
%%
It is interesting to note that expanding out the first argument of
l / rbalance , the colour , in store etc . is actually slower than not
%% doing it. Measured.
%% new() -> Dict.
new() -> new(fun default_compare/2).
new(Compare) when is_function(Compare) ->
{empty, Compare}.
compare_fun({empty, Compare}) -> Compare;
compare_fun({_, _, _, _, _, Compare}) -> Compare.
default_compare(X, X) -> 0;
default_compare(?NIL, _) -> -1;
default_compare(_, ?NIL) -> 1;
default_compare(X, Y) when X < Y -> -1;
default_compare(X, Y) when X > Y -> 1.
%% is_key(Key, Dict) -> true | false.
is_key(_, {empty, _}) -> false;
is_key(K, {_, Left, K1, _, Right, Compare}) when K < K1 ->
case Compare(K, K1) of
-1 -> is_key(K, Left);
1 -> is_key(K, Right);
0 -> true
end.
%% to_list(Dict) -> [{Key,Value}].
-spec to_list(dict()) -> [{any(), any()}].
to_list(T) -> to_list(T, true).
-spec to_list(dict(), boolean()) -> [{any(), any()}].
to_list(T, Ascending) ->
to_list_order(T, Ascending, []).
-spec to_list_order(dict(), boolean(), list()) -> [{any(), any()}].
to_list_order({empty, _}, _Ascending, List) -> List;
to_list_order({_, A, Xk, Xv, B, _}, true, List) ->
to_list_order(A, true, [{Xk, Xv} | to_list_order(B, true, List)]);
to_list_order({_, A, Xk, Xv, B, _}, false, List) ->
to_list_order(B, false, [{Xk, Xv} | to_list_order(A, false, List)]).
-spec to_list_from(dict(), any(), boolean()) -> [{any(), any()}].
to_list_from(T, Key, Ascending) ->
to_list_from(T, Key, Ascending, []).
to_list_from({empty, _Compare}, _Key, _Ascending, _Stack) ->
?NIL;
to_list_from( {_RB, L, K, _V, R, Compare} = Node
, Key
, Ascending
, Stack
) ->
case Compare(Key, K) of
0 -> to_list_from_result([Node | Stack], Ascending, []);
-1 when Ascending -> to_list_from(L, Key, Ascending, [Node | Stack]);
1 when Ascending -> to_list_from(R, Key, Ascending, Stack);
-1 when not Ascending -> to_list_from(L, Key, Ascending, Stack);
1 when not Ascending -> to_list_from(R, Key, Ascending, [Node | Stack])
end.
to_list_from_result([], _Ascending, Result) ->
lists:reverse(Result);
to_list_from_result([{_, L, K, V, R, _} | Stack], Ascending, Result) ->
ChildNode = case Ascending of
true -> R;
false -> L
end,
NewStack = to_list_from_push(ChildNode, Stack, Ascending),
to_list_from_result(NewStack, Ascending, [{K, V} | Result]).
to_list_from_push({empty, _}, Stack, _) ->
Stack;
to_list_from_push({_, L, _, _, _, _} = Node, Stack, true) ->
to_list_from_push(L, [Node | Stack], true);
to_list_from_push({_, _, _, _, R, _} = Node, Stack, false) ->
to_list_from_push(R, [Node | Stack], false).
%% from_list([{Key, Value}]) -> Dict.
from_list(L) ->
from_list(fun default_compare/2, L).
from_list(Compare, L) ->
lists:foldl(fun ({K, V}, D) -> store(K, V, D) end, new(Compare), L).
%% size(Dict) -> int().
size(T) -> size1(T).
size1({empty, _}) -> 0;
size1({_, L, _, _, R, _}) ->
size1(L) + size1(R) + 1.
%% fetch(Key, Dict) -> Value.
fetch(_, {empty, _}) ->
?NIL;
fetch(K, {_, Left, K1, Val, Right, Compare}) ->
case Compare(K, K1) of
-1 -> fetch(K, Left);
1 -> fetch(K, Right);
0 -> Val
end.
find(Key , ) - > { ok , Value } | error .
find(_, {empty, _}) -> error;
find(K, {_, Left, K1, Val, Right, Compare}) ->
case Compare(K, K1) of
-1 -> find(K, Left);
1 -> find(K, Right);
0 -> {ok, Val}
end.
%% fetch_keys(Dict) -> [Key].
fetch_keys(T) -> fetch_keys(T, true).
%% fetch_keys(Dict, Ascending) -> [Key].
fetch_keys(T, Ascending) ->
fetch_keys_order(T, Ascending, []).
fetch_keys_order({empty, _Compare}, _Ascending, Tail) -> Tail;
fetch_keys_order({_RedBlack, L, K, _V, R, _Compare}, true, Tail) ->
fetch_keys_order(L, true, [K | fetch_keys_order(R, true, Tail)]);
fetch_keys_order({_RedBlack, L, K, _V, R, _Compare}, false, Tail) ->
fetch_keys_order(R, false, [K | fetch_keys_order(L, false, Tail)]).
%% fetch_keys_from(Dict, Key, Ascending) -> [Key].
fetch_keys_from(Dict, Key, Ascending) ->
[K || {K, _} <- to_list_from(Dict, Key, Ascending)].
store(Key , , Dict ) - > Dict .
store(K, V, T) ->
{_, L, K1, V1, R, Compare} = store1(K, V, T),
{b, L, K1, V1, R, Compare}. %setelement(1, b, T1).
store1(K, V, {empty, Compare}) ->
{r, {empty, Compare}, K, V, {empty, Compare}, Compare};
store1(K, V, {C, Left, K1, V1, Right, Compare}) ->
case Compare(K, K1) of
-1 -> lbalance(C, store1(K, V, Left), K1, V1, Right, Compare);
1 -> rbalance(C, Left, K1, V1, store1(K, V, Right), Compare);
0 -> {C, Left, K, V, Right, Compare}
end.
Expanding out l / rbalance is slower !
%% store1(K, V, empty) -> {r, empty, K, V, empty};
store1(K , V , { r , Left , K1 , V1 , Right } ) - >
if K < K1 - > { r , store1(K , V , Left ) , K1 , V1 , Right } ;
K > K1 - > { r , Left , K1 , V1 , store1(K , V , Right ) } ;
%% true -> {r, Left, K, V, Right}
%% end;
store1(K , V , { b , Left , K1 , V1 , Right } ) - >
%% if K < K1 ->
lbalance(store1(K , V , Left ) , K1 , V1 , Right ) ;
%% K > K1 ->
rbalance(Left , K1 , V1 , store1(K , V , Right ) ) ;
%% true -> {b, Left, K, V, Right}
%% end.
append(Key , , Dict ) - > Dict .
append(K, V, T) ->
{_, L, K1, V1, R, Compare} = append1(K, V, T),
{b, L, K1, V1, R, Compare}. %setelement(1, b, T1).
append1(K, V, {empty, Compare}) ->
{r, {empty, Compare}, K, [V], {empty, Compare}};
append1(K, V, {C, Left, K1, V1, Right, Compare}) ->
case Compare(K, K1) of
-1 -> lbalance(C, append1(K, V, Left), K1, V1, Right, Compare);
1 -> rbalance(C, Left, K1, V1, append1(K, V, Right), Compare);
0 -> {C, Left, K, V1 ++ [V], Right, Compare}
end.
append(Key , [ ] , Dict ) - > Dict .
append_list(K, V, T) ->
{_, L, K1, V1, R, Compare} = append_list1(K, V, T),
{b, L, K1, V1, R, Compare}. %setelement(1, b, T1).
append_list1(K, V, {empty, Compare}) ->
{r, {empty, Compare}, K, V, {empty, Compare}};
append_list1(K, V, {C, Left, K1, V1, Right, Compare}) ->
case Compare(K, K1) of
-1 -> lbalance(C, append_list1(K, V, Left), K1, V1, Right, Compare);
1 -> rbalance(C, Left, K1, V1, append_list1(K, V, Right), Compare);
0 -> {C, Left, K, V1 ++ V, Right, Compare}
end.
update_val(Key , , Dict ) - > Dict .
update_val(K, V, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> {RB, update_val(K, V, A), Xk, Xv, B, Compare};
1 -> {RB, A, Xk, Xv, update_val(K, V, B), Compare};
0 -> {RB, A, Xk, V, B, Compare}
end.
update(Key , Fun , Dict ) - > Dict .
update(K, F, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> {RB, update(K, F, A), Xk, Xv, B, Compare};
1 -> {RB, A, Xk, Xv, update(K, F, B), Compare};
0 -> {RB, A, Xk, F(Xv), B, Compare}
end.
%% update(Key, Fun, Init, Dict) -> Dict.
update(K, F, I, T) ->
{_, L, K1, V1, R, Compare} = update1(K, F, I, T),
{b, L, K1, V1, R, Compare}. %setelement(1, b, T1).
update1(K, _, I, {empty, Compare}) ->
{r, {empty, Compare}, K, I, {empty, Compare}, Compare};
update1(K, F, I, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> lbalance(RB, update1(K, F, I, A), Xk, Xv, B, Compare);
1 -> rbalance(RB, A, Xk, Xv, update1(K, F, I, B), Compare);
0 -> {RB, A, Xk, F(Xv), B, Compare}
end.
update_counter(Key , Incr , Dict ) - > Dict .
update_counter(K, I, T) ->
{_, L, K1, V1, R, Compare} = update_counter1(K, I, T),
{b, L, K1, V1, R, Compare}. %setelement(1, b, T1).
update_counter1(K, I, {empty, Compare}) ->
{r, {empty, Compare}, K, I, {empty, Compare}, Compare};
update_counter1(K, I, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> lbalance(RB, update_counter1(K, I, A), Xk, Xv, B, Compare);
1 -> rbalance(RB, A, Xk, Xv, update_counter1(K, I, B), Compare);
0 -> {RB, A, Xk, Xv + I, B}
end.
lbalance(Colour , Left , Key , , Right ) .
rbalance(Colour , Left , Key , , Right ) .
%% Balance a tree after (possibly) adding a node to the left/right.
lbalance(b, {r, {r, A, Xk, Xv, B, F}, Yk, Yv, C, F}, Zk, Zv, D, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
lbalance(b, {r, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F}, Zk, Zv, D, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
lbalance(C, A, Xk, Xv, B, F) -> {C, A, Xk, Xv, B, F}.
rbalance(b, A, Xk, Xv, {r, {r, B, Yk, Yv, C, F}, Zk, Zv, D, F}, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, {r, C, Zk, Zv, D, F}, F}, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
rbalance(C, A, Xk, Xv, B, F) -> {C, A, Xk, Xv, B, F}.
erase(Key , ) - > Dict .
erase(K, T) ->
{T1, _} = erase_aux(K, T),
T1.
erase_aux(Key , ) - > { Node , Decreased } .
erase_aux(_, {empty, F}) -> {{empty, F}, false};
erase_aux(K, {b, A, Xk, Xv, B, F}) ->
case F(K, Xk) of
-1 ->
{A1, Dec} = erase_aux(K, A),
if Dec -> unbalright(b, A1, Xk, Xv, B, F);
true -> {{b, A1, Xk, Xv, B, F}, false}
end;
1 ->
{B1, Dec} = erase_aux(K, B),
if Dec -> unballeft(b, A, Xk, Xv, B1, F);
true -> {{b, A, Xk, Xv, B1, F}, false}
end;
0 ->
case B of
{empty, _} -> blackify(A);
_ ->
{B1, {Mk, Mv}, Dec} = erase_min(B),
erase_aux2(Dec, b, A, Mk, Mv, B1, F)
end
end;
erase_aux(K, {r, A, Xk, Xv, B, F}) ->
case F(K, Xk) of
-1 ->
{A1, Dec} = erase_aux(K, A),
if Dec -> unbalright(r, A1, Xk, Xv, B, F);
true -> {{r, A1, Xk, Xv, B, F}, false}
end;
1 ->
{B1, Dec} = erase_aux(K, B),
if Dec -> unballeft(r, A, Xk, Xv, B1, F);
true -> {{r, A, Xk, Xv, B1, F}, false}
end;
0 ->
case B of
{empty, _} -> {A, false};
_ ->
{B1, {Mk, Mv}, Dec} = erase_min(B),
erase_aux2(Dec, r, A, Mk, Mv, B1, F)
end
end.
erase_aux2(true = _Dec, Color, A, Mk, Mv, B1, F) ->
unballeft(Color, A, Mk, Mv, B1, F);
erase_aux2(_, Color, A, Mk, Mv, B1, F) ->
{{Color, A, Mk, Mv, B1, F}, false}.
erase_min(Node ) - > { Node , { NodeKey , NodeVal } , Decreased } .
erase_min({b, {empty, F}, Xk, Xv, {empty, F}, F}) ->
{{empty, F}, {Xk, Xv}, true};
erase_min({b, {empty, F}, Xk, Xv, {r, A, Yk, Yv, B, F}, F}) ->
{{b, A, Yk, Yv, B, F}, {Xk, Xv}, false};
erase_min({b, {empty, _}, _, _, {b, _, _, _, _, _}, _}) -> exit(boom);
erase_min({r, {empty, F}, Xk, Xv, A, F}) ->
{A, {Xk, Xv}, false};
%% Rec from left
erase_min({b, A, Xk, Xv, B, F}) ->
{A1, Min, Dec} = erase_min(A),
if Dec ->
{T, Dec1} = unbalright(b, A1, Xk, Xv, B, F),
{T, Min, Dec1};
true -> {{b, A1, Xk, Xv, B, F}, Min, false}
end;
erase_min({r, A, Xk, Xv, B, F}) ->
{A1, Min, Dec} = erase_min(A),
if Dec ->
{T, Dec1} = unbalright(r, A1, Xk, Xv, B, F),
{T, Min, Dec1};
true -> {{r, A1, Xk, Xv, B, F}, Min, false}
end.
blackify({r, A, K, V, B, F}) -> {{b, A, K, V, B, F}, false};
blackify(Node) -> {Node, true}.
unballeft(r, {b, A, Xk, Xv, B, F}, Yk, Yv, C, F) ->
{lbalance(b, {r, A, Xk, Xv, B, F}, Yk, Yv, C, F), false};
unballeft(b, {b, A, Xk, Xv, B, F}, Yk, Yv, C, F) ->
{lbalance(b, {r, A, Xk, Xv, B, F}, Yk, Yv, C, F), true};
unballeft(b, {r, A, Xk, Xv, {b, B, Yk, Yv, C, F}, F}, Zk, Zv, D, F) ->
{{b, A, Xk, Xv, lbalance(b, {r, B, Yk, Yv, C, F}, Zk, Zv, D, F), F}, false}.
unbalright(r, A, Xk, Xv, {b, B, Yk, Yv, C, F}, F) ->
{rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F), false};
unbalright(b, A, Xk, Xv, {b, B, Yk, Yv, C, F}, F) ->
{rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F), true};
unbalright(b, A, Xk, Xv, {r, {b, B, Yk, Yv, C, F}, Zk, Zv, D, F}, F) ->
{{b, rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F), Zk, Zv, D, F}, false}.
fold(Fun , Acc , Dict ) - > Acc .
fold(_, Acc, {empty, _}) -> Acc;
fold(F, Acc, {_, A, Xk, Xv, B, _}) ->
fold(F, F(Xk, Xv, fold(F, Acc, A)), B).
%% map(Fun, Dict) -> Dict.
map(_, {empty, _} = T) -> T;
map(F, {RB, A, Xk, Xv, B, Compare}) ->
{RB, map(F, A), Xk, F(Xk, Xv), map(F, B), Compare}.
filter(Fun , ) - > Dict .
filter(F, T) -> filter(F, T, new()).
filter(_, {empty, _}, New) -> New;
filter(F, {_, A, Xk, Xv, B, _}, New0) ->
New1 = filter(F, A, New0),
New2 = case F(Xk, Xv) of
true -> store(Xk, Xv, New1);
false -> New1
end,
filter(F, B, New2).
merge(Fun , Dict , Dict ) - > Dict .
merge(F, D1, D2) ->
fold(fun (K, V2, D) ->
update(K, fun(V1) -> F(K, V1, V2) end, V2, D)
end, D1, D2).
| null | https://raw.githubusercontent.com/clojerl/clojerl/5b412b87de13811b5a6ee4d82329d6a44dc499f0/src/erl/rbdict.erl | erlang |
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
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.
@doc Dictionary implementation using a red-black tree.
Standard interface.
interface.
The following structures are used to build the the RB-dict:
empty
doing it. Measured.
new() -> Dict.
is_key(Key, Dict) -> true | false.
to_list(Dict) -> [{Key,Value}].
from_list([{Key, Value}]) -> Dict.
size(Dict) -> int().
fetch(Key, Dict) -> Value.
fetch_keys(Dict) -> [Key].
fetch_keys(Dict, Ascending) -> [Key].
fetch_keys_from(Dict, Key, Ascending) -> [Key].
setelement(1, b, T1).
store1(K, V, empty) -> {r, empty, K, V, empty};
true -> {r, Left, K, V, Right}
end;
if K < K1 ->
K > K1 ->
true -> {b, Left, K, V, Right}
end.
setelement(1, b, T1).
setelement(1, b, T1).
update(Key, Fun, Init, Dict) -> Dict.
setelement(1, b, T1).
setelement(1, b, T1).
Balance a tree after (possibly) adding a node to the left/right.
Rec from left
map(Fun, Dict) -> Dict. | Copyright ( c ) 2008 . All rights reserved .
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
COPYRIGHT HOLDERS OR 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
@private
-module(rbdict).
-include("clojerl.hrl").
-export([ new/0
, new/1
, compare_fun/1
, is_key/2
, to_list/1
, to_list/2
, to_list_from/3
, from_list/1
, from_list/2
, size/1
]).
-export([ fetch/2
, find/2
, fetch_keys/1
, fetch_keys/2
, fetch_keys_from/3
, erase/2
]).
-export([ store/3
, append/3
, append_list/3
]).
-export([ update_val/3
, update/3
, update/4
, update_counter/3
]).
-export([ fold/3
, map/2
, filter/2
, merge/3
]).
-export([default_compare/2]).
-type dict() :: {empty, fun()} | {r | b, dict(), any(), any(), dict(), fun()}.
-export_type([dict/0]).
The algorithms here are taken directly from Okasaki and in
ML / Scheme . The interface is compatible with the standard dict
{ r , Left , Key , , Right }
{ b , Left , Key , , Right }
It is interesting to note that expanding out the first argument of
l / rbalance , the colour , in store etc . is actually slower than not
new() -> new(fun default_compare/2).
new(Compare) when is_function(Compare) ->
{empty, Compare}.
compare_fun({empty, Compare}) -> Compare;
compare_fun({_, _, _, _, _, Compare}) -> Compare.
default_compare(X, X) -> 0;
default_compare(?NIL, _) -> -1;
default_compare(_, ?NIL) -> 1;
default_compare(X, Y) when X < Y -> -1;
default_compare(X, Y) when X > Y -> 1.
is_key(_, {empty, _}) -> false;
is_key(K, {_, Left, K1, _, Right, Compare}) when K < K1 ->
case Compare(K, K1) of
-1 -> is_key(K, Left);
1 -> is_key(K, Right);
0 -> true
end.
-spec to_list(dict()) -> [{any(), any()}].
to_list(T) -> to_list(T, true).
-spec to_list(dict(), boolean()) -> [{any(), any()}].
to_list(T, Ascending) ->
to_list_order(T, Ascending, []).
-spec to_list_order(dict(), boolean(), list()) -> [{any(), any()}].
to_list_order({empty, _}, _Ascending, List) -> List;
to_list_order({_, A, Xk, Xv, B, _}, true, List) ->
to_list_order(A, true, [{Xk, Xv} | to_list_order(B, true, List)]);
to_list_order({_, A, Xk, Xv, B, _}, false, List) ->
to_list_order(B, false, [{Xk, Xv} | to_list_order(A, false, List)]).
-spec to_list_from(dict(), any(), boolean()) -> [{any(), any()}].
to_list_from(T, Key, Ascending) ->
to_list_from(T, Key, Ascending, []).
to_list_from({empty, _Compare}, _Key, _Ascending, _Stack) ->
?NIL;
to_list_from( {_RB, L, K, _V, R, Compare} = Node
, Key
, Ascending
, Stack
) ->
case Compare(Key, K) of
0 -> to_list_from_result([Node | Stack], Ascending, []);
-1 when Ascending -> to_list_from(L, Key, Ascending, [Node | Stack]);
1 when Ascending -> to_list_from(R, Key, Ascending, Stack);
-1 when not Ascending -> to_list_from(L, Key, Ascending, Stack);
1 when not Ascending -> to_list_from(R, Key, Ascending, [Node | Stack])
end.
to_list_from_result([], _Ascending, Result) ->
lists:reverse(Result);
to_list_from_result([{_, L, K, V, R, _} | Stack], Ascending, Result) ->
ChildNode = case Ascending of
true -> R;
false -> L
end,
NewStack = to_list_from_push(ChildNode, Stack, Ascending),
to_list_from_result(NewStack, Ascending, [{K, V} | Result]).
to_list_from_push({empty, _}, Stack, _) ->
Stack;
to_list_from_push({_, L, _, _, _, _} = Node, Stack, true) ->
to_list_from_push(L, [Node | Stack], true);
to_list_from_push({_, _, _, _, R, _} = Node, Stack, false) ->
to_list_from_push(R, [Node | Stack], false).
from_list(L) ->
from_list(fun default_compare/2, L).
from_list(Compare, L) ->
lists:foldl(fun ({K, V}, D) -> store(K, V, D) end, new(Compare), L).
size(T) -> size1(T).
size1({empty, _}) -> 0;
size1({_, L, _, _, R, _}) ->
size1(L) + size1(R) + 1.
fetch(_, {empty, _}) ->
?NIL;
fetch(K, {_, Left, K1, Val, Right, Compare}) ->
case Compare(K, K1) of
-1 -> fetch(K, Left);
1 -> fetch(K, Right);
0 -> Val
end.
find(Key , ) - > { ok , Value } | error .
find(_, {empty, _}) -> error;
find(K, {_, Left, K1, Val, Right, Compare}) ->
case Compare(K, K1) of
-1 -> find(K, Left);
1 -> find(K, Right);
0 -> {ok, Val}
end.
fetch_keys(T) -> fetch_keys(T, true).
fetch_keys(T, Ascending) ->
fetch_keys_order(T, Ascending, []).
fetch_keys_order({empty, _Compare}, _Ascending, Tail) -> Tail;
fetch_keys_order({_RedBlack, L, K, _V, R, _Compare}, true, Tail) ->
fetch_keys_order(L, true, [K | fetch_keys_order(R, true, Tail)]);
fetch_keys_order({_RedBlack, L, K, _V, R, _Compare}, false, Tail) ->
fetch_keys_order(R, false, [K | fetch_keys_order(L, false, Tail)]).
fetch_keys_from(Dict, Key, Ascending) ->
[K || {K, _} <- to_list_from(Dict, Key, Ascending)].
store(Key , , Dict ) - > Dict .
store(K, V, T) ->
{_, L, K1, V1, R, Compare} = store1(K, V, T),
store1(K, V, {empty, Compare}) ->
{r, {empty, Compare}, K, V, {empty, Compare}, Compare};
store1(K, V, {C, Left, K1, V1, Right, Compare}) ->
case Compare(K, K1) of
-1 -> lbalance(C, store1(K, V, Left), K1, V1, Right, Compare);
1 -> rbalance(C, Left, K1, V1, store1(K, V, Right), Compare);
0 -> {C, Left, K, V, Right, Compare}
end.
Expanding out l / rbalance is slower !
store1(K , V , { r , Left , K1 , V1 , Right } ) - >
if K < K1 - > { r , store1(K , V , Left ) , K1 , V1 , Right } ;
K > K1 - > { r , Left , K1 , V1 , store1(K , V , Right ) } ;
store1(K , V , { b , Left , K1 , V1 , Right } ) - >
lbalance(store1(K , V , Left ) , K1 , V1 , Right ) ;
rbalance(Left , K1 , V1 , store1(K , V , Right ) ) ;
append(Key , , Dict ) - > Dict .
append(K, V, T) ->
{_, L, K1, V1, R, Compare} = append1(K, V, T),
append1(K, V, {empty, Compare}) ->
{r, {empty, Compare}, K, [V], {empty, Compare}};
append1(K, V, {C, Left, K1, V1, Right, Compare}) ->
case Compare(K, K1) of
-1 -> lbalance(C, append1(K, V, Left), K1, V1, Right, Compare);
1 -> rbalance(C, Left, K1, V1, append1(K, V, Right), Compare);
0 -> {C, Left, K, V1 ++ [V], Right, Compare}
end.
append(Key , [ ] , Dict ) - > Dict .
append_list(K, V, T) ->
{_, L, K1, V1, R, Compare} = append_list1(K, V, T),
append_list1(K, V, {empty, Compare}) ->
{r, {empty, Compare}, K, V, {empty, Compare}};
append_list1(K, V, {C, Left, K1, V1, Right, Compare}) ->
case Compare(K, K1) of
-1 -> lbalance(C, append_list1(K, V, Left), K1, V1, Right, Compare);
1 -> rbalance(C, Left, K1, V1, append_list1(K, V, Right), Compare);
0 -> {C, Left, K, V1 ++ V, Right, Compare}
end.
update_val(Key , , Dict ) - > Dict .
update_val(K, V, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> {RB, update_val(K, V, A), Xk, Xv, B, Compare};
1 -> {RB, A, Xk, Xv, update_val(K, V, B), Compare};
0 -> {RB, A, Xk, V, B, Compare}
end.
update(Key , Fun , Dict ) - > Dict .
update(K, F, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> {RB, update(K, F, A), Xk, Xv, B, Compare};
1 -> {RB, A, Xk, Xv, update(K, F, B), Compare};
0 -> {RB, A, Xk, F(Xv), B, Compare}
end.
update(K, F, I, T) ->
{_, L, K1, V1, R, Compare} = update1(K, F, I, T),
update1(K, _, I, {empty, Compare}) ->
{r, {empty, Compare}, K, I, {empty, Compare}, Compare};
update1(K, F, I, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> lbalance(RB, update1(K, F, I, A), Xk, Xv, B, Compare);
1 -> rbalance(RB, A, Xk, Xv, update1(K, F, I, B), Compare);
0 -> {RB, A, Xk, F(Xv), B, Compare}
end.
update_counter(Key , Incr , Dict ) - > Dict .
update_counter(K, I, T) ->
{_, L, K1, V1, R, Compare} = update_counter1(K, I, T),
update_counter1(K, I, {empty, Compare}) ->
{r, {empty, Compare}, K, I, {empty, Compare}, Compare};
update_counter1(K, I, {RB, A, Xk, Xv, B, Compare}) ->
case Compare(K, Xk) of
-1 -> lbalance(RB, update_counter1(K, I, A), Xk, Xv, B, Compare);
1 -> rbalance(RB, A, Xk, Xv, update_counter1(K, I, B), Compare);
0 -> {RB, A, Xk, Xv + I, B}
end.
lbalance(Colour , Left , Key , , Right ) .
rbalance(Colour , Left , Key , , Right ) .
lbalance(b, {r, {r, A, Xk, Xv, B, F}, Yk, Yv, C, F}, Zk, Zv, D, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
lbalance(b, {r, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F}, Zk, Zv, D, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
lbalance(C, A, Xk, Xv, B, F) -> {C, A, Xk, Xv, B, F}.
rbalance(b, A, Xk, Xv, {r, {r, B, Yk, Yv, C, F}, Zk, Zv, D, F}, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, {r, C, Zk, Zv, D, F}, F}, F) ->
{r, {b, A, Xk, Xv, B, F}, Yk, Yv, {b, C, Zk, Zv, D, F}, F};
rbalance(C, A, Xk, Xv, B, F) -> {C, A, Xk, Xv, B, F}.
erase(Key , ) - > Dict .
erase(K, T) ->
{T1, _} = erase_aux(K, T),
T1.
erase_aux(Key , ) - > { Node , Decreased } .
erase_aux(_, {empty, F}) -> {{empty, F}, false};
erase_aux(K, {b, A, Xk, Xv, B, F}) ->
case F(K, Xk) of
-1 ->
{A1, Dec} = erase_aux(K, A),
if Dec -> unbalright(b, A1, Xk, Xv, B, F);
true -> {{b, A1, Xk, Xv, B, F}, false}
end;
1 ->
{B1, Dec} = erase_aux(K, B),
if Dec -> unballeft(b, A, Xk, Xv, B1, F);
true -> {{b, A, Xk, Xv, B1, F}, false}
end;
0 ->
case B of
{empty, _} -> blackify(A);
_ ->
{B1, {Mk, Mv}, Dec} = erase_min(B),
erase_aux2(Dec, b, A, Mk, Mv, B1, F)
end
end;
erase_aux(K, {r, A, Xk, Xv, B, F}) ->
case F(K, Xk) of
-1 ->
{A1, Dec} = erase_aux(K, A),
if Dec -> unbalright(r, A1, Xk, Xv, B, F);
true -> {{r, A1, Xk, Xv, B, F}, false}
end;
1 ->
{B1, Dec} = erase_aux(K, B),
if Dec -> unballeft(r, A, Xk, Xv, B1, F);
true -> {{r, A, Xk, Xv, B1, F}, false}
end;
0 ->
case B of
{empty, _} -> {A, false};
_ ->
{B1, {Mk, Mv}, Dec} = erase_min(B),
erase_aux2(Dec, r, A, Mk, Mv, B1, F)
end
end.
erase_aux2(true = _Dec, Color, A, Mk, Mv, B1, F) ->
unballeft(Color, A, Mk, Mv, B1, F);
erase_aux2(_, Color, A, Mk, Mv, B1, F) ->
{{Color, A, Mk, Mv, B1, F}, false}.
erase_min(Node ) - > { Node , { NodeKey , NodeVal } , Decreased } .
erase_min({b, {empty, F}, Xk, Xv, {empty, F}, F}) ->
{{empty, F}, {Xk, Xv}, true};
erase_min({b, {empty, F}, Xk, Xv, {r, A, Yk, Yv, B, F}, F}) ->
{{b, A, Yk, Yv, B, F}, {Xk, Xv}, false};
erase_min({b, {empty, _}, _, _, {b, _, _, _, _, _}, _}) -> exit(boom);
erase_min({r, {empty, F}, Xk, Xv, A, F}) ->
{A, {Xk, Xv}, false};
erase_min({b, A, Xk, Xv, B, F}) ->
{A1, Min, Dec} = erase_min(A),
if Dec ->
{T, Dec1} = unbalright(b, A1, Xk, Xv, B, F),
{T, Min, Dec1};
true -> {{b, A1, Xk, Xv, B, F}, Min, false}
end;
erase_min({r, A, Xk, Xv, B, F}) ->
{A1, Min, Dec} = erase_min(A),
if Dec ->
{T, Dec1} = unbalright(r, A1, Xk, Xv, B, F),
{T, Min, Dec1};
true -> {{r, A1, Xk, Xv, B, F}, Min, false}
end.
blackify({r, A, K, V, B, F}) -> {{b, A, K, V, B, F}, false};
blackify(Node) -> {Node, true}.
unballeft(r, {b, A, Xk, Xv, B, F}, Yk, Yv, C, F) ->
{lbalance(b, {r, A, Xk, Xv, B, F}, Yk, Yv, C, F), false};
unballeft(b, {b, A, Xk, Xv, B, F}, Yk, Yv, C, F) ->
{lbalance(b, {r, A, Xk, Xv, B, F}, Yk, Yv, C, F), true};
unballeft(b, {r, A, Xk, Xv, {b, B, Yk, Yv, C, F}, F}, Zk, Zv, D, F) ->
{{b, A, Xk, Xv, lbalance(b, {r, B, Yk, Yv, C, F}, Zk, Zv, D, F), F}, false}.
unbalright(r, A, Xk, Xv, {b, B, Yk, Yv, C, F}, F) ->
{rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F), false};
unbalright(b, A, Xk, Xv, {b, B, Yk, Yv, C, F}, F) ->
{rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F), true};
unbalright(b, A, Xk, Xv, {r, {b, B, Yk, Yv, C, F}, Zk, Zv, D, F}, F) ->
{{b, rbalance(b, A, Xk, Xv, {r, B, Yk, Yv, C, F}, F), Zk, Zv, D, F}, false}.
fold(Fun , Acc , Dict ) - > Acc .
fold(_, Acc, {empty, _}) -> Acc;
fold(F, Acc, {_, A, Xk, Xv, B, _}) ->
fold(F, F(Xk, Xv, fold(F, Acc, A)), B).
map(_, {empty, _} = T) -> T;
map(F, {RB, A, Xk, Xv, B, Compare}) ->
{RB, map(F, A), Xk, F(Xk, Xv), map(F, B), Compare}.
filter(Fun , ) - > Dict .
filter(F, T) -> filter(F, T, new()).
filter(_, {empty, _}, New) -> New;
filter(F, {_, A, Xk, Xv, B, _}, New0) ->
New1 = filter(F, A, New0),
New2 = case F(Xk, Xv) of
true -> store(Xk, Xv, New1);
false -> New1
end,
filter(F, B, New2).
merge(Fun , Dict , Dict ) - > Dict .
merge(F, D1, D2) ->
fold(fun (K, V2, D) ->
update(K, fun(V1) -> F(K, V1, V2) end, V2, D)
end, D1, D2).
|
49ac2a9f56bb676020406ce23ba3170211e2c4f4f681c4fe2dfd6064f315bfa9 | Elzair/nazghul | trigrave-zones.scm | ;;----------------------------------------------------------------------------
Zones for 's Hut
;;
;; A zone is a rectangle formatted as:
;; (upper-left-corner-x upper-left-corner-y width height)
;;----------------------------------------------------------------------------
(define (mk-zone x y w h) (list 'p_trigrave x y w h))
(define trigrave-chants-bed (mk-zone 12 6 1 1))
(define trigrave-forge (mk-zone 25 4 5 5))
(define trigrave-jims-bed (mk-zone 25 11 1 1))
(define trigrave-tavern-hall (mk-zone 18 23 8 6))
(define trigrave-tavern-kitchen (mk-zone 27 25 3 5))
(define trigrave-tavern-bed (mk-zone 27 22 1 1))
(define trigrave-tavern-table-1a (mk-zone 19 23 1 1))
(define trigrave-tavern-table-1d (mk-zone 21 23 1 1))
(define trigrave-tavern-table-3a (mk-zone 19 27 1 1))
(define trigrave-inn-counter (mk-zone 5 4 9 3))
(define trigrave-gwens-bed (mk-zone 12 2 1 1))
(define trigrave-gwens-room (mk-zone 11 2 2 3))
(define trigrave-inn-room-1 (mk-zone 2 6 2 2))
(define trigrave-inn-room-2 (mk-zone 2 9 2 2))
(define trigrave-inn-room-3 (mk-zone 11 6 2 2))
(define trigrave-inn-room-4 (mk-zone 11 9 2 2))
(define trigrave-east-west-road (mk-zone 0 15 32 3))
(define trigrave-earls-bed (mk-zone 2 9 1 1))
(define trigrave-earls-counter (mk-zone 2 24 5 1))
(define trigrave-earls-room (mk-zone 2 9 2 2))
| null | https://raw.githubusercontent.com/Elzair/nazghul/8f3a45ed6289cd9f469c4ff618d39366f2fbc1d8/worlds/haxima-1.001/trigrave-zones.scm | scheme | ----------------------------------------------------------------------------
A zone is a rectangle formatted as:
(upper-left-corner-x upper-left-corner-y width height)
---------------------------------------------------------------------------- | Zones for 's Hut
(define (mk-zone x y w h) (list 'p_trigrave x y w h))
(define trigrave-chants-bed (mk-zone 12 6 1 1))
(define trigrave-forge (mk-zone 25 4 5 5))
(define trigrave-jims-bed (mk-zone 25 11 1 1))
(define trigrave-tavern-hall (mk-zone 18 23 8 6))
(define trigrave-tavern-kitchen (mk-zone 27 25 3 5))
(define trigrave-tavern-bed (mk-zone 27 22 1 1))
(define trigrave-tavern-table-1a (mk-zone 19 23 1 1))
(define trigrave-tavern-table-1d (mk-zone 21 23 1 1))
(define trigrave-tavern-table-3a (mk-zone 19 27 1 1))
(define trigrave-inn-counter (mk-zone 5 4 9 3))
(define trigrave-gwens-bed (mk-zone 12 2 1 1))
(define trigrave-gwens-room (mk-zone 11 2 2 3))
(define trigrave-inn-room-1 (mk-zone 2 6 2 2))
(define trigrave-inn-room-2 (mk-zone 2 9 2 2))
(define trigrave-inn-room-3 (mk-zone 11 6 2 2))
(define trigrave-inn-room-4 (mk-zone 11 9 2 2))
(define trigrave-east-west-road (mk-zone 0 15 32 3))
(define trigrave-earls-bed (mk-zone 2 9 1 1))
(define trigrave-earls-counter (mk-zone 2 24 5 1))
(define trigrave-earls-room (mk-zone 2 9 2 2))
|
f97cb2f1bed93aa4e813e2ea0922130a54a15576a2b84fa36ab2c1e239dc5ce7 | pyr/cyanite | dsl_test.clj | (ns io.cyanite.dsl-test
(:require [io.cyanite.query.parser :as parser]
[io.cyanite.query.path :as path]
[clojure.test :refer :all]))
(deftest ast-test
(let [inputs [["simple path"
"foo"
[:path "foo"]
#{"foo"}]
["wildcard path"
"foo.*"
[:path "foo.*"]
#{"foo.*"}]
["absolute"
"absolute(foo)"
[:absolute [:path "foo"]]
#{"foo"}]
["aggregate line"
"aggregateLine(foo,'max')"
[:aggregateline [:path "foo"] "max"]
#{"foo"}]
["alias"
"alias(foo,'bar')"
[:alias [:path "foo"] "bar"]
#{"foo"}]
["alias by metric"
"aliasByMetric(foo)"
[:aliasmetric [:path "foo"]]
#{"foo"}]
["alias by node (2-arity)"
"aliasByNode(foo,5)"
[:aliasnode [:path "foo"] "5"]
#{"foo"}]
["alias by node (3-arity)"
"aliasByNode(foo,5,30)"
[:aliasnode [:path "foo"] "5" "30"]
#{"foo"}]
["alias sub"
"aliasSub(foo,'foo','bar')"
[:aliassub [:path "foo"] "foo" "bar"]
#{"foo"}]
["alpha"
"alpha(foo,0.5)"
[:alpha [:path "foo"] "0.5"]
#{"foo"}]
["area between"
"areaBetween(foo,bar,baz)"
[:areabetween [:path "foo"]
[:path "bar"]
[:path "baz"]]
#{"foo" "bar" "baz"}]
["as percent (arity-1)"
"aspercent(foo)"
[:aspercent [:path "foo"]]
#{"foo"}]
["as percent (arity-2)"
"asPercent(foo,100)"
[:aspercent [:path "foo"] "100"]
#{"foo"}]
["as percent (arity-2 with expr)"
"asPercent(foo,alias(bar,'baz'))"
[:aspercent [:path "foo"] [:alias [:path "bar"] "baz"]]
#{"foo" "bar"}]
["average agove"
"averageAbove(foo,5.2)"
[:avgabove [:path "foo"] "5.2"]
#{"foo"}]
["average below"
"averageBelow(foo,5.2)"
[:avgbelow [:path "foo"] "5.2"]
#{"foo"}]
["group"
"group(foo,bar,baz,foo,qux)"
[:group [:path "foo"]
[:path "bar"]
[:path "baz"]
[:path "foo"]
[:path "qux"]]
#{"foo" "bar" "baz" "qux"}]
["scale"
"scale(foo,5)"
[:scale [:path "foo"] "5"]
#{"foo"}]
]]
(doseq [[shortname query expected-tokens paths] inputs
:let [tokens (parser/query->tokens query)]]
(testing (str "tokens output for " shortname)
(is (= expected-tokens tokens)))
(testing (str "parsed paths for " shortname)
(is (= paths (path/tokens->paths tokens)))))))
| null | https://raw.githubusercontent.com/pyr/cyanite/2b9a1f26df808abdad3465dd1946036749b93000/test/io/cyanite/dsl_test.clj | clojure | (ns io.cyanite.dsl-test
(:require [io.cyanite.query.parser :as parser]
[io.cyanite.query.path :as path]
[clojure.test :refer :all]))
(deftest ast-test
(let [inputs [["simple path"
"foo"
[:path "foo"]
#{"foo"}]
["wildcard path"
"foo.*"
[:path "foo.*"]
#{"foo.*"}]
["absolute"
"absolute(foo)"
[:absolute [:path "foo"]]
#{"foo"}]
["aggregate line"
"aggregateLine(foo,'max')"
[:aggregateline [:path "foo"] "max"]
#{"foo"}]
["alias"
"alias(foo,'bar')"
[:alias [:path "foo"] "bar"]
#{"foo"}]
["alias by metric"
"aliasByMetric(foo)"
[:aliasmetric [:path "foo"]]
#{"foo"}]
["alias by node (2-arity)"
"aliasByNode(foo,5)"
[:aliasnode [:path "foo"] "5"]
#{"foo"}]
["alias by node (3-arity)"
"aliasByNode(foo,5,30)"
[:aliasnode [:path "foo"] "5" "30"]
#{"foo"}]
["alias sub"
"aliasSub(foo,'foo','bar')"
[:aliassub [:path "foo"] "foo" "bar"]
#{"foo"}]
["alpha"
"alpha(foo,0.5)"
[:alpha [:path "foo"] "0.5"]
#{"foo"}]
["area between"
"areaBetween(foo,bar,baz)"
[:areabetween [:path "foo"]
[:path "bar"]
[:path "baz"]]
#{"foo" "bar" "baz"}]
["as percent (arity-1)"
"aspercent(foo)"
[:aspercent [:path "foo"]]
#{"foo"}]
["as percent (arity-2)"
"asPercent(foo,100)"
[:aspercent [:path "foo"] "100"]
#{"foo"}]
["as percent (arity-2 with expr)"
"asPercent(foo,alias(bar,'baz'))"
[:aspercent [:path "foo"] [:alias [:path "bar"] "baz"]]
#{"foo" "bar"}]
["average agove"
"averageAbove(foo,5.2)"
[:avgabove [:path "foo"] "5.2"]
#{"foo"}]
["average below"
"averageBelow(foo,5.2)"
[:avgbelow [:path "foo"] "5.2"]
#{"foo"}]
["group"
"group(foo,bar,baz,foo,qux)"
[:group [:path "foo"]
[:path "bar"]
[:path "baz"]
[:path "foo"]
[:path "qux"]]
#{"foo" "bar" "baz" "qux"}]
["scale"
"scale(foo,5)"
[:scale [:path "foo"] "5"]
#{"foo"}]
]]
(doseq [[shortname query expected-tokens paths] inputs
:let [tokens (parser/query->tokens query)]]
(testing (str "tokens output for " shortname)
(is (= expected-tokens tokens)))
(testing (str "parsed paths for " shortname)
(is (= paths (path/tokens->paths tokens)))))))
|
|
543b9ace50041e0a71ab57bf8db25818b937eaa90a666c166cc480a2e5298efa | brendanhay/amazonka | ListCertificates.hs | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
{-# LANGUAGE StrictData #-}
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
-- |
Module : Amazonka . Transfer . ListCertificates
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
-- Returns a list of the current certificates that have been imported into
-- Transfer Family. If you want to limit the results to a certain number,
supply a value for the @MaxResults@ parameter . If you ran the command
-- previously and received a value for the @NextToken@ parameter, you can
-- supply that value to continue listing certificates from where you left
-- off.
--
-- This operation returns paginated results.
module Amazonka.Transfer.ListCertificates
( -- * Creating a Request
ListCertificates (..),
newListCertificates,
-- * Request Lenses
listCertificates_maxResults,
listCertificates_nextToken,
-- * Destructuring the Response
ListCertificatesResponse (..),
newListCertificatesResponse,
-- * Response Lenses
listCertificatesResponse_nextToken,
listCertificatesResponse_httpStatus,
listCertificatesResponse_certificates,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.Transfer.Types
-- | /See:/ 'newListCertificates' smart constructor.
data ListCertificates = ListCertificates'
{ -- | The maximum number of certificates to return.
maxResults :: Prelude.Maybe Prelude.Natural,
-- | When you can get additional results from the @ListCertificates@ call, a
-- @NextToken@ parameter is returned in the output. You can then pass in a
-- subsequent command to the @NextToken@ parameter to continue listing
-- additional certificates.
nextToken :: Prelude.Maybe Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
Create a value of ' ListCertificates ' with all optional fields omitted .
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
-- 'maxResults', 'listCertificates_maxResults' - The maximum number of certificates to return.
--
' ' , ' listCertificates_nextToken ' - When you can get additional results from the @ListCertificates@ call , a
-- @NextToken@ parameter is returned in the output. You can then pass in a
-- subsequent command to the @NextToken@ parameter to continue listing
-- additional certificates.
newListCertificates ::
ListCertificates
newListCertificates =
ListCertificates'
{ maxResults = Prelude.Nothing,
nextToken = Prelude.Nothing
}
-- | The maximum number of certificates to return.
listCertificates_maxResults :: Lens.Lens' ListCertificates (Prelude.Maybe Prelude.Natural)
listCertificates_maxResults = Lens.lens (\ListCertificates' {maxResults} -> maxResults) (\s@ListCertificates' {} a -> s {maxResults = a} :: ListCertificates)
-- | When you can get additional results from the @ListCertificates@ call, a
-- @NextToken@ parameter is returned in the output. You can then pass in a
-- subsequent command to the @NextToken@ parameter to continue listing
-- additional certificates.
listCertificates_nextToken :: Lens.Lens' ListCertificates (Prelude.Maybe Prelude.Text)
listCertificates_nextToken = Lens.lens (\ListCertificates' {nextToken} -> nextToken) (\s@ListCertificates' {} a -> s {nextToken = a} :: ListCertificates)
instance Core.AWSPager ListCertificates where
page rq rs
| Core.stop
( rs
Lens.^? listCertificatesResponse_nextToken
Prelude.. Lens._Just
) =
Prelude.Nothing
| Core.stop
(rs Lens.^. listCertificatesResponse_certificates) =
Prelude.Nothing
| Prelude.otherwise =
Prelude.Just Prelude.$
rq
Prelude.& listCertificates_nextToken
Lens..~ rs
Lens.^? listCertificatesResponse_nextToken
Prelude.. Lens._Just
instance Core.AWSRequest ListCertificates where
type
AWSResponse ListCertificates =
ListCertificatesResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
ListCertificatesResponse'
Prelude.<$> (x Data..?> "NextToken")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
Prelude.<*> (x Data..?> "Certificates" Core..!@ Prelude.mempty)
)
instance Prelude.Hashable ListCertificates where
hashWithSalt _salt ListCertificates' {..} =
_salt `Prelude.hashWithSalt` maxResults
`Prelude.hashWithSalt` nextToken
instance Prelude.NFData ListCertificates where
rnf ListCertificates' {..} =
Prelude.rnf maxResults
`Prelude.seq` Prelude.rnf nextToken
instance Data.ToHeaders ListCertificates where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "X-Amz-Target"
Data.=# ( "TransferService.ListCertificates" ::
Prelude.ByteString
),
"Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToJSON ListCertificates where
toJSON ListCertificates' {..} =
Data.object
( Prelude.catMaybes
[ ("MaxResults" Data..=) Prelude.<$> maxResults,
("NextToken" Data..=) Prelude.<$> nextToken
]
)
instance Data.ToPath ListCertificates where
toPath = Prelude.const "/"
instance Data.ToQuery ListCertificates where
toQuery = Prelude.const Prelude.mempty
-- | /See:/ 'newListCertificatesResponse' smart constructor.
data ListCertificatesResponse = ListCertificatesResponse'
{ -- | Returns the next token, which you can use to list the next certificate.
nextToken :: Prelude.Maybe Prelude.Text,
-- | The response's http status code.
httpStatus :: Prelude.Int,
-- | Returns an array of the certificates that are specified in the
-- @ListCertificates@ call.
certificates :: [ListedCertificate]
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
-- |
-- Create a value of 'ListCertificatesResponse' with all optional fields omitted.
--
Use < -lens generic - lens > or < optics > to modify other optional fields .
--
-- The following record fields are available, with the corresponding lenses provided
-- for backwards compatibility:
--
' ' , ' listCertificatesResponse_nextToken ' - Returns the next token , which you can use to list the next certificate .
--
-- 'httpStatus', 'listCertificatesResponse_httpStatus' - The response's http status code.
--
-- 'certificates', 'listCertificatesResponse_certificates' - Returns an array of the certificates that are specified in the
-- @ListCertificates@ call.
newListCertificatesResponse ::
-- | 'httpStatus'
Prelude.Int ->
ListCertificatesResponse
newListCertificatesResponse pHttpStatus_ =
ListCertificatesResponse'
{ nextToken =
Prelude.Nothing,
httpStatus = pHttpStatus_,
certificates = Prelude.mempty
}
-- | Returns the next token, which you can use to list the next certificate.
listCertificatesResponse_nextToken :: Lens.Lens' ListCertificatesResponse (Prelude.Maybe Prelude.Text)
listCertificatesResponse_nextToken = Lens.lens (\ListCertificatesResponse' {nextToken} -> nextToken) (\s@ListCertificatesResponse' {} a -> s {nextToken = a} :: ListCertificatesResponse)
-- | The response's http status code.
listCertificatesResponse_httpStatus :: Lens.Lens' ListCertificatesResponse Prelude.Int
listCertificatesResponse_httpStatus = Lens.lens (\ListCertificatesResponse' {httpStatus} -> httpStatus) (\s@ListCertificatesResponse' {} a -> s {httpStatus = a} :: ListCertificatesResponse)
-- | Returns an array of the certificates that are specified in the
-- @ListCertificates@ call.
listCertificatesResponse_certificates :: Lens.Lens' ListCertificatesResponse [ListedCertificate]
listCertificatesResponse_certificates = Lens.lens (\ListCertificatesResponse' {certificates} -> certificates) (\s@ListCertificatesResponse' {} a -> s {certificates = a} :: ListCertificatesResponse) Prelude.. Lens.coerced
instance Prelude.NFData ListCertificatesResponse where
rnf ListCertificatesResponse' {..} =
Prelude.rnf nextToken
`Prelude.seq` Prelude.rnf httpStatus
`Prelude.seq` Prelude.rnf certificates
| null | https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-transfer/gen/Amazonka/Transfer/ListCertificates.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE StrictData #
|
Stability : auto-generated
Returns a list of the current certificates that have been imported into
Transfer Family. If you want to limit the results to a certain number,
previously and received a value for the @NextToken@ parameter, you can
supply that value to continue listing certificates from where you left
off.
This operation returns paginated results.
* Creating a Request
* Request Lenses
* Destructuring the Response
* Response Lenses
| /See:/ 'newListCertificates' smart constructor.
| The maximum number of certificates to return.
| When you can get additional results from the @ListCertificates@ call, a
@NextToken@ parameter is returned in the output. You can then pass in a
subsequent command to the @NextToken@ parameter to continue listing
additional certificates.
|
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'maxResults', 'listCertificates_maxResults' - The maximum number of certificates to return.
@NextToken@ parameter is returned in the output. You can then pass in a
subsequent command to the @NextToken@ parameter to continue listing
additional certificates.
| The maximum number of certificates to return.
| When you can get additional results from the @ListCertificates@ call, a
@NextToken@ parameter is returned in the output. You can then pass in a
subsequent command to the @NextToken@ parameter to continue listing
additional certificates.
| /See:/ 'newListCertificatesResponse' smart constructor.
| Returns the next token, which you can use to list the next certificate.
| The response's http status code.
| Returns an array of the certificates that are specified in the
@ListCertificates@ call.
|
Create a value of 'ListCertificatesResponse' with all optional fields omitted.
The following record fields are available, with the corresponding lenses provided
for backwards compatibility:
'httpStatus', 'listCertificatesResponse_httpStatus' - The response's http status code.
'certificates', 'listCertificatesResponse_certificates' - Returns an array of the certificates that are specified in the
@ListCertificates@ call.
| 'httpStatus'
| Returns the next token, which you can use to list the next certificate.
| The response's http status code.
| Returns an array of the certificates that are specified in the
@ListCertificates@ call. | # LANGUAGE DeriveGeneric #
# LANGUAGE DuplicateRecordFields #
# LANGUAGE NamedFieldPuns #
# LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - unused - binds #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fno - warn - unused - matches #
Derived from AWS service descriptions , licensed under Apache 2.0 .
Module : Amazonka . Transfer . ListCertificates
Copyright : ( c ) 2013 - 2023
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
supply a value for the @MaxResults@ parameter . If you ran the command
module Amazonka.Transfer.ListCertificates
ListCertificates (..),
newListCertificates,
listCertificates_maxResults,
listCertificates_nextToken,
ListCertificatesResponse (..),
newListCertificatesResponse,
listCertificatesResponse_nextToken,
listCertificatesResponse_httpStatus,
listCertificatesResponse_certificates,
)
where
import qualified Amazonka.Core as Core
import qualified Amazonka.Core.Lens.Internal as Lens
import qualified Amazonka.Data as Data
import qualified Amazonka.Prelude as Prelude
import qualified Amazonka.Request as Request
import qualified Amazonka.Response as Response
import Amazonka.Transfer.Types
data ListCertificates = ListCertificates'
maxResults :: Prelude.Maybe Prelude.Natural,
nextToken :: Prelude.Maybe Prelude.Text
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Create a value of ' ListCertificates ' with all optional fields omitted .
Use < -lens generic - lens > or < optics > to modify other optional fields .
' ' , ' listCertificates_nextToken ' - When you can get additional results from the @ListCertificates@ call , a
newListCertificates ::
ListCertificates
newListCertificates =
ListCertificates'
{ maxResults = Prelude.Nothing,
nextToken = Prelude.Nothing
}
listCertificates_maxResults :: Lens.Lens' ListCertificates (Prelude.Maybe Prelude.Natural)
listCertificates_maxResults = Lens.lens (\ListCertificates' {maxResults} -> maxResults) (\s@ListCertificates' {} a -> s {maxResults = a} :: ListCertificates)
listCertificates_nextToken :: Lens.Lens' ListCertificates (Prelude.Maybe Prelude.Text)
listCertificates_nextToken = Lens.lens (\ListCertificates' {nextToken} -> nextToken) (\s@ListCertificates' {} a -> s {nextToken = a} :: ListCertificates)
instance Core.AWSPager ListCertificates where
page rq rs
| Core.stop
( rs
Lens.^? listCertificatesResponse_nextToken
Prelude.. Lens._Just
) =
Prelude.Nothing
| Core.stop
(rs Lens.^. listCertificatesResponse_certificates) =
Prelude.Nothing
| Prelude.otherwise =
Prelude.Just Prelude.$
rq
Prelude.& listCertificates_nextToken
Lens..~ rs
Lens.^? listCertificatesResponse_nextToken
Prelude.. Lens._Just
instance Core.AWSRequest ListCertificates where
type
AWSResponse ListCertificates =
ListCertificatesResponse
request overrides =
Request.postJSON (overrides defaultService)
response =
Response.receiveJSON
( \s h x ->
ListCertificatesResponse'
Prelude.<$> (x Data..?> "NextToken")
Prelude.<*> (Prelude.pure (Prelude.fromEnum s))
Prelude.<*> (x Data..?> "Certificates" Core..!@ Prelude.mempty)
)
instance Prelude.Hashable ListCertificates where
hashWithSalt _salt ListCertificates' {..} =
_salt `Prelude.hashWithSalt` maxResults
`Prelude.hashWithSalt` nextToken
instance Prelude.NFData ListCertificates where
rnf ListCertificates' {..} =
Prelude.rnf maxResults
`Prelude.seq` Prelude.rnf nextToken
instance Data.ToHeaders ListCertificates where
toHeaders =
Prelude.const
( Prelude.mconcat
[ "X-Amz-Target"
Data.=# ( "TransferService.ListCertificates" ::
Prelude.ByteString
),
"Content-Type"
Data.=# ( "application/x-amz-json-1.1" ::
Prelude.ByteString
)
]
)
instance Data.ToJSON ListCertificates where
toJSON ListCertificates' {..} =
Data.object
( Prelude.catMaybes
[ ("MaxResults" Data..=) Prelude.<$> maxResults,
("NextToken" Data..=) Prelude.<$> nextToken
]
)
instance Data.ToPath ListCertificates where
toPath = Prelude.const "/"
instance Data.ToQuery ListCertificates where
toQuery = Prelude.const Prelude.mempty
data ListCertificatesResponse = ListCertificatesResponse'
nextToken :: Prelude.Maybe Prelude.Text,
httpStatus :: Prelude.Int,
certificates :: [ListedCertificate]
}
deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic)
Use < -lens generic - lens > or < optics > to modify other optional fields .
' ' , ' listCertificatesResponse_nextToken ' - Returns the next token , which you can use to list the next certificate .
newListCertificatesResponse ::
Prelude.Int ->
ListCertificatesResponse
newListCertificatesResponse pHttpStatus_ =
ListCertificatesResponse'
{ nextToken =
Prelude.Nothing,
httpStatus = pHttpStatus_,
certificates = Prelude.mempty
}
listCertificatesResponse_nextToken :: Lens.Lens' ListCertificatesResponse (Prelude.Maybe Prelude.Text)
listCertificatesResponse_nextToken = Lens.lens (\ListCertificatesResponse' {nextToken} -> nextToken) (\s@ListCertificatesResponse' {} a -> s {nextToken = a} :: ListCertificatesResponse)
listCertificatesResponse_httpStatus :: Lens.Lens' ListCertificatesResponse Prelude.Int
listCertificatesResponse_httpStatus = Lens.lens (\ListCertificatesResponse' {httpStatus} -> httpStatus) (\s@ListCertificatesResponse' {} a -> s {httpStatus = a} :: ListCertificatesResponse)
listCertificatesResponse_certificates :: Lens.Lens' ListCertificatesResponse [ListedCertificate]
listCertificatesResponse_certificates = Lens.lens (\ListCertificatesResponse' {certificates} -> certificates) (\s@ListCertificatesResponse' {} a -> s {certificates = a} :: ListCertificatesResponse) Prelude.. Lens.coerced
instance Prelude.NFData ListCertificatesResponse where
rnf ListCertificatesResponse' {..} =
Prelude.rnf nextToken
`Prelude.seq` Prelude.rnf httpStatus
`Prelude.seq` Prelude.rnf certificates
|
aa3a4114842a32b515b77d3e6a19c6479854e46953593b878f7fe18166d29e9c | ogaml/ogaml | context.ml |
exception Invalid_context of string
type capabilities = {
max_3D_texture_size : int;
max_array_texture_layers : int;
max_color_texture_samples : int;
max_cube_map_texture_size : int;
max_depth_texture_samples : int;
max_elements_indices : int;
max_elements_vertices : int;
max_integer_samples : int;
max_renderbuffer_size : int;
max_texture_buffer_size : int;
max_texture_image_units : int;
max_texture_size : int;
max_color_attachments : int;
}
type t = {
capabilities : capabilities;
major : int;
minor : int;
glsl : int;
sprite_program : ProgramInternal.t;
shape_program : ProgramInternal.t;
text_program : ProgramInternal.t;
mutable msaa : bool;
mutable culling_mode : DrawParameter.CullingMode.t;
mutable polygon_mode : DrawParameter.PolygonMode.t;
mutable depth_test : bool;
mutable depth_writing : bool;
mutable depth_function : DrawParameter.DepthTest.t;
mutable texture_id : int;
mutable texture_unit : int;
mutable pooled_tex_array : bool array;
mutable bound_texture : (GL.Texture.t * int * GLTypes.TextureTarget.t) option array;
mutable program_id : int;
mutable linked_program : (GL.Program.t * int) option;
mutable bound_vbo : (GL.VBO.t * int) option;
mutable vao_id : int;
mutable bound_vao : (GL.VAO.t * int) option;
mutable ebo_id : int;
mutable bound_ebo : (GL.EBO.t * int) option;
mutable fbo_id : int;
mutable rbo_id : int;
mutable bound_fbo : (GL.FBO.t * int) option;
mutable color : Color.t;
mutable blending : bool;
mutable blend_equation : DrawParameter.BlendMode.t;
mutable viewport : OgamlMath.IntRect.t
}
let error msg = raise (Invalid_context msg)
let capabilities t = t.capabilities
let version s =
(s.major, s.minor)
let is_version_supported s (maj, min) =
let convert v =
if v < 10 then v*10 else v
in
maj < s.major || (maj = s.major && (convert min) <= s.minor)
let glsl_version s =
s.glsl
let is_glsl_version_supported s v =
v <= s.glsl
let assert_no_error s =
match GL.Pervasives.error () with
| Some GLTypes.GlError.Invalid_enum -> error "Invalid enum"
| Some GLTypes.GlError.Invalid_value -> error "Invalid value"
| Some GLTypes.GlError.Invalid_op -> error "Invalid op"
| Some GLTypes.GlError.Invalid_fbop -> error "Invalid fbop"
| Some GLTypes.GlError.Out_of_memory -> error "Out of memory"
| Some GLTypes.GlError.Stack_overflow -> error "Stack overflow"
| Some GLTypes.GlError.Stack_underflow -> error "Stack underflow"
| None -> ()
let flush s =
GL.Pervasives.flush ()
let finish s =
GL.Pervasives.finish ()
module LL = struct
let create () =
let convert v =
if v < 10 then v*10 else v
in
let major, minor =
let str = GL.Pervasives.gl_version () in
Scanf.sscanf str "%i.%i" (fun a b -> (a, convert b))
in
let glsl =
let str = GL.Pervasives.glsl_version () in
Scanf.sscanf str "%i.%i" (fun a b -> a * 100 + (convert b))
in
assert (GL.Pervasives.error () = None);
let capabilities = {
max_3D_texture_size = GL.Pervasives.get_integerv GLTypes.Parameter.Max3DTextureSize ;
max_array_texture_layers = GL.Pervasives.get_integerv GLTypes.Parameter.MaxArrayTextureLayers ;
max_color_texture_samples = GL.Pervasives.get_integerv GLTypes.Parameter.MaxColorTextureSamples;
max_cube_map_texture_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxCubeMapTextureSize ;
max_depth_texture_samples = GL.Pervasives.get_integerv GLTypes.Parameter.MaxDepthTextureSamples;
max_elements_indices = GL.Pervasives.get_integerv GLTypes.Parameter.MaxElementsIndices ;
max_elements_vertices = GL.Pervasives.get_integerv GLTypes.Parameter.MaxElementsVertices ;
max_integer_samples = GL.Pervasives.get_integerv GLTypes.Parameter.MaxIntegerSamples ;
max_renderbuffer_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxRenderbufferSize ;
max_texture_buffer_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxTextureBufferSize ;
max_texture_image_units = GL.Pervasives.get_integerv GLTypes.Parameter.MaxTextureImageUnits ;
max_texture_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxTextureSize ;
max_color_attachments = GL.Pervasives.get_integerv GLTypes.Parameter.MaxColorAttachments ;
}
in
(* A bit ugly, but Invalid_enum occurs sometimes even if a feature is supported... *)
ignore (GL.Pervasives.error ());
{
capabilities;
major ;
minor ;
glsl ;
sprite_program = ProgramInternal.Sources.create_sprite (-3) glsl;
shape_program = ProgramInternal.Sources.create_shape (-2) glsl;
text_program = ProgramInternal.Sources.create_text (-1) glsl;
msaa = false;
culling_mode = DrawParameter.CullingMode.CullNone;
polygon_mode = DrawParameter.PolygonMode.DrawFill;
depth_test = false;
depth_writing = true;
depth_function = DrawParameter.DepthTest.Less;
texture_id = 0;
texture_unit = 0;
pooled_tex_array = Array.make capabilities.max_texture_image_units true;
bound_texture = Array.make capabilities.max_texture_image_units None;
program_id = 0;
linked_program = None;
bound_vbo = None;
vao_id = 0;
bound_vao = None;
ebo_id = 0;
bound_ebo = None;
fbo_id = 1;
bound_fbo = None;
rbo_id = 0;
color = `RGB (Color.RGB.transparent);
blending = false;
blend_equation = DrawParameter.BlendMode.(
{color = Equation.Add (Factor.One, Factor.Zero);
alpha = Equation.Add (Factor.One, Factor.Zero)});
viewport = OgamlMath.IntRect.({x = 0; y = 0; width = 0; height = 0})
}
let sprite_drawing s = s.sprite_program
let shape_drawing s = s.shape_program
let text_drawing s = s.text_program
let culling_mode s =
s.culling_mode
let polygon_mode s =
s.polygon_mode
let depth_test s =
s.depth_test
let depth_writing s =
s.depth_writing
let depth_function s =
s.depth_function
let clear_color s =
s.color
let set_culling_mode s m =
s.culling_mode <- m
let set_polygon_mode s m =
s.polygon_mode <- m
let set_depth_test s v =
s.depth_test <- v
let set_depth_writing s v =
s.depth_writing <- v
let set_depth_function s f =
s.depth_function <- f
let msaa s = s.msaa
let set_msaa s b = s.msaa <- b
let texture_unit s =
s.texture_unit
let set_texture_unit s i =
s.texture_unit <- i
let texture_id s =
s.texture_id <- s.texture_id + 1;
s.texture_id - 1
let bound_texture s i =
if i >= s.capabilities.max_texture_image_units || i < 0 then
Printf.ksprintf error "Invalid texture unit %i" i;
match s.bound_texture.(i) with
| None -> None
| Some (_,t,_) -> Some t
let bound_target s i =
if i >= s.capabilities.max_texture_image_units || i < 0 then
Printf.ksprintf error "Invalid texture unit %i" i;
match s.bound_texture.(i) with
| None -> None
| Some (_,_,t) -> Some t
let set_bound_texture s i t =
if i >= s.capabilities.max_texture_image_units || i < 0 then
Printf.ksprintf error "Invalid texture unit %i" i;
s.bound_texture.(i) <- t
let pooled_texture_array s =
s.pooled_tex_array
let linked_program s =
match s.linked_program with
| None -> None
| Some (_,t) -> Some t
let set_linked_program s p =
s.linked_program <- p
let program_id s =
s.program_id <- s.program_id + 1;
s.program_id - 1
let bound_vbo s =
match s.bound_vbo with
| None -> None
| Some (_,t) -> Some t
let set_bound_vbo s v =
s.bound_vbo <- v
let bound_vao s =
match s.bound_vao with
| None -> None
| Some (_,t) -> Some t
let set_bound_vao s v =
s.bound_vao <- v
let vao_id s =
s.vao_id <- s.vao_id + 1;
s.vao_id - 1
let bound_ebo s =
match s.bound_ebo with
| None -> None
| Some (_,t) -> Some t
let set_bound_ebo s v =
s.bound_ebo <- v
let ebo_id s =
s.ebo_id <- s.ebo_id + 1;
s.ebo_id - 1
let bound_fbo s =
match s.bound_fbo with
| None -> 0
| Some (_,t) -> t
let set_bound_fbo s i =
s.bound_fbo <- i
let fbo_id s =
s.fbo_id <- s.fbo_id + 1;
s.fbo_id - 1
let rbo_id s =
s.rbo_id <- s.rbo_id + 1;
s.rbo_id - 1
let set_clear_color s c =
s.color <- c
let blending s = s.blending
let set_blending s b = s.blending <- b
let blend_equation s = s.blend_equation
let set_blend_equation s eq = s.blend_equation <- eq
let viewport s = s.viewport
let set_viewport s v = s.viewport <- v
end
| null | https://raw.githubusercontent.com/ogaml/ogaml/5e74597521abf7ba2833a9247e55780eabfbab78/src/graphics/backend/context.ml | ocaml | A bit ugly, but Invalid_enum occurs sometimes even if a feature is supported... |
exception Invalid_context of string
type capabilities = {
max_3D_texture_size : int;
max_array_texture_layers : int;
max_color_texture_samples : int;
max_cube_map_texture_size : int;
max_depth_texture_samples : int;
max_elements_indices : int;
max_elements_vertices : int;
max_integer_samples : int;
max_renderbuffer_size : int;
max_texture_buffer_size : int;
max_texture_image_units : int;
max_texture_size : int;
max_color_attachments : int;
}
type t = {
capabilities : capabilities;
major : int;
minor : int;
glsl : int;
sprite_program : ProgramInternal.t;
shape_program : ProgramInternal.t;
text_program : ProgramInternal.t;
mutable msaa : bool;
mutable culling_mode : DrawParameter.CullingMode.t;
mutable polygon_mode : DrawParameter.PolygonMode.t;
mutable depth_test : bool;
mutable depth_writing : bool;
mutable depth_function : DrawParameter.DepthTest.t;
mutable texture_id : int;
mutable texture_unit : int;
mutable pooled_tex_array : bool array;
mutable bound_texture : (GL.Texture.t * int * GLTypes.TextureTarget.t) option array;
mutable program_id : int;
mutable linked_program : (GL.Program.t * int) option;
mutable bound_vbo : (GL.VBO.t * int) option;
mutable vao_id : int;
mutable bound_vao : (GL.VAO.t * int) option;
mutable ebo_id : int;
mutable bound_ebo : (GL.EBO.t * int) option;
mutable fbo_id : int;
mutable rbo_id : int;
mutable bound_fbo : (GL.FBO.t * int) option;
mutable color : Color.t;
mutable blending : bool;
mutable blend_equation : DrawParameter.BlendMode.t;
mutable viewport : OgamlMath.IntRect.t
}
let error msg = raise (Invalid_context msg)
let capabilities t = t.capabilities
let version s =
(s.major, s.minor)
let is_version_supported s (maj, min) =
let convert v =
if v < 10 then v*10 else v
in
maj < s.major || (maj = s.major && (convert min) <= s.minor)
let glsl_version s =
s.glsl
let is_glsl_version_supported s v =
v <= s.glsl
let assert_no_error s =
match GL.Pervasives.error () with
| Some GLTypes.GlError.Invalid_enum -> error "Invalid enum"
| Some GLTypes.GlError.Invalid_value -> error "Invalid value"
| Some GLTypes.GlError.Invalid_op -> error "Invalid op"
| Some GLTypes.GlError.Invalid_fbop -> error "Invalid fbop"
| Some GLTypes.GlError.Out_of_memory -> error "Out of memory"
| Some GLTypes.GlError.Stack_overflow -> error "Stack overflow"
| Some GLTypes.GlError.Stack_underflow -> error "Stack underflow"
| None -> ()
let flush s =
GL.Pervasives.flush ()
let finish s =
GL.Pervasives.finish ()
module LL = struct
let create () =
let convert v =
if v < 10 then v*10 else v
in
let major, minor =
let str = GL.Pervasives.gl_version () in
Scanf.sscanf str "%i.%i" (fun a b -> (a, convert b))
in
let glsl =
let str = GL.Pervasives.glsl_version () in
Scanf.sscanf str "%i.%i" (fun a b -> a * 100 + (convert b))
in
assert (GL.Pervasives.error () = None);
let capabilities = {
max_3D_texture_size = GL.Pervasives.get_integerv GLTypes.Parameter.Max3DTextureSize ;
max_array_texture_layers = GL.Pervasives.get_integerv GLTypes.Parameter.MaxArrayTextureLayers ;
max_color_texture_samples = GL.Pervasives.get_integerv GLTypes.Parameter.MaxColorTextureSamples;
max_cube_map_texture_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxCubeMapTextureSize ;
max_depth_texture_samples = GL.Pervasives.get_integerv GLTypes.Parameter.MaxDepthTextureSamples;
max_elements_indices = GL.Pervasives.get_integerv GLTypes.Parameter.MaxElementsIndices ;
max_elements_vertices = GL.Pervasives.get_integerv GLTypes.Parameter.MaxElementsVertices ;
max_integer_samples = GL.Pervasives.get_integerv GLTypes.Parameter.MaxIntegerSamples ;
max_renderbuffer_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxRenderbufferSize ;
max_texture_buffer_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxTextureBufferSize ;
max_texture_image_units = GL.Pervasives.get_integerv GLTypes.Parameter.MaxTextureImageUnits ;
max_texture_size = GL.Pervasives.get_integerv GLTypes.Parameter.MaxTextureSize ;
max_color_attachments = GL.Pervasives.get_integerv GLTypes.Parameter.MaxColorAttachments ;
}
in
ignore (GL.Pervasives.error ());
{
capabilities;
major ;
minor ;
glsl ;
sprite_program = ProgramInternal.Sources.create_sprite (-3) glsl;
shape_program = ProgramInternal.Sources.create_shape (-2) glsl;
text_program = ProgramInternal.Sources.create_text (-1) glsl;
msaa = false;
culling_mode = DrawParameter.CullingMode.CullNone;
polygon_mode = DrawParameter.PolygonMode.DrawFill;
depth_test = false;
depth_writing = true;
depth_function = DrawParameter.DepthTest.Less;
texture_id = 0;
texture_unit = 0;
pooled_tex_array = Array.make capabilities.max_texture_image_units true;
bound_texture = Array.make capabilities.max_texture_image_units None;
program_id = 0;
linked_program = None;
bound_vbo = None;
vao_id = 0;
bound_vao = None;
ebo_id = 0;
bound_ebo = None;
fbo_id = 1;
bound_fbo = None;
rbo_id = 0;
color = `RGB (Color.RGB.transparent);
blending = false;
blend_equation = DrawParameter.BlendMode.(
{color = Equation.Add (Factor.One, Factor.Zero);
alpha = Equation.Add (Factor.One, Factor.Zero)});
viewport = OgamlMath.IntRect.({x = 0; y = 0; width = 0; height = 0})
}
let sprite_drawing s = s.sprite_program
let shape_drawing s = s.shape_program
let text_drawing s = s.text_program
let culling_mode s =
s.culling_mode
let polygon_mode s =
s.polygon_mode
let depth_test s =
s.depth_test
let depth_writing s =
s.depth_writing
let depth_function s =
s.depth_function
let clear_color s =
s.color
let set_culling_mode s m =
s.culling_mode <- m
let set_polygon_mode s m =
s.polygon_mode <- m
let set_depth_test s v =
s.depth_test <- v
let set_depth_writing s v =
s.depth_writing <- v
let set_depth_function s f =
s.depth_function <- f
let msaa s = s.msaa
let set_msaa s b = s.msaa <- b
let texture_unit s =
s.texture_unit
let set_texture_unit s i =
s.texture_unit <- i
let texture_id s =
s.texture_id <- s.texture_id + 1;
s.texture_id - 1
let bound_texture s i =
if i >= s.capabilities.max_texture_image_units || i < 0 then
Printf.ksprintf error "Invalid texture unit %i" i;
match s.bound_texture.(i) with
| None -> None
| Some (_,t,_) -> Some t
let bound_target s i =
if i >= s.capabilities.max_texture_image_units || i < 0 then
Printf.ksprintf error "Invalid texture unit %i" i;
match s.bound_texture.(i) with
| None -> None
| Some (_,_,t) -> Some t
let set_bound_texture s i t =
if i >= s.capabilities.max_texture_image_units || i < 0 then
Printf.ksprintf error "Invalid texture unit %i" i;
s.bound_texture.(i) <- t
let pooled_texture_array s =
s.pooled_tex_array
let linked_program s =
match s.linked_program with
| None -> None
| Some (_,t) -> Some t
let set_linked_program s p =
s.linked_program <- p
let program_id s =
s.program_id <- s.program_id + 1;
s.program_id - 1
let bound_vbo s =
match s.bound_vbo with
| None -> None
| Some (_,t) -> Some t
let set_bound_vbo s v =
s.bound_vbo <- v
let bound_vao s =
match s.bound_vao with
| None -> None
| Some (_,t) -> Some t
let set_bound_vao s v =
s.bound_vao <- v
let vao_id s =
s.vao_id <- s.vao_id + 1;
s.vao_id - 1
let bound_ebo s =
match s.bound_ebo with
| None -> None
| Some (_,t) -> Some t
let set_bound_ebo s v =
s.bound_ebo <- v
let ebo_id s =
s.ebo_id <- s.ebo_id + 1;
s.ebo_id - 1
let bound_fbo s =
match s.bound_fbo with
| None -> 0
| Some (_,t) -> t
let set_bound_fbo s i =
s.bound_fbo <- i
let fbo_id s =
s.fbo_id <- s.fbo_id + 1;
s.fbo_id - 1
let rbo_id s =
s.rbo_id <- s.rbo_id + 1;
s.rbo_id - 1
let set_clear_color s c =
s.color <- c
let blending s = s.blending
let set_blending s b = s.blending <- b
let blend_equation s = s.blend_equation
let set_blend_equation s eq = s.blend_equation <- eq
let viewport s = s.viewport
let set_viewport s v = s.viewport <- v
end
|
2321173b725c291b5e30b9d34eaaf75bbce6b83e7e631696b9a9efc01cb1a114 | hemmi/coq2scala | evar_tactics.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Term
open Util
open Evar_refiner
open Tacmach
open Tacexpr
open Refiner
open Proof_type
open Evd
open Sign
open Termops
(* The instantiate tactic *)
let instantiate n (ist,rawc) ido gl =
let sigma = gl.sigma in
let evl =
match ido with
ConclLocation () -> evar_list sigma (pf_concl gl)
| HypLocation (id,hloc) ->
let decl = Environ.lookup_named_val id (Goal.V82.hyps sigma (sig_it gl)) in
match hloc with
InHyp ->
(match decl with
(_,None,typ) -> evar_list sigma typ
| _ -> error
"Please be more specific: in type or value?")
| InHypTypeOnly ->
let (_, _, typ) = decl in evar_list sigma typ
| InHypValueOnly ->
(match decl with
(_,Some body,_) -> evar_list sigma body
| _ -> error "Not a defined hypothesis.") in
if List.length evl < n then
error "Not enough uninstantiated existential variables.";
if n <= 0 then error "Incorrect existential variable index.";
let evk,_ = List.nth evl (n-1) in
let evi = Evd.find sigma evk in
let ltac_vars = Tacinterp.extract_ltac_constr_values ist (Evd.evar_env evi) in
let sigma' = w_refine (evk,evi) (ltac_vars,rawc) sigma in
tclTHEN
(tclEVARS sigma')
tclNORMEVAR
gl
let let_evar name typ gls =
let src = (dummy_loc,GoalEvar) in
let sigma',evar = Evarutil.new_evar gls.sigma (pf_env gls) ~src typ in
Refiner.tclTHEN (Refiner.tclEVARS sigma')
(Tactics.letin_tac None name evar None nowhere) gls
| null | https://raw.githubusercontent.com/hemmi/coq2scala/d10f441c18146933a99bf2088116bd213ac3648d/coq-8.4pl2-old/tactics/evar_tactics.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
The instantiate tactic | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Term
open Util
open Evar_refiner
open Tacmach
open Tacexpr
open Refiner
open Proof_type
open Evd
open Sign
open Termops
let instantiate n (ist,rawc) ido gl =
let sigma = gl.sigma in
let evl =
match ido with
ConclLocation () -> evar_list sigma (pf_concl gl)
| HypLocation (id,hloc) ->
let decl = Environ.lookup_named_val id (Goal.V82.hyps sigma (sig_it gl)) in
match hloc with
InHyp ->
(match decl with
(_,None,typ) -> evar_list sigma typ
| _ -> error
"Please be more specific: in type or value?")
| InHypTypeOnly ->
let (_, _, typ) = decl in evar_list sigma typ
| InHypValueOnly ->
(match decl with
(_,Some body,_) -> evar_list sigma body
| _ -> error "Not a defined hypothesis.") in
if List.length evl < n then
error "Not enough uninstantiated existential variables.";
if n <= 0 then error "Incorrect existential variable index.";
let evk,_ = List.nth evl (n-1) in
let evi = Evd.find sigma evk in
let ltac_vars = Tacinterp.extract_ltac_constr_values ist (Evd.evar_env evi) in
let sigma' = w_refine (evk,evi) (ltac_vars,rawc) sigma in
tclTHEN
(tclEVARS sigma')
tclNORMEVAR
gl
let let_evar name typ gls =
let src = (dummy_loc,GoalEvar) in
let sigma',evar = Evarutil.new_evar gls.sigma (pf_env gls) ~src typ in
Refiner.tclTHEN (Refiner.tclEVARS sigma')
(Tactics.letin_tac None name evar None nowhere) gls
|
96c9d83ba146cd3fdece3c1fa66fe76d18608354d7687602e68593a606c063b1 | arenadotio/pgx | pgx_async.mli | * Async based Postgres client based on Pgx .
open Async_kernel
include
Pgx.S
with type 'a Io.t = 'a Deferred.t
and type Io.ssl_config = Conduit_async.Ssl.config
(* for testing purposes *)
module Thread : Pgx.Io with type 'a t = 'a Deferred.t
(** Like [execute] but returns a pipe so you can operate on the results before they have all returned.
Note that [execute_iter] and [execute_fold] can perform significantly better because they don't have
as much overhead. *)
val execute_pipe : ?params:Pgx.row -> t -> string -> Pgx.row Pipe.Reader.t
(** Exposed for backwards compatiblity. New code should use [Pgx_value_core] directly. *)
module Value = Pgx_value_core
| null | https://raw.githubusercontent.com/arenadotio/pgx/cdef3ff4eba56ea9b2a74c2b3bbfe652b4864a39/pgx_async/src/pgx_async.mli | ocaml | for testing purposes
* Like [execute] but returns a pipe so you can operate on the results before they have all returned.
Note that [execute_iter] and [execute_fold] can perform significantly better because they don't have
as much overhead.
* Exposed for backwards compatiblity. New code should use [Pgx_value_core] directly. | * Async based Postgres client based on Pgx .
open Async_kernel
include
Pgx.S
with type 'a Io.t = 'a Deferred.t
and type Io.ssl_config = Conduit_async.Ssl.config
module Thread : Pgx.Io with type 'a t = 'a Deferred.t
val execute_pipe : ?params:Pgx.row -> t -> string -> Pgx.row Pipe.Reader.t
module Value = Pgx_value_core
|
f09d9f23d1024ea2a41b04669f91420018b58072b39dc80c7d3e5613854acdc1 | senapk/funcional_arcade | solver.hs | max3 x y z = max z $ max x y
| null | https://raw.githubusercontent.com/senapk/funcional_arcade/70fa04b4799d5a8c7e5add39d9f217f38f418600/base/001/solver.hs | haskell | max3 x y z = max z $ max x y
|
|
88d1797a92fb8aa79e2999f2d16f5d3cca0e6c173459b66e6d7a0a73d12cf61b | kqqsysu/ssdb-erlang | ssdb.erl | %%% @author
( C ) 2015 , kongqingquan
@doc SSDB erlang client
%%% @end
Created : 2015.05.01
%%%-------------------------------------------------------------------
-module(ssdb).
-author("").
-include("ssdb.hrl").
-export([start/0,start/2,start/3,start/4,start/5,start/6]).
-export([query/1, query/2, query/3]).
start()->
start("localhost",8888).
start(Host,Port) ->
PoolSize = 5,
start(Host,Port,PoolSize).
start(Host,Port,PoolSize)->
Password = undefined,
start(Host,Port,PoolSize,Password).
start(Host,Port,PoolSize,Password)->
IsReconnect = 0,
start(Host,Port,PoolSize,Password,IsReconnect).
start(Host,Port,PoolSize,Password,IsReconnect) ->
application:ensure_started(ssdb),
ssdb_sup:start_pool(?SSDB_SERVER,Host,Port,PoolSize,Password,IsReconnect).
start(PoolName, Host, Port, PoolSize, Password, IsReconnect) ->
application:ensure_started(ssdb),
ssdb_sup:start_pool(PoolName, Host, Port, PoolSize, Password, IsReconnect).
query(Cmd) ->
query(?SSDB_SERVER,Cmd).
query(Pid,[Cmd | _] = CmdList) ->
Res = ssdb_pool:query(Pid,CmdList),
AtomCmd = to_atom(Cmd),
parse_res(AtomCmd,Res);
query(Pid,Cmd) ->
ssdb_pool:query(Pid,[Cmd]).
query(Pid, [Cmd | _] = CmdList, Timeout) ->
Res = ssdb_pool:query(Pid, CmdList, Timeout),
AtomCmd = to_atom(Cmd),
parse_res(AtomCmd, Res);
query(Pid, Cmd, Timeout) ->
ssdb_pool:query(Pid, [Cmd], Timeout).
parse_res(Cmd,Res) when Cmd == 'zavg' ->
case Res of
[<<"ok">>,Avg] ->
try
{ok,binary_to_float(Avg)}
catch
_:Exception ->
{error,Exception}
end;
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'get'; Cmd == 'substr'; Cmd == 'getset'; Cmd == 'hget'; Cmd == 'qget'; Cmd == 'qfront'; Cmd == 'qback' ->
case Res of
[<<"ok">>,Data] ->
{ok,Data};
[<<"not_found">>] ->
{not_found,null};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'qpop';Cmd == 'qpop_front';Cmd == 'qpop_back' ->
case Res of
[<<"ok">> | Data] ->
{ok,Data};
[<<"not_found">>]->
{not_found,null};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'keys';Cmd == 'zkeys';Cmd == 'hkeys';Cmd == 'hlist';Cmd == 'zlist';Cmd == 'qslice' ->
case Res of
[<<"ok">> | T] ->
{ok,T};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'auth';Cmd == 'exists';Cmd == 'hexists';Cmd == 'zexists' ->
case Res of
[<<"ok">>,Data] ->
try
{ok,binary_to_integer(Data)}
catch
_:Exception ->
{error,Exception}
end;
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'multi_exists';Cmd == 'multi_hexists'; Cmd == 'multi_zexists'->
case Res of
[<<"ok">> | Data] ->
try
Return = parse_mutil_return(Data,[]),
{ok,Return}
catch
_:Exception ->
{error,Exception}
end;
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'scan';Cmd == 'rscan';Cmd == 'zscan';Cmd == 'zrscan';Cmd == 'zrange';Cmd == 'zrrange';Cmd == 'hscan';Cmd == 'hrscan';Cmd == 'hgetall';Cmd == 'multi_hsize';Cmd == 'multi_zsize';Cmd == 'multi_get';Cmd == 'multi_hget';Cmd == 'multi_zget';Cmd == 'zpop_front';Cmd == 'zpop_back' ->
case Res of
[<<"ok">> | Data] ->
case atom_to_list(Cmd) of
["z" | _] ->
{ok,parse_mutil_return(Data,[])};
_ ->
{ok,parse_mutil_return2(Data,[])}
end;
_ ->
Res
end;
%%% Cmd: 'dbsize','ping','qset','getbit','setbit','countbit','strlen','set','setx','setnx','zset','hset','qpush','qpush_front','qpush_back','qtrim_front','qtrim_back','del','zdel','hdel','hsize','zsize','qsize','hclear','zclear','qclear','multi_set','multi_del','multi_hset','multi_hdel','multi_zset','multi_zdel','incr','decr','zincr','zdecr','hincr','hdecr','zget','zrank','zrrank','zcount','zsum','zremrangebyrank','zremrangebyscore'
parse_res(Cmd,Res) ->
case Res of
[<<"ok">>] ->
{ok,0};
[<<"ok">>,Data] ->
try
{ok,binary_to_integer(Data)}
catch
_:Exception ->
{error,Exception}
end;
[<<"not_found">>]->
{not_found,null};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end.
parse_mutil_return([Key,IsExist | T],Res) ->
NewRes = [{Key,binary_to_integer(IsExist)} | Res],
parse_mutil_return(T,NewRes);
parse_mutil_return([],Res) ->
lists:reverse(Res).
parse_mutil_return2([Key,Val | T],Res) ->
NewRes = [{Key,Val} | Res],
parse_mutil_return2(T,NewRes);
parse_mutil_return2([],Res) ->
lists:reverse(Res).
to_atom(Cmd) when is_atom(Cmd) ->
Cmd;
to_atom(Cmd) when is_list(Cmd) ->
list_to_atom(Cmd);
to_atom(Cmd) when is_binary(Cmd) ->
binary_to_atom(Cmd,utf8).
| null | https://raw.githubusercontent.com/kqqsysu/ssdb-erlang/158b5b494794f241eded66a1ad04d97e9303975b/src/ssdb.erl | erlang | @author
@end
-------------------------------------------------------------------
Cmd: 'dbsize','ping','qset','getbit','setbit','countbit','strlen','set','setx','setnx','zset','hset','qpush','qpush_front','qpush_back','qtrim_front','qtrim_back','del','zdel','hdel','hsize','zsize','qsize','hclear','zclear','qclear','multi_set','multi_del','multi_hset','multi_hdel','multi_zset','multi_zdel','incr','decr','zincr','zdecr','hincr','hdecr','zget','zrank','zrrank','zcount','zsum','zremrangebyrank','zremrangebyscore' | ( C ) 2015 , kongqingquan
@doc SSDB erlang client
Created : 2015.05.01
-module(ssdb).
-author("").
-include("ssdb.hrl").
-export([start/0,start/2,start/3,start/4,start/5,start/6]).
-export([query/1, query/2, query/3]).
start()->
start("localhost",8888).
start(Host,Port) ->
PoolSize = 5,
start(Host,Port,PoolSize).
start(Host,Port,PoolSize)->
Password = undefined,
start(Host,Port,PoolSize,Password).
start(Host,Port,PoolSize,Password)->
IsReconnect = 0,
start(Host,Port,PoolSize,Password,IsReconnect).
start(Host,Port,PoolSize,Password,IsReconnect) ->
application:ensure_started(ssdb),
ssdb_sup:start_pool(?SSDB_SERVER,Host,Port,PoolSize,Password,IsReconnect).
start(PoolName, Host, Port, PoolSize, Password, IsReconnect) ->
application:ensure_started(ssdb),
ssdb_sup:start_pool(PoolName, Host, Port, PoolSize, Password, IsReconnect).
query(Cmd) ->
query(?SSDB_SERVER,Cmd).
query(Pid,[Cmd | _] = CmdList) ->
Res = ssdb_pool:query(Pid,CmdList),
AtomCmd = to_atom(Cmd),
parse_res(AtomCmd,Res);
query(Pid,Cmd) ->
ssdb_pool:query(Pid,[Cmd]).
query(Pid, [Cmd | _] = CmdList, Timeout) ->
Res = ssdb_pool:query(Pid, CmdList, Timeout),
AtomCmd = to_atom(Cmd),
parse_res(AtomCmd, Res);
query(Pid, Cmd, Timeout) ->
ssdb_pool:query(Pid, [Cmd], Timeout).
parse_res(Cmd,Res) when Cmd == 'zavg' ->
case Res of
[<<"ok">>,Avg] ->
try
{ok,binary_to_float(Avg)}
catch
_:Exception ->
{error,Exception}
end;
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'get'; Cmd == 'substr'; Cmd == 'getset'; Cmd == 'hget'; Cmd == 'qget'; Cmd == 'qfront'; Cmd == 'qback' ->
case Res of
[<<"ok">>,Data] ->
{ok,Data};
[<<"not_found">>] ->
{not_found,null};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'qpop';Cmd == 'qpop_front';Cmd == 'qpop_back' ->
case Res of
[<<"ok">> | Data] ->
{ok,Data};
[<<"not_found">>]->
{not_found,null};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'keys';Cmd == 'zkeys';Cmd == 'hkeys';Cmd == 'hlist';Cmd == 'zlist';Cmd == 'qslice' ->
case Res of
[<<"ok">> | T] ->
{ok,T};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'auth';Cmd == 'exists';Cmd == 'hexists';Cmd == 'zexists' ->
case Res of
[<<"ok">>,Data] ->
try
{ok,binary_to_integer(Data)}
catch
_:Exception ->
{error,Exception}
end;
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'multi_exists';Cmd == 'multi_hexists'; Cmd == 'multi_zexists'->
case Res of
[<<"ok">> | Data] ->
try
Return = parse_mutil_return(Data,[]),
{ok,Return}
catch
_:Exception ->
{error,Exception}
end;
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end;
parse_res(Cmd,Res) when Cmd == 'scan';Cmd == 'rscan';Cmd == 'zscan';Cmd == 'zrscan';Cmd == 'zrange';Cmd == 'zrrange';Cmd == 'hscan';Cmd == 'hrscan';Cmd == 'hgetall';Cmd == 'multi_hsize';Cmd == 'multi_zsize';Cmd == 'multi_get';Cmd == 'multi_hget';Cmd == 'multi_zget';Cmd == 'zpop_front';Cmd == 'zpop_back' ->
case Res of
[<<"ok">> | Data] ->
case atom_to_list(Cmd) of
["z" | _] ->
{ok,parse_mutil_return(Data,[])};
_ ->
{ok,parse_mutil_return2(Data,[])}
end;
_ ->
Res
end;
parse_res(Cmd,Res) ->
case Res of
[<<"ok">>] ->
{ok,0};
[<<"ok">>,Data] ->
try
{ok,binary_to_integer(Data)}
catch
_:Exception ->
{error,Exception}
end;
[<<"not_found">>]->
{not_found,null};
_ ->
?PRINT("Query ~p Error:~p",[Cmd,Res]),
Res
end.
parse_mutil_return([Key,IsExist | T],Res) ->
NewRes = [{Key,binary_to_integer(IsExist)} | Res],
parse_mutil_return(T,NewRes);
parse_mutil_return([],Res) ->
lists:reverse(Res).
parse_mutil_return2([Key,Val | T],Res) ->
NewRes = [{Key,Val} | Res],
parse_mutil_return2(T,NewRes);
parse_mutil_return2([],Res) ->
lists:reverse(Res).
to_atom(Cmd) when is_atom(Cmd) ->
Cmd;
to_atom(Cmd) when is_list(Cmd) ->
list_to_atom(Cmd);
to_atom(Cmd) when is_binary(Cmd) ->
binary_to_atom(Cmd,utf8).
|
a139ad59984e7bd668c04b5003ef7612c035c12ab9bf75f2982807c6f2edd909 | qfpl/reflex-tutorial | Exercise.hs | # LANGUAGE CPP #
# LANGUAGE RecursiveDo #
{-# LANGUAGE OverloadedStrings #-}
module Ex10.Exercise where
import Control.Monad.Fix (MonadFix)
import Data.Text (Text)
import qualified Data.Map as Map
import Reflex
import Reflex.Dom.Core
#ifndef ghcjs_HOST_OS
import Util.Run
#endif
import Ex10.Common
import Ex10.Run
grid :: MonadWidget t m
=> m a
-> m a
grid =
el "table"
row :: MonadWidget t m
=> m a
-> m b
-> m c
-> m d
-> m d
row ma mb mc md =
error "TODO"
mkStock ::
( Reflex t
, MonadHold t m
, MonadFix m
) =>
Int ->
Product ->
Event t Text ->
m (Dynamic t Stock)
mkStock =
error "TODO"
ex10 ::
( MonadWidget t m
) =>
Inputs t ->
m (Event t Text)
ex10 (Inputs dCarrot dCelery dCucumber dSelected) = mdo
let
eVend =
never
pure eVend
#ifndef ghcjs_HOST_OS
go ::
IO ()
go =
run $
host grid row mkStock ex10
#endif
| null | https://raw.githubusercontent.com/qfpl/reflex-tutorial/07c1e6fab387cbeedd031630ba6a5cd946cc612e/code/exercises/src/Ex10/Exercise.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE CPP #
# LANGUAGE RecursiveDo #
module Ex10.Exercise where
import Control.Monad.Fix (MonadFix)
import Data.Text (Text)
import qualified Data.Map as Map
import Reflex
import Reflex.Dom.Core
#ifndef ghcjs_HOST_OS
import Util.Run
#endif
import Ex10.Common
import Ex10.Run
grid :: MonadWidget t m
=> m a
-> m a
grid =
el "table"
row :: MonadWidget t m
=> m a
-> m b
-> m c
-> m d
-> m d
row ma mb mc md =
error "TODO"
mkStock ::
( Reflex t
, MonadHold t m
, MonadFix m
) =>
Int ->
Product ->
Event t Text ->
m (Dynamic t Stock)
mkStock =
error "TODO"
ex10 ::
( MonadWidget t m
) =>
Inputs t ->
m (Event t Text)
ex10 (Inputs dCarrot dCelery dCucumber dSelected) = mdo
let
eVend =
never
pure eVend
#ifndef ghcjs_HOST_OS
go ::
IO ()
go =
run $
host grid row mkStock ex10
#endif
|
e22f46f605ef4f4d6411a5ad7c48dfb211ba1b3cb12a6ed571ef7bc5b378a764 | GNOME/gimp-tiny-fu | comic-logo.scm | ; GIMP - The GNU Image Manipulation Program
Copyright ( C ) 1995 and
;
; 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 </>.
;
Comic Book Logo v0.1 04/08/98
by
Creates snazzy - looking text , inspired by watching a Maxx marathon :)
(define (apply-comic-logo-effect img
logo-layer
gradient
gradient-reverse
ol-width
ol-color
bg-color)
(let* (
(width (car (gimp-drawable-width logo-layer)))
(height (car (gimp-drawable-height logo-layer)))
(posx (- (car (gimp-drawable-offsets logo-layer))))
(posy (- (cadr (gimp-drawable-offsets logo-layer))))
(bg-layer (car (gimp-layer-new img width height RGBA-IMAGE
"Background" 100 NORMAL-MODE)))
(white-layer (car (gimp-layer-copy logo-layer 1)))
(black-layer (car (gimp-layer-copy logo-layer 1)))
)
(gimp-context-push)
(script-fu-util-image-resize-from-layer img logo-layer)
(script-fu-util-image-add-layers img black-layer white-layer bg-layer)
(gimp-layer-translate white-layer posx posy)
(gimp-item-set-name white-layer "White")
(gimp-layer-translate black-layer posx posy)
(gimp-item-set-name black-layer "Black")
(gimp-selection-all img)
(gimp-context-set-background bg-color)
(gimp-edit-fill bg-layer BACKGROUND-FILL)
(gimp-selection-none img)
(gimp-layer-set-lock-alpha white-layer TRUE)
(gimp-context-set-background ol-color)
(gimp-selection-all img)
(gimp-edit-fill white-layer BACKGROUND-FILL)
(gimp-layer-set-lock-alpha white-layer FALSE)
(plug-in-spread RUN-NONINTERACTIVE img white-layer (* 3 ol-width) (* 3 ol-width))
(plug-in-gauss-rle RUN-NONINTERACTIVE img white-layer (* 2 ol-width) 1 1)
(plug-in-threshold-alpha RUN-NONINTERACTIVE img white-layer 0)
(gimp-layer-set-lock-alpha white-layer TRUE)
(gimp-edit-fill white-layer BACKGROUND-FILL)
(gimp-selection-none img)
(gimp-context-set-background '(0 0 0))
(gimp-layer-set-lock-alpha black-layer TRUE)
(gimp-selection-all img)
(gimp-edit-fill black-layer BACKGROUND-FILL)
(gimp-selection-none img)
(gimp-layer-set-lock-alpha black-layer FALSE)
(plug-in-gauss-rle RUN-NONINTERACTIVE img black-layer ol-width 1 1)
(plug-in-threshold-alpha RUN-NONINTERACTIVE img black-layer 0)
(gimp-context-set-gradient gradient)
(gimp-layer-set-lock-alpha logo-layer TRUE)
(gimp-selection-all img)
(gimp-edit-blend logo-layer CUSTOM-MODE NORMAL-MODE
GRADIENT-LINEAR 100 0 REPEAT-NONE gradient-reverse
FALSE 0 0 TRUE
0 (* height 0.3) 0 (* height 0.78))
(plug-in-noisify RUN-NONINTERACTIVE img logo-layer 0 0.20 0.20 0.20 0.20)
(gimp-selection-none img)
(gimp-layer-set-lock-alpha logo-layer FALSE)
(gimp-brightness-contrast logo-layer 0 30)
(plug-in-threshold-alpha RUN-NONINTERACTIVE img logo-layer 60)
(gimp-image-set-active-layer img logo-layer)
(gimp-context-pop)
)
)
(define (script-fu-comic-logo-alpha img
logo-layer
gradient
gradient-reverse
ol-width
ol-color
bg-color)
(begin
(gimp-image-undo-group-start img)
(apply-comic-logo-effect img logo-layer
gradient gradient-reverse
ol-width ol-color bg-color)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
)
)
(script-fu-register "script-fu-comic-logo-alpha"
_"Comic Boo_k..."
_"Add a comic-book effect to the selected region (or alpha) by outlining and filling with a gradient"
"Brian McFee <>"
"Brian McFee"
"April 1998"
"RGBA"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-GRADIENT _"Gradient" "Incandescent"
SF-TOGGLE _"Gradient reverse" FALSE
SF-ADJUSTMENT _"Outline size" '(5 1 100 1 10 0 1)
SF-COLOR _"Outline color" "white"
SF-COLOR _"Background color" "white"
)
(script-fu-menu-register "script-fu-comic-logo-alpha"
"<Image>/Filters/Alpha to Logo")
(define (script-fu-comic-logo text
size
font
gradient
gradient-reverse
ol-width
ol-color
bg-color)
(let* ((img (car (gimp-image-new 256 256 RGB)))
(border (/ size 4))
(text-layer (car (gimp-text-fontname
img -1 0 0 text border TRUE size PIXELS font))))
(gimp-image-undo-disable img)
(apply-comic-logo-effect img text-layer gradient gradient-reverse
ol-width ol-color bg-color)
(gimp-image-undo-enable img)
(gimp-display-new img)
)
)
(script-fu-register "script-fu-comic-logo"
_"Comic Boo_k..."
_"Create a comic-book style logo by outlining and filling with a gradient"
"Brian McFee <>"
"Brian McFee"
"April 1998"
""
SF-STRING _"Text" "Moo"
SF-ADJUSTMENT _"Font size (pixels)" '(85 2 1000 1 10 0 1)
SF-FONT _"Font" "Tribeca"
SF-GRADIENT _"Gradient" "Incandescent"
SF-TOGGLE _"Gradient reverse" FALSE
SF-ADJUSTMENT _"Outline size" '(5 1 100 1 10 0 1)
SF-COLOR _"Outline color" "white"
SF-COLOR _"Background color" "white"
)
(script-fu-menu-register "script-fu-comic-logo"
"<Image>/File/Create/Logos")
| null | https://raw.githubusercontent.com/GNOME/gimp-tiny-fu/a64d85eec23b997e535488d67f55b44395ba3f2e/scripts/comic-logo.scm | scheme | GIMP - The GNU Image Manipulation Program
This program is free software: you can redistribute it and/or modify
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.
along with this program. If not, see </>.
| Copyright ( C ) 1995 and
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Comic Book Logo v0.1 04/08/98
by
Creates snazzy - looking text , inspired by watching a Maxx marathon :)
(define (apply-comic-logo-effect img
logo-layer
gradient
gradient-reverse
ol-width
ol-color
bg-color)
(let* (
(width (car (gimp-drawable-width logo-layer)))
(height (car (gimp-drawable-height logo-layer)))
(posx (- (car (gimp-drawable-offsets logo-layer))))
(posy (- (cadr (gimp-drawable-offsets logo-layer))))
(bg-layer (car (gimp-layer-new img width height RGBA-IMAGE
"Background" 100 NORMAL-MODE)))
(white-layer (car (gimp-layer-copy logo-layer 1)))
(black-layer (car (gimp-layer-copy logo-layer 1)))
)
(gimp-context-push)
(script-fu-util-image-resize-from-layer img logo-layer)
(script-fu-util-image-add-layers img black-layer white-layer bg-layer)
(gimp-layer-translate white-layer posx posy)
(gimp-item-set-name white-layer "White")
(gimp-layer-translate black-layer posx posy)
(gimp-item-set-name black-layer "Black")
(gimp-selection-all img)
(gimp-context-set-background bg-color)
(gimp-edit-fill bg-layer BACKGROUND-FILL)
(gimp-selection-none img)
(gimp-layer-set-lock-alpha white-layer TRUE)
(gimp-context-set-background ol-color)
(gimp-selection-all img)
(gimp-edit-fill white-layer BACKGROUND-FILL)
(gimp-layer-set-lock-alpha white-layer FALSE)
(plug-in-spread RUN-NONINTERACTIVE img white-layer (* 3 ol-width) (* 3 ol-width))
(plug-in-gauss-rle RUN-NONINTERACTIVE img white-layer (* 2 ol-width) 1 1)
(plug-in-threshold-alpha RUN-NONINTERACTIVE img white-layer 0)
(gimp-layer-set-lock-alpha white-layer TRUE)
(gimp-edit-fill white-layer BACKGROUND-FILL)
(gimp-selection-none img)
(gimp-context-set-background '(0 0 0))
(gimp-layer-set-lock-alpha black-layer TRUE)
(gimp-selection-all img)
(gimp-edit-fill black-layer BACKGROUND-FILL)
(gimp-selection-none img)
(gimp-layer-set-lock-alpha black-layer FALSE)
(plug-in-gauss-rle RUN-NONINTERACTIVE img black-layer ol-width 1 1)
(plug-in-threshold-alpha RUN-NONINTERACTIVE img black-layer 0)
(gimp-context-set-gradient gradient)
(gimp-layer-set-lock-alpha logo-layer TRUE)
(gimp-selection-all img)
(gimp-edit-blend logo-layer CUSTOM-MODE NORMAL-MODE
GRADIENT-LINEAR 100 0 REPEAT-NONE gradient-reverse
FALSE 0 0 TRUE
0 (* height 0.3) 0 (* height 0.78))
(plug-in-noisify RUN-NONINTERACTIVE img logo-layer 0 0.20 0.20 0.20 0.20)
(gimp-selection-none img)
(gimp-layer-set-lock-alpha logo-layer FALSE)
(gimp-brightness-contrast logo-layer 0 30)
(plug-in-threshold-alpha RUN-NONINTERACTIVE img logo-layer 60)
(gimp-image-set-active-layer img logo-layer)
(gimp-context-pop)
)
)
(define (script-fu-comic-logo-alpha img
logo-layer
gradient
gradient-reverse
ol-width
ol-color
bg-color)
(begin
(gimp-image-undo-group-start img)
(apply-comic-logo-effect img logo-layer
gradient gradient-reverse
ol-width ol-color bg-color)
(gimp-image-undo-group-end img)
(gimp-displays-flush)
)
)
(script-fu-register "script-fu-comic-logo-alpha"
_"Comic Boo_k..."
_"Add a comic-book effect to the selected region (or alpha) by outlining and filling with a gradient"
"Brian McFee <>"
"Brian McFee"
"April 1998"
"RGBA"
SF-IMAGE "Image" 0
SF-DRAWABLE "Drawable" 0
SF-GRADIENT _"Gradient" "Incandescent"
SF-TOGGLE _"Gradient reverse" FALSE
SF-ADJUSTMENT _"Outline size" '(5 1 100 1 10 0 1)
SF-COLOR _"Outline color" "white"
SF-COLOR _"Background color" "white"
)
(script-fu-menu-register "script-fu-comic-logo-alpha"
"<Image>/Filters/Alpha to Logo")
(define (script-fu-comic-logo text
size
font
gradient
gradient-reverse
ol-width
ol-color
bg-color)
(let* ((img (car (gimp-image-new 256 256 RGB)))
(border (/ size 4))
(text-layer (car (gimp-text-fontname
img -1 0 0 text border TRUE size PIXELS font))))
(gimp-image-undo-disable img)
(apply-comic-logo-effect img text-layer gradient gradient-reverse
ol-width ol-color bg-color)
(gimp-image-undo-enable img)
(gimp-display-new img)
)
)
(script-fu-register "script-fu-comic-logo"
_"Comic Boo_k..."
_"Create a comic-book style logo by outlining and filling with a gradient"
"Brian McFee <>"
"Brian McFee"
"April 1998"
""
SF-STRING _"Text" "Moo"
SF-ADJUSTMENT _"Font size (pixels)" '(85 2 1000 1 10 0 1)
SF-FONT _"Font" "Tribeca"
SF-GRADIENT _"Gradient" "Incandescent"
SF-TOGGLE _"Gradient reverse" FALSE
SF-ADJUSTMENT _"Outline size" '(5 1 100 1 10 0 1)
SF-COLOR _"Outline color" "white"
SF-COLOR _"Background color" "white"
)
(script-fu-menu-register "script-fu-comic-logo"
"<Image>/File/Create/Logos")
|
3dbab3a1bc6419cf1c7898b188507d532a4f27a0d429ef2e74024f444b9a221e | ocsigen/tuto | tuto.ml | open Eliom_content.Html5.D
open Eliom_parameter
(* Services *)
let main_service = Eliom_service.service ~path:[""] ~get_params:unit ()
let user_service =
Eliom_service.service
~path:["users"] ~get_params:(suffix (string "name")) ()
let connection_service =
Eliom_service.post_service
~fallback:main_service
~post_params:(string "name" ** string "password")
()
let disconnection_service = Eliom_service.post_coservice' ~post_params:unit ()
let new_user_form_service = Eliom_service.service ~path:["create account"] ~get_params:unit ()
let account_confirmation_service =
Eliom_service.post_coservice ~fallback:new_user_form_service ~post_params:(string "name" ** string "password") ()
(* User names and passwords: *)
let users = ref [("Calvin", "123"); ("Hobbes", "456")]
let user_links () =
ul (List.map (fun (name, _) -> li [a ~service:user_service [pcdata name] name]) !users)
let check_pwd name pwd = try List.assoc name !users = pwd with Not_found -> false
Eliom references
let username = Eliom_reference.eref ~scope:Eliom_common.session None
let wrong_pwd = Eliom_reference.eref ~scope:Eliom_common.request false
(* Page widgets: *)
let disconnect_box () =
post_form disconnection_service
(fun _ -> [fieldset
[string_input
~input_type:`Submit ~value:"Log out" ()]]) ()
let connection_box () =
lwt u = Eliom_reference.get username in
lwt wp = Eliom_reference.get wrong_pwd in
Lwt.return
(match u with
| Some s -> div [p [pcdata "You are connected as "; pcdata s; ];
disconnect_box () ]
| None ->
let l =
[post_form ~service:connection_service
(fun (name1, name2) ->
[fieldset
[label ~a:[a_for name1] [pcdata "login: "];
string_input ~input_type:`Text ~name:name1 ();
br ();
label ~a:[a_for name2] [pcdata "password: "];
string_input ~input_type:`Password ~name:name2 ();
br ();
string_input ~input_type:`Submit ~value:"Connect" ()
]]) ();
p [a new_user_form_service [pcdata "Create an account"] ()]]
in
if wp
then div ((p [em [pcdata "Wrong user or password"]])::l)
else div l
)
let create_account_form () =
post_form ~service:account_confirmation_service
(fun (name1, name2) ->
[fieldset
[label ~a:[a_for name1] [pcdata "login: "];
string_input ~input_type:`Text ~name:name1 ();
br ();
label ~a:[a_for name2] [pcdata "password: "];
string_input ~input_type:`Password ~name:name2 ();
br ();
string_input ~input_type:`Submit ~value:"Connect" ()
]]) ()
(* Registration of services *)
let _ =
Eliom_registration.Html5.register
~service:main_service
(fun () () ->
lwt cf = connection_box () in
Lwt.return
(html (head (title (pcdata "")) [])
(body [h1 [pcdata "Hello"];
cf;
user_links ()])));
Eliom_registration.Any.register
~service:user_service
(fun name () ->
if List.exists (fun (n, _) -> n = name) !users
then begin
lwt cf = connection_box () in
Eliom_registration.Html5.send
(html (head (title (pcdata name)) [])
(body [h1 [pcdata name];
cf;
p [a ~service:main_service [pcdata "Home"] ()]]))
end
else
Eliom_registration.Html5.send
~code:404
(html (head (title (pcdata "404")) [])
(body [h1 [pcdata "404"];
p [pcdata "That page does not exist"]]))
);
Eliom_registration.Action.register
~service:connection_service
(fun () (name, password) ->
if check_pwd name password
then Eliom_reference.set username (Some name)
else Eliom_reference.set wrong_pwd true);
Eliom_registration.Action.register
~service:disconnection_service
(fun () () -> Eliom_state.discard ~scope:Eliom_common.session ());
Eliom_registration.Html5.register
~service:new_user_form_service
(fun () () ->
Lwt.return
(html (head (title (pcdata "")) [])
(body [h1 [pcdata "Create an account"];
create_account_form ();
])));
Eliom_registration.Html5.register
~service:account_confirmation_service
(fun () (name, pwd) ->
let create_account_service =
Eliom_registration.Action.register_coservice
~fallback:main_service
~get_params:Eliom_parameter.unit
~timeout:60.
(fun () () ->
users := (name, pwd)::!users;
Lwt.return ())
in
Lwt.return
(html (head (title (pcdata "")) [])
(body [h1 [pcdata "Confirm account creation for "; pcdata name];
p [a ~service:create_account_service [pcdata "Yes"] ();
pcdata " ";
a ~service:main_service [pcdata "No"] ()]
])))
| null | https://raw.githubusercontent.com/ocsigen/tuto/5fbde05a5d496b184d4ecde75ffebd33873acac5/tutos/2.2/manual/files/tutorial/chapter2/tuto.ml | ocaml | Services
User names and passwords:
Page widgets:
Registration of services | open Eliom_content.Html5.D
open Eliom_parameter
let main_service = Eliom_service.service ~path:[""] ~get_params:unit ()
let user_service =
Eliom_service.service
~path:["users"] ~get_params:(suffix (string "name")) ()
let connection_service =
Eliom_service.post_service
~fallback:main_service
~post_params:(string "name" ** string "password")
()
let disconnection_service = Eliom_service.post_coservice' ~post_params:unit ()
let new_user_form_service = Eliom_service.service ~path:["create account"] ~get_params:unit ()
let account_confirmation_service =
Eliom_service.post_coservice ~fallback:new_user_form_service ~post_params:(string "name" ** string "password") ()
let users = ref [("Calvin", "123"); ("Hobbes", "456")]
let user_links () =
ul (List.map (fun (name, _) -> li [a ~service:user_service [pcdata name] name]) !users)
let check_pwd name pwd = try List.assoc name !users = pwd with Not_found -> false
Eliom references
let username = Eliom_reference.eref ~scope:Eliom_common.session None
let wrong_pwd = Eliom_reference.eref ~scope:Eliom_common.request false
let disconnect_box () =
post_form disconnection_service
(fun _ -> [fieldset
[string_input
~input_type:`Submit ~value:"Log out" ()]]) ()
let connection_box () =
lwt u = Eliom_reference.get username in
lwt wp = Eliom_reference.get wrong_pwd in
Lwt.return
(match u with
| Some s -> div [p [pcdata "You are connected as "; pcdata s; ];
disconnect_box () ]
| None ->
let l =
[post_form ~service:connection_service
(fun (name1, name2) ->
[fieldset
[label ~a:[a_for name1] [pcdata "login: "];
string_input ~input_type:`Text ~name:name1 ();
br ();
label ~a:[a_for name2] [pcdata "password: "];
string_input ~input_type:`Password ~name:name2 ();
br ();
string_input ~input_type:`Submit ~value:"Connect" ()
]]) ();
p [a new_user_form_service [pcdata "Create an account"] ()]]
in
if wp
then div ((p [em [pcdata "Wrong user or password"]])::l)
else div l
)
let create_account_form () =
post_form ~service:account_confirmation_service
(fun (name1, name2) ->
[fieldset
[label ~a:[a_for name1] [pcdata "login: "];
string_input ~input_type:`Text ~name:name1 ();
br ();
label ~a:[a_for name2] [pcdata "password: "];
string_input ~input_type:`Password ~name:name2 ();
br ();
string_input ~input_type:`Submit ~value:"Connect" ()
]]) ()
let _ =
Eliom_registration.Html5.register
~service:main_service
(fun () () ->
lwt cf = connection_box () in
Lwt.return
(html (head (title (pcdata "")) [])
(body [h1 [pcdata "Hello"];
cf;
user_links ()])));
Eliom_registration.Any.register
~service:user_service
(fun name () ->
if List.exists (fun (n, _) -> n = name) !users
then begin
lwt cf = connection_box () in
Eliom_registration.Html5.send
(html (head (title (pcdata name)) [])
(body [h1 [pcdata name];
cf;
p [a ~service:main_service [pcdata "Home"] ()]]))
end
else
Eliom_registration.Html5.send
~code:404
(html (head (title (pcdata "404")) [])
(body [h1 [pcdata "404"];
p [pcdata "That page does not exist"]]))
);
Eliom_registration.Action.register
~service:connection_service
(fun () (name, password) ->
if check_pwd name password
then Eliom_reference.set username (Some name)
else Eliom_reference.set wrong_pwd true);
Eliom_registration.Action.register
~service:disconnection_service
(fun () () -> Eliom_state.discard ~scope:Eliom_common.session ());
Eliom_registration.Html5.register
~service:new_user_form_service
(fun () () ->
Lwt.return
(html (head (title (pcdata "")) [])
(body [h1 [pcdata "Create an account"];
create_account_form ();
])));
Eliom_registration.Html5.register
~service:account_confirmation_service
(fun () (name, pwd) ->
let create_account_service =
Eliom_registration.Action.register_coservice
~fallback:main_service
~get_params:Eliom_parameter.unit
~timeout:60.
(fun () () ->
users := (name, pwd)::!users;
Lwt.return ())
in
Lwt.return
(html (head (title (pcdata "")) [])
(body [h1 [pcdata "Confirm account creation for "; pcdata name];
p [a ~service:create_account_service [pcdata "Yes"] ();
pcdata " ";
a ~service:main_service [pcdata "No"] ()]
])))
|
9624cfc2283ee161d274d37dc2708378a6c9cafe95a9622471f63304a0613cb8 | onedata/op-worker | view_test_SUITE.erl | %%%-------------------------------------------------------------------
@author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%%--------------------------------------------------------------------
%%% @doc
Basic tests of couchbase views .
%%% @end
%%%-------------------------------------------------------------------
-module(view_test_SUITE).
-author("Jakub Kudzia").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include_lib("ctool/include/test/test_utils.hrl").
-include_lib("ctool/include/test/assertions.hrl").
-include_lib("ctool/include/test/performance.hrl").
-include_lib("ctool/include/errors.hrl").
%% API
%% export for ct
-export([
all/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2
]).
%% tests
-export([
create_and_delete_simple_view_test/1,
query_simple_empty_view_test/1,
query_view_using_file_meta/1,
query_view_using_times/1,
query_view_using_custom_metadata_when_xattr_is_not_set/1,
query_view_using_custom_metadata/1,
query_view_using_file_popularity/1,
query_view_and_emit_ctx/1,
wrong_map_function/1,
emitting_null_key_in_map_function_should_return_empty_result/1,
spatial_function_returning_null_in_key_should_return_empty_result/1,
spatial_function_returning_null_in_array_key_should_return_empty_result/1,
spatial_function_returning_null_in_range_key_should_return_empty_result/1,
spatial_function_returning_integer_key_should_return_error/1,
spatial_function_returning_string_key_should_return_error/1
]).
%% macros
-define(SPACE_ID, <<"space_id1">>).
-define(SPACE_NAME, <<"space_name1">>).
-define(TEST_FILE(SpaceName), begin
FunctionNameBin = str_utils:to_binary(?FUNCTION),
RandIntBin = str_utils:to_binary(rand:uniform(1000000000)),
FileName = <<FunctionNameBin/binary, "_", RandIntBin/binary>>,
filename:join(["/", SpaceName, FileName])
end).
-define(USER_ID, <<"user1">>).
-define(SESS_ID(Worker),
?config({session_id, {?USER_ID, ?GET_DOMAIN(Worker)}}, Config)).
-define(view_name, begin <<"view_", (str_utils:to_binary(?FUNCTION))/binary>> end).
-define(ATTEMPTS, 15).
-define(assertQuery(ExpectedRows, Worker, SpaceId, ViewName, Options),
?assertQuery(ExpectedRows, Worker, SpaceId, ViewName, Options, ?ATTEMPTS)).
-define(assertQuery(ExpectedRows, Worker, SpaceId, ViewName, Options, Attempts),
?assertMatch(ExpectedRows, begin
case query_view(Worker, SpaceId, ViewName, Options) of
{ok, #{<<"rows">> := Rows}} -> Rows;
Error -> Error
end
end, Attempts)).
%%%===================================================================
%%% API
%%%===================================================================
all() -> ?ALL([
create_and_delete_simple_view_test,
query_simple_empty_view_test,
query_view_using_file_meta,
query_view_using_times,
query_view_using_custom_metadata_when_xattr_is_not_set,
query_view_using_custom_metadata,
query_view_using_file_popularity,
query_view_and_emit_ctx,
wrong_map_function,
emitting_null_key_in_map_function_should_return_empty_result,
spatial_function_returning_null_in_key_should_return_empty_result,
spatial_function_returning_null_in_array_key_should_return_empty_result,
spatial_function_returning_null_in_range_key_should_return_empty_result,
spatial_function_returning_integer_key_should_return_error,
spatial_function_returning_string_key_should_return_error
]).
%%%===================================================================
%%% Test functions
%%%===================================================================
create_and_delete_simple_view_test(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
return [id, id];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertMatch({ok, [ViewName]}, list_views(Worker, SpaceId)),
delete_view(Worker, SpaceId, ViewName),
?assertMatch({ok, []}, list_views(Worker, SpaceId)).
query_simple_empty_view_test(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
return null;
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_file_meta(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceUuid = fslogic_file_id:spaceid_to_space_dir_uuid(SpaceId),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
TrashGuid = fslogic_file_id:spaceid_to_trash_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
{ok, TrashObjectId} = file_id:guid_to_objectid(TrashGuid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'file_meta')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
SpaceOwnerId = ?SPACE_OWNER_ID(SpaceId),
?assertQuery([
#{
<<"id">> := _,
<<"key">> := TrashObjectId,
<<"value">> := #{
<<"name">> := ?TRASH_DIR_NAME,
<<"type">> := <<"DIR">>,
<<"mode">> := ?DEFAULT_DIR_MODE,
<<"owner">> := SpaceOwnerId,
<<"provider_id">> := ProviderId,
<<"shares">> := [],
<<"deleted">> := false,
<<"parent_uuid">> := SpaceUuid
}
},
#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"name">> := ?SPACE_ID,
<<"type">> := <<"DIR">>,
<<"mode">> := ?DEFAULT_DIR_MODE,
<<"owner">> := SpaceOwnerId,
<<"provider_id">> := ProviderId,
<<"shares">> := [],
<<"deleted">> := false,
<<"parent_uuid">> := <<"">>
}
}
],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_times(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'times')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"atime">> := _,
<<"mtime">> := _,
<<"ctime">> := _
}}],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_custom_metadata_when_xattr_is_not_set(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(id, file_meta, times, custom_metadata, file_popularity, ctx) {
if(type == 'custom_metadata')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_custom_metadata(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
ProviderId = ?GET_DOMAIN_BIN(Worker),
XattrName = <<"xattr_name">>,
XattrValue = <<"xattr_value">>,
Xattr = #xattr{name = XattrName, value = XattrValue},
lfm_proxy:set_xattr(Worker, ?SESS_ID(Worker), ?FILE_REF(SpaceGuid), Xattr),
XattrName2 = <<"xattr_name2">>,
XattrValue2 = <<"xattr_value2">>,
Xattr2 = #xattr{name = XattrName2, value = XattrValue2},
lfm_proxy:set_xattr(Worker, ?SESS_ID(Worker), ?FILE_REF(SpaceGuid), Xattr2),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'custom_metadata')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
XattrName := XattrValue,
XattrName2 := XattrValue2
}
}],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_file_popularity(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
SessionId = ?SESS_ID(Worker),
ProviderId = ?GET_DOMAIN_BIN(Worker),
TestData = <<"test_data">>,
TestDataSize = byte_size(TestData),
ok = rpc:call(Worker, file_popularity_api, enable, [?SPACE_ID]),
FilePath = ?TEST_FILE(?SPACE_NAME),
{ok, Guid} = lfm_proxy:create(Worker, SessionId, FilePath),
Uuid = file_id:guid_to_uuid(Guid),
{ok, H} = lfm_proxy:open(Worker, SessionId, ?FILE_REF(Guid), write),
lfm_proxy:write(Worker, H, 0, TestData),
lfm_proxy:close(Worker, H),
{ok, CdmiId} = file_id:guid_to_objectid(Guid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'file_popularity')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"file_uuid">> := Uuid,
<<"space_id">> := ?SPACE_ID,
<<"dy_hist">> :=[1 | _],
<<"hr_hist">> := [1 | _],
<<"mth_hist">> := [1 | _],
<<"dy_mov_avg">> := 1/30,
<<"hr_mov_avg">> := 1/24,
<<"mth_mov_avg">> := 1/12,
<<"last_open">> := _,
<<"open_count">> := 1,
<<"size">> := TestDataSize
}}],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_and_emit_ctx(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'file_meta')
return [id, ctx];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"providerId">> := ProviderId
}}],Worker, SpaceId, ViewName, [{stale, false}, {key, CdmiId}]).
wrong_map_function(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
SimpleMapFunction = <<"
function(_, _, _, _) {
throw 'Test error';
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {key, CdmiId}]).
emitting_null_key_in_map_function_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(_, _, _, _) {
return [null, null];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {key, CdmiId}]).
spatial_function_returning_null_in_key_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [null, null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_null_in_array_key_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [[null, 1], null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_null_in_range_key_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [[[null, 1], [5, 7]], null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_integer_key_should_return_error(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [1, null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery(?ERROR_VIEW_QUERY_FAILED(_, _),
Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_string_key_should_return_error(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [[\"string\"], null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery(?ERROR_VIEW_QUERY_FAILED(_, _),
Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
%%%===================================================================
SetUp and TearDown functions
%%%===================================================================
init_per_suite(Config) ->
Posthook = fun(NewConfig) -> initializer:setup_storage(NewConfig) end,
[{?ENV_UP_POSTHOOK, Posthook}, {?LOAD_MODULES, [initializer]} | Config].
end_per_suite(Config) ->
initializer:teardown_storage(Config).
init_per_testcase(_Case, Config) ->
Workers = ?config(op_worker_nodes, Config),
initializer:communicator_mock(Workers),
ConfigWithSessionInfo = initializer:create_test_users_and_spaces(?TEST_FILE(Config, "env_desc.json"), Config),
lfm_proxy:init(ConfigWithSessionInfo).
end_per_testcase(_Case, Config) ->
Workers = ?config(op_worker_nodes, Config),
lfm_proxy:teardown(Config),
initializer:clean_test_users_and_spaces_no_validate(Config),
test_utils:mock_validate_and_unload(Workers, [communicator]).
%%%===================================================================
Internal functions
%%%===================================================================
create_view(Worker, SpaceId, ViewName, MapFunction, ReduceFunction, Options, Spatial, ProviderIds) ->
ok = rpc:call(Worker, index, save, [SpaceId, ViewName, MapFunction,
ReduceFunction, Options, Spatial, ProviderIds]).
delete_view(Worker, SpaceId, ViewName) ->
ok = rpc:call(Worker, index, delete, [SpaceId, ViewName]).
query_view(Worker, SpaceId, ViewName, Options) ->
rpc:call(Worker, index, query, [SpaceId, ViewName, Options]).
list_views(Worker, SpaceId) ->
rpc:call(Worker, index, list, [SpaceId]). | null | https://raw.githubusercontent.com/onedata/op-worker/239b30c6510ccf0f2f429dc5c48ecf04d192549a/test_distributed/view_test_SUITE.erl | erlang | -------------------------------------------------------------------
--------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
API
export for ct
tests
macros
===================================================================
API
===================================================================
===================================================================
Test functions
===================================================================
===================================================================
===================================================================
===================================================================
=================================================================== | @author
( C ) 2018 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
Basic tests of couchbase views .
-module(view_test_SUITE).
-author("Jakub Kudzia").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/logical_file_manager/lfm.hrl").
-include_lib("ctool/include/test/test_utils.hrl").
-include_lib("ctool/include/test/assertions.hrl").
-include_lib("ctool/include/test/performance.hrl").
-include_lib("ctool/include/errors.hrl").
-export([
all/0,
init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2
]).
-export([
create_and_delete_simple_view_test/1,
query_simple_empty_view_test/1,
query_view_using_file_meta/1,
query_view_using_times/1,
query_view_using_custom_metadata_when_xattr_is_not_set/1,
query_view_using_custom_metadata/1,
query_view_using_file_popularity/1,
query_view_and_emit_ctx/1,
wrong_map_function/1,
emitting_null_key_in_map_function_should_return_empty_result/1,
spatial_function_returning_null_in_key_should_return_empty_result/1,
spatial_function_returning_null_in_array_key_should_return_empty_result/1,
spatial_function_returning_null_in_range_key_should_return_empty_result/1,
spatial_function_returning_integer_key_should_return_error/1,
spatial_function_returning_string_key_should_return_error/1
]).
-define(SPACE_ID, <<"space_id1">>).
-define(SPACE_NAME, <<"space_name1">>).
-define(TEST_FILE(SpaceName), begin
FunctionNameBin = str_utils:to_binary(?FUNCTION),
RandIntBin = str_utils:to_binary(rand:uniform(1000000000)),
FileName = <<FunctionNameBin/binary, "_", RandIntBin/binary>>,
filename:join(["/", SpaceName, FileName])
end).
-define(USER_ID, <<"user1">>).
-define(SESS_ID(Worker),
?config({session_id, {?USER_ID, ?GET_DOMAIN(Worker)}}, Config)).
-define(view_name, begin <<"view_", (str_utils:to_binary(?FUNCTION))/binary>> end).
-define(ATTEMPTS, 15).
-define(assertQuery(ExpectedRows, Worker, SpaceId, ViewName, Options),
?assertQuery(ExpectedRows, Worker, SpaceId, ViewName, Options, ?ATTEMPTS)).
-define(assertQuery(ExpectedRows, Worker, SpaceId, ViewName, Options, Attempts),
?assertMatch(ExpectedRows, begin
case query_view(Worker, SpaceId, ViewName, Options) of
{ok, #{<<"rows">> := Rows}} -> Rows;
Error -> Error
end
end, Attempts)).
all() -> ?ALL([
create_and_delete_simple_view_test,
query_simple_empty_view_test,
query_view_using_file_meta,
query_view_using_times,
query_view_using_custom_metadata_when_xattr_is_not_set,
query_view_using_custom_metadata,
query_view_using_file_popularity,
query_view_and_emit_ctx,
wrong_map_function,
emitting_null_key_in_map_function_should_return_empty_result,
spatial_function_returning_null_in_key_should_return_empty_result,
spatial_function_returning_null_in_array_key_should_return_empty_result,
spatial_function_returning_null_in_range_key_should_return_empty_result,
spatial_function_returning_integer_key_should_return_error,
spatial_function_returning_string_key_should_return_error
]).
create_and_delete_simple_view_test(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
return [id, id];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertMatch({ok, [ViewName]}, list_views(Worker, SpaceId)),
delete_view(Worker, SpaceId, ViewName),
?assertMatch({ok, []}, list_views(Worker, SpaceId)).
query_simple_empty_view_test(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
return null;
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_file_meta(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceUuid = fslogic_file_id:spaceid_to_space_dir_uuid(SpaceId),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
TrashGuid = fslogic_file_id:spaceid_to_trash_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
{ok, TrashObjectId} = file_id:guid_to_objectid(TrashGuid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'file_meta')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
SpaceOwnerId = ?SPACE_OWNER_ID(SpaceId),
?assertQuery([
#{
<<"id">> := _,
<<"key">> := TrashObjectId,
<<"value">> := #{
<<"name">> := ?TRASH_DIR_NAME,
<<"type">> := <<"DIR">>,
<<"mode">> := ?DEFAULT_DIR_MODE,
<<"owner">> := SpaceOwnerId,
<<"provider_id">> := ProviderId,
<<"shares">> := [],
<<"deleted">> := false,
<<"parent_uuid">> := SpaceUuid
}
},
#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"name">> := ?SPACE_ID,
<<"type">> := <<"DIR">>,
<<"mode">> := ?DEFAULT_DIR_MODE,
<<"owner">> := SpaceOwnerId,
<<"provider_id">> := ProviderId,
<<"shares">> := [],
<<"deleted">> := false,
<<"parent_uuid">> := <<"">>
}
}
],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_times(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'times')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"atime">> := _,
<<"mtime">> := _,
<<"ctime">> := _
}}],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_custom_metadata_when_xattr_is_not_set(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(id, file_meta, times, custom_metadata, file_popularity, ctx) {
if(type == 'custom_metadata')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_custom_metadata(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
ProviderId = ?GET_DOMAIN_BIN(Worker),
XattrName = <<"xattr_name">>,
XattrValue = <<"xattr_value">>,
Xattr = #xattr{name = XattrName, value = XattrValue},
lfm_proxy:set_xattr(Worker, ?SESS_ID(Worker), ?FILE_REF(SpaceGuid), Xattr),
XattrName2 = <<"xattr_name2">>,
XattrValue2 = <<"xattr_value2">>,
Xattr2 = #xattr{name = XattrName2, value = XattrValue2},
lfm_proxy:set_xattr(Worker, ?SESS_ID(Worker), ?FILE_REF(SpaceGuid), Xattr2),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'custom_metadata')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
XattrName := XattrValue,
XattrName2 := XattrValue2
}
}],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_using_file_popularity(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
SessionId = ?SESS_ID(Worker),
ProviderId = ?GET_DOMAIN_BIN(Worker),
TestData = <<"test_data">>,
TestDataSize = byte_size(TestData),
ok = rpc:call(Worker, file_popularity_api, enable, [?SPACE_ID]),
FilePath = ?TEST_FILE(?SPACE_NAME),
{ok, Guid} = lfm_proxy:create(Worker, SessionId, FilePath),
Uuid = file_id:guid_to_uuid(Guid),
{ok, H} = lfm_proxy:open(Worker, SessionId, ?FILE_REF(Guid), write),
lfm_proxy:write(Worker, H, 0, TestData),
lfm_proxy:close(Worker, H),
{ok, CdmiId} = file_id:guid_to_objectid(Guid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'file_popularity')
return [id, meta];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"file_uuid">> := Uuid,
<<"space_id">> := ?SPACE_ID,
<<"dy_hist">> :=[1 | _],
<<"hr_hist">> := [1 | _],
<<"mth_hist">> := [1 | _],
<<"dy_mov_avg">> := 1/30,
<<"hr_mov_avg">> := 1/24,
<<"mth_mov_avg">> := 1/12,
<<"last_open">> := _,
<<"open_count">> := 1,
<<"size">> := TestDataSize
}}],Worker, SpaceId, ViewName, [{stale, false}]).
query_view_and_emit_ctx(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
SimpleMapFunction = <<"
function(id, type, meta, ctx) {
if(type == 'file_meta')
return [id, ctx];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([#{
<<"id">> := _,
<<"key">> := CdmiId,
<<"value">> := #{
<<"providerId">> := ProviderId
}}],Worker, SpaceId, ViewName, [{stale, false}, {key, CdmiId}]).
wrong_map_function(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
SimpleMapFunction = <<"
function(_, _, _, _) {
throw 'Test error';
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {key, CdmiId}]).
emitting_null_key_in_map_function_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
SpaceGuid = fslogic_file_id:spaceid_to_space_dir_guid(SpaceId),
{ok, CdmiId} = file_id:guid_to_objectid(SpaceGuid),
ProviderId = ?GET_DOMAIN_BIN(Worker),
SimpleMapFunction = <<"
function(_, _, _, _) {
return [null, null];
}
">>,
create_view(Worker, SpaceId, ViewName, SimpleMapFunction, undefined, [], false, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {key, CdmiId}]).
spatial_function_returning_null_in_key_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [null, null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_null_in_array_key_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [[null, 1], null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_null_in_range_key_should_return_empty_result(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [[[null, 1], [5, 7]], null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery([], Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_integer_key_should_return_error(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [1, null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery(?ERROR_VIEW_QUERY_FAILED(_, _),
Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
spatial_function_returning_string_key_should_return_error(Config) ->
[Worker | _] = ?config(op_worker_nodes, Config),
SpaceId = <<"space_id1">>,
ViewName = ?view_name,
ProviderId = ?GET_DOMAIN_BIN(Worker),
SpatialFunction = <<"
function(_, _, _, _) {
return [[\"string\"], null];
}
">>,
create_view(Worker, SpaceId, ViewName, SpatialFunction, undefined, [], true, [ProviderId]),
?assertQuery(?ERROR_VIEW_QUERY_FAILED(_, _),
Worker, SpaceId, ViewName, [{stale, false}, {spatial, true}]).
SetUp and TearDown functions
init_per_suite(Config) ->
Posthook = fun(NewConfig) -> initializer:setup_storage(NewConfig) end,
[{?ENV_UP_POSTHOOK, Posthook}, {?LOAD_MODULES, [initializer]} | Config].
end_per_suite(Config) ->
initializer:teardown_storage(Config).
init_per_testcase(_Case, Config) ->
Workers = ?config(op_worker_nodes, Config),
initializer:communicator_mock(Workers),
ConfigWithSessionInfo = initializer:create_test_users_and_spaces(?TEST_FILE(Config, "env_desc.json"), Config),
lfm_proxy:init(ConfigWithSessionInfo).
end_per_testcase(_Case, Config) ->
Workers = ?config(op_worker_nodes, Config),
lfm_proxy:teardown(Config),
initializer:clean_test_users_and_spaces_no_validate(Config),
test_utils:mock_validate_and_unload(Workers, [communicator]).
Internal functions
create_view(Worker, SpaceId, ViewName, MapFunction, ReduceFunction, Options, Spatial, ProviderIds) ->
ok = rpc:call(Worker, index, save, [SpaceId, ViewName, MapFunction,
ReduceFunction, Options, Spatial, ProviderIds]).
delete_view(Worker, SpaceId, ViewName) ->
ok = rpc:call(Worker, index, delete, [SpaceId, ViewName]).
query_view(Worker, SpaceId, ViewName, Options) ->
rpc:call(Worker, index, query, [SpaceId, ViewName, Options]).
list_views(Worker, SpaceId) ->
rpc:call(Worker, index, list, [SpaceId]). |
3beab1703a756cfeb1d6b6c756125fa3cdb718af905701ff9baf29b02ea89fef | aryx/xix | cmd.ml | s : version_control / cmd.ml
(*s: type [[Cmd.t]] *)
type t = {
name: string;
usage: string;
options: (Arg.key * Arg.spec * Arg.doc) list;
(* the command! *)
f: string list -> unit;
(* less: man: when do git -help get short help, and with --help man page *)
}
(*e: type [[Cmd.t]] *)
(*s: exception [[Cmd.ShowUsage]] *)
Cmd.f can raise ShowUsage . It will be catched by Main.main
exception ShowUsage
(*e: exception [[Cmd.ShowUsage]] *)
e : version_control / cmd.ml
| null | https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/version_control/cmd.ml | ocaml | s: type [[Cmd.t]]
the command!
less: man: when do git -help get short help, and with --help man page
e: type [[Cmd.t]]
s: exception [[Cmd.ShowUsage]]
e: exception [[Cmd.ShowUsage]] | s : version_control / cmd.ml
type t = {
name: string;
usage: string;
options: (Arg.key * Arg.spec * Arg.doc) list;
f: string list -> unit;
}
Cmd.f can raise ShowUsage . It will be catched by Main.main
exception ShowUsage
e : version_control / cmd.ml
|
6f408ca6f41f870d2e4416d11a973d03fde821468754bc683e003133c81b8ea8 | shirok/Gauche | u64.scm | (define-module srfi.160.u64 (extend gauche.uvector.u64))
| null | https://raw.githubusercontent.com/shirok/Gauche/ecaf82f72e2e946f62d99ed8febe0df8960d20c4/lib/srfi/160/u64.scm | scheme | (define-module srfi.160.u64 (extend gauche.uvector.u64))
|
|
30e5b8a4272911851834eec6699b0d56fb0ea88a72f81b62c8990729defa4a57 | rm-hull/wireframes | platonic_solids.clj | (ns wireframes.shapes.platonic-solids
(:require [wireframes.shapes.primitives :as p]
[wireframes.transform :as t]))
(def epsilon 0.00001)
(defn- =approx [^double x ^double y]
(< (Math/abs (- x y)) epsilon))
(def sqrt-2 (Math/sqrt 2))
(def sqrt-5 (Math/sqrt 5))
(def rho (/ (inc sqrt-5) 2))
(def -rho (- rho))
(def tetrahedron
{:points [(t/point 1 0 (/ -1 sqrt-2))
(t/point -1 0 (/ -1 sqrt-2))
(t/point 0 1 (/ 1 sqrt-2))
(t/point 0 -1 (/ 1 sqrt-2))]
:polygons [{:vertices [0 1 2]}
{:vertices [0 2 3]}
{:vertices [0 1 3]}
{:vertices [1 2 3]}]})
(def cube
"Start with a square polygon, and extrude to a line alone the Z-plane."
(->
(p/make-polygon
(p/make-point 0 0 0)
(p/make-point 0 1 0)
(p/make-point 1 1 0)
(p/make-point 1 0 0))
(p/extrude
(t/translate 0 0 1) 1)
(p/center-at-origin)))
(def octahedron
"A regular octahedron composed of eight equilateral triangles"
(let [points (vec
(apply concat
(for [a [-1 1]]
[(t/point a 0 0)
(t/point 0 a 0)
(t/point 0 0 a)])))
polygons (vec
(for [a (range (count points))
b (range a)
c (range b)
:when (and
(=approx (t/distance (points a) (points b)) sqrt-2)
(=approx (t/distance (points a) (points c)) sqrt-2)
(=approx (t/distance (points b) (points c)) sqrt-2))]
{:vertices [a b c]}))]
{:points points :polygons polygons }))
(def dodecahedron
"A 12-sided polyhedron with regular pentagonal faces"
{:points (vec
(apply concat
(for [x [-1 1]
y [-1 1]
z [-1 1]]
(t/point x y z))
(for [a [(/ -1 rho) (/ 1 rho)]
b [(- rho) rho]]
(map #(apply t/point %) (take 3 (partition 3 1 (cycle [0 a b])))))))
:polygons [{:vertices [14 8 0 10 2]}
{:vertices [14 8 4 13 6]}
{:vertices [15 9 0 8 4]}
{:vertices [15 9 1 11 5]}
{:vertices [16 10 0 9 1]}
{:vertices [16 10 2 12 3]}
{:vertices [17 11 1 16 3]}
{:vertices [17 11 5 19 7]}
{:vertices [18 12 2 14 6]}
{:vertices [18 12 3 17 7]}
{:vertices [19 13 4 15 5]}
{:vertices [19 13 6 18 7]}]})
(def icosahedron
"A 20-sided polyhedron with triangular faces"
(let [points (vec
(apply concat
(for [x [-1 1]
y [rho -rho]]
[(t/point 0 x y)
(t/point x y 0)
(t/point y 0 x)])))
polygons (vec
(for [a (range (count points))
b (range a)
c (range b)
:when (and
(=approx (t/distance (points a) (points b)) 2)
(=approx (t/distance (points a) (points c)) 2)
(=approx (t/distance (points b) (points c)) 2))]
{:vertices [a b c]}))]
{:points points :polygons polygons }))
| null | https://raw.githubusercontent.com/rm-hull/wireframes/7df78cc6e2040cd0de026795f2e63ad129e4fee5/src/clj/wireframes/shapes/platonic_solids.clj | clojure | (ns wireframes.shapes.platonic-solids
(:require [wireframes.shapes.primitives :as p]
[wireframes.transform :as t]))
(def epsilon 0.00001)
(defn- =approx [^double x ^double y]
(< (Math/abs (- x y)) epsilon))
(def sqrt-2 (Math/sqrt 2))
(def sqrt-5 (Math/sqrt 5))
(def rho (/ (inc sqrt-5) 2))
(def -rho (- rho))
(def tetrahedron
{:points [(t/point 1 0 (/ -1 sqrt-2))
(t/point -1 0 (/ -1 sqrt-2))
(t/point 0 1 (/ 1 sqrt-2))
(t/point 0 -1 (/ 1 sqrt-2))]
:polygons [{:vertices [0 1 2]}
{:vertices [0 2 3]}
{:vertices [0 1 3]}
{:vertices [1 2 3]}]})
(def cube
"Start with a square polygon, and extrude to a line alone the Z-plane."
(->
(p/make-polygon
(p/make-point 0 0 0)
(p/make-point 0 1 0)
(p/make-point 1 1 0)
(p/make-point 1 0 0))
(p/extrude
(t/translate 0 0 1) 1)
(p/center-at-origin)))
(def octahedron
"A regular octahedron composed of eight equilateral triangles"
(let [points (vec
(apply concat
(for [a [-1 1]]
[(t/point a 0 0)
(t/point 0 a 0)
(t/point 0 0 a)])))
polygons (vec
(for [a (range (count points))
b (range a)
c (range b)
:when (and
(=approx (t/distance (points a) (points b)) sqrt-2)
(=approx (t/distance (points a) (points c)) sqrt-2)
(=approx (t/distance (points b) (points c)) sqrt-2))]
{:vertices [a b c]}))]
{:points points :polygons polygons }))
(def dodecahedron
"A 12-sided polyhedron with regular pentagonal faces"
{:points (vec
(apply concat
(for [x [-1 1]
y [-1 1]
z [-1 1]]
(t/point x y z))
(for [a [(/ -1 rho) (/ 1 rho)]
b [(- rho) rho]]
(map #(apply t/point %) (take 3 (partition 3 1 (cycle [0 a b])))))))
:polygons [{:vertices [14 8 0 10 2]}
{:vertices [14 8 4 13 6]}
{:vertices [15 9 0 8 4]}
{:vertices [15 9 1 11 5]}
{:vertices [16 10 0 9 1]}
{:vertices [16 10 2 12 3]}
{:vertices [17 11 1 16 3]}
{:vertices [17 11 5 19 7]}
{:vertices [18 12 2 14 6]}
{:vertices [18 12 3 17 7]}
{:vertices [19 13 4 15 5]}
{:vertices [19 13 6 18 7]}]})
(def icosahedron
"A 20-sided polyhedron with triangular faces"
(let [points (vec
(apply concat
(for [x [-1 1]
y [rho -rho]]
[(t/point 0 x y)
(t/point x y 0)
(t/point y 0 x)])))
polygons (vec
(for [a (range (count points))
b (range a)
c (range b)
:when (and
(=approx (t/distance (points a) (points b)) 2)
(=approx (t/distance (points a) (points c)) 2)
(=approx (t/distance (points b) (points c)) 2))]
{:vertices [a b c]}))]
{:points points :polygons polygons }))
|
|
f33a166cf8b1b4fc571844732e244b5c458a1f77e6aa05cae900a710ab578450 | haskell-tools/haskell-tools | Checkers.hs | module Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers
( module X
) where
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ArrowsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.BangPatternsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ConstraintKindsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ConstrainedClassMethodsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.CPPChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.DefaultSignaturesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.DerivingsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ExplicitForAllChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ExplicitNamespacesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.FlexibleInstancesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.FlexibleContextsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.FunctionalDependenciesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.GADTsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.KindSignaturesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.LambdaCaseChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.MagicHashChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.MultiParamTypeClassesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.MultiWayIfChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.OverloadedStringsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ParallelListCompChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.PatternSynonymsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.RecordWildCardsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.RecursiveDoChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TemplateHaskellChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TupleSectionsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TypeFamiliesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TypeOperatorsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TypeSynonymInstancesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.UnboxedTuplesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.UndecidableInstancesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ViewPatternsChecker as X
| null | https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/Language/Haskell/Tools/Refactor/Builtin/ExtensionOrganizer/Checkers.hs | haskell | module Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers
( module X
) where
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ArrowsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.BangPatternsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ConstraintKindsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ConstrainedClassMethodsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.CPPChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.DefaultSignaturesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.DerivingsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ExplicitForAllChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ExplicitNamespacesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.FlexibleInstancesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.FlexibleContextsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.FunctionalDependenciesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.GADTsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.KindSignaturesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.LambdaCaseChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.MagicHashChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.MultiParamTypeClassesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.MultiWayIfChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.OverloadedStringsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ParallelListCompChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.PatternSynonymsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.RecordWildCardsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.RecursiveDoChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TemplateHaskellChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TupleSectionsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TypeFamiliesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TypeOperatorsChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.TypeSynonymInstancesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.UnboxedTuplesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.UndecidableInstancesChecker as X
import Language.Haskell.Tools.Refactor.Builtin.ExtensionOrganizer.Checkers.ViewPatternsChecker as X
|
|
45f113c9b04b9a34a460e6969ae0db11da633ad74c638f2fa0b3876e4f6b70b2 | amnh/PCG | generate-random-sequence.hs | {-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Main where
import Control.Monad
import Data.Alphabet
import Data.Alphabet.IUPAC
import qualified Data.Bimap as BM
import Data.BitVector.LittleEndian
import Data.Bits
import Data.Foldable
import Data.Key
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NE
import Data.Maybe
import Data.Scientific
import Data.String (IsString(fromString))
import Data.Text.Lazy (Text, unlines, unwords)
import qualified Data.Text.Lazy as T
import Data.Text.Lazy.IO (putStrLn, writeFile)
import Data.Validation
import Numeric.Natural
import Options.Applicative
import Prelude hiding (putStrLn, unlines, unwords, writeFile)
import System.Random
import Text.PrettyPrint.ANSI.Leijen (string)
data Specification
= Specification
{ specifiedAlphabet :: Alphabet Text
, specifiedLength :: Natural
, specifiedFASTC :: FilePath
}
deriving stock (Eq, Show)
data UserInput
= UserInput
{ inputAlphabet :: [String]
, inputLength :: Scientific
, inputFASTC :: FilePath
}
deriving stock (Eq, Show)
main :: IO ()
main = do
userInput <- parseUserInput
case toEither $ validateUserInput userInput of
Left errors -> putStrLn . unlines $ toList errors
Right spec -> do
randomSeqence <- generateSequence spec
let fileContent = unlines
[ fromString $ "> " <> show (specifiedLength spec)
, showSequence (specifiedAlphabet spec) randomSeqence
]
writeFile (specifiedFASTC spec) fileContent
parseUserInput :: IO UserInput
parseUserInput = customExecParser preferences $ info (helper <*> userInput) description
where
userInput =
UserInput
<$> argSpec 'a' "alphabet" "List of symbols in the alphabet :: [String]"
<*> argSpec 'l' "length" "Sequence length :: Word"
<*> argStr 'f' "fastc" "FASTC data output file :: FilePath"
argSpec :: Read a => Char -> String -> String -> Parser a
argSpec c s h = option auto $ fold [short c, long s, help h]
argStr :: Char -> String -> String -> Parser String
argStr c s h = strOption $ fold [short c, long s, help h]
description = fold
[ fullDesc
, headerDoc . Just $ string "\n Generate a uniformly random sequence of symbols from the alphabet"
, footerDoc $ Just mempty
]
preferences = prefs $ fold [showHelpOnError, showHelpOnEmpty]
validateUserInput :: UserInput -> Validation (NonEmpty Text) Specification
validateUserInput userInput =
Specification
(fromSymbols . fmap fromString $ inputAlphabet userInput)
<$> validate (pure "length is non-positive") validLength (inputLength userInput)
<*> (pure . inputFASTC) userInput
where
validLength :: Scientific -> Maybe Natural
validLength x =
case res of
Left _ -> Nothing
Right i | i < 1 -> Nothing
Right i -> Just $ fromInteger i
where
res :: Either Double Integer
res = floatingOrInteger x
generateSequence :: Specification -> IO (NonEmpty (NonEmpty Text))
generateSequence spec =
let !a = length alphabet
!n = fromEnum $ specifiedLength spec
!r = (0, 2^a - 2) :: (Integer, Integer)
in NE.fromList <$> replicateM n (buildAmbiguityGroup <$> randomRIO r)
where
alphabet = specifiedAlphabet spec
buildAmbiguityGroup nat = NE.fromList $ go bv0
where
len = length alphabet
bv0 = fromNumber (toEnum len) $ nat + 1
go bv
| isZeroVector bv = []
| otherwise = let i = countLeadingZeros bv
b = bv `clearBit` i
in alphabet ! i : go b
showSequence :: Alphabet Text -> NonEmpty (NonEmpty Text) -> Text
showSequence alphabet xs
| any (\e -> T.length e > 1) shownElems = T.unwords shownElems
| otherwise = fold shownElems
where
shownElems = showSequenceElement alphabet <$> toList xs
showSequenceElement :: Alphabet Text -> NonEmpty Text -> Text
showSequenceElement alphabet element = renderAmbiguity $ toIUPAC element
where
renderAmbiguity amb =
case amb of
x:|[] -> x
x:|xs -> "[ " <> unwords (x:xs) <> " ]"
toIUPAC :: NonEmpty Text -> NonEmpty Text
toIUPAC x
| isAlphabetDna alphabet = fromMaybe x $ x `BM.lookup` BM.twist iupacToDna
| isAlphabetRna alphabet = fromMaybe x $ x `BM.lookup` BM.twist iupacToRna
| isAlphabetAminoAcid alphabet = fromMaybe x $ x `BM.lookup` BM.twist iupacToAminoAcid
| otherwise = x
toFASTA : : Set Text - > BinaryTree ( Vector Int ) Text - > Text
toFASTA alphabet = foldMapWithKey f . buildMap
where
buildMap ( Terminal s i ) = M.singleton i $ renderer s
buildMap ( Branch l r ) = buildMap l < > buildMap r
f k v = fold [ " > " , k , " \n " , v , " \n\n " ]
! renderer = selectSequenceRenderer alphabet
selectSequenceRenderer : : Set Text - > Vector Int - > Text
selectSequenceRenderer inAlphabet
| anyOf specialAlphabetsAre ourAlphabet = T.pack . V.toList . V.backpermute | otherwise = toLazyText . V.foldl ' g where
ourAlphabet = fromSymbols inAlphabet
specialAlphabetsAre =
[ isAlphabetAminoAcid
, isAlphabetDna
, isAlphabetRna
, isAlphabetDiscrete
]
vec = V.fromList . fmap T.head $ toList a i = a < > fromLazyText ( ourAlphabet ! i ) < > " "
anyOf : : Foldable f = > f ( a - > Bool ) - > a - > Bool
anyOf fns v = go $ toList fns
where
go [ ] = False
go ( x : xs ) = let ! b = x v
in b || go xs
toFASTA :: Set Text -> BinaryTree (Vector Int) Text -> Text
toFASTA alphabet = foldMapWithKey f . buildMap
where
buildMap (Terminal s i) = M.singleton i $ renderer s
buildMap (Branch l r) = buildMap l <> buildMap r
f k v = fold [ ">", k, "\n", v, "\n\n" ]
!renderer = selectSequenceRenderer alphabet
selectSequenceRenderer :: Set Text -> Vector Int -> Text
selectSequenceRenderer inAlphabet
| anyOf specialAlphabetsAre ourAlphabet = T.pack . V.toList . V.backpermute vec
| otherwise = toLazyText . V.foldl' g mempty
where
ourAlphabet = fromSymbols inAlphabet
specialAlphabetsAre =
[ isAlphabetAminoAcid
, isAlphabetDna
, isAlphabetRna
, isAlphabetDiscrete
]
vec = V.fromList . fmap T.head $ toList inAlphabet
g a i = a <> fromLazyText (ourAlphabet ! i) <> " "
anyOf :: Foldable f => f (a -> Bool) -> a -> Bool
anyOf fns v = go $ toList fns
where
go [] = False
go (x:xs) = let !b = x v
in b || go xs
-}
| null | https://raw.githubusercontent.com/amnh/PCG/3a1b6bdde273ed4dc09717623986e1144b006904/app/generate-random-sequence.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveTraversable #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Main where
import Control.Monad
import Data.Alphabet
import Data.Alphabet.IUPAC
import qualified Data.Bimap as BM
import Data.BitVector.LittleEndian
import Data.Bits
import Data.Foldable
import Data.Key
import Data.List.NonEmpty (NonEmpty(..))
import qualified Data.List.NonEmpty as NE
import Data.Maybe
import Data.Scientific
import Data.String (IsString(fromString))
import Data.Text.Lazy (Text, unlines, unwords)
import qualified Data.Text.Lazy as T
import Data.Text.Lazy.IO (putStrLn, writeFile)
import Data.Validation
import Numeric.Natural
import Options.Applicative
import Prelude hiding (putStrLn, unlines, unwords, writeFile)
import System.Random
import Text.PrettyPrint.ANSI.Leijen (string)
data Specification
= Specification
{ specifiedAlphabet :: Alphabet Text
, specifiedLength :: Natural
, specifiedFASTC :: FilePath
}
deriving stock (Eq, Show)
data UserInput
= UserInput
{ inputAlphabet :: [String]
, inputLength :: Scientific
, inputFASTC :: FilePath
}
deriving stock (Eq, Show)
main :: IO ()
main = do
userInput <- parseUserInput
case toEither $ validateUserInput userInput of
Left errors -> putStrLn . unlines $ toList errors
Right spec -> do
randomSeqence <- generateSequence spec
let fileContent = unlines
[ fromString $ "> " <> show (specifiedLength spec)
, showSequence (specifiedAlphabet spec) randomSeqence
]
writeFile (specifiedFASTC spec) fileContent
parseUserInput :: IO UserInput
parseUserInput = customExecParser preferences $ info (helper <*> userInput) description
where
userInput =
UserInput
<$> argSpec 'a' "alphabet" "List of symbols in the alphabet :: [String]"
<*> argSpec 'l' "length" "Sequence length :: Word"
<*> argStr 'f' "fastc" "FASTC data output file :: FilePath"
argSpec :: Read a => Char -> String -> String -> Parser a
argSpec c s h = option auto $ fold [short c, long s, help h]
argStr :: Char -> String -> String -> Parser String
argStr c s h = strOption $ fold [short c, long s, help h]
description = fold
[ fullDesc
, headerDoc . Just $ string "\n Generate a uniformly random sequence of symbols from the alphabet"
, footerDoc $ Just mempty
]
preferences = prefs $ fold [showHelpOnError, showHelpOnEmpty]
validateUserInput :: UserInput -> Validation (NonEmpty Text) Specification
validateUserInput userInput =
Specification
(fromSymbols . fmap fromString $ inputAlphabet userInput)
<$> validate (pure "length is non-positive") validLength (inputLength userInput)
<*> (pure . inputFASTC) userInput
where
validLength :: Scientific -> Maybe Natural
validLength x =
case res of
Left _ -> Nothing
Right i | i < 1 -> Nothing
Right i -> Just $ fromInteger i
where
res :: Either Double Integer
res = floatingOrInteger x
generateSequence :: Specification -> IO (NonEmpty (NonEmpty Text))
generateSequence spec =
let !a = length alphabet
!n = fromEnum $ specifiedLength spec
!r = (0, 2^a - 2) :: (Integer, Integer)
in NE.fromList <$> replicateM n (buildAmbiguityGroup <$> randomRIO r)
where
alphabet = specifiedAlphabet spec
buildAmbiguityGroup nat = NE.fromList $ go bv0
where
len = length alphabet
bv0 = fromNumber (toEnum len) $ nat + 1
go bv
| isZeroVector bv = []
| otherwise = let i = countLeadingZeros bv
b = bv `clearBit` i
in alphabet ! i : go b
showSequence :: Alphabet Text -> NonEmpty (NonEmpty Text) -> Text
showSequence alphabet xs
| any (\e -> T.length e > 1) shownElems = T.unwords shownElems
| otherwise = fold shownElems
where
shownElems = showSequenceElement alphabet <$> toList xs
showSequenceElement :: Alphabet Text -> NonEmpty Text -> Text
showSequenceElement alphabet element = renderAmbiguity $ toIUPAC element
where
renderAmbiguity amb =
case amb of
x:|[] -> x
x:|xs -> "[ " <> unwords (x:xs) <> " ]"
toIUPAC :: NonEmpty Text -> NonEmpty Text
toIUPAC x
| isAlphabetDna alphabet = fromMaybe x $ x `BM.lookup` BM.twist iupacToDna
| isAlphabetRna alphabet = fromMaybe x $ x `BM.lookup` BM.twist iupacToRna
| isAlphabetAminoAcid alphabet = fromMaybe x $ x `BM.lookup` BM.twist iupacToAminoAcid
| otherwise = x
toFASTA : : Set Text - > BinaryTree ( Vector Int ) Text - > Text
toFASTA alphabet = foldMapWithKey f . buildMap
where
buildMap ( Terminal s i ) = M.singleton i $ renderer s
buildMap ( Branch l r ) = buildMap l < > buildMap r
f k v = fold [ " > " , k , " \n " , v , " \n\n " ]
! renderer = selectSequenceRenderer alphabet
selectSequenceRenderer : : Set Text - > Vector Int - > Text
selectSequenceRenderer inAlphabet
| anyOf specialAlphabetsAre ourAlphabet = T.pack . V.toList . V.backpermute | otherwise = toLazyText . V.foldl ' g where
ourAlphabet = fromSymbols inAlphabet
specialAlphabetsAre =
[ isAlphabetAminoAcid
, isAlphabetDna
, isAlphabetRna
, isAlphabetDiscrete
]
vec = V.fromList . fmap T.head $ toList a i = a < > fromLazyText ( ourAlphabet ! i ) < > " "
anyOf : : Foldable f = > f ( a - > Bool ) - > a - > Bool
anyOf fns v = go $ toList fns
where
go [ ] = False
go ( x : xs ) = let ! b = x v
in b || go xs
toFASTA :: Set Text -> BinaryTree (Vector Int) Text -> Text
toFASTA alphabet = foldMapWithKey f . buildMap
where
buildMap (Terminal s i) = M.singleton i $ renderer s
buildMap (Branch l r) = buildMap l <> buildMap r
f k v = fold [ ">", k, "\n", v, "\n\n" ]
!renderer = selectSequenceRenderer alphabet
selectSequenceRenderer :: Set Text -> Vector Int -> Text
selectSequenceRenderer inAlphabet
| anyOf specialAlphabetsAre ourAlphabet = T.pack . V.toList . V.backpermute vec
| otherwise = toLazyText . V.foldl' g mempty
where
ourAlphabet = fromSymbols inAlphabet
specialAlphabetsAre =
[ isAlphabetAminoAcid
, isAlphabetDna
, isAlphabetRna
, isAlphabetDiscrete
]
vec = V.fromList . fmap T.head $ toList inAlphabet
g a i = a <> fromLazyText (ourAlphabet ! i) <> " "
anyOf :: Foldable f => f (a -> Bool) -> a -> Bool
anyOf fns v = go $ toList fns
where
go [] = False
go (x:xs) = let !b = x v
in b || go xs
-}
|
b8d182b290d5c645258749613c97b3e8576d87d9c1c66e71001da45fa7240910 | rmascarenhas/foppl | core_test.clj | (ns foppl.core-test
(:require [clojure.test :refer :all]
[foppl.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
| null | https://raw.githubusercontent.com/rmascarenhas/foppl/f3d7013c97652c8b555dae2bd7067e2b0134b030/test/foppl/core_test.clj | clojure | (ns foppl.core-test
(:require [clojure.test :refer :all]
[foppl.core :refer :all]))
(deftest a-test
(testing "FIXME, I fail."
(is (= 0 1))))
|
|
a0e8c87dfdadc8ea51ea9e901a706b3f36202579ecd25703c84d99ca1ee8a70a | imeckler/stationary | stationary.ml | module Html = Html
module Attribute = Attribute
module File = File
module File_system = File_system
module Site = Site
| null | https://raw.githubusercontent.com/imeckler/stationary/d2d6c1c1ec7d6bea63736226a7e511c0e426c5e5/src/stationary.ml | ocaml | module Html = Html
module Attribute = Attribute
module File = File
module File_system = File_system
module Site = Site
|
|
d51763bb3558330a7827eb32e211a23ba388dbb145c5c21968b169f24a933070 | evrim/core-server | http.lisp | (in-package :core-server)
(defvar *dojo-url* "/dojo/dojo.js")
(eval-always
(defclass test-application (http-application)
()))
(unregister core-server::*server* *app*)
(eval-always
(defparameter *app*
(make-instance 'test-application
:fqdn "test"
:admin-email "")))
(register core-server::*server* *app*)
(defun/cc header () (<:div "I'm a header, jo!"))
(defun/cc greeting () (<:div "Greeting, lets do it!"))
(defun/cc footer () (<:div "say, don't make me foot, i'll make you a footer."))
(defun/cc navigation ()
(<:ul
(<:li (<:a :href (action/url ()
(answer :menu1)) "menu1"))
(<:li (<:a :href (action/url ()
(answer :menu2)) "menu2"))))
(defun/cc settings (name)
(<:div "Here is the settings:")
(<:form :action "index.core" :method "GET"
:onsubmit
(js:js*
`(progn
(dojo.io.bind
(create :url ,(function/url ((dekst "dekst") (mekst "mekst"))
(answer dekst))
:mimetype "text/javascript"
:form-node this))
(return false)))
(<:ah "Neym:") (<:input :type "text" :value name :name "dekst")
(<:input :type "submit" :value "kaydit")))
(defun/cc window (&optional (b0dy #'greeting))
(format t "into the window~%")
(prog1
(send/suspend
(<:html
(<:head (<:script :src *dojo-url* :type "text/javascript"))
(<:body
(<:div :class "container"
(header)
(navigation)
(<:div :id "body" :class "wrapper" (funcall b0dy))
(footer)))))
(format t "out to window~%")))
(defun/cc coretal (app &optional (b0dy #'greeting))
(let ((it (window b0dy)))
(format t "window ret:~A~%" it)
(cond
((eq it :menu1)
(format t "Do menu1~%")
(let ((r (window (lambda () (settings "neym")))))
(format t "r:~A" r)
(javascript
(lambda ()
(format t "Javascript~%")
(<:js
`(setf (slot-value ($ "body") 'inner-h-t-m-l) (+ "Result:" ,r)))))))
((eq it :menu2)
(format t "Do menu2~%")
(coretal app (lambda () (<:ah "menu2"))))
(t
(break it)))))
(defurl *app* "index.core" ((command "cmd"))
;; (describe command)
;; (describe *context*)
(loop
(progn
(format t "looping~%")
(coretal *app*))))
(defun/cc get-number ()
(send/suspend
(<:html
;; (<:head (<:script :src *dojo-url* :type "text/javascript"))
(<:body
(<:form :action "number.core" :method "GET"
(<:input :type "hidden" :name "k" :value (function/hash ((number "number"))
(answer (parse-integer number :junk-allowed t))))
(<:input :type "hidden" :name "s" :value (id (session +context+)))
(<:ah "Enter Number:") (<:input :type "text" :name "number")
(<:input :type "submit" :value "Tamam"))))))
(defun/cc print-number (number)
(send/suspend
(<:html
; (<:head (<:script :src *dojo-url* :type "text/javascript"))
(<:body
(<:div
(<:p (<:ah number)))))))
(defun add-numbers (num1 num2)
(print (+ num1 num2)))
(defurl *app* "number.core" ()
(print-number (+ (get-number) (get-number))))
(defun/cc test-fun (acc)
(send/suspend
(<:html
(<:head)
(<:body
(<:a :href (action/url ()
(test-fun (1+ acc))) (<:ah "Acc(action):" acc))
(<:br)
(<:a :href (function/url ()
(test-fun (1+ acc))) (<:ah "Acc(function):" acc))))))
(defurl *app* "gee.core" ()
(test-fun 0))
(defun/cc render-node (name)
(send/suspend
(<:html
(<:body
(dotimes (i 3)
(<:a :href (let ((i i))
(function/url ()
(render-node (format nil "~A.~D" name i))))
(format nil "~A.~D" name i))
(<:br))))))
(defurl *app* "tree.core" ()
(render-node "ahmet"))
(defun/cc render-graph-node (name)
(send/suspend
(<:html
(<:body
(<:p (format nil "~A" name))
(dotimes (i 3)
(<:a :href (let ((i i))
(function/url ()
(render-graph-node (format nil "~A.~D" name i))))
(format nil "~A.~D" name i))
(<:br))
(<:a :href (action/url ()
(ana-sayfa))
"Ana Sayfa")))))
(defun/cc ana-sayfa ()
(<:html
(<:body
(render-graph-node "mehmet"))))
(defurl *app* "graph.core" ()
(ana-sayfa))
(defurl *app* "form.core" ()
(send/suspend
(<:html
(<:head)
(<:body
(<:form :action (action/url ((f1 "f1") (f2 "f2"))
(setf *a (request +context+))
(break (request +context+))
(break (list f1 f2)))
:method "POST" :enctype "multipart/form-data"
(<:input :type "text" :name "f1" :value "f1-value")
(<:input :type "file" :name "f2")
(<:input :type "submit" :value "Gonder Bakalim"))))))
(defurl *app* "gee.core" ()
(labels ((abc ()
(send/suspend
(<:div "eben")
(<:a :href (action/url ()
(abc))
"Continue"))))
(abc)))
(defurl *app* "omed.core" ()
(labels ((gee (a)
(cond
((eq a 1) (gee 2))
(t (<:p (format nil "~D" (+ a (send/suspend
(<:a :href (function/url ()
(answer (+ a 1)))
"Return")))))))))
(gee 1)))
(defurl *app* "demo.core" ()
(labels ((gee (a b)
(describe (list a b))
(cond
((> b a)
(gee a 0))
(t
(gee a
(send/suspend
(<:div "START"
(format nil "~A" a)
(format nil " ~A~%" b))
(<:a :href (action/url ()
(gee 1 2))
"Link1")
(<:a :href (action/url ((var "gee"))
(answer (parse-integer "5")))
"Link2")))))))
(gee 10 0)))
(defurl *app* "demo.core" ()
(labels ((gee (a b)
(cond
((> a b)
(gee 0 b))
(t
(gee (send/suspend
(<:div "START"
(format nil "~A" a)
(format nil " ~A~%" b))
(<:a :href (action/url ()
(gee 1 2))
"Link1")
(<:a :href (action/url ()
(answer 3))
"Link2"))
b)))))
(gee 0 0)))
(defurl *app* "demo.core" ()
(labels ((gee (a b)
(let ((result (send/suspend
(<:div "START"
(format nil "~A" a)
(format nil " ~A~%" b))
(<:a :href (action/url ()
(gee 1 2))
"Link1")
(<:a :href (action/url ()
(answer (cons 3 4)))
"Link2"))))
(gee (car result) (cdr result)))))
(gee nil nil)))
(defurl *app* "crud.core" ()
(let ((result
(send/suspend
(<:h1 "View of First User")
(user/view (car *users*))
(<:h1 "Edit of Second User")
(user/edit (cadr *users*)))))
(send/suspend
(<:h1 "User is:" (format nil "~A" result))
(let ((result (send/suspend
(user/edit (car *users*)
(action/url ((name "NAME") (pass "PASS"))
(answer 'eben name pass))))))
(send/suspend
(<:h1 "test!" (format nil "~A" result))))))) | null | https://raw.githubusercontent.com/evrim/core-server/200ea8151d2f8d81b593d605b183a9cddae1e82d/t/http.lisp | lisp | (describe command)
(describe *context*)
(<:head (<:script :src *dojo-url* :type "text/javascript"))
(<:head (<:script :src *dojo-url* :type "text/javascript")) | (in-package :core-server)
(defvar *dojo-url* "/dojo/dojo.js")
(eval-always
(defclass test-application (http-application)
()))
(unregister core-server::*server* *app*)
(eval-always
(defparameter *app*
(make-instance 'test-application
:fqdn "test"
:admin-email "")))
(register core-server::*server* *app*)
(defun/cc header () (<:div "I'm a header, jo!"))
(defun/cc greeting () (<:div "Greeting, lets do it!"))
(defun/cc footer () (<:div "say, don't make me foot, i'll make you a footer."))
(defun/cc navigation ()
(<:ul
(<:li (<:a :href (action/url ()
(answer :menu1)) "menu1"))
(<:li (<:a :href (action/url ()
(answer :menu2)) "menu2"))))
(defun/cc settings (name)
(<:div "Here is the settings:")
(<:form :action "index.core" :method "GET"
:onsubmit
(js:js*
`(progn
(dojo.io.bind
(create :url ,(function/url ((dekst "dekst") (mekst "mekst"))
(answer dekst))
:mimetype "text/javascript"
:form-node this))
(return false)))
(<:ah "Neym:") (<:input :type "text" :value name :name "dekst")
(<:input :type "submit" :value "kaydit")))
(defun/cc window (&optional (b0dy #'greeting))
(format t "into the window~%")
(prog1
(send/suspend
(<:html
(<:head (<:script :src *dojo-url* :type "text/javascript"))
(<:body
(<:div :class "container"
(header)
(navigation)
(<:div :id "body" :class "wrapper" (funcall b0dy))
(footer)))))
(format t "out to window~%")))
(defun/cc coretal (app &optional (b0dy #'greeting))
(let ((it (window b0dy)))
(format t "window ret:~A~%" it)
(cond
((eq it :menu1)
(format t "Do menu1~%")
(let ((r (window (lambda () (settings "neym")))))
(format t "r:~A" r)
(javascript
(lambda ()
(format t "Javascript~%")
(<:js
`(setf (slot-value ($ "body") 'inner-h-t-m-l) (+ "Result:" ,r)))))))
((eq it :menu2)
(format t "Do menu2~%")
(coretal app (lambda () (<:ah "menu2"))))
(t
(break it)))))
(defurl *app* "index.core" ((command "cmd"))
(loop
(progn
(format t "looping~%")
(coretal *app*))))
(defun/cc get-number ()
(send/suspend
(<:html
(<:body
(<:form :action "number.core" :method "GET"
(<:input :type "hidden" :name "k" :value (function/hash ((number "number"))
(answer (parse-integer number :junk-allowed t))))
(<:input :type "hidden" :name "s" :value (id (session +context+)))
(<:ah "Enter Number:") (<:input :type "text" :name "number")
(<:input :type "submit" :value "Tamam"))))))
(defun/cc print-number (number)
(send/suspend
(<:html
(<:body
(<:div
(<:p (<:ah number)))))))
(defun add-numbers (num1 num2)
(print (+ num1 num2)))
(defurl *app* "number.core" ()
(print-number (+ (get-number) (get-number))))
(defun/cc test-fun (acc)
(send/suspend
(<:html
(<:head)
(<:body
(<:a :href (action/url ()
(test-fun (1+ acc))) (<:ah "Acc(action):" acc))
(<:br)
(<:a :href (function/url ()
(test-fun (1+ acc))) (<:ah "Acc(function):" acc))))))
(defurl *app* "gee.core" ()
(test-fun 0))
(defun/cc render-node (name)
(send/suspend
(<:html
(<:body
(dotimes (i 3)
(<:a :href (let ((i i))
(function/url ()
(render-node (format nil "~A.~D" name i))))
(format nil "~A.~D" name i))
(<:br))))))
(defurl *app* "tree.core" ()
(render-node "ahmet"))
(defun/cc render-graph-node (name)
(send/suspend
(<:html
(<:body
(<:p (format nil "~A" name))
(dotimes (i 3)
(<:a :href (let ((i i))
(function/url ()
(render-graph-node (format nil "~A.~D" name i))))
(format nil "~A.~D" name i))
(<:br))
(<:a :href (action/url ()
(ana-sayfa))
"Ana Sayfa")))))
(defun/cc ana-sayfa ()
(<:html
(<:body
(render-graph-node "mehmet"))))
(defurl *app* "graph.core" ()
(ana-sayfa))
(defurl *app* "form.core" ()
(send/suspend
(<:html
(<:head)
(<:body
(<:form :action (action/url ((f1 "f1") (f2 "f2"))
(setf *a (request +context+))
(break (request +context+))
(break (list f1 f2)))
:method "POST" :enctype "multipart/form-data"
(<:input :type "text" :name "f1" :value "f1-value")
(<:input :type "file" :name "f2")
(<:input :type "submit" :value "Gonder Bakalim"))))))
(defurl *app* "gee.core" ()
(labels ((abc ()
(send/suspend
(<:div "eben")
(<:a :href (action/url ()
(abc))
"Continue"))))
(abc)))
(defurl *app* "omed.core" ()
(labels ((gee (a)
(cond
((eq a 1) (gee 2))
(t (<:p (format nil "~D" (+ a (send/suspend
(<:a :href (function/url ()
(answer (+ a 1)))
"Return")))))))))
(gee 1)))
(defurl *app* "demo.core" ()
(labels ((gee (a b)
(describe (list a b))
(cond
((> b a)
(gee a 0))
(t
(gee a
(send/suspend
(<:div "START"
(format nil "~A" a)
(format nil " ~A~%" b))
(<:a :href (action/url ()
(gee 1 2))
"Link1")
(<:a :href (action/url ((var "gee"))
(answer (parse-integer "5")))
"Link2")))))))
(gee 10 0)))
(defurl *app* "demo.core" ()
(labels ((gee (a b)
(cond
((> a b)
(gee 0 b))
(t
(gee (send/suspend
(<:div "START"
(format nil "~A" a)
(format nil " ~A~%" b))
(<:a :href (action/url ()
(gee 1 2))
"Link1")
(<:a :href (action/url ()
(answer 3))
"Link2"))
b)))))
(gee 0 0)))
(defurl *app* "demo.core" ()
(labels ((gee (a b)
(let ((result (send/suspend
(<:div "START"
(format nil "~A" a)
(format nil " ~A~%" b))
(<:a :href (action/url ()
(gee 1 2))
"Link1")
(<:a :href (action/url ()
(answer (cons 3 4)))
"Link2"))))
(gee (car result) (cdr result)))))
(gee nil nil)))
(defurl *app* "crud.core" ()
(let ((result
(send/suspend
(<:h1 "View of First User")
(user/view (car *users*))
(<:h1 "Edit of Second User")
(user/edit (cadr *users*)))))
(send/suspend
(<:h1 "User is:" (format nil "~A" result))
(let ((result (send/suspend
(user/edit (car *users*)
(action/url ((name "NAME") (pass "PASS"))
(answer 'eben name pass))))))
(send/suspend
(<:h1 "test!" (format nil "~A" result))))))) |
35e6859ff37a3c57cf150704fedd41ebb1fbfc8cd5036c17cc644a0444121131 | xxyzz/SICP | Exercise_3_69.rkt | #lang racket/base
(require racket/stream)
(require racket/list)
(define (interleave s1 s2)
(if (stream-empty? s1)
s2
(stream-cons (stream-first s1)
(interleave s2 (stream-rest s1)))))
(define (pairs s t)
(stream-cons
(list (stream-first s) (stream-first t))
(interleave
(stream-map (lambda (x) (list (stream-first s) x))
(stream-rest t))
(pairs (stream-rest s) (stream-rest t)))))
(define (triples s t u)
(stream-cons
(list (stream-first s) (stream-first t) (stream-first u))
(interleave
(stream-map (lambda (x) (cons (stream-first s) x))
(pairs (stream-rest t) (stream-rest u)))
(triples (stream-rest s) (stream-rest t) (stream-rest u)))))
(define (stream-map proc . argstreams)
(if (stream-empty? (car argstreams))
empty-stream
(stream-cons
(apply proc (map stream-first argstreams))
(apply stream-map
(cons proc (map stream-rest argstreams))))))
(define (add-streams s1 s2) (stream-map + s1 s2))
(define ones (stream-cons 1 ones))
(define integers
(stream-cons 1 (add-streams ones integers)))
(define pythagorean-triples
(stream-filter (lambda (x) (= (+ (expt (first x) 2) (expt (second x) 2))
(expt (third x) 2)))
(triples integers integers integers)))
(stream->list (stream-take pythagorean-triples 3))
' ( ( 3 4 5 ) ( 6 8 10 ) ( 5 12 13 ) )
| null | https://raw.githubusercontent.com/xxyzz/SICP/e26aea1c58fd896297dbf5406f7fcd32bb4f8f78/3_Modularity_Objects_and_State/3.5_Streams/Exercise_3_69.rkt | racket | #lang racket/base
(require racket/stream)
(require racket/list)
(define (interleave s1 s2)
(if (stream-empty? s1)
s2
(stream-cons (stream-first s1)
(interleave s2 (stream-rest s1)))))
(define (pairs s t)
(stream-cons
(list (stream-first s) (stream-first t))
(interleave
(stream-map (lambda (x) (list (stream-first s) x))
(stream-rest t))
(pairs (stream-rest s) (stream-rest t)))))
(define (triples s t u)
(stream-cons
(list (stream-first s) (stream-first t) (stream-first u))
(interleave
(stream-map (lambda (x) (cons (stream-first s) x))
(pairs (stream-rest t) (stream-rest u)))
(triples (stream-rest s) (stream-rest t) (stream-rest u)))))
(define (stream-map proc . argstreams)
(if (stream-empty? (car argstreams))
empty-stream
(stream-cons
(apply proc (map stream-first argstreams))
(apply stream-map
(cons proc (map stream-rest argstreams))))))
(define (add-streams s1 s2) (stream-map + s1 s2))
(define ones (stream-cons 1 ones))
(define integers
(stream-cons 1 (add-streams ones integers)))
(define pythagorean-triples
(stream-filter (lambda (x) (= (+ (expt (first x) 2) (expt (second x) 2))
(expt (third x) 2)))
(triples integers integers integers)))
(stream->list (stream-take pythagorean-triples 3))
' ( ( 3 4 5 ) ( 6 8 10 ) ( 5 12 13 ) )
|
|
387b5bbdfb7cb5b1c48102b5a8e0846f58d1bf6be41806843a699fc0cdc593f4 | B-Lang-org/bsc | IOUtil.hs | # LANGUAGE CPP #
module IOUtil(progArgs, getEnvDef) where
import System.Environment(getArgs,getEnv)
import System.IO.Unsafe
import qualified Control.Exception as CE
# NOINLINE progArgs #
progArgs :: [String]
progArgs = unsafePerformIO $ do
args <- getArgs
bscopts <- getEnvDef "BSC_OPTIONS" ""
return $ (words bscopts) ++ args
getEnvDef :: String -> String -> IO String
getEnvDef e d = CE.catch (getEnv e) handler
where
handler :: CE.SomeException -> IO String
handler _ = return d
| null | https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/comp/Libs/IOUtil.hs | haskell | # LANGUAGE CPP #
module IOUtil(progArgs, getEnvDef) where
import System.Environment(getArgs,getEnv)
import System.IO.Unsafe
import qualified Control.Exception as CE
# NOINLINE progArgs #
progArgs :: [String]
progArgs = unsafePerformIO $ do
args <- getArgs
bscopts <- getEnvDef "BSC_OPTIONS" ""
return $ (words bscopts) ++ args
getEnvDef :: String -> String -> IO String
getEnvDef e d = CE.catch (getEnv e) handler
where
handler :: CE.SomeException -> IO String
handler _ = return d
|
|
738b04926c7b0c20b99f49ea23109042aa6a0195713f456c7c5ad47a8115734f | exoscale/clojure-kubernetes-client | v1_daemon_set_update_strategy.clj | (ns clojure-kubernetes-client.specs.v1-daemon-set-update-strategy
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-rolling-update-daemon-set :refer :all]
)
(:import (java.io File)))
(declare v1-daemon-set-update-strategy-data v1-daemon-set-update-strategy)
(def v1-daemon-set-update-strategy-data
{
(ds/opt :rollingUpdate) v1-rolling-update-daemon-set
(ds/opt :type) string?
})
(def v1-daemon-set-update-strategy
(ds/spec
{:name ::v1-daemon-set-update-strategy
:spec v1-daemon-set-update-strategy-data}))
| null | https://raw.githubusercontent.com/exoscale/clojure-kubernetes-client/79d84417f28d048c5ac015c17e3926c73e6ac668/src/clojure_kubernetes_client/specs/v1_daemon_set_update_strategy.clj | clojure | (ns clojure-kubernetes-client.specs.v1-daemon-set-update-strategy
(:require [clojure.spec.alpha :as s]
[spec-tools.data-spec :as ds]
[clojure-kubernetes-client.specs.v1-rolling-update-daemon-set :refer :all]
)
(:import (java.io File)))
(declare v1-daemon-set-update-strategy-data v1-daemon-set-update-strategy)
(def v1-daemon-set-update-strategy-data
{
(ds/opt :rollingUpdate) v1-rolling-update-daemon-set
(ds/opt :type) string?
})
(def v1-daemon-set-update-strategy
(ds/spec
{:name ::v1-daemon-set-update-strategy
:spec v1-daemon-set-update-strategy-data}))
|
|
e1d76cd1abe17a0268eab8df958b6431fbd410136f301fa29f5fe41a39423334 | masukomi/private_comments | comment-recording.import.scm | ;;;; comment-recording.import.scm - GENERATED BY CHICKEN 5.2.0 -*- Scheme -*-
(##sys#with-environment
(lambda ()
(##sys#register-compiled-module
'comment-recording
'comment-recording
(scheme#list)
'((post-or-delete-comment . comment-recording#post-or-delete-comment)
(prep-comment-info-alist . comment-recording#prep-comment-info-alist))
(scheme#list)
(scheme#list))))
END OF FILE
| null | https://raw.githubusercontent.com/masukomi/private_comments/9261d6a3349b2421e0f7c02790b852ab20d88c20/src/comment-recording.import.scm | scheme | comment-recording.import.scm - GENERATED BY CHICKEN 5.2.0 -*- Scheme -*- |
(##sys#with-environment
(lambda ()
(##sys#register-compiled-module
'comment-recording
'comment-recording
(scheme#list)
'((post-or-delete-comment . comment-recording#post-or-delete-comment)
(prep-comment-info-alist . comment-recording#prep-comment-info-alist))
(scheme#list)
(scheme#list))))
END OF FILE
|
c9478a5c376643d16df3b760cce4cf7274c642d699260db65bbb4bd8fa15e2bd | cryptomeme/nario | BrokenBlock.hs | -- -*- mode: haskell; Encoding: UTF-8 -*-
-- Broken block
module Actor.BrokenBlock (
newBrokenBlock
) where
import Actor (Actor(..))
import Const
import AppUtil (putimg)
import Images
data BrokenBlock = BrokenBlock {
x :: Int,
y :: Int,
vx :: Int,
vy :: Int
}
instance Actor BrokenBlock where
update _ self = (self { x = x self + vx self, y = y self + vy self, vy = vy self + gravity }, [])
render self imgres scrx sur =
putimg sur imgres ImgBroken (x self `div` one - 4 - scrx) (y self `div` one - 4 - 8)
bDead self = y self >= (screenHeight + chrSize * 2) * one
newBrokenBlock :: Int -> Int -> [BrokenBlock]
newBrokenBlock cx cy =
[ BrokenBlock { x = xx + dx1, y = yy + dy1, vx = -vx', vy = vy1 },
BrokenBlock { x = xx + dx2, y = yy + dy1, vx = vx', vy = vy1 },
BrokenBlock { x = xx + dx1, y = yy + dy2, vx = -vx', vy = vy2 },
BrokenBlock { x = xx + dx2, y = yy + dy2, vx = vx', vy = vy2 } ]
where
xx = cx * chrSize * one
yy = cy * chrSize * one
dx1 = 4 * one
dx2 = 12 * one
dy1 = 4 * one
dy2 = 12 * one
vx' = 3 * one `div` 2
vy1 = -8 * one
vy2 = -5 * one
| null | https://raw.githubusercontent.com/cryptomeme/nario/5f1ef10a1530763e1d2f51d280266ba48dae0c26/Actor/BrokenBlock.hs | haskell | -*- mode: haskell; Encoding: UTF-8 -*-
Broken block |
module Actor.BrokenBlock (
newBrokenBlock
) where
import Actor (Actor(..))
import Const
import AppUtil (putimg)
import Images
data BrokenBlock = BrokenBlock {
x :: Int,
y :: Int,
vx :: Int,
vy :: Int
}
instance Actor BrokenBlock where
update _ self = (self { x = x self + vx self, y = y self + vy self, vy = vy self + gravity }, [])
render self imgres scrx sur =
putimg sur imgres ImgBroken (x self `div` one - 4 - scrx) (y self `div` one - 4 - 8)
bDead self = y self >= (screenHeight + chrSize * 2) * one
newBrokenBlock :: Int -> Int -> [BrokenBlock]
newBrokenBlock cx cy =
[ BrokenBlock { x = xx + dx1, y = yy + dy1, vx = -vx', vy = vy1 },
BrokenBlock { x = xx + dx2, y = yy + dy1, vx = vx', vy = vy1 },
BrokenBlock { x = xx + dx1, y = yy + dy2, vx = -vx', vy = vy2 },
BrokenBlock { x = xx + dx2, y = yy + dy2, vx = vx', vy = vy2 } ]
where
xx = cx * chrSize * one
yy = cy * chrSize * one
dx1 = 4 * one
dx2 = 12 * one
dy1 = 4 * one
dy2 = 12 * one
vx' = 3 * one `div` 2
vy1 = -8 * one
vy2 = -5 * one
|
73dfd161c3d4b955c78e054c2c3f21057404064042803609bde4fab6b28fd27b | ucsd-progsys/liquidhaskell | CyclicTypeAlias2.hs | @ LIQUID " --expect - error - containing = Cyclic type alias definition for ` CyclicC ` " @
module CyclicTypeAlias2 () where
@ type CyclicC = [ CyclicC ] @
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/errors/CyclicTypeAlias2.hs | haskell | @ LIQUID " --expect - error - containing = Cyclic type alias definition for ` CyclicC ` " @
module CyclicTypeAlias2 () where
@ type CyclicC = [ CyclicC ] @
|
|
3ab3a36f54953b745b0d2fd5a2a2030a335c41f5dd978f54750b902552730f54 | gator1/jepsen | project.clj | (defproject block-e "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[jepsen "0.1.2"]
[knossos "0.2.8"]])
| null | https://raw.githubusercontent.com/gator1/jepsen/1932cbd72cbc1f6c2a27abe0fe347ea989f0cfbb/block-e/project.clj | clojure | (defproject block-e "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.8.0"]
[jepsen "0.1.2"]
[knossos "0.2.8"]])
|
|
4db5e7b9467cd719e43a5bec2fba681bb1433f78dde6a459920d4e7ec697b770 | ChrisPenner/rasa | RangeSpec.hs | module Rasa.Internal.RangeSpec where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck.Instances ()
import ArbitraryInstances ()
import Rasa.Internal.Range
spec :: Spec
spec = do
describe "overRow" $
prop "overRow f ~= Coord (f a) b" $ \crd@(Coord r c) -> Coord (r+1) c `shouldBe` overRow (+1) crd
describe "overCol" $
prop "overCol f ~= Coord a (f b)" $ \crd@(Coord r c) -> Coord r (c+1) `shouldBe` overCol (+1) crd
describe "overBoth" $
prop "overBoth f ~= Coord (f a) (f b)" $ \crd@(Coord r c) -> Coord (r+1) (c+1) `shouldBe` overBoth (+ (1 :: Int)) crd
| null | https://raw.githubusercontent.com/ChrisPenner/rasa/a2680324849088ee92f063fab091de21c4c2c086/rasa/test/Rasa/Internal/RangeSpec.hs | haskell | module Rasa.Internal.RangeSpec where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck.Instances ()
import ArbitraryInstances ()
import Rasa.Internal.Range
spec :: Spec
spec = do
describe "overRow" $
prop "overRow f ~= Coord (f a) b" $ \crd@(Coord r c) -> Coord (r+1) c `shouldBe` overRow (+1) crd
describe "overCol" $
prop "overCol f ~= Coord a (f b)" $ \crd@(Coord r c) -> Coord r (c+1) `shouldBe` overCol (+1) crd
describe "overBoth" $
prop "overBoth f ~= Coord (f a) (f b)" $ \crd@(Coord r c) -> Coord (r+1) (c+1) `shouldBe` overBoth (+ (1 :: Int)) crd
|
|
bb7f68d2c82befc3878c7831ba5e0f955ac71a81e0cf8effad4b8ba1770ba404 | timbertson/vdoml | event_types_.ml | type response = [
| `Unhandled
| `Handled
| `Stop
]
type 'msg result = {
response : response;
message: 'msg option;
}
| null | https://raw.githubusercontent.com/timbertson/vdoml/fcbf81e89df989206bdad4a92327e593078525b2/src/event_types_.ml | ocaml | type response = [
| `Unhandled
| `Handled
| `Stop
]
type 'msg result = {
response : response;
message: 'msg option;
}
|
|
5b69928806519a1b225923e1b7de50b2a1849b5c2bc320a631f3f96d75eb59c5 | inhabitedtype/ocaml-aws | getDeployablePatchSnapshotForInstance.ml | open Types
open Aws
type input = GetDeployablePatchSnapshotForInstanceRequest.t
type output = GetDeployablePatchSnapshotForInstanceResult.t
type error = Errors_internal.t
let service = "ssm"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-11-06" ]
; "Action", [ "GetDeployablePatchSnapshotForInstance" ]
]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (GetDeployablePatchSnapshotForInstanceRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp = Xml.member "GetDeployablePatchSnapshotForInstanceResponse" (snd xml) in
try
Util.or_error
(Util.option_bind resp GetDeployablePatchSnapshotForInstanceResult.parse)
(let open Error in
BadResponse
{ body
; message =
"Could not find well formed GetDeployablePatchSnapshotForInstanceResult."
})
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing GetDeployablePatchSnapshotForInstanceResult - missing \
field in body or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
| null | https://raw.githubusercontent.com/inhabitedtype/ocaml-aws/3bc554af7ae7ef9e2dcea44a1b72c9e687435fa9/libraries/ssm/lib/getDeployablePatchSnapshotForInstance.ml | ocaml | open Types
open Aws
type input = GetDeployablePatchSnapshotForInstanceRequest.t
type output = GetDeployablePatchSnapshotForInstanceResult.t
type error = Errors_internal.t
let service = "ssm"
let signature_version = Request.V4
let to_http service region req =
let uri =
Uri.add_query_params
(Uri.of_string (Aws.Util.of_option_exn (Endpoints.url_of service region)))
(List.append
[ "Version", [ "2014-11-06" ]
; "Action", [ "GetDeployablePatchSnapshotForInstance" ]
]
(Util.drop_empty
(Uri.query_of_encoded
(Query.render (GetDeployablePatchSnapshotForInstanceRequest.to_query req)))))
in
`POST, uri, []
let of_http body =
try
let xml = Ezxmlm.from_string body in
let resp = Xml.member "GetDeployablePatchSnapshotForInstanceResponse" (snd xml) in
try
Util.or_error
(Util.option_bind resp GetDeployablePatchSnapshotForInstanceResult.parse)
(let open Error in
BadResponse
{ body
; message =
"Could not find well formed GetDeployablePatchSnapshotForInstanceResult."
})
with Xml.RequiredFieldMissing msg ->
let open Error in
`Error
(BadResponse
{ body
; message =
"Error parsing GetDeployablePatchSnapshotForInstanceResult - missing \
field in body or children: "
^ msg
})
with Failure msg ->
`Error
(let open Error in
BadResponse { body; message = "Error parsing xml: " ^ msg })
let parse_error code err =
let errors = [] @ Errors_internal.common in
match Errors_internal.of_string err with
| Some var ->
if List.mem var errors
&&
match Errors_internal.to_http_code var with
| Some var -> var = code
| None -> true
then Some var
else None
| None -> None
|
|
2cd9356b4bacabe5cd045928320b7e1fc63b25a1feefde776b1854b951fadf78 | gregr/ina | effect.scm | ;; See: -effect.html
(load "common.scm")
(define (done datum) (vector 'done datum))
(define (done? v) (eq? 'done (vector-ref v 0)))
(define (done-datum d) (vector-ref d 1))
(define (request details k) (vector 'request details k))
(define (request? v) (eq? 'request (vector-ref v 0)))
(define (request-details r) (vector-ref r 1))
(define (request-k r) (vector-ref r 2))
(define (process-requests c k)
(if (request? c)
(request (request-details c)
(lambda (v) (process-requests ((request-k c) v) k)))
(k (done-datum c))))
(define (e-literal datum) (vector 'lit datum))
(define (e-literal? e) (eq? 'lit (vector-ref e 0)))
(define (e-literal-datum e) (vector-ref e 1))
(define (e-app operator operands) (vector 'app operator operands))
(define (e-app* operator . operands) (e-app operator operands))
(define (e-app? e) (eq? 'app (vector-ref e 0)))
(define (e-app-operator e) (vector-ref e 1))
(define (e-app-operands e) (vector-ref e 2))
(define (e-if c t f) (vector 'if c t f))
(define (e-if? e) (eq? 'if (vector-ref e 0)))
(define (e-if-condition e) (vector-ref e 1))
(define (e-if-true e) (vector-ref e 2))
(define (e-if-false e) (vector-ref e 3))
(define (err e) (request `(error ,e) (lambda (_) (compute-error e))))
(define (compute-error _) err)
(define (compute-literal base)
(lambda (compute)
(lambda (e) (if (e-literal? e) (done (e-literal-datum e)) (base e)))))
(define (compute-app base)
(lambda (compute)
(lambda (e)
(if (e-app? e)
(process-requests
(compute (e-app-operator e))
(lambda (operator)
(let loop ((operands (e-app-operands e)) (args '()))
(if (null? operands)
(operator (reverse args))
(process-requests
(compute (car operands))
(lambda (arg) (loop (cdr operands) (cons arg args))))))))
(base e)))))
(define (compute-if base)
(lambda (compute)
(lambda (e)
(if (e-if? e)
(process-requests
(compute (e-if-condition e))
(lambda (condition)
(process-requests
(compute (if condition (e-if-true e) (e-if-false e)))
done)))
(base e)))))
(define (e-ref name) (vector 'ref name))
(define (e-ref? e) (eq? 'ref (vector-ref e 0)))
(define (e-ref-name e) (vector-ref e 1))
(define (e-lambda p* body) (vector 'lambda p* body))
(define (e-lambda? e) (eq? 'lambda (vector-ref e 0)))
(define (e-lambda-p* e) (vector-ref e 1))
(define (e-lambda-body e) (vector-ref e 2))
(define (req-env-ref name) `(env-ref ,name))
(define (req-env-ref? req)
(and (pair? req) (eq? 'env-ref (car req))
(pair? (cdr req)) (null? (cddr req))))
(define (req-env-ref-name req) (cadr req))
(define req-env-lambda 'env-lambda)
(define (req-env-lambda? req) (eq? 'env-lambda req))
(define (compute-lambda base)
(lambda (compute)
(lambda (e)
(cond
((e-ref? e) (request (req-env-ref (e-ref-name e)) done))
((e-lambda? e)
(request
req-env-lambda
(lambda (cenv)
(done
(lambda (args)
((respond-env (env-extend* cenv (e-lambda-p* e) args))
(compute (e-lambda-body e))))))))
(else (base e))))))
(define (delegate-response c respond)
(request (request-details c) (lambda (v) (respond ((request-k c) v)))))
(define (respond-env env)
(lambda (c)
(cond
((done? c) c)
((req-env-ref? (request-details c))
((respond-env env)
((request-k c)
(env-ref env (env-address
env (req-env-ref-name (request-details c)))))))
((req-env-lambda? (request-details c))
((respond-env env) ((request-k c) env)))
(else (delegate-response c (respond-env env))))))
(define e-get (vector 'get))
(define (e-get? e) (eq? 'get (vector-ref e 0)))
(define (e-put e) (vector 'put e))
(define (e-put? e) (eq? 'put (vector-ref e 0)))
(define (e-put-arg e) (vector-ref e 1))
(define req-state-get 'state-get)
(define (req-state-get? req) (eq? 'state-get req))
(define (req-state-put v) `(state-put ,v))
(define (req-state-put? req) (and (pair? req) (eq? 'state-put (car req))
(pair? (cdr req)) (null? (cddr req))))
(define (req-state-put-value req) (cadr req))
(define (compute-state base)
(lambda (compute)
(lambda (e)
(cond
((e-get? e) (request req-state-get done))
((e-put? e) (process-requests
(compute (e-put-arg e))
(lambda (arg) (request (req-state-put arg) done))))
(else (base e))))))
(define (respond-state state)
(lambda (c)
(cond
((done? c) c)
((req-state-get? (request-details c))
((respond-state state) ((request-k c) state)))
((req-state-put? (request-details c))
(let ((value (req-state-put-value (request-details c))))
((respond-state value) ((request-k c) value))))
(else (delegate-response c (respond-state state))))))
(define (extend-compute c base)
(lambda (compute) ((c (base compute)) compute)))
(define (extend*-compute . cs)
(if (null? cs)
compute-error
(extend-compute (car cs) (apply extend*-compute (cdr cs)))))
(define (fix-compute c)
(letrec ((compute (lambda (e) ((c compute) e)))) compute))
(define e-inc (vector 'inc))
(define (e-inc? e) (eq? 'inc (vector-ref e 0)))
(define (apply-inc args)
(if (and (= 1 (length args)) (number? (car args)))
(done (+ 1 (car args)))
(err `(invalid arguments to inc: ,args))))
(define (compute-inc base)
(lambda (compute)
(lambda (e)
(if (e-inc? e) (done apply-inc) (base e)))))
(define e-equal (vector '=))
(define (e-equal? e) (eq? '= (vector-ref e 0)))
(define (apply-equal args)
(if (= 2 (length args))
(done (apply equal? args))
(err `(invalid arguments to =: ,args))))
(define (compute-equal base)
(lambda (compute)
(lambda (e)
(if (e-equal? e) (done apply-equal) (base e)))))
(define compute
(fix-compute
(extend*-compute
compute-state
compute-lambda
compute-equal
compute-inc
compute-if
compute-app
compute-literal)))
(define (ev e) ((respond-state #f) ((respond-env env-empty) (compute e))))
4
(define tinc (e-app* e-inc (e-app* e-inc (e-literal 2))))
5
(define tif (e-if (e-app* e-equal (e-literal 3) tinc)
(e-literal 10)
(e-app* e-inc tinc)))
5
(define ts (e-if (e-app* e-equal (e-literal 3) (e-put tinc))
(e-put (e-literal 10))
(e-put (e-app* e-inc e-get))))
(define th0 (e-lambda '(x) (e-app* e-inc (e-ref 'x))))
2
(define th1 (e-app*
(e-lambda '(z x) (e-app* (e-ref 'z) (e-ref 'x)))
e-inc (e-literal 1)))
;; TODO: parse : syntax -> expr
| null | https://raw.githubusercontent.com/gregr/ina/5e0a5b7ec44c8c9575b22ce5c394f7a96b766545/nscheme/old/old-experiments/effect.scm | scheme | See: -effect.html
TODO: parse : syntax -> expr | (load "common.scm")
(define (done datum) (vector 'done datum))
(define (done? v) (eq? 'done (vector-ref v 0)))
(define (done-datum d) (vector-ref d 1))
(define (request details k) (vector 'request details k))
(define (request? v) (eq? 'request (vector-ref v 0)))
(define (request-details r) (vector-ref r 1))
(define (request-k r) (vector-ref r 2))
(define (process-requests c k)
(if (request? c)
(request (request-details c)
(lambda (v) (process-requests ((request-k c) v) k)))
(k (done-datum c))))
(define (e-literal datum) (vector 'lit datum))
(define (e-literal? e) (eq? 'lit (vector-ref e 0)))
(define (e-literal-datum e) (vector-ref e 1))
(define (e-app operator operands) (vector 'app operator operands))
(define (e-app* operator . operands) (e-app operator operands))
(define (e-app? e) (eq? 'app (vector-ref e 0)))
(define (e-app-operator e) (vector-ref e 1))
(define (e-app-operands e) (vector-ref e 2))
(define (e-if c t f) (vector 'if c t f))
(define (e-if? e) (eq? 'if (vector-ref e 0)))
(define (e-if-condition e) (vector-ref e 1))
(define (e-if-true e) (vector-ref e 2))
(define (e-if-false e) (vector-ref e 3))
(define (err e) (request `(error ,e) (lambda (_) (compute-error e))))
(define (compute-error _) err)
(define (compute-literal base)
(lambda (compute)
(lambda (e) (if (e-literal? e) (done (e-literal-datum e)) (base e)))))
(define (compute-app base)
(lambda (compute)
(lambda (e)
(if (e-app? e)
(process-requests
(compute (e-app-operator e))
(lambda (operator)
(let loop ((operands (e-app-operands e)) (args '()))
(if (null? operands)
(operator (reverse args))
(process-requests
(compute (car operands))
(lambda (arg) (loop (cdr operands) (cons arg args))))))))
(base e)))))
(define (compute-if base)
(lambda (compute)
(lambda (e)
(if (e-if? e)
(process-requests
(compute (e-if-condition e))
(lambda (condition)
(process-requests
(compute (if condition (e-if-true e) (e-if-false e)))
done)))
(base e)))))
(define (e-ref name) (vector 'ref name))
(define (e-ref? e) (eq? 'ref (vector-ref e 0)))
(define (e-ref-name e) (vector-ref e 1))
(define (e-lambda p* body) (vector 'lambda p* body))
(define (e-lambda? e) (eq? 'lambda (vector-ref e 0)))
(define (e-lambda-p* e) (vector-ref e 1))
(define (e-lambda-body e) (vector-ref e 2))
(define (req-env-ref name) `(env-ref ,name))
(define (req-env-ref? req)
(and (pair? req) (eq? 'env-ref (car req))
(pair? (cdr req)) (null? (cddr req))))
(define (req-env-ref-name req) (cadr req))
(define req-env-lambda 'env-lambda)
(define (req-env-lambda? req) (eq? 'env-lambda req))
(define (compute-lambda base)
(lambda (compute)
(lambda (e)
(cond
((e-ref? e) (request (req-env-ref (e-ref-name e)) done))
((e-lambda? e)
(request
req-env-lambda
(lambda (cenv)
(done
(lambda (args)
((respond-env (env-extend* cenv (e-lambda-p* e) args))
(compute (e-lambda-body e))))))))
(else (base e))))))
(define (delegate-response c respond)
(request (request-details c) (lambda (v) (respond ((request-k c) v)))))
(define (respond-env env)
(lambda (c)
(cond
((done? c) c)
((req-env-ref? (request-details c))
((respond-env env)
((request-k c)
(env-ref env (env-address
env (req-env-ref-name (request-details c)))))))
((req-env-lambda? (request-details c))
((respond-env env) ((request-k c) env)))
(else (delegate-response c (respond-env env))))))
(define e-get (vector 'get))
(define (e-get? e) (eq? 'get (vector-ref e 0)))
(define (e-put e) (vector 'put e))
(define (e-put? e) (eq? 'put (vector-ref e 0)))
(define (e-put-arg e) (vector-ref e 1))
(define req-state-get 'state-get)
(define (req-state-get? req) (eq? 'state-get req))
(define (req-state-put v) `(state-put ,v))
(define (req-state-put? req) (and (pair? req) (eq? 'state-put (car req))
(pair? (cdr req)) (null? (cddr req))))
(define (req-state-put-value req) (cadr req))
(define (compute-state base)
(lambda (compute)
(lambda (e)
(cond
((e-get? e) (request req-state-get done))
((e-put? e) (process-requests
(compute (e-put-arg e))
(lambda (arg) (request (req-state-put arg) done))))
(else (base e))))))
(define (respond-state state)
(lambda (c)
(cond
((done? c) c)
((req-state-get? (request-details c))
((respond-state state) ((request-k c) state)))
((req-state-put? (request-details c))
(let ((value (req-state-put-value (request-details c))))
((respond-state value) ((request-k c) value))))
(else (delegate-response c (respond-state state))))))
(define (extend-compute c base)
(lambda (compute) ((c (base compute)) compute)))
(define (extend*-compute . cs)
(if (null? cs)
compute-error
(extend-compute (car cs) (apply extend*-compute (cdr cs)))))
(define (fix-compute c)
(letrec ((compute (lambda (e) ((c compute) e)))) compute))
(define e-inc (vector 'inc))
(define (e-inc? e) (eq? 'inc (vector-ref e 0)))
(define (apply-inc args)
(if (and (= 1 (length args)) (number? (car args)))
(done (+ 1 (car args)))
(err `(invalid arguments to inc: ,args))))
(define (compute-inc base)
(lambda (compute)
(lambda (e)
(if (e-inc? e) (done apply-inc) (base e)))))
(define e-equal (vector '=))
(define (e-equal? e) (eq? '= (vector-ref e 0)))
(define (apply-equal args)
(if (= 2 (length args))
(done (apply equal? args))
(err `(invalid arguments to =: ,args))))
(define (compute-equal base)
(lambda (compute)
(lambda (e)
(if (e-equal? e) (done apply-equal) (base e)))))
(define compute
(fix-compute
(extend*-compute
compute-state
compute-lambda
compute-equal
compute-inc
compute-if
compute-app
compute-literal)))
(define (ev e) ((respond-state #f) ((respond-env env-empty) (compute e))))
4
(define tinc (e-app* e-inc (e-app* e-inc (e-literal 2))))
5
(define tif (e-if (e-app* e-equal (e-literal 3) tinc)
(e-literal 10)
(e-app* e-inc tinc)))
5
(define ts (e-if (e-app* e-equal (e-literal 3) (e-put tinc))
(e-put (e-literal 10))
(e-put (e-app* e-inc e-get))))
(define th0 (e-lambda '(x) (e-app* e-inc (e-ref 'x))))
2
(define th1 (e-app*
(e-lambda '(z x) (e-app* (e-ref 'z) (e-ref 'x)))
e-inc (e-literal 1)))
|
fa8553ee1ea9fb1775c15d59c4d7711f9014613ab7fbf159de614908c3cc34d8 | GaloisInc/jvm-verifier | MergeFrame.hs | |
Module : Verifier . Java . MergeFrame
Description : operators for manipulating merge frames in the simulator
License : BSD3
Stability : stable
Point - of - contact : acfoltzer
Module : Verifier.Java.MergeFrame
Description : operators for manipulating merge frames in the simulator
License : BSD3
Stability : stable
Point-of-contact : acfoltzer
-}
# LANGUAGE TupleSections #
# LANGUAGE CPP #
module Verifier.Java.MergeFrame where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Monad.Error
import Control.Lens hiding (Path)
import Verifier.Java.Common
pushMF :: MergeFrame sym -> Simulator sym ()
pushMF mf = ctrlStk.mergeFrames %= (mf :)
popMF :: String -> Simulator sym (MergeFrame sym)
popMF ctx = do
stk <- use (ctrlStk.mergeFrames)
case stk of
[] -> fail $ ctx ++ ": empty CtrlStk"
(mf:mfs) -> ctrlStk.mergeFrames .= mfs >> return mf
peekMF :: String -> Simulator sym (MergeFrame sym)
peekMF ctx = SM $ try =<< use (ctrlStk.mergeFrames)
where try = tryHead $ ctx ++ ": empty CtrlStk"
{-# DEPRECATED bottomMF "is there ever a good use of this?" #-}
bottomMF :: Simulator sym (Maybe (MergeFrame sym))
bottomMF = SM $ uses (ctrlStk.mergeFrames) lastMay
modifyMF :: String
-> (MergeFrame sym -> MergeFrame sym)
-> Simulator sym ()
modifyMF ctx f = pushMF . f =<< popMF ctx
withTopMF :: String -> (MergeFrame sym -> a) -> Simulator sym a
withTopMF ctx f = f <$> peekMF ctx
-- | Run a computation with the top 'MergeFrame'. If 'fst' of the
result is ' Just mf ' , then ' mf ' will be pushed back on the ' CtrlStk '
-- after running.
withPoppedMF :: String
-> (MergeFrame sym -> Simulator sym (Maybe (MergeFrame sym), a))
-> Simulator sym a
withPoppedMF ctx f = do
(mmf', a) <- f =<< popMF ctx
case mmf' of
Just mf' -> pushMF mf'
_ -> return ()
return a
pushPending :: String -> SymPath sym -> Simulator sym ()
pushPending ctx p = modifyMF ctx $ \mf -> mf & pending %~ (p :)
popPending :: String -> Simulator sym (SymPath sym)
popPending ctx = withPoppedMF ctx $ \mf ->
case mf^.pending of
[] -> fail $ ctx ++ ": no pending paths"
(p:ps) -> return (Just $ mf & pending .~ ps, p)
peekPending :: String -> Simulator sym (SymPath sym)
peekPending ctx = do
mf <- popMF ctx
SM . try $ mf^.pending
where try = tryHead $ ctx ++ ": no pending paths"
modifyPending :: String
-> (SymPath sym -> SymPath sym)
-> Simulator sym ()
modifyPending ctx f = pushPending ctx . f =<< popPending ctx
-- | Run a computation with the top 'SymPath' If 'fst' of the
-- result is 'Just p', then 'p' will be pushed back on the top 'MergeFrame'
-- after running.
withPoppedPending :: String
-> (SymPath sym -> Simulator sym (Maybe (SymPath sym), a))
-> Simulator sym a
withPoppedPending ctx f = do
(mp', a) <- f =<< popPending ctx
case mp' of
Just p' -> pushPending ctx p'
_ -> return ()
return a
withPoppedPending_ :: String
-> (SymPath sym -> Simulator sym (Maybe (SymPath sym)))
-> Simulator sym ()
withPoppedPending_ ctx f = withPoppedPending ctx (\p -> (,()) <$> f p)
hasPending :: Simulator sym Bool
hasPending = (popPending "" >>= pushPending "" >> return True)
`catchError`
const (return False)
--------------------------------------------------------------------------------
Utilities
tryHead :: (Monad m, Error e) => String -> [a] -> ErrorT e m a
tryHead msg [] = fail msg
tryHead _ (x:_) = return x
lastMay [] = Nothing
lastMay xs = Just (last xs)
| null | https://raw.githubusercontent.com/GaloisInc/jvm-verifier/3905dda18d0bdd5c595eef49804780f4a48c22f5/src/Verifier/Java/MergeFrame.hs | haskell | # DEPRECATED bottomMF "is there ever a good use of this?" #
| Run a computation with the top 'MergeFrame'. If 'fst' of the
after running.
| Run a computation with the top 'SymPath' If 'fst' of the
result is 'Just p', then 'p' will be pushed back on the top 'MergeFrame'
after running.
------------------------------------------------------------------------------ | |
Module : Verifier . Java . MergeFrame
Description : operators for manipulating merge frames in the simulator
License : BSD3
Stability : stable
Point - of - contact : acfoltzer
Module : Verifier.Java.MergeFrame
Description : operators for manipulating merge frames in the simulator
License : BSD3
Stability : stable
Point-of-contact : acfoltzer
-}
# LANGUAGE TupleSections #
# LANGUAGE CPP #
module Verifier.Java.MergeFrame where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Control.Monad.Error
import Control.Lens hiding (Path)
import Verifier.Java.Common
pushMF :: MergeFrame sym -> Simulator sym ()
pushMF mf = ctrlStk.mergeFrames %= (mf :)
popMF :: String -> Simulator sym (MergeFrame sym)
popMF ctx = do
stk <- use (ctrlStk.mergeFrames)
case stk of
[] -> fail $ ctx ++ ": empty CtrlStk"
(mf:mfs) -> ctrlStk.mergeFrames .= mfs >> return mf
peekMF :: String -> Simulator sym (MergeFrame sym)
peekMF ctx = SM $ try =<< use (ctrlStk.mergeFrames)
where try = tryHead $ ctx ++ ": empty CtrlStk"
bottomMF :: Simulator sym (Maybe (MergeFrame sym))
bottomMF = SM $ uses (ctrlStk.mergeFrames) lastMay
modifyMF :: String
-> (MergeFrame sym -> MergeFrame sym)
-> Simulator sym ()
modifyMF ctx f = pushMF . f =<< popMF ctx
withTopMF :: String -> (MergeFrame sym -> a) -> Simulator sym a
withTopMF ctx f = f <$> peekMF ctx
result is ' Just mf ' , then ' mf ' will be pushed back on the ' CtrlStk '
withPoppedMF :: String
-> (MergeFrame sym -> Simulator sym (Maybe (MergeFrame sym), a))
-> Simulator sym a
withPoppedMF ctx f = do
(mmf', a) <- f =<< popMF ctx
case mmf' of
Just mf' -> pushMF mf'
_ -> return ()
return a
pushPending :: String -> SymPath sym -> Simulator sym ()
pushPending ctx p = modifyMF ctx $ \mf -> mf & pending %~ (p :)
popPending :: String -> Simulator sym (SymPath sym)
popPending ctx = withPoppedMF ctx $ \mf ->
case mf^.pending of
[] -> fail $ ctx ++ ": no pending paths"
(p:ps) -> return (Just $ mf & pending .~ ps, p)
peekPending :: String -> Simulator sym (SymPath sym)
peekPending ctx = do
mf <- popMF ctx
SM . try $ mf^.pending
where try = tryHead $ ctx ++ ": no pending paths"
modifyPending :: String
-> (SymPath sym -> SymPath sym)
-> Simulator sym ()
modifyPending ctx f = pushPending ctx . f =<< popPending ctx
withPoppedPending :: String
-> (SymPath sym -> Simulator sym (Maybe (SymPath sym), a))
-> Simulator sym a
withPoppedPending ctx f = do
(mp', a) <- f =<< popPending ctx
case mp' of
Just p' -> pushPending ctx p'
_ -> return ()
return a
withPoppedPending_ :: String
-> (SymPath sym -> Simulator sym (Maybe (SymPath sym)))
-> Simulator sym ()
withPoppedPending_ ctx f = withPoppedPending ctx (\p -> (,()) <$> f p)
hasPending :: Simulator sym Bool
hasPending = (popPending "" >>= pushPending "" >> return True)
`catchError`
const (return False)
Utilities
tryHead :: (Monad m, Error e) => String -> [a] -> ErrorT e m a
tryHead msg [] = fail msg
tryHead _ (x:_) = return x
lastMay [] = Nothing
lastMay xs = Just (last xs)
|
153eaa1d8277acaa18d9e7b8a022552e87bd2c204c536b672e2d4e43af616490 | janegca/htdp2e | Exercise-047-TrafficLight.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname Exercise-047-TrafficLight) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")))))
Exercise 47 .
; Design an interactive program that simulates a traffic light for a given
; duration. The program renders the state of a traffic light as a solid circle
; of the appropriate color, and it changes state on every clock tick.
; What is the most appropriate initial state? Ask your engineering friends.
; -- Physical Constants
(define RADIUS 10)
(define BG-WIDTH (* 3 RADIUS))
; -- Graphical Constants
(define BACKGROUND (empty-scene BG-WIDTH BG-WIDTH "black"))
; -- Functions
TrafficLight - >
; Determines the next state of the traffic light from the given s
(check-expect (traffic-light-next "red") "green")
(check-expect (traffic-light-next "green") "yellow") ; added check
(check-expect (traffic-light-next "yellow") "red") ; added check
(define (traffic-light-next s)
(cond
[(string=? "red" s) "green"]
[(string=? "green" s) "yellow"]
[(string=? "yellow" s) "red"]))
; WorldState -> Image
; redraws the traffic light using the colour given by cs
(check-expect
(render "red")
(overlay/align "center" "center" (circle RADIUS "solid" "red") BACKGROUND))
(check-expect
(render "green")
(overlay/align "center" "center" (circle RADIUS "solid" "green") BACKGROUND))
(check-expect
(render "yellow")
(overlay/align "center" "center" (circle RADIUS "solid" "yellow") BACKGROUND))
(define (render cs)
(overlay/align "center" "center" (circle RADIUS "solid" cs) BACKGROUND))
; WorldState -> WorldState
; changes the colour of the traffic light on every clock tick
(define (tock cs)
(traffic-light-next cs))
; -- Main function
TrafficLight is a String that determines the colour of the
; rendered traffic light
(define (traffic-light cs)
(big-bang cs
[on-tick tock]
[to-draw render]))
; usage example
(traffic-light "red") | null | https://raw.githubusercontent.com/janegca/htdp2e/2d50378135edc2b8b1816204021f8763f8b2707b/01-FixedSizeData/Exercise-047-TrafficLight.rkt | racket | about the language level of this file in a form that our tools can easily process.
Design an interactive program that simulates a traffic light for a given
duration. The program renders the state of a traffic light as a solid circle
of the appropriate color, and it changes state on every clock tick.
What is the most appropriate initial state? Ask your engineering friends.
-- Physical Constants
-- Graphical Constants
-- Functions
Determines the next state of the traffic light from the given s
added check
added check
WorldState -> Image
redraws the traffic light using the colour given by cs
WorldState -> WorldState
changes the colour of the traffic light on every clock tick
-- Main function
rendered traffic light
usage example | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname Exercise-047-TrafficLight) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")))))
Exercise 47 .
(define RADIUS 10)
(define BG-WIDTH (* 3 RADIUS))
(define BACKGROUND (empty-scene BG-WIDTH BG-WIDTH "black"))
TrafficLight - >
(check-expect (traffic-light-next "red") "green")
(define (traffic-light-next s)
(cond
[(string=? "red" s) "green"]
[(string=? "green" s) "yellow"]
[(string=? "yellow" s) "red"]))
(check-expect
(render "red")
(overlay/align "center" "center" (circle RADIUS "solid" "red") BACKGROUND))
(check-expect
(render "green")
(overlay/align "center" "center" (circle RADIUS "solid" "green") BACKGROUND))
(check-expect
(render "yellow")
(overlay/align "center" "center" (circle RADIUS "solid" "yellow") BACKGROUND))
(define (render cs)
(overlay/align "center" "center" (circle RADIUS "solid" cs) BACKGROUND))
(define (tock cs)
(traffic-light-next cs))
TrafficLight is a String that determines the colour of the
(define (traffic-light cs)
(big-bang cs
[on-tick tock]
[to-draw render]))
(traffic-light "red") |
2907879712c17a1b8b2a55b4392b4366b36a504f2b9bf5186fb4ee69e39c0ef7 | simonmar/monad-par | issue_forkOmega.hs |
import Control . Monad . IO.Class
import Control . . Par . IO
import Control . . Par . Class
import Control . . Par . . Trace
import Control.Monad.Par.Scheds.Direct
import System.IO.Unsafe(unsafePerformIO)
import System.IO
foo :: Par Int
foo = do fork $ loop 0
return 3
loop :: Integer -> Par ()
loop n = do case unsafePerformIO (dot n) of
() -> return ()
loop (n+1)
dot :: Integer -> IO ()
dot n | n `mod` 10000 == 0 =
do putStr "."
hFlush stdout
dot _ = return ()
main :: IO ()
main = do
putStrLn "Launching runPar:"
x <- runParIO foo
putStrLn "Returned from runPar:"
print x
| null | https://raw.githubusercontent.com/simonmar/monad-par/1266b0ac1b4040963ab356cf032c6aae6b8a7add/tests/issue_forkOmega.hs | haskell |
import Control . Monad . IO.Class
import Control . . Par . IO
import Control . . Par . Class
import Control . . Par . . Trace
import Control.Monad.Par.Scheds.Direct
import System.IO.Unsafe(unsafePerformIO)
import System.IO
foo :: Par Int
foo = do fork $ loop 0
return 3
loop :: Integer -> Par ()
loop n = do case unsafePerformIO (dot n) of
() -> return ()
loop (n+1)
dot :: Integer -> IO ()
dot n | n `mod` 10000 == 0 =
do putStr "."
hFlush stdout
dot _ = return ()
main :: IO ()
main = do
putStrLn "Launching runPar:"
x <- runParIO foo
putStrLn "Returned from runPar:"
print x
|
|
e1382dbaa512d3668e65b844f65aff618617f4c97ecfbfc918543ce078e559a9 | moby/vpnkit | hosts.mli | val default_etc_hosts_path: string
(** Default path where /etc/hosts should be on this machine *)
val etc_hosts: (string * Ipaddr.t) list ref
(** The current contents of the hosts file *)
val of_string: string -> (string * Ipaddr.t) list
* the contents of a hosts file
module Make(Files: Sig.FILES): sig
type watch
val watch: ?path:string -> unit -> (watch, [ `Msg of string ]) result Lwt.t
(** Start watching the hosts file, updating the [etc_hosts] binding in the
background. The [?path] argument allows the location of the hosts file
to be overriden. This blocks until the watch has been established. *)
val unwatch: watch -> unit Lwt.t
(** Stop watching the hosts file *)
end
| null | https://raw.githubusercontent.com/moby/vpnkit/6039eac025e0740e530f2ff11f57d6d990d1c4a1/src/hostnet/hosts.mli | ocaml | * Default path where /etc/hosts should be on this machine
* The current contents of the hosts file
* Start watching the hosts file, updating the [etc_hosts] binding in the
background. The [?path] argument allows the location of the hosts file
to be overriden. This blocks until the watch has been established.
* Stop watching the hosts file | val default_etc_hosts_path: string
val etc_hosts: (string * Ipaddr.t) list ref
val of_string: string -> (string * Ipaddr.t) list
* the contents of a hosts file
module Make(Files: Sig.FILES): sig
type watch
val watch: ?path:string -> unit -> (watch, [ `Msg of string ]) result Lwt.t
val unwatch: watch -> unit Lwt.t
end
|
390eeb9895c1ba495e3b6c4cfac627fbd07ccb16c6fb8a799ce101663e2c416b | qkrgud55/ocamlmulti | mtype.mli | (***********************************************************************)
(* *)
(* 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 Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : mtype.mli 11156 2011 - 07 - 27 14:17:02Z doligez $
(* Operations on module types *)
open Types
val scrape: Env.t -> module_type -> module_type
(* Expand toplevel module type abbreviations
till hitting a "hard" module type (signature, functor,
or abstract module type ident. *)
val freshen: module_type -> module_type
(* Return an alpha-equivalent copy of the given module type
where bound identifiers are fresh. *)
val strengthen: Env.t -> module_type -> Path.t -> module_type
(* Strengthen abstract type components relative to the
given path. *)
val nondep_supertype: Env.t -> Ident.t -> module_type -> module_type
(* Return the smallest supertype of the given type
in which the given ident does not appear.
Raise [Not_found] if no such type exists. *)
val no_code_needed: Env.t -> module_type -> bool
val no_code_needed_sig: Env.t -> signature -> bool
(* Determine whether a module needs no implementation code,
i.e. consists only of type definitions. *)
val enrich_modtype: Env.t -> Path.t -> module_type -> module_type
val enrich_typedecl: Env.t -> Path.t -> type_declaration -> type_declaration
val type_paths: Env.t -> Path.t -> module_type -> Path.t list
| null | https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/typing/mtype.mli | ocaml | *********************************************************************
OCaml
*********************************************************************
Operations on module types
Expand toplevel module type abbreviations
till hitting a "hard" module type (signature, functor,
or abstract module type ident.
Return an alpha-equivalent copy of the given module type
where bound identifiers are fresh.
Strengthen abstract type components relative to the
given path.
Return the smallest supertype of the given type
in which the given ident does not appear.
Raise [Not_found] if no such type exists.
Determine whether a module needs no implementation code,
i.e. consists only of type definitions. | , 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 Q Public License version 1.0 .
$ I d : mtype.mli 11156 2011 - 07 - 27 14:17:02Z doligez $
open Types
val scrape: Env.t -> module_type -> module_type
val freshen: module_type -> module_type
val strengthen: Env.t -> module_type -> Path.t -> module_type
val nondep_supertype: Env.t -> Ident.t -> module_type -> module_type
val no_code_needed: Env.t -> module_type -> bool
val no_code_needed_sig: Env.t -> signature -> bool
val enrich_modtype: Env.t -> Path.t -> module_type -> module_type
val enrich_typedecl: Env.t -> Path.t -> type_declaration -> type_declaration
val type_paths: Env.t -> Path.t -> module_type -> Path.t list
|
25c60b971e554f831157e5c3eb1b8a92ad53dc71e7c7f5ded7db5af6c5058dad | b0-system/b0 | b00_pdf_viewer.mli | ---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
(** PDF viewer interaction. *)
open B0_std
* { 1 : env Environment variables }
(** Environment variables. *)
module Env : sig
val pdfviewer : string
* [ pdfviewer ] is [ PDFVIEWER ] .
end
* { 1 : show_pdfs Show PDFs }
type t
(** The type for specifying a PDF viewer. *)
val find :
?search:Fpath.t list -> pdf_viewer:Cmd.t option -> unit ->
(t option, string) result
* [ find ~search ~pdf_viewer ] tries to find a PDF viewer in a
platform dependent way .
platform dependent way. *)
val show : t option -> Fpath.t -> (unit, string) result
* [ show pdf_viewer file ] shows PDF file using the viewer
[ pdf_viewer ] ( if [ None ] an error message is returned mentioning no
viewer was found ) .
[pdf_viewer] (if [None] an error message is returned mentioning no
viewer was found). *)
* { 1 : cli Cli interaction }
val pdf_viewer :
?docs:string -> ?opts:string list -> unit -> Cmd.t option Cmdliner.Term.t
* [ pdf_viewer ~docs ~opts ( ) ] is an option and [ PDFVIEWER ]
environment variable to use with [ pdf_viewer ] argument of
{ ! find } . [ opts ] are the cli options and default to
[ " pdf - viewer " ] . [ docs ] is the documentation section where the
option gets documented .
environment variable to use with [pdf_viewer] argument of
{!find}. [opts] are the cli options and default to
["pdf-viewer"]. [docs] is the documentation section where the
option gets documented. *)
---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers
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
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 .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers
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.
---------------------------------------------------------------------------*)
| null | https://raw.githubusercontent.com/b0-system/b0/cbe12b8a55da6b50ab01ed058b339dbed3cfe894/src/b00/kit/b00_pdf_viewer.mli | ocaml | * PDF viewer interaction.
* Environment variables.
* The type for specifying a PDF viewer. | ---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers . All rights reserved .
Distributed under the ISC license , see terms at the end of the file .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers. All rights reserved.
Distributed under the ISC license, see terms at the end of the file.
---------------------------------------------------------------------------*)
open B0_std
* { 1 : env Environment variables }
module Env : sig
val pdfviewer : string
* [ pdfviewer ] is [ PDFVIEWER ] .
end
* { 1 : show_pdfs Show PDFs }
type t
val find :
?search:Fpath.t list -> pdf_viewer:Cmd.t option -> unit ->
(t option, string) result
* [ find ~search ~pdf_viewer ] tries to find a PDF viewer in a
platform dependent way .
platform dependent way. *)
val show : t option -> Fpath.t -> (unit, string) result
* [ show pdf_viewer file ] shows PDF file using the viewer
[ pdf_viewer ] ( if [ None ] an error message is returned mentioning no
viewer was found ) .
[pdf_viewer] (if [None] an error message is returned mentioning no
viewer was found). *)
* { 1 : cli Cli interaction }
val pdf_viewer :
?docs:string -> ?opts:string list -> unit -> Cmd.t option Cmdliner.Term.t
* [ pdf_viewer ~docs ~opts ( ) ] is an option and [ PDFVIEWER ]
environment variable to use with [ pdf_viewer ] argument of
{ ! find } . [ opts ] are the cli options and default to
[ " pdf - viewer " ] . [ docs ] is the documentation section where the
option gets documented .
environment variable to use with [pdf_viewer] argument of
{!find}. [opts] are the cli options and default to
["pdf-viewer"]. [docs] is the documentation section where the
option gets documented. *)
---------------------------------------------------------------------------
Copyright ( c ) 2018 The b0 programmers
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
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 .
---------------------------------------------------------------------------
Copyright (c) 2018 The b0 programmers
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.
---------------------------------------------------------------------------*)
|
df9a70a6c1889543ca863b4827076efefd0d49b47bac505b8996b4b3ddf28848 | samee/netlist | DemoCircuits.hs | Used only by Benchmark . Demo
module Benchmark.DemoCircuits where
import Control.Monad
import Data.List
import Debug.Trace
import Circuit.Sorter
import Circuit.NetList
import qualified Circuit.Queue as Nq
import qualified Circuit.Stack as Ns
import Util
TODO move this to NetList.hs if it is useful
type NetCondMod a = NetBool -> a -> NetWriter a
betterMaybe :: NetCondMod a -> (b -> NetCondMod a)
-> NetMaybe b -> NetCondMod a
betterMaybe nothCase justCase mb en piped
| knownNothing mb = nothCase en piped
| otherwise = do
(jen,nen) <- decoderUnit en =<< netIsNothing mb
justCase (netFromJust mb) jen =<< nothCase nen piped
-- Given a set of points on the circumference of a circle,
-- find the widest angle made by them at the center. All angles are
-- scaled by a factor of maxTheta/(2*pi) to avoid use of floating point
Assumes n > = 2 , and that theta is sorted in ascending order
Implements the following code , in circuit ( why is this still so painful ! )
result = 0
j = 0
i = 1
while(i < n )
{
result = max result ( f theta[i ] theta[j ] )
if ( ( j < i ) & & ( f theta[i ] theta[j ] < = modDiff ] theta[j+1 ] ) )
j++
else
i++
}
Mapping : theta[j+1 .. i ] - > inRange ( Queue , possibly empty )
theta[i .. n-1 ] - > unseen ( Stack , possibly empty )
theta[j ] - > curj
Implements the following code, in circuit (why is this still so painful!)
result = 0
j = 0
i = 1
while(i<n)
{
result = max result (f theta[i] theta[j])
if ((j<i) && (f theta[i] theta[j] <= modDiff maxTheta theta[i] theta[j+1]))
j++
else
i++
}
Mapping: theta[j+1..i] -> inRange (Queue, possibly empty)
theta[i..n-1] -> unseen (Stack, possibly empty)
theta[j] -> curj
-}
wideAngle :: [NetUInt] -> NetUInt -> NetWriter NetUInt
wideAngle theta maxTheta = if n <= 1
then return $ constInt 0
else do
let inRange = Nq.fromList [theta!!1]
unseen = Ns.fromList $ tail theta
curj = theta!!0
(result,_,_,_) <- foldM (\loopVars@(_,_,unseen,_) _ -> do
mb <- Ns.top unseen
betterMaybe
(const return)
(\curi en (result,inRange,unseen,curj) -> do
curSep <- modDiff maxTheta curj curi
updres <- netAnd en =<< curSep `greaterThan` result
result <- mux updres result curSep
mb <- Nq.front inRange
(incI,(inRange,curj)) <- betterMaybe
(\en (incI,lv) -> do
incI <- netOr incI en
return (incI,lv))
(\nxtj en (incI,(inRange,curj)) -> do
nxtSep <- modDiff maxTheta nxtj curi
wider <- netNot =<< greaterThan curSep nxtSep
incJ <- netAnd en wider
incI <- netOr incI =<< netXor en incJ
curj <- mux incJ curj nxtj
inRange <- Nq.condPop incJ inRange
return (incI,(inRange,curj)))
mb en (netFalse,(inRange,curj))
unseen <- Ns.condPop incI unseen
mb <- Ns.top unseen
inRange <- betterMaybe
(const return)
(\nxti en inRange -> Nq.condPush en nxti inRange)
mb incI inRange
return (result,inRange,unseen,curj))
mb netTrue loopVars)
(constIntW (intWidth maxTheta) 0,inRange,unseen,curj) [0..2*n-1]
return result
where
n = length theta
-- modDiff m a b assumes a <= b < maxtheta
modDiff m a b = do
x <- sub b a
y <- sub m x
netMin x y
foldMWithBreak :: Monad m => (a -> b -> m (Maybe a)) -> a -> [b] -> m a
foldMWithBreak f init [] = return init
foldMWithBreak f init (h:t) = do mb <- f init h
case mb of Nothing -> return init
Just x -> foldMWithBreak f x t
-- Naive O(n^2) comparison
More readable versions of this function was overflowing the stack FIXME
wideAngleNaive :: [NetUInt] -> NetUInt -> NetWriter NetUInt
wideAngleNaive theta maxTheta = foldM (\res (h:ts) ->
foldM (\res t -> netMax res =<< modDiff maxTheta h t) res ts
) (constInt 0) (init $ tails theta)
shiftLeft amt x = bitConcat [ x,(constIntW amt 0 ) ]
multiply :: NetUInt -> NetUInt -> NetWriter NetUInt
multiply a b = aux =<< bitify b where
addop bt = mux bt (constInt 0) a
-- = Gc.bitwiseAnd a =<< Gc.sextend awidth (bitToInt bt)
-- awidth = bitWidth a
aux b = if bwidth == 1 then addop =<< lsb b
else do (bt,b') <- splitLsb b
s <- shiftLeft 1 =<< aux b'
add s =<< addop bt
where bwidth = bitWidth b
aux b = if bwidth = = 1 then addop = < < lsb b -- ( intToBit b )
else do ( bt , b ' ) < - splitMsb b
s < - leadz = < < multiply a b '
addU s = < < shiftLeft ( bwidth-1 ) = < < addop bt
where bwidth = bitWidth b
leadz x = zextend ( bitWidth x + 1 ) x
aux b = if bwidth == 1 then addop =<< lsb b -- (intToBit b)
else do (bt,b') <- splitMsb b
s <- leadz =<< multiply a b'
addU s =<< shiftLeft (bwidth-1) =<< addop bt
where bwidth = bitWidth b
leadz x = zextend (bitWidth x + 1) x
-}
TODO stack needs condModifyTop
{-
Stack of (height,startx) pair
Add zeroes to both sides
if top shorterThan current, push (current.x,current.h), i++
if top sameHeightAs current, i++
if top tallerThan current, updateWith (current.x-top.x)*top.h, pop
-}
rectangleInHistogram :: [NetUInt] -> NetWriter NetUInt
rectangleInHistogram heights = do
(best,_,_,_) <- foldMWithBreak (\(best,heightsLeft,ascStack,nxLeftEnd) _ -> do
mbcur <- Ns.top heightsLeft
if knownNothing mbcur then return Nothing
else liftM Just $ do
mbright <- Ns.top heightsLeft
let (rightEnd,rightH) = netFromJust mbright
notDone <- netNot =<< netIsNothing mbright
(leftEnd,leftH) <- liftM netFromJust $ Ns.top ascStack
shortCase <- greaterThan rightH leftH
tallCase <- greaterThan leftH rightH
heightsLeft <- flip Ns.condPop heightsLeft =<< netNot tallCase
pushC <- netAnd shortCase notDone
ascStack <- Ns.condPush pushC (nxLeftEnd,rightH) ascStack
xdiff <- sub rightEnd leftEnd
candidate <- multiply leftH xdiff
better <- greaterThan candidate best
updateC <- netAnds [tallCase,notDone,better]
best <- mux updateC best =<< extend resultWidth candidate
nxLeftEnd'<- add const1 rightEnd
nxLeftEnd <- mux tallCase nxLeftEnd' leftEnd
ascStack <- Ns.condPop tallCase ascStack
return (best,heightsLeft,ascStack,nxLeftEnd)
) (resultInit,Ns.fromList heightsLeft,Ns.fromList [(constIntW xw 0,const0)]
,constIntW xw 1)
[1..2*n]
return best
where
n = length heights
xw = valueSize (n+1)
heightsLeft = zip (map constInt [1..]) $ heights++[const0]
resultWidth = xw+maximum (map intWidth heights)
const1 = constInt 1
const0 = constInt 0
resultInit = constIntW resultWidth 0
| null | https://raw.githubusercontent.com/samee/netlist/9fc20829f29724dc1148e54bd64fefd7e70af5ba/Benchmark/DemoCircuits.hs | haskell | Given a set of points on the circumference of a circle,
find the widest angle made by them at the center. All angles are
scaled by a factor of maxTheta/(2*pi) to avoid use of floating point
modDiff m a b assumes a <= b < maxtheta
Naive O(n^2) comparison
= Gc.bitwiseAnd a =<< Gc.sextend awidth (bitToInt bt)
awidth = bitWidth a
( intToBit b )
(intToBit b)
Stack of (height,startx) pair
Add zeroes to both sides
if top shorterThan current, push (current.x,current.h), i++
if top sameHeightAs current, i++
if top tallerThan current, updateWith (current.x-top.x)*top.h, pop
| Used only by Benchmark . Demo
module Benchmark.DemoCircuits where
import Control.Monad
import Data.List
import Debug.Trace
import Circuit.Sorter
import Circuit.NetList
import qualified Circuit.Queue as Nq
import qualified Circuit.Stack as Ns
import Util
TODO move this to NetList.hs if it is useful
type NetCondMod a = NetBool -> a -> NetWriter a
betterMaybe :: NetCondMod a -> (b -> NetCondMod a)
-> NetMaybe b -> NetCondMod a
betterMaybe nothCase justCase mb en piped
| knownNothing mb = nothCase en piped
| otherwise = do
(jen,nen) <- decoderUnit en =<< netIsNothing mb
justCase (netFromJust mb) jen =<< nothCase nen piped
Assumes n > = 2 , and that theta is sorted in ascending order
Implements the following code , in circuit ( why is this still so painful ! )
result = 0
j = 0
i = 1
while(i < n )
{
result = max result ( f theta[i ] theta[j ] )
if ( ( j < i ) & & ( f theta[i ] theta[j ] < = modDiff ] theta[j+1 ] ) )
j++
else
i++
}
Mapping : theta[j+1 .. i ] - > inRange ( Queue , possibly empty )
theta[i .. n-1 ] - > unseen ( Stack , possibly empty )
theta[j ] - > curj
Implements the following code, in circuit (why is this still so painful!)
result = 0
j = 0
i = 1
while(i<n)
{
result = max result (f theta[i] theta[j])
if ((j<i) && (f theta[i] theta[j] <= modDiff maxTheta theta[i] theta[j+1]))
j++
else
i++
}
Mapping: theta[j+1..i] -> inRange (Queue, possibly empty)
theta[i..n-1] -> unseen (Stack, possibly empty)
theta[j] -> curj
-}
wideAngle :: [NetUInt] -> NetUInt -> NetWriter NetUInt
wideAngle theta maxTheta = if n <= 1
then return $ constInt 0
else do
let inRange = Nq.fromList [theta!!1]
unseen = Ns.fromList $ tail theta
curj = theta!!0
(result,_,_,_) <- foldM (\loopVars@(_,_,unseen,_) _ -> do
mb <- Ns.top unseen
betterMaybe
(const return)
(\curi en (result,inRange,unseen,curj) -> do
curSep <- modDiff maxTheta curj curi
updres <- netAnd en =<< curSep `greaterThan` result
result <- mux updres result curSep
mb <- Nq.front inRange
(incI,(inRange,curj)) <- betterMaybe
(\en (incI,lv) -> do
incI <- netOr incI en
return (incI,lv))
(\nxtj en (incI,(inRange,curj)) -> do
nxtSep <- modDiff maxTheta nxtj curi
wider <- netNot =<< greaterThan curSep nxtSep
incJ <- netAnd en wider
incI <- netOr incI =<< netXor en incJ
curj <- mux incJ curj nxtj
inRange <- Nq.condPop incJ inRange
return (incI,(inRange,curj)))
mb en (netFalse,(inRange,curj))
unseen <- Ns.condPop incI unseen
mb <- Ns.top unseen
inRange <- betterMaybe
(const return)
(\nxti en inRange -> Nq.condPush en nxti inRange)
mb incI inRange
return (result,inRange,unseen,curj))
mb netTrue loopVars)
(constIntW (intWidth maxTheta) 0,inRange,unseen,curj) [0..2*n-1]
return result
where
n = length theta
modDiff m a b = do
x <- sub b a
y <- sub m x
netMin x y
foldMWithBreak :: Monad m => (a -> b -> m (Maybe a)) -> a -> [b] -> m a
foldMWithBreak f init [] = return init
foldMWithBreak f init (h:t) = do mb <- f init h
case mb of Nothing -> return init
Just x -> foldMWithBreak f x t
More readable versions of this function was overflowing the stack FIXME
wideAngleNaive :: [NetUInt] -> NetUInt -> NetWriter NetUInt
wideAngleNaive theta maxTheta = foldM (\res (h:ts) ->
foldM (\res t -> netMax res =<< modDiff maxTheta h t) res ts
) (constInt 0) (init $ tails theta)
shiftLeft amt x = bitConcat [ x,(constIntW amt 0 ) ]
multiply :: NetUInt -> NetUInt -> NetWriter NetUInt
multiply a b = aux =<< bitify b where
addop bt = mux bt (constInt 0) a
aux b = if bwidth == 1 then addop =<< lsb b
else do (bt,b') <- splitLsb b
s <- shiftLeft 1 =<< aux b'
add s =<< addop bt
where bwidth = bitWidth b
else do ( bt , b ' ) < - splitMsb b
s < - leadz = < < multiply a b '
addU s = < < shiftLeft ( bwidth-1 ) = < < addop bt
where bwidth = bitWidth b
leadz x = zextend ( bitWidth x + 1 ) x
else do (bt,b') <- splitMsb b
s <- leadz =<< multiply a b'
addU s =<< shiftLeft (bwidth-1) =<< addop bt
where bwidth = bitWidth b
leadz x = zextend (bitWidth x + 1) x
-}
TODO stack needs condModifyTop
rectangleInHistogram :: [NetUInt] -> NetWriter NetUInt
rectangleInHistogram heights = do
(best,_,_,_) <- foldMWithBreak (\(best,heightsLeft,ascStack,nxLeftEnd) _ -> do
mbcur <- Ns.top heightsLeft
if knownNothing mbcur then return Nothing
else liftM Just $ do
mbright <- Ns.top heightsLeft
let (rightEnd,rightH) = netFromJust mbright
notDone <- netNot =<< netIsNothing mbright
(leftEnd,leftH) <- liftM netFromJust $ Ns.top ascStack
shortCase <- greaterThan rightH leftH
tallCase <- greaterThan leftH rightH
heightsLeft <- flip Ns.condPop heightsLeft =<< netNot tallCase
pushC <- netAnd shortCase notDone
ascStack <- Ns.condPush pushC (nxLeftEnd,rightH) ascStack
xdiff <- sub rightEnd leftEnd
candidate <- multiply leftH xdiff
better <- greaterThan candidate best
updateC <- netAnds [tallCase,notDone,better]
best <- mux updateC best =<< extend resultWidth candidate
nxLeftEnd'<- add const1 rightEnd
nxLeftEnd <- mux tallCase nxLeftEnd' leftEnd
ascStack <- Ns.condPop tallCase ascStack
return (best,heightsLeft,ascStack,nxLeftEnd)
) (resultInit,Ns.fromList heightsLeft,Ns.fromList [(constIntW xw 0,const0)]
,constIntW xw 1)
[1..2*n]
return best
where
n = length heights
xw = valueSize (n+1)
heightsLeft = zip (map constInt [1..]) $ heights++[const0]
resultWidth = xw+maximum (map intWidth heights)
const1 = constInt 1
const0 = constInt 0
resultInit = constIntW resultWidth 0
|
3846595445de32ad3a30a32f751e85d70ce69a2d03d0ba68f1d4f3ba5a1eb28a | uhc/uhc | ClassMonadic.hs | {-# OPTIONS -fglasgow-exts -fallow-undecidable-instances #-}
-----------------------------------------------------------------------------
-- | License : GPL
--
-- Maintainer :
-- Stability : provisional
-- Portability : non-portable (requires extensions)
-----------------------------------------------------------------------------
module Top.Implementation.TypeGraph.ClassMonadic where
import Top.Interface.Basic
import Top.Interface.TypeInference
import Top.Interface.Qualification
import qualified Top.Implementation.TypeGraph.Class as TG
import Top.Implementation.TypeGraph.Basics
import Top.Types
import Top.Solver
import qualified Data.Map as M
import qualified Data.Set as S
class (HasBasic m info, HasTI m info, HasQual m info, HasTG m info, MonadWriter LogEntries m, Show info) => HasTypeGraph m info | m -> info
instance (HasBasic m info, HasTI m info, HasQual m info, HasTG m info, MonadWriter LogEntries m, Show info) => HasTypeGraph m info
class Monad m => HasTG m info | m -> info where
withTypeGraph :: (forall graph . TG.TypeGraph graph info => graph -> (a, graph)) -> m a
useTypeGraph :: HasTG m info => (forall graph . TG.TypeGraph graph info => graph -> a) -> m a
useTypeGraph f = withTypeGraph (\g -> (f g, g))
changeTypeGraph :: HasTG m info => (forall graph . TG.TypeGraph graph info => graph -> graph ) -> m ()
changeTypeGraph f = withTypeGraph (\g -> ((), f g))
-- construct a type graph
addTermGraph :: HasTypeGraph m info => Tp -> m VertexId
addTermGraph tp =
do unique <- getUnique
synonyms <- getTypeSynonyms
(newUnique, vid) <- withTypeGraph
(\graph -> let (u, v, g) = TG.addTermGraph synonyms unique tp graph
in ((u, v), g))
setUnique newUnique
return vid
addVertex :: HasTypeGraph m info => VertexId -> VertexInfo -> m ()
addVertex vid info = changeTypeGraph (TG.addVertex vid info)
addEdge :: HasTypeGraph m info => EdgeId -> info -> m ()
addEdge edgeId info = changeTypeGraph (TG.addEdge edgeId info)
addNewEdge :: HasTypeGraph m info => (VertexId, VertexId) -> info -> m ()
addNewEdge pair info = changeTypeGraph (TG.addNewEdge pair info)
-- deconstruct a type graph
deleteEdge :: HasTypeGraph m info => EdgeId -> m ()
deleteEdge edgeId = changeTypeGraph (TG.deleteEdge edgeId)
-- inspect an equivalence group in a type graph
verticesInGroupOf :: HasTypeGraph m info => VertexId -> m [(VertexId, VertexInfo)]
verticesInGroupOf vid = useTypeGraph (TG.verticesInGroupOf vid)
childrenInGroupOf :: HasTypeGraph m info => VertexId -> m ([ParentChild], [ParentChild])
childrenInGroupOf vid = useTypeGraph (TG.childrenInGroupOf vid)
constantsInGroupOf :: HasTypeGraph m info => VertexId -> m [String]
constantsInGroupOf vid = useTypeGraph (TG.constantsInGroupOf vid)
representativeInGroupOf :: HasTypeGraph m info => VertexId -> m VertexId
representativeInGroupOf vid = useTypeGraph (TG.representativeInGroupOf vid)
edgesFrom :: HasTypeGraph m info => VertexId -> m [(EdgeId, info)]
edgesFrom vid = useTypeGraph (TG.edgesFrom vid)
-- query a path in an equivalence group
allPaths :: HasTypeGraph m info => VertexId -> VertexId -> m (TypeGraphPath info)
allPaths v1 v2 = useTypeGraph (TG.allPaths v1 v2)
allPathsList :: HasTypeGraph m info => VertexId -> [VertexId] -> m (TypeGraphPath info)
allPathsList v1 vs = useTypeGraph (TG.allPathsList v1 vs)
allPathsListWithout :: HasTypeGraph m info => S.Set VertexId -> VertexId -> [VertexId] -> m (TypeGraphPath info)
allPathsListWithout set v1 vs = useTypeGraph (TG.allPathsListWithout set v1 vs)
-- substitution and term graph
substituteVariable :: HasTypeGraph m info => Int -> m Tp
substituteVariable i =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.substituteVariable synonyms i)
substituteType :: HasTypeGraph m info => Tp -> m Tp
substituteType tp =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.substituteType synonyms tp)
substituteTypeSafe :: HasTypeGraph m info => Tp -> m (Maybe Tp)
substituteTypeSafe tp =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.substituteTypeSafe synonyms tp)
makeSubstitution :: HasTypeGraph m info => m [(VertexId, Tp)]
makeSubstitution =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.makeSubstitution synonyms)
typeFromTermGraph :: HasTypeGraph m info => VertexId -> m Tp
typeFromTermGraph vid = useTypeGraph (TG.typeFromTermGraph vid)
-- Extra administration
markAsPossibleError :: HasTypeGraph m info => VertexId -> m ()
markAsPossibleError vid = changeTypeGraph (TG.markAsPossibleError vid)
getMarkedPossibleErrors :: HasTypeGraph m info => m [VertexId]
getMarkedPossibleErrors = useTypeGraph TG.getMarkedPossibleErrors
unmarkPossibleErrors :: HasTypeGraph m info => m ()
unmarkPossibleErrors = changeTypeGraph TG.unmarkPossibleErrors
---------------------
------ EXTRA
theUnifyTerms :: HasTypeGraph m info => info -> Tp -> Tp -> m ()
theUnifyTerms info t1 t2 =
do v1 <- addTermGraph t1
v2 <- addTermGraph t2
addNewEdge (v1, v2) info
makeFixpointSubst :: HasTypeGraph m info => m FixpointSubstitution
makeFixpointSubst =
do xs <- makeSubstitution
let list = [ (i, tp) | (VertexId i, tp) <- xs ]
return (FixpointSubstitution (M.fromList list))
| null | https://raw.githubusercontent.com/uhc/uhc/8eb6914df3ba2ba43916a1a4956c6f25aa0e07c5/EHC/src/top/Implementation/TypeGraph/ClassMonadic.hs | haskell | # OPTIONS -fglasgow-exts -fallow-undecidable-instances #
---------------------------------------------------------------------------
| License : GPL
Maintainer :
Stability : provisional
Portability : non-portable (requires extensions)
---------------------------------------------------------------------------
construct a type graph
deconstruct a type graph
inspect an equivalence group in a type graph
query a path in an equivalence group
substitution and term graph
Extra administration
-------------------
---- EXTRA |
module Top.Implementation.TypeGraph.ClassMonadic where
import Top.Interface.Basic
import Top.Interface.TypeInference
import Top.Interface.Qualification
import qualified Top.Implementation.TypeGraph.Class as TG
import Top.Implementation.TypeGraph.Basics
import Top.Types
import Top.Solver
import qualified Data.Map as M
import qualified Data.Set as S
class (HasBasic m info, HasTI m info, HasQual m info, HasTG m info, MonadWriter LogEntries m, Show info) => HasTypeGraph m info | m -> info
instance (HasBasic m info, HasTI m info, HasQual m info, HasTG m info, MonadWriter LogEntries m, Show info) => HasTypeGraph m info
class Monad m => HasTG m info | m -> info where
withTypeGraph :: (forall graph . TG.TypeGraph graph info => graph -> (a, graph)) -> m a
useTypeGraph :: HasTG m info => (forall graph . TG.TypeGraph graph info => graph -> a) -> m a
useTypeGraph f = withTypeGraph (\g -> (f g, g))
changeTypeGraph :: HasTG m info => (forall graph . TG.TypeGraph graph info => graph -> graph ) -> m ()
changeTypeGraph f = withTypeGraph (\g -> ((), f g))
addTermGraph :: HasTypeGraph m info => Tp -> m VertexId
addTermGraph tp =
do unique <- getUnique
synonyms <- getTypeSynonyms
(newUnique, vid) <- withTypeGraph
(\graph -> let (u, v, g) = TG.addTermGraph synonyms unique tp graph
in ((u, v), g))
setUnique newUnique
return vid
addVertex :: HasTypeGraph m info => VertexId -> VertexInfo -> m ()
addVertex vid info = changeTypeGraph (TG.addVertex vid info)
addEdge :: HasTypeGraph m info => EdgeId -> info -> m ()
addEdge edgeId info = changeTypeGraph (TG.addEdge edgeId info)
addNewEdge :: HasTypeGraph m info => (VertexId, VertexId) -> info -> m ()
addNewEdge pair info = changeTypeGraph (TG.addNewEdge pair info)
deleteEdge :: HasTypeGraph m info => EdgeId -> m ()
deleteEdge edgeId = changeTypeGraph (TG.deleteEdge edgeId)
verticesInGroupOf :: HasTypeGraph m info => VertexId -> m [(VertexId, VertexInfo)]
verticesInGroupOf vid = useTypeGraph (TG.verticesInGroupOf vid)
childrenInGroupOf :: HasTypeGraph m info => VertexId -> m ([ParentChild], [ParentChild])
childrenInGroupOf vid = useTypeGraph (TG.childrenInGroupOf vid)
constantsInGroupOf :: HasTypeGraph m info => VertexId -> m [String]
constantsInGroupOf vid = useTypeGraph (TG.constantsInGroupOf vid)
representativeInGroupOf :: HasTypeGraph m info => VertexId -> m VertexId
representativeInGroupOf vid = useTypeGraph (TG.representativeInGroupOf vid)
edgesFrom :: HasTypeGraph m info => VertexId -> m [(EdgeId, info)]
edgesFrom vid = useTypeGraph (TG.edgesFrom vid)
allPaths :: HasTypeGraph m info => VertexId -> VertexId -> m (TypeGraphPath info)
allPaths v1 v2 = useTypeGraph (TG.allPaths v1 v2)
allPathsList :: HasTypeGraph m info => VertexId -> [VertexId] -> m (TypeGraphPath info)
allPathsList v1 vs = useTypeGraph (TG.allPathsList v1 vs)
allPathsListWithout :: HasTypeGraph m info => S.Set VertexId -> VertexId -> [VertexId] -> m (TypeGraphPath info)
allPathsListWithout set v1 vs = useTypeGraph (TG.allPathsListWithout set v1 vs)
substituteVariable :: HasTypeGraph m info => Int -> m Tp
substituteVariable i =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.substituteVariable synonyms i)
substituteType :: HasTypeGraph m info => Tp -> m Tp
substituteType tp =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.substituteType synonyms tp)
substituteTypeSafe :: HasTypeGraph m info => Tp -> m (Maybe Tp)
substituteTypeSafe tp =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.substituteTypeSafe synonyms tp)
makeSubstitution :: HasTypeGraph m info => m [(VertexId, Tp)]
makeSubstitution =
do synonyms <- getTypeSynonyms
useTypeGraph (TG.makeSubstitution synonyms)
typeFromTermGraph :: HasTypeGraph m info => VertexId -> m Tp
typeFromTermGraph vid = useTypeGraph (TG.typeFromTermGraph vid)
markAsPossibleError :: HasTypeGraph m info => VertexId -> m ()
markAsPossibleError vid = changeTypeGraph (TG.markAsPossibleError vid)
getMarkedPossibleErrors :: HasTypeGraph m info => m [VertexId]
getMarkedPossibleErrors = useTypeGraph TG.getMarkedPossibleErrors
unmarkPossibleErrors :: HasTypeGraph m info => m ()
unmarkPossibleErrors = changeTypeGraph TG.unmarkPossibleErrors
theUnifyTerms :: HasTypeGraph m info => info -> Tp -> Tp -> m ()
theUnifyTerms info t1 t2 =
do v1 <- addTermGraph t1
v2 <- addTermGraph t2
addNewEdge (v1, v2) info
makeFixpointSubst :: HasTypeGraph m info => m FixpointSubstitution
makeFixpointSubst =
do xs <- makeSubstitution
let list = [ (i, tp) | (VertexId i, tp) <- xs ]
return (FixpointSubstitution (M.fromList list))
|
54744e8b104b24b2b1893ed7e167688baa2f61e453a8391081edf79595f34f52 | ktakashi/sagittarius-scheme | serializer.scm | -*- mode : scheme ; coding : utf-8 -*-
serializer.scm - sxml serializer ported to Sagittarius by
#!nobacktrace
(library (text sxml serializer)
(export srl:sxml->xml
srl:sxml->xml-noindent
srl:sxml->html
srl:sxml->html-noindent
srl:parameterizable
srl:sxml->string
srl:display-sxml
srl:conventional-ns-prefixes
Sagittarius
*srl:empty-elements*
*srl:escape-alist-char-data*
*srl:escape-alist-att-value*
*srl:escape-alist-html-att*
*srl:boolean-attributes*)
(import (rnrs)
(sagittarius)
(srfi :0 cond-expand)
(srfi :1 lists)
(srfi :39 parameters))
(define *srl:empty-elements*
(make-parameter '("area" "base" "basefont" "br" "col"
"frame" "hr" "img" "input" "isindex"
"link" "meta" "param")))
(define *srl:boolean-attributes*
(make-parameter '(allowfullscreen
allowpaymentrequest
async
autofocus
autoplay
checked
controls
default
defer
disabled
formnovalidate
hidden
ismap
itemscope
loop
multiple
muted
nomodule
novalidate
open
playsinline
readonly
required
reversed
selected
truespeed)))
SXML serializer into XML and HTML
;
; Partial conformance with
; [1] XSLT 2.0 and XQuery 1.0 Serialization
W3C Candidate Recommendation 3 November 2005
; -xslt-xquery-serialization-20051103/
;
; This software is in Public Domain.
IT IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND .
;
; Please send bug reports and comments to:
; Dmitry Lizorkin
Prefix for global identifiers in this module is ` srl : '
; short for "serialization"
; Requires: function `filter' from SRFI-1
; syntax `cond-expand' from SRFI-0
In particular , for PLT , ` filter ' can be acquired as follows :
;(require (lib "filter.ss" "srfi/1"))
;==========================================================================
; Basic
; `map' and `append' in a single pass:
( srl : map - append func lst ) = ( apply append ( map func lst ) )
; A simplified analogue of `map-union' from "sxpathlib.scm"
(define (srl:map-append func lst)
(if (null? lst)
lst
(append (func (car lst))
(srl:map-append func (cdr lst)))))
procedure srl : apply - string - append : : STR - LST - > STRING
str - lst : : = ( string )
Concatenates ` str - lst ' members into a single string
( srl : apply - string - append str - lst ) = ( apply string - append str - lst )
(cond-expand
(chicken
In Chicken , procedures are generally limited to 126 arguments
; -with-current-continuation.org/
Due to this Chicken limitation , we can not apply ` string - append ' directly
; for a potentially long `str-lst'
Similar to R5RS ' list - tail ' but returns the new list consisting of the
; first 'k' members of 'lst'
(define (srl:list-head lst k)
(if (or (null? lst) (zero? k))
'()
(cons (car lst) (srl:list-head (cdr lst) (- k 1)))))
Because of Chicken 126 - argument limitation , I do not care of intermediate
; garbage produced in the following solution:
(define (srl:apply-string-append str-lst)
(cond
((null? str-lst) "")
((null? (cdr str-lst)) (car str-lst))
at least two members
(let ((middle (inexact->exact (round (/ (length str-lst) 2)))))
(string-append
(srl:apply-string-append (srl:list-head str-lst middle))
(srl:apply-string-append (list-tail str-lst middle)))))))
)
(else
(define (srl:apply-string-append str-lst)
(apply string-append str-lst))
))
Analogue of ` assoc '
; However, search is performed by `cdr' of each alist member and `string=?' is
; used for comparison
(define (srl:assoc-cdr-string= item alist)
(cond
((null? alist) #f)
((string=? (cdar alist) item) (car alist))
(else (srl:assoc-cdr-string= item (cdr alist)))))
Analogue of ` member ' for strings that uses case insensitive comparison
(define (srl:member-ci str lst)
(cond
((null? lst) #f)
((string-ci=? str (car lst)) lst)
(else (srl:member-ci str (cdr lst)))))
Analogue of ` member '
The end of the ` lst ' is returned , from the first member that satisfies
; the `pred?'
(define (srl:mem-pred pred? lst)
(cond
((null? lst) #f)
((pred? (car lst)) lst)
(else (srl:mem-pred pred? (cdr lst)))))
;-------------------------------------------------
; Borrowed from "char-encoding.scm"
; The newline character
(cond-expand
((or scheme48 scsh)
(define srl:char-nl (ascii->char 10)))
(else
(define srl:char-nl (integer->char 10))))
; A string consisting of a single newline character
(define srl:newline (string srl:char-nl))
;-------------------------------------------------
; Borrowed from "sxpathlib.scm"
; A simplified implementation of `select-kids' is sufficienf for the serializer
(define (srl:select-kids test-pred?)
(lambda (node) ; node or node-set
(cond
((null? node) node)
((not (pair? node)) '()) ; No children
((symbol? (car node))
(filter test-pred? (cdr node)))
(else
(srl:map-append (srl:select-kids test-pred?) node)))))
;-------------------------------------------------
; Borrowed from "modif.scm"
Separates the list into two lists with respect to the predicate
Returns : ( values )
; res-lst1 - contains all members from the input lst that satisfy the pred?
res - lst2 - contains the remaining members of the input lst
(define (srl:separate-list pred? lst)
(let loop ((lst lst)
(satisfy '())
(rest '()))
(cond
((null? lst)
(values (reverse satisfy) (reverse rest)))
the first member satisfies the predicate
(loop (cdr lst)
(cons (car lst) satisfy) rest))
(else
(loop (cdr lst)
satisfy (cons (car lst) rest))))))
;-------------------------------------------------
; Borrowed from "fragments.scm"
; A simplified implementation of `sxml:clean-fragments'
(define (srl:clean-fragments fragments)
(reverse
(let loop ((fragments fragments) (result '()))
(cond
((null? fragments) result)
((null? (car fragments)) (loop (cdr fragments) result))
((pair? (car fragments))
(loop (cdr fragments)
(loop (car fragments) result)))
(else
(loop (cdr fragments)
(cons (car fragments) result)))))))
; A very much simplified analogue of `sxml:display-fragments' for fragments
that have no more than two levels of nesting
; fragments-level2 ::= (listof fragments-level1)
fragments - level1 : : = string | ( listof string )
(define (srl:display-fragments-2nesting fragments-level2 port)
(for-each
(lambda (level1)
(if (pair? level1)
(for-each (lambda (x) (display x port))
level1)
(display level1 port)))
fragments-level2))
;==========================================================================
; Helper SXML utilities
Splits an SXML ` name ' into namespace id / uri and local part
; Returns: (cons namespace-id local-part)
; local-part - string
; namespace-id - string or #f if the `name' does not have a prefix
(define (srl:split-name name)
(let* ((name-str (symbol->string name))
(lng (string-length name-str)))
(let iter ((i (- lng 1)))
(cond
((< i 0) ; name scanned, #\: not found
(cons #f name-str))
((char=? (string-ref name-str i) #\:)
(cons (substring name-str 0 i)
(substring name-str (+ i 1) lng)))
(else
(iter (- i 1)))))))
Converts SXML atomic object to a string . Keeps non - atomic object unchanged .
A simplified analogue of applying the XPath ` string ( . ) ' function to atomic
; object.
(define (srl:atomic->string obj)
(cond
((or (pair? obj) ; non-atomic type
(string? obj)) obj)
((number? obj)
(number->string obj))
((boolean? obj)
(if obj "true" "false"))
(else ; unexpected type
; ATTENTION: should probably raise an error here
obj)))
Whether an SXML element is empty
(define (srl:empty-elem? elem)
(or (null? (cdr elem)) ; just the name
(and (null? (cddr elem)) ; just the name and attributes
(pair? (cadr elem)) (eq? (caadr elem) '@))
name , attributes , and SXML 2.X aux - list
(null? (cdddr elem))
(pair? (caddr elem)) (eq? (caaddr elem) '@@))))
;-------------------------------------------------
Handling SXML namespaces
< namespace - assoc > is defined in the SXML specification as
; <namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
; Conventional namespace prefix referred to in XML-related specifications
; These prefixes are used for serializing the corresponding namespace URIs by
; default, unless a different prefix is supplied
(define-constant srl:conventional-ns-prefixes
'((dc . "/")
(fo . "")
(rdf . "-rdf-syntax-ns#")
(rng . "")
(xlink . "")
(xqx . "")
(xsd . "")
(xsi . "-instance")
(xsl . "")))
Returns ( listof < namespace - assoc > ) for the given SXML element
(define (srl:namespace-assoc-for-elem elem)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
(append
compatibility with SXML 3.0
(lambda (node) (and (pair? node) (eq? (car node) '@))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem))
compatibility with SXML 2.X
(lambda (node) (and (pair? node) (eq? (car node) '@@))))
elem)))))
Returns ( listof < namespace - assoc > ) for the SXML document node
(define (srl:ns-assoc-for-top doc)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
((srl:select-kids
(lambda (node)
After sequence normalization [ 1 ] , the SXML 3.0 aux - list is used
; at the top-level
(and (pair? node) (eq? (car node) '@))))
doc))))
; Extract original prefix-binding from `namespace-assoc-lst'
namespace - assoc - lst : : = ( listof < namespace - assoc > )
; <namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
Returns : ( listof ( cons original - prefix " URI " ) )
(define (srl:extract-original-prefix-binding namespace-assoc-lst)
(map
(lambda (triple) (cons (caddr triple) (cadr triple)))
(filter ; specifies original prefix
(lambda (memb) (= (length memb) 3))
namespace-assoc-lst)))
;-------------------------------------------------
; Handling xml:space attribute
; Returns the new value of `space-preserve?' in accordance with the value of
xml : space attribute probably presented for the given SXML element ` elem '
space - preserve ? : : = # t | # f - whether the SXML subtree inherits the
; xml:space attribute with the value "preserve"
(define (srl:update-space-specifier elem space-preserve?)
(let ((xml-space-val
((srl:select-kids string?)
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) 'xml:space))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem)))))
(cond
((null? xml-space-val) ; no xml:space attribute
space-preserve?)
((string=? (car xml-space-val) "preserve")
#t)
((string=? (car xml-space-val) "default")
#f)
(else space-preserve?))))
;==========================================================================
; Sequence normalization
Sect . 2 in [ 1 ]
Performs sequence normalization in accordance with [ 1 ]
Returns the SXML document node
(define (srl:normalize-sequence node-or-sequence)
(letrec
((normaliz-step-1
; "If the sequence that is input to serialization is empty, create a
sequence S1 that consists of a zero - length string . Otherwise , copy
; each item in the sequence that is input to serialization to create
the new sequence S1 . " [ 1 ]
(lambda (node-or-seq)
(cond
((null? node-or-seq) ; empty sequence
'(""))
; Effect of `as-nodeset' from "sxpathlib.scm"
((or (not (pair? node-or-seq)) ; single item
(symbol? (car node-or-seq))) ; single node
(list node-or-seq))
(else
node-or-seq))))
(normaliz-step-2
; "For each item in S1, if the item is atomic, obtain the lexical
; representation of the item by casting it to an xs:string and copy
; the string representation to the new sequence; otherwise, copy the
; item, which will be a node, to the new sequence. The new sequence is
S2 . " [ 1 ]
(lambda (seq)
(map
(lambda (item) (srl:atomic->string item))
seq)))
(normaliz-step-3
; "For each subsequence of adjacent strings in S2, copy a single
; string to the new sequence equal to the values of the strings in the
; subsequence concatenated in order, each separated by a single space.
; Copy all other items to the new sequence. The new sequence is S3."
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
((null? src) ; source sequence is over
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
(adjacent (cdr src)
(cons (car src) (cons " " adj-strs))))
(else
(loop (cdr src)
(cons (car src)
(cons (srl:apply-string-append adj-strs)
res)))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
Step 4 from [ 1 ] is redundant for SXML , since SXML text nodes are not
; distinquished from strings
(normaliz-step-5
; "For each item in S4, if the item is a document node, copy its
; children to the new sequence; otherwise, copy the item to the new
sequence . The new sequence is S5 . " [ 1 ]
(lambda (seq)
(cond
((null? seq)
seq)
((and (pair? (car seq)) (eq? (caar seq) '*TOP*))
; Document node
(append (cdar seq) (normaliz-step-5 (cdr seq))))
(else
(cons (car seq) (normaliz-step-5 (cdr seq)))))))
(normaliz-step-6
; "For each subsequence of adjacent text nodes in S5, copy a single
; text node to the new sequence equal to the values of the text nodes
; in the subsequence concatenated in order. Any text nodes with values
of zero length are dropped . Copy all other items to the new sequence .
The new sequence is S6 . " [ 1 ]
Much like Step 3 ; however , a space between adjacent strings is not
inserted and the zero - length strings are removed
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(if
(string=? (car src) "") ; empty string
(loop (cdr src) res)
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
((null? src) ; source sequence is over
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
; If it is an empty string, the effect of its presense
; will be removed by string concatenation
(adjacent (cdr src)
(cons (car src) adj-strs)))
(else
(loop (cdr src)
(cons (car src)
(cons
(srl:apply-string-append adj-strs)
res))))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
(normaliz-step-7
; "It is a serialization error [err:SENR0001] if an item in S6 is an
; attribute node or a namespace node. Otherwise, construct a new
; sequence, S7, that consists of a single document node and copy all
; the items in the sequence, which are all nodes, as children of that
document node . " [ 1 ]
On this step , we should take care of SXML aux - lists
; ATTENTION: should generally raise an error in the presense of
attribute nodes in a sequence . By nature of SXML 3.0 , however ,
; attribute nodes on the top level are treated as aux-nodes
(lambda (seq)
(call-with-values
(lambda ()
(srl:separate-list
(lambda (item)
(and (pair? item)
aux - list in SXML 2.X
aux - list in SXML 3.0
)))
seq))
(lambda (aux-lists body)
(if
(null? aux-lists)
`(*TOP* ,@body)
`(*TOP*
(@ ,@(srl:map-append cdr aux-lists))
,@body)))))))
TODO : According to [ 1 ] , if the normalized sequence does not have exactly
one element node node child or has text node children , then the
; serialized output should be an XML external general parsed entity.
; However, external parsed entities are not currently handled by SSAX
; parser. Should think of a compromise between conformance and practical
; usability.
(normaliz-step-7
(normaliz-step-6
(normaliz-step-5
(normaliz-step-3
(normaliz-step-2
(normaliz-step-1 node-or-sequence))))))))
;==========================================================================
; Character escaping during string serialization
Escaping in accordance with [ 1 ] and [ 2 ] :
;
[ 2 ] Extensible Markup Language ( XML ) 1.0 ( Third Edition )
W3C Recommendation 04 February 2004
-xml-20040204
;-------------------------------------------------
CDATA sections
Returns # f if a given character ` ch ' is in XML character range [ 2 ]
; Otherwise, returns a string representing the character reference for that
; character
(define (srl:xml-char-escaped ch)
(let ((code (char->integer ch)))
(if (or (= code 9) (= code 10) (= code 13)
(and (>= code 32) (<= code 55295))
(and (>= code 57344) (<= code 65533))
(>= code 65536))
#f
(string-append "&#" (number->string code) ";"
))))
Represents a given string ` str ' as a CDATA section
(define (srl:string->cdata-section str)
(let ((flush-buffer
If a ` buffer ' is non - empty , converts it to a CDATA string and
; cons'es this string to `res'. Returns a new res
(lambda (buffer res)
(if (null? buffer)
res
(cons
(string-append
"<![CDATA[" (list->string (reverse buffer)) "]]>")
res)))))
(let loop ((src (string->list str))
(buffer '())
(res '("")))
(cond
((null? src)
(srl:apply-string-append
(reverse (flush-buffer buffer res))))
((srl:xml-char-escaped (car src))
=> (lambda (charref)
(loop (cdr src)
'()
(cons charref (flush-buffer buffer res)))))
((and (char=? (car src) #\])
(not (null? buffer))
(char=? (car buffer) #\]))
(loop (cdr src)
'()
(cons (string (car buffer) (car src)) ;= "]]"
(flush-buffer (cdr buffer) res))))
(else ; any other character
(loop (cdr src)
(cons (car src) buffer)
res))))))
;-------------------------------------------------
; Character data and attribute values
Associative lists of characters to be escaped in XML character data and
attribute values respectively [ 2 ]
(define *srl:escape-alist-char-data*
(make-parameter '((#\& . "&") (#\< . "<") (#\> . ">"))))
(define *srl:escape-alist-att-value*
(make-parameter
(append `((#\' . "'") (#\" . """)
;; Escaping the newline character in attribute value
(,srl:char-nl . " "))
(*srl:escape-alist-char-data*))))
(define *srl:escape-alist-html-att*
(make-parameter
'((#\& . "&") (#\> . ">") (#\' . "'") (#\" . """))))
; Escape a string with the `srl:xml-char-escaped' and with the `escape-alist'
; supplied
escape - alist : : = ( listof ( cons char string ) )
; html-method? ::= #t | #f
; Returns the escaped string
(define (srl:string->escaped str escape-alist html-method?)
(let loop ((src (string->list str))
(adj-chars '())
(res '()))
(cond
((null? src)
(srl:apply-string-append
(reverse (cons (list->string (reverse adj-chars))
res))))
((assv (car src) escape-alist) ; current character matches the alist
=> (lambda (pair)
(if
Subsect . 7.2 in [ 1 ] :
; "The HTML output method MUST NOT escape a & character occurring
; in an attribute value immediately followed by a { character"
(and (char=? (car src) #\&)
html-method?
(not (null? (cdr src))) (char=? (cadr src) #\{))
(loop (cdr src)
(cons (car src) adj-chars)
res)
(loop (cdr src)
'()
(cons (cdr pair)
(cons (list->string (reverse adj-chars))
res))))))
((srl:xml-char-escaped (car src))
=> (lambda (esc)
(loop (cdr src)
'()
(cons esc
(cons (list->string (reverse adj-chars))
res)))))
(else
(loop (cdr src)
(cons (car src) adj-chars)
res)))))
(define (srl:string->char-data str)
(srl:string->escaped str (*srl:escape-alist-char-data*) #f))
(define (srl:string->att-value str)
(srl:string->escaped str (*srl:escape-alist-att-value*) #f))
(define (srl:string->html-att str)
(srl:string->escaped str (*srl:escape-alist-html-att*) #t))
;-------------------------------------------------
; Serializing entities produced by HtmlPrag
;
[ 3 ] .
HtmlPrag : Pragmatic Parsing and Emitting of HTML using SXML and SHTML
Version 0.16 , 2005 - 12 - 18 , /
; "..SHTML adds a special & syntax for non-ASCII (or non-Extended-ASCII)
characters . The syntax is ( & val ) , where is a symbol or string naming
; with the symbolic name of the character, or an integer with the numeric
value of the character . " [ 3 ]
; entity ::= `(& ,val)
: : = symbol | string | number
; Returns the string representation for the entity
(define (srl:shtml-entity->char-data entity)
; TODO: think of an appropriate error message for an ill-formed entity
(if
(= (length entity) 2)
(let ((val (cadr entity)))
(cond
((symbol? val) (string-append "&" (symbol->string val) ";")
)
((string? val) (string-append "&" val ";")
)
((and (number? val) (integer? val) (> val 0))
; to guarantee well-formedness of the result produced
(string-append "&#" (number->string val) ";")
)
(else ; should signal of an error
"")))
""))
;==========================================================================
; Serialization for markup
declared - ns - prefixes : : = ( listof ( cons prefix - string namespace - uri ) )
; prefix-string, namespace-uri - strings
; Returns the string representation for a QName
; prefix-string ::= string or #f if the name contains no prefix
; TODO: should check names for proper characters
(define (srl:qname->string prefix-string local-part)
(if prefix-string
(string-append prefix-string ":" local-part)
local-part))
;-------------------------------------------------
; Different types of nodes
; Returns the list of strings that constitute the serialized representation
; for the attribute. Inserts a whitespace symbol in the beginning
; method ::= 'xml | 'html
(define (srl:attribute->str-lst prefix-string local-part att-value method)
(let ((attval (srl:atomic->string att-value)))
(cond
(prefix-string
(list " " prefix-string ":" local-part "=\""
((if (eq? method 'html)
srl:string->html-att
srl:string->att-value) attval)
"\""))
((eq? method 'html)
( if ( string= ? local - part attval ) ; boolean attribute
Change for Sagittarius , we do properly
(if (memq (string->symbol local-part) (*srl:boolean-attributes*))
(list " " local-part)
(list " " local-part "=\"" (srl:string->html-att attval) "\"")))
(else ; unprefixed attribute, XML output method
(list " " local-part "=\"" (srl:string->att-value attval) "\"")))))
; Returns the list of strings that constitute the serialized representation
; for the namespace declaration. Inserts a whitespace symbol in the beginning
ATTENTION : character escaping for namespace URI may be improper , study this
; issue
(define (srl:namespace-decl->str-lst prefix-string namespace-uri)
Sagittarius
(if prefix-string
(list " xmlns:" prefix-string "=\""
(srl:string->att-value namespace-uri) "\"")
(list " xmlns" "=\"" (srl:string->att-value namespace-uri) "\"")))
According to SXML specification ,
; <comment> ::= ( *COMMENT* "comment string" )
; ATTENTION: in the case of ill-formed comment, should probably report an error
; instead of recovering
(define (srl:comment->str-lst comment-node)
(let ((proper-string-in-comment?
; Whether a proper string occurs in the comment node. Thus,
; "For compatibility, the string '--' (double-hyphen) MUST NOT occur
; within comments. ... Note that the grammar does not allow a comment
ending in --- > . " [ 2 ]
(lambda (str)
(let ((lng (string-length str)))
(or
empty string allowed in comment [ 2 ]
(and
(not (char=? (string-ref str 0) #\-))
(let iter ((i 1)
(prev-hyphen? #f))
(cond
((>= i lng)
(not prev-hyphen?) ; string must not end with hyphen
)
((char=? (string-ref str i) #\-)
(if prev-hyphen?
#f
(iter (+ i 1) #t)))
(else
(iter (+ i 1) #f))))))))))
(if (and (= (length comment-node) 2)
(string? (cadr comment-node))
(proper-string-in-comment? (cadr comment-node)))
(list "<!--" (cadr comment-node) "-->")
(list "<!--" "-->") ; should probably report of an error
)))
According to SXML specification ,
; <PI> ::= ( *PI* pi-target
; <annotations>? "processing instruction content string" )
; method ::= 'xml | 'html
Subsect 7.3 in [ 1 ] : " The HTML output method MUST terminate processing
; instructions with > rather than ?>."
; ATTENTION: in the case of ill-formed PI content string, should probably
; report an error instead of recovering
(define (srl:processing-instruction->str-lst pi-node method)
(let ((string-not-contain-charlist?
; Whether `str' does not contain a sequence of characters from
; `char-lst' as its substring
(lambda (str char-lst)
(let ((lng (string-length str)))
(or
(zero? lng) ; empty string doesn't contain
(let iter ((i 0)
(pattern char-lst))
(cond
((>= i lng) #t)
((char=? (string-ref str i) (car pattern))
(if (null? (cdr pattern)) ; it is the last member
#f ; contains
(iter (+ i 1) (cdr pattern))))
(else
(iter (+ i 1) char-lst)))))))))
(if
(or (null? (cdr pi-node))
no target = > ill - formed PI
'() ; should probably raise an error
(let ((content (filter string? (cddr pi-node))))
(cond
((null? content) ; PI with no content - correct situation
(list "<?" (symbol->string (cadr pi-node))
(if (eq? method 'html) ">" "?>")))
Subsect . 7.3 in [ 1 ] : " It is a serialization error to use the HTML
; output method when > appears within a processing instruction in
; the data model instance being serialized."
((and (null? (cdr content)) ; only a single member
(string-not-contain-charlist?
(car content)
(if (eq? method 'html) '(#\>) '(#\? #\>))))
(list "<?" (symbol->string (cadr pi-node)) " " (car content)
(if (eq? method 'html) ">" "?>")))
(else ; should probably signal of an error
'()))))))
Sagittarius specific
In some cases , we want to hold broken / partial HTML on SXML tree
e.g. node . This special marker holds this kind of content
;; and dumps as it is. Means no escaping nor sanitisation
;; <raw-html> ::= ( *RAW-HTML* raw-html-string )
(define (srl:raw-html->str-lst raw-html-node)
(if (and (= (length raw-html-node) 2)
(for-all string? (cdr raw-html-node)))
(cdr raw-html-node)
'()))
;-------------------------------------------------
SXML element
; Returns: (values
; prefix-string namespace-uri local-part declaration-required?)
; prefix-string - namespace prefix to be given to the serialized name: a string
; or #f if no prefix is required
namespace - uri - the namespace URI for the given ` name ' , # f if the name has no
namespace URI
; local-part - local part of the name
; declaration-required ::= #t | #f - whether `prefix' has to be declared
(define (srl:name->qname-components
name ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((use-ns-id-or-generate-prefix
(lambda (ns-id)
(if
(and ns-id ; try to use namespace-id as a prefix
(not (assq (string->symbol ns-id) ns-prefix-assig))
(not (assoc ns-id declared-ns-prefixes)))
ns-id
; Otherwise - generate unique prefix
; Returns a prefix-string not presented in ns-prefix-assig and
; declared-ns-prefixes
(let loop ((i 1))
(let ((candidate (string-append "prfx" (number->string i))))
(if (or (assoc candidate declared-ns-prefixes)
(assq (string->symbol candidate) ns-prefix-assig))
(loop (+ i 1))
candidate))))))
(n-parts (srl:split-name name)))
(cond
((not (car n-parts)) ; no namespace-id => no namespace
Sagittarius , handling * default * namespace
(cond ((or (assq '*default* namespace-assoc)
(assq '*default* ns-prefix-assig)) =>
(lambda (slot)
(values #f (cadr slot) (cdr n-parts)
(not (srl:assoc-cdr-string= (cadr slot)
declared-ns-prefixes)))))
(else
(values #f #f (cdr n-parts) ; name as a string
#f))))
((string-ci=? (car n-parts) "xml") ; reserved XML namespace
(values (car n-parts) ""
(cdr n-parts) #f))
(else
(call-with-values
(lambda ()
(cond
((assq (string->symbol (car n-parts)) ; suppose a namespace-id
namespace-assoc)
=> (lambda (lst)
(values (cadr lst) (car n-parts))))
first part of a name is a namespace URI
(values (car n-parts) #f))))
(lambda (namespace-uri ns-id)
(cond
((srl:assoc-cdr-string= namespace-uri declared-ns-prefixes)
=> (lambda (pair)
Prefix for that namespace URI already declared
(values (car pair) namespace-uri (cdr n-parts) #f)))
(else ; namespace undeclared
(values
(cond
((srl:assoc-cdr-string= namespace-uri ns-prefix-assig)
=> (lambda (pair)
; A candidate namespace prefix is supplied from the user
(let ((candidate (symbol->string (car pair))))
(if
(assoc candidate declared-ns-prefixes)
; The prefix already bound to a different namespace
; Avoid XML prefix re-declaration
(use-ns-id-or-generate-prefix ns-id)
candidate))))
(else
(use-ns-id-or-generate-prefix ns-id)))
namespace-uri
(cdr n-parts)
#t ; in any case, prefix declaration is required
)))))))))
Constructs start and end tags for an SXML element ` elem '
; method ::= 'xml | 'html
; Returns: (values start-tag end-tag
; ns-prefix-assig namespace-assoc declared-ns-prefixes)
start - tag : : = ( string )
end - tag : : = ( string ) or # f for empty element
TODO : escape URI attributes for HTML
; TODO: indentation probably should be made between attribute declarations
(define (srl:construct-start-end-tags
elem method
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((ns-assoc-here (srl:namespace-assoc-for-elem elem))
(empty? (srl:empty-elem? elem)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding ns-assoc-here)
ns-prefix-assig))
(namespace-assoc
(append ns-assoc-here namespace-assoc)))
(call-with-values
(lambda ()
(srl:name->qname-components ; element name
(car elem) ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (elem-prefix elem-uri elem-local elem-decl-required?)
(let loop ((attrs
(reverse
((srl:select-kids
not SXML 3.0 aux - list
(and (pair? node) (not (eq? (car node) '@)))))
((srl:select-kids
(lambda (node)
(and (pair? node) (eq? (car node) '@))))
elem))))
(start-tag
(if
(or (not empty?)
(and (eq? method 'html)
(not elem-prefix)
(srl:member-ci
elem-local
; ATTENTION: should probably move this list
; to a global const
(*srl:empty-elements*))))
'(">") '(" />")))
(ns-prefix-assig ns-prefix-assig)
(namespace-assoc namespace-assoc)
(declared-ns-prefixes
; As if element namespace already declared
(if elem-decl-required?
(cons (cons elem-prefix elem-uri)
declared-ns-prefixes)
declared-ns-prefixes)))
(if
(null? attrs) ; attributes scanned
(let ((elem-name (srl:qname->string elem-prefix elem-local)))
(values
(cons "<"
(cons elem-name
(if
elem-decl-required?
(cons
(srl:namespace-decl->str-lst elem-prefix elem-uri)
start-tag)
start-tag)))
(if empty? #f
(list "</" elem-name ">"))
ns-prefix-assig
namespace-assoc
declared-ns-prefixes))
(call-with-values
(lambda ()
(srl:name->qname-components
(caar attrs) ; attribute name
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (attr-prefix attr-uri attr-local attr-decl-required?)
(let ((start-tag
(cons
(srl:attribute->str-lst
attr-prefix attr-local
; TODO: optimize for HTML output method
(if (null? (cdar attrs)) ; no attribute value
attr-local
(cadar attrs))
method)
start-tag)))
(loop
(cdr attrs)
(if attr-decl-required?
(cons (srl:namespace-decl->str-lst attr-prefix attr-uri)
start-tag)
start-tag)
ns-prefix-assig
namespace-assoc
(if attr-decl-required?
(cons (cons attr-prefix attr-uri) declared-ns-prefixes)
declared-ns-prefixes))))))))))))
;==========================================================================
Recursively walking the tree of SXML elements
indentation : : = ( string ) or # f - a list of whitespace strings
; depending on the node nesting or #f if no indent is required
; space-preserve? ::= #t | #f - whether the subtree inherits the xml:space
; attribute with the value "preserve"
cdata - section - elements : : = ( listof symbol ) - list of element names whose
child nodes are to be output with CDATA section
; text-node-handler :: string -> string - a function that performs a proper
; character escaping for the given node if it is a text node
; TODO: do not insert whitespaces adjacent to HTML %inline elements in HTML
; output method
(define (srl:node->nested-str-lst-recursive
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(not (pair? node)) ; text node
(text-node-handler (srl:atomic->string node))
(case (car node) ; node name
((*COMMENT*)
(srl:comment->str-lst node))
((*PI*)
(srl:processing-instruction->str-lst node method))
((&)
(srl:shtml-entity->char-data node))
recovering for non - SXML nodes
'())
((*RAW-HTML*)
(srl:raw-html->str-lst node))
(else ; otherwise - an element node
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(if
(not end-tag) ; empty element => recursion stops
start-tag
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
; No escaping for strings inside these HTML elements
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
; No indent - on this level and subsequent levels
(values #f #f))
((or space-preserve?
(srl:mem-pred ; at least a single text node
(lambda (node) (not (pair? node)))
content))
; No indent on this level, possible indent on nested levels
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(if
indent-here
(append
start-tag
(map
(lambda (kid)
(list
indent-here
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(cons srl:newline
(cons (cdr indentation) end-tag)))
(append
start-tag
(map
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler))
content)
end-tag))))))))))))
(define (srl:display-node-out-recursive
node port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(not (pair? node)) ; text node
(display (text-node-handler (srl:atomic->string node)) port)
(case (car node) ; node name
((*COMMENT*)
(for-each
(lambda (x) (display x port))
(srl:comment->str-lst node)))
((*PI*)
(for-each
(lambda (x) (display x port))
(srl:processing-instruction->str-lst node method)))
((&)
(display (srl:shtml-entity->char-data node) port))
recovering for non - SXML nodes
#f)
((*RAW-HTML*)
(for-each (lambda (x) (display x port))
(srl:raw-html->str-lst node)))
(else ; otherwise - an element node
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(begin
(srl:display-fragments-2nesting start-tag port)
(if
end-tag ; there exists content
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
; No escaping for strings inside these HTML elements
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
; No indent - on this level and subsequent levels
(values #f #f))
((or space-preserve?
(srl:mem-pred ; at least a single text node
(lambda (node) (not (pair? node)))
content))
; No indent on this level, possible indent on nested levels
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(begin
(for-each ; display content
(if
indent-here
(lambda (kid)
(begin
(for-each
(lambda (x) (display x port))
indent-here)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(if indent-here
(begin
(display srl:newline port)
(for-each
(lambda (x) (display x port))
(cdr indentation))))
(for-each
(lambda (x) (display x port))
end-tag)))))))))))))
;-------------------------------------------------
; Serializing the document node - start of recursion
Creates the serialized representation for the XML declaration
; Returns: (listof string)
; version ::= string | number
; standalone ::= 'yes | 'no | 'omit
(define (srl:make-xml-decl version standalone)
(let ((version (if (number? version) (number->string version) version)))
(if (eq? standalone 'omit)
(list "<?xml version='" version "'?>")
(list "<?xml version='" version "' standalone='"
(symbol->string standalone) "'?>"))))
; omit-xml-declaration? ::= #t | #f
; standalone ::= 'yes | 'no | 'omit
; version ::= string | number
(define (srl:top->nested-str-lst doc
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(let* ((namespace-assoc (srl:ns-assoc-for-top doc))
(ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig))
(serialized-content
(map
(if
indent ; => output each member from the newline
(let ((indentation (list indent))) ; for nested elements
(lambda (kid)
(list
srl:newline
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
((srl:select-kids ; document node content
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))))
(if (or (eq? method 'html) omit-xml-declaration?)
(if (and indent (not (null? serialized-content)))
; Remove the starting newline
; ATTENTION: beware of `Gambit cadar bug':
; -list/
; 2005-July/000315.html
(cons (cadar serialized-content) (cdr serialized-content))
serialized-content)
(list (srl:make-xml-decl version standalone) serialized-content))))
(define (srl:display-top-out doc port
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
no XML declaration was displayed ?
(if (not (or (eq? method 'html) omit-xml-declaration?))
(begin
(for-each ; display xml declaration
(lambda (x) (display x port))
(srl:make-xml-decl version standalone))
#f)
#t))
(content ; document node content
((srl:select-kids
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))
(namespace-assoc (srl:ns-assoc-for-top doc)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig)))
(cond
((null? content) ; generally a rare practical situation
#t) ; nothing more to do
((and indent no-xml-decl?)
; We'll not display newline before (car content)
(let ((indentation (list indent))) ; for nested elements
(for-each
(lambda (kid put-newline?)
(begin
(if put-newline?
(display srl:newline port))
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data)))
content
; After sequence normalization, content does not contain #f
(cons #f (cdr content)))))
(else
(for-each
(if
indent ; => output each member from the newline
(let ((indentation (list indent))) ; for nested elements
(lambda (kid)
(begin
(display srl:newline port)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
content))))))
;==========================================================================
Interface
;-------------------------------------------------
; Calling the serializer with all the serialization parameters supported
; and with no overhead of parameters parsing.
; ATTENTION: As future versions of this library may provide support for
additional serialization parameters , the functions ` srl : sxml->string ' and
` srl : display - sxml ' specified in this subsections may have a different number
; of their arguments in the future versions of the library.
; Returns a string that contains the serialized representation for `sxml-obj'.
cdata - section - elements : : = ( - name )
; indent ::= #t | #f | whitespace-string
; method = 'xml | 'html
ns - prefix - assign : : = ( listof ( cons prefix - symbol namespace - uri - string ) )
; omit-xml-declaration? ::= #t | #f
; standalone ::= 'yes | 'no | 'omit
version : : = number | string
(define (srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:apply-string-append
(srl:clean-fragments
(srl:top->nested-str-lst (srl:normalize-sequence sxml-obj)
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version))))
; Writes the serialized representation of the `sxml-obj' to an output port
; `port'. The result returned by the function is unspecified.
(define (srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(if
(string? port-or-filename) ; a filename?
(let ((out (open-output-file port-or-filename)))
(begin
(srl:display-top-out (srl:normalize-sequence sxml-obj) out
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)
(display srl:newline out) ; newline at the end of file
(close-output-port out)))
(srl:display-top-out (srl:normalize-sequence sxml-obj) port-or-filename
cdata-section-elements
(if (and indent (not (string? indent))) " " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)))
;-------------------------------------------------
; Generalized serialization procedure, parameterizable with all the
; serialization params supported by this implementation
procedure srl : parameterizable : : SXML - OBJ [ PORT ] { PARAM } * - >
; -> STRING|unspecified
sxml - obj - an SXML object to serialize
; param ::= (cons param-name param-value)
; param-name ::= symbol
;
1 . cdata - section - elements
value : : = ( - elem - name )
sxml - elem - name : : = symbol
;
2 . indent
; value ::= 'yes | #t | 'no | #f | whitespace-string
;
3 . method
; value ::= 'xml | 'html
;
4 . ns - prefix - assig
value : : = ( listof ( cons prefix namespace - uri ) )
; prefix ::= symbol
; namespace-uri ::= string
;
5 . omit - xml - declaration ?
; value ::= 'yes | #t | 'no | #f
;
6 . standalone
; value ::= 'yes | #t | 'no | #f | 'omit
;
7 . version
; value ::= string | number
;
; ATTENTION: If a parameter name is unexpected or a parameter value is
; ill-formed, the parameter is silently ignored. Probably, a warning message
; in such a case would be more appropriate.
;
; Example:
( srl : parameterizable
; '(tag (@ (attr "value")) (nested "text node") (empty))
; (current-output-port)
; '(method . xml) ; XML output method is used by default
; '(indent . "\t") ; use a single tabulation to indent nested elements
' ( omit - xml - declaration . # f ) ; add XML declaration
' ( standalone . yes ) ; denote a standalone XML document
' ( version . " 1.0 " ) ) ; XML version
(define (srl:parameterizable sxml-obj . port-or-filename+params)
(call-with-values
(lambda ()
(if (and (not (null? port-or-filename+params))
(or (output-port? (car port-or-filename+params))
(string? (car port-or-filename+params))))
(values (car port-or-filename+params) (cdr port-or-filename+params))
(values #f port-or-filename+params)))
(lambda (port-or-filename params)
(let loop ((params params)
(cdata-section-elements '())
(indent " ")
(method 'xml)
(ns-prefix-assig srl:conventional-ns-prefixes)
(omit-xml-declaration? #t)
(standalone 'omit)
(version "1.0"))
(cond
((null? params) ; all parameters parsed
(if port-or-filename
(srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)))
((or (not (pair? (car params))) ; not a pair or has no param value
(null? (cdar params)))
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))
(else
(let ((prm-value (cdar params)))
(case (caar params)
((cdata-section-elements)
(loop (cdr params)
(if (list? prm-value) prm-value cdata-section-elements)
indent method ns-prefix-assig
omit-xml-declaration? standalone version))
((indent)
(loop (cdr params)
cdata-section-elements
(cond
((boolean? prm-value)
(if prm-value " " prm-value))
((string? prm-value) prm-value)
((eq? prm-value 'yes) " ")
((eq? prm-value 'no) #f)
(else indent))
method ns-prefix-assig
omit-xml-declaration? standalone version))
((method)
(loop (cdr params)
cdata-section-elements indent
(if (or (eq? prm-value 'xml) (eq? prm-value 'html))
prm-value method)
ns-prefix-assig
omit-xml-declaration? standalone version))
((ns-prefix-assig)
(loop (cdr params)
cdata-section-elements indent method
(if (and (list? prm-value)
(not (srl:mem-pred ; no non-pair members
(lambda (x) (not (pair? x)))
prm-value)))
(append prm-value ns-prefix-assig)
ns-prefix-assig)
omit-xml-declaration? standalone version))
((omit-xml-declaration)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
(cond
((boolean? prm-value) prm-value)
((eq? prm-value 'yes) #t)
((eq? prm-value 'no) #f)
(else indent))
standalone version))
((standalone)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig omit-xml-declaration?
(cond
((memv prm-value '(yes no omit))
prm-value)
((boolean? prm-value)
(if prm-value 'yes 'no))
(else standalone))
version))
((version)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone
(if (or (string? prm-value) (number? prm-value))
prm-value version)))
(else
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))))))))))
;-------------------------------------------------
; High-level functions for popular serialization use-cases
; These functions use only a subset of serializer functionality, however, this
; subset seems sufficient for most practical purposes.
procedure srl : sxml->xml : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
;
Serializes the ` sxml - obj ' into XML , with indentation to facilitate
; readability by a human.
;
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
; port-or-filename - an output port or an output file name, an optional
; argument
; If `port-or-filename' is not supplied, the functions return a string that
; contains the serialized representation of the `sxml-obj'.
; If `port-or-filename' is supplied and is a port, the functions write the
; serialized representation of `sxml-obj' to this port and return an
; unspecified result.
; If `port-or-filename' is supplied and is a string, this string is treated as
; an output filename, the serialized representation of `sxml-obj' is written to
; that filename and an unspecified result is returned. If a file with the given
; name already exists, the effect is unspecified.
(define (srl:sxml->xml sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->xml - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
; -> STRING|unspecified
;
Serializes the ` sxml - obj ' into XML , without indentation .
(define (srl:sxml->xml-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->html : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
;
Serializes the ` sxml - obj ' into HTML , with indentation to facilitate
; readability by a human.
;
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
; port-or-filename - an output port or an output file name, an optional
; argument
; If `port-or-filename' is not supplied, the functions return a string that
; contains the serialized representation of the `sxml-obj'.
; If `port-or-filename' is supplied and is a port, the functions write the
; serialized representation of `sxml-obj' to this port and return an
; unspecified result.
; If `port-or-filename' is supplied and is a string, this string is treated as
; an output filename, the serialized representation of `sxml-obj' is written to
; that filename and an unspecified result is returned. If a file with the given
; name already exists, the effect is unspecified.
(define (srl:sxml->html sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #t 'html '() #t 'omit "4.0")))
procedure srl : sxml->html - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
; -> STRING|unspecified
;
Serializes the ` sxml - obj ' into HTML , without indentation .
(define (srl:sxml->html-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #f 'html '() #t 'omit "4.0")))
)
| null | https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/8454886fad51fb12aa972c3e3a6ac3a0adca097d/sitelib/text/sxml/serializer.scm | scheme | coding : utf-8 -*-
Partial conformance with
[1] XSLT 2.0 and XQuery 1.0 Serialization
-xslt-xquery-serialization-20051103/
This software is in Public Domain.
Please send bug reports and comments to:
Dmitry Lizorkin
short for "serialization"
Requires: function `filter' from SRFI-1
syntax `cond-expand' from SRFI-0
(require (lib "filter.ss" "srfi/1"))
==========================================================================
Basic
`map' and `append' in a single pass:
A simplified analogue of `map-union' from "sxpathlib.scm"
-with-current-continuation.org/
for a potentially long `str-lst'
first 'k' members of 'lst'
garbage produced in the following solution:
However, search is performed by `cdr' of each alist member and `string=?' is
used for comparison
the `pred?'
-------------------------------------------------
Borrowed from "char-encoding.scm"
The newline character
A string consisting of a single newline character
-------------------------------------------------
Borrowed from "sxpathlib.scm"
A simplified implementation of `select-kids' is sufficienf for the serializer
node or node-set
No children
-------------------------------------------------
Borrowed from "modif.scm"
res-lst1 - contains all members from the input lst that satisfy the pred?
-------------------------------------------------
Borrowed from "fragments.scm"
A simplified implementation of `sxml:clean-fragments'
A very much simplified analogue of `sxml:display-fragments' for fragments
fragments-level2 ::= (listof fragments-level1)
==========================================================================
Helper SXML utilities
Returns: (cons namespace-id local-part)
local-part - string
namespace-id - string or #f if the `name' does not have a prefix
name scanned, #\: not found
object.
non-atomic type
unexpected type
ATTENTION: should probably raise an error here
just the name
just the name and attributes
-------------------------------------------------
<namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
Conventional namespace prefix referred to in XML-related specifications
These prefixes are used for serializing the corresponding namespace URIs by
default, unless a different prefix is supplied
at the top-level
Extract original prefix-binding from `namespace-assoc-lst'
<namespace-assoc> ::= ( <namespace-id> "URI" original-prefix? )
specifies original prefix
-------------------------------------------------
Handling xml:space attribute
Returns the new value of `space-preserve?' in accordance with the value of
xml:space attribute with the value "preserve"
no xml:space attribute
==========================================================================
Sequence normalization
"If the sequence that is input to serialization is empty, create a
each item in the sequence that is input to serialization to create
empty sequence
Effect of `as-nodeset' from "sxpathlib.scm"
single item
single node
"For each item in S1, if the item is atomic, obtain the lexical
representation of the item by casting it to an xs:string and copy
the string representation to the new sequence; otherwise, copy the
item, which will be a node, to the new sequence. The new sequence is
"For each subsequence of adjacent strings in S2, copy a single
string to the new sequence equal to the values of the strings in the
subsequence concatenated in order, each separated by a single space.
Copy all other items to the new sequence. The new sequence is S3."
source sequence is over
distinquished from strings
"For each item in S4, if the item is a document node, copy its
children to the new sequence; otherwise, copy the item to the new
Document node
"For each subsequence of adjacent text nodes in S5, copy a single
text node to the new sequence equal to the values of the text nodes
in the subsequence concatenated in order. Any text nodes with values
however , a space between adjacent strings is not
empty string
source sequence is over
If it is an empty string, the effect of its presense
will be removed by string concatenation
"It is a serialization error [err:SENR0001] if an item in S6 is an
attribute node or a namespace node. Otherwise, construct a new
sequence, S7, that consists of a single document node and copy all
the items in the sequence, which are all nodes, as children of that
ATTENTION: should generally raise an error in the presense of
attribute nodes on the top level are treated as aux-nodes
serialized output should be an XML external general parsed entity.
However, external parsed entities are not currently handled by SSAX
parser. Should think of a compromise between conformance and practical
usability.
==========================================================================
Character escaping during string serialization
-------------------------------------------------
Otherwise, returns a string representing the character reference for that
character
cons'es this string to `res'. Returns a new res
= "]]"
any other character
-------------------------------------------------
Character data and attribute values
")
Escaping the newline character in attribute value
"))))
Escape a string with the `srl:xml-char-escaped' and with the `escape-alist'
supplied
html-method? ::= #t | #f
Returns the escaped string
current character matches the alist
"The HTML output method MUST NOT escape a & character occurring
in an attribute value immediately followed by a { character"
-------------------------------------------------
Serializing entities produced by HtmlPrag
"..SHTML adds a special & syntax for non-ASCII (or non-Extended-ASCII)
with the symbolic name of the character, or an integer with the numeric
entity ::= `(& ,val)
Returns the string representation for the entity
TODO: think of an appropriate error message for an ill-formed entity
to guarantee well-formedness of the result produced
should signal of an error
==========================================================================
Serialization for markup
prefix-string, namespace-uri - strings
Returns the string representation for a QName
prefix-string ::= string or #f if the name contains no prefix
TODO: should check names for proper characters
-------------------------------------------------
Different types of nodes
Returns the list of strings that constitute the serialized representation
for the attribute. Inserts a whitespace symbol in the beginning
method ::= 'xml | 'html
boolean attribute
unprefixed attribute, XML output method
Returns the list of strings that constitute the serialized representation
for the namespace declaration. Inserts a whitespace symbol in the beginning
issue
<comment> ::= ( *COMMENT* "comment string" )
ATTENTION: in the case of ill-formed comment, should probably report an error
instead of recovering
Whether a proper string occurs in the comment node. Thus,
"For compatibility, the string '--' (double-hyphen) MUST NOT occur
within comments. ... Note that the grammar does not allow a comment
string must not end with hyphen
should probably report of an error
<PI> ::= ( *PI* pi-target
<annotations>? "processing instruction content string" )
method ::= 'xml | 'html
instructions with > rather than ?>."
ATTENTION: in the case of ill-formed PI content string, should probably
report an error instead of recovering
Whether `str' does not contain a sequence of characters from
`char-lst' as its substring
empty string doesn't contain
it is the last member
contains
should probably raise an error
PI with no content - correct situation
output method when > appears within a processing instruction in
the data model instance being serialized."
only a single member
should probably signal of an error
and dumps as it is. Means no escaping nor sanitisation
<raw-html> ::= ( *RAW-HTML* raw-html-string )
-------------------------------------------------
Returns: (values
prefix-string namespace-uri local-part declaration-required?)
prefix-string - namespace prefix to be given to the serialized name: a string
or #f if no prefix is required
local-part - local part of the name
declaration-required ::= #t | #f - whether `prefix' has to be declared
try to use namespace-id as a prefix
Otherwise - generate unique prefix
Returns a prefix-string not presented in ns-prefix-assig and
declared-ns-prefixes
no namespace-id => no namespace
name as a string
reserved XML namespace
suppose a namespace-id
namespace undeclared
A candidate namespace prefix is supplied from the user
The prefix already bound to a different namespace
Avoid XML prefix re-declaration
in any case, prefix declaration is required
method ::= 'xml | 'html
Returns: (values start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
TODO: indentation probably should be made between attribute declarations
element name
ATTENTION: should probably move this list
to a global const
As if element namespace already declared
attributes scanned
attribute name
TODO: optimize for HTML output method
no attribute value
==========================================================================
depending on the node nesting or #f if no indent is required
space-preserve? ::= #t | #f - whether the subtree inherits the xml:space
attribute with the value "preserve"
text-node-handler :: string -> string - a function that performs a proper
character escaping for the given node if it is a text node
TODO: do not insert whitespaces adjacent to HTML %inline elements in HTML
output method
text node
node name
otherwise - an element node
empty element => recursion stops
No escaping for strings inside these HTML elements
No indent - on this level and subsequent levels
at least a single text node
No indent on this level, possible indent on nested levels
text node
node name
otherwise - an element node
there exists content
No escaping for strings inside these HTML elements
No indent - on this level and subsequent levels
at least a single text node
No indent on this level, possible indent on nested levels
display content
-------------------------------------------------
Serializing the document node - start of recursion
Returns: (listof string)
version ::= string | number
standalone ::= 'yes | 'no | 'omit
omit-xml-declaration? ::= #t | #f
standalone ::= 'yes | 'no | 'omit
version ::= string | number
=> output each member from the newline
for nested elements
document node content
Remove the starting newline
ATTENTION: beware of `Gambit cadar bug':
-list/
2005-July/000315.html
display xml declaration
document node content
generally a rare practical situation
nothing more to do
We'll not display newline before (car content)
for nested elements
After sequence normalization, content does not contain #f
=> output each member from the newline
for nested elements
==========================================================================
-------------------------------------------------
Calling the serializer with all the serialization parameters supported
and with no overhead of parameters parsing.
ATTENTION: As future versions of this library may provide support for
of their arguments in the future versions of the library.
Returns a string that contains the serialized representation for `sxml-obj'.
indent ::= #t | #f | whitespace-string
method = 'xml | 'html
omit-xml-declaration? ::= #t | #f
standalone ::= 'yes | 'no | 'omit
Writes the serialized representation of the `sxml-obj' to an output port
`port'. The result returned by the function is unspecified.
a filename?
newline at the end of file
-------------------------------------------------
Generalized serialization procedure, parameterizable with all the
serialization params supported by this implementation
-> STRING|unspecified
param ::= (cons param-name param-value)
param-name ::= symbol
value ::= 'yes | #t | 'no | #f | whitespace-string
value ::= 'xml | 'html
prefix ::= symbol
namespace-uri ::= string
value ::= 'yes | #t | 'no | #f
value ::= 'yes | #t | 'no | #f | 'omit
value ::= string | number
ATTENTION: If a parameter name is unexpected or a parameter value is
ill-formed, the parameter is silently ignored. Probably, a warning message
in such a case would be more appropriate.
Example:
'(tag (@ (attr "value")) (nested "text node") (empty))
(current-output-port)
'(method . xml) ; XML output method is used by default
'(indent . "\t") ; use a single tabulation to indent nested elements
add XML declaration
denote a standalone XML document
XML version
all parameters parsed
not a pair or has no param value
no non-pair members
-------------------------------------------------
High-level functions for popular serialization use-cases
These functions use only a subset of serializer functionality, however, this
subset seems sufficient for most practical purposes.
readability by a human.
port-or-filename - an output port or an output file name, an optional
argument
If `port-or-filename' is not supplied, the functions return a string that
contains the serialized representation of the `sxml-obj'.
If `port-or-filename' is supplied and is a port, the functions write the
serialized representation of `sxml-obj' to this port and return an
unspecified result.
If `port-or-filename' is supplied and is a string, this string is treated as
an output filename, the serialized representation of `sxml-obj' is written to
that filename and an unspecified result is returned. If a file with the given
name already exists, the effect is unspecified.
-> STRING|unspecified
readability by a human.
port-or-filename - an output port or an output file name, an optional
argument
If `port-or-filename' is not supplied, the functions return a string that
contains the serialized representation of the `sxml-obj'.
If `port-or-filename' is supplied and is a port, the functions write the
serialized representation of `sxml-obj' to this port and return an
unspecified result.
If `port-or-filename' is supplied and is a string, this string is treated as
an output filename, the serialized representation of `sxml-obj' is written to
that filename and an unspecified result is returned. If a file with the given
name already exists, the effect is unspecified.
-> STRING|unspecified
| serializer.scm - sxml serializer ported to Sagittarius by
#!nobacktrace
(library (text sxml serializer)
(export srl:sxml->xml
srl:sxml->xml-noindent
srl:sxml->html
srl:sxml->html-noindent
srl:parameterizable
srl:sxml->string
srl:display-sxml
srl:conventional-ns-prefixes
Sagittarius
*srl:empty-elements*
*srl:escape-alist-char-data*
*srl:escape-alist-att-value*
*srl:escape-alist-html-att*
*srl:boolean-attributes*)
(import (rnrs)
(sagittarius)
(srfi :0 cond-expand)
(srfi :1 lists)
(srfi :39 parameters))
(define *srl:empty-elements*
(make-parameter '("area" "base" "basefont" "br" "col"
"frame" "hr" "img" "input" "isindex"
"link" "meta" "param")))
(define *srl:boolean-attributes*
(make-parameter '(allowfullscreen
allowpaymentrequest
async
autofocus
autoplay
checked
controls
default
defer
disabled
formnovalidate
hidden
ismap
itemscope
loop
multiple
muted
nomodule
novalidate
open
playsinline
readonly
required
reversed
selected
truespeed)))
SXML serializer into XML and HTML
W3C Candidate Recommendation 3 November 2005
IT IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND .
Prefix for global identifiers in this module is ` srl : '
In particular , for PLT , ` filter ' can be acquired as follows :
( srl : map - append func lst ) = ( apply append ( map func lst ) )
(define (srl:map-append func lst)
(if (null? lst)
lst
(append (func (car lst))
(srl:map-append func (cdr lst)))))
procedure srl : apply - string - append : : STR - LST - > STRING
str - lst : : = ( string )
Concatenates ` str - lst ' members into a single string
( srl : apply - string - append str - lst ) = ( apply string - append str - lst )
(cond-expand
(chicken
In Chicken , procedures are generally limited to 126 arguments
Due to this Chicken limitation , we can not apply ` string - append ' directly
Similar to R5RS ' list - tail ' but returns the new list consisting of the
(define (srl:list-head lst k)
(if (or (null? lst) (zero? k))
'()
(cons (car lst) (srl:list-head (cdr lst) (- k 1)))))
Because of Chicken 126 - argument limitation , I do not care of intermediate
(define (srl:apply-string-append str-lst)
(cond
((null? str-lst) "")
((null? (cdr str-lst)) (car str-lst))
at least two members
(let ((middle (inexact->exact (round (/ (length str-lst) 2)))))
(string-append
(srl:apply-string-append (srl:list-head str-lst middle))
(srl:apply-string-append (list-tail str-lst middle)))))))
)
(else
(define (srl:apply-string-append str-lst)
(apply string-append str-lst))
))
Analogue of ` assoc '
(define (srl:assoc-cdr-string= item alist)
(cond
((null? alist) #f)
((string=? (cdar alist) item) (car alist))
(else (srl:assoc-cdr-string= item (cdr alist)))))
Analogue of ` member ' for strings that uses case insensitive comparison
(define (srl:member-ci str lst)
(cond
((null? lst) #f)
((string-ci=? str (car lst)) lst)
(else (srl:member-ci str (cdr lst)))))
Analogue of ` member '
The end of the ` lst ' is returned , from the first member that satisfies
(define (srl:mem-pred pred? lst)
(cond
((null? lst) #f)
((pred? (car lst)) lst)
(else (srl:mem-pred pred? (cdr lst)))))
(cond-expand
((or scheme48 scsh)
(define srl:char-nl (ascii->char 10)))
(else
(define srl:char-nl (integer->char 10))))
(define srl:newline (string srl:char-nl))
(define (srl:select-kids test-pred?)
(cond
((null? node) node)
((symbol? (car node))
(filter test-pred? (cdr node)))
(else
(srl:map-append (srl:select-kids test-pred?) node)))))
Separates the list into two lists with respect to the predicate
Returns : ( values )
res - lst2 - contains the remaining members of the input lst
(define (srl:separate-list pred? lst)
(let loop ((lst lst)
(satisfy '())
(rest '()))
(cond
((null? lst)
(values (reverse satisfy) (reverse rest)))
the first member satisfies the predicate
(loop (cdr lst)
(cons (car lst) satisfy) rest))
(else
(loop (cdr lst)
satisfy (cons (car lst) rest))))))
(define (srl:clean-fragments fragments)
(reverse
(let loop ((fragments fragments) (result '()))
(cond
((null? fragments) result)
((null? (car fragments)) (loop (cdr fragments) result))
((pair? (car fragments))
(loop (cdr fragments)
(loop (car fragments) result)))
(else
(loop (cdr fragments)
(cons (car fragments) result)))))))
that have no more than two levels of nesting
fragments - level1 : : = string | ( listof string )
(define (srl:display-fragments-2nesting fragments-level2 port)
(for-each
(lambda (level1)
(if (pair? level1)
(for-each (lambda (x) (display x port))
level1)
(display level1 port)))
fragments-level2))
Splits an SXML ` name ' into namespace id / uri and local part
(define (srl:split-name name)
(let* ((name-str (symbol->string name))
(lng (string-length name-str)))
(let iter ((i (- lng 1)))
(cond
(cons #f name-str))
((char=? (string-ref name-str i) #\:)
(cons (substring name-str 0 i)
(substring name-str (+ i 1) lng)))
(else
(iter (- i 1)))))))
Converts SXML atomic object to a string . Keeps non - atomic object unchanged .
A simplified analogue of applying the XPath ` string ( . ) ' function to atomic
(define (srl:atomic->string obj)
(cond
(string? obj)) obj)
((number? obj)
(number->string obj))
((boolean? obj)
(if obj "true" "false"))
obj)))
Whether an SXML element is empty
(define (srl:empty-elem? elem)
(pair? (cadr elem)) (eq? (caadr elem) '@))
name , attributes , and SXML 2.X aux - list
(null? (cdddr elem))
(pair? (caddr elem)) (eq? (caaddr elem) '@@))))
Handling SXML namespaces
< namespace - assoc > is defined in the SXML specification as
(define-constant srl:conventional-ns-prefixes
'((dc . "/")
(fo . "")
(rdf . "-rdf-syntax-ns#")
(rng . "")
(xlink . "")
(xqx . "")
(xsd . "")
(xsi . "-instance")
(xsl . "")))
Returns ( listof < namespace - assoc > ) for the given SXML element
(define (srl:namespace-assoc-for-elem elem)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
(append
compatibility with SXML 3.0
(lambda (node) (and (pair? node) (eq? (car node) '@))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem))
compatibility with SXML 2.X
(lambda (node) (and (pair? node) (eq? (car node) '@@))))
elem)))))
Returns ( listof < namespace - assoc > ) for the SXML document node
(define (srl:ns-assoc-for-top doc)
((srl:select-kids (lambda (node) (pair? node)))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '*NAMESPACES*))))
((srl:select-kids
(lambda (node)
After sequence normalization [ 1 ] , the SXML 3.0 aux - list is used
(and (pair? node) (eq? (car node) '@))))
doc))))
namespace - assoc - lst : : = ( listof < namespace - assoc > )
Returns : ( listof ( cons original - prefix " URI " ) )
(define (srl:extract-original-prefix-binding namespace-assoc-lst)
(map
(lambda (triple) (cons (caddr triple) (cadr triple)))
(lambda (memb) (= (length memb) 3))
namespace-assoc-lst)))
xml : space attribute probably presented for the given SXML element ` elem '
space - preserve ? : : = # t | # f - whether the SXML subtree inherits the
(define (srl:update-space-specifier elem space-preserve?)
(let ((xml-space-val
((srl:select-kids string?)
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) 'xml:space))))
((srl:select-kids
(lambda (node) (and (pair? node) (eq? (car node) '@))))
elem)))))
(cond
space-preserve?)
((string=? (car xml-space-val) "preserve")
#t)
((string=? (car xml-space-val) "default")
#f)
(else space-preserve?))))
Sect . 2 in [ 1 ]
Performs sequence normalization in accordance with [ 1 ]
Returns the SXML document node
(define (srl:normalize-sequence node-or-sequence)
(letrec
((normaliz-step-1
sequence S1 that consists of a zero - length string . Otherwise , copy
the new sequence S1 . " [ 1 ]
(lambda (node-or-seq)
(cond
'(""))
(list node-or-seq))
(else
node-or-seq))))
(normaliz-step-2
S2 . " [ 1 ]
(lambda (seq)
(map
(lambda (item) (srl:atomic->string item))
seq)))
(normaliz-step-3
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
(adjacent (cdr src)
(cons (car src) (cons " " adj-strs))))
(else
(loop (cdr src)
(cons (car src)
(cons (srl:apply-string-append adj-strs)
res)))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
Step 4 from [ 1 ] is redundant for SXML , since SXML text nodes are not
(normaliz-step-5
sequence . The new sequence is S5 . " [ 1 ]
(lambda (seq)
(cond
((null? seq)
seq)
((and (pair? (car seq)) (eq? (caar seq) '*TOP*))
(append (cdar seq) (normaliz-step-5 (cdr seq))))
(else
(cons (car seq) (normaliz-step-5 (cdr seq)))))))
(normaliz-step-6
of zero length are dropped . Copy all other items to the new sequence .
The new sequence is S6 . " [ 1 ]
inserted and the zero - length strings are removed
(lambda (seq)
(let loop ((src (reverse seq))
(res '()))
(cond
((null? src)
res)
((string? (car src))
(if
(loop (cdr src) res)
(let adjacent ((src (cdr src))
(adj-strs (list (car src))))
(cond
(cons (srl:apply-string-append adj-strs) res))
((string? (car src))
(adjacent (cdr src)
(cons (car src) adj-strs)))
(else
(loop (cdr src)
(cons (car src)
(cons
(srl:apply-string-append adj-strs)
res))))))))
(else
(loop (cdr src)
(cons (car src) res)))))))
(normaliz-step-7
document node . " [ 1 ]
On this step , we should take care of SXML aux - lists
attribute nodes in a sequence . By nature of SXML 3.0 , however ,
(lambda (seq)
(call-with-values
(lambda ()
(srl:separate-list
(lambda (item)
(and (pair? item)
aux - list in SXML 2.X
aux - list in SXML 3.0
)))
seq))
(lambda (aux-lists body)
(if
(null? aux-lists)
`(*TOP* ,@body)
`(*TOP*
(@ ,@(srl:map-append cdr aux-lists))
,@body)))))))
TODO : According to [ 1 ] , if the normalized sequence does not have exactly
one element node node child or has text node children , then the
(normaliz-step-7
(normaliz-step-6
(normaliz-step-5
(normaliz-step-3
(normaliz-step-2
(normaliz-step-1 node-or-sequence))))))))
Escaping in accordance with [ 1 ] and [ 2 ] :
[ 2 ] Extensible Markup Language ( XML ) 1.0 ( Third Edition )
W3C Recommendation 04 February 2004
-xml-20040204
CDATA sections
Returns # f if a given character ` ch ' is in XML character range [ 2 ]
(define (srl:xml-char-escaped ch)
(let ((code (char->integer ch)))
(if (or (= code 9) (= code 10) (= code 13)
(and (>= code 32) (<= code 55295))
(and (>= code 57344) (<= code 65533))
(>= code 65536))
#f
(string-append "&#" (number->string code) ";"
))))
Represents a given string ` str ' as a CDATA section
(define (srl:string->cdata-section str)
(let ((flush-buffer
If a ` buffer ' is non - empty , converts it to a CDATA string and
(lambda (buffer res)
(if (null? buffer)
res
(cons
(string-append
"<![CDATA[" (list->string (reverse buffer)) "]]>")
res)))))
(let loop ((src (string->list str))
(buffer '())
(res '("")))
(cond
((null? src)
(srl:apply-string-append
(reverse (flush-buffer buffer res))))
((srl:xml-char-escaped (car src))
=> (lambda (charref)
(loop (cdr src)
'()
(cons charref (flush-buffer buffer res)))))
((and (char=? (car src) #\])
(not (null? buffer))
(char=? (car buffer) #\]))
(loop (cdr src)
'()
(flush-buffer (cdr buffer) res))))
(loop (cdr src)
(cons (car src) buffer)
res))))))
Associative lists of characters to be escaped in XML character data and
attribute values respectively [ 2 ]
(define *srl:escape-alist-char-data*
(make-parameter '((#\& . "&") (#\< . "<") (#\> . ">"))))
(define *srl:escape-alist-att-value*
(make-parameter
(,srl:char-nl . " "))
(*srl:escape-alist-char-data*))))
(define *srl:escape-alist-html-att*
(make-parameter
escape - alist : : = ( listof ( cons char string ) )
(define (srl:string->escaped str escape-alist html-method?)
(let loop ((src (string->list str))
(adj-chars '())
(res '()))
(cond
((null? src)
(srl:apply-string-append
(reverse (cons (list->string (reverse adj-chars))
res))))
=> (lambda (pair)
(if
Subsect . 7.2 in [ 1 ] :
(and (char=? (car src) #\&)
html-method?
(not (null? (cdr src))) (char=? (cadr src) #\{))
(loop (cdr src)
(cons (car src) adj-chars)
res)
(loop (cdr src)
'()
(cons (cdr pair)
(cons (list->string (reverse adj-chars))
res))))))
((srl:xml-char-escaped (car src))
=> (lambda (esc)
(loop (cdr src)
'()
(cons esc
(cons (list->string (reverse adj-chars))
res)))))
(else
(loop (cdr src)
(cons (car src) adj-chars)
res)))))
(define (srl:string->char-data str)
(srl:string->escaped str (*srl:escape-alist-char-data*) #f))
(define (srl:string->att-value str)
(srl:string->escaped str (*srl:escape-alist-att-value*) #f))
(define (srl:string->html-att str)
(srl:string->escaped str (*srl:escape-alist-html-att*) #t))
[ 3 ] .
HtmlPrag : Pragmatic Parsing and Emitting of HTML using SXML and SHTML
Version 0.16 , 2005 - 12 - 18 , /
characters . The syntax is ( & val ) , where is a symbol or string naming
value of the character . " [ 3 ]
: : = symbol | string | number
(define (srl:shtml-entity->char-data entity)
(if
(= (length entity) 2)
(let ((val (cadr entity)))
(cond
((symbol? val) (string-append "&" (symbol->string val) ";")
)
((string? val) (string-append "&" val ";")
)
((and (number? val) (integer? val) (> val 0))
(string-append "&#" (number->string val) ";")
)
"")))
""))
declared - ns - prefixes : : = ( listof ( cons prefix - string namespace - uri ) )
(define (srl:qname->string prefix-string local-part)
(if prefix-string
(string-append prefix-string ":" local-part)
local-part))
(define (srl:attribute->str-lst prefix-string local-part att-value method)
(let ((attval (srl:atomic->string att-value)))
(cond
(prefix-string
(list " " prefix-string ":" local-part "=\""
((if (eq? method 'html)
srl:string->html-att
srl:string->att-value) attval)
"\""))
((eq? method 'html)
Change for Sagittarius , we do properly
(if (memq (string->symbol local-part) (*srl:boolean-attributes*))
(list " " local-part)
(list " " local-part "=\"" (srl:string->html-att attval) "\"")))
(list " " local-part "=\"" (srl:string->att-value attval) "\"")))))
ATTENTION : character escaping for namespace URI may be improper , study this
(define (srl:namespace-decl->str-lst prefix-string namespace-uri)
Sagittarius
(if prefix-string
(list " xmlns:" prefix-string "=\""
(srl:string->att-value namespace-uri) "\"")
(list " xmlns" "=\"" (srl:string->att-value namespace-uri) "\"")))
According to SXML specification ,
(define (srl:comment->str-lst comment-node)
(let ((proper-string-in-comment?
ending in --- > . " [ 2 ]
(lambda (str)
(let ((lng (string-length str)))
(or
empty string allowed in comment [ 2 ]
(and
(not (char=? (string-ref str 0) #\-))
(let iter ((i 1)
(prev-hyphen? #f))
(cond
((>= i lng)
)
((char=? (string-ref str i) #\-)
(if prev-hyphen?
#f
(iter (+ i 1) #t)))
(else
(iter (+ i 1) #f))))))))))
(if (and (= (length comment-node) 2)
(string? (cadr comment-node))
(proper-string-in-comment? (cadr comment-node)))
(list "<!--" (cadr comment-node) "-->")
)))
According to SXML specification ,
Subsect 7.3 in [ 1 ] : " The HTML output method MUST terminate processing
(define (srl:processing-instruction->str-lst pi-node method)
(let ((string-not-contain-charlist?
(lambda (str char-lst)
(let ((lng (string-length str)))
(or
(let iter ((i 0)
(pattern char-lst))
(cond
((>= i lng) #t)
((char=? (string-ref str i) (car pattern))
(iter (+ i 1) (cdr pattern))))
(else
(iter (+ i 1) char-lst)))))))))
(if
(or (null? (cdr pi-node))
no target = > ill - formed PI
(let ((content (filter string? (cddr pi-node))))
(cond
(list "<?" (symbol->string (cadr pi-node))
(if (eq? method 'html) ">" "?>")))
Subsect . 7.3 in [ 1 ] : " It is a serialization error to use the HTML
(string-not-contain-charlist?
(car content)
(if (eq? method 'html) '(#\>) '(#\? #\>))))
(list "<?" (symbol->string (cadr pi-node)) " " (car content)
(if (eq? method 'html) ">" "?>")))
'()))))))
Sagittarius specific
In some cases , we want to hold broken / partial HTML on SXML tree
e.g. node . This special marker holds this kind of content
(define (srl:raw-html->str-lst raw-html-node)
(if (and (= (length raw-html-node) 2)
(for-all string? (cdr raw-html-node)))
(cdr raw-html-node)
'()))
SXML element
namespace - uri - the namespace URI for the given ` name ' , # f if the name has no
namespace URI
(define (srl:name->qname-components
name ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((use-ns-id-or-generate-prefix
(lambda (ns-id)
(if
(not (assq (string->symbol ns-id) ns-prefix-assig))
(not (assoc ns-id declared-ns-prefixes)))
ns-id
(let loop ((i 1))
(let ((candidate (string-append "prfx" (number->string i))))
(if (or (assoc candidate declared-ns-prefixes)
(assq (string->symbol candidate) ns-prefix-assig))
(loop (+ i 1))
candidate))))))
(n-parts (srl:split-name name)))
(cond
Sagittarius , handling * default * namespace
(cond ((or (assq '*default* namespace-assoc)
(assq '*default* ns-prefix-assig)) =>
(lambda (slot)
(values #f (cadr slot) (cdr n-parts)
(not (srl:assoc-cdr-string= (cadr slot)
declared-ns-prefixes)))))
(else
#f))))
(values (car n-parts) ""
(cdr n-parts) #f))
(else
(call-with-values
(lambda ()
(cond
namespace-assoc)
=> (lambda (lst)
(values (cadr lst) (car n-parts))))
first part of a name is a namespace URI
(values (car n-parts) #f))))
(lambda (namespace-uri ns-id)
(cond
((srl:assoc-cdr-string= namespace-uri declared-ns-prefixes)
=> (lambda (pair)
Prefix for that namespace URI already declared
(values (car pair) namespace-uri (cdr n-parts) #f)))
(values
(cond
((srl:assoc-cdr-string= namespace-uri ns-prefix-assig)
=> (lambda (pair)
(let ((candidate (symbol->string (car pair))))
(if
(assoc candidate declared-ns-prefixes)
(use-ns-id-or-generate-prefix ns-id)
candidate))))
(else
(use-ns-id-or-generate-prefix ns-id)))
namespace-uri
(cdr n-parts)
)))))))))
Constructs start and end tags for an SXML element ` elem '
start - tag : : = ( string )
end - tag : : = ( string ) or # f for empty element
TODO : escape URI attributes for HTML
(define (srl:construct-start-end-tags
elem method
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(let ((ns-assoc-here (srl:namespace-assoc-for-elem elem))
(empty? (srl:empty-elem? elem)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding ns-assoc-here)
ns-prefix-assig))
(namespace-assoc
(append ns-assoc-here namespace-assoc)))
(call-with-values
(lambda ()
(car elem) ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (elem-prefix elem-uri elem-local elem-decl-required?)
(let loop ((attrs
(reverse
((srl:select-kids
not SXML 3.0 aux - list
(and (pair? node) (not (eq? (car node) '@)))))
((srl:select-kids
(lambda (node)
(and (pair? node) (eq? (car node) '@))))
elem))))
(start-tag
(if
(or (not empty?)
(and (eq? method 'html)
(not elem-prefix)
(srl:member-ci
elem-local
(*srl:empty-elements*))))
'(">") '(" />")))
(ns-prefix-assig ns-prefix-assig)
(namespace-assoc namespace-assoc)
(declared-ns-prefixes
(if elem-decl-required?
(cons (cons elem-prefix elem-uri)
declared-ns-prefixes)
declared-ns-prefixes)))
(if
(let ((elem-name (srl:qname->string elem-prefix elem-local)))
(values
(cons "<"
(cons elem-name
(if
elem-decl-required?
(cons
(srl:namespace-decl->str-lst elem-prefix elem-uri)
start-tag)
start-tag)))
(if empty? #f
(list "</" elem-name ">"))
ns-prefix-assig
namespace-assoc
declared-ns-prefixes))
(call-with-values
(lambda ()
(srl:name->qname-components
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (attr-prefix attr-uri attr-local attr-decl-required?)
(let ((start-tag
(cons
(srl:attribute->str-lst
attr-prefix attr-local
attr-local
(cadar attrs))
method)
start-tag)))
(loop
(cdr attrs)
(if attr-decl-required?
(cons (srl:namespace-decl->str-lst attr-prefix attr-uri)
start-tag)
start-tag)
ns-prefix-assig
namespace-assoc
(if attr-decl-required?
(cons (cons attr-prefix attr-uri) declared-ns-prefixes)
declared-ns-prefixes))))))))))))
Recursively walking the tree of SXML elements
indentation : : = ( string ) or # f - a list of whitespace strings
cdata - section - elements : : = ( listof symbol ) - list of element names whose
child nodes are to be output with CDATA section
(define (srl:node->nested-str-lst-recursive
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(text-node-handler (srl:atomic->string node))
((*COMMENT*)
(srl:comment->str-lst node))
((*PI*)
(srl:processing-instruction->str-lst node method))
((&)
(srl:shtml-entity->char-data node))
recovering for non - SXML nodes
'())
((*RAW-HTML*)
(srl:raw-html->str-lst node))
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(if
start-tag
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
(values #f #f))
((or space-preserve?
(lambda (node) (not (pair? node)))
content))
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(if
indent-here
(append
start-tag
(map
(lambda (kid)
(list
indent-here
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(cons srl:newline
(cons (cdr indentation) end-tag)))
(append
start-tag
(map
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler))
content)
end-tag))))))))))))
(define (srl:display-node-out-recursive
node port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indentation space-preserve?
cdata-section-elements text-node-handler)
(if
(display (text-node-handler (srl:atomic->string node)) port)
((*COMMENT*)
(for-each
(lambda (x) (display x port))
(srl:comment->str-lst node)))
((*PI*)
(for-each
(lambda (x) (display x port))
(srl:processing-instruction->str-lst node method)))
((&)
(display (srl:shtml-entity->char-data node) port))
recovering for non - SXML nodes
#f)
((*RAW-HTML*)
(for-each (lambda (x) (display x port))
(srl:raw-html->str-lst node)))
(call-with-values
(lambda ()
(srl:construct-start-end-tags
node method
ns-prefix-assig namespace-assoc declared-ns-prefixes))
(lambda (start-tag end-tag
ns-prefix-assig namespace-assoc declared-ns-prefixes)
(begin
(srl:display-fragments-2nesting start-tag port)
(if
(let ((space-preserve?
(srl:update-space-specifier node space-preserve?))
(text-node-handler
(cond
((memq (car node) cdata-section-elements)
srl:string->cdata-section)
((and (eq? method 'html)
(srl:member-ci (symbol->string (car node))
'("script" "style")))
(lambda (str) str))
(else
srl:string->char-data)))
(content ((srl:select-kids
TODO : support SXML entities
(not (and (pair? node)
(memq (car node) '(@ @@ *ENTITY*))))))
node)))
(call-with-values
(lambda ()
(cond
((or (not indentation)
(and (eq? method 'html)
(srl:member-ci
(symbol->string (car node))
'("pre" "script" "style" "textarea"))))
(values #f #f))
((or space-preserve?
(lambda (node) (not (pair? node)))
content))
(values #f indentation))
(else
(values (cons srl:newline indentation)
(cons (car indentation) indentation)))))
(lambda (indent-here indent4recursive)
(begin
(if
indent-here
(lambda (kid)
(begin
(for-each
(lambda (x) (display x port))
indent-here)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc declared-ns-prefixes
indent4recursive space-preserve?
cdata-section-elements text-node-handler)))
content)
(if indent-here
(begin
(display srl:newline port)
(for-each
(lambda (x) (display x port))
(cdr indentation))))
(for-each
(lambda (x) (display x port))
end-tag)))))))))))))
Creates the serialized representation for the XML declaration
(define (srl:make-xml-decl version standalone)
(let ((version (if (number? version) (number->string version) version)))
(if (eq? standalone 'omit)
(list "<?xml version='" version "'?>")
(list "<?xml version='" version "' standalone='"
(symbol->string standalone) "'?>"))))
(define (srl:top->nested-str-lst doc
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(let* ((namespace-assoc (srl:ns-assoc-for-top doc))
(ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig))
(serialized-content
(map
(if
(lambda (kid)
(list
srl:newline
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:node->nested-str-lst-recursive
kid method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))))
(if (or (eq? method 'html) omit-xml-declaration?)
(if (and indent (not (null? serialized-content)))
(cons (cadar serialized-content) (cdr serialized-content))
serialized-content)
(list (srl:make-xml-decl version standalone) serialized-content))))
(define (srl:display-top-out doc port
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
no XML declaration was displayed ?
(if (not (or (eq? method 'html) omit-xml-declaration?))
(begin
(lambda (x) (display x port))
(srl:make-xml-decl version standalone))
#f)
#t))
((srl:select-kids
TODO : support SXML entities
(not (and
(pair? node) (memq (car node) '(@ @@ *ENTITY*))))))
doc))
(namespace-assoc (srl:ns-assoc-for-top doc)))
(let ((ns-prefix-assig
(append
(srl:extract-original-prefix-binding namespace-assoc)
ns-prefix-assig)))
(cond
((and indent no-xml-decl?)
(for-each
(lambda (kid put-newline?)
(begin
(if put-newline?
(display srl:newline port))
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data)))
content
(cons #f (cdr content)))))
(else
(for-each
(if
(lambda (kid)
(begin
(display srl:newline port)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indentation #f
cdata-section-elements srl:string->char-data))))
(lambda (kid)
(srl:display-node-out-recursive
kid port method
ns-prefix-assig namespace-assoc '()
indent #f
cdata-section-elements srl:string->char-data)))
content))))))
Interface
additional serialization parameters , the functions ` srl : sxml->string ' and
` srl : display - sxml ' specified in this subsections may have a different number
cdata - section - elements : : = ( - name )
ns - prefix - assign : : = ( listof ( cons prefix - symbol namespace - uri - string ) )
version : : = number | string
(define (srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:apply-string-append
(srl:clean-fragments
(srl:top->nested-str-lst (srl:normalize-sequence sxml-obj)
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version))))
(define (srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(if
(let ((out (open-output-file port-or-filename)))
(begin
(srl:display-top-out (srl:normalize-sequence sxml-obj) out
cdata-section-elements
(if (and indent (not (string? indent)))
" " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)
(close-output-port out)))
(srl:display-top-out (srl:normalize-sequence sxml-obj) port-or-filename
cdata-section-elements
(if (and indent (not (string? indent))) " " indent)
method ns-prefix-assig
omit-xml-declaration? standalone version)))
procedure srl : parameterizable : : SXML - OBJ [ PORT ] { PARAM } * - >
sxml - obj - an SXML object to serialize
1 . cdata - section - elements
value : : = ( - elem - name )
sxml - elem - name : : = symbol
2 . indent
3 . method
4 . ns - prefix - assig
value : : = ( listof ( cons prefix namespace - uri ) )
5 . omit - xml - declaration ?
6 . standalone
7 . version
( srl : parameterizable
(define (srl:parameterizable sxml-obj . port-or-filename+params)
(call-with-values
(lambda ()
(if (and (not (null? port-or-filename+params))
(or (output-port? (car port-or-filename+params))
(string? (car port-or-filename+params))))
(values (car port-or-filename+params) (cdr port-or-filename+params))
(values #f port-or-filename+params)))
(lambda (port-or-filename params)
(let loop ((params params)
(cdata-section-elements '())
(indent " ")
(method 'xml)
(ns-prefix-assig srl:conventional-ns-prefixes)
(omit-xml-declaration? #t)
(standalone 'omit)
(version "1.0"))
(cond
(if port-or-filename
(srl:display-sxml sxml-obj port-or-filename
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)
(srl:sxml->string sxml-obj
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version)))
(null? (cdar params)))
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))
(else
(let ((prm-value (cdar params)))
(case (caar params)
((cdata-section-elements)
(loop (cdr params)
(if (list? prm-value) prm-value cdata-section-elements)
indent method ns-prefix-assig
omit-xml-declaration? standalone version))
((indent)
(loop (cdr params)
cdata-section-elements
(cond
((boolean? prm-value)
(if prm-value " " prm-value))
((string? prm-value) prm-value)
((eq? prm-value 'yes) " ")
((eq? prm-value 'no) #f)
(else indent))
method ns-prefix-assig
omit-xml-declaration? standalone version))
((method)
(loop (cdr params)
cdata-section-elements indent
(if (or (eq? prm-value 'xml) (eq? prm-value 'html))
prm-value method)
ns-prefix-assig
omit-xml-declaration? standalone version))
((ns-prefix-assig)
(loop (cdr params)
cdata-section-elements indent method
(if (and (list? prm-value)
(lambda (x) (not (pair? x)))
prm-value)))
(append prm-value ns-prefix-assig)
ns-prefix-assig)
omit-xml-declaration? standalone version))
((omit-xml-declaration)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
(cond
((boolean? prm-value) prm-value)
((eq? prm-value 'yes) #t)
((eq? prm-value 'no) #f)
(else indent))
standalone version))
((standalone)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig omit-xml-declaration?
(cond
((memv prm-value '(yes no omit))
prm-value)
((boolean? prm-value)
(if prm-value 'yes 'no))
(else standalone))
version))
((version)
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone
(if (or (string? prm-value) (number? prm-value))
prm-value version)))
(else
(loop (cdr params)
cdata-section-elements indent
method ns-prefix-assig
omit-xml-declaration? standalone version))))))))))
procedure srl : sxml->xml : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
Serializes the ` sxml - obj ' into XML , with indentation to facilitate
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
(define (srl:sxml->xml sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #t 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->xml - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
Serializes the ` sxml - obj ' into XML , without indentation .
(define (srl:sxml->xml-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")
(srl:display-sxml sxml-obj (car port-or-filename) '() #f 'xml
srl:conventional-ns-prefixes #t 'omit "1.0")))
procedure srl : sxml->html : : SXML - OBJ [ PORT - OR - FILENAME ] - > STRING|unspecified
Serializes the ` sxml - obj ' into HTML , with indentation to facilitate
sxml - obj - an SXML object ( a node or a nodeset ) to be serialized
(define (srl:sxml->html sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #t 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #t 'html '() #t 'omit "4.0")))
procedure srl : sxml->html - noindent : : SXML - OBJ [ PORT - OR - FILENAME ] - >
Serializes the ` sxml - obj ' into HTML , without indentation .
(define (srl:sxml->html-noindent sxml-obj . port-or-filename)
(if (null? port-or-filename)
(srl:sxml->string sxml-obj '() #f 'html '() #t 'omit "4.0")
(srl:display-sxml sxml-obj (car port-or-filename)
'() #f 'html '() #t 'omit "4.0")))
)
|
6fc9add2db5a281d628c2db694d1830c5aa493588a7bfda96699356fca75a9e4 | bufferswap/ViralityEngine | hash-table-nested.lisp | (in-package #:vutils)
(defun ensure-nested-hash-table (table tests keys)
"Walk down the nested hash table `TABLE` ensuring that we have the correct
number of hash tables made (one less than the list of keys `KEYS`) with the
correct tests, received from the list of tests `TESTS`. NOTE: The first element
of `TESTS` is the test function for `TABLE` itself."
;; TODO: This looks painful for performance. Oh well, we'll see if the
;; profiler actually cares or not. It is likely that these won't be nested
;; deeply. Also, the algorithm is slightly painful, but the deal is that we
;; can't make a hash table containing the last key, since the last key is
;; where we'll either look something up or store it.
(loop :with key-count = (length keys)
:with current = table
:for test :in (cdr tests)
:for key :in keys
:for i :below key-count
:for last = (= i (1- key-count))
:do (unless (nth-value 1 (href current key))
;; If the key doesn't exist, we make a new hash table and store it
;; at the key unless it is the last entry, in which case we do
;; nothing.
(unless last
(setf (href current key)
(dict test))))
;; The key is potentially newly minted.
(setf current (href current key)))
table)
(defmacro make-nested-dict (test-func &rest keys)
`(dict ,test-func ,@(mapcan (lambda (x) `(,x (dict ,test-func))) (copy-seq keys))))
| null | https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/support/vutils/src/hash-table-nested.lisp | lisp | TODO: This looks painful for performance. Oh well, we'll see if the
profiler actually cares or not. It is likely that these won't be nested
deeply. Also, the algorithm is slightly painful, but the deal is that we
can't make a hash table containing the last key, since the last key is
where we'll either look something up or store it.
If the key doesn't exist, we make a new hash table and store it
at the key unless it is the last entry, in which case we do
nothing.
The key is potentially newly minted. | (in-package #:vutils)
(defun ensure-nested-hash-table (table tests keys)
"Walk down the nested hash table `TABLE` ensuring that we have the correct
number of hash tables made (one less than the list of keys `KEYS`) with the
correct tests, received from the list of tests `TESTS`. NOTE: The first element
of `TESTS` is the test function for `TABLE` itself."
(loop :with key-count = (length keys)
:with current = table
:for test :in (cdr tests)
:for key :in keys
:for i :below key-count
:for last = (= i (1- key-count))
:do (unless (nth-value 1 (href current key))
(unless last
(setf (href current key)
(dict test))))
(setf current (href current key)))
table)
(defmacro make-nested-dict (test-func &rest keys)
`(dict ,test-func ,@(mapcan (lambda (x) `(,x (dict ,test-func))) (copy-seq keys))))
|
85aa0e1f9918972a5816121d4d117c1441ce0ec7e7bcb01cc7d516dc259fe793 | patricoferris/ocaml-multicore-monorepo | status.ml | ----------------------------------------------------------------------------
* Copyright ( c ) 2017 Inhabited Type LLC .
* Copyright ( c ) 2019 .
*
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions
* are met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . Neither the name of the author nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ` ` AS IS '' AND ANY EXPRESS
* OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED . IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
* DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION )
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
* STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE .
* ---------------------------------------------------------------------------
* Copyright (c) 2017 Inhabited Type LLC.
* Copyright (c) 2019 Antonio N. Monteiro.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the author nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*---------------------------------------------------------------------------*)
From RFC7540§8.1.1 :
* HTTP/2 removes support for the 101 ( Switching Protocols ) informational
* status code ( [ RFC7231 ] , Section 6.2.2 ) .
*
* Note : While the above is true , we do n't enforce in this library , as it
* makes unifying types with http / af much easier . ` H2.Status.t ` is , thus , a
* strict superset of ` Httpaf . Status.t ` .
* HTTP/2 removes support for the 101 (Switching Protocols) informational
* status code ([RFC7231], Section 6.2.2).
*
* Note: While the above is true, we don't enforce in this library, as it
* makes unifying types with http/af much easier. `H2.Status.t` is, thus, a
* strict superset of `Httpaf.Status.t`. *)
include (
Httpaf.Status :
module type of Httpaf.Status
with type client_error := Httpaf.Status.client_error
and type standard := Httpaf.Status.standard
and type t := Httpaf.Status.t)
type client_error =
[ Httpaf.Status.client_error
From RFC7540§9.1.2 :
* The 421 ( Misdirected Request ) status code indicates that the request
* was directed at a server that is not able to produce a response . This
* can be sent by a server that is not configured to produce responses
* for the combination of scheme and authority that are included in the
* request URI .
* The 421 (Misdirected Request) status code indicates that the request
* was directed at a server that is not able to produce a response. This
* can be sent by a server that is not configured to produce responses
* for the combination of scheme and authority that are included in the
* request URI. *)
`Misdirected_request
]
type standard =
[ Httpaf.Status.standard
| client_error
]
type t =
[ standard
| `Code of int
]
(* Note: The value for reason phrases is never actually serialized to the
* input or output channels.
*
* From RFC7540§8.1.2.4:
* HTTP/2 does not define a way to carry the version or reason phrase that is
* included in an HTTP/1.1 status line. *)
let default_reason_phrase = function
| `Misdirected_request ->
"Misdirected Request"
| #Httpaf.Status.standard as t ->
Httpaf.Status.default_reason_phrase t
let to_code = function
| `Misdirected_request ->
421
| #Httpaf.Status.t as t ->
Httpaf.Status.to_code t
let unsafe_of_code = function
| 421 ->
`Misdirected_request
| c ->
(Httpaf.Status.unsafe_of_code c :> t)
let of_code = function
| 421 ->
`Misdirected_request
| c ->
(Httpaf.Status.of_code c :> t)
let is_informational = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_informational t
let is_successful = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_successful t
let is_redirection = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_redirection t
let is_client_error = function
| `Misdirected_request ->
true
| #Httpaf.Status.t as t ->
Httpaf.Status.is_client_error t
let is_server_error = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_server_error t
let is_error = function
| `Misdirected_request ->
true
| #Httpaf.Status.t as t ->
Httpaf.Status.is_error t
let to_string = function
| `Misdirected_request ->
"421"
| #Httpaf.Status.t as t ->
Httpaf.Status.to_string t
let of_string x = of_code (int_of_string x)
let pp_hum fmt t = Format.fprintf fmt "%u" (to_code t)
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/dream/src/vendor/h2/lib/status.ml | ocaml | Note: The value for reason phrases is never actually serialized to the
* input or output channels.
*
* From RFC7540§8.1.2.4:
* HTTP/2 does not define a way to carry the version or reason phrase that is
* included in an HTTP/1.1 status line. | ----------------------------------------------------------------------------
* Copyright ( c ) 2017 Inhabited Type LLC .
* Copyright ( c ) 2019 .
*
* All rights reserved .
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions
* are met :
*
* 1 . Redistributions of source code must retain the above copyright
* notice , this list of conditions and the following disclaimer .
*
* 2 . Redistributions in binary form must reproduce the above copyright
* notice , this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution .
*
* 3 . Neither the name of the author nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ` ` AS IS '' AND ANY EXPRESS
* OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED . IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
* DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION )
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT ,
* STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE .
* ---------------------------------------------------------------------------
* Copyright (c) 2017 Inhabited Type LLC.
* Copyright (c) 2019 Antonio N. Monteiro.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the author nor the names of his contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*---------------------------------------------------------------------------*)
From RFC7540§8.1.1 :
* HTTP/2 removes support for the 101 ( Switching Protocols ) informational
* status code ( [ RFC7231 ] , Section 6.2.2 ) .
*
* Note : While the above is true , we do n't enforce in this library , as it
* makes unifying types with http / af much easier . ` H2.Status.t ` is , thus , a
* strict superset of ` Httpaf . Status.t ` .
* HTTP/2 removes support for the 101 (Switching Protocols) informational
* status code ([RFC7231], Section 6.2.2).
*
* Note: While the above is true, we don't enforce in this library, as it
* makes unifying types with http/af much easier. `H2.Status.t` is, thus, a
* strict superset of `Httpaf.Status.t`. *)
include (
Httpaf.Status :
module type of Httpaf.Status
with type client_error := Httpaf.Status.client_error
and type standard := Httpaf.Status.standard
and type t := Httpaf.Status.t)
type client_error =
[ Httpaf.Status.client_error
From RFC7540§9.1.2 :
* The 421 ( Misdirected Request ) status code indicates that the request
* was directed at a server that is not able to produce a response . This
* can be sent by a server that is not configured to produce responses
* for the combination of scheme and authority that are included in the
* request URI .
* The 421 (Misdirected Request) status code indicates that the request
* was directed at a server that is not able to produce a response. This
* can be sent by a server that is not configured to produce responses
* for the combination of scheme and authority that are included in the
* request URI. *)
`Misdirected_request
]
type standard =
[ Httpaf.Status.standard
| client_error
]
type t =
[ standard
| `Code of int
]
let default_reason_phrase = function
| `Misdirected_request ->
"Misdirected Request"
| #Httpaf.Status.standard as t ->
Httpaf.Status.default_reason_phrase t
let to_code = function
| `Misdirected_request ->
421
| #Httpaf.Status.t as t ->
Httpaf.Status.to_code t
let unsafe_of_code = function
| 421 ->
`Misdirected_request
| c ->
(Httpaf.Status.unsafe_of_code c :> t)
let of_code = function
| 421 ->
`Misdirected_request
| c ->
(Httpaf.Status.of_code c :> t)
let is_informational = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_informational t
let is_successful = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_successful t
let is_redirection = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_redirection t
let is_client_error = function
| `Misdirected_request ->
true
| #Httpaf.Status.t as t ->
Httpaf.Status.is_client_error t
let is_server_error = function
| `Misdirected_request ->
false
| #Httpaf.Status.t as t ->
Httpaf.Status.is_server_error t
let is_error = function
| `Misdirected_request ->
true
| #Httpaf.Status.t as t ->
Httpaf.Status.is_error t
let to_string = function
| `Misdirected_request ->
"421"
| #Httpaf.Status.t as t ->
Httpaf.Status.to_string t
let of_string x = of_code (int_of_string x)
let pp_hum fmt t = Format.fprintf fmt "%u" (to_code t)
|
abcebd190aaab65e4d628f24314ecbb792df17e597e2179e46f1212e3e35f1a8 | RichiH/git-annex | UrlContents.hs | git - annex URL contents
-
- Copyright 2014 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2014 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Types.UrlContents (
UrlContents(..),
SafeFilePath,
mkSafeFilePath,
fromSafeFilePath
) where
import Utility.Url
import Utility.Path
import System.FilePath
data UrlContents
-- An URL contains a file, whose size may be known.
-- There might be a nicer filename to use.
= UrlContents (Maybe Integer) (Maybe SafeFilePath)
-- Sometimes an URL points to multiple files, each accessible
-- by their own URL.
| UrlMulti [(URLString, Maybe Integer, SafeFilePath)]
This is a FilePath , from an untrusted source ,
-- sanitized so it doesn't contain any directory traversal tricks
-- and is always relative. It can still contain subdirectories.
-- Any unusual characters are also filtered out.
newtype SafeFilePath = SafeFilePath FilePath
deriving (Show)
mkSafeFilePath :: FilePath -> SafeFilePath
mkSafeFilePath p = SafeFilePath $ if null p' then "file" else p'
where
p' = joinPath $ filter safe $ map sanitizeFilePath $ splitDirectories p
safe s
| isDrive s = False
| s == ".." = False
| s == ".git" = False
| null s = False
| otherwise = True
fromSafeFilePath :: SafeFilePath -> FilePath
fromSafeFilePath (SafeFilePath p) = p
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Types/UrlContents.hs | haskell | An URL contains a file, whose size may be known.
There might be a nicer filename to use.
Sometimes an URL points to multiple files, each accessible
by their own URL.
sanitized so it doesn't contain any directory traversal tricks
and is always relative. It can still contain subdirectories.
Any unusual characters are also filtered out. | git - annex URL contents
-
- Copyright 2014 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2014 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Types.UrlContents (
UrlContents(..),
SafeFilePath,
mkSafeFilePath,
fromSafeFilePath
) where
import Utility.Url
import Utility.Path
import System.FilePath
data UrlContents
= UrlContents (Maybe Integer) (Maybe SafeFilePath)
| UrlMulti [(URLString, Maybe Integer, SafeFilePath)]
This is a FilePath , from an untrusted source ,
newtype SafeFilePath = SafeFilePath FilePath
deriving (Show)
mkSafeFilePath :: FilePath -> SafeFilePath
mkSafeFilePath p = SafeFilePath $ if null p' then "file" else p'
where
p' = joinPath $ filter safe $ map sanitizeFilePath $ splitDirectories p
safe s
| isDrive s = False
| s == ".." = False
| s == ".git" = False
| null s = False
| otherwise = True
fromSafeFilePath :: SafeFilePath -> FilePath
fromSafeFilePath (SafeFilePath p) = p
|
77cd6c2a51226a161a981f7795f1bd19d1c430c5d97af7dcd352f4dc72f798f1 | facebookarchive/pfff | draw_macrolevel.mli |
val draw_treemap_rectangle:
Canvas_helpers.context ->
?color:Simple_color.emacs_color option ->
?alpha:float ->
Treemap.treemap_rectangle ->
unit
| null | https://raw.githubusercontent.com/facebookarchive/pfff/ec21095ab7d445559576513a63314e794378c367/web/code_map/draw_macrolevel.mli | ocaml |
val draw_treemap_rectangle:
Canvas_helpers.context ->
?color:Simple_color.emacs_color option ->
?alpha:float ->
Treemap.treemap_rectangle ->
unit
|
|
842af066de323020b92e8b66de8ab89b24ca4a4bd3b0814c6614a73692227c4e | haskell/haskell-ide-engine | HlintParseFail.hs | # LANGUAGE TypeFamilies #
{-# LANGUAGE GADTs #-}
# LANGUAGE TypeOperators #
# LANGUAGE DataKinds #
{-# LANGUAGE TypeInType #-}
module Test where
import Data.Singletons.Prelude
import Data.Singletons.TypeLits
import Data.Type.Equality ((:~:) (..), (:~~:) (..))
data instance Sing (z :: (a :~: b)) where
SRefl :: Sing Refl +
| null | https://raw.githubusercontent.com/haskell/haskell-ide-engine/d84b84322ccac81bf4963983d55cc4e6e98ad418/test/testdata/HlintParseFail.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE TypeInType # | # LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
# LANGUAGE DataKinds #
module Test where
import Data.Singletons.Prelude
import Data.Singletons.TypeLits
import Data.Type.Equality ((:~:) (..), (:~~:) (..))
data instance Sing (z :: (a :~: b)) where
SRefl :: Sing Refl +
|
c4b556059b874e5a26a0d2c46f75555d37c26a40429866f085faadd188550728 | corecursive/sicp-study-group | ex01_15.scm | ; The sine of an angle (specified in radians) can be computer by making use of the approximation sin x ~= x if x is sufficiently small, and the trigonometric identity:
sin x = 3*sin(x/3 ) - 4*sin^3(x/3 )
to reduce the size of the arugment sin . ( For purposes of this exercise , an angle is consdiered " sufficiently small " if its magnitude is not greater than 0.1 radians . ) These ideas are incorporated in the following procedrues :
(define (sine angle)
(define (cube x)
(* x x x))
(define (p x)
(- (* 3 x) (* 4 (cube x))))
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0))))
PART A : How many times is procedure p applied when ( sine 12.15 ) is evaluated ?
( sine 12.15 )
; (p (sine (/ 12.15 3.0)))
( p ( sine 4.05 ) )
( p ( p ( sine ( / 4.05 3.0 ) ) ) )
( p ( p ( sine 1.35 ) ) )
; (p (p (p (sine (/ 1.35 3.0)))))
( p ( p ( p ( sine 0.45 ) ) ) )
; (p (p (p (p (sine (/ 0.45 3.0))))))
( p ( p ( p ( p ( sine 0.15 ) ) ) ) )
; (p (p (p (p (p (sine (/ 0.15 3.0)))))))
( p ( p ( p ( p ( p ( sine 0.05 ) ) ) ) ) )
( p ( p ( p ( p ( p 0.05 ) ) ) ) )
; ...
ANSWER : 5 times
; PART BWhat is the order of growth in space and number of steps (as a function of a) used by the process generated by the sine procedure when (sine a) is evaluated?
ANSWER : For space , I think it 's cube root ? I 'm not really sure : it 's less than linear , but I 'm not 100 % certain how . I believe the same is true for the number of steps .
| null | https://raw.githubusercontent.com/corecursive/sicp-study-group/d87da159d16d09493fd500f736c186edfeecfb83/plundaahl/exercises/ex01_15.scm | scheme | The sine of an angle (specified in radians) can be computer by making use of the approximation sin x ~= x if x is sufficiently small, and the trigonometric identity:
(p (sine (/ 12.15 3.0)))
(p (p (p (sine (/ 1.35 3.0)))))
(p (p (p (p (sine (/ 0.45 3.0))))))
(p (p (p (p (p (sine (/ 0.15 3.0)))))))
...
PART BWhat is the order of growth in space and number of steps (as a function of a) used by the process generated by the sine procedure when (sine a) is evaluated? |
sin x = 3*sin(x/3 ) - 4*sin^3(x/3 )
to reduce the size of the arugment sin . ( For purposes of this exercise , an angle is consdiered " sufficiently small " if its magnitude is not greater than 0.1 radians . ) These ideas are incorporated in the following procedrues :
(define (sine angle)
(define (cube x)
(* x x x))
(define (p x)
(- (* 3 x) (* 4 (cube x))))
(if (not (> (abs angle) 0.1))
angle
(p (sine (/ angle 3.0))))
PART A : How many times is procedure p applied when ( sine 12.15 ) is evaluated ?
( sine 12.15 )
( p ( sine 4.05 ) )
( p ( p ( sine ( / 4.05 3.0 ) ) ) )
( p ( p ( sine 1.35 ) ) )
( p ( p ( p ( sine 0.45 ) ) ) )
( p ( p ( p ( p ( sine 0.15 ) ) ) ) )
( p ( p ( p ( p ( p ( sine 0.05 ) ) ) ) ) )
( p ( p ( p ( p ( p 0.05 ) ) ) ) )
ANSWER : 5 times
ANSWER : For space , I think it 's cube root ? I 'm not really sure : it 's less than linear , but I 'm not 100 % certain how . I believe the same is true for the number of steps .
|
78f15925033e0981724ebe45af94d64ac615338fcbcb58f1ea12e48a3b94f4f9 | jgrodziski/keycloak-clojure | config.cljs | (ns myapp.front.config)
(def debug?
^boolean goog.DEBUG)
| null | https://raw.githubusercontent.com/jgrodziski/keycloak-clojure/2b71a1d1bf8d053f2e193af699daba3370ab6b2f/sample/frontend/src/cljs/myapp/front/config.cljs | clojure | (ns myapp.front.config)
(def debug?
^boolean goog.DEBUG)
|
|
01a2e3c25b277b7a4672209e1be63f56dc420576fb245b6a0963f385420f6e67 | shop-planner/shop3 | decls.lisp | (in-package :shop2)
(defparameter +pddl-requirements-keywords+
'(:strips
:typing
:negative-preconditions
:disjunctive-preconditions
:equality
:existential-preconditions
:universal-preconditions
:quantified-preconditions ; existential + universal
:conditional-effects
:fluents ; metric functions and effects
:adl
:durative-actions ; does not imply fluents
:duration-inequalities
:continuous-effects
:costs)) | null | https://raw.githubusercontent.com/shop-planner/shop3/ba429cf91a575e88f28b7f0e89065de7b4d666a6/shop3/pddl/decls.lisp | lisp | existential + universal
metric functions and effects
does not imply fluents | (in-package :shop2)
(defparameter +pddl-requirements-keywords+
'(:strips
:typing
:negative-preconditions
:disjunctive-preconditions
:equality
:existential-preconditions
:universal-preconditions
:conditional-effects
:adl
:duration-inequalities
:continuous-effects
:costs)) |
e813d4e23c46bb80d206dcb65fae47a9075c1175937c1e9fec979ba415da0bb3 | janestreet/memtrace_viewer_with_deps | test_string.ml | open! Core_kernel
open! Import
open! String
(*TEST = slice "hey" 0 0 = ""*)
(* This is what I would expect *)
let%test _ = slice "hey" 0 0 = "hey"
(* But this is what we get! *)
let%test _ = slice "hey" 0 1 = "h"
let%test _ = slice "hey" 0 2 = "he"
let%test _ = slice "hey" 0 3 = "hey"
let%test _ = slice "hey" 1 1 = ""
let%test _ = slice "hey" 1 2 = "e"
let%test _ = slice "hey" 1 3 = "ey"
let%test _ = slice "hey" 2 2 = ""
let%test _ = slice "hey" 2 3 = "y"
let%test _ = slice "hey" 3 3 = ""
let%test_module "Caseless Comparable" =
(module struct
let%test _ =
Int.equal (Base.Map.find_exn (Caseless.Map.of_alist_exn [ "a", 4; "b", 5 ]) "A") 4
;;
let%test _ = Base.Set.mem (Caseless.Set.of_list [ "hello"; "world" ]) "heLLO"
let%test _ = Int.equal (Base.Set.length (Caseless.Set.of_list [ "a"; "A" ])) 1
end)
;;
let%test_module "Caseless Hash" =
(module struct
let%test _ = Int.equal (Caseless.hash "Hello") (Caseless.hash "HELLO")
end)
;;
let%test_module "take_while" =
(module struct
let f = Char.is_digit
let%test_unit _ = [%test_result: t] (take_while "123abc456" ~f) ~expect:"123"
let%test_unit _ = [%test_result: t] (rtake_while "123abc456" ~f) ~expect:"456"
let%test_unit _ = [%test_result: t] (take_while "123456" ~f) ~expect:"123456"
let%test_unit _ = [%test_result: t] (rtake_while "123456" ~f) ~expect:"123456"
end)
;;
let%test_module "Verify reading/writing stable table sexp" =
(module struct
let expected_sexp = Sexp.of_string "((alpha beta) (delta gamma))"
let table =
let s = String.Table.create () in
Hashtbl.add_exn s ~key:"delta" ~data:"gamma";
Hashtbl.add_exn s ~key:"alpha" ~data:"beta";
s
;;
let%expect_test "sexp_of_t" =
print_s [%sexp (table : string String.Stable.V1.Table.t)];
[%expect {|
((alpha beta)
(delta gamma)) |}]
;;
let%test_unit "t_of_sexp" =
let loaded_table = [%of_sexp: string String.Stable.V1.Table.t] expected_sexp in
assert (Hashtbl.equal String.equal loaded_table table)
;;
end)
;;
let%expect_test "Hashtbl.merge of String.Table and String.Stable.V1.Table" =
Expect_test_helpers_core.require_does_not_raise [%here] (fun () ->
let result =
Hashtbl.merge
(String.Table.t_of_sexp int_of_sexp [%sexp []])
(String.Stable.V1.Table.t_of_sexp int_of_sexp [%sexp []])
~f:(fun ~key:_ x -> Some x)
in
require [%here] (Hashtbl.is_empty result));
[%expect {| |}]
;;
| null | https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/core_kernel/test/src/test_string.ml | ocaml | TEST = slice "hey" 0 0 = ""
This is what I would expect
But this is what we get! | open! Core_kernel
open! Import
open! String
let%test _ = slice "hey" 0 0 = "hey"
let%test _ = slice "hey" 0 1 = "h"
let%test _ = slice "hey" 0 2 = "he"
let%test _ = slice "hey" 0 3 = "hey"
let%test _ = slice "hey" 1 1 = ""
let%test _ = slice "hey" 1 2 = "e"
let%test _ = slice "hey" 1 3 = "ey"
let%test _ = slice "hey" 2 2 = ""
let%test _ = slice "hey" 2 3 = "y"
let%test _ = slice "hey" 3 3 = ""
let%test_module "Caseless Comparable" =
(module struct
let%test _ =
Int.equal (Base.Map.find_exn (Caseless.Map.of_alist_exn [ "a", 4; "b", 5 ]) "A") 4
;;
let%test _ = Base.Set.mem (Caseless.Set.of_list [ "hello"; "world" ]) "heLLO"
let%test _ = Int.equal (Base.Set.length (Caseless.Set.of_list [ "a"; "A" ])) 1
end)
;;
let%test_module "Caseless Hash" =
(module struct
let%test _ = Int.equal (Caseless.hash "Hello") (Caseless.hash "HELLO")
end)
;;
let%test_module "take_while" =
(module struct
let f = Char.is_digit
let%test_unit _ = [%test_result: t] (take_while "123abc456" ~f) ~expect:"123"
let%test_unit _ = [%test_result: t] (rtake_while "123abc456" ~f) ~expect:"456"
let%test_unit _ = [%test_result: t] (take_while "123456" ~f) ~expect:"123456"
let%test_unit _ = [%test_result: t] (rtake_while "123456" ~f) ~expect:"123456"
end)
;;
let%test_module "Verify reading/writing stable table sexp" =
(module struct
let expected_sexp = Sexp.of_string "((alpha beta) (delta gamma))"
let table =
let s = String.Table.create () in
Hashtbl.add_exn s ~key:"delta" ~data:"gamma";
Hashtbl.add_exn s ~key:"alpha" ~data:"beta";
s
;;
let%expect_test "sexp_of_t" =
print_s [%sexp (table : string String.Stable.V1.Table.t)];
[%expect {|
((alpha beta)
(delta gamma)) |}]
;;
let%test_unit "t_of_sexp" =
let loaded_table = [%of_sexp: string String.Stable.V1.Table.t] expected_sexp in
assert (Hashtbl.equal String.equal loaded_table table)
;;
end)
;;
let%expect_test "Hashtbl.merge of String.Table and String.Stable.V1.Table" =
Expect_test_helpers_core.require_does_not_raise [%here] (fun () ->
let result =
Hashtbl.merge
(String.Table.t_of_sexp int_of_sexp [%sexp []])
(String.Stable.V1.Table.t_of_sexp int_of_sexp [%sexp []])
~f:(fun ~key:_ x -> Some x)
in
require [%here] (Hashtbl.is_empty result));
[%expect {| |}]
;;
|
9b76cc63e6e798130e3622050689425574b68754b7bfa5cac8fc9870f20fc453 | inconvergent/weir | main.lisp |
(in-package :parallel)
;-concurrency-and-parallelism-in-common-lisp-part-4a-parallelism-using-lparallel-fundamentals/
(defun init (&key (cores 4) (name "custom-kernel"))
(setf lparallel:*kernel*
(lparallel:make-kernel cores :name name)))
(defun end ()
(lparallel:end-kernel :wait t))
(defun info ()
(let ((name (lparallel:kernel-name))
(count (lparallel:kernel-worker-count))
(context (lparallel:kernel-context))
(bindings (lparallel:kernel-bindings)))
(format t "kernel name = ~a~%" name)
(format t "worker threads count = ~d~%" count)
(format t "kernel context = ~a~%" context)
(format t "kernel bindings = ~a~%" bindings)))
(defun create-channel ()
(lparallel:make-channel))
(defun submit-task (channel fx)
(lparallel:submit-task channel fx)
(lparallel:receive-result channel))
| null | https://raw.githubusercontent.com/inconvergent/weir/3c364e3a0e15526f0d6985f08a57b312b5c35f7d/src/parallel/main.lisp | lisp | -concurrency-and-parallelism-in-common-lisp-part-4a-parallelism-using-lparallel-fundamentals/ |
(in-package :parallel)
(defun init (&key (cores 4) (name "custom-kernel"))
(setf lparallel:*kernel*
(lparallel:make-kernel cores :name name)))
(defun end ()
(lparallel:end-kernel :wait t))
(defun info ()
(let ((name (lparallel:kernel-name))
(count (lparallel:kernel-worker-count))
(context (lparallel:kernel-context))
(bindings (lparallel:kernel-bindings)))
(format t "kernel name = ~a~%" name)
(format t "worker threads count = ~d~%" count)
(format t "kernel context = ~a~%" context)
(format t "kernel bindings = ~a~%" bindings)))
(defun create-channel ()
(lparallel:make-channel))
(defun submit-task (channel fx)
(lparallel:submit-task channel fx)
(lparallel:receive-result channel))
|
eed9e344cad32c8bbaec1c147920e1a8970a18490a54308e64c410968b503595 | tov/shcaml | timeout.ml | #!/usr/bin/env ocaml
#use "topfind";;
#require "shcaml.top";;
let usage = "[-s SECONDS] [COMMAND ARGS...]"
let lookup = Flags.go ~usage "-s <SECONDS:int>"
let delay = lookup # int ~default:1 "-s"
let to_run =
match lookup # strings "" with
| prog :: args -> program prog args
| _ -> command "yes i am going to run forever"
;;
run begin
to_run ^&= fun proc ->
sleep delay;
Proc.kill ~raise:false Sys.sigint proc;
yield (Proc.WEXITED 0)
end
| null | https://raw.githubusercontent.com/tov/shcaml/43ae852a00e3a11520f90f2451baa71863409774/examples/timeout.ml | ocaml | #!/usr/bin/env ocaml
#use "topfind";;
#require "shcaml.top";;
let usage = "[-s SECONDS] [COMMAND ARGS...]"
let lookup = Flags.go ~usage "-s <SECONDS:int>"
let delay = lookup # int ~default:1 "-s"
let to_run =
match lookup # strings "" with
| prog :: args -> program prog args
| _ -> command "yes i am going to run forever"
;;
run begin
to_run ^&= fun proc ->
sleep delay;
Proc.kill ~raise:false Sys.sigint proc;
yield (Proc.WEXITED 0)
end
|
|
137f6c0f3083bb9fbe0336169bda547d7ecc95ae802c8872072d04338e320956 | ocaml-flambda/flambda-backend | printcmm.mli | (**************************************************************************)
(* *)
(* 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. *)
(* *)
(**************************************************************************)
Pretty - printing of C-- code
open Format
val rec_flag : formatter -> Cmm.rec_flag -> unit
val machtype_component : formatter -> Cmm.machtype_component -> unit
val machtype : formatter -> Cmm.machtype -> unit
val exttype : formatter -> Cmm.exttype -> unit
val extcall_signature : formatter -> Cmm.machtype option * Cmm.exttype list -> unit
val integer_comparison : Cmm.integer_comparison -> string
val float_comparison : Cmm.float_comparison -> string
val trap_action_list : formatter -> Cmm.trap_action list -> unit
val trywith_kind : formatter -> Cmm.trywith_kind -> unit
val chunk : Cmm.memory_chunk -> string
val atomic_bitwidth : Cmm.atomic_bitwidth -> string
val operation : Debuginfo.t -> Cmm.operation -> string
val expression : formatter -> Cmm.expression -> unit
val fundecl : formatter -> Cmm.fundecl -> unit
val data : formatter -> Cmm.data_item list -> unit
val phrase : formatter -> Cmm.phrase -> unit
val temporal_locality : Cmm.prefetch_temporal_locality_hint -> string
val print_codegen_options : formatter -> Cmm.codegen_option list -> unit
| null | https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/712c57c247efe2c4fabb7fb270070d3d809c5076/backend/printcmm.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************ | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
Pretty - printing of C-- code
open Format
val rec_flag : formatter -> Cmm.rec_flag -> unit
val machtype_component : formatter -> Cmm.machtype_component -> unit
val machtype : formatter -> Cmm.machtype -> unit
val exttype : formatter -> Cmm.exttype -> unit
val extcall_signature : formatter -> Cmm.machtype option * Cmm.exttype list -> unit
val integer_comparison : Cmm.integer_comparison -> string
val float_comparison : Cmm.float_comparison -> string
val trap_action_list : formatter -> Cmm.trap_action list -> unit
val trywith_kind : formatter -> Cmm.trywith_kind -> unit
val chunk : Cmm.memory_chunk -> string
val atomic_bitwidth : Cmm.atomic_bitwidth -> string
val operation : Debuginfo.t -> Cmm.operation -> string
val expression : formatter -> Cmm.expression -> unit
val fundecl : formatter -> Cmm.fundecl -> unit
val data : formatter -> Cmm.data_item list -> unit
val phrase : formatter -> Cmm.phrase -> unit
val temporal_locality : Cmm.prefetch_temporal_locality_hint -> string
val print_codegen_options : formatter -> Cmm.codegen_option list -> unit
|
013cd967a222cebacd2a1bb02d02aa18696c5b51af75a1bbee69626f6ab9e579 | Spivoxity/obc-3 | symtab.mli |
* symtab.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2006 - -2016 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
* 3 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
* IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
* IN NO EVENT SHALL THE AUTHOR 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 ,
* 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 .
* symtab.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2006--2016 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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.
*)
(* ident -- type of identifiers *)
type ident
val intern : string -> ident
val intern_sys : string -> ident
val extern : ident -> string
val anon : ident
val fId : ident -> Print.arg
val fQual : ident * ident -> Print.arg
(* |kind| -- basic types *)
type kind =
NumT | ByteT | ShortT | IntT | LongT | FloatT | DoubleT
Numerics in order of width
| CharT | BoolT | SetT | PtrT | LongPtrT | SysByteT
(* Non-numerics *)
| VoidT | ErrT (* Fictitious types *)
(* op -- type of operators *)
type op =
Plus | Minus | Times | Over | Div | Mod | Eq | Uminus | Uplus
| Lt | Gt | Leq | Geq | Neq | And | Or | Not
| In | BitAnd | BitOr | BitNot | BitXor | BitShl
| Inc | Dec | Lsl | Lsr | Asr | Ror | Compare
val fOp : op -> Print.arg
(* commute -- find operator with commuted operands *)
val commute : op -> op
(* opposite -- negate a comparison operator *)
val opposite : op -> op
libid -- type of Oberon library procedures
type libid =
ChrFun | OrdFun | OddFun | NewProc | LenFun | AbsFun
| IncProc | DecProc | Assert | Entier | Short | Long
| MinFun | MaxFun | AshFun | SizeFun | InclProc | ExclProc
| AdrFun | ValFun | BitFun | GetProc | PutProc
| LslFun | LsrFun | AsrFun | RorFun | FltFun
| PackProc | UnpkProc
type symbol = string
val nosym : symbol
val gensym : unit -> string
val genlab : unit -> symbol
val proc_name : ident -> int -> ident -> symbol
val fSym : symbol -> Print.arg
type codelab
(* label -- generate a code label *)
val label : unit -> codelab
val nolab : codelab
val fLab : codelab -> Print.arg
(* current -- name of the module being compiled *)
val current : ident ref
(* put -- output assembly directive *)
val put : string -> Print.arg list -> unit
(* put_int -- output integer constant *)
val put_int : int -> unit
(* put_sym -- output symbolic constant *)
val put_sym : symbol -> unit
(* save_string -- store a string constant *)
val save_string : string -> symbol
(* put_strings -- generate table of string constants *)
val put_strings : unit -> unit
| null | https://raw.githubusercontent.com/Spivoxity/obc-3/9e5094df8382ac5dd25ff08768277be6bd71a4ae/compiler/symtab.mli | ocaml | ident -- type of identifiers
|kind| -- basic types
Non-numerics
Fictitious types
op -- type of operators
commute -- find operator with commuted operands
opposite -- negate a comparison operator
label -- generate a code label
current -- name of the module being compiled
put -- output assembly directive
put_int -- output integer constant
put_sym -- output symbolic constant
save_string -- store a string constant
put_strings -- generate table of string constants |
* symtab.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright ( c ) 2006 - -2016 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms , with or without
* modification , are permitted provided that the following conditions are met :
*
* 1 . Redistributions of source code must retain the above copyright notice ,
* this list of conditions and the following disclaimer .
* 2 . Redistributions in binary form must reproduce the above copyright notice ,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution .
* 3 . The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission .
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR
* IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED .
* IN NO EVENT SHALL THE AUTHOR 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 ,
* 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 .
* symtab.mli
*
* This file is part of the Oxford Oberon-2 compiler
* Copyright (c) 2006--2016 J. M. Spivey
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR 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.
*)
type ident
val intern : string -> ident
val intern_sys : string -> ident
val extern : ident -> string
val anon : ident
val fId : ident -> Print.arg
val fQual : ident * ident -> Print.arg
type kind =
NumT | ByteT | ShortT | IntT | LongT | FloatT | DoubleT
Numerics in order of width
| CharT | BoolT | SetT | PtrT | LongPtrT | SysByteT
type op =
Plus | Minus | Times | Over | Div | Mod | Eq | Uminus | Uplus
| Lt | Gt | Leq | Geq | Neq | And | Or | Not
| In | BitAnd | BitOr | BitNot | BitXor | BitShl
| Inc | Dec | Lsl | Lsr | Asr | Ror | Compare
val fOp : op -> Print.arg
val commute : op -> op
val opposite : op -> op
libid -- type of Oberon library procedures
type libid =
ChrFun | OrdFun | OddFun | NewProc | LenFun | AbsFun
| IncProc | DecProc | Assert | Entier | Short | Long
| MinFun | MaxFun | AshFun | SizeFun | InclProc | ExclProc
| AdrFun | ValFun | BitFun | GetProc | PutProc
| LslFun | LsrFun | AsrFun | RorFun | FltFun
| PackProc | UnpkProc
type symbol = string
val nosym : symbol
val gensym : unit -> string
val genlab : unit -> symbol
val proc_name : ident -> int -> ident -> symbol
val fSym : symbol -> Print.arg
type codelab
val label : unit -> codelab
val nolab : codelab
val fLab : codelab -> Print.arg
val current : ident ref
val put : string -> Print.arg list -> unit
val put_int : int -> unit
val put_sym : symbol -> unit
val save_string : string -> symbol
val put_strings : unit -> unit
|
8c4148b7df5b66f2ac17b2e56c4b54ef20c6951e421500aca939982988e141fb | webyrd/n-grams-for-synthesis | titlecase-test.scm | ;;;; Chicken-specific tests for titlecase library
Note : The strings embed Unicode characters using the Chicken - specific lexical
syntax " \u1234 " rather than the R7RS syntax " \x1234 ; "
(use utf8)
(use titlecase)
(use test)
(test-group "titlecase"
(test-group "titlecase/predicate"
(test-assert (char-title-case? #\u01C5))
(test-assert (char-title-case? #\u1FFC))
(test-assert (not (char-title-case? #\Z)))
(test-assert (not (char-title-case? #\z)))
) ; end titlecase/predicate
(test-group "titlecase/char"
(test #\u01C5 (char-titlecase #\u01C4))
(test #\u01C5 (char-titlecase #\u01C6))
(test #\Z (char-titlecase #\Z))
(test #\Z (char-titlecase #\z))
) ; end titlecase/char
(test-group "titlecase/string"
(test "\u01C5" (string-titlecase "\u01C5"))
(test "\u01C5" (string-titlecase "\u01C4"))
(test "Ss" (string-titlecase "\u00DF"))
(test "Xi\u0307" (string-titlecase "x\u0130"))
(test "\u1F88" (string-titlecase "\u1F80"))
(test "\u1F88" (string-titlecase "\u1F88"))
(define Floo "\uFB02oo")
(define Floo-bar "\uFB02oo bar")
(define Baffle "Ba\uFB04e")
(define LJUBLJANA "\u01C7ub\u01C7ana")
(define Ljubljana "\u01C8ub\u01C9ana")
(define ljubljana "\u01C9ub\u01C9ana")
(test "Bar Baz" (string-titlecase "bAr baZ"))
(test "Floo" (string-titlecase "floo"))
(test "Floo" (string-titlecase "FLOO"))
(test "Floo" (string-titlecase Floo))
(test "Floo Bar" (string-titlecase "floo bar"))
(test "Floo Bar" (string-titlecase "FLOO BAR"))
(test "Floo Bar" (string-titlecase Floo-bar))
(test Baffle (string-titlecase Baffle))
(test Ljubljana (string-titlecase LJUBLJANA))
(test Ljubljana (string-titlecase Ljubljana))
(test Ljubljana (string-titlecase ljubljana))
) ; end titlecase/string
) ; end titlecase
(test-exit)
| null | https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-129/titlecase/titlecase-test.scm | scheme | Chicken-specific tests for titlecase library
end titlecase/predicate
end titlecase/char
end titlecase/string
end titlecase |
Note : The strings embed Unicode characters using the Chicken - specific lexical
syntax " \u1234 " rather than the R7RS syntax " \x1234 ; "
(use utf8)
(use titlecase)
(use test)
(test-group "titlecase"
(test-group "titlecase/predicate"
(test-assert (char-title-case? #\u01C5))
(test-assert (char-title-case? #\u1FFC))
(test-assert (not (char-title-case? #\Z)))
(test-assert (not (char-title-case? #\z)))
(test-group "titlecase/char"
(test #\u01C5 (char-titlecase #\u01C4))
(test #\u01C5 (char-titlecase #\u01C6))
(test #\Z (char-titlecase #\Z))
(test #\Z (char-titlecase #\z))
(test-group "titlecase/string"
(test "\u01C5" (string-titlecase "\u01C5"))
(test "\u01C5" (string-titlecase "\u01C4"))
(test "Ss" (string-titlecase "\u00DF"))
(test "Xi\u0307" (string-titlecase "x\u0130"))
(test "\u1F88" (string-titlecase "\u1F80"))
(test "\u1F88" (string-titlecase "\u1F88"))
(define Floo "\uFB02oo")
(define Floo-bar "\uFB02oo bar")
(define Baffle "Ba\uFB04e")
(define LJUBLJANA "\u01C7ub\u01C7ana")
(define Ljubljana "\u01C8ub\u01C9ana")
(define ljubljana "\u01C9ub\u01C9ana")
(test "Bar Baz" (string-titlecase "bAr baZ"))
(test "Floo" (string-titlecase "floo"))
(test "Floo" (string-titlecase "FLOO"))
(test "Floo" (string-titlecase Floo))
(test "Floo Bar" (string-titlecase "floo bar"))
(test "Floo Bar" (string-titlecase "FLOO BAR"))
(test "Floo Bar" (string-titlecase Floo-bar))
(test Baffle (string-titlecase Baffle))
(test Ljubljana (string-titlecase LJUBLJANA))
(test Ljubljana (string-titlecase Ljubljana))
(test Ljubljana (string-titlecase ljubljana))
(test-exit)
|
494f1f01f1b2f12c3887a67727bd42ef578c551011f96adf015a028d074d7a18 | synduce/Synduce | unknowns_are_ids.ml | type 'a clist = CNil | Single of 'a | Concat of 'a clist * 'a clist
type 'a list = Nil | Cons of 'a * 'a list
(*
This is our reference function. It is not named spec and we will need to
declare our synthesis objective using an assert statement at the end of
the file.
*)
let rec sum = function Nil -> 0 | Cons (hd, tl) -> hd + sum tl
This is the representation function . Remark that it is the same as the one
defined in the mpshom.pmrs or sumhom.pmrs files !
defined in the mpshom.pmrs or sumhom.pmrs files!
*)
let rec clist_to_list = function
| CNil -> Nil
| Single a -> Cons (a, Nil)
| Concat (x, y) -> dec y x
and dec l1 = function
| CNil -> clist_to_list l1
| Single a -> Cons (a, clist_to_list l1)
| Concat (x, y) -> dec (Concat (y, l1)) x
This is the target function . There are three unknown components :
s0 , f0 and join
s0, f0 and join
*)
let rec hsum = function
| CNil -> [%synt s0]
| Single a -> [%synt f0] a
| Concat (x, y) -> [%synt f1] (hsum x) + [%synt f2] (hsum y) + 0
(* The assertion should be of the form:
assert (recursion skeleton = representation function @@ reference function)
*)
;;
assert (hsum = clist_to_list @@ sum)
| null | https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/misc/unknowns_are_ids.ml | ocaml |
This is our reference function. It is not named spec and we will need to
declare our synthesis objective using an assert statement at the end of
the file.
The assertion should be of the form:
assert (recursion skeleton = representation function @@ reference function)
| type 'a clist = CNil | Single of 'a | Concat of 'a clist * 'a clist
type 'a list = Nil | Cons of 'a * 'a list
let rec sum = function Nil -> 0 | Cons (hd, tl) -> hd + sum tl
This is the representation function . Remark that it is the same as the one
defined in the mpshom.pmrs or sumhom.pmrs files !
defined in the mpshom.pmrs or sumhom.pmrs files!
*)
let rec clist_to_list = function
| CNil -> Nil
| Single a -> Cons (a, Nil)
| Concat (x, y) -> dec y x
and dec l1 = function
| CNil -> clist_to_list l1
| Single a -> Cons (a, clist_to_list l1)
| Concat (x, y) -> dec (Concat (y, l1)) x
This is the target function . There are three unknown components :
s0 , f0 and join
s0, f0 and join
*)
let rec hsum = function
| CNil -> [%synt s0]
| Single a -> [%synt f0] a
| Concat (x, y) -> [%synt f1] (hsum x) + [%synt f2] (hsum y) + 0
;;
assert (hsum = clist_to_list @@ sum)
|
1c516c0139dd98d784565f7dc0b853ec678a5c7376b2ffbd18de2694f1cc1f41 | garrigue/labltk | searchid.ml | (*************************************************************************)
(* *)
(* OCaml LablTk library *)
(* *)
, Kyoto University RIMS
(* *)
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
(* General Public License, with the special exception on linking *)
(* described in file ../../../LICENSE. *)
(* *)
(*************************************************************************)
$ Id$
open Asttypes
open StdLabels
open Location
open Longident
open Path
open Types
open Typedtree
open Env
open Btype
open Ctype
only empty here , but replaced by Pervasives later
let start_env = ref Env.empty
let module_list = ref []
type pkind =
Pvalue
| Ptype
| Plabel
| Pconstructor
| Pmodule
| Pmodtype
| Pclass
| Pcltype
let string_of_kind = function
Pvalue -> "v"
| Ptype -> "t"
| Plabel -> "l"
| Pconstructor -> "cn"
| Pmodule -> "m"
| Pmodtype -> "s"
| Pclass -> "c"
| Pcltype -> "ct"
let rec longident_of_path = function
Pident id -> Lident (Ident.name id)
| Pdot (path, s) -> Ldot (longident_of_path path, s)
| Papply (p1, p2) -> Lapply (longident_of_path p1, longident_of_path p2)
let rec remove_prefix lid ~prefix =
let rec remove_hd lid ~name =
match lid with
Ldot (Lident s1, s2) when s1 = name -> Lident s2
| Ldot (l, s) -> Ldot (remove_hd ~name l, s)
| _ -> raise Not_found
in
match prefix with
[] -> lid
| name :: prefix ->
try remove_prefix ~prefix (remove_hd ~name lid)
with Not_found -> lid
let rec permutations l = match l with
[] | [_] -> [l]
| [a;b] -> [l; [b;a]]
| _ ->
let _, perms =
List.fold_left l ~init:(l,[]) ~f:
begin fun (l, perms) a ->
let l = List.tl l in
l @ [a],
List.map (permutations l) ~f:(fun l -> a :: l) @ perms
end
in perms
let rec choose n ~card:l =
let len = List.length l in
if n = len then [l] else
if n = 1 then List.map l ~f:(fun x -> [x]) else
if n = 0 then [[]] else
if n > len then [] else
match l with [] -> []
| a :: l ->
List.map (choose (n-1) ~card:l) ~f:(fun l -> a :: l)
@ choose n ~card:l
let rec arr p ~card:n =
if p = 0 then 1 else n * arr (p-1) ~card:(n-1)
let rec all_args ty =
match get_desc ty with
Tarrow(l, ty1, ty2, _) -> let (tl,ty) = all_args ty2 in ((l,ty1)::tl, ty)
| _ -> ([], ty)
let rec equal ~prefix t1 t2 =
match get_desc t1, get_desc t2 with
Tvar _, Tvar _ -> true
| Tvariant row1, Tvariant row2 ->
let fields1 = filter_row_fields false (row_fields row1)
and fields2 = filter_row_fields false (row_fields row1)
in
let r1, r2, pairs = merge_row_fields fields1 fields2 in
row_closed row1 = row_closed row2 && r1 = [] && r2 = [] &&
List.for_all pairs ~f:
begin fun (_,f1,f2) ->
match row_field_repr f1, row_field_repr f2 with
Rpresent None, Rpresent None -> true
| Rpresent(Some t1), Rpresent (Some t2) -> equal t1 t2 ~prefix
| Reither(c1, tl1, _), Reither(c2, tl2, _) ->
c1 = c2 && List.length tl1 = List.length tl2 &&
List.for_all2 tl1 tl2 ~f:(equal ~prefix)
| _ -> false
end
| Tarrow _, Tarrow _ ->
let l1, t1 = all_args t1 and l2, t2 = all_args t2 in
equal t1 t2 ~prefix &&
List.length l1 = List.length l2 &&
List.exists (permutations l1) ~f:
begin fun l1 ->
List.for_all2 l1 l2 ~f:
begin fun (p1,t1) (p2,t2) ->
(p1 = Nolabel || p1 = p2) && equal t1 t2 ~prefix
end
end
| Ttuple l1, Ttuple l2 ->
List.length l1 = List.length l2 &&
List.for_all2 l1 l2 ~f:(equal ~prefix)
| Tconstr (p1, l1, _), Tconstr (p2, l2, _) ->
remove_prefix ~prefix (longident_of_path p1) = (longident_of_path p2)
&& List.length l1 = List.length l2
&& List.for_all2 l1 l2 ~f:(equal ~prefix)
| _ -> false
let get_options = List.filter ~f:Btype.is_optional
let rec included ~prefix t1 t2 =
match get_desc t1, get_desc t2 with
Tvar _, _ -> true
| Tvariant row1, Tvariant row2 ->
let fields1 = filter_row_fields false (row_fields row1)
and fields2 = filter_row_fields false (row_fields row2)
in
let r1, r2, pairs = merge_row_fields fields1 fields2 in
r1 = [] &&
List.for_all pairs ~f:
begin fun (_,f1,f2) ->
match row_field_repr f1, row_field_repr f2 with
Rpresent None, Rpresent None -> true
| Rpresent(Some t1), Rpresent (Some t2) -> included t1 t2 ~prefix
| Reither(c1, tl1, _), Reither(c2, tl2, _) ->
c1 = c2 && List.length tl1 = List.length tl2 &&
List.for_all2 tl1 tl2 ~f:(included ~prefix)
| _ -> false
end
| Tarrow _, Tarrow _ ->
let l1, t1 = all_args t1 and l2, t2 = all_args t2 in
included t1 t2 ~prefix &&
let len1 = List.length l1 and len2 = List.length l2 in
let l2 = if arr len1 ~card:len2 < 100 then l2 else
let ll1 = get_options (fst (List.split l1)) in
List.filter l2
~f:(fun (l,_) -> not (is_optional l) || List.mem l ~set:ll1)
in
len1 <= len2 &&
List.exists (List2.flat_map ~f:permutations (choose len1 ~card:l2)) ~f:
begin fun l2 ->
List.for_all2 l1 l2 ~f:
begin fun (p1,t1) (p2,t2) ->
(p1 = Nolabel || p1 = p2) && included t1 t2 ~prefix
end
end
| Ttuple l1, Ttuple l2 ->
let len1 = List.length l1 in
len1 <= List.length l2 &&
List.exists (List2.flat_map ~f:permutations (choose len1 ~card:l2)) ~f:
begin fun l2 ->
List.for_all2 l1 l2 ~f:(included ~prefix)
end
| _, Ttuple _ -> included (newty (Ttuple [t1])) t2 ~prefix
| Tconstr (p1, l1, _), Tconstr (p2, l2, _) ->
remove_prefix ~prefix (longident_of_path p1) = (longident_of_path p2)
&& List.length l1 = List.length l2
&& List.for_all2 l1 l2 ~f:(included ~prefix)
| _ -> false
let mklid = function
[] -> raise (Invalid_argument "Searchid.mklid")
| x :: l ->
List.fold_left l ~init:(Lident x) ~f:(fun acc x -> Ldot (acc, x))
let mkpath = function
[] -> raise (Invalid_argument "Searchid.mklid")
| x :: l ->
List.fold_left l ~init:(Pident (Ident.create_local x))
~f:(fun acc x -> Pdot (acc, x))
let get_fields ~prefix ~sign self =
(*let env = open_signature Fresh (mkpath prefix) sign !start_env in*)
let env = add_signature sign !start_env in
match get_desc (expand_head env self) with
Tobject (ty_obj, _) ->
let l,_ = flatten_fields ty_obj in l
| _ -> []
let rec search_type_in_signature t ~sign ~prefix ~mode =
let matches = match mode with
`Included -> included t ~prefix
| `Exact -> equal t ~prefix
and lid_of_id id = mklid (prefix @ [Ident.name id]) in
let constructor_matches = function
Types.Cstr_tuple l -> List.exists l ~f:matches
| Cstr_record l -> List.exists l ~f:(fun d -> matches d.Types.ld_type)
in
List2.flat_map sign ~f:
begin fun item -> match item with
Sig_value (id, vd, _) ->
if matches vd.val_type then [lid_of_id id, Pvalue] else []
| Sig_type (id, td, _, _) ->
if
matches (newconstr (Pident id) td.type_params) ||
begin match td.type_manifest with
None -> false
| Some t -> matches t
end ||
begin match td.type_kind with
Type_abstract
| Type_open -> false
| Type_variant (l, _) ->
List.exists l ~f:
begin fun {Types.cd_args=args; cd_res=r} ->
constructor_matches args ||
match r with None -> false | Some x -> matches x
end
| Type_record(l, rep) ->
List.exists l ~f:(fun {Types.ld_type=t} -> matches t)
end
then [lid_of_id id, Ptype] else []
| Sig_typext (id, l, _, _) ->
if constructor_matches l.ext_args
then [lid_of_id id, Pconstructor]
else []
| Sig_module (id, _, {md_type=Mty_signature sign}, _, _) ->
search_type_in_signature t ~sign ~mode
~prefix:(prefix @ [Ident.name id])
| Sig_module _ -> []
| Sig_modtype _ -> []
| Sig_class (id, cl, _, _) ->
let self = self_type cl.cty_type in
if matches self
|| (match cl.cty_new with None -> false | Some ty -> matches ty)
(* || List.exists (get_fields ~prefix ~sign self)
~f:(fun (_,_,ty_field) -> matches ty_field) *)
then [lid_of_id id, Pclass] else []
| Sig_class_type (id, cl, _, _) ->
let self = self_type cl.clty_type in
if matches self
(* || List.exists (get_fields ~prefix ~sign self)
~f:(fun (_,_,ty_field) -> matches ty_field) *)
then [lid_of_id id, Pclass] else []
end
let search_all_types t ~mode =
let tl = match mode, get_desc t with
`Exact, _ -> [t]
| `Included, Tarrow _ -> [t]
| `Included, _ ->
[t; newty(Tarrow(Nolabel,t,newvar(),commu_ok));
newty(Tarrow(Nolabel,newvar(),t,commu_ok))]
in List2.flat_map !module_list ~f:
begin fun modname ->
let mlid = Lident modname in
try match Env.find_module_by_name mlid !start_env
with _, {md_type=Mty_signature sign} ->
List2.flat_map tl
~f:(search_type_in_signature ~sign ~prefix:[modname] ~mode)
| _ -> []
with Not_found | Env.Error _ | Persistent_env.Error _ -> []
end
exception Error of int * int
let search_string_type text ~mode =
try
let sexp = Parse.interface (Lexing.from_string ("val z : " ^ text)) in
let sign =
try (Typemod.transl_signature !start_env sexp).sig_type with _ ->
let env = List.fold_left !module_list ~init:!start_env ~f:
begin fun acc m ->
match open_pers_signature m acc with
Ok env -> env
| Error _ -> acc
end in
try (Typemod.transl_signature env sexp).sig_type
with
Env.Error _ | Persistent_env.Error _ -> []
| Typemod.Error (l,_,_) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
| Typetexp.Error (l,_,_) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
in match sign with
[ Sig_value (_, vd, _) ] ->
search_all_types vd.val_type ~mode
| _ -> []
with
Syntaxerr.Error(Syntaxerr.Unclosed(l,_,_,_)) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
| Syntaxerr.Error(Syntaxerr.Other l) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
| Lexer.Error (_, l) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
let longident_of_string text =
let exploded = ref [] and l = ref 0 in
for i = 0 to String.length text - 2 do
if text.[i] ='.' then
(exploded := String.sub text ~pos:!l ~len:(i - !l) :: !exploded; l := i+1)
done;
let sym = String.sub text ~pos:!l ~len:(String.length text - !l) in
let rec mklid = function
[s] -> Lident s
| s :: l -> Ldot (mklid l, s)
| [] -> assert false in
sym, fun l -> mklid (sym :: !exploded @ l)
let explode s =
let l = ref [] in
for i = String.length s - 1 downto 0 do
l := s.[i] :: !l
done; !l
let rec check_match ~pattern s =
match pattern, s with
[], [] -> true
| '*'::l, l' -> check_match ~pattern:l l'
|| check_match ~pattern:('?'::'*'::l) l'
| '?'::l, _::l' -> check_match ~pattern:l l'
| x::l, y::l' when x == y -> check_match ~pattern:l l'
| _ -> false
let search_pattern_symbol text =
if text = "" then [] else
let pattern = explode text in
let check i = check_match ~pattern (explode (Ident.name i)) in
let l = List.map !module_list ~f:
begin fun modname -> Lident modname,
try match find_module_by_name (Lident modname) !start_env with
| _, {md_type=Mty_signature sign} ->
List2.flat_map sign ~f:
begin function
Sig_value (i, _, _) when check i -> [i, Pvalue]
| Sig_type (i, _, _, _) when check i -> [i, Ptype]
| Sig_typext (i, _, _, _) when check i -> [i, Pconstructor]
| Sig_module (i, _, _, _, _) when check i -> [i, Pmodule]
| Sig_modtype (i, _, _) when check i -> [i, Pmodtype]
| Sig_class (i, cl, _, _) when check i
|| List.exists
(get_fields ~prefix:[modname] ~sign (self_type cl.cty_type))
~f:(fun (name,_,_) -> check_match ~pattern (explode name))
-> [i, Pclass]
| Sig_class_type (i, cl, _, _) when check i
|| List.exists
(get_fields ~prefix:[modname] ~sign (self_type cl.clty_type))
~f:(fun (name,_,_) -> check_match ~pattern (explode name))
-> [i, Pcltype]
| _ -> []
end
| _ -> []
with Env.Error _ | Persistent_env.Error _ -> []
end
in
List2.flat_map l ~f:
begin fun (m, l) ->
List.map l ~f:(fun (i, p) -> Ldot (m, Ident.name i), p)
end
let is_pattern s =
try for i = 0 to String.length s -1 do
if s.[i ] = ' ? ' || s.[i ] = ' * ' then raise Exit
done ; false
with Exit - > true
let is_pattern s =
try for i = 0 to String.length s -1 do
if s.[i] = '?' || s.[i] = '*' then raise Exit
done; false
with Exit -> true
*)
let search_string_symbol text =
if text = "" then [] else
let lid = snd (longident_of_string text) [] in
let try_lookup f k =
try let _ = f lid !start_env in [lid, k]
with Not_found | Env.Error _ | Persistent_env.Error _ -> []
in
try_lookup find_constructor_by_name Pconstructor @
try_lookup find_module_by_name Pmodule @
try_lookup find_modtype_by_name Pmodtype @
try_lookup find_value_by_name Pvalue @
try_lookup find_type_by_name Ptype @
try_lookup find_label_by_name Plabel @
try_lookup find_class_by_name Pclass
open Parsetree
let rec bound_variables pat =
match pat.ppat_desc with
Ppat_any | Ppat_constant _ | Ppat_type _ | Ppat_unpack _
| Ppat_interval _ -> []
| Ppat_var s -> [s.txt]
| Ppat_alias (pat,s) -> s.txt :: bound_variables pat
| Ppat_tuple l -> List2.flat_map l ~f:bound_variables
| Ppat_construct (_,None) -> []
| Ppat_construct (_,Some (_, pat)) -> bound_variables pat
| Ppat_variant (_,None) -> []
| Ppat_variant (_,Some pat) -> bound_variables pat
| Ppat_record (l, _) ->
List2.flat_map l ~f:(fun (_,pat) -> bound_variables pat)
| Ppat_array l ->
List2.flat_map l ~f:bound_variables
| Ppat_or (pat1,pat2) ->
bound_variables pat1 @ bound_variables pat2
| Ppat_constraint (pat,_) -> bound_variables pat
| Ppat_lazy pat -> bound_variables pat
| Ppat_extension _ -> []
| Ppat_exception pat -> bound_variables pat
| Ppat_open (_, pat) -> bound_variables pat
let search_structure str ~name ~kind ~prefix =
let loc = ref 0 in
let rec search_module str ~prefix =
match prefix with [] -> str
| modu::prefix ->
let str =
List.fold_left ~init:[] str ~f:
begin fun acc item ->
match item.pstr_desc with
Pstr_module x when x.pmb_name.txt = Some modu ->
loc := x.pmb_expr.pmod_loc.loc_start.Lexing.pos_cnum;
begin match x.pmb_expr.pmod_desc with
Pmod_structure str -> str
| _ -> []
end
| _ -> acc
end
in search_module str ~prefix
in
List.iter (search_module str ~prefix) ~f:
begin fun item ->
if match item.pstr_desc with
Pstr_value (_, l) when kind = Pvalue ->
List.iter l ~f:
begin fun {pvb_pat=pat} ->
if List.mem name ~set:(bound_variables pat)
then loc := pat.ppat_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_primitive vd when kind = Pvalue -> name = vd.pval_name.txt
| Pstr_type (_, l) when kind = Ptype ->
List.iter l ~f:
begin fun td ->
if td.ptype_name.txt = name
then loc := td.ptype_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_typext l when kind = Ptype ->
List.iter l.ptyext_constructors ~f:
begin fun td ->
if td.pext_name.txt = name
then loc := td.pext_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_exception pcd when kind = Pconstructor ->
name = pcd.ptyexn_constructor.pext_name.txt
| Pstr_module x when kind = Pmodule -> Some name = x.pmb_name.txt
| Pstr_modtype x when kind = Pmodtype -> name = x.pmtd_name.txt
| Pstr_class l when kind = Pclass || kind = Ptype || kind = Pcltype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_class_type l when kind = Pcltype || kind = Ptype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| _ -> false
then loc := item.pstr_loc.loc_start.Lexing.pos_cnum
end;
!loc
let search_signature sign ~name ~kind ~prefix =
ignore (name = "");
ignore (prefix = [""]);
let loc = ref 0 in
let rec search_module_type sign ~prefix =
match prefix with [] -> sign
| modu::prefix ->
let sign =
List.fold_left ~init:[] sign ~f:
begin fun acc item ->
match item.psig_desc with
Psig_module pmd when pmd.pmd_name.txt = Some modu ->
loc := pmd.pmd_type.pmty_loc.loc_start.Lexing.pos_cnum;
begin match pmd.pmd_type.pmty_desc with
Pmty_signature sign -> sign
| _ -> []
end
| _ -> acc
end
in search_module_type sign ~prefix
in
List.iter (search_module_type sign ~prefix) ~f:
begin fun item ->
if match item.psig_desc with
Psig_value vd when kind = Pvalue -> name = vd.pval_name.txt
| Psig_type (_, l) when kind = Ptype ->
List.iter l ~f:
begin fun td ->
if td.ptype_name.txt = name
then loc := td.ptype_loc.loc_start.Lexing.pos_cnum
end;
false
| Psig_typext l when kind = Pconstructor ->
List.iter l.ptyext_constructors ~f:
begin fun td ->
if td.pext_name.txt = name
then loc := td.pext_loc.loc_start.Lexing.pos_cnum
end;
false
| Psig_exception pcd when kind = Pconstructor ->
name = pcd.ptyexn_constructor.pext_name.txt
| Psig_module pmd when kind = Pmodule -> Some name = pmd.pmd_name.txt
| Psig_modtype pmtd when kind = Pmodtype -> name = pmtd.pmtd_name.txt
| Psig_class l when kind = Pclass || kind = Ptype || kind = Pcltype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| Psig_class_type l when kind = Ptype || kind = Pcltype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| _ -> false
then loc := item.psig_loc.loc_start.Lexing.pos_cnum
end;
!loc
| null | https://raw.githubusercontent.com/garrigue/labltk/0e52cb81271236d904eaf18d26821d5df5e4234a/browser/searchid.ml | ocaml | ***********************************************************************
OCaml LablTk library
General Public License, with the special exception on linking
described in file ../../../LICENSE.
***********************************************************************
let env = open_signature Fresh (mkpath prefix) sign !start_env in
|| List.exists (get_fields ~prefix ~sign self)
~f:(fun (_,_,ty_field) -> matches ty_field)
|| List.exists (get_fields ~prefix ~sign self)
~f:(fun (_,_,ty_field) -> matches ty_field) | , Kyoto University RIMS
Copyright 1999 Institut National de Recherche en Informatique et
en Automatique and Kyoto University . All rights reserved .
This file is distributed under the terms of the GNU Library
$ Id$
open Asttypes
open StdLabels
open Location
open Longident
open Path
open Types
open Typedtree
open Env
open Btype
open Ctype
only empty here , but replaced by Pervasives later
let start_env = ref Env.empty
let module_list = ref []
type pkind =
Pvalue
| Ptype
| Plabel
| Pconstructor
| Pmodule
| Pmodtype
| Pclass
| Pcltype
let string_of_kind = function
Pvalue -> "v"
| Ptype -> "t"
| Plabel -> "l"
| Pconstructor -> "cn"
| Pmodule -> "m"
| Pmodtype -> "s"
| Pclass -> "c"
| Pcltype -> "ct"
let rec longident_of_path = function
Pident id -> Lident (Ident.name id)
| Pdot (path, s) -> Ldot (longident_of_path path, s)
| Papply (p1, p2) -> Lapply (longident_of_path p1, longident_of_path p2)
let rec remove_prefix lid ~prefix =
let rec remove_hd lid ~name =
match lid with
Ldot (Lident s1, s2) when s1 = name -> Lident s2
| Ldot (l, s) -> Ldot (remove_hd ~name l, s)
| _ -> raise Not_found
in
match prefix with
[] -> lid
| name :: prefix ->
try remove_prefix ~prefix (remove_hd ~name lid)
with Not_found -> lid
let rec permutations l = match l with
[] | [_] -> [l]
| [a;b] -> [l; [b;a]]
| _ ->
let _, perms =
List.fold_left l ~init:(l,[]) ~f:
begin fun (l, perms) a ->
let l = List.tl l in
l @ [a],
List.map (permutations l) ~f:(fun l -> a :: l) @ perms
end
in perms
let rec choose n ~card:l =
let len = List.length l in
if n = len then [l] else
if n = 1 then List.map l ~f:(fun x -> [x]) else
if n = 0 then [[]] else
if n > len then [] else
match l with [] -> []
| a :: l ->
List.map (choose (n-1) ~card:l) ~f:(fun l -> a :: l)
@ choose n ~card:l
let rec arr p ~card:n =
if p = 0 then 1 else n * arr (p-1) ~card:(n-1)
let rec all_args ty =
match get_desc ty with
Tarrow(l, ty1, ty2, _) -> let (tl,ty) = all_args ty2 in ((l,ty1)::tl, ty)
| _ -> ([], ty)
let rec equal ~prefix t1 t2 =
match get_desc t1, get_desc t2 with
Tvar _, Tvar _ -> true
| Tvariant row1, Tvariant row2 ->
let fields1 = filter_row_fields false (row_fields row1)
and fields2 = filter_row_fields false (row_fields row1)
in
let r1, r2, pairs = merge_row_fields fields1 fields2 in
row_closed row1 = row_closed row2 && r1 = [] && r2 = [] &&
List.for_all pairs ~f:
begin fun (_,f1,f2) ->
match row_field_repr f1, row_field_repr f2 with
Rpresent None, Rpresent None -> true
| Rpresent(Some t1), Rpresent (Some t2) -> equal t1 t2 ~prefix
| Reither(c1, tl1, _), Reither(c2, tl2, _) ->
c1 = c2 && List.length tl1 = List.length tl2 &&
List.for_all2 tl1 tl2 ~f:(equal ~prefix)
| _ -> false
end
| Tarrow _, Tarrow _ ->
let l1, t1 = all_args t1 and l2, t2 = all_args t2 in
equal t1 t2 ~prefix &&
List.length l1 = List.length l2 &&
List.exists (permutations l1) ~f:
begin fun l1 ->
List.for_all2 l1 l2 ~f:
begin fun (p1,t1) (p2,t2) ->
(p1 = Nolabel || p1 = p2) && equal t1 t2 ~prefix
end
end
| Ttuple l1, Ttuple l2 ->
List.length l1 = List.length l2 &&
List.for_all2 l1 l2 ~f:(equal ~prefix)
| Tconstr (p1, l1, _), Tconstr (p2, l2, _) ->
remove_prefix ~prefix (longident_of_path p1) = (longident_of_path p2)
&& List.length l1 = List.length l2
&& List.for_all2 l1 l2 ~f:(equal ~prefix)
| _ -> false
let get_options = List.filter ~f:Btype.is_optional
let rec included ~prefix t1 t2 =
match get_desc t1, get_desc t2 with
Tvar _, _ -> true
| Tvariant row1, Tvariant row2 ->
let fields1 = filter_row_fields false (row_fields row1)
and fields2 = filter_row_fields false (row_fields row2)
in
let r1, r2, pairs = merge_row_fields fields1 fields2 in
r1 = [] &&
List.for_all pairs ~f:
begin fun (_,f1,f2) ->
match row_field_repr f1, row_field_repr f2 with
Rpresent None, Rpresent None -> true
| Rpresent(Some t1), Rpresent (Some t2) -> included t1 t2 ~prefix
| Reither(c1, tl1, _), Reither(c2, tl2, _) ->
c1 = c2 && List.length tl1 = List.length tl2 &&
List.for_all2 tl1 tl2 ~f:(included ~prefix)
| _ -> false
end
| Tarrow _, Tarrow _ ->
let l1, t1 = all_args t1 and l2, t2 = all_args t2 in
included t1 t2 ~prefix &&
let len1 = List.length l1 and len2 = List.length l2 in
let l2 = if arr len1 ~card:len2 < 100 then l2 else
let ll1 = get_options (fst (List.split l1)) in
List.filter l2
~f:(fun (l,_) -> not (is_optional l) || List.mem l ~set:ll1)
in
len1 <= len2 &&
List.exists (List2.flat_map ~f:permutations (choose len1 ~card:l2)) ~f:
begin fun l2 ->
List.for_all2 l1 l2 ~f:
begin fun (p1,t1) (p2,t2) ->
(p1 = Nolabel || p1 = p2) && included t1 t2 ~prefix
end
end
| Ttuple l1, Ttuple l2 ->
let len1 = List.length l1 in
len1 <= List.length l2 &&
List.exists (List2.flat_map ~f:permutations (choose len1 ~card:l2)) ~f:
begin fun l2 ->
List.for_all2 l1 l2 ~f:(included ~prefix)
end
| _, Ttuple _ -> included (newty (Ttuple [t1])) t2 ~prefix
| Tconstr (p1, l1, _), Tconstr (p2, l2, _) ->
remove_prefix ~prefix (longident_of_path p1) = (longident_of_path p2)
&& List.length l1 = List.length l2
&& List.for_all2 l1 l2 ~f:(included ~prefix)
| _ -> false
let mklid = function
[] -> raise (Invalid_argument "Searchid.mklid")
| x :: l ->
List.fold_left l ~init:(Lident x) ~f:(fun acc x -> Ldot (acc, x))
let mkpath = function
[] -> raise (Invalid_argument "Searchid.mklid")
| x :: l ->
List.fold_left l ~init:(Pident (Ident.create_local x))
~f:(fun acc x -> Pdot (acc, x))
let get_fields ~prefix ~sign self =
let env = add_signature sign !start_env in
match get_desc (expand_head env self) with
Tobject (ty_obj, _) ->
let l,_ = flatten_fields ty_obj in l
| _ -> []
let rec search_type_in_signature t ~sign ~prefix ~mode =
let matches = match mode with
`Included -> included t ~prefix
| `Exact -> equal t ~prefix
and lid_of_id id = mklid (prefix @ [Ident.name id]) in
let constructor_matches = function
Types.Cstr_tuple l -> List.exists l ~f:matches
| Cstr_record l -> List.exists l ~f:(fun d -> matches d.Types.ld_type)
in
List2.flat_map sign ~f:
begin fun item -> match item with
Sig_value (id, vd, _) ->
if matches vd.val_type then [lid_of_id id, Pvalue] else []
| Sig_type (id, td, _, _) ->
if
matches (newconstr (Pident id) td.type_params) ||
begin match td.type_manifest with
None -> false
| Some t -> matches t
end ||
begin match td.type_kind with
Type_abstract
| Type_open -> false
| Type_variant (l, _) ->
List.exists l ~f:
begin fun {Types.cd_args=args; cd_res=r} ->
constructor_matches args ||
match r with None -> false | Some x -> matches x
end
| Type_record(l, rep) ->
List.exists l ~f:(fun {Types.ld_type=t} -> matches t)
end
then [lid_of_id id, Ptype] else []
| Sig_typext (id, l, _, _) ->
if constructor_matches l.ext_args
then [lid_of_id id, Pconstructor]
else []
| Sig_module (id, _, {md_type=Mty_signature sign}, _, _) ->
search_type_in_signature t ~sign ~mode
~prefix:(prefix @ [Ident.name id])
| Sig_module _ -> []
| Sig_modtype _ -> []
| Sig_class (id, cl, _, _) ->
let self = self_type cl.cty_type in
if matches self
|| (match cl.cty_new with None -> false | Some ty -> matches ty)
then [lid_of_id id, Pclass] else []
| Sig_class_type (id, cl, _, _) ->
let self = self_type cl.clty_type in
if matches self
then [lid_of_id id, Pclass] else []
end
let search_all_types t ~mode =
let tl = match mode, get_desc t with
`Exact, _ -> [t]
| `Included, Tarrow _ -> [t]
| `Included, _ ->
[t; newty(Tarrow(Nolabel,t,newvar(),commu_ok));
newty(Tarrow(Nolabel,newvar(),t,commu_ok))]
in List2.flat_map !module_list ~f:
begin fun modname ->
let mlid = Lident modname in
try match Env.find_module_by_name mlid !start_env
with _, {md_type=Mty_signature sign} ->
List2.flat_map tl
~f:(search_type_in_signature ~sign ~prefix:[modname] ~mode)
| _ -> []
with Not_found | Env.Error _ | Persistent_env.Error _ -> []
end
exception Error of int * int
let search_string_type text ~mode =
try
let sexp = Parse.interface (Lexing.from_string ("val z : " ^ text)) in
let sign =
try (Typemod.transl_signature !start_env sexp).sig_type with _ ->
let env = List.fold_left !module_list ~init:!start_env ~f:
begin fun acc m ->
match open_pers_signature m acc with
Ok env -> env
| Error _ -> acc
end in
try (Typemod.transl_signature env sexp).sig_type
with
Env.Error _ | Persistent_env.Error _ -> []
| Typemod.Error (l,_,_) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
| Typetexp.Error (l,_,_) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
in match sign with
[ Sig_value (_, vd, _) ] ->
search_all_types vd.val_type ~mode
| _ -> []
with
Syntaxerr.Error(Syntaxerr.Unclosed(l,_,_,_)) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
| Syntaxerr.Error(Syntaxerr.Other l) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
| Lexer.Error (_, l) ->
let start_c = l.loc_start.Lexing.pos_cnum in
let end_c = l.loc_end.Lexing.pos_cnum in
raise (Error (start_c - 8, end_c - 8))
let longident_of_string text =
let exploded = ref [] and l = ref 0 in
for i = 0 to String.length text - 2 do
if text.[i] ='.' then
(exploded := String.sub text ~pos:!l ~len:(i - !l) :: !exploded; l := i+1)
done;
let sym = String.sub text ~pos:!l ~len:(String.length text - !l) in
let rec mklid = function
[s] -> Lident s
| s :: l -> Ldot (mklid l, s)
| [] -> assert false in
sym, fun l -> mklid (sym :: !exploded @ l)
let explode s =
let l = ref [] in
for i = String.length s - 1 downto 0 do
l := s.[i] :: !l
done; !l
let rec check_match ~pattern s =
match pattern, s with
[], [] -> true
| '*'::l, l' -> check_match ~pattern:l l'
|| check_match ~pattern:('?'::'*'::l) l'
| '?'::l, _::l' -> check_match ~pattern:l l'
| x::l, y::l' when x == y -> check_match ~pattern:l l'
| _ -> false
let search_pattern_symbol text =
if text = "" then [] else
let pattern = explode text in
let check i = check_match ~pattern (explode (Ident.name i)) in
let l = List.map !module_list ~f:
begin fun modname -> Lident modname,
try match find_module_by_name (Lident modname) !start_env with
| _, {md_type=Mty_signature sign} ->
List2.flat_map sign ~f:
begin function
Sig_value (i, _, _) when check i -> [i, Pvalue]
| Sig_type (i, _, _, _) when check i -> [i, Ptype]
| Sig_typext (i, _, _, _) when check i -> [i, Pconstructor]
| Sig_module (i, _, _, _, _) when check i -> [i, Pmodule]
| Sig_modtype (i, _, _) when check i -> [i, Pmodtype]
| Sig_class (i, cl, _, _) when check i
|| List.exists
(get_fields ~prefix:[modname] ~sign (self_type cl.cty_type))
~f:(fun (name,_,_) -> check_match ~pattern (explode name))
-> [i, Pclass]
| Sig_class_type (i, cl, _, _) when check i
|| List.exists
(get_fields ~prefix:[modname] ~sign (self_type cl.clty_type))
~f:(fun (name,_,_) -> check_match ~pattern (explode name))
-> [i, Pcltype]
| _ -> []
end
| _ -> []
with Env.Error _ | Persistent_env.Error _ -> []
end
in
List2.flat_map l ~f:
begin fun (m, l) ->
List.map l ~f:(fun (i, p) -> Ldot (m, Ident.name i), p)
end
let is_pattern s =
try for i = 0 to String.length s -1 do
if s.[i ] = ' ? ' || s.[i ] = ' * ' then raise Exit
done ; false
with Exit - > true
let is_pattern s =
try for i = 0 to String.length s -1 do
if s.[i] = '?' || s.[i] = '*' then raise Exit
done; false
with Exit -> true
*)
let search_string_symbol text =
if text = "" then [] else
let lid = snd (longident_of_string text) [] in
let try_lookup f k =
try let _ = f lid !start_env in [lid, k]
with Not_found | Env.Error _ | Persistent_env.Error _ -> []
in
try_lookup find_constructor_by_name Pconstructor @
try_lookup find_module_by_name Pmodule @
try_lookup find_modtype_by_name Pmodtype @
try_lookup find_value_by_name Pvalue @
try_lookup find_type_by_name Ptype @
try_lookup find_label_by_name Plabel @
try_lookup find_class_by_name Pclass
open Parsetree
let rec bound_variables pat =
match pat.ppat_desc with
Ppat_any | Ppat_constant _ | Ppat_type _ | Ppat_unpack _
| Ppat_interval _ -> []
| Ppat_var s -> [s.txt]
| Ppat_alias (pat,s) -> s.txt :: bound_variables pat
| Ppat_tuple l -> List2.flat_map l ~f:bound_variables
| Ppat_construct (_,None) -> []
| Ppat_construct (_,Some (_, pat)) -> bound_variables pat
| Ppat_variant (_,None) -> []
| Ppat_variant (_,Some pat) -> bound_variables pat
| Ppat_record (l, _) ->
List2.flat_map l ~f:(fun (_,pat) -> bound_variables pat)
| Ppat_array l ->
List2.flat_map l ~f:bound_variables
| Ppat_or (pat1,pat2) ->
bound_variables pat1 @ bound_variables pat2
| Ppat_constraint (pat,_) -> bound_variables pat
| Ppat_lazy pat -> bound_variables pat
| Ppat_extension _ -> []
| Ppat_exception pat -> bound_variables pat
| Ppat_open (_, pat) -> bound_variables pat
let search_structure str ~name ~kind ~prefix =
let loc = ref 0 in
let rec search_module str ~prefix =
match prefix with [] -> str
| modu::prefix ->
let str =
List.fold_left ~init:[] str ~f:
begin fun acc item ->
match item.pstr_desc with
Pstr_module x when x.pmb_name.txt = Some modu ->
loc := x.pmb_expr.pmod_loc.loc_start.Lexing.pos_cnum;
begin match x.pmb_expr.pmod_desc with
Pmod_structure str -> str
| _ -> []
end
| _ -> acc
end
in search_module str ~prefix
in
List.iter (search_module str ~prefix) ~f:
begin fun item ->
if match item.pstr_desc with
Pstr_value (_, l) when kind = Pvalue ->
List.iter l ~f:
begin fun {pvb_pat=pat} ->
if List.mem name ~set:(bound_variables pat)
then loc := pat.ppat_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_primitive vd when kind = Pvalue -> name = vd.pval_name.txt
| Pstr_type (_, l) when kind = Ptype ->
List.iter l ~f:
begin fun td ->
if td.ptype_name.txt = name
then loc := td.ptype_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_typext l when kind = Ptype ->
List.iter l.ptyext_constructors ~f:
begin fun td ->
if td.pext_name.txt = name
then loc := td.pext_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_exception pcd when kind = Pconstructor ->
name = pcd.ptyexn_constructor.pext_name.txt
| Pstr_module x when kind = Pmodule -> Some name = x.pmb_name.txt
| Pstr_modtype x when kind = Pmodtype -> name = x.pmtd_name.txt
| Pstr_class l when kind = Pclass || kind = Ptype || kind = Pcltype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| Pstr_class_type l when kind = Pcltype || kind = Ptype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| _ -> false
then loc := item.pstr_loc.loc_start.Lexing.pos_cnum
end;
!loc
let search_signature sign ~name ~kind ~prefix =
ignore (name = "");
ignore (prefix = [""]);
let loc = ref 0 in
let rec search_module_type sign ~prefix =
match prefix with [] -> sign
| modu::prefix ->
let sign =
List.fold_left ~init:[] sign ~f:
begin fun acc item ->
match item.psig_desc with
Psig_module pmd when pmd.pmd_name.txt = Some modu ->
loc := pmd.pmd_type.pmty_loc.loc_start.Lexing.pos_cnum;
begin match pmd.pmd_type.pmty_desc with
Pmty_signature sign -> sign
| _ -> []
end
| _ -> acc
end
in search_module_type sign ~prefix
in
List.iter (search_module_type sign ~prefix) ~f:
begin fun item ->
if match item.psig_desc with
Psig_value vd when kind = Pvalue -> name = vd.pval_name.txt
| Psig_type (_, l) when kind = Ptype ->
List.iter l ~f:
begin fun td ->
if td.ptype_name.txt = name
then loc := td.ptype_loc.loc_start.Lexing.pos_cnum
end;
false
| Psig_typext l when kind = Pconstructor ->
List.iter l.ptyext_constructors ~f:
begin fun td ->
if td.pext_name.txt = name
then loc := td.pext_loc.loc_start.Lexing.pos_cnum
end;
false
| Psig_exception pcd when kind = Pconstructor ->
name = pcd.ptyexn_constructor.pext_name.txt
| Psig_module pmd when kind = Pmodule -> Some name = pmd.pmd_name.txt
| Psig_modtype pmtd when kind = Pmodtype -> name = pmtd.pmtd_name.txt
| Psig_class l when kind = Pclass || kind = Ptype || kind = Pcltype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| Psig_class_type l when kind = Ptype || kind = Pcltype ->
List.iter l ~f:
begin fun c ->
if c.pci_name.txt = name
then loc := c.pci_loc.loc_start.Lexing.pos_cnum
end;
false
| _ -> false
then loc := item.psig_loc.loc_start.Lexing.pos_cnum
end;
!loc
|
c0ab77fea78d29308b1f30898725e9ad2cb55f9af131ccf69440ffc95d92108e | OCamlPro/digodoc | headfoot.ml | (**************************************************************************)
(* *)
Copyright ( c ) 2021 OCamlPro SAS & Origin Labs SAS
(* *)
(* 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 LICENSE.md file in the root directory. *)
(* *)
(* *)
(**************************************************************************)
open Globals
open Js_of_ocaml
(** Module [Headfoot] unions functions that manipulate header and footer of the page. *)
(** {1 Header} *)
let activate_bar () =
Activate specified item
let activate item =
let item_bar = get_element_by_id item in
item_bar##.className := js "active"
in
if in_root_directory then
match filename with
| "about.html" -> activate "about-item";
| "search.html" -> activate "search-page-item";
| "packages.html" -> activate "packages-item"
| "libraries.html" -> activate "libraries-item"
| "metas.html" -> activate "metas-item"
| "modules.html" -> activate "modules-item"
| "sources.html" -> activate "sources-item"
| "fulltext_search.html" -> activate "fulltext-search-item"
| _ ->
raise @@
web_app_error (Printf.sprintf {|activate_bar : file "%s" couldn't activate the bar|} filename)
(** Activates header's item according to current page.
Activation is done only for files under the root directory.
Raise [Web_app_exception] if file under root directory doesn't have header's item. *)
(** {1 Footer} *)
let hider () =
let footer = get_element_by_id "footer" in
footer##.style##.opacity := js "0" |> Js.Optdef.return
(** Hide footer *)
let footerHandler () =
let footer = get_element_by_id "footer" in
(* Footer is rendered after the last element. This is used to calculate correct client height *)
(* footer##.style##.opacity := js "0" |> Js.Optdef.return; *)
footer##.style##.position := js "relative";
let innerHeight = unoptdef @@ window##.innerHeight
and clientHeight = document##.body##.clientHeight in
(* If page height is bigger than window height *)
if innerHeight <= clientHeight
then footer##.style##.position := js "relative"
else footer##.style##.position := js "fixed";
footer##.style##.opacity := js "1" |> Js.Optdef.return
(** Handler that places footer correctly according to the page height *) | null | https://raw.githubusercontent.com/OCamlPro/digodoc/a781c251b3b6ef94badbaea1cfd8dc176d47d364/src/frontend/headfoot.ml | ocaml | ************************************************************************
All rights reserved.
This file is distributed under the terms of the GNU Lesser General
described in the LICENSE.md file in the root directory.
************************************************************************
* Module [Headfoot] unions functions that manipulate header and footer of the page.
* {1 Header}
* Activates header's item according to current page.
Activation is done only for files under the root directory.
Raise [Web_app_exception] if file under root directory doesn't have header's item.
* {1 Footer}
* Hide footer
Footer is rendered after the last element. This is used to calculate correct client height
footer##.style##.opacity := js "0" |> Js.Optdef.return;
If page height is bigger than window height
* Handler that places footer correctly according to the page height | Copyright ( c ) 2021 OCamlPro SAS & Origin Labs SAS
Public License version 2.1 , with the special exception on linking
open Globals
open Js_of_ocaml
let activate_bar () =
Activate specified item
let activate item =
let item_bar = get_element_by_id item in
item_bar##.className := js "active"
in
if in_root_directory then
match filename with
| "about.html" -> activate "about-item";
| "search.html" -> activate "search-page-item";
| "packages.html" -> activate "packages-item"
| "libraries.html" -> activate "libraries-item"
| "metas.html" -> activate "metas-item"
| "modules.html" -> activate "modules-item"
| "sources.html" -> activate "sources-item"
| "fulltext_search.html" -> activate "fulltext-search-item"
| _ ->
raise @@
web_app_error (Printf.sprintf {|activate_bar : file "%s" couldn't activate the bar|} filename)
let hider () =
let footer = get_element_by_id "footer" in
footer##.style##.opacity := js "0" |> Js.Optdef.return
let footerHandler () =
let footer = get_element_by_id "footer" in
footer##.style##.position := js "relative";
let innerHeight = unoptdef @@ window##.innerHeight
and clientHeight = document##.body##.clientHeight in
if innerHeight <= clientHeight
then footer##.style##.position := js "relative"
else footer##.style##.position := js "fixed";
footer##.style##.opacity := js "1" |> Js.Optdef.return |
8af227566b0dbb956705dc49f8d004a590e7040a660f37ae8f8507cb8fce9586 | tek/helic | NetConfig.hs | {-# options_haddock prune #-}
|NetConfig Data Type , Internal
module Helic.Data.NetConfig where
import Polysemy.Time.Json (json)
import Helic.Data.Host (Host)
newtype Timeout =
Timeout { unTimeout :: Int }
deriving stock (Eq, Show, Generic)
deriving newtype (Num, Real, Enum, Integral, Ord)
json ''Timeout
data NetConfig =
NetConfig {
port :: Maybe Int,
timeout :: Maybe Timeout,
hosts :: Maybe [Host]
}
deriving stock (Eq, Show, Generic)
deriving anyclass (Default)
json ''NetConfig
| null | https://raw.githubusercontent.com/tek/helic/055b2ffa063936ad4ae6249c9e6e0603482baaa9/packages/helic/lib/Helic/Data/NetConfig.hs | haskell | # options_haddock prune # |
|NetConfig Data Type , Internal
module Helic.Data.NetConfig where
import Polysemy.Time.Json (json)
import Helic.Data.Host (Host)
newtype Timeout =
Timeout { unTimeout :: Int }
deriving stock (Eq, Show, Generic)
deriving newtype (Num, Real, Enum, Integral, Ord)
json ''Timeout
data NetConfig =
NetConfig {
port :: Maybe Int,
timeout :: Maybe Timeout,
hosts :: Maybe [Host]
}
deriving stock (Eq, Show, Generic)
deriving anyclass (Default)
json ''NetConfig
|
d62c2764779699c960709daf99c1c2973da939b99d7e033c541ca1fae98e4d08 | chaoxu/fancy-walks | template_codejam.hs | {-# OPTIONS_GHC -O2 #-}
import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Control.Parallel.Strategies
parseInput = do
cas <- readInt
replicateM cas $ do
a <- readInt
b <- readInt
return (a, b)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = do
input <- evalState parseInput <$> BS.getContents
let output = parMap rdeepseq solve input
forM_ (zip [1..] output) $ \(cas, result) -> do
putStrLn $ "Case #" ++ show cas ++ ": " ++ show result
solve (a, b) = a + b
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/templates/template_codejam.hs | haskell | # OPTIONS_GHC -O2 # |
import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph
import Control.Parallel.Strategies
parseInput = do
cas <- readInt
replicateM cas $ do
a <- readInt
b <- readInt
return (a, b)
where
readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
isEoln ch = ch == '\r' || ch == '\n'
main = do
input <- evalState parseInput <$> BS.getContents
let output = parMap rdeepseq solve input
forM_ (zip [1..] output) $ \(cas, result) -> do
putStrLn $ "Case #" ++ show cas ++ ": " ++ show result
solve (a, b) = a + b
|
2595aa374f4fdf88c3139fb0f77c3d16cd4c01d043caf86f1d2acd54c4f9f291 | kappelmann/eidi2_repetitorium_tum | SparseVector.ml | let todo _ = failwith "Something is not implemented!"
type v = todo
let empty = todo
let sb_vektor = todo
let set = todo
let mul = todo
let add_sb_vektor = todo
let mul_sb_vektor = todo
| null | https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/2016/sparse_vector/exercises/SparseVector.ml | ocaml | let todo _ = failwith "Something is not implemented!"
type v = todo
let empty = todo
let sb_vektor = todo
let set = todo
let mul = todo
let add_sb_vektor = todo
let mul_sb_vektor = todo
|
|
0902368fbe52b2ec72c0040688364c2c737eddf4d8e924c87ea6050a86508c8b | JonasDuregard/sized-functors | Derive.hs | {-#Language CPP#-}
{-#Language TemplateHaskell#-}
module Control.Enumerable.Derive (instanceFor, module Language.Haskell.TH) where
import Language.Haskell.TH
-- General combinator for class derivation
instanceFor :: Name -> [[(Name,[Type])] -> Q Dec] -> Name -> Q Dec
instanceFor clname confs dtname = do
(cxt,dtvs,cons) <- extractData dtname
cd <- mapM conData cons
let
#if MIN_VERSION_template_haskell(2,10,0)
mkCxt = fmap (cxt++) $ mapM (appT (conT clname) . varT) dtvs
#else
mkCxt = fmap (cxt++) $ mapM (classP clname . return . varT) dtvs
#endif
mkTyp = mkInstanceType clname dtname dtvs
mkDecs conf = conf cd
instanceD mkCxt mkTyp (map mkDecs confs)
mkInstanceType :: Name -> Name -> [Name] -> Q Type
mkInstanceType cn dn vns = appT (conT cn) (foldl (appT) (conT dn) (map varT vns))
extractData :: Name -> Q (Cxt, [Name], [Con])
extractData n = reify n >>= \i -> return $ case i of
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (DataD cxt _ tvbs _ cons _) -> (cxt, map tvbName tvbs, cons)
TyConI (NewtypeD cxt _ tvbs _ con _) -> (cxt, map tvbName tvbs, [con])
#else
TyConI (DataD cxt _ tvbs cons _) -> (cxt, map tvbName tvbs, cons)
TyConI (NewtypeD cxt _ tvbs con _) -> (cxt, map tvbName tvbs, [con])
#endif
tvbName :: TyVarBndr -> Name
tvbName (PlainTV n) = n
tvbName (KindedTV n _) = n
conData :: Con -> Q (Name,[Type])
conData c = case c of
NormalC n sts -> return (n,map snd sts)
RecC n vsts -> return (n,map (\(_,s,t) -> t) vsts)
InfixC st1 n st2 -> return (n,[snd st1,snd st2])
ForallC _ _ c' -> conData c'
x :: IO Type
x = runQ $ (toType ''(,))
toType n = case lookup n tups of
Nothing -> conT n
Just q -> q
tups = (''(), [t|()|]):map (\(n,i) -> (n, tupleT i)) (zip [''(,), ''(,,)] [2..])
| null | https://raw.githubusercontent.com/JonasDuregard/sized-functors/d76bb90ec31b915f9b2469e056a910c30eab5fa3/Control/Enumerable/Derive.hs | haskell | #Language CPP#
#Language TemplateHaskell#
General combinator for class derivation | module Control.Enumerable.Derive (instanceFor, module Language.Haskell.TH) where
import Language.Haskell.TH
instanceFor :: Name -> [[(Name,[Type])] -> Q Dec] -> Name -> Q Dec
instanceFor clname confs dtname = do
(cxt,dtvs,cons) <- extractData dtname
cd <- mapM conData cons
let
#if MIN_VERSION_template_haskell(2,10,0)
mkCxt = fmap (cxt++) $ mapM (appT (conT clname) . varT) dtvs
#else
mkCxt = fmap (cxt++) $ mapM (classP clname . return . varT) dtvs
#endif
mkTyp = mkInstanceType clname dtname dtvs
mkDecs conf = conf cd
instanceD mkCxt mkTyp (map mkDecs confs)
mkInstanceType :: Name -> Name -> [Name] -> Q Type
mkInstanceType cn dn vns = appT (conT cn) (foldl (appT) (conT dn) (map varT vns))
extractData :: Name -> Q (Cxt, [Name], [Con])
extractData n = reify n >>= \i -> return $ case i of
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (DataD cxt _ tvbs _ cons _) -> (cxt, map tvbName tvbs, cons)
TyConI (NewtypeD cxt _ tvbs _ con _) -> (cxt, map tvbName tvbs, [con])
#else
TyConI (DataD cxt _ tvbs cons _) -> (cxt, map tvbName tvbs, cons)
TyConI (NewtypeD cxt _ tvbs con _) -> (cxt, map tvbName tvbs, [con])
#endif
tvbName :: TyVarBndr -> Name
tvbName (PlainTV n) = n
tvbName (KindedTV n _) = n
conData :: Con -> Q (Name,[Type])
conData c = case c of
NormalC n sts -> return (n,map snd sts)
RecC n vsts -> return (n,map (\(_,s,t) -> t) vsts)
InfixC st1 n st2 -> return (n,[snd st1,snd st2])
ForallC _ _ c' -> conData c'
x :: IO Type
x = runQ $ (toType ''(,))
toType n = case lookup n tups of
Nothing -> conT n
Just q -> q
tups = (''(), [t|()|]):map (\(n,i) -> (n, tupleT i)) (zip [''(,), ''(,,)] [2..])
|
dff3571566e0e4f086af7280a13102cadbf0d510a88fa7e18b5e118cedaff962 | mschuldt/ga144 | common.rkt | #lang racket ;; -*- lexical-binding: t -*-
(require compatibility/defmacro
"rom.rkt"
"rom-dump.rkt"
"el.rkt")
(provide (all-defined-out))
TODO : compile arbitrarily large programs per node but warn if > 64 words
(define num-nodes 144)
(define opcodes (vector ";" "ex" "jump" "call" "unext" "next" "if"
"-if" "@p" "@+" "@b" "@" "!p" "!+" "!b" "!" "+*"
"2*" "2/" "-" "+" "and" "or" "drop" "dup" "pop"
"over" "a" "." "push" "b!" "a!"))
from DB002 . Typical time . pico seconds
(define opcode-time '((";" . 5200)
("ex" . 5200)
("jump" . 5200)
("call" . 5200)
("unext" . 2400)
("next" . 5200)
("if" . 5200)
("-if" . 5200)
("@p" . 5000) ;; TODO @p time is slot dependent
3500 when reading from IO register
("@b" . 5000)
("@" . 5000)
("!p" . 5000)
("!+" . 5000)
("!b" . 5000)
("!" . 5000)
("+*" . 1400)
("2*" . 1400)
("2/" . 1400)
("-" . 1400)
("+" . 1400)
("and" . 1400)
("or" . 1400)
("drop" . 1400)
("dup" . 1400)
("pop" . 1400)
("over" . 1400)
("a" . 1400)
("." . 1400)
("push" . 1400)
("b!" . 1400)
("a!" . 1400)))
(define opcode-time-v (list->vector (map cdr opcode-time)))
(define opcode-set (list->set (vector->list opcodes)))
(defconst address-required '("jump" "call" "next" "if" "-if"))
(defconst last-slot-instructions
'(";" "unext" "@p" "!p" "+*" "+" "dup" "." ))
(defconst instructions-preceded-by-nops '("+" "+*"))
(defconst instructions-using-rest-of-word '(";" "ex"))
(defconst named-addresses '(("right" . #x1D5)
("down" . #x115)
("left" . #x175)
("up" . #x145)
("io" . #x15D)
("ldata" . #x171)
("data" . #x141)
("warp" . #x157)
("center" . #x1A5)
("top" . #x1B5)
("side" . #x185)
("corner" . #x195)))
(define addresses->names (make-hash (for/list ((x named-addresses))
(cons (cdr x) (car x)))))
(define names->addresses (make-hash named-addresses))
(define (port-name address)
(hash-ref addresses->names address))
(define io-places '(("---u" . #x145)
("--l-" . #x175)
("--lu" . #x165)
("-d--" . #x115)
("-d-u" . #x105)
("-dl-" . #x135)
("-dlu" . #x125)
("r---" . #x1D5)
("r--u" . #x1C5)
("r-l-" . #x1F5)
("r-lu" . #x1E5)
("rd--" . #x195)
("rd-u" . #x185)
("rdl-" . #x1B5)
("rdlu" . #x1A5)))
(define node-to-gpio-pins '((701 . 2)
(705 . 4)
(708 . 2)
(715 . 1)
(517 . 1)
(417 . 1)
(317 . 1)
(217 . 1)
(008 . 4)
(001 . 2)
(100 . 1)
(200 . 1)
(300 . 2)
(500 . 1)
(600 . 1)))
(define address-names (make-hash (map (lambda (x) (cons (cdr x) (car x)))
(append named-addresses io-places))))
325
277
373
469
(defconst &IO #x15d)
(defconst &DATA #x141)
(defconst &---U #x145)
(defconst &--L- #x175)
(defconst &--LU #x165)
(defconst &-D-- #x115)
(defconst &-D-U #x105)
(defconst &-DL- #x135)
(defconst &-DLU #x125)
(defconst &R--- #x1D5)
(defconst &R--U #x1C5)
(defconst &R-L- #x1F5)
(defconst &R-LU #x1E5)
(defconst &RD-- #x195)
(defconst &RD-U #x185)
(defconst &RDL- #x1B5)
(defconst &RDLU #x1A5)
(defconst MEM-SIZE #x301)
(define rom-ht (make-hash ROM-DUMP))
(define basic-rom-ht (make-hash basic-rom))
(define analog-rom-ht (make-hash analog-rom))
(define serdes-boot-rom-ht (make-hash serdes-boot-rom))
(define sync-boot-rom-ht (make-hash sync-boot-rom))
(define async-boot-rom-ht (make-hash async-boot-rom))
(define spi-boot-rom-ht (make-hash spi-boot-rom))
(define 1-wire-rom-ht (make-hash 1-wire-rom))
(define SDRAM-addr-rom-ht (make-hash SDRAM-addr-rom))
(define SDRAM-control-rom-ht (make-hash SDRAM-control-rom))
(define SDRAM-data-rom-ht (make-hash SDRAM-data-rom))
(define eForth-bitsy-rom-ht (make-hash eForth-bitsy-rom))
(define eForth-stack-rom-ht (make-hash eForth-stack-rom))
(define SDRAM-mux-rom-ht (make-hash SDRAM-mux-rom))
(define SDRAM-idle-rom-ht (make-hash SDRAM-idle-rom))
from section 2.3 , DB002
(defconst analog-nodes '(709 713 717 617 117))
(defconst serdes-nodes '(1 701))
(defconst sync-boot-nodes '(300))
(defconst async-boot-nodes '(708))
(defconst spi-boot-nodes '(705))
(defconst 1-wire-nodes '(200))
(defconst SDRAM-addr-node 9)
(defconst SDRAM-control-node 8)
(defconst SDRAM-data-node 7)
(defconst eForth-Bitsy-node 105)
(defconst eForth-stack-node 106)
(defconst SDRAM-mux-node 107)
(defconst SDRAM-idle-node 108)
(defconst node-rom-type `((300 . ,sync-boot-rom-ht)
(708 . ,async-boot-rom-ht)
(705 . ,spi-boot-rom-ht)
(200 . ,1-wire-rom-ht )
(9 . ,SDRAM-addr-rom-ht)
(8 . ,SDRAM-control-rom-ht)
(7 . ,SDRAM-data-rom-ht)
(105 . ,eForth-bitsy-rom-ht)
(106 . ,eForth-stack-rom-ht)
(107 . ,SDRAM-mux-rom-ht)
(108 . ,SDRAM-idle-rom-ht)))
(define (get-node-rom node)
(let ((nodes false))
(cond ((member node analog-nodes) analog-rom-ht)
((member node serdes-nodes) serdes-boot-rom-ht)
((setq nodes (assoc node node-rom-type))
(cdr nodes))
(else basic-rom-ht))))
;; This is the type that holds compiled code and other node info.
;; Compiling a program returns a list of these
(struct node (coord mem buffer-map len (symbols #:auto) (word-dict #:auto)
(a #:auto) (b #:auto) (io #:auto) (stack #:auto) (p #:auto)
(address-cells #:auto) (consts #:auto) (extern-funcs #:auto))
#:mutable #:transparent)
;; 'coord' is the node coordinate this code belongs to
;; 'mem' is the vector of compiled words
;; 'len' is how many instructions are used in mem. len <= length(mem)
;; the remaining words in mem are all #f
;; 'symbols' a list of symbol structs
(struct compiled (nodes (error-info #:auto) (node-locations #:auto) ) #:mutable #:transparent)
;; struct to hold compiled code
;; 'nodes': list of 'node' structs
;; 'error-info': struct error-info
(struct symbol (val address line col))
(struct token (tok line col))
(struct bootstream (name start path))
(struct address-cell (val next-addr name (type #:auto)) #:mutable #:transparent)
load through node 708 serial
load through node 300 2wire
in host node 708 to target node 300
))
(define default-bootstream-type "async")
(define (create-node coord (mem false) (buffer-map false) (len 0) (buffer false))
(let ((new (node coord mem buffer-map len buffer)))
(set-node-symbols! new (list))
(set-node-word-dict! new (make-hash))
(set-node-address-cells! new (make-set))
(set-node-consts! new (make-hash))
new))
(define (coord->index n)
(+ (* (quotient n 100) 18) (remainder n 100)))
(define (index->coord n)
(+ (* (quotient n 18) 100) (remainder n 18)))
(define (coord->row coord)
(quotient coord 100))
(define (coord->col coord)
(remainder coord 100))
(define (valid-coord? coord)
(and (>= coord 0)
(< (modulo coord 100) 18)
(< (/ coord 100) 8)))
(define (convert-direction coord dir)
converts DIR={North , East , South , West } Into Left , Up , Down , or Right
depending on the nodes coordinate COORD
(let ((x (remainder coord 100))
(y (quotient coord 100)))
(cond
((equal? dir "north")
(if (= (modulo y 2) 0) "down" "up"))
((equal? dir "south")
(if (= (modulo y 2) 0) "up" "down"))
((equal? dir "east")
(if (= (modulo x 2) 0) "right" "left"))
((equal? dir "west")
(if (= (modulo x 2) 0) "left" "right"))
(else (raise "convert-direction: invalid direction")))))
;;successfully parses a token as a number, or returns false
(define (parse-num tok)
(define base nil)
(cond ((number? tok)
tok)
((string? tok)
(if (and (> (string-length tok) 2)
(eq? (string-ref tok 0) _char-0)
(or (and (eq? (string-ref tok 1) _char-x)
(setq base 16))
(and (eq? (string-ref tok 1) _char-b)
(setq base 2))))
(if elisp?
(string->number (subseq tok 2) base)
convert format 0x ... to # x ...
(begin (set! tok (list->string (cons _char-hash (cdr (string->list tok)))))
(string->number tok)))
(string->number tok)))
(else (error (rkt-format "parse-num -- invalid arg type ~a" tok)))))
(define (get-address name (node false))
(cond ((hash-has-key? names->addresses name) ;;normal address names
(hash-ref names->addresses name))
((and node ;;relative names
(member name '("north" "south" "east" "west")))
(cdr (assoc (convert-direction node name) named-addresses)))
((and node
(assoc name named-addresses))
(cdr (assoc name named-addresses)))
(else (parse-num name)))) ;; literals and word addresses
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;stack macros
(defmacro swap (stack)
`(if (> (length ,stack) 1)
(set! ,stack (cons (cadr ,stack) (cons (car ,stack) (cddr ,stack))))
(error "swap! requires stack depth of 2")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro enum (syms)
(let ((i 0)
(code '()))
(for ((sym syms))
(set! code (cons (list 'define sym i) code))
(set! i (add1 i)))
(cons 'begin code)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (& a b)
(bitwise-and a b))
(define (^ a b)
(bitwise-xor a b))
(define (<< a b)
(arithmetic-shift a b))
(define (>> x n) (arithmetic-shift x (- n)))
(define (ior a b)
(bitwise-ior a b))
(define (~ x)
(bitwise-not x))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(enum (LEFT UP DOWN RIGHT))
(defconst port-names (vector "LEFT" "UP" "DOWN" "RIGHT"))
(enum (N E S W))
(define (get-direction coord dir)
converts dir={N , E , S , W } into an address for node COORD
(define dir-names (vector "north" "east" "south" "west"))
(cdr (assoc (convert-direction coord
(vector-ref dir-names dir))
named-addresses)))
(define (comma-join things)
(when (vector? things)
(set! things (vector->list things)))
(string-join (for/list ((thing things))
(cond ((string? thing)
thing)
((number? thing)
(number->string thing))
;(else (raise "invalid thing"))
(else (rkt-format "~a" thing))
))
","))
(define (port-addr? addr)
True if ADDR is an IO port or register , else False
(> (& addr #x100) 0))
Determine if we are in RAM or ROM , return the index for that memory location
DB001 section 2.2 Top half of RAM and ROM is repeated
(define (region-index addr)
(if (port-addr? addr)
addr
(begin
(set! addr (& addr #xff)) ;; get rid of extended arithmetic bit
(if (>= addr #x80);;ROM
(if (> addr #xbf)
(- addr #x40)
addr)
(if (> addr #x3F)
(- addr #x40)
addr)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; compiler options
(define auto-nop-insertion false)
(define compile-0-as-dup-dup-or false)
(define reorder-words-with-fallthrough false)
| null | https://raw.githubusercontent.com/mschuldt/ga144/5b327b958f5d35cf5a015044e6ee62f46446169f/src/common.rkt | racket | -*- lexical-binding: t -*-
TODO @p time is slot dependent
This is the type that holds compiled code and other node info.
Compiling a program returns a list of these
'coord' is the node coordinate this code belongs to
'mem' is the vector of compiled words
'len' is how many instructions are used in mem. len <= length(mem)
the remaining words in mem are all #f
'symbols' a list of symbol structs
struct to hold compiled code
'nodes': list of 'node' structs
'error-info': struct error-info
successfully parses a token as a number, or returns false
normal address names
relative names
literals and word addresses
stack macros
(else (raise "invalid thing"))
get rid of extended arithmetic bit
ROM
compiler options |
(require compatibility/defmacro
"rom.rkt"
"rom-dump.rkt"
"el.rkt")
(provide (all-defined-out))
TODO : compile arbitrarily large programs per node but warn if > 64 words
(define num-nodes 144)
(define opcodes (vector ";" "ex" "jump" "call" "unext" "next" "if"
"-if" "@p" "@+" "@b" "@" "!p" "!+" "!b" "!" "+*"
"2*" "2/" "-" "+" "and" "or" "drop" "dup" "pop"
"over" "a" "." "push" "b!" "a!"))
from DB002 . Typical time . pico seconds
(define opcode-time '((";" . 5200)
("ex" . 5200)
("jump" . 5200)
("call" . 5200)
("unext" . 2400)
("next" . 5200)
("if" . 5200)
("-if" . 5200)
3500 when reading from IO register
("@b" . 5000)
("@" . 5000)
("!p" . 5000)
("!+" . 5000)
("!b" . 5000)
("!" . 5000)
("+*" . 1400)
("2*" . 1400)
("2/" . 1400)
("-" . 1400)
("+" . 1400)
("and" . 1400)
("or" . 1400)
("drop" . 1400)
("dup" . 1400)
("pop" . 1400)
("over" . 1400)
("a" . 1400)
("." . 1400)
("push" . 1400)
("b!" . 1400)
("a!" . 1400)))
(define opcode-time-v (list->vector (map cdr opcode-time)))
(define opcode-set (list->set (vector->list opcodes)))
(defconst address-required '("jump" "call" "next" "if" "-if"))
(defconst last-slot-instructions
'(";" "unext" "@p" "!p" "+*" "+" "dup" "." ))
(defconst instructions-preceded-by-nops '("+" "+*"))
(defconst instructions-using-rest-of-word '(";" "ex"))
(defconst named-addresses '(("right" . #x1D5)
("down" . #x115)
("left" . #x175)
("up" . #x145)
("io" . #x15D)
("ldata" . #x171)
("data" . #x141)
("warp" . #x157)
("center" . #x1A5)
("top" . #x1B5)
("side" . #x185)
("corner" . #x195)))
(define addresses->names (make-hash (for/list ((x named-addresses))
(cons (cdr x) (car x)))))
(define names->addresses (make-hash named-addresses))
(define (port-name address)
(hash-ref addresses->names address))
(define io-places '(("---u" . #x145)
("--l-" . #x175)
("--lu" . #x165)
("-d--" . #x115)
("-d-u" . #x105)
("-dl-" . #x135)
("-dlu" . #x125)
("r---" . #x1D5)
("r--u" . #x1C5)
("r-l-" . #x1F5)
("r-lu" . #x1E5)
("rd--" . #x195)
("rd-u" . #x185)
("rdl-" . #x1B5)
("rdlu" . #x1A5)))
(define node-to-gpio-pins '((701 . 2)
(705 . 4)
(708 . 2)
(715 . 1)
(517 . 1)
(417 . 1)
(317 . 1)
(217 . 1)
(008 . 4)
(001 . 2)
(100 . 1)
(200 . 1)
(300 . 2)
(500 . 1)
(600 . 1)))
(define address-names (make-hash (map (lambda (x) (cons (cdr x) (car x)))
(append named-addresses io-places))))
325
277
373
469
(defconst &IO #x15d)
(defconst &DATA #x141)
(defconst &---U #x145)
(defconst &--L- #x175)
(defconst &--LU #x165)
(defconst &-D-- #x115)
(defconst &-D-U #x105)
(defconst &-DL- #x135)
(defconst &-DLU #x125)
(defconst &R--- #x1D5)
(defconst &R--U #x1C5)
(defconst &R-L- #x1F5)
(defconst &R-LU #x1E5)
(defconst &RD-- #x195)
(defconst &RD-U #x185)
(defconst &RDL- #x1B5)
(defconst &RDLU #x1A5)
(defconst MEM-SIZE #x301)
(define rom-ht (make-hash ROM-DUMP))
(define basic-rom-ht (make-hash basic-rom))
(define analog-rom-ht (make-hash analog-rom))
(define serdes-boot-rom-ht (make-hash serdes-boot-rom))
(define sync-boot-rom-ht (make-hash sync-boot-rom))
(define async-boot-rom-ht (make-hash async-boot-rom))
(define spi-boot-rom-ht (make-hash spi-boot-rom))
(define 1-wire-rom-ht (make-hash 1-wire-rom))
(define SDRAM-addr-rom-ht (make-hash SDRAM-addr-rom))
(define SDRAM-control-rom-ht (make-hash SDRAM-control-rom))
(define SDRAM-data-rom-ht (make-hash SDRAM-data-rom))
(define eForth-bitsy-rom-ht (make-hash eForth-bitsy-rom))
(define eForth-stack-rom-ht (make-hash eForth-stack-rom))
(define SDRAM-mux-rom-ht (make-hash SDRAM-mux-rom))
(define SDRAM-idle-rom-ht (make-hash SDRAM-idle-rom))
from section 2.3 , DB002
(defconst analog-nodes '(709 713 717 617 117))
(defconst serdes-nodes '(1 701))
(defconst sync-boot-nodes '(300))
(defconst async-boot-nodes '(708))
(defconst spi-boot-nodes '(705))
(defconst 1-wire-nodes '(200))
(defconst SDRAM-addr-node 9)
(defconst SDRAM-control-node 8)
(defconst SDRAM-data-node 7)
(defconst eForth-Bitsy-node 105)
(defconst eForth-stack-node 106)
(defconst SDRAM-mux-node 107)
(defconst SDRAM-idle-node 108)
(defconst node-rom-type `((300 . ,sync-boot-rom-ht)
(708 . ,async-boot-rom-ht)
(705 . ,spi-boot-rom-ht)
(200 . ,1-wire-rom-ht )
(9 . ,SDRAM-addr-rom-ht)
(8 . ,SDRAM-control-rom-ht)
(7 . ,SDRAM-data-rom-ht)
(105 . ,eForth-bitsy-rom-ht)
(106 . ,eForth-stack-rom-ht)
(107 . ,SDRAM-mux-rom-ht)
(108 . ,SDRAM-idle-rom-ht)))
(define (get-node-rom node)
(let ((nodes false))
(cond ((member node analog-nodes) analog-rom-ht)
((member node serdes-nodes) serdes-boot-rom-ht)
((setq nodes (assoc node node-rom-type))
(cdr nodes))
(else basic-rom-ht))))
(struct node (coord mem buffer-map len (symbols #:auto) (word-dict #:auto)
(a #:auto) (b #:auto) (io #:auto) (stack #:auto) (p #:auto)
(address-cells #:auto) (consts #:auto) (extern-funcs #:auto))
#:mutable #:transparent)
(struct compiled (nodes (error-info #:auto) (node-locations #:auto) ) #:mutable #:transparent)
(struct symbol (val address line col))
(struct token (tok line col))
(struct bootstream (name start path))
(struct address-cell (val next-addr name (type #:auto)) #:mutable #:transparent)
load through node 708 serial
load through node 300 2wire
in host node 708 to target node 300
))
(define default-bootstream-type "async")
(define (create-node coord (mem false) (buffer-map false) (len 0) (buffer false))
(let ((new (node coord mem buffer-map len buffer)))
(set-node-symbols! new (list))
(set-node-word-dict! new (make-hash))
(set-node-address-cells! new (make-set))
(set-node-consts! new (make-hash))
new))
(define (coord->index n)
(+ (* (quotient n 100) 18) (remainder n 100)))
(define (index->coord n)
(+ (* (quotient n 18) 100) (remainder n 18)))
(define (coord->row coord)
(quotient coord 100))
(define (coord->col coord)
(remainder coord 100))
(define (valid-coord? coord)
(and (>= coord 0)
(< (modulo coord 100) 18)
(< (/ coord 100) 8)))
(define (convert-direction coord dir)
converts DIR={North , East , South , West } Into Left , Up , Down , or Right
depending on the nodes coordinate COORD
(let ((x (remainder coord 100))
(y (quotient coord 100)))
(cond
((equal? dir "north")
(if (= (modulo y 2) 0) "down" "up"))
((equal? dir "south")
(if (= (modulo y 2) 0) "up" "down"))
((equal? dir "east")
(if (= (modulo x 2) 0) "right" "left"))
((equal? dir "west")
(if (= (modulo x 2) 0) "left" "right"))
(else (raise "convert-direction: invalid direction")))))
(define (parse-num tok)
(define base nil)
(cond ((number? tok)
tok)
((string? tok)
(if (and (> (string-length tok) 2)
(eq? (string-ref tok 0) _char-0)
(or (and (eq? (string-ref tok 1) _char-x)
(setq base 16))
(and (eq? (string-ref tok 1) _char-b)
(setq base 2))))
(if elisp?
(string->number (subseq tok 2) base)
convert format 0x ... to # x ...
(begin (set! tok (list->string (cons _char-hash (cdr (string->list tok)))))
(string->number tok)))
(string->number tok)))
(else (error (rkt-format "parse-num -- invalid arg type ~a" tok)))))
(define (get-address name (node false))
(hash-ref names->addresses name))
(member name '("north" "south" "east" "west")))
(cdr (assoc (convert-direction node name) named-addresses)))
((and node
(assoc name named-addresses))
(cdr (assoc name named-addresses)))
(defmacro swap (stack)
`(if (> (length ,stack) 1)
(set! ,stack (cons (cadr ,stack) (cons (car ,stack) (cddr ,stack))))
(error "swap! requires stack depth of 2")))
(defmacro enum (syms)
(let ((i 0)
(code '()))
(for ((sym syms))
(set! code (cons (list 'define sym i) code))
(set! i (add1 i)))
(cons 'begin code)))
(define (& a b)
(bitwise-and a b))
(define (^ a b)
(bitwise-xor a b))
(define (<< a b)
(arithmetic-shift a b))
(define (>> x n) (arithmetic-shift x (- n)))
(define (ior a b)
(bitwise-ior a b))
(define (~ x)
(bitwise-not x))
(enum (LEFT UP DOWN RIGHT))
(defconst port-names (vector "LEFT" "UP" "DOWN" "RIGHT"))
(enum (N E S W))
(define (get-direction coord dir)
converts dir={N , E , S , W } into an address for node COORD
(define dir-names (vector "north" "east" "south" "west"))
(cdr (assoc (convert-direction coord
(vector-ref dir-names dir))
named-addresses)))
(define (comma-join things)
(when (vector? things)
(set! things (vector->list things)))
(string-join (for/list ((thing things))
(cond ((string? thing)
thing)
((number? thing)
(number->string thing))
(else (rkt-format "~a" thing))
))
","))
(define (port-addr? addr)
True if ADDR is an IO port or register , else False
(> (& addr #x100) 0))
Determine if we are in RAM or ROM , return the index for that memory location
DB001 section 2.2 Top half of RAM and ROM is repeated
(define (region-index addr)
(if (port-addr? addr)
addr
(begin
(if (> addr #xbf)
(- addr #x40)
addr)
(if (> addr #x3F)
(- addr #x40)
addr)))))
(define auto-nop-insertion false)
(define compile-0-as-dup-dup-or false)
(define reorder-words-with-fallthrough false)
|
0b4149c21a9fe435c1bc713cdec862f836a67053c662f04ae289dea9a23514ee | ghc/testsuite | tcfail101.hs | This one broke GHC 5.02 , because of the unsaturated
-- uses of type synonyms, which are nevertheless kind-correct.
module ShouldCompile where
type A i = i
data T k = MkT (k Int)
f :: T A -- BAD!
f = error "foo"
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_fail/tcfail101.hs | haskell | uses of type synonyms, which are nevertheless kind-correct.
BAD! | This one broke GHC 5.02 , because of the unsaturated
module ShouldCompile where
type A i = i
data T k = MkT (k Int)
f = error "foo"
|
d35707e2a37f3cb9b9ce36630ef2bcfe769f4bb4c57bc26fbe98620e685df510 | unclebob/more-speech | tab_searcher.clj | (ns more-speech.nostr.tab-searcher
(:use [seesaw core font tree])
(:require [more-speech.nostr.util :as util]
[more-speech.mem :refer :all]
[more-speech.config :refer [get-db]]
[more-speech.ui.formatters :as formatters]
[more-speech.bech32 :as bech32]
[more-speech.db.gateway :as gateway]
[more-speech.nostr.contact-list :as contact-list]
[more-speech.ui.swing.article-tree-util :as at-util]
[more-speech.config :as config]))
(defn get-subject [event]
(let [subject-tags (filter #(= :subject (first %)) (:tags event))]
(second (first subject-tags))))
(defn id-matches-tag [id tags]
(some #(= (util/hexify id) (second %)) tags))
(defn match-id [id event]
(or (= id (:pubkey event))
(= id (:id event))
(id-matches-tag id (:tags event))))
(defn match-hex-id [target event]
(let [id (util/unhexify target)]
(match-id id event)))
(defn match-string-target [target event]
(let [content (formatters/replace-references event)
author-name (:name (gateway/get-profile (get-db) (:pubkey event)))
author-id (contact-list/get-pubkey-from-petname target)
author-id (or author-id (gateway/get-id-from-username (get-db) target))
petname (contact-list/get-petname (:pubkey event))
subject (get-subject event)
re-target (re-pattern target)]
(or (re-find re-target content)
(and subject (re-find re-target subject))
(and author-name (re-find re-target author-name))
(and petname (re-find re-target petname))
(and author-id (match-id author-id event)))))
(defn match-npub [target event]
(match-id (bech32/address->number target) event))
(defn is-npub? [target]
(try
(bech32/address->number target)
true
(catch Exception _e
false)))
(defn match-target [target event]
(cond
(is-npub? target)
(match-npub target event)
(re-matches #"\#\".*\"" target)
(match-string-target (read-string target) event)
(re-matches config/hex-key-pattern target)
(match-hex-id target event)
:else
(match-string-target target event)))
(defn get-search-target [tab-name]
(let [search-id (keyword (str "#" tab-name "-search"))
search-text (select (get-mem :frame) [search-id])
target-text (config search-text :text)]
target-text))
(defn get-status-field [tab-name]
(let [status-id (keyword (str "#" tab-name "-status"))
status-field (select (get-mem :frame) [status-id])]
status-field))
(defn set-search-status [tab-name status]
(let [status-field (get-status-field tab-name)]
(config! status-field :text status)))
(defn event-matches [target id]
(let [event (gateway/get-event (get-db) id)]
(match-target target event)))
(defn add-id-to-results [[target n results] id]
[target n (conj results id)])
(defn update-search-status [tab-name]
(let [[_ n results] (get-mem [:tab-search tab-name])]
(set-search-status tab-name (format "%d of %d" n (count results)))))
(defn inc-n [[target n results]]
(if (zero? (count results))
[target n results]
(let [next-n (if (= n (count results)) 1 (inc n))]
[target next-n results])))
(defn dec-n [[target n results]]
(if (zero? (count results))
[target n results]
(let [next-n (if (<= n 1) (count results) (dec n))]
[target next-n results])))
(defn update-position-and-select [tab-name update-f]
(when (some? (get-mem [:tab-search tab-name]))
(let [[_ n results] (update-mem [:tab-search tab-name] update-f)]
(when (> (count results) 0)
(update-search-status tab-name)
(let [event-id (nth results (dec n))
tree (get-mem [:tab-tree-map tab-name])
model (config tree :model)
root-node (.getRoot model)
node (at-util/find-header-node root-node event-id)]
(at-util/select-tree-node tree node))))))
(defn select-next [tab-name _e]
(update-position-and-select tab-name inc-n))
(defn select-prev [tab-name _e]
(update-position-and-select tab-name dec-n))
(defn load-tab-search [tab-name]
(let [[target] (get-mem [:tab-search tab-name])
tree (get-mem [:tab-tree-map tab-name])
model (config tree :model)
root (.getRoot model)]
(try
(loop [children (enumeration-seq (.children root))
n 0]
(if (= target (get-search-target tab-name))
(let [child (first children)]
(cond
(nil? child)
(update-search-status tab-name)
(event-matches target (.getUserObject child))
(do
(update-mem [:tab-search tab-name]
add-id-to-results (.getUserObject child))
(update-search-status tab-name)
(when (zero? n)
(select-next tab-name nil))
(recur (rest children) (inc n)))
:else
(recur (rest children) n)))))
(catch Exception e
(prn 'load-tab-search e)))))
(defn search-event [tab-name e]
(let [c (.getKeyChar e)]
(when (= \newline c)
(set-search-status tab-name "")
(let [target-text (get-search-target tab-name)]
(set-mem [:tab-search tab-name] [target-text 0 []])
(when-not (empty? target-text)
(set-search-status tab-name "Searching...")
(future (load-tab-search tab-name)))))))
| null | https://raw.githubusercontent.com/unclebob/more-speech/460b77d57551f19ca0810acc7dd1656a3160fdf8/src/more_speech/nostr/tab_searcher.clj | clojure | (ns more-speech.nostr.tab-searcher
(:use [seesaw core font tree])
(:require [more-speech.nostr.util :as util]
[more-speech.mem :refer :all]
[more-speech.config :refer [get-db]]
[more-speech.ui.formatters :as formatters]
[more-speech.bech32 :as bech32]
[more-speech.db.gateway :as gateway]
[more-speech.nostr.contact-list :as contact-list]
[more-speech.ui.swing.article-tree-util :as at-util]
[more-speech.config :as config]))
(defn get-subject [event]
(let [subject-tags (filter #(= :subject (first %)) (:tags event))]
(second (first subject-tags))))
(defn id-matches-tag [id tags]
(some #(= (util/hexify id) (second %)) tags))
(defn match-id [id event]
(or (= id (:pubkey event))
(= id (:id event))
(id-matches-tag id (:tags event))))
(defn match-hex-id [target event]
(let [id (util/unhexify target)]
(match-id id event)))
(defn match-string-target [target event]
(let [content (formatters/replace-references event)
author-name (:name (gateway/get-profile (get-db) (:pubkey event)))
author-id (contact-list/get-pubkey-from-petname target)
author-id (or author-id (gateway/get-id-from-username (get-db) target))
petname (contact-list/get-petname (:pubkey event))
subject (get-subject event)
re-target (re-pattern target)]
(or (re-find re-target content)
(and subject (re-find re-target subject))
(and author-name (re-find re-target author-name))
(and petname (re-find re-target petname))
(and author-id (match-id author-id event)))))
(defn match-npub [target event]
(match-id (bech32/address->number target) event))
(defn is-npub? [target]
(try
(bech32/address->number target)
true
(catch Exception _e
false)))
(defn match-target [target event]
(cond
(is-npub? target)
(match-npub target event)
(re-matches #"\#\".*\"" target)
(match-string-target (read-string target) event)
(re-matches config/hex-key-pattern target)
(match-hex-id target event)
:else
(match-string-target target event)))
(defn get-search-target [tab-name]
(let [search-id (keyword (str "#" tab-name "-search"))
search-text (select (get-mem :frame) [search-id])
target-text (config search-text :text)]
target-text))
(defn get-status-field [tab-name]
(let [status-id (keyword (str "#" tab-name "-status"))
status-field (select (get-mem :frame) [status-id])]
status-field))
(defn set-search-status [tab-name status]
(let [status-field (get-status-field tab-name)]
(config! status-field :text status)))
(defn event-matches [target id]
(let [event (gateway/get-event (get-db) id)]
(match-target target event)))
(defn add-id-to-results [[target n results] id]
[target n (conj results id)])
(defn update-search-status [tab-name]
(let [[_ n results] (get-mem [:tab-search tab-name])]
(set-search-status tab-name (format "%d of %d" n (count results)))))
(defn inc-n [[target n results]]
(if (zero? (count results))
[target n results]
(let [next-n (if (= n (count results)) 1 (inc n))]
[target next-n results])))
(defn dec-n [[target n results]]
(if (zero? (count results))
[target n results]
(let [next-n (if (<= n 1) (count results) (dec n))]
[target next-n results])))
(defn update-position-and-select [tab-name update-f]
(when (some? (get-mem [:tab-search tab-name]))
(let [[_ n results] (update-mem [:tab-search tab-name] update-f)]
(when (> (count results) 0)
(update-search-status tab-name)
(let [event-id (nth results (dec n))
tree (get-mem [:tab-tree-map tab-name])
model (config tree :model)
root-node (.getRoot model)
node (at-util/find-header-node root-node event-id)]
(at-util/select-tree-node tree node))))))
(defn select-next [tab-name _e]
(update-position-and-select tab-name inc-n))
(defn select-prev [tab-name _e]
(update-position-and-select tab-name dec-n))
(defn load-tab-search [tab-name]
(let [[target] (get-mem [:tab-search tab-name])
tree (get-mem [:tab-tree-map tab-name])
model (config tree :model)
root (.getRoot model)]
(try
(loop [children (enumeration-seq (.children root))
n 0]
(if (= target (get-search-target tab-name))
(let [child (first children)]
(cond
(nil? child)
(update-search-status tab-name)
(event-matches target (.getUserObject child))
(do
(update-mem [:tab-search tab-name]
add-id-to-results (.getUserObject child))
(update-search-status tab-name)
(when (zero? n)
(select-next tab-name nil))
(recur (rest children) (inc n)))
:else
(recur (rest children) n)))))
(catch Exception e
(prn 'load-tab-search e)))))
(defn search-event [tab-name e]
(let [c (.getKeyChar e)]
(when (= \newline c)
(set-search-status tab-name "")
(let [target-text (get-search-target tab-name)]
(set-mem [:tab-search tab-name] [target-text 0 []])
(when-not (empty? target-text)
(set-search-status tab-name "Searching...")
(future (load-tab-search tab-name)))))))
|
|
6c1d128af65e0e11d26a95ffa4bf318991949b0ee4f850b3a074cdd3315067d6 | jonschoning/espial | TestImport.hs | # LANGUAGE QuasiQuotes #
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE FlexibleContexts #
module TestImport
( module TestImport
, module X
) where
import Application (makeFoundation, makeLogWare)
import ClassyPrelude as X hiding (delete, deleteBy, Handler)
import Database.Persist as X hiding (get)
import Database.Persist.Sql (SqlPersistM, runSqlPersistMPool, rawExecute, rawSql, unSingle)
import Foundation as X
import Model as X
import Test.Hspec as X
import Yesod.Default.Config2 (useEnv, loadYamlSettings)
import Yesod.Auth as X
import Yesod.Test as X
import Yesod.Core.Unsafe (fakeHandlerGetLogger)
-- Wiping the database
import Database.Persist.Sqlite (sqlDatabase, mkSqliteConnectionInfo, fkEnabled, createSqlitePoolFromInfo)
import Control.Monad.Logger (runLoggingT)
import Lens.Micro (set)
import Settings (appDatabaseConf)
import Yesod.Core (messageLoggerSource)
import Types
runDB :: SqlPersistM a -> YesodExample App a
runDB query = do
pool <- fmap appConnPool getTestYesod
liftIO $ runSqlPersistMPool query pool
runHandler :: Handler a -> YesodExample App a
runHandler handler = do
app <- getTestYesod
fakeHandlerGetLogger appLogger app handler
withApp :: SpecWith (TestApp App) -> Spec
withApp = before $ do
settings <- loadYamlSettings
["config/test-settings.yml", "config/settings.yml"]
[]
useEnv
foundation <- makeFoundation settings
wipeDB foundation
logWare <- liftIO $ makeLogWare foundation
return (foundation, logWare)
-- This function will truncate all of the tables in your database.
-- 'withApp' calls it before each test, creating a clean environment for each
-- spec to run in.
wipeDB :: App -> IO ()
wipeDB app = do
let logFunc = messageLoggerSource app (appLogger app)
let dbName = sqlDatabase $ appDatabaseConf $ appSettings app
connInfo = set fkEnabled False $ mkSqliteConnectionInfo dbName
pool <- runLoggingT (createSqlitePoolFromInfo connInfo 1) logFunc
flip runSqlPersistMPool pool $ do
tables <- getTables
-- sqlBackend <- ask
-- let queries = map (\t -> "DELETE FROM " ++ (connEscapeName sqlBackend $ DBName t)) tables
let queries = map (\t -> "DELETE FROM " ++ t) tables
forM_ queries (\q -> rawExecute q [])
getTables :: DB [Text]
getTables = do
tables <- rawSql "SELECT name FROM sqlite_master WHERE type = 'table';" []
return (fmap unSingle tables)
| null | https://raw.githubusercontent.com/jonschoning/espial/c98030139b7ddd15a9b101220235808c6b7db6f5/test/TestImport.hs | haskell | # LANGUAGE OverloadedStrings #
Wiping the database
This function will truncate all of the tables in your database.
'withApp' calls it before each test, creating a clean environment for each
spec to run in.
sqlBackend <- ask
let queries = map (\t -> "DELETE FROM " ++ (connEscapeName sqlBackend $ DBName t)) tables | # LANGUAGE QuasiQuotes #
# LANGUAGE NoImplicitPrelude #
# LANGUAGE FlexibleContexts #
module TestImport
( module TestImport
, module X
) where
import Application (makeFoundation, makeLogWare)
import ClassyPrelude as X hiding (delete, deleteBy, Handler)
import Database.Persist as X hiding (get)
import Database.Persist.Sql (SqlPersistM, runSqlPersistMPool, rawExecute, rawSql, unSingle)
import Foundation as X
import Model as X
import Test.Hspec as X
import Yesod.Default.Config2 (useEnv, loadYamlSettings)
import Yesod.Auth as X
import Yesod.Test as X
import Yesod.Core.Unsafe (fakeHandlerGetLogger)
import Database.Persist.Sqlite (sqlDatabase, mkSqliteConnectionInfo, fkEnabled, createSqlitePoolFromInfo)
import Control.Monad.Logger (runLoggingT)
import Lens.Micro (set)
import Settings (appDatabaseConf)
import Yesod.Core (messageLoggerSource)
import Types
runDB :: SqlPersistM a -> YesodExample App a
runDB query = do
pool <- fmap appConnPool getTestYesod
liftIO $ runSqlPersistMPool query pool
runHandler :: Handler a -> YesodExample App a
runHandler handler = do
app <- getTestYesod
fakeHandlerGetLogger appLogger app handler
withApp :: SpecWith (TestApp App) -> Spec
withApp = before $ do
settings <- loadYamlSettings
["config/test-settings.yml", "config/settings.yml"]
[]
useEnv
foundation <- makeFoundation settings
wipeDB foundation
logWare <- liftIO $ makeLogWare foundation
return (foundation, logWare)
wipeDB :: App -> IO ()
wipeDB app = do
let logFunc = messageLoggerSource app (appLogger app)
let dbName = sqlDatabase $ appDatabaseConf $ appSettings app
connInfo = set fkEnabled False $ mkSqliteConnectionInfo dbName
pool <- runLoggingT (createSqlitePoolFromInfo connInfo 1) logFunc
flip runSqlPersistMPool pool $ do
tables <- getTables
let queries = map (\t -> "DELETE FROM " ++ t) tables
forM_ queries (\q -> rawExecute q [])
getTables :: DB [Text]
getTables = do
tables <- rawSql "SELECT name FROM sqlite_master WHERE type = 'table';" []
return (fmap unSingle tables)
|
8e3aef40fcd97d7c585b27464b992664865da1880f0f3d499adb30ee6c15f4a1 | eponai/sulolive | mutate.cljs | (ns eponai.mobile.parser.mutate
(:require [eponai.common.parser :refer [client-mutate]]
[eponai.common.database :as db]
[om.next :as om]
[datascript.core :as d]
[taoensso.timbre :refer-macros [debug]]))
(defn set-route-tx [route]
{:ui/component :ui.component/app
:ui.component.app/route route})
(defmethod client-mutate 'app/set-route
[{:keys [state]} _ {:keys [route]}]
{:action #(db/transact state [(set-route-tx route)])})
( defmethod mutate ' login / verify
; [{:keys [state]} k {:keys [verify-uuid]}]
; (let [verify-endpoint (-> (d/entity (d/db state) [:ui/singleton :ui.singleton/configuration])
; :ui.singleton.configuration.endpoints/verify)
; verify-endpoint (str verify-endpoint "/" verify-uuid)]
; (debug "Will verify verify-uuid: " verify-endpoint)
; ;; Special http remote which uses the query to call some endpoint.
; ;; Response can be merged with the parser.merge function.
; {:http/call (om/query->ast `[(http/get ~{:mutation 'login/verify
; :endpoint verify-endpoint})])}))
| null | https://raw.githubusercontent.com/eponai/sulolive/7a70701bbd3df6bbb92682679dcedb53f8822c18/sulo-native/src/eponai/mobile/parser/mutate.cljs | clojure | [{:keys [state]} k {:keys [verify-uuid]}]
(let [verify-endpoint (-> (d/entity (d/db state) [:ui/singleton :ui.singleton/configuration])
:ui.singleton.configuration.endpoints/verify)
verify-endpoint (str verify-endpoint "/" verify-uuid)]
(debug "Will verify verify-uuid: " verify-endpoint)
;; Special http remote which uses the query to call some endpoint.
;; Response can be merged with the parser.merge function.
{:http/call (om/query->ast `[(http/get ~{:mutation 'login/verify
:endpoint verify-endpoint})])})) | (ns eponai.mobile.parser.mutate
(:require [eponai.common.parser :refer [client-mutate]]
[eponai.common.database :as db]
[om.next :as om]
[datascript.core :as d]
[taoensso.timbre :refer-macros [debug]]))
(defn set-route-tx [route]
{:ui/component :ui.component/app
:ui.component.app/route route})
(defmethod client-mutate 'app/set-route
[{:keys [state]} _ {:keys [route]}]
{:action #(db/transact state [(set-route-tx route)])})
( defmethod mutate ' login / verify
|
28af7eb835ceb57b9de67705ee471929dd3000d46617c5f9114c0a67c69d56b5 | pdarragh/camlrack | tokenize.ml | open Errors
include TokenTypes
let regexps =
[ (Str.regexp "(", fun _ -> LParen)
; (Str.regexp "{", fun _ -> LBrace)
; (Str.regexp "\\[", fun _ -> LBracket)
; (Str.regexp ")", fun _ -> RParen)
; (Str.regexp "}", fun _ -> RBrace)
; (Str.regexp "]", fun _ -> RBracket)
; (Str.regexp "[-+]?[0-9]+\\.[0-9]*\\([eE][-+]?[0-9]+\\)?", (fun s -> Float (float_of_string s)))
; (Str.regexp "[-+]?[0-9]+[eE][-+]?[0-9]+", (fun s -> Float (float_of_string s)))
; (Str.regexp "[-+]?[0-9]+", (fun s -> Integer (int_of_string s)))
; (Str.regexp {r|"[^"]*"|r}, (fun s -> String (String.sub s 1 ((String.length s) - 2))))
; (Str.regexp "[^])}[({ \t\n0-9][^])}[({ \t\n]*", (fun s -> Symbol s))
]
let whitespace = Str.regexp "[ \t\n]*"
let tokenize (input : string) : token list =
let length = String.length input in
let pos = ref 0 in
let advance (offset : int) =
pos := !pos + offset in
let spaces () =
let _ = Str.string_match whitespace input !pos in
advance (String.length (Str.matched_string input)) in
let try_regexp (regexp, confun) : (int * token) option =
if Str.string_match regexp input !pos
then
let s = Str.matched_string input in
Some (String.length s, confun s)
else None in
let tokens = ref [] in
while !pos < length do
spaces ();
let matches = List.filter_map try_regexp regexps in
let (length, token) = List.fold_left
(fun p c -> if fst c > fst p then c else p)
(-1, LParen) matches in
if length < 0
then raise (CamlrackError (("Could not lex input at position " ^ string_of_int !pos ^
", beginning with character: " ^ String.sub input !pos 1)))
else (tokens := token::!tokens; advance length)
done;
List.rev !tokens
| null | https://raw.githubusercontent.com/pdarragh/camlrack/b80f35a973529f029c0715b83ce64c1de4e8467d/camlrack/src/tokenize.ml | ocaml | open Errors
include TokenTypes
let regexps =
[ (Str.regexp "(", fun _ -> LParen)
; (Str.regexp "{", fun _ -> LBrace)
; (Str.regexp "\\[", fun _ -> LBracket)
; (Str.regexp ")", fun _ -> RParen)
; (Str.regexp "}", fun _ -> RBrace)
; (Str.regexp "]", fun _ -> RBracket)
; (Str.regexp "[-+]?[0-9]+\\.[0-9]*\\([eE][-+]?[0-9]+\\)?", (fun s -> Float (float_of_string s)))
; (Str.regexp "[-+]?[0-9]+[eE][-+]?[0-9]+", (fun s -> Float (float_of_string s)))
; (Str.regexp "[-+]?[0-9]+", (fun s -> Integer (int_of_string s)))
; (Str.regexp {r|"[^"]*"|r}, (fun s -> String (String.sub s 1 ((String.length s) - 2))))
; (Str.regexp "[^])}[({ \t\n0-9][^])}[({ \t\n]*", (fun s -> Symbol s))
]
let whitespace = Str.regexp "[ \t\n]*"
let tokenize (input : string) : token list =
let length = String.length input in
let pos = ref 0 in
let advance (offset : int) =
pos := !pos + offset in
let spaces () =
let _ = Str.string_match whitespace input !pos in
advance (String.length (Str.matched_string input)) in
let try_regexp (regexp, confun) : (int * token) option =
if Str.string_match regexp input !pos
then
let s = Str.matched_string input in
Some (String.length s, confun s)
else None in
let tokens = ref [] in
while !pos < length do
spaces ();
let matches = List.filter_map try_regexp regexps in
let (length, token) = List.fold_left
(fun p c -> if fst c > fst p then c else p)
(-1, LParen) matches in
if length < 0
then raise (CamlrackError (("Could not lex input at position " ^ string_of_int !pos ^
", beginning with character: " ^ String.sub input !pos 1)))
else (tokens := token::!tokens; advance length)
done;
List.rev !tokens
|
|
29c6397b57b4a385ee9a4215289832ec1b8c1d51caa96a43d558dddf32b21caf | flipstone/haskell-for-beginners | 3_walk_the_line.hs | -- A Bomb is defined by the order in
-- which its wires must be cut to disable
-- it. If a wire is cut out of order, the
-- bomb explodes.
--
type Bomb = [Wire]
data Wire = Red | Blue | Green deriving (Show, Eq)
-- Define a function that cuts a Wire of a
-- Bomb, returning Just the Wires remaining
-- to be cut. If the incorrect Wire is cut,
-- the Bomb expodes, leaving Nothing to return.
-- If any attempt is made to cut a Wire on
-- a Bomb with no Wires remaining, the Bomb
-- explodes.
--
cutWire :: Wire -> Bomb -> Maybe Bomb
cutWire cut (w:ws) | cut == w = Just ws
cutWire _ _ = Nothing
-- Define a function that waits to see if the
-- Bomb will explode. If there are no remaining
-- wires, return Just a happy message. If any
-- wires remain uncut, the Bomb explodes.
--
wait :: Bomb -> Maybe String
wait [] = Just "Saved again!"
wait _ = Nothing
-- Quick, disarm the Bomb! (Be sure sure to use
Monad functions )
--
bomb = [Red, Green, Blue]
disarmed = return bomb >>=
cutWire Red >>=
cutWire Green >>=
cutWire Blue >>=
wait
-- Now see what happens if you accidentally cut the Blue
wire second .
--
boomed = return bomb >>=
cutWire Red >>=
cutWire Blue >>=
cutWire Green >>=
wait
-- All good Bombs are equipped with a dead man switch to
-- protect their creators. Define a disarming operation
-- to make the Bomb explode if someone takes out its maker.
--
takeOutBombMaker :: Maybe Bomb
takeOutBombMaker = Nothing
-- Try it out! See what happens if someone takes
-- out the Bomb's maker while you are disarming it.
--
takeEmOut = return bomb >>=
cutWire Red >>=
cutWire Green >>
takeOutBombMaker >>=
cutWire Blue >>=
wait
Pick one of the 3 disarming examples above and re - write it
without using the Maybe Monad . Just use pattern matching at
-- each step of the sequence.
--
boomed' =
case cutWire Red bomb of
Nothing -> Nothing
Just bomb' -> case cutWire Blue bomb' of
Nothing -> Nothing
Just bomb'' -> case cutWire Green bomb'' of
Nothing -> Nothing
Just bomb''' -> wait bomb'''
| null | https://raw.githubusercontent.com/flipstone/haskell-for-beginners/e586a1f3ef08f21d5181171fe7a7b27057391f0b/answers/chapter_12/3_walk_the_line.hs | haskell | A Bomb is defined by the order in
which its wires must be cut to disable
it. If a wire is cut out of order, the
bomb explodes.
Define a function that cuts a Wire of a
Bomb, returning Just the Wires remaining
to be cut. If the incorrect Wire is cut,
the Bomb expodes, leaving Nothing to return.
If any attempt is made to cut a Wire on
a Bomb with no Wires remaining, the Bomb
explodes.
Define a function that waits to see if the
Bomb will explode. If there are no remaining
wires, return Just a happy message. If any
wires remain uncut, the Bomb explodes.
Quick, disarm the Bomb! (Be sure sure to use
Now see what happens if you accidentally cut the Blue
All good Bombs are equipped with a dead man switch to
protect their creators. Define a disarming operation
to make the Bomb explode if someone takes out its maker.
Try it out! See what happens if someone takes
out the Bomb's maker while you are disarming it.
each step of the sequence.
| type Bomb = [Wire]
data Wire = Red | Blue | Green deriving (Show, Eq)
cutWire :: Wire -> Bomb -> Maybe Bomb
cutWire cut (w:ws) | cut == w = Just ws
cutWire _ _ = Nothing
wait :: Bomb -> Maybe String
wait [] = Just "Saved again!"
wait _ = Nothing
Monad functions )
bomb = [Red, Green, Blue]
disarmed = return bomb >>=
cutWire Red >>=
cutWire Green >>=
cutWire Blue >>=
wait
wire second .
boomed = return bomb >>=
cutWire Red >>=
cutWire Blue >>=
cutWire Green >>=
wait
takeOutBombMaker :: Maybe Bomb
takeOutBombMaker = Nothing
takeEmOut = return bomb >>=
cutWire Red >>=
cutWire Green >>
takeOutBombMaker >>=
cutWire Blue >>=
wait
Pick one of the 3 disarming examples above and re - write it
without using the Maybe Monad . Just use pattern matching at
boomed' =
case cutWire Red bomb of
Nothing -> Nothing
Just bomb' -> case cutWire Blue bomb' of
Nothing -> Nothing
Just bomb'' -> case cutWire Green bomb'' of
Nothing -> Nothing
Just bomb''' -> wait bomb'''
|
5caf05db921a81d89986455582a70ce67ccd8caaffa40142f466a2e1e5e0a7b7 | spechub/Hets | GenericATP.hs | # LANGUAGE CPP #
|
Module : ./GUI / GenericATP.hs
Description : Generic Prover GUI .
Copyright : ( c ) , Uni Bremen 2009
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers . CPP between and Gtk .
Module : ./GUI/GenericATP.hs
Description : Generic Prover GUI.
Copyright : (c) Thiemo Wiedemeyer, Uni Bremen 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers. CPP between HTk and Gtk.
-}
module GUI.GenericATP (genericATPgui) where
import Interfaces.GenericATPState
import Logic.Prover
#ifdef GTKGLADE
import qualified GUI.GtkGenericATP as Gtk
#elif defined UNI_PACKAGE
import qualified GUI.HTkGenericATP as HTk
#endif
|
Invokes the prover GUI . Users may start the batch prover run on all goals ,
or use a detailed GUI for proving each goal manually .
Invokes the prover GUI. Users may start the batch prover run on all goals,
or use a detailed GUI for proving each goal manually.
-}
genericATPgui :: (Show sentence, Ord proof_tree, Ord sentence)
=> ATPFunctions sign sentence mor proof_tree pst
-- ^ prover specific -- functions
-> Bool -- ^ prover supports extra options
-> String -- ^ prover name
-> String -- ^ theory name
-> Theory sign sentence proof_tree {- ^ theory consisting of a
signature and a list of Named sentence -}
-> [FreeDefMorphism sentence mor] -- ^ freeness constraints
-> proof_tree -- ^ initial empty proof_tree
-> IO [ProofStatus proof_tree] -- ^ proof status for each goal
#ifdef GTKGLADE
genericATPgui = Gtk.genericATPgui
#elif defined UNI_PACKAGE
genericATPgui = HTk.genericATPgui
#else
genericATPgui = error "not implemented"
#endif
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/GUI/GenericATP.hs | haskell | ^ prover specific -- functions
^ prover supports extra options
^ prover name
^ theory name
^ theory consisting of a
signature and a list of Named sentence
^ freeness constraints
^ initial empty proof_tree
^ proof status for each goal | # LANGUAGE CPP #
|
Module : ./GUI / GenericATP.hs
Description : Generic Prover GUI .
Copyright : ( c ) , Uni Bremen 2009
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers . CPP between and Gtk .
Module : ./GUI/GenericATP.hs
Description : Generic Prover GUI.
Copyright : (c) Thiemo Wiedemeyer, Uni Bremen 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : needs POSIX
Generic GUI for automatic theorem provers. CPP between HTk and Gtk.
-}
module GUI.GenericATP (genericATPgui) where
import Interfaces.GenericATPState
import Logic.Prover
#ifdef GTKGLADE
import qualified GUI.GtkGenericATP as Gtk
#elif defined UNI_PACKAGE
import qualified GUI.HTkGenericATP as HTk
#endif
|
Invokes the prover GUI . Users may start the batch prover run on all goals ,
or use a detailed GUI for proving each goal manually .
Invokes the prover GUI. Users may start the batch prover run on all goals,
or use a detailed GUI for proving each goal manually.
-}
genericATPgui :: (Show sentence, Ord proof_tree, Ord sentence)
=> ATPFunctions sign sentence mor proof_tree pst
#ifdef GTKGLADE
genericATPgui = Gtk.genericATPgui
#elif defined UNI_PACKAGE
genericATPgui = HTk.genericATPgui
#else
genericATPgui = error "not implemented"
#endif
|
Subsets and Splits